mirror of
https://github.com/freqtrade/freqtrade.git
synced 2025-11-29 08:33:07 +00:00
Compare commits
1276 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8371003c05 | ||
|
|
cff8498b42 | ||
|
|
fdf6121b6e | ||
|
|
3541f7bfce | ||
|
|
3a2443b5fa | ||
|
|
e488ce0d07 | ||
|
|
521e497ba3 | ||
|
|
c9ee678a52 | ||
|
|
078e25e383 | ||
|
|
a3b0f75289 | ||
|
|
66939bdcf6 | ||
|
|
184a6005a6 | ||
|
|
161c06fd4e | ||
|
|
5d7317ef77 | ||
|
|
aae14dd9fe | ||
|
|
30e3e434ab | ||
|
|
33645e45fd | ||
|
|
27d46ed06f | ||
|
|
02563019fc | ||
|
|
8c9119b471 | ||
|
|
2d02c3f2a4 | ||
|
|
a3e9d04383 | ||
|
|
7f851ad8d9 | ||
|
|
a1c684f67c | ||
|
|
f347e5934a | ||
|
|
e033df6a2f | ||
|
|
b254bdfea3 | ||
|
|
70a0346b0a | ||
|
|
7e23304187 | ||
|
|
926bf07df1 | ||
|
|
6e85280467 | ||
|
|
80ed1c3e14 | ||
|
|
1ae3fb4d2f | ||
|
|
3f2542fcbc | ||
|
|
f6278da23f | ||
|
|
a3ac05cc16 | ||
|
|
a97bb10877 | ||
|
|
bd4dd8403b | ||
|
|
52f0ed5310 | ||
|
|
f4c7edf551 | ||
|
|
82797e768f | ||
|
|
9176064047 | ||
|
|
aad10ceee3 | ||
|
|
58ceda4b90 | ||
|
|
f36bc80ad1 | ||
|
|
2b4d821d30 | ||
|
|
8a940eb0c1 | ||
|
|
9c2f21b07e | ||
|
|
055f3fd1fd | ||
|
|
40843566d0 | ||
|
|
e13045b599 | ||
|
|
7d2d0235a0 | ||
|
|
bff0a09537 | ||
|
|
c1c2717bc9 | ||
|
|
66415d48d4 | ||
|
|
d54b1dade3 | ||
|
|
1bf475fa1a | ||
|
|
099bbc5c7f | ||
|
|
6e3336cb30 | ||
|
|
eb6c7f8595 | ||
|
|
10a706851a | ||
|
|
8d4515935a | ||
|
|
9474cb1792 | ||
|
|
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 | ||
|
|
ca054799d0 | ||
|
|
b37f34ff5b | ||
|
|
a75420f75f | ||
|
|
7daa5bc338 | ||
|
|
53499e01de | ||
|
|
bdda620397 | ||
|
|
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 | ||
|
|
2537b8cb0c | ||
|
|
78883663a0 | ||
|
|
b00406a7eb | ||
|
|
4d56e3b36e | ||
|
|
8e9a3e8fc8 | ||
|
|
1ffda29fd2 | ||
|
|
024aa3ab6b | ||
|
|
20abf67779 | ||
|
|
fb3a53b8af | ||
|
|
4c9295fe2d | ||
|
|
6a7163d3a9 | ||
|
|
de23f3928d | ||
|
|
8975e38b1d | ||
|
|
20a132651f | ||
|
|
88ba7e467d | ||
|
|
df7ceb4ccb | ||
|
|
47bb8ad0d4 | ||
|
|
304d15e236 | ||
|
|
d1c45cf3f8 | ||
|
|
04f28ed9bc | ||
|
|
ce84f74528 | ||
|
|
762604300f | ||
|
|
433fd2a7c3 | ||
|
|
09b77d9f14 | ||
|
|
5c39ebd0a0 | ||
|
|
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 | ||
|
|
7c53dcb0af | ||
|
|
fda8f7e305 | ||
|
|
52b212db64 | ||
|
|
931d24b5a8 | ||
|
|
18dfa56752 | ||
|
|
26ab108890 | ||
|
|
1cc174c007 | ||
|
|
e26f563f4b | ||
|
|
ebd0a1722d | ||
|
|
f81c49ce6d | ||
|
|
ded2d3c293 | ||
|
|
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 | ||
|
|
29745bb4ec | ||
|
|
641e3fdf7a | ||
|
|
2f76eaf358 | ||
|
|
0e4ef33d6a | ||
|
|
18c73ceb90 | ||
|
|
8431b54b21 | ||
|
|
5fc357ee10 | ||
|
|
de33ec4250 | ||
|
|
a9f7e9fb7a | ||
|
|
aa335d8485 | ||
|
|
82f7798f48 | ||
|
|
ce80bbe24c | ||
|
|
da195d0272 | ||
|
|
4eae02b723 | ||
|
|
081b21fe82 | ||
|
|
ed053d240e | ||
|
|
0ca3157a8b | ||
|
|
25447329a0 | ||
|
|
4934456751 | ||
|
|
0f4dcaa403 | ||
|
|
4b560880fd | ||
|
|
dc9fed4a5f | ||
|
|
88a24da272 | ||
|
|
e4655c9b07 | ||
|
|
1495c93083 | ||
|
|
21c6855705 | ||
|
|
a7d6dc9d3a | ||
|
|
ed7207d4c8 | ||
|
|
bb9235c715 | ||
|
|
45d12dbc83 | ||
|
|
189835b963 | ||
|
|
3163cbdf8a | ||
|
|
1e6f9f9fe2 | ||
|
|
3091869115 | ||
|
|
9e85376a2d | ||
|
|
a379c19e9a | ||
|
|
2bd4008cb2 | ||
|
|
d21ae4edd3 | ||
|
|
1da008b3af | ||
|
|
703458f365 | ||
|
|
4b0a4c936a | ||
|
|
216094a761 | ||
|
|
4efd8b96e5 | ||
|
|
b61f43835d | ||
|
|
017a94adc1 | ||
|
|
b20bea8492 | ||
|
|
54694dd3a4 | ||
|
|
8dd9b5c6fb | ||
|
|
16a50fbe4e | ||
|
|
32897ce769 | ||
|
|
51f074ba4b | ||
|
|
0ba804d051 | ||
|
|
611a594a46 | ||
|
|
8a7fe3f1d6 | ||
|
|
054484ad73 | ||
|
|
ac3e061508 | ||
|
|
ddf86d6342 | ||
|
|
ba29a2ffe4 | ||
|
|
b33e47a49e | ||
|
|
298e8b2332 | ||
|
|
78f8ba1226 | ||
|
|
17e03559dc | ||
|
|
2825206d37 | ||
|
|
cd20d5b5c5 | ||
|
|
ebf6dad3f6 | ||
|
|
683406b57d | ||
|
|
406dfe21f8 | ||
|
|
346d381ab8 | ||
|
|
d7980fa0b6 | ||
|
|
fc7b9846ae | ||
|
|
15e695a9bd | ||
|
|
110fbd3f06 | ||
|
|
f0428be91e | ||
|
|
0b03c6c786 | ||
|
|
150a497cb4 | ||
|
|
3d666ea68e | ||
|
|
ee733210ca | ||
|
|
86342efa7a | ||
|
|
05967442c3 | ||
|
|
d6b587678e | ||
|
|
668d42447f | ||
|
|
32c9b5f415 | ||
|
|
f42ce8fc2a | ||
|
|
6b142d716f | ||
|
|
26a7af85ea | ||
|
|
69b0767165 | ||
|
|
f862b4d0f0 | ||
|
|
a88bfa8ded | ||
|
|
fffd47e3d8 | ||
|
|
7a3c3c4ddf | ||
|
|
eafccb445c | ||
|
|
b040cbffdd | ||
|
|
153434561d | ||
|
|
36b2ed172c | ||
|
|
58d70b2079 | ||
|
|
e0e0bad7c1 | ||
|
|
0e9e6b3443 | ||
|
|
9199fd5964 | ||
|
|
8f9b5095b5 | ||
|
|
5b996920f2 | ||
|
|
bcec070ad7 | ||
|
|
c3d7411668 | ||
|
|
997c426228 | ||
|
|
7a52334c9f | ||
|
|
111f018c85 | ||
|
|
64da877161 | ||
|
|
f0e6a9e0e3 | ||
|
|
a373e48939 | ||
|
|
f2cd4fdafe | ||
|
|
9991c892ac | ||
|
|
8e7512161a | ||
|
|
5e09913e3d | ||
|
|
cceb00c406 | ||
|
|
585b8332ad | ||
|
|
066f324060 | ||
|
|
8e1e20bf0d | ||
|
|
0ac592ad40 | ||
|
|
17269c88be | ||
|
|
8204107315 | ||
|
|
9e7d367b5c | ||
|
|
12b9257c6d | ||
|
|
37f698d9c1 | ||
|
|
e7c17df844 | ||
|
|
28ec8b5bc2 | ||
|
|
200b8e48bf | ||
|
|
2a8ad9e35b | ||
|
|
be8ad0f022 | ||
|
|
a77efc3949 | ||
|
|
418ca00305 | ||
|
|
03f02294d1 | ||
|
|
0a7a1290e3 | ||
|
|
28f73ecb3d | ||
|
|
6ab7f93ce7 | ||
|
|
d1511a1085 | ||
|
|
0775ac081a | ||
|
|
646a9d12b2 | ||
|
|
e7be742c58 | ||
|
|
8d002a8f28 | ||
|
|
af3eea3805 | ||
|
|
4dc0631a4b | ||
|
|
a3415e52c0 | ||
|
|
1b337fe5e1 | ||
|
|
50350a09cd | ||
|
|
1bf8d8cff3 | ||
|
|
62d50f512d | ||
|
|
8c64be3cfd | ||
|
|
cc0a733f1f | ||
|
|
1b645d64c8 | ||
|
|
a374df7622 | ||
|
|
cbf710a4f8 | ||
|
|
f05818a86e | ||
|
|
cab748588c | ||
|
|
63ad95a474 | ||
|
|
e9da4d8505 | ||
|
|
26a2292f6d | ||
|
|
5fb14e769b | ||
|
|
c7c7a1c2aa | ||
|
|
1242263d25 | ||
|
|
31c598f88a | ||
|
|
6cb4830534 | ||
|
|
067267f4cf | ||
|
|
99db53417c | ||
|
|
737c07c5b6 | ||
|
|
097cdcb57a | ||
|
|
175591e524 | ||
|
|
e7ddd81251 | ||
|
|
a183162d8b | ||
|
|
a6bb7595e8 | ||
|
|
210d468a9b | ||
|
|
5f8fcebb88 | ||
|
|
f23f659ac5 | ||
|
|
99eeb2e605 | ||
|
|
f26171082c | ||
|
|
2acd2542ac | ||
|
|
f26c40082d | ||
|
|
b3dbb81838 | ||
|
|
5e5ef21f61 | ||
|
|
be4a4180ae | ||
|
|
f7322358cf | ||
|
|
671b98ecad | ||
|
|
ed04f7f39d | ||
|
|
cbb187e9b9 | ||
|
|
03cdfe8cae | ||
|
|
37f8139432 | ||
|
|
79891671e9 | ||
|
|
65489c894d | ||
|
|
b36a1d3260 | ||
|
|
8a1d02e185 | ||
|
|
8c2ff2f46e | ||
|
|
e492d47621 | ||
|
|
98baae9456 | ||
|
|
e3cf6188a1 | ||
|
|
8cf8ab089e | ||
|
|
ed1d450099 | ||
|
|
41494f28da | ||
|
|
19b1a6c638 | ||
|
|
471bd4d889 | ||
|
|
084efc98d7 | ||
|
|
1d2ef5c2ce | ||
|
|
fd45ebd0e9 | ||
|
|
258d4bd6ae | ||
|
|
b8aa727edf | ||
|
|
eac01960a7 | ||
|
|
a5bd4e329a | ||
|
|
5ce665f279 | ||
|
|
9aac080414 | ||
|
|
8b639b5026 | ||
|
|
7f119a28e7 | ||
|
|
5f88c4aad9 | ||
|
|
dfe3d78767 | ||
|
|
633996216a | ||
|
|
09b302abf7 | ||
|
|
c92f233c15 | ||
|
|
751157b4ea | ||
|
|
5f62a9e4d8 | ||
|
|
a8855bf795 | ||
|
|
c22b00b303 | ||
|
|
67c5115b41 | ||
|
|
ab4b1cc8fe | ||
|
|
716785c65f | ||
|
|
baa7fd6c79 | ||
|
|
9045f796e0 | ||
|
|
988c1744af | ||
|
|
cd6d276119 | ||
|
|
d085a2bd3e | ||
|
|
dddccf8f1a | ||
|
|
8b3fb3d6d5 | ||
|
|
80b450d4e6 | ||
|
|
0bc71403ff | ||
|
|
cb6b3e17a9 | ||
|
|
e7157faddd | ||
|
|
a33d408780 | ||
|
|
42474b7144 | ||
|
|
933564591d | ||
|
|
599e18b920 | ||
|
|
547d65b065 | ||
|
|
e4e8a611be | ||
|
|
2b190e5638 | ||
|
|
acab56793f | ||
|
|
2c976bdd24 | ||
|
|
3aee8d2b2a | ||
|
|
841c379797 | ||
|
|
b6a12044ba | ||
|
|
8e087cb639 | ||
|
|
bcb5913291 | ||
|
|
be53c0885d | ||
|
|
91047830fd | ||
|
|
6e0655b3b7 | ||
|
|
edc0d7f2c7 | ||
|
|
1d18e0a11a | ||
|
|
b167fb071a | ||
|
|
3b9899dfd4 | ||
|
|
f94d46316e | ||
|
|
569a547b3f | ||
|
|
6c306c0013 | ||
|
|
9b050523e9 | ||
|
|
f9a92c2879 | ||
|
|
ab194c7d75 | ||
|
|
904a9c5dc7 | ||
|
|
38243c52fd | ||
|
|
c8c48156dd | ||
|
|
f4d18034d9 | ||
|
|
17c11b2afa | ||
|
|
68904296e7 | ||
|
|
d4499338e0 | ||
|
|
6174a5dd55 | ||
|
|
e26bbc7de8 | ||
|
|
62c1ff776e | ||
|
|
baea06eac7 | ||
|
|
6ac73f7cde | ||
|
|
66619204ba | ||
|
|
1d7fb2ffac | ||
|
|
c42c5a1f85 | ||
|
|
5b62ad876e | ||
|
|
ec460ab9c9 | ||
|
|
2eb6513251 | ||
|
|
c449e39280 | ||
|
|
1c57a4ac35 | ||
|
|
334ac8b10c | ||
|
|
d801dec6aa | ||
|
|
08aedc18e1 | ||
|
|
e4bdb92521 | ||
|
|
11f7ab61b9 | ||
|
|
df9bfb6c2e | ||
|
|
ab9506df48 | ||
|
|
136ef077b2 | ||
|
|
e8a8f416f3 | ||
|
|
8c76f45030 | ||
|
|
96f550c6aa | ||
|
|
37ef5c38f0 | ||
|
|
66a273b31b | ||
|
|
52e24c3a25 | ||
|
|
7a2d917c66 | ||
|
|
025350ebff | ||
|
|
411e035005 | ||
|
|
800997437a | ||
|
|
75d5ff69ef | ||
|
|
a241c2af0d | ||
|
|
d1729a624d | ||
|
|
e51a720193 | ||
|
|
ff1d36434d | ||
|
|
904ae5af91 | ||
|
|
42e8e1c16a | ||
|
|
9fb493d2f4 | ||
|
|
031157f215 | ||
|
|
c65d217d1e | ||
|
|
0a13f7e1c7 | ||
|
|
173375de7c | ||
|
|
27d81bb68c | ||
|
|
044105e8e0 | ||
|
|
48f8a62335 | ||
|
|
71f99ba79c | ||
|
|
95492958f9 | ||
|
|
661c8251c5 | ||
|
|
83067c1edc | ||
|
|
c5ed004c9e | ||
|
|
04b51a982e | ||
|
|
e810597eec | ||
|
|
692d6afbd9 | ||
|
|
59fa02e11a | ||
|
|
6ef6a24841 | ||
|
|
eba55c2783 | ||
|
|
085aa3084e | ||
|
|
de2d04f06b | ||
|
|
12654cb810 | ||
|
|
4b15873ee1 | ||
|
|
748fe94603 | ||
|
|
86a5dfa62e | ||
|
|
0b4800835c | ||
|
|
5caeca7509 | ||
|
|
7ff61f12e9 | ||
|
|
ae35649366 | ||
|
|
a01b34a004 | ||
|
|
02b9da8aba | ||
|
|
ed0c7a6aaf | ||
|
|
25cb935eee | ||
|
|
c74d766275 | ||
|
|
37985310d5 | ||
|
|
c3b4a4dde1 | ||
|
|
d7262c0b4e | ||
|
|
870966dcd0 | ||
|
|
85beb3b6a9 | ||
|
|
bf69b055eb | ||
|
|
31c7189b8b | ||
|
|
eaf3fd80c5 | ||
|
|
1059586226 | ||
|
|
b610e8c7e6 | ||
|
|
e632720c02 | ||
|
|
1f042f5e32 | ||
|
|
54b63e89f8 | ||
|
|
3f65c31883 | ||
|
|
31ab32f0b9 | ||
|
|
bc5c91f681 | ||
|
|
076ef0407b | ||
|
|
b0150d548a | ||
|
|
60acbc97ab | ||
|
|
dd47bd04cd | ||
|
|
da57396d07 | ||
|
|
d3a3765819 | ||
|
|
f90676cfc5 | ||
|
|
ad2289c34c | ||
|
|
ca77dbe8da | ||
|
|
6c6efd7214 | ||
|
|
7f099d41fa | ||
|
|
60109aaa1f | ||
|
|
ef057c16cb | ||
|
|
39e728a7c2 | ||
|
|
28f0c00281 | ||
|
|
bc78316aa5 | ||
|
|
b8a6c55b10 | ||
|
|
6df1dd1ef2 | ||
|
|
c8638ce82f | ||
|
|
1a61d89bcc | ||
|
|
eb0b0350e0 | ||
|
|
4ec7fcd836 | ||
|
|
f6a66cd3de | ||
|
|
871019c8b9 | ||
|
|
581907305a | ||
|
|
54b0fbca59 | ||
|
|
1e44f93c31 | ||
|
|
3eca80217c | ||
|
|
6f01d7f8ea | ||
|
|
500d16620b | ||
|
|
6550e1fa99 | ||
|
|
80ad37ad93 | ||
|
|
3287cdd47a | ||
|
|
12e86ee4bd | ||
|
|
97d0f93d3c | ||
|
|
861f10dca6 | ||
|
|
2a1385f94b | ||
|
|
e9af6b393f | ||
|
|
2124661cee | ||
|
|
1593847203 | ||
|
|
e8a08011be | ||
|
|
691cec7956 | ||
|
|
241d947564 | ||
|
|
880834b902 | ||
|
|
f435384bf0 | ||
|
|
3149c12a14 | ||
|
|
6a9a2e7f88 | ||
|
|
5b87393a95 | ||
|
|
5a27b10579 | ||
|
|
a80e49bd81 | ||
|
|
ffed13b979 | ||
|
|
9f0f1096e1 | ||
|
|
9a42afe0be | ||
|
|
b6616d7a13 | ||
|
|
7be378aaa9 | ||
|
|
734a9d5d87 | ||
|
|
ce6b869f84 | ||
|
|
dc5f1b2878 | ||
|
|
a041b8bf72 | ||
|
|
4fa12ffda0 | ||
|
|
5dcf28cafb | ||
|
|
365a408df5 | ||
|
|
7204227022 | ||
|
|
dab4ab78fc | ||
|
|
a74b941b72 | ||
|
|
89bba6f776 | ||
|
|
82f86569ee | ||
|
|
9e988783de | ||
|
|
bba8e61409 | ||
|
|
dee9b84322 | ||
|
|
ad98d61939 | ||
|
|
14758dbe10 | ||
|
|
d89a7d5235 | ||
|
|
640423c362 | ||
|
|
fd9c02603c | ||
|
|
44289e4c58 | ||
|
|
6928c685a8 | ||
|
|
dd408aa5d6 | ||
|
|
dac88c6aed | ||
|
|
78fe5a46c1 | ||
|
|
7a96d3c9ae | ||
|
|
b7b1e66c6e | ||
|
|
5ed7771148 | ||
|
|
c2076d86a4 | ||
|
|
b37c5e4878 | ||
|
|
26a5800a7f | ||
|
|
01efebc42f | ||
|
|
ab117527c9 | ||
|
|
f20f5cebbe | ||
|
|
0c3a8ddfb9 | ||
|
|
669a6cf119 | ||
|
|
6fe7b13e37 | ||
|
|
9c180e587b | ||
|
|
a368646745 | ||
|
|
de2cc58b0c | ||
|
|
d803d86f4d | ||
|
|
5254059fe4 | ||
|
|
d706571e6f | ||
|
|
907baea8b2 | ||
|
|
062536438e | ||
|
|
4ff035537b | ||
|
|
466a3b87fc | ||
|
|
b947f3c2a5 | ||
|
|
069da224bc | ||
|
|
e82460bde6 | ||
|
|
61c037f2cf | ||
|
|
f98290ba6e | ||
|
|
73343b3387 | ||
|
|
3a6020dcd7 | ||
|
|
596a269dfd | ||
|
|
7329fce87c | ||
|
|
4059116787 | ||
|
|
1561322af2 | ||
|
|
44d0a6f2b8 | ||
|
|
60b99469b9 | ||
|
|
46b975a491 | ||
|
|
70ad909b16 | ||
|
|
2af3ce3ecc | ||
|
|
132a4da7cf | ||
|
|
73f5bff9c5 | ||
|
|
223f0cd4d3 | ||
|
|
c4cb098d14 | ||
|
|
2bc74882e9 | ||
|
|
2ba388074e | ||
|
|
33164ac78e | ||
|
|
86624411c6 | ||
|
|
5cdae17d19 | ||
|
|
bd4a23beeb | ||
|
|
5c2682e2c9 | ||
|
|
6382a4cd04 | ||
|
|
704121c197 | ||
|
|
9c7696a8ce | ||
|
|
9e7e051eb4 | ||
|
|
616fe08bce | ||
|
|
141c454187 | ||
|
|
17fce00a5e | ||
|
|
0b8d04d75e | ||
|
|
e5487441ba | ||
|
|
48d83715a5 | ||
|
|
8b4fea4b71 | ||
|
|
4c1f0c3c59 | ||
|
|
13ae339a2e | ||
|
|
73a03565e5 | ||
|
|
bf20f3b7d8 | ||
|
|
20dabd9c41 | ||
|
|
32df73c056 | ||
|
|
ef1885c38b | ||
|
|
f5351e60e7 | ||
|
|
bfec9d974b | ||
|
|
3a7553eef6 | ||
|
|
d0521d33ce | ||
|
|
9155598ca4 | ||
|
|
ea6b94fd0c | ||
|
|
2a95d6855b | ||
|
|
3929ad4e1f | ||
|
|
2f1d9696cd | ||
|
|
2e896462c1 | ||
|
|
e63377980e | ||
|
|
41f97a73c9 | ||
|
|
0773a65333 | ||
|
|
8201f70a80 | ||
|
|
45b83cc544 | ||
|
|
b3e028e853 | ||
|
|
74b2f11d4f | ||
|
|
514e073c57 | ||
|
|
59e881c59d | ||
|
|
2e1e080022 | ||
|
|
13255b370c | ||
|
|
e1edf36307 | ||
|
|
470efd6f40 | ||
|
|
6640f4a1b2 | ||
|
|
e408274fb3 | ||
|
|
4ce278a06e | ||
|
|
a135eaa993 | ||
|
|
87ff7be550 | ||
|
|
7441300270 | ||
|
|
b4f4fae0ca | ||
|
|
336808ec54 | ||
|
|
b26faa13bd | ||
|
|
562e4e63de | ||
|
|
ad5f7e1581 | ||
|
|
3cf95f9f6c | ||
|
|
f0710cafd0 | ||
|
|
73fa5bae96 | ||
|
|
a43d436f98 | ||
|
|
ff5ba64385 | ||
|
|
7e38a07490 | ||
|
|
8872158a6a | ||
|
|
db3e789294 | ||
|
|
4813ff338b | ||
|
|
fbd7dc1d6c | ||
|
|
f07b26f245 | ||
|
|
3acc10dd48 | ||
|
|
e5f06c201f | ||
|
|
bf20cde83d | ||
|
|
364859394b | ||
|
|
657f1b6c45 | ||
|
|
e350bcc2ef | ||
|
|
c2566f2436 | ||
|
|
cac314d4b3 | ||
|
|
b116cc75c4 | ||
|
|
bedbd964fc | ||
|
|
1c503f39b2 | ||
|
|
ca4d0067e4 | ||
|
|
8a0d90136c | ||
|
|
5b680f2ece | ||
|
|
1bc63288a3 | ||
|
|
45b2d24b79 | ||
|
|
10ca249293 | ||
|
|
d6b6ded8bd | ||
|
|
2d34c0f52d | ||
|
|
f3cfe147b5 | ||
|
|
a52366c45d | ||
|
|
88c91a8a54 | ||
|
|
14755779de | ||
|
|
20dd3f2d67 | ||
|
|
8a31b4c646 | ||
|
|
78cd75dfef | ||
|
|
b805e4e150 | ||
|
|
df43b1f533 | ||
|
|
6e938b59c8 | ||
|
|
4f17511fdc | ||
|
|
d8630ef847 | ||
|
|
47fabca1d9 | ||
|
|
c48876b196 | ||
|
|
16e10d99b9 | ||
|
|
0adcee9233 | ||
|
|
f41c659cb2 | ||
|
|
4c977b2e01 | ||
|
|
b152585d9b | ||
|
|
fd22c87295 | ||
|
|
93b213ae0b | ||
|
|
30eb23e1aa | ||
|
|
4ec83a2c24 | ||
|
|
9e23ca14d1 | ||
|
|
ebf5738a6e | ||
|
|
c649f9844e | ||
|
|
3208f30c30 | ||
|
|
5e731ec278 | ||
|
|
e55b2a1a1c | ||
|
|
ed8d805797 | ||
|
|
0ebf2e44be | ||
|
|
00a95945e1 | ||
|
|
9d739f98ac | ||
|
|
2588990f4b | ||
|
|
271846dfb6 | ||
|
|
c181fac6c7 | ||
|
|
0ac46eddca | ||
|
|
c735d35265 | ||
|
|
e957894852 | ||
|
|
369335b80c | ||
|
|
2ebddcf45c | ||
|
|
8564affdf0 | ||
|
|
a39d51d7d0 | ||
|
|
750dc8bf56 | ||
|
|
033742b708 | ||
|
|
84ba431d10 | ||
|
|
b6e26c82ea | ||
|
|
e8eb968a6f | ||
|
|
66605a1909 | ||
|
|
1e61263a28 | ||
|
|
bd08874f1f | ||
|
|
ff6a3465a7 | ||
|
|
5b58141f6b | ||
|
|
bf4e9a5dbb | ||
|
|
837d4d82b4 | ||
|
|
a8ffd29e18 | ||
|
|
92fda0f76c | ||
|
|
df62dd65d3 | ||
|
|
d72d388726 | ||
|
|
fda71085e0 | ||
|
|
1a765f1a17 | ||
|
|
06ab51b53d | ||
|
|
7de1631045 | ||
|
|
4c8411e835 | ||
|
|
f348956e4c | ||
|
|
a4dfd77d23 | ||
|
|
89e0c76a3f | ||
|
|
abc504412a | ||
|
|
36d5bb6f99 | ||
|
|
ad89d19955 | ||
|
|
e6e35c2584 | ||
|
|
ace70510f3 | ||
|
|
cb4d6efb29 | ||
|
|
f1cddfdc62 | ||
|
|
6fb96183c0 | ||
|
|
a5c83b66df | ||
|
|
a320d4ccba | ||
|
|
790e6146f5 | ||
|
|
89283ef486 | ||
|
|
96bd5a6dc1 | ||
|
|
f5d8741832 | ||
|
|
effcc988c1 | ||
|
|
7ac3fbfdc9 | ||
|
|
4c4134a272 | ||
|
|
b2682bcbf5 | ||
|
|
4111734637 | ||
|
|
6e27c47dee | ||
|
|
18cc3539ca | ||
|
|
76ad5bea0e | ||
|
|
13e80e449c | ||
|
|
023eb19615 | ||
|
|
3e4617be37 | ||
|
|
ed9ec402fd | ||
|
|
56de81a1f9 | ||
|
|
ccb41d1ef9 | ||
|
|
2374cda8d0 | ||
|
|
1b7a09c184 | ||
|
|
37925e7f6c | ||
|
|
762ae3a598 | ||
|
|
9f8a2acf46 | ||
|
|
4fdec9d6e5 | ||
|
|
640d58eb13 | ||
|
|
fa8c61382b | ||
|
|
b6ac898f8f | ||
|
|
57bcff1964 | ||
|
|
939a87ed2e | ||
|
|
16d6914b15 | ||
|
|
05e473642b | ||
|
|
0d592f6c55 | ||
|
|
476adf872a | ||
|
|
9584629f50 | ||
|
|
c1c49183b5 | ||
|
|
8069cd6689 | ||
|
|
1f79ca9539 | ||
|
|
1d8fc97053 | ||
|
|
19f3669fbd | ||
|
|
06024b0ab0 | ||
|
|
6e952a0aa8 | ||
|
|
57dee794d1 | ||
|
|
2c0bb71a6e | ||
|
|
ab8f638e44 | ||
|
|
d250b67f33 | ||
|
|
42b8241541 | ||
|
|
6cc98c1ea9 | ||
|
|
77c367ad1d | ||
|
|
26b3148904 | ||
|
|
27dc9ca799 | ||
|
|
63e87ef85b | ||
|
|
6697b677dc | ||
|
|
baad1a5166 | ||
|
|
7cf7982565 | ||
|
|
f3f6e9d365 | ||
|
|
4228137dff | ||
|
|
3c8d27d098 | ||
|
|
2c200873c1 | ||
|
|
ff1fa17dc3 | ||
|
|
08e6d8a780 | ||
|
|
4c1705fb1e | ||
|
|
31389b38f1 | ||
|
|
ff7a3cc885 | ||
|
|
4d1488498c | ||
|
|
10a22e7872 | ||
|
|
e72b6a440b | ||
|
|
b5ca4b7f35 | ||
|
|
c49f4b73dd | ||
|
|
80cbf08a58 | ||
|
|
5e23cc719d | ||
|
|
0680fe2a1a | ||
|
|
bba5f54722 | ||
|
|
85c4546333 | ||
|
|
c4105436eb | ||
|
|
23b5c0e833 | ||
|
|
cdd1bc425b | ||
|
|
2a9c06c40f | ||
|
|
434e0234c5 | ||
|
|
caf415dc97 | ||
|
|
e9337bf56e | ||
|
|
bcd02a871f | ||
|
|
e1c14bc86c | ||
|
|
69c23c00e0 | ||
|
|
1e19d7e463 | ||
|
|
5e0391aa2b | ||
|
|
2e91ee3849 | ||
|
|
9b32d617db | ||
|
|
2ec8376af9 | ||
|
|
86ef32318c | ||
|
|
4d062d41cb | ||
|
|
e78e42339d | ||
|
|
057ab1b7a6 | ||
|
|
613300c61d | ||
|
|
7d1f66ccf8 | ||
|
|
a7418449f9 | ||
|
|
d68e6f8362 | ||
|
|
c34ce15b14 | ||
|
|
1350d2cd1a | ||
|
|
9db2aca791 | ||
|
|
80d58b7930 | ||
|
|
568ecc201a | ||
|
|
cad7ed5570 | ||
|
|
57bb9281f6 | ||
|
|
5e53e9bcaa | ||
|
|
edfbb56749 | ||
|
|
652a04ac70 | ||
|
|
5e9ab3e261 | ||
|
|
be6fd3af9a | ||
|
|
e272cd485c | ||
|
|
f27528538d | ||
|
|
ad35a3d7ab | ||
|
|
211b9cbe04 | ||
|
|
946b8c29d7 | ||
|
|
33940ae66b | ||
|
|
d2589c4415 | ||
|
|
22733e44bf | ||
|
|
82d4051a39 | ||
|
|
0664a8c0e6 | ||
|
|
9b23376415 | ||
|
|
553a1b90ba | ||
|
|
7ea9da9605 | ||
|
|
9b98e608e6 | ||
|
|
885edc9768 | ||
|
|
e1b8485b51 | ||
|
|
764a35d035 | ||
|
|
e93bbd3831 | ||
|
|
8938c95e00 | ||
|
|
00ab6f572a | ||
|
|
73e9cbdea1 | ||
|
|
78381e9e7b | ||
|
|
95299d94c4 | ||
|
|
75252b6251 | ||
|
|
f95b0ccdab | ||
|
|
38f184e50d | ||
|
|
1f4e5b17b7 | ||
|
|
9ee7e28ef8 | ||
|
|
3ac5b91899 | ||
|
|
4b29c4cdbf | ||
|
|
89729aefe8 | ||
|
|
15aae8a58c | ||
|
|
096c69dc4f | ||
|
|
2c0d2c1532 | ||
|
|
eca8ddabe9 | ||
|
|
c57d5ef1cd | ||
|
|
8c5b299449 | ||
|
|
543b19b376 | ||
|
|
f2e878d9ec | ||
|
|
b73426b91f | ||
|
|
628c4c996a | ||
|
|
642d20b2f7 | ||
|
|
f6a88c6e9b | ||
|
|
d1fa5f307b | ||
|
|
cd0e813a85 | ||
|
|
dc47a391da | ||
|
|
9f94678478 | ||
|
|
04fea69a28 | ||
|
|
d6a8821596 | ||
|
|
7617dd5029 | ||
|
|
e9d9df3473 | ||
|
|
b6ee3d99b1 | ||
|
|
9a2bd83827 | ||
|
|
f359f869ab | ||
|
|
d6fba7c2f3 | ||
|
|
498bcf213f | ||
|
|
33efb7ace6 | ||
|
|
d74ca78bd8 | ||
|
|
3c91ba134f | ||
|
|
9a83d84109 | ||
|
|
8ae4018e4d | ||
|
|
739901b606 | ||
|
|
03b5be91f7 | ||
|
|
272c977d08 | ||
|
|
75446d8195 | ||
|
|
52ff391c8a | ||
|
|
344a0a094f | ||
|
|
2710226326 | ||
|
|
381b0d3d07 | ||
|
|
52523bcd8b | ||
|
|
0d13e2cb2e | ||
|
|
014881e550 | ||
|
|
67b82638db | ||
|
|
09f18d07b0 | ||
|
|
9ef874e979 | ||
|
|
0aa73d5b35 | ||
|
|
ad2fa61765 | ||
|
|
e8106f3792 | ||
|
|
db3b974479 | ||
|
|
d62a4d3566 | ||
|
|
1b25b5f590 | ||
|
|
03add90c94 | ||
|
|
0f2e277f80 | ||
|
|
8664e7f7d3 | ||
|
|
cb37f43277 | ||
|
|
2a535b72ff | ||
|
|
cd2336887c | ||
|
|
448b09d7b6 | ||
|
|
704fea616b | ||
|
|
23665c7731 | ||
|
|
11bb7e520c | ||
|
|
83e596c06f | ||
|
|
9391c27b80 | ||
|
|
fe483ad011 | ||
|
|
0ce070acac | ||
|
|
cb6e136893 | ||
|
|
5c3fb4d5b3 | ||
|
|
7c6921c743 | ||
|
|
359b0ba088 | ||
|
|
5234f8bf28 | ||
|
|
9a3bad291a | ||
|
|
e8e05b6876 |
@@ -1,6 +1,7 @@
|
|||||||
[run]
|
[run]
|
||||||
omit =
|
omit =
|
||||||
scripts/*
|
scripts/*
|
||||||
|
freqtrade/templates/*
|
||||||
freqtrade/vendor/*
|
freqtrade/vendor/*
|
||||||
freqtrade/__main__.py
|
freqtrade/__main__.py
|
||||||
tests/*
|
tests/*
|
||||||
|
|||||||
233
.github/workflows/ci.yml
vendored
Normal file
233
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,233 @@
|
|||||||
|
name: Freqtrade CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
- develop
|
||||||
|
- github_actions_tests
|
||||||
|
tags:
|
||||||
|
pull_request:
|
||||||
|
schedule:
|
||||||
|
- cron: '0 5 * * 4'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [ ubuntu-18.04, macos-latest ]
|
||||||
|
python-version: [3.7]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v1
|
||||||
|
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v1
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
|
- name: Cache_dependencies
|
||||||
|
uses: actions/cache@v1
|
||||||
|
id: cache
|
||||||
|
with:
|
||||||
|
path: ~/dependencies/
|
||||||
|
key: ${{ runner.os }}-dependencies
|
||||||
|
|
||||||
|
- name: pip cache (linux)
|
||||||
|
uses: actions/cache@preview
|
||||||
|
if: startsWith(matrix.os, 'ubuntu')
|
||||||
|
with:
|
||||||
|
path: ~/.cache/pip
|
||||||
|
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
||||||
|
|
||||||
|
- name: pip cache (macOS)
|
||||||
|
uses: actions/cache@preview
|
||||||
|
if: startsWith(matrix.os, 'macOS')
|
||||||
|
with:
|
||||||
|
path: ~/Library/Caches/pip
|
||||||
|
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
||||||
|
|
||||||
|
- name: TA binary *nix
|
||||||
|
if: steps.cache.outputs.cache-hit != 'true'
|
||||||
|
run: |
|
||||||
|
cd build_helpers && ./install_ta-lib.sh ${HOME}/dependencies/; cd ..
|
||||||
|
|
||||||
|
- name: Installation - *nix
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH
|
||||||
|
export TA_LIBRARY_PATH=${HOME}/dependencies/lib
|
||||||
|
export TA_INCLUDE_PATH=${HOME}/dependencies/include
|
||||||
|
pip install -r requirements-dev.txt
|
||||||
|
pip install -e .
|
||||||
|
|
||||||
|
- name: Tests
|
||||||
|
run: |
|
||||||
|
pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
||||||
|
|
||||||
|
- name: Coveralls
|
||||||
|
if: startsWith(matrix.os, 'ubuntu')
|
||||||
|
env:
|
||||||
|
# Coveralls token. Not used as secret due to github not providing secrets to forked repositories
|
||||||
|
COVERALLS_REPO_TOKEN: 6D1m0xupS3FgutfuGao8keFf9Hc0FpIXu
|
||||||
|
run: |
|
||||||
|
# Allow failure for coveralls
|
||||||
|
coveralls -v || true
|
||||||
|
|
||||||
|
- name: Backtesting
|
||||||
|
run: |
|
||||||
|
cp config.json.example config.json
|
||||||
|
freqtrade create-userdir --userdir user_data
|
||||||
|
freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
|
||||||
|
|
||||||
|
- name: Hyperopt
|
||||||
|
run: |
|
||||||
|
cp config.json.example config.json
|
||||||
|
freqtrade create-userdir --userdir user_data
|
||||||
|
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt
|
||||||
|
|
||||||
|
- name: Flake8
|
||||||
|
run: |
|
||||||
|
flake8
|
||||||
|
|
||||||
|
- name: Mypy
|
||||||
|
run: |
|
||||||
|
mypy freqtrade scripts
|
||||||
|
|
||||||
|
- name: Slack Notification
|
||||||
|
uses: homoluctus/slatify@v1.8.0
|
||||||
|
if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
|
||||||
|
with:
|
||||||
|
type: ${{ job.status }}
|
||||||
|
job_name: '*Freqtrade CI ${{ matrix.os }}*'
|
||||||
|
mention: 'here'
|
||||||
|
mention_if: 'failure'
|
||||||
|
channel: '#notifications'
|
||||||
|
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
|
|
||||||
|
build_windows:
|
||||||
|
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [ windows-latest ]
|
||||||
|
python-version: [3.7]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v1
|
||||||
|
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v1
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
|
- name: Pip cache (Windows)
|
||||||
|
uses: actions/cache@preview
|
||||||
|
if: startsWith(runner.os, 'Windows')
|
||||||
|
with:
|
||||||
|
path: ~\AppData\Local\pip\Cache
|
||||||
|
key: ${{ runner.os }}-pip
|
||||||
|
restore-keys: ${{ runner.os }}-pip
|
||||||
|
|
||||||
|
- name: Installation
|
||||||
|
run: |
|
||||||
|
./build_helpers/install_windows.ps1
|
||||||
|
|
||||||
|
- name: Tests
|
||||||
|
run: |
|
||||||
|
pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
||||||
|
|
||||||
|
- name: Backtesting
|
||||||
|
run: |
|
||||||
|
cp config.json.example config.json
|
||||||
|
freqtrade create-userdir --userdir user_data
|
||||||
|
freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
|
||||||
|
|
||||||
|
- name: Hyperopt
|
||||||
|
run: |
|
||||||
|
cp config.json.example config.json
|
||||||
|
freqtrade create-userdir --userdir user_data
|
||||||
|
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt
|
||||||
|
|
||||||
|
- name: Flake8
|
||||||
|
run: |
|
||||||
|
flake8
|
||||||
|
|
||||||
|
- name: Mypy
|
||||||
|
run: |
|
||||||
|
mypy freqtrade scripts
|
||||||
|
|
||||||
|
- name: Slack Notification
|
||||||
|
uses: homoluctus/slatify@v1.8.0
|
||||||
|
if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
|
||||||
|
with:
|
||||||
|
type: ${{ job.status }}
|
||||||
|
job_name: '*Freqtrade CI windows*'
|
||||||
|
mention: 'here'
|
||||||
|
mention_if: 'failure'
|
||||||
|
channel: '#notifications'
|
||||||
|
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
|
|
||||||
|
docs_check:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v1
|
||||||
|
|
||||||
|
- name: Documentation syntax
|
||||||
|
run: |
|
||||||
|
./tests/test_docs.sh
|
||||||
|
|
||||||
|
- name: Slack Notification
|
||||||
|
uses: homoluctus/slatify@v1.8.0
|
||||||
|
if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
|
||||||
|
with:
|
||||||
|
type: ${{ job.status }}
|
||||||
|
job_name: '*Freqtrade Docs*'
|
||||||
|
channel: '#notifications'
|
||||||
|
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
|
|
||||||
|
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'
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v1
|
||||||
|
|
||||||
|
- name: Extract branch name
|
||||||
|
shell: bash
|
||||||
|
run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})"
|
||||||
|
id: extract_branch
|
||||||
|
|
||||||
|
- name: Build and test and push docker image
|
||||||
|
env:
|
||||||
|
IMAGE_NAME: freqtradeorg/freqtrade
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
BRANCH_NAME: ${{ steps.extract_branch.outputs.branch }}
|
||||||
|
run: |
|
||||||
|
build_helpers/publish_docker.sh
|
||||||
|
|
||||||
|
- name: Build raspberry image for ${{ steps.extract_branch.outputs.branch }}_pi
|
||||||
|
uses: elgohr/Publish-Docker-Github-Action@2.7
|
||||||
|
with:
|
||||||
|
name: freqtradeorg/freqtrade:${{ steps.extract_branch.outputs.branch }}_pi
|
||||||
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
dockerfile: Dockerfile.pi
|
||||||
|
# cache: true
|
||||||
|
cache: ${{ github.event_name != 'schedule' }}
|
||||||
|
tag_names: true
|
||||||
|
|
||||||
|
- name: Slack Notification
|
||||||
|
uses: homoluctus/slatify@v1.8.0
|
||||||
|
if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
|
||||||
|
with:
|
||||||
|
type: ${{ job.status }}
|
||||||
|
job_name: '*Freqtrade CI Deploy*'
|
||||||
|
mention: 'here'
|
||||||
|
mention_if: 'failure'
|
||||||
|
channel: '#notifications'
|
||||||
|
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
|
|
||||||
18
.github/workflows/docker_update_readme.yml
vendored
Normal file
18
.github/workflows/docker_update_readme.yml
vendored
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
name: Update Docker Hub Description
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
dockerHubDescription:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v1
|
||||||
|
- name: Docker Hub Description
|
||||||
|
uses: peter-evans/dockerhub-description@v2.1.0
|
||||||
|
env:
|
||||||
|
DOCKERHUB_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
DOCKERHUB_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
DOCKERHUB_REPOSITORY: freqtradeorg/freqtrade
|
||||||
|
|
||||||
21
.travis.yml
21
.travis.yml
@@ -24,31 +24,34 @@ jobs:
|
|||||||
script:
|
script:
|
||||||
- pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
- pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
||||||
# Allow failure for coveralls
|
# Allow failure for coveralls
|
||||||
- coveralls || true
|
# - coveralls || true
|
||||||
name: pytest
|
name: pytest
|
||||||
- script:
|
- script:
|
||||||
- cp config.json.example config.json
|
- cp config.json.example config.json
|
||||||
- freqtrade --datadir tests/testdata backtesting
|
- freqtrade create-userdir --userdir user_data
|
||||||
|
- freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
|
||||||
name: backtest
|
name: backtest
|
||||||
- script:
|
- script:
|
||||||
- cp config.json.example config.json
|
- cp config.json.example config.json
|
||||||
- freqtrade --datadir tests/testdata hyperopt -e 5
|
- freqtrade create-userdir --userdir user_data
|
||||||
|
- freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt
|
||||||
name: hyperopt
|
name: hyperopt
|
||||||
- script: flake8
|
- script: flake8
|
||||||
name: flake8
|
name: flake8
|
||||||
- script:
|
- script:
|
||||||
# Test Documentation boxes -
|
# Test Documentation boxes -
|
||||||
# !!! <TYPE>: is not allowed!
|
# !!! <TYPE>: is not allowed!
|
||||||
- grep -Er '^!{3}\s\S+:' docs/*; test $? -ne 0
|
# !!! <TYPE> "title" - Title needs to be quoted!
|
||||||
|
- grep -Er '^!{3}\s\S+:|^!{3}\s\S+\s[^"]' docs/*; test $? -ne 0
|
||||||
name: doc syntax
|
name: doc syntax
|
||||||
- script: mypy freqtrade scripts
|
- script: mypy freqtrade scripts
|
||||||
name: mypy
|
name: mypy
|
||||||
|
|
||||||
- stage: docker
|
# - stage: docker
|
||||||
if: branch in (master, develop, feat/improve_travis) AND (type in (push, cron))
|
# if: branch in (master, develop, feat/improve_travis) AND (type in (push, cron))
|
||||||
script:
|
# script:
|
||||||
- build_helpers/publish_docker.sh
|
# - build_helpers/publish_docker.sh
|
||||||
name: "Build and test and push docker image"
|
# name: "Build and test and push docker image"
|
||||||
|
|
||||||
notifications:
|
notifications:
|
||||||
slack:
|
slack:
|
||||||
|
|||||||
@@ -114,6 +114,6 @@ Contributors may be given commit privileges. Preference will be given to those w
|
|||||||
1. Access to resources for cross-platform development and testing.
|
1. Access to resources for cross-platform development and testing.
|
||||||
1. Time to devote to the project regularly.
|
1. Time to devote to the project regularly.
|
||||||
|
|
||||||
Beeing 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 beeing Committer for some time, a Committer may be named Core Committer and given full repository access.
|
After being Committer for some time, a Committer may be named Core Committer and given full repository access.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
FROM python:3.7.4-slim-stretch
|
FROM python:3.7.6-slim-stretch
|
||||||
|
|
||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get -y install curl build-essential libssl-dev \
|
&& apt-get -y install curl build-essential libssl-dev \
|
||||||
@@ -16,11 +16,13 @@ RUN cd /tmp && /tmp/install_ta-lib.sh && rm -r /tmp/*ta-lib*
|
|||||||
ENV LD_LIBRARY_PATH /usr/local/lib
|
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||||
|
|
||||||
# Install dependencies
|
# Install dependencies
|
||||||
COPY requirements.txt requirements-common.txt /freqtrade/
|
COPY requirements.txt requirements-common.txt requirements-hyperopt.txt /freqtrade/
|
||||||
RUN pip install numpy --no-cache-dir \
|
RUN pip install numpy --no-cache-dir \
|
||||||
&& pip install -r requirements.txt --no-cache-dir
|
&& pip install -r requirements-hyperopt.txt --no-cache-dir
|
||||||
|
|
||||||
# Install and execute
|
# Install and execute
|
||||||
COPY . /freqtrade/
|
COPY . /freqtrade/
|
||||||
RUN pip install -e . --no-cache-dir
|
RUN pip install -e . --no-cache-dir
|
||||||
ENTRYPOINT ["freqtrade"]
|
ENTRYPOINT ["freqtrade"]
|
||||||
|
# Default to trade mode
|
||||||
|
CMD [ "trade" ]
|
||||||
|
|||||||
@@ -38,3 +38,4 @@ RUN ~/berryconda3/bin/pip install -e . --no-cache-dir
|
|||||||
RUN [ "cross-build-end" ]
|
RUN [ "cross-build-end" ]
|
||||||
|
|
||||||
ENTRYPOINT ["/root/berryconda3/bin/python","./freqtrade/main.py"]
|
ENTRYPOINT ["/root/berryconda3/bin/python","./freqtrade/main.py"]
|
||||||
|
CMD [ "trade" ]
|
||||||
|
|||||||
@@ -62,7 +62,6 @@ git checkout develop
|
|||||||
|
|
||||||
For any other type of installation please refer to [Installation doc](https://www.freqtrade.io/en/latest/installation/).
|
For any other type of installation please refer to [Installation doc](https://www.freqtrade.io/en/latest/installation/).
|
||||||
|
|
||||||
|
|
||||||
## Basic Usage
|
## Basic Usage
|
||||||
|
|
||||||
### Bot commands
|
### Bot commands
|
||||||
@@ -106,7 +105,7 @@ optional arguments:
|
|||||||
|
|
||||||
### Telegram RPC commands
|
### Telegram RPC commands
|
||||||
|
|
||||||
Telegram is not mandatory. However, this is a great way to control your bot. More details on our [documentation](https://www.freqtrade.io/en/latest/telegram-usage/)
|
Telegram is not mandatory. However, this is a great way to control your bot. More details and the full command list on our [documentation](https://www.freqtrade.io/en/latest/telegram-usage/)
|
||||||
|
|
||||||
- `/start`: Starts the trader
|
- `/start`: Starts the trader
|
||||||
- `/stop`: Stops the trader
|
- `/stop`: Stops the trader
|
||||||
@@ -129,11 +128,6 @@ The project is currently setup in two main branches:
|
|||||||
- `master` - This branch contains the latest stable release. The bot 'should' be stable on this branch, and is generally well tested.
|
- `master` - This branch contains the latest stable release. The bot 'should' be stable on this branch, and is generally well tested.
|
||||||
- `feat/*` - These are feature branches, which are being worked on heavily. Please don't use these unless you want to test a specific feature.
|
- `feat/*` - These are feature branches, which are being worked on heavily. Please don't use these unless you want to test a specific feature.
|
||||||
|
|
||||||
## A note on Binance
|
|
||||||
|
|
||||||
For Binance, please add `"BNB/<STAKE>"` to your blacklist to avoid issues.
|
|
||||||
Accounts having BNB accounts use this to pay for fees - if your first trade happens to be on `BNB`, further trades will consume this position and make the initial BNB order unsellable as the expected amount is not there anymore.
|
|
||||||
|
|
||||||
## Support
|
## Support
|
||||||
|
|
||||||
### Help / Slack
|
### Help / Slack
|
||||||
|
|||||||
BIN
build_helpers/TA_Lib-0.4.17-cp37-cp37m-win_amd64.whl
Normal file
BIN
build_helpers/TA_Lib-0.4.17-cp37-cp37m-win_amd64.whl
Normal file
Binary file not shown.
9
build_helpers/install_windows.ps1
Normal file
9
build_helpers/install_windows.ps1
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
# Downloads don't work automatically, since the URL is regenerated via javascript.
|
||||||
|
# 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
|
||||||
|
pip install -e .
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# - export TAG=`if [ "$TRAVIS_BRANCH" == "develop" ]; then echo "latest"; else echo $TRAVIS_BRANCH ; fi`
|
|
||||||
# Replace / with _ to create a valid tag
|
|
||||||
TAG=$(echo "${TRAVIS_BRANCH}" | sed -e "s/\//_/")
|
|
||||||
|
|
||||||
|
# Replace / with _ to create a valid tag
|
||||||
|
TAG=$(echo "${BRANCH_NAME}" | sed -e "s/\//_/g")
|
||||||
|
echo "Running for ${TAG}"
|
||||||
|
|
||||||
# Add commit and commit_message to docker container
|
# Add commit and commit_message to docker container
|
||||||
echo "${TRAVIS_COMMIT} ${TRAVIS_COMMIT_MESSAGE}" > freqtrade_commit
|
echo "${GITHUB_SHA}" > freqtrade_commit
|
||||||
|
|
||||||
if [ "${TRAVIS_EVENT_TYPE}" = "cron" ]; then
|
if [ "${GITHUB_EVENT_NAME}" = "schedule" ]; then
|
||||||
echo "event ${TRAVIS_EVENT_TYPE}: full rebuild - skipping cache"
|
echo "event ${GITHUB_EVENT_NAME}: full rebuild - skipping cache"
|
||||||
docker build -t freqtrade:${TAG} .
|
docker build -t freqtrade:${TAG} .
|
||||||
else
|
else
|
||||||
echo "event ${TRAVIS_EVENT_TYPE}: building with cache"
|
echo "event ${GITHUB_EVENT_NAME}: building with cache"
|
||||||
# Pull last build to avoid rebuilding the whole image
|
# Pull last build to avoid rebuilding the whole image
|
||||||
docker pull ${IMAGE_NAME}:${TAG}
|
docker pull ${IMAGE_NAME}:${TAG}
|
||||||
docker build --cache-from ${IMAGE_NAME}:${TAG} -t freqtrade:${TAG} .
|
docker build --cache-from ${IMAGE_NAME}:${TAG} -t freqtrade:${TAG} .
|
||||||
@@ -23,7 +23,7 @@ if [ $? -ne 0 ]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# Run backtest
|
# Run backtest
|
||||||
docker run --rm -it -v $(pwd)/config.json.example:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} --datadir /tests/testdata backtesting
|
docker run --rm -v $(pwd)/config.json.example:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy DefaultStrategy
|
||||||
|
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "failed running backtest"
|
echo "failed running backtest"
|
||||||
@@ -38,12 +38,12 @@ if [ $? -ne 0 ]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# Tag as latest for develop builds
|
# Tag as latest for develop builds
|
||||||
if [ "${TRAVIS_BRANCH}" = "develop" ]; then
|
if [ "${TAG}" = "develop" ]; then
|
||||||
docker tag freqtrade:$TAG ${IMAGE_NAME}:latest
|
docker tag freqtrade:$TAG ${IMAGE_NAME}:latest
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Login
|
# Login
|
||||||
echo "$DOCKER_PASS" | docker login -u $DOCKER_USER --password-stdin
|
docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD
|
||||||
|
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "failed login"
|
echo "failed login"
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
"max_open_trades": 3,
|
"max_open_trades": 3,
|
||||||
"stake_currency": "BTC",
|
"stake_currency": "BTC",
|
||||||
"stake_amount": 0.05,
|
"stake_amount": 0.05,
|
||||||
|
"tradable_balance_ratio": 0.99,
|
||||||
"fiat_display_currency": "USD",
|
"fiat_display_currency": "USD",
|
||||||
"ticker_interval" : "5m",
|
"ticker_interval" : "5m",
|
||||||
"dry_run": false,
|
"dry_run": false,
|
||||||
@@ -22,7 +23,10 @@
|
|||||||
"ask_strategy":{
|
"ask_strategy":{
|
||||||
"use_order_book": false,
|
"use_order_book": false,
|
||||||
"order_book_min": 1,
|
"order_book_min": 1,
|
||||||
"order_book_max": 9
|
"order_book_max": 9,
|
||||||
|
"use_sell_signal": true,
|
||||||
|
"sell_profit_only": false,
|
||||||
|
"ignore_roi_if_buy_signal": false
|
||||||
},
|
},
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "bittrex",
|
"name": "bittrex",
|
||||||
@@ -41,7 +45,7 @@
|
|||||||
"ZEC/BTC",
|
"ZEC/BTC",
|
||||||
"XLM/BTC",
|
"XLM/BTC",
|
||||||
"NXT/BTC",
|
"NXT/BTC",
|
||||||
"POWR/BTC",
|
"TRX/BTC",
|
||||||
"ADA/BTC",
|
"ADA/BTC",
|
||||||
"XMR/BTC"
|
"XMR/BTC"
|
||||||
],
|
],
|
||||||
@@ -49,16 +53,13 @@
|
|||||||
"DOGE/BTC"
|
"DOGE/BTC"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"experimental": {
|
"pairlists": [
|
||||||
"use_sell_signal": false,
|
{"method": "StaticPairList"}
|
||||||
"sell_profit_only": false,
|
],
|
||||||
"ignore_roi_if_buy_signal": false
|
|
||||||
},
|
|
||||||
"edge": {
|
"edge": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"process_throttle_secs": 3600,
|
"process_throttle_secs": 3600,
|
||||||
"calculate_since_number_of_days": 7,
|
"calculate_since_number_of_days": 7,
|
||||||
"capital_available_percentage": 0.5,
|
|
||||||
"allowed_risk": 0.01,
|
"allowed_risk": 0.01,
|
||||||
"stoploss_range_min": -0.01,
|
"stoploss_range_min": -0.01,
|
||||||
"stoploss_range_max": -0.1,
|
"stoploss_range_max": -0.1,
|
||||||
@@ -70,7 +71,7 @@
|
|||||||
"remove_pumps": false
|
"remove_pumps": false
|
||||||
},
|
},
|
||||||
"telegram": {
|
"telegram": {
|
||||||
"enabled": true,
|
"enabled": false,
|
||||||
"token": "your_telegram_token",
|
"token": "your_telegram_token",
|
||||||
"chat_id": "your_telegram_chat_id"
|
"chat_id": "your_telegram_chat_id"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
"max_open_trades": 3,
|
"max_open_trades": 3,
|
||||||
"stake_currency": "BTC",
|
"stake_currency": "BTC",
|
||||||
"stake_amount": 0.05,
|
"stake_amount": 0.05,
|
||||||
|
"tradable_balance_ratio": 0.99,
|
||||||
"fiat_display_currency": "USD",
|
"fiat_display_currency": "USD",
|
||||||
"ticker_interval" : "5m",
|
"ticker_interval" : "5m",
|
||||||
"dry_run": true,
|
"dry_run": true,
|
||||||
@@ -22,7 +23,10 @@
|
|||||||
"ask_strategy":{
|
"ask_strategy":{
|
||||||
"use_order_book": false,
|
"use_order_book": false,
|
||||||
"order_book_min": 1,
|
"order_book_min": 1,
|
||||||
"order_book_max": 9
|
"order_book_max": 9,
|
||||||
|
"use_sell_signal": true,
|
||||||
|
"sell_profit_only": false,
|
||||||
|
"ignore_roi_if_buy_signal": false
|
||||||
},
|
},
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "binance",
|
"name": "binance",
|
||||||
@@ -34,33 +38,33 @@
|
|||||||
"rateLimit": 200
|
"rateLimit": 200
|
||||||
},
|
},
|
||||||
"pair_whitelist": [
|
"pair_whitelist": [
|
||||||
"AST/BTC",
|
"ALGO/BTC",
|
||||||
"ETC/BTC",
|
"ATOM/BTC",
|
||||||
"ETH/BTC",
|
"BAT/BTC",
|
||||||
|
"BCH/BTC",
|
||||||
|
"BRD/BTC",
|
||||||
"EOS/BTC",
|
"EOS/BTC",
|
||||||
|
"ETH/BTC",
|
||||||
"IOTA/BTC",
|
"IOTA/BTC",
|
||||||
|
"LINK/BTC",
|
||||||
"LTC/BTC",
|
"LTC/BTC",
|
||||||
"MTH/BTC",
|
"NEO/BTC",
|
||||||
"NCASH/BTC",
|
"NXS/BTC",
|
||||||
"TNT/BTC",
|
|
||||||
"XMR/BTC",
|
"XMR/BTC",
|
||||||
"XLM/BTC",
|
"XRP/BTC",
|
||||||
"XRP/BTC"
|
"XTZ/BTC"
|
||||||
],
|
],
|
||||||
"pair_blacklist": [
|
"pair_blacklist": [
|
||||||
"BNB/BTC"
|
"BNB/BTC"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"experimental": {
|
"pairlists": [
|
||||||
"use_sell_signal": false,
|
{"method": "StaticPairList"}
|
||||||
"sell_profit_only": false,
|
],
|
||||||
"ignore_roi_if_buy_signal": false
|
|
||||||
},
|
|
||||||
"edge": {
|
"edge": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"process_throttle_secs": 3600,
|
"process_throttle_secs": 3600,
|
||||||
"calculate_since_number_of_days": 7,
|
"calculate_since_number_of_days": 7,
|
||||||
"capital_available_percentage": 0.5,
|
|
||||||
"allowed_risk": 0.01,
|
"allowed_risk": 0.01,
|
||||||
"stoploss_range_min": -0.01,
|
"stoploss_range_min": -0.01,
|
||||||
"stoploss_range_max": -0.1,
|
"stoploss_range_max": -0.1,
|
||||||
|
|||||||
@@ -2,8 +2,11 @@
|
|||||||
"max_open_trades": 3,
|
"max_open_trades": 3,
|
||||||
"stake_currency": "BTC",
|
"stake_currency": "BTC",
|
||||||
"stake_amount": 0.05,
|
"stake_amount": 0.05,
|
||||||
|
"tradable_balance_ratio": 0.99,
|
||||||
"fiat_display_currency": "USD",
|
"fiat_display_currency": "USD",
|
||||||
"amount_reserve_percent" : 0.05,
|
"amount_reserve_percent" : 0.05,
|
||||||
|
"amend_last_stake_amount": false,
|
||||||
|
"last_stake_amount_min_ratio": 0.5,
|
||||||
"dry_run": false,
|
"dry_run": false,
|
||||||
"ticker_interval": "5m",
|
"ticker_interval": "5m",
|
||||||
"trailing_stop": false,
|
"trailing_stop": false,
|
||||||
@@ -33,7 +36,10 @@
|
|||||||
"ask_strategy":{
|
"ask_strategy":{
|
||||||
"use_order_book": false,
|
"use_order_book": false,
|
||||||
"order_book_min": 1,
|
"order_book_min": 1,
|
||||||
"order_book_max": 9
|
"order_book_max": 9,
|
||||||
|
"use_sell_signal": true,
|
||||||
|
"sell_profit_only": false,
|
||||||
|
"ignore_roi_if_buy_signal": false
|
||||||
},
|
},
|
||||||
"order_types": {
|
"order_types": {
|
||||||
"buy": "limit",
|
"buy": "limit",
|
||||||
@@ -47,14 +53,18 @@
|
|||||||
"buy": "gtc",
|
"buy": "gtc",
|
||||||
"sell": "gtc"
|
"sell": "gtc"
|
||||||
},
|
},
|
||||||
"pairlist": {
|
"pairlists": [
|
||||||
"method": "VolumePairList",
|
{"method": "StaticPairList"},
|
||||||
"config": {
|
{
|
||||||
|
"method": "VolumePairList",
|
||||||
"number_assets": 20,
|
"number_assets": 20,
|
||||||
"sort_key": "quoteVolume",
|
"sort_key": "quoteVolume",
|
||||||
"precision_filter": false
|
"refresh_period": 1800
|
||||||
|
},
|
||||||
|
{"method": "PrecisionFilter"},
|
||||||
|
{"method": "PriceFilter", "low_price_ratio": 0.01
|
||||||
}
|
}
|
||||||
},
|
],
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "bittrex",
|
"name": "bittrex",
|
||||||
"sandbox": false,
|
"sandbox": false,
|
||||||
@@ -75,7 +85,7 @@
|
|||||||
"ZEC/BTC",
|
"ZEC/BTC",
|
||||||
"XLM/BTC",
|
"XLM/BTC",
|
||||||
"NXT/BTC",
|
"NXT/BTC",
|
||||||
"POWR/BTC",
|
"TRX/BTC",
|
||||||
"ADA/BTC",
|
"ADA/BTC",
|
||||||
"XMR/BTC"
|
"XMR/BTC"
|
||||||
],
|
],
|
||||||
@@ -89,7 +99,6 @@
|
|||||||
"enabled": false,
|
"enabled": false,
|
||||||
"process_throttle_secs": 3600,
|
"process_throttle_secs": 3600,
|
||||||
"calculate_since_number_of_days": 7,
|
"calculate_since_number_of_days": 7,
|
||||||
"capital_available_percentage": 0.5,
|
|
||||||
"allowed_risk": 0.01,
|
"allowed_risk": 0.01,
|
||||||
"stoploss_range_min": -0.01,
|
"stoploss_range_min": -0.01,
|
||||||
"stoploss_range_max": -0.1,
|
"stoploss_range_max": -0.1,
|
||||||
@@ -100,11 +109,6 @@
|
|||||||
"max_trade_duration_minute": 1440,
|
"max_trade_duration_minute": 1440,
|
||||||
"remove_pumps": false
|
"remove_pumps": false
|
||||||
},
|
},
|
||||||
"experimental": {
|
|
||||||
"use_sell_signal": false,
|
|
||||||
"sell_profit_only": false,
|
|
||||||
"ignore_roi_if_buy_signal": false
|
|
||||||
},
|
|
||||||
"telegram": {
|
"telegram": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"token": "your_telegram_token",
|
"token": "your_telegram_token",
|
||||||
@@ -121,7 +125,8 @@
|
|||||||
"initial_state": "running",
|
"initial_state": "running",
|
||||||
"forcebuy_enable": false,
|
"forcebuy_enable": false,
|
||||||
"internals": {
|
"internals": {
|
||||||
"process_throttle_secs": 5
|
"process_throttle_secs": 5,
|
||||||
|
"heartbeat_interval": 60
|
||||||
},
|
},
|
||||||
"strategy": "DefaultStrategy",
|
"strategy": "DefaultStrategy",
|
||||||
"strategy_path": "user_data/strategies/"
|
"strategy_path": "user_data/strategies/"
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
"max_open_trades": 5,
|
"max_open_trades": 5,
|
||||||
"stake_currency": "EUR",
|
"stake_currency": "EUR",
|
||||||
"stake_amount": 10,
|
"stake_amount": 10,
|
||||||
|
"tradable_balance_ratio": 0.99,
|
||||||
"fiat_display_currency": "EUR",
|
"fiat_display_currency": "EUR",
|
||||||
"ticker_interval" : "5m",
|
"ticker_interval" : "5m",
|
||||||
"dry_run": true,
|
"dry_run": true,
|
||||||
@@ -22,7 +23,11 @@
|
|||||||
"ask_strategy":{
|
"ask_strategy":{
|
||||||
"use_order_book": false,
|
"use_order_book": false,
|
||||||
"order_book_min": 1,
|
"order_book_min": 1,
|
||||||
"order_book_max": 9
|
"order_book_max": 9,
|
||||||
|
"use_sell_signal": true,
|
||||||
|
"sell_profit_only": false,
|
||||||
|
"ignore_roi_if_buy_signal": false
|
||||||
|
|
||||||
},
|
},
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "kraken",
|
"name": "kraken",
|
||||||
@@ -34,19 +39,38 @@
|
|||||||
"rateLimit": 1000
|
"rateLimit": 1000
|
||||||
},
|
},
|
||||||
"pair_whitelist": [
|
"pair_whitelist": [
|
||||||
"ETH/EUR",
|
"ADA/EUR",
|
||||||
|
"ATOM/EUR",
|
||||||
|
"BAT/EUR",
|
||||||
|
"BCH/EUR",
|
||||||
"BTC/EUR",
|
"BTC/EUR",
|
||||||
"BCH/EUR"
|
"DAI/EUR",
|
||||||
|
"DASH/EUR",
|
||||||
|
"EOS/EUR",
|
||||||
|
"ETC/EUR",
|
||||||
|
"ETH/EUR",
|
||||||
|
"LINK/EUR",
|
||||||
|
"LTC/EUR",
|
||||||
|
"QTUM/EUR",
|
||||||
|
"REP/EUR",
|
||||||
|
"WAVES/EUR",
|
||||||
|
"XLM/EUR",
|
||||||
|
"XMR/EUR",
|
||||||
|
"XRP/EUR",
|
||||||
|
"XTZ/EUR",
|
||||||
|
"ZEC/EUR"
|
||||||
],
|
],
|
||||||
"pair_blacklist": [
|
"pair_blacklist": [
|
||||||
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"pairlists": [
|
||||||
|
{"method": "StaticPairList"}
|
||||||
|
],
|
||||||
"edge": {
|
"edge": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"process_throttle_secs": 3600,
|
"process_throttle_secs": 3600,
|
||||||
"calculate_since_number_of_days": 7,
|
"calculate_since_number_of_days": 7,
|
||||||
"capital_available_percentage": 0.5,
|
|
||||||
"allowed_risk": 0.01,
|
"allowed_risk": 0.01,
|
||||||
"stoploss_range_min": -0.01,
|
"stoploss_range_min": -0.01,
|
||||||
"stoploss_range_max": -0.1,
|
"stoploss_range_max": -0.1,
|
||||||
@@ -66,5 +90,6 @@
|
|||||||
"forcebuy_enable": false,
|
"forcebuy_enable": false,
|
||||||
"internals": {
|
"internals": {
|
||||||
"process_throttle_secs": 5
|
"process_throttle_secs": 5
|
||||||
}
|
},
|
||||||
|
"download_trades": true
|
||||||
}
|
}
|
||||||
|
|||||||
20
docker-compose.develop.yml
Normal file
20
docker-compose.develop.yml
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
version: '3'
|
||||||
|
services:
|
||||||
|
freqtrade_develop:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: "./Dockerfile.develop"
|
||||||
|
volumes:
|
||||||
|
- ".:/freqtrade"
|
||||||
|
entrypoint:
|
||||||
|
- "freqtrade"
|
||||||
|
|
||||||
|
freqtrade_bash:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: "./Dockerfile.develop"
|
||||||
|
volumes:
|
||||||
|
- ".:/freqtrade"
|
||||||
|
entrypoint:
|
||||||
|
- "/bin/bash"
|
||||||
8
docker-compose.yml
Normal file
8
docker-compose.yml
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
---
|
||||||
|
version: '3'
|
||||||
|
services:
|
||||||
|
freqtrade:
|
||||||
|
image: freqtradeorg/freqtrade:master
|
||||||
|
volumes:
|
||||||
|
- "./user_data:/freqtrade/user_data"
|
||||||
|
- "./config.json:/freqtrade/config.json"
|
||||||
63
docs/advanced-hyperopt.md
Normal file
63
docs/advanced-hyperopt.md
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
# Advanced Hyperopt
|
||||||
|
|
||||||
|
This page explains some advanced Hyperopt topics that may require higher
|
||||||
|
coding skills and Python knowledge than creation of an ordinal hyperoptimization
|
||||||
|
class.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
For the sample below, you then need to add the command line parameter `--hyperopt-loss SuperDuperHyperOptLoss` to your hyperopt call so this function is being used.
|
||||||
|
|
||||||
|
A sample of this can be found below, which is identical to the Default Hyperopt loss implementation. A full sample can be found in [userdata/hyperopts](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_loss.py).
|
||||||
|
|
||||||
|
``` python
|
||||||
|
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
||||||
|
|
||||||
|
TARGET_TRADES = 600
|
||||||
|
EXPECTED_MAX_PROFIT = 3.0
|
||||||
|
MAX_ACCEPTED_TRADE_DURATION = 300
|
||||||
|
|
||||||
|
class SuperDuperHyperOptLoss(IHyperOptLoss):
|
||||||
|
"""
|
||||||
|
Defines the default loss function for hyperopt
|
||||||
|
"""
|
||||||
|
|
||||||
|
@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 better results
|
||||||
|
This is the legacy algorithm (used until now in freqtrade).
|
||||||
|
Weights are distributed as follows:
|
||||||
|
* 0.4 to trade duration
|
||||||
|
* 0.25: Avoiding trade loss
|
||||||
|
* 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above
|
||||||
|
"""
|
||||||
|
total_profit = results.profit_percent.sum()
|
||||||
|
trade_duration = results.trade_duration.mean()
|
||||||
|
|
||||||
|
trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8)
|
||||||
|
profit_loss = max(0, 1 - total_profit / EXPECTED_MAX_PROFIT)
|
||||||
|
duration_loss = 0.4 * min(trade_duration / MAX_ACCEPTED_TRADE_DURATION, 1)
|
||||||
|
result = trade_loss + profit_loss + duration_loss
|
||||||
|
return result
|
||||||
|
```
|
||||||
|
|
||||||
|
Currently, the arguments are:
|
||||||
|
|
||||||
|
* `results`: DataFrame containing the result
|
||||||
|
The following columns are available in results (corresponds to the output-file of backtesting when used with `--export trades`):
|
||||||
|
`pair, profit_percent, profit_abs, open_time, close_time, open_index, close_index, trade_duration, open_at_end, open_rate, close_rate, sell_reason`
|
||||||
|
* `trade_count`: Amount of trades (identical to `len(results)`)
|
||||||
|
* `min_date`: Start date of the hyperopting TimeFrame
|
||||||
|
* `min_date`: End date of the hyperopting TimeFrame
|
||||||
|
|
||||||
|
This function needs to return a floating point number (`float`). Smaller numbers will be interpreted as better results. The parameters and balancing for this is up to you.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
This function is called once per iteration - so please make sure to have this as optimized as possible to not slow hyperopt down unnecessarily.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Please keep the arguments `*args` and `**kwargs` in the interface to allow us to extend this interface later.
|
||||||
92
docs/advanced-setup.md
Normal file
92
docs/advanced-setup.md
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
# Advanced Post-installation Tasks
|
||||||
|
|
||||||
|
This page explains some advanced tasks and configuration options that can be performed after the bot installation and may be uselful in some environments.
|
||||||
|
|
||||||
|
If you do not know what things mentioned here mean, you probably do not need it.
|
||||||
|
|
||||||
|
## Configure the bot running as a systemd service
|
||||||
|
|
||||||
|
Copy the `freqtrade.service` file to your systemd user directory (usually `~/.config/systemd/user`) and update `WorkingDirectory` and `ExecStart` to match your setup.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Certain systems (like Raspbian) don't load service unit files from the user directory. In this case, copy `freqtrade.service` into `/etc/systemd/user/` (requires superuser permissions).
|
||||||
|
|
||||||
|
After that you can start the daemon with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
systemctl --user start freqtrade
|
||||||
|
```
|
||||||
|
|
||||||
|
For this to be persistent (run when user is logged out) you'll need to enable `linger` for your freqtrade user.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo loginctl enable-linger "$USER"
|
||||||
|
```
|
||||||
|
|
||||||
|
If you run the bot as a service, you can use systemd service manager as a software watchdog monitoring freqtrade bot
|
||||||
|
state and restarting it in the case of failures. If the `internals.sd_notify` parameter is set to true in the
|
||||||
|
configuration or the `--sd-notify` command line option is used, the bot will send keep-alive ping messages to systemd
|
||||||
|
using the sd_notify (systemd notifications) protocol and will also tell systemd its current state (Running or Stopped)
|
||||||
|
when it changes.
|
||||||
|
|
||||||
|
The `freqtrade.service.watchdog` file contains an example of the service unit configuration file which uses systemd
|
||||||
|
as the watchdog.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
The sd_notify communication between the bot and the systemd service manager will not work if the bot runs in a Docker container.
|
||||||
|
|
||||||
|
## Advanced Logging
|
||||||
|
|
||||||
|
On many Linux systems the bot can be configured to send its log messages to `syslog` or `journald` system services. Logging to a remote `syslog` server is also available on Windows. The special values for the `--logfilename` command line option can be used for this.
|
||||||
|
|
||||||
|
### Logging to syslog
|
||||||
|
|
||||||
|
To send Freqtrade log messages to a local or remote `syslog` service use the `--logfilename` command line option with the value in the following format:
|
||||||
|
|
||||||
|
* `--logfilename syslog:<syslog_address>` -- send log messages to `syslog` service using the `<syslog_address>` as the syslog address.
|
||||||
|
|
||||||
|
The syslog address can be either a Unix domain socket (socket filename) or a UDP socket specification, consisting of IP address and UDP port, separated by the `:` character.
|
||||||
|
|
||||||
|
So, the following are the examples of possible usages:
|
||||||
|
|
||||||
|
* `--logfilename syslog:/dev/log` -- log to syslog (rsyslog) using the `/dev/log` socket, suitable for most systems.
|
||||||
|
* `--logfilename syslog` -- same as above, the shortcut for `/dev/log`.
|
||||||
|
* `--logfilename syslog:/var/run/syslog` -- log to syslog (rsyslog) using the `/var/run/syslog` socket. Use this on MacOS.
|
||||||
|
* `--logfilename syslog:localhost:514` -- log to local syslog using UDP socket, if it listens on port 514.
|
||||||
|
* `--logfilename syslog:<ip>:514` -- log to remote syslog at IP address and port 514. This may be used on Windows for remote logging to an external syslog server.
|
||||||
|
|
||||||
|
Log messages are send to `syslog` with the `user` facility. So you can see them with the following commands:
|
||||||
|
|
||||||
|
* `tail -f /var/log/user`, or
|
||||||
|
* install a comprehensive graphical viewer (for instance, 'Log File Viewer' for Ubuntu).
|
||||||
|
|
||||||
|
On many systems `syslog` (`rsyslog`) fetches data from `journald` (and vice versa), so both `--logfilename syslog` or `--logfilename journald` can be used and the messages be viewed with both `journalctl` and a syslog viewer utility. You can combine this in any way which suites you better.
|
||||||
|
|
||||||
|
For `rsyslog` the messages from the bot can be redirected into a separate dedicated log file. To achieve this, add
|
||||||
|
```
|
||||||
|
if $programname startswith "freqtrade" then -/var/log/freqtrade.log
|
||||||
|
```
|
||||||
|
to one of the rsyslog configuration files, for example at the end of the `/etc/rsyslog.d/50-default.conf`.
|
||||||
|
|
||||||
|
For `syslog` (`rsyslog`), the reduction mode can be switched on. This will reduce the number of repeating messages. For instance, multiple bot Heartbeat messages will be reduced to a single message when nothing else happens with the bot. To achieve this, set in `/etc/rsyslog.conf`:
|
||||||
|
```
|
||||||
|
# Filter duplicated messages
|
||||||
|
$RepeatedMsgReduction on
|
||||||
|
```
|
||||||
|
|
||||||
|
### Logging to journald
|
||||||
|
|
||||||
|
This needs the `systemd` python package installed as the dependency, which is not available on Windows. Hence, the whole journald logging functionality is not available for a bot running on Windows.
|
||||||
|
|
||||||
|
To send Freqtrade log messages to `journald` system service use the `--logfilename` command line option with the value in the following format:
|
||||||
|
|
||||||
|
* `--logfilename journald` -- send log messages to `journald`.
|
||||||
|
|
||||||
|
Log messages are send to `journald` with the `user` facility. So you can see them with the following commands:
|
||||||
|
|
||||||
|
* `journalctl -f` -- shows Freqtrade log messages sent to `journald` along with other log messages fetched by `journald`.
|
||||||
|
* `journalctl -f -u freqtrade.service` -- this command can be used when the bot is run as a `systemd` service.
|
||||||
|
|
||||||
|
There are many other options in the `journalctl` utility to filter the messages, see manual pages for this utility.
|
||||||
|
|
||||||
|
On many systems `syslog` (`rsyslog`) fetches data from `journald` (and vice versa), so both `--logfilename syslog` or `--logfilename journald` can be used and the messages be viewed with both `journalctl` and a syslog viewer utility. You can combine this in any way which suites you better.
|
||||||
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 |
@@ -11,14 +11,15 @@ Now you have good Buy and Sell strategies and some historic data, you want to te
|
|||||||
real data. This is what we call
|
real data. This is what we call
|
||||||
[backtesting](https://en.wikipedia.org/wiki/Backtesting).
|
[backtesting](https://en.wikipedia.org/wiki/Backtesting).
|
||||||
|
|
||||||
Backtesting will use the crypto-currencies (pairs) from your config file
|
Backtesting will use the crypto-currencies (pairs) from your config file and load ticker data from `user_data/data/<exchange>` by default.
|
||||||
and load ticker data from `user_data/data/<exchange>` by default.
|
If no data is available for the exchange / pair / ticker interval combination, backtesting will ask you to download them first using `freqtrade download-data`.
|
||||||
If no data is available for the exchange / pair / ticker interval combination, backtesting will
|
|
||||||
ask you to download them first using `freqtrade download-data`.
|
|
||||||
For details on downloading, please refer to the [Data Downloading](data-download.md) section in the documentation.
|
For details on downloading, please refer to the [Data Downloading](data-download.md) section in the documentation.
|
||||||
|
|
||||||
The result of backtesting will confirm if your bot has better odds of making a profit than a loss.
|
The result of backtesting will confirm if your bot has better odds of making a profit than a loss.
|
||||||
|
|
||||||
|
!!! Tip "Using dynamic pairlists for backtesting"
|
||||||
|
While using dynamic pairlists during backtesting is not possible, a dynamic pairlist using current data can be generated via the [`test-pairlist`](utils.md#test-pairlist) command, and needs to be specified as `"pair_whitelist"` attribute in the configuration.
|
||||||
|
|
||||||
### Run a backtesting against the currencies listed in your config file
|
### Run a backtesting against the currencies listed in your config file
|
||||||
|
|
||||||
#### With 5 min tickers (Per default)
|
#### With 5 min tickers (Per default)
|
||||||
@@ -39,13 +40,13 @@ Assume you downloaded the history data from the Bittrex exchange and kept it in
|
|||||||
You can then use this data for backtesting as follows:
|
You can then use this data for backtesting as follows:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade backtesting --datadir user_data/data/bittrex-20180101
|
freqtrade --datadir user_data/data/bittrex-20180101 backtesting
|
||||||
```
|
```
|
||||||
|
|
||||||
#### With a (custom) strategy file
|
#### With a (custom) strategy file
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade -s SampleStrategy backtesting
|
freqtrade backtesting -s SampleStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
Where `-s SampleStrategy` refers to the class name within the strategy file `sample_strategy.py` found in the `freqtrade/user_data/strategies` directory.
|
Where `-s SampleStrategy` refers to the class name within the strategy file `sample_strategy.py` found in the `freqtrade/user_data/strategies` directory.
|
||||||
@@ -72,6 +73,23 @@ The exported trades can be used for [further analysis](#further-backtest-result-
|
|||||||
freqtrade backtesting --export trades --export-filename=backtest_samplestrategy.json
|
freqtrade backtesting --export trades --export-filename=backtest_samplestrategy.json
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Please also read about the [strategy startup period](strategy-customization.md#strategy-startup-period).
|
||||||
|
|
||||||
|
#### 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 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
|
#### Running backtest with smaller testset by using timerange
|
||||||
|
|
||||||
Use the `--timerange` argument to change how much of the testset you want to use.
|
Use the `--timerange` argument to change how much of the testset you want to use.
|
||||||
@@ -92,12 +110,6 @@ The full timerange specification:
|
|||||||
- Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
|
- Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
|
||||||
- Use tickframes between POSIX timestamps 1527595200 1527618600:
|
- Use tickframes between POSIX timestamps 1527595200 1527618600:
|
||||||
`--timerange=1527595200-1527618600`
|
`--timerange=1527595200-1527618600`
|
||||||
- Use last 123 tickframes of data: `--timerange=-123`
|
|
||||||
- Use first 123 tickframes of data: `--timerange=123-`
|
|
||||||
- Use tickframes from line 123 through 456: `--timerange=123-456`
|
|
||||||
|
|
||||||
!!! warning
|
|
||||||
Be carefull when using non-date functions - these do not allow you to specify precise dates, so if you updated the test-data it will probably use a different dataset.
|
|
||||||
|
|
||||||
## Understand the backtesting result
|
## Understand the backtesting result
|
||||||
|
|
||||||
@@ -129,12 +141,12 @@ A backtesting result will look like that:
|
|||||||
| ZEC/BTC | 22 | -0.46 | -10.18 | -0.00050971 | -5.09 | 2:22:00 | 7 | 15 |
|
| 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 |
|
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 243 |
|
||||||
========================================================= SELL REASON STATS =========================================================
|
========================================================= SELL REASON STATS =========================================================
|
||||||
| Sell Reason | Count |
|
| Sell Reason | Count | Profit | Loss |
|
||||||
|:-------------------|--------:|
|
|:-------------------|--------:|---------:|-------:|
|
||||||
| trailing_stop_loss | 205 |
|
| trailing_stop_loss | 205 | 150 | 55 |
|
||||||
| stop_loss | 166 |
|
| stop_loss | 166 | 0 | 166 |
|
||||||
| sell_signal | 56 |
|
| sell_signal | 56 | 36 | 20 |
|
||||||
| force_sell | 2 |
|
| force_sell | 2 | 0 | 2 |
|
||||||
====================================================== LEFT OPEN TRADES REPORT ======================================================
|
====================================================== LEFT OPEN TRADES REPORT ======================================================
|
||||||
| pair | buy count | avg profit % | cum profit % | tot profit BTC | tot profit % | avg duration | profit | loss |
|
| pair | buy count | avg profit % | cum profit % | tot profit BTC | tot profit % | avg duration | profit | loss |
|
||||||
|:---------|------------:|---------------:|---------------:|-----------------:|---------------:|:---------------|---------:|-------:|
|
|:---------|------------:|---------------:|---------------:|-----------------:|---------------:|:---------------|---------:|-------:|
|
||||||
@@ -146,6 +158,7 @@ A backtesting result will look like that:
|
|||||||
The 1st table contains all trades the bot made, including "left open trades".
|
The 1st table contains all trades the bot made, including "left open trades".
|
||||||
|
|
||||||
The 2nd table contains a recap of sell reasons.
|
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.
|
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.
|
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.
|
||||||
@@ -184,14 +197,23 @@ Hence, keep in mind that your performance is an integral mix of all different el
|
|||||||
Since backtesting lacks some detailed information about what happens within a candle, it needs to take a few assumptions:
|
Since backtesting lacks some detailed information about what happens within a candle, it needs to take a few assumptions:
|
||||||
|
|
||||||
- Buys happen at open-price
|
- Buys happen at open-price
|
||||||
|
- Sell signal sells happen at open-price of the following candle
|
||||||
- Low happens before high for stoploss, protecting capital first.
|
- 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
|
- Stoploss sells happen exactly at stoploss price, even if low was lower
|
||||||
- Trailing stoploss
|
- Trailing stoploss
|
||||||
- High happens first - adjusting stoploss
|
- High happens first - adjusting stoploss
|
||||||
- Low uses the adjusted stoploss (so sells with large high-low difference are backtested correctly)
|
- Low uses the adjusted stoploss (so sells with large high-low difference are backtested correctly)
|
||||||
- Sell-reason does not explain if a trade was positive or negative, just what triggered the sell (this can look odd if negative ROI values are used)
|
- Sell-reason does not explain if a trade was positive or negative, just what triggered the sell (this can look odd if negative ROI values are used)
|
||||||
|
|
||||||
|
Taking these assumptions, backtesting tries to mirror real trading as closely as possible. However, backtesting will **never** replace running a strategy in dry-run mode.
|
||||||
|
Also, keep in mind that past results don't guarantee future success.
|
||||||
|
|
||||||
|
In addition to the above assumptions, strategy authors should carefully read the [Common Mistakes](strategy-customization.md#common-mistakes-when-developing-strategies) section, to avoid using data in backtesting which is not available in real market conditions.
|
||||||
|
|
||||||
### Further backtest-result analysis
|
### Further backtest-result analysis
|
||||||
|
|
||||||
To further analyze your backtest results, you can [export the trades](#exporting-trades-to-file).
|
To further analyze your backtest results, you can [export the trades](#exporting-trades-to-file).
|
||||||
|
|||||||
@@ -5,29 +5,57 @@ This page explains the different parameters of the bot and how to run it.
|
|||||||
!!! Note
|
!!! Note
|
||||||
If you've used `setup.sh`, don't forget to activate your virtual environment (`source .env/bin/activate`) before running freqtrade commands.
|
If you've used `setup.sh`, don't forget to activate your virtual environment (`source .env/bin/activate`) before running freqtrade commands.
|
||||||
|
|
||||||
|
|
||||||
## Bot commands
|
## Bot commands
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
usage: freqtrade [-h] [-V]
|
||||||
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
{trade,backtesting,edge,hyperopt,create-userdir,list-exchanges,list-timeframes,download-data,plot-dataframe,plot-profit}
|
||||||
[--db-url PATH] [--sd-notify]
|
...
|
||||||
{backtesting,edge,hyperopt,create-userdir,list-exchanges} ...
|
|
||||||
|
|
||||||
Free, open source crypto trading bot
|
Free, open source crypto trading bot
|
||||||
|
|
||||||
positional arguments:
|
positional arguments:
|
||||||
{backtesting,edge,hyperopt,create-userdir,list-exchanges}
|
{trade,backtesting,edge,hyperopt,create-userdir,list-exchanges,list-timeframes,download-data,plot-dataframe,plot-profit}
|
||||||
|
trade Trade module.
|
||||||
backtesting Backtesting module.
|
backtesting Backtesting module.
|
||||||
edge Edge module.
|
edge Edge module.
|
||||||
hyperopt Hyperopt module.
|
hyperopt Hyperopt module.
|
||||||
create-userdir Create user-data directory.
|
create-userdir Create user-data directory.
|
||||||
list-exchanges Print available exchanges.
|
list-exchanges Print available exchanges.
|
||||||
|
list-timeframes Print available ticker intervals (timeframes) for the
|
||||||
|
exchange.
|
||||||
|
download-data Download backtesting data.
|
||||||
|
plot-dataframe Plot candles with indicators.
|
||||||
|
plot-profit Generate plot showing profits.
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
|
-V, --version show program's version number and exit
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
### Bot trading commands
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade trade [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||||
|
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||||
|
[--db-url PATH] [--sd-notify] [--dry-run]
|
||||||
|
|
||||||
|
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:///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).
|
-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
|
-V, --version show program's version number and exit
|
||||||
-c PATH, --config PATH
|
-c PATH, --config PATH
|
||||||
Specify configuration file (default: `config.json`).
|
Specify configuration file (default: `config.json`).
|
||||||
@@ -37,14 +65,12 @@ optional arguments:
|
|||||||
Path to directory with historical backtesting data.
|
Path to directory with historical backtesting data.
|
||||||
--userdir PATH, --user-data-dir PATH
|
--userdir PATH, --user-data-dir PATH
|
||||||
Path to userdata directory.
|
Path to userdata directory.
|
||||||
|
|
||||||
|
Strategy arguments:
|
||||||
-s NAME, --strategy NAME
|
-s NAME, --strategy NAME
|
||||||
Specify strategy class name (default:
|
Specify strategy class name which will be used by the
|
||||||
`DefaultStrategy`).
|
bot.
|
||||||
--strategy-path PATH Specify additional strategy lookup path.
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
--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).
|
|
||||||
--sd-notify Notify systemd service manager.
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -54,7 +80,7 @@ The bot allows you to select which configuration file you want to use by means o
|
|||||||
the `-c/--config` command line option:
|
the `-c/--config` command line option:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade -c path/far/far/away/config.json
|
freqtrade trade -c path/far/far/away/config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
Per default, the bot loads the `config.json` configuration file from the current
|
Per default, the bot loads the `config.json` configuration file from the current
|
||||||
@@ -67,22 +93,22 @@ The bot allows you to use multiple configuration files by specifying multiple
|
|||||||
defined in the latter configuration files override parameters with the same name
|
defined in the latter configuration files override parameters with the same name
|
||||||
defined in the previous configuration files specified in the command line earlier.
|
defined in the previous configuration files specified in the command line earlier.
|
||||||
|
|
||||||
For example, you can make a separate configuration file with your key and secrete
|
For example, you can make a separate configuration file with your key and secret
|
||||||
for the Exchange you use for trading, specify default configuration file with
|
for the Exchange you use for trading, specify default configuration file with
|
||||||
empty key and secrete values while running in the Dry Mode (which does not actually
|
empty key and secret values while running in the Dry Mode (which does not actually
|
||||||
require them):
|
require them):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade -c ./config.json
|
freqtrade trade -c ./config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
and specify both configuration files when running in the normal Live Trade Mode:
|
and specify both configuration files when running in the normal Live Trade Mode:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade -c ./config.json -c path/to/secrets/keys.config.json
|
freqtrade trade -c ./config.json -c path/to/secrets/keys.config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
This could help you hide your private Exchange key and Exchange secrete on you local machine
|
This could help you hide your private Exchange key and Exchange secret on you local machine
|
||||||
by setting appropriate file permissions for the file which contains actual secrets and, additionally,
|
by setting appropriate file permissions for the file which contains actual secrets and, additionally,
|
||||||
prevent unintended disclosure of sensitive private data when you publish examples
|
prevent unintended disclosure of sensitive private data when you publish examples
|
||||||
of your configuration in the project issues or in the Internet.
|
of your configuration in the project issues or in the Internet.
|
||||||
@@ -100,7 +126,7 @@ user_data/
|
|||||||
├── backtest_results
|
├── backtest_results
|
||||||
├── data
|
├── data
|
||||||
├── hyperopts
|
├── hyperopts
|
||||||
├── hyperopts_results
|
├── hyperopt_results
|
||||||
├── plot
|
├── plot
|
||||||
└── strategies
|
└── strategies
|
||||||
```
|
```
|
||||||
@@ -128,7 +154,7 @@ In `user_data/strategies` you have a file `my_awesome_strategy.py` which has
|
|||||||
a strategy class called `AwesomeStrategy` to load it:
|
a strategy class called `AwesomeStrategy` to load it:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade --strategy AwesomeStrategy
|
freqtrade trade --strategy AwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
If the bot does not find your strategy file, it will display in an error
|
If the bot does not find your strategy file, it will display in an error
|
||||||
@@ -143,7 +169,7 @@ This parameter allows you to add an additional strategy lookup path, which gets
|
|||||||
checked before the default locations (The passed path must be a directory!):
|
checked before the default locations (The passed path must be a directory!):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade --strategy AwesomeStrategy --strategy-path /some/directory
|
freqtrade trade --strategy AwesomeStrategy --strategy-path /some/directory
|
||||||
```
|
```
|
||||||
|
|
||||||
#### How to install a strategy?
|
#### How to install a strategy?
|
||||||
@@ -159,7 +185,7 @@ using `--db-url`. This can also be used to specify a custom database
|
|||||||
in production mode. Example command:
|
in production mode. Example command:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite
|
freqtrade trade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite
|
||||||
```
|
```
|
||||||
|
|
||||||
## Backtesting commands
|
## Backtesting commands
|
||||||
@@ -167,23 +193,30 @@ freqtrade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite
|
|||||||
Backtesting also uses the config specified via `-c/--config`.
|
Backtesting also uses the config specified via `-c/--config`.
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade backtesting [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
[--max_open_trades MAX_OPEN_TRADES]
|
[-d PATH] [--userdir PATH] [-s NAME]
|
||||||
[--stake_amount STAKE_AMOUNT] [-r] [--eps] [--dmmp]
|
[--strategy-path PATH] [-i TICKER_INTERVAL]
|
||||||
[-l]
|
[--timerange TIMERANGE] [--max-open-trades INT]
|
||||||
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
|
||||||
[--export EXPORT] [--export-filename PATH]
|
[--eps] [--dmmp]
|
||||||
|
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
||||||
|
[--export EXPORT] [--export-filename PATH]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||||
Specify ticker interval (1m, 5m, 30m, 1h, 1d).
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
|
`1d`).
|
||||||
--timerange TIMERANGE
|
--timerange TIMERANGE
|
||||||
Specify what timerange of data to use.
|
Specify what timerange of data to use.
|
||||||
--max_open_trades MAX_OPEN_TRADES
|
--max-open-trades INT
|
||||||
Specify max_open_trades to use.
|
Override the value of the `max_open_trades`
|
||||||
--stake_amount STAKE_AMOUNT
|
configuration setting.
|
||||||
Specify stake_amount.
|
--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
|
--eps, --enable-position-stacking
|
||||||
Allow buying the same pair multiple times (position
|
Allow buying the same pair multiple times (position
|
||||||
stacking).
|
stacking).
|
||||||
@@ -193,26 +226,46 @@ optional arguments:
|
|||||||
number).
|
number).
|
||||||
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
|
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
|
||||||
Provide a space-separated list of strategies to
|
Provide a space-separated list of strategies to
|
||||||
backtest Please note that ticker-interval needs to be
|
backtest. Please note that ticker-interval needs to be
|
||||||
set either in config or via command line. When using
|
set either in config or via command line. When using
|
||||||
this together with --export trades, the strategy-name
|
this together with `--export trades`, the strategy-
|
||||||
is injected into the filename (so backtest-data.json
|
name is injected into the filename (so `backtest-
|
||||||
becomes backtest-data-DefaultStrategy.json
|
data.json` becomes `backtest-data-
|
||||||
--export EXPORT Export backtest results, argument are: trades. Example
|
DefaultStrategy.json`
|
||||||
--export=trades
|
--export EXPORT Export backtest results, argument are: trades.
|
||||||
|
Example: `--export=trades`
|
||||||
--export-filename PATH
|
--export-filename PATH
|
||||||
Save backtest results to this filename requires
|
Save backtest results to the file with this filename.
|
||||||
--export to be set as well Example --export-
|
Requires `--export` to be set as well. Example:
|
||||||
filename=user_data/backtest_results/backtest_today.json
|
`--export-filename=user_data/backtest_results/backtest
|
||||||
(default: user_data/backtest_results/backtest-
|
_today.json`
|
||||||
result.json)
|
|
||||||
|
Common arguments:
|
||||||
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
|
--logfile FILE Log to the file specified.
|
||||||
|
-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.
|
||||||
|
|
||||||
|
Strategy arguments:
|
||||||
|
-s NAME, --strategy NAME
|
||||||
|
Specify strategy class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Getting historic data for backtesting
|
### Getting historic data for backtesting
|
||||||
|
|
||||||
The first time your run Backtesting, you will need to download some historic data first.
|
The first time your run Backtesting, you will need to download some historic data first.
|
||||||
This can be accomplished by using `freqtrade download-data`.
|
This can be accomplished by using `freqtrade download-data`.
|
||||||
Check the corresponding [help page section](backtesting.md#Getting-data-for-backtesting-and-hyperopt) for more details
|
Check the corresponding [Data Downloading](data-download.md) section for more details
|
||||||
|
|
||||||
## Hyperopt commands
|
## Hyperopt commands
|
||||||
|
|
||||||
@@ -220,15 +273,17 @@ To optimize your strategy, you can use hyperopt parameter hyperoptimization
|
|||||||
to find optimal parameter values for your stategy.
|
to find optimal parameter values for your stategy.
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade hyperopt [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||||
[--max_open_trades INT]
|
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||||
[--stake_amount STAKE_AMOUNT] [-r]
|
[-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
||||||
[--customhyperopt NAME] [--hyperopt-path PATH]
|
[--max-open-trades INT]
|
||||||
[--eps] [-e INT]
|
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
|
||||||
[-s {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...]]
|
[--hyperopt NAME] [--hyperopt-path PATH] [--eps]
|
||||||
[--dmmp] [--print-all] [--no-color] [-j JOBS]
|
[-e INT]
|
||||||
[--random-state INT] [--min-trades INT] [--continue]
|
[--spaces {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...]]
|
||||||
[--hyperopt-loss NAME]
|
[--dmmp] [--print-all] [--no-color] [--print-json]
|
||||||
|
[-j JOBS] [--random-state INT] [--min-trades INT]
|
||||||
|
[--continue] [--hyperopt-loss NAME]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
@@ -237,20 +292,23 @@ optional arguments:
|
|||||||
`1d`).
|
`1d`).
|
||||||
--timerange TIMERANGE
|
--timerange TIMERANGE
|
||||||
Specify what timerange of data to use.
|
Specify what timerange of data to use.
|
||||||
--max_open_trades INT
|
--max-open-trades INT
|
||||||
Specify max_open_trades to use.
|
Override the value of the `max_open_trades`
|
||||||
--stake_amount STAKE_AMOUNT
|
configuration setting.
|
||||||
Specify stake_amount.
|
--stake-amount STAKE_AMOUNT
|
||||||
--customhyperopt NAME
|
Override the value of the `stake_amount` configuration
|
||||||
Specify hyperopt class name (default:
|
setting.
|
||||||
`DefaultHyperOpts`).
|
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
|
||||||
--hyperopt-path PATH Specify additional lookup path for Hyperopts and
|
entry and exit).
|
||||||
|
--hyperopt NAME Specify hyperopt class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--hyperopt-path PATH Specify additional lookup path for Hyperopt and
|
||||||
Hyperopt Loss functions.
|
Hyperopt Loss functions.
|
||||||
--eps, --enable-position-stacking
|
--eps, --enable-position-stacking
|
||||||
Allow buying the same pair multiple times (position
|
Allow buying the same pair multiple times (position
|
||||||
stacking).
|
stacking).
|
||||||
-e INT, --epochs INT Specify number of epochs (default: 100).
|
-e INT, --epochs INT Specify number of epochs (default: 100).
|
||||||
-s {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...], --spaces {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...]
|
--spaces {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...]
|
||||||
Specify which parameters to hyperopt. Space-separated
|
Specify which parameters to hyperopt. Space-separated
|
||||||
list. Default: `all`.
|
list. Default: `all`.
|
||||||
--dmmp, --disable-max-market-positions
|
--dmmp, --disable-max-market-positions
|
||||||
@@ -260,6 +318,7 @@ optional arguments:
|
|||||||
--print-all Print all results, not only the best ones.
|
--print-all Print all results, not only the best ones.
|
||||||
--no-color Disable colorization of hyperopt results. May be
|
--no-color Disable colorization of hyperopt results. May be
|
||||||
useful if you are redirecting output to a file.
|
useful if you are redirecting output to a file.
|
||||||
|
--print-json Print best result detailization in JSON format.
|
||||||
-j JOBS, --job-workers JOBS
|
-j JOBS, --job-workers JOBS
|
||||||
The number of concurrently running jobs for
|
The number of concurrently running jobs for
|
||||||
hyperoptimization (hyperopt worker processes). If -1
|
hyperoptimization (hyperopt worker processes). If -1
|
||||||
@@ -278,8 +337,27 @@ optional arguments:
|
|||||||
generate completely different results, since the
|
generate completely different results, since the
|
||||||
target for optimization is different. Built-in
|
target for optimization is different. Built-in
|
||||||
Hyperopt-loss-functions are: DefaultHyperOptLoss,
|
Hyperopt-loss-functions are: DefaultHyperOptLoss,
|
||||||
OnlyProfitHyperOptLoss, SharpeHyperOptLoss.
|
OnlyProfitHyperOptLoss, SharpeHyperOptLoss (default:
|
||||||
(default: `DefaultHyperOptLoss`).
|
`DefaultHyperOptLoss`).
|
||||||
|
|
||||||
|
Common arguments:
|
||||||
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
|
--logfile FILE Log to the file specified.
|
||||||
|
-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.
|
||||||
|
|
||||||
|
Strategy arguments:
|
||||||
|
-s NAME, --strategy NAME
|
||||||
|
Specify strategy class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Edge commands
|
## Edge commands
|
||||||
@@ -287,26 +365,51 @@ optional arguments:
|
|||||||
To know your trade expectancy and winrate against historical data, you can use Edge.
|
To know your trade expectancy and winrate against historical data, you can use Edge.
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade edge [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
usage: freqtrade edge [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||||
[--max_open_trades MAX_OPEN_TRADES]
|
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||||
[--stake_amount STAKE_AMOUNT] [-r]
|
[-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
||||||
[--stoplosses STOPLOSS_RANGE]
|
[--max-open-trades INT] [--stake-amount STAKE_AMOUNT]
|
||||||
|
[--fee FLOAT] [--stoplosses STOPLOSS_RANGE]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||||
Specify ticker interval (1m, 5m, 30m, 1h, 1d).
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
|
`1d`).
|
||||||
--timerange TIMERANGE
|
--timerange TIMERANGE
|
||||||
Specify what timerange of data to use.
|
Specify what timerange of data to use.
|
||||||
--max_open_trades MAX_OPEN_TRADES
|
--max-open-trades INT
|
||||||
Specify max_open_trades to use.
|
Override the value of the `max_open_trades`
|
||||||
--stake_amount STAKE_AMOUNT
|
configuration setting.
|
||||||
Specify stake_amount.
|
--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
|
--stoplosses STOPLOSS_RANGE
|
||||||
Defines a range of stoploss against which edge will
|
Defines a range of stoploss values against which edge
|
||||||
assess the strategy the format is "min,max,step"
|
will assess the strategy. The format is "min,max,step"
|
||||||
(without any space).example:
|
(without any space). Example:
|
||||||
--stoplosses=-0.01,-0.1,-0.001
|
`--stoplosses=-0.01,-0.1,-0.001`
|
||||||
|
|
||||||
|
Common arguments:
|
||||||
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
|
--logfile FILE Log to the file specified.
|
||||||
|
-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.
|
||||||
|
|
||||||
|
Strategy arguments:
|
||||||
|
-s NAME, --strategy NAME
|
||||||
|
Specify strategy class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
```
|
```
|
||||||
|
|
||||||
To understand edge and how to read the results, please read the [edge documentation](edge.md).
|
To understand edge and how to read the results, please read the [edge documentation](edge.md).
|
||||||
|
|||||||
@@ -38,104 +38,171 @@ 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.
|
Mandatory parameters are marked as **Required**, which means that they are required to be set in one of the possible ways.
|
||||||
|
|
||||||
| Command | Default | Description |
|
| Parameter | Description |
|
||||||
|----------|---------|-------------|
|
|------------|-------------|
|
||||||
| `max_open_trades` | 3 | **Required.** Number of trades open your bot will have. If -1 then it is ignored (i.e. potentially unlimited open trades)
|
| `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` | BTC | **Required.** Crypto-currency used for trading.
|
| `stake_currency` | **Required.** Crypto-currency used for trading. [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *String*
|
||||||
| `stake_amount` | 0.05 | **Required.** Amount of crypto-currency your bot will use for each trade. Per default, the bot will use (0.05 BTC x 3) = 0.15 BTC in total will be always engaged. Set it to `"unlimited"` to allow the bot to use all available balance.
|
| `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"`.*
|
||||||
| `amount_reserve_percent` | 0.05 | Reserve some amount in min pair stake amount. Default is 5%. The bot will reserve `amount_reserve_percent` + stop-loss value when calculating min pair stake amount in order to avoid possible trade refusals.
|
| `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`.*
|
||||||
| `ticker_interval` | [1m, 5m, 15m, 30m, 1h, 1d, ...] | The ticker interval to use (1min, 5 min, 15 min, 30 min, 1 hour or 1 day). Default is 5 minutes. [Strategy Override](#parameters-in-the-strategy).
|
| `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*
|
||||||
| `fiat_display_currency` | USD | **Required.** Fiat currency used to show your profits. More information below.
|
| `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)*
|
||||||
| `dry_run` | true | **Required.** Define if the bot must be in Dry-run or production mode.
|
| `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.*
|
||||||
| `dry_run_wallet` | 999.9 | 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.
|
| `ticker_interval` | The ticker interval to use (e.g `1m`, `5m`, `15m`, `30m`, `1h` ...). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *String*
|
||||||
| `process_only_new_candles` | false | If set to true indicators are processed only once a new candle arrives. 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).
|
| `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*
|
||||||
| `minimal_roi` | See below | Set the threshold in percent the bot will use to sell a trade. More information below. [Strategy Override](#parameters-in-the-strategy).
|
| `dry_run` | **Required.** Define if the bot must be in Dry Run or production mode. <br>*Defaults to `true`.* <br> ***Datatype:*** *Boolean*
|
||||||
| `stoploss` | -0.10 | Value of the stoploss in percent used by the bot. More information below. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
| `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*
|
||||||
| `trailing_stop` | false | Enables trailing stop-loss (based on `stoploss` in either configuration or strategy file). More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
| `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*
|
||||||
| `trailing_stop_positive` | 0 | Changes stop-loss once profit has been reached. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
| `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*
|
||||||
| `trailing_stop_positive_offset` | 0 | 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).
|
| `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_only_offset_is_reached` | false | Only apply trailing stoploss when the offset is reached. [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
| `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*
|
||||||
| `unfilledtimeout.buy` | 10 | **Required.** How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled.
|
| `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*
|
||||||
| `unfilledtimeout.sell` | 10 | **Required.** How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled.
|
| `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*
|
||||||
| `bid_strategy.ask_last_balance` | 0.0 | **Required.** Set the bidding price. More information [below](#understand-ask_last_balance).
|
| `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*
|
||||||
| `bid_strategy.use_order_book` | false | Allows buying of pair using the rates in Order Book Bids.
|
| `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*
|
||||||
| `bid_strategy.order_book_top` | 0 | Bot will use the top N rate in Order Book Bids. Ie. a value of 2 will allow the bot to pick the 2nd bid rate in Order Book Bids.
|
| `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. check_depth_of_market.enabled` | false | Does not buy if the % difference of buy orders and sell orders is met in Order Book.
|
| `bid_strategy.ask_last_balance` | **Required.** Set the bidding price. More information [below](#buy-price-without-orderbook).
|
||||||
| `bid_strategy. check_depth_of_market.bids_to_ask_delta` | 0 | 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.
|
| `bid_strategy.use_order_book` | Enable buying using the rates in [Order Book Bids](#buy-price-with-orderbook-enabled). <br> ***Datatype:*** *Boolean*
|
||||||
| `ask_strategy.use_order_book` | false | Allows selling of open traded pair using the rates in Order Book Asks.
|
| `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*
|
||||||
| `ask_strategy.order_book_min` | 0 | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
| `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*
|
||||||
| `ask_strategy.order_book_max` | 0 | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
| `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)*
|
||||||
| `order_types` | None | 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).
|
| `ask_strategy.use_order_book` | Enable selling of open trades using [Order Book Asks](#sell-price-with-orderbook-enabled). <br> ***Datatype:*** *Boolean*
|
||||||
| `order_time_in_force` | None | Configure time in force for buy and sell orders. [More information below](#understand-order_time_in_force). [Strategy Override](#parameters-in-the-strategy).
|
| `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*
|
||||||
| `exchange.name` | | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename).
|
| `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*
|
||||||
| `exchange.sandbox` | false | 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.
|
| `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*
|
||||||
| `exchange.key` | '' | API key to use for the exchange. Only required when you are in production mode. ***Keep it in secrete, do not disclose publicly.***
|
| `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*
|
||||||
| `exchange.secret` | '' | API secret to use for the exchange. Only required when you are in production mode. ***Keep it in secrete, do not disclose publicly.***
|
| `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*
|
||||||
| `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 secrete, do not disclose publicly.***
|
| `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*
|
||||||
| `exchange.pair_whitelist` | [] | List of pairs to use by the bot for trading and to check for potential trades during backtesting. Can be overriden by dynamic pairlists (see [below](#dynamic-pairlists)).
|
| `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.pair_blacklist` | [] | List of pairs the bot must absolutely avoid for trading and backtesting. Can be overriden by dynamic pairlists (see [below](#dynamic-pairlists)).
|
| `exchange.name` | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename). <br> ***Datatype:*** *String*
|
||||||
| `exchange.ccxt_config` | None | 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)
|
| `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.ccxt_async_config` | None | 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)
|
| `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.markets_refresh_interval` | 60 | The interval in minutes in which markets are reloaded.
|
| `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*
|
||||||
| `edge` | false | Please refer to [edge configuration document](edge.md) for detailed explanation.
|
| `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*
|
||||||
| `experimental.use_sell_signal` | false | Use your sell strategy in addition of the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy).
|
| `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*
|
||||||
| `experimental.sell_profit_only` | false | Waits until you have made a positive profit before taking a sell decision. [Strategy Override](#parameters-in-the-strategy).
|
| `exchange.pair_blacklist` | List of pairs the bot must absolutely avoid for trading and backtesting (see [below](#dynamic-pairlists)). <br> ***Datatype:*** *List*
|
||||||
| `experimental.ignore_roi_if_buy_signal` | false | Does not sell if the buy-signal is still active. Takes preference over `minimal_roi` and `use_sell_signal`. [Strategy Override](#parameters-in-the-strategy).
|
| `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*
|
||||||
| `experimental.block_bad_exchanges` | true | Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now.
|
| `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*
|
||||||
| `pairlist.method` | StaticPairList | Use static or dynamic volume-based pairlist. [More information below](#dynamic-pairlists).
|
| `exchange.markets_refresh_interval` | The interval in minutes in which markets are reloaded. <br>*Defaults to `60` minutes.* <br> ***Datatype:*** *Positive Integer*
|
||||||
| `pairlist.config` | None | Additional configuration for dynamic pairlists. [More information below](#dynamic-pairlists).
|
| `edge.*` | Please refer to [edge configuration document](edge.md) for detailed explanation.
|
||||||
| `telegram.enabled` | true | **Required.** Enable or not the usage of Telegram.
|
| `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*
|
||||||
| `telegram.token` | token | Your Telegram bot token. Only required if `telegram.enabled` is `true`. ***Keep it in secrete, do not disclose publicly.***
|
| `pairlists` | Define one or more pairlists to be used. [More information below](#dynamic-pairlists). <br>*Defaults to `StaticPairList`.* <br> ***Datatype:*** *List of Dicts*
|
||||||
| `telegram.chat_id` | chat_id | Your personal Telegram account id. Only required if `telegram.enabled` is `true`. ***Keep it in secrete, do not disclose publicly.***
|
| `telegram.enabled` | Enable the usage of Telegram. <br> ***Datatype:*** *Boolean*
|
||||||
| `webhook.enabled` | false | Enable usage of Webhook notifications
|
| `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*
|
||||||
| `webhook.url` | false | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details.
|
| `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.webhookbuy` | false | Payload to send on buy. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details.
|
| `webhook.enabled` | Enable usage of Webhook notifications <br> ***Datatype:*** *Boolean*
|
||||||
| `webhook.webhooksell` | false | Payload to send on sell. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details.
|
| `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.webhookstatus` | false | Payload to send on status calls. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details.
|
| `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*
|
||||||
| `db_url` | `sqlite:///tradesv3.sqlite`| Declares database URL to use. NOTE: This defaults to `sqlite://` if `dry_run` is `True`.
|
| `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*
|
||||||
| `initial_state` | running | Defines the initial application state. More information below.
|
| `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*
|
||||||
| `forcebuy_enable` | false | Enables the RPC Commands to force a buy. More information below.
|
| `api_server.enabled` | Enable usage of API Server. See the [API Server documentation](rest-api.md) for more details. <br> ***Datatype:*** *Boolean*
|
||||||
| `strategy` | DefaultStrategy | Defines Strategy class to use.
|
| `api_server.listen_ip_address` | Bind IP address. See the [API Server documentation](rest-api.md) for more details. <br> ***Datatype:*** *IPv4*
|
||||||
| `strategy_path` | null | Adds an additional strategy lookup path (must be a directory).
|
| `api_server.listen_port` | Bind Port. See the [API Server documentation](rest-api.md) for more details. <br>***Datatype:*** *Integer between 1024 and 65535*
|
||||||
| `internals.process_throttle_secs` | 5 | **Required.** Set the process throttle. Value in second.
|
| `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*
|
||||||
| `internals.sd_notify` | false | 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.
|
| `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*
|
||||||
| `logfile` | | Specify Logfile. Uses a rolling strategy of 10 files, with 1Mb per file.
|
| `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*
|
||||||
| `user_data_dir` | cwd()/user_data | Directory containing user data. Defaults to `./user_data/`.
|
| `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*
|
||||||
|
|
||||||
### Parameters in the strategy
|
### Parameters in the strategy
|
||||||
|
|
||||||
The following parameters can be set in either configuration file or strategy.
|
The following parameters can be set in either configuration file or strategy.
|
||||||
Values set in the configuration file always overwrite values set in the strategy.
|
Values set in the configuration file always overwrite values set in the strategy.
|
||||||
|
|
||||||
* `ticker_interval`
|
|
||||||
* `minimal_roi`
|
* `minimal_roi`
|
||||||
|
* `ticker_interval`
|
||||||
* `stoploss`
|
* `stoploss`
|
||||||
* `trailing_stop`
|
* `trailing_stop`
|
||||||
* `trailing_stop_positive`
|
* `trailing_stop_positive`
|
||||||
* `trailing_stop_positive_offset`
|
* `trailing_stop_positive_offset`
|
||||||
|
* `trailing_only_offset_is_reached`
|
||||||
* `process_only_new_candles`
|
* `process_only_new_candles`
|
||||||
* `order_types`
|
* `order_types`
|
||||||
* `order_time_in_force`
|
* `order_time_in_force`
|
||||||
* `use_sell_signal` (experimental)
|
* `stake_currency`
|
||||||
* `sell_profit_only` (experimental)
|
* `stake_amount`
|
||||||
* `ignore_roi_if_buy_signal` (experimental)
|
* `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 value is 0.0005. If there is not enough crypto-currency in
|
|
||||||
the account an exception is generated.
|
#### Available balance
|
||||||
To allow the bot to trade all the available `stake_currency` in your account set
|
|
||||||
|
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`.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
This setting respects the [available balance configuration](#available-balance).
|
||||||
|
|
||||||
|
#### 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:
|
||||||
|
|
||||||
|
```python
|
||||||
|
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
|
```json
|
||||||
"stake_amount" : "unlimited",
|
"stake_amount" : "unlimited",
|
||||||
|
"tradable_balance_ratio": 0.99,
|
||||||
```
|
```
|
||||||
|
|
||||||
In this case a trade amount is calclulated as:
|
!!! 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).
|
||||||
|
|
||||||
```python
|
!!! Note "When using Dry-Run Mode"
|
||||||
currency_balanse / (max_open_trades - current_open_trades)
|
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
|
### Understand minimal_roi
|
||||||
|
|
||||||
@@ -157,6 +224,9 @@ This parameter can be set in either Strategy or Configuration file. If you use i
|
|||||||
`minimal_roi` value from the strategy file.
|
`minimal_roi` value from the strategy file.
|
||||||
If it is not set in either Strategy or Configuration, a default of 1000% `{"0": 10}` is used, and minimal roi is disabled unless your trade generates 1000% profit.
|
If it is not set in either Strategy or Configuration, a default of 1000% `{"0": 10}` is used, and minimal roi is disabled unless your trade generates 1000% profit.
|
||||||
|
|
||||||
|
!!! Note "Special case to forcesell after a specific time"
|
||||||
|
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
|
### Understand stoploss
|
||||||
|
|
||||||
Go to the [stoploss documentation](stoploss.md) for more details.
|
Go to the [stoploss documentation](stoploss.md) for more details.
|
||||||
@@ -189,13 +259,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
|
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.
|
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
|
### Understand order_types
|
||||||
|
|
||||||
The `order_types` configuration parameter maps actions (`buy`, `sell`, `stoploss`) to order-types (`market`, `limit`, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.
|
The `order_types` configuration parameter maps actions (`buy`, `sell`, `stoploss`) to order-types (`market`, `limit`, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.
|
||||||
@@ -214,6 +277,11 @@ If this is configured, the following 4 values (`buy`, `sell`, `stoploss` and
|
|||||||
`emergencysell` is an optional value, which defaults to `market` and is used when creating stoploss on exchange orders fails.
|
`emergencysell` is an optional value, which defaults to `market` and is used when creating stoploss on exchange orders fails.
|
||||||
The below is the default which is used if this is not configured in either strategy or configuration file.
|
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%.
|
||||||
|
Calculation example: we bought the asset at 100$.
|
||||||
|
Stop-price is 95$, then limit would be `95 * 0.99 = 94.05$` - so the stoploss will happen between 95$ and 94.05$.
|
||||||
|
|
||||||
Syntax for Strategy:
|
Syntax for Strategy:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
@@ -223,7 +291,8 @@ order_types = {
|
|||||||
"emergencysell": "market",
|
"emergencysell": "market",
|
||||||
"stoploss": "market",
|
"stoploss": "market",
|
||||||
"stoploss_on_exchange": False,
|
"stoploss_on_exchange": False,
|
||||||
"stoploss_on_exchange_interval": 60
|
"stoploss_on_exchange_interval": 60,
|
||||||
|
"stoploss_on_exchange_limit_ratio": 0.99,
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -253,7 +322,7 @@ Configuration:
|
|||||||
!!! Note
|
!!! Note
|
||||||
If `stoploss_on_exchange` is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new order.
|
If `stoploss_on_exchange` is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new order.
|
||||||
|
|
||||||
!!! Warning stoploss_on_exchange failures
|
!!! Warning "Warning: stoploss_on_exchange failures"
|
||||||
If stoploss on exchange creation fails for some reason, then an "emergency sell" is initiated. By default, this will sell the asset using a market order. The order-type for the emergency-sell can be changed by setting the `emergencysell` value in the `order_types` dictionary - however this is not advised.
|
If stoploss on exchange creation fails for some reason, then an "emergency sell" is initiated. By default, this will sell the asset using a market order. The order-type for the emergency-sell can be changed by setting the `emergencysell` value in the `order_types` dictionary - however this is not advised.
|
||||||
|
|
||||||
### Understand order_time_in_force
|
### Understand order_time_in_force
|
||||||
@@ -330,7 +399,7 @@ This configuration enables binance, as well as rate limiting to avoid bans from
|
|||||||
Optimal settings for rate limiting depend on the exchange and the size of the whitelist, so an ideal parameter will vary on many other settings.
|
Optimal settings for rate limiting depend on the exchange and the size of the whitelist, so an ideal parameter will vary on many other settings.
|
||||||
We try to provide sensible defaults per exchange where possible, if you encounter bans please make sure that `"enableRateLimit"` is enabled and increase the `"rateLimit"` parameter step by step.
|
We try to provide sensible defaults per exchange where possible, if you encounter bans please make sure that `"enableRateLimit"` is enabled and increase the `"rateLimit"` parameter step by step.
|
||||||
|
|
||||||
#### Advanced FreqTrade Exchange configuration
|
#### Advanced Freqtrade Exchange configuration
|
||||||
|
|
||||||
Advanced options can be configured using the `_ft_has_params` setting, which will override Defaults and exchange-specific behaviours.
|
Advanced options can be configured using the `_ft_has_params` setting, which will override Defaults and exchange-specific behaviours.
|
||||||
|
|
||||||
@@ -369,6 +438,139 @@ The valid values are:
|
|||||||
"BTC", "ETH", "XRP", "LTC", "BCH", "USDT"
|
"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.
|
||||||
|
There are [`StaticPairList`](#static-pair-list) and dynamic Whitelists available.
|
||||||
|
|
||||||
|
[`PrecisionFilter`](#precision-filter) and [`PriceFilter`](#price-pair-filter) act as filters, removing low-value pairs.
|
||||||
|
|
||||||
|
All pairlists can be chained, and a combination of all pairlists will become your new whitelist. Pairlists are executed in the sequence they are configured. You should always configure either `StaticPairList` or `DynamicPairList` as starting pairlists.
|
||||||
|
|
||||||
|
Inactive markets and blacklisted pairs are always removed from the resulting `pair_whitelist`.
|
||||||
|
|
||||||
|
### Available Pairlists
|
||||||
|
|
||||||
|
* [`StaticPairList`](#static-pair-list) (default, if not configured differently)
|
||||||
|
* [`VolumePairList`](#volume-pair-list)
|
||||||
|
* [`PrecisionFilter`](#precision-filter)
|
||||||
|
* [`PriceFilter`](#price-pair-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.
|
||||||
|
|
||||||
|
#### Static Pair List
|
||||||
|
|
||||||
|
By default, the `StaticPairList` method is used, which uses a statically defined pair whitelist from the configuration.
|
||||||
|
|
||||||
|
It uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"pairlists": [
|
||||||
|
{"method": "StaticPairList"}
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Volume Pair List
|
||||||
|
|
||||||
|
`VolumePairList` selects `number_assets` top pairs based on `sort_key`, which can be one of `askVolume`, `bidVolume` and `quoteVolume` and defaults to `quoteVolume`.
|
||||||
|
|
||||||
|
`VolumePairList` considers outputs of previous pairlists unless it's the first configured pairlist, it does not consider `pair_whitelist`, but selects the top assets from all available markets (with matching stake-currency) on the exchange.
|
||||||
|
|
||||||
|
`refresh_period` allows setting the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes).
|
||||||
|
|
||||||
|
```json
|
||||||
|
"pairlists": [{
|
||||||
|
"method": "VolumePairList",
|
||||||
|
"number_assets": 20,
|
||||||
|
"sort_key": "quoteVolume",
|
||||||
|
"refresh_period": 1800,
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Precision Filter
|
||||||
|
|
||||||
|
Filters low-value coins which would not allow setting a stoploss.
|
||||||
|
|
||||||
|
#### Price Pair Filter
|
||||||
|
|
||||||
|
The `PriceFilter` allows filtering of pairs by price.
|
||||||
|
Currently, only `low_price_ratio` is implemented, where a raise of 1 price unit (pip) is below the `low_price_ratio` ratio.
|
||||||
|
This option is disabled by default, and will only apply if set to <> 0.
|
||||||
|
|
||||||
|
Calculation example:
|
||||||
|
Min price precision is 8 decimals. If price is 0.00000011 - one step would be 0.00000012 - which is almost 10% higher than the previous value.
|
||||||
|
|
||||||
|
These pairs are dangerous since it may be impossible to place the desired stoploss - and often result in high losses.
|
||||||
|
|
||||||
|
### 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%.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"exchange": {
|
||||||
|
"pair_whitelist": [],
|
||||||
|
"pair_blacklist": ["BNB/BTC"]
|
||||||
|
},
|
||||||
|
"pairlists": [
|
||||||
|
{
|
||||||
|
"method": "VolumePairList",
|
||||||
|
"number_assets": 20,
|
||||||
|
"sort_key": "quoteVolume",
|
||||||
|
},
|
||||||
|
{"method": "PrecisionFilter"},
|
||||||
|
{"method": "PriceFilter", "low_price_ratio": 0.01}
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
## Switch to Dry-run mode
|
## Switch to Dry-run mode
|
||||||
|
|
||||||
We recommend starting the bot in the Dry-run mode to see how your bot will
|
We recommend starting the bot in the Dry-run mode to see how your bot will
|
||||||
@@ -384,7 +586,7 @@ creating trades on the exchange.
|
|||||||
"db_url": "sqlite:///tradesv3.dryrun.sqlite",
|
"db_url": "sqlite:///tradesv3.dryrun.sqlite",
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Remove your Exchange API key and secrete (change them by empty values or fake credentials):
|
3. Remove your Exchange API key and secret (change them by empty values or fake credentials):
|
||||||
|
|
||||||
```json
|
```json
|
||||||
"exchange": {
|
"exchange": {
|
||||||
@@ -395,41 +597,10 @@ creating trades on the exchange.
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Once you will be happy with your bot performance running in the Dry-run mode,
|
Once you will be happy with your bot performance running in the Dry-run mode, you can switch it to production mode.
|
||||||
you can switch it to production mode.
|
|
||||||
|
|
||||||
### Dynamic Pairlists
|
!!! Note
|
||||||
|
A simulated wallet is available during dry-run mode, and will assume a starting capital of `dry_run_wallet` (defaults to 1000).
|
||||||
Dynamic pairlists select pairs for you based on the logic configured.
|
|
||||||
The bot runs against all pairs (with that stake) on the exchange, and a number of assets
|
|
||||||
(`number_assets`) is selected based on the selected criteria.
|
|
||||||
|
|
||||||
By default, the `StaticPairList` method is used.
|
|
||||||
The Pairlist method is configured as `pair_whitelist` parameter under the `exchange`
|
|
||||||
section of the configuration.
|
|
||||||
|
|
||||||
**Available Pairlist methods:**
|
|
||||||
|
|
||||||
* `StaticPairList`
|
|
||||||
* It uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`.
|
|
||||||
* `VolumePairList`
|
|
||||||
* It selects `number_assets` top pairs based on `sort_key`, which can be one of
|
|
||||||
`askVolume`, `bidVolume` and `quoteVolume`, defaults to `quoteVolume`.
|
|
||||||
* There is a possibility to filter low-value coins that would not allow setting a stop loss
|
|
||||||
(set `precision_filter` parameter to `true` for this).
|
|
||||||
|
|
||||||
Example:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"pairlist": {
|
|
||||||
"method": "VolumePairList",
|
|
||||||
"config": {
|
|
||||||
"number_assets": 20,
|
|
||||||
"sort_key": "quoteVolume",
|
|
||||||
"precision_filter": false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
```
|
|
||||||
|
|
||||||
## Switch to production mode
|
## Switch to production mode
|
||||||
|
|
||||||
@@ -456,12 +627,14 @@ you run it in production mode.
|
|||||||
"secret": "08a9dc6db3d7b53e1acebd9275677f4b0a04f1a5",
|
"secret": "08a9dc6db3d7b53e1acebd9275677f4b0a04f1a5",
|
||||||
...
|
...
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
!!! Note
|
|
||||||
If you have an exchange API key yet, [see our tutorial](/pre-requisite).
|
|
||||||
|
|
||||||
### Using proxy with FreqTrade
|
!!! Note
|
||||||
|
If you have an exchange API key yet, [see our tutorial](installation.md#setup-your-exchange-account).
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
To use a proxy with freqtrade, add the kwarg `"aiohttp_trust_env"=true` to the `"ccxt_async_kwargs"` dict in the exchange section of the configuration.
|
To use a proxy with freqtrade, add the kwarg `"aiohttp_trust_env"=true` to the `"ccxt_async_kwargs"` dict in the exchange section of the configuration.
|
||||||
|
|
||||||
@@ -481,14 +654,13 @@ export HTTPS_PROXY="http://addr:port"
|
|||||||
freqtrade
|
freqtrade
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Embedding Strategies
|
||||||
### 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,
|
This is done by utilizing BASE64 encoding and providing this string at the strategy configuration field,
|
||||||
in your chosen config file.
|
in your chosen config file.
|
||||||
|
|
||||||
#### Encoding a string as BASE64
|
### Encoding a string as BASE64
|
||||||
|
|
||||||
This is a quick example, how to generate the BASE64 string in python
|
This is a quick example, how to generate the BASE64 string in python
|
||||||
|
|
||||||
|
|||||||
@@ -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)*
|
* Don't forget to start a Jupyter notebook server from within your conda or venv environment or use [nb_conda_kernels](https://github.com/Anaconda-Platform/nb_conda_kernels)*
|
||||||
* Copy the example notebook before use so your changes don't get clobbered with the next freqtrade update.
|
* Copy the example notebook before use so your changes don't get 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
|
## Fine print
|
||||||
|
|
||||||
Some tasks don't work especially well in notebooks. For example, anything using asynchronous execution is a problem for Jupyter. Also, freqtrade's primary entry point is the shell cli, so using pure python in a notebook bypasses arguments that provide required objects and parameters to helper functions. You may need to set those values or create expected objects manually.
|
Some tasks don't work especially well in notebooks. For example, anything using asynchronous execution is a problem for Jupyter. Also, freqtrade's primary entry point is the shell cli, so using pure python in a notebook bypasses arguments that provide required objects and parameters to helper functions. You may need to set those values or create expected objects manually.
|
||||||
@@ -61,34 +82,6 @@ except:
|
|||||||
print(Path.cwd())
|
print(Path.cwd())
|
||||||
```
|
```
|
||||||
|
|
||||||
## Load existing objects into a Jupyter notebook
|
|
||||||
|
|
||||||
These examples assume that you have already generated data using the cli. They will allow you to drill deeper into your results, and perform analysis which otherwise would make the output very difficult to digest due to information overload.
|
|
||||||
|
|
||||||
### Load backtest results into a pandas dataframe
|
|
||||||
|
|
||||||
```python
|
|
||||||
from freqtrade.data.btanalysis import load_backtest_data
|
|
||||||
|
|
||||||
# Load backtest results
|
|
||||||
df = load_backtest_data("user_data/backtest_results/backtest-result.json")
|
|
||||||
|
|
||||||
# Show value-counts per pair
|
|
||||||
df.groupby("pair")["sell_reason"].value_counts()
|
|
||||||
```
|
|
||||||
|
|
||||||
### Load live trading results into a pandas dataframe
|
|
||||||
|
|
||||||
``` python
|
|
||||||
from freqtrade.data.btanalysis import load_trades_from_db
|
|
||||||
|
|
||||||
# Fetch trades from database
|
|
||||||
df = load_trades_from_db("sqlite:///tradesv3.sqlite")
|
|
||||||
|
|
||||||
# Display results
|
|
||||||
df.groupby("pair")["sell_reason"].value_counts()
|
|
||||||
```
|
|
||||||
|
|
||||||
### Load multiple configuration files
|
### Load multiple configuration files
|
||||||
|
|
||||||
This option can be useful to inspect the results of passing in multiple configs.
|
This option can be useful to inspect the results of passing in multiple configs.
|
||||||
@@ -114,99 +107,9 @@ Best avoid relative paths, since this starts at the storage location of the jupy
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Load exchange data to a pandas dataframe
|
### Further Data analysis documentation
|
||||||
|
|
||||||
This loads candle data to a dataframe
|
* [Strategy debugging](strategy_analysis_example.md) - also available as Jupyter notebook (`user_data/notebooks/strategy_analysis_example.ipynb`)
|
||||||
|
* [Plotting](plotting.md)
|
||||||
```python
|
|
||||||
from pathlib import Path
|
|
||||||
from freqtrade.data.history import load_pair_history
|
|
||||||
|
|
||||||
# Load data using values passed to function
|
|
||||||
ticker_interval = "5m"
|
|
||||||
data_location = Path('user_data', 'data', 'bitrex')
|
|
||||||
pair = "BTC_USDT"
|
|
||||||
candles = load_pair_history(datadir=data_location,
|
|
||||||
ticker_interval=ticker_interval,
|
|
||||||
pair=pair)
|
|
||||||
|
|
||||||
# Confirm success
|
|
||||||
print(f"Loaded len(candles) rows of data for {pair} from {data_location}")
|
|
||||||
candles.head()
|
|
||||||
```
|
|
||||||
|
|
||||||
## Strategy debugging example
|
|
||||||
|
|
||||||
Debugging a strategy can be time-consuming. FreqTrade offers helper functions to visualize raw data.
|
|
||||||
|
|
||||||
### Define variables used in analyses
|
|
||||||
|
|
||||||
You can override strategy settings as demonstrated below.
|
|
||||||
|
|
||||||
```python
|
|
||||||
# Customize these according to your needs.
|
|
||||||
|
|
||||||
# Define some constants
|
|
||||||
ticker_interval = "5m"
|
|
||||||
# Name of the strategy class
|
|
||||||
strategy_name = 'SampleStrategy'
|
|
||||||
# Path to user data
|
|
||||||
user_data_dir = 'user_data'
|
|
||||||
# Location of the strategy
|
|
||||||
strategy_location = Path(user_data_dir, 'strategies')
|
|
||||||
# Location of the data
|
|
||||||
data_location = Path(user_data_dir, 'data', 'binance')
|
|
||||||
# Pair to analyze - Only use one pair here
|
|
||||||
pair = "BTC_USDT"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Load exchange data
|
|
||||||
|
|
||||||
```python
|
|
||||||
from pathlib import Path
|
|
||||||
from freqtrade.data.history import load_pair_history
|
|
||||||
|
|
||||||
# Load data using values set above
|
|
||||||
candles = load_pair_history(datadir=data_location,
|
|
||||||
ticker_interval=ticker_interval,
|
|
||||||
pair=pair)
|
|
||||||
|
|
||||||
# Confirm success
|
|
||||||
print(f"Loaded {len(candles)} rows of data for {pair} from {data_location}")
|
|
||||||
candles.head()
|
|
||||||
```
|
|
||||||
|
|
||||||
### Load and run strategy
|
|
||||||
|
|
||||||
* Rerun each time the strategy file is changed
|
|
||||||
|
|
||||||
```python
|
|
||||||
from freqtrade.resolvers import StrategyResolver
|
|
||||||
|
|
||||||
# Load strategy using values set above
|
|
||||||
strategy = StrategyResolver({'strategy': strategy_name,
|
|
||||||
'user_data_dir': user_data_dir,
|
|
||||||
'strategy_path': strategy_location}).strategy
|
|
||||||
|
|
||||||
# Generate buy/sell signals using strategy
|
|
||||||
df = strategy.analyze_ticker(candles, {'pair': pair})
|
|
||||||
```
|
|
||||||
|
|
||||||
### Display the trade details
|
|
||||||
|
|
||||||
* Note that using `data.tail()` is preferable to `data.head()` as most indicators have some "startup" data at the top of the dataframe.
|
|
||||||
* Some possible problems
|
|
||||||
* Columns with NaN values at the end of the dataframe
|
|
||||||
* Columns used in `crossed*()` functions with completely different units
|
|
||||||
* Comparison with full backtest
|
|
||||||
* having 200 buy signals as output for one pair from `analyze_ticker()` does not necessarily mean that 200 trades will be made during backtesting.
|
|
||||||
* Assuming you use only one condition such as, `df['rsi'] < 30` as buy condition, this will generate multiple "buy" signals for each pair in sequence (until rsi returns > 29). The bot will only buy on the first of these signals (and also only if a trade-slot ("max_open_trades") is still available), or on one of the middle signals, as soon as a "slot" becomes available.
|
|
||||||
|
|
||||||
```python
|
|
||||||
# Report results
|
|
||||||
print(f"Generated {df['buy'].sum()} buy signals")
|
|
||||||
data = df.set_index('date', drop=True)
|
|
||||||
data.tail()
|
|
||||||
```
|
|
||||||
|
|
||||||
Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.
|
Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ If no additional parameter is specified, freqtrade will download data for `"1m"`
|
|||||||
Exchange and pairs will come from `config.json` (if specified using `-c/--config`).
|
Exchange and pairs will come from `config.json` (if specified using `-c/--config`).
|
||||||
Otherwise `--exchange` becomes mandatory.
|
Otherwise `--exchange` becomes mandatory.
|
||||||
|
|
||||||
!!! Tip Updating existing data
|
!!! Tip "Tip: Updating existing data"
|
||||||
If you already have backtesting data available in your data-directory and would like to refresh this data up to today, use `--days xx` with a number slightly higher than the missing number of days. Freqtrade will keep the available data and only download the missing data.
|
If you already have backtesting data available in your data-directory and would like to refresh this data up to today, use `--days xx` with a number slightly higher than the missing number of days. Freqtrade will keep the available data and only download the missing data.
|
||||||
Be carefull though: If the number is too small (which would result in a few missing days), the whole dataset will be removed and only xx days will be downloaded.
|
Be 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.
|
||||||
|
|
||||||
@@ -38,7 +38,7 @@ Mixing different stake-currencies is allowed for this file, since it's only used
|
|||||||
]
|
]
|
||||||
```
|
```
|
||||||
|
|
||||||
### start download
|
### Start download
|
||||||
|
|
||||||
Then run:
|
Then run:
|
||||||
|
|
||||||
@@ -57,6 +57,30 @@ This will download ticker data for all the currency pairs you defined in `pairs.
|
|||||||
- Use `--timeframes` to specify which tickers to download. Default is `--timeframes 1m 5m` which will download 1-minute and 5-minute tickers.
|
- Use `--timeframes` to specify which tickers to download. Default is `--timeframes 1m 5m` which will download 1-minute and 5-minute tickers.
|
||||||
- To use exchange, timeframe and list of pairs as defined in your configuration file, use the `-c/--config` option. With this, the script uses the whitelist defined in the config as the list of currency pairs to download data for and does not require the pairs.json file. You can combine `-c/--config` with most other options.
|
- To use exchange, timeframe and list of pairs as defined in your configuration file, use the `-c/--config` option. With this, the script uses the whitelist defined in the config as the list of currency pairs to download data for and does not require the pairs.json file. You can combine `-c/--config` with most other options.
|
||||||
|
|
||||||
|
### Trades (tick) data
|
||||||
|
|
||||||
|
By default, `download-data` subcommand downloads Candles (OHLCV) data. Some exchanges also provide historic trade-data via their API.
|
||||||
|
This data can be useful if you need many different timeframes, since it is only downloaded once, and then resampled locally to the desired timeframes.
|
||||||
|
|
||||||
|
Since this data is large by default, the files use gzip by default. They are stored in your data-directory with the naming convention of `<pair>-trades.json.gz` (`ETH_BTC-trades.json.gz`). Incremental mode is also supported, as for historic OHLCV data, so downloading the data once per week with `--days 8` will create an incremental data-repository.
|
||||||
|
|
||||||
|
To use this mode, simply add `--dl-trades` to your call. This will swap the download method to download trades, and resamples the data locally.
|
||||||
|
|
||||||
|
Example call:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade download-data --exchange binance --pairs XRP/ETH ETH/BTC --days 20 --dl-trades
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
While this method uses async calls, it will be slow, since it requires the result of the previous call to generate the next request to the exchange.
|
||||||
|
|
||||||
|
!!! Warning
|
||||||
|
The historic trades are not available during Freqtrade dry-run and live trade modes because all exchanges tested provide this data with a delay of few 100 candles, so it's not suitable for real-time trading.
|
||||||
|
|
||||||
|
!!! Note "Kraken user"
|
||||||
|
Kraken users should read [this](exchanges.md#historic-kraken-data) before starting to download data.
|
||||||
|
|
||||||
## Next step
|
## Next step
|
||||||
|
|
||||||
Great, you now have backtest data downloaded, so you can now start [backtesting](backtesting.md) your strategy.
|
Great, you now have backtest data downloaded, so you can now start [backtesting](backtesting.md) your strategy.
|
||||||
|
|||||||
@@ -38,8 +38,53 @@ def test_method_to_test(caplog):
|
|||||||
assert log_has("This event happened", caplog)
|
assert log_has("This event happened", caplog)
|
||||||
# Check regex with trailing number ...
|
# Check regex with trailing number ...
|
||||||
assert log_has_re(r"This dynamic event happened and produced \d+", caplog)
|
assert log_has_re(r"This dynamic event happened and produced \d+", caplog)
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Local docker usage
|
||||||
|
|
||||||
|
The fastest and easiest way to start up is to use docker-compose.develop which gives developers the ability to start the bot up with all the required dependencies, *without* needing to install any freqtrade specific dependencies on your local machine.
|
||||||
|
|
||||||
|
#### Install
|
||||||
|
|
||||||
|
* [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||||
|
* [docker](https://docs.docker.com/install/)
|
||||||
|
* [docker-compose](https://docs.docker.com/compose/install/)
|
||||||
|
|
||||||
|
#### Starting the bot
|
||||||
|
##### Use the develop dockerfile
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
rm docker-compose.yml && mv docker-compose.develop.yml docker-compose.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Docker Compose
|
||||||
|
|
||||||
|
##### Starting
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
docker-compose up
|
||||||
|
```
|
||||||
|
|
||||||
|

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

|
||||||
|
|
||||||
## Modules
|
## Modules
|
||||||
|
|
||||||
### Dynamic Pairlist
|
### Dynamic Pairlist
|
||||||
@@ -55,22 +100,22 @@ This is a simple provider, which however serves as a good example on how to star
|
|||||||
|
|
||||||
Next, modify the classname of the provider (ideally align this with the Filename).
|
Next, modify the classname of the provider (ideally align this with the Filename).
|
||||||
|
|
||||||
The base-class provides the an instance of the bot (`self._freqtrade`), as well as the configuration (`self._config`), and initiates both `_blacklist` and `_whitelist`.
|
The base-class provides an instance of the exchange (`self._exchange`) the pairlist manager (`self._pairlistmanager`), as well as the main configuration (`self._config`), the pairlist dedicated configuration (`self._pairlistconfig`) and the absolute position within the list of pairlists.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
self._freqtrade = freqtrade
|
self._exchange = exchange
|
||||||
|
self._pairlistmanager = pairlistmanager
|
||||||
self._config = config
|
self._config = config
|
||||||
self._whitelist = self._config['exchange']['pair_whitelist']
|
self._pairlistconfig = pairlistconfig
|
||||||
self._blacklist = self._config['exchange'].get('pair_blacklist', [])
|
self._pairlist_pos = pairlist_pos
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
Now, let's step through the methods which require actions:
|
Now, let's step through the methods which require actions:
|
||||||
|
|
||||||
#### configuration
|
#### Pairlist configuration
|
||||||
|
|
||||||
Configuration for PairListProvider is done in the bot configuration file in the element `"pairlist"`.
|
Configuration for PairListProvider is done in the bot configuration file in the element `"pairlist"`.
|
||||||
This Pairlist-object may contain a `"config"` dict with additional configurations for the configured pairlist.
|
This Pairlist-object may contain configurations with additional configurations for the configured pairlist.
|
||||||
By convention, `"number_assets"` is used to specify the maximum number of pairs to keep in the whitelist. Please follow this to ensure a consistent user experience.
|
By convention, `"number_assets"` is used to specify the maximum number of pairs to keep in the whitelist. Please follow this to ensure a consistent user experience.
|
||||||
|
|
||||||
Additional elements can be configured as needed. `VolumePairList` uses `"sort_key"` to specify the sorting value - however feel free to specify whatever is necessary for your great algorithm to be successfull and dynamic.
|
Additional elements can be configured as needed. `VolumePairList` uses `"sort_key"` to specify the sorting value - however feel free to specify whatever is necessary for your great algorithm to be successfull and dynamic.
|
||||||
@@ -80,29 +125,30 @@ Additional elements can be configured as needed. `VolumePairList` uses `"sort_ke
|
|||||||
Returns a description used for Telegram messages.
|
Returns a description used for Telegram messages.
|
||||||
This should contain the name of the Provider, as well as a short description containing the number of assets. Please follow the format `"PairlistName - top/bottom X pairs"`.
|
This should contain the name of the Provider, as well as a short description containing the number of assets. Please follow the format `"PairlistName - top/bottom X pairs"`.
|
||||||
|
|
||||||
#### refresh_pairlist
|
#### filter_pairlist
|
||||||
|
|
||||||
Override this method and run all calculations needed in this method.
|
Override this method and run all calculations needed in this method.
|
||||||
This is called with each iteration of the bot - so consider implementing caching for compute/network heavy calculations.
|
This is called with each iteration of the bot - so consider implementing caching for compute/network heavy calculations.
|
||||||
|
|
||||||
Assign the resulting whiteslist to `self._whitelist` and `self._blacklist` respectively. These will then be used to run the bot in this iteration. Pairs with open trades will be added to the whitelist to have the sell-methods run correctly.
|
It get's passed a pairlist (which can be the result of previous pairlists) as well as `tickers`, a pre-fetched version of `get_tickers()`.
|
||||||
|
|
||||||
Please also run `self._validate_whitelist(pairs)` and to check and remove pairs with inactive markets. This function is available in the Parent class (`StaticPairList`) and should ideally not be overwritten.
|
It must return the resulting pairlist (which may then be passed into the next pairlist filter).
|
||||||
|
|
||||||
|
Validations are optional, the parent class exposes a `_verify_blacklist(pairlist)` and `_whitelist_for_active_markets(pairlist)` to do default filters. Use this if you limit your result to a certain number of pairs - so the endresult is not shorter than expected.
|
||||||
|
|
||||||
##### sample
|
##### sample
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
def refresh_pairlist(self) -> None:
|
def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
|
||||||
# Generate dynamic whitelist
|
# Generate dynamic whitelist
|
||||||
pairs = self._gen_pair_whitelist(self._config['stake_currency'], self._sort_key)
|
pairs = self._calculate_pairlist(pairlist, tickers)
|
||||||
# Validate whitelist to only have active market pairs
|
return pairs
|
||||||
self._whitelist = self._validate_whitelist(pairs)[:self._number_pairs]
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### _gen_pair_whitelist
|
#### _gen_pair_whitelist
|
||||||
|
|
||||||
This is a simple method used by `VolumePairList` - however serves as a good example.
|
This is a simple method used by `VolumePairList` - however serves as a good example.
|
||||||
It implements caching (`@cached(TTLCache(maxsize=1, ttl=1800))`) as well as a configuration option to allow different (but similar) strategies to work with the same PairListProvider.
|
In VolumePairList, this implements different methods of sorting, does early validation so only the expected number of pairs is returned.
|
||||||
|
|
||||||
## Implement a new Exchange (WIP)
|
## Implement a new Exchange (WIP)
|
||||||
|
|
||||||
@@ -137,17 +183,41 @@ raw = ct.fetch_ohlcv(pair, timeframe=timeframe)
|
|||||||
# convert to dataframe
|
# convert to dataframe
|
||||||
df1 = parse_ticker_dataframe(raw, timeframe, pair=pair, drop_incomplete=False)
|
df1 = parse_ticker_dataframe(raw, timeframe, pair=pair, drop_incomplete=False)
|
||||||
|
|
||||||
print(df1["date"].tail(1))
|
print(df1.tail(1))
|
||||||
print(datetime.utcnow())
|
print(datetime.utcnow())
|
||||||
```
|
```
|
||||||
|
|
||||||
``` output
|
``` 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
|
2019-06-09 12:30:27.873327
|
||||||
```
|
```
|
||||||
|
|
||||||
The output will show the last entry from the Exchange as well as the current UTC date.
|
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).
|
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
|
||||||
|
|
||||||
|
To keep the jupyter notebooks aligned with the documentation, the following should be ran after updating a example notebook.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace freqtrade/templates/strategy_analysis_example.ipynb
|
||||||
|
jupyter nbconvert --ClearOutputPreprocessor.enabled=True --to markdown freqtrade/templates/strategy_analysis_example.ipynb --stdout > docs/strategy_analysis_example.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## Continuous integration
|
||||||
|
|
||||||
|
This documents some decisions taken for the CI Pipeline.
|
||||||
|
|
||||||
|
* CI runs on all OS variants, Linux (ubuntu), macOS and Windows.
|
||||||
|
* Docker images are build for the branches `master` and `develop`.
|
||||||
|
* Raspberry PI Docker images are postfixed with `_pi` - so tags will be `:master_pi` and `develop_pi`.
|
||||||
|
* Docker images contain a file, `/freqtrade/freqtrade_commit` containing the commit this image is based of.
|
||||||
|
* Full docker image rebuilds are run once a week via schedule.
|
||||||
|
* Deployments run on ubuntu.
|
||||||
|
* ta-lib binaries are contained in the build_helpers directory to avoid fails related to external unavailability.
|
||||||
|
* All tests must pass for a PR to be merged to `master` or `develop`.
|
||||||
|
|
||||||
## Creating a release
|
## Creating a release
|
||||||
|
|
||||||
@@ -155,14 +225,15 @@ This part of the documentation is aimed at maintainers, and shows how to create
|
|||||||
|
|
||||||
### Create release branch
|
### Create release branch
|
||||||
|
|
||||||
``` bash
|
First, pick a commit that's about one week old (to not include latest additions to releases).
|
||||||
# make sure you're in develop branch
|
|
||||||
git checkout develop
|
|
||||||
|
|
||||||
|
``` bash
|
||||||
# create new branch
|
# create new branch
|
||||||
git checkout -b new_release
|
git checkout -b new_release <commitid>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Determine if crucial bugfixes have been made between this commit and the current state, and eventually cherry-pick these.
|
||||||
|
|
||||||
* Edit `freqtrade/__init__.py` and add the version matching the current date (for example `2019.7` for July 2019). Minor versions can be `2019.7-1` should we need to do a second release that month.
|
* Edit `freqtrade/__init__.py` and add the version matching the current date (for example `2019.7` for July 2019). Minor versions can be `2019.7-1` should we need to do a second release that month.
|
||||||
* Commit this part
|
* Commit this part
|
||||||
* push that branch to the remote and create a PR against the master branch
|
* push that branch to the remote and create a PR against the master branch
|
||||||
@@ -170,18 +241,29 @@ git checkout -b new_release
|
|||||||
### Create changelog from git commits
|
### Create changelog from git commits
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Make sure that both master and develop are up-todate!.
|
Make sure that the master branch is uptodate!
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
# Needs to be done before merging / pulling that branch.
|
# Needs to be done before merging / pulling that branch.
|
||||||
git log --oneline --no-decorate --no-merges master..develop
|
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
|
### Create github release / tag
|
||||||
|
|
||||||
Once the PR against master is merged (best right after merging):
|
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 button "Draft a new release" in the Github UI (subsection releases).
|
||||||
* Use the version-number specified as tag.
|
* Use the version-number specified as tag.
|
||||||
* Use "master" as reference (this step comes after the above PR is merged).
|
* Use "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)
|
||||||
@@ -190,3 +272,23 @@ Once the PR against master is merged (best right after merging):
|
|||||||
|
|
||||||
* Update version in develop by postfixing that with `-dev` (`2019.6 -> 2019.6-dev`).
|
* Update version in develop by postfixing that with `-dev` (`2019.6 -> 2019.6-dev`).
|
||||||
* Create a PR against develop to update that branch.
|
* 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.
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ To update the image, simply run the above commands again and restart your runnin
|
|||||||
|
|
||||||
Should you require additional libraries, please [build the image yourself](#build-your-own-docker-image).
|
Should you require additional libraries, please [build the image yourself](#build-your-own-docker-image).
|
||||||
|
|
||||||
!!! Note Docker image update frequency
|
!!! Note "Docker image update frequency"
|
||||||
The official docker images with tags `master`, `develop` and `latest` are automatically rebuild once a week to keep the base image uptodate.
|
The official docker images with tags `master`, `develop` and `latest` are automatically rebuild once a week to keep the base image uptodate.
|
||||||
In addition to that, every merge to `develop` will trigger a rebuild for `develop` and `latest`.
|
In addition to that, every merge to `develop` will trigger a rebuild for `develop` and `latest`.
|
||||||
|
|
||||||
@@ -160,16 +160,18 @@ docker run -d \
|
|||||||
-v ~/.freqtrade/config.json:/freqtrade/config.json \
|
-v ~/.freqtrade/config.json:/freqtrade/config.json \
|
||||||
-v ~/.freqtrade/user_data/:/freqtrade/user_data \
|
-v ~/.freqtrade/user_data/:/freqtrade/user_data \
|
||||||
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
||||||
freqtrade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy
|
freqtrade trade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
db-url defaults to `sqlite:///tradesv3.sqlite` but it defaults to `sqlite://` if `dry_run=True` is being used.
|
When using docker, it's best to specify `--db-url` explicitly to ensure that the database URL and the mounted database file match.
|
||||||
To override this behaviour use a custom db-url value: i.e.: `--db-url sqlite:///tradesv3.dryrun.sqlite`
|
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
All available bot command line parameters can be added to the end of the `docker run` command.
|
All available bot command line parameters can be added to the end of the `docker run` command.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
You can define a [restart policy](https://docs.docker.com/config/containers/start-containers-automatically/) in docker. It can be useful in some cases to use the `--restart unless-stopped` flag (crash of freqtrade or reboot of your system).
|
||||||
|
|
||||||
### Monitor your Docker instance
|
### Monitor your Docker instance
|
||||||
|
|
||||||
You can use the following commands to monitor and manage your container:
|
You can use the following commands to monitor and manage your container:
|
||||||
@@ -199,7 +201,7 @@ docker run -d \
|
|||||||
-v ~/.freqtrade/config.json:/freqtrade/config.json \
|
-v ~/.freqtrade/config.json:/freqtrade/config.json \
|
||||||
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
||||||
-v ~/.freqtrade/user_data/:/freqtrade/user_data/ \
|
-v ~/.freqtrade/user_data/:/freqtrade/user_data/ \
|
||||||
freqtrade --strategy AwsomelyProfitableStrategy backtesting
|
freqtrade backtesting --strategy AwsomelyProfitableStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
Head over to the [Backtesting Documentation](backtesting.md) for more details.
|
Head over to the [Backtesting Documentation](backtesting.md) for more details.
|
||||||
|
|||||||
160
docs/edge.md
160
docs/edge.md
@@ -1,4 +1,4 @@
|
|||||||
# Edge positioning
|
# Edge positioning
|
||||||
|
|
||||||
This page explains how to use Edge Positioning module in your bot in order to enter into a trade only if the trade has a reasonable win rate and risk reward ratio, and consequently adjust your position size and stoploss.
|
This page explains how to use Edge Positioning module in your bot in order to enter into a trade only if the trade has a reasonable win rate and risk reward ratio, and consequently adjust your position size and stoploss.
|
||||||
|
|
||||||
@@ -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.
|
Edge does not consider anything else than buy/sell/stoploss signals. So trailing stoploss, ROI, and everything else are ignored in its calculation.
|
||||||
|
|
||||||
## Introduction
|
## Introduction
|
||||||
|
|
||||||
Trading is all about probability. No one can claim that he has a strategy working all the time. You have to assume that sometimes you lose.
|
Trading 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?
|
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 question is: How do you calculate that? How do you know if you wanna play?
|
||||||
|
|
||||||
The answer comes to two factors:
|
The answer comes to two factors:
|
||||||
|
|
||||||
- Win Rate
|
- Win Rate
|
||||||
- Risk Reward Ratio
|
- Risk Reward Ratio
|
||||||
|
|
||||||
### Win Rate
|
### 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).
|
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
|
```
|
||||||
|
W = (Number of winning trades) / (Total number of trades) = (Number of winning trades) / N
|
||||||
|
```
|
||||||
|
|
||||||
Complementary Loss Rate (*L*) is defined as
|
Complementary Loss Rate (*L*) is defined as
|
||||||
|
|
||||||
L = (Number of losing trades) / (Total number of trades) = (Number of losing trades) / N
|
```
|
||||||
|
L = (Number of losing trades) / (Total number of trades) = (Number of losing trades) / N
|
||||||
|
```
|
||||||
|
|
||||||
or, which is the same, as
|
or, which is the same, as
|
||||||
|
|
||||||
L = 1 – W
|
```
|
||||||
|
L = 1 – W
|
||||||
|
```
|
||||||
|
|
||||||
### Risk Reward Ratio
|
### Risk Reward Ratio
|
||||||
|
|
||||||
Risk Reward Ratio (*R*) is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose:
|
Risk Reward Ratio (*R*) is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose:
|
||||||
|
|
||||||
R = Profit / Loss
|
```
|
||||||
|
R = Profit / Loss
|
||||||
|
```
|
||||||
|
|
||||||
Over time, on many trades, you can calculate your risk reward by dividing your average profit on winning trades by your average loss on losing trades:
|
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 profit = (Sum of profits) / (Number of winning trades)
|
||||||
|
|
||||||
Average loss = (Sum of losses) / (Number of losing trades)
|
Average loss = (Sum of losses) / (Number of losing trades)
|
||||||
|
|
||||||
R = (Average profit) / (Average loss)
|
R = (Average profit) / (Average loss)
|
||||||
|
```
|
||||||
|
|
||||||
### Expectancy
|
### Expectancy
|
||||||
|
|
||||||
At this point we can combine *W* and *R* to create an expectancy ratio. This is a simple process of multiplying the risk reward ratio by the percentage of winning trades and subtracting the percentage of losing trades, which is calculated as follows:
|
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
|
```
|
||||||
|
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:
|
So lets say your Win rate is 28% and your Risk Reward Ratio is 5:
|
||||||
|
|
||||||
Expectancy = (5 X 0.28) – 0.72 = 0.68
|
```
|
||||||
|
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.
|
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.
|
**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?
|
## 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:
|
If enabled in config, Edge will go through historical data with a range of stoplosses in order to find buy and sell/stoploss signals. It then calculates win rate and expectancy over *N* trades for each stoploss. Here is an example:
|
||||||
|
|
||||||
| Pair | Stoploss | Win Rate | Risk Reward Ratio | Expectancy |
|
| Pair | Stoploss | Win Rate | Risk Reward Ratio | Expectancy |
|
||||||
@@ -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.
|
Edge module then forces stoploss value it evaluated to your strategy dynamically.
|
||||||
|
|
||||||
### Position size
|
### Position size
|
||||||
|
|
||||||
Edge also dictates the stake amount for each trade to the bot according to the following factors:
|
Edge also dictates the stake amount for each trade to the bot according to the following factors:
|
||||||
|
|
||||||
- Allowed capital at risk
|
- 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 is calculated as follows:
|
||||||
|
|
||||||
Allowed capital at risk = (Capital available_percentage) X (Allowed risk per trade)
|
```
|
||||||
|
Allowed capital at risk = (Capital available_percentage) X (Allowed risk per trade)
|
||||||
|
```
|
||||||
|
|
||||||
Stoploss is calculated as described above against historical data.
|
Stoploss is calculated as described above against historical data.
|
||||||
|
|
||||||
Your position size then will be:
|
Your position size then will be:
|
||||||
|
|
||||||
Position size = (Allowed capital at risk) / Stoploss
|
```
|
||||||
|
Position size = (Allowed capital at risk) / Stoploss
|
||||||
|
```
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
||||||
@@ -115,100 +140,30 @@ 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**.
|
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
|
## Configurations
|
||||||
|
|
||||||
Edge module has following configuration options:
|
Edge module has following configuration options:
|
||||||
|
|
||||||
#### enabled
|
| Parameter | Description |
|
||||||
If true, then Edge will run periodically.
|
|------------|-------------|
|
||||||
|
| `enabled` | If true, then Edge will run periodically. <br>*Defaults to `false`.* <br> ***Datatype:*** *Boolean*
|
||||||
(defaults to false)
|
| `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*
|
||||||
#### process_throttle_secs
|
| `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*
|
||||||
How often should Edge run in seconds?
|
| `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*
|
||||||
(defaults to 3600 so one hour)
|
| `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*
|
||||||
#### calculate_since_number_of_days
|
| `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*
|
||||||
Number of days of data against which Edge calculates Win Rate, Risk Reward and Expectancy
|
| `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*
|
||||||
Note that it downloads historical data so increasing this number would lead to slowing down the bot.
|
| `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*
|
||||||
(defaults to 7)
|
| `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*
|
||||||
|
|
||||||
#### 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)
|
|
||||||
|
|
||||||
## Running Edge independently
|
## Running Edge independently
|
||||||
|
|
||||||
You can run Edge independently in order to see in details the result. Here is an example:
|
You can run Edge independently in order to see in details the result. Here is an example:
|
||||||
|
|
||||||
```bash
|
``` bash
|
||||||
freqtrade edge
|
freqtrade edge
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -235,7 +190,7 @@ An example of its output:
|
|||||||
### Update cached pairs with the latest data
|
### Update cached pairs with the latest data
|
||||||
|
|
||||||
Edge requires historic data the same way as backtesting does.
|
Edge requires historic data the same way as backtesting does.
|
||||||
Please refer to the [download section](backtesting.md#Getting-data-for-backtesting-and-hyperopt) of the documentation for details.
|
Please refer to the [Data Downloading](data-download.md) section of the documentation for details.
|
||||||
|
|
||||||
### Precising stoploss range
|
### Precising stoploss range
|
||||||
|
|
||||||
@@ -249,13 +204,10 @@ freqtrade edge --stoplosses=-0.01,-0.1,-0.001 #min,max,step
|
|||||||
freqtrade edge --timerange=20181110-20181113
|
freqtrade edge --timerange=20181110-20181113
|
||||||
```
|
```
|
||||||
|
|
||||||
Doing `--timerange=-200` will get the last 200 timeframes from your inputdata. You can also specify specific dates, or a range span indexed by start and stop.
|
Doing `--timerange=-20190901` will get all available data until September 1st (excluding September 1st 2019).
|
||||||
|
|
||||||
The full timerange specification:
|
The full timerange specification:
|
||||||
|
|
||||||
* Use last 123 tickframes of data: `--timerange=-123`
|
|
||||||
* Use first 123 tickframes of data: `--timerange=123-`
|
|
||||||
* Use tickframes from line 123 through 456: `--timerange=123-456`
|
|
||||||
* Use tickframes till 2018/01/31: `--timerange=-20180131`
|
* Use tickframes till 2018/01/31: `--timerange=-20180131`
|
||||||
* Use tickframes since 2018/01/31: `--timerange=20180131-`
|
* Use tickframes since 2018/01/31: `--timerange=20180131-`
|
||||||
* Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
|
* Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
|
||||||
|
|||||||
84
docs/exchanges.md
Normal file
84
docs/exchanges.md
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
# Exchange-specific Notes
|
||||||
|
|
||||||
|
This page combines common gotchas and informations which are exchange-specific and most likely don't apply to other exchanges.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
### Blacklists
|
||||||
|
|
||||||
|
For Binance, please add `"BNB/<STAKE>"` to your blacklist to avoid issues.
|
||||||
|
Accounts having BNB accounts use this to pay for fees - if your first trade happens to be on `BNB`, further trades will consume this position and make the initial BNB order unsellable as the expected amount is not there anymore.
|
||||||
|
|
||||||
|
### Binance sites
|
||||||
|
|
||||||
|
Binance has been split into 3, and users must use the correct ccxt exchange ID for their exchange, otherwise API keys are not recognized.
|
||||||
|
|
||||||
|
* [binance.com](https://www.binance.com/) - International users. Use exchange id: `binance`.
|
||||||
|
* [binance.us](https://www.binance.us/) - US based users. Use exchange id: `binanceus`.
|
||||||
|
* [binance.je](https://www.binance.je/) - Binance Jersey, trading fiat currencies. Use exchange id: `binanceje`.
|
||||||
|
|
||||||
|
## Kraken
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
To download data for the Kraken exchange, using `--dl-trades` is mandatory, otherwise the bot will download the same 720 candles over and over, and you'll not have enough backtest data.
|
||||||
|
|
||||||
|
## Bittrex
|
||||||
|
|
||||||
|
### Restricted markets
|
||||||
|
|
||||||
|
Bittrex split its exchange into US and International versions.
|
||||||
|
The International version has more pairs available, however the API always returns all pairs, so there is currently no automated way to detect if you're affected by the restriction.
|
||||||
|
|
||||||
|
If you have restricted pairs in your whitelist, you'll get a warning message in the log on Freqtrade startup for each restricted pair.
|
||||||
|
|
||||||
|
The warning message will look similar to the following:
|
||||||
|
|
||||||
|
``` output
|
||||||
|
[...] Message: bittrex {"success":false,"message":"RESTRICTED_MARKET","result":null,"explanation":null}"
|
||||||
|
```
|
||||||
|
|
||||||
|
If you're an "International" customer on the Bittrex exchange, then this warning will probably not impact you.
|
||||||
|
If you're a US customer, the bot will fail to create orders for these pairs, and you should remove them from your whitelist.
|
||||||
|
|
||||||
|
You can get a list of restricted markets by using the following snippet:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
import ccxt
|
||||||
|
ct = ccxt.bittrex()
|
||||||
|
_ = ct.load_markets()
|
||||||
|
res = [ f"{x['MarketCurrency']}/{x['BaseCurrency']}" for x in ct.publicGetMarkets()['result'] if x['IsRestricted']]
|
||||||
|
print(res)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Random notes for other exchanges
|
||||||
|
|
||||||
|
* The Ocean (exchange id: `theocean`) exchange uses Web3 functionality and requires `web3` python package to be installed:
|
||||||
|
```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.
|
||||||
50
docs/faq.md
50
docs/faq.md
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
### The bot does not start
|
### The bot does not start
|
||||||
|
|
||||||
Running the bot with `freqtrade --config config.json` does show the output `freqtrade: command not found`.
|
Running the bot with `freqtrade trade --config config.json` does show the output `freqtrade: command not found`.
|
||||||
|
|
||||||
This could have the following reasons:
|
This could have the following reasons:
|
||||||
|
|
||||||
@@ -38,7 +38,7 @@ like pauses. You can stop your bot, adjust settings and start it again.
|
|||||||
|
|
||||||
### I want to improve the bot with a new strategy
|
### I want to improve the bot with a new strategy
|
||||||
|
|
||||||
That's great. We have a nice backtesting and hyperoptimizing setup. See
|
That's great. We have a nice backtesting and hyperoptimization setup. See
|
||||||
the tutorial [here|Testing-new-strategies-with-Hyperopt](bot-usage.md#hyperopt-commands).
|
the tutorial [here|Testing-new-strategies-with-Hyperopt](bot-usage.md#hyperopt-commands).
|
||||||
|
|
||||||
### Is there a setting to only SELL the coins being held and not perform anymore BUYS?
|
### Is there a setting to only SELL the coins being held and not perform anymore BUYS?
|
||||||
@@ -48,18 +48,52 @@ You can use the `/forcesell all` command from Telegram.
|
|||||||
### I get the message "RESTRICTED_MARKET"
|
### I get the message "RESTRICTED_MARKET"
|
||||||
|
|
||||||
Currently known to happen for US Bittrex users.
|
Currently known to happen for US Bittrex users.
|
||||||
Bittrex split its exchange into US and International versions.
|
|
||||||
The International version has more pairs available, however the API always returns all pairs, so there is currently no automated way to detect if you're affected by the restriction.
|
|
||||||
|
|
||||||
If you have restricted pairs in your whitelist, you'll get a warning message in the log on FreqTrade startup for each restricted pair.
|
Read [the Bittrex section about restricted markets](exchanges.md#restricted-markets) for more information.
|
||||||
If you're an "International" Customer on the Bittrex exchange, then this warning will probably not impact you.
|
|
||||||
If you're a US customer, the bot will fail to create orders for these pairs, and you should remove them from your Whitelist.
|
### 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.
|
||||||
|
|
||||||
|
* In unix shells, this normally can be done as simple as:
|
||||||
|
```shell
|
||||||
|
$ freqtrade --some-options 2>&1 >/dev/null | grep 'something'
|
||||||
|
```
|
||||||
|
(note, `2>&1` and `>/dev/null` should be written in this order)
|
||||||
|
|
||||||
|
* Bash interpreter also supports so called process substitution syntax, you can grep the log for a string with it as:
|
||||||
|
```shell
|
||||||
|
$ freqtrade --some-options 2> >(grep 'something') >/dev/null
|
||||||
|
```
|
||||||
|
or
|
||||||
|
```shell
|
||||||
|
$ freqtrade --some-options 2> >(grep -v 'something' 1>&2)
|
||||||
|
```
|
||||||
|
|
||||||
|
* You can also write the copy of Freqtrade log messages to a file with the `--logfile` option:
|
||||||
|
```shell
|
||||||
|
$ freqtrade --logfile /path/to/mylogfile.log --some-options
|
||||||
|
```
|
||||||
|
and then grep it as:
|
||||||
|
```shell
|
||||||
|
$ cat /path/to/mylogfile.log | grep 'something'
|
||||||
|
```
|
||||||
|
or even on the fly, as the bot works and the logfile grows:
|
||||||
|
```shell
|
||||||
|
$ tail -f /path/to/mylogfile.log | grep 'something'
|
||||||
|
```
|
||||||
|
from a separate terminal window.
|
||||||
|
|
||||||
|
On Windows, the `--logfilename` option is also supported by Freqtrade and you can use the `findstr` command to search the log for the string of interest:
|
||||||
|
```
|
||||||
|
> type \path\to\mylogfile.log | findstr "something"
|
||||||
|
```
|
||||||
|
|
||||||
## Hyperopt module
|
## Hyperopt module
|
||||||
|
|
||||||
### How many epoch do I need to get a good Hyperopt result?
|
### How many epoch do I need to get a good Hyperopt result?
|
||||||
|
|
||||||
Per default Hyperopts without `-e` or `--epochs` parameter will only
|
Per default Hyperopt called without the `-e`/`--epochs` command line option will only
|
||||||
run 100 epochs, means 100 evals of your triggers, guards, ... Too few
|
run 100 epochs, means 100 evals of your triggers, guards, ... Too few
|
||||||
to find a great result (unless if you are very lucky), so you probably
|
to find a great result (unless if you are very lucky), so you probably
|
||||||
have to run it for 10.000 or more. But it will take an eternity to
|
have to run it for 10.000 or more. But it will take an eternity to
|
||||||
|
|||||||
199
docs/hyperopt.md
199
docs/hyperopt.md
@@ -6,39 +6,63 @@ 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
|
search will burn all your CPU cores, make your laptop sound like a fighter jet
|
||||||
and still take a long time.
|
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.
|
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
|
!!! Bug
|
||||||
Hyperopt will crash when used with only 1 CPU Core as found out in [Issue #1133](https://github.com/freqtrade/freqtrade/issues/1133)
|
Hyperopt can crash when used with only 1 CPU Core as found out in [Issue #1133](https://github.com/freqtrade/freqtrade/issues/1133)
|
||||||
|
|
||||||
## Prepare Hyperopting
|
## Prepare Hyperopting
|
||||||
|
|
||||||
Before we start digging into Hyperopt, we recommend you to take a look at
|
Before we start digging into Hyperopt, we recommend you to take a look at
|
||||||
an example hyperopt file located into [user_data/hyperopts/](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/sample_hyperopt.py)
|
the sample hyperopt file located in [user_data/hyperopts/](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt.py).
|
||||||
|
|
||||||
Configuring hyperopt is similar to writing your own strategy, and many tasks will be similar and a lot of code can be copied across from the strategy.
|
Configuring hyperopt is similar to writing your own strategy, and many tasks will be similar and a lot of code can be copied across from the strategy.
|
||||||
|
|
||||||
|
The simplest way to get started is to use `freqtrade new-hyperopt --hyperopt AwesomeHyperopt`.
|
||||||
|
This will create a new hyperopt file from a template, which will be located under `user_data/hyperopts/AwesomeHyperopt.py`.
|
||||||
|
|
||||||
### Checklist on all tasks / possibilities in hyperopt
|
### Checklist on all tasks / possibilities in hyperopt
|
||||||
|
|
||||||
Depending on the space you want to optimize, only some of the below are required:
|
Depending on the space you want to optimize, only some of the below are required:
|
||||||
|
|
||||||
* fill `populate_indicators` - probably a copy from your strategy
|
|
||||||
* fill `buy_strategy_generator` - for buy signal optimization
|
* fill `buy_strategy_generator` - for buy signal optimization
|
||||||
* fill `indicator_space` - for buy signal optimzation
|
* fill `indicator_space` - for buy signal optimzation
|
||||||
* fill `sell_strategy_generator` - for sell signal optimization
|
* fill `sell_strategy_generator` - for sell signal optimization
|
||||||
* fill `sell_indicator_space` - for sell signal optimzation
|
* fill `sell_indicator_space` - for sell signal optimzation
|
||||||
|
|
||||||
Optional, but recommended:
|
!!! Note
|
||||||
|
`populate_indicators` needs to create all indicators any of thee spaces may use, otherwise hyperopt will not work.
|
||||||
|
|
||||||
|
Optional - can also be loaded from a strategy:
|
||||||
|
|
||||||
|
* copy `populate_indicators` from your strategy - otherwise default-strategy will be used
|
||||||
* copy `populate_buy_trend` from your strategy - otherwise default-strategy will be used
|
* copy `populate_buy_trend` from your strategy - otherwise default-strategy will be used
|
||||||
* copy `populate_sell_trend` from your strategy - otherwise default-strategy will be used
|
* copy `populate_sell_trend` from your strategy - otherwise default-strategy will be used
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Assuming the optional methods are not in your hyperopt file, please use `--strategy AweSomeStrategy` which contains these methods so hyperopt can use these methods instead.
|
||||||
|
|
||||||
Rarely you may also need to override:
|
Rarely you may also need to override:
|
||||||
|
|
||||||
* `roi_space` - for custom ROI optimization (if you need the ranges for the ROI parameters in the optimization hyperspace that differ from default)
|
* `roi_space` - for custom ROI optimization (if you need the ranges for the ROI parameters in the optimization hyperspace that differ from default)
|
||||||
* `generate_roi_table` - for custom ROI optimization (if you need more than 4 entries in the ROI table)
|
* `generate_roi_table` - for custom ROI optimization (if you need the ranges for the values in the ROI table that differ from default or the number of entries (steps) in the ROI table which differs from the default 4 steps)
|
||||||
* `stoploss_space` - for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default)
|
* `stoploss_space` - for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default)
|
||||||
|
* `trailing_space` - for custom trailing stop optimization (if you need the ranges for the trailing stop parameters in the optimization hyperspace that differ from default)
|
||||||
|
|
||||||
|
!!! Tip "Quickly optimize ROI, stoploss and trailing stoploss"
|
||||||
|
You can quickly optimize the spaces `roi`, `stoploss` and `trailing` without changing anything (i.e. without creation of a "complete" Hyperopt class with dimensions, parameters, triggers and guards, as described in this document) from the default hyperopt template by relying on your strategy to do most of the calculations.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
# Have a working strategy at hand.
|
||||||
|
freqtrade new-hyperopt --hyperopt EmptyHyperopt
|
||||||
|
|
||||||
|
freqtrade hyperopt --hyperopt EmptyHyperopt --spaces roi stoploss trailing --strategy MyWorkingStrategy --config config.json -e 100
|
||||||
|
```
|
||||||
|
|
||||||
### 1. Install a Custom Hyperopt File
|
### 1. Install a Custom Hyperopt File
|
||||||
|
|
||||||
@@ -64,9 +88,9 @@ multiple guards. The constructed strategy will be something like
|
|||||||
"*buy exactly when close price touches lower bollinger band, BUT only if
|
"*buy exactly when close price touches lower bollinger band, BUT only if
|
||||||
ADX > 10*".
|
ADX > 10*".
|
||||||
|
|
||||||
If you have updated the buy strategy, ie. changed the contents of
|
If you have updated the buy strategy, i.e. changed the contents of
|
||||||
`populate_buy_trend()` method you have to update the `guards` and
|
`populate_buy_trend()` method, you have to update the `guards` and
|
||||||
`triggers` hyperopts must use.
|
`triggers` your hyperopt must use correspondingly.
|
||||||
|
|
||||||
#### Sell optimization
|
#### Sell optimization
|
||||||
|
|
||||||
@@ -82,7 +106,7 @@ To avoid naming collisions in the search-space, please prefix all sell-spaces wi
|
|||||||
#### Using ticker-interval as part of the Strategy
|
#### Using ticker-interval as part of the Strategy
|
||||||
|
|
||||||
The Strategy exposes the ticker-interval as `self.ticker_interval`. The same value is available as class-attribute `HyperoptName.ticker_interval`.
|
The Strategy exposes the ticker-interval as `self.ticker_interval`. The same value is available as class-attribute `HyperoptName.ticker_interval`.
|
||||||
In the case of the linked sample-value this would be `SampleHyperOpts.ticker_interval`.
|
In the case of the linked sample-value this would be `SampleHyperOpt.ticker_interval`.
|
||||||
|
|
||||||
## Solving a Mystery
|
## Solving a Mystery
|
||||||
|
|
||||||
@@ -150,13 +174,9 @@ 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
|
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.
|
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.
|
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
|
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 `hyperopt.py`.
|
add it to the `populate_indicators()` method in your custom hyperopt file.
|
||||||
|
|
||||||
## Loss-functions
|
## Loss-functions
|
||||||
|
|
||||||
@@ -173,63 +193,7 @@ Currently, the following loss functions are builtin:
|
|||||||
* `OnlyProfitHyperOptLoss` (which takes only amount of profit into consideration)
|
* `OnlyProfitHyperOptLoss` (which takes only amount of profit into consideration)
|
||||||
* `SharpeHyperOptLoss` (optimizes Sharpe Ratio calculated on the trade returns)
|
* `SharpeHyperOptLoss` (optimizes Sharpe Ratio calculated on the trade returns)
|
||||||
|
|
||||||
### Creating and using a custom loss function
|
Creation of a custom loss function is covered in the [Advanced Hyperopt](advanced-hyperopt.md) part of the documentation.
|
||||||
|
|
||||||
To use a custom loss function class, make sure that the function `hyperopt_loss_function` is defined in your custom hyperopt loss class.
|
|
||||||
For the sample below, you then need to add the command line parameter `--hyperopt-loss SuperDuperHyperOptLoss` to your hyperopt call so this fuction is being used.
|
|
||||||
|
|
||||||
A sample of this can be found below, which is identical to the Default Hyperopt loss implementation. A full sample can be found [user_data/hyperopts/](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/sample_hyperopt_loss.py)
|
|
||||||
|
|
||||||
``` python
|
|
||||||
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
|
||||||
|
|
||||||
TARGET_TRADES = 600
|
|
||||||
EXPECTED_MAX_PROFIT = 3.0
|
|
||||||
MAX_ACCEPTED_TRADE_DURATION = 300
|
|
||||||
|
|
||||||
class SuperDuperHyperOptLoss(IHyperOptLoss):
|
|
||||||
"""
|
|
||||||
Defines the default loss function for hyperopt
|
|
||||||
"""
|
|
||||||
|
|
||||||
@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 better results
|
|
||||||
This is the legacy algorithm (used until now in freqtrade).
|
|
||||||
Weights are distributed as follows:
|
|
||||||
* 0.4 to trade duration
|
|
||||||
* 0.25: Avoiding trade loss
|
|
||||||
* 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above
|
|
||||||
"""
|
|
||||||
total_profit = results.profit_percent.sum()
|
|
||||||
trade_duration = results.trade_duration.mean()
|
|
||||||
|
|
||||||
trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8)
|
|
||||||
profit_loss = max(0, 1 - total_profit / EXPECTED_MAX_PROFIT)
|
|
||||||
duration_loss = 0.4 * min(trade_duration / MAX_ACCEPTED_TRADE_DURATION, 1)
|
|
||||||
result = trade_loss + profit_loss + duration_loss
|
|
||||||
return result
|
|
||||||
```
|
|
||||||
|
|
||||||
Currently, the arguments are:
|
|
||||||
|
|
||||||
* `results`: DataFrame containing the result
|
|
||||||
The following columns are available in results (corresponds to the output-file of backtesting when used with `--export trades`):
|
|
||||||
`pair, profit_percent, profit_abs, open_time, close_time, open_index, close_index, trade_duration, open_at_end, open_rate, close_rate, sell_reason`
|
|
||||||
* `trade_count`: Amount of trades (identical to `len(results)`)
|
|
||||||
* `min_date`: Start date of the hyperopting TimeFrame
|
|
||||||
* `min_date`: End date of the hyperopting TimeFrame
|
|
||||||
|
|
||||||
This function needs to return a floating point number (`float`). Smaller numbers will be interpreted as better results. The parameters and balancing for this is up to you.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
This function is called once per iteration - so please make sure to have this as optimized as possible to not slow hyperopt down unnecessarily.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Please keep the arguments `*args` and `**kwargs` in the interface to allow us to extend this interface later.
|
|
||||||
|
|
||||||
## Execute Hyperopt
|
## Execute Hyperopt
|
||||||
|
|
||||||
@@ -239,15 +203,15 @@ Because hyperopt tries a lot of combinations to find the best parameters it will
|
|||||||
We strongly recommend to use `screen` or `tmux` to prevent any connection loss.
|
We strongly recommend to use `screen` or `tmux` to prevent any connection loss.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade -c config.json hyperopt --customhyperopt <hyperoptname> -e 5000 --spaces all
|
freqtrade hyperopt --config config.json --hyperopt <hyperoptname> -e 5000 --spaces all
|
||||||
```
|
```
|
||||||
|
|
||||||
Use `<hyperoptname>` as the name of the custom hyperopt used.
|
Use `<hyperoptname>` as the name of the custom hyperopt used.
|
||||||
|
|
||||||
The `-e` flag will set how many evaluations hyperopt will do. We recommend
|
The `-e` option will set how many evaluations hyperopt will do. We recommend
|
||||||
running at least several thousand evaluations.
|
running at least several thousand evaluations.
|
||||||
|
|
||||||
The `--spaces all` flag determines that all possible parameters should be optimized. Possibilities are listed below.
|
The `--spaces all` option determines that all possible parameters should be optimized. Possibilities are listed below.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
By default, hyperopt will erase previous results and start from scratch. Continuation can be archived by using `--continue`.
|
By default, hyperopt will erase previous results and start from scratch. Continuation can be archived by using `--continue`.
|
||||||
@@ -270,9 +234,17 @@ For example, to use one month of data, pass the following parameter to the hyper
|
|||||||
freqtrade hyperopt --timerange 20180401-20180501
|
freqtrade hyperopt --timerange 20180401-20180501
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Running Hyperopt using methods from a strategy
|
||||||
|
|
||||||
|
Hyperopt can reuse `populate_indicators`, `populate_buy_trend`, `populate_sell_trend` from your strategy, assuming these methods are **not** in your custom hyperopt file, and a strategy is provided.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade hyperopt --strategy SampleStrategy --customhyperopt SampleHyperopt
|
||||||
|
```
|
||||||
|
|
||||||
### Running Hyperopt with Smaller Search Space
|
### Running Hyperopt with Smaller Search Space
|
||||||
|
|
||||||
Use the `--spaces` argument to limit the search space used by hyperopt.
|
Use the `--spaces` option to limit the search space used by hyperopt.
|
||||||
Letting Hyperopt optimize everything is a huuuuge search space. Often it
|
Letting Hyperopt optimize everything is a huuuuge search space. Often it
|
||||||
might make more sense to start by just searching for initial buy algorithm.
|
might make more sense to start by just searching for initial buy algorithm.
|
||||||
Or maybe you just want to optimize your stoploss or roi table for that awesome
|
Or maybe you just want to optimize your stoploss or roi table for that awesome
|
||||||
@@ -285,8 +257,12 @@ Legal values are:
|
|||||||
* `sell`: just search for a new sell strategy
|
* `sell`: just search for a new sell strategy
|
||||||
* `roi`: just optimize the minimal profit table for your strategy
|
* `roi`: just optimize the minimal profit table for your strategy
|
||||||
* `stoploss`: search for the best stoploss value
|
* `stoploss`: search for the best stoploss value
|
||||||
|
* `trailing`: search for the best trailing stop values
|
||||||
|
* `default`: `all` except `trailing`
|
||||||
* space-separated list of any of the above values for example `--spaces roi stoploss`
|
* space-separated list of any of the above values for example `--spaces roi stoploss`
|
||||||
|
|
||||||
|
The default Hyperopt Search Space, used when no `--space` command line option is specified, does not include the `trailing` hyperspace. We recommend you to run optimization for the `trailing` hyperspace separately, when the best parameters for other hyperspaces were found, validated and pasted into your custom strategy.
|
||||||
|
|
||||||
### Position stacking and disabling max market positions
|
### Position stacking and disabling max market positions
|
||||||
|
|
||||||
In some situations, you may need to run Hyperopt (and Backtesting) with the
|
In some situations, you may need to run Hyperopt (and Backtesting) with the
|
||||||
@@ -308,6 +284,16 @@ number).
|
|||||||
You can also enable position stacking in the configuration file by explicitly setting
|
You can also enable position stacking in the configuration file by explicitly setting
|
||||||
`"position_stacking"=true`.
|
`"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
|
## Understand the Hyperopt Result
|
||||||
|
|
||||||
Once Hyperopt is completed you can use the result to create a new strategy.
|
Once Hyperopt is completed you can use the result to create a new strategy.
|
||||||
@@ -341,8 +327,7 @@ So for example you had `rsi-value: 29.0` so we would look at `rsi`-block, that t
|
|||||||
(dataframe['rsi'] < 29.0)
|
(dataframe['rsi'] < 29.0)
|
||||||
```
|
```
|
||||||
|
|
||||||
Translating your whole hyperopt result as the new buy-signal
|
Translating your whole hyperopt result as the new buy-signal would then look like:
|
||||||
would then look like:
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:
|
def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:
|
||||||
@@ -361,19 +346,13 @@ You can use the `--print-all` command line option if you would like to see all r
|
|||||||
|
|
||||||
### Understand Hyperopt ROI results
|
### Understand Hyperopt ROI results
|
||||||
|
|
||||||
If you are optimizing ROI (i.e. if optimization search-space contains 'all' or 'roi'), your result will look as follows and include a ROI table:
|
If you are optimizing ROI (i.e. if optimization search-space contains 'all', 'default' or 'roi'), your result will look as follows and include a ROI table:
|
||||||
|
|
||||||
```
|
```
|
||||||
Best result:
|
Best result:
|
||||||
|
|
||||||
44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins. Objective: 1.94367
|
44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins. Objective: 1.94367
|
||||||
|
|
||||||
Buy hyperspace params:
|
|
||||||
{ 'adx-value': 44,
|
|
||||||
'rsi-value': 29,
|
|
||||||
'adx-enabled': False,
|
|
||||||
'rsi-enabled': True,
|
|
||||||
'trigger': 'bb_lower'}
|
|
||||||
ROI table:
|
ROI table:
|
||||||
{ 0: 0.10674,
|
{ 0: 0.10674,
|
||||||
21: 0.09158,
|
21: 0.09158,
|
||||||
@@ -397,7 +376,7 @@ As stated in the comment, you can also use it as the value of the `minimal_roi`
|
|||||||
|
|
||||||
#### Default ROI Search Space
|
#### Default ROI Search Space
|
||||||
|
|
||||||
If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace for you -- it's the hyperspace of components for the ROI tables. By default, each ROI table generated by the Freqtrade consists of 4 rows (steps). Hyperopt implements adaptive ranges for ROI tables with ranges for values in the ROI steps that depend on the ticker_interval used. By default the values can vary in the following ranges (for some of the most used ticker intervals, values are rounded to 5 digits after the decimal point):
|
If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace for you -- it's the hyperspace of components for the ROI tables. By default, each ROI table generated by the Freqtrade consists of 4 rows (steps). Hyperopt implements adaptive ranges for ROI tables with ranges for values in the ROI steps that depend on the 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 | |
|
| # step | 1m | | 5m | | 1h | | 1d | |
|
||||||
|---|---|---|---|---|---|---|---|---|
|
|---|---|---|---|---|---|---|---|---|
|
||||||
@@ -410,11 +389,11 @@ These ranges should be sufficient in most cases. The minutes in the steps (ROI d
|
|||||||
|
|
||||||
If you have the `generate_roi_table()` and `roi_space()` methods in your custom hyperopt file, remove them in order to utilize these adaptive ROI tables and the ROI hyperoptimization space generated by Freqtrade by default.
|
If you have the `generate_roi_table()` and `roi_space()` methods in your custom hyperopt file, remove them in order to utilize these adaptive ROI tables and the ROI hyperoptimization space generated by Freqtrade by default.
|
||||||
|
|
||||||
Override the `roi_space()` method if you need components of the ROI tables to vary in other ranges. Override the `generate_roi_table()` and `roi_space()` methods and implement your own custom approach for generation of the ROI tables during hyperoptimization if you need a different structure of the ROI tables or other amount of rows (steps). A sample for these methods can be found in [user_data/hyperopts/sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/sample_hyperopt_advanced.py).
|
Override the `roi_space()` method if you need components of the ROI tables to vary in other ranges. Override the `generate_roi_table()` and `roi_space()` methods and implement your own custom approach for generation of the ROI tables during hyperoptimization if you need a different structure of the ROI tables or other amount of rows (steps). A sample for these methods can be found in [user_data/hyperopts/sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_advanced.py).
|
||||||
|
|
||||||
### Understand Hyperopt Stoploss results
|
### Understand Hyperopt Stoploss results
|
||||||
|
|
||||||
If you are optimizing stoploss values (i.e. if optimization search-space contains 'all' or 'stoploss'), your result will look as follows and include stoploss:
|
If you are optimizing stoploss values (i.e. if optimization search-space contains 'all', 'default' or 'stoploss'), your result will look as follows and include stoploss:
|
||||||
|
|
||||||
```
|
```
|
||||||
Best result:
|
Best result:
|
||||||
@@ -441,13 +420,51 @@ As stated in the comment, you can also use it as the value of the `stoploss` set
|
|||||||
|
|
||||||
#### Default Stoploss Search Space
|
#### Default Stoploss Search Space
|
||||||
|
|
||||||
If you are optimizing stoploss values, Freqtrade creates the 'stoploss' optimization hyperspace for you. By default, the stoploss values in that hyperspace can vary in the range -0.35...-0.02, which is sufficient in most cases.
|
If you are optimizing stoploss values, Freqtrade creates the 'stoploss' optimization hyperspace for you. By default, the stoploss values in that hyperspace vary in the range -0.35...-0.02, which is sufficient in most cases.
|
||||||
|
|
||||||
If you have the `stoploss_space()` method in your custom hyperopt file, remove it in order to utilize Stoploss hyperoptimization space generated by Freqtrade by default.
|
If you have the `stoploss_space()` method in your custom hyperopt file, remove it in order to utilize Stoploss hyperoptimization space generated by Freqtrade by default.
|
||||||
|
|
||||||
Override the `stoploss_space()` method and define the desired range in it if you need stoploss values to vary in other range during hyperoptimization. A sample for this method can be found in [user_data/hyperopts/sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/sample_hyperopt_advanced.py).
|
Override the `stoploss_space()` method and define the desired range in it if you need stoploss values to vary in other range during hyperoptimization. A sample for this method can be found in [user_data/hyperopts/sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_advanced.py).
|
||||||
|
|
||||||
### Validate backtesting results
|
### Understand Hyperopt Trailing Stop results
|
||||||
|
|
||||||
|
If you are optimizing trailing stop values (i.e. if optimization search-space contains 'all' or 'trailing'), your result will look as follows and include trailing stop parameters:
|
||||||
|
|
||||||
|
```
|
||||||
|
Best result:
|
||||||
|
|
||||||
|
45/100: 606 trades. Avg profit 1.04%. Total profit 0.31555614 BTC ( 630.48Σ%). Avg duration 150.3 mins. Objective: -1.10161
|
||||||
|
|
||||||
|
Trailing stop:
|
||||||
|
{ 'trailing_only_offset_is_reached': True,
|
||||||
|
'trailing_stop': True,
|
||||||
|
'trailing_stop_positive': 0.02001,
|
||||||
|
'trailing_stop_positive_offset': 0.06038}
|
||||||
|
```
|
||||||
|
|
||||||
|
In order to use these best trailing stop parameters found by Hyperopt in backtesting and for live trades/dry-run, copy-paste them as the values of the corresponding attributes of your custom strategy:
|
||||||
|
|
||||||
|
```
|
||||||
|
# Trailing stop
|
||||||
|
# These attributes will be overridden if the config file contains corresponding values.
|
||||||
|
trailing_stop = True
|
||||||
|
trailing_stop_positive = 0.02001
|
||||||
|
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
|
||||||
|
|
||||||
|
If you are optimizing trailing stop values, Freqtrade creates the 'trailing' optimization hyperspace for you. By default, the `trailing_stop` parameter is always set to True in that hyperspace, the value of the `trailing_only_offset_is_reached` vary between True and False, the values of the `trailing_stop_positive` and `trailing_stop_positive_offset` parameters vary in the ranges 0.02...0.35 and 0.01...0.1 correspondingly, which is sufficient in most cases.
|
||||||
|
|
||||||
|
Override the `trailing_space()` method and define the desired range in it if you need values of the trailing stop parameters to vary in other ranges during hyperoptimization. A sample for this method can be found in [user_data/hyperopts/sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/sample_hyperopt_advanced.py).
|
||||||
|
|
||||||
|
## Show details of Hyperopt results
|
||||||
|
|
||||||
|
After you run Hyperopt for the desired amount of epochs, you can later list all results for analysis, select only best or profitable once, and show the details for any of the epochs previously evaluated. This can be done with the `hyperopt-list` and `hyperopt-show` subcommands. The usage of these subcommands is described in the [Utils](utils.md#list-hyperopt-results) chapter.
|
||||||
|
|
||||||
|
## Validate backtesting results
|
||||||
|
|
||||||
Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.
|
Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
<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. -->
|
<!-- Place this tag where you want the button to render. -->
|
||||||
<a class="github-button" href="https://github.com/freqtrade" data-size="large" aria-label="Follow @freqtrade on GitHub">Follow @freqtrade</a>
|
<a class="github-button" href="https://github.com/freqtrade" data-size="large" aria-label="Follow @freqtrade on GitHub">Follow @freqtrade</a>
|
||||||
|
|
||||||
## Introduction
|
## Introduction
|
||||||
Freqtrade is a 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"
|
!!! Danger "DISCLAIMER"
|
||||||
This software is for educational purposes only. Do not risk money which you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.
|
This software is for educational purposes only. Do not risk money which you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.
|
||||||
@@ -23,18 +25,15 @@ Freqtrade is a cryptocurrency trading bot written in Python.
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Based on Python 3.6+: For botting on any operating system — Windows, macOS and Linux.
|
- 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).
|
||||||
- Persistence: Persistence is achieved through sqlite database.
|
- Download market data: Download historical data of the exchange and the markets your may want to trade with.
|
||||||
- Dry-run mode: Run the bot without playing money.
|
- Backtest: Test your strategy on downloaded historical data.
|
||||||
- Backtesting: Run a simulation of your buy/sell strategy with 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.
|
||||||
- Strategy Optimization by machine learning: Use machine learning to optimize your buy/sell strategy parameters with real exchange data.
|
- 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.
|
||||||
- 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.
|
- Run: Test your strategy with simulated money (Dry-Run mode) or deploy it with real money (Live-Trade mode).
|
||||||
- Whitelist crypto-currencies: Select which crypto-currency you want to trade or use dynamic whitelists based on market (pair) trade volume.
|
- 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.
|
||||||
- Blacklist crypto-currencies: Select which crypto-currency you want to avoid.
|
- Control/Monitor: Use Telegram or a REST API (start/stop the bot, show profit/loss, daily summary, current open trades results, etc.).
|
||||||
- Manageable via Telegram or REST APi: Manage the bot with Telegram or via the builtin REST API.
|
- 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).
|
||||||
- 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.
|
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
@@ -61,10 +60,10 @@ To run this bot we recommend you a cloud instance with a minimum of:
|
|||||||
|
|
||||||
## Support
|
## Support
|
||||||
|
|
||||||
Help / Slack
|
### 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.
|
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?
|
## Ready to try?
|
||||||
|
|
||||||
|
|||||||
@@ -26,24 +26,32 @@ You will need to create API Keys (Usually you get `key` and `secret`) from the E
|
|||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
Freqtrade provides a Linux/MacOS script to install all dependencies and help you to configure the bot.
|
Freqtrade provides the Linux/MacOS Easy Installation script to install all dependencies and help you configure the bot.
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Python3.6 or higher and the corresponding pip are assumed to be available. The install-script will warn and stop if that's not the case.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git clone git@github.com:freqtrade/freqtrade.git
|
|
||||||
cd freqtrade
|
|
||||||
git checkout develop
|
|
||||||
./setup.sh --install
|
|
||||||
```
|
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Windows installation is explained [here](#windows).
|
Windows installation is explained [here](#windows).
|
||||||
|
|
||||||
## Easy Installation - Linux Script
|
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.
|
||||||
|
|
||||||
If you are on Debian, Ubuntu or MacOS freqtrade provides a script to Install, Update, Configure, and Reset your bot.
|
!!! 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).
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Python3.6 or higher and the corresponding `pip` are assumed to be available. The install-script will warn you and stop if that's not the case. `git` is also needed to clone the Freqtrade repository.
|
||||||
|
|
||||||
|
This can be achieved with the following commands:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone git@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)
|
||||||
|
|
||||||
|
If you are on Debian, Ubuntu or MacOS Freqtrade provides the script to install, update, configure and reset the codebase of your bot.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ ./setup.sh
|
$ ./setup.sh
|
||||||
@@ -56,25 +64,25 @@ usage:
|
|||||||
|
|
||||||
** --install **
|
** --install **
|
||||||
|
|
||||||
This script will install everything you need to run the bot:
|
With this option, the script will install everything you need to run the bot:
|
||||||
|
|
||||||
* Mandatory software as: `ta-lib`
|
* Mandatory software as: `ta-lib`
|
||||||
* Setup your virtualenv
|
* Setup your virtualenv
|
||||||
* Configure your `config.json` file
|
* Configure your `config.json` file
|
||||||
|
|
||||||
This script is a combination of `install script` `--reset`, `--config`
|
This option is a combination of installation tasks, `--reset` and `--config`.
|
||||||
|
|
||||||
** --update **
|
** --update **
|
||||||
|
|
||||||
Update parameter will pull the last version of your current branch and update your virtualenv.
|
This option will pull the last version of your current branch and update your virtualenv. Run the script with this option periodically to update your bot.
|
||||||
|
|
||||||
** --reset **
|
** --reset **
|
||||||
|
|
||||||
Reset parameter will hard reset your branch (only if you are on `master` or `develop`) and recreate your virtualenv.
|
This option will hard reset your branch (only if you are on either `master` or `develop`) and recreate your virtualenv.
|
||||||
|
|
||||||
** --config **
|
** --config **
|
||||||
|
|
||||||
Config parameter is a `config.json` configurator. This script will ask you questions to setup your bot and create your `config.json`.
|
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`.
|
||||||
|
|
||||||
------
|
------
|
||||||
|
|
||||||
@@ -95,29 +103,26 @@ sudo apt-get update
|
|||||||
sudo apt-get install build-essential git
|
sudo apt-get install build-essential git
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Raspberry Pi / Raspbian
|
### Raspberry Pi / Raspbian
|
||||||
|
|
||||||
Before installing FreqTrade on a Raspberry Pi running the official Raspbian Image, make sure you have at least Python 3.6 installed. The default image only provides Python 3.5. Probably the easiest way to get a recent version of python is [miniconda](https://repo.continuum.io/miniconda/).
|
The following assumes the latest [Raspbian Buster lite image](https://www.raspberrypi.org/downloads/raspbian/) from at least September 2019.
|
||||||
|
This image comes with python3.7 preinstalled, making it easy to get freqtrade up and running.
|
||||||
|
|
||||||
The following assumes that miniconda3 is installed and available in your environment. Since the last miniconda3 installation file uses python 3.4, we will update to python 3.6 on this installation.
|
Tested using a Raspberry Pi 3 with the Raspbian Buster lite image, all updates applied.
|
||||||
It's recommended to use (mini)conda for this as installation/compilation of `numpy` and `pandas` takes a long time.
|
|
||||||
|
|
||||||
Additional package to install on your Raspbian, `libffi-dev` required by cryptography (from python-telegram-bot).
|
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
conda config --add channels rpi
|
sudo apt-get install python3-venv libatlas-base-dev
|
||||||
conda install python=3.6
|
git clone https://github.com/freqtrade/freqtrade.git
|
||||||
conda create -n freqtrade python=3.6
|
cd freqtrade
|
||||||
conda activate freqtrade
|
|
||||||
conda install pandas numpy
|
|
||||||
|
|
||||||
sudo apt install libffi-dev
|
bash setup.sh -i
|
||||||
python3 -m pip install -r requirements-common.txt
|
|
||||||
python3 -m pip install -e .
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
!!! Note "Installation duration"
|
||||||
|
Depending on your internet speed and the Raspberry Pi version, installation can take multiple hours to complete.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
This does not install hyperopt dependencies. To install these, please use `python3 -m pip install -e .[hyperopt]`.
|
The above does not install hyperopt dependencies. To install these, please use `python3 -m pip install -e .[hyperopt]`.
|
||||||
We do not advise to run hyperopt on a Raspberry Pi, since this is a very resource-heavy operation, which should be done on powerful machine.
|
We do not advise to run hyperopt on a Raspberry Pi, since this is a very resource-heavy operation, which should be done on powerful machine.
|
||||||
|
|
||||||
### Common
|
### Common
|
||||||
@@ -151,13 +156,13 @@ python3 -m venv .env
|
|||||||
source .env/bin/activate
|
source .env/bin/activate
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 3. Install FreqTrade
|
#### 3. Install Freqtrade
|
||||||
|
|
||||||
Clone the git repository:
|
Clone the git repository:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/freqtrade/freqtrade.git
|
git clone https://github.com/freqtrade/freqtrade.git
|
||||||
|
cd freqtrade
|
||||||
```
|
```
|
||||||
|
|
||||||
Optionally checkout the master branch to get the latest stable release:
|
Optionally checkout the master branch to get the latest stable release:
|
||||||
@@ -166,59 +171,37 @@ Optionally checkout the master branch to get the latest stable release:
|
|||||||
git checkout master
|
git checkout master
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 4. Initialize the configuration
|
#### 4. Install python dependencies
|
||||||
|
|
||||||
```bash
|
|
||||||
cd freqtrade
|
|
||||||
cp config.json.example config.json
|
|
||||||
```
|
|
||||||
|
|
||||||
> *To edit the config please refer to [Bot Configuration](configuration.md).*
|
|
||||||
|
|
||||||
#### 5. Install python dependencies
|
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
python3 -m pip install --upgrade pip
|
python3 -m pip install --upgrade pip
|
||||||
python3 -m pip install -e .
|
python3 -m pip install -e .
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### 5. Initialize the configuration
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Initialize the user_directory
|
||||||
|
freqtrade create-userdir --userdir user_data/
|
||||||
|
|
||||||
|
cp config.json.example config.json
|
||||||
|
```
|
||||||
|
|
||||||
|
> *To edit the config please refer to [Bot Configuration](configuration.md).*
|
||||||
|
|
||||||
#### 6. Run the Bot
|
#### 6. Run the Bot
|
||||||
|
|
||||||
If this is the first time you run the bot, ensure you are running it in Dry-run `"dry_run": true,` otherwise it will start to buy and sell coins.
|
If this is the first time you run the bot, ensure you are running it in Dry-run `"dry_run": true,` otherwise it will start to buy and sell coins.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade -c config.json
|
freqtrade trade -c config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
*Note*: If you run the bot on a server, you should consider using [Docker](docker.md) or a terminal multiplexer like `screen` or [`tmux`](https://en.wikipedia.org/wiki/Tmux) to avoid that the bot is stopped on logout.
|
*Note*: If you run the bot on a server, you should consider using [Docker](docker.md) or a terminal multiplexer like `screen` or [`tmux`](https://en.wikipedia.org/wiki/Tmux) to avoid that the bot is stopped on logout.
|
||||||
|
|
||||||
#### 7. [Optional] Configure `freqtrade` as a `systemd` service
|
#### 7. (Optional) Post-installation Tasks
|
||||||
|
|
||||||
From the freqtrade repo... copy `freqtrade.service` to your systemd user directory (usually `~/.config/systemd/user`) and update `WorkingDirectory` and `ExecStart` to match your setup.
|
On Linux, as an optional post-installation task, you may wish to setup the bot to run as a `systemd` service or configure it to send the log messages to the `syslog`/`rsyslog` or `journald` daemons. See [Advanced Logging](advanced-setup.md#advanced-logging) for details.
|
||||||
|
|
||||||
After that you can start the daemon with:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
systemctl --user start freqtrade
|
|
||||||
```
|
|
||||||
|
|
||||||
For this to be persistent (run when user is logged out) you'll need to enable `linger` for your freqtrade user.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo loginctl enable-linger "$USER"
|
|
||||||
```
|
|
||||||
|
|
||||||
If you run the bot as a service, you can use systemd service manager as a software watchdog monitoring freqtrade bot
|
|
||||||
state and restarting it in the case of failures. If the `internals.sd_notify` parameter is set to true in the
|
|
||||||
configuration or the `--sd-notify` command line option is used, the bot will send keep-alive ping messages to systemd
|
|
||||||
using the sd_notify (systemd notifications) protocol and will also tell systemd its current state (Running or Stopped)
|
|
||||||
when it changes.
|
|
||||||
|
|
||||||
The `freqtrade.service.watchdog` file contains an example of the service unit configuration file which uses systemd
|
|
||||||
as the watchdog.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
The sd_notify communication between the bot and the systemd service manager will not work if the bot runs in a Docker container.
|
|
||||||
|
|
||||||
------
|
------
|
||||||
|
|
||||||
@@ -242,6 +225,12 @@ If that is not available on your system, feel free to try the instructions below
|
|||||||
|
|
||||||
### Install freqtrade manually
|
### Install freqtrade manually
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Make sure to use 64bit Windows and 64bit Python to avoid problems with backtesting or hyperopt due to the memory constraints 32bit applications have under Windows.
|
||||||
|
|
||||||
|
!!! Hint
|
||||||
|
Using the [Anaconda Distribution](https://www.anaconda.com/distribution/) under Windows can greatly help with installation problems. Check out the [Conda section](#using-conda) in this document for more information.
|
||||||
|
|
||||||
#### Clone the git repository
|
#### Clone the git repository
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -257,14 +246,12 @@ As compiling from source on windows has heavy dependencies (requires a partial v
|
|||||||
```cmd
|
```cmd
|
||||||
>cd \path\freqtrade-develop
|
>cd \path\freqtrade-develop
|
||||||
>python -m venv .env
|
>python -m venv .env
|
||||||
>cd .env\Scripts
|
>.env\Scripts\activate.bat
|
||||||
>activate.bat
|
|
||||||
>cd \path\freqtrade-develop
|
|
||||||
REM optionally install ta-lib from wheel
|
REM optionally install ta-lib from wheel
|
||||||
REM >pip install TA_Lib‑0.4.17‑cp36‑cp36m‑win32.whl
|
REM >pip install TA_Lib‑0.4.17‑cp36‑cp36m‑win32.whl
|
||||||
>pip install -r requirements.txt
|
>pip install -r requirements.txt
|
||||||
>pip install -e .
|
>pip install -e .
|
||||||
>python freqtrade\main.py
|
>freqtrade
|
||||||
```
|
```
|
||||||
|
|
||||||
> Thanks [Owdr](https://github.com/Owdr) for the commands. Source: [Issue #222](https://github.com/freqtrade/freqtrade/issues/222)
|
> Thanks [Owdr](https://github.com/Owdr) for the commands. Source: [Issue #222](https://github.com/freqtrade/freqtrade/issues/222)
|
||||||
@@ -283,3 +270,18 @@ The easiest way is to download install Microsoft Visual Studio Community [here](
|
|||||||
|
|
||||||
Now you have an environment ready, the next step is
|
Now you have an environment ready, the next step is
|
||||||
[Bot Configuration](configuration.md).
|
[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.
|
||||||
|
|||||||
@@ -49,4 +49,6 @@
|
|||||||
</nav>
|
</nav>
|
||||||
<!-- Place this tag in your head or just before your close body tag. -->
|
<!-- Place this tag in your head or just before your close body tag. -->
|
||||||
<script async defer src="https://buttons.github.io/buttons.js"></script>
|
<script async defer src="https://buttons.github.io/buttons.js"></script>
|
||||||
|
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
|
||||||
|
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
|
||||||
</header>
|
</header>
|
||||||
182
docs/plotting.md
182
docs/plotting.md
@@ -23,45 +23,53 @@ The `freqtrade plot-dataframe` subcommand shows an interactive graph with three
|
|||||||
Possible arguments:
|
Possible arguments:
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade plot-dataframe [-h] [-p PAIRS [PAIRS ...]]
|
usage: freqtrade plot-dataframe [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME]
|
||||||
[--indicators1 INDICATORS1 [INDICATORS1 ...]]
|
[--strategy-path PATH] [-p PAIRS [PAIRS ...]] [--indicators1 INDICATORS1 [INDICATORS1 ...]]
|
||||||
[--indicators2 INDICATORS2 [INDICATORS2 ...]]
|
[--indicators2 INDICATORS2 [INDICATORS2 ...]] [--plot-limit INT] [--db-url PATH]
|
||||||
[--plot-limit INT] [--db-url PATH]
|
[--trade-source {DB,file}] [--export EXPORT] [--export-filename PATH] [--timerange TIMERANGE]
|
||||||
[--trade-source {DB,file}] [--export EXPORT]
|
[-i TICKER_INTERVAL]
|
||||||
[--export-filename PATH]
|
|
||||||
[--timerange TIMERANGE]
|
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||||
Show profits for only these pairs. Pairs are space-
|
Show profits for only these pairs. Pairs are space-separated.
|
||||||
separated.
|
|
||||||
--indicators1 INDICATORS1 [INDICATORS1 ...]
|
--indicators1 INDICATORS1 [INDICATORS1 ...]
|
||||||
Set indicators from your strategy you want in the
|
Set indicators from your strategy you want in the first row of the graph. Space-separated list. Example:
|
||||||
first row of the graph. Space-separated list. Example:
|
|
||||||
`ema3 ema5`. Default: `['sma', 'ema3', 'ema5']`.
|
`ema3 ema5`. Default: `['sma', 'ema3', 'ema5']`.
|
||||||
--indicators2 INDICATORS2 [INDICATORS2 ...]
|
--indicators2 INDICATORS2 [INDICATORS2 ...]
|
||||||
Set indicators from your strategy you want in the
|
Set indicators from your strategy you want in the third row of the graph. Space-separated list. Example:
|
||||||
third row of the graph. Space-separated list. Example:
|
|
||||||
`fastd fastk`. Default: `['macd', 'macdsignal']`.
|
`fastd fastk`. Default: `['macd', 'macdsignal']`.
|
||||||
--plot-limit INT Specify tick limit for plotting. Notice: too high
|
--plot-limit INT Specify tick limit for plotting. Notice: too high values cause huge files. Default: 750.
|
||||||
values cause huge files. Default: 750.
|
--db-url PATH Override trades database URL, this is useful in custom deployments (default: `sqlite:///tradesv3.sqlite`
|
||||||
--db-url PATH Override trades database URL, this is useful in custom
|
for Live Run mode, `sqlite:///tradesv3.dryrun.sqlite` for Dry Run).
|
||||||
deployments (default: `sqlite:///tradesv3.sqlite` for
|
|
||||||
Live Run mode, `sqlite://` for Dry Run).
|
|
||||||
--trade-source {DB,file}
|
--trade-source {DB,file}
|
||||||
Specify the source for trades (Can be DB or file
|
Specify the source for trades (Can be DB or file (backtest file)) Default: file
|
||||||
(backtest file)) Default: file
|
--export EXPORT Export backtest results, argument are: trades. Example: `--export=trades`
|
||||||
--export EXPORT Export backtest results, argument are: trades.
|
|
||||||
Example: `--export=trades`
|
|
||||||
--export-filename PATH
|
--export-filename PATH
|
||||||
Save backtest results to the file with this filename
|
Save backtest results to the file with this filename. Requires `--export` to be set as well. Example:
|
||||||
(default: `user_data/backtest_results/backtest-
|
`--export-filename=user_data/backtest_results/backtest_today.json`
|
||||||
result.json`). Requires `--export` to be set as well.
|
|
||||||
Example: `--export-filename=user_data/backtest_results
|
|
||||||
/backtest_today.json`
|
|
||||||
--timerange TIMERANGE
|
--timerange TIMERANGE
|
||||||
Specify what timerange of data to use.
|
Specify what timerange of data to use.
|
||||||
|
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||||
|
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. 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.
|
||||||
|
|
||||||
|
Strategy arguments:
|
||||||
|
-s NAME, --strategy NAME
|
||||||
|
Specify strategy class name which will be used by the bot.
|
||||||
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -79,11 +87,11 @@ The `-p/--pairs` argument can be used to specify pairs you would like to plot.
|
|||||||
Specify custom indicators.
|
Specify custom indicators.
|
||||||
Use `--indicators1` for the main plot and `--indicators2` for the subplot below (if values are in a different range than prices).
|
Use `--indicators1` for the main plot and `--indicators2` for the subplot below (if values are in a different range than prices).
|
||||||
|
|
||||||
!!! tip
|
!!! Tip
|
||||||
You will almost certainly want to specify a custom strategy! This can be done by adding `-s Classname` / `--strategy ClassName` to the command.
|
You will almost certainly want to specify a custom strategy! This can be done by adding `-s Classname` / `--strategy ClassName` to the command.
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade --strategy AwesomeStrategy plot-dataframe -p BTC/ETH --indicators1 sma ema --indicators2 macd
|
freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --indicators1 sma ema --indicators2 macd
|
||||||
```
|
```
|
||||||
|
|
||||||
### Further usage examples
|
### Further usage examples
|
||||||
@@ -91,37 +99,98 @@ freqtrade --strategy AwesomeStrategy plot-dataframe -p BTC/ETH --indicators1 sma
|
|||||||
To plot multiple pairs, separate them with a space:
|
To plot multiple pairs, separate them with a space:
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade --strategy AwesomeStrategy plot-dataframe -p BTC/ETH XRP/ETH
|
freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH XRP/ETH
|
||||||
```
|
```
|
||||||
|
|
||||||
To plot a timerange (to zoom in)
|
To plot a timerange (to zoom in)
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade --strategy AwesomeStrategy plot-dataframe -p BTC/ETH --timerange=20180801-20180805
|
freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --timerange=20180801-20180805
|
||||||
```
|
```
|
||||||
|
|
||||||
To plot trades stored in a database use `--db-url` in combination with `--trade-source DB`:
|
To plot trades stored in a database use `--db-url` in combination with `--trade-source DB`:
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade --strategy AwesomeStrategy plot-dataframe --db-url sqlite:///tradesv3.dry_run.sqlite -p BTC/ETH --trade-source DB
|
freqtrade plot-dataframe --strategy AwesomeStrategy --db-url sqlite:///tradesv3.dry_run.sqlite -p BTC/ETH --trade-source DB
|
||||||
```
|
```
|
||||||
|
|
||||||
To plot trades from a backtesting result, use `--export-filename <filename>`
|
To plot trades from a backtesting result, use `--export-filename <filename>`
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade --strategy AwesomeStrategy plot-dataframe --export-filename user_data/backtest_results/backtest-result.json -p BTC/ETH
|
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
|
## 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
|
* Average closing price for all pairs.
|
||||||
2) The summarized profit made by backtesting.
|
* The summarized profit made by backtesting.
|
||||||
Note that this is not the real-world profit, but more of an estimate.
|
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.
|
The first graph is good to get a grip of how the overall market progresses.
|
||||||
|
|
||||||
@@ -133,10 +202,11 @@ The third graph can be useful to spot outliers, events in pairs that cause profi
|
|||||||
Possible options for the `freqtrade plot-profit` subcommand:
|
Possible options for the `freqtrade plot-profit` subcommand:
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade plot-profit [-h] [-p PAIRS [PAIRS ...]]
|
usage: freqtrade plot-profit [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
|
[-d PATH] [--userdir PATH] [-p PAIRS [PAIRS ...]]
|
||||||
[--timerange TIMERANGE] [--export EXPORT]
|
[--timerange TIMERANGE] [--export EXPORT]
|
||||||
[--export-filename PATH] [--db-url PATH]
|
[--export-filename PATH] [--db-url PATH]
|
||||||
[--trade-source {DB,file}]
|
[--trade-source {DB,file}] [-i TICKER_INTERVAL]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
@@ -148,17 +218,35 @@ optional arguments:
|
|||||||
--export EXPORT Export backtest results, argument are: trades.
|
--export EXPORT Export backtest results, argument are: trades.
|
||||||
Example: `--export=trades`
|
Example: `--export=trades`
|
||||||
--export-filename PATH
|
--export-filename PATH
|
||||||
Save backtest results to the file with this filename
|
Save backtest results to the file with this filename.
|
||||||
(default: `user_data/backtest_results/backtest-
|
Requires `--export` to be set as well. Example:
|
||||||
result.json`). Requires `--export` to be set as well.
|
`--export-filename=user_data/backtest_results/backtest
|
||||||
Example: `--export-filename=user_data/backtest_results
|
_today.json`
|
||||||
/backtest_today.json`
|
|
||||||
--db-url PATH Override trades database URL, this is useful in custom
|
--db-url PATH Override trades database URL, this is useful in custom
|
||||||
deployments (default: `sqlite:///tradesv3.sqlite` for
|
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}
|
--trade-source {DB,file}
|
||||||
Specify the source for trades (Can be DB or file
|
Specify the source for trades (Can be DB or file
|
||||||
(backtest file)) Default: file
|
(backtest file)) Default: file
|
||||||
|
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||||
|
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. 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.
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -179,5 +267,5 @@ freqtrade plot-profit -p LTC/BTC --db-url sqlite:///tradesv3.sqlite --trade-sou
|
|||||||
```
|
```
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade plot-profit --datadir user_data/data/binance_save/ -p LTC/BTC
|
freqtrade --datadir user_data/data/binance_save/ plot-profit -p LTC/BTC
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
mkdocs-material==4.4.2
|
mkdocs-material==4.6.0
|
||||||
|
mdx_truly_sane_lists==1.2
|
||||||
|
|||||||
@@ -16,13 +16,20 @@ Sample configuration:
|
|||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Danger Security warning
|
!!! Danger "Security warning"
|
||||||
By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet and choose a strong, unique password, since others will potentially be able to control your bot.
|
By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet and choose a strong, unique password, since others will potentially be able to control your bot.
|
||||||
|
|
||||||
!!! Danger Password selection
|
!!! Danger "Password selection"
|
||||||
Please make sure to select a very strong, unique password to protect your bot from unauthorized access.
|
Please make sure to select a very strong, unique password to protect your bot from unauthorized access.
|
||||||
|
|
||||||
You can then access the API by going to `http://127.0.0.1:8080/api/v1/version` to check if the API is running correctly.
|
You can then access the API by going to `http://127.0.0.1:8080/api/v1/ping` in a browser to check if the API is running correctly.
|
||||||
|
This should return the response:
|
||||||
|
|
||||||
|
``` output
|
||||||
|
{"status":"pong"}
|
||||||
|
```
|
||||||
|
|
||||||
|
All other endpoints return sensitive info and require authentication, so are not available through a web browser.
|
||||||
|
|
||||||
To generate a secure password, either use a password manager, or use the below code snipped.
|
To generate a secure password, either use a password manager, or use the below code snipped.
|
||||||
|
|
||||||
@@ -58,7 +65,7 @@ docker run -d \
|
|||||||
-v ~/.freqtrade/user_data/:/freqtrade/user_data \
|
-v ~/.freqtrade/user_data/:/freqtrade/user_data \
|
||||||
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
||||||
-p 127.0.0.1:8080:8080 \
|
-p 127.0.0.1:8080:8080 \
|
||||||
freqtrade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy
|
freqtrade trade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Danger "Security warning"
|
!!! Danger "Security warning"
|
||||||
@@ -99,8 +106,8 @@ python3 scripts/rest_client.py --config rest_config.json <command> [optional par
|
|||||||
| `stop` | | Stops the trader
|
| `stop` | | Stops the trader
|
||||||
| `stopbuy` | | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
| `stopbuy` | | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
||||||
| `reload_conf` | | Reloads the configuration file
|
| `reload_conf` | | Reloads the configuration file
|
||||||
|
| `show_config` | | Shows part of the current configuration with relevant settings to operation
|
||||||
| `status` | | Lists all open trades
|
| `status` | | Lists all open trades
|
||||||
| `status table` | | List all open trades in a table format
|
|
||||||
| `count` | | Displays number of trades used and available
|
| `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
|
| `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`).
|
| `forcesell <trade_id>` | | Instantly sells the given trade (Ignoring `minimum_roi`).
|
||||||
@@ -166,6 +173,10 @@ reload_conf
|
|||||||
Reload configuration
|
Reload configuration
|
||||||
:returns: json object
|
:returns: json object
|
||||||
|
|
||||||
|
show_config
|
||||||
|
Returns part of the configuration, relevant for trading operations.
|
||||||
|
:return: json object containing the version
|
||||||
|
|
||||||
start
|
start
|
||||||
Start the bot if it's in stopped state.
|
Start the bot if it's in stopped state.
|
||||||
:returns: json object
|
:returns: json object
|
||||||
|
|||||||
101
docs/stoploss.md
101
docs/stoploss.md
@@ -3,74 +3,101 @@
|
|||||||
The `stoploss` configuration parameter is loss in percentage that should trigger a sale.
|
The `stoploss` configuration parameter is loss in percentage that should trigger a sale.
|
||||||
For example, value `-0.10` will cause immediate sell if the profit dips below -10% for a given trade. This parameter is optional.
|
For example, value `-0.10` will cause immediate sell if the profit dips below -10% for a given trade. This parameter is optional.
|
||||||
|
|
||||||
Most of the strategy files already include the optimal `stoploss`
|
Most of the strategy files already include the optimal `stoploss` value.
|
||||||
value. This parameter is optional. If you use it in the configuration file, it will take over the
|
|
||||||
`stoploss` value from the strategy file.
|
|
||||||
|
|
||||||
## Stop Loss support
|
!!! Info
|
||||||
|
All stoploss properties mentioned in this file can be set in the Strategy, or in the configuration. Configuration values will override the strategy values.
|
||||||
|
|
||||||
|
## Stop Loss Types
|
||||||
|
|
||||||
At this stage the bot contains the following stoploss support modes:
|
At this stage the bot contains the following stoploss support modes:
|
||||||
|
|
||||||
1. static stop loss, defined in either the strategy or configuration.
|
1. Static stop loss.
|
||||||
2. trailing stop loss, defined in the configuration.
|
2. Trailing stop loss.
|
||||||
3. trailing stop loss, custom positive loss, defined in configuration.
|
3. Trailing stop loss, custom positive loss.
|
||||||
|
4. Trailing stop loss only once the trade has reached a certain offset.
|
||||||
|
|
||||||
!!! Note
|
Those stoploss modes can be *on exchange* or *off exchange*. If the stoploss is *on exchange* it means a stoploss limit order is placed on the exchange immediately after buy order happens successfully. This will protect you against sudden crashes in market as the order will be in the queue immediately and if market goes down then the order has more chance of being fulfilled.
|
||||||
All stoploss properties can be configured in either Strategy or configuration. Configuration values override strategy values.
|
|
||||||
|
|
||||||
Those stoploss modes can be *on exchange* or *off exchange*. If the stoploss is *on exchange* it means a stoploss limit order is placed on the exchange immediately after buy order happens successfuly. This will protect you against sudden crashes in market as the order will be in the queue immediately and if market goes down then the order has more chance of being fulfilled.
|
In case of stoploss on exchange there is another parameter called `stoploss_on_exchange_interval`. This configures the interval in seconds at which the bot will check the stoploss and update it if necessary.
|
||||||
|
|
||||||
In case of stoploss on exchange there is another parameter called `stoploss_on_exchange_interval`. This configures the interval in seconds at which the bot will check the stoploss and update it if necessary. As an example in case of trailing stoploss if the order is on the exchange and the market is going up then the bot automatically cancels the previous stoploss order and put a new one with a stop value higher than previous one. It is clear that the bot cannot do it every 5 seconds otherwise it gets banned. So this parameter will tell the bot how often it should update the stoploss order. The default value is 60 (1 minute).
|
For example, assuming the stoploss is on exchange, and trailing stoploss is enabled, and the market is going up, then the bot automatically cancels the previous stoploss order and puts a new one with a stop value higher than the previous stoploss order.
|
||||||
|
The bot cannot do this every 5 seconds (at each iteration), otherwise it would get banned by the exchange.
|
||||||
|
So this parameter will tell the bot how often it should update the stoploss order. The default value is 60 (1 minute).
|
||||||
|
This same logic will reapply a stoploss order on the exchange should you cancel it accidentally.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Stoploss on exchange is only supported for Binance as of now.
|
Stoploss on exchange is only supported for Binance as of now.
|
||||||
|
|
||||||
## Static Stop Loss
|
## Static Stop Loss
|
||||||
|
|
||||||
This is very simple, basically you define a stop loss of x in your strategy file or alternative in the configuration, which
|
This is very simple, you define a stop loss of x (as a ratio of price, i.e. x * 100% of price). This will try to sell the asset once the loss exceeds the defined loss.
|
||||||
will overwrite the strategy definition. This will basically try to sell your asset, the second the loss exceeds the defined loss.
|
|
||||||
|
|
||||||
## Trailing Stop Loss
|
## Trailing Stop Loss
|
||||||
|
|
||||||
The initial value for this stop loss, is defined in your strategy or configuration. Just as you would define your Stop Loss normally.
|
The initial value for this is `stoploss`, just as you would define your static Stop loss.
|
||||||
To enable this Feauture all you have to do is to define the configuration element:
|
To enable trailing stoploss:
|
||||||
|
|
||||||
``` json
|
``` python
|
||||||
"trailing_stop" : True
|
trailing_stop = True
|
||||||
```
|
```
|
||||||
|
|
||||||
This will now activate an algorithm, which automatically moves your stop loss up every time the price of your asset increases.
|
This will now activate an algorithm, which automatically moves the stop loss up every time the price of your asset increases.
|
||||||
|
|
||||||
For example, simplified math,
|
For example, simplified math:
|
||||||
|
|
||||||
* you buy an asset at a price of 100$
|
* the bot buys an asset at a price of 100$
|
||||||
* your stop loss is defined at 2%
|
* the stop loss is defined at 2%
|
||||||
* which means your stop loss, gets triggered once your asset dropped below 98$
|
* the stop loss would get triggered once the asset dropps below 98$
|
||||||
* assuming your asset now increases to 102$
|
* assuming the asset now increases to 102$
|
||||||
* your stop loss, will now be 2% of 102$ or 99.96$
|
* the stop loss will now be 2% of 102$ or 99.96$
|
||||||
* now your asset drops in value to 101$, your stop loss, will still be 99.96$
|
* now the asset drops in value to 101$, the stop loss will still be 99.96$ and would trigger at 99.96$.
|
||||||
|
|
||||||
basically what this means is that your stop loss will be adjusted to be always be 2% of the highest observed price
|
In summary: The stoploss will be adjusted to be always be 2% of the highest observed price.
|
||||||
|
|
||||||
### Custom positive loss
|
### Custom positive stoploss
|
||||||
|
|
||||||
Due to demand, it is possible to have a default stop loss, when you are in the red with your buy, but once your profit surpasses a certain percentage,
|
It is also possible to have a default stop loss, when you are in the red with your buy, but once your profit surpasses a certain percentage, the system will utilize a new stop loss, which can have a different value.
|
||||||
the system will utilize a new stop loss, which can be a different value. For example your default stop loss is 5%, but once you have 1.1% profit,
|
For example your default stop loss is 5%, but once you have 1.1% profit, it will be changed to be only a 1% stop loss, which trails the green candles until it goes below them.
|
||||||
it will be changed to be only a 1% stop loss, which trails the green candles until it goes below them.
|
|
||||||
|
|
||||||
Both values can be configured in the main configuration file and requires `"trailing_stop": true` to be set to true.
|
Both values require `trailing_stop` to be set to true.
|
||||||
|
|
||||||
``` json
|
``` python
|
||||||
"trailing_stop_positive": 0.01,
|
trailing_stop_positive = 0.01
|
||||||
"trailing_stop_positive_offset": 0.011,
|
trailing_stop_positive_offset = 0.011
|
||||||
"trailing_only_offset_is_reached": false
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The 0.01 would translate to a 1% stop loss, once you hit 1.1% profit.
|
The 0.01 would translate to a 1% stop loss, once you hit 1.1% profit.
|
||||||
|
Before this, `stoploss` is used for the trailing stoploss.
|
||||||
|
|
||||||
You should also make sure to have this value (`trailing_stop_positive_offset`) lower than your minimal ROI, otherwise minimal ROI will apply first and sell your trade.
|
Read the [next section](#trailing-only-once-offset-is-reached) to keep stoploss at 5% of the entry point.
|
||||||
|
|
||||||
If `"trailing_only_offset_is_reached": true` then the trailing stoploss is only activated once the offset is reached. Until then, the stoploss remains at the configured`stoploss`.
|
!!! Tip
|
||||||
|
Make sure to have this value (`trailing_stop_positive_offset`) lower than minimal ROI, otherwise minimal ROI will apply first and sell the trade.
|
||||||
|
|
||||||
|
### Trailing only once offset is reached
|
||||||
|
|
||||||
|
It is also possible to use a static stoploss until the offset is reached, and then trail the trade to take profits once the market turns.
|
||||||
|
|
||||||
|
If `"trailing_only_offset_is_reached": true` then the trailing stoploss is only activated once the offset is reached. Until then, the stoploss remains at the configured `stoploss`.
|
||||||
|
This option can be used with or without `trailing_stop_positive`, but uses `trailing_stop_positive_offset` as offset.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
trailing_stop_positive_offset = 0.011
|
||||||
|
trailing_only_offset_is_reached = true
|
||||||
|
```
|
||||||
|
|
||||||
|
Simplified example:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
stoploss = 0.05
|
||||||
|
trailing_stop_positive_offset = 0.03
|
||||||
|
trailing_only_offset_is_reached = True
|
||||||
|
```
|
||||||
|
|
||||||
|
* the bot buys an asset at a price of 100$
|
||||||
|
* the stop loss is defined at 5%
|
||||||
|
* the stop loss will remain at 95% until profit reaches +3%
|
||||||
|
|
||||||
## Changing stoploss on open trades
|
## Changing stoploss on open trades
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Optimization
|
# Strategy Customization
|
||||||
|
|
||||||
This page explains where to customize your strategies, and add new
|
This page explains where to customize your strategies, and add new
|
||||||
indicators.
|
indicators.
|
||||||
@@ -7,24 +7,28 @@ indicators.
|
|||||||
|
|
||||||
This is very simple. Copy paste your strategy file into the directory `user_data/strategies`.
|
This is very simple. Copy paste your strategy file into the directory `user_data/strategies`.
|
||||||
|
|
||||||
Let assume you have a class called `AwesomeStrategy` in the file `awesome-strategy.py`:
|
Let assume you have a class called `AwesomeStrategy` in the file `AwesomeStrategy.py`:
|
||||||
|
|
||||||
1. Move your file into `user_data/strategies` (you should have `user_data/strategies/awesome-strategy.py`
|
1. Move your file into `user_data/strategies` (you should have `user_data/strategies/AwesomeStrategy.py`
|
||||||
2. Start the bot with the param `--strategy AwesomeStrategy` (the parameter is the class name)
|
2. Start the bot with the param `--strategy AwesomeStrategy` (the parameter is the class name)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade --strategy AwesomeStrategy
|
freqtrade trade --strategy AwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
## Change your strategy
|
## Develop your own strategy
|
||||||
|
|
||||||
The bot includes a default strategy file. However, we recommend you to
|
The bot includes a default strategy file.
|
||||||
use your own file to not have to lose your parameters every time the default
|
Also, several other strategies are available in the [strategy repository](https://github.com/freqtrade/freqtrade-strategies).
|
||||||
strategy file will be updated on Github. Put your custom strategy file
|
|
||||||
into the directory `user_data/strategies`.
|
|
||||||
|
|
||||||
Best copy the test-strategy and modify this copy to avoid having bot-updates override your changes.
|
You will however most likely have your own idea for a strategy.
|
||||||
`cp user_data/strategies/sample_strategy.py user_data/strategies/awesome-strategy.py`
|
This document intends to help you develop one for yourself.
|
||||||
|
|
||||||
|
To get started, use `freqtrade new-strategy --strategy AwesomeStrategy`.
|
||||||
|
This will create a new strategy file from a template, which will be located under `user_data/strategies/AwesomeStrategy.py`.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
This is just a template file, which will most likely not be profitable out of the box.
|
||||||
|
|
||||||
### Anatomy of a strategy
|
### Anatomy of a strategy
|
||||||
|
|
||||||
@@ -45,23 +49,22 @@ The current version is 2 - which is also the default when it's not set explicitl
|
|||||||
Future versions will require this to be set.
|
Future versions will require this to be set.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade --strategy AwesomeStrategy
|
freqtrade trade --strategy AwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
**For the following section we will use the [user_data/strategies/sample_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/strategies/sample_strategy.py)
|
**For the following section we will use the [user_data/strategies/sample_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_strategy.py)
|
||||||
file as reference.**
|
file as reference.**
|
||||||
|
|
||||||
!!! Note Strategies and Backtesting
|
!!! Note "Strategies and Backtesting"
|
||||||
To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware
|
To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware
|
||||||
that during backtesting the full time-interval is passed to the `populate_*()` methods at once.
|
that during backtesting the full time-interval is passed to the `populate_*()` methods at once.
|
||||||
It is therefore best to use vectorized operations (across the whole dataframe, not loops) and
|
It is therefore best to use vectorized operations (across the whole dataframe, not loops) and
|
||||||
avoid index referencing (`df.iloc[-1]`), but instead use `df.shift()` to get to the previous candle.
|
avoid index referencing (`df.iloc[-1]`), but instead use `df.shift()` to get to the previous candle.
|
||||||
|
|
||||||
!!! Warning Using future data
|
!!! Warning "Warning: Using future data"
|
||||||
Since backtesting passes the full time interval to the `populate_*()` methods, the strategy author
|
Since backtesting passes the full time interval to the `populate_*()` methods, the strategy author
|
||||||
needs to take care to avoid having the strategy utilize data from the future.
|
needs to take care to avoid having the strategy utilize data from the future.
|
||||||
Samples for usage of future data are `dataframe.shift(-1)`, `dataframe.resample("1h")` (this uses the left border of the interval, so moves data from an hour to the start of the hour).
|
Some common patterns for this are listed in the [Common Mistakes](#common-mistakes-when-developing-strategies) section of this document.
|
||||||
They all use data which is not available during regular operations, so these strategies will perform well during backtesting, but will fail / perform badly in dry-runs.
|
|
||||||
|
|
||||||
### Customize Indicators
|
### Customize Indicators
|
||||||
|
|
||||||
@@ -115,9 +118,40 @@ def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame
|
|||||||
```
|
```
|
||||||
|
|
||||||
!!! Note "Want more indicator examples?"
|
!!! Note "Want more indicator examples?"
|
||||||
Look into the [user_data/strategies/sample_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/strategies/sample_strategy.py).
|
Look into the [user_data/strategies/sample_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_strategy.py).
|
||||||
Then uncomment indicators you need.
|
Then uncomment indicators you need.
|
||||||
|
|
||||||
|
### Strategy startup period
|
||||||
|
|
||||||
|
Most indicators have an instable startup period, in which they are either not available, or the calculation is incorrect. This can lead to inconsistencies, since Freqtrade does not know how long this instable period should be.
|
||||||
|
To account for this, the strategy can be assigned the `startup_candle_count` attribute.
|
||||||
|
This should be set to the maximum number of candles that the strategy requires to calculate stable indicators.
|
||||||
|
|
||||||
|
In this example strategy, this should be set to 100 (`startup_candle_count = 100`), since the longest needed history is 100 candles.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)
|
||||||
|
```
|
||||||
|
|
||||||
|
By letting the bot know how much history is needed, backtest trades can start at the specified timerange during backtesting and hyperopt.
|
||||||
|
|
||||||
|
!!! Warning
|
||||||
|
`startup_candle_count` should be below `ohlcv_candle_limit` (which is 500 for most exchanges) - since only this amount of candles will be available during Dry-Run/Live Trade operations.
|
||||||
|
|
||||||
|
#### Example
|
||||||
|
|
||||||
|
Let's try to backtest 1 month (January 2019) of 5m candles using the an example strategy with EMA100, as above.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade backtesting --timerange 20190101-20190201 --ticker-interval 5m
|
||||||
|
```
|
||||||
|
|
||||||
|
Assuming `startup_candle_count` is set to 100, backtesting knows it needs 100 candles to generate valid buy signals. It will load data from `20190101 - (100 * 5m)` - which is ~2019-12-31 15:30:00.
|
||||||
|
If this data is available, indicators will be calculated with this extended timerange. The instable startup period (up to 2019-01-01 00:00:00) will then be removed before starting backtesting.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
If data for the startup period is not available, then the timerange will be adjusted to account for this startup period - so Backtesting would start at 2019-01-01 08:30:00.
|
||||||
|
|
||||||
### Buy signal rules
|
### Buy signal rules
|
||||||
|
|
||||||
Edit the method `populate_buy_trend()` in your strategy file to update your buy strategy.
|
Edit the method `populate_buy_trend()` in your strategy file to update your buy strategy.
|
||||||
@@ -138,15 +172,19 @@ def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|||||||
"""
|
"""
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(
|
(
|
||||||
(dataframe['adx'] > 30) &
|
(qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30
|
||||||
(dataframe['tema'] <= dataframe['bb_middleband']) &
|
(dataframe['tema'] <= dataframe['bb_middleband']) & # Guard
|
||||||
(dataframe['tema'] > dataframe['tema'].shift(1))
|
(dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
),
|
),
|
||||||
'buy'] = 1
|
'buy'] = 1
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
```
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Buying requires sellers to buy from - therefore volume needs to be > 0 (`dataframe['volume'] > 0`) to make sure that the bot does not buy/sell in no-activity periods.
|
||||||
|
|
||||||
### Sell signal rules
|
### Sell signal rules
|
||||||
|
|
||||||
Edit the method `populate_sell_trend()` into your strategy file to update your sell strategy.
|
Edit the method `populate_sell_trend()` into your strategy file to update your sell strategy.
|
||||||
@@ -168,9 +206,10 @@ def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame
|
|||||||
"""
|
"""
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(
|
(
|
||||||
(dataframe['adx'] > 70) &
|
(qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70
|
||||||
(dataframe['tema'] > dataframe['bb_middleband']) &
|
(dataframe['tema'] > dataframe['bb_middleband']) & # Guard
|
||||||
(dataframe['tema'] < dataframe['tema'].shift(1))
|
(dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
),
|
),
|
||||||
'sell'] = 1
|
'sell'] = 1
|
||||||
return dataframe
|
return dataframe
|
||||||
@@ -246,9 +285,9 @@ Instead, have a look at the section [Storing information](#Storing-information)
|
|||||||
|
|
||||||
### Storing information
|
### Storing information
|
||||||
|
|
||||||
Storing information can be accomplished by crating a new dictionary within the strategy class.
|
Storing information can be accomplished by creating a new dictionary within the strategy class.
|
||||||
|
|
||||||
The name of the variable can be choosen at will, but should be prefixed with `cust_` to avoid naming collisions with predefined strategy variables.
|
The name of the variable can be chosen at will, but should be prefixed with `cust_` to avoid naming collisions with predefined strategy variables.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
class Awesomestrategy(IStrategy):
|
class Awesomestrategy(IStrategy):
|
||||||
@@ -263,10 +302,10 @@ class Awesomestrategy(IStrategy):
|
|||||||
```
|
```
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash.
|
The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.
|
If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.
|
||||||
|
|
||||||
### Additional data (DataProvider)
|
### Additional data (DataProvider)
|
||||||
|
|
||||||
@@ -279,9 +318,11 @@ Please always check the mode of operation to select the correct method to get da
|
|||||||
#### Possible options for DataProvider
|
#### Possible options for DataProvider
|
||||||
|
|
||||||
- `available_pairs` - Property with tuples listing cached pairs with their intervals (pair, interval).
|
- `available_pairs` - Property with tuples listing cached pairs with their intervals (pair, interval).
|
||||||
- `ohlcv(pair, ticker_interval)` - Currently cached ticker data for the pair, returns DataFrame or empty DataFrame.
|
- `ohlcv(pair, timeframe)` - Currently cached ticker data for the pair, returns DataFrame or empty DataFrame.
|
||||||
- `historic_ohlcv(pair, ticker_interval)` - Returns historical data stored on disk.
|
- `historic_ohlcv(pair, timeframe)` - Returns historical data stored on disk.
|
||||||
- `get_pair_dataframe(pair, ticker_interval)` - This is a universal method, which returns either historical data (for backtesting) or cached live data (for the Dry-Run and Live-Run modes).
|
- `get_pair_dataframe(pair, timeframe)` - This is a universal method, which returns either historical data (for backtesting) or cached live data (for the Dry-Run and Live-Run modes).
|
||||||
|
- `orderbook(pair, maximum)` - Returns latest orderbook data for the pair, a dict with bids/asks with a total of `maximum` entries.
|
||||||
|
- `market(pair)` - Returns market data for the pair: fees, limits, precisions, activity flag, etc. See [ccxt documentation](https://github.com/ccxt/ccxt/wiki/Manual#markets) for more details on Market data structure.
|
||||||
- `runmode` - Property containing the current runmode.
|
- `runmode` - Property containing the current runmode.
|
||||||
|
|
||||||
#### Example: fetch live ohlcv / historic data for the first informative pair
|
#### Example: fetch live ohlcv / historic data for the first informative pair
|
||||||
@@ -290,15 +331,15 @@ Please always check the mode of operation to select the correct method to get da
|
|||||||
if self.dp:
|
if self.dp:
|
||||||
inf_pair, inf_timeframe = self.informative_pairs()[0]
|
inf_pair, inf_timeframe = self.informative_pairs()[0]
|
||||||
informative = self.dp.get_pair_dataframe(pair=inf_pair,
|
informative = self.dp.get_pair_dataframe(pair=inf_pair,
|
||||||
ticker_interval=inf_timeframe)
|
timeframe=inf_timeframe)
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Warning Warning about backtesting
|
!!! Warning "Warning about backtesting"
|
||||||
Be carefull when using dataprovider in backtesting. `historic_ohlcv()` (and `get_pair_dataframe()`
|
Be carefull when using dataprovider in backtesting. `historic_ohlcv()` (and `get_pair_dataframe()`
|
||||||
for the backtesting runmode) provides the full time-range in one go,
|
for the backtesting runmode) provides the full time-range in one go,
|
||||||
so please be aware of it and make sure to not "look into the future" to avoid surprises when running in dry/live mode).
|
so please be aware of it and make sure to not "look into the future" to avoid surprises when running in dry/live mode).
|
||||||
|
|
||||||
!!! Warning Warning in hyperopt
|
!!! Warning "Warning in hyperopt"
|
||||||
This option cannot currently be used during hyperopt.
|
This option cannot currently be used during hyperopt.
|
||||||
|
|
||||||
#### Orderbook
|
#### Orderbook
|
||||||
@@ -344,9 +385,9 @@ def informative_pairs(self):
|
|||||||
As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short.
|
As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short.
|
||||||
All intervals and all pairs can be specified as long as they are available (and active) on the used exchange.
|
All intervals and all pairs can be specified as long as they are available (and active) on the used exchange.
|
||||||
It is however better to use resampling to longer time-intervals when possible
|
It is however better to use resampling to longer time-intervals when possible
|
||||||
to avoid hammering the exchange with too many requests and risk beeing blocked.
|
to avoid hammering the exchange with too many requests and risk being blocked.
|
||||||
|
|
||||||
### Additional data - Wallets
|
### Additional data (Wallets)
|
||||||
|
|
||||||
The strategy provides access to the `Wallets` object. This contains the current balances on the exchange.
|
The strategy provides access to the `Wallets` object. This contains the current balances on the exchange.
|
||||||
|
|
||||||
@@ -368,6 +409,97 @@ if self.wallets:
|
|||||||
- `get_used(asset)` - currently tied up balance (open orders)
|
- `get_used(asset)` - currently tied up balance (open orders)
|
||||||
- `get_total(asset)` - total available balance - sum of the 2 above
|
- `get_total(asset)` - total available balance - sum of the 2 above
|
||||||
|
|
||||||
|
### Additional data (Trades)
|
||||||
|
|
||||||
|
A history of Trades can be retrieved in the strategy by querying the database.
|
||||||
|
|
||||||
|
At the top of the file, import Trade.
|
||||||
|
|
||||||
|
```python
|
||||||
|
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'):
|
||||||
|
trades = Trade.get_trades([Trade.pair == metadata['pair'],
|
||||||
|
Trade.open_date > datetime.utcnow() - timedelta(days=1),
|
||||||
|
Trade.is_open == False,
|
||||||
|
]).order_by(Trade.close_date).all()
|
||||||
|
# Summarize profit for this pair.
|
||||||
|
curdayprofit = sum(trade.close_profit for trade in trades)
|
||||||
|
```
|
||||||
|
|
||||||
|
Get amount of stake_currency currently invested in Trades:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
if self.config['runmode'] in ('live', 'dry_run'):
|
||||||
|
total_stakes = Trade.total_open_trades_stakes()
|
||||||
|
```
|
||||||
|
|
||||||
|
Retrieve performance per pair.
|
||||||
|
Returns a List of dicts per pair.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
if self.config['runmode'] in ('live', 'dry_run'):
|
||||||
|
performance = Trade.get_overall_performance()
|
||||||
|
```
|
||||||
|
|
||||||
|
Sample return value: ETH/BTC had 5 trades, with a total profit of 1.5% (ratio of 0.015).
|
||||||
|
|
||||||
|
``` json
|
||||||
|
{'pair': "ETH/BTC", 'profit': 0.015, 'count': 5}
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! 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'] 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
|
### Print created dataframe
|
||||||
|
|
||||||
To inspect the created dataframe, you can issue a print-statement in either `populate_buy_trend()` or `populate_sell_trend()`.
|
To inspect the created dataframe, you can issue a print-statement in either `populate_buy_trend()` or `populate_sell_trend()`.
|
||||||
@@ -392,19 +524,26 @@ def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|||||||
|
|
||||||
Printing more than a few rows is also possible (simply use `print(dataframe)` instead of `print(dataframe.tail())`), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds).
|
Printing more than a few rows is also possible (simply use `print(dataframe)` instead of `print(dataframe.tail())`), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds).
|
||||||
|
|
||||||
### Where is the default strategy?
|
|
||||||
|
|
||||||
The default buy strategy is located in the file
|
|
||||||
[freqtrade/default_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/strategy/default_strategy.py).
|
|
||||||
|
|
||||||
### Specify custom strategy location
|
### Specify custom strategy location
|
||||||
|
|
||||||
If you want to use a strategy from a different directory you can pass `--strategy-path`
|
If you want to use a strategy from a different directory you can pass `--strategy-path`
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade --strategy AwesomeStrategy --strategy-path /some/directory
|
freqtrade trade --strategy AwesomeStrategy --strategy-path /some/directory
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
This is a common pain-point, which can cause huge differences between backtesting and dry/live run methods, since they all use data which is not available during dry/live runs, so these strategies will perform well during backtesting, but will fail / perform badly in real conditions.
|
||||||
|
|
||||||
|
The following lists some common patterns which should be avoided to prevent frustration:
|
||||||
|
|
||||||
|
- don't use `shift(-1)`. This uses data from the future, which is not available.
|
||||||
|
- don't use `.iloc[-1]` or any other absolute position in the dataframe, this will be different between dry-run and backtesting.
|
||||||
|
- don't use `dataframe['volume'].mean()`. This uses the full DataFrame for backtesting, including data from the future. Use `dataframe['volume'].rolling(<window>).mean()` instead
|
||||||
|
- don't use `.resample('1h')`. This uses the left border of the interval, so moves data from an hour to the start of the hour. Use `.resample('1h', label='right')` instead.
|
||||||
|
|
||||||
### Further strategy ideas
|
### Further strategy ideas
|
||||||
|
|
||||||
To get additional Ideas for strategies, head over to our [strategy repository](https://github.com/freqtrade/freqtrade-strategies). Feel free to use them as they are - but results will depend on the current market situation, pairs used etc. - therefore please backtest the strategy for your exchange/desired pairs first, evaluate carefully, use at your own risk.
|
To get additional Ideas for strategies, head over to our [strategy repository](https://github.com/freqtrade/freqtrade-strategies). Feel free to use them as they are - but results will depend on the current market situation, pairs used etc. - therefore please backtest the strategy for your exchange/desired pairs first, evaluate carefully, use at your own risk.
|
||||||
|
|||||||
158
docs/strategy_analysis_example.md
Normal file
158
docs/strategy_analysis_example.md
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
# Strategy analysis example
|
||||||
|
|
||||||
|
Debugging a strategy can be time-consuming. FreqTrade offers helper functions to visualize raw data.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from pathlib import Path
|
||||||
|
# Customize these according to your needs.
|
||||||
|
|
||||||
|
# Define some constants
|
||||||
|
timeframe = "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'
|
||||||
|
# Location of the data
|
||||||
|
data_location = Path(user_data_dir, 'data', 'binance')
|
||||||
|
# Pair to analyze - Only use one pair here
|
||||||
|
pair = "BTC_USDT"
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Load data using values set above
|
||||||
|
from freqtrade.data.history import load_pair_history
|
||||||
|
|
||||||
|
candles = load_pair_history(datadir=data_location,
|
||||||
|
timeframe=timeframe,
|
||||||
|
pair=pair)
|
||||||
|
|
||||||
|
# Confirm success
|
||||||
|
print("Loaded " + str(len(candles)) + f" rows of data for {pair} from {data_location}")
|
||||||
|
candles.head()
|
||||||
|
```
|
||||||
|
|
||||||
|
## Load and run strategy
|
||||||
|
* Rerun each time the strategy file is changed
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Load strategy using values set above
|
||||||
|
from freqtrade.resolvers import StrategyResolver
|
||||||
|
strategy = StrategyResolver.load_strategy({'strategy': strategy_name,
|
||||||
|
'user_data_dir': user_data_dir,
|
||||||
|
'strategy_path': strategy_location})
|
||||||
|
|
||||||
|
# Generate buy/sell signals using strategy
|
||||||
|
df = strategy.analyze_ticker(candles, {'pair': pair})
|
||||||
|
df.tail()
|
||||||
|
```
|
||||||
|
|
||||||
|
### Display the trade details
|
||||||
|
|
||||||
|
* Note that using `data.head()` would also work, however most indicators have some "startup" data at the top of the dataframe.
|
||||||
|
* Some possible problems
|
||||||
|
* Columns with NaN values at the end of the dataframe
|
||||||
|
* Columns used in `crossed*()` functions with completely different units
|
||||||
|
* Comparison with full backtest
|
||||||
|
* having 200 buy signals as output for one pair from `analyze_ticker()` does not necessarily mean that 200 trades will be made during backtesting.
|
||||||
|
* Assuming you use only one condition such as, `df['rsi'] < 30` as buy condition, this will generate multiple "buy" signals for each pair in sequence (until rsi returns > 29). The bot will only buy on the first of these signals (and also only if a trade-slot ("max_open_trades") is still available), or on one of the middle signals, as soon as a "slot" becomes available.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Report results
|
||||||
|
print(f"Generated {df['buy'].sum()} buy signals")
|
||||||
|
data = df.set_index('date', drop=False)
|
||||||
|
data.tail()
|
||||||
|
```
|
||||||
|
|
||||||
|
## Load existing objects into a Jupyter notebook
|
||||||
|
|
||||||
|
The following cells assume that you have already generated data using the cli.
|
||||||
|
They will allow you to drill deeper into your results, and perform analysis which otherwise would make the output very difficult to digest due to information overload.
|
||||||
|
|
||||||
|
### Load backtest results to pandas dataframe
|
||||||
|
|
||||||
|
Analyze a trades dataframe (also used below for plotting)
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from freqtrade.data.btanalysis import load_backtest_data
|
||||||
|
|
||||||
|
# Load backtest results
|
||||||
|
trades = load_backtest_data(user_data_dir / "backtest_results/backtest-result.json")
|
||||||
|
|
||||||
|
# Show value-counts per pair
|
||||||
|
trades.groupby("pair")["sell_reason"].value_counts()
|
||||||
|
```
|
||||||
|
|
||||||
|
### Load live trading results into a pandas dataframe
|
||||||
|
|
||||||
|
In case you did already some trading and want to analyze your performance
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from freqtrade.data.btanalysis import load_trades_from_db
|
||||||
|
|
||||||
|
# Fetch trades from database
|
||||||
|
trades = load_trades_from_db("sqlite:///tradesv3.sqlite")
|
||||||
|
|
||||||
|
# Display results
|
||||||
|
trades.groupby("pair")["sell_reason"].value_counts()
|
||||||
|
```
|
||||||
|
|
||||||
|
## Analyze the loaded trades for trade parallelism
|
||||||
|
This can be useful to find the best `max_open_trades` parameter, when used with backtesting in conjunction with `--disable-max-market-positions`.
|
||||||
|
|
||||||
|
`analyze_trade_parallelism()` returns a timeseries dataframe with an "open_trades" column, specifying the number of open trades for each candle.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from freqtrade.data.btanalysis import analyze_trade_parallelism
|
||||||
|
|
||||||
|
# Analyze the above
|
||||||
|
parallel_trades = analyze_trade_parallelism(trades, '5m')
|
||||||
|
|
||||||
|
|
||||||
|
parallel_trades.plot()
|
||||||
|
```
|
||||||
|
|
||||||
|
## Plot results
|
||||||
|
|
||||||
|
Freqtrade offers interactive plotting capabilities based on plotly.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from freqtrade.plot.plotting import generate_candlestick_graph
|
||||||
|
# Limit graph period to keep plotly quick and reactive
|
||||||
|
|
||||||
|
data_red = data['2019-06-01':'2019-06-10']
|
||||||
|
# Generate candlestick graph
|
||||||
|
graph = generate_candlestick_graph(pair=pair,
|
||||||
|
data=data_red,
|
||||||
|
trades=trades,
|
||||||
|
indicators1=['sma20', 'ema50', 'ema55'],
|
||||||
|
indicators2=['rsi', 'macd', 'macdsignal', 'macdhist']
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Show graph inline
|
||||||
|
# graph.show()
|
||||||
|
|
||||||
|
# Render graph in a seperate window
|
||||||
|
graph.show(renderer="browser")
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.
|
||||||
13
docs/stylesheets/ft.extra.css
Normal file
13
docs/stylesheets/ft.extra.css
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
.rst-versions {
|
||||||
|
font-size: .7rem;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rst-versions.rst-badge .rst-current-version {
|
||||||
|
font-size: .7rem;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rst-versions .rst-other-versions {
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
@@ -53,6 +53,7 @@ official commands. You can ask at any moment for help with `/help`.
|
|||||||
| `/stop` | | Stops the trader
|
| `/stop` | | Stops the trader
|
||||||
| `/stopbuy` | | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
| `/stopbuy` | | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
||||||
| `/reload_conf` | | Reloads the configuration file
|
| `/reload_conf` | | Reloads the configuration file
|
||||||
|
| `/show_config` | | Shows part of the current configuration with relevant settings to operation
|
||||||
| `/status` | | Lists all open trades
|
| `/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
|
||||||
| `/count` | | Displays number of trades used and available
|
| `/count` | | Displays number of trades used and available
|
||||||
@@ -93,7 +94,7 @@ Once all positions are sold, run `/stop` to completely stop the bot.
|
|||||||
|
|
||||||
`/reload_conf` resets "max_open_trades" to the value set in the configuration and resets this command.
|
`/reload_conf` resets "max_open_trades" to the value set in the configuration and resets this command.
|
||||||
|
|
||||||
!!! warning
|
!!! Warning
|
||||||
The stop-buy signal is ONLY active while the bot is running, and is not persisted anyway, so restarting the bot will cause this to reset.
|
The stop-buy signal is ONLY active while the bot is running, and is not persisted anyway, so restarting the bot will cause this to reset.
|
||||||
|
|
||||||
### /status
|
### /status
|
||||||
|
|||||||
370
docs/utils.md
Normal file
370
docs/utils.md
Normal file
@@ -0,0 +1,370 @@
|
|||||||
|
# Utility Subcommands
|
||||||
|
|
||||||
|
Besides the Live-Trade and Dry-Run run modes, the `backtesting`, `edge` and `hyperopt` optimization subcommands, and the `download-data` subcommand which prepares historical data, the bot contains a number of utility subcommands. They are described in this section.
|
||||||
|
|
||||||
|
## Create userdir
|
||||||
|
|
||||||
|
Creates the directory structure to hold your files for freqtrade.
|
||||||
|
Will also create strategy and hyperopt examples for you to get started.
|
||||||
|
Can be used multiple times - using `--reset` will reset the sample strategy and hyperopt files to their default state.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade create-userdir [-h] [--userdir PATH] [--reset]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
--reset Reset sample files to their original state.
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Warning
|
||||||
|
Using `--reset` may result in loss of data, since this will overwrite all sample files without asking again.
|
||||||
|
|
||||||
|
```
|
||||||
|
├── backtest_results
|
||||||
|
├── data
|
||||||
|
├── hyperopt_results
|
||||||
|
├── hyperopts
|
||||||
|
│ ├── sample_hyperopt_advanced.py
|
||||||
|
│ ├── sample_hyperopt_loss.py
|
||||||
|
│ └── sample_hyperopt.py
|
||||||
|
├── notebooks
|
||||||
|
│ └── strategy_analysis_example.ipynb
|
||||||
|
├── plot
|
||||||
|
└── strategies
|
||||||
|
└── sample_strategy.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## Create new strategy
|
||||||
|
|
||||||
|
Creates a new strategy from a template similar to SampleStrategy.
|
||||||
|
The file will be named inline with your class name, and will not overwrite existing files.
|
||||||
|
|
||||||
|
Results will be located in `user_data/strategies/<strategyclassname>.py`.
|
||||||
|
|
||||||
|
``` output
|
||||||
|
usage: freqtrade new-strategy [-h] [--userdir PATH] [-s NAME]
|
||||||
|
[--template {full,minimal}]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
-s NAME, --strategy NAME
|
||||||
|
Specify strategy class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--template {full,minimal}
|
||||||
|
Use a template which is either `minimal` or `full`
|
||||||
|
(containing multiple sample indicators). Default:
|
||||||
|
`full`.
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
### Sample usage of new-strategy
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade new-strategy --strategy AwesomeStrategy
|
||||||
|
```
|
||||||
|
|
||||||
|
With custom user directory
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade new-strategy --userdir ~/.freqtrade/ --strategy AwesomeStrategy
|
||||||
|
```
|
||||||
|
|
||||||
|
## Create new hyperopt
|
||||||
|
|
||||||
|
Creates a new hyperopt from a template similar to SampleHyperopt.
|
||||||
|
The file will be named inline with your class name, and will not overwrite existing files.
|
||||||
|
|
||||||
|
Results will be located in `user_data/hyperopts/<classname>.py`.
|
||||||
|
|
||||||
|
``` output
|
||||||
|
usage: freqtrade new-hyperopt [-h] [--userdir PATH] [--hyperopt NAME]
|
||||||
|
[--template {full,minimal}]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
--hyperopt NAME Specify hyperopt class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--template {full,minimal}
|
||||||
|
Use a template which is either `minimal` or `full`
|
||||||
|
(containing multiple sample indicators). Default:
|
||||||
|
`full`.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Sample usage of new-hyperopt
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade new-hyperopt --hyperopt AwesomeHyperopt
|
||||||
|
```
|
||||||
|
|
||||||
|
With custom user directory
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade new-hyperopt --userdir ~/.freqtrade/ --hyperopt AwesomeHyperopt
|
||||||
|
```
|
||||||
|
|
||||||
|
## List Strategies
|
||||||
|
|
||||||
|
Use the `list-strategies` subcommand to see all strategies in one particular directory.
|
||||||
|
|
||||||
|
```
|
||||||
|
freqtrade list-strategies --help
|
||||||
|
usage: freqtrade list-strategies [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--strategy-path PATH] [-1]
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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 this command 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 strategy directory within userdir
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade list-strategies --userdir ~/.freqtrade/
|
||||||
|
```
|
||||||
|
|
||||||
|
Example: search dedicated strategy path
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade list-strategies --strategy-path ~/.freqtrade/strategies/
|
||||||
|
```
|
||||||
|
|
||||||
|
## List Exchanges
|
||||||
|
|
||||||
|
Use the `list-exchanges` subcommand to see the exchanges available for the bot.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade list-exchanges [-h] [-1] [-a]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
-1, --one-column Print output in one column.
|
||||||
|
-a, --all Print all exchanges known to the ccxt library.
|
||||||
|
```
|
||||||
|
|
||||||
|
* Example: see exchanges available for the bot:
|
||||||
|
```
|
||||||
|
$ freqtrade list-exchanges
|
||||||
|
Exchanges available for Freqtrade: _1btcxe, acx, allcoin, bequant, bibox, binance, binanceje, binanceus, bitbank, bitfinex, bitfinex2, bitkk, bitlish, bitmart, bittrex, bitz, bleutrade, btcalpha, btcmarkets, btcturk, buda, cex, cobinhood, coinbaseprime, coinbasepro, coinex, cointiger, coss, crex24, digifinex, dsx, dx, ethfinex, fcoin, fcoinjp, gateio, gdax, gemini, hitbtc2, huobipro, huobiru, idex, kkex, kraken, kucoin, kucoin2, kuna, lbank, mandala, mercado, oceanex, okcoincny, okcoinusd, okex, okex3, poloniex, rightbtc, theocean, tidebit, upbit, zb
|
||||||
|
```
|
||||||
|
|
||||||
|
* Example: see all exchanges supported by the ccxt library (including 'bad' ones, i.e. those that are known to not work with Freqtrade):
|
||||||
|
```
|
||||||
|
$ freqtrade list-exchanges -a
|
||||||
|
All exchanges supported by the ccxt library: _1btcxe, acx, adara, allcoin, anxpro, bcex, bequant, bibox, bigone, binance, binanceje, binanceus, bit2c, bitbank, bitbay, bitfinex, bitfinex2, bitflyer, bitforex, bithumb, bitkk, bitlish, bitmart, bitmex, bitso, bitstamp, bitstamp1, bittrex, bitz, bl3p, bleutrade, braziliex, btcalpha, btcbox, btcchina, btcmarkets, btctradeim, btctradeua, btcturk, buda, bxinth, cex, chilebit, cobinhood, coinbase, coinbaseprime, coinbasepro, coincheck, coinegg, coinex, coinexchange, coinfalcon, coinfloor, coingi, coinmarketcap, coinmate, coinone, coinspot, cointiger, coolcoin, coss, crex24, crypton, deribit, digifinex, dsx, dx, ethfinex, exmo, exx, fcoin, fcoinjp, flowbtc, foxbit, fybse, gateio, gdax, gemini, hitbtc, hitbtc2, huobipro, huobiru, ice3x, idex, independentreserve, indodax, itbit, kkex, kraken, kucoin, kucoin2, kuna, lakebtc, latoken, lbank, liquid, livecoin, luno, lykke, mandala, mercado, mixcoins, negociecoins, nova, oceanex, okcoincny, okcoinusd, okex, okex3, paymium, poloniex, rightbtc, southxchange, stronghold, surbitcoin, theocean, therock, tidebit, tidex, upbit, vaultoro, vbtc, virwox, xbtce, yobit, zaif, zb
|
||||||
|
```
|
||||||
|
|
||||||
|
## List Timeframes
|
||||||
|
|
||||||
|
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]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||||
|
config is provided.
|
||||||
|
-1, --one-column Print output in one column.
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
* Example: see the timeframes for the 'binance' exchange, set in the configuration file:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ freqtrade -c config_binance.json list-timeframes
|
||||||
|
...
|
||||||
|
Timeframes available for the exchange `binance`: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M
|
||||||
|
```
|
||||||
|
|
||||||
|
* Example: enumerate exchanges available for Freqtrade and print timeframes supported by each of them:
|
||||||
|
```
|
||||||
|
$ for i in `freqtrade list-exchanges -1`; do freqtrade list-timeframes --exchange $i; done
|
||||||
|
```
|
||||||
|
|
||||||
|
## List pairs/list markets
|
||||||
|
|
||||||
|
The `list-pairs` and `list-markets` subcommands allow to see the pairs/markets available on exchange.
|
||||||
|
|
||||||
|
Pairs are markets with the '/' character between the base currency part and the quote currency part in the market symbol.
|
||||||
|
For example, in the 'ETH/BTC' pair 'ETH' is the base currency, while 'BTC' is the quote currency.
|
||||||
|
|
||||||
|
For pairs traded by Freqtrade the pair quote currency is defined by the value of the `stake_currency` configuration setting.
|
||||||
|
|
||||||
|
You can print info about any pair/market with these subcommands - and you can filter output by quote-currency using `--quote BTC`, or by base-currency using `--base ETH` options correspondingly.
|
||||||
|
|
||||||
|
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]
|
||||||
|
[--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]
|
||||||
|
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
||||||
|
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||||
|
config is provided.
|
||||||
|
--print-list Print list of pairs or market symbols. By default data
|
||||||
|
is printed in the tabular format.
|
||||||
|
--print-json Print list of pairs or market symbols in JSON format.
|
||||||
|
-1, --one-column Print output in one column.
|
||||||
|
--print-csv Print exchange pair or market data in the csv format.
|
||||||
|
--base BASE_CURRENCY [BASE_CURRENCY ...]
|
||||||
|
Specify base currency(-ies). Space-separated list.
|
||||||
|
--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]
|
||||||
|
Specify quote currency(-ies). Space-separated list.
|
||||||
|
-a, --all Print all pairs or market symbols. By default only
|
||||||
|
active ones are shown.
|
||||||
|
```
|
||||||
|
|
||||||
|
By default, only active pairs/markets are shown. Active pairs/markets are those that can currently be traded
|
||||||
|
on the exchange. The see the list of all pairs/markets (not only the active ones), use the `-a`/`-all` option.
|
||||||
|
|
||||||
|
Pairs/markets are sorted by its symbol string in the printed output.
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
* Print the list of active pairs with quote currency USD on exchange, specified in the default
|
||||||
|
configuration file (i.e. pairs on the "Bittrex" exchange) in JSON format:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ freqtrade list-pairs --quote USD --print-json
|
||||||
|
```
|
||||||
|
|
||||||
|
* Print the list of all pairs on the exchange, specified in the `config_binance.json` configuration file
|
||||||
|
(i.e. on the "Binance" exchange) with base currencies BTC or ETH and quote currencies USDT or USD, as the
|
||||||
|
human-readable list with summary:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ freqtrade -c config_binance.json list-pairs --all --base BTC ETH --quote USDT USD --print-list
|
||||||
|
```
|
||||||
|
|
||||||
|
* Print all markets on exchange "Kraken", in the tabular format:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ freqtrade list-markets --exchange kraken --all
|
||||||
|
```
|
||||||
|
|
||||||
|
## Test pairlist
|
||||||
|
|
||||||
|
Use the `test-pairlist` subcommand to test the configuration of [dynamic pairlists](configuration.md#pairlists).
|
||||||
|
|
||||||
|
Requires a configuration with specified `pairlists` attribute.
|
||||||
|
Can be used to generate static pairlists to be used during backtesting / hyperopt.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade test-pairlist [-h] [-c PATH]
|
||||||
|
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]
|
||||||
|
[-1] [--print-json]
|
||||||
|
|
||||||
|
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.
|
||||||
|
--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]
|
||||||
|
Specify quote currency(-ies). Space-separated list.
|
||||||
|
-1, --one-column Print output in one column.
|
||||||
|
--print-json Print list of pairs or market symbols in JSON format.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
Show whitelist when using a [dynamic pairlist](configuration.md#pairlists).
|
||||||
|
|
||||||
|
```
|
||||||
|
freqtrade test-pairlist --config config.json --quote USDT BTC
|
||||||
|
```
|
||||||
|
|
||||||
|
## List Hyperopt results
|
||||||
|
|
||||||
|
You can list the hyperoptimization epochs the Hyperopt module evaluated previously with the `hyperopt-list` subcommand.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade hyperopt-list [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
|
[-d PATH] [--userdir PATH] [--best]
|
||||||
|
[--profitable] [--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.
|
||||||
|
--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.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
List all results, print details of the best result at the end:
|
||||||
|
```
|
||||||
|
freqtrade hyperopt-list
|
||||||
|
```
|
||||||
|
|
||||||
|
List only epochs with positive profit. Do not print the details of the best epoch, so that the list can be iterated in a script:
|
||||||
|
```
|
||||||
|
freqtrade hyperopt-list --profitable --no-details
|
||||||
|
```
|
||||||
|
|
||||||
|
## Show details of Hyperopt results
|
||||||
|
|
||||||
|
You can show the details of any hyperoptimization epoch previously evaluated by the Hyperopt module with the `hyperopt-show` subcommand.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade hyperopt-show [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
|
[-d PATH] [--userdir PATH] [--best]
|
||||||
|
[--profitable] [-n INT] [--print-json]
|
||||||
|
[--no-header]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--best Select only best epochs.
|
||||||
|
--profitable Select only profitable epochs.
|
||||||
|
-n INT, --index INT Specify the index of the epoch to print details for.
|
||||||
|
--print-json Print best result detailization in JSON format.
|
||||||
|
--no-header Do not print epoch details header.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
Print details for the epoch 168 (the number of the epoch is shown by the `hyperopt-list` subcommand or by Hyperopt itself during hyperoptimization run):
|
||||||
|
|
||||||
|
```
|
||||||
|
freqtrade hyperopt-show -n 168
|
||||||
|
```
|
||||||
|
|
||||||
|
Prints JSON data with details for the last best epoch (i.e., the best of all epochs):
|
||||||
|
|
||||||
|
```
|
||||||
|
freqtrade hyperopt-show --best -n -1 --print-json --no-header
|
||||||
|
```
|
||||||
@@ -63,6 +63,8 @@ Possible parameters are:
|
|||||||
* `fiat_currency`
|
* `fiat_currency`
|
||||||
* `sell_reason`
|
* `sell_reason`
|
||||||
* `order_type`
|
* `order_type`
|
||||||
|
* `open_date`
|
||||||
|
* `close_date`
|
||||||
|
|
||||||
### Webhookstatus
|
### Webhookstatus
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ After=network.target
|
|||||||
# Set WorkingDirectory and ExecStart to your file paths accordingly
|
# Set WorkingDirectory and ExecStart to your file paths accordingly
|
||||||
# NOTE: %h will be resolved to /home/<username>
|
# NOTE: %h will be resolved to /home/<username>
|
||||||
WorkingDirectory=%h/freqtrade
|
WorkingDirectory=%h/freqtrade
|
||||||
ExecStart=/usr/bin/freqtrade
|
ExecStart=/usr/bin/freqtrade trade
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ After=network.target
|
|||||||
# Set WorkingDirectory and ExecStart to your file paths accordingly
|
# Set WorkingDirectory and ExecStart to your file paths accordingly
|
||||||
# NOTE: %h will be resolved to /home/<username>
|
# NOTE: %h will be resolved to /home/<username>
|
||||||
WorkingDirectory=%h/freqtrade
|
WorkingDirectory=%h/freqtrade
|
||||||
ExecStart=/usr/bin/freqtrade --sd-notify
|
ExecStart=/usr/bin/freqtrade trade --sd-notify
|
||||||
|
|
||||||
Restart=always
|
Restart=always
|
||||||
#Restart=on-failure
|
#Restart=on-failure
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
""" FreqTrade bot """
|
""" FreqTrade bot """
|
||||||
__version__ = '2019.9'
|
__version__ = '2020.01'
|
||||||
|
|
||||||
if __version__ == 'develop':
|
if __version__ == 'develop':
|
||||||
|
|
||||||
@@ -11,34 +11,3 @@ if __version__ == 'develop':
|
|||||||
except Exception:
|
except Exception:
|
||||||
# git not available, ignore
|
# git not available, ignore
|
||||||
pass
|
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.
|
|
||||||
"""
|
|
||||||
|
|||||||
25
freqtrade/commands/__init__.py
Normal file
25
freqtrade/commands/__init__.py
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
# 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.data_commands import 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_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
|
||||||
288
freqtrade/commands/arguments.py
Normal file
288
freqtrade/commands/arguments.py
Normal file
@@ -0,0 +1,288 @@
|
|||||||
|
"""
|
||||||
|
This module contains the argument manager class
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
from functools import partial
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from freqtrade import constants
|
||||||
|
from freqtrade.commands.cli_options import AVAILABLE_CLI_OPTIONS
|
||||||
|
|
||||||
|
ARGS_COMMON = ["verbosity", "logfile", "version", "config", "datadir", "user_data_dir"]
|
||||||
|
|
||||||
|
ARGS_STRATEGY = ["strategy", "strategy_path"]
|
||||||
|
|
||||||
|
ARGS_TRADE = ["db_url", "sd_notify", "dry_run"]
|
||||||
|
|
||||||
|
ARGS_COMMON_OPTIMIZE = ["ticker_interval", "timerange",
|
||||||
|
"max_open_trades", "stake_amount", "fee"]
|
||||||
|
|
||||||
|
ARGS_BACKTEST = ARGS_COMMON_OPTIMIZE + ["position_stacking", "use_max_market_positions",
|
||||||
|
"strategy_list", "export", "exportfilename"]
|
||||||
|
|
||||||
|
ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
|
||||||
|
"position_stacking", "epochs", "spaces",
|
||||||
|
"use_max_market_positions", "print_all",
|
||||||
|
"print_colorized", "print_json", "hyperopt_jobs",
|
||||||
|
"hyperopt_random_state", "hyperopt_min_trades",
|
||||||
|
"hyperopt_continue", "hyperopt_loss"]
|
||||||
|
|
||||||
|
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
|
||||||
|
|
||||||
|
ARGS_LIST_STRATEGIES = ["strategy_path", "print_one_column"]
|
||||||
|
|
||||||
|
ARGS_LIST_EXCHANGES = ["print_one_column", "list_exchanges_all"]
|
||||||
|
|
||||||
|
ARGS_LIST_TIMEFRAMES = ["exchange", "print_one_column"]
|
||||||
|
|
||||||
|
ARGS_LIST_PAIRS = ["exchange", "print_list", "list_pairs_print_json", "print_one_column",
|
||||||
|
"print_csv", "base_currencies", "quote_currencies", "list_pairs_all"]
|
||||||
|
|
||||||
|
ARGS_TEST_PAIRLIST = ["config", "quote_currencies", "print_one_column", "list_pairs_print_json"]
|
||||||
|
|
||||||
|
ARGS_CREATE_USERDIR = ["user_data_dir", "reset"]
|
||||||
|
|
||||||
|
ARGS_BUILD_STRATEGY = ["user_data_dir", "strategy", "template"]
|
||||||
|
|
||||||
|
ARGS_BUILD_HYPEROPT = ["user_data_dir", "hyperopt", "template"]
|
||||||
|
|
||||||
|
ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "download_trades", "exchange",
|
||||||
|
"timeframes", "erase"]
|
||||||
|
|
||||||
|
ARGS_PLOT_DATAFRAME = ["pairs", "indicators1", "indicators2", "plot_limit",
|
||||||
|
"db_url", "trade_source", "export", "exportfilename",
|
||||||
|
"timerange", "ticker_interval"]
|
||||||
|
|
||||||
|
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_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",
|
||||||
|
"list-strategies", "hyperopt-list", "hyperopt-show", "plot-dataframe",
|
||||||
|
"plot-profit"]
|
||||||
|
|
||||||
|
NO_CONF_ALLOWED = ["create-userdir", "list-exchanges", "new-hyperopt", "new-strategy"]
|
||||||
|
|
||||||
|
|
||||||
|
class Arguments:
|
||||||
|
"""
|
||||||
|
Arguments Class. Manage the arguments received by the cli
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, args: Optional[List[str]]) -> None:
|
||||||
|
self.args = args
|
||||||
|
self._parsed_arg: Optional[argparse.Namespace] = None
|
||||||
|
|
||||||
|
def get_parsed_arg(self) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Return the list of arguments
|
||||||
|
:return: List[str] List of arguments
|
||||||
|
"""
|
||||||
|
if self._parsed_arg is None:
|
||||||
|
self._build_subcommands()
|
||||||
|
self._parsed_arg = self._parse_args()
|
||||||
|
|
||||||
|
return vars(self._parsed_arg)
|
||||||
|
|
||||||
|
def _parse_args(self) -> argparse.Namespace:
|
||||||
|
"""
|
||||||
|
Parses given arguments and returns an argparse Namespace instance.
|
||||||
|
"""
|
||||||
|
parsed_arg = self.parser.parse_args(self.args)
|
||||||
|
|
||||||
|
# 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]
|
||||||
|
|
||||||
|
return parsed_arg
|
||||||
|
|
||||||
|
def _build_args(self, optionlist, parser):
|
||||||
|
|
||||||
|
for val in optionlist:
|
||||||
|
opt = AVAILABLE_CLI_OPTIONS[val]
|
||||||
|
parser.add_argument(*opt.cli, dest=val, **opt.kwargs)
|
||||||
|
|
||||||
|
def _build_subcommands(self) -> None:
|
||||||
|
"""
|
||||||
|
Builds and attaches all subcommands.
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
# Build shared arguments (as group Common Options)
|
||||||
|
_common_parser = argparse.ArgumentParser(add_help=False)
|
||||||
|
group = _common_parser.add_argument_group("Common arguments")
|
||||||
|
self._build_args(optionlist=ARGS_COMMON, parser=group)
|
||||||
|
|
||||||
|
_strategy_parser = argparse.ArgumentParser(add_help=False)
|
||||||
|
strategy_group = _strategy_parser.add_argument_group("Strategy arguments")
|
||||||
|
self._build_args(optionlist=ARGS_STRATEGY, parser=strategy_group)
|
||||||
|
|
||||||
|
# Build main command
|
||||||
|
self.parser = argparse.ArgumentParser(description='Free, open source crypto trading bot')
|
||||||
|
self._build_args(optionlist=['version'], parser=self.parser)
|
||||||
|
|
||||||
|
from freqtrade.commands import (start_create_userdir, start_download_data,
|
||||||
|
start_hyperopt_list, start_hyperopt_show,
|
||||||
|
start_list_exchanges, start_list_markets,
|
||||||
|
start_list_strategies, start_new_hyperopt,
|
||||||
|
start_new_strategy, start_list_timeframes,
|
||||||
|
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
|
||||||
|
# shown from `main.py`
|
||||||
|
# required=True
|
||||||
|
)
|
||||||
|
|
||||||
|
# Add trade subcommand
|
||||||
|
trade_cmd = subparsers.add_parser('trade', help='Trade module.',
|
||||||
|
parents=[_common_parser, _strategy_parser])
|
||||||
|
trade_cmd.set_defaults(func=start_trading)
|
||||||
|
self._build_args(optionlist=ARGS_TRADE, parser=trade_cmd)
|
||||||
|
|
||||||
|
# Add backtesting subcommand
|
||||||
|
backtesting_cmd = subparsers.add_parser('backtesting', help='Backtesting module.',
|
||||||
|
parents=[_common_parser, _strategy_parser])
|
||||||
|
backtesting_cmd.set_defaults(func=start_backtesting)
|
||||||
|
self._build_args(optionlist=ARGS_BACKTEST, parser=backtesting_cmd)
|
||||||
|
|
||||||
|
# Add edge subcommand
|
||||||
|
edge_cmd = subparsers.add_parser('edge', help='Edge module.',
|
||||||
|
parents=[_common_parser, _strategy_parser])
|
||||||
|
edge_cmd.set_defaults(func=start_edge)
|
||||||
|
self._build_args(optionlist=ARGS_EDGE, parser=edge_cmd)
|
||||||
|
|
||||||
|
# Add hyperopt subcommand
|
||||||
|
hyperopt_cmd = subparsers.add_parser('hyperopt', help='Hyperopt module.',
|
||||||
|
parents=[_common_parser, _strategy_parser],
|
||||||
|
)
|
||||||
|
hyperopt_cmd.set_defaults(func=start_hyperopt)
|
||||||
|
self._build_args(optionlist=ARGS_HYPEROPT, parser=hyperopt_cmd)
|
||||||
|
|
||||||
|
# add create-userdir subcommand
|
||||||
|
create_userdir_cmd = subparsers.add_parser('create-userdir',
|
||||||
|
help="Create user-data directory.",
|
||||||
|
)
|
||||||
|
create_userdir_cmd.set_defaults(func=start_create_userdir)
|
||||||
|
self._build_args(optionlist=ARGS_CREATE_USERDIR, parser=create_userdir_cmd)
|
||||||
|
|
||||||
|
# add new-strategy subcommand
|
||||||
|
build_strategy_cmd = subparsers.add_parser('new-strategy',
|
||||||
|
help="Create new strategy")
|
||||||
|
build_strategy_cmd.set_defaults(func=start_new_strategy)
|
||||||
|
self._build_args(optionlist=ARGS_BUILD_STRATEGY, parser=build_strategy_cmd)
|
||||||
|
|
||||||
|
# add new-hyperopt subcommand
|
||||||
|
build_hyperopt_cmd = subparsers.add_parser('new-hyperopt',
|
||||||
|
help="Create new hyperopt")
|
||||||
|
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-exchanges subcommand
|
||||||
|
list_exchanges_cmd = subparsers.add_parser(
|
||||||
|
'list-exchanges',
|
||||||
|
help='Print available exchanges.',
|
||||||
|
parents=[_common_parser],
|
||||||
|
)
|
||||||
|
list_exchanges_cmd.set_defaults(func=start_list_exchanges)
|
||||||
|
self._build_args(optionlist=ARGS_LIST_EXCHANGES, parser=list_exchanges_cmd)
|
||||||
|
|
||||||
|
# Add list-timeframes subcommand
|
||||||
|
list_timeframes_cmd = subparsers.add_parser(
|
||||||
|
'list-timeframes',
|
||||||
|
help='Print available ticker intervals (timeframes) for the exchange.',
|
||||||
|
parents=[_common_parser],
|
||||||
|
)
|
||||||
|
list_timeframes_cmd.set_defaults(func=start_list_timeframes)
|
||||||
|
self._build_args(optionlist=ARGS_LIST_TIMEFRAMES, parser=list_timeframes_cmd)
|
||||||
|
|
||||||
|
# Add list-markets subcommand
|
||||||
|
list_markets_cmd = subparsers.add_parser(
|
||||||
|
'list-markets',
|
||||||
|
help='Print markets on exchange.',
|
||||||
|
parents=[_common_parser],
|
||||||
|
)
|
||||||
|
list_markets_cmd.set_defaults(func=partial(start_list_markets, pairs_only=False))
|
||||||
|
self._build_args(optionlist=ARGS_LIST_PAIRS, parser=list_markets_cmd)
|
||||||
|
|
||||||
|
# Add list-pairs subcommand
|
||||||
|
list_pairs_cmd = subparsers.add_parser(
|
||||||
|
'list-pairs',
|
||||||
|
help='Print pairs on exchange.',
|
||||||
|
parents=[_common_parser],
|
||||||
|
)
|
||||||
|
list_pairs_cmd.set_defaults(func=partial(start_list_markets, pairs_only=True))
|
||||||
|
self._build_args(optionlist=ARGS_LIST_PAIRS, parser=list_pairs_cmd)
|
||||||
|
|
||||||
|
# Add test-pairlist subcommand
|
||||||
|
test_pairlist_cmd = subparsers.add_parser(
|
||||||
|
'test-pairlist',
|
||||||
|
help='Test your pairlist configuration.',
|
||||||
|
)
|
||||||
|
test_pairlist_cmd.set_defaults(func=start_test_pairlist)
|
||||||
|
self._build_args(optionlist=ARGS_TEST_PAIRLIST, parser=test_pairlist_cmd)
|
||||||
|
|
||||||
|
# Add download-data subcommand
|
||||||
|
download_data_cmd = subparsers.add_parser(
|
||||||
|
'download-data',
|
||||||
|
help='Download backtesting data.',
|
||||||
|
parents=[_common_parser],
|
||||||
|
)
|
||||||
|
download_data_cmd.set_defaults(func=start_download_data)
|
||||||
|
self._build_args(optionlist=ARGS_DOWNLOAD_DATA, parser=download_data_cmd)
|
||||||
|
|
||||||
|
# Add Plotting subcommand
|
||||||
|
plot_dataframe_cmd = subparsers.add_parser(
|
||||||
|
'plot-dataframe',
|
||||||
|
help='Plot candles with indicators.',
|
||||||
|
parents=[_common_parser, _strategy_parser],
|
||||||
|
)
|
||||||
|
plot_dataframe_cmd.set_defaults(func=start_plot_dataframe)
|
||||||
|
self._build_args(optionlist=ARGS_PLOT_DATAFRAME, parser=plot_dataframe_cmd)
|
||||||
|
|
||||||
|
# Plot profit
|
||||||
|
plot_profit_cmd = subparsers.add_parser(
|
||||||
|
'plot-profit',
|
||||||
|
help='Generate plot showing profits.',
|
||||||
|
parents=[_common_parser],
|
||||||
|
)
|
||||||
|
plot_profit_cmd.set_defaults(func=start_plot_profit)
|
||||||
|
self._build_args(optionlist=ARGS_PLOT_PROFIT, parser=plot_profit_cmd)
|
||||||
|
|
||||||
|
# Add hyperopt-list subcommand
|
||||||
|
hyperopt_list_cmd = subparsers.add_parser(
|
||||||
|
'hyperopt-list',
|
||||||
|
help='List Hyperopt results',
|
||||||
|
parents=[_common_parser],
|
||||||
|
)
|
||||||
|
hyperopt_list_cmd.set_defaults(func=start_hyperopt_list)
|
||||||
|
self._build_args(optionlist=ARGS_HYPEROPT_LIST, parser=hyperopt_list_cmd)
|
||||||
|
|
||||||
|
# Add hyperopt-show subcommand
|
||||||
|
hyperopt_show_cmd = subparsers.add_parser(
|
||||||
|
'hyperopt-show',
|
||||||
|
help='Show details of Hyperopt results',
|
||||||
|
parents=[_common_parser],
|
||||||
|
)
|
||||||
|
hyperopt_show_cmd.set_defaults(func=start_hyperopt_show)
|
||||||
|
self._build_args(optionlist=ARGS_HYPEROPT_SHOW, parser=hyperopt_show_cmd)
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
Definition of cli arguments used in arguments.py
|
Definition of cli arguments used in arguments.py
|
||||||
"""
|
"""
|
||||||
import argparse
|
from argparse import ArgumentTypeError
|
||||||
import os
|
|
||||||
|
|
||||||
from freqtrade import __version__, constants
|
from freqtrade import __version__, constants
|
||||||
|
|
||||||
@@ -13,12 +12,24 @@ def check_int_positive(value: str) -> int:
|
|||||||
if uint <= 0:
|
if uint <= 0:
|
||||||
raise ValueError
|
raise ValueError
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise argparse.ArgumentTypeError(
|
raise ArgumentTypeError(
|
||||||
f"{value} is invalid for this parameter, should be a positive integer value"
|
f"{value} is invalid for this parameter, should be a positive integer value"
|
||||||
)
|
)
|
||||||
return uint
|
return uint
|
||||||
|
|
||||||
|
|
||||||
|
def check_int_nonzero(value: str) -> int:
|
||||||
|
try:
|
||||||
|
uint = int(value)
|
||||||
|
if uint == 0:
|
||||||
|
raise ValueError
|
||||||
|
except ValueError:
|
||||||
|
raise ArgumentTypeError(
|
||||||
|
f"{value} is invalid for this parameter, should be a non-zero integer value"
|
||||||
|
)
|
||||||
|
return uint
|
||||||
|
|
||||||
|
|
||||||
class Arg:
|
class Arg:
|
||||||
# Optional CLI arguments
|
# Optional CLI arguments
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
@@ -37,7 +48,8 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
),
|
),
|
||||||
"logfile": Arg(
|
"logfile": Arg(
|
||||||
'--logfile',
|
'--logfile',
|
||||||
help='Log to the file specified.',
|
help="Log to the file specified. Special values are: 'syslog', 'journald'. "
|
||||||
|
"See the documentation for more details.",
|
||||||
metavar='FILE',
|
metavar='FILE',
|
||||||
),
|
),
|
||||||
"version": Arg(
|
"version": Arg(
|
||||||
@@ -63,12 +75,16 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
help='Path to userdata directory.',
|
help='Path to userdata directory.',
|
||||||
metavar='PATH',
|
metavar='PATH',
|
||||||
),
|
),
|
||||||
|
"reset": Arg(
|
||||||
|
'--reset',
|
||||||
|
help='Reset sample files to their original state.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
# Main options
|
# Main options
|
||||||
"strategy": Arg(
|
"strategy": Arg(
|
||||||
'-s', '--strategy',
|
'-s', '--strategy',
|
||||||
help='Specify strategy class name (default: `%(default)s`).',
|
help='Specify strategy class name which will be used by the bot.',
|
||||||
metavar='NAME',
|
metavar='NAME',
|
||||||
default='DefaultStrategy',
|
|
||||||
),
|
),
|
||||||
"strategy_path": Arg(
|
"strategy_path": Arg(
|
||||||
'--strategy-path',
|
'--strategy-path',
|
||||||
@@ -87,6 +103,11 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
help='Notify systemd service manager.',
|
help='Notify systemd service manager.',
|
||||||
action='store_true',
|
action='store_true',
|
||||||
),
|
),
|
||||||
|
"dry_run": Arg(
|
||||||
|
'--dry-run',
|
||||||
|
help='Enforce dry-run for trading (removes Exchange secrets and simulates trades).',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
# Optimize common
|
# Optimize common
|
||||||
"ticker_interval": Arg(
|
"ticker_interval": Arg(
|
||||||
'-i', '--ticker-interval',
|
'-i', '--ticker-interval',
|
||||||
@@ -97,14 +118,14 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
help='Specify what timerange of data to use.',
|
help='Specify what timerange of data to use.',
|
||||||
),
|
),
|
||||||
"max_open_trades": Arg(
|
"max_open_trades": Arg(
|
||||||
'--max_open_trades',
|
'--max-open-trades',
|
||||||
help='Specify max_open_trades to use.',
|
help='Override the value of the `max_open_trades` configuration setting.',
|
||||||
type=int,
|
type=int,
|
||||||
metavar='INT',
|
metavar='INT',
|
||||||
),
|
),
|
||||||
"stake_amount": Arg(
|
"stake_amount": Arg(
|
||||||
'--stake_amount',
|
'--stake-amount',
|
||||||
help='Specify stake_amount.',
|
help='Override the value of the `stake_amount` configuration setting.',
|
||||||
type=float,
|
type=float,
|
||||||
),
|
),
|
||||||
# Backtesting
|
# Backtesting
|
||||||
@@ -137,12 +158,16 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
),
|
),
|
||||||
"exportfilename": Arg(
|
"exportfilename": Arg(
|
||||||
'--export-filename',
|
'--export-filename',
|
||||||
help='Save backtest results to the file with this filename (default: `%(default)s`). '
|
help='Save backtest results to the file with this filename. '
|
||||||
'Requires `--export` to be set as well. '
|
'Requires `--export` to be set as well. '
|
||||||
'Example: `--export-filename=user_data/backtest_results/backtest_today.json`',
|
'Example: `--export-filename=user_data/backtest_results/backtest_today.json`',
|
||||||
metavar='PATH',
|
metavar='PATH',
|
||||||
default=os.path.join('user_data', 'backtest_results',
|
),
|
||||||
'backtest-result.json'),
|
"fee": Arg(
|
||||||
|
'--fee',
|
||||||
|
help='Specify fee ratio. Will be applied twice (on trade entry and exit).',
|
||||||
|
type=float,
|
||||||
|
metavar='FLOAT',
|
||||||
),
|
),
|
||||||
# Edge
|
# Edge
|
||||||
"stoploss_range": Arg(
|
"stoploss_range": Arg(
|
||||||
@@ -153,14 +178,13 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
),
|
),
|
||||||
# Hyperopt
|
# Hyperopt
|
||||||
"hyperopt": Arg(
|
"hyperopt": Arg(
|
||||||
'--customhyperopt',
|
'--hyperopt',
|
||||||
help='Specify hyperopt class name (default: `%(default)s`).',
|
help='Specify hyperopt class name which will be used by the bot.',
|
||||||
metavar='NAME',
|
metavar='NAME',
|
||||||
default=constants.DEFAULT_HYPEROPT,
|
|
||||||
),
|
),
|
||||||
"hyperopt_path": Arg(
|
"hyperopt_path": Arg(
|
||||||
'--hyperopt-path',
|
'--hyperopt-path',
|
||||||
help='Specify additional lookup path for Hyperopts and Hyperopt Loss functions.',
|
help='Specify additional lookup path for Hyperopt and Hyperopt Loss functions.',
|
||||||
metavar='PATH',
|
metavar='PATH',
|
||||||
),
|
),
|
||||||
"epochs": Arg(
|
"epochs": Arg(
|
||||||
@@ -171,12 +195,11 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
default=constants.HYPEROPT_EPOCH,
|
default=constants.HYPEROPT_EPOCH,
|
||||||
),
|
),
|
||||||
"spaces": Arg(
|
"spaces": Arg(
|
||||||
'-s', '--spaces',
|
'--spaces',
|
||||||
help='Specify which parameters to hyperopt. Space-separated list. '
|
help='Specify which parameters to hyperopt. Space-separated list.',
|
||||||
'Default: `%(default)s`.',
|
choices=['all', 'buy', 'sell', 'roi', 'stoploss', 'trailing', 'default'],
|
||||||
choices=['all', 'buy', 'sell', 'roi', 'stoploss'],
|
|
||||||
nargs='+',
|
nargs='+',
|
||||||
default='all',
|
default='default',
|
||||||
),
|
),
|
||||||
"print_all": Arg(
|
"print_all": Arg(
|
||||||
'--print-all',
|
'--print-all',
|
||||||
@@ -241,9 +264,50 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
# List exchanges
|
# List exchanges
|
||||||
"print_one_column": Arg(
|
"print_one_column": Arg(
|
||||||
'-1', '--one-column',
|
'-1', '--one-column',
|
||||||
help='Print exchanges in one column.',
|
help='Print output in one column.',
|
||||||
action='store_true',
|
action='store_true',
|
||||||
),
|
),
|
||||||
|
"list_exchanges_all": Arg(
|
||||||
|
'-a', '--all',
|
||||||
|
help='Print all exchanges known to the ccxt library.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
# List pairs / markets
|
||||||
|
"list_pairs_all": Arg(
|
||||||
|
'-a', '--all',
|
||||||
|
help='Print all pairs or market symbols. By default only active '
|
||||||
|
'ones are shown.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"print_list": Arg(
|
||||||
|
'--print-list',
|
||||||
|
help='Print list of pairs or market symbols. By default data is '
|
||||||
|
'printed in the tabular format.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"list_pairs_print_json": Arg(
|
||||||
|
'--print-json',
|
||||||
|
help='Print list of pairs or market symbols in JSON format.',
|
||||||
|
action='store_true',
|
||||||
|
default=False,
|
||||||
|
),
|
||||||
|
"print_csv": Arg(
|
||||||
|
'--print-csv',
|
||||||
|
help='Print exchange pair or market data in the csv format.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"quote_currencies": Arg(
|
||||||
|
'--quote',
|
||||||
|
help='Specify quote currency(-ies). Space-separated list.',
|
||||||
|
nargs='+',
|
||||||
|
metavar='QUOTE_CURRENCY',
|
||||||
|
),
|
||||||
|
"base_currencies": Arg(
|
||||||
|
'--base',
|
||||||
|
help='Specify base currency(-ies). Space-separated list.',
|
||||||
|
nargs='+',
|
||||||
|
metavar='BASE_CURRENCY',
|
||||||
|
),
|
||||||
# Script options
|
# Script options
|
||||||
"pairs": Arg(
|
"pairs": Arg(
|
||||||
'-p', '--pairs',
|
'-p', '--pairs',
|
||||||
@@ -262,6 +326,12 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
type=check_int_positive,
|
type=check_int_positive,
|
||||||
metavar='INT',
|
metavar='INT',
|
||||||
),
|
),
|
||||||
|
"download_trades": Arg(
|
||||||
|
'--dl-trades',
|
||||||
|
help='Download trades instead of OHLCV data. The bot will resample trades to the '
|
||||||
|
'desired timeframe as specified as --timeframes/-t.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
"exchange": Arg(
|
"exchange": Arg(
|
||||||
'--exchange',
|
'--exchange',
|
||||||
help=f'Exchange name (default: `{constants.DEFAULT_EXCHANGE}`). '
|
help=f'Exchange name (default: `{constants.DEFAULT_EXCHANGE}`). '
|
||||||
@@ -281,19 +351,25 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
help='Clean all existing data for the selected exchange/pairs/timeframes.',
|
help='Clean all existing data for the selected exchange/pairs/timeframes.',
|
||||||
action='store_true',
|
action='store_true',
|
||||||
),
|
),
|
||||||
|
# Templating options
|
||||||
|
"template": Arg(
|
||||||
|
'--template',
|
||||||
|
help='Use a template which is either `minimal` or '
|
||||||
|
'`full` (containing multiple sample indicators). Default: `%(default)s`.',
|
||||||
|
choices=['full', 'minimal'],
|
||||||
|
default='full',
|
||||||
|
),
|
||||||
# Plot dataframe
|
# Plot dataframe
|
||||||
"indicators1": Arg(
|
"indicators1": Arg(
|
||||||
'--indicators1',
|
'--indicators1',
|
||||||
help='Set indicators from your strategy you want in the first row of the graph. '
|
help='Set indicators from your strategy you want in the first row of the graph. '
|
||||||
'Space-separated list. Example: `ema3 ema5`. Default: `%(default)s`.',
|
"Space-separated list. Example: `ema3 ema5`. Default: `['sma', 'ema3', 'ema5']`.",
|
||||||
default=['sma', 'ema3', 'ema5'],
|
|
||||||
nargs='+',
|
nargs='+',
|
||||||
),
|
),
|
||||||
"indicators2": Arg(
|
"indicators2": Arg(
|
||||||
'--indicators2',
|
'--indicators2',
|
||||||
help='Set indicators from your strategy you want in the third row of the graph. '
|
help='Set indicators from your strategy you want in the third row of the graph. '
|
||||||
'Space-separated list. Example: `fastd fastk`. Default: `%(default)s`.',
|
"Space-separated list. Example: `fastd fastk`. Default: `['macd', 'macdsignal']`.",
|
||||||
default=['macd', 'macdsignal'],
|
|
||||||
nargs='+',
|
nargs='+',
|
||||||
),
|
),
|
||||||
"plot_limit": Arg(
|
"plot_limit": Arg(
|
||||||
@@ -311,4 +387,31 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
choices=["DB", "file"],
|
choices=["DB", "file"],
|
||||||
default="file",
|
default="file",
|
||||||
),
|
),
|
||||||
|
# hyperopt-list, hyperopt-show
|
||||||
|
"hyperopt_list_profitable": Arg(
|
||||||
|
'--profitable',
|
||||||
|
help='Select only profitable epochs.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"hyperopt_list_best": Arg(
|
||||||
|
'--best',
|
||||||
|
help='Select only best epochs.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"hyperopt_list_no_details": Arg(
|
||||||
|
'--no-details',
|
||||||
|
help='Do not print best epoch details.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"hyperopt_show_index": Arg(
|
||||||
|
'-n', '--index',
|
||||||
|
help='Specify the index of the epoch to print details for.',
|
||||||
|
type=check_int_nonzero,
|
||||||
|
metavar='INT',
|
||||||
|
),
|
||||||
|
"hyperopt_show_no_header": Arg(
|
||||||
|
'--no-header',
|
||||||
|
help='Do not print epoch details header.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
}
|
}
|
||||||
63
freqtrade/commands/data_commands.py
Normal file
63
freqtrade/commands/data_commands.py
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
import arrow
|
||||||
|
|
||||||
|
from freqtrade.configuration import TimeRange, setup_utils_configuration
|
||||||
|
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)
|
||||||
|
try:
|
||||||
|
|
||||||
|
if config.get('download_trades'):
|
||||||
|
pairs_not_available = refresh_backtest_trades_data(
|
||||||
|
exchange, pairs=config["pairs"], datadir=config['datadir'],
|
||||||
|
timerange=timerange, erase=config.get("erase"))
|
||||||
|
|
||||||
|
# Convert downloaded trade data to different timeframes
|
||||||
|
convert_trades_to_ohlcv(
|
||||||
|
pairs=config["pairs"], timeframes=config["timeframes"],
|
||||||
|
datadir=config['datadir'], timerange=timerange, erase=config.get("erase"))
|
||||||
|
else:
|
||||||
|
pairs_not_available = refresh_backtest_ohlcv_data(
|
||||||
|
exchange, pairs=config["pairs"], timeframes=config["timeframes"],
|
||||||
|
datadir=config['datadir'], timerange=timerange, erase=config.get("erase"))
|
||||||
|
|
||||||
|
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}.")
|
||||||
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_STRATEGY
|
||||||
|
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, strategy_path: Path, subtemplate: str):
|
||||||
|
"""
|
||||||
|
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_STRATEGY / (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, hyperopt_path: Path, subtemplate: str):
|
||||||
|
"""
|
||||||
|
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.")
|
||||||
114
freqtrade/commands/hyperopt_commands.py
Normal file
114
freqtrade/commands/hyperopt_commands.py
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
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)
|
||||||
|
|
||||||
|
only_best = config.get('hyperopt_list_best', False)
|
||||||
|
only_profitable = config.get('hyperopt_list_profitable', False)
|
||||||
|
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
|
||||||
|
|
||||||
|
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, only_best, only_profitable)
|
||||||
|
|
||||||
|
# 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 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)
|
||||||
|
|
||||||
|
only_best = config.get('hyperopt_list_best', False)
|
||||||
|
only_profitable = config.get('hyperopt_list_profitable', False)
|
||||||
|
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, only_best, only_profitable)
|
||||||
|
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, only_best: bool, only_profitable: bool) -> List:
|
||||||
|
"""
|
||||||
|
Filter our items from the list of hyperopt results
|
||||||
|
"""
|
||||||
|
if only_best:
|
||||||
|
trials = [x for x in trials if x['is_best']]
|
||||||
|
if only_profitable:
|
||||||
|
trials = [x for x in trials if x['results_metrics']['profit'] > 0]
|
||||||
|
|
||||||
|
logger.info(f"{len(trials)} " +
|
||||||
|
("best " if only_best else "") +
|
||||||
|
("profitable " if only_profitable else "") +
|
||||||
|
"epochs found.")
|
||||||
|
|
||||||
|
return trials
|
||||||
156
freqtrade/commands/list_commands.py
Normal file
156
freqtrade/commands/list_commands.py
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
import csv
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
from collections import OrderedDict
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict
|
||||||
|
|
||||||
|
import rapidjson
|
||||||
|
from tabulate import tabulate
|
||||||
|
|
||||||
|
from freqtrade.configuration import setup_utils_configuration
|
||||||
|
from freqtrade.constants import USERPATH_STRATEGY
|
||||||
|
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 start_list_strategies(args: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Print Strategies available in a directory
|
||||||
|
"""
|
||||||
|
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||||
|
|
||||||
|
directory = Path(config.get('strategy_path', config['user_data_dir'] / USERPATH_STRATEGY))
|
||||||
|
strategies = StrategyResolver.search_all_objects(directory)
|
||||||
|
# Sort alphabetically
|
||||||
|
strategies = sorted(strategies, key=lambda x: x['name'])
|
||||||
|
strats_to_print = [{'name': s['name'], 'location': s['location'].name} for s in strategies]
|
||||||
|
|
||||||
|
if args['print_one_column']:
|
||||||
|
print('\n'.join([s['name'] for s in strategies]))
|
||||||
|
else:
|
||||||
|
print(tabulate(strats_to_print, headers='keys', tablefmt='pipe'))
|
||||||
|
|
||||||
|
|
||||||
|
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,8 +1,8 @@
|
|||||||
from typing import Any, Dict
|
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.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]):
|
||||||
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,4 +1,7 @@
|
|||||||
from freqtrade.configuration.arguments import Arguments # noqa: F401
|
# flake8: noqa: F401
|
||||||
from freqtrade.configuration.timerange import TimeRange # noqa: F401
|
|
||||||
from freqtrade.configuration.configuration import Configuration # noqa: F401
|
from freqtrade.configuration.config_setup import setup_utils_configuration
|
||||||
from freqtrade.configuration.config_validation import validate_config_consistency # noqa: F401
|
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,157 +0,0 @@
|
|||||||
"""
|
|
||||||
This module contains the argument manager class
|
|
||||||
"""
|
|
||||||
import argparse
|
|
||||||
from pathlib import Path
|
|
||||||
from typing import Any, Dict, List, Optional
|
|
||||||
|
|
||||||
from freqtrade import constants
|
|
||||||
from freqtrade.configuration.cli_options import AVAILABLE_CLI_OPTIONS
|
|
||||||
|
|
||||||
ARGS_COMMON = ["verbosity", "logfile", "version", "config", "datadir", "user_data_dir"]
|
|
||||||
|
|
||||||
ARGS_STRATEGY = ["strategy", "strategy_path"]
|
|
||||||
|
|
||||||
ARGS_MAIN = ARGS_COMMON + ARGS_STRATEGY + ["db_url", "sd_notify"]
|
|
||||||
|
|
||||||
ARGS_COMMON_OPTIMIZE = ["ticker_interval", "timerange",
|
|
||||||
"max_open_trades", "stake_amount"]
|
|
||||||
|
|
||||||
ARGS_BACKTEST = ARGS_COMMON_OPTIMIZE + ["position_stacking", "use_max_market_positions",
|
|
||||||
"strategy_list", "export", "exportfilename"]
|
|
||||||
|
|
||||||
ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
|
|
||||||
"position_stacking", "epochs", "spaces",
|
|
||||||
"use_max_market_positions", "print_all",
|
|
||||||
"print_colorized", "print_json", "hyperopt_jobs",
|
|
||||||
"hyperopt_random_state", "hyperopt_min_trades",
|
|
||||||
"hyperopt_continue", "hyperopt_loss"]
|
|
||||||
|
|
||||||
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
|
|
||||||
|
|
||||||
ARGS_LIST_EXCHANGES = ["print_one_column"]
|
|
||||||
|
|
||||||
ARGS_CREATE_USERDIR = ["user_data_dir"]
|
|
||||||
|
|
||||||
ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "exchange", "timeframes", "erase"]
|
|
||||||
|
|
||||||
ARGS_PLOT_DATAFRAME = ["pairs", "indicators1", "indicators2", "plot_limit", "db_url",
|
|
||||||
"trade_source", "export", "exportfilename", "timerange", "ticker_interval"]
|
|
||||||
|
|
||||||
ARGS_PLOT_PROFIT = ["pairs", "timerange", "export", "exportfilename", "db_url",
|
|
||||||
"trade_source", "ticker_interval"]
|
|
||||||
|
|
||||||
NO_CONF_REQURIED = ["create-userdir", "download-data", "plot-dataframe", "plot-profit"]
|
|
||||||
|
|
||||||
|
|
||||||
class Arguments:
|
|
||||||
"""
|
|
||||||
Arguments Class. Manage the arguments received by the cli
|
|
||||||
"""
|
|
||||||
def __init__(self, args: Optional[List[str]]) -> None:
|
|
||||||
self.args = args
|
|
||||||
self._parsed_arg: Optional[argparse.Namespace] = None
|
|
||||||
self.parser = argparse.ArgumentParser(description='Free, open source crypto trading bot')
|
|
||||||
|
|
||||||
def _load_args(self) -> None:
|
|
||||||
self._build_args(optionlist=ARGS_MAIN)
|
|
||||||
self._build_subcommands()
|
|
||||||
|
|
||||||
def get_parsed_arg(self) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Return the list of arguments
|
|
||||||
:return: List[str] List of arguments
|
|
||||||
"""
|
|
||||||
if self._parsed_arg is None:
|
|
||||||
self._load_args()
|
|
||||||
self._parsed_arg = self._parse_args()
|
|
||||||
|
|
||||||
return vars(self._parsed_arg)
|
|
||||||
|
|
||||||
def _parse_args(self) -> argparse.Namespace:
|
|
||||||
"""
|
|
||||||
Parses given arguments and returns an argparse Namespace instance.
|
|
||||||
"""
|
|
||||||
parsed_arg = self.parser.parse_args(self.args)
|
|
||||||
|
|
||||||
# When no config is provided, but a config exists, use that configuration!
|
|
||||||
|
|
||||||
# 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 (parsed_arg.config is None and ((Path.cwd() / constants.DEFAULT_CONFIG).is_file() or
|
|
||||||
not ('subparser' in parsed_arg and parsed_arg.subparser in NO_CONF_REQURIED))):
|
|
||||||
parsed_arg.config = [constants.DEFAULT_CONFIG]
|
|
||||||
|
|
||||||
return parsed_arg
|
|
||||||
|
|
||||||
def _build_args(self, optionlist, parser=None):
|
|
||||||
parser = parser or self.parser
|
|
||||||
|
|
||||||
for val in optionlist:
|
|
||||||
opt = AVAILABLE_CLI_OPTIONS[val]
|
|
||||||
parser.add_argument(*opt.cli, dest=val, **opt.kwargs)
|
|
||||||
|
|
||||||
def _build_subcommands(self) -> None:
|
|
||||||
"""
|
|
||||||
Builds and attaches all subcommands.
|
|
||||||
:return: None
|
|
||||||
"""
|
|
||||||
from freqtrade.optimize import start_backtesting, start_hyperopt, start_edge
|
|
||||||
from freqtrade.utils import start_create_userdir, start_download_data, start_list_exchanges
|
|
||||||
|
|
||||||
subparsers = self.parser.add_subparsers(dest='subparser')
|
|
||||||
|
|
||||||
# Add backtesting subcommand
|
|
||||||
backtesting_cmd = subparsers.add_parser('backtesting', help='Backtesting module.')
|
|
||||||
backtesting_cmd.set_defaults(func=start_backtesting)
|
|
||||||
self._build_args(optionlist=ARGS_BACKTEST, parser=backtesting_cmd)
|
|
||||||
|
|
||||||
# Add edge subcommand
|
|
||||||
edge_cmd = subparsers.add_parser('edge', help='Edge module.')
|
|
||||||
edge_cmd.set_defaults(func=start_edge)
|
|
||||||
self._build_args(optionlist=ARGS_EDGE, parser=edge_cmd)
|
|
||||||
|
|
||||||
# Add hyperopt subcommand
|
|
||||||
hyperopt_cmd = subparsers.add_parser('hyperopt', help='Hyperopt module.')
|
|
||||||
hyperopt_cmd.set_defaults(func=start_hyperopt)
|
|
||||||
self._build_args(optionlist=ARGS_HYPEROPT, parser=hyperopt_cmd)
|
|
||||||
|
|
||||||
# add create-userdir subcommand
|
|
||||||
create_userdir_cmd = subparsers.add_parser('create-userdir',
|
|
||||||
help="Create user-data directory.")
|
|
||||||
create_userdir_cmd.set_defaults(func=start_create_userdir)
|
|
||||||
self._build_args(optionlist=ARGS_CREATE_USERDIR, parser=create_userdir_cmd)
|
|
||||||
|
|
||||||
# Add list-exchanges subcommand
|
|
||||||
list_exchanges_cmd = subparsers.add_parser(
|
|
||||||
'list-exchanges',
|
|
||||||
help='Print available exchanges.'
|
|
||||||
)
|
|
||||||
list_exchanges_cmd.set_defaults(func=start_list_exchanges)
|
|
||||||
self._build_args(optionlist=ARGS_LIST_EXCHANGES, parser=list_exchanges_cmd)
|
|
||||||
|
|
||||||
# Add download-data subcommand
|
|
||||||
download_data_cmd = subparsers.add_parser(
|
|
||||||
'download-data',
|
|
||||||
help='Download backtesting data.'
|
|
||||||
)
|
|
||||||
download_data_cmd.set_defaults(func=start_download_data)
|
|
||||||
self._build_args(optionlist=ARGS_DOWNLOAD_DATA, parser=download_data_cmd)
|
|
||||||
|
|
||||||
# Add Plotting subcommand
|
|
||||||
from freqtrade.plot.plot_utils import start_plot_dataframe, start_plot_profit
|
|
||||||
plot_dataframe_cmd = subparsers.add_parser(
|
|
||||||
'plot-dataframe',
|
|
||||||
help='Plot candles with indicators.'
|
|
||||||
)
|
|
||||||
plot_dataframe_cmd.set_defaults(func=start_plot_dataframe)
|
|
||||||
self._build_args(optionlist=ARGS_PLOT_DATAFRAME, parser=plot_dataframe_cmd)
|
|
||||||
|
|
||||||
# Plot profit
|
|
||||||
plot_profit_cmd = subparsers.add_parser(
|
|
||||||
'plot-profit',
|
|
||||||
help='Generate plot showing profits.'
|
|
||||||
)
|
|
||||||
plot_profit_cmd.set_defaults(func=start_plot_profit)
|
|
||||||
self._build_args(optionlist=ARGS_PLOT_PROFIT, parser=plot_profit_cmd)
|
|
||||||
@@ -1,15 +1,28 @@
|
|||||||
import logging
|
import logging
|
||||||
from typing import Any, Dict
|
from typing import Any, Dict
|
||||||
|
|
||||||
from freqtrade import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.exchange import (available_exchanges, get_exchange_bad_reason,
|
from freqtrade.exchange import (available_exchanges, get_exchange_bad_reason,
|
||||||
is_exchange_available, is_exchange_bad,
|
is_exchange_bad, is_exchange_known_ccxt,
|
||||||
is_exchange_officially_supported)
|
is_exchange_officially_supported)
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def remove_credentials(config: Dict[str, Any]):
|
||||||
|
"""
|
||||||
|
Removes exchange keys from the configuration and specifies dry-run
|
||||||
|
Used for backtesting / hyperopt / edge and utils.
|
||||||
|
Modifies the input dict!
|
||||||
|
"""
|
||||||
|
config['exchange']['key'] = ''
|
||||||
|
config['exchange']['secret'] = ''
|
||||||
|
config['exchange']['password'] = ''
|
||||||
|
config['exchange']['uid'] = ''
|
||||||
|
config['dry_run'] = True
|
||||||
|
|
||||||
|
|
||||||
def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
||||||
"""
|
"""
|
||||||
Check if the exchange name in the config file is supported by Freqtrade
|
Check if the exchange name in the config file is supported by Freqtrade
|
||||||
@@ -21,7 +34,8 @@ def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
|||||||
and thus is not known for the Freqtrade at all.
|
and thus is not known for the Freqtrade at all.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if config['runmode'] in [RunMode.PLOT] and not config.get('exchange', {}).get('name'):
|
if (config['runmode'] in [RunMode.PLOT, RunMode.UTIL_NO_EXCHANGE, RunMode.OTHER]
|
||||||
|
and not config.get('exchange', {}).get('name')):
|
||||||
# Skip checking exchange in plot mode, since it requires no exchange
|
# Skip checking exchange in plot mode, since it requires no exchange
|
||||||
return True
|
return True
|
||||||
logger.info("Checking exchange...")
|
logger.info("Checking exchange...")
|
||||||
@@ -31,15 +45,15 @@ def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
|||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f'This command requires a configured exchange. You should either use '
|
f'This command requires a configured exchange. You should either use '
|
||||||
f'`--exchange <exchange_name>` or specify a configuration file via `--config`.\n'
|
f'`--exchange <exchange_name>` or specify a configuration file via `--config`.\n'
|
||||||
f'The following exchanges are supported by ccxt: '
|
f'The following exchanges are available for Freqtrade: '
|
||||||
f'{", ".join(available_exchanges())}'
|
f'{", ".join(available_exchanges())}'
|
||||||
)
|
)
|
||||||
|
|
||||||
if not is_exchange_available(exchange):
|
if not is_exchange_known_ccxt(exchange):
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f'Exchange "{exchange}" is not supported by ccxt '
|
f'Exchange "{exchange}" is not known to the ccxt library '
|
||||||
f'and therefore not available for the bot.\n'
|
f'and therefore not available for the bot.\n'
|
||||||
f'The following exchanges are supported by ccxt: '
|
f'The following exchanges are available for Freqtrade: '
|
||||||
f'{", ".join(available_exchanges())}'
|
f'{", ".join(available_exchanges())}'
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -51,8 +65,8 @@ def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
|||||||
logger.info(f'Exchange "{exchange}" is officially supported '
|
logger.info(f'Exchange "{exchange}" is officially supported '
|
||||||
f'by the Freqtrade development team.')
|
f'by the Freqtrade development team.')
|
||||||
else:
|
else:
|
||||||
logger.warning(f'Exchange "{exchange}" is supported by ccxt '
|
logger.warning(f'Exchange "{exchange}" is known to the the ccxt library, '
|
||||||
f'and therefore available for the bot but not officially supported '
|
f'available for the bot, but not officially supported '
|
||||||
f'by the Freqtrade development team. '
|
f'by the Freqtrade development team. '
|
||||||
f'It may work flawlessly (please report back) or have serious issues. '
|
f'It may work flawlessly (please report back) or have serious issues. '
|
||||||
f'Use it at your own discretion.')
|
f'Use it at your own discretion.')
|
||||||
|
|||||||
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,11 +1,13 @@
|
|||||||
import logging
|
import logging
|
||||||
|
from copy import deepcopy
|
||||||
from typing import Any, Dict
|
from typing import Any, Dict
|
||||||
|
|
||||||
from jsonschema import Draft4Validator, validators
|
from jsonschema import Draft4Validator, validators
|
||||||
from jsonschema.exceptions import ValidationError, best_match
|
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__)
|
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
|
:param conf: Config in JSON format
|
||||||
:return: Returns the config if valid, otherwise throw an exception
|
: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:
|
try:
|
||||||
FreqtradeValidator(constants.CONF_SCHEMA).validate(conf)
|
FreqtradeValidator(conf_schema).validate(conf)
|
||||||
return conf
|
return conf
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
logger.critical(
|
logger.critical(
|
||||||
f"Invalid configuration. See config.json.example. Reason: {e}"
|
f"Invalid configuration. See config.json.example. Reason: {e}"
|
||||||
)
|
)
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
best_match(Draft4Validator(constants.CONF_SCHEMA).iter_errors(conf)).message
|
best_match(Draft4Validator(conf_schema).iter_errors(conf)).message
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -61,9 +68,27 @@ def validate_config_consistency(conf: Dict[str, Any]) -> None:
|
|||||||
:param conf: Config in JSON format
|
:param conf: Config in JSON format
|
||||||
:return: Returns None if everything is ok, otherwise throw an OperationalException
|
:return: Returns None if everything is ok, otherwise throw an OperationalException
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# validating trailing stoploss
|
# validating trailing stoploss
|
||||||
_validate_trailing_stoploss(conf)
|
_validate_trailing_stoploss(conf)
|
||||||
_validate_edge(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:
|
def _validate_trailing_stoploss(conf: Dict[str, Any]) -> None:
|
||||||
@@ -111,3 +136,29 @@ def _validate_edge(conf: Dict[str, Any]) -> None:
|
|||||||
"Edge and VolumePairList are incompatible, "
|
"Edge and VolumePairList are incompatible, "
|
||||||
"Edge will override whatever pairs VolumePairlist selects."
|
"Edge will override whatever pairs VolumePairlist selects."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_whitelist(conf: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Dynamic whitelist does not require pair_whitelist to be set - however StaticWhitelist does.
|
||||||
|
"""
|
||||||
|
if conf.get('runmode', RunMode.OTHER) in [RunMode.OTHER, RunMode.PLOT,
|
||||||
|
RunMode.UTIL_NO_EXCHANGE, RunMode.UTIL_EXCHANGE]:
|
||||||
|
return
|
||||||
|
|
||||||
|
for pl in conf.get('pairlists', [{'method': 'StaticPairList'}]):
|
||||||
|
if (pl.get('method') == 'StaticPairList'
|
||||||
|
and not conf.get('exchange', {}).get('pair_whitelist')):
|
||||||
|
raise OperationalException("StaticPairList requires pair_whitelist to be set.")
|
||||||
|
|
||||||
|
if pl.get('method') == 'StaticPairList':
|
||||||
|
stake = conf['stake_currency']
|
||||||
|
invalid_pairs = []
|
||||||
|
for pair in conf['exchange'].get('pair_whitelist'):
|
||||||
|
if not pair.endswith(f'/{stake}'):
|
||||||
|
invalid_pairs.append(pair)
|
||||||
|
|
||||||
|
if invalid_pairs:
|
||||||
|
raise OperationalException(
|
||||||
|
f"Stake-currency '{stake}' not compatible with pair-whitelist. "
|
||||||
|
f"Please remove the following pairs: {invalid_pairs}")
|
||||||
|
|||||||
@@ -7,16 +7,16 @@ from copy import deepcopy
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Callable, Dict, List, Optional
|
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.check_exchange import check_exchange
|
||||||
from freqtrade.configuration.config_validation import (
|
from freqtrade.configuration.deprecated_settings import process_temporary_deprecated_settings
|
||||||
validate_config_consistency, validate_config_schema)
|
|
||||||
from freqtrade.configuration.directory_operations import (create_datadir,
|
from freqtrade.configuration.directory_operations import (create_datadir,
|
||||||
create_userdata_dir)
|
create_userdata_dir)
|
||||||
from freqtrade.configuration.load_config import load_config_file
|
from freqtrade.configuration.load_config import load_config_file
|
||||||
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.loggers import setup_logging
|
from freqtrade.loggers import setup_logging
|
||||||
from freqtrade.misc import deep_merge_dicts, json_load
|
from freqtrade.misc import deep_merge_dicts, json_load
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import NON_UTIL_MODES, TRADING_MODES, RunMode
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -75,10 +75,13 @@ class Configuration:
|
|||||||
# Normalize config
|
# Normalize config
|
||||||
if 'internals' not in config:
|
if 'internals' not in config:
|
||||||
config['internals'] = {}
|
config['internals'] = {}
|
||||||
|
# TODO: This can be deleted along with removal of deprecated
|
||||||
|
# experimental settings
|
||||||
|
if 'ask_strategy' not in config:
|
||||||
|
config['ask_strategy'] = {}
|
||||||
|
|
||||||
# validate configuration before returning
|
if 'pairlists' not in config:
|
||||||
logger.info('Validating configuration ...')
|
config['pairlists'] = []
|
||||||
validate_config_schema(config)
|
|
||||||
|
|
||||||
return config
|
return config
|
||||||
|
|
||||||
@@ -88,25 +91,27 @@ class Configuration:
|
|||||||
:return: Configuration dictionary
|
:return: Configuration dictionary
|
||||||
"""
|
"""
|
||||||
# Load all configs
|
# Load all configs
|
||||||
config: Dict[str, Any] = self.load_from_files(self.args["config"])
|
config: Dict[str, Any] = self.load_from_files(self.args.get("config", []))
|
||||||
|
|
||||||
# Keep a copy of the original configuration file
|
# Keep a copy of the original configuration file
|
||||||
config['original_config'] = deepcopy(config)
|
config['original_config'] = deepcopy(config)
|
||||||
|
|
||||||
|
self._process_runmode(config)
|
||||||
|
|
||||||
self._process_common_options(config)
|
self._process_common_options(config)
|
||||||
|
|
||||||
|
self._process_trading_options(config)
|
||||||
|
|
||||||
self._process_optimize_options(config)
|
self._process_optimize_options(config)
|
||||||
|
|
||||||
self._process_plot_options(config)
|
self._process_plot_options(config)
|
||||||
|
|
||||||
self._process_runmode(config)
|
|
||||||
|
|
||||||
# Check if the exchange set by the user is supported
|
# Check if the exchange set by the user is supported
|
||||||
check_exchange(config, config.get('experimental', {}).get('block_bad_exchanges', True))
|
check_exchange(config, config.get('experimental', {}).get('block_bad_exchanges', True))
|
||||||
|
|
||||||
self._resolve_pairs_list(config)
|
self._resolve_pairs_list(config)
|
||||||
|
|
||||||
validate_config_consistency(config)
|
process_temporary_deprecated_settings(config)
|
||||||
|
|
||||||
return config
|
return config
|
||||||
|
|
||||||
@@ -123,21 +128,9 @@ class Configuration:
|
|||||||
|
|
||||||
setup_logging(config)
|
setup_logging(config)
|
||||||
|
|
||||||
def _process_common_options(self, config: Dict[str, Any]) -> None:
|
def _process_trading_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
if config['runmode'] not in TRADING_MODES:
|
||||||
self._process_logging_options(config)
|
return
|
||||||
|
|
||||||
# Set strategy if not specified in config and or if it's non default
|
|
||||||
if self.args.get("strategy") != constants.DEFAULT_STRATEGY or not config.get('strategy'):
|
|
||||||
config.update({'strategy': self.args.get("strategy")})
|
|
||||||
|
|
||||||
self._args_to_config(config, argname='strategy_path',
|
|
||||||
logstring='Using additional Strategy lookup path: {}')
|
|
||||||
|
|
||||||
if ('db_url' in self.args and self.args["db_url"] and
|
|
||||||
self.args["db_url"] != constants.DEFAULT_DB_PROD_URL):
|
|
||||||
config.update({'db_url': self.args["db_url"]})
|
|
||||||
logger.info('Parameter --db-url detected ...')
|
|
||||||
|
|
||||||
if config.get('dry_run', False):
|
if config.get('dry_run', False):
|
||||||
logger.info('Dry run is enabled')
|
logger.info('Dry run is enabled')
|
||||||
@@ -151,17 +144,33 @@ class Configuration:
|
|||||||
|
|
||||||
logger.info(f'Using DB: "{config["db_url"]}"')
|
logger.info(f'Using DB: "{config["db_url"]}"')
|
||||||
|
|
||||||
|
def _process_common_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
self._process_logging_options(config)
|
||||||
|
|
||||||
|
# Set strategy if not specified in config and or if it's non default
|
||||||
|
if self.args.get("strategy") or not config.get('strategy'):
|
||||||
|
config.update({'strategy': self.args.get("strategy")})
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='strategy_path',
|
||||||
|
logstring='Using additional Strategy lookup path: {}')
|
||||||
|
|
||||||
|
if ('db_url' in self.args and self.args["db_url"] and
|
||||||
|
self.args["db_url"] != constants.DEFAULT_DB_PROD_URL):
|
||||||
|
config.update({'db_url': self.args["db_url"]})
|
||||||
|
logger.info('Parameter --db-url detected ...')
|
||||||
|
|
||||||
if config.get('forcebuy_enable', False):
|
if config.get('forcebuy_enable', False):
|
||||||
logger.warning('`forcebuy` RPC message enabled.')
|
logger.warning('`forcebuy` RPC message enabled.')
|
||||||
|
|
||||||
# Setting max_open_trades to infinite if -1
|
|
||||||
if config.get('max_open_trades') == -1:
|
|
||||||
config['max_open_trades'] = float('inf')
|
|
||||||
|
|
||||||
# Support for sd_notify
|
# Support for sd_notify
|
||||||
if 'sd_notify' in self.args and self.args["sd_notify"]:
|
if 'sd_notify' in self.args and self.args["sd_notify"]:
|
||||||
config['internals'].update({'sd_notify': True})
|
config['internals'].update({'sd_notify': True})
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='dry_run',
|
||||||
|
logstring='Parameter --dry-run detected, '
|
||||||
|
'overriding dry_run to: {} ...')
|
||||||
|
|
||||||
def _process_datadir_options(self, config: Dict[str, Any]) -> None:
|
def _process_datadir_options(self, config: Dict[str, Any]) -> None:
|
||||||
"""
|
"""
|
||||||
Extract information for sys.argv and load directory configurations
|
Extract information for sys.argv and load directory configurations
|
||||||
@@ -172,6 +181,9 @@ class Configuration:
|
|||||||
config['exchange']['name'] = self.args["exchange"]
|
config['exchange']['name'] = self.args["exchange"]
|
||||||
logger.info(f"Using exchange {config['exchange']['name']}")
|
logger.info(f"Using exchange {config['exchange']['name']}")
|
||||||
|
|
||||||
|
if 'pair_whitelist' not in config['exchange']:
|
||||||
|
config['exchange']['pair_whitelist'] = []
|
||||||
|
|
||||||
if 'user_data_dir' in self.args and self.args["user_data_dir"]:
|
if 'user_data_dir' in self.args and self.args["user_data_dir"]:
|
||||||
config.update({'user_data_dir': self.args["user_data_dir"]})
|
config.update({'user_data_dir': self.args["user_data_dir"]})
|
||||||
elif 'user_data_dir' not in config:
|
elif 'user_data_dir' not in config:
|
||||||
@@ -185,6 +197,13 @@ class Configuration:
|
|||||||
config.update({'datadir': create_datadir(config, self.args.get("datadir", None))})
|
config.update({'datadir': create_datadir(config, self.args.get("datadir", None))})
|
||||||
logger.info('Using data directory: %s ...', config.get('datadir'))
|
logger.info('Using data directory: %s ...', config.get('datadir'))
|
||||||
|
|
||||||
|
if self.args.get('exportfilename'):
|
||||||
|
self._args_to_config(config, argname='exportfilename',
|
||||||
|
logstring='Storing backtest results to {} ...')
|
||||||
|
else:
|
||||||
|
config['exportfilename'] = (config['user_data_dir']
|
||||||
|
/ 'backtest_results/backtest-result.json')
|
||||||
|
|
||||||
def _process_optimize_options(self, config: Dict[str, Any]) -> None:
|
def _process_optimize_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
# This will override the strategy configuration
|
# This will override the strategy configuration
|
||||||
@@ -195,21 +214,29 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname='position_stacking',
|
self._args_to_config(config, argname='position_stacking',
|
||||||
logstring='Parameter --enable-position-stacking detected ...')
|
logstring='Parameter --enable-position-stacking detected ...')
|
||||||
|
|
||||||
|
# Setting max_open_trades to infinite if -1
|
||||||
|
if config.get('max_open_trades') == -1:
|
||||||
|
config['max_open_trades'] = float('inf')
|
||||||
|
|
||||||
if 'use_max_market_positions' in self.args and not self.args["use_max_market_positions"]:
|
if 'use_max_market_positions' in self.args and not self.args["use_max_market_positions"]:
|
||||||
config.update({'use_max_market_positions': False})
|
config.update({'use_max_market_positions': False})
|
||||||
logger.info('Parameter --disable-max-market-positions detected ...')
|
logger.info('Parameter --disable-max-market-positions detected ...')
|
||||||
logger.info('max_open_trades set to unlimited ...')
|
logger.info('max_open_trades set to unlimited ...')
|
||||||
elif 'max_open_trades' in self.args and self.args["max_open_trades"]:
|
elif 'max_open_trades' in self.args and self.args["max_open_trades"]:
|
||||||
config.update({'max_open_trades': self.args["max_open_trades"]})
|
config.update({'max_open_trades': self.args["max_open_trades"]})
|
||||||
logger.info('Parameter --max_open_trades detected, '
|
logger.info('Parameter --max-open-trades detected, '
|
||||||
'overriding max_open_trades to: %s ...', config.get('max_open_trades'))
|
'overriding max_open_trades to: %s ...', config.get('max_open_trades'))
|
||||||
else:
|
elif config['runmode'] in NON_UTIL_MODES:
|
||||||
logger.info('Using max_open_trades: %s ...', config.get('max_open_trades'))
|
logger.info('Using max_open_trades: %s ...', config.get('max_open_trades'))
|
||||||
|
|
||||||
self._args_to_config(config, argname='stake_amount',
|
self._args_to_config(config, argname='stake_amount',
|
||||||
logstring='Parameter --stake_amount detected, '
|
logstring='Parameter --stake-amount detected, '
|
||||||
'overriding stake_amount to: {} ...')
|
'overriding stake_amount to: {} ...')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='fee',
|
||||||
|
logstring='Parameter --fee detected, '
|
||||||
|
'setting fee to: {} ...')
|
||||||
|
|
||||||
self._args_to_config(config, argname='timerange',
|
self._args_to_config(config, argname='timerange',
|
||||||
logstring='Parameter --timerange detected: {} ...')
|
logstring='Parameter --timerange detected: {} ...')
|
||||||
|
|
||||||
@@ -224,9 +251,6 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname='export',
|
self._args_to_config(config, argname='export',
|
||||||
logstring='Parameter --export detected: {} ...')
|
logstring='Parameter --export detected: {} ...')
|
||||||
|
|
||||||
self._args_to_config(config, argname='exportfilename',
|
|
||||||
logstring='Storing backtest results to {} ...')
|
|
||||||
|
|
||||||
# Edge section:
|
# Edge section:
|
||||||
if 'stoploss_range' in self.args and self.args["stoploss_range"]:
|
if 'stoploss_range' in self.args and self.args["stoploss_range"]:
|
||||||
txt_range = eval(self.args["stoploss_range"])
|
txt_range = eval(self.args["stoploss_range"])
|
||||||
@@ -277,6 +301,21 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname='hyperopt_loss',
|
self._args_to_config(config, argname='hyperopt_loss',
|
||||||
logstring='Using Hyperopt loss class name: {}')
|
logstring='Using Hyperopt loss class name: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_show_index',
|
||||||
|
logstring='Parameter -n/--index detected: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_list_best',
|
||||||
|
logstring='Parameter --best detected: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_list_profitable',
|
||||||
|
logstring='Parameter --profitable detected: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_list_no_details',
|
||||||
|
logstring='Parameter --no-details detected: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_show_no_header',
|
||||||
|
logstring='Parameter --no-header detected: {}')
|
||||||
|
|
||||||
def _process_plot_options(self, config: Dict[str, Any]) -> None:
|
def _process_plot_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
self._args_to_config(config, argname='pairs',
|
self._args_to_config(config, argname='pairs',
|
||||||
@@ -301,6 +340,8 @@ class Configuration:
|
|||||||
|
|
||||||
self._args_to_config(config, argname='days',
|
self._args_to_config(config, argname='days',
|
||||||
logstring='Detected --days: {}')
|
logstring='Detected --days: {}')
|
||||||
|
self._args_to_config(config, argname='download_trades',
|
||||||
|
logstring='Detected --dl-trades: {}')
|
||||||
|
|
||||||
def _process_runmode(self, config: Dict[str, Any]) -> None:
|
def _process_runmode(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
@@ -323,7 +364,8 @@ class Configuration:
|
|||||||
sample: logfun=len (prints the length of the found
|
sample: logfun=len (prints the length of the found
|
||||||
configuration instead of the content)
|
configuration instead of the content)
|
||||||
"""
|
"""
|
||||||
if argname in self.args and self.args[argname]:
|
if (argname in self.args and self.args[argname] is not None
|
||||||
|
and self.args[argname] is not False):
|
||||||
|
|
||||||
config.update({argname: self.args[argname]})
|
config.update({argname: self.args[argname]})
|
||||||
if logfun:
|
if logfun:
|
||||||
@@ -362,7 +404,7 @@ class Configuration:
|
|||||||
config['pairs'] = config.get('exchange', {}).get('pair_whitelist')
|
config['pairs'] = config.get('exchange', {}).get('pair_whitelist')
|
||||||
else:
|
else:
|
||||||
# Fall back to /dl_path/pairs.json
|
# Fall back to /dl_path/pairs.json
|
||||||
pairs_file = Path(config['datadir']) / "pairs.json"
|
pairs_file = config['datadir'] / "pairs.json"
|
||||||
if pairs_file.exists():
|
if pairs_file.exists():
|
||||||
with pairs_file.open('r') as f:
|
with pairs_file.open('r') as f:
|
||||||
config['pairs'] = json_load(f)
|
config['pairs'] = json_load(f)
|
||||||
|
|||||||
92
freqtrade/configuration/deprecated_settings.py
Normal file
92
freqtrade/configuration/deprecated_settings.py
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
"""
|
||||||
|
Functions to handle deprecated settings
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any, Dict
|
||||||
|
|
||||||
|
from freqtrade.exceptions import OperationalException
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def check_conflicting_settings(config: Dict[str, Any],
|
||||||
|
section1: str, name1: str,
|
||||||
|
section2: str, name2: str):
|
||||||
|
section1_config = config.get(section1, {})
|
||||||
|
section2_config = config.get(section2, {})
|
||||||
|
if name1 in section1_config and name2 in section2_config:
|
||||||
|
raise OperationalException(
|
||||||
|
f"Conflicting settings `{section1}.{name1}` and `{section2}.{name2}` "
|
||||||
|
"(DEPRECATED) detected in the configuration file. "
|
||||||
|
"This deprecated setting will be removed in the next versions of Freqtrade. "
|
||||||
|
f"Please delete it from your configuration and use the `{section1}.{name1}` "
|
||||||
|
"setting instead."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def process_deprecated_setting(config: Dict[str, Any],
|
||||||
|
section1: str, name1: str,
|
||||||
|
section2: str, name2: str):
|
||||||
|
section2_config = config.get(section2, {})
|
||||||
|
|
||||||
|
if name2 in section2_config:
|
||||||
|
logger.warning(
|
||||||
|
"DEPRECATED: "
|
||||||
|
f"The `{section2}.{name2}` setting is deprecated and "
|
||||||
|
"will be removed in the next versions of Freqtrade. "
|
||||||
|
f"Please use the `{section1}.{name1}` setting in your configuration instead."
|
||||||
|
)
|
||||||
|
section1_config = config.get(section1, {})
|
||||||
|
section1_config[name1] = section2_config[name2]
|
||||||
|
|
||||||
|
|
||||||
|
def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
check_conflicting_settings(config, 'ask_strategy', 'use_sell_signal',
|
||||||
|
'experimental', 'use_sell_signal')
|
||||||
|
check_conflicting_settings(config, 'ask_strategy', 'sell_profit_only',
|
||||||
|
'experimental', 'sell_profit_only')
|
||||||
|
check_conflicting_settings(config, 'ask_strategy', 'ignore_roi_if_buy_signal',
|
||||||
|
'experimental', 'ignore_roi_if_buy_signal')
|
||||||
|
|
||||||
|
process_deprecated_setting(config, 'ask_strategy', 'use_sell_signal',
|
||||||
|
'experimental', 'use_sell_signal')
|
||||||
|
process_deprecated_setting(config, 'ask_strategy', 'sell_profit_only',
|
||||||
|
'experimental', 'sell_profit_only')
|
||||||
|
process_deprecated_setting(config, 'ask_strategy', 'ignore_roi_if_buy_signal',
|
||||||
|
'experimental', 'ignore_roi_if_buy_signal')
|
||||||
|
|
||||||
|
if not config.get('pairlists') and not config.get('pairlists'):
|
||||||
|
config['pairlists'] = [{'method': 'StaticPairList'}]
|
||||||
|
logger.warning(
|
||||||
|
"DEPRECATED: "
|
||||||
|
"Pairlists must be defined explicitly in the future."
|
||||||
|
"Defaulting to StaticPairList for now.")
|
||||||
|
|
||||||
|
if config.get('pairlist', {}).get("method") == 'VolumePairList':
|
||||||
|
logger.warning(
|
||||||
|
"DEPRECATED: "
|
||||||
|
f"Using VolumePairList in pairlist is deprecated and must be moved to pairlists. "
|
||||||
|
"Please refer to the docs on configuration details")
|
||||||
|
pl = {'method': 'VolumePairList'}
|
||||||
|
pl.update(config.get('pairlist', {}).get('config'))
|
||||||
|
config['pairlists'].append(pl)
|
||||||
|
|
||||||
|
if config.get('pairlist', {}).get('config', {}).get('precision_filter'):
|
||||||
|
logger.warning(
|
||||||
|
"DEPRECATED: "
|
||||||
|
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."
|
||||||
|
)
|
||||||
@@ -1,13 +1,15 @@
|
|||||||
import logging
|
import logging
|
||||||
from typing import Any, Dict, Optional
|
import shutil
|
||||||
from pathlib import Path
|
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__)
|
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")
|
folder = Path(datadir) if datadir else Path(f"{config['user_data_dir']}/data")
|
||||||
if not datadir:
|
if not datadir:
|
||||||
@@ -18,7 +20,7 @@ def create_datadir(config: Dict[str, Any], datadir: Optional[str] = None) -> str
|
|||||||
if not folder.is_dir():
|
if not folder.is_dir():
|
||||||
folder.mkdir(parents=True)
|
folder.mkdir(parents=True)
|
||||||
logger.info(f'Created data directory: {datadir}')
|
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=False) -> Path:
|
||||||
@@ -31,7 +33,8 @@ def create_userdata_dir(directory: str, create_dir=False) -> Path:
|
|||||||
:param create_dir: Create directory if it does not exist.
|
:param create_dir: Create directory if it does not exist.
|
||||||
:return: Path object containing the directory
|
:return: Path object containing the directory
|
||||||
"""
|
"""
|
||||||
sub_dirs = ["backtest_results", "data", "hyperopts", "hyperopt_results", "plot", "strategies", ]
|
sub_dirs = ["backtest_results", "data", "hyperopts", "hyperopt_results", "notebooks",
|
||||||
|
"plot", "strategies", ]
|
||||||
folder = Path(directory)
|
folder = Path(directory)
|
||||||
if not folder.is_dir():
|
if not folder.is_dir():
|
||||||
if create_dir:
|
if create_dir:
|
||||||
@@ -48,3 +51,26 @@ def create_userdata_dir(directory: str, create_dir=False) -> Path:
|
|||||||
if not subfolder.is_dir():
|
if not subfolder.is_dir():
|
||||||
subfolder.mkdir(parents=False)
|
subfolder.mkdir(parents=False)
|
||||||
return folder
|
return folder
|
||||||
|
|
||||||
|
|
||||||
|
def copy_sample_files(directory: Path, overwrite: bool = False) -> None:
|
||||||
|
"""
|
||||||
|
Copy files from templates to User data directory.
|
||||||
|
:param directory: Directory to copy data to
|
||||||
|
:param overwrite: Overwrite existing sample files
|
||||||
|
"""
|
||||||
|
if not directory.is_dir():
|
||||||
|
raise OperationalException(f"Directory `{directory}` does not exist.")
|
||||||
|
sourcedir = Path(__file__).parents[1] / "templates"
|
||||||
|
for source, target in USER_DATA_FILES.items():
|
||||||
|
targetdir = directory / target
|
||||||
|
if not targetdir.is_dir():
|
||||||
|
raise OperationalException(f"Directory `{targetdir}` does not exist.")
|
||||||
|
targetfile = targetdir / source
|
||||||
|
if targetfile.exists():
|
||||||
|
if not overwrite:
|
||||||
|
logger.warning(f"File `{targetfile}` exists already, not deploying sample file.")
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
logger.warning(f"File `{targetfile}` exists already, overwriting.")
|
||||||
|
shutil.copy(str(sourcedir / source), str(targetfile))
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import logging
|
|||||||
import sys
|
import sys
|
||||||
from typing import Any, Dict
|
from typing import Any, Dict
|
||||||
|
|
||||||
from freqtrade import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
"""
|
"""
|
||||||
This module contains the argument manager class
|
This module contains the argument manager class
|
||||||
"""
|
"""
|
||||||
|
import logging
|
||||||
import re
|
import re
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
import arrow
|
import arrow
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class TimeRange:
|
class TimeRange:
|
||||||
"""
|
"""
|
||||||
@@ -27,6 +30,34 @@ class TimeRange:
|
|||||||
return (self.starttype == other.starttype and self.stoptype == other.stoptype
|
return (self.starttype == other.starttype and self.stoptype == other.stoptype
|
||||||
and self.startts == other.startts and self.stopts == other.stopts)
|
and self.startts == other.startts and self.stopts == other.stopts)
|
||||||
|
|
||||||
|
def subtract_start(self, seconds) -> None:
|
||||||
|
"""
|
||||||
|
Subtracts <seconds> from startts if startts is set.
|
||||||
|
:param seconds: Seconds to subtract from starttime
|
||||||
|
:return: None (Modifies the object in place)
|
||||||
|
"""
|
||||||
|
if self.startts:
|
||||||
|
self.startts = self.startts - seconds
|
||||||
|
|
||||||
|
def adjust_start_if_necessary(self, timeframe_secs: int, startup_candles: int,
|
||||||
|
min_date: arrow.Arrow) -> None:
|
||||||
|
"""
|
||||||
|
Adjust startts by <startup_candles> candles.
|
||||||
|
Applies only if no startup-candles have been available.
|
||||||
|
:param timeframe_secs: Ticker timeframe in seconds e.g. `timeframe_to_seconds('5m')`
|
||||||
|
:param startup_candles: Number of candles to move start-date forward
|
||||||
|
:param min_date: Minimum data date loaded. Key kriterium to decide if start-time
|
||||||
|
has to be moved
|
||||||
|
:return: None (Modifies the object in place)
|
||||||
|
"""
|
||||||
|
if (not self.starttype or (startup_candles
|
||||||
|
and min_date.timestamp >= self.startts)):
|
||||||
|
# If no startts was defined, or backtest-data starts at the defined backtest-date
|
||||||
|
logger.warning("Moving start-date by %s candles to account for startup time.",
|
||||||
|
startup_candles)
|
||||||
|
self.startts = (min_date.timestamp + timeframe_secs * startup_candles)
|
||||||
|
self.starttype = 'date'
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def parse_timerange(text: Optional[str]):
|
def parse_timerange(text: Optional[str]):
|
||||||
"""
|
"""
|
||||||
@@ -42,9 +73,10 @@ class TimeRange:
|
|||||||
(r'^-(\d{10})$', (None, 'date')),
|
(r'^-(\d{10})$', (None, 'date')),
|
||||||
(r'^(\d{10})-$', ('date', None)),
|
(r'^(\d{10})-$', ('date', None)),
|
||||||
(r'^(\d{10})-(\d{10})$', ('date', 'date')),
|
(r'^(\d{10})-(\d{10})$', ('date', 'date')),
|
||||||
(r'^(-\d+)$', (None, 'line')),
|
(r'^-(\d{13})$', (None, 'date')),
|
||||||
(r'^(\d+)-$', ('line', None)),
|
(r'^(\d{13})-$', ('date', None)),
|
||||||
(r'^(\d+)-(\d+)$', ('index', 'index'))]
|
(r'^(\d{13})-(\d{13})$', ('date', 'date')),
|
||||||
|
]
|
||||||
for rex, stype in syntax:
|
for rex, stype in syntax:
|
||||||
# Apply the regular expression to text
|
# Apply the regular expression to text
|
||||||
match = re.match(rex, text)
|
match = re.match(rex, text)
|
||||||
@@ -57,6 +89,8 @@ class TimeRange:
|
|||||||
starts = rvals[index]
|
starts = rvals[index]
|
||||||
if stype[0] == 'date' and len(starts) == 8:
|
if stype[0] == 'date' and len(starts) == 8:
|
||||||
start = arrow.get(starts, 'YYYYMMDD').timestamp
|
start = arrow.get(starts, 'YYYYMMDD').timestamp
|
||||||
|
elif len(starts) == 13:
|
||||||
|
start = int(starts) // 1000
|
||||||
else:
|
else:
|
||||||
start = int(starts)
|
start = int(starts)
|
||||||
index += 1
|
index += 1
|
||||||
@@ -64,6 +98,8 @@ class TimeRange:
|
|||||||
stops = rvals[index]
|
stops = rvals[index]
|
||||||
if stype[1] == 'date' and len(stops) == 8:
|
if stype[1] == 'date' and len(stops) == 8:
|
||||||
stop = arrow.get(stops, 'YYYYMMDD').timestamp
|
stop = arrow.get(stops, 'YYYYMMDD').timestamp
|
||||||
|
elif len(stops) == 13:
|
||||||
|
stop = int(stops) // 1000
|
||||||
else:
|
else:
|
||||||
stop = int(stops)
|
stop = int(stops)
|
||||||
return TimeRange(stype[0], stype[1], start, stop)
|
return TimeRange(stype[0], stype[1], start, stop)
|
||||||
|
|||||||
@@ -6,29 +6,32 @@ bot constants
|
|||||||
DEFAULT_CONFIG = 'config.json'
|
DEFAULT_CONFIG = 'config.json'
|
||||||
DEFAULT_EXCHANGE = 'bittrex'
|
DEFAULT_EXCHANGE = 'bittrex'
|
||||||
PROCESS_THROTTLE_SECS = 5 # sec
|
PROCESS_THROTTLE_SECS = 5 # sec
|
||||||
DEFAULT_TICKER_INTERVAL = 5 # min
|
|
||||||
HYPEROPT_EPOCH = 100 # epochs
|
HYPEROPT_EPOCH = 100 # epochs
|
||||||
RETRY_TIMEOUT = 30 # sec
|
RETRY_TIMEOUT = 30 # sec
|
||||||
DEFAULT_STRATEGY = 'DefaultStrategy'
|
|
||||||
DEFAULT_HYPEROPT = 'DefaultHyperOpts'
|
|
||||||
DEFAULT_HYPEROPT_LOSS = 'DefaultHyperOptLoss'
|
DEFAULT_HYPEROPT_LOSS = 'DefaultHyperOptLoss'
|
||||||
DEFAULT_DB_PROD_URL = 'sqlite:///tradesv3.sqlite'
|
DEFAULT_DB_PROD_URL = 'sqlite:///tradesv3.sqlite'
|
||||||
DEFAULT_DB_DRYRUN_URL = 'sqlite://'
|
DEFAULT_DB_DRYRUN_URL = 'sqlite:///tradesv3.dryrun.sqlite'
|
||||||
UNLIMITED_STAKE_AMOUNT = 'unlimited'
|
UNLIMITED_STAKE_AMOUNT = 'unlimited'
|
||||||
DEFAULT_AMOUNT_RESERVE_PERCENT = 0.05
|
DEFAULT_AMOUNT_RESERVE_PERCENT = 0.05
|
||||||
REQUIRED_ORDERTIF = ['buy', 'sell']
|
REQUIRED_ORDERTIF = ['buy', 'sell']
|
||||||
REQUIRED_ORDERTYPES = ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
REQUIRED_ORDERTYPES = ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
||||||
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
||||||
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
||||||
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList']
|
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList', 'PrecisionFilter', 'PriceFilter']
|
||||||
DRY_RUN_WALLET = 999.9
|
DRY_RUN_WALLET = 1000
|
||||||
MATH_CLOSE_PREC = 1e-14 # Precision used for float comparisons
|
MATH_CLOSE_PREC = 1e-14 # Precision used for float comparisons
|
||||||
|
|
||||||
TICKER_INTERVALS = [
|
USERPATH_HYPEROPTS = 'hyperopts'
|
||||||
'1m', '3m', '5m', '15m', '30m',
|
USERPATH_STRATEGY = 'strategies'
|
||||||
'1h', '2h', '4h', '6h', '8h', '12h',
|
|
||||||
'1d', '3d', '1w',
|
# Soure files with destination directories within user-directory
|
||||||
]
|
USER_DATA_FILES = {
|
||||||
|
'sample_strategy.py': USERPATH_STRATEGY,
|
||||||
|
'sample_hyperopt_advanced.py': USERPATH_HYPEROPTS,
|
||||||
|
'sample_hyperopt_loss.py': USERPATH_HYPEROPTS,
|
||||||
|
'sample_hyperopt.py': USERPATH_HYPEROPTS,
|
||||||
|
'strategy_analysis_example.ipynb': 'notebooks',
|
||||||
|
}
|
||||||
|
|
||||||
SUPPORTED_FIAT = [
|
SUPPORTED_FIAT = [
|
||||||
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK",
|
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK",
|
||||||
@@ -56,17 +59,27 @@ MINIMAL_CONFIG = {
|
|||||||
CONF_SCHEMA = {
|
CONF_SCHEMA = {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'max_open_trades': {'type': 'integer', 'minimum': -1},
|
'max_open_trades': {'type': ['integer', 'number'], 'minimum': -1},
|
||||||
'ticker_interval': {'type': 'string', 'enum': TICKER_INTERVALS},
|
'ticker_interval': {'type': 'string'},
|
||||||
'stake_currency': {'type': 'string', 'enum': ['BTC', 'XBT', 'ETH', 'USDT', 'EUR', 'USD']},
|
'stake_currency': {'type': 'string'},
|
||||||
'stake_amount': {
|
'stake_amount': {
|
||||||
"type": ["number", "string"],
|
'type': ['number', 'string'],
|
||||||
"minimum": 0.0005,
|
'minimum': 0.0001,
|
||||||
"pattern": UNLIMITED_STAKE_AMOUNT
|
'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},
|
'fiat_display_currency': {'type': 'string', 'enum': SUPPORTED_FIAT},
|
||||||
'dry_run': {'type': 'boolean'},
|
'dry_run': {'type': 'boolean'},
|
||||||
'dry_run_wallet': {'type': 'number'},
|
'dry_run_wallet': {'type': 'number', 'default': DRY_RUN_WALLET},
|
||||||
'process_only_new_candles': {'type': 'boolean'},
|
'process_only_new_candles': {'type': 'boolean'},
|
||||||
'minimal_roi': {
|
'minimal_roi': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
@@ -84,8 +97,8 @@ CONF_SCHEMA = {
|
|||||||
'unfilledtimeout': {
|
'unfilledtimeout': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'buy': {'type': 'number', 'minimum': 3},
|
'buy': {'type': 'number', 'minimum': 1},
|
||||||
'sell': {'type': 'number', 'minimum': 10}
|
'sell': {'type': 'number', 'minimum': 1}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
'bid_strategy': {
|
'bid_strategy': {
|
||||||
@@ -97,7 +110,7 @@ CONF_SCHEMA = {
|
|||||||
'maximum': 1,
|
'maximum': 1,
|
||||||
'exclusiveMaximum': False,
|
'exclusiveMaximum': False,
|
||||||
'use_order_book': {'type': 'boolean'},
|
'use_order_book': {'type': 'boolean'},
|
||||||
'order_book_top': {'type': 'number', 'maximum': 20, 'minimum': 1},
|
'order_book_top': {'type': 'integer', 'maximum': 20, 'minimum': 1},
|
||||||
'check_depth_of_market': {
|
'check_depth_of_market': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
@@ -113,8 +126,11 @@ CONF_SCHEMA = {
|
|||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'use_order_book': {'type': 'boolean'},
|
'use_order_book': {'type': 'boolean'},
|
||||||
'order_book_min': {'type': 'number', 'minimum': 1},
|
'order_book_min': {'type': 'integer', 'minimum': 1},
|
||||||
'order_book_max': {'type': 'number', 'minimum': 1, 'maximum': 50}
|
'order_book_max': {'type': 'integer', 'minimum': 1, 'maximum': 50},
|
||||||
|
'use_sell_signal': {'type': 'boolean'},
|
||||||
|
'sell_profit_only': {'type': 'boolean'},
|
||||||
|
'ignore_roi_if_buy_signal': {'type': 'boolean'}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
'order_types': {
|
'order_types': {
|
||||||
@@ -144,16 +160,20 @@ CONF_SCHEMA = {
|
|||||||
'properties': {
|
'properties': {
|
||||||
'use_sell_signal': {'type': 'boolean'},
|
'use_sell_signal': {'type': 'boolean'},
|
||||||
'sell_profit_only': {'type': 'boolean'},
|
'sell_profit_only': {'type': 'boolean'},
|
||||||
'ignore_roi_if_buy_signal_true': {'type': 'boolean'}
|
'ignore_roi_if_buy_signal': {'type': 'boolean'},
|
||||||
|
'block_bad_exchanges': {'type': 'boolean'}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
'pairlist': {
|
'pairlists': {
|
||||||
'type': 'object',
|
'type': 'array',
|
||||||
'properties': {
|
'items': {
|
||||||
'method': {'type': 'string', 'enum': AVAILABLE_PAIRLISTS},
|
'type': 'object',
|
||||||
'config': {'type': 'object'}
|
'properties': {
|
||||||
},
|
'method': {'type': 'string', 'enum': AVAILABLE_PAIRLISTS},
|
||||||
'required': ['method']
|
'config': {'type': 'object'}
|
||||||
|
},
|
||||||
|
'required': ['method'],
|
||||||
|
}
|
||||||
},
|
},
|
||||||
'telegram': {
|
'telegram': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
@@ -180,8 +200,8 @@ CONF_SCHEMA = {
|
|||||||
'listen_ip_address': {'format': 'ipv4'},
|
'listen_ip_address': {'format': 'ipv4'},
|
||||||
'listen_port': {
|
'listen_port': {
|
||||||
'type': 'integer',
|
'type': 'integer',
|
||||||
"minimum": 1024,
|
'minimum': 1024,
|
||||||
"maximum": 65535
|
'maximum': 65535
|
||||||
},
|
},
|
||||||
'username': {'type': 'string'},
|
'username': {'type': 'string'},
|
||||||
'password': {'type': 'string'},
|
'password': {'type': 'string'},
|
||||||
@@ -194,7 +214,7 @@ CONF_SCHEMA = {
|
|||||||
'internals': {
|
'internals': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'process_throttle_secs': {'type': 'number'},
|
'process_throttle_secs': {'type': 'integer'},
|
||||||
'interval': {'type': 'integer'},
|
'interval': {'type': 'integer'},
|
||||||
'sd_notify': {'type': 'boolean'},
|
'sd_notify': {'type': 'boolean'},
|
||||||
}
|
}
|
||||||
@@ -231,37 +251,46 @@ CONF_SCHEMA = {
|
|||||||
'ccxt_config': {'type': 'object'},
|
'ccxt_config': {'type': 'object'},
|
||||||
'ccxt_async_config': {'type': 'object'}
|
'ccxt_async_config': {'type': 'object'}
|
||||||
},
|
},
|
||||||
'required': ['name', 'pair_whitelist']
|
'required': ['name']
|
||||||
},
|
},
|
||||||
'edge': {
|
'edge': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
"enabled": {'type': 'boolean'},
|
'enabled': {'type': 'boolean'},
|
||||||
"process_throttle_secs": {'type': 'integer', 'minimum': 600},
|
'process_throttle_secs': {'type': 'integer', 'minimum': 600},
|
||||||
"calculate_since_number_of_days": {'type': 'integer'},
|
'calculate_since_number_of_days': {'type': 'integer'},
|
||||||
"allowed_risk": {'type': 'number'},
|
'allowed_risk': {'type': 'number'},
|
||||||
"capital_available_percentage": {'type': 'number'},
|
'capital_available_percentage': {'type': 'number'},
|
||||||
"stoploss_range_min": {'type': 'number'},
|
'stoploss_range_min': {'type': 'number'},
|
||||||
"stoploss_range_max": {'type': 'number'},
|
'stoploss_range_max': {'type': 'number'},
|
||||||
"stoploss_range_step": {'type': 'number'},
|
'stoploss_range_step': {'type': 'number'},
|
||||||
"minimum_winrate": {'type': 'number'},
|
'minimum_winrate': {'type': 'number'},
|
||||||
"minimum_expectancy": {'type': 'number'},
|
'minimum_expectancy': {'type': 'number'},
|
||||||
"min_trade_number": {'type': 'number'},
|
'min_trade_number': {'type': 'number'},
|
||||||
"max_trade_duration_minute": {'type': 'integer'},
|
'max_trade_duration_minute': {'type': 'integer'},
|
||||||
"remove_pumps": {'type': 'boolean'}
|
'remove_pumps': {'type': 'boolean'}
|
||||||
},
|
},
|
||||||
'required': ['process_throttle_secs', 'allowed_risk', 'capital_available_percentage']
|
'required': ['process_throttle_secs', 'allowed_risk']
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
'anyOf': [
|
|
||||||
{'required': ['exchange']}
|
|
||||||
],
|
|
||||||
'required': [
|
|
||||||
'max_open_trades',
|
|
||||||
'stake_currency',
|
|
||||||
'stake_amount',
|
|
||||||
'dry_run',
|
|
||||||
'bid_strategy',
|
|
||||||
'telegram'
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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',
|
||||||
|
]
|
||||||
|
|
||||||
|
SCHEMA_MINIMAL_REQUIRED = [
|
||||||
|
'exchange',
|
||||||
|
'dry_run',
|
||||||
|
]
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from typing import Dict
|
|||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pytz
|
from datetime import timezone
|
||||||
|
|
||||||
from freqtrade import persistence
|
from freqtrade import persistence
|
||||||
from freqtrade.misc import json_load
|
from freqtrade.misc import json_load
|
||||||
@@ -47,21 +47,23 @@ def load_backtest_data(filename) -> pd.DataFrame:
|
|||||||
utc=True,
|
utc=True,
|
||||||
infer_datetime_format=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)
|
df = df.sort_values("open_time").reset_index(drop=True)
|
||||||
return df
|
return df
|
||||||
|
|
||||||
|
|
||||||
def evaluate_result_multi(results: pd.DataFrame, freq: str, max_open_trades: int) -> pd.DataFrame:
|
def analyze_trade_parallelism(results: pd.DataFrame, timeframe: str) -> pd.DataFrame:
|
||||||
"""
|
"""
|
||||||
Find overlapping trades by expanding each trade once per period it was open
|
Find overlapping trades by expanding each trade once per period it was open
|
||||||
and then counting overlaps
|
and then counting overlaps.
|
||||||
:param results: Results Dataframe - can be loaded
|
:param results: Results Dataframe - can be loaded
|
||||||
:param freq: Frequency used for the backtest
|
:param timeframe: Timeframe used for backtest
|
||||||
:param max_open_trades: parameter max_open_trades used during backtest run
|
:return: dataframe with open-counts per time-period in timeframe
|
||||||
:return: dataframe with open-counts per time-period in freq
|
|
||||||
"""
|
"""
|
||||||
dates = [pd.Series(pd.date_range(row[1].open_time, row[1].close_time, freq=freq))
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
timeframe_min = timeframe_to_minutes(timeframe)
|
||||||
|
dates = [pd.Series(pd.date_range(row[1].open_time, row[1].close_time,
|
||||||
|
freq=f"{timeframe_min}min"))
|
||||||
for row in results[['open_time', 'close_time']].iterrows()]
|
for row in results[['open_time', 'close_time']].iterrows()]
|
||||||
deltas = [len(x) for x in dates]
|
deltas = [len(x) for x in dates]
|
||||||
dates = pd.Series(pd.concat(dates).values, name='date')
|
dates = pd.Series(pd.concat(dates).values, name='date')
|
||||||
@@ -69,8 +71,23 @@ def evaluate_result_multi(results: pd.DataFrame, freq: str, max_open_trades: int
|
|||||||
|
|
||||||
df2 = pd.concat([dates, df2], axis=1)
|
df2 = pd.concat([dates, df2], axis=1)
|
||||||
df2 = df2.set_index('date')
|
df2 = df2.set_index('date')
|
||||||
df_final = df2.resample(freq)[['pair']].count()
|
df_final = df2.resample(f"{timeframe_min}min")[['pair']].count()
|
||||||
return df_final[df_final['pair'] > max_open_trades]
|
df_final = df_final.rename({'pair': 'open_trades'}, axis=1)
|
||||||
|
return df_final
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_result_multi(results: pd.DataFrame, timeframe: str,
|
||||||
|
max_open_trades: int) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Find overlapping trades by expanding each trade once per period it was open
|
||||||
|
and then counting overlaps
|
||||||
|
:param results: Results Dataframe - can be loaded
|
||||||
|
:param timeframe: Frequency used for the backtest
|
||||||
|
:param max_open_trades: parameter max_open_trades used during backtest run
|
||||||
|
:return: dataframe with open-counts per time-period in freq
|
||||||
|
"""
|
||||||
|
df_final = analyze_trade_parallelism(results, timeframe)
|
||||||
|
return df_final[df_final['open_trades'] > max_open_trades]
|
||||||
|
|
||||||
|
|
||||||
def load_trades_from_db(db_url: str) -> pd.DataFrame:
|
def load_trades_from_db(db_url: str) -> pd.DataFrame:
|
||||||
@@ -89,11 +106,11 @@ def load_trades_from_db(db_url: str) -> pd.DataFrame:
|
|||||||
"stop_loss", "initial_stop_loss", "strategy", "ticker_interval"]
|
"stop_loss", "initial_stop_loss", "strategy", "ticker_interval"]
|
||||||
|
|
||||||
trades = pd.DataFrame([(t.pair,
|
trades = pd.DataFrame([(t.pair,
|
||||||
t.open_date.replace(tzinfo=pytz.UTC),
|
t.open_date.replace(tzinfo=timezone.utc),
|
||||||
t.close_date.replace(tzinfo=pytz.UTC) if t.close_date else None,
|
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,
|
t.open_rate, t.close_rate, t.amount,
|
||||||
(t.close_date.timestamp() - t.open_date.timestamp()
|
(round((t.close_date.timestamp() - t.open_date.timestamp()) / 60, 2)
|
||||||
if t.close_date else None),
|
if t.close_date else None),
|
||||||
t.sell_reason,
|
t.sell_reason,
|
||||||
t.fee_open, t.fee_close,
|
t.fee_open, t.fee_close,
|
||||||
@@ -106,7 +123,7 @@ def load_trades_from_db(db_url: str) -> pd.DataFrame:
|
|||||||
t.stop_loss, t.initial_stop_loss,
|
t.stop_loss, t.initial_stop_loss,
|
||||||
t.strategy, t.ticker_interval
|
t.strategy, t.ticker_interval
|
||||||
)
|
)
|
||||||
for t in Trade.query.all()],
|
for t in Trade.get_trades().all()],
|
||||||
columns=columns)
|
columns=columns)
|
||||||
|
|
||||||
return trades
|
return trades
|
||||||
@@ -150,15 +167,21 @@ def combine_tickers_with_mean(tickers: Dict[str, pd.DataFrame], column: str = "c
|
|||||||
return df_comb
|
return df_comb
|
||||||
|
|
||||||
|
|
||||||
def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str) -> pd.DataFrame:
|
def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str,
|
||||||
|
timeframe: str) -> pd.DataFrame:
|
||||||
"""
|
"""
|
||||||
Adds a column `col_name` with the cumulative profit for the given trades array.
|
Adds a column `col_name` with the cumulative profit for the given trades array.
|
||||||
:param df: DataFrame with date index
|
:param df: DataFrame with date index
|
||||||
:param trades: DataFrame containing trades (requires columns close_time and profitperc)
|
:param trades: DataFrame containing trades (requires columns close_time and profitperc)
|
||||||
|
:param col_name: Column name that will be assigned the results
|
||||||
|
:param timeframe: Timeframe used during the operations
|
||||||
:return: Returns df with one additional column, col_name, containing the cumulative profit.
|
:return: Returns df with one additional column, col_name, containing the cumulative profit.
|
||||||
"""
|
"""
|
||||||
# Use groupby/sum().cumsum() to avoid errors when multiple trades sold at the same candle.
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
df[col_name] = trades.groupby('close_time')['profitperc'].sum().cumsum()
|
timeframe_minutes = timeframe_to_minutes(timeframe)
|
||||||
|
# Resample to timeframe to make sure trades match candles
|
||||||
|
_trades_sum = trades.resample(f'{timeframe_minutes}min', on='close_time')[['profitperc']].sum()
|
||||||
|
df.loc[:, col_name] = _trades_sum.cumsum()
|
||||||
# Set first value to 0
|
# Set first value to 0
|
||||||
df.loc[df.iloc[0].name, col_name] = 0
|
df.loc[df.iloc[0].name, col_name] = 0
|
||||||
# FFill to get continuous
|
# FFill to get continuous
|
||||||
|
|||||||
@@ -10,13 +10,13 @@ from pandas import DataFrame, to_datetime
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def parse_ticker_dataframe(ticker: list, ticker_interval: str, pair: str, *,
|
def parse_ticker_dataframe(ticker: list, timeframe: str, pair: str, *,
|
||||||
fill_missing: bool = True,
|
fill_missing: bool = True,
|
||||||
drop_incomplete: bool = True) -> DataFrame:
|
drop_incomplete: bool = True) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Converts a ticker-list (format ccxt.fetch_ohlcv) to a Dataframe
|
Converts a ticker-list (format ccxt.fetch_ohlcv) to a Dataframe
|
||||||
:param ticker: ticker list, as returned by exchange.async_get_candle_history
|
:param ticker: ticker list, as returned by exchange.async_get_candle_history
|
||||||
:param ticker_interval: ticker_interval (e.g. 5m). Used to fill up eventual missing 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 pair: Pair this data is for (used to warn if fillup was necessary)
|
||||||
:param fill_missing: fill up missing candles with 0 candles
|
:param fill_missing: fill up missing candles with 0 candles
|
||||||
(see ohlcv_fill_up_missing_data for details)
|
(see ohlcv_fill_up_missing_data for details)
|
||||||
@@ -52,12 +52,12 @@ def parse_ticker_dataframe(ticker: list, ticker_interval: str, pair: str, *,
|
|||||||
logger.debug('Dropping last candle')
|
logger.debug('Dropping last candle')
|
||||||
|
|
||||||
if fill_missing:
|
if fill_missing:
|
||||||
return ohlcv_fill_up_missing_data(frame, ticker_interval, pair)
|
return ohlcv_fill_up_missing_data(frame, timeframe, pair)
|
||||||
else:
|
else:
|
||||||
return frame
|
return frame
|
||||||
|
|
||||||
|
|
||||||
def ohlcv_fill_up_missing_data(dataframe: DataFrame, ticker_interval: str, pair: str) -> DataFrame:
|
def ohlcv_fill_up_missing_data(dataframe: DataFrame, timeframe: str, pair: str) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Fills up missing data with 0 volume rows,
|
Fills up missing data with 0 volume rows,
|
||||||
using the previous close as price for "open", "high" "low" and "close", volume is set to 0
|
using the previous close as price for "open", "high" "low" and "close", volume is set to 0
|
||||||
@@ -72,7 +72,7 @@ def ohlcv_fill_up_missing_data(dataframe: DataFrame, ticker_interval: str, pair:
|
|||||||
'close': 'last',
|
'close': 'last',
|
||||||
'volume': 'sum'
|
'volume': 'sum'
|
||||||
}
|
}
|
||||||
ticker_minutes = timeframe_to_minutes(ticker_interval)
|
ticker_minutes = timeframe_to_minutes(timeframe)
|
||||||
# Resample to create "NAN" values
|
# Resample to create "NAN" values
|
||||||
df = dataframe.resample(f'{ticker_minutes}min', on='date').agg(ohlc_dict)
|
df = dataframe.resample(f'{ticker_minutes}min', on='date').agg(ohlc_dict)
|
||||||
|
|
||||||
@@ -114,3 +114,25 @@ def order_book_to_dataframe(bids: list, asks: list) -> DataFrame:
|
|||||||
keys=['b_sum', 'b_size', 'bids', 'asks', 'a_size', 'a_sum'])
|
keys=['b_sum', 'b_size', 'bids', 'asks', 'a_size', 'a_sum'])
|
||||||
# logger.info('order book %s', frame )
|
# logger.info('order book %s', frame )
|
||||||
return frame
|
return frame
|
||||||
|
|
||||||
|
|
||||||
|
def trades_to_ohlcv(trades: list, timeframe: str) -> list:
|
||||||
|
"""
|
||||||
|
Converts trades list to ohlcv list
|
||||||
|
: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)
|
||||||
|
"""
|
||||||
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
ticker_minutes = timeframe_to_minutes(timeframe)
|
||||||
|
df = pd.DataFrame(trades)
|
||||||
|
df['datetime'] = pd.to_datetime(df['datetime'])
|
||||||
|
df = df.set_index('datetime')
|
||||||
|
|
||||||
|
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
|
||||||
|
# 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]))
|
||||||
|
|||||||
@@ -5,8 +5,7 @@ including Klines, tickers, historic data
|
|||||||
Common Interface for bot and strategy to access data.
|
Common Interface for bot and strategy to access data.
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
from pathlib import Path
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
from typing import List, Tuple
|
|
||||||
|
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
@@ -37,54 +36,63 @@ class DataProvider:
|
|||||||
@property
|
@property
|
||||||
def available_pairs(self) -> List[Tuple[str, str]]:
|
def available_pairs(self) -> List[Tuple[str, str]]:
|
||||||
"""
|
"""
|
||||||
Return a list of tuples containing pair, ticker_interval for which data is currently cached.
|
Return a list of tuples containing (pair, timeframe) for which data is currently cached.
|
||||||
Should be whitelist + open trades.
|
Should be whitelist + open trades.
|
||||||
"""
|
"""
|
||||||
return list(self._exchange._klines.keys())
|
return list(self._exchange._klines.keys())
|
||||||
|
|
||||||
def ohlcv(self, pair: str, ticker_interval: str = None, copy: bool = True) -> DataFrame:
|
def ohlcv(self, pair: str, timeframe: str = None, copy: bool = True) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Get ohlcv data for the given pair as DataFrame
|
Get ohlcv data for the given pair as DataFrame
|
||||||
Please use the `available_pairs` method to verify which pairs are currently cached.
|
Please use the `available_pairs` method to verify which pairs are currently cached.
|
||||||
:param pair: pair to get the data for
|
:param pair: pair to get the data for
|
||||||
:param ticker_interval: ticker interval to get data for
|
:param timeframe: Ticker timeframe to get data for
|
||||||
:param copy: copy dataframe before returning if True.
|
:param copy: copy dataframe before returning if True.
|
||||||
Use False only for read-only operations (where the dataframe is not modified)
|
Use False only for read-only operations (where the dataframe is not modified)
|
||||||
"""
|
"""
|
||||||
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
||||||
return self._exchange.klines((pair, ticker_interval or self._config['ticker_interval']),
|
return self._exchange.klines((pair, timeframe or self._config['ticker_interval']),
|
||||||
copy=copy)
|
copy=copy)
|
||||||
else:
|
else:
|
||||||
return DataFrame()
|
return DataFrame()
|
||||||
|
|
||||||
def historic_ohlcv(self, pair: str, ticker_interval: str = None) -> DataFrame:
|
def historic_ohlcv(self, pair: str, timeframe: str = None) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Get stored historic ohlcv data
|
Get stored historic ohlcv data
|
||||||
:param pair: pair to get the data for
|
:param pair: pair to get the data for
|
||||||
:param ticker_interval: ticker interval to get data for
|
:param timeframe: timeframe to get data for
|
||||||
"""
|
"""
|
||||||
return load_pair_history(pair=pair,
|
return load_pair_history(pair=pair,
|
||||||
ticker_interval=ticker_interval or self._config['ticker_interval'],
|
timeframe=timeframe or self._config['ticker_interval'],
|
||||||
datadir=Path(self._config['datadir'])
|
datadir=self._config['datadir']
|
||||||
)
|
)
|
||||||
|
|
||||||
def get_pair_dataframe(self, pair: str, ticker_interval: str = None) -> DataFrame:
|
def get_pair_dataframe(self, pair: str, timeframe: str = None) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Return pair ohlcv data, either live or cached historical -- depending
|
Return pair ohlcv data, either live or cached historical -- depending
|
||||||
on the runmode.
|
on the runmode.
|
||||||
:param pair: pair to get the data for
|
:param pair: pair to get the data for
|
||||||
:param ticker_interval: ticker interval to get data for
|
:param timeframe: timeframe to get data for
|
||||||
|
:return: Dataframe for this pair
|
||||||
"""
|
"""
|
||||||
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
||||||
# Get live ohlcv data.
|
# Get live ohlcv data.
|
||||||
data = self.ohlcv(pair=pair, ticker_interval=ticker_interval)
|
data = self.ohlcv(pair=pair, timeframe=timeframe)
|
||||||
else:
|
else:
|
||||||
# Get historic ohlcv data (cached on disk).
|
# Get historic ohlcv data (cached on disk).
|
||||||
data = self.historic_ohlcv(pair=pair, ticker_interval=ticker_interval)
|
data = self.historic_ohlcv(pair=pair, timeframe=timeframe)
|
||||||
if len(data) == 0:
|
if len(data) == 0:
|
||||||
logger.warning(f"No data found for ({pair}, {ticker_interval}).")
|
logger.warning(f"No data found for ({pair}, {timeframe}).")
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
def market(self, pair: str) -> Optional[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Return market data for the pair
|
||||||
|
:param pair: Pair to get the data for
|
||||||
|
:return: Market data dict from ccxt or None if market info is not available for the pair
|
||||||
|
"""
|
||||||
|
return self._exchange.markets.get(pair)
|
||||||
|
|
||||||
def ticker(self, pair: str):
|
def ticker(self, pair: str):
|
||||||
"""
|
"""
|
||||||
Return last ticker data
|
Return last ticker data
|
||||||
@@ -92,9 +100,9 @@ class DataProvider:
|
|||||||
# TODO: Implement me
|
# TODO: Implement me
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def orderbook(self, pair: str, maximum: int):
|
def orderbook(self, pair: str, maximum: int) -> Dict[str, List]:
|
||||||
"""
|
"""
|
||||||
return latest orderbook data
|
fetch latest orderbook data
|
||||||
:param pair: pair to get the data for
|
:param pair: pair to get the data for
|
||||||
:param maximum: Maximum number of orderbook entries to query
|
:param maximum: Maximum number of orderbook entries to query
|
||||||
:return: dict including bids/asks with a total of `maximum` entries.
|
:return: dict including bids/asks with a total of `maximum` entries.
|
||||||
|
|||||||
@@ -8,17 +8,20 @@ Includes:
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
import operator
|
import operator
|
||||||
from datetime import datetime
|
from copy import deepcopy
|
||||||
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, List, Optional, Tuple
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
import arrow
|
import arrow
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
from freqtrade import OperationalException, misc
|
from freqtrade import misc
|
||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.data.converter import parse_ticker_dataframe
|
from freqtrade.data.converter import parse_ticker_dataframe, trades_to_ohlcv
|
||||||
from freqtrade.exchange import Exchange, timeframe_to_minutes
|
from freqtrade.exceptions import OperationalException
|
||||||
|
from freqtrade.exchange import (Exchange, timeframe_to_minutes,
|
||||||
|
timeframe_to_seconds)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -33,20 +36,12 @@ def trim_tickerlist(tickerlist: List[Dict], timerange: TimeRange) -> List[Dict]:
|
|||||||
start_index = 0
|
start_index = 0
|
||||||
stop_index = len(tickerlist)
|
stop_index = len(tickerlist)
|
||||||
|
|
||||||
if timerange.starttype == 'line':
|
if timerange.starttype == 'date':
|
||||||
stop_index = timerange.startts
|
|
||||||
if timerange.starttype == 'index':
|
|
||||||
start_index = timerange.startts
|
|
||||||
elif timerange.starttype == 'date':
|
|
||||||
while (start_index < len(tickerlist) and
|
while (start_index < len(tickerlist) and
|
||||||
tickerlist[start_index][0] < timerange.startts * 1000):
|
tickerlist[start_index][0] < timerange.startts * 1000):
|
||||||
start_index += 1
|
start_index += 1
|
||||||
|
|
||||||
if timerange.stoptype == 'line':
|
if timerange.stoptype == 'date':
|
||||||
start_index = max(len(tickerlist) + timerange.stopts, 0)
|
|
||||||
if timerange.stoptype == 'index':
|
|
||||||
stop_index = timerange.stopts
|
|
||||||
elif timerange.stoptype == 'date':
|
|
||||||
while (stop_index > 0 and
|
while (stop_index > 0 and
|
||||||
tickerlist[stop_index-1][0] > timerange.stopts * 1000):
|
tickerlist[stop_index-1][0] > timerange.stopts * 1000):
|
||||||
stop_index -= 1
|
stop_index -= 1
|
||||||
@@ -57,13 +52,30 @@ def trim_tickerlist(tickerlist: List[Dict], timerange: TimeRange) -> List[Dict]:
|
|||||||
return tickerlist[start_index:stop_index]
|
return tickerlist[start_index:stop_index]
|
||||||
|
|
||||||
|
|
||||||
def load_tickerdata_file(datadir: Path, pair: str, ticker_interval: str,
|
def trim_dataframe(df: DataFrame, timerange: TimeRange, df_date_col: str = 'date') -> DataFrame:
|
||||||
timerange: Optional[TimeRange] = None) -> Optional[list]:
|
"""
|
||||||
|
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) -> List[Dict]:
|
||||||
"""
|
"""
|
||||||
Load a pair from file, either .json.gz or .json
|
Load a pair from file, either .json.gz or .json
|
||||||
:return: tickerlist or None if unsuccessful
|
:return: tickerlist or None if unsuccessful
|
||||||
"""
|
"""
|
||||||
filename = pair_data_filename(datadir, pair, ticker_interval)
|
filename = pair_data_filename(datadir, pair, timeframe)
|
||||||
pairdata = misc.file_load_json(filename)
|
pairdata = misc.file_load_json(filename)
|
||||||
if not pairdata:
|
if not pairdata:
|
||||||
return []
|
return []
|
||||||
@@ -74,108 +86,164 @@ def load_tickerdata_file(datadir: Path, pair: str, ticker_interval: str,
|
|||||||
|
|
||||||
|
|
||||||
def store_tickerdata_file(datadir: Path, pair: str,
|
def store_tickerdata_file(datadir: Path, pair: str,
|
||||||
ticker_interval: str, data: list, is_zip: bool = False):
|
timeframe: str, data: list, is_zip: bool = False):
|
||||||
"""
|
"""
|
||||||
Stores tickerdata to file
|
Stores tickerdata to file
|
||||||
"""
|
"""
|
||||||
filename = pair_data_filename(datadir, pair, ticker_interval)
|
filename = pair_data_filename(datadir, pair, timeframe)
|
||||||
misc.file_dump_json(filename, data, is_zip=is_zip)
|
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,
|
def load_pair_history(pair: str,
|
||||||
ticker_interval: str,
|
timeframe: str,
|
||||||
datadir: Path,
|
datadir: Path,
|
||||||
timerange: TimeRange = TimeRange(None, None, 0, 0),
|
timerange: Optional[TimeRange] = None,
|
||||||
refresh_pairs: bool = False,
|
|
||||||
exchange: Optional[Exchange] = None,
|
|
||||||
fill_up_missing: bool = True,
|
fill_up_missing: bool = True,
|
||||||
drop_incomplete: bool = True
|
drop_incomplete: bool = True,
|
||||||
|
startup_candles: int = 0,
|
||||||
) -> DataFrame:
|
) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Loads cached ticker history for the given pair.
|
Load cached ticker history for the given pair.
|
||||||
|
|
||||||
:param pair: Pair to load data for
|
:param pair: Pair to load data for
|
||||||
:param ticker_interval: Ticker-interval (e.g. "5m")
|
:param timeframe: Ticker timeframe (e.g. "5m")
|
||||||
:param datadir: Path to the data storage location.
|
:param datadir: Path to the data storage location.
|
||||||
:param timerange: Limit data to be loaded to this timerange
|
: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 fill_up_missing: Fill missing values with "No action"-candles
|
||||||
:param drop_incomplete: Drop last candle assuming it may be incomplete.
|
:param drop_incomplete: Drop last candle assuming it may be incomplete.
|
||||||
:return: DataFrame with ohlcv data
|
: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
|
pairdata = load_tickerdata_file(datadir, pair, timeframe, timerange=timerange_startup)
|
||||||
if refresh_pairs:
|
|
||||||
download_pair_history(datadir=datadir,
|
|
||||||
exchange=exchange,
|
|
||||||
pair=pair,
|
|
||||||
ticker_interval=ticker_interval,
|
|
||||||
timerange=timerange)
|
|
||||||
|
|
||||||
pairdata = load_tickerdata_file(datadir, pair, ticker_interval, timerange=timerange)
|
|
||||||
|
|
||||||
if pairdata:
|
if pairdata:
|
||||||
if timerange.starttype == 'date' and pairdata[0][0] > timerange.startts * 1000:
|
if timerange_startup:
|
||||||
logger.warning('Missing data at start for pair %s, data starts at %s',
|
_validate_pairdata(pair, pairdata, timerange_startup)
|
||||||
pair, arrow.get(pairdata[0][0] // 1000).strftime('%Y-%m-%d %H:%M:%S'))
|
return parse_ticker_dataframe(pairdata, timeframe, pair=pair,
|
||||||
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'))
|
|
||||||
return parse_ticker_dataframe(pairdata, ticker_interval, pair=pair,
|
|
||||||
fill_missing=fill_up_missing,
|
fill_missing=fill_up_missing,
|
||||||
drop_incomplete=drop_incomplete)
|
drop_incomplete=drop_incomplete)
|
||||||
else:
|
else:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f'No history data for pair: "{pair}", interval: {ticker_interval}. '
|
f'No history data for pair: "{pair}", timeframe: {timeframe}. '
|
||||||
'Use `freqtrade download-data` to download the data'
|
'Use `freqtrade download-data` to download the data'
|
||||||
)
|
)
|
||||||
return None
|
return DataFrame()
|
||||||
|
|
||||||
|
|
||||||
def load_data(datadir: Path,
|
def load_data(datadir: Path,
|
||||||
ticker_interval: str,
|
timeframe: str,
|
||||||
pairs: List[str],
|
pairs: List[str],
|
||||||
refresh_pairs: bool = False,
|
timerange: Optional[TimeRange] = None,
|
||||||
exchange: Optional[Exchange] = None,
|
|
||||||
timerange: TimeRange = TimeRange(None, None, 0, 0),
|
|
||||||
fill_up_missing: bool = True,
|
fill_up_missing: bool = True,
|
||||||
|
startup_candles: int = 0,
|
||||||
|
fail_without_data: bool = False
|
||||||
) -> Dict[str, DataFrame]:
|
) -> Dict[str, DataFrame]:
|
||||||
"""
|
"""
|
||||||
Loads ticker history data for a list of pairs
|
Load ticker history data for a list of pairs.
|
||||||
:return: dict(<pair>:<tickerlist>)
|
|
||||||
TODO: refresh_pairs is still used by edge to keep the data uptodate.
|
:param datadir: Path to the data storage location.
|
||||||
This should be replaced in the future. Instead, writing the current candles to disk
|
:param timeframe: Ticker Timeframe (e.g. "5m")
|
||||||
from dataprovider should be implemented, as this would avoid loading ohlcv data twice.
|
:param pairs: List of pairs to load
|
||||||
exchange and refresh_pairs are then not needed here nor in load_pair_history.
|
: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>)
|
||||||
"""
|
"""
|
||||||
result: Dict[str, DataFrame] = {}
|
result: Dict[str, DataFrame] = {}
|
||||||
|
if startup_candles > 0 and timerange:
|
||||||
|
logger.info(f'Using indicator startup period: {startup_candles} ...')
|
||||||
|
|
||||||
for pair in pairs:
|
for pair in pairs:
|
||||||
hist = load_pair_history(pair=pair, ticker_interval=ticker_interval,
|
hist = load_pair_history(pair=pair, timeframe=timeframe,
|
||||||
datadir=datadir, timerange=timerange,
|
datadir=datadir, timerange=timerange,
|
||||||
refresh_pairs=refresh_pairs,
|
fill_up_missing=fill_up_missing,
|
||||||
exchange=exchange,
|
startup_candles=startup_candles)
|
||||||
fill_up_missing=fill_up_missing)
|
if not hist.empty:
|
||||||
if hist is not None:
|
|
||||||
result[pair] = hist
|
result[pair] = hist
|
||||||
|
|
||||||
|
if fail_without_data and not result:
|
||||||
|
raise OperationalException("No data found. Terminating.")
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def pair_data_filename(datadir: Path, pair: str, ticker_interval: str) -> Path:
|
def refresh_data(datadir: Path,
|
||||||
|
timeframe: str,
|
||||||
|
pairs: List[str],
|
||||||
|
exchange: Exchange,
|
||||||
|
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
|
||||||
|
"""
|
||||||
|
for pair in pairs:
|
||||||
|
_download_pair_history(pair=pair, timeframe=timeframe,
|
||||||
|
datadir=datadir, timerange=timerange,
|
||||||
|
exchange=exchange)
|
||||||
|
|
||||||
|
|
||||||
|
def pair_data_filename(datadir: Path, pair: str, timeframe: str) -> Path:
|
||||||
pair_s = pair.replace("/", "_")
|
pair_s = pair.replace("/", "_")
|
||||||
filename = datadir.joinpath(f'{pair_s}-{ticker_interval}.json')
|
filename = datadir.joinpath(f'{pair_s}-{timeframe}.json')
|
||||||
return filename
|
return filename
|
||||||
|
|
||||||
|
|
||||||
def load_cached_data_for_updating(datadir: Path, pair: str, ticker_interval: str,
|
def pair_trades_filename(datadir: Path, pair: str) -> Path:
|
||||||
timerange: Optional[TimeRange]) -> Tuple[List[Any],
|
pair_s = pair.replace("/", "_")
|
||||||
Optional[int]]:
|
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.
|
Load cached data to download more data.
|
||||||
If timerange is passed in, checks wether data from an before the stored data will be downloaded.
|
If timerange is passed in, checks whether data from an before the stored data will be
|
||||||
If that's the case than what's available should be completely overwritten.
|
downloaded.
|
||||||
|
If that's the case then what's available should be completely overwritten.
|
||||||
Only used by download_pair_history().
|
Only used by download_pair_history().
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -186,12 +254,12 @@ def load_cached_data_for_updating(datadir: Path, pair: str, ticker_interval: str
|
|||||||
if timerange.starttype == 'date':
|
if timerange.starttype == 'date':
|
||||||
since_ms = timerange.startts * 1000
|
since_ms = timerange.startts * 1000
|
||||||
elif timerange.stoptype == 'line':
|
elif timerange.stoptype == 'line':
|
||||||
num_minutes = timerange.stopts * timeframe_to_minutes(ticker_interval)
|
num_minutes = timerange.stopts * timeframe_to_minutes(timeframe)
|
||||||
since_ms = arrow.utcnow().shift(minutes=num_minutes).timestamp * 1000
|
since_ms = arrow.utcnow().shift(minutes=num_minutes).timestamp * 1000
|
||||||
|
|
||||||
# read the cached file
|
# read the cached file
|
||||||
# Intentionally don't pass timerange in - since we need to load the full dataset.
|
# Intentionally don't pass timerange in - since we need to load the full dataset.
|
||||||
data = load_tickerdata_file(datadir, pair, ticker_interval)
|
data = load_tickerdata_file(datadir, pair, timeframe)
|
||||||
# remove the last item, could be incomplete candle
|
# remove the last item, could be incomplete candle
|
||||||
if data:
|
if data:
|
||||||
data.pop()
|
data.pop()
|
||||||
@@ -209,69 +277,65 @@ def load_cached_data_for_updating(datadir: Path, pair: str, ticker_interval: str
|
|||||||
return (data, since_ms)
|
return (data, since_ms)
|
||||||
|
|
||||||
|
|
||||||
def download_pair_history(datadir: Path,
|
def _download_pair_history(datadir: Path,
|
||||||
exchange: Optional[Exchange],
|
exchange: Exchange,
|
||||||
pair: str,
|
pair: str,
|
||||||
ticker_interval: str = '5m',
|
timeframe: str = '5m',
|
||||||
timerange: Optional[TimeRange] = None) -> bool:
|
timerange: Optional[TimeRange] = None) -> bool:
|
||||||
"""
|
"""
|
||||||
Download the latest ticker intervals from the exchange for the pair passed in parameters
|
Download latest candles from the exchange for the pair and timeframe passed in parameters
|
||||||
The data is downloaded starting from the last correct ticker interval data that
|
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,
|
exists in a cache. If timerange starts earlier than the data in the cache,
|
||||||
the full data will be redownloaded
|
the full data will be redownloaded
|
||||||
|
|
||||||
Based on @Rybolov work: https://github.com/rybolov/freqtrade-data
|
Based on @Rybolov work: https://github.com/rybolov/freqtrade-data
|
||||||
|
|
||||||
:param pair: pair to download
|
:param pair: pair to download
|
||||||
:param ticker_interval: ticker interval
|
:param timeframe: Ticker Timeframe (e.g 5m)
|
||||||
:param timerange: range of time to download
|
:param timerange: range of time to download
|
||||||
:return: bool with success state
|
:return: bool with success state
|
||||||
"""
|
"""
|
||||||
if not exchange:
|
|
||||||
raise OperationalException(
|
|
||||||
"Exchange needs to be initialized when downloading pair history data"
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
logger.info(
|
logger.info(
|
||||||
f'Download history data for pair: "{pair}", interval: {ticker_interval} '
|
f'Download history data for pair: "{pair}", timeframe: {timeframe} '
|
||||||
f'and store in {datadir}.'
|
f'and store in {datadir}.'
|
||||||
)
|
)
|
||||||
|
|
||||||
data, since_ms = load_cached_data_for_updating(datadir, pair, ticker_interval, timerange)
|
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 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')
|
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
|
# Default since_ms to 30 days if nothing is given
|
||||||
new_data = exchange.get_historic_ohlcv(pair=pair, ticker_interval=ticker_interval,
|
new_data = exchange.get_historic_ohlcv(pair=pair,
|
||||||
since_ms=since_ms if since_ms
|
timeframe=timeframe,
|
||||||
else
|
since_ms=since_ms if since_ms else
|
||||||
int(arrow.utcnow().shift(
|
int(arrow.utcnow().shift(
|
||||||
days=-30).float_timestamp) * 1000)
|
days=-30).float_timestamp) * 1000
|
||||||
|
)
|
||||||
data.extend(new_data)
|
data.extend(new_data)
|
||||||
|
|
||||||
logger.debug("New Start: %s", misc.format_ms_time(data[0][0]))
|
logger.debug("New Start: %s", misc.format_ms_time(data[0][0]))
|
||||||
logger.debug("New End: %s", misc.format_ms_time(data[-1][0]))
|
logger.debug("New End: %s", misc.format_ms_time(data[-1][0]))
|
||||||
|
|
||||||
store_tickerdata_file(datadir, pair, ticker_interval, data=data)
|
store_tickerdata_file(datadir, pair, timeframe, data=data)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(
|
logger.error(
|
||||||
f'Failed to download history data for pair: "{pair}", interval: {ticker_interval}. '
|
f'Failed to download history data for pair: "{pair}", timeframe: {timeframe}. '
|
||||||
f'Error: {e}'
|
f'Error: {e}'
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes: List[str],
|
def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes: List[str],
|
||||||
dl_path: Path, timerange: TimeRange,
|
datadir: Path, timerange: Optional[TimeRange] = None,
|
||||||
erase=False) -> List[str]:
|
erase=False) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Refresh stored ohlcv data for backtesting and hyperopt operations.
|
Refresh stored ohlcv data for backtesting and hyperopt operations.
|
||||||
Used by freqtrade download-data
|
Used by freqtrade download-data subcommand.
|
||||||
:return: Pairs not available
|
:return: List of pairs that are not available.
|
||||||
"""
|
"""
|
||||||
pairs_not_available = []
|
pairs_not_available = []
|
||||||
for pair in pairs:
|
for pair in pairs:
|
||||||
@@ -279,37 +343,124 @@ def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes
|
|||||||
pairs_not_available.append(pair)
|
pairs_not_available.append(pair)
|
||||||
logger.info(f"Skipping pair {pair}...")
|
logger.info(f"Skipping pair {pair}...")
|
||||||
continue
|
continue
|
||||||
for ticker_interval in timeframes:
|
for timeframe in timeframes:
|
||||||
|
|
||||||
dl_file = pair_data_filename(dl_path, pair, ticker_interval)
|
dl_file = pair_data_filename(datadir, pair, timeframe)
|
||||||
if erase and dl_file.exists():
|
if erase and dl_file.exists():
|
||||||
logger.info(
|
logger.info(
|
||||||
f'Deleting existing data for pair {pair}, interval {ticker_interval}.')
|
f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
||||||
dl_file.unlink()
|
dl_file.unlink()
|
||||||
|
|
||||||
logger.info(f'Downloading pair {pair}, interval {ticker_interval}.')
|
logger.info(f'Downloading pair {pair}, interval {timeframe}.')
|
||||||
download_pair_history(datadir=dl_path, exchange=exchange,
|
_download_pair_history(datadir=datadir, exchange=exchange,
|
||||||
pair=pair, ticker_interval=str(ticker_interval),
|
pair=pair, timeframe=str(timeframe),
|
||||||
timerange=timerange)
|
timerange=timerange)
|
||||||
return pairs_not_available
|
return pairs_not_available
|
||||||
|
|
||||||
|
|
||||||
def get_timeframe(data: Dict[str, DataFrame]) -> Tuple[arrow.Arrow, arrow.Arrow]:
|
def _download_trades_history(datadir: Path,
|
||||||
|
exchange: Exchange,
|
||||||
|
pair: str,
|
||||||
|
timerange: Optional[TimeRange] = None) -> bool:
|
||||||
"""
|
"""
|
||||||
Get the maximum timeframe for the given backtest data
|
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')
|
||||||
|
|
||||||
|
# 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])
|
||||||
|
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 for backtesting and hyperopt operations.
|
||||||
|
Used by freqtrade download-data subcommand.
|
||||||
|
:return: List of pairs that are 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_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
|
:param data: dictionary with preprocessed backtesting data
|
||||||
:return: tuple containing min_date, max_date
|
:return: tuple containing min_date, max_date
|
||||||
"""
|
"""
|
||||||
timeframe = [
|
timeranges = [
|
||||||
(arrow.get(frame['date'].min()), arrow.get(frame['date'].max()))
|
(arrow.get(frame['date'].min()), arrow.get(frame['date'].max()))
|
||||||
for frame in data.values()
|
for frame in data.values()
|
||||||
]
|
]
|
||||||
return min(timeframe, key=operator.itemgetter(0))[0], \
|
return (min(timeranges, key=operator.itemgetter(0))[0],
|
||||||
max(timeframe, key=operator.itemgetter(1))[1]
|
max(timeranges, key=operator.itemgetter(1))[1])
|
||||||
|
|
||||||
|
|
||||||
def validate_backtest_data(data: DataFrame, pair: str, min_date: datetime,
|
def validate_backtest_data(data: DataFrame, pair: str, min_date: datetime,
|
||||||
max_date: datetime, ticker_interval_mins: int) -> bool:
|
max_date: datetime, timeframe_min: int) -> bool:
|
||||||
"""
|
"""
|
||||||
Validates preprocessed backtesting data for missing values and shows warnings about it that.
|
Validates preprocessed backtesting data for missing values and shows warnings about it that.
|
||||||
|
|
||||||
@@ -317,10 +468,10 @@ def validate_backtest_data(data: DataFrame, pair: str, min_date: datetime,
|
|||||||
:param pair: pair used for log output.
|
:param pair: pair used for log output.
|
||||||
:param min_date: start-date of the data
|
:param min_date: start-date of the data
|
||||||
:param max_date: end-date of the data
|
:param max_date: end-date of the data
|
||||||
:param ticker_interval_mins: ticker interval in minutes
|
:param timeframe_min: ticker Timeframe in minutes
|
||||||
"""
|
"""
|
||||||
# total difference in minutes / interval-minutes
|
# total difference in minutes / timeframe-minutes
|
||||||
expected_frames = int((max_date - min_date).total_seconds() // 60 // ticker_interval_mins)
|
expected_frames = int((max_date - min_date).total_seconds() // 60 // timeframe_min)
|
||||||
found_missing = False
|
found_missing = False
|
||||||
dflen = len(data)
|
dflen = len(data)
|
||||||
if dflen < expected_frames:
|
if dflen < expected_frames:
|
||||||
|
|||||||
@@ -1,453 +1 @@
|
|||||||
# pragma pylint: disable=W0603
|
from .edge_positioning import Edge, PairInfo # noqa: F401
|
||||||
""" 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'))
|
|
||||||
|
|
||||||
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,
|
|
||||||
ticker_interval=self.strategy.ticker_interval,
|
|
||||||
refresh_pairs=self._refresh_pairs,
|
|
||||||
exchange=self.exchange,
|
|
||||||
timerange=self._timerange
|
|
||||||
)
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|||||||
464
freqtrade/edge/edge_positioning.py
Normal file
464
freqtrade/edge/edge_positioning.py
Normal file
@@ -0,0 +1,464 @@
|
|||||||
|
# pragma pylint: disable=W0603
|
||||||
|
""" Edge positioning package """
|
||||||
|
import logging
|
||||||
|
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
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
|
||||||
|
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:
|
||||||
|
"""
|
||||||
|
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,13 +1,18 @@
|
|||||||
|
from freqtrade.exchange.common import MAP_EXCHANGE_CHILDCLASS # noqa: F401
|
||||||
from freqtrade.exchange.exchange import Exchange # noqa: F401
|
from freqtrade.exchange.exchange import Exchange # noqa: F401
|
||||||
from freqtrade.exchange.exchange import (get_exchange_bad_reason, # noqa: F401
|
from freqtrade.exchange.exchange import (get_exchange_bad_reason, # noqa: F401
|
||||||
is_exchange_bad,
|
is_exchange_bad,
|
||||||
is_exchange_available,
|
is_exchange_known_ccxt,
|
||||||
is_exchange_officially_supported,
|
is_exchange_officially_supported,
|
||||||
|
ccxt_exchanges,
|
||||||
available_exchanges)
|
available_exchanges)
|
||||||
from freqtrade.exchange.exchange import (timeframe_to_seconds, # noqa: F401
|
from freqtrade.exchange.exchange import (timeframe_to_seconds, # noqa: F401
|
||||||
timeframe_to_minutes,
|
timeframe_to_minutes,
|
||||||
timeframe_to_msecs,
|
timeframe_to_msecs,
|
||||||
timeframe_to_next_date,
|
timeframe_to_next_date,
|
||||||
timeframe_to_prev_date)
|
timeframe_to_prev_date)
|
||||||
|
from freqtrade.exchange.exchange import (market_is_active, # noqa: F401
|
||||||
|
symbol_is_pair)
|
||||||
from freqtrade.exchange.kraken import Kraken # noqa: F401
|
from freqtrade.exchange.kraken import Kraken # noqa: F401
|
||||||
from freqtrade.exchange.binance import Binance # noqa: F401
|
from freqtrade.exchange.binance import Binance # noqa: F401
|
||||||
|
from freqtrade.exchange.bibox import Bibox # noqa: F401
|
||||||
|
|||||||
22
freqtrade/exchange/bibox.py
Normal file
22
freqtrade/exchange/bibox.py
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
""" Bibox exchange subclass """
|
||||||
|
import logging
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
from freqtrade.exchange import Exchange
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class Bibox(Exchange):
|
||||||
|
"""
|
||||||
|
Bibox exchange class. Contains adjustments needed for Freqtrade to work
|
||||||
|
with this exchange.
|
||||||
|
|
||||||
|
Please note that this exchange is not included in the list of exchanges
|
||||||
|
officially supported by the Freqtrade development team. So some features
|
||||||
|
may still not work as expected.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# fetchCurrencies API point requires authentication for Bibox,
|
||||||
|
# so switch it off for Freqtrade load_markets()
|
||||||
|
_ccxt_config: Dict = {"has": {"fetchCurrencies": False}}
|
||||||
@@ -4,8 +4,8 @@ from typing import Dict
|
|||||||
|
|
||||||
import ccxt
|
import ccxt
|
||||||
|
|
||||||
from freqtrade import (DependencyException, InvalidOrderException,
|
from freqtrade.exceptions import (DependencyException, InvalidOrderException,
|
||||||
OperationalException, TemporaryError)
|
OperationalException, TemporaryError)
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -16,6 +16,8 @@ class Binance(Exchange):
|
|||||||
_ft_has: Dict = {
|
_ft_has: Dict = {
|
||||||
"stoploss_on_exchange": True,
|
"stoploss_on_exchange": True,
|
||||||
"order_time_in_force": ['gtc', 'fok', 'ioc'],
|
"order_time_in_force": ['gtc', 'fok', 'ioc'],
|
||||||
|
"trades_pagination": "id",
|
||||||
|
"trades_pagination_arg": "fromId",
|
||||||
}
|
}
|
||||||
|
|
||||||
def get_order_book(self, pair: str, limit: int = 100) -> dict:
|
def get_order_book(self, pair: str, limit: int = 100) -> dict:
|
||||||
@@ -39,7 +41,7 @@ class Binance(Exchange):
|
|||||||
"""
|
"""
|
||||||
ordertype = "stop_loss_limit"
|
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
|
# Ensure rate is less than stop price
|
||||||
if stop_price <= rate:
|
if stop_price <= rate:
|
||||||
@@ -55,9 +57,9 @@ class Binance(Exchange):
|
|||||||
params = self._params.copy()
|
params = self._params.copy()
|
||||||
params.update({'stopPrice': stop_price})
|
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',
|
order = self._api.create_order(pair, ordertype, 'sell',
|
||||||
amount, rate, params)
|
amount, rate, params)
|
||||||
|
|||||||
124
freqtrade/exchange/common.py
Normal file
124
freqtrade/exchange/common.py
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
import logging
|
||||||
|
|
||||||
|
from freqtrade.exceptions import DependencyException, TemporaryError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
API_RETRY_COUNT = 4
|
||||||
|
BAD_EXCHANGES = {
|
||||||
|
"bitmex": "Various reasons.",
|
||||||
|
"bitstamp": "Does not provide history. "
|
||||||
|
"Details in https://github.com/freqtrade/freqtrade/issues/1983",
|
||||||
|
"hitbtc": "This API cannot be used with Freqtrade. "
|
||||||
|
"Use `hitbtc2` exchange id to access this exchange.",
|
||||||
|
**dict.fromkeys([
|
||||||
|
'adara',
|
||||||
|
'anxpro',
|
||||||
|
'bigone',
|
||||||
|
'coinbase',
|
||||||
|
'coinexchange',
|
||||||
|
'coinmarketcap',
|
||||||
|
'lykke',
|
||||||
|
'xbtce',
|
||||||
|
], "Does not provide timeframes. ccxt fetchOHLCV: False"),
|
||||||
|
**dict.fromkeys([
|
||||||
|
'bcex',
|
||||||
|
'bit2c',
|
||||||
|
'bitbay',
|
||||||
|
'bitflyer',
|
||||||
|
'bitforex',
|
||||||
|
'bithumb',
|
||||||
|
'bitso',
|
||||||
|
'bitstamp1',
|
||||||
|
'bl3p',
|
||||||
|
'braziliex',
|
||||||
|
'btcbox',
|
||||||
|
'btcchina',
|
||||||
|
'btctradeim',
|
||||||
|
'btctradeua',
|
||||||
|
'bxinth',
|
||||||
|
'chilebit',
|
||||||
|
'coincheck',
|
||||||
|
'coinegg',
|
||||||
|
'coinfalcon',
|
||||||
|
'coinfloor',
|
||||||
|
'coingi',
|
||||||
|
'coinmate',
|
||||||
|
'coinone',
|
||||||
|
'coinspot',
|
||||||
|
'coolcoin',
|
||||||
|
'crypton',
|
||||||
|
'deribit',
|
||||||
|
'exmo',
|
||||||
|
'exx',
|
||||||
|
'flowbtc',
|
||||||
|
'foxbit',
|
||||||
|
'fybse',
|
||||||
|
# 'hitbtc',
|
||||||
|
'ice3x',
|
||||||
|
'independentreserve',
|
||||||
|
'indodax',
|
||||||
|
'itbit',
|
||||||
|
'lakebtc',
|
||||||
|
'latoken',
|
||||||
|
'liquid',
|
||||||
|
'livecoin',
|
||||||
|
'luno',
|
||||||
|
'mixcoins',
|
||||||
|
'negociecoins',
|
||||||
|
'nova',
|
||||||
|
'paymium',
|
||||||
|
'southxchange',
|
||||||
|
'stronghold',
|
||||||
|
'surbitcoin',
|
||||||
|
'therock',
|
||||||
|
'tidex',
|
||||||
|
'vaultoro',
|
||||||
|
'vbtc',
|
||||||
|
'virwox',
|
||||||
|
'yobit',
|
||||||
|
'zaif',
|
||||||
|
], "Does not provide timeframes. ccxt fetchOHLCV: emulated"),
|
||||||
|
}
|
||||||
|
|
||||||
|
MAP_EXCHANGE_CHILDCLASS = {
|
||||||
|
'binanceus': 'binance',
|
||||||
|
'binanceje': 'binance',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def retrier_async(f):
|
||||||
|
async def wrapper(*args, **kwargs):
|
||||||
|
count = kwargs.pop('count', API_RETRY_COUNT)
|
||||||
|
try:
|
||||||
|
return await f(*args, **kwargs)
|
||||||
|
except (TemporaryError, DependencyException) as ex:
|
||||||
|
logger.warning('%s() returned exception: "%s"', f.__name__, ex)
|
||||||
|
if count > 0:
|
||||||
|
count -= 1
|
||||||
|
kwargs.update({'count': count})
|
||||||
|
logger.warning('retrying %s() still for %s times', f.__name__, count)
|
||||||
|
return await wrapper(*args, **kwargs)
|
||||||
|
else:
|
||||||
|
logger.warning('Giving up retrying: %s()', f.__name__)
|
||||||
|
raise ex
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
def retrier(f):
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
count = kwargs.pop('count', API_RETRY_COUNT)
|
||||||
|
try:
|
||||||
|
return f(*args, **kwargs)
|
||||||
|
except (TemporaryError, DependencyException) as ex:
|
||||||
|
logger.warning('%s() returned exception: "%s"', f.__name__, ex)
|
||||||
|
if count > 0:
|
||||||
|
count -= 1
|
||||||
|
kwargs.update({'count': count})
|
||||||
|
logger.warning('retrying %s() still for %s times', f.__name__, count)
|
||||||
|
return wrapper(*args, **kwargs)
|
||||||
|
else:
|
||||||
|
logger.warning('Giving up retrying: %s()', f.__name__)
|
||||||
|
raise ex
|
||||||
|
return wrapper
|
||||||
@@ -7,71 +7,34 @@ import inspect
|
|||||||
import logging
|
import logging
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from math import ceil, floor
|
from math import ceil
|
||||||
from random import randint
|
from random import randint
|
||||||
from typing import Any, Dict, List, Optional, Tuple
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
import arrow
|
import arrow
|
||||||
import ccxt
|
import ccxt
|
||||||
import ccxt.async_support as ccxt_async
|
import ccxt.async_support as ccxt_async
|
||||||
from ccxt.base.decimal_to_precision import ROUND_UP, ROUND_DOWN
|
from ccxt.base.decimal_to_precision import (ROUND_DOWN, ROUND_UP, TICK_SIZE,
|
||||||
|
TRUNCATE, decimal_to_precision)
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
from freqtrade import (DependencyException, InvalidOrderException,
|
|
||||||
OperationalException, TemporaryError, constants)
|
|
||||||
from freqtrade.data.converter import parse_ticker_dataframe
|
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
|
from freqtrade.misc import deep_merge_dicts
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
API_RETRY_COUNT = 4
|
|
||||||
BAD_EXCHANGES = {
|
|
||||||
"bitmex": "Various reasons",
|
|
||||||
"bitstamp": "Does not provide history. "
|
|
||||||
"Details in https://github.com/freqtrade/freqtrade/issues/1983",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def retrier_async(f):
|
|
||||||
async def wrapper(*args, **kwargs):
|
|
||||||
count = kwargs.pop('count', API_RETRY_COUNT)
|
|
||||||
try:
|
|
||||||
return await f(*args, **kwargs)
|
|
||||||
except (TemporaryError, DependencyException) as ex:
|
|
||||||
logger.warning('%s() returned exception: "%s"', f.__name__, ex)
|
|
||||||
if count > 0:
|
|
||||||
count -= 1
|
|
||||||
kwargs.update({'count': count})
|
|
||||||
logger.warning('retrying %s() still for %s times', f.__name__, count)
|
|
||||||
return await wrapper(*args, **kwargs)
|
|
||||||
else:
|
|
||||||
logger.warning('Giving up retrying: %s()', f.__name__)
|
|
||||||
raise ex
|
|
||||||
return wrapper
|
|
||||||
|
|
||||||
|
|
||||||
def retrier(f):
|
|
||||||
def wrapper(*args, **kwargs):
|
|
||||||
count = kwargs.pop('count', API_RETRY_COUNT)
|
|
||||||
try:
|
|
||||||
return f(*args, **kwargs)
|
|
||||||
except (TemporaryError, DependencyException) as ex:
|
|
||||||
logger.warning('%s() returned exception: "%s"', f.__name__, ex)
|
|
||||||
if count > 0:
|
|
||||||
count -= 1
|
|
||||||
kwargs.update({'count': count})
|
|
||||||
logger.warning('retrying %s() still for %s times', f.__name__, count)
|
|
||||||
return wrapper(*args, **kwargs)
|
|
||||||
else:
|
|
||||||
logger.warning('Giving up retrying: %s()', f.__name__)
|
|
||||||
raise ex
|
|
||||||
return wrapper
|
|
||||||
|
|
||||||
|
|
||||||
class Exchange:
|
class Exchange:
|
||||||
|
|
||||||
_config: Dict = {}
|
_config: Dict = {}
|
||||||
|
|
||||||
|
# Parameters to add directly to ccxt sync/async initialization.
|
||||||
|
_ccxt_config: Dict = {}
|
||||||
|
|
||||||
|
# Parameters to add directly to buy/sell calls (like agreeing to trading agreement)
|
||||||
_params: Dict = {}
|
_params: Dict = {}
|
||||||
|
|
||||||
# Dict to specify which options each exchange implements
|
# Dict to specify which options each exchange implements
|
||||||
@@ -82,10 +45,13 @@ class Exchange:
|
|||||||
"order_time_in_force": ["gtc"],
|
"order_time_in_force": ["gtc"],
|
||||||
"ohlcv_candle_limit": 500,
|
"ohlcv_candle_limit": 500,
|
||||||
"ohlcv_partial_candle": True,
|
"ohlcv_partial_candle": True,
|
||||||
|
"trades_pagination": "time", # Possible are "time" or "id"
|
||||||
|
"trades_pagination_arg": "since",
|
||||||
|
|
||||||
}
|
}
|
||||||
_ft_has: Dict = {}
|
_ft_has: Dict = {}
|
||||||
|
|
||||||
def __init__(self, config: dict) -> None:
|
def __init__(self, config: dict, validate: bool = True) -> None:
|
||||||
"""
|
"""
|
||||||
Initializes this module with the given config,
|
Initializes this module with the given config,
|
||||||
it does basic validation whether the specified exchange and pairs are valid.
|
it does basic validation whether the specified exchange and pairs are valid.
|
||||||
@@ -125,28 +91,41 @@ class Exchange:
|
|||||||
self._ohlcv_candle_limit = self._ft_has['ohlcv_candle_limit']
|
self._ohlcv_candle_limit = self._ft_has['ohlcv_candle_limit']
|
||||||
self._ohlcv_partial_candle = self._ft_has['ohlcv_partial_candle']
|
self._ohlcv_partial_candle = self._ft_has['ohlcv_partial_candle']
|
||||||
|
|
||||||
|
self._trades_pagination = self._ft_has['trades_pagination']
|
||||||
|
self._trades_pagination_arg = self._ft_has['trades_pagination_arg']
|
||||||
|
|
||||||
# Initialize ccxt objects
|
# Initialize ccxt objects
|
||||||
|
ccxt_config = self._ccxt_config.copy()
|
||||||
|
ccxt_config = deep_merge_dicts(exchange_config.get('ccxt_config', {}),
|
||||||
|
ccxt_config)
|
||||||
self._api = self._init_ccxt(
|
self._api = self._init_ccxt(
|
||||||
exchange_config, ccxt_kwargs=exchange_config.get('ccxt_config'))
|
exchange_config, ccxt_kwargs=ccxt_config)
|
||||||
|
|
||||||
|
ccxt_async_config = self._ccxt_config.copy()
|
||||||
|
ccxt_async_config = deep_merge_dicts(exchange_config.get('ccxt_async_config', {}),
|
||||||
|
ccxt_async_config)
|
||||||
self._api_async = self._init_ccxt(
|
self._api_async = self._init_ccxt(
|
||||||
exchange_config, ccxt_async, ccxt_kwargs=exchange_config.get('ccxt_async_config'))
|
exchange_config, ccxt_async, ccxt_kwargs=ccxt_async_config)
|
||||||
|
|
||||||
logger.info('Using Exchange "%s"', self.name)
|
logger.info('Using Exchange "%s"', self.name)
|
||||||
|
|
||||||
|
if validate:
|
||||||
|
# Check if timeframe is available
|
||||||
|
self.validate_timeframes(config.get('ticker_interval'))
|
||||||
|
|
||||||
|
# Initial markets load
|
||||||
|
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', {}))
|
||||||
|
self.validate_required_startup_candles(config.get('startup_candle_count', 0))
|
||||||
|
|
||||||
# Converts the interval provided in minutes in config to seconds
|
# Converts the interval provided in minutes in config to seconds
|
||||||
self.markets_refresh_interval: int = exchange_config.get(
|
self.markets_refresh_interval: int = exchange_config.get(
|
||||||
"markets_refresh_interval", 60) * 60
|
"markets_refresh_interval", 60) * 60
|
||||||
# Initial markets load
|
|
||||||
self._load_markets()
|
|
||||||
|
|
||||||
# Check if all pairs are available
|
|
||||||
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', {}))
|
|
||||||
|
|
||||||
if config.get('ticker_interval'):
|
|
||||||
# Check if timeframe is available
|
|
||||||
self.validate_timeframes(config['ticker_interval'])
|
|
||||||
|
|
||||||
def __del__(self):
|
def __del__(self):
|
||||||
"""
|
"""
|
||||||
@@ -165,7 +144,7 @@ class Exchange:
|
|||||||
# Find matching class for the given exchange name
|
# Find matching class for the given exchange name
|
||||||
name = exchange_config['name']
|
name = exchange_config['name']
|
||||||
|
|
||||||
if not is_exchange_available(name, ccxt_module):
|
if not is_exchange_known_ccxt(name, ccxt_module):
|
||||||
raise OperationalException(f'Exchange {name} is not supported by ccxt')
|
raise OperationalException(f'Exchange {name} is not supported by ccxt')
|
||||||
|
|
||||||
ex_config = {
|
ex_config = {
|
||||||
@@ -199,6 +178,10 @@ class Exchange:
|
|||||||
"""exchange ccxt id"""
|
"""exchange ccxt id"""
|
||||||
return self._api.id
|
return self._api.id
|
||||||
|
|
||||||
|
@property
|
||||||
|
def timeframes(self) -> List[str]:
|
||||||
|
return list((self._api.timeframes or {}).keys())
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def markets(self) -> Dict:
|
def markets(self) -> Dict:
|
||||||
"""exchange ccxt markets"""
|
"""exchange ccxt markets"""
|
||||||
@@ -207,6 +190,40 @@ class Exchange:
|
|||||||
self._load_markets()
|
self._load_markets()
|
||||||
return self._api.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:
|
||||||
|
"""
|
||||||
|
Return exchange ccxt markets, filtered out by base currency and quote currency
|
||||||
|
if this was requested in parameters.
|
||||||
|
|
||||||
|
TODO: consider moving it to the Dataprovider
|
||||||
|
"""
|
||||||
|
markets = self.markets
|
||||||
|
if not markets:
|
||||||
|
raise OperationalException("Markets were not loaded.")
|
||||||
|
|
||||||
|
if base_currencies:
|
||||||
|
markets = {k: v for k, v in markets.items() if v['base'] in base_currencies}
|
||||||
|
if quote_currencies:
|
||||||
|
markets = {k: v for k, v in markets.items() if v['quote'] in quote_currencies}
|
||||||
|
if pairs_only:
|
||||||
|
markets = {k: v for k, v in markets.items() if symbol_is_pair(v['symbol'])}
|
||||||
|
if active_only:
|
||||||
|
markets = {k: v for k, v in markets.items() if market_is_active(v)}
|
||||||
|
return markets
|
||||||
|
|
||||||
|
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=True) -> DataFrame:
|
def klines(self, pair_interval: Tuple[str, str], copy=True) -> DataFrame:
|
||||||
if pair_interval in self._klines:
|
if pair_interval in self._klines:
|
||||||
return self._klines[pair_interval].copy() if copy else self._klines[pair_interval]
|
return self._klines[pair_interval].copy() if copy else self._klines[pair_interval]
|
||||||
@@ -256,11 +273,23 @@ class Exchange:
|
|||||||
except ccxt.BaseError:
|
except ccxt.BaseError:
|
||||||
logger.exception("Could not reload markets.")
|
logger.exception("Could not reload markets.")
|
||||||
|
|
||||||
|
def validate_stakecurrency(self, stake_currency) -> 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:
|
def validate_pairs(self, pairs: List[str]) -> None:
|
||||||
"""
|
"""
|
||||||
Checks if all given pairs are tradable on the current exchange.
|
Checks if all given pairs are tradable on the current exchange.
|
||||||
Raises OperationalException if one pair is not available.
|
|
||||||
:param pairs: list of pairs
|
:param pairs: list of pairs
|
||||||
|
:raise: OperationalException if one pair is not available
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -275,7 +304,15 @@ class Exchange:
|
|||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f'Pair {pair} is not available on {self.name}. '
|
f'Pair {pair} is not available on {self.name}. '
|
||||||
f'Please remove {pair} from your whitelist.')
|
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.
|
# Warn users about restricted pairs in whitelist.
|
||||||
# We cannot determine reliably if Users are affected.
|
# We cannot determine reliably if Users are affected.
|
||||||
logger.warning(f"Pair {pair} is restricted for some users on this exchange."
|
logger.warning(f"Pair {pair} is restricted for some users on this exchange."
|
||||||
@@ -291,7 +328,7 @@ class Exchange:
|
|||||||
return pair
|
return pair
|
||||||
raise DependencyException(f"Could not combine {curr_1} and {curr_2} to get a valid pair.")
|
raise DependencyException(f"Could not combine {curr_1} and {curr_2} to get a valid pair.")
|
||||||
|
|
||||||
def validate_timeframes(self, timeframe: List[str]) -> None:
|
def validate_timeframes(self, timeframe: Optional[str]) -> None:
|
||||||
"""
|
"""
|
||||||
Checks if ticker interval from config is a supported timeframe on the exchange
|
Checks if ticker interval from config is a supported timeframe on the exchange
|
||||||
"""
|
"""
|
||||||
@@ -304,10 +341,13 @@ class Exchange:
|
|||||||
f"for the exchange \"{self.name}\" and this exchange "
|
f"for the exchange \"{self.name}\" and this exchange "
|
||||||
f"is therefore not supported. ccxt fetchOHLCV: {self.exchange_has('fetchOHLCV')}")
|
f"is therefore not supported. ccxt fetchOHLCV: {self.exchange_has('fetchOHLCV')}")
|
||||||
|
|
||||||
timeframes = self._api.timeframes
|
if timeframe and (timeframe not in self.timeframes):
|
||||||
if timeframe not in timeframes:
|
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f'Invalid ticker {timeframe}, this Exchange supports {timeframes}')
|
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:
|
def validate_ordertypes(self, order_types: Dict) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -333,6 +373,16 @@ class Exchange:
|
|||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f'Time in force policies are not supported for {self.name} yet.')
|
f'Time in force policies are not supported for {self.name} yet.')
|
||||||
|
|
||||||
|
def validate_required_startup_candles(self, startup_candles) -> 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.
|
||||||
|
"""
|
||||||
|
if startup_candles + 5 > self._ft_has['ohlcv_candle_limit']:
|
||||||
|
raise OperationalException(
|
||||||
|
f"This strategy requires {startup_candles} candles to start. "
|
||||||
|
f"{self.name} only provides {self._ft_has['ohlcv_candle_limit']}.")
|
||||||
|
|
||||||
def exchange_has(self, endpoint: str) -> bool:
|
def exchange_has(self, endpoint: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Checks if exchange implements a specific API endpoint.
|
Checks if exchange implements a specific API endpoint.
|
||||||
@@ -342,40 +392,58 @@ class Exchange:
|
|||||||
"""
|
"""
|
||||||
return endpoint in self._api.has and self._api.has[endpoint]
|
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, amount: float) -> float:
|
||||||
'''
|
'''
|
||||||
Returns the amount to buy or sell to a precision the Exchange accepts
|
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']:
|
if self.markets[pair]['precision']['amount']:
|
||||||
symbol_prec = self.markets[pair]['precision']['amount']
|
amount = float(decimal_to_precision(amount, rounding_mode=TRUNCATE,
|
||||||
big_amount = amount * pow(10, symbol_prec)
|
precision=self.markets[pair]['precision']['amount'],
|
||||||
amount = floor(big_amount) / pow(10, symbol_prec)
|
counting_mode=self.precisionMode,
|
||||||
|
))
|
||||||
|
|
||||||
return amount
|
return amount
|
||||||
|
|
||||||
def symbol_price_prec(self, pair, price: float):
|
def price_to_precision(self, pair, 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
|
Rounds up
|
||||||
'''
|
'''
|
||||||
if self.markets[pair]['precision']['price']:
|
if self.markets[pair]['precision']['price']:
|
||||||
symbol_prec = self.markets[pair]['precision']['price']
|
# price = float(decimal_to_precision(price, rounding_mode=ROUND,
|
||||||
big_price = price * pow(10, symbol_prec)
|
# precision=self.markets[pair]['precision']['price'],
|
||||||
price = ceil(big_price) / pow(10, symbol_prec)
|
# 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)
|
||||||
return price
|
return price
|
||||||
|
|
||||||
def dry_run_order(self, pair: str, ordertype: str, side: str, amount: float,
|
def dry_run_order(self, pair: str, ordertype: str, side: str, amount: float,
|
||||||
rate: float, params: Dict = {}) -> Dict[str, Any]:
|
rate: float, params: Dict = {}) -> Dict[str, Any]:
|
||||||
order_id = f'dry_run_{side}_{randint(0, 10**6)}'
|
order_id = f'dry_run_{side}_{randint(0, 10**6)}'
|
||||||
|
_amount = self.amount_to_precision(pair, amount)
|
||||||
dry_order = {
|
dry_order = {
|
||||||
"id": order_id,
|
"id": order_id,
|
||||||
'pair': pair,
|
'pair': pair,
|
||||||
'price': rate,
|
'price': rate,
|
||||||
'amount': amount,
|
'amount': _amount,
|
||||||
"cost": amount * rate,
|
"cost": _amount * rate,
|
||||||
'type': ordertype,
|
'type': ordertype,
|
||||||
'side': side,
|
'side': side,
|
||||||
'remaining': amount,
|
'remaining': _amount,
|
||||||
'datetime': arrow.utcnow().isoformat(),
|
'datetime': arrow.utcnow().isoformat(),
|
||||||
'status': "closed" if ordertype == "market" else "open",
|
'status': "closed" if ordertype == "market" else "open",
|
||||||
'fee': None,
|
'fee': None,
|
||||||
@@ -401,13 +469,13 @@ class Exchange:
|
|||||||
rate: float, params: Dict = {}) -> Dict:
|
rate: float, params: Dict = {}) -> Dict:
|
||||||
try:
|
try:
|
||||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
# 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'
|
needs_price = (ordertype != 'market'
|
||||||
or self._api.options.get("createMarketBuyOrderRequiresPrice", False))
|
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,
|
return self._api.create_order(pair, ordertype, side,
|
||||||
amount, rate, params)
|
amount, rate_for_order, params)
|
||||||
|
|
||||||
except ccxt.InsufficientFunds as e:
|
except ccxt.InsufficientFunds as e:
|
||||||
raise DependencyException(
|
raise DependencyException(
|
||||||
@@ -466,7 +534,7 @@ class Exchange:
|
|||||||
@retrier
|
@retrier
|
||||||
def get_balance(self, currency: str) -> float:
|
def get_balance(self, currency: str) -> float:
|
||||||
if self._config['dry_run']:
|
if self._config['dry_run']:
|
||||||
return constants.DRY_RUN_WALLET
|
return self._config['dry_run_wallet']
|
||||||
|
|
||||||
# ccxt exception is already handled by get_balances
|
# ccxt exception is already handled by get_balances
|
||||||
balances = self.get_balances()
|
balances = self.get_balances()
|
||||||
@@ -511,7 +579,7 @@ class Exchange:
|
|||||||
raise OperationalException(e) from e
|
raise OperationalException(e) from e
|
||||||
|
|
||||||
@retrier
|
@retrier
|
||||||
def get_ticker(self, pair: str, refresh: Optional[bool] = True) -> dict:
|
def fetch_ticker(self, pair: str, refresh: Optional[bool] = True) -> dict:
|
||||||
if refresh or pair not in self._cached_ticker.keys():
|
if refresh or pair not in self._cached_ticker.keys():
|
||||||
try:
|
try:
|
||||||
if pair not in self._api.markets or not self._api.markets[pair].get('active'):
|
if pair not in self._api.markets or not self._api.markets[pair].get('active'):
|
||||||
@@ -534,40 +602,40 @@ class Exchange:
|
|||||||
logger.info("returning cached ticker-data for %s", pair)
|
logger.info("returning cached ticker-data for %s", pair)
|
||||||
return self._cached_ticker[pair]
|
return self._cached_ticker[pair]
|
||||||
|
|
||||||
def get_historic_ohlcv(self, pair: str, ticker_interval: str,
|
def get_historic_ohlcv(self, pair: str, timeframe: str,
|
||||||
since_ms: int) -> List:
|
since_ms: int) -> List:
|
||||||
"""
|
"""
|
||||||
Gets candle history using asyncio and returns the list of candles.
|
Gets candle history using asyncio and returns the list of candles.
|
||||||
Handles all async doing.
|
Handles all async doing.
|
||||||
Async over one pair, assuming we get `_ohlcv_candle_limit` candles per call.
|
Async over one pair, assuming we get `_ohlcv_candle_limit` candles per call.
|
||||||
:param pair: Pair to download
|
:param pair: Pair to download
|
||||||
:param ticker_interval: Interval to get
|
:param timeframe: Ticker Timeframe to get
|
||||||
:param since_ms: Timestamp in milliseconds to get history from
|
:param since_ms: Timestamp in milliseconds to get history from
|
||||||
:returns List of tickers
|
:returns List of tickers
|
||||||
"""
|
"""
|
||||||
return asyncio.get_event_loop().run_until_complete(
|
return asyncio.get_event_loop().run_until_complete(
|
||||||
self._async_get_historic_ohlcv(pair=pair, ticker_interval=ticker_interval,
|
self._async_get_historic_ohlcv(pair=pair, timeframe=timeframe,
|
||||||
since_ms=since_ms))
|
since_ms=since_ms))
|
||||||
|
|
||||||
async def _async_get_historic_ohlcv(self, pair: str,
|
async def _async_get_historic_ohlcv(self, pair: str,
|
||||||
ticker_interval: str,
|
timeframe: str,
|
||||||
since_ms: int) -> List:
|
since_ms: int) -> List:
|
||||||
|
|
||||||
one_call = timeframe_to_msecs(ticker_interval) * self._ohlcv_candle_limit
|
one_call = timeframe_to_msecs(timeframe) * self._ohlcv_candle_limit
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"one_call: %s msecs (%s)",
|
"one_call: %s msecs (%s)",
|
||||||
one_call,
|
one_call,
|
||||||
arrow.utcnow().shift(seconds=one_call // 1000).humanize(only_distance=True)
|
arrow.utcnow().shift(seconds=one_call // 1000).humanize(only_distance=True)
|
||||||
)
|
)
|
||||||
input_coroutines = [self._async_get_candle_history(
|
input_coroutines = [self._async_get_candle_history(
|
||||||
pair, ticker_interval, since) for since in
|
pair, timeframe, since) for since in
|
||||||
range(since_ms, arrow.utcnow().timestamp * 1000, one_call)]
|
range(since_ms, arrow.utcnow().timestamp * 1000, one_call)]
|
||||||
|
|
||||||
tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
|
tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
|
||||||
|
|
||||||
# Combine tickers
|
# Combine tickers
|
||||||
data: List = []
|
data: List = []
|
||||||
for p, ticker_interval, ticker in tickers:
|
for p, timeframe, ticker in tickers:
|
||||||
if p == pair:
|
if p == pair:
|
||||||
data.extend(ticker)
|
data.extend(ticker)
|
||||||
# Sort data again after extending the result - above calls return in "async order"
|
# Sort data again after extending the result - above calls return in "async order"
|
||||||
@@ -587,14 +655,14 @@ class Exchange:
|
|||||||
input_coroutines = []
|
input_coroutines = []
|
||||||
|
|
||||||
# Gather coroutines to run
|
# Gather coroutines to run
|
||||||
for pair, ticker_interval in set(pair_list):
|
for pair, timeframe in set(pair_list):
|
||||||
if (not ((pair, ticker_interval) in self._klines)
|
if (not ((pair, timeframe) in self._klines)
|
||||||
or self._now_is_time_to_refresh(pair, ticker_interval)):
|
or self._now_is_time_to_refresh(pair, timeframe)):
|
||||||
input_coroutines.append(self._async_get_candle_history(pair, ticker_interval))
|
input_coroutines.append(self._async_get_candle_history(pair, timeframe))
|
||||||
else:
|
else:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Using cached ohlcv data for pair %s, interval %s ...",
|
"Using cached ohlcv data for pair %s, timeframe %s ...",
|
||||||
pair, ticker_interval
|
pair, timeframe
|
||||||
)
|
)
|
||||||
|
|
||||||
tickers = asyncio.get_event_loop().run_until_complete(
|
tickers = asyncio.get_event_loop().run_until_complete(
|
||||||
@@ -606,40 +674,40 @@ class Exchange:
|
|||||||
logger.warning("Async code raised an exception: %s", res.__class__.__name__)
|
logger.warning("Async code raised an exception: %s", res.__class__.__name__)
|
||||||
continue
|
continue
|
||||||
pair = res[0]
|
pair = res[0]
|
||||||
ticker_interval = res[1]
|
timeframe = res[1]
|
||||||
ticks = res[2]
|
ticks = res[2]
|
||||||
# keeping last candle time as last refreshed time of the pair
|
# keeping last candle time as last refreshed time of the pair
|
||||||
if ticks:
|
if ticks:
|
||||||
self._pairs_last_refresh_time[(pair, ticker_interval)] = ticks[-1][0] // 1000
|
self._pairs_last_refresh_time[(pair, timeframe)] = ticks[-1][0] // 1000
|
||||||
# keeping parsed dataframe in cache
|
# keeping parsed dataframe in cache
|
||||||
self._klines[(pair, ticker_interval)] = parse_ticker_dataframe(
|
self._klines[(pair, timeframe)] = parse_ticker_dataframe(
|
||||||
ticks, ticker_interval, pair=pair, fill_missing=True,
|
ticks, timeframe, pair=pair, fill_missing=True,
|
||||||
drop_incomplete=self._ohlcv_partial_candle)
|
drop_incomplete=self._ohlcv_partial_candle)
|
||||||
return tickers
|
return tickers
|
||||||
|
|
||||||
def _now_is_time_to_refresh(self, pair: str, ticker_interval: str) -> bool:
|
def _now_is_time_to_refresh(self, pair: str, timeframe: str) -> bool:
|
||||||
# Calculating ticker interval in seconds
|
# Calculating ticker interval in seconds
|
||||||
interval_in_sec = timeframe_to_seconds(ticker_interval)
|
interval_in_sec = timeframe_to_seconds(timeframe)
|
||||||
|
|
||||||
return not ((self._pairs_last_refresh_time.get((pair, ticker_interval), 0)
|
return not ((self._pairs_last_refresh_time.get((pair, timeframe), 0)
|
||||||
+ interval_in_sec) >= arrow.utcnow().timestamp)
|
+ interval_in_sec) >= arrow.utcnow().timestamp)
|
||||||
|
|
||||||
@retrier_async
|
@retrier_async
|
||||||
async def _async_get_candle_history(self, pair: str, ticker_interval: str,
|
async def _async_get_candle_history(self, pair: str, timeframe: str,
|
||||||
since_ms: Optional[int] = None) -> Tuple[str, str, List]:
|
since_ms: Optional[int] = None) -> Tuple[str, str, List]:
|
||||||
"""
|
"""
|
||||||
Asynchronously gets candle histories using fetch_ohlcv
|
Asynchronously gets candle histories using fetch_ohlcv
|
||||||
returns tuple: (pair, ticker_interval, ohlcv_list)
|
returns tuple: (pair, timeframe, ohlcv_list)
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# fetch ohlcv asynchronously
|
# fetch ohlcv asynchronously
|
||||||
s = '(' + arrow.get(since_ms // 1000).isoformat() + ') ' if since_ms is not None else ''
|
s = '(' + arrow.get(since_ms // 1000).isoformat() + ') ' if since_ms is not None else ''
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Fetching pair %s, interval %s, since %s %s...",
|
"Fetching pair %s, interval %s, since %s %s...",
|
||||||
pair, ticker_interval, since_ms, s
|
pair, timeframe, since_ms, s
|
||||||
)
|
)
|
||||||
|
|
||||||
data = await self._api_async.fetch_ohlcv(pair, timeframe=ticker_interval,
|
data = await self._api_async.fetch_ohlcv(pair, timeframe=timeframe,
|
||||||
since=since_ms)
|
since=since_ms)
|
||||||
|
|
||||||
# Because some exchange sort Tickers ASC and other DESC.
|
# Because some exchange sort Tickers ASC and other DESC.
|
||||||
@@ -651,9 +719,9 @@ class Exchange:
|
|||||||
data = sorted(data, key=lambda x: x[0])
|
data = sorted(data, key=lambda x: x[0])
|
||||||
except IndexError:
|
except IndexError:
|
||||||
logger.exception("Error loading %s. Result was %s.", pair, data)
|
logger.exception("Error loading %s. Result was %s.", pair, data)
|
||||||
return pair, ticker_interval, []
|
return pair, timeframe, []
|
||||||
logger.debug("Done fetching pair %s, interval %s ...", pair, ticker_interval)
|
logger.debug("Done fetching pair %s, interval %s ...", pair, timeframe)
|
||||||
return pair, ticker_interval, data
|
return pair, timeframe, data
|
||||||
|
|
||||||
except ccxt.NotSupported as e:
|
except ccxt.NotSupported as e:
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
@@ -665,6 +733,153 @@ class Exchange:
|
|||||||
except ccxt.BaseError as 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. Msg: {e}') from e
|
||||||
|
|
||||||
|
@retrier_async
|
||||||
|
async def _async_fetch_trades(self, pair: str,
|
||||||
|
since: Optional[int] = None,
|
||||||
|
params: Optional[dict] = None) -> List[Dict]:
|
||||||
|
"""
|
||||||
|
Asyncronously gets trade history using fetch_trades.
|
||||||
|
Handles exchange errors, does one call to the exchange.
|
||||||
|
:param pair: Pair to fetch trade data for
|
||||||
|
:param since: Since as integer timestamp in milliseconds
|
||||||
|
returns: List of dicts containing trades
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# fetch trades asynchronously
|
||||||
|
if params:
|
||||||
|
logger.debug("Fetching trades for pair %s, params: %s ", pair, params)
|
||||||
|
trades = await self._api_async.fetch_trades(pair, params=params, limit=1000)
|
||||||
|
else:
|
||||||
|
logger.debug(
|
||||||
|
"Fetching trades for pair %s, since %s %s...",
|
||||||
|
pair, since,
|
||||||
|
'(' + arrow.get(since // 1000).isoformat() + ') ' if since is not None else ''
|
||||||
|
)
|
||||||
|
trades = await self._api_async.fetch_trades(pair, since=since, limit=1000)
|
||||||
|
return trades
|
||||||
|
except ccxt.NotSupported as e:
|
||||||
|
raise OperationalException(
|
||||||
|
f'Exchange {self._api.name} does not support fetching historical trade data.'
|
||||||
|
f'Message: {e}') from e
|
||||||
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||||
|
raise TemporaryError(f'Could not load trade history due to {e.__class__.__name__}. '
|
||||||
|
f'Message: {e}') from e
|
||||||
|
except ccxt.BaseError as e:
|
||||||
|
raise OperationalException(f'Could not fetch trade data. Msg: {e}') from e
|
||||||
|
|
||||||
|
async def _async_get_trade_history_id(self, pair: str,
|
||||||
|
until: int,
|
||||||
|
since: Optional[int] = None,
|
||||||
|
from_id: Optional[str] = None) -> Tuple[str, List[Dict]]:
|
||||||
|
"""
|
||||||
|
Asyncronously gets trade history using fetch_trades
|
||||||
|
use this when exchange uses id-based iteration (check `self._trades_pagination`)
|
||||||
|
:param pair: Pair to fetch trade data for
|
||||||
|
:param since: Since as integer timestamp in milliseconds
|
||||||
|
:param until: Until as integer timestamp in milliseconds
|
||||||
|
:param from_id: Download data starting with ID (if id is known). Ignores "since" if set.
|
||||||
|
returns tuple: (pair, trades-list)
|
||||||
|
"""
|
||||||
|
|
||||||
|
trades: List[Dict] = []
|
||||||
|
|
||||||
|
if not from_id:
|
||||||
|
# Fetch first elements using timebased method to get an ID to paginate on
|
||||||
|
# Depending on the Exchange, this can introduce a drift at the start of the interval
|
||||||
|
# of up to an hour.
|
||||||
|
# e.g. Binance returns the "last 1000" candles within a 1h time interval
|
||||||
|
# - so we will miss the first trades.
|
||||||
|
t = await self._async_fetch_trades(pair, since=since)
|
||||||
|
from_id = t[-1]['id']
|
||||||
|
trades.extend(t[:-1])
|
||||||
|
while True:
|
||||||
|
t = await self._async_fetch_trades(pair,
|
||||||
|
params={self._trades_pagination_arg: from_id})
|
||||||
|
if len(t):
|
||||||
|
# Skip last id since its the key for the next call
|
||||||
|
trades.extend(t[:-1])
|
||||||
|
if from_id == t[-1]['id'] or t[-1]['timestamp'] > until:
|
||||||
|
logger.debug(f"Stopping because from_id did not change. "
|
||||||
|
f"Reached {t[-1]['timestamp']} > {until}")
|
||||||
|
# Reached the end of the defined-download period - add last trade as well.
|
||||||
|
trades.extend(t[-1:])
|
||||||
|
break
|
||||||
|
|
||||||
|
from_id = t[-1]['id']
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
return (pair, trades)
|
||||||
|
|
||||||
|
async def _async_get_trade_history_time(self, pair: str, until: int,
|
||||||
|
since: Optional[int] = None) -> Tuple[str, List]:
|
||||||
|
"""
|
||||||
|
Asyncronously gets trade history using fetch_trades,
|
||||||
|
when the exchange uses time-based iteration (check `self._trades_pagination`)
|
||||||
|
:param pair: Pair to fetch trade data for
|
||||||
|
:param since: Since as integer timestamp in milliseconds
|
||||||
|
:param until: Until as integer timestamp in milliseconds
|
||||||
|
returns tuple: (pair, trades-list)
|
||||||
|
"""
|
||||||
|
|
||||||
|
trades: List[Dict] = []
|
||||||
|
while True:
|
||||||
|
t = await self._async_fetch_trades(pair, since=since)
|
||||||
|
if len(t):
|
||||||
|
since = t[-1]['timestamp']
|
||||||
|
trades.extend(t)
|
||||||
|
# Reached the end of the defined-download period
|
||||||
|
if until and t[-1]['timestamp'] > until:
|
||||||
|
logger.debug(
|
||||||
|
f"Stopping because until was reached. {t[-1]['timestamp']} > {until}")
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
return (pair, trades)
|
||||||
|
|
||||||
|
async def _async_get_trade_history(self, pair: str,
|
||||||
|
since: Optional[int] = None,
|
||||||
|
until: Optional[int] = None,
|
||||||
|
from_id: Optional[str] = None) -> Tuple[str, List[Dict]]:
|
||||||
|
"""
|
||||||
|
Async wrapper handling downloading trades using either time or id based methods.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if self._trades_pagination == 'time':
|
||||||
|
return await self._async_get_trade_history_time(
|
||||||
|
pair=pair, since=since,
|
||||||
|
until=until or ccxt.Exchange.milliseconds())
|
||||||
|
elif self._trades_pagination == 'id':
|
||||||
|
return await self._async_get_trade_history_id(
|
||||||
|
pair=pair, since=since,
|
||||||
|
until=until or ccxt.Exchange.milliseconds(), from_id=from_id
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise OperationalException(f"Exchange {self.name} does use neither time, "
|
||||||
|
f"nor id based pagination")
|
||||||
|
|
||||||
|
def get_historic_trades(self, pair: str,
|
||||||
|
since: Optional[int] = None,
|
||||||
|
until: Optional[int] = None,
|
||||||
|
from_id: Optional[str] = None) -> Tuple[str, List]:
|
||||||
|
"""
|
||||||
|
Gets candle history using asyncio and returns the list of candles.
|
||||||
|
Handles all async doing.
|
||||||
|
Async over one pair, assuming we get `_ohlcv_candle_limit` candles per call.
|
||||||
|
:param pair: Pair to download
|
||||||
|
:param since: Timestamp in milliseconds to get history from
|
||||||
|
:param until: Timestamp in milliseconds. Defaults to current timestamp if not defined.
|
||||||
|
:param from_id: Download data starting with ID (if id is known)
|
||||||
|
:returns List of tickers
|
||||||
|
"""
|
||||||
|
if not self.exchange_has("fetchTrades"):
|
||||||
|
raise OperationalException("This exchange does not suport downloading Trades.")
|
||||||
|
|
||||||
|
return asyncio.get_event_loop().run_until_complete(
|
||||||
|
self._async_get_trade_history(pair=pair, since=since,
|
||||||
|
until=until, from_id=from_id))
|
||||||
|
|
||||||
@retrier
|
@retrier
|
||||||
def cancel_order(self, order_id: str, pair: str) -> None:
|
def cancel_order(self, order_id: str, pair: str) -> None:
|
||||||
if self._config['dry_run']:
|
if self._config['dry_run']:
|
||||||
@@ -725,6 +940,22 @@ class Exchange:
|
|||||||
|
|
||||||
@retrier
|
@retrier
|
||||||
def get_trades_for_order(self, order_id: str, pair: str, since: datetime) -> List:
|
def get_trades_for_order(self, order_id: str, pair: str, since: datetime) -> List:
|
||||||
|
"""
|
||||||
|
Fetch Orders using the "fetch_my_trades" endpoint and filter them by order-id.
|
||||||
|
The "since" argument passed in is coming from the database and is in UTC,
|
||||||
|
as timezone-native datetime object.
|
||||||
|
From the python documentation:
|
||||||
|
> Naive datetime instances are assumed to represent local time
|
||||||
|
Therefore, calling "since.timestamp()" will get the UTC timestamp, after applying the
|
||||||
|
transformation from local timezone to UTC.
|
||||||
|
This works for timezones UTC+ since then the result will contain trades from a few hours
|
||||||
|
instead of from the last 5 seconds, however fails for UTC- timezones,
|
||||||
|
since we're then asking for trades with a "since" argument in the future.
|
||||||
|
|
||||||
|
:param order_id order_id: Order-id as given when creating the order
|
||||||
|
:param pair: Pair the order is for
|
||||||
|
:param since: datetime object of the order creation time. Assumes object is in UTC.
|
||||||
|
"""
|
||||||
if self._config['dry_run']:
|
if self._config['dry_run']:
|
||||||
return []
|
return []
|
||||||
if not self.exchange_has('fetchMyTrades'):
|
if not self.exchange_has('fetchMyTrades'):
|
||||||
@@ -732,7 +963,8 @@ class Exchange:
|
|||||||
try:
|
try:
|
||||||
# Allow 5s offset to catch slight time offsets (discovered in #1185)
|
# Allow 5s offset to catch slight time offsets (discovered in #1185)
|
||||||
# since needs to be int in milliseconds
|
# since needs to be int in milliseconds
|
||||||
my_trades = self._api.fetch_my_trades(pair, int((since.timestamp() - 5) * 1000))
|
my_trades = self._api.fetch_my_trades(
|
||||||
|
pair, int((since.replace(tzinfo=timezone.utc).timestamp() - 5) * 1000))
|
||||||
matched_trades = [trade for trade in my_trades if trade['order'] == order_id]
|
matched_trades = [trade for trade in my_trades if trade['order'] == order_id]
|
||||||
|
|
||||||
return matched_trades
|
return matched_trades
|
||||||
@@ -744,7 +976,7 @@ class Exchange:
|
|||||||
raise OperationalException(e) from e
|
raise OperationalException(e) from e
|
||||||
|
|
||||||
@retrier
|
@retrier
|
||||||
def get_fee(self, symbol='ETH/BTC', type='', side='', amount=1,
|
def get_fee(self, symbol, type='', side='', amount=1,
|
||||||
price=1, taker_or_maker='maker') -> float:
|
price=1, taker_or_maker='maker') -> float:
|
||||||
try:
|
try:
|
||||||
# validate that markets are loaded before trying to get fee
|
# validate that markets are loaded before trying to get fee
|
||||||
@@ -768,39 +1000,50 @@ def get_exchange_bad_reason(exchange_name: str) -> str:
|
|||||||
return BAD_EXCHANGES.get(exchange_name, "")
|
return BAD_EXCHANGES.get(exchange_name, "")
|
||||||
|
|
||||||
|
|
||||||
def is_exchange_available(exchange_name: str, ccxt_module=None) -> bool:
|
def is_exchange_known_ccxt(exchange_name: str, ccxt_module=None) -> bool:
|
||||||
return exchange_name in available_exchanges(ccxt_module)
|
return exchange_name in ccxt_exchanges(ccxt_module)
|
||||||
|
|
||||||
|
|
||||||
def is_exchange_officially_supported(exchange_name: str) -> bool:
|
def is_exchange_officially_supported(exchange_name: str) -> bool:
|
||||||
return exchange_name in ['bittrex', 'binance']
|
return exchange_name in ['bittrex', 'binance']
|
||||||
|
|
||||||
|
|
||||||
def available_exchanges(ccxt_module=None) -> List[str]:
|
def ccxt_exchanges(ccxt_module=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
|
return ccxt_module.exchanges if ccxt_module is not None else ccxt.exchanges
|
||||||
|
|
||||||
|
|
||||||
def timeframe_to_seconds(ticker_interval: str) -> int:
|
def available_exchanges(ccxt_module=None) -> List[str]:
|
||||||
|
"""
|
||||||
|
Return exchanges available to the bot, i.e. non-bad exchanges in the ccxt list
|
||||||
|
"""
|
||||||
|
exchanges = ccxt_exchanges(ccxt_module)
|
||||||
|
return [x for x in exchanges if not is_exchange_bad(x)]
|
||||||
|
|
||||||
|
|
||||||
|
def timeframe_to_seconds(timeframe: str) -> int:
|
||||||
"""
|
"""
|
||||||
Translates the timeframe interval value written in the human readable
|
Translates the timeframe interval value written in the human readable
|
||||||
form ('1m', '5m', '1h', '1d', '1w', etc.) to the number
|
form ('1m', '5m', '1h', '1d', '1w', etc.) to the number
|
||||||
of seconds for one timeframe interval.
|
of seconds for one timeframe interval.
|
||||||
"""
|
"""
|
||||||
return ccxt.Exchange.parse_timeframe(ticker_interval)
|
return ccxt.Exchange.parse_timeframe(timeframe)
|
||||||
|
|
||||||
|
|
||||||
def timeframe_to_minutes(ticker_interval: str) -> int:
|
def timeframe_to_minutes(timeframe: str) -> int:
|
||||||
"""
|
"""
|
||||||
Same as timeframe_to_seconds, but returns minutes.
|
Same as timeframe_to_seconds, but returns minutes.
|
||||||
"""
|
"""
|
||||||
return ccxt.Exchange.parse_timeframe(ticker_interval) // 60
|
return ccxt.Exchange.parse_timeframe(timeframe) // 60
|
||||||
|
|
||||||
|
|
||||||
def timeframe_to_msecs(ticker_interval: str) -> int:
|
def timeframe_to_msecs(timeframe: str) -> int:
|
||||||
"""
|
"""
|
||||||
Same as timeframe_to_seconds, but returns milliseconds.
|
Same as timeframe_to_seconds, but returns milliseconds.
|
||||||
"""
|
"""
|
||||||
return ccxt.Exchange.parse_timeframe(ticker_interval) * 1000
|
return ccxt.Exchange.parse_timeframe(timeframe) * 1000
|
||||||
|
|
||||||
|
|
||||||
def timeframe_to_prev_date(timeframe: str, date: datetime = None) -> datetime:
|
def timeframe_to_prev_date(timeframe: str, date: datetime = None) -> datetime:
|
||||||
@@ -830,3 +1073,27 @@ def timeframe_to_next_date(timeframe: str, date: datetime = None) -> datetime:
|
|||||||
new_timestamp = ccxt.Exchange.round_timeframe(timeframe, date.timestamp() * 1000,
|
new_timestamp = ccxt.Exchange.round_timeframe(timeframe, date.timestamp() * 1000,
|
||||||
ROUND_UP) // 1000
|
ROUND_UP) // 1000
|
||||||
return datetime.fromtimestamp(new_timestamp, tz=timezone.utc)
|
return datetime.fromtimestamp(new_timestamp, tz=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def symbol_is_pair(market_symbol: str, base_currency: str = None, quote_currency: str = None):
|
||||||
|
"""
|
||||||
|
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,
|
||||||
|
it also checks that the symbol contains appropriate base and/or quote currency part before
|
||||||
|
and after the separating character correspondingly.
|
||||||
|
"""
|
||||||
|
symbol_parts = market_symbol.split('/')
|
||||||
|
return (len(symbol_parts) == 2 and
|
||||||
|
(symbol_parts[0] == base_currency if base_currency else len(symbol_parts[0]) > 0) and
|
||||||
|
(symbol_parts[1] == quote_currency if quote_currency else len(symbol_parts[1]) > 0))
|
||||||
|
|
||||||
|
|
||||||
|
def market_is_active(market):
|
||||||
|
"""
|
||||||
|
Return True if the market is active.
|
||||||
|
"""
|
||||||
|
# "It's active, if the active flag isn't explicitly set to false. If it's missing or
|
||||||
|
# true then it's true. If it's undefined, then it's most likely true, but not 100% )"
|
||||||
|
# See https://github.com/ccxt/ccxt/issues/4874,
|
||||||
|
# https://github.com/ccxt/ccxt/issues/4075#issuecomment-434760520
|
||||||
|
return market.get('active', True) is not False
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from typing import Dict
|
|||||||
|
|
||||||
import ccxt
|
import ccxt
|
||||||
|
|
||||||
from freqtrade import OperationalException, TemporaryError
|
from freqtrade.exceptions import OperationalException, TemporaryError
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
from freqtrade.exchange.exchange import retrier
|
from freqtrade.exchange.exchange import retrier
|
||||||
|
|
||||||
@@ -14,6 +14,10 @@ logger = logging.getLogger(__name__)
|
|||||||
class Kraken(Exchange):
|
class Kraken(Exchange):
|
||||||
|
|
||||||
_params: Dict = {"trading_agreement": "agree"}
|
_params: Dict = {"trading_agreement": "agree"}
|
||||||
|
_ft_has: Dict = {
|
||||||
|
"trades_pagination": "id",
|
||||||
|
"trades_pagination_arg": "since",
|
||||||
|
}
|
||||||
|
|
||||||
@retrier
|
@retrier
|
||||||
def get_balances(self) -> dict:
|
def get_balances(self) -> dict:
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,40 +0,0 @@
|
|||||||
from math import cos, exp, pi, sqrt
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import talib as ta
|
|
||||||
from pandas import Series
|
|
||||||
|
|
||||||
|
|
||||||
def went_up(series: Series) -> bool:
|
|
||||||
return series > series.shift(1)
|
|
||||||
|
|
||||||
|
|
||||||
def went_down(series: Series) -> bool:
|
|
||||||
return series < series.shift(1)
|
|
||||||
|
|
||||||
|
|
||||||
def ehlers_super_smoother(series: Series, smoothing: float = 6) -> Series:
|
|
||||||
magic = pi * sqrt(2) / smoothing
|
|
||||||
a1 = exp(-magic)
|
|
||||||
coeff2 = 2 * a1 * cos(magic)
|
|
||||||
coeff3 = -a1 * a1
|
|
||||||
coeff1 = (1 - coeff2 - coeff3) / 2
|
|
||||||
|
|
||||||
filtered = series.copy()
|
|
||||||
|
|
||||||
for i in range(2, len(series)):
|
|
||||||
filtered.iloc[i] = coeff1 * (series.iloc[i] + series.iloc[i-1]) + \
|
|
||||||
coeff2 * filtered.iloc[i-1] + coeff3 * filtered.iloc[i-2]
|
|
||||||
|
|
||||||
return filtered
|
|
||||||
|
|
||||||
|
|
||||||
def fishers_inverse(series: Series, smoothing: float = 0) -> np.ndarray:
|
|
||||||
""" Does a smoothed fishers inverse transformation.
|
|
||||||
Can be used with any oscillator that goes from 0 to 100 like RSI or MFI """
|
|
||||||
v1 = 0.1 * (series - 50)
|
|
||||||
if smoothing > 0:
|
|
||||||
v2 = ta.WMA(v1.values, timeperiod=smoothing)
|
|
||||||
else:
|
|
||||||
v2 = v1
|
|
||||||
return (np.exp(2 * v2)-1) / (np.exp(2 * v2) + 1)
|
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
from logging.handlers import RotatingFileHandler
|
from logging import Formatter
|
||||||
|
from logging.handlers import RotatingFileHandler, SysLogHandler
|
||||||
from typing import Any, Dict, List
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
from freqtrade.exceptions import OperationalException
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -33,13 +36,41 @@ def setup_logging(config: Dict[str, Any]) -> None:
|
|||||||
# Log level
|
# Log level
|
||||||
verbosity = config['verbosity']
|
verbosity = config['verbosity']
|
||||||
|
|
||||||
# Log to stdout, not stderr
|
# Log to stderr
|
||||||
log_handlers: List[logging.Handler] = [logging.StreamHandler(sys.stdout)]
|
log_handlers: List[logging.Handler] = [logging.StreamHandler(sys.stderr)]
|
||||||
|
|
||||||
if config.get('logfile'):
|
logfile = config.get('logfile')
|
||||||
log_handlers.append(RotatingFileHandler(config['logfile'],
|
if logfile:
|
||||||
maxBytes=1024 * 1024, # 1Mb
|
s = logfile.split(':')
|
||||||
backupCount=10))
|
if s[0] == 'syslog':
|
||||||
|
# Address can be either a string (socket filename) for Unix domain socket or
|
||||||
|
# a tuple (hostname, port) for UDP socket.
|
||||||
|
# Address can be omitted (i.e. simple 'syslog' used as the value of
|
||||||
|
# config['logfilename']), which defaults to '/dev/log', applicable for most
|
||||||
|
# of the systems.
|
||||||
|
address = (s[1], int(s[2])) if len(s) > 2 else s[1] if len(s) > 1 else '/dev/log'
|
||||||
|
handler = SysLogHandler(address=address)
|
||||||
|
# No datetime field for logging into syslog, to allow syslog
|
||||||
|
# to perform reduction of repeating messages if this is set in the
|
||||||
|
# syslog config. The messages should be equal for this.
|
||||||
|
handler.setFormatter(Formatter('%(name)s - %(levelname)s - %(message)s'))
|
||||||
|
log_handlers.append(handler)
|
||||||
|
elif s[0] == 'journald':
|
||||||
|
try:
|
||||||
|
from systemd.journal import JournaldLogHandler
|
||||||
|
except ImportError:
|
||||||
|
raise OperationalException("You need the systemd python package be installed in "
|
||||||
|
"order to use logging to journald.")
|
||||||
|
handler = JournaldLogHandler()
|
||||||
|
# No datetime field for logging into journald, to allow syslog
|
||||||
|
# to perform reduction of repeating messages if this is set in the
|
||||||
|
# syslog config. The messages should be equal for this.
|
||||||
|
handler.setFormatter(Formatter('%(name)s - %(levelname)s - %(message)s'))
|
||||||
|
log_handlers.append(handler)
|
||||||
|
else:
|
||||||
|
log_handlers.append(RotatingFileHandler(logfile,
|
||||||
|
maxBytes=1024 * 1024, # 1Mb
|
||||||
|
backupCount=10))
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
level=logging.INFO if verbosity < 1 else logging.DEBUG,
|
level=logging.INFO if verbosity < 1 else logging.DEBUG,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ Main Freqtrade bot script.
|
|||||||
Read the documentation to know what cli arguments you need.
|
Read the documentation to know what cli arguments you need.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from freqtrade.exceptions import FreqtradeException, OperationalException
|
||||||
import sys
|
import sys
|
||||||
# check min. python version
|
# check min. python version
|
||||||
if sys.version_info < (3, 6):
|
if sys.version_info < (3, 6):
|
||||||
@@ -13,9 +14,7 @@ if sys.version_info < (3, 6):
|
|||||||
import logging
|
import logging
|
||||||
from typing import Any, List
|
from typing import Any, List
|
||||||
|
|
||||||
from freqtrade import OperationalException
|
from freqtrade.commands import Arguments
|
||||||
from freqtrade.configuration import Arguments
|
|
||||||
from freqtrade.worker import Worker
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger('freqtrade')
|
logger = logging.getLogger('freqtrade')
|
||||||
@@ -28,35 +27,35 @@ def main(sysargv: List[str] = None) -> None:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
return_code: Any = 1
|
return_code: Any = 1
|
||||||
worker = None
|
|
||||||
try:
|
try:
|
||||||
arguments = Arguments(sysargv)
|
arguments = Arguments(sysargv)
|
||||||
args = arguments.get_parsed_arg()
|
args = arguments.get_parsed_arg()
|
||||||
|
|
||||||
# A subcommand has been issued.
|
# Call subcommand.
|
||||||
# Means if Backtesting or Hyperopt have been called we exit the bot
|
|
||||||
if 'func' in args:
|
if 'func' in args:
|
||||||
args['func'](args)
|
return_code = args['func'](args)
|
||||||
# TODO: fetch return_code as returned by the command function here
|
|
||||||
return_code = 0
|
|
||||||
else:
|
else:
|
||||||
# Load and run worker
|
# No subcommand was issued.
|
||||||
worker = Worker(args)
|
raise OperationalException(
|
||||||
worker.run()
|
"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 "
|
||||||
|
"as `freqtrade trade [options...]`.\n"
|
||||||
|
"To see the full list of options available, please use "
|
||||||
|
"`freqtrade --help` or `freqtrade <command> --help`."
|
||||||
|
)
|
||||||
|
|
||||||
except SystemExit as e:
|
except SystemExit as e:
|
||||||
return_code = e
|
return_code = e
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
logger.info('SIGINT received, aborting ...')
|
logger.info('SIGINT received, aborting ...')
|
||||||
return_code = 0
|
return_code = 0
|
||||||
except OperationalException as e:
|
except FreqtradeException as e:
|
||||||
logger.error(str(e))
|
logger.error(str(e))
|
||||||
return_code = 2
|
return_code = 2
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception('Fatal exception!')
|
logger.exception('Fatal exception!')
|
||||||
finally:
|
finally:
|
||||||
if worker:
|
|
||||||
worker.exit()
|
|
||||||
sys.exit(return_code)
|
sys.exit(return_code)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -72,8 +72,10 @@ def json_load(datafile: IO):
|
|||||||
|
|
||||||
def file_load_json(file):
|
def file_load_json(file):
|
||||||
|
|
||||||
gzipfile = file.with_suffix(file.suffix + '.gz')
|
if file.suffix != ".gz":
|
||||||
|
gzipfile = file.with_suffix(file.suffix + '.gz')
|
||||||
|
else:
|
||||||
|
gzipfile = file
|
||||||
# Try gzip file first, otherwise regular json file.
|
# Try gzip file first, otherwise regular json file.
|
||||||
if gzipfile.is_file():
|
if gzipfile.is_file():
|
||||||
logger.debug('Loading ticker data from file %s', gzipfile)
|
logger.debug('Loading ticker data from file %s', gzipfile)
|
||||||
@@ -121,3 +123,20 @@ def round_dict(d, n):
|
|||||||
Rounds float values in the dict to n digits after the decimal point.
|
Rounds float values in the dict to n digits after the decimal point.
|
||||||
"""
|
"""
|
||||||
return {k: (round(v, n) if isinstance(v, float) else v) for k, v in d.items()}
|
return {k: (round(v, n) if isinstance(v, float) else v) for k, v in d.items()}
|
||||||
|
|
||||||
|
|
||||||
|
def plural(num, 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 = {}):
|
||||||
|
|
||||||
|
from jinja2 import Environment, PackageLoader, select_autoescape
|
||||||
|
|
||||||
|
env = Environment(
|
||||||
|
loader=PackageLoader('freqtrade', 'templates'),
|
||||||
|
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 Hyperopts 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()
|
|
||||||
|
|||||||
@@ -11,17 +11,20 @@ from typing import Any, Dict, List, NamedTuple, Optional
|
|||||||
|
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
from freqtrade import OperationalException
|
from freqtrade.configuration import (TimeRange, remove_credentials,
|
||||||
from freqtrade.configuration import TimeRange
|
validate_config_consistency)
|
||||||
from freqtrade.data import history
|
from freqtrade.data import history
|
||||||
from freqtrade.data.dataprovider import DataProvider
|
from freqtrade.data.dataprovider import DataProvider
|
||||||
from freqtrade.exchange import timeframe_to_minutes
|
from freqtrade.exceptions import OperationalException
|
||||||
|
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds
|
||||||
from freqtrade.misc import file_dump_json
|
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.persistence import Trade
|
||||||
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode
|
||||||
from freqtrade.strategy.interface import IStrategy, SellType
|
from freqtrade.strategy.interface import IStrategy, SellType
|
||||||
from tabulate import tabulate
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -57,15 +60,14 @@ class Backtesting:
|
|||||||
self.config = config
|
self.config = config
|
||||||
|
|
||||||
# Reset keys for backtesting
|
# Reset keys for backtesting
|
||||||
self.config['exchange']['key'] = ''
|
remove_credentials(self.config)
|
||||||
self.config['exchange']['secret'] = ''
|
|
||||||
self.config['exchange']['password'] = ''
|
|
||||||
self.config['exchange']['uid'] = ''
|
|
||||||
self.config['dry_run'] = True
|
|
||||||
self.strategylist: List[IStrategy] = []
|
self.strategylist: List[IStrategy] = []
|
||||||
|
self.exchange = ExchangeResolver.load_exchange(self.config['exchange']['name'], self.config)
|
||||||
|
|
||||||
self.exchange = ExchangeResolver(self.config['exchange']['name'], self.config).exchange
|
if config.get('fee'):
|
||||||
self.fee = self.exchange.get_fee()
|
self.fee = config['fee']
|
||||||
|
else:
|
||||||
|
self.fee = self.exchange.get_fee(symbol=self.config['exchange']['pair_whitelist'][0])
|
||||||
|
|
||||||
if self.config.get('runmode') != RunMode.HYPEROPT:
|
if self.config.get('runmode') != RunMode.HYPEROPT:
|
||||||
self.dataprovider = DataProvider(self.config, self.exchange)
|
self.dataprovider = DataProvider(self.config, self.exchange)
|
||||||
@@ -75,18 +77,22 @@ class Backtesting:
|
|||||||
for strat in list(self.config['strategy_list']):
|
for strat in list(self.config['strategy_list']):
|
||||||
stratconf = deepcopy(self.config)
|
stratconf = deepcopy(self.config)
|
||||||
stratconf['strategy'] = strat
|
stratconf['strategy'] = strat
|
||||||
self.strategylist.append(StrategyResolver(stratconf).strategy)
|
self.strategylist.append(StrategyResolver.load_strategy(stratconf))
|
||||||
|
validate_config_consistency(stratconf)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# No strategy list specified, only one strategy
|
# 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:
|
if "ticker_interval" not in self.config:
|
||||||
raise OperationalException("Ticker-interval needs to be set in either configuration "
|
raise OperationalException("Ticker-interval needs to be set in either configuration "
|
||||||
"or as cli argument `--ticker-interval 5m`")
|
"or as cli argument `--ticker-interval 5m`")
|
||||||
self.ticker_interval = str(self.config.get('ticker_interval'))
|
self.timeframe = str(self.config.get('ticker_interval'))
|
||||||
self.ticker_interval_mins = timeframe_to_minutes(self.ticker_interval)
|
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])
|
||||||
# Load one (first) strategy
|
# Load one (first) strategy
|
||||||
self._set_strategy(self.strategylist[0])
|
self._set_strategy(self.strategylist[0])
|
||||||
|
|
||||||
@@ -100,93 +106,30 @@ class Backtesting:
|
|||||||
# And the regular "stoploss" function would not apply to that case
|
# And the regular "stoploss" function would not apply to that case
|
||||||
self.strategy.order_types['stoploss_on_exchange'] = False
|
self.strategy.order_types['stoploss_on_exchange'] = False
|
||||||
|
|
||||||
def _generate_text_table(self, data: Dict[str, Dict], results: DataFrame,
|
def load_bt_data(self):
|
||||||
skip_nan: bool = False) -> str:
|
timerange = TimeRange.parse_timerange(None if self.config.get(
|
||||||
"""
|
'timerange') is None else str(self.config.get('timerange')))
|
||||||
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')
|
data = history.load_data(
|
||||||
tabular_data = []
|
datadir=self.config['datadir'],
|
||||||
headers = ['pair', 'buy count', 'avg profit %', 'cum profit %',
|
pairs=self.config['exchange']['pair_whitelist'],
|
||||||
'tot profit ' + stake_currency, 'tot profit %', 'avg duration',
|
timeframe=self.timeframe,
|
||||||
'profit', 'loss']
|
timerange=timerange,
|
||||||
for pair in data:
|
startup_candles=self.required_startup,
|
||||||
result = results[results.pair == pair]
|
fail_without_data=True,
|
||||||
if skip_nan and result.profit_abs.isnull().all():
|
)
|
||||||
continue
|
|
||||||
|
|
||||||
tabular_data.append([
|
min_date, max_date = history.get_timerange(data)
|
||||||
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
|
logger.info(
|
||||||
tabular_data.append([
|
'Loading data from %s up to %s (%s days)..',
|
||||||
'TOTAL',
|
min_date.isoformat(), max_date.isoformat(), (max_date - min_date).days
|
||||||
len(results.index),
|
)
|
||||||
results.profit_percent.mean() * 100.0,
|
# Adjust startts forward if not enough data is available
|
||||||
results.profit_percent.sum() * 100.0,
|
timerange.adjust_start_if_necessary(timeframe_to_seconds(self.timeframe),
|
||||||
results.profit_abs.sum(),
|
self.required_startup, min_date)
|
||||||
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, # type: ignore
|
|
||||||
floatfmt=floatfmt, tablefmt="pipe")
|
|
||||||
|
|
||||||
def _generate_text_table_sell_reason(self, data: Dict[str, Dict], results: DataFrame) -> str:
|
return data, timerange
|
||||||
"""
|
|
||||||
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, # type: ignore
|
|
||||||
floatfmt=floatfmt, tablefmt="pipe")
|
|
||||||
|
|
||||||
def _store_backtest_result(self, recordfilename: Path, results: DataFrame,
|
def _store_backtest_result(self, recordfilename: Path, results: DataFrame,
|
||||||
strategyname: Optional[str] = None) -> None:
|
strategyname: Optional[str] = None) -> None:
|
||||||
@@ -215,7 +158,8 @@ class Backtesting:
|
|||||||
ticker: Dict = {}
|
ticker: Dict = {}
|
||||||
# Create ticker dict
|
# Create ticker dict
|
||||||
for pair, pair_data in processed.items():
|
for pair, pair_data in processed.items():
|
||||||
pair_data['buy'], pair_data['sell'] = 0, 0 # cleanup from previous run
|
pair_data.loc[:, 'buy'] = 0 # cleanup from previous run
|
||||||
|
pair_data.loc[:, 'sell'] = 0 # cleanup from previous run
|
||||||
|
|
||||||
ticker_data = self.strategy.advise_sell(
|
ticker_data = self.strategy.advise_sell(
|
||||||
self.strategy.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy()
|
self.strategy.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy()
|
||||||
@@ -231,6 +175,45 @@ class Backtesting:
|
|||||||
ticker[pair] = [x for x in ticker_data.itertuples()]
|
ticker[pair] = [x for x in ticker_data.itertuples()]
|
||||||
return ticker
|
return ticker
|
||||||
|
|
||||||
|
def _get_close_rate(self, sell_row, trade: Trade, sell, trade_dur) -> 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(
|
def _get_sell_trade_entry(
|
||||||
self, pair: str, buy_row: DataFrame,
|
self, pair: str, buy_row: DataFrame,
|
||||||
partial_ticker: List, trade_count_lock: Dict,
|
partial_ticker: List, trade_count_lock: Dict,
|
||||||
@@ -257,24 +240,10 @@ class Backtesting:
|
|||||||
sell_row.sell, low=sell_row.low, high=sell_row.high)
|
sell_row.sell, low=sell_row.low, high=sell_row.high)
|
||||||
if sell.sell_flag:
|
if sell.sell_flag:
|
||||||
trade_dur = int((sell_row.date - buy_row.date).total_seconds() // 60)
|
trade_dur = int((sell_row.date - buy_row.date).total_seconds() // 60)
|
||||||
# Special handling if high or low hit STOP_LOSS or ROI
|
closerate = self._get_close_rate(sell_row, trade, sell, trade_dur)
|
||||||
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)
|
|
||||||
else:
|
|
||||||
# This should not be reached...
|
|
||||||
closerate = sell_row.open
|
|
||||||
else:
|
|
||||||
closerate = sell_row.open
|
|
||||||
|
|
||||||
return BacktestResult(pair=pair,
|
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),
|
profit_abs=trade.calc_profit(rate=closerate),
|
||||||
open_time=buy_row.date,
|
open_time=buy_row.date,
|
||||||
close_time=sell_row.date,
|
close_time=sell_row.date,
|
||||||
@@ -290,7 +259,7 @@ class Backtesting:
|
|||||||
# no sell condition found - trade stil open at end of backtest period
|
# no sell condition found - trade stil open at end of backtest period
|
||||||
sell_row = partial_ticker[-1]
|
sell_row = partial_ticker[-1]
|
||||||
bt_res = BacktestResult(pair=pair,
|
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),
|
profit_abs=trade.calc_profit(rate=sell_row.open),
|
||||||
open_time=buy_row.date,
|
open_time=buy_row.date,
|
||||||
close_time=sell_row.date,
|
close_time=sell_row.date,
|
||||||
@@ -310,30 +279,28 @@ class Backtesting:
|
|||||||
return bt_res
|
return bt_res
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def backtest(self, args: Dict) -> DataFrame:
|
def backtest(self, processed: Dict, stake_amount: float,
|
||||||
|
start_date, end_date,
|
||||||
|
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.
|
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.
|
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:
|
:param processed: a processed dictionary with format {pair, data}
|
||||||
stake_amount: btc amount to use for each trade
|
:param stake_amount: amount to use for each trade
|
||||||
processed: a processed dictionary with format {pair, data}
|
:param start_date: backtesting timerange start datetime
|
||||||
max_open_trades: maximum number of concurrent trades (default: 0, disabled)
|
:param end_date: backtesting timerange end datetime
|
||||||
position_stacking: do we allow position stacking? (default: False)
|
:param max_open_trades: maximum number of concurrent trades, <= 0 means unlimited
|
||||||
:return: DataFrame
|
: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.
|
logger.debug(f"Run backtest, stake_amount: {stake_amount}, "
|
||||||
# Uncomment if you need to debug the backtest() method.
|
f"start_date: {start_date}, end_date: {end_date}, "
|
||||||
# logger.debug(f"Start backtest, args: {args}")
|
f"max_open_trades: {max_open_trades}, position_stacking: {position_stacking}"
|
||||||
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']
|
|
||||||
trades = []
|
trades = []
|
||||||
trade_count_lock: Dict = {}
|
trade_count_lock: Dict = {}
|
||||||
|
|
||||||
@@ -343,7 +310,7 @@ class Backtesting:
|
|||||||
lock_pair_until: Dict = {}
|
lock_pair_until: Dict = {}
|
||||||
# Indexes per pair, so some pairs are allowed to have a missing start.
|
# Indexes per pair, so some pairs are allowed to have a missing start.
|
||||||
indexes: Dict = {}
|
indexes: Dict = {}
|
||||||
tmp = start_date + timedelta(minutes=self.ticker_interval_mins)
|
tmp = start_date + timedelta(minutes=self.timeframe_min)
|
||||||
|
|
||||||
# Loop timerange and get candle for each pair at that point in time
|
# Loop timerange and get candle for each pair at that point in time
|
||||||
while tmp < end_date:
|
while tmp < end_date:
|
||||||
@@ -395,48 +362,30 @@ class Backtesting:
|
|||||||
lock_pair_until[pair] = end_date.datetime
|
lock_pair_until[pair] = end_date.datetime
|
||||||
|
|
||||||
# Move time one configured time_interval ahead.
|
# Move time one configured time_interval ahead.
|
||||||
tmp += timedelta(minutes=self.ticker_interval_mins)
|
tmp += timedelta(minutes=self.timeframe_min)
|
||||||
return DataFrame.from_records(trades, columns=BacktestResult._fields)
|
return DataFrame.from_records(trades, columns=BacktestResult._fields)
|
||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
"""
|
"""
|
||||||
Run a backtesting end-to-end
|
Run backtesting end-to-end
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
data: Dict[str, Any] = {}
|
data: Dict[str, Any] = {}
|
||||||
pairs = self.config['exchange']['pair_whitelist']
|
|
||||||
logger.info('Using stake_currency: %s ...', self.config['stake_currency'])
|
logger.info('Using stake_currency: %s ...', self.config['stake_currency'])
|
||||||
logger.info('Using stake_amount: %s ...', self.config['stake_amount'])
|
logger.info('Using stake_amount: %s ...', self.config['stake_amount'])
|
||||||
|
|
||||||
timerange = TimeRange.parse_timerange(None if self.config.get(
|
|
||||||
'timerange') is None else str(self.config.get('timerange')))
|
|
||||||
data = history.load_data(
|
|
||||||
datadir=Path(self.config['datadir']),
|
|
||||||
pairs=pairs,
|
|
||||||
ticker_interval=self.ticker_interval,
|
|
||||||
timerange=timerange,
|
|
||||||
)
|
|
||||||
|
|
||||||
if not data:
|
|
||||||
logger.critical("No data found. Terminating.")
|
|
||||||
return
|
|
||||||
# Use max_open_trades in backtesting, except --disable-max-market-positions is set
|
# Use max_open_trades in backtesting, except --disable-max-market-positions is set
|
||||||
if self.config.get('use_max_market_positions', True):
|
if self.config.get('use_max_market_positions', True):
|
||||||
max_open_trades = self.config['max_open_trades']
|
max_open_trades = self.config['max_open_trades']
|
||||||
else:
|
else:
|
||||||
logger.info('Ignoring max_open_trades (--disable-max-market-positions was used) ...')
|
logger.info('Ignoring max_open_trades (--disable-max-market-positions was used) ...')
|
||||||
max_open_trades = 0
|
max_open_trades = 0
|
||||||
|
position_stacking = self.config.get('position_stacking', False)
|
||||||
|
|
||||||
|
data, timerange = self.load_bt_data()
|
||||||
|
|
||||||
all_results = {}
|
all_results = {}
|
||||||
|
|
||||||
min_date, max_date = history.get_timeframe(data)
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
'Backtesting with data from %s up to %s (%s days)..',
|
|
||||||
min_date.isoformat(),
|
|
||||||
max_date.isoformat(),
|
|
||||||
(max_date - min_date).days
|
|
||||||
)
|
|
||||||
|
|
||||||
for strat in self.strategylist:
|
for strat in self.strategylist:
|
||||||
logger.info("Running backtesting for Strategy %s", strat.get_strategy_name())
|
logger.info("Running backtesting for Strategy %s", strat.get_strategy_name())
|
||||||
self._set_strategy(strat)
|
self._set_strategy(strat)
|
||||||
@@ -444,16 +393,23 @@ class Backtesting:
|
|||||||
# need to reprocess data every time to populate signals
|
# need to reprocess data every time to populate signals
|
||||||
preprocessed = self.strategy.tickerdata_to_dataframe(data)
|
preprocessed = self.strategy.tickerdata_to_dataframe(data)
|
||||||
|
|
||||||
|
# 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_timerange(preprocessed)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
'Backtesting with data from %s up to %s (%s days)..',
|
||||||
|
min_date.isoformat(), max_date.isoformat(), (max_date - min_date).days
|
||||||
|
)
|
||||||
# Execute backtest and print results
|
# Execute backtest and print results
|
||||||
all_results[self.strategy.get_strategy_name()] = self.backtest(
|
all_results[self.strategy.get_strategy_name()] = self.backtest(
|
||||||
{
|
processed=preprocessed,
|
||||||
'stake_amount': self.config.get('stake_amount'),
|
stake_amount=self.config['stake_amount'],
|
||||||
'processed': preprocessed,
|
start_date=min_date,
|
||||||
'max_open_trades': max_open_trades,
|
end_date=max_date,
|
||||||
'position_stacking': self.config.get('position_stacking', False),
|
max_open_trades=max_open_trades,
|
||||||
'start_date': min_date,
|
position_stacking=position_stacking,
|
||||||
'end_date': max_date,
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
for strategy, results in all_results.items():
|
for strategy, results in all_results.items():
|
||||||
@@ -464,16 +420,24 @@ class Backtesting:
|
|||||||
|
|
||||||
print(f"Result for strategy {strategy}")
|
print(f"Result for strategy {strategy}")
|
||||||
print(' BACKTESTING REPORT '.center(133, '='))
|
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(' SELL REASON STATS '.center(133, '='))
|
||||||
print(self._generate_text_table_sell_reason(data, results))
|
print(generate_text_table_sell_reason(data, results))
|
||||||
|
|
||||||
print(' LEFT OPEN TRADES REPORT '.center(133, '='))
|
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()
|
print()
|
||||||
if len(all_results) > 1:
|
if len(all_results) > 1:
|
||||||
# Print Strategy summary table
|
# Print Strategy summary table
|
||||||
print(' Strategy Summary '.center(133, '='))
|
print(' Strategy Summary '.center(133, '='))
|
||||||
print(self._generate_text_table_strategy(all_results))
|
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')
|
print('\nFor more details, please look at the detail tables above')
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import freqtrade.vendor.qtpylib.indicators as qtpylib
|
|||||||
from freqtrade.optimize.hyperopt_interface import IHyperOpt
|
from freqtrade.optimize.hyperopt_interface import IHyperOpt
|
||||||
|
|
||||||
|
|
||||||
class DefaultHyperOpts(IHyperOpt):
|
class DefaultHyperOpt(IHyperOpt):
|
||||||
"""
|
"""
|
||||||
Default hyperopt provided by the Freqtrade bot.
|
Default hyperopt provided by the Freqtrade bot.
|
||||||
You can override it with your own Hyperopt
|
You can override it with your own Hyperopt
|
||||||
|
|||||||
@@ -4,14 +4,14 @@
|
|||||||
This module contains the edge backtesting interface
|
This module contains the edge backtesting interface
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
from typing import Dict, Any
|
from typing import Any, Dict
|
||||||
from tabulate import tabulate
|
|
||||||
from freqtrade import constants
|
|
||||||
from freqtrade.edge import Edge
|
|
||||||
|
|
||||||
from freqtrade.configuration import TimeRange
|
from freqtrade import constants
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.configuration import (TimeRange, remove_credentials,
|
||||||
from freqtrade.resolvers import StrategyResolver
|
validate_config_consistency)
|
||||||
|
from freqtrade.edge import Edge
|
||||||
|
from freqtrade.optimize.optimize_reports import generate_edge_table
|
||||||
|
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -29,51 +29,22 @@ class EdgeCli:
|
|||||||
self.config = config
|
self.config = config
|
||||||
|
|
||||||
# Reset keys for edge
|
# Reset keys for edge
|
||||||
self.config['exchange']['key'] = ''
|
remove_credentials(self.config)
|
||||||
self.config['exchange']['secret'] = ''
|
|
||||||
self.config['exchange']['password'] = ''
|
|
||||||
self.config['exchange']['uid'] = ''
|
|
||||||
self.config['stake_amount'] = constants.UNLIMITED_STAKE_AMOUNT
|
self.config['stake_amount'] = constants.UNLIMITED_STAKE_AMOUNT
|
||||||
self.config['dry_run'] = True
|
self.exchange = ExchangeResolver.load_exchange(self.config['exchange']['name'], self.config)
|
||||||
self.exchange = Exchange(self.config)
|
self.strategy = StrategyResolver.load_strategy(self.config)
|
||||||
self.strategy = StrategyResolver(self.config).strategy
|
|
||||||
|
validate_config_consistency(self.config)
|
||||||
|
|
||||||
self.edge = Edge(config, self.exchange, self.strategy)
|
self.edge = Edge(config, self.exchange, self.strategy)
|
||||||
# Set refresh_pairs to false for edge-cli (it must be true for edge)
|
# Set refresh_pairs to false for edge-cli (it must be true for edge)
|
||||||
self.edge._refresh_pairs = False
|
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')))
|
'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, # type: ignore
|
|
||||||
floatfmt=floatfmt, tablefmt="pipe")
|
|
||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
result = self.edge.calculate()
|
result = self.edge.calculate()
|
||||||
if result:
|
if result:
|
||||||
print('') # blank line for readability
|
print('') # blank line for readability
|
||||||
print(self._generate_edge_table(self.edge._cached_pairs))
|
print(generate_edge_table(self.edge._cached_pairs))
|
||||||
|
|||||||
@@ -4,9 +4,11 @@
|
|||||||
This module contains the hyperopt logic
|
This module contains the hyperopt logic
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import locale
|
||||||
import logging
|
import logging
|
||||||
|
import random
|
||||||
import sys
|
import sys
|
||||||
|
import warnings
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
from operator import itemgetter
|
from operator import itemgetter
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -14,22 +16,27 @@ from pprint import pprint
|
|||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
import rapidjson
|
import rapidjson
|
||||||
|
|
||||||
from colorama import init as colorama_init
|
|
||||||
from colorama import Fore, Style
|
from colorama import Fore, Style
|
||||||
from joblib import Parallel, delayed, dump, load, wrap_non_picklable_objects, cpu_count
|
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 pandas import DataFrame
|
||||||
from skopt import Optimizer
|
|
||||||
from skopt.space import Dimension
|
|
||||||
|
|
||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.data.history import get_timerange, trim_dataframe
|
||||||
from freqtrade.data.history import load_data, get_timeframe
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.misc import round_dict
|
from freqtrade.misc import plural, round_dict
|
||||||
from freqtrade.optimize.backtesting import Backtesting
|
from freqtrade.optimize.backtesting import Backtesting
|
||||||
# Import IHyperOpt and IHyperOptLoss to allow unpickling classes from these modules
|
# Import IHyperOpt and IHyperOptLoss to allow unpickling classes from these modules
|
||||||
from freqtrade.optimize.hyperopt_interface import IHyperOpt # noqa: F4
|
from freqtrade.optimize.hyperopt_interface import IHyperOpt # noqa: F401
|
||||||
from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss # noqa: F4
|
from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss # noqa: F401
|
||||||
from freqtrade.resolvers.hyperopt_resolver import HyperOptResolver, HyperOptLossResolver
|
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__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -55,11 +62,11 @@ class Hyperopt:
|
|||||||
def __init__(self, config: Dict[str, Any]) -> None:
|
def __init__(self, config: Dict[str, Any]) -> None:
|
||||||
self.config = config
|
self.config = config
|
||||||
|
|
||||||
self.custom_hyperopt = HyperOptResolver(self.config).hyperopt
|
|
||||||
|
|
||||||
self.backtesting = Backtesting(self.config)
|
self.backtesting = Backtesting(self.config)
|
||||||
|
|
||||||
self.custom_hyperoptloss = HyperOptLossResolver(self.config).hyperoptloss
|
self.custom_hyperopt = HyperOptResolver.load_hyperopt(self.config)
|
||||||
|
|
||||||
|
self.custom_hyperoptloss = HyperOptLossResolver.load_hyperoptloss(self.config)
|
||||||
self.calculate_loss = self.custom_hyperoptloss.hyperopt_loss_function
|
self.calculate_loss = self.custom_hyperoptloss.hyperopt_loss_function
|
||||||
|
|
||||||
self.trials_file = (self.config['user_data_dir'] /
|
self.trials_file = (self.config['user_data_dir'] /
|
||||||
@@ -75,6 +82,8 @@ class Hyperopt:
|
|||||||
else:
|
else:
|
||||||
logger.info("Continuing on previous hyperopt results.")
|
logger.info("Continuing on previous hyperopt results.")
|
||||||
|
|
||||||
|
self.num_trials_saved = 0
|
||||||
|
|
||||||
# Previous evaluations
|
# Previous evaluations
|
||||||
self.trials: List = []
|
self.trials: List = []
|
||||||
|
|
||||||
@@ -98,10 +107,14 @@ class Hyperopt:
|
|||||||
self.position_stacking = self.config.get('position_stacking', False)
|
self.position_stacking = self.config.get('position_stacking', False)
|
||||||
|
|
||||||
if self.has_space('sell'):
|
if self.has_space('sell'):
|
||||||
# Make sure experimental is enabled
|
# Make sure use_sell_signal is enabled
|
||||||
if 'experimental' not in self.config:
|
if 'ask_strategy' not in self.config:
|
||||||
self.config['experimental'] = {}
|
self.config['ask_strategy'] = {}
|
||||||
self.config['experimental']['use_sell_signal'] = True
|
self.config['ask_strategy']['use_sell_signal'] = True
|
||||||
|
|
||||||
|
self.print_all = self.config.get('print_all', False)
|
||||||
|
self.print_colorized = self.config.get('print_colorized', False)
|
||||||
|
self.print_json = self.config.get('print_json', False)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_lock_filename(config) -> str:
|
def get_lock_filename(config) -> str:
|
||||||
@@ -118,125 +131,178 @@ class Hyperopt:
|
|||||||
logger.info(f"Removing `{p}`.")
|
logger.info(f"Removing `{p}`.")
|
||||||
p.unlink()
|
p.unlink()
|
||||||
|
|
||||||
def get_args(self, params):
|
def _get_params_dict(self, raw_params: List[Any]) -> Dict:
|
||||||
|
|
||||||
dimensions = self.dimensions
|
dimensions: List[Dimension] = self.dimensions
|
||||||
|
|
||||||
# Ensure the number of dimensions match
|
# Ensure the number of dimensions match
|
||||||
# the number of parameters in the list x.
|
# the number of parameters in the list.
|
||||||
if len(params) != len(dimensions):
|
if len(raw_params) != len(dimensions):
|
||||||
raise ValueError('Mismatch in number of search-space dimensions. '
|
raise ValueError('Mismatch in number of search-space dimensions.')
|
||||||
f'len(dimensions)=={len(dimensions)} and len(x)=={len(params)}')
|
|
||||||
|
|
||||||
# Create a dict where the keys are the names of the dimensions
|
# Return a dict where the keys are the names of the dimensions
|
||||||
# and the values are taken from the list of parameters x.
|
# and the values are taken from the list of parameters.
|
||||||
arg_dict = {dim.name: value for dim, value in zip(dimensions, params)}
|
return {d.name: v for d, v in zip(dimensions, raw_params)}
|
||||||
return arg_dict
|
|
||||||
|
|
||||||
def save_trials(self) -> None:
|
def save_trials(self, final: bool = False) -> None:
|
||||||
"""
|
"""
|
||||||
Save hyperopt trials to file
|
Save hyperopt trials to file
|
||||||
"""
|
"""
|
||||||
if self.trials:
|
num_trials = len(self.trials)
|
||||||
logger.info("Saving %d evaluations to '%s'", len(self.trials), self.trials_file)
|
if num_trials > self.num_trials_saved:
|
||||||
|
logger.info(f"Saving {num_trials} {plural(num_trials, 'epoch')}.")
|
||||||
dump(self.trials, self.trials_file)
|
dump(self.trials, self.trials_file)
|
||||||
|
self.num_trials_saved = num_trials
|
||||||
|
if final:
|
||||||
|
logger.info(f"{num_trials} {plural(num_trials, 'epoch')} "
|
||||||
|
f"saved to '{self.trials_file}'.")
|
||||||
|
|
||||||
def read_trials(self) -> List:
|
@staticmethod
|
||||||
|
def _read_trials(trials_file) -> List:
|
||||||
"""
|
"""
|
||||||
Read hyperopt trials file
|
Read hyperopt trials file
|
||||||
"""
|
"""
|
||||||
logger.info("Reading Trials from '%s'", self.trials_file)
|
logger.info("Reading Trials from '%s'", trials_file)
|
||||||
trials = load(self.trials_file)
|
trials = load(trials_file)
|
||||||
self.trials_file.unlink()
|
|
||||||
return trials
|
return trials
|
||||||
|
|
||||||
def log_trials_result(self) -> None:
|
def _get_params_details(self, params: Dict) -> Dict:
|
||||||
"""
|
"""
|
||||||
Display Best hyperopt result
|
Return the params for each space
|
||||||
"""
|
"""
|
||||||
results = sorted(self.trials, key=itemgetter('loss'))
|
result: Dict = {}
|
||||||
best_result = results[0]
|
|
||||||
params = best_result['params']
|
|
||||||
log_str = self.format_results_logstring(best_result)
|
|
||||||
print(f"\nBest result:\n\n{log_str}\n")
|
|
||||||
|
|
||||||
if self.config.get('print_json'):
|
if self.has_space('buy'):
|
||||||
|
result['buy'] = {p.name: params.get(p.name)
|
||||||
|
for p in self.hyperopt_space('buy')}
|
||||||
|
if self.has_space('sell'):
|
||||||
|
result['sell'] = {p.name: params.get(p.name)
|
||||||
|
for p in self.hyperopt_space('sell')}
|
||||||
|
if self.has_space('roi'):
|
||||||
|
result['roi'] = self.custom_hyperopt.generate_roi_table(params)
|
||||||
|
if self.has_space('stoploss'):
|
||||||
|
result['stoploss'] = {p.name: params.get(p.name)
|
||||||
|
for p in self.hyperopt_space('stoploss')}
|
||||||
|
if self.has_space('trailing'):
|
||||||
|
result['trailing'] = self.custom_hyperopt.generate_trailing_params(params)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def print_epoch_details(results, total_epochs, print_json: bool,
|
||||||
|
no_header: bool = False, header_str: str = None) -> None:
|
||||||
|
"""
|
||||||
|
Display details of the hyperopt result
|
||||||
|
"""
|
||||||
|
params = results.get('params_details', {})
|
||||||
|
|
||||||
|
# Default header string
|
||||||
|
if header_str is None:
|
||||||
|
header_str = "Best result"
|
||||||
|
|
||||||
|
if not no_header:
|
||||||
|
explanation_str = Hyperopt._format_explanation_string(results, total_epochs)
|
||||||
|
print(f"\n{header_str}:\n\n{explanation_str}\n")
|
||||||
|
|
||||||
|
if print_json:
|
||||||
result_dict: Dict = {}
|
result_dict: Dict = {}
|
||||||
if self.has_space('buy') or self.has_space('sell'):
|
for s in ['buy', 'sell', 'roi', 'stoploss', 'trailing']:
|
||||||
result_dict['params'] = {}
|
Hyperopt._params_update_for_json(result_dict, params, s)
|
||||||
if self.has_space('buy'):
|
print(rapidjson.dumps(result_dict, default=str, number_mode=rapidjson.NM_NATIVE))
|
||||||
result_dict['params'].update({p.name: params.get(p.name)
|
|
||||||
for p in self.hyperopt_space('buy')})
|
else:
|
||||||
if self.has_space('sell'):
|
Hyperopt._params_pretty_print(params, 'buy', "Buy hyperspace params:")
|
||||||
result_dict['params'].update({p.name: params.get(p.name)
|
Hyperopt._params_pretty_print(params, 'sell', "Sell hyperspace params:")
|
||||||
for p in self.hyperopt_space('sell')})
|
Hyperopt._params_pretty_print(params, 'roi', "ROI table:")
|
||||||
if self.has_space('roi'):
|
Hyperopt._params_pretty_print(params, 'stoploss', "Stoploss:")
|
||||||
|
Hyperopt._params_pretty_print(params, 'trailing', "Trailing stop:")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _params_update_for_json(result_dict, params, space: str):
|
||||||
|
if space in params:
|
||||||
|
space_params = Hyperopt._space_params(params, space)
|
||||||
|
if space in ['buy', 'sell']:
|
||||||
|
result_dict.setdefault('params', {}).update(space_params)
|
||||||
|
elif space == 'roi':
|
||||||
# Convert keys in min_roi dict to strings because
|
# Convert keys in min_roi dict to strings because
|
||||||
# rapidjson cannot dump dicts with integer keys...
|
# rapidjson cannot dump dicts with integer keys...
|
||||||
# OrderedDict is used to keep the numeric order of the items
|
# OrderedDict is used to keep the numeric order of the items
|
||||||
# in the dict.
|
# in the dict.
|
||||||
result_dict['minimal_roi'] = OrderedDict(
|
result_dict['minimal_roi'] = OrderedDict(
|
||||||
(str(k), v) for k, v in self.custom_hyperopt.generate_roi_table(params).items()
|
(str(k), v) for k, v in space_params.items()
|
||||||
)
|
)
|
||||||
if self.has_space('stoploss'):
|
else: # 'stoploss', 'trailing'
|
||||||
result_dict['stoploss'] = params.get('stoploss')
|
result_dict.update(space_params)
|
||||||
print(rapidjson.dumps(result_dict, default=str, number_mode=rapidjson.NM_NATIVE))
|
|
||||||
else:
|
|
||||||
if self.has_space('buy'):
|
|
||||||
print('Buy hyperspace params:')
|
|
||||||
pprint({p.name: params.get(p.name) for p in self.hyperopt_space('buy')},
|
|
||||||
indent=4)
|
|
||||||
if self.has_space('sell'):
|
|
||||||
print('Sell hyperspace params:')
|
|
||||||
pprint({p.name: params.get(p.name) for p in self.hyperopt_space('sell')},
|
|
||||||
indent=4)
|
|
||||||
if self.has_space('roi'):
|
|
||||||
print("ROI table:")
|
|
||||||
# Round printed values to 5 digits after the decimal point
|
|
||||||
pprint(round_dict(self.custom_hyperopt.generate_roi_table(params), 5), indent=4)
|
|
||||||
if self.has_space('stoploss'):
|
|
||||||
# Also round to 5 digits after the decimal point
|
|
||||||
print(f"Stoploss: {round(params.get('stoploss'), 5)}")
|
|
||||||
|
|
||||||
def log_results(self, results) -> None:
|
@staticmethod
|
||||||
|
def _params_pretty_print(params, space: str, header: str):
|
||||||
|
if space in params:
|
||||||
|
space_params = Hyperopt._space_params(params, space, 5)
|
||||||
|
if space == 'stoploss':
|
||||||
|
print(header, space_params.get('stoploss'))
|
||||||
|
else:
|
||||||
|
print(header)
|
||||||
|
pprint(space_params, indent=4)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _space_params(params, space: str, r: int = None) -> Dict:
|
||||||
|
d = params[space]
|
||||||
|
# Round floats to `r` digits after the decimal point if requested
|
||||||
|
return round_dict(d, r) if r else d
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def is_best_loss(results, current_best_loss) -> bool:
|
||||||
|
return results['loss'] < current_best_loss
|
||||||
|
|
||||||
|
def print_results(self, results) -> None:
|
||||||
"""
|
"""
|
||||||
Log results if it is better than any previous evaluation
|
Log results if it is better than any previous evaluation
|
||||||
"""
|
"""
|
||||||
print_all = self.config.get('print_all', False)
|
is_best = results['is_best']
|
||||||
is_best_loss = results['loss'] < self.current_best_loss
|
if not self.print_all:
|
||||||
if print_all or is_best_loss:
|
# Print '\n' after each 100th epoch to separate dots from the log messages.
|
||||||
if is_best_loss:
|
# Otherwise output is messy on a terminal.
|
||||||
self.current_best_loss = results['loss']
|
print('.', end='' if results['current_epoch'] % 100 != 0 else None) # type: ignore
|
||||||
log_str = self.format_results_logstring(results)
|
|
||||||
# Colorize output
|
|
||||||
if self.config.get('print_colorized', False):
|
|
||||||
if results['total_profit'] > 0:
|
|
||||||
log_str = Fore.GREEN + log_str
|
|
||||||
if print_all and is_best_loss:
|
|
||||||
log_str = Style.BRIGHT + log_str
|
|
||||||
if print_all:
|
|
||||||
print(log_str)
|
|
||||||
else:
|
|
||||||
print('\n' + log_str)
|
|
||||||
else:
|
|
||||||
print('.', end='')
|
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
|
|
||||||
def format_results_logstring(self, results) -> str:
|
if self.print_all or is_best:
|
||||||
# Output human-friendly index here (starting from 1)
|
if not self.print_all:
|
||||||
current = results['current_epoch'] + 1
|
# Separate the results explanation string from dots
|
||||||
total = self.total_epochs
|
print("\n")
|
||||||
res = results['results_explanation']
|
self.print_results_explanation(results, self.total_epochs, self.print_all,
|
||||||
loss = results['loss']
|
self.print_colorized)
|
||||||
log_str = f'{current:5d}/{total}: {res} Objective: {loss:.5f}'
|
|
||||||
log_str = f'*{log_str}' if results['is_initial_point'] else f' {log_str}'
|
@staticmethod
|
||||||
return log_str
|
def print_results_explanation(results, total_epochs, highlight_best: bool,
|
||||||
|
print_colorized: bool) -> None:
|
||||||
|
"""
|
||||||
|
Log results explanation string
|
||||||
|
"""
|
||||||
|
explanation_str = Hyperopt._format_explanation_string(results, total_epochs)
|
||||||
|
# Colorize output
|
||||||
|
if print_colorized:
|
||||||
|
if results['total_profit'] > 0:
|
||||||
|
explanation_str = Fore.GREEN + explanation_str
|
||||||
|
if highlight_best and results['is_best']:
|
||||||
|
explanation_str = Style.BRIGHT + explanation_str
|
||||||
|
print(explanation_str)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _format_explanation_string(results, total_epochs) -> str:
|
||||||
|
return (("*" if results['is_initial_point'] else " ") +
|
||||||
|
f"{results['current_epoch']:5d}/{total_epochs}: " +
|
||||||
|
f"{results['results_explanation']} " +
|
||||||
|
f"Objective: {results['loss']:.5f}")
|
||||||
|
|
||||||
def has_space(self, space: str) -> bool:
|
def has_space(self, space: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Tell if a space value is contained in the configuration
|
Tell if the space value is contained in the configuration
|
||||||
"""
|
"""
|
||||||
return any(s in self.config['spaces'] for s in [space, 'all'])
|
# The 'trailing' space is not included in the 'default' set of spaces
|
||||||
|
if space == 'trailing':
|
||||||
|
return any(s in self.config['spaces'] for s in [space, 'all'])
|
||||||
|
else:
|
||||||
|
return any(s in self.config['spaces'] for s in [space, 'all', 'default'])
|
||||||
|
|
||||||
def hyperopt_space(self, space: Optional[str] = None) -> List[Dimension]:
|
def hyperopt_space(self, space: Optional[str] = None) -> List[Dimension]:
|
||||||
"""
|
"""
|
||||||
@@ -246,106 +312,130 @@ class Hyperopt:
|
|||||||
for all hyperspaces used.
|
for all hyperspaces used.
|
||||||
"""
|
"""
|
||||||
spaces: List[Dimension] = []
|
spaces: List[Dimension] = []
|
||||||
|
|
||||||
if space == 'buy' or (space is None and self.has_space('buy')):
|
if space == 'buy' or (space is None and self.has_space('buy')):
|
||||||
logger.debug("Hyperopt has 'buy' space")
|
logger.debug("Hyperopt has 'buy' space")
|
||||||
spaces += self.custom_hyperopt.indicator_space()
|
spaces += self.custom_hyperopt.indicator_space()
|
||||||
|
|
||||||
if space == 'sell' or (space is None and self.has_space('sell')):
|
if space == 'sell' or (space is None and self.has_space('sell')):
|
||||||
logger.debug("Hyperopt has 'sell' space")
|
logger.debug("Hyperopt has 'sell' space")
|
||||||
spaces += self.custom_hyperopt.sell_indicator_space()
|
spaces += self.custom_hyperopt.sell_indicator_space()
|
||||||
|
|
||||||
if space == 'roi' or (space is None and self.has_space('roi')):
|
if space == 'roi' or (space is None and self.has_space('roi')):
|
||||||
logger.debug("Hyperopt has 'roi' space")
|
logger.debug("Hyperopt has 'roi' space")
|
||||||
spaces += self.custom_hyperopt.roi_space()
|
spaces += self.custom_hyperopt.roi_space()
|
||||||
|
|
||||||
if space == 'stoploss' or (space is None and self.has_space('stoploss')):
|
if space == 'stoploss' or (space is None and self.has_space('stoploss')):
|
||||||
logger.debug("Hyperopt has 'stoploss' space")
|
logger.debug("Hyperopt has 'stoploss' space")
|
||||||
spaces += self.custom_hyperopt.stoploss_space()
|
spaces += self.custom_hyperopt.stoploss_space()
|
||||||
|
|
||||||
|
if space == 'trailing' or (space is None and self.has_space('trailing')):
|
||||||
|
logger.debug("Hyperopt has 'trailing' space")
|
||||||
|
spaces += self.custom_hyperopt.trailing_space()
|
||||||
|
|
||||||
return spaces
|
return spaces
|
||||||
|
|
||||||
def generate_optimizer(self, _params: Dict, iteration=None) -> Dict:
|
def generate_optimizer(self, raw_params: List[Any], iteration=None) -> Dict:
|
||||||
"""
|
"""
|
||||||
Used Optimize function. Called once per epoch to optimize whatever is configured.
|
Used Optimize function. Called once per epoch to optimize whatever is configured.
|
||||||
Keep this function as optimized as possible!
|
Keep this function as optimized as possible!
|
||||||
"""
|
"""
|
||||||
params = self.get_args(_params)
|
params_dict = self._get_params_dict(raw_params)
|
||||||
|
params_details = self._get_params_details(params_dict)
|
||||||
|
|
||||||
if self.has_space('roi'):
|
if self.has_space('roi'):
|
||||||
self.backtesting.strategy.minimal_roi = \
|
self.backtesting.strategy.minimal_roi = \
|
||||||
self.custom_hyperopt.generate_roi_table(params)
|
self.custom_hyperopt.generate_roi_table(params_dict)
|
||||||
|
|
||||||
if self.has_space('buy'):
|
if self.has_space('buy'):
|
||||||
self.backtesting.strategy.advise_buy = \
|
self.backtesting.strategy.advise_buy = \
|
||||||
self.custom_hyperopt.buy_strategy_generator(params)
|
self.custom_hyperopt.buy_strategy_generator(params_dict)
|
||||||
|
|
||||||
if self.has_space('sell'):
|
if self.has_space('sell'):
|
||||||
self.backtesting.strategy.advise_sell = \
|
self.backtesting.strategy.advise_sell = \
|
||||||
self.custom_hyperopt.sell_strategy_generator(params)
|
self.custom_hyperopt.sell_strategy_generator(params_dict)
|
||||||
|
|
||||||
if self.has_space('stoploss'):
|
if self.has_space('stoploss'):
|
||||||
self.backtesting.strategy.stoploss = params['stoploss']
|
self.backtesting.strategy.stoploss = params_dict['stoploss']
|
||||||
|
|
||||||
|
if self.has_space('trailing'):
|
||||||
|
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 = \
|
||||||
|
d['trailing_stop_positive_offset']
|
||||||
|
self.backtesting.strategy.trailing_only_offset_is_reached = \
|
||||||
|
d['trailing_only_offset_is_reached']
|
||||||
|
|
||||||
processed = load(self.tickerdata_pickle)
|
processed = load(self.tickerdata_pickle)
|
||||||
|
|
||||||
min_date, max_date = get_timeframe(processed)
|
min_date, max_date = get_timerange(processed)
|
||||||
|
|
||||||
results = self.backtesting.backtest(
|
backtesting_results = self.backtesting.backtest(
|
||||||
{
|
processed=processed,
|
||||||
'stake_amount': self.config['stake_amount'],
|
stake_amount=self.config['stake_amount'],
|
||||||
'processed': processed,
|
start_date=min_date,
|
||||||
'max_open_trades': self.max_open_trades,
|
end_date=max_date,
|
||||||
'position_stacking': self.position_stacking,
|
max_open_trades=self.max_open_trades,
|
||||||
'start_date': min_date,
|
position_stacking=self.position_stacking,
|
||||||
'end_date': max_date,
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
results_explanation = self.format_results(results)
|
return self._get_results_dict(backtesting_results, min_date, max_date,
|
||||||
|
params_dict, params_details)
|
||||||
|
|
||||||
trade_count = len(results.index)
|
def _get_results_dict(self, backtesting_results, min_date, max_date,
|
||||||
total_profit = results.profit_abs.sum()
|
params_dict, params_details):
|
||||||
|
results_metrics = self._calculate_results_metrics(backtesting_results)
|
||||||
|
results_explanation = self._format_results_explanation_string(results_metrics)
|
||||||
|
|
||||||
|
trade_count = results_metrics['trade_count']
|
||||||
|
total_profit = results_metrics['total_profit']
|
||||||
|
|
||||||
# If this evaluation contains too short amount of trades to be
|
# If this evaluation contains too short amount of trades to be
|
||||||
# interesting -- consider it as 'bad' (assigned max. loss value)
|
# interesting -- consider it as 'bad' (assigned max. loss value)
|
||||||
# in order to cast this hyperspace point away from optimization
|
# in order to cast this hyperspace point away from optimization
|
||||||
# path. We do not want to optimize 'hodl' strategies.
|
# path. We do not want to optimize 'hodl' strategies.
|
||||||
if trade_count < self.config['hyperopt_min_trades']:
|
loss: float = MAX_LOSS
|
||||||
return {
|
if trade_count >= self.config['hyperopt_min_trades']:
|
||||||
'loss': MAX_LOSS,
|
loss = self.calculate_loss(results=backtesting_results, trade_count=trade_count,
|
||||||
'params': params,
|
min_date=min_date.datetime, max_date=max_date.datetime)
|
||||||
'results_explanation': results_explanation,
|
|
||||||
'total_profit': total_profit,
|
|
||||||
}
|
|
||||||
|
|
||||||
loss = self.calculate_loss(results=results, trade_count=trade_count,
|
|
||||||
min_date=min_date.datetime, max_date=max_date.datetime)
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'loss': loss,
|
'loss': loss,
|
||||||
'params': params,
|
'params_dict': params_dict,
|
||||||
|
'params_details': params_details,
|
||||||
|
'results_metrics': results_metrics,
|
||||||
'results_explanation': results_explanation,
|
'results_explanation': results_explanation,
|
||||||
'total_profit': total_profit,
|
'total_profit': total_profit,
|
||||||
}
|
}
|
||||||
|
|
||||||
def format_results(self, results: DataFrame) -> str:
|
def _calculate_results_metrics(self, backtesting_results: DataFrame) -> Dict:
|
||||||
|
return {
|
||||||
|
'trade_count': len(backtesting_results.index),
|
||||||
|
'avg_profit': backtesting_results.profit_percent.mean() * 100.0,
|
||||||
|
'total_profit': backtesting_results.profit_abs.sum(),
|
||||||
|
'profit': backtesting_results.profit_percent.sum() * 100.0,
|
||||||
|
'duration': backtesting_results.trade_duration.mean(),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _format_results_explanation_string(self, results_metrics: Dict) -> str:
|
||||||
"""
|
"""
|
||||||
Return the formatted results explanation in a string
|
Return the formatted results explanation in a string
|
||||||
"""
|
"""
|
||||||
trades = len(results.index)
|
|
||||||
avg_profit = results.profit_percent.mean() * 100.0
|
|
||||||
total_profit = results.profit_abs.sum()
|
|
||||||
stake_cur = self.config['stake_currency']
|
stake_cur = self.config['stake_currency']
|
||||||
profit = results.profit_percent.sum() * 100.0
|
return (f"{results_metrics['trade_count']:6d} trades. "
|
||||||
duration = results.trade_duration.mean()
|
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} min."
|
||||||
|
).encode(locale.getpreferredencoding(), 'replace').decode('utf-8')
|
||||||
|
|
||||||
return (f'{trades:6d} trades. Avg profit {avg_profit: 5.2f}%. '
|
def get_optimizer(self, dimensions: List[Dimension], cpu_count) -> Optimizer:
|
||||||
f'Total profit {total_profit: 11.8f} {stake_cur} '
|
|
||||||
f'({profit: 7.2f}Σ%). Avg duration {duration:5.1f} mins.')
|
|
||||||
|
|
||||||
def get_optimizer(self, dimensions, cpu_count) -> Optimizer:
|
|
||||||
return Optimizer(
|
return Optimizer(
|
||||||
dimensions,
|
dimensions,
|
||||||
base_estimator="ET",
|
base_estimator="ET",
|
||||||
acq_optimizer="auto",
|
acq_optimizer="auto",
|
||||||
n_initial_points=INITIAL_POINTS,
|
n_initial_points=INITIAL_POINTS,
|
||||||
acq_optimizer_kwargs={'n_jobs': cpu_count},
|
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):
|
||||||
@@ -369,56 +459,57 @@ class Hyperopt:
|
|||||||
return parallel(delayed(
|
return parallel(delayed(
|
||||||
wrap_non_picklable_objects(self.generate_optimizer))(v, i) for v in asked)
|
wrap_non_picklable_objects(self.generate_optimizer))(v, i) for v in asked)
|
||||||
|
|
||||||
def load_previous_results(self):
|
@staticmethod
|
||||||
""" read trials file if we have one """
|
def load_previous_results(trials_file) -> List:
|
||||||
if self.trials_file.is_file() and self.trials_file.stat().st_size > 0:
|
"""
|
||||||
self.trials = self.read_trials()
|
Load data for epochs from the file if we have one
|
||||||
logger.info(
|
"""
|
||||||
'Loaded %d previous evaluations from disk.',
|
trials: List = []
|
||||||
len(self.trials)
|
if trials_file.is_file() and trials_file.stat().st_size > 0:
|
||||||
)
|
trials = Hyperopt._read_trials(trials_file)
|
||||||
|
if trials[0].get('is_best') is None:
|
||||||
|
raise OperationalException(
|
||||||
|
"The file with Hyperopt results is incompatible with this version "
|
||||||
|
"of Freqtrade and cannot be loaded.")
|
||||||
|
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:
|
def start(self) -> None:
|
||||||
timerange = TimeRange.parse_timerange(None if self.config.get(
|
self.random_state = self._set_random_state(self.config.get('hyperopt_random_state', None))
|
||||||
'timerange') is None else str(self.config.get('timerange')))
|
logger.info(f"Using optimizer random state: {self.random_state}")
|
||||||
data = load_data(
|
|
||||||
datadir=Path(self.config['datadir']),
|
|
||||||
pairs=self.config['exchange']['pair_whitelist'],
|
|
||||||
ticker_interval=self.backtesting.ticker_interval,
|
|
||||||
timerange=timerange
|
|
||||||
)
|
|
||||||
|
|
||||||
if not data:
|
data, timerange = self.backtesting.load_bt_data()
|
||||||
logger.critical("No data found. Terminating.")
|
|
||||||
return
|
|
||||||
|
|
||||||
min_date, max_date = get_timeframe(data)
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
'Hyperopting with data from %s up to %s (%s days)..',
|
|
||||||
min_date.isoformat(),
|
|
||||||
max_date.isoformat(),
|
|
||||||
(max_date - min_date).days
|
|
||||||
)
|
|
||||||
|
|
||||||
preprocessed = self.backtesting.strategy.tickerdata_to_dataframe(data)
|
preprocessed = self.backtesting.strategy.tickerdata_to_dataframe(data)
|
||||||
|
|
||||||
|
# Trim startup period from analyzed dataframe
|
||||||
|
for pair, df in preprocessed.items():
|
||||||
|
preprocessed[pair] = trim_dataframe(df, timerange)
|
||||||
|
min_date, max_date = get_timerange(data)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
'Hyperopting with data from %s up to %s (%s days)..',
|
||||||
|
min_date.isoformat(), max_date.isoformat(), (max_date - min_date).days
|
||||||
|
)
|
||||||
dump(preprocessed, self.tickerdata_pickle)
|
dump(preprocessed, self.tickerdata_pickle)
|
||||||
|
|
||||||
# We don't need exchange instance anymore while running hyperopt
|
# We don't need exchange instance anymore while running hyperopt
|
||||||
self.backtesting.exchange = None # type: ignore
|
self.backtesting.exchange = None # type: ignore
|
||||||
|
|
||||||
self.load_previous_results()
|
self.trials = self.load_previous_results(self.trials_file)
|
||||||
|
|
||||||
cpus = cpu_count()
|
cpus = cpu_count()
|
||||||
logger.info(f"Found {cpus} CPU cores. Let's make them scream!")
|
logger.info(f"Found {cpus} CPU cores. Let's make them scream!")
|
||||||
config_jobs = self.config.get('hyperopt_jobs', -1)
|
config_jobs = self.config.get('hyperopt_jobs', -1)
|
||||||
logger.info(f'Number of parallel jobs set as: {config_jobs}')
|
logger.info(f'Number of parallel jobs set as: {config_jobs}')
|
||||||
|
|
||||||
self.dimensions = self.hyperopt_space()
|
self.dimensions: List[Dimension] = self.hyperopt_space()
|
||||||
self.opt = self.get_optimizer(self.dimensions, config_jobs)
|
self.opt = self.get_optimizer(self.dimensions, config_jobs)
|
||||||
|
|
||||||
if self.config.get('print_colorized', False):
|
if self.print_colorized:
|
||||||
colorama_init(autoreset=True)
|
colorama_init(autoreset=True)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -432,15 +523,38 @@ class Hyperopt:
|
|||||||
self.opt.tell(asked, [v['loss'] for v in f_val])
|
self.opt.tell(asked, [v['loss'] for v in f_val])
|
||||||
self.fix_optimizer_models_list()
|
self.fix_optimizer_models_list()
|
||||||
for j in range(jobs):
|
for j in range(jobs):
|
||||||
current = i * jobs + j
|
# Use human-friendly indexes here (starting from 1)
|
||||||
|
current = i * jobs + j + 1
|
||||||
val = f_val[j]
|
val = f_val[j]
|
||||||
val['current_epoch'] = current
|
val['current_epoch'] = current
|
||||||
val['is_initial_point'] = current < INITIAL_POINTS
|
val['is_initial_point'] = current <= INITIAL_POINTS
|
||||||
self.log_results(val)
|
|
||||||
self.trials.append(val)
|
|
||||||
logger.debug(f"Optimizer epoch evaluated: {val}")
|
logger.debug(f"Optimizer epoch evaluated: {val}")
|
||||||
|
|
||||||
|
is_best = self.is_best_loss(val, self.current_best_loss)
|
||||||
|
# This value is assigned here and not in the optimization method
|
||||||
|
# to keep proper order in the list of results. That's because
|
||||||
|
# evaluations can take different time. Here they are aligned in the
|
||||||
|
# order they will be shown to the user.
|
||||||
|
val['is_best'] = is_best
|
||||||
|
|
||||||
|
self.print_results(val)
|
||||||
|
|
||||||
|
if is_best:
|
||||||
|
self.current_best_loss = val['loss']
|
||||||
|
self.trials.append(val)
|
||||||
|
# Save results after each best epoch and every 100 epochs
|
||||||
|
if is_best or current % 100 == 0:
|
||||||
|
self.save_trials()
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print('User interrupted..')
|
print('User interrupted..')
|
||||||
|
|
||||||
self.save_trials()
|
self.save_trials(final=True)
|
||||||
self.log_trials_result()
|
|
||||||
|
if self.trials:
|
||||||
|
sorted_trials = sorted(self.trials, key=itemgetter('loss'))
|
||||||
|
results = sorted_trials[0]
|
||||||
|
self.print_epoch_details(results, self.total_epochs, self.print_json)
|
||||||
|
else:
|
||||||
|
# This is printed when Ctrl+C is pressed quickly, before first epochs have
|
||||||
|
# a chance to be evaluated.
|
||||||
|
print("No epochs evaluated yet, no best result.")
|
||||||
|
|||||||
@@ -1,21 +1,18 @@
|
|||||||
"""
|
"""
|
||||||
IHyperOpt interface
|
IHyperOpt interface
|
||||||
This module defines the interface to apply for hyperopts
|
This module defines the interface to apply for hyperopt
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import math
|
import math
|
||||||
|
from abc import ABC
|
||||||
|
from typing import Any, Callable, Dict, List
|
||||||
|
|
||||||
from abc import ABC, abstractmethod
|
from skopt.space import Categorical, Dimension, Integer, Real
|
||||||
from typing import Dict, Any, Callable, List
|
|
||||||
|
|
||||||
from pandas import DataFrame
|
from freqtrade.exceptions import OperationalException
|
||||||
from skopt.space import Dimension, Integer, Real
|
|
||||||
|
|
||||||
from freqtrade import OperationalException
|
|
||||||
from freqtrade.exchange import timeframe_to_minutes
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
from freqtrade.misc import round_dict
|
from freqtrade.misc import round_dict
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@@ -28,8 +25,8 @@ def _format_exception_message(method: str, space: str) -> str:
|
|||||||
|
|
||||||
class IHyperOpt(ABC):
|
class IHyperOpt(ABC):
|
||||||
"""
|
"""
|
||||||
Interface for freqtrade hyperopts
|
Interface for freqtrade hyperopt
|
||||||
Defines the mandatory structure must follow any custom hyperopts
|
Defines the mandatory structure must follow any custom hyperopt
|
||||||
|
|
||||||
Class attributes you can use:
|
Class attributes you can use:
|
||||||
ticker_interval -> int: value of the ticker interval to use for the strategy
|
ticker_interval -> int: value of the ticker interval to use for the strategy
|
||||||
@@ -42,15 +39,6 @@ class IHyperOpt(ABC):
|
|||||||
# Assign ticker_interval to be used in hyperopt
|
# Assign ticker_interval to be used in hyperopt
|
||||||
IHyperOpt.ticker_interval = str(config['ticker_interval'])
|
IHyperOpt.ticker_interval = str(config['ticker_interval'])
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
@abstractmethod
|
|
||||||
def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
||||||
"""
|
|
||||||
Populate indicators that will be used in the Buy and Sell strategy.
|
|
||||||
:param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe().
|
|
||||||
:return: A Dataframe with all mandatory indicators for the strategies.
|
|
||||||
"""
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
|
def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||||
"""
|
"""
|
||||||
@@ -116,10 +104,10 @@ class IHyperOpt(ABC):
|
|||||||
roi_t_alpha = 1.0
|
roi_t_alpha = 1.0
|
||||||
roi_p_alpha = 1.0
|
roi_p_alpha = 1.0
|
||||||
|
|
||||||
ticker_interval_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
|
# We define here limits for the ROI space parameters automagically adapted to the
|
||||||
# ticker_interval used by the bot:
|
# timeframe used by the bot:
|
||||||
#
|
#
|
||||||
# * 'roi_t' (limits for the time intervals in the ROI tables) components
|
# * 'roi_t' (limits for the time intervals in the ROI tables) components
|
||||||
# are scaled linearly.
|
# are scaled linearly.
|
||||||
@@ -127,8 +115,8 @@ class IHyperOpt(ABC):
|
|||||||
#
|
#
|
||||||
# The scaling is designed so that it maps exactly to the legacy Freqtrade roi_space()
|
# The scaling is designed so that it maps exactly to the legacy Freqtrade roi_space()
|
||||||
# method for the 5m ticker interval.
|
# method for the 5m ticker interval.
|
||||||
roi_t_scale = ticker_interval_mins / 5
|
roi_t_scale = timeframe_min / 5
|
||||||
roi_p_scale = math.log1p(ticker_interval_mins) / math.log1p(5)
|
roi_p_scale = math.log1p(timeframe_min) / math.log1p(5)
|
||||||
roi_limits = {
|
roi_limits = {
|
||||||
'roi_t1_min': int(10 * roi_t_scale * roi_t_alpha),
|
'roi_t1_min': int(10 * roi_t_scale * roi_t_alpha),
|
||||||
'roi_t1_max': int(120 * roi_t_scale * roi_t_alpha),
|
'roi_t1_max': int(120 * roi_t_scale * roi_t_alpha),
|
||||||
@@ -184,6 +172,47 @@ class IHyperOpt(ABC):
|
|||||||
Real(-0.35, -0.02, name='stoploss'),
|
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]:
|
||||||
|
"""
|
||||||
|
Create a trailing stoploss space.
|
||||||
|
|
||||||
|
You may override it in your custom Hyperopt class.
|
||||||
|
"""
|
||||||
|
return [
|
||||||
|
# It was decided to always set trailing_stop is to True if the 'trailing' hyperspace
|
||||||
|
# is used. Otherwise hyperopt will vary other parameters that won't have effect if
|
||||||
|
# trailing_stop is set False.
|
||||||
|
# This parameter is included into the hyperspace dimensions rather than assigning
|
||||||
|
# it explicitly in the code in order to have it printed in the results along with
|
||||||
|
# other 'trailing' hyperspace parameters.
|
||||||
|
Categorical([True], name='trailing_stop'),
|
||||||
|
|
||||||
|
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'),
|
||||||
|
]
|
||||||
|
|
||||||
# This is needed for proper unpickling the class attribute ticker_interval
|
# This is needed for proper unpickling the class attribute ticker_interval
|
||||||
# which is set to the actual value by the resolver.
|
# which is set to the actual value by the resolver.
|
||||||
# Why do I still need such shamanic mantras in modern python?
|
# Why do I still need such shamanic mantras in modern python?
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"""
|
"""
|
||||||
IHyperOptLoss interface
|
IHyperOptLoss interface
|
||||||
This module defines the interface for the loss-function for hyperopts
|
This module defines the interface for the loss-function for hyperopt
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
@@ -11,7 +11,7 @@ from pandas import DataFrame
|
|||||||
|
|
||||||
class IHyperOptLoss(ABC):
|
class IHyperOptLoss(ABC):
|
||||||
"""
|
"""
|
||||||
Interface for freqtrade hyperopts Loss functions.
|
Interface for freqtrade hyperopt Loss functions.
|
||||||
Defines the custom loss function (`hyperopt_loss_function()` which is evaluated every epoch.)
|
Defines the custom loss function (`hyperopt_loss_function()` which is evaluated every epoch.)
|
||||||
"""
|
"""
|
||||||
ticker_interval: str
|
ticker_interval: str
|
||||||
|
|||||||
135
freqtrade/optimize/optimize_reports.py
Normal file
135
freqtrade/optimize/optimize_reports.py
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
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', 'buy count', 'avg profit %', 'cum profit %',
|
||||||
|
f'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(data: Dict[str, Dict], 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', 'Count', 'Profit', 'Loss', 'Profit %']
|
||||||
|
for reason, count in results['sell_reason'].value_counts().iteritems():
|
||||||
|
result = results.loc[results['sell_reason'] == reason]
|
||||||
|
profit = len(result[result['profit_abs'] >= 0])
|
||||||
|
loss = len(result[result['profit_abs'] < 0])
|
||||||
|
profit_mean = round(result['profit_percent'].mean() * 100.0, 2)
|
||||||
|
tabular_data.append([reason.value, count, profit, loss, profit_mean])
|
||||||
|
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', 'buy count', 'avg profit %', 'cum profit %',
|
||||||
|
f'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 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
|
||||||
@@ -5,19 +5,31 @@ Provides lists as configured in config.json
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod, abstractproperty
|
||||||
from typing import List
|
from copy import deepcopy
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
from freqtrade.exchange import market_is_active
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class IPairList(ABC):
|
class IPairList(ABC):
|
||||||
|
|
||||||
def __init__(self, freqtrade, config: dict) -> None:
|
def __init__(self, exchange, pairlistmanager, config, pairlistconfig: dict,
|
||||||
self._freqtrade = freqtrade
|
pairlist_pos: int) -> None:
|
||||||
|
"""
|
||||||
|
:param exchange: Exchange instance
|
||||||
|
:param pairlistmanager: Instanciating Pairlist manager
|
||||||
|
:param config: Global bot configuration
|
||||||
|
:param pairlistconfig: Configuration for this pairlist - can be empty.
|
||||||
|
:param pairlist_pos: Position of the filter in the pairlist-filter-list
|
||||||
|
"""
|
||||||
|
self._exchange = exchange
|
||||||
|
self._pairlistmanager = pairlistmanager
|
||||||
self._config = config
|
self._config = config
|
||||||
self._whitelist = self._config['exchange']['pair_whitelist']
|
self._pairlistconfig = pairlistconfig
|
||||||
self._blacklist = self._config['exchange'].get('pair_blacklist', [])
|
self._pairlist_pos = pairlist_pos
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def name(self) -> str:
|
def name(self) -> str:
|
||||||
@@ -27,21 +39,13 @@ class IPairList(ABC):
|
|||||||
"""
|
"""
|
||||||
return self.__class__.__name__
|
return self.__class__.__name__
|
||||||
|
|
||||||
@property
|
@abstractproperty
|
||||||
def whitelist(self) -> List[str]:
|
def needstickers(self) -> bool:
|
||||||
"""
|
"""
|
||||||
Has the current whitelist
|
Boolean property defining if tickers are necessary.
|
||||||
-> no need to overwrite in subclasses
|
If no Pairlist requries tickers, an empty List is passed
|
||||||
|
as tickers argument to filter_pairlist
|
||||||
"""
|
"""
|
||||||
return self._whitelist
|
|
||||||
|
|
||||||
@property
|
|
||||||
def blacklist(self) -> List[str]:
|
|
||||||
"""
|
|
||||||
Has the current blacklist
|
|
||||||
-> no need to overwrite in subclasses
|
|
||||||
"""
|
|
||||||
return self._blacklist
|
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def short_desc(self) -> str:
|
def short_desc(self) -> str:
|
||||||
@@ -51,36 +55,62 @@ class IPairList(ABC):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def refresh_pairlist(self) -> None:
|
def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Refreshes pairlists and assigns them to self._whitelist and self._blacklist respectively
|
Filters and sorts pairlist and returns the whitelist again.
|
||||||
|
Called on each bot iteration - please use internal caching if necessary
|
||||||
-> Please overwrite in subclasses
|
-> Please overwrite in subclasses
|
||||||
|
:param pairlist: pairlist to filter or sort
|
||||||
|
:param tickers: Tickers (from exchange.get_tickers()). May be cached.
|
||||||
|
:return: new whitelist
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def _validate_whitelist(self, whitelist: List[str]) -> List[str]:
|
@staticmethod
|
||||||
|
def verify_blacklist(pairlist: List[str], blacklist: List[str]) -> List[str]:
|
||||||
|
"""
|
||||||
|
Verify and remove items from pairlist - returning a filtered pairlist.
|
||||||
|
"""
|
||||||
|
for pair in deepcopy(pairlist):
|
||||||
|
if pair in blacklist:
|
||||||
|
logger.warning(f"Pair {pair} in your blacklist. Removing it from whitelist...")
|
||||||
|
pairlist.remove(pair)
|
||||||
|
return pairlist
|
||||||
|
|
||||||
|
def _verify_blacklist(self, pairlist: List[str]) -> List[str]:
|
||||||
|
"""
|
||||||
|
Proxy method to verify_blacklist for easy access for child classes.
|
||||||
|
"""
|
||||||
|
return IPairList.verify_blacklist(pairlist, self._pairlistmanager.blacklist)
|
||||||
|
|
||||||
|
def _whitelist_for_active_markets(self, pairlist: List[str]) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Check available markets and remove pair from whitelist if necessary
|
Check available markets and remove pair from whitelist if necessary
|
||||||
:param whitelist: the sorted list of pairs the user might want to trade
|
:param whitelist: the sorted list of pairs the user might want to trade
|
||||||
:return: the list of pairs the user wants to trade without those unavailable or
|
:return: the list of pairs the user wants to trade without those unavailable or
|
||||||
black_listed
|
black_listed
|
||||||
"""
|
"""
|
||||||
markets = self._freqtrade.exchange.markets
|
markets = self._exchange.markets
|
||||||
|
|
||||||
sanitized_whitelist = set()
|
sanitized_whitelist: List[str] = []
|
||||||
for pair in whitelist:
|
for pair in pairlist:
|
||||||
# pair is not in the generated dynamic market, or in the blacklist ... ignore it
|
# pair is not in the generated dynamic market or has the wrong stake currency
|
||||||
if (pair in self.blacklist or pair not in markets
|
if pair not in markets:
|
||||||
or not pair.endswith(self._config['stake_currency'])):
|
|
||||||
logger.warning(f"Pair {pair} is not compatible with exchange "
|
logger.warning(f"Pair {pair} is not compatible with exchange "
|
||||||
f"{self._freqtrade.exchange.name} or contained in "
|
f"{self._exchange.name}. Removing it from whitelist..")
|
||||||
f"your blacklist. Removing it from whitelist..")
|
|
||||||
continue
|
continue
|
||||||
|
if not pair.endswith(self._config['stake_currency']):
|
||||||
|
logger.warning(f"Pair {pair} is not compatible with your stake currency "
|
||||||
|
f"{self._config['stake_currency']}. Removing it from whitelist..")
|
||||||
|
continue
|
||||||
|
|
||||||
# Check if market is active
|
# Check if market is active
|
||||||
market = markets[pair]
|
market = markets[pair]
|
||||||
if not market['active']:
|
if not market_is_active(market):
|
||||||
logger.info(f"Ignoring {pair} from whitelist. Market is not active.")
|
logger.info(f"Ignoring {pair} from whitelist. Market is not active.")
|
||||||
continue
|
continue
|
||||||
sanitized_whitelist.add(pair)
|
if pair not in sanitized_whitelist:
|
||||||
|
sanitized_whitelist.append(pair)
|
||||||
|
|
||||||
|
sanitized_whitelist = self._verify_blacklist(sanitized_whitelist)
|
||||||
# We need to remove pairs that are unknown
|
# We need to remove pairs that are unknown
|
||||||
return list(sanitized_whitelist)
|
return sanitized_whitelist
|
||||||
|
|||||||
63
freqtrade/pairlist/PrecisionFilter.py
Normal file
63
freqtrade/pairlist/PrecisionFilter.py
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import logging
|
||||||
|
from copy import deepcopy
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
from freqtrade.pairlist.IPairList import IPairList
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class PrecisionFilter(IPairList):
|
||||||
|
|
||||||
|
@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 untradable pairs."
|
||||||
|
|
||||||
|
def _validate_precision_filter(self, ticker: dict, stoploss: float) -> bool:
|
||||||
|
"""
|
||||||
|
Check if pair has enough room to add a stoploss to avoid "unsellable" buys of very
|
||||||
|
low value pairs.
|
||||||
|
:param ticker: ticker dict as returned from ccxt.load_markets()
|
||||||
|
:param stoploss: stoploss value as set in the configuration
|
||||||
|
(already cleaned to be 1 - stoploss)
|
||||||
|
:return: True if the pair can stay, false if it should be removed
|
||||||
|
"""
|
||||||
|
stop_price = ticker['ask'] * stoploss
|
||||||
|
# Adjust stop-prices to precision
|
||||||
|
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, "
|
||||||
|
f"because stop price {sp} would be <= stop limit {stop_gap_price}")
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
|
||||||
|
"""
|
||||||
|
Filters and sorts pairlists and assigns and returns them again.
|
||||||
|
"""
|
||||||
|
stoploss = None
|
||||||
|
if self._config.get('stoploss') is not None:
|
||||||
|
# Precalculate sanitized stoploss value to avoid recalculation for every pair
|
||||||
|
stoploss = 1 - abs(self._config.get('stoploss'))
|
||||||
|
# Copy list since we're modifying this list
|
||||||
|
for p in deepcopy(pairlist):
|
||||||
|
ticker = tickers.get(p)
|
||||||
|
# Filter out assets which would not allow setting a stoploss
|
||||||
|
if not ticker or (stoploss and not self._validate_precision_filter(ticker, stoploss)):
|
||||||
|
pairlist.remove(p)
|
||||||
|
continue
|
||||||
|
|
||||||
|
return pairlist
|
||||||
69
freqtrade/pairlist/PriceFilter.py
Normal file
69
freqtrade/pairlist/PriceFilter.py
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
import logging
|
||||||
|
from copy import deepcopy
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
from freqtrade.pairlist.IPairList import IPairList
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class PriceFilter(IPairList):
|
||||||
|
|
||||||
|
def __init__(self, exchange, pairlistmanager, config, pairlistconfig: dict,
|
||||||
|
pairlist_pos: int) -> None:
|
||||||
|
super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos)
|
||||||
|
|
||||||
|
self._low_price_ratio = pairlistconfig.get('low_price_ratio', 0)
|
||||||
|
|
||||||
|
@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 priced below {self._low_price_ratio * 100}%."
|
||||||
|
|
||||||
|
def _validate_ticker_lowprice(self, ticker) -> bool:
|
||||||
|
"""
|
||||||
|
Check if if one price-step (pip) is > than a certain barrier.
|
||||||
|
:param ticker: ticker dict as returned from ccxt.load_markets()
|
||||||
|
:param precision: Precision
|
||||||
|
:return: True if the pair can stay, false if it should be removed
|
||||||
|
"""
|
||||||
|
precision = self._exchange.markets[ticker['symbol']]['precision']['price']
|
||||||
|
|
||||||
|
compare = ticker['last'] + 1 / pow(10, precision)
|
||||||
|
changeperc = (compare - ticker['last']) / ticker['last']
|
||||||
|
if changeperc > self._low_price_ratio:
|
||||||
|
logger.info(f"Removed {ticker['symbol']} from whitelist, "
|
||||||
|
f"because 1 unit is {changeperc * 100:.3f}%")
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
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
|
||||||
|
for p in deepcopy(pairlist):
|
||||||
|
ticker = tickers.get(p)
|
||||||
|
if not ticker:
|
||||||
|
pairlist.remove(p)
|
||||||
|
|
||||||
|
# Filter out assets which would not allow setting a stoploss
|
||||||
|
if self._low_price_ratio and not self._validate_ticker_lowprice(ticker):
|
||||||
|
pairlist.remove(p)
|
||||||
|
|
||||||
|
return pairlist
|
||||||
@@ -5,6 +5,7 @@ Provides lists as configured in config.json
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
from freqtrade.pairlist.IPairList import IPairList
|
from freqtrade.pairlist.IPairList import IPairList
|
||||||
|
|
||||||
@@ -13,18 +14,28 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
class StaticPairList(IPairList):
|
class StaticPairList(IPairList):
|
||||||
|
|
||||||
def __init__(self, freqtrade, config: dict) -> None:
|
@property
|
||||||
super().__init__(freqtrade, config)
|
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 False
|
||||||
|
|
||||||
def short_desc(self) -> str:
|
def short_desc(self) -> str:
|
||||||
"""
|
"""
|
||||||
Short whitelist method description - used for startup-messages
|
Short whitelist method description - used for startup-messages
|
||||||
-> Please overwrite in subclasses
|
-> Please overwrite in subclasses
|
||||||
"""
|
"""
|
||||||
return f"{self.name}: {self.whitelist}"
|
return f"{self.name}"
|
||||||
|
|
||||||
def refresh_pairlist(self) -> None:
|
def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Refreshes pairlists and assigns them to self._whitelist and self._blacklist respectively
|
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
|
||||||
"""
|
"""
|
||||||
self._whitelist = self._validate_whitelist(self._config['exchange']['pair_whitelist'])
|
return self._whitelist_for_active_markets(self._config['exchange']['pair_whitelist'])
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user