mirror of
https://github.com/freqtrade/freqtrade.git
synced 2025-11-29 08:33:07 +00:00
Compare commits
2791 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
905beef8a3 | ||
|
|
af02e34b57 | ||
|
|
9e082ca3a9 | ||
|
|
ba23f58ff3 | ||
|
|
d76dc3ca0e | ||
|
|
7dbb7a52ed | ||
|
|
3ec3438acf | ||
|
|
1cd54829cc | ||
|
|
bd6644a91a | ||
|
|
ab62bbc0a4 | ||
|
|
58864adc4a | ||
|
|
788cbb6776 | ||
|
|
f9d68d919c | ||
|
|
dffb27326e | ||
|
|
6d7834a389 | ||
|
|
f63fdf411d | ||
|
|
cd48556c5a | ||
|
|
9fad83bd15 | ||
|
|
19625e9e1d | ||
|
|
f1ededf0eb | ||
|
|
1bbb04da60 | ||
|
|
e785a66768 | ||
|
|
df8067d6c4 | ||
|
|
66cc600076 | ||
|
|
ea6d4a9d36 | ||
|
|
e0c420b93f | ||
|
|
67cea9dce6 | ||
|
|
7c651632f1 | ||
|
|
13a16178d2 | ||
|
|
c2bc316e2f | ||
|
|
98bd713624 | ||
|
|
f852be1a9b | ||
|
|
dcc86bfa55 | ||
|
|
aee7b2c29d | ||
|
|
c17eb89e84 | ||
|
|
aaa8567708 | ||
|
|
7e1e09d45a | ||
|
|
b87e15774b | ||
|
|
8e7e670003 | ||
|
|
8fc8c985d8 | ||
|
|
69a24c1272 | ||
|
|
e8daadfb7e | ||
|
|
91629807f7 | ||
|
|
f551fb5ff7 | ||
|
|
e8ef36fb6e | ||
|
|
b9a5899c99 | ||
|
|
607190cd38 | ||
|
|
018cee8413 | ||
|
|
0b5f4dc38e | ||
|
|
160c467e01 | ||
|
|
d91dbf4090 | ||
|
|
69f69d965c | ||
|
|
624ce6707a | ||
|
|
5e741a0f73 | ||
|
|
d6c0c107ac | ||
|
|
7ed15c64ba | ||
|
|
08d35f3e15 | ||
|
|
4dffb17dd6 | ||
|
|
14d6cdf9b2 | ||
|
|
7248537d4a | ||
|
|
b91981f0aa | ||
|
|
585f525879 | ||
|
|
58bd272c0f | ||
|
|
fe2f98c802 | ||
|
|
76187cc3d9 | ||
|
|
3bb9e17b0d | ||
|
|
f0c9064b77 | ||
|
|
e0142526e3 | ||
|
|
e9aba03981 | ||
|
|
9a50771a27 | ||
|
|
92eb951966 | ||
|
|
e6a8ecbf66 | ||
|
|
39626bb520 | ||
|
|
f48936dcde | ||
|
|
395a7b25be | ||
|
|
02698c7493 | ||
|
|
6fd932bf7d | ||
|
|
fcc7cb9892 | ||
|
|
21ffdbb3a2 | ||
|
|
f847bf0b8d | ||
|
|
64891df122 | ||
|
|
218b501119 | ||
|
|
0a71ebce68 | ||
|
|
80440f25cf | ||
|
|
1d940041e3 | ||
|
|
40fea4593f | ||
|
|
02c3552954 | ||
|
|
91ed02134e | ||
|
|
e8ed8a2ea7 | ||
|
|
f2dd32e319 | ||
|
|
5243941c4d | ||
|
|
8d5474d4d5 | ||
|
|
576d893d95 | ||
|
|
697e698abc | ||
|
|
24f779eda7 | ||
|
|
2ce3bd956d | ||
|
|
ba4e5cae54 | ||
|
|
645ec30ec5 | ||
|
|
d07cc5929e | ||
|
|
8d9114aa79 | ||
|
|
68a4e0426e | ||
|
|
10e548dcab | ||
|
|
e3ae8d3f69 | ||
|
|
576d9b8f5c | ||
|
|
0c959c22ec | ||
|
|
6ad1089f45 | ||
|
|
9f87a27465 | ||
|
|
2b71e8de5c | ||
|
|
84b6b8fe97 | ||
|
|
421be5da86 | ||
|
|
09cb043b24 | ||
|
|
cf283344de | ||
|
|
dcfa4d421e | ||
|
|
1a1123a555 | ||
|
|
382215eb70 | ||
|
|
f095492804 | ||
|
|
22e82f5e47 | ||
|
|
69ef743811 | ||
|
|
38f73dafb3 | ||
|
|
e0ad095bc7 | ||
|
|
1d08ada939 | ||
|
|
3446dd1792 | ||
|
|
02d13645b0 | ||
|
|
ba07348b82 | ||
|
|
bfd8609352 | ||
|
|
b112f2f315 | ||
|
|
d222dd6717 | ||
|
|
3bc96c16ac | ||
|
|
da5210ef5b | ||
|
|
e5b0224050 | ||
|
|
e43aaaef9c | ||
|
|
422a0ce114 | ||
|
|
22e7ad8ec1 | ||
|
|
b840b9f53a | ||
|
|
eec7276393 | ||
|
|
5e7ba85dbe | ||
|
|
3c316fe3e4 | ||
|
|
56a3d78128 | ||
|
|
ab8cc5f586 | ||
|
|
bd24646822 | ||
|
|
a97b3ab04a | ||
|
|
3afe54790e | ||
|
|
38d293cc26 | ||
|
|
497a467864 | ||
|
|
dcceb40fab | ||
|
|
9960fe07bc | ||
|
|
74b03d0529 | ||
|
|
ac199b626a | ||
|
|
8750f1be3f | ||
|
|
05d65b81da | ||
|
|
d136cac181 | ||
|
|
97f6a45819 | ||
|
|
ad8b1bbb79 | ||
|
|
5ea332e9be | ||
|
|
06e0616fb0 | ||
|
|
372c5d813a | ||
|
|
fd94b322be | ||
|
|
896c9d34fd | ||
|
|
13e2f71d30 | ||
|
|
c412cd9e57 | ||
|
|
86a0863e30 | ||
|
|
a06593e6e9 | ||
|
|
89ddfe08f4 | ||
|
|
580e9ccaf3 | ||
|
|
7c71b9513c | ||
|
|
188c391444 | ||
|
|
c77607b997 | ||
|
|
3221f883d3 | ||
|
|
1e7431a7b8 | ||
|
|
e66808bb02 | ||
|
|
fc92491a47 | ||
|
|
6e2de75bcb | ||
|
|
d6cdfc58af | ||
|
|
7b138ef3b4 | ||
|
|
27b2021726 | ||
|
|
e7800aa88a | ||
|
|
a2bc1da669 | ||
|
|
1e749a0f9b | ||
|
|
d7df5d5715 | ||
|
|
6525a838d1 | ||
|
|
f0af4601f9 | ||
|
|
a9abc25785 | ||
|
|
0aa0b1d4fe | ||
|
|
5f61da30ed | ||
|
|
d6df3e55c0 | ||
|
|
e503d811bd | ||
|
|
b981cfcaa0 | ||
|
|
a206777fe5 | ||
|
|
06ec106079 | ||
|
|
646e98da55 | ||
|
|
2b029b2a86 | ||
|
|
9edb88051d | ||
|
|
35c8d1dcbe | ||
|
|
8f3ea3608a | ||
|
|
5ecdecd1eb | ||
|
|
58f1abf287 | ||
|
|
d3a37db79a | ||
|
|
f034235af4 | ||
|
|
1340b71633 | ||
|
|
fed3ebfb46 | ||
|
|
a7db4d74cb | ||
|
|
84cc4887ce | ||
|
|
e38c06afe9 | ||
|
|
f1a5a8e20e | ||
|
|
4ab7edd3d6 | ||
|
|
05570732c6 | ||
|
|
7206287b00 | ||
|
|
b119a767de | ||
|
|
a6d74a1463 | ||
|
|
70881f12d2 | ||
|
|
1be3d57b60 | ||
|
|
07577ac18d | ||
|
|
e4a399039b | ||
|
|
34b617065d | ||
|
|
2a16e9b6a0 | ||
|
|
8a3615dea3 | ||
|
|
6fb50e35c9 | ||
|
|
a733630083 | ||
|
|
b48430f922 | ||
|
|
4e760e1a5e | ||
|
|
30e3b52b1e | ||
|
|
b52da0ad09 | ||
|
|
797ac71376 | ||
|
|
e8423d8155 | ||
|
|
b421e437ab | ||
|
|
2b65e3f35c | ||
|
|
c2578c7321 | ||
|
|
87329a393c | ||
|
|
a2618208ef | ||
|
|
70780bb01e | ||
|
|
89eddfd349 | ||
|
|
1c4ee35eca | ||
|
|
e41e45413f | ||
|
|
c7ebd8228e | ||
|
|
cc6466388e | ||
|
|
27d907e71b | ||
|
|
a2c01916e1 | ||
|
|
357c28d5ea | ||
|
|
648def69ca | ||
|
|
97a8341436 | ||
|
|
30cdf85ffa | ||
|
|
75cedfafb8 | ||
|
|
9d6c54791b | ||
|
|
e682eceae4 | ||
|
|
2533112254 | ||
|
|
08d98773f3 | ||
|
|
da51ef40f8 | ||
|
|
91c714c7d1 | ||
|
|
5e2e96acd2 | ||
|
|
611b48dbb9 | ||
|
|
50bc20134f | ||
|
|
baa5cc5b9e | ||
|
|
aa03a864f7 | ||
|
|
a44f781284 | ||
|
|
d108138999 | ||
|
|
cffc9ce890 | ||
|
|
6d588b3b0b | ||
|
|
bfb7121583 | ||
|
|
e31fa8721f | ||
|
|
29439c05d6 | ||
|
|
1cd5abde37 | ||
|
|
12e8108015 | ||
|
|
07b4afedf7 | ||
|
|
399d2d89a3 | ||
|
|
22d3881b6e | ||
|
|
494b905d1e | ||
|
|
f0cfab7940 | ||
|
|
cfe00c2f0c | ||
|
|
678162fada | ||
|
|
da04182287 | ||
|
|
a3897c990d | ||
|
|
929995117f | ||
|
|
04786f09f4 | ||
|
|
9b97e1e8fb | ||
|
|
cd2bccd441 | ||
|
|
e9d61eb35d | ||
|
|
9e0902e72f | ||
|
|
690fbeb907 | ||
|
|
e95351fd04 | ||
|
|
a095ccd1d6 | ||
|
|
3867f73c8c | ||
|
|
d8f2d868c1 | ||
|
|
4920ee3455 | ||
|
|
3f8092192e | ||
|
|
e025ad3918 | ||
|
|
5ac5b18e6d | ||
|
|
c1007f95b3 | ||
|
|
4d52301ee6 | ||
|
|
a494755449 | ||
|
|
2e530a3e03 | ||
|
|
e76ed31b08 | ||
|
|
f4979e0e8a | ||
|
|
dd7d655a63 | ||
|
|
f9a99f4ad3 | ||
|
|
99e2d795c5 | ||
|
|
7a13565efb | ||
|
|
bb3d78757d | ||
|
|
356a17cdaa | ||
|
|
da436c920f | ||
|
|
69eed95a54 | ||
|
|
df97652f6e | ||
|
|
64372ea6fb | ||
|
|
b3f67bb8c6 | ||
|
|
d29c294f6a | ||
|
|
b5adfcf51a | ||
|
|
1a27258469 | ||
|
|
9e133eb32e | ||
|
|
f4ceeca438 | ||
|
|
aed855284c | ||
|
|
f4e0e04462 | ||
|
|
4069e2fdfb | ||
|
|
ec22512fd9 | ||
|
|
c3107272d3 | ||
|
|
b98526d32c | ||
|
|
4fbb9d4462 | ||
|
|
16472535eb | ||
|
|
f620449bec | ||
|
|
440a7ec9c2 | ||
|
|
40b1d8f067 | ||
|
|
5dd1f9b38a | ||
|
|
dd2af86a41 | ||
|
|
821e299afb | ||
|
|
85bca58905 | ||
|
|
f5fc9e69cf | ||
|
|
167088827a | ||
|
|
a0df7b9d7c | ||
|
|
87cbff5d0e | ||
|
|
13800701ce | ||
|
|
3f82dd05aa | ||
|
|
2147bd8847 | ||
|
|
798ae460d8 | ||
|
|
5e08769366 | ||
|
|
68ba1e1f37 | ||
|
|
b731973c7a | ||
|
|
a07353d3c7 | ||
|
|
86023744d9 | ||
|
|
e91be7aff9 | ||
|
|
5af656d3ba | ||
|
|
4a0bc8937d | ||
|
|
506237e3b4 | ||
|
|
f088f43b40 | ||
|
|
01e2dc17b5 | ||
|
|
337ebdeccb | ||
|
|
9e5e485d0a | ||
|
|
31da42a485 | ||
|
|
94aa1aaff3 | ||
|
|
dbf8ec6a20 | ||
|
|
c8d40e81f0 | ||
|
|
16512d9918 | ||
|
|
8505ffbe78 | ||
|
|
f7b96d839d | ||
|
|
f32232ba96 | ||
|
|
cacb9ef3ad | ||
|
|
00c5ac56d4 | ||
|
|
a7dc6b18aa | ||
|
|
5e23442032 | ||
|
|
4599c80e79 | ||
|
|
29db2078d6 | ||
|
|
67cbd5d77f | ||
|
|
26a77e193e | ||
|
|
55235ce20d | ||
|
|
a5ec564fc3 | ||
|
|
f1bb4233c9 | ||
|
|
afffa2f313 | ||
|
|
221bca0aaa | ||
|
|
de278a77d7 | ||
|
|
56924e6909 | ||
|
|
2c31fd662c | ||
|
|
3b5785884f | ||
|
|
3329ffd071 | ||
|
|
05ce7787d6 | ||
|
|
68a9d1b2b8 | ||
|
|
207daf084e | ||
|
|
dcdd7d7436 | ||
|
|
138de389e2 | ||
|
|
41a4621caf | ||
|
|
516217b6cb | ||
|
|
6cc6ce359b | ||
|
|
848af3755e | ||
|
|
71eba2afba | ||
|
|
1b84aa82eb | ||
|
|
2bc76771bf | ||
|
|
1d518885a9 | ||
|
|
b55994cb71 | ||
|
|
da6f1a3945 | ||
|
|
2b5e02fae8 | ||
|
|
e3cf838bc6 | ||
|
|
a54d8f0e16 | ||
|
|
c337a931c2 | ||
|
|
a909322f60 | ||
|
|
672d115eca | ||
|
|
dd1d3430b9 | ||
|
|
fae875f588 | ||
|
|
ef4555735a | ||
|
|
8b9cc45f41 | ||
|
|
0824db03e7 | ||
|
|
7b1f4aec76 | ||
|
|
827a8309d7 | ||
|
|
366980fd62 | ||
|
|
42cc3e525e | ||
|
|
5be21fd9d8 | ||
|
|
361b294e43 | ||
|
|
dd91b5c731 | ||
|
|
a07a004bb6 | ||
|
|
a86b34e41c | ||
|
|
7bf1a92dc3 | ||
|
|
db1c9b8edf | ||
|
|
79ac20636f | ||
|
|
04483da8df | ||
|
|
d409211908 | ||
|
|
03389d961f | ||
|
|
a021cd3ae2 | ||
|
|
be1969adc8 | ||
|
|
689ca76456 | ||
|
|
034bcd64d5 | ||
|
|
faad07aa3d | ||
|
|
4d415205d1 | ||
|
|
c357483eef | ||
|
|
aa542784ab | ||
|
|
49c37692f3 | ||
|
|
f42df56a88 | ||
|
|
808ce3e7ba | ||
|
|
87cbf6aaaa | ||
|
|
863cf303e3 | ||
|
|
b029a98980 | ||
|
|
219e9d9e2b | ||
|
|
da380e6a0d | ||
|
|
83b9732106 | ||
|
|
016522b151 | ||
|
|
cb1d9b6200 | ||
|
|
e215373ad0 | ||
|
|
f32dfc57ca | ||
|
|
b321c66654 | ||
|
|
a6e23e6b9b | ||
|
|
af85080113 | ||
|
|
460900ddd7 | ||
|
|
884e1bd9a9 | ||
|
|
f6ff9b0419 | ||
|
|
0bcadbd854 | ||
|
|
78f29a7454 | ||
|
|
71de820adf | ||
|
|
dcf0feefb9 | ||
|
|
ad696a9d12 | ||
|
|
793dd38445 | ||
|
|
ffbe95ef02 | ||
|
|
9c442455a2 | ||
|
|
a5452d2c75 | ||
|
|
b45af56199 | ||
|
|
cf0e31c5a2 | ||
|
|
305f2b74e8 | ||
|
|
b859fa1e42 | ||
|
|
f286e092fb | ||
|
|
fab7663ab3 | ||
|
|
61f8ce5c0e | ||
|
|
0f86e218c1 | ||
|
|
7dc40cdac5 | ||
|
|
27abdd9788 | ||
|
|
065b469a10 | ||
|
|
c955415cc3 | ||
|
|
98ac2b15ca | ||
|
|
1ce8f416ca | ||
|
|
29e0a45b5b | ||
|
|
1167b24eeb | ||
|
|
9e735de3c6 | ||
|
|
cb654a82db | ||
|
|
407a978e08 | ||
|
|
24e1de91eb | ||
|
|
ecb5cdc9e3 | ||
|
|
23d0cea01f | ||
|
|
bb9dd86e77 | ||
|
|
0cbdf10ebe | ||
|
|
9af2fca718 | ||
|
|
20cdabbe9c | ||
|
|
9d906d013a | ||
|
|
8b38f44da6 | ||
|
|
3f1248405f | ||
|
|
5b30815d7b | ||
|
|
37cde77e18 | ||
|
|
1fc0dcb9d8 | ||
|
|
3411d3d5fa | ||
|
|
93a9642abf | ||
|
|
b2bc5d9396 | ||
|
|
32f43d3294 | ||
|
|
dc4e412e21 | ||
|
|
5e3e7b6928 | ||
|
|
f2beaf101c | ||
|
|
d951289862 | ||
|
|
b28b2369da | ||
|
|
2f1721a45b | ||
|
|
0e6dbfab5e | ||
|
|
8e5ea8620b | ||
|
|
34b93eb952 | ||
|
|
8fbeb700d6 | ||
|
|
22cd84de09 | ||
|
|
ae51458585 | ||
|
|
cef1fa8636 | ||
|
|
a5137e4fa4 | ||
|
|
390f13bbe4 | ||
|
|
741e336864 | ||
|
|
30fe06aa55 | ||
|
|
7243da3afe | ||
|
|
f563dec0d6 | ||
|
|
7c69dbae30 | ||
|
|
82a3806015 | ||
|
|
41ef02a292 | ||
|
|
34e3af6ad4 | ||
|
|
a13b30b2de | ||
|
|
a45ec1ed1c | ||
|
|
7f4b5e43fc | ||
|
|
358b5d7e5d | ||
|
|
fc4384c96f | ||
|
|
f54a21ae8f | ||
|
|
ad4952731a | ||
|
|
ff0fc064c7 | ||
|
|
2e06d52240 | ||
|
|
fd4cfefda5 | ||
|
|
d90a86ddef | ||
|
|
b1e9fa754a | ||
|
|
215ded2e0a | ||
|
|
1483593e65 | ||
|
|
a4aa87c21b | ||
|
|
ac9189ebc0 | ||
|
|
1dbcab0b09 | ||
|
|
1372095c66 | ||
|
|
5d253f352c | ||
|
|
b3bb98777b | ||
|
|
5493d1a7e0 | ||
|
|
c21bf7d6bb | ||
|
|
7357d6b089 | ||
|
|
c784b829e5 | ||
|
|
213155e6d3 | ||
|
|
f756f1ad28 | ||
|
|
2e7028442d | ||
|
|
a967b8918a | ||
|
|
9d8a3b4ec5 | ||
|
|
806ab3729f | ||
|
|
b6474e4a3c | ||
|
|
eb7034c7a7 | ||
|
|
50938d410a | ||
|
|
8bd4d03e13 | ||
|
|
8826a1df5f | ||
|
|
043cefd60a | ||
|
|
ebb80b6906 | ||
|
|
f5b2430cda | ||
|
|
8a3c2a0c63 | ||
|
|
429f846ad1 | ||
|
|
acd07d40a0 | ||
|
|
d421e4e8af | ||
|
|
d0c9791ca6 | ||
|
|
34ea214f7c | ||
|
|
1c5031b468 | ||
|
|
c1a32bc6c8 | ||
|
|
b4f1a80dc1 | ||
|
|
6c02cc5993 | ||
|
|
21aba1620c | ||
|
|
f261911285 | ||
|
|
c82d165713 | ||
|
|
a34c2cf64b | ||
|
|
4ad507f8dd | ||
|
|
7e463b209c | ||
|
|
df01e8b326 | ||
|
|
c42d5002a1 | ||
|
|
43039aa6ab | ||
|
|
407139b0e0 | ||
|
|
17a820e5c0 | ||
|
|
92c800d925 | ||
|
|
4ca6aad99a | ||
|
|
432cc00283 | ||
|
|
0250a96feb | ||
|
|
1a3fcd4771 | ||
|
|
b38195e9b3 | ||
|
|
1f29802884 | ||
|
|
453f62cdfa | ||
|
|
030ecbfc17 | ||
|
|
04c330f10b | ||
|
|
aca243086e | ||
|
|
eb7fb2ff0f | ||
|
|
6c9c03b3d5 | ||
|
|
cdd0ef3094 | ||
|
|
6b4bab272f | ||
|
|
960abeac0a | ||
|
|
c3af7220f1 | ||
|
|
df5a280169 | ||
|
|
7e3955b04c | ||
|
|
5c3dcf3e2b | ||
|
|
d6ba4f0e81 | ||
|
|
7a533de1a8 | ||
|
|
fe3990af3d | ||
|
|
627ab9f583 | ||
|
|
a377088421 | ||
|
|
aa1262bea6 | ||
|
|
79f5c4adfe | ||
|
|
fd953bab8c | ||
|
|
8d8b53f4d1 | ||
|
|
62f6dd5b17 | ||
|
|
81b4940eef | ||
|
|
efc709501a | ||
|
|
0f2c547805 | ||
|
|
5a7451a823 | ||
|
|
0ab8ac1c1d | ||
|
|
80efef87ab | ||
|
|
70ad8a06c3 | ||
|
|
97e7b0d9f6 | ||
|
|
8c1901ad1e | ||
|
|
523dea4a04 | ||
|
|
e2bff9d5cb | ||
|
|
36de451809 | ||
|
|
adcaa8439e | ||
|
|
e6fd7da43f | ||
|
|
6018f2d252 | ||
|
|
3e479d045d | ||
|
|
d904667c87 | ||
|
|
866b7aee8e | ||
|
|
663e33d2ef | ||
|
|
20d794e265 | ||
|
|
2f5c8941eb | ||
|
|
b35199a772 | ||
|
|
510f78079b | ||
|
|
c15231d1b9 | ||
|
|
acb96eb501 | ||
|
|
7e476e6144 | ||
|
|
3b951c3817 | ||
|
|
2c27736dfe | ||
|
|
4e5fb6afd4 | ||
|
|
b3b6eda2ba | ||
|
|
e5a51456ef | ||
|
|
ac9f19aee5 | ||
|
|
c38a1d0324 | ||
|
|
aa579bafa4 | ||
|
|
8f19c83f6b | ||
|
|
a63f123b6d | ||
|
|
40376c1e74 | ||
|
|
0ea7dc9272 | ||
|
|
bf1841d2a8 | ||
|
|
0c10719037 | ||
|
|
2f0d7a1aea | ||
|
|
3e2fa58029 | ||
|
|
43031aa3bb | ||
|
|
1a10e12861 | ||
|
|
21906e4892 | ||
|
|
616ca0237e | ||
|
|
ed22419b32 | ||
|
|
37ebe05c6d | ||
|
|
ee26b6bcff | ||
|
|
d12cc39a5e | ||
|
|
910601ba1d | ||
|
|
e3876bcf0f | ||
|
|
b7aa77acdd | ||
|
|
369a609f61 | ||
|
|
1c3ce265f1 | ||
|
|
6ab907bef1 | ||
|
|
4143e2c032 | ||
|
|
33e9ed5a5e | ||
|
|
24f9ea29c6 | ||
|
|
e7684b446b | ||
|
|
cc3b84a8de | ||
|
|
32b6cd9dff | ||
|
|
4a6cec752d | ||
|
|
bf678164c7 | ||
|
|
ba3218a87d | ||
|
|
ab60571ac7 | ||
|
|
0929f59680 | ||
|
|
18ad3388b4 | ||
|
|
ef1208b366 | ||
|
|
1b3ecb8343 | ||
|
|
108d9a1117 | ||
|
|
43bafc391f | ||
|
|
b5192193fd | ||
|
|
3360e777a1 | ||
|
|
49a6581dfe | ||
|
|
11da297c25 | ||
|
|
f748a63df2 | ||
|
|
99f7c3752a | ||
|
|
3a086aac58 | ||
|
|
26187ef6c7 | ||
|
|
d09dbfe2e6 | ||
|
|
58c7adae0a | ||
|
|
8fd713f3ae | ||
|
|
1738633efc | ||
|
|
e8fbe77ebc | ||
|
|
bb828c308f | ||
|
|
dee6249977 | ||
|
|
35d678c505 | ||
|
|
27c2e80cff | ||
|
|
0f4a3365ad | ||
|
|
b594bc7ccc | ||
|
|
a5414b8437 | ||
|
|
2d17346b0e | ||
|
|
7ddbaa70ad | ||
|
|
237dc8290f | ||
|
|
bd673178ce | ||
|
|
33f1cc13b3 | ||
|
|
1d41a91788 | ||
|
|
ee62adf4f7 | ||
|
|
4431e3bdb6 | ||
|
|
88d277ea55 | ||
|
|
9c0be99ff7 | ||
|
|
c4f17f1c45 | ||
|
|
86d9457ea1 | ||
|
|
9c987fdedd | ||
|
|
b1c81acfcb | ||
|
|
042e631f87 | ||
|
|
bf990ec599 | ||
|
|
f100432fe8 | ||
|
|
24f573f3b0 | ||
|
|
e31963f6e1 | ||
|
|
d4f83a7516 | ||
|
|
f04655c012 | ||
|
|
3ac2106a16 | ||
|
|
8effcc2de5 | ||
|
|
4a2d60370c | ||
|
|
7e86ec31be | ||
|
|
c61ede4182 | ||
|
|
aadc9f052a | ||
|
|
11101e6668 | ||
|
|
12471e012e | ||
|
|
abd88767f8 | ||
|
|
7767470af8 | ||
|
|
9d005678c3 | ||
|
|
eedc790b53 | ||
|
|
7570a0d0a4 | ||
|
|
f554647efd | ||
|
|
42c8888fa1 | ||
|
|
8ff82e3dac | ||
|
|
efcec736b5 | ||
|
|
49e44d5481 | ||
|
|
74ca34f2de | ||
|
|
3d37c5d767 | ||
|
|
6cf897a17a | ||
|
|
a6eb3328d2 | ||
|
|
bc2f6d3b71 | ||
|
|
6bedcc5d79 | ||
|
|
a61daed8e9 | ||
|
|
cb9104fd8a | ||
|
|
38592c6fa6 | ||
|
|
e698590bb2 | ||
|
|
1a5465fb50 | ||
|
|
b090b7f4f0 | ||
|
|
c913fef80c | ||
|
|
e9305b6592 | ||
|
|
fb755880fa | ||
|
|
da94e97c60 | ||
|
|
50a384130f | ||
|
|
4ffc74d5fa | ||
|
|
ff8987f517 | ||
|
|
29f680ec5d | ||
|
|
7dbf0fed68 | ||
|
|
159ac6e657 | ||
|
|
7832fe7074 | ||
|
|
5fa3548dbe | ||
|
|
f5a70750f0 | ||
|
|
6351fe7a7f | ||
|
|
3131788639 | ||
|
|
7f6fc7e90f | ||
|
|
86354ed258 | ||
|
|
2135976cb8 | ||
|
|
b63535083e | ||
|
|
1f1770ad5a | ||
|
|
17004a5a72 | ||
|
|
b2634e8e08 | ||
|
|
823bc3abb6 | ||
|
|
a584327d2f | ||
|
|
d3712c6e40 | ||
|
|
854af9c124 | ||
|
|
ad8592f316 | ||
|
|
797a0e8fd0 | ||
|
|
c38f8b8ae2 | ||
|
|
16eec078d7 | ||
|
|
9f26022ce5 | ||
|
|
962b02b079 | ||
|
|
29c23e3136 | ||
|
|
181424e8ea | ||
|
|
ba20b1b5c7 | ||
|
|
890cef88ab | ||
|
|
fb7b65c909 | ||
|
|
6c38bde24a | ||
|
|
b579768618 | ||
|
|
5c257730a8 | ||
|
|
59fc67f85b | ||
|
|
1ad5ccdfb0 | ||
|
|
a80c984323 | ||
|
|
92930b2343 | ||
|
|
5e1fb11124 | ||
|
|
3e29fbb17a | ||
|
|
ebaf58b0fe | ||
|
|
8a43611992 | ||
|
|
745a517795 | ||
|
|
317eba2139 | ||
|
|
fd7184718b | ||
|
|
200484ab8b | ||
|
|
5a36dd5d5b | ||
|
|
e89df448e8 | ||
|
|
0aa74b8d72 | ||
|
|
e4744c1ba4 | ||
|
|
dcae3a2644 | ||
|
|
664b96173e | ||
|
|
1d35428c8d | ||
|
|
a3477e07eb | ||
|
|
266bd7b9b6 | ||
|
|
20de8c82e4 | ||
|
|
cc7b820978 | ||
|
|
519b1f00e2 | ||
|
|
2c0d0946e6 | ||
|
|
21a093bcdb | ||
|
|
c8a0956e1b | ||
|
|
e442390b1b | ||
|
|
b5192880df | ||
|
|
fe8927136c | ||
|
|
b2c0b20a58 | ||
|
|
000711b025 | ||
|
|
870631f324 | ||
|
|
531d9ecd0c | ||
|
|
afd0a054b2 | ||
|
|
a9ec5c6699 | ||
|
|
1a8e9ebc0f | ||
|
|
63c2ea110a | ||
|
|
29347a6931 | ||
|
|
2b0b7ffa5e | ||
|
|
29a4c99d1d | ||
|
|
412a627d9e | ||
|
|
3e8de28b51 | ||
|
|
805f509498 | ||
|
|
f88a113109 | ||
|
|
dedf1ff703 | ||
|
|
89eb3d9f36 | ||
|
|
1c2c19b12c | ||
|
|
9144a8f79d | ||
|
|
5ee2faa182 | ||
|
|
fea77824d0 | ||
|
|
605211dbaf | ||
|
|
270624c0c5 | ||
|
|
a9f04609d3 | ||
|
|
27a6dcf3fc | ||
|
|
1dde56790c | ||
|
|
6f0025c6de | ||
|
|
7faafea8a2 | ||
|
|
07ac902451 | ||
|
|
ecb2c4dca3 | ||
|
|
cc1422d448 | ||
|
|
3418592908 | ||
|
|
24df093a85 | ||
|
|
2461d86c8d | ||
|
|
3a1c378325 | ||
|
|
e4d9d72ff1 | ||
|
|
bbe8e4e494 | ||
|
|
da5617624c | ||
|
|
fad7593935 | ||
|
|
bb37b56dea | ||
|
|
3b7e05e07b | ||
|
|
bfbdddff26 | ||
|
|
f73a18c56c | ||
|
|
238dd6413c | ||
|
|
1810fc9efa | ||
|
|
8e62fc1c03 | ||
|
|
eb53281434 | ||
|
|
4b86b2b7e3 | ||
|
|
3a2134db24 | ||
|
|
4d75e9059c | ||
|
|
b129750f4d | ||
|
|
88f61581d9 | ||
|
|
cb3cf960d7 | ||
|
|
64028647a0 | ||
|
|
aeb372c2f0 | ||
|
|
5b68940213 | ||
|
|
68f81aa2af | ||
|
|
d2ae5e9201 | ||
|
|
0f21c80335 | ||
|
|
c1673aaba3 | ||
|
|
64129897f9 | ||
|
|
d745e577b4 | ||
|
|
a3b6004115 | ||
|
|
7757c53b06 | ||
|
|
5dd013c3b1 | ||
|
|
5a550ef2af | ||
|
|
3d006b6cf9 | ||
|
|
ce092742da | ||
|
|
e69f943911 | ||
|
|
b50250139e | ||
|
|
d72e605cb7 | ||
|
|
2ce13713fb | ||
|
|
cf2d68501c | ||
|
|
003480ad90 | ||
|
|
b680681b34 | ||
|
|
c033378048 | ||
|
|
9c549f4513 | ||
|
|
608ce98e1a | ||
|
|
a92619f18c | ||
|
|
7cb8b28f58 | ||
|
|
606e41d574 | ||
|
|
f4bb203782 | ||
|
|
d5b47abe98 | ||
|
|
a0658bb504 | ||
|
|
12f07ee126 | ||
|
|
b815c8fe2d | ||
|
|
afe52efc8a | ||
|
|
82cb0e4d95 | ||
|
|
b3e08831f7 | ||
|
|
c11984d943 | ||
|
|
968184ef0d | ||
|
|
69dd56b237 | ||
|
|
2799994098 | ||
|
|
492868a966 | ||
|
|
681659f2d2 | ||
|
|
a9a157af0f | ||
|
|
ef1e20bfe8 | ||
|
|
543873263a | ||
|
|
e485aff597 | ||
|
|
9ba281c141 | ||
|
|
54a86d72f2 | ||
|
|
3ab0cf49af | ||
|
|
6e78efd971 | ||
|
|
24ed9a8b7d | ||
|
|
797de3e0c3 | ||
|
|
b7abf7dda9 | ||
|
|
de57da3249 | ||
|
|
cb1ab0aa49 | ||
|
|
98df3c8103 | ||
|
|
db8c8ea4a4 | ||
|
|
d05c671a7e | ||
|
|
f1340142f0 | ||
|
|
44c682724d | ||
|
|
dcf9930858 | ||
|
|
e6baa9ccf2 | ||
|
|
52f4d700ca | ||
|
|
23295514f6 | ||
|
|
69619030f3 | ||
|
|
03e6caa501 | ||
|
|
1cfd19aee3 | ||
|
|
f666d1596b | ||
|
|
6a71f80a9e | ||
|
|
4f800bfbc8 | ||
|
|
bb9a1e5f9f | ||
|
|
23958ba96a | ||
|
|
9698eee934 | ||
|
|
ca22a116ad | ||
|
|
5d73b303fe | ||
|
|
0767718a17 | ||
|
|
dd47d7adb4 | ||
|
|
b0e4aa8eff | ||
|
|
454fba2328 | ||
|
|
36030176bb | ||
|
|
ac0c931492 | ||
|
|
7fb8ae3e1b | ||
|
|
9baf228e8d | ||
|
|
5de3f1d9dd | ||
|
|
95cbbf1cb5 | ||
|
|
cf974168e9 | ||
|
|
51dfd2bf47 | ||
|
|
5c8544a425 | ||
|
|
7fff389f34 | ||
|
|
4e64bc3d29 | ||
|
|
bdba6186d8 | ||
|
|
79b255179d | ||
|
|
028139fa3a | ||
|
|
c29543dd6c | ||
|
|
6e1bbb5c88 | ||
|
|
261cd7746b | ||
|
|
ef2c31b543 | ||
|
|
060a1b3fbc | ||
|
|
08ef2730a9 | ||
|
|
62402351b3 | ||
|
|
02527eeea4 | ||
|
|
b3157fc499 | ||
|
|
94f56af77d | ||
|
|
9bbaeb4e6f | ||
|
|
aacc1d5004 | ||
|
|
d613553306 | ||
|
|
7dd74c374a | ||
|
|
97fd33d752 | ||
|
|
523a9a603c | ||
|
|
0f2ddbbef2 | ||
|
|
2e4e5c86da | ||
|
|
4dcd15da1d | ||
|
|
617a58402f | ||
|
|
12e735e831 | ||
|
|
b41633cfe3 | ||
|
|
59cd4fe0ef | ||
|
|
292962d64d | ||
|
|
610d5210ce | ||
|
|
1840695a1c | ||
|
|
1db9169cfc | ||
|
|
5c5fe4c13a | ||
|
|
272ff51d51 | ||
|
|
56dcf080a9 | ||
|
|
93429a58b2 | ||
|
|
9cd2ed5a16 | ||
|
|
fa4c199aa6 | ||
|
|
2371d1e696 | ||
|
|
66487f2a13 | ||
|
|
83a8d79115 | ||
|
|
db17ccef2b | ||
|
|
03cda8e23e | ||
|
|
6729dfa6d3 | ||
|
|
96efd12a31 | ||
|
|
e94da7ca41 | ||
|
|
cc3d05488b | ||
|
|
d8c224c212 | ||
|
|
aefc20738a | ||
|
|
a7dc8f5f4f | ||
|
|
5d850825f5 | ||
|
|
cca371c573 | ||
|
|
6d80c03877 | ||
|
|
e5c6499706 | ||
|
|
7b62e71f23 | ||
|
|
866da8aaa1 | ||
|
|
3330d327ed | ||
|
|
7b80985533 | ||
|
|
934dd97eb2 | ||
|
|
96a43327ca | ||
|
|
b425cc3e3b | ||
|
|
f75606d295 | ||
|
|
5bd3bae5af | ||
|
|
bd1b05828e | ||
|
|
6d63de1932 | ||
|
|
553e5656ac | ||
|
|
6838ae0591 | ||
|
|
a96112f631 | ||
|
|
f4b626eda3 | ||
|
|
8044846d37 | ||
|
|
477515c4b5 | ||
|
|
e0f420983e | ||
|
|
40368bd1b2 | ||
|
|
5816d1c1bd | ||
|
|
469db0d434 | ||
|
|
23d3a7f31e | ||
|
|
1b457e902c | ||
|
|
bcecaa69d4 | ||
|
|
e0489878d8 | ||
|
|
133ba5d6a1 | ||
|
|
5c38b92a75 | ||
|
|
8adaaf37e0 | ||
|
|
7278cdc7d5 | ||
|
|
d95ae135a8 | ||
|
|
5754e51960 | ||
|
|
8a25490146 | ||
|
|
4fbabd3b99 | ||
|
|
49d30ad0e2 | ||
|
|
cc41317670 | ||
|
|
2c0fc3c735 | ||
|
|
f92d229f2e | ||
|
|
9f03c26c9a | ||
|
|
8a5e4c3f30 | ||
|
|
3666e01396 | ||
|
|
ed24d96a79 | ||
|
|
8ea9b3746b | ||
|
|
714ac6dd08 | ||
|
|
120655d262 | ||
|
|
14bfd4b7ee | ||
|
|
67618e5db5 | ||
|
|
81f971f13e | ||
|
|
7e5fd82f25 | ||
|
|
31a51bd96c | ||
|
|
d7821acbf0 | ||
|
|
b6d4e11e88 | ||
|
|
4ab7a0fb5c | ||
|
|
7155e5cfeb | ||
|
|
f6498bf5f7 | ||
|
|
9cb660776c | ||
|
|
f77fa6b592 | ||
|
|
b57ae20af4 | ||
|
|
83b3323c56 | ||
|
|
85768fcc51 | ||
|
|
7e7af07c04 | ||
|
|
ece1c8a702 | ||
|
|
d1ba994e54 | ||
|
|
237233c300 | ||
|
|
2ef2754ffd | ||
|
|
3eeaa50fe5 | ||
|
|
62b546b180 | ||
|
|
bb791eac7e | ||
|
|
7f3b4a97dd | ||
|
|
333d505b66 | ||
|
|
080ecae332 | ||
|
|
05b8010460 | ||
|
|
2f6aafe66c | ||
|
|
9cadb188d7 | ||
|
|
efd59ed9ad | ||
|
|
509b1901b3 | ||
|
|
17895282a1 | ||
|
|
b3e144f317 | ||
|
|
afc1329126 | ||
|
|
92f9c828e6 | ||
|
|
8316acfa78 | ||
|
|
95d271ca5d | ||
|
|
c21b45647d | ||
|
|
dedb91645c | ||
|
|
eab15e09f5 | ||
|
|
a321d0a820 | ||
|
|
daa9863d0b | ||
|
|
79d1d63e6f | ||
|
|
8c93760a6d | ||
|
|
fe2c158e59 | ||
|
|
f96f0cdea7 | ||
|
|
9e921d4410 | ||
|
|
e442e22a20 | ||
|
|
9798e881cb | ||
|
|
3679b0948a | ||
|
|
fc3f8b436d | ||
|
|
b383113d6c | ||
|
|
8559b2dc23 | ||
|
|
936441a853 | ||
|
|
9065e79f53 | ||
|
|
6096f3ca47 | ||
|
|
98050ff594 | ||
|
|
233c442af9 | ||
|
|
a0e8bfbd77 | ||
|
|
409465ac8e | ||
|
|
30a6e684a6 | ||
|
|
b8f78cb187 | ||
|
|
e0fda7a5dd | ||
|
|
2f55cbde35 | ||
|
|
d66ff78e79 | ||
|
|
35759b372d | ||
|
|
d733657db5 | ||
|
|
1121ec0724 | ||
|
|
f9fefc14c9 | ||
|
|
86ad0c047c | ||
|
|
d3387dec45 | ||
|
|
551dc79cf7 | ||
|
|
7e4a0baef2 | ||
|
|
a4fc5afb66 | ||
|
|
db9a85f4a2 | ||
|
|
20c48fb351 | ||
|
|
57d3a6f7a7 | ||
|
|
ae13f3db17 | ||
|
|
f860aab094 | ||
|
|
7e1a30f9bf | ||
|
|
8a316aba35 | ||
|
|
426db72126 | ||
|
|
dfeabcf7e5 | ||
|
|
c5474794d1 | ||
|
|
92e2a3c0ea | ||
|
|
5c77dc6b3b | ||
|
|
1fe066e4ad | ||
|
|
b09a1d1abe | ||
|
|
346e155dd9 | ||
|
|
25daf3a0f7 | ||
|
|
67ace0a76c | ||
|
|
a063397447 | ||
|
|
b90392f9be | ||
|
|
59545013c1 | ||
|
|
49d1687229 | ||
|
|
7da127d28e | ||
|
|
11900eff39 | ||
|
|
764aed2c37 | ||
|
|
91dc8644bf | ||
|
|
130a6f42c5 | ||
|
|
7fdd23a29d | ||
|
|
ee697d609c | ||
|
|
530d521d78 | ||
|
|
39efda19f4 | ||
|
|
7301d76cff | ||
|
|
0535660db7 | ||
|
|
af7283017b | ||
|
|
907761f994 | ||
|
|
98738c482a | ||
|
|
184b5ca3fc | ||
|
|
677a9e56af | ||
|
|
202b1d1f0b | ||
|
|
2f81dc8ff4 | ||
|
|
71814ae2d6 | ||
|
|
c69b87914d | ||
|
|
7f9f53248c | ||
|
|
3c6d10f03e | ||
|
|
bc356c4d65 | ||
|
|
518dcf5209 | ||
|
|
fb52d32296 | ||
|
|
57bc4a866a | ||
|
|
d7459bbbf3 | ||
|
|
8a3272e7c5 | ||
|
|
f9bbeb79fa | ||
|
|
d953190ca5 | ||
|
|
14e5816975 | ||
|
|
5134736c61 | ||
|
|
ca2ffaa201 | ||
|
|
b10d41c28a | ||
|
|
b546f0302e | ||
|
|
80bd4129f1 | ||
|
|
b278dcd6db | ||
|
|
a9642dbcdb | ||
|
|
631ba464f3 | ||
|
|
4b9d04a2ca | ||
|
|
e0081bcb53 | ||
|
|
93503d6051 | ||
|
|
6aa9cd1060 | ||
|
|
cda3ddffac | ||
|
|
fb3fd7cb15 | ||
|
|
912e9bd15c | ||
|
|
138c8152c2 | ||
|
|
701978a4b1 | ||
|
|
3628659810 | ||
|
|
792d2dbe32 | ||
|
|
a4d2bb6f29 | ||
|
|
3e8e8a55fa | ||
|
|
3de3c246b4 | ||
|
|
6ff4c9b888 | ||
|
|
bb057408b0 | ||
|
|
03fb188555 | ||
|
|
8cf435f0ba | ||
|
|
5b7279793c | ||
|
|
a541d0a931 | ||
|
|
44c275c801 | ||
|
|
8c6d7c48ad | ||
|
|
fbe69cee3f | ||
|
|
eee0958a58 | ||
|
|
29b38bdcbe | ||
|
|
98c1706cdd | ||
|
|
b1f016b9c0 | ||
|
|
5029003957 | ||
|
|
2126b00dce | ||
|
|
a20ceb9e31 | ||
|
|
d23dc3ec41 | ||
|
|
21480d4219 | ||
|
|
2cd7b40b38 | ||
|
|
d7994cf9a3 | ||
|
|
3af655d170 | ||
|
|
55a6cac966 | ||
|
|
d5409287e0 | ||
|
|
6dec05b2a5 | ||
|
|
1d38c35e6a | ||
|
|
6d4f68fcdb | ||
|
|
9e44b260e2 | ||
|
|
bd25212bd6 | ||
|
|
36d928d411 | ||
|
|
f56bd5f5b7 | ||
|
|
18c04ab4e2 | ||
|
|
ce4f0696e1 | ||
|
|
3973d3697c | ||
|
|
37088cfb39 | ||
|
|
ddc1513286 | ||
|
|
d1edcf9dcd | ||
|
|
e7d5cf9d9d | ||
|
|
939aa6009a | ||
|
|
d3078d7564 | ||
|
|
77cac9e562 | ||
|
|
06d75a8bad | ||
|
|
9723300a07 | ||
|
|
73efe52aea | ||
|
|
3ed486f3a0 | ||
|
|
8532e66982 | ||
|
|
fa38772942 | ||
|
|
1e669c7228 | ||
|
|
b57d9edda8 | ||
|
|
6f79b55845 | ||
|
|
e63e808521 | ||
|
|
a46b3ec9e7 | ||
|
|
e1ffc11f00 | ||
|
|
de20e142a0 | ||
|
|
a364a1e40d | ||
|
|
697493bd01 | ||
|
|
23f8980973 | ||
|
|
8741a63783 | ||
|
|
26b3c3f7a8 | ||
|
|
3b57aef168 | ||
|
|
9c4fdc1bc5 | ||
|
|
d634a03455 | ||
|
|
e4fc298bd6 | ||
|
|
11c3b3fdb9 | ||
|
|
a6c2e40bd4 | ||
|
|
d549fe351c | ||
|
|
4a9ed02b9b | ||
|
|
9137338771 | ||
|
|
f306abb3ee | ||
|
|
8b3631d1ac | ||
|
|
2056b6f5f1 | ||
|
|
ad666ac65c | ||
|
|
f72fb0ad04 | ||
|
|
114fd7feef | ||
|
|
aa1948750f | ||
|
|
2a9ca9a3dc | ||
|
|
d0c7b7c582 | ||
|
|
b130a923f7 | ||
|
|
3af3094a56 | ||
|
|
9d70d25064 | ||
|
|
05adebb536 | ||
|
|
e1ddddad4f | ||
|
|
84622dc84b | ||
|
|
36e9abc841 | ||
|
|
1b290ffb5d | ||
|
|
334e7553e1 | ||
|
|
f4585a2745 | ||
|
|
448f3a7197 | ||
|
|
cff83d3e6f | ||
|
|
c8d06e2b0e | ||
|
|
f15825e3a7 | ||
|
|
e822d5d721 | ||
|
|
96a0fc88cb | ||
|
|
6e66763e5f | ||
|
|
d6415f3499 | ||
|
|
89b515be60 | ||
|
|
d481895763 | ||
|
|
4ad3e96a2f | ||
|
|
3893b638fe | ||
|
|
21f5a94eca | ||
|
|
5dac3b5664 | ||
|
|
bcb13d041e | ||
|
|
25d6ed319a | ||
|
|
24364a56ea | ||
|
|
0594deafc6 | ||
|
|
75ba6578a3 | ||
|
|
abb398786e | ||
|
|
fcf837bfda | ||
|
|
87df4e4556 | ||
|
|
f790f95319 | ||
|
|
766d32897d | ||
|
|
e09674b77f | ||
|
|
88ccdc0366 | ||
|
|
d04247cd9e | ||
|
|
d13e87d7a4 | ||
|
|
40d73de357 | ||
|
|
e8716f16ad | ||
|
|
a806dd45f2 | ||
|
|
027ec4d98e | ||
|
|
308428644b | ||
|
|
76dd754963 | ||
|
|
303eefda76 | ||
|
|
1366783517 | ||
|
|
a26131cea3 | ||
|
|
56050e5afe | ||
|
|
bbcbf6adc8 | ||
|
|
6116c27aa9 | ||
|
|
12e6287875 | ||
|
|
0e168159c1 | ||
|
|
29459d7d30 | ||
|
|
e1c9b77c44 | ||
|
|
f1b4e4b36c | ||
|
|
54b714ba3f | ||
|
|
cf37093e5a | ||
|
|
d6d3dfdcc2 | ||
|
|
c11e97caf6 | ||
|
|
66b1eac1db | ||
|
|
e1ca80734d | ||
|
|
fbc77c1f28 | ||
|
|
3b925e46be | ||
|
|
3e3ed947cc | ||
|
|
61095db071 | ||
|
|
4fd037f83f | ||
|
|
4bd956d5b1 | ||
|
|
74979943ba | ||
|
|
2d432bfa95 | ||
|
|
21f4b85c7f | ||
|
|
4746aea05c | ||
|
|
ef52c7b510 | ||
|
|
f302882f67 | ||
|
|
8e659af580 | ||
|
|
567211e9f9 | ||
|
|
95f884f4f3 | ||
|
|
decaf6c42e | ||
|
|
53c0f01bef | ||
|
|
0aa8557c03 | ||
|
|
4d5e368c2e | ||
|
|
2d4d1d7306 | ||
|
|
2c5b6aca91 | ||
|
|
eaa657aa3b | ||
|
|
a5d4de8037 | ||
|
|
52b75c5997 | ||
|
|
f04e4f2123 | ||
|
|
176bae2d59 | ||
|
|
14e21765f2 | ||
|
|
eebaede80d | ||
|
|
9b83a09224 | ||
|
|
0a4b2f19e3 | ||
|
|
3abc294e5f | ||
|
|
6aa18bddc9 | ||
|
|
16279bc171 | ||
|
|
14961e2e38 | ||
|
|
30ae5829f5 | ||
|
|
200dfa7575 | ||
|
|
51b3eb78d7 | ||
|
|
9685c09c1a | ||
|
|
4303e86e09 | ||
|
|
88854cba2d | ||
|
|
07ba14d1ea | ||
|
|
f4d26961c8 | ||
|
|
5d9c7fa82d | ||
|
|
029a6798a4 | ||
|
|
5f68834ccc | ||
|
|
e30d23cf23 | ||
|
|
f5ba34addf | ||
|
|
bcf47b29ed | ||
|
|
91c0e3640f | ||
|
|
3f890335c5 | ||
|
|
601ae05459 | ||
|
|
fadf82dd32 | ||
|
|
241b23e5d8 | ||
|
|
c429eae6e4 | ||
|
|
674bad2a4f | ||
|
|
14b7fc42fa | ||
|
|
14717b1701 | ||
|
|
51ef137981 | ||
|
|
f954efbd64 | ||
|
|
0a29096794 | ||
|
|
687dc78dbd | ||
|
|
8aaf174578 | ||
|
|
2660be9b13 | ||
|
|
65ad9cf741 | ||
|
|
179bcf3907 | ||
|
|
062eca19b8 | ||
|
|
4692174677 | ||
|
|
65699f702e | ||
|
|
e57be10772 | ||
|
|
5ba6cfe406 | ||
|
|
f0c7394bc8 | ||
|
|
fb4f83b32c | ||
|
|
a49a60b4fa | ||
|
|
13ffd88053 | ||
|
|
4e847f26bc | ||
|
|
0004b32411 | ||
|
|
a74953cb4d | ||
|
|
4f583d61c8 | ||
|
|
3eb2e92d53 | ||
|
|
a748c0794e | ||
|
|
1682d6b365 | ||
|
|
27ffce4c3f | ||
|
|
d62f97dc3b | ||
|
|
9c1cd4bee2 | ||
|
|
754027efed | ||
|
|
e9deb928f6 | ||
|
|
6b74fb0893 | ||
|
|
feb14990c2 | ||
|
|
3831f198e9 | ||
|
|
adfd8c7f5c | ||
|
|
3fd00c9a9c | ||
|
|
2ec5a536aa | ||
|
|
d35d3bb38c | ||
|
|
cb46aeb73c | ||
|
|
b8624e5909 | ||
|
|
fa5c8e4bb1 | ||
|
|
9945b97595 | ||
|
|
17d6d92302 | ||
|
|
9560cb8056 | ||
|
|
3ed97fe5e8 | ||
|
|
35c5d4f580 | ||
|
|
a1bd30aa60 | ||
|
|
ffd4469c1d | ||
|
|
54ddd908e6 | ||
|
|
d41f0667b8 | ||
|
|
9f8e68ce02 | ||
|
|
f7b67cec5b | ||
|
|
e14e7d9b8a | ||
|
|
b659ec00ee | ||
|
|
b6b89a464f | ||
|
|
c9ee528050 | ||
|
|
9bce6c5f48 | ||
|
|
cdfff57403 | ||
|
|
19628d317a | ||
|
|
32ae344e59 | ||
|
|
c99ff78f2f | ||
|
|
188cfc435d | ||
|
|
1a9c085f10 | ||
|
|
eefc5349c8 | ||
|
|
fe169483ed | ||
|
|
4dfaf1d284 | ||
|
|
c5efcace47 | ||
|
|
c770eae70b | ||
|
|
2ee1a2d851 | ||
|
|
42587741dd | ||
|
|
a489a044ad | ||
|
|
1d0802192d | ||
|
|
ab628c1381 | ||
|
|
bc6b80ff38 | ||
|
|
a37802e21c | ||
|
|
8c0e33753e | ||
|
|
cac7e2c745 | ||
|
|
ebc072396b | ||
|
|
4508349d07 | ||
|
|
7376a0d538 | ||
|
|
36e0e652f0 | ||
|
|
5e4ae46b3c | ||
|
|
66d52c1236 | ||
|
|
6e90d482ef | ||
|
|
37bb6ac57b | ||
|
|
8a844488d4 | ||
|
|
e5707b8a2c | ||
|
|
8f41e0e190 | ||
|
|
4bf0542204 | ||
|
|
43f73c5aec | ||
|
|
a077955efa | ||
|
|
0674c3e8f0 | ||
|
|
6d1c82a5fa | ||
|
|
de0f3e43bf | ||
|
|
694b8be32f | ||
|
|
9403248e4d | ||
|
|
c955c7c494 | ||
|
|
5a0876704a | ||
|
|
97e9a44fd2 | ||
|
|
088c54b88c | ||
|
|
d722c12109 | ||
|
|
d556f669b0 | ||
|
|
66255b8c61 | ||
|
|
bc22320f77 | ||
|
|
64781643d3 | ||
|
|
56188f2f67 | ||
|
|
eb4bc66443 | ||
|
|
d1c5eebff2 | ||
|
|
98240e0e48 | ||
|
|
0750d356a1 | ||
|
|
f57bf8f269 | ||
|
|
dc41a19f99 | ||
|
|
16fa877b67 | ||
|
|
ff8ed564f1 | ||
|
|
e6e2799f03 | ||
|
|
4a8c120926 | ||
|
|
aa10c6e6fe | ||
|
|
a2d9126917 | ||
|
|
e02f964e3a | ||
|
|
be373e7563 | ||
|
|
baeffee80d | ||
|
|
76914c2c07 | ||
|
|
ca6594cd24 | ||
|
|
d007ac4b96 | ||
|
|
6e2a2abe80 | ||
|
|
dd7f540e5a | ||
|
|
78d1a677d7 | ||
|
|
2999588ea7 | ||
|
|
1edbc494ee | ||
|
|
b34aa46181 | ||
|
|
48e218d6c0 | ||
|
|
2bc7a668a3 | ||
|
|
8b9f1cadaa | ||
|
|
3aa210cf93 | ||
|
|
e37cb49dc2 | ||
|
|
67cbbc86f2 | ||
|
|
37e504610a | ||
|
|
8528143ffa | ||
|
|
69cc6aa958 | ||
|
|
a6b69da391 | ||
|
|
05cfbde8fc | ||
|
|
04878da66b | ||
|
|
0b44dda7b7 | ||
|
|
78610bb47f | ||
|
|
721fb3e326 | ||
|
|
50494858f1 | ||
|
|
eca8682528 | ||
|
|
a488734efa | ||
|
|
2e7837976d | ||
|
|
a0bc17d1ef | ||
|
|
2b37c1ff0e | ||
|
|
7d72e364aa | ||
|
|
bd61478367 | ||
|
|
f7afd9a5ff | ||
|
|
7f6f5791ea | ||
|
|
e3e79a55fa | ||
|
|
e73331b9b6 | ||
|
|
ffa47151ee | ||
|
|
5f8ec82319 | ||
|
|
3ad6ee6b2c | ||
|
|
5bec389e85 | ||
|
|
88e85e8d33 | ||
|
|
fce071843d | ||
|
|
a852d2ff32 | ||
|
|
a107c4c7b4 | ||
|
|
74d6816a1a | ||
|
|
e34f2abc3a | ||
|
|
8a0fc888d6 | ||
|
|
36f05af79a | ||
|
|
e654b76bc8 | ||
|
|
56768f1a61 | ||
|
|
b008649d79 | ||
|
|
3b2f161573 | ||
|
|
df960241bd | ||
|
|
4ece5d6d7a | ||
|
|
e36067afd3 | ||
|
|
c4e43039f2 | ||
|
|
853374d156 | ||
|
|
1bcd4333fc | ||
|
|
029d61b8c5 | ||
|
|
280ead7bdb | ||
|
|
98730939d4 | ||
|
|
d1306a2177 | ||
|
|
cb26085229 | ||
|
|
ed4771bf6e | ||
|
|
cef09f49a6 | ||
|
|
e1921c8849 | ||
|
|
3c451e0677 | ||
|
|
636ae1dcd8 | ||
|
|
4d03fc213f | ||
|
|
863110422a | ||
|
|
3d94720be9 | ||
|
|
c9c0e108ab | ||
|
|
c9580b31d0 | ||
|
|
255f303850 | ||
|
|
131d268721 | ||
|
|
eca5c6f389 | ||
|
|
bc62f626c5 | ||
|
|
199bd7bc50 | ||
|
|
8fc0f6ecec | ||
|
|
65f7b75c34 | ||
|
|
848ecb91bb | ||
|
|
a5554604e0 | ||
|
|
0b825e96aa | ||
|
|
a2730cd86e | ||
|
|
1309c2b14f | ||
|
|
7143b64fb7 | ||
|
|
26d591ea43 | ||
|
|
ba4de4137e | ||
|
|
be9436b2a6 | ||
|
|
4a9bf78770 | ||
|
|
d73d0a5253 | ||
|
|
ea506b05c6 | ||
|
|
6ef14677de | ||
|
|
721341e412 | ||
|
|
3ce4d20ab9 | ||
|
|
af93b18475 | ||
|
|
a586a7526e | ||
|
|
3987a8aeb8 | ||
|
|
59b9a6d94d | ||
|
|
b963b95ee9 | ||
|
|
3037d85529 | ||
|
|
10ab6c7ffa | ||
|
|
71b0e15182 | ||
|
|
1fef384bba | ||
|
|
d2a728cebd | ||
|
|
6b3e8dcc33 | ||
|
|
c38d94df2d | ||
|
|
2cfa3b7607 | ||
|
|
85c73ea850 | ||
|
|
337d9174d9 | ||
|
|
80a1c6ea64 | ||
|
|
05ca78d2a3 | ||
|
|
2ec2f1abce | ||
|
|
7dc440b874 | ||
|
|
ea72af7ce4 | ||
|
|
145008421f | ||
|
|
398c61786a | ||
|
|
00b81e3f0d | ||
|
|
0fc4a7910d | ||
|
|
7f4472ad77 | ||
|
|
e282d57a91 | ||
|
|
3a5b435dfa | ||
|
|
17d78b7807 | ||
|
|
1f97d0d78b | ||
|
|
a741f1144a | ||
|
|
f619cd1d2a | ||
|
|
4f5b530dcb | ||
|
|
9c08cdc81d | ||
|
|
915160f21f | ||
|
|
c466a028e0 | ||
|
|
29dcd2ea43 | ||
|
|
f7f75b4b04 | ||
|
|
7458aa438c | ||
|
|
36f91fcdf5 | ||
|
|
5b8ee214f9 | ||
|
|
038e97667f | ||
|
|
04d5e857e2 | ||
|
|
3428b6666b | ||
|
|
b47c5f1d9a | ||
|
|
40ee86b357 | ||
|
|
76fbb89a03 | ||
|
|
c648e2acfc | ||
|
|
765d1c769c | ||
|
|
028589abd2 | ||
|
|
5125076f5d | ||
|
|
4ea6780153 | ||
|
|
a8b55b8989 | ||
|
|
a57a2f4a75 | ||
|
|
bd3563df67 | ||
|
|
644f729aea | ||
|
|
5f2e92ec5c | ||
|
|
65aaa3dffd | ||
|
|
9a42aac0f2 | ||
|
|
56046b3cb3 | ||
|
|
e7d0439741 | ||
|
|
136442245c | ||
|
|
12417cc303 | ||
|
|
52065178e1 | ||
|
|
b45d465ed8 | ||
|
|
31870abd25 | ||
|
|
a486b1d01c | ||
|
|
e38e0e60e1 | ||
|
|
74fa4ddca4 | ||
|
|
66a0986496 | ||
|
|
72480188b7 | ||
|
|
ab4343b7c0 | ||
|
|
be1298dbd2 | ||
|
|
154e4569d7 | ||
|
|
c8f125dbb9 | ||
|
|
1044d15b17 | ||
|
|
2d7ef30185 | ||
|
|
bf0b1af878 | ||
|
|
b83487cc36 | ||
|
|
d048f3ce6d | ||
|
|
5a55cd25ff | ||
|
|
f85cc422a3 | ||
|
|
155e134f50 | ||
|
|
81cf7229be | ||
|
|
fe27ca63b4 | ||
|
|
012fe94333 | ||
|
|
075a42d615 | ||
|
|
8b8d3f3b75 | ||
|
|
3ecc502d86 | ||
|
|
67d1693901 | ||
|
|
3083e5d2be | ||
|
|
affdeb8fd8 | ||
|
|
fb80964b69 | ||
|
|
1c20ef873d | ||
|
|
df53e912f0 | ||
|
|
e242842805 | ||
|
|
2401fa15d2 | ||
|
|
787d6042de | ||
|
|
941879dc19 | ||
|
|
82680ac6aa | ||
|
|
5fbce13830 | ||
|
|
39cf0decce | ||
|
|
f286ba6b87 | ||
|
|
98665dcef4 | ||
|
|
cf83416d69 | ||
|
|
791c5ff071 | ||
|
|
8a9c54ed61 | ||
|
|
18b8f20f1c | ||
|
|
f12167f0dc | ||
|
|
df8700ead0 | ||
|
|
0eff6719c2 | ||
|
|
aa772c28ad | ||
|
|
4ebd706cb8 | ||
|
|
fa48b8a535 | ||
|
|
c9a97bccb7 | ||
|
|
2f905cb696 | ||
|
|
7300c0a0fe | ||
|
|
921f645623 | ||
|
|
0dcaa82c3b | ||
|
|
3dd7d209e9 | ||
|
|
abc55a6e6b | ||
|
|
5871488858 | ||
|
|
2e6e5029ba | ||
|
|
19b9966417 | ||
|
|
57f683697d | ||
|
|
296d3d8bbe | ||
|
|
336cd524a3 | ||
|
|
f832edf5bc | ||
|
|
1bbb86c621 | ||
|
|
2ef35400c9 | ||
|
|
9c7f53d90d | ||
|
|
ebfcc0fc13 | ||
|
|
42024134ec | ||
|
|
7f27beff4b | ||
|
|
dd71071740 | ||
|
|
c85c7a3a77 | ||
|
|
1e804c0df5 | ||
|
|
fc06d028b8 | ||
|
|
618784d060 | ||
|
|
cfcc2e61e5 | ||
|
|
187e039a58 | ||
|
|
b3df1b1ba7 | ||
|
|
ab66fe1b72 | ||
|
|
ed47240b6e | ||
|
|
1a673c6ac9 | ||
|
|
0a059662b3 | ||
|
|
cb2fff8909 | ||
|
|
cdd8cc551c | ||
|
|
8648ac9da2 | ||
|
|
083befaafc | ||
|
|
099e7020c8 | ||
|
|
6ab8fa8c71 | ||
|
|
b2b81c8b2d | ||
|
|
243b63e39c | ||
|
|
a3d870ad3e | ||
|
|
1ceaa2200a | ||
|
|
c8ac98501c | ||
|
|
ca0d658f15 | ||
|
|
4547ae930a | ||
|
|
40ae250193 | ||
|
|
c47253133a | ||
|
|
7efa81073a | ||
|
|
d23b3ccc5e | ||
|
|
48cd468b6c | ||
|
|
0372485cf0 | ||
|
|
93ba80b5a9 | ||
|
|
2dc3d6a6b8 | ||
|
|
e39ae45d2f | ||
|
|
df3e76a65d | ||
|
|
f2a9be3684 | ||
|
|
3324cdfcbe | ||
|
|
484103b957 | ||
|
|
6e437a7290 | ||
|
|
0c7ceadb27 | ||
|
|
726b94b077 | ||
|
|
482b85182a | ||
|
|
452a1cad9d | ||
|
|
7b49f746d1 | ||
|
|
78f8c6566e | ||
|
|
79f931f296 | ||
|
|
4b38c8b11d | ||
|
|
3fa1c5b19f | ||
|
|
4f4daf4071 | ||
|
|
dc1ad3cbf6 | ||
|
|
ff6435948e | ||
|
|
23c2a75fc4 | ||
|
|
7feea8c7a6 | ||
|
|
cf6e229729 | ||
|
|
4928686af9 | ||
|
|
30b72ad98a | ||
|
|
1a9ead45eb | ||
|
|
0b3190552e | ||
|
|
456e49fe35 | ||
|
|
ab67822af2 | ||
|
|
7f877aed6f | ||
|
|
4575919d78 | ||
|
|
10fc2c67c7 | ||
|
|
643de58c4d | ||
|
|
aba3c69765 | ||
|
|
0775a371fe | ||
|
|
23fe0db2df | ||
|
|
f54ac5a8de | ||
|
|
4c8411537f | ||
|
|
bd2771b8f9 | ||
|
|
4d864df59e | ||
|
|
fae4c3a4e3 | ||
|
|
2b297869a1 | ||
|
|
6cc0a72bca | ||
|
|
f53e03767c | ||
|
|
5ab1e66978 | ||
|
|
849ded7772 | ||
|
|
f297d22edb | ||
|
|
0681a806cc | ||
|
|
be3f04775a | ||
|
|
9467461160 | ||
|
|
66af41192a | ||
|
|
6f7898809a | ||
|
|
ab3478a742 | ||
|
|
00fa41d63f | ||
|
|
7f6c79eb76 | ||
|
|
b45128f53d | ||
|
|
dd1290e38e | ||
|
|
62701888c9 | ||
|
|
90915b6b2f | ||
|
|
1b2bfad348 | ||
|
|
060469fefc | ||
|
|
4fb9823cfb | ||
|
|
760c79c5e9 | ||
|
|
a452864b41 | ||
|
|
ad98c62329 | ||
|
|
506aa0e3d3 | ||
|
|
426c25f631 | ||
|
|
4059871c28 | ||
|
|
2a61629014 | ||
|
|
8c0b19f80c | ||
|
|
838b0e7b76 | ||
|
|
cbffd3650b | ||
|
|
0147b1631a | ||
|
|
49a7c7f08e | ||
|
|
1af24af391 | ||
|
|
0cc1b66ae7 | ||
|
|
6070d819b8 | ||
|
|
f2bfc9ccc2 | ||
|
|
f991109b0a | ||
|
|
6bb7167b56 | ||
|
|
365ba98131 | ||
|
|
6a3c8e3933 | ||
|
|
c0a7725c1f | ||
|
|
71100a67c9 | ||
|
|
8f254031c6 | ||
|
|
aa69177436 | ||
|
|
64f933477d | ||
|
|
aaa58a956d | ||
|
|
75c0a476f8 | ||
|
|
1ab7f5fb6d | ||
|
|
789b98015f | ||
|
|
7134c15e86 | ||
|
|
79b1030435 | ||
|
|
ac6955fd3b | ||
|
|
a374f95687 | ||
|
|
f9f6a3bd04 | ||
|
|
8e4d2abd4e | ||
|
|
08237abe20 | ||
|
|
5b3fa3c635 | ||
|
|
ee8e890f50 | ||
|
|
3184c85dca | ||
|
|
3df79b8542 | ||
|
|
a290286fef | ||
|
|
c82276ecbe | ||
|
|
b29eed32ca | ||
|
|
e17618407b | ||
|
|
85fd4dd3ff | ||
|
|
78205da4f0 | ||
|
|
e021d22c7f | ||
|
|
8cea0517eb | ||
|
|
ed4bf32f2a | ||
|
|
4a26eb34ea | ||
|
|
50b15b8052 | ||
|
|
e11ec28962 | ||
|
|
baaf0a5b21 | ||
|
|
06d024cc46 | ||
|
|
084264669f | ||
|
|
dbc3874b4f | ||
|
|
78af4bc785 | ||
|
|
a313917347 | ||
|
|
357c8c0ba0 | ||
|
|
3b0cb7bc33 | ||
|
|
8d5da4e6ad | ||
|
|
ec1960530b | ||
|
|
99d16e82c0 | ||
|
|
885a653439 | ||
|
|
059aceb582 | ||
|
|
0f3339f74f | ||
|
|
4a39a754f4 | ||
|
|
5aaf454f12 | ||
|
|
fb0edd71ff | ||
|
|
eed29a6b8a | ||
|
|
2795db3ea0 | ||
|
|
4f957728bf | ||
|
|
62f4d734b9 | ||
|
|
7174f27eb8 | ||
|
|
a3466f4b42 | ||
|
|
050afe2bc0 | ||
|
|
5c87c420c7 | ||
|
|
aeb4102bcb | ||
|
|
f6b8c2b40f | ||
|
|
85e6c9585a | ||
|
|
a74147c472 | ||
|
|
a8b62a21cc | ||
|
|
727f569e3a | ||
|
|
8f59759e97 | ||
|
|
4e68362d46 | ||
|
|
71c3106f8f | ||
|
|
158226012a | ||
|
|
b4ba641131 | ||
|
|
07175ebc5a | ||
|
|
90e3c38757 | ||
|
|
682f4c1ade | ||
|
|
e1de988f85 | ||
|
|
bc83c34118 | ||
|
|
278e7159bc | ||
|
|
1284627219 | ||
|
|
120fc29643 | ||
|
|
6336d8a0e2 | ||
|
|
ee2f6ccbe9 | ||
|
|
144d308e5e | ||
|
|
3ca161f196 | ||
|
|
f55df7ba63 | ||
|
|
71df41c4eb | ||
|
|
a4643066a8 | ||
|
|
25250f7c10 | ||
|
|
fa8512789f | ||
|
|
ae22af1ea3 | ||
|
|
6e16c1d80d | ||
|
|
266092a05d | ||
|
|
fa8b349200 | ||
|
|
04bed3e53e | ||
|
|
68ddd1b951 | ||
|
|
b6e1020f39 | ||
|
|
5b02b87735 | ||
|
|
c17e8d6abb | ||
|
|
cb8cd21e22 | ||
|
|
a559e22f16 | ||
|
|
7eaeb8d146 | ||
|
|
0920fb6120 | ||
|
|
4cb1aa1d97 | ||
|
|
96a405feb7 | ||
|
|
112998c205 | ||
|
|
f1a370b3b9 | ||
|
|
29670b9814 | ||
|
|
df8ba28ce5 | ||
|
|
5288e18f2f | ||
|
|
ddfc4722b9 | ||
|
|
bd46b4faf3 | ||
|
|
46708e7d29 | ||
|
|
06c9494a46 | ||
|
|
8f6252b312 | ||
|
|
1f16ff268f | ||
|
|
aa2366346a | ||
|
|
8b72560eba | ||
|
|
773fb5953b | ||
|
|
3540ba3712 | ||
|
|
d546a4b29f | ||
|
|
b4be3c2499 | ||
|
|
85c60519b0 | ||
|
|
6be6448334 | ||
|
|
f5bc65b877 | ||
|
|
a7a82635b4 | ||
|
|
b9916b60f9 | ||
|
|
b773e3472a | ||
|
|
4654792784 | ||
|
|
750d737b7d | ||
|
|
0bd9674b5c | ||
|
|
8b06000f0f | ||
|
|
efaa8f16e7 | ||
|
|
38487644f0 | ||
|
|
1a24afef77 | ||
|
|
8fb146ba6a | ||
|
|
05b078b8dd | ||
|
|
6926e468a4 | ||
|
|
34764108cc | ||
|
|
17c9c183f5 | ||
|
|
cc107bb3cc | ||
|
|
8dd6e29426 | ||
|
|
3e03a208f1 | ||
|
|
570d27a0c4 | ||
|
|
7c8c8e83d3 | ||
|
|
2b488d1da2 | ||
|
|
e98efe3a35 | ||
|
|
3f6e9cd28f | ||
|
|
af17cef002 | ||
|
|
742fefa786 | ||
|
|
08fe10e302 | ||
|
|
9906da46f6 | ||
|
|
54976fa103 | ||
|
|
e1d7c72bb8 | ||
|
|
af03c17209 | ||
|
|
1897a1cb6a | ||
|
|
58879ff012 | ||
|
|
e1f5745f59 | ||
|
|
1c48902e64 | ||
|
|
8bbee4038b | ||
|
|
c35d1b9c9d | ||
|
|
4f642b769c | ||
|
|
e808b3a2a1 | ||
|
|
df68b0990f | ||
|
|
adbffc69e1 | ||
|
|
21fc933678 | ||
|
|
a2063ede55 | ||
|
|
7dca3c6d03 | ||
|
|
03c112a601 | ||
|
|
c77686c7a7 | ||
|
|
239f8606e1 | ||
|
|
bfd1e90154 | ||
|
|
5ab644dea6 | ||
|
|
966668f48a | ||
|
|
d8d0579c5a | ||
|
|
64c68d93c3 | ||
|
|
700f02dde8 | ||
|
|
ac20bf31df | ||
|
|
bf4d0a9b70 | ||
|
|
96bb2efe69 | ||
|
|
c4a8435e00 | ||
|
|
9dbe0f50a3 | ||
|
|
3a7056ea1b | ||
|
|
2cde540645 | ||
|
|
ef59f9ad24 | ||
|
|
e91cfbfeeb | ||
|
|
2c0e950486 | ||
|
|
ee4754cfb9 | ||
|
|
4a26b88a17 | ||
|
|
2713fdb860 | ||
|
|
79aab4cce2 | ||
|
|
2b34d10973 | ||
|
|
76343ecb77 | ||
|
|
fa8fc3e4ce | ||
|
|
aec3f582e1 | ||
|
|
a58d51ded0 | ||
|
|
5e4a6ba7ba | ||
|
|
3c5be55eb9 | ||
|
|
782570e71e | ||
|
|
ed2a1becef | ||
|
|
937644a04b | ||
|
|
e39d88ef65 | ||
|
|
f91263c8ef | ||
|
|
e2127f5af1 | ||
|
|
2dc881558d | ||
|
|
c66f858b98 | ||
|
|
8023fdf923 | ||
|
|
2cee8e52c1 | ||
|
|
8f49d5eb10 | ||
|
|
9e3e900f78 | ||
|
|
14e12bd3c0 | ||
|
|
c29163a51c | ||
|
|
5a591e01c0 | ||
|
|
c447644fd1 | ||
|
|
98108a78f1 | ||
|
|
0ce08932ed | ||
|
|
6dd5f85fb6 | ||
|
|
d8f2a683c6 | ||
|
|
8a941f3aa8 | ||
|
|
cf6b1a637a | ||
|
|
dcdc18a338 | ||
|
|
15c7854e7f | ||
|
|
fe8a21681e | ||
|
|
ebbfc720b2 | ||
|
|
8ec9a09749 | ||
|
|
2d4ce593b5 | ||
|
|
c5a00b4d45 | ||
|
|
7cecae5279 | ||
|
|
d5ad066f8d | ||
|
|
860b270e30 | ||
|
|
35e07bf11e | ||
|
|
19beb0941f | ||
|
|
8ecdae67e1 | ||
|
|
e6e868a03c | ||
|
|
78e6c9fdf6 | ||
|
|
c997aa9864 | ||
|
|
a91d75b3b2 | ||
|
|
e9d5bceeb9 | ||
|
|
88b898cce4 | ||
|
|
8bec505bbe | ||
|
|
a3708bc56e | ||
|
|
03005bc0f1 | ||
|
|
da5be9fbd0 | ||
|
|
3e167e1170 | ||
|
|
5015bc9bb0 | ||
|
|
243c36b39b | ||
|
|
9ac3c559b6 | ||
|
|
257e1847b1 | ||
|
|
54f52fb366 | ||
|
|
e1d8a59b69 | ||
|
|
7c2a50cef9 | ||
|
|
4c7d1c90db | ||
|
|
4f1fa28658 | ||
|
|
2b6407e598 | ||
|
|
0bddc58ec4 | ||
|
|
17ee7f8be5 | ||
|
|
375ea940f4 | ||
|
|
43f1a1d264 | ||
|
|
e70cb963f7 | ||
|
|
a8cb0b0321 | ||
|
|
118a43cbb8 | ||
|
|
5e7e977ffa | ||
|
|
660ec6f443 | ||
|
|
e98f22ef2f | ||
|
|
2bb63ba33d | ||
|
|
1529ce8bdb | ||
|
|
d8cb63efdd | ||
|
|
5055563458 | ||
|
|
f506ebcd62 | ||
|
|
3cedace2f6 | ||
|
|
3384679bad | ||
|
|
46a062d5fb | ||
|
|
8b7183cdbc | ||
|
|
beb15532f7 | ||
|
|
107f3ed35b | ||
|
|
f82b809fcf | ||
|
|
9bad75f37d | ||
|
|
864bbc441a | ||
|
|
e2df908304 | ||
|
|
642ad02316 | ||
|
|
ab9e2fcea0 | ||
|
|
136456afc0 | ||
|
|
4ea5fcc661 | ||
|
|
9c66c25890 | ||
|
|
925b9b0c19 | ||
|
|
09261b11af | ||
|
|
e25d8f9435 | ||
|
|
0440a19171 | ||
|
|
0b3e4f6bcd | ||
|
|
295dfe2652 | ||
|
|
df9015a7f1 | ||
|
|
e8f2e6956d | ||
|
|
dde7df7fd3 | ||
|
|
a525cba8e9 | ||
|
|
8272120c3a | ||
|
|
8fee2e2409 | ||
|
|
c415014153 | ||
|
|
964cbdc262 | ||
|
|
a46badd5c0 | ||
|
|
0cb1aedf5b | ||
|
|
b485e6e0ba | ||
|
|
810d7de869 | ||
|
|
398b21a11d | ||
|
|
78f50a1471 | ||
|
|
5aae215c94 | ||
|
|
2738d3aed8 | ||
|
|
01d45bee76 | ||
|
|
c1691f21f3 | ||
|
|
a68c90c512 | ||
|
|
90caa09ae0 | ||
|
|
909fd39b80 | ||
|
|
d23cd73ba8 | ||
|
|
fc219b4e94 | ||
|
|
818a6b12ed | ||
|
|
4bd61df3a7 | ||
|
|
c40e6a12d1 | ||
|
|
3360bf4001 | ||
|
|
168ed91fe1 | ||
|
|
9a07d57ed7 | ||
|
|
2be7b3d9eb | ||
|
|
e2a2a0be9b | ||
|
|
f7e5d2c3a5 | ||
|
|
cbfee51f32 | ||
|
|
8a44dff595 | ||
|
|
c73b9f5c77 | ||
|
|
e759a90b2d | ||
|
|
c413e94f83 | ||
|
|
98cd8970f9 | ||
|
|
5fcdd3831c | ||
|
|
7f927b4d7a | ||
|
|
99e3c6e526 | ||
|
|
c7976f51e2 | ||
|
|
2c43590268 | ||
|
|
36cfea3d0f | ||
|
|
a493a2ceef | ||
|
|
96b7273b8f | ||
|
|
e66b861c9e | ||
|
|
e0db31e9db | ||
|
|
a7be15d72f | ||
|
|
f7b46d5404 | ||
|
|
488f1717a1 | ||
|
|
2b0ef54595 | ||
|
|
896afe7118 | ||
|
|
ef53134499 | ||
|
|
c31519fdb2 | ||
|
|
162f948729 | ||
|
|
ae4c4e77bf | ||
|
|
695beecf14 | ||
|
|
cb015dec7b | ||
|
|
9bc8331667 | ||
|
|
520c7feeab | ||
|
|
1e3d722bc2 | ||
|
|
c9f8dfc6c5 | ||
|
|
d156de39f1 | ||
|
|
2b099a89e4 | ||
|
|
6e6ec969eb | ||
|
|
e194af8d25 | ||
|
|
ace5198475 | ||
|
|
52d36c33cf | ||
|
|
251f7db3ca | ||
|
|
c83e8b7cb5 | ||
|
|
64e09f74a1 | ||
|
|
63b568989a | ||
|
|
975b42caa3 | ||
|
|
75d02df60d | ||
|
|
082b6077e9 | ||
|
|
e8ab76f55b | ||
|
|
495f15f13c | ||
|
|
68f6423d39 | ||
|
|
67d345bc08 | ||
|
|
a159db6863 | ||
|
|
dea26fadfe | ||
|
|
21edcbdc27 | ||
|
|
e3c91df081 | ||
|
|
c608f1e21e | ||
|
|
fef267a0dc | ||
|
|
5ce2071279 | ||
|
|
ad0549414b | ||
|
|
c6cc9ae29d | ||
|
|
ae94ab17f4 | ||
|
|
eb909068c5 | ||
|
|
90a7fb603d | ||
|
|
7cfd99d17f | ||
|
|
972736f0ab | ||
|
|
934974a547 | ||
|
|
17801871b1 | ||
|
|
7564f7e526 | ||
|
|
fa00157d12 | ||
|
|
a5511e2e30 | ||
|
|
0347ce21fd | ||
|
|
7e2e7946c5 | ||
|
|
0c85febe76 | ||
|
|
c1f8f641e6 | ||
|
|
af16830a38 | ||
|
|
a8d25266f9 | ||
|
|
b78b9dccc8 | ||
|
|
e8fd11d6ce | ||
|
|
1e208e39b0 | ||
|
|
5c3e37412e | ||
|
|
c731f7dd29 | ||
|
|
ea805a8fb7 | ||
|
|
c0289ad844 | ||
|
|
e600be4f56 | ||
|
|
d7e7ef11f9 | ||
|
|
d684ff5715 | ||
|
|
6edb25f5c2 | ||
|
|
e6e5c5daf0 | ||
|
|
61f92b7460 | ||
|
|
2b74982a1d | ||
|
|
46080f5168 | ||
|
|
1dcc2de776 | ||
|
|
875408215b | ||
|
|
038acd3f5e | ||
|
|
f404e0f5b3 | ||
|
|
92b0cbdc19 | ||
|
|
e14c9e2090 | ||
|
|
83eb7a0a9d | ||
|
|
6c1bb7983b | ||
|
|
34e10a145c | ||
|
|
3787dad212 | ||
|
|
4048859912 | ||
|
|
cddb062db5 | ||
|
|
13ba68acc6 | ||
|
|
e22da45474 | ||
|
|
6357812743 | ||
|
|
6e68c3b230 | ||
|
|
0f117d480e | ||
|
|
8d8e6dcffc | ||
|
|
e3ced7c15e | ||
|
|
182f4c603b | ||
|
|
1f6b9c332b | ||
|
|
bfde33c945 | ||
|
|
bd6ed3ada4 | ||
|
|
aa6e276cf9 | ||
|
|
3694499a6a | ||
|
|
06b71d713c | ||
|
|
7141060a2d | ||
|
|
59a4dffc56 | ||
|
|
708320318c | ||
|
|
40746c3fcb | ||
|
|
a0f735d4f2 | ||
|
|
335d1fbbbc | ||
|
|
90025d0ac4 | ||
|
|
ce663f6af5 | ||
|
|
3676015184 | ||
|
|
3aff67605e | ||
|
|
7801688c6e | ||
|
|
17f3b217de | ||
|
|
d02af07d35 | ||
|
|
c46e50864b | ||
|
|
6c361c190b | ||
|
|
12e455cbf5 | ||
|
|
a9f3744f1b | ||
|
|
53e1b8c0d5 | ||
|
|
2ba363684d | ||
|
|
9cc087c788 | ||
|
|
4710210cff | ||
|
|
27ee8f7360 | ||
|
|
1cd7ac55a8 | ||
|
|
b81588307f | ||
|
|
31025216f9 | ||
|
|
aff1ede46b | ||
|
|
322a528c12 | ||
|
|
17c0ceec04 | ||
|
|
c9476fade8 | ||
|
|
7b5a2946e5 | ||
|
|
9c57d3aa8b | ||
|
|
c1b2e06eda | ||
|
|
3094acc7fb | ||
|
|
24a875ed46 | ||
|
|
5623ea3ac6 | ||
|
|
655155bbab | ||
|
|
28e8840456 | ||
|
|
8c73fd6e59 | ||
|
|
eb58e7cb82 | ||
|
|
8db3dfa8c6 | ||
|
|
efd69b2cd5 | ||
|
|
38c32f0e10 | ||
|
|
62b4efb881 | ||
|
|
b5c200f6c4 | ||
|
|
18e3090379 | ||
|
|
1e1be6bc3f | ||
|
|
f0456bb802 | ||
|
|
61da7f63b2 | ||
|
|
0b5d21f32a | ||
|
|
74db82d759 | ||
|
|
5851cc70a7 | ||
|
|
faeda0e70c | ||
|
|
73c5f0ec90 | ||
|
|
66f6e71e7e | ||
|
|
cc4b2eef13 | ||
|
|
8effc5f929 | ||
|
|
5f93c5e789 | ||
|
|
980172a55a | ||
|
|
760e878dd8 | ||
|
|
4dbc7abd0f | ||
|
|
867faf1c30 | ||
|
|
43d19790ae | ||
|
|
0bc86e72b3 | ||
|
|
5ca84acb6d | ||
|
|
c4af66e312 | ||
|
|
c37792dbc4 | ||
|
|
50852136ef | ||
|
|
20082f52a2 | ||
|
|
5ec3eb76eb | ||
|
|
dfbc94c05b | ||
|
|
81ce7d720d | ||
|
|
1db0f2bd55 | ||
|
|
9292eb664a | ||
|
|
8f91eeb195 | ||
|
|
10e12ec1b9 | ||
|
|
61b2373dd1 | ||
|
|
7f881cce85 | ||
|
|
bea9a3304e | ||
|
|
95d6c9c678 | ||
|
|
a2a1a517da | ||
|
|
27f83b511f | ||
|
|
b1b87731b1 | ||
|
|
b4138f29c8 | ||
|
|
dd3a53fb5f | ||
|
|
d23bcc435a | ||
|
|
45eb1b4f0a | ||
|
|
d41f71bc34 | ||
|
|
f5fe9a4b1c | ||
|
|
0e699b87af | ||
|
|
3f5efef6e5 | ||
|
|
d4f8704a4c | ||
|
|
526cb1ea20 | ||
|
|
f5b47fbd86 | ||
|
|
3cee04fb8c | ||
|
|
ac602ed5a9 | ||
|
|
ad510b8b5f | ||
|
|
3436af3931 | ||
|
|
01675f50bf | ||
|
|
17742df591 | ||
|
|
5b1ff6675f | ||
|
|
7bcac064c0 | ||
|
|
867145cd09 | ||
|
|
959a03a6b0 | ||
|
|
b4ae5a36a8 | ||
|
|
7f8e0ba25f | ||
|
|
c75b70463b | ||
|
|
f9788afbfb | ||
|
|
7b0a5644a3 | ||
|
|
34b5203760 | ||
|
|
a2fd70417c | ||
|
|
c3d0980763 | ||
|
|
4ee5271de7 | ||
|
|
f6ef466876 | ||
|
|
00b646158c | ||
|
|
c8a43bad67 | ||
|
|
a29ac44d64 | ||
|
|
e2aa78c11b | ||
|
|
58a6f21705 | ||
|
|
8583e89550 | ||
|
|
e8ab754646 | ||
|
|
5c1ee52815 | ||
|
|
02671a7e10 | ||
|
|
2ba5e2053a | ||
|
|
7714490530 | ||
|
|
4a17671f45 | ||
|
|
a901f21bcd | ||
|
|
e690003621 | ||
|
|
fb49d706d0 | ||
|
|
cac6e0d715 | ||
|
|
f37c5b70ba | ||
|
|
270ccbb0da | ||
|
|
7a34578b4d | ||
|
|
12d8a8b1a3 | ||
|
|
7d3eefa97a | ||
|
|
608fc170d9 | ||
|
|
456d0a050f | ||
|
|
399dd7df95 | ||
|
|
7cc36eee0f | ||
|
|
5024cd52af | ||
|
|
c29c13dfd7 | ||
|
|
947462e134 | ||
|
|
3778bcda24 | ||
|
|
1b071b1f4a | ||
|
|
8edcef6d32 | ||
|
|
662436acd2 | ||
|
|
e16fb45d84 | ||
|
|
1c75bfdddd | ||
|
|
64504e6777 | ||
|
|
af76d5f0e0 | ||
|
|
5683f9e10e | ||
|
|
15fb81da92 | ||
|
|
e52ec14588 | ||
|
|
b13658b319 | ||
|
|
a44978a068 | ||
|
|
bee2541bd8 | ||
|
|
7c8bf95f8f | ||
|
|
7df77b1b28 | ||
|
|
b995e04daa | ||
|
|
0f3dc821f2 | ||
|
|
5ff405b0b0 | ||
|
|
86ae9d25f0 | ||
|
|
3321e4cafd | ||
|
|
639b6bc4f6 | ||
|
|
af1ba1e191 | ||
|
|
5c7899ae98 | ||
|
|
d4b431a335 | ||
|
|
6891054b84 | ||
|
|
e10279b7b4 | ||
|
|
a0c79bd727 | ||
|
|
4b8f382cfd | ||
|
|
eeda93a359 | ||
|
|
7b79ca3e8f | ||
|
|
3030bf9778 | ||
|
|
87f750da35 | ||
|
|
daa9c0c026 | ||
|
|
5ef2654eb4 | ||
|
|
26120ff675 | ||
|
|
e453dab4a3 | ||
|
|
482d063638 | ||
|
|
2f3b0cd422 | ||
|
|
e3227a741c | ||
|
|
4eb8295955 | ||
|
|
bdb25bbcbc | ||
|
|
43696eff5c | ||
|
|
c6b93f8fe5 | ||
|
|
d3d62e90d3 | ||
|
|
20815771ab | ||
|
|
b6754601ef | ||
|
|
0f352a4b5c | ||
|
|
7d6b11cb10 | ||
|
|
3a158faa30 | ||
|
|
fff7ec1dab | ||
|
|
50fc5f91ca | ||
|
|
ec7c11513e | ||
|
|
cfb06ceb58 | ||
|
|
e8a59f4c20 | ||
|
|
638d98735f | ||
|
|
c9e49ed7b4 | ||
|
|
acbfe91f13 | ||
|
|
7edafbb772 | ||
|
|
a657e3d24a | ||
|
|
2cd8782a88 | ||
|
|
fe8ff1b929 | ||
|
|
127cf5d619 | ||
|
|
5e99df1759 | ||
|
|
94e586c049 | ||
|
|
dc65753a64 | ||
|
|
43ba02afc6 | ||
|
|
9537f17dd4 | ||
|
|
2791d543ea | ||
|
|
9dbe5fdb85 | ||
|
|
6ca375a397 | ||
|
|
81bb128cf7 | ||
|
|
a8bf5092e8 | ||
|
|
f88729f0e8 | ||
|
|
3447e4bb97 | ||
|
|
884395415f | ||
|
|
0007002c80 | ||
|
|
0a595190a3 | ||
|
|
32300f6d5f | ||
|
|
d9e951447f | ||
|
|
6fc21e30e5 | ||
|
|
6106822d10 | ||
|
|
4a322abd4d | ||
|
|
52309cc292 | ||
|
|
b5c41ca0fc | ||
|
|
a82a31341b | ||
|
|
0980e7e82d | ||
|
|
41efe99770 | ||
|
|
792dd556a1 | ||
|
|
b731a65c75 | ||
|
|
e28973c50a | ||
|
|
633620a5e9 | ||
|
|
41a47df93f | ||
|
|
3fb1dd02f1 | ||
|
|
cf34b84cf1 | ||
|
|
f4f821e88e | ||
|
|
c0cef7250d | ||
|
|
2976a50c58 | ||
|
|
69006b8fe8 | ||
|
|
4eb55acdbc | ||
|
|
1352f135d0 | ||
|
|
0d251cbfdd | ||
|
|
4733aad7ff | ||
|
|
48516e6e1e | ||
|
|
45909af7e0 | ||
|
|
88755fcded | ||
|
|
0d6dffdc7e | ||
|
|
9aa468adda | ||
|
|
52386d8153 | ||
|
|
b7e0466d7c | ||
|
|
f91de3c10e | ||
|
|
4329c15a9b | ||
|
|
963d2a8368 | ||
|
|
d9eddfb1ee | ||
|
|
f59f534c64 | ||
|
|
5a4eb2cbf2 | ||
|
|
c471ccb2db | ||
|
|
656be523bc | ||
|
|
9cd7749867 | ||
|
|
1845e5d7ca | ||
|
|
9639a3805d | ||
|
|
bc88fbf948 | ||
|
|
94c1a6f2a6 | ||
|
|
280e8b3208 | ||
|
|
607c895065 | ||
|
|
a98fcee4f9 | ||
|
|
1ba5c5d9c6 | ||
|
|
3427c7eb54 | ||
|
|
cf5d691950 | ||
|
|
4e0b095f2b | ||
|
|
0837f3f9f3 | ||
|
|
bad5d57d71 | ||
|
|
620c7e8312 | ||
|
|
af0b1e806f | ||
|
|
cf522d1df2 | ||
|
|
318c973461 | ||
|
|
34e78a7400 | ||
|
|
9be98cd8f7 | ||
|
|
e267b84510 | ||
|
|
c7ef69f4eb | ||
|
|
8c22cfce37 | ||
|
|
e1cb0dbf28 | ||
|
|
e2efd7c6ec | ||
|
|
56e697acf5 | ||
|
|
13d6297b9f | ||
|
|
65c069dd9f | ||
|
|
b0536dba0b | ||
|
|
0c051b1b7a | ||
|
|
16eb793081 | ||
|
|
1cc132afe2 | ||
|
|
d985405fe7 | ||
|
|
e88fabe1d6 | ||
|
|
7f1f1ec1ad | ||
|
|
8094f84efe | ||
|
|
ef78f2f03a | ||
|
|
a1fa688da0 | ||
|
|
263bf918b1 | ||
|
|
58a2af8d80 | ||
|
|
594b541f34 | ||
|
|
cc3e4e9aa7 | ||
|
|
d74a0f0526 | ||
|
|
d112d90e8e | ||
|
|
2383a83c2d | ||
|
|
c2245362da | ||
|
|
c96f912043 | ||
|
|
f175f48418 | ||
|
|
6cc8017943 | ||
|
|
e0bd45efab | ||
|
|
f80864b5bc | ||
|
|
9a09e6b815 | ||
|
|
91f90920c2 | ||
|
|
8549201502 | ||
|
|
0665a23b0f | ||
|
|
b1c53ec656 | ||
|
|
790f35a5c8 | ||
|
|
3246c60472 | ||
|
|
57fc9df5f3 | ||
|
|
144be37a9a | ||
|
|
9b8f90dc9f | ||
|
|
d07491ceb2 | ||
|
|
14c140d242 | ||
|
|
263d34ae82 | ||
|
|
8f17b11610 | ||
|
|
177962fa05 | ||
|
|
d51ac94662 | ||
|
|
40dfe4b3a9 | ||
|
|
8b098859f4 | ||
|
|
72a2c37769 | ||
|
|
bc25007fef | ||
|
|
1e119013c8 | ||
|
|
189873f9d4 | ||
|
|
5b25ed99ac | ||
|
|
edd840ac35 | ||
|
|
58425993da | ||
|
|
e3ae1c6c2f | ||
|
|
40c581e5a8 | ||
|
|
631081a2b2 | ||
|
|
8e3ff8235f | ||
|
|
ada98abfee | ||
|
|
49266fc4b8 | ||
|
|
f5ff6ceead | ||
|
|
81ee6f8265 | ||
|
|
ab4e2bd5a9 | ||
|
|
01b6a0eb53 | ||
|
|
b55822ad30 | ||
|
|
7552c912a2 | ||
|
|
1dbdb880e6 | ||
|
|
ccf1c894b4 | ||
|
|
d3fb2e4516 | ||
|
|
932b65da27 | ||
|
|
2bfce64e6a | ||
|
|
43fd9b37df | ||
|
|
ceeb98dda9 | ||
|
|
a5c1547251 | ||
|
|
306885e174 | ||
|
|
90a107393a | ||
|
|
c72d4665a1 | ||
|
|
a76ed88496 | ||
|
|
24ab1b5be5 | ||
|
|
842b0c2270 | ||
|
|
a127e1db07 | ||
|
|
2267a420a4 | ||
|
|
82ea56c8fd | ||
|
|
ecaf6b763c | ||
|
|
0987af910e | ||
|
|
2e1124af1a | ||
|
|
2fe7812e20 | ||
|
|
8bd9ed1543 | ||
|
|
72c17e29c0 | ||
|
|
483415cd65 | ||
|
|
98669a3d62 | ||
|
|
9c2115c917 | ||
|
|
f6ecd8e514 | ||
|
|
6675120324 | ||
|
|
ab6589d573 | ||
|
|
9e94778fd7 | ||
|
|
2968347062 | ||
|
|
9450b76414 | ||
|
|
d2608cbf13 | ||
|
|
f580fbb91d | ||
|
|
9b0fbbdc14 | ||
|
|
aa213a3640 | ||
|
|
baeeaa777d | ||
|
|
20af4bae7c | ||
|
|
5baab91bb5 | ||
|
|
4c49229b77 | ||
|
|
93a7c46977 | ||
|
|
bc2bd7fe1e | ||
|
|
a70958da41 | ||
|
|
9f1544978d | ||
|
|
f838ba2a9b | ||
|
|
53e76a89ac | ||
|
|
de8db9293c | ||
|
|
fded8e5117 | ||
|
|
be95d699d2 | ||
|
|
c43ceb2045 | ||
|
|
9ab4953472 | ||
|
|
bbe3bc4423 | ||
|
|
acb1b50924 | ||
|
|
a140748b5a | ||
|
|
573b6b8e15 | ||
|
|
23e989d31f | ||
|
|
990f8a996b | ||
|
|
f4077a51c1 | ||
|
|
403f59ef45 | ||
|
|
001d7443da | ||
|
|
4eb66aa9ce | ||
|
|
ce90ee4ac2 | ||
|
|
06d230279c | ||
|
|
47748bc6f7 | ||
|
|
a620aa8352 | ||
|
|
09fb4ea584 | ||
|
|
3997b6038d | ||
|
|
7f4c70827a | ||
|
|
f69e8458f4 | ||
|
|
02f0f22621 | ||
|
|
1d43dc229b | ||
|
|
c7d1a767f7 | ||
|
|
11d8f7d522 | ||
|
|
1332ab397f | ||
|
|
78bafee39d | ||
|
|
66866ff260 | ||
|
|
1dcd7e747e | ||
|
|
42c0d7c7c3 | ||
|
|
488210915a | ||
|
|
f1d406b1e6 | ||
|
|
89ed2e0127 | ||
|
|
53b1f8d3a4 | ||
|
|
cc5991d269 | ||
|
|
b8184e4fdd | ||
|
|
37dee02e1c | ||
|
|
2765a065a7 | ||
|
|
bb7b2cdfd5 | ||
|
|
94287d66a8 | ||
|
|
1cfa0a3c0e | ||
|
|
1678518cd4 | ||
|
|
838bd5824e | ||
|
|
a650072fe0 | ||
|
|
6115fb08c0 | ||
|
|
91b2092d55 | ||
|
|
cba8745164 | ||
|
|
c3d00a8825 | ||
|
|
261522446e | ||
|
|
a86104d0fe | ||
|
|
4ac2afacfa | ||
|
|
07c655cf41 | ||
|
|
a9ba0981c7 | ||
|
|
7a074f21bd | ||
|
|
fef8a4c978 | ||
|
|
0c8ecf2b1f | ||
|
|
5fc8250ee4 | ||
|
|
e42403fecc | ||
|
|
12a84cc30b | ||
|
|
0ae5b75f33 | ||
|
|
4810d87044 | ||
|
|
0b71f7186c | ||
|
|
eac3c4b72c | ||
|
|
d03f58417b | ||
|
|
7123985325 | ||
|
|
7eb5138276 | ||
|
|
d50445108e | ||
|
|
65c5a0b308 | ||
|
|
bfe1eaadcf | ||
|
|
ce3603f84f | ||
|
|
21468d72d3 | ||
|
|
4f4cb3698e | ||
|
|
21c5282eb1 | ||
|
|
db46ad6502 | ||
|
|
616006caf8 | ||
|
|
cbc0b81d2e | ||
|
|
c1c6ed6ed7 | ||
|
|
1f75636e56 | ||
|
|
f3847a3a9a | ||
|
|
0203a48f3e | ||
|
|
5420bb9f6d | ||
|
|
4ac591b076 | ||
|
|
18f8686cdb | ||
|
|
2f40e23dcc | ||
|
|
8a83e050d0 | ||
|
|
a972b8768d | ||
|
|
a4906c477e | ||
|
|
7cafd1f17e | ||
|
|
3d2c6a22a3 | ||
|
|
052404ffbd | ||
|
|
96b2210c0f | ||
|
|
756bd63e1d | ||
|
|
9d2b7c1fc0 | ||
|
|
0a32d38ad9 | ||
|
|
3069a422e9 | ||
|
|
1b4c1980c2 | ||
|
|
aba09b8107 | ||
|
|
f51ef1a791 | ||
|
|
016232a8e9 | ||
|
|
dbb0a6261f | ||
|
|
b07ee26e08 | ||
|
|
ae803474f9 | ||
|
|
0a068db285 | ||
|
|
32222ae6ef | ||
|
|
82a2144296 | ||
|
|
22ef860312 | ||
|
|
a6587b209f | ||
|
|
4dc1d7538e | ||
|
|
609c1eee55 | ||
|
|
ab6e32f6bb | ||
|
|
85af68d807 | ||
|
|
eb4ac73b78 | ||
|
|
d20e3f79be | ||
|
|
40a0689183 | ||
|
|
14d16d573c | ||
|
|
556533f160 |
@@ -3,3 +3,4 @@ omit =
|
||||
scripts/*
|
||||
freqtrade/tests/*
|
||||
freqtrade/vendor/*
|
||||
freqtrade/__main__.py
|
||||
|
||||
4
.github/ISSUE_TEMPLATE.md
vendored
4
.github/ISSUE_TEMPLATE.md
vendored
@@ -1,15 +1,17 @@
|
||||
## Step 1: Have you search for this issue before posting it?
|
||||
|
||||
If you have discovered a bug in the bot, please [search our issue tracker](https://github.com/gcarq/freqtrade/issues?q=is%3Aissue).
|
||||
If you have discovered a bug in the bot, please [search our issue tracker](https://github.com/freqtrade/freqtrade/issues?q=is%3Aissue).
|
||||
If it hasn't been reported, please create a new issue.
|
||||
|
||||
## Step 2: Describe your environment
|
||||
|
||||
* Python Version: _____ (`python -V`)
|
||||
* CCXT version: _____ (`pip freeze | grep ccxt`)
|
||||
* Branch: Master | Develop
|
||||
* Last Commit ID: _____ (`git log --format="%H" -n 1`)
|
||||
|
||||
## Step 3: Describe the problem:
|
||||
|
||||
*Explain the problem you have encountered*
|
||||
|
||||
### Steps to reproduce:
|
||||
|
||||
2
.github/PULL_REQUEST_TEMPLATE.md
vendored
2
.github/PULL_REQUEST_TEMPLATE.md
vendored
@@ -1,5 +1,5 @@
|
||||
Thank you for sending your pull request. But first, have you included
|
||||
unit tests, and is your code PEP8 conformant? [More details](https://github.com/gcarq/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||
unit tests, and is your code PEP8 conformant? [More details](https://github.com/freqtrade/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||
|
||||
## Summary
|
||||
Explain in one sentence the goal of this PR
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,13 +1,14 @@
|
||||
# Freqtrade rules
|
||||
freqtrade/tests/testdata/*.json
|
||||
hyperopt_conf.py
|
||||
config.json
|
||||
config*.json
|
||||
*.sqlite
|
||||
.hyperopt
|
||||
logfile.txt
|
||||
hyperopt_trials.pickle
|
||||
user_data/
|
||||
freqtrade-plot.html
|
||||
freqtrade-profit-plot.html
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
@@ -90,3 +91,4 @@ target/
|
||||
.vscode
|
||||
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
|
||||
33
.pyup.yml
Normal file
33
.pyup.yml
Normal file
@@ -0,0 +1,33 @@
|
||||
# autogenerated pyup.io config file
|
||||
# see https://pyup.io/docs/configuration/ for all available options
|
||||
|
||||
# configure updates globally
|
||||
# default: all
|
||||
# allowed: all, insecure, False
|
||||
update: all
|
||||
|
||||
# configure dependency pinning globally
|
||||
# default: True
|
||||
# allowed: True, False
|
||||
pin: True
|
||||
|
||||
schedule: "every day"
|
||||
|
||||
|
||||
search: False
|
||||
# Specify requirement files by hand, default is empty
|
||||
# default: empty
|
||||
# allowed: list
|
||||
requirements:
|
||||
- requirements.txt
|
||||
- requirements-dev.txt
|
||||
- requirements-plot.txt
|
||||
|
||||
|
||||
# configure the branch prefix the bot is using
|
||||
# default: pyup-
|
||||
branch_prefix: pyup/
|
||||
|
||||
# allow to close stale PRs
|
||||
# default: True
|
||||
close_prs: True
|
||||
8
.readthedocs.yml
Normal file
8
.readthedocs.yml
Normal file
@@ -0,0 +1,8 @@
|
||||
# .readthedocs.yml
|
||||
|
||||
build:
|
||||
image: latest
|
||||
|
||||
python:
|
||||
version: 3.6
|
||||
setup_py_install: false
|
||||
40
.travis.yml
40
.travis.yml
@@ -1,9 +1,15 @@
|
||||
sudo: true
|
||||
os:
|
||||
- linux
|
||||
dist: xenial
|
||||
language: python
|
||||
python:
|
||||
- 3.6
|
||||
services:
|
||||
- docker
|
||||
env:
|
||||
global:
|
||||
- IMAGE_NAME=freqtradeorg/freqtrade
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
@@ -11,27 +17,43 @@ addons:
|
||||
- libdw-dev
|
||||
- binutils-dev
|
||||
install:
|
||||
- ./install_ta-lib.sh
|
||||
- cd build_helpers && ./install_ta-lib.sh; cd ..
|
||||
- export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
|
||||
- pip install --upgrade flake8 coveralls pytest-random-order
|
||||
- pip install -r requirements.txt
|
||||
- pip install --upgrade pytest-random-order
|
||||
- pip install -r requirements-dev.txt
|
||||
- pip install -e .
|
||||
jobs:
|
||||
include:
|
||||
- script: pytest --cov=freqtrade --cov-config=.coveragerc freqtrade/tests/
|
||||
- stage: tests
|
||||
script:
|
||||
- pytest --cov=freqtrade --cov-config=.coveragerc freqtrade/tests/
|
||||
name: pytest
|
||||
- script:
|
||||
- cp config.json.example config.json
|
||||
- python freqtrade/main.py backtesting
|
||||
- python freqtrade/main.py --datadir freqtrade/tests/testdata backtesting
|
||||
name: backtest
|
||||
- script:
|
||||
- cp config.json.example config.json
|
||||
- python freqtrade/main.py hyperopt -e 5
|
||||
- python freqtrade/main.py --datadir freqtrade/tests/testdata hyperopt -e 5
|
||||
name: hyperopt
|
||||
- script: flake8 freqtrade
|
||||
name: flake8
|
||||
- script: mypy freqtrade
|
||||
name: mypy
|
||||
|
||||
- stage: docker
|
||||
if: branch in (master, develop, feat/improve_travis) AND (type in (push, cron))
|
||||
script:
|
||||
- build_helpers/publish_docker.sh
|
||||
name: "Build and test and push docker image"
|
||||
|
||||
after_success:
|
||||
- coveralls
|
||||
- coveralls
|
||||
|
||||
notifications:
|
||||
slack:
|
||||
secure: bKLXmOrx8e2aPZl7W8DA5BdPAXWGpI5UzST33oc1G/thegXcDVmHBTJrBs4sZak6bgAclQQrdZIsRd2eFYzHLalJEaw6pk7hoAw8SvLnZO0ZurWboz7qg2+aZZXfK4eKl/VUe4sM9M4e/qxjkK+yWG7Marg69c4v1ypF7ezUi1fPYILYw8u0paaiX0N5UX8XNlXy+PBlga2MxDjUY70MuajSZhPsY2pDUvYnMY1D/7XN3cFW0g+3O8zXjF0IF4q1Z/1ASQe+eYjKwPQacE+O8KDD+ZJYoTOFBAPllrtpO1jnOPFjNGf3JIbVMZw4bFjIL0mSQaiSUaUErbU3sFZ5Or79rF93XZ81V7uEZ55vD8KMfR2CB1cQJcZcj0v50BxLo0InkFqa0Y8Nra3sbpV4fV5Oe8pDmomPJrNFJnX6ULQhQ1gTCe0M5beKgVms5SITEpt4/Y0CmLUr6iHDT0CUiyMIRWAXdIgbGh1jfaWOMksybeRevlgDsIsNBjXmYI1Sw2ZZR2Eo2u4R6zyfyjOMLwYJ3vgq9IrACv2w5nmf0+oguMWHf6iWi2hiOqhlAN1W74+3HsYQcqnuM3LGOmuCnPprV1oGBqkPXjIFGpy21gNx4vHfO1noLUyJnMnlu2L7SSuN1CdLsnjJ1hVjpJjPfqB4nn8g12x87TqM1bOm+3Q=
|
||||
cache:
|
||||
pip: True
|
||||
directories:
|
||||
- $HOME/.cache/pip
|
||||
- ta-lib
|
||||
- /usr/local/lib
|
||||
|
||||
106
CONTRIBUTING.md
106
CONTRIBUTING.md
@@ -1,45 +1,119 @@
|
||||
# Contribute to freqtrade
|
||||
# Contributing
|
||||
|
||||
Feel like our bot is missing a feature? We welcome your pull requests! Few pointers for contributions:
|
||||
## Contribute to freqtrade
|
||||
|
||||
Feel like our bot is missing a feature? We welcome your pull requests!
|
||||
|
||||
Issues labeled [good first issue](https://github.com/freqtrade/freqtrade/labels/good%20first%20issue) can be good first contributions, and will help get you familiar with the codebase.
|
||||
|
||||
Few pointers for contributions:
|
||||
|
||||
- Create your PR against the `develop` branch, not `master`.
|
||||
- New features need to contain unit tests and must be PEP8
|
||||
conformant (max-line-length = 100).
|
||||
- New features need to contain unit tests and must be PEP8 conformant (max-line-length = 100).
|
||||
|
||||
If you are unsure, discuss the feature on our [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE)
|
||||
or in a [issue](https://github.com/gcarq/freqtrade/issues) before a PR.
|
||||
or in a [issue](https://github.com/freqtrade/freqtrade/issues) before a PR.
|
||||
|
||||
## Getting started
|
||||
|
||||
**Before sending the PR:**
|
||||
Best start by reading the [documentation](https://www.freqtrade.io/) to get a feel for what is possible with the bot, or head straight to the [Developer-documentation](https://www.freqtrade.io/en/latest/developer/) (WIP) which should help you getting started.
|
||||
|
||||
## 1. Run unit tests
|
||||
## Before sending the PR:
|
||||
|
||||
### 1. Run unit tests
|
||||
|
||||
All unit tests must pass. If a unit test is broken, change your code to
|
||||
make it pass. It means you have introduced a regression.
|
||||
|
||||
**Test the whole project**
|
||||
#### Test the whole project
|
||||
|
||||
```bash
|
||||
pytest freqtrade
|
||||
```
|
||||
|
||||
**Test only one file**
|
||||
#### Test only one file
|
||||
|
||||
```bash
|
||||
pytest freqtrade/tests/test_<file_name>.py
|
||||
```
|
||||
|
||||
**Test only one method from one file**
|
||||
#### Test only one method from one file
|
||||
|
||||
```bash
|
||||
pytest freqtrade/tests/test_<file_name>.py::test_<method_name>
|
||||
```
|
||||
|
||||
## 2. Test if your code is PEP8 compliant
|
||||
**Install packages** (If not already installed)
|
||||
```bash
|
||||
pip3.6 install flake8 coveralls
|
||||
```
|
||||
**Run Flake8**
|
||||
### 2. Test if your code is PEP8 compliant
|
||||
|
||||
#### Run Flake8
|
||||
|
||||
```bash
|
||||
flake8 freqtrade
|
||||
```
|
||||
|
||||
We receive a lot of code that fails the `flake8` checks.
|
||||
To help with that, we encourage you to install the git pre-commit
|
||||
hook that will warn you when you try to commit code that fails these checks.
|
||||
Guide for installing them is [here](http://flake8.pycqa.org/en/latest/user/using-hooks.html).
|
||||
|
||||
### 3. Test if all type-hints are correct
|
||||
|
||||
#### Run mypy
|
||||
|
||||
``` bash
|
||||
mypy freqtrade
|
||||
```
|
||||
|
||||
## (Core)-Committer Guide
|
||||
|
||||
### Process: Pull Requests
|
||||
|
||||
How to prioritize pull requests, from most to least important:
|
||||
|
||||
1. Fixes for broken tests. Broken means broken on any supported platform or Python version.
|
||||
1. Extra tests to cover corner cases.
|
||||
1. Minor edits to docs.
|
||||
1. Bug fixes.
|
||||
1. Major edits to docs.
|
||||
1. Features.
|
||||
|
||||
Ensure that each pull request meets all requirements in the Contributing document.
|
||||
|
||||
### Process: Issues
|
||||
|
||||
If an issue is a bug that needs an urgent fix, mark it for the next patch release.
|
||||
Then either fix it or mark as please-help.
|
||||
|
||||
For other issues: encourage friendly discussion, moderate debate, offer your thoughts.
|
||||
|
||||
### Process: Your own code changes
|
||||
|
||||
All code changes, regardless of who does them, need to be reviewed and merged by someone else.
|
||||
This rule applies to all the core committers.
|
||||
|
||||
Exceptions:
|
||||
|
||||
- Minor corrections and fixes to pull requests submitted by others.
|
||||
- While making a formal release, the release manager can make necessary, appropriate changes.
|
||||
- Small documentation changes that reinforce existing subject matter. Most commonly being, but not limited to spelling and grammar corrections.
|
||||
|
||||
### Responsibilities
|
||||
|
||||
- Ensure cross-platform compatibility for every change that's accepted. Windows, Mac & Linux.
|
||||
- Ensure no malicious code is introduced into the core code.
|
||||
- Create issues for any major changes and enhancements that you wish to make. Discuss things transparently and get community feedback.
|
||||
- Keep feature versions as small as possible, preferably one new feature per version.
|
||||
- Be welcoming to newcomers and encourage diverse new contributors from all backgrounds. See the Python Community Code of Conduct (https://www.python.org/psf/codeofconduct/).
|
||||
|
||||
### Becoming a Committer
|
||||
|
||||
Contributors may be given commit privileges. Preference will be given to those with:
|
||||
|
||||
1. Past contributions to FreqTrade and other related open-source projects. Contributions to FreqTrade include both code (both accepted and pending) and friendly participation in the issue tracker and Pull request reviews. Quantity and quality are considered.
|
||||
1. A coding style that the other core committers find simple, minimal, and clean.
|
||||
1. Access to resources for cross-platform development and testing.
|
||||
1. Time to devote to the project regularly.
|
||||
|
||||
Beeing 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.
|
||||
|
||||
25
Dockerfile
25
Dockerfile
@@ -1,23 +1,26 @@
|
||||
FROM python:3.6.5-slim-stretch
|
||||
FROM python:3.7.2-slim-stretch
|
||||
|
||||
# Install TA-lib
|
||||
RUN apt-get update && apt-get -y install curl build-essential && apt-get clean
|
||||
RUN curl -L http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz | \
|
||||
tar xzvf - && \
|
||||
cd ta-lib && \
|
||||
./configure && make && make install && \
|
||||
cd .. && rm -rf ta-lib
|
||||
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||
RUN apt-get update \
|
||||
&& apt-get -y install curl build-essential \
|
||||
&& apt-get clean \
|
||||
&& pip install --upgrade pip
|
||||
|
||||
# Prepare environment
|
||||
RUN mkdir /freqtrade
|
||||
WORKDIR /freqtrade
|
||||
|
||||
# Install TA-lib
|
||||
COPY build_helpers/* /tmp/
|
||||
RUN cd /tmp && /tmp/install_ta-lib.sh && rm -r /tmp/*ta-lib*
|
||||
|
||||
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||
|
||||
# Install dependencies
|
||||
COPY requirements.txt /freqtrade/
|
||||
RUN pip install -r requirements.txt
|
||||
RUN pip install numpy --no-cache-dir \
|
||||
&& pip install -r requirements.txt --no-cache-dir
|
||||
|
||||
# Install and execute
|
||||
COPY . /freqtrade/
|
||||
RUN pip install -e .
|
||||
RUN pip install -e . --no-cache-dir
|
||||
ENTRYPOINT ["freqtrade"]
|
||||
|
||||
9
Dockerfile.develop
Normal file
9
Dockerfile.develop
Normal file
@@ -0,0 +1,9 @@
|
||||
FROM freqtradeorg/freqtrade:develop
|
||||
|
||||
# Install dependencies
|
||||
COPY requirements-dev.txt /freqtrade/
|
||||
RUN pip install numpy --no-cache-dir \
|
||||
&& pip install -r requirements-dev.txt --no-cache-dir
|
||||
|
||||
# Empty the ENTRYPOINT to allow all commands
|
||||
ENTRYPOINT []
|
||||
6
Dockerfile.technical
Normal file
6
Dockerfile.technical
Normal file
@@ -0,0 +1,6 @@
|
||||
FROM freqtradeorg/freqtrade:develop
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get -y install git \
|
||||
&& apt-get clean \
|
||||
&& pip install git+https://github.com/berlinguyinca/technical
|
||||
259
README.md
259
README.md
@@ -1,16 +1,16 @@
|
||||
# freqtrade
|
||||
# Freqtrade
|
||||
|
||||
[](https://travis-ci.org/gcarq/freqtrade)
|
||||
[](https://coveralls.io/github/gcarq/freqtrade?branch=develop)
|
||||
[](https://codeclimate.com/github/gcarq/freqtrade/maintainability)
|
||||
[](https://travis-ci.org/freqtrade/freqtrade)
|
||||
[](https://coveralls.io/github/freqtrade/freqtrade?branch=develop)
|
||||
[](https://www.freqtrade.io)
|
||||
[](https://codeclimate.com/github/freqtrade/freqtrade/maintainability)
|
||||
|
||||
Freqtrade is a free and open source crypto trading bot written in Python. It is designed to support all major exchanges and be controlled via Telegram. It contains backtesting, plotting and money management tools as well as strategy optimization by machine learning.
|
||||
|
||||
Simple High frequency trading bot for crypto currencies designed to
|
||||
support multi exchanges and be controlled via Telegram.
|
||||
|
||||

|
||||

|
||||
|
||||
## 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.
|
||||
@@ -22,183 +22,174 @@ expect.
|
||||
We strongly recommend you to have coding and Python knowledge. Do not
|
||||
hesitate to read the source code and understand the mechanism of this bot.
|
||||
|
||||
## Table of Contents
|
||||
- [Features](#features)
|
||||
- [Quick start](#quick-start)
|
||||
- [Documentations](https://github.com/gcarq/freqtrade/blob/develop/docs/index.md)
|
||||
- [Installation](https://github.com/gcarq/freqtrade/blob/develop/docs/installation.md)
|
||||
- [Configuration](https://github.com/gcarq/freqtrade/blob/develop/docs/configuration.md)
|
||||
- [Strategy Optimization](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-optimization.md)
|
||||
- [Backtesting](https://github.com/gcarq/freqtrade/blob/develop/docs/backtesting.md)
|
||||
- [Hyperopt](https://github.com/gcarq/freqtrade/blob/develop/docs/hyperopt.md)
|
||||
- [Support](#support)
|
||||
- [Help](#help--slack)
|
||||
- [Bugs](#bugs--issues)
|
||||
- [Feature Requests](#feature-requests)
|
||||
- [Pull Requests](#pull-requests)
|
||||
- [Basic Usage](#basic-usage)
|
||||
- [Bot commands](#bot-commands)
|
||||
- [Telegram RPC commands](#telegram-rpc-commands)
|
||||
- [Requirements](#requirements)
|
||||
- [Min hardware required](#min-hardware-required)
|
||||
- [Software requirements](#software-requirements)
|
||||
## Exchange marketplaces supported
|
||||
|
||||
## Branches
|
||||
The project is currently setup in two main branches:
|
||||
- `develop` - This branch has often new features, but might also cause
|
||||
breaking changes.
|
||||
- `master` - This branch contains the latest stable release. The bot
|
||||
'should' be stable on this branch, and is generally well tested.
|
||||
- [X] [Bittrex](https://bittrex.com/)
|
||||
- [X] [Binance](https://www.binance.com/) ([*Note for binance users](#a-note-on-binance))
|
||||
- [ ] [113 others to tests](https://github.com/ccxt/ccxt/). _(We cannot guarantee they will work)_
|
||||
|
||||
## Documentation
|
||||
|
||||
We invite you to read the bot documentation to ensure you understand how the bot is working.
|
||||
|
||||
Please find the complete documentation on our [website](https://www.freqtrade.io).
|
||||
|
||||
## Features
|
||||
- [x] **Based on Python 3.6+**: For botting on any operating system -
|
||||
Windows, macOS and Linux
|
||||
- [x] **Persistence**: Persistence is achieved through sqlite
|
||||
|
||||
- [x] **Based on Python 3.6+**: For botting on any operating system - Windows, macOS and Linux.
|
||||
- [x] **Persistence**: Persistence is achieved through sqlite.
|
||||
- [x] **Dry-run**: Run the bot without playing money.
|
||||
- [x] **Backtesting**: Run a simulation of your buy/sell strategy.
|
||||
- [x] **Strategy Optimization**: Optimize your buy/sell strategy
|
||||
parameters with Hyperopts.
|
||||
- [x] **Whitelist crypto-currencies**: Select which crypto-currency you
|
||||
want to trade.
|
||||
- [x] **Blacklist crypto-currencies**: Select which crypto-currency you
|
||||
want to avoid.
|
||||
- [x] **Manageable via Telegram**: Manage the bot with Telegram
|
||||
- [x] **Display profit/loss in fiat**: Display your profit/loss in
|
||||
33 fiat.
|
||||
- [x] **Daily summary of profit/loss**: Provide a daily summary
|
||||
of your profit/loss.
|
||||
- [x] **Performance status report**: Provide a performance status of
|
||||
your current trades.
|
||||
|
||||
### Exchange supported
|
||||
- [x] Bittrex
|
||||
- [ ] Binance
|
||||
- [ ] Others
|
||||
- [x] **Strategy Optimization by machine learning**: Use machine learning to optimize your buy/sell strategy parameters with real exchange data.
|
||||
- [x] **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. [Learn more](https://www.freqtrade.io/en/latest/edge/).
|
||||
- [x] **Whitelist crypto-currencies**: Select which crypto-currency you want to trade or use dynamic whitelists.
|
||||
- [x] **Blacklist crypto-currencies**: Select which crypto-currency you want to avoid.
|
||||
- [x] **Manageable via Telegram**: Manage the bot with Telegram.
|
||||
- [x] **Display profit/loss in fiat**: Display your profit/loss in 33 fiat.
|
||||
- [x] **Daily summary of profit/loss**: Provide a daily summary of your profit/loss.
|
||||
- [x] **Performance status report**: Provide a performance status of your current trades.
|
||||
|
||||
## Quick start
|
||||
This quick start section is a very short explanation on how to test the
|
||||
bot in dry-run. We invite you to read the
|
||||
[bot documentation](https://github.com/gcarq/freqtrade/blob/develop/docs/index.md)
|
||||
to ensure you understand how the bot is working.
|
||||
|
||||
### Easy installation
|
||||
The script below will install all dependencies and help you to configure the bot.
|
||||
Freqtrade provides a Linux/macOS script to install all dependencies and help you to configure the bot.
|
||||
|
||||
```bash
|
||||
git clone git@github.com:freqtrade/freqtrade.git
|
||||
cd freqtrade
|
||||
git checkout develop
|
||||
./setup.sh --install
|
||||
```
|
||||
|
||||
### Manual installation
|
||||
The following steps are made for Linux/MacOS environment
|
||||
For any other type of installation please refer to [Installation doc](https://www.freqtrade.io/en/latest/installation/).
|
||||
|
||||
**1. Clone the repo**
|
||||
```bash
|
||||
git clone git@github.com:gcarq/freqtrade.git
|
||||
git checkout develop
|
||||
cd freqtrade
|
||||
```
|
||||
**2. Create the config file**
|
||||
Switch `"dry_run": true,`
|
||||
```bash
|
||||
cp config.json.example config.json
|
||||
vi config.json
|
||||
```
|
||||
**3. Build your docker image and run it**
|
||||
```bash
|
||||
docker build -t freqtrade .
|
||||
docker run --rm -v /etc/localtime:/etc/localtime:ro -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
||||
```
|
||||
|
||||
|
||||
### 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.
|
||||
- [Click here to join Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE).
|
||||
|
||||
### [Bugs / Issues](https://github.com/gcarq/freqtrade/issues?q=is%3Aissue)
|
||||
If you discover a bug in the bot, please
|
||||
[search our issue tracker](https://github.com/gcarq/freqtrade/issues?q=is%3Aissue)
|
||||
first. If it hasn't been reported, please
|
||||
[create a new issue](https://github.com/gcarq/freqtrade/issues/new) and
|
||||
ensure you follow the template guide so that our team can assist you as
|
||||
quickly as possible.
|
||||
|
||||
### [Feature Requests](https://github.com/gcarq/freqtrade/labels/enhancement)
|
||||
Have you a great idea to improve the bot you want to share? Please,
|
||||
first search if this feature was not [already discussed](https://github.com/gcarq/freqtrade/labels/enhancement).
|
||||
If it hasn't been requested, please
|
||||
[create a new request](https://github.com/gcarq/freqtrade/issues/new)
|
||||
and ensure you follow the template guide so that it does not get lost
|
||||
in the bug reports.
|
||||
|
||||
### [Pull Requests](https://github.com/gcarq/freqtrade/pulls)
|
||||
Feel like our bot is missing a feature? We welcome your pull requests!
|
||||
Please read our
|
||||
[Contributing document](https://github.com/gcarq/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||
to understand the requirements before sending your pull-requests.
|
||||
|
||||
**Important:** Always create your PR against the `develop` branch, not
|
||||
`master`.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Bot commands
|
||||
|
||||
```bash
|
||||
usage: main.py [-h] [-v] [--version] [-c PATH] [--dry-run-db] [--datadir PATH]
|
||||
[--dynamic-whitelist [INT]]
|
||||
{backtesting,hyperopt} ...
|
||||
```
|
||||
usage: main.py [-h] [-v] [--version] [-c PATH] [-d PATH] [-s NAME]
|
||||
[--strategy-path PATH] [--customhyperopt NAME]
|
||||
[--dynamic-whitelist [INT]] [--db-url PATH]
|
||||
{backtesting,edge,hyperopt} ...
|
||||
|
||||
Simple High Frequency Trading Bot for crypto currencies
|
||||
Free, open source crypto trading bot
|
||||
|
||||
positional arguments:
|
||||
{backtesting,hyperopt}
|
||||
{backtesting,edge,hyperopt}
|
||||
backtesting backtesting module
|
||||
edge edge module
|
||||
hyperopt hyperopt module
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-v, --verbose be verbose
|
||||
--version show program's version number and exit
|
||||
-v, --verbose verbose mode (-vv for more, -vvv to get all messages)
|
||||
--version show program\'s version number and exit
|
||||
-c PATH, --config PATH
|
||||
specify configuration file (default: config.json)
|
||||
--dry-run-db Force dry run to use a local DB
|
||||
"tradesv3.dry_run.sqlite" instead of memory DB. Work
|
||||
only if dry_run is enabled.
|
||||
--datadir PATH path to backtest data (default freqdata/tests/testdata
|
||||
-d PATH, --datadir PATH
|
||||
path to backtest data
|
||||
-s NAME, --strategy NAME
|
||||
specify strategy class name (default: DefaultStrategy)
|
||||
--strategy-path PATH specify additional strategy lookup path
|
||||
--customhyperopt NAME
|
||||
specify hyperopt class name (default:
|
||||
DefaultHyperOpts)
|
||||
--dynamic-whitelist [INT]
|
||||
dynamically generate and update whitelist based on 24h
|
||||
BaseVolume (Default 20 currencies)
|
||||
BaseVolume (default: 20) DEPRECATED.
|
||||
--db-url PATH Override trades database URL, this is useful if
|
||||
dry_run is enabled or in custom deployments (default:
|
||||
None)
|
||||
```
|
||||
More details on:
|
||||
- [How to run the bot](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-usage.md#bot-commands)
|
||||
- [How to use Backtesting](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-usage.md#backtesting-commands)
|
||||
- [How to use Hyperopt](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-usage.md#hyperopt-commands)
|
||||
|
||||
### Telegram RPC commands
|
||||
Telegram is not mandatory. However, this is a great way to control your
|
||||
bot. More details on our
|
||||
[documentation](https://github.com/gcarq/freqtrade/blob/develop/docs/index.md)
|
||||
|
||||
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/)
|
||||
|
||||
- `/start`: Starts the trader
|
||||
- `/stop`: Stops the trader
|
||||
- `/status [table]`: Lists all open trades
|
||||
- `/count`: Displays number of open trades
|
||||
- `/profit`: Lists cumulative profit from all finished trades
|
||||
- `/forcesell <trade_id>|all`: Instantly sells the given trade
|
||||
(Ignoring `minimum_roi`).
|
||||
- `/forcesell <trade_id>|all`: Instantly sells the given trade (Ignoring `minimum_roi`).
|
||||
- `/performance`: Show performance of each finished trade grouped by pair
|
||||
- `/balance`: Show account balance per currency
|
||||
- `/daily <n>`: Shows profit or loss per day, over the last n days
|
||||
- `/help`: Show help message
|
||||
- `/version`: Show version
|
||||
|
||||
|
||||
## Development branches
|
||||
|
||||
The project is currently setup in two main branches:
|
||||
|
||||
- `develop` - This branch has often new features, but might also cause breaking changes.
|
||||
- `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.
|
||||
|
||||
|
||||
## 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
|
||||
|
||||
### 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.
|
||||
|
||||
- [Click here to join Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE).
|
||||
|
||||
### [Bugs / Issues](https://github.com/freqtrade/freqtrade/issues?q=is%3Aissue)
|
||||
|
||||
If you discover a bug in the bot, please
|
||||
[search our issue tracker](https://github.com/freqtrade/freqtrade/issues?q=is%3Aissue)
|
||||
first. If it hasn't been reported, please
|
||||
[create a new issue](https://github.com/freqtrade/freqtrade/issues/new) and
|
||||
ensure you follow the template guide so that our team can assist you as
|
||||
quickly as possible.
|
||||
|
||||
### [Feature Requests](https://github.com/freqtrade/freqtrade/labels/enhancement)
|
||||
|
||||
Have you a great idea to improve the bot you want to share? Please,
|
||||
first search if this feature was not [already discussed](https://github.com/freqtrade/freqtrade/labels/enhancement).
|
||||
If it hasn't been requested, please
|
||||
[create a new request](https://github.com/freqtrade/freqtrade/issues/new)
|
||||
and ensure you follow the template guide so that it does not get lost
|
||||
in the bug reports.
|
||||
|
||||
### [Pull Requests](https://github.com/freqtrade/freqtrade/pulls)
|
||||
|
||||
Feel like our bot is missing a feature? We welcome your pull requests!
|
||||
|
||||
Please read our
|
||||
[Contributing document](https://github.com/freqtrade/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||
to understand the requirements before sending your pull-requests.
|
||||
|
||||
Coding is not a neccessity to contribute - maybe start with improving our documentation?
|
||||
Issues labeled [good first issue](https://github.com/freqtrade/freqtrade/labels/good%20first%20issue) can be good first contributions, and will help get you familiar with the codebase.
|
||||
|
||||
**Note** before starting any major new feature work, *please open an issue describing what you are planning to do* or talk to us on [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE). This will ensure that interested parties can give valuable feedback on the feature, and let others know that you are working on it.
|
||||
|
||||
**Important:** Always create your PR against the `develop` branch, not `master`.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Uptodate clock
|
||||
|
||||
The clock must be accurate, syncronized to a NTP server very frequently to avoid problems with communication to the exchanges.
|
||||
|
||||
### Min hardware required
|
||||
|
||||
To run this bot we recommend you a cloud instance with a minimum of:
|
||||
* Minimal (advised) system requirements: 2GB RAM, 1GB disk space, 2vCPU
|
||||
|
||||
- Minimal (advised) system requirements: 2GB RAM, 1GB disk space, 2vCPU
|
||||
|
||||
### Software requirements
|
||||
|
||||
- [Python 3.6.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
||||
- [pip](https://pip.pypa.io/en/stable/installing/)
|
||||
- [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
|
||||
11
build_helpers/install_ta-lib.sh
Executable file
11
build_helpers/install_ta-lib.sh
Executable file
@@ -0,0 +1,11 @@
|
||||
if [ ! -f "/usr/local/lib/libta_lib.a" ]; then
|
||||
tar zxvf ta-lib-0.4.0-src.tar.gz
|
||||
cd ta-lib \
|
||||
&& sed -i.bak "s|0.00000001|0.000000000000000001 |g" src/ta_func/ta_utility.h \
|
||||
&& ./configure \
|
||||
&& make \
|
||||
&& which sudo && sudo make install || make install \
|
||||
&& cd ..
|
||||
else
|
||||
echo "TA-lib already installed, skipping installation"
|
||||
fi
|
||||
60
build_helpers/publish_docker.sh
Executable file
60
build_helpers/publish_docker.sh
Executable file
@@ -0,0 +1,60 @@
|
||||
#!/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/\//_/")
|
||||
|
||||
|
||||
# Add commit and commit_message to docker container
|
||||
echo "${TRAVIS_COMMIT} ${TRAVIS_COMMIT_MESSAGE}" > freqtrade_commit
|
||||
|
||||
if [ "${TRAVIS_EVENT_TYPE}" = "cron" ]; then
|
||||
echo "event ${TRAVIS_EVENT_TYPE}: full rebuild - skipping cache"
|
||||
docker build -t freqtrade:${TAG} .
|
||||
else
|
||||
echo "event ${TRAVIS_EVENT_TYPE}: building with cache"
|
||||
# Pull last build to avoid rebuilding the whole image
|
||||
docker pull ${IMAGE_NAME}:${TAG}
|
||||
docker build --cache-from ${IMAGE_NAME}:${TAG} -t freqtrade:${TAG} .
|
||||
fi
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "failed building image"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Run backtest
|
||||
docker run --rm -it -v $(pwd)/config.json.example:/freqtrade/config.json:ro freqtrade:${TAG} --datadir freqtrade/tests/testdata backtesting
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "failed running backtest"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Tag image for upload
|
||||
docker tag freqtrade:$TAG ${IMAGE_NAME}:$TAG
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "failed tagging image"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Tag as latest for develop builds
|
||||
if [ "${TRAVIS_BRANCH}" = "develop" ]; then
|
||||
docker tag freqtrade:$TAG ${IMAGE_NAME}:latest
|
||||
fi
|
||||
|
||||
# Login
|
||||
echo "$DOCKER_PASS" | docker login -u $DOCKER_USER --password-stdin
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "failed login"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Show all available images
|
||||
docker images
|
||||
|
||||
docker push ${IMAGE_NAME}
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "failed pushing repo"
|
||||
return 1
|
||||
fi
|
||||
BIN
build_helpers/ta-lib-0.4.0-src.tar.gz
Normal file
BIN
build_helpers/ta-lib-0.4.0-src.tar.gz
Normal file
Binary file not shown.
@@ -3,34 +3,70 @@
|
||||
"stake_currency": "BTC",
|
||||
"stake_amount": 0.05,
|
||||
"fiat_display_currency": "USD",
|
||||
"ticker_interval" : "5m",
|
||||
"dry_run": false,
|
||||
"unfilledtimeout": 600,
|
||||
"trailing_stop": false,
|
||||
"unfilledtimeout": {
|
||||
"buy": 10,
|
||||
"sell": 30
|
||||
},
|
||||
"bid_strategy": {
|
||||
"ask_last_balance": 0.0
|
||||
"ask_last_balance": 0.0,
|
||||
"use_order_book": false,
|
||||
"order_book_top": 1,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"ask_strategy":{
|
||||
"use_order_book": false,
|
||||
"order_book_min": 1,
|
||||
"order_book_max": 9
|
||||
},
|
||||
"exchange": {
|
||||
"name": "bittrex",
|
||||
"key": "your_exchange_key",
|
||||
"secret": "your_exchange_secret",
|
||||
"ccxt_config": {"enableRateLimit": true},
|
||||
"ccxt_async_config": {
|
||||
"enableRateLimit": false
|
||||
},
|
||||
"pair_whitelist": [
|
||||
"BTC_ETH",
|
||||
"BTC_LTC",
|
||||
"BTC_ETC",
|
||||
"BTC_DASH",
|
||||
"BTC_ZEC",
|
||||
"BTC_XLM",
|
||||
"BTC_NXT",
|
||||
"BTC_POWR",
|
||||
"BTC_ADA",
|
||||
"BTC_XMR"
|
||||
"ETH/BTC",
|
||||
"LTC/BTC",
|
||||
"ETC/BTC",
|
||||
"DASH/BTC",
|
||||
"ZEC/BTC",
|
||||
"XLM/BTC",
|
||||
"NXT/BTC",
|
||||
"POWR/BTC",
|
||||
"ADA/BTC",
|
||||
"XMR/BTC"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BTC_DOGE"
|
||||
"DOGE/BTC"
|
||||
]
|
||||
},
|
||||
"experimental": {
|
||||
"use_sell_signal": false,
|
||||
"sell_profit_only": false
|
||||
"sell_profit_only": false,
|
||||
"ignore_roi_if_buy_signal": false
|
||||
},
|
||||
"edge": {
|
||||
"enabled": false,
|
||||
"process_throttle_secs": 3600,
|
||||
"calculate_since_number_of_days": 7,
|
||||
"capital_available_percentage": 0.5,
|
||||
"allowed_risk": 0.01,
|
||||
"stoploss_range_min": -0.01,
|
||||
"stoploss_range_max": -0.1,
|
||||
"stoploss_range_step": -0.01,
|
||||
"minimum_winrate": 0.60,
|
||||
"minimum_expectancy": 0.20,
|
||||
"min_trade_number": 10,
|
||||
"max_trade_duration_minute": 1440,
|
||||
"remove_pumps": false
|
||||
},
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
@@ -38,6 +74,7 @@
|
||||
"chat_id": "your_telegram_chat_id"
|
||||
},
|
||||
"initial_state": "running",
|
||||
"forcebuy_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 5
|
||||
}
|
||||
|
||||
83
config_binance.json.example
Normal file
83
config_binance.json.example
Normal file
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"max_open_trades": 3,
|
||||
"stake_currency": "BTC",
|
||||
"stake_amount": 0.05,
|
||||
"fiat_display_currency": "USD",
|
||||
"ticker_interval" : "5m",
|
||||
"dry_run": true,
|
||||
"trailing_stop": false,
|
||||
"unfilledtimeout": {
|
||||
"buy": 10,
|
||||
"sell": 30
|
||||
},
|
||||
"bid_strategy": {
|
||||
"ask_last_balance": 0.0,
|
||||
"use_order_book": false,
|
||||
"order_book_top": 1,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"ask_strategy":{
|
||||
"use_order_book": false,
|
||||
"order_book_min": 1,
|
||||
"order_book_max": 9
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "your_exchange_key",
|
||||
"secret": "your_exchange_secret",
|
||||
"ccxt_config": {"enableRateLimit": true},
|
||||
"ccxt_async_config": {
|
||||
"enableRateLimit": false
|
||||
},
|
||||
"pair_whitelist": [
|
||||
"AST/BTC",
|
||||
"ETC/BTC",
|
||||
"ETH/BTC",
|
||||
"EOS/BTC",
|
||||
"IOTA/BTC",
|
||||
"LTC/BTC",
|
||||
"MTH/BTC",
|
||||
"NCASH/BTC",
|
||||
"TNT/BTC",
|
||||
"XMR/BTC",
|
||||
"XLM/BTC",
|
||||
"XRP/BTC"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/BTC"
|
||||
]
|
||||
},
|
||||
"experimental": {
|
||||
"use_sell_signal": false,
|
||||
"sell_profit_only": false,
|
||||
"ignore_roi_if_buy_signal": false
|
||||
},
|
||||
"edge": {
|
||||
"enabled": false,
|
||||
"process_throttle_secs": 3600,
|
||||
"calculate_since_number_of_days": 7,
|
||||
"capital_available_percentage": 0.5,
|
||||
"allowed_risk": 0.01,
|
||||
"stoploss_range_min": -0.01,
|
||||
"stoploss_range_max": -0.1,
|
||||
"stoploss_range_step": -0.01,
|
||||
"minimum_winrate": 0.60,
|
||||
"minimum_expectancy": 0.20,
|
||||
"min_trade_number": 10,
|
||||
"max_trade_duration_minute": 1440,
|
||||
"remove_pumps": false
|
||||
},
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "your_telegram_token",
|
||||
"chat_id": "your_telegram_chat_id"
|
||||
},
|
||||
"initial_state": "running",
|
||||
"forcebuy_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 5
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,12 @@
|
||||
"stake_currency": "BTC",
|
||||
"stake_amount": 0.05,
|
||||
"fiat_display_currency": "USD",
|
||||
"amount_reserve_percent" : 0.05,
|
||||
"dry_run": false,
|
||||
"ticker_interval": 5,
|
||||
"ticker_interval": "5m",
|
||||
"trailing_stop": false,
|
||||
"trailing_stop_positive": 0.005,
|
||||
"trailing_stop_positive_offset": 0.0051,
|
||||
"minimal_roi": {
|
||||
"40": 0.0,
|
||||
"30": 0.01,
|
||||
@@ -12,40 +16,96 @@
|
||||
"0": 0.04
|
||||
},
|
||||
"stoploss": -0.10,
|
||||
"unfilledtimeout": 600,
|
||||
"unfilledtimeout": {
|
||||
"buy": 10,
|
||||
"sell": 30
|
||||
},
|
||||
"bid_strategy": {
|
||||
"ask_last_balance": 0.0
|
||||
"ask_last_balance": 0.0,
|
||||
"use_order_book": false,
|
||||
"order_book_top": 1,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"ask_strategy":{
|
||||
"use_order_book": false,
|
||||
"order_book_min": 1,
|
||||
"order_book_max": 9
|
||||
},
|
||||
"order_types": {
|
||||
"buy": "limit",
|
||||
"sell": "limit",
|
||||
"stoploss": "market",
|
||||
"stoploss_on_exchange": "false",
|
||||
"stoploss_on_exchange_interval": 60
|
||||
},
|
||||
"order_time_in_force": {
|
||||
"buy": "gtc",
|
||||
"sell": "gtc",
|
||||
},
|
||||
"pairlist": {
|
||||
"method": "VolumePairList",
|
||||
"config": {
|
||||
"number_assets": 20,
|
||||
"sort_key": "quoteVolume"
|
||||
}
|
||||
},
|
||||
"exchange": {
|
||||
"name": "bittrex",
|
||||
"key": "your_exchange_key",
|
||||
"secret": "your_exchange_secret",
|
||||
"ccxt_config": {"enableRateLimit": true},
|
||||
"ccxt_async_config": {
|
||||
"enableRateLimit": false,
|
||||
"aiohttp_trust_env": false
|
||||
},
|
||||
"pair_whitelist": [
|
||||
"BTC_ETH",
|
||||
"BTC_LTC",
|
||||
"BTC_ETC",
|
||||
"BTC_DASH",
|
||||
"BTC_ZEC",
|
||||
"BTC_XLM",
|
||||
"BTC_NXT",
|
||||
"BTC_POWR",
|
||||
"BTC_ADA",
|
||||
"BTC_XMR"
|
||||
"ETH/BTC",
|
||||
"LTC/BTC",
|
||||
"ETC/BTC",
|
||||
"DASH/BTC",
|
||||
"ZEC/BTC",
|
||||
"XLM/BTC",
|
||||
"NXT/BTC",
|
||||
"POWR/BTC",
|
||||
"ADA/BTC",
|
||||
"XMR/BTC"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BTC_DOGE"
|
||||
]
|
||||
"DOGE/BTC"
|
||||
],
|
||||
"outdated_offset": 5
|
||||
},
|
||||
"edge": {
|
||||
"enabled": false,
|
||||
"process_throttle_secs": 3600,
|
||||
"calculate_since_number_of_days": 7,
|
||||
"capital_available_percentage": 0.5,
|
||||
"allowed_risk": 0.01,
|
||||
"stoploss_range_min": -0.01,
|
||||
"stoploss_range_max": -0.1,
|
||||
"stoploss_range_step": -0.01,
|
||||
"minimum_winrate": 0.60,
|
||||
"minimum_expectancy": 0.20,
|
||||
"min_trade_number": 10,
|
||||
"max_trade_duration_minute": 1440,
|
||||
"remove_pumps": false
|
||||
},
|
||||
"experimental": {
|
||||
"use_sell_signal": false,
|
||||
"sell_profit_only": false
|
||||
"sell_profit_only": false,
|
||||
"ignore_roi_if_buy_signal": false
|
||||
},
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "your_telegram_token",
|
||||
"chat_id": "your_telegram_chat_id"
|
||||
},
|
||||
"db_url": "sqlite:///tradesv3.sqlite",
|
||||
"initial_state": "running",
|
||||
"forcebuy_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 5
|
||||
},
|
||||
|
||||
@@ -1,144 +1,230 @@
|
||||
# Backtesting
|
||||
|
||||
This page explains how to validate your strategy performance by using
|
||||
Backtesting.
|
||||
|
||||
## Table of Contents
|
||||
- [Test your strategy with Backtesting](#test-your-strategy-with-backtesting)
|
||||
- [Understand the backtesting result](#understand-the-backtesting-result)
|
||||
|
||||
## Test your strategy with Backtesting
|
||||
|
||||
Now you have good Buy and Sell strategies, you want to test it against
|
||||
real data. This is what we call
|
||||
[backtesting](https://en.wikipedia.org/wiki/Backtesting).
|
||||
|
||||
|
||||
Backtesting will use the crypto-currencies (pair) from your config file
|
||||
and load static tickers located in
|
||||
[/freqtrade/tests/testdata](https://github.com/gcarq/freqtrade/tree/develop/freqtrade/tests/testdata).
|
||||
[/freqtrade/tests/testdata](https://github.com/freqtrade/freqtrade/tree/develop/freqtrade/tests/testdata).
|
||||
If the 5 min and 1 min ticker for the crypto-currencies to test is not
|
||||
already in the `testdata` folder, backtesting will download them
|
||||
automatically. Testdata files will not be updated until you specify it.
|
||||
|
||||
The result of backtesting will confirm you if your bot as more chance to
|
||||
make a profit than a loss.
|
||||
|
||||
The result of backtesting will confirm you if your bot has better odds of making a profit than a loss.
|
||||
|
||||
The backtesting is very easy with freqtrade.
|
||||
|
||||
### Run a backtesting against the currencies listed in your config file
|
||||
**With 5 min tickers (Per default)**
|
||||
#### With 5 min tickers (Per default)
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --realistic-simulation
|
||||
python3 ./freqtrade/main.py backtesting
|
||||
```
|
||||
|
||||
**With 1 min tickers**
|
||||
#### With 1 min tickers
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --realistic-simulation --ticker-interval 1
|
||||
python3 ./freqtrade/main.py backtesting --ticker-interval 1m
|
||||
```
|
||||
|
||||
**Reload your testdata files**
|
||||
#### Update cached pairs with the latest data
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --realistic-simulation --refresh-pairs-cached
|
||||
python3 ./freqtrade/main.py backtesting --refresh-pairs-cached
|
||||
```
|
||||
|
||||
**With live data (do not alter your testdata files)**
|
||||
#### With live data (do not alter your testdata files)
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --realistic-simulation --live
|
||||
python3 ./freqtrade/main.py backtesting --live
|
||||
```
|
||||
|
||||
**Using a different on-disk ticker-data source**
|
||||
#### Using a different on-disk ticker-data source
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --datadir freqtrade/tests/testdata-20180101
|
||||
```
|
||||
|
||||
**With a (custom) strategy file**
|
||||
```bash
|
||||
python3 ./freqtrade/main.py -s currentstrategy backtesting
|
||||
```
|
||||
Where `-s currentstrategy` refers to a filename `currentstrategy.py` in `freqtrade/user_data/strategies`
|
||||
#### With a (custom) strategy file
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py -s TestStrategy backtesting
|
||||
```
|
||||
|
||||
Where `-s TestStrategy` refers to the class name within the strategy file `test_strategy.py` found in the `freqtrade/user_data/strategies` directory
|
||||
|
||||
#### Exporting trades to file
|
||||
|
||||
**Exporting trades to file**
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --export trades
|
||||
```
|
||||
|
||||
**Running backtest with smaller testset**
|
||||
The exported trades can be read using the following code for manual analysis, or can be used by the plotting script `plot_dataframe.py` in the scripts folder.
|
||||
|
||||
``` python
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pandas as pd
|
||||
|
||||
filename=Path('user_data/backtest_data/backtest-result.json')
|
||||
|
||||
with filename.open() as file:
|
||||
data = json.load(file)
|
||||
|
||||
columns = ["pair", "profit", "opents", "closets", "index", "duration",
|
||||
"open_rate", "close_rate", "open_at_end", "sell_reason"]
|
||||
df = pd.DataFrame(data, columns=columns)
|
||||
|
||||
df['opents'] = pd.to_datetime(df['opents'],
|
||||
unit='s',
|
||||
utc=True,
|
||||
infer_datetime_format=True
|
||||
)
|
||||
df['closets'] = pd.to_datetime(df['closets'],
|
||||
unit='s',
|
||||
utc=True,
|
||||
infer_datetime_format=True
|
||||
)
|
||||
```
|
||||
|
||||
If you have some ideas for interesting / helpful backtest data analysis, feel free to submit a PR so the community can benefit from it.
|
||||
|
||||
#### Exporting trades to file specifying a custom filename
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --export trades --export-filename=backtest_teststrategy.json
|
||||
```
|
||||
|
||||
#### Running backtest with smaller testset
|
||||
|
||||
Use the `--timerange` argument to change how much of the testset
|
||||
you want to use. The last N ticks/timeframes will be used.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --timerange=-200
|
||||
```
|
||||
|
||||
***Advanced use of timerange***
|
||||
#### Advanced use of timerange
|
||||
|
||||
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.
|
||||
|
||||
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 since 2018/01/31: `--timerange=20180131-`
|
||||
- Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
|
||||
- Use tickframes between POSIX timestamps 1527595200 1527618600:
|
||||
`--timerange=1527595200-1527618600`
|
||||
|
||||
#### Downloading new set of ticker data
|
||||
|
||||
Incoming feature, not implemented yet:
|
||||
- `--timerange=-20180131`
|
||||
- `--timerange=20180101-`
|
||||
- `--timerange=20180101-20181231`
|
||||
To download new set of backtesting ticker data, you can use a download script.
|
||||
|
||||
If you are using Binance for example:
|
||||
|
||||
**Update testdata directory**
|
||||
To update your testdata directory, or download into another testdata directory:
|
||||
```bash
|
||||
mkdir -p user_data/data/testdata-20180113
|
||||
cp freqtrade/tests/testdata/pairs.json user_data/data-20180113
|
||||
cd user_data/data-20180113
|
||||
```
|
||||
|
||||
Possibly edit pairs.json file to include/exclude pairs
|
||||
- create a folder `user_data/data/binance` and copy `pairs.json` in that folder.
|
||||
- update the `pairs.json` to contain the currency pairs you are interested in.
|
||||
|
||||
```bash
|
||||
python3 freqtrade/tests/testdata/download_backtest_data.py -p pairs.json
|
||||
mkdir -p user_data/data/binance
|
||||
cp freqtrade/tests/testdata/pairs.json user_data/data/binance
|
||||
```
|
||||
|
||||
The script will read your pairs.json file, and download ticker data
|
||||
into the current working directory.
|
||||
Then run:
|
||||
|
||||
```bash
|
||||
python scripts/download_backtest_data.py --exchange binance
|
||||
```
|
||||
|
||||
For help about backtesting usage, please refer to
|
||||
[Backtesting commands](#backtesting-commands).
|
||||
This will download ticker data for all the currency pairs you defined in `pairs.json`.
|
||||
|
||||
- To use a different folder than the exchange specific default, use `--export user_data/data/some_directory`.
|
||||
- To change the exchange used to download the tickers, use `--exchange`. Default is `bittrex`.
|
||||
- To use `pairs.json` from some other folder, use `--pairs-file some_other_dir/pairs.json`.
|
||||
- To download ticker data for only 10 days, use `--days 10`.
|
||||
- Use `--timeframes` to specify which tickers to download. Default is `--timeframes 1m 5m` which will download 1-minute and 5-minute tickers.
|
||||
|
||||
For help about backtesting usage, please refer to [Backtesting commands](#backtesting-commands).
|
||||
|
||||
## Understand the backtesting result
|
||||
|
||||
The most important in the backtesting is to understand the result.
|
||||
|
||||
A backtesting result will look like that:
|
||||
|
||||
```
|
||||
====================== BACKTESTING REPORT ================================
|
||||
pair buy count avg profit % total profit BTC avg duration
|
||||
-------- ----------- -------------- ------------------ --------------
|
||||
BTC_ETH 56 -0.67 -0.00075455 62.3
|
||||
BTC_LTC 38 -0.48 -0.00036315 57.9
|
||||
BTC_ETC 42 -1.15 -0.00096469 67.0
|
||||
BTC_DASH 72 -0.62 -0.00089368 39.9
|
||||
BTC_ZEC 45 -0.46 -0.00041387 63.2
|
||||
BTC_XLM 24 -0.88 -0.00041846 47.7
|
||||
BTC_NXT 24 0.68 0.00031833 40.2
|
||||
BTC_POWR 35 0.98 0.00064887 45.3
|
||||
BTC_ADA 43 -0.39 -0.00032292 55.0
|
||||
BTC_XMR 40 -0.40 -0.00032181 47.4
|
||||
TOTAL 419 -0.41 -0.00348593 52.9
|
||||
========================================================= BACKTESTING REPORT ========================================================
|
||||
| pair | buy count | avg profit % | cum profit % | tot profit BTC | tot profit % | avg duration | profit | loss |
|
||||
|:---------|------------:|---------------:|---------------:|-----------------:|---------------:|:---------------|---------:|-------:|
|
||||
| ADA/BTC | 35 | -0.11 | -3.88 | -0.00019428 | -1.94 | 4:35:00 | 14 | 21 |
|
||||
| ARK/BTC | 11 | -0.41 | -4.52 | -0.00022647 | -2.26 | 2:03:00 | 3 | 8 |
|
||||
| BTS/BTC | 32 | 0.31 | 9.78 | 0.00048938 | 4.89 | 5:05:00 | 18 | 14 |
|
||||
| DASH/BTC | 13 | -0.08 | -1.07 | -0.00005343 | -0.53 | 4:39:00 | 6 | 7 |
|
||||
| ENG/BTC | 18 | 1.36 | 24.54 | 0.00122807 | 12.27 | 2:50:00 | 8 | 10 |
|
||||
| EOS/BTC | 36 | 0.08 | 3.06 | 0.00015304 | 1.53 | 3:34:00 | 16 | 20 |
|
||||
| ETC/BTC | 26 | 0.37 | 9.51 | 0.00047576 | 4.75 | 6:14:00 | 11 | 15 |
|
||||
| ETH/BTC | 33 | 0.30 | 9.96 | 0.00049856 | 4.98 | 7:31:00 | 16 | 17 |
|
||||
| IOTA/BTC | 32 | 0.03 | 1.09 | 0.00005444 | 0.54 | 3:12:00 | 14 | 18 |
|
||||
| LSK/BTC | 15 | 1.75 | 26.26 | 0.00131413 | 13.13 | 2:58:00 | 6 | 9 |
|
||||
| LTC/BTC | 32 | -0.04 | -1.38 | -0.00006886 | -0.69 | 4:49:00 | 11 | 21 |
|
||||
| NANO/BTC | 17 | 1.26 | 21.39 | 0.00107058 | 10.70 | 1:55:00 | 10 | 7 |
|
||||
| NEO/BTC | 23 | 0.82 | 18.97 | 0.00094936 | 9.48 | 2:59:00 | 10 | 13 |
|
||||
| REQ/BTC | 9 | 1.17 | 10.54 | 0.00052734 | 5.27 | 3:47:00 | 4 | 5 |
|
||||
| XLM/BTC | 16 | 1.22 | 19.54 | 0.00097800 | 9.77 | 3:15:00 | 7 | 9 |
|
||||
| XMR/BTC | 23 | -0.18 | -4.13 | -0.00020696 | -2.07 | 5:30:00 | 12 | 11 |
|
||||
| XRP/BTC | 35 | 0.66 | 22.96 | 0.00114897 | 11.48 | 3:49:00 | 12 | 23 |
|
||||
| ZEC/BTC | 22 | -0.46 | -10.18 | -0.00050971 | -5.09 | 2:22:00 | 7 | 15 |
|
||||
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 243 |
|
||||
========================================================= SELL REASON STATS =========================================================
|
||||
| Sell Reason | Count |
|
||||
|:-------------------|--------:|
|
||||
| trailing_stop_loss | 205 |
|
||||
| stop_loss | 166 |
|
||||
| sell_signal | 56 |
|
||||
| force_sell | 2 |
|
||||
====================================================== LEFT OPEN TRADES REPORT ======================================================
|
||||
| pair | buy count | avg profit % | cum profit % | tot profit BTC | tot profit % | avg duration | profit | loss |
|
||||
|:---------|------------:|---------------:|---------------:|-----------------:|---------------:|:---------------|---------:|-------:|
|
||||
| ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 | 0 |
|
||||
| LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 | 0 |
|
||||
| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 | 0 |
|
||||
```
|
||||
|
||||
The 1st table will contain all trades the bot made.
|
||||
|
||||
The 2nd table will contain a recap of sell reasons.
|
||||
|
||||
The 3rd table will contain all trades the bot had to `forcesell` at the end of the backtest period to present a full picture.
|
||||
These trades are also included in the first table, but are extracted separately for clarity.
|
||||
|
||||
The last line will give you the overall performance of your strategy,
|
||||
here:
|
||||
|
||||
```
|
||||
TOTAL 419 -0.41 -0.00348593 52.9
|
||||
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 243 |
|
||||
```
|
||||
|
||||
We understand the bot has made `419` trades for an average duration of
|
||||
`52.9` min, with a performance of `-0.41%` (loss), that means it has
|
||||
lost a total of `-0.00348593 BTC`.
|
||||
We understand the bot has made `429` trades for an average duration of
|
||||
`4:12:00`, with a performance of `76.20%` (profit), that means it has
|
||||
earned a total of `0.00762792 BTC` starting with a capital of 0.01 BTC.
|
||||
|
||||
The column `avg profit %` shows the average profit for all trades made while the column `cum profit %` sums all the profits/losses.
|
||||
The column `tot profit %` shows instead the total profit % in relation to allocated capital
|
||||
(`max_open_trades * stake_amount`). In the above results we have `max_open_trades=2 stake_amount=0.005` in config
|
||||
so `(76.20/100) * (0.005 * 2) =~ 0.00762792 BTC`.
|
||||
|
||||
As you will see your strategy performance will be influenced by your buy
|
||||
strategy, your sell strategy, and also by the `minimal_roi` and
|
||||
@@ -147,6 +233,7 @@ strategy, your sell strategy, and also by the `minimal_roi` and
|
||||
As for an example if your minimal_roi is only `"0": 0.01`. You cannot
|
||||
expect the bot to make more profit than 1% (because it will sell every
|
||||
time a trade will reach 1%).
|
||||
|
||||
```json
|
||||
"minimal_roi": {
|
||||
"0": 0.01
|
||||
@@ -158,7 +245,33 @@ On the other hand, if you set a too high `minimal_roi` like `"0": 0.55`
|
||||
profit. Hence, keep in mind that your performance is a mix of your
|
||||
strategies, your configuration, and the crypto-currency you have set up.
|
||||
|
||||
## Backtesting multiple strategies
|
||||
|
||||
To backtest multiple strategies, a list of Strategies can be provided.
|
||||
|
||||
This is limited to 1 ticker-interval per run, however, data is only loaded once from disk so if you have multiple
|
||||
strategies you'd like to compare, this should give a nice runtime boost.
|
||||
|
||||
All listed Strategies need to be in the same folder.
|
||||
|
||||
``` bash
|
||||
freqtrade backtesting --timerange 20180401-20180410 --ticker-interval 5m --strategy-list Strategy001 Strategy002 --export trades
|
||||
```
|
||||
|
||||
This will save the results to `user_data/backtest_data/backtest-result-<strategy>.json`, injecting the strategy-name into the target filename.
|
||||
There will be an additional table comparing win/losses of the different strategies (identical to the "Total" row in the first table).
|
||||
Detailed output for all strategies one after the other will be available, so make sure to scroll up.
|
||||
|
||||
```
|
||||
=========================================================== Strategy Summary ===========================================================
|
||||
| Strategy | buy count | avg profit % | cum profit % | tot profit BTC | tot profit % | avg duration | profit | loss |
|
||||
|:------------|------------:|---------------:|---------------:|-----------------:|---------------:|:---------------|---------:|-------:|
|
||||
| Strategy1 | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 243 |
|
||||
| Strategy2 | 1487 | -0.13 | -197.58 | -0.00988917 | -98.79 | 4:43:00 | 662 | 825 |
|
||||
```
|
||||
|
||||
## Next step
|
||||
|
||||
Great, your strategy is profitable. What if the bot can give your the
|
||||
optimal parameters to use for your strategy?
|
||||
Your next step is to learn [how to find optimal parameters with Hyperopt](https://github.com/gcarq/freqtrade/blob/develop/docs/hyperopt.md)
|
||||
Your next step is to learn [how to find optimal parameters with Hyperopt](hyperopt.md)
|
||||
|
||||
@@ -1,20 +1,15 @@
|
||||
# Bot Optimization
|
||||
# Optimization
|
||||
|
||||
This page explains where to customize your strategies, and add new
|
||||
indicators.
|
||||
|
||||
## Table of Contents
|
||||
- [Install a custom strategy file](#install-a-custom-strategy-file)
|
||||
- [Customize your strategy](#change-your-strategy)
|
||||
- [Add more Indicator](#add-more-indicator)
|
||||
- [Where is the default strategy](#where-is-the-default-strategy)
|
||||
|
||||
Since the version `0.16.0` the bot allows using custom strategy file.
|
||||
|
||||
## Install a custom strategy file
|
||||
|
||||
This is very simple. Copy paste your strategy file into the folder
|
||||
`user_data/strategies`.
|
||||
|
||||
Let assume you have a class called `AwesomeStrategy` in the file `awesome-strategy.py`:
|
||||
|
||||
1. Move your file into `user_data/strategies` (you should have `user_data/strategies/awesome-strategy.py`
|
||||
2. Start the bot with the param `--strategy AwesomeStrategy` (the parameter is the class name)
|
||||
|
||||
@@ -23,17 +18,24 @@ python3 ./freqtrade/main.py --strategy AwesomeStrategy
|
||||
```
|
||||
|
||||
## Change your strategy
|
||||
|
||||
The bot includes a default strategy file. However, we recommend you to
|
||||
use your own file to not have to lose your parameters every time the default
|
||||
strategy file will be updated on Github. Put your custom strategy file
|
||||
into the folder `user_data/strategies`.
|
||||
|
||||
Best copy the test-strategy and modify this copy to avoid having bot-updates override your changes.
|
||||
`cp user_data/strategies/test_strategy.py user_data/strategies/awesome-strategy.py`
|
||||
|
||||
### Anatomy of a strategy
|
||||
|
||||
A strategy file contains all the information needed to build a good strategy:
|
||||
|
||||
- Indicators
|
||||
- Buy strategy rules
|
||||
- Sell strategy rules
|
||||
- Minimal ROI recommended
|
||||
- Stoploss recommended
|
||||
- Hyperopt parameter
|
||||
- Stoploss strongly recommended
|
||||
|
||||
The bot also include a sample strategy called `TestStrategy` you can update: `user_data/strategies/test_strategy.py`.
|
||||
You can test it with the parameter: `--strategy TestStrategy`
|
||||
@@ -42,71 +44,36 @@ You can test it with the parameter: `--strategy TestStrategy`
|
||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy
|
||||
```
|
||||
|
||||
### Specify custom strategy location
|
||||
If you want to use a strategy from a different folder you can pass `--strategy-path`
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy --strategy-path /some/folder
|
||||
```
|
||||
|
||||
**For the following section we will use the [user_data/strategies/test_strategy.py](https://github.com/gcarq/freqtrade/blob/develop/user_data/strategies/test_strategy.py)
|
||||
**For the following section we will use the [user_data/strategies/test_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/strategies/test_strategy.py)
|
||||
file as reference.**
|
||||
|
||||
### Buy strategy
|
||||
Edit the method `populate_buy_trend()` into your strategy file to
|
||||
update your buy strategy.
|
||||
!!! Note: Strategies and Backtesting
|
||||
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.
|
||||
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.
|
||||
|
||||
Sample from `user_data/strategies/test_strategy.py`:
|
||||
```python
|
||||
def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the buy signal for the given dataframe
|
||||
:param dataframe: DataFrame
|
||||
:return: DataFrame with buy column
|
||||
"""
|
||||
dataframe.loc[
|
||||
(
|
||||
(dataframe['adx'] > 30) &
|
||||
(dataframe['tema'] <= dataframe['blower']) &
|
||||
(dataframe['tema'] > dataframe['tema'].shift(1))
|
||||
),
|
||||
'buy'] = 1
|
||||
### Customize Indicators
|
||||
|
||||
return dataframe
|
||||
```
|
||||
Buy and sell strategies need indicators. You can add more indicators by extending the list contained in the method `populate_indicators()` from your strategy file.
|
||||
|
||||
### Sell strategy
|
||||
Edit the method `populate_sell_trend()` into your strategy file to
|
||||
update your sell strategy.
|
||||
You should only add the indicators used in either `populate_buy_trend()`, `populate_sell_trend()`, or to populate another indicator, otherwise performance may suffer.
|
||||
|
||||
Sample from `user_data/strategies/test_strategy.py`:
|
||||
```python
|
||||
def populate_sell_trend(self, dataframe: DataFrame) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the sell signal for the given dataframe
|
||||
:param dataframe: DataFrame
|
||||
:return: DataFrame with buy column
|
||||
"""
|
||||
dataframe.loc[
|
||||
(
|
||||
(dataframe['adx'] > 70) &
|
||||
(dataframe['tema'] > dataframe['blower']) &
|
||||
(dataframe['tema'] < dataframe['tema'].shift(1))
|
||||
),
|
||||
'sell'] = 1
|
||||
return dataframe
|
||||
```
|
||||
|
||||
## Add more Indicator
|
||||
As you have seen, buy and sell strategies need indicators. You can add
|
||||
more indicators by extending the list contained in
|
||||
the method `populate_indicators()` from your strategy file.
|
||||
It's important to always return the dataframe without removing/modifying the columns `"open", "high", "low", "close", "volume"`, otherwise these fields would contain something unexpected.
|
||||
|
||||
Sample:
|
||||
|
||||
```python
|
||||
def populate_indicators(dataframe: DataFrame) -> DataFrame:
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Adds several different TA indicators to the given DataFrame
|
||||
|
||||
Performance Note: For the best performance be frugal on the number of indicators
|
||||
you are using. Let uncomment only the indicator you are using in your strategies
|
||||
or your hyperopt configuration, otherwise you will waste your memory and CPU usage.
|
||||
:param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe()
|
||||
:param metadata: Additional information, like the currently traded pair
|
||||
:return: a Dataframe with all mandatory indicators for the strategies
|
||||
"""
|
||||
dataframe['sar'] = ta.SAR(dataframe)
|
||||
dataframe['adx'] = ta.ADX(dataframe)
|
||||
@@ -137,16 +104,269 @@ def populate_indicators(dataframe: DataFrame) -> DataFrame:
|
||||
return dataframe
|
||||
```
|
||||
|
||||
**Want more indicators example?**
|
||||
Look into the [user_data/strategies/test_strategy.py](https://github.com/gcarq/freqtrade/blob/develop/user_data/strategies/test_strategy.py).
|
||||
Then uncomment indicators you need.
|
||||
|
||||
!!! Note "Want more indicator examples?"
|
||||
Look into the [user_data/strategies/test_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/strategies/test_strategy.py).<br/>
|
||||
Then uncomment indicators you need.
|
||||
|
||||
### Buy signal rules
|
||||
|
||||
Edit the method `populate_buy_trend()` in your strategy file to update your buy strategy.
|
||||
|
||||
It's important to always return the dataframe without removing/modifying the columns `"open", "high", "low", "close", "volume"`, otherwise these fields would contain something unexpected.
|
||||
|
||||
This will method will also define a new column, `"buy"`, which needs to contain 1 for buys, and 0 for "no action".
|
||||
|
||||
Sample from `user_data/strategies/test_strategy.py`:
|
||||
|
||||
```python
|
||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the buy signal for the given dataframe
|
||||
:param dataframe: DataFrame populated with indicators
|
||||
:param metadata: Additional information, like the currently traded pair
|
||||
:return: DataFrame with buy column
|
||||
"""
|
||||
dataframe.loc[
|
||||
(
|
||||
(dataframe['adx'] > 30) &
|
||||
(dataframe['tema'] <= dataframe['bb_middleband']) &
|
||||
(dataframe['tema'] > dataframe['tema'].shift(1))
|
||||
),
|
||||
'buy'] = 1
|
||||
|
||||
return dataframe
|
||||
```
|
||||
|
||||
### Sell signal rules
|
||||
|
||||
Edit the method `populate_sell_trend()` into your strategy file to update your sell strategy.
|
||||
Please note that the sell-signal is only used if `use_sell_signal` is set to true in the configuration.
|
||||
|
||||
It's important to always return the dataframe without removing/modifying the columns `"open", "high", "low", "close", "volume"`, otherwise these fields would contain something unexpected.
|
||||
|
||||
This will method will also define a new column, `"sell"`, which needs to contain 1 for sells, and 0 for "no action".
|
||||
|
||||
Sample from `user_data/strategies/test_strategy.py`:
|
||||
|
||||
```python
|
||||
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the sell signal for the given dataframe
|
||||
:param dataframe: DataFrame populated with indicators
|
||||
:param metadata: Additional information, like the currently traded pair
|
||||
:return: DataFrame with buy column
|
||||
"""
|
||||
dataframe.loc[
|
||||
(
|
||||
(dataframe['adx'] > 70) &
|
||||
(dataframe['tema'] > dataframe['bb_middleband']) &
|
||||
(dataframe['tema'] < dataframe['tema'].shift(1))
|
||||
),
|
||||
'sell'] = 1
|
||||
return dataframe
|
||||
```
|
||||
|
||||
### Minimal ROI
|
||||
|
||||
This dict defines the minimal Return On Investment (ROI) a trade should reach before selling, independent from the sell signal.
|
||||
|
||||
It is of the following format, with the dict key (left side of the colon) being the minutes passed since the trade opened, and the value (right side of the colon) being the percentage.
|
||||
|
||||
```python
|
||||
minimal_roi = {
|
||||
"40": 0.0,
|
||||
"30": 0.01,
|
||||
"20": 0.02,
|
||||
"0": 0.04
|
||||
}
|
||||
```
|
||||
|
||||
The above configuration would therefore mean:
|
||||
|
||||
- Sell whenever 4% profit was reached
|
||||
- Sell when 2% profit was reached (in effect after 20 minutes)
|
||||
- Sell when 1% profit was reached (in effect after 30 minutes)
|
||||
- Sell when trade is non-loosing (in effect after 40 minutes)
|
||||
|
||||
The calculation does include fees.
|
||||
|
||||
To disable ROI completely, set it to an insanely high number:
|
||||
|
||||
```python
|
||||
minimal_roi = {
|
||||
"0": 100
|
||||
}
|
||||
```
|
||||
|
||||
While technically not completely disabled, this would sell once the trade reaches 10000% Profit.
|
||||
|
||||
### Stoploss
|
||||
|
||||
Setting a stoploss is highly recommended to protect your capital from strong moves against you.
|
||||
|
||||
Sample:
|
||||
|
||||
``` python
|
||||
stoploss = -0.10
|
||||
```
|
||||
|
||||
This would signify a stoploss of -10%.
|
||||
If your exchange supports it, it's recommended to also set `"stoploss_on_exchange"` in the order dict, so your stoploss is on the exchange and cannot be missed for network-problems (or other problems).
|
||||
|
||||
For more information on order_types please look [here](https://github.com/freqtrade/freqtrade/blob/develop/docs/configuration.md#understand-order_types).
|
||||
|
||||
### Ticker interval
|
||||
|
||||
This is the set of candles the bot should download and use for the analysis.
|
||||
Common values are `"1m"`, `"5m"`, `"15m"`, `"1h"`, however all values supported by your exchange should work.
|
||||
|
||||
Please note that the same buy/sell signals may work with one interval, but not the other.
|
||||
This setting is accessible within the strategy by using `self.ticker_interval`.
|
||||
|
||||
### Metadata dict
|
||||
|
||||
The metadata-dict (available for `populate_buy_trend`, `populate_sell_trend`, `populate_indicators`) contains additional information.
|
||||
Currently this is `pair`, which can be accessed using `metadata['pair']` - and will return a pair in the format `XRP/BTC`.
|
||||
|
||||
The Metadata-dict should not be modified and does not persist information across multiple calls.
|
||||
Instead, have a look at the section [Storing information](#Storing-information)
|
||||
|
||||
### Storing information
|
||||
|
||||
Storing information can be accomplished by crating 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.
|
||||
|
||||
```python
|
||||
class Awesomestrategy(IStrategy):
|
||||
# Create custom dictionary
|
||||
cust_info = {}
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
# Check if the entry already exists
|
||||
if "crosstime" in self.cust_info[metadata["pair"]:
|
||||
self.cust_info[metadata["pair"]["crosstime"] += 1
|
||||
else:
|
||||
self.cust_info[metadata["pair"]["crosstime"] = 1
|
||||
```
|
||||
|
||||
!!! 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.
|
||||
|
||||
!!! Note:
|
||||
If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.
|
||||
|
||||
### Additional data (DataProvider)
|
||||
|
||||
The strategy provides access to the `DataProvider`. This allows you to get additional data to use in your strategy.
|
||||
|
||||
!!!Note:
|
||||
The DataProvier is currently not available during backtesting / hyperopt, but this is planned for the future.
|
||||
|
||||
All methods return `None` in case of failure (do not raise an exception).
|
||||
|
||||
Please always check if the `DataProvider` is available to avoid failures during backtesting.
|
||||
|
||||
#### Possible options for DataProvider
|
||||
|
||||
- `available_pairs` - Property with tuples listing cached pairs with their intervals. (pair, interval)
|
||||
- `ohlcv(pair, ticker_interval)` - Currently cached ticker data for all pairs in the whitelist, returns DataFrame or empty DataFrame
|
||||
- `historic_ohlcv(pair, ticker_interval)` - Data stored on disk
|
||||
- `runmode` - Property containing the current runmode.
|
||||
|
||||
#### ohlcv / historic_ohlcv
|
||||
|
||||
``` python
|
||||
if self.dp:
|
||||
if dp.runmode == 'live':
|
||||
if ('ETH/BTC', ticker_interval) in self.dp.available_pairs:
|
||||
data_eth = self.dp.ohlcv(pair='ETH/BTC',
|
||||
ticker_interval=ticker_interval)
|
||||
else:
|
||||
# Get historic ohlcv data (cached on disk).
|
||||
history_eth = self.dp.historic_ohlcv(pair='ETH/BTC',
|
||||
ticker_interval='1h')
|
||||
```
|
||||
|
||||
!!! Warning: Warning about backtesting
|
||||
Be carefull when using dataprovider in backtesting. `historic_ohlcv()` 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).
|
||||
|
||||
#### Available Pairs
|
||||
|
||||
``` python
|
||||
if self.dp:
|
||||
for pair, ticker in self.dp.available_pairs:
|
||||
print(f"available {pair}, {ticker}")
|
||||
```
|
||||
|
||||
#### Get data for non-tradeable pairs
|
||||
|
||||
Data for additional, informative pairs (reference pairs) can be beneficial for some strategies.
|
||||
Ohlcv data for these pairs will be downloaded as part of the regular whitelist refresh process and is available via `DataProvider` just as other pairs (see above).
|
||||
These parts will **not** be traded unless they are also specified in the pair whitelist, or have been selected by Dynamic Whitelisting.
|
||||
|
||||
The pairs need to be specified as tuples in the format `("pair", "interval")`, with pair as the first and time interval as the second argument.
|
||||
|
||||
Sample:
|
||||
|
||||
``` python
|
||||
def informative_pairs(self):
|
||||
return [("ETH/USDT", "5m"),
|
||||
("BTC/TUSD", "15m"),
|
||||
]
|
||||
```
|
||||
|
||||
!!! Warning:
|
||||
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.
|
||||
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.
|
||||
|
||||
### Additional data - Wallets
|
||||
|
||||
The strategy provides access to the `Wallets` object. This contains the current balances on the exchange.
|
||||
|
||||
!!!NOTE:
|
||||
Wallets is not available during backtesting / hyperopt.
|
||||
|
||||
Please always check if `Wallets` is available to avoid failures during backtesting.
|
||||
|
||||
``` python
|
||||
if self.wallets:
|
||||
free_eth = self.wallets.get_free('ETH')
|
||||
used_eth = self.wallets.get_used('ETH')
|
||||
total_eth = self.wallets.get_total('ETH')
|
||||
```
|
||||
|
||||
#### Possible options for Wallets
|
||||
|
||||
- `get_free(asset)` - currently available balance to trade
|
||||
- `get_used(asset)` - currently tied up balance (open orders)
|
||||
- `get_total(asset)` - total available balance - sum of the 2 above
|
||||
|
||||
### Where is the default strategy?
|
||||
The default buy strategy is located in the file
|
||||
[freqtrade/default_strategy.py](https://github.com/gcarq/freqtrade/blob/develop/freqtrade/strategy/default_strategy.py).
|
||||
|
||||
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
|
||||
|
||||
If you want to use a strategy from a different folder you can pass `--strategy-path`
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy --strategy-path /some/folder
|
||||
```
|
||||
|
||||
### 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.
|
||||
Feel free to use any of them as inspiration for your own strategies.
|
||||
We're happy to accept Pull Requests containing new Strategies to that repo.
|
||||
|
||||
We also got a *strategy-sharing* channel in our [Slack community](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE) which is a great place to get and/or share ideas.
|
||||
|
||||
## Next step
|
||||
Now you have a perfect strategy you probably want to backtesting it.
|
||||
Your next step is to learn [How to use the Backtesting](https://github.com/gcarq/freqtrade/blob/develop/docs/backtesting.md).
|
||||
|
||||
Now you have a perfect strategy you probably want to backtest it.
|
||||
Your next step is to learn [How to use the Backtesting](backtesting.md).
|
||||
|
||||
@@ -1,45 +1,48 @@
|
||||
# Bot usage
|
||||
This page explains the difference parameters of the bot and how to run
|
||||
it.
|
||||
# Start the bot
|
||||
|
||||
This page explains the different parameters of the bot and how to run it.
|
||||
|
||||
## Table of Contents
|
||||
- [Bot commands](#bot-commands)
|
||||
- [Backtesting commands](#backtesting-commands)
|
||||
- [Hyperopt commands](#hyperopt-commands)
|
||||
|
||||
## Bot commands
|
||||
```
|
||||
usage: main.py [-h] [-c PATH] [-v] [--version] [--dynamic-whitelist [INT]]
|
||||
[--dry-run-db]
|
||||
{backtesting,hyperopt} ...
|
||||
|
||||
Simple High Frequency Trading Bot for crypto currencies
|
||||
```
|
||||
usage: main.py [-h] [-v] [--version] [-c PATH] [-d PATH] [-s NAME]
|
||||
[--strategy-path PATH] [--customhyperopt NAME]
|
||||
[--dynamic-whitelist [INT]] [--db-url PATH]
|
||||
{backtesting,edge,hyperopt} ...
|
||||
|
||||
Free, open source crypto trading bot
|
||||
|
||||
positional arguments:
|
||||
{backtesting,hyperopt}
|
||||
{backtesting,edge,hyperopt}
|
||||
backtesting backtesting module
|
||||
edge edge module
|
||||
hyperopt hyperopt module
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-v, --verbose be verbose
|
||||
--version show program's version number and exit
|
||||
-v, --verbose verbose mode (-vv for more, -vvv to get all messages)
|
||||
--version show program\'s version number and exit
|
||||
-c PATH, --config PATH
|
||||
specify configuration file (default: config.json)
|
||||
-d PATH, --datadir PATH
|
||||
path to backtest data
|
||||
-s NAME, --strategy NAME
|
||||
specify strategy class name (default: DefaultStrategy)
|
||||
--strategy-path PATH specify additional strategy lookup path
|
||||
--dry-run-db Force dry run to use a local DB
|
||||
"tradesv3.dry_run.sqlite" instead of memory DB. Work
|
||||
only if dry_run is enabled.
|
||||
--datadir PATH
|
||||
path to backtest data (default freqdata/tests/testdata
|
||||
--customhyperopt NAME
|
||||
specify hyperopt class name (default:
|
||||
DefaultHyperOpts)
|
||||
--dynamic-whitelist [INT]
|
||||
dynamically generate and update whitelist based on 24h
|
||||
BaseVolume (Default 20 currencies)
|
||||
BaseVolume (default: 20) DEPRECATED.
|
||||
--db-url PATH Override trades database URL, this is useful if
|
||||
dry_run is enabled or in custom deployments (default:
|
||||
None)
|
||||
```
|
||||
|
||||
### How to use a different config file?
|
||||
|
||||
The bot allows you to select which config file you want to use. Per
|
||||
default, the bot will load the file `./config.json`
|
||||
|
||||
@@ -47,7 +50,8 @@ default, the bot will load the file `./config.json`
|
||||
python3 ./freqtrade/main.py -c path/far/far/away/config.json
|
||||
```
|
||||
|
||||
### How to use --strategy?
|
||||
### How to use **--strategy**?
|
||||
|
||||
This parameter will allow you to load your custom strategy class.
|
||||
Per default without `--strategy` or `-s` the bot will load the
|
||||
`DefaultStrategy` included with the bot (`freqtrade/strategy/default_strategy.py`).
|
||||
@@ -59,6 +63,7 @@ To load a strategy, simply pass the class name (e.g.: `CustomStrategy`) in this
|
||||
**Example:**
|
||||
In `user_data/strategies` you have a file `my_awesome_strategy.py` which has
|
||||
a strategy class called `AwesomeStrategy` to load it:
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy
|
||||
```
|
||||
@@ -66,9 +71,10 @@ python3 ./freqtrade/main.py --strategy AwesomeStrategy
|
||||
If the bot does not find your strategy file, it will display in an error
|
||||
message the reason (File not found, or errors in your code).
|
||||
|
||||
Learn more about strategy file in [optimize your bot](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-optimization.md).
|
||||
Learn more about strategy file in [optimize your bot](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-optimization.md).
|
||||
|
||||
### How to use **--strategy-path**?
|
||||
|
||||
### How to use --strategy-path?
|
||||
This parameter allows you to add an additional strategy lookup path, which gets
|
||||
checked before the default locations (The passed path must be a folder!):
|
||||
```bash
|
||||
@@ -76,21 +82,28 @@ python3 ./freqtrade/main.py --strategy AwesomeStrategy --strategy-path /some/fol
|
||||
```
|
||||
|
||||
#### How to install a strategy?
|
||||
|
||||
This is very simple. Copy paste your strategy file into the folder
|
||||
`user_data/strategies` or use `--strategy-path`. And voila, the bot is ready to use it.
|
||||
|
||||
### How to use --dynamic-whitelist?
|
||||
### How to use **--dynamic-whitelist**?
|
||||
|
||||
!!! danger "DEPRECATED"
|
||||
Dynamic-whitelist is deprecated. Please move your configurations to the configuration as outlined [here](/configuration/#dynamic-pairlists)
|
||||
|
||||
Per default `--dynamic-whitelist` will retrieve the 20 currencies based
|
||||
on BaseVolume. This value can be changed when you run the script.
|
||||
|
||||
**By Default**
|
||||
Get the 20 currencies based on BaseVolume.
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py --dynamic-whitelist
|
||||
```
|
||||
|
||||
**Customize the number of currencies to retrieve**
|
||||
Get the 30 currencies based on BaseVolume.
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py --dynamic-whitelist 30
|
||||
```
|
||||
@@ -100,74 +113,141 @@ python3 ./freqtrade/main.py --dynamic-whitelist 30
|
||||
negative value (e.g -2), `--dynamic-whitelist` will use the default
|
||||
value (20).
|
||||
|
||||
### How to use --dry-run-db?
|
||||
### How to use **--db-url**?
|
||||
|
||||
When you run the bot in Dry-run mode, per default no transactions are
|
||||
stored in a database. If you want to store your bot actions in a DB
|
||||
using `--dry-run-db`. This command will use a separate database file
|
||||
`tradesv3.dry_run.sqlite`
|
||||
using `--db-url`. This can also be used to specify a custom database
|
||||
in production mode. Example command:
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py -c config.json --dry-run-db
|
||||
python3 ./freqtrade/main.py -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite
|
||||
```
|
||||
|
||||
|
||||
## Backtesting commands
|
||||
|
||||
Backtesting also uses the config specified via `-c/--config`.
|
||||
|
||||
```
|
||||
usage: freqtrade backtesting [-h] [-l] [-i INT] [--realistic-simulation]
|
||||
[-r]
|
||||
usage: main.py backtesting [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
||||
[--eps] [--dmmp] [-l] [-r]
|
||||
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
||||
[--export EXPORT] [--export-filename PATH]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||
specify ticker interval (1m, 5m, 30m, 1h, 1d)
|
||||
--timerange TIMERANGE
|
||||
specify what timerange of data to use.
|
||||
--eps, --enable-position-stacking
|
||||
Allow buying the same pair multiple times (position
|
||||
stacking)
|
||||
--dmmp, --disable-max-market-positions
|
||||
Disable applying `max_open_trades` during backtest
|
||||
(same as setting `max_open_trades` to a very high
|
||||
number)
|
||||
-l, --live using live data
|
||||
-i INT, --ticker-interval INT
|
||||
specify ticker interval in minutes (default: 5)
|
||||
--realistic-simulation
|
||||
uses max_open_trades from config to simulate real
|
||||
world limitations
|
||||
-r, --refresh-pairs-cached
|
||||
refresh the pairs files in tests/testdata with
|
||||
the latest data from Bittrex. Use it if you want
|
||||
to run your backtesting with up-to-date data.
|
||||
refresh the pairs files in tests/testdata with the
|
||||
latest data from the exchange. Use it if you want to
|
||||
run your backtesting with up-to-date data.
|
||||
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
|
||||
Provide a commaseparated list of strategies to
|
||||
backtest Please note that ticker-interval needs to be
|
||||
set either in config or via command line. When using
|
||||
this together with --export trades, the strategy-name
|
||||
is injected into the filename (so backtest-data.json
|
||||
becomes backtest-data-DefaultStrategy.json
|
||||
--export EXPORT export backtest results, argument are: trades Example
|
||||
--export=trades
|
||||
--export-filename PATH
|
||||
Save backtest results to this filename requires
|
||||
--export to be set as well Example --export-
|
||||
filename=user_data/backtest_data/backtest_today.json
|
||||
(default: user_data/backtest_data/backtest-
|
||||
result.json)
|
||||
```
|
||||
|
||||
### How to use --refresh-pairs-cached parameter?
|
||||
### How to use **--refresh-pairs-cached** parameter?
|
||||
|
||||
The first time your run Backtesting, it will take the pairs you have
|
||||
set in your config file and download data from Bittrex.
|
||||
|
||||
If for any reason you want to update your data set, you use
|
||||
`--refresh-pairs-cached` to force Backtesting to update the data it has.
|
||||
**Use it only if you want to update your data set. You will not be able
|
||||
to come back to the previous version.**
|
||||
|
||||
!!! Note
|
||||
Use it only if you want to update your data set. You will not be able to come back to the previous version.
|
||||
|
||||
To test your strategy with latest data, we recommend continuing using
|
||||
the parameter `-l` or `--live`.
|
||||
|
||||
|
||||
## Hyperopt commands
|
||||
|
||||
It is possible to use hyperopt for trading strategy optimization.
|
||||
Hyperopt uses an internal json config return by `hyperopt_optimize_conf()`
|
||||
located in `freqtrade/optimize/hyperopt_conf.py`.
|
||||
To optimize your strategy, you can use hyperopt parameter hyperoptimization
|
||||
to find optimal parameter values for your stategy.
|
||||
|
||||
```
|
||||
usage: freqtrade hyperopt [-h] [-e INT] [--use-mongodb]
|
||||
usage: freqtrade hyperopt [-h] [-i TICKER_INTERVAL] [--eps] [--dmmp]
|
||||
[--timerange TIMERANGE] [-e INT]
|
||||
[-s {all,buy,roi,stoploss} [{all,buy,roi,stoploss} ...]]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||
specify ticker interval (1m, 5m, 30m, 1h, 1d)
|
||||
--eps, --enable-position-stacking
|
||||
Allow buying the same pair multiple times (position
|
||||
stacking)
|
||||
--dmmp, --disable-max-market-positions
|
||||
Disable applying `max_open_trades` during backtest
|
||||
(same as setting `max_open_trades` to a very high
|
||||
number)
|
||||
--timerange TIMERANGE
|
||||
specify what timerange of data to use.
|
||||
--hyperopt PATH specify hyperopt file (default:
|
||||
freqtrade/optimize/default_hyperopt.py)
|
||||
-e INT, --epochs INT specify number of epochs (default: 100)
|
||||
--use-mongodb parallelize evaluations with mongodb (requires mongod
|
||||
in PATH)
|
||||
-s {all,buy,roi,stoploss} [{all,buy,roi,stoploss} ...], --spaces {all,buy,roi,stoploss} [{all,buy,roi,stoploss} ...]
|
||||
Specify which parameters to hyperopt. Space separate
|
||||
list. Default: all
|
||||
|
||||
```
|
||||
|
||||
## Edge commands
|
||||
|
||||
To know your trade expectacny and winrate against historical data, you can use Edge.
|
||||
|
||||
```
|
||||
usage: main.py edge [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE] [-r]
|
||||
[--stoplosses STOPLOSS_RANGE]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||
specify ticker interval (1m, 5m, 30m, 1h, 1d)
|
||||
--timerange TIMERANGE
|
||||
specify what timerange of data to use.
|
||||
-r, --refresh-pairs-cached
|
||||
refresh the pairs files in tests/testdata with the
|
||||
latest data from the exchange. Use it if you want to
|
||||
run your edge with up-to-date data.
|
||||
--stoplosses STOPLOSS_RANGE
|
||||
defines a range of stoploss against which edge will
|
||||
assess the strategythe format is "min,max,step"
|
||||
(without any space).example:
|
||||
--stoplosses=-0.01,-0.1,-0.001
|
||||
```
|
||||
|
||||
To understand edge and how to read the results, please read the [edge documentation](edge.md).
|
||||
|
||||
## A parameter missing in the configuration?
|
||||
|
||||
All parameters for `main.py`, `backtesting`, `hyperopt` are referenced
|
||||
in [misc.py](https://github.com/gcarq/freqtrade/blob/develop/freqtrade/misc.py#L84)
|
||||
in [misc.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/misc.py#L84)
|
||||
|
||||
## Next step
|
||||
The optimal strategy of the bot will change with time depending of the
|
||||
market trends. The next step is to
|
||||
[optimize your bot](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-optimization.md).
|
||||
|
||||
The optimal strategy of the bot will change with time depending of the market trends. The next step is to
|
||||
[optimize your bot](bot-optimization.md).
|
||||
|
||||
@@ -1,52 +1,114 @@
|
||||
# Configure the bot
|
||||
|
||||
This page explains how to configure your `config.json` file.
|
||||
|
||||
## Table of Contents
|
||||
- [Bot commands](#bot-commands)
|
||||
- [Backtesting commands](#backtesting-commands)
|
||||
- [Hyperopt commands](#hyperopt-commands)
|
||||
|
||||
## Setup config.json
|
||||
|
||||
We recommend to copy and use the `config.json.example` as a template
|
||||
for your bot configuration.
|
||||
|
||||
The table below will list all configuration parameters.
|
||||
|
||||
| Command | Default | Mandatory | Description |
|
||||
|----------|---------|----------|-------------|
|
||||
| `max_open_trades` | 3 | Yes | Number of trades open your bot will have.
|
||||
| `stake_currency` | BTC | Yes | Crypto-currency used for trading.
|
||||
| `stake_amount` | 0.05 | Yes | 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.
|
||||
| `ticker_interval` | [1, 5, 30, 60, 1440] | No | The ticker interval to use (1min, 5 min, 30 min, 1 hour or 1 day). Defaut is 5 minutes
|
||||
| `fiat_display_currency` | USD | Yes | Fiat currency used to show your profits. More information below.
|
||||
| `dry_run` | true | Yes | Define if the bot must be in Dry-run or production mode.
|
||||
| `minimal_roi` | See below | No | Set the threshold in percent the bot will use to sell a trade. More information below. If set, this parameter will override `minimal_roi` from your strategy file.
|
||||
| `stoploss` | -0.10 | No | Value of the stoploss in percent used by the bot. More information below. If set, this parameter will override `stoploss` from your strategy file.
|
||||
| `unfilledtimeout` | 0 | No | How long (in minutes) the bot will wait for an unfilled order to complete, after which the order will be cancelled.
|
||||
| `bid_strategy.ask_last_balance` | 0.0 | Yes | Set the bidding price. More information below.
|
||||
| `exchange.name` | bittrex | Yes | Name of the exchange class to use.
|
||||
| `exchange.key` | key | No | API key to use for the exchange. Only required when you are in production mode.
|
||||
| `exchange.secret` | secret | No | API secret to use for the exchange. Only required when you are in production mode.
|
||||
| `exchange.pair_whitelist` | [] | No | List of currency to use by the bot. Can be overrided with `--dynamic-whitelist` param.
|
||||
| `exchange.pair_blacklist` | [] | No | List of currency the bot must avoid. Useful when using `--dynamic-whitelist` param.
|
||||
| `experimental.use_sell_signal` | false | No | Use your sell strategy in addition of the `minimal_roi`.
|
||||
| `experimental.sell_profit_only` | false | No | waits until you have made a positive profit before taking a sell decision.
|
||||
| `telegram.enabled` | true | Yes | Enable or not the usage of Telegram.
|
||||
| `telegram.token` | token | No | Your Telegram bot token. Only required if `telegram.enabled` is `true`.
|
||||
| `telegram.chat_id` | chat_id | No | Your personal Telegram account id. Only required if `telegram.enabled` is `true`.
|
||||
| `initial_state` | running | No | Defines the initial application state. More information below.
|
||||
| `strategy` | DefaultStrategy | No | Defines Strategy class to use.
|
||||
| `strategy_path` | null | No | Adds an additional strategy lookup path (must be a folder).
|
||||
| `internals.process_throttle_secs` | 5 | Yes | Set the process throttle. Value in second.
|
||||
Mandatory Parameters are marked as **Required**.
|
||||
|
||||
The definition of each config parameters is in
|
||||
[misc.py](https://github.com/gcarq/freqtrade/blob/develop/freqtrade/misc.py#L205).
|
||||
| Command | Default | 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)
|
||||
| `stake_currency` | BTC | **Required.** Crypto-currency used for trading.
|
||||
| `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.
|
||||
| `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.
|
||||
| `ticker_interval` | [1m, 5m, 30m, 1h, 1d] | The ticker interval to use (1min, 5 min, 30 min, 1 hour or 1 day). Default is 5 minutes. [Strategy Override](#parameters-in-strategy).
|
||||
| `fiat_display_currency` | USD | **Required.** Fiat currency used to show your profits. More information below.
|
||||
| `dry_run` | true | **Required.** Define if the bot must be in Dry-run or production mode.
|
||||
| `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-strategy).
|
||||
| `minimal_roi` | See below | Set the threshold in percent the bot will use to sell a trade. More information below. [Strategy Override](#parameters-in-strategy).
|
||||
| `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-strategy).
|
||||
| `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-strategy).
|
||||
| `trailing_stop_positive` | 0 | Changes stop-loss once profit has been reached. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-strategy).
|
||||
| `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-strategy).
|
||||
| `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.
|
||||
| `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.
|
||||
| `bid_strategy.ask_last_balance` | 0.0 | **Required.** Set the bidding price. More information [below](#understand-ask_last_balance).
|
||||
| `bid_strategy.use_order_book` | false | Allows buying of pair using the rates in Order Book Bids.
|
||||
| `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.
|
||||
| `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. 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.
|
||||
| `ask_strategy.use_order_book` | false | Allows selling of open traded pair using the rates in Order Book Asks.
|
||||
| `ask_strategy.order_book_min` | 0 | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
||||
| `ask_strategy.order_book_max` | 0 | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
||||
| `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-strategy).
|
||||
| `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-strategy).
|
||||
| `exchange.name` | bittrex | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename).
|
||||
| `exchange.key` | key | API key to use for the exchange. Only required when you are in production mode.
|
||||
| `exchange.secret` | secret | API secret to use for the exchange. Only required when you are in production mode.
|
||||
| `exchange.pair_whitelist` | [] | List of currency to use by the bot. Can be overrided with `--dynamic-whitelist` param.
|
||||
| `exchange.pair_blacklist` | [] | List of currency the bot must avoid. Useful when using `--dynamic-whitelist` param.
|
||||
| `exchange.ccxt_rate_limit` | True | DEPRECATED!! Have CCXT handle Exchange rate limits. Depending on the exchange, having this to false can lead to temporary bans from the exchange.
|
||||
| `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.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)
|
||||
| `edge` | false | Please refer to [edge configuration document](edge.md) for detailed explanation.
|
||||
| `experimental.use_sell_signal` | false | Use your sell strategy in addition of the `minimal_roi`. [Strategy Override](#parameters-in-strategy).
|
||||
| `experimental.sell_profit_only` | false | Waits until you have made a positive profit before taking a sell decision. [Strategy Override](#parameters-in-strategy).
|
||||
| `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-strategy).
|
||||
| `pairlist.method` | StaticPairList | Use Static whitelist. [More information below](#dynamic-pairlists).
|
||||
| `pairlist.config` | None | Additional configuration for dynamic pairlists. [More information below](#dynamic-pairlists).
|
||||
| `telegram.enabled` | true | **Required.** Enable or not the usage of Telegram.
|
||||
| `telegram.token` | token | Your Telegram bot token. Only required if `telegram.enabled` is `true`.
|
||||
| `telegram.chat_id` | chat_id | Your personal Telegram account id. Only required if `telegram.enabled` is `true`.
|
||||
| `webhook.enabled` | false | Enable usage of Webhook notifications
|
||||
| `webhook.url` | false | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details.
|
||||
| `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.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.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.
|
||||
| `db_url` | `sqlite:///tradesv3.sqlite`| Declares database URL to use. NOTE: This defaults to `sqlite://` if `dry_run` is `True`.
|
||||
| `initial_state` | running | Defines the initial application state. More information below.
|
||||
| `forcebuy_enable` | false | Enables the RPC Commands to force a buy. More information below.
|
||||
| `strategy` | DefaultStrategy | Defines Strategy class to use.
|
||||
| `strategy_path` | null | Adds an additional strategy lookup path (must be a folder).
|
||||
| `internals.process_throttle_secs` | 5 | **Required.** Set the process throttle. Value in second.
|
||||
|
||||
### Parameters in strategy
|
||||
|
||||
The following parameters can be set in either configuration or strategy.
|
||||
Values in the configuration are always overwriting values set in the strategy.
|
||||
|
||||
* `minimal_roi`
|
||||
* `ticker_interval`
|
||||
* `stoploss`
|
||||
* `trailing_stop`
|
||||
* `trailing_stop_positive`
|
||||
* `trailing_stop_positive_offset`
|
||||
* `process_only_new_candles`
|
||||
* `order_types`
|
||||
* `order_time_in_force`
|
||||
* `use_sell_signal` (experimental)
|
||||
* `sell_profit_only` (experimental)
|
||||
* `ignore_roi_if_buy_signal` (experimental)
|
||||
|
||||
### Understand stake_amount
|
||||
|
||||
`stake_amount` is an amount of crypto-currency your bot will use for each trade.
|
||||
The minimal value is 0.0005. If there is not enough crypto-currency in
|
||||
the account an exception is generated.
|
||||
To allow the bot to trade all the available `stake_currency` in your account set
|
||||
|
||||
```json
|
||||
"stake_amount" : "unlimited",
|
||||
```
|
||||
|
||||
In this case a trade amount is calclulated as:
|
||||
|
||||
```python
|
||||
currency_balanse / (max_open_trades - current_open_trades)
|
||||
```
|
||||
|
||||
### Understand minimal_roi
|
||||
|
||||
`minimal_roi` is a JSON object where the key is a duration
|
||||
in minutes and the value is the minimum ROI in percent.
|
||||
See the example below:
|
||||
```
|
||||
|
||||
```json
|
||||
"minimal_roi": {
|
||||
"40": 0.0, # Sell after 40 minutes if the profit is not negative
|
||||
"30": 0.01, # Sell after 30 minutes if there is at least 1% profit
|
||||
@@ -60,6 +122,7 @@ value. This parameter is optional. If you use it, it will take over the
|
||||
`minimal_roi` value from the strategy file.
|
||||
|
||||
### Understand stoploss
|
||||
|
||||
`stoploss` 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.
|
||||
@@ -68,35 +131,129 @@ Most of the strategy files already include the optimal `stoploss`
|
||||
value. This parameter is optional. If you use it, it will take over the
|
||||
`stoploss` value from the strategy file.
|
||||
|
||||
### Understand trailing stoploss
|
||||
|
||||
Go to the [trailing stoploss Documentation](stoploss.md) for details on trailing stoploss.
|
||||
|
||||
### Understand initial_state
|
||||
|
||||
`initial_state` is an optional field that defines the initial application state.
|
||||
Possible values are `running` or `stopped`. (default=`running`)
|
||||
If the value is `stopped` the bot has to be started with `/start` first.
|
||||
|
||||
### Understand forcebuy_enable
|
||||
|
||||
`forcebuy_enable` enables the usage of forcebuy commands via Telegram.
|
||||
This is disabled for security reasons by default, and will show a warning message on startup if enabled.
|
||||
You send `/forcebuy ETH/BTC` to the bot, who buys the pair and holds it until a regular sell-signal appears (ROI, stoploss, /forcesell).
|
||||
|
||||
Can be dangerous with some strategies, so use with care
|
||||
See [the telegram documentation](telegram-usage.md) for details on usage.
|
||||
|
||||
### Understand process_throttle_secs
|
||||
|
||||
`process_throttle_secs` is an optional field that defines in seconds how long the bot should wait
|
||||
before asking the strategy if we should buy or a sell an asset. After each wait period, the strategy is asked again for
|
||||
every opened trade wether or not we should sell, and for all the remaining pairs (either the dynamic list of pairs or
|
||||
the static list of pairs) if we should buy.
|
||||
|
||||
### Understand ask_last_balance
|
||||
|
||||
`ask_last_balance` 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
|
||||
|
||||
`order_types` contains a dict mapping order-types to market-types as well as stoploss on or off exchange type and stoploss on exchange update interval in seconds. This allows to buy using limit orders, sell using limit-orders, and create stoploss orders using market. It also allows to set the stoploss "on exchange" which means stoploss order would be placed immediately once the buy order is fulfilled. In case stoploss on exchange and `trailing_stop` are both set, then the bot will use `stoploss_on_exchange_interval` to check it periodically and update it if necessary (e.x. in case of trailing stoploss).
|
||||
This can be set in the configuration or in the strategy. Configuration overwrites strategy configurations.
|
||||
|
||||
If this is configured, all 4 values (`"buy"`, `"sell"`, `"stoploss"` and `"stoploss_on_exchange"`) need to be present, otherwise the bot warn about it and will fail to start.
|
||||
The below is the default which is used if this is not configured in either Strategy or configuration.
|
||||
|
||||
```python
|
||||
"order_types": {
|
||||
"buy": "limit",
|
||||
"sell": "limit",
|
||||
"stoploss": "market",
|
||||
"stoploss_on_exchange": False,
|
||||
"stoploss_on_exchange_interval": 60
|
||||
},
|
||||
```
|
||||
|
||||
!!! Note
|
||||
Not all exchanges support "market" orders.
|
||||
The following message will be shown if your exchange does not support market orders: `"Exchange <yourexchange> does not support market orders."`
|
||||
|
||||
!!! Note
|
||||
stoploss on exchange interval is not mandatory. Do not change it's value if you are unsure of what you are doing. For more information about how stoploss works please read [the stoploss documentation](stoploss.md).
|
||||
|
||||
### Understand order_time_in_force
|
||||
`order_time_in_force` defines the policy by which the order is executed on the exchange. Three commonly used time in force are:<br/>
|
||||
**GTC (Goog Till Canceled):**
|
||||
This is most of the time the default time in force. It means the order will remain on exchange till it is canceled by user. It can be fully or partially fulfilled. If partially fulfilled, the remaining will stay on the exchange till cancelled.<br/>
|
||||
**FOK (Full Or Kill):**
|
||||
It means if the order is not executed immediately AND fully then it is canceled by the exchange.<br/>
|
||||
**IOC (Immediate Or Canceled):**
|
||||
It is the same as FOK (above) except it can be partially fulfilled. The remaining part is automatically cancelled by the exchange.
|
||||
<br/>
|
||||
`order_time_in_force` contains a dict buy and sell time in force policy. This can be set in the configuration or in the strategy. Configuration overwrites strategy configurations.<br/>
|
||||
possible values are: `gtc` (default), `fok` or `ioc`.<br/>
|
||||
``` python
|
||||
"order_time_in_force": {
|
||||
"buy": "gtc",
|
||||
"sell": "gtc"
|
||||
},
|
||||
```
|
||||
|
||||
!!! Warning
|
||||
This is an ongoing work. For now it is supported only for binance and only for buy orders. Please don't change the default value unless you know what you are doing.
|
||||
|
||||
### What values for exchange.name?
|
||||
|
||||
Freqtrade is based on [CCXT library](https://github.com/ccxt/ccxt) that supports 115 cryptocurrency
|
||||
exchange markets and trading APIs. The complete up-to-date list can be found in the
|
||||
[CCXT repo homepage](https://github.com/ccxt/ccxt/tree/master/python). However, the bot was tested
|
||||
with only Bittrex and Binance.
|
||||
|
||||
The bot was tested with the following exchanges:
|
||||
|
||||
- [Bittrex](https://bittrex.com/): "bittrex"
|
||||
- [Binance](https://www.binance.com/): "binance"
|
||||
|
||||
Feel free to test other exchanges and submit your PR to improve the bot.
|
||||
|
||||
### What values for fiat_display_currency?
|
||||
`fiat_display_currency` set the fiat to use for the conversion form coin to fiat in Telegram.
|
||||
The valid value are: "AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR", "USD".
|
||||
|
||||
`fiat_display_currency` set the base currency to use for the conversion from coin to fiat in Telegram.
|
||||
The valid values are:<br/>
|
||||
```json
|
||||
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR", "USD"
|
||||
```
|
||||
In addition to FIAT currencies, a range of cryto currencies are supported.
|
||||
The valid values are:
|
||||
```json
|
||||
"BTC", "ETH", "XRP", "LTC", "BCH", "USDT"
|
||||
```
|
||||
|
||||
## Switch to dry-run mode
|
||||
|
||||
We recommend starting the bot in dry-run mode to see how your bot will
|
||||
behave and how is the performance of your strategy. In Dry-run mode the
|
||||
bot does not engage your money. It only runs a live simulation without
|
||||
creating trades.
|
||||
|
||||
### To switch your bot in Dry-run mode:
|
||||
1. Edit your `config.json` file
|
||||
2. Switch dry-run to true
|
||||
2. Switch dry-run to true and specify db_url for a persistent db
|
||||
|
||||
```json
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.dryrun.sqlite",
|
||||
```
|
||||
|
||||
3. Remove your Bittrex API key (change them by fake api credentials)
|
||||
3. Remove your Exchange API key (change them by fake api credentials)
|
||||
|
||||
```json
|
||||
"exchange": {
|
||||
"name": "bittrex",
|
||||
@@ -109,20 +266,49 @@ creating trades.
|
||||
Once you will be happy with your bot performance, you can switch it to
|
||||
production mode.
|
||||
|
||||
### Dynamic Pairlists
|
||||
|
||||
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, a Static Pairlist is used (configured as `"pair_whitelist"` under the `"exchange"` section of this configuration).
|
||||
|
||||
**Available Pairlist methods:**
|
||||
|
||||
* `"StaticPairList"`
|
||||
* uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`
|
||||
* `"VolumePairList"`
|
||||
* Formerly available as `--dynamic-whitelist [<number_assets>]`
|
||||
* Selects `number_assets` top pairs based on `sort_key`, which can be one of `askVolume`, `bidVolume` and `quoteVolume`, defaults to `quoteVolume`.
|
||||
|
||||
```json
|
||||
"pairlist": {
|
||||
"method": "VolumePairList",
|
||||
"config": {
|
||||
"number_assets": 20,
|
||||
"sort_key": "quoteVolume"
|
||||
}
|
||||
},
|
||||
```
|
||||
|
||||
## Switch to production mode
|
||||
|
||||
In production mode, the bot will engage your money. Be careful a wrong
|
||||
strategy can lose all your money. Be aware of what you are doing when
|
||||
you run it in production mode.
|
||||
|
||||
### To switch your bot in production mode:
|
||||
1. Edit your `config.json` file
|
||||
### To switch your bot in production mode
|
||||
|
||||
**Edit your `config.json` file.**
|
||||
|
||||
**Switch dry-run to false and don't forget to adapt your database URL if set:**
|
||||
|
||||
2. Switch dry-run to false
|
||||
```json
|
||||
"dry_run": false,
|
||||
```
|
||||
|
||||
3. Insert your Bittrex API key (change them by fake api keys)
|
||||
**Insert your Exchange API key (change them by fake api keys):**
|
||||
|
||||
```json
|
||||
"exchange": {
|
||||
"name": "bittrex",
|
||||
@@ -130,11 +316,58 @@ you run it in production mode.
|
||||
"secret": "08a9dc6db3d7b53e1acebd9275677f4b0a04f1a5",
|
||||
...
|
||||
}
|
||||
```
|
||||
If you have not your Bittrex API key yet,
|
||||
[see our tutorial](https://github.com/gcarq/freqtrade/blob/develop/docs/pre-requisite.md).
|
||||
|
||||
```
|
||||
!!! Note
|
||||
If you have an exchange API key yet, [see our tutorial](/pre-requisite).
|
||||
|
||||
### 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.
|
||||
|
||||
An example for this can be found in `config_full.json.example`
|
||||
|
||||
``` json
|
||||
"ccxt_async_config": {
|
||||
"aiohttp_trust_env": true
|
||||
}
|
||||
```
|
||||
|
||||
Then, export your proxy settings using the variables `"HTTP_PROXY"` and `"HTTPS_PROXY"` set to the appropriate values
|
||||
|
||||
``` bash
|
||||
export HTTP_PROXY="http://addr:port"
|
||||
export HTTPS_PROXY="http://addr:port"
|
||||
freqtrade
|
||||
```
|
||||
|
||||
|
||||
### Embedding Strategies
|
||||
|
||||
FreqTrade provides you with with an easy way to embed the strategy into your configuration file.
|
||||
This is done by utilizing BASE64 encoding and providing this string at the strategy configuration field,
|
||||
in your chosen config file.
|
||||
|
||||
#### Encoding a string as BASE64
|
||||
|
||||
This is a quick example, how to generate the BASE64 string in python
|
||||
|
||||
```python
|
||||
from base64 import urlsafe_b64encode
|
||||
|
||||
with open(file, 'r') as f:
|
||||
content = f.read()
|
||||
content = urlsafe_b64encode(content.encode('utf-8'))
|
||||
```
|
||||
|
||||
The variable 'content', will contain the strategy file in a BASE64 encoded form. Which can now be set in your configurations file as following
|
||||
|
||||
```json
|
||||
"strategy": "NameOfStrategy:BASE64String"
|
||||
```
|
||||
|
||||
Please ensure that 'NameOfStrategy' is identical to the strategy name!
|
||||
|
||||
## Next step
|
||||
Now you have configured your config.json, the next step is to
|
||||
[start your bot](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-usage.md).
|
||||
|
||||
Now you have configured your config.json, the next step is to [start your bot](bot-usage.md).
|
||||
|
||||
117
docs/developer.md
Normal file
117
docs/developer.md
Normal file
@@ -0,0 +1,117 @@
|
||||
# Development Help
|
||||
|
||||
This page is intended for developers of FreqTrade, people who want to contribute to the FreqTrade codebase or documentation, or people who want to understand the source code of the application they're running.
|
||||
|
||||
All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We [track issues](https://github.com/freqtrade/freqtrade/issues) on [GitHub](https://github.com) and also have a dev channel in [slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE) where you can ask questions.
|
||||
|
||||
## Documentation
|
||||
|
||||
Documentation is available at [https://freqtrade.io](https://www.freqtrade.io/) and needs to be provided with every new feature PR.
|
||||
|
||||
Special fields for the documentation (like Note boxes, ...) can be found [here](https://squidfunk.github.io/mkdocs-material/extensions/admonition/).
|
||||
|
||||
## Developer setup
|
||||
|
||||
To configure a development environment, use best use the `setup.sh` script and answer "y" when asked "Do you want to install dependencies for dev [y/N]? ".
|
||||
Alternatively (if your system is not supported by the setup.sh script), follow the manual installation process and run `pip3 install -r requirements-dev.txt`.
|
||||
|
||||
This will install all required tools for development, including `pytest`, `flake8`, `mypy`, and `coveralls`.
|
||||
|
||||
## Modules
|
||||
|
||||
### Dynamic Pairlist
|
||||
|
||||
You have a great idea for a new pair selection algorithm you would like to try out? Great.
|
||||
Hopefully you also want to contribute this back upstream.
|
||||
|
||||
Whatever your motivations are - This should get you off the ground in trying to develop a new Pairlist provider.
|
||||
|
||||
First of all, have a look at the [VolumePairList](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/pairlist/VolumePairList.py) provider, and best copy this file with a name of your new Pairlist Provider.
|
||||
|
||||
This is a simple provider, which however serves as a good example on how to start developing.
|
||||
|
||||
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`.
|
||||
|
||||
```python
|
||||
self._freqtrade = freqtrade
|
||||
self._config = config
|
||||
self._whitelist = self._config['exchange']['pair_whitelist']
|
||||
self._blacklist = self._config['exchange'].get('pair_blacklist', [])
|
||||
```
|
||||
|
||||
|
||||
Now, let's step through the methods which require actions:
|
||||
|
||||
#### configuration
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
#### short_desc
|
||||
|
||||
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"`.
|
||||
|
||||
#### refresh_pairlist
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
##### sample
|
||||
|
||||
``` python
|
||||
def refresh_pairlist(self) -> None:
|
||||
# Generate dynamic whitelist
|
||||
pairs = self._gen_pair_whitelist(self._config['stake_currency'], self._sort_key)
|
||||
# Validate whitelist to only have active market pairs
|
||||
self._whitelist = self._validate_whitelist(pairs)[:self._number_pairs]
|
||||
```
|
||||
|
||||
#### _gen_pair_whitelist
|
||||
|
||||
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.
|
||||
|
||||
## Creating a release
|
||||
|
||||
This part of the documentation is aimed at maintainers, and shows how to create a release.
|
||||
|
||||
### create release branch
|
||||
|
||||
``` bash
|
||||
# make sure you're in develop branch
|
||||
git checkout develop
|
||||
|
||||
# create new branch
|
||||
git checkout -b new_release
|
||||
```
|
||||
|
||||
* edit `freqtrade/__init__.py` and add the desired version (for example `0.18.0`)
|
||||
* Commit this part
|
||||
* push that branch to the remote and create a PR
|
||||
|
||||
### create changelog from git commits
|
||||
|
||||
``` bash
|
||||
# Needs to be done before merging / pulling that branch.
|
||||
git log --oneline --no-decorate --no-merges master..develop
|
||||
```
|
||||
|
||||
### Create github release / tag
|
||||
|
||||
* Use the version-number specified as tag.
|
||||
* Use "master" as reference (this step comes after the above PR is merged).
|
||||
* use the above changelog as release comment (as codeblock)
|
||||
|
||||
### After-release
|
||||
|
||||
* update version in develop to next valid version and postfix that with `-dev` (`0.18.0 -> 0.18.1-dev`)
|
||||
212
docs/edge.md
Normal file
212
docs/edge.md
Normal file
@@ -0,0 +1,212 @@
|
||||
# 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.
|
||||
|
||||
!!! Warning
|
||||
Edge positioning is not compatible with dynamic whitelist. it overrides dynamic whitelist.
|
||||
|
||||
!!! Note
|
||||
Edge won't consider anything else than buy/sell/stoploss signals. So trailing stoploss, ROI, and everything else will be ignored in its calculation.
|
||||
|
||||
## Introduction
|
||||
Trading is all about probability. No one can claim that he has a strategy working all the time. You have to assume that sometimes you lose.<br/><br/>
|
||||
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 is quite boring, isn't it?<br/><br/>
|
||||
But let's say the probability that we have heads is 80%, and the probability that we have tails is 20%. Now it is becoming interesting ...
|
||||
That means 10$ x 80% versus 10$ x 20%. 8$ versus 2$. That means over time you will win 8$ risking only 2$ on each toss of coin.<br/><br/>
|
||||
Let's complicate it more: you win 80% of the time but only 2$, I win 20% of the time but 8$. The calculation is: 80% * 2$ versus 20% * 8$. It is becoming boring again because overtime you win $1.6$ (80% x 2$) and me $1.6 (20% * 8$) too.<br/><br/>
|
||||
The question is: How do you calculate that? how do you know if you wanna play?
|
||||
The answer comes to two factors:
|
||||
- Win Rate
|
||||
- Risk Reward Ratio
|
||||
|
||||
|
||||
### Win Rate
|
||||
Means over X trades 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)`
|
||||
|
||||
### Risk Reward Ratio
|
||||
Risk Reward Ratio is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose:
|
||||
|
||||
`R = Profit / Loss`
|
||||
|
||||
Over time, on many trades, you can calculate your risk reward by dividing your average profit on winning trades by your average loss on losing trades:
|
||||
|
||||
`Average profit = (Sum of profits) / (Number of winning trades)`
|
||||
|
||||
`Average loss = (Sum of losses) / (Number of losing trades)`
|
||||
|
||||
`R = (Average profit) / (Average loss)`
|
||||
|
||||
### Expectancy
|
||||
|
||||
At this point we can combine W and R to create an expectancy ratio. This is a simple process of multiplying the risk reward ratio by the percentage of winning trades, and subtracting the percentage of losing trades, which is calculated as follows:
|
||||
|
||||
Expectancy Ratio = (Risk Reward Ratio x Win Rate) – Loss Rate
|
||||
|
||||
So lets say your Win rate is 28% and your Risk Reward Ratio is 5:
|
||||
|
||||
`Expectancy = (5 * 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 losers. This is important for two reasons: First, it may seem obvious, but you know right away that you have a positive return. Second, you now have a number you can compare to other candidate systems to make decisions about which ones you employ.
|
||||
|
||||
It is important to remember that any system with an expectancy greater than 0 is profitable using past data. The key is finding one that will be profitable in the future.
|
||||
|
||||
You can also use this number to evaluate the effectiveness of modifications to this system.
|
||||
|
||||
**NOTICE:** It's important to keep in mind that Edge is testing your expectancy using historical data , there's no guarantee that you will have a similar edge in the future. It's still vital to do this testing in order to build confidence in your methodology, but be wary of "curve-fitting" your approach to the historical data as things are unlikely to play out the exact same way for future trades.
|
||||
|
||||
## 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 X trades for each stoploss. Here is an example:
|
||||
|
||||
| Pair | Stoploss | Win Rate | Risk Reward Ratio | Expectancy |
|
||||
|----------|:-------------:|-------------:|------------------:|-----------:|
|
||||
| XZC/ETH | -0.03 | 0.52 |1.359670 | 0.228 |
|
||||
| XZC/ETH | -0.01 | 0.50 |1.176384 | 0.088 |
|
||||
| XZC/ETH | -0.02 | 0.51 |1.115941 | 0.079 |
|
||||
|
||||
The goal here is to find the best stoploss for the strategy in order to have the maximum expectancy. In the above example stoploss at 3% leads to the maximum expectancy according to historical data.
|
||||
|
||||
Edge then forces stoploss to your strategy dynamically.
|
||||
|
||||
### Position size
|
||||
Edge dictates the stake amount for each trade to the bot according to the following factors:
|
||||
|
||||
- Allowed capital at risk
|
||||
- Stoploss
|
||||
|
||||
Allowed capital at risk is calculated as follows:
|
||||
|
||||
**allowed capital at risk** = **capital_available_percentage** X **allowed risk per trade**
|
||||
|
||||
**Stoploss** is calculated as described above against historical data.
|
||||
|
||||
Your position size then will be:
|
||||
|
||||
**position size** = **allowed capital at risk** / **stoploss**
|
||||
|
||||
Example:<br/>
|
||||
Let's say the stake currency is ETH and you have 10 ETH on the exchange, your **capital_available_percentage** is 50% and you would allow 1% of risk for each trade. thus your available capital for trading is **10 x 0.5 = 5 ETH** and allowed capital at risk would be **5 x 0.01 = 0.05 ETH**. <br/>
|
||||
Let's assume Edge has calculated that for **XLM/ETH** market your stoploss should be at 2%. So your position size will be **0.05 / 0.02 = 2.5ETH**.<br/>
|
||||
Bot takes a position of 2.5ETH on XLM/ETH (call it trade 1). Up next, you receive another buy signal while trade 1 is still open. This time on BTC/ETH market. Edge calculated stoploss for this market at 4%. So your position size would be 0.05 / 0.04 = 1.25ETH (call it trade 2).<br/>
|
||||
Note that available capital for trading didn’t change for trade 2 even if you had already trade 1. The available capital doesn’t mean the free amount on your wallet.<br/>
|
||||
Now you have two trades open. The Bot receives yet another buy signal for another market: **ADA/ETH**. This time the stoploss is calculated at 1%. So your position size is **0.05 / 0.01 = 5ETH**. But there are already 4ETH blocked in two previous trades. So the position size for this third trade would be 1ETH.<br/>
|
||||
Available capital doesn’t change before a position is sold. Let’s assume that trade 1 receives a sell signal and it is sold with a profit of 1ETH. Your total capital on exchange would be 11 ETH and the available capital for trading becomes 5.5ETH. <br/>
|
||||
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**.
|
||||
|
||||
## Configurations
|
||||
Edge has following configurations:
|
||||
|
||||
#### enabled
|
||||
If true, then Edge will run periodically.<br/>
|
||||
(default to false)
|
||||
|
||||
#### process_throttle_secs
|
||||
How often should Edge run in seconds? <br/>
|
||||
(default to 3600 so one hour)
|
||||
|
||||
#### calculate_since_number_of_days
|
||||
Number of days of data against which Edge calculates Win Rate, Risk Reward and Expectancy
|
||||
Note that it downloads historical data so increasing this number would lead to slowing down the bot.<br/>
|
||||
(default to 7)
|
||||
|
||||
#### capital_available_percentage
|
||||
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/>
|
||||
(default to 0.5)
|
||||
|
||||
#### allowed_risk
|
||||
Percentage of allowed risk per trade.<br/>
|
||||
(default to 0.01 [1%])
|
||||
|
||||
#### stoploss_range_min
|
||||
Minimum stoploss.<br/>
|
||||
(default to -0.01)
|
||||
|
||||
#### stoploss_range_max
|
||||
Maximum stoploss.<br/>
|
||||
(default 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. <br/>
|
||||
if you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10. <br/>
|
||||
(default to -0.01)
|
||||
|
||||
#### minimum_winrate
|
||||
It filters 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 favor of risk reward ratio.<br/>
|
||||
(default to 0.60)
|
||||
|
||||
#### minimum_expectancy
|
||||
It filters paris which have an expectancy lower than this number .
|
||||
Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return.<br/>
|
||||
(default to 0.20)
|
||||
|
||||
#### min_trade_number
|
||||
When calculating W and 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. <br/>
|
||||
(default 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.<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/>
|
||||
(default to 1 day, 1440 = 60 * 24)
|
||||
|
||||
#### 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/>
|
||||
(default to false)
|
||||
|
||||
|
||||
## Running Edge independently
|
||||
You can run Edge independently in order to see in details the result. Here is an example:
|
||||
```bash
|
||||
python3 ./freqtrade/main.py edge
|
||||
```
|
||||
|
||||
An example of its output:
|
||||
|
||||
| pair | stoploss | win rate | risk reward ratio | required risk reward | expectancy | total number of trades | average duration (min) |
|
||||
|:----------|-----------:|-----------:|--------------------:|-----------------------:|-------------:|-------------------------:|-------------------------:|
|
||||
| AGI/BTC | -0.02 | 0.64 | 5.86 | 0.56 | 3.41 | 14 | 54 |
|
||||
| NXS/BTC | -0.03 | 0.64 | 2.99 | 0.57 | 1.54 | 11 | 26 |
|
||||
| LEND/BTC | -0.02 | 0.82 | 2.05 | 0.22 | 1.50 | 11 | 36 |
|
||||
| VIA/BTC | -0.01 | 0.55 | 3.01 | 0.83 | 1.19 | 11 | 48 |
|
||||
| MTH/BTC | -0.09 | 0.56 | 2.82 | 0.80 | 1.12 | 18 | 52 |
|
||||
| ARDR/BTC | -0.04 | 0.42 | 3.14 | 1.40 | 0.73 | 12 | 42 |
|
||||
| BCPT/BTC | -0.01 | 0.71 | 1.34 | 0.40 | 0.67 | 14 | 30 |
|
||||
| WINGS/BTC | -0.02 | 0.56 | 1.97 | 0.80 | 0.65 | 27 | 42 |
|
||||
| VIBE/BTC | -0.02 | 0.83 | 0.91 | 0.20 | 0.59 | 12 | 35 |
|
||||
| MCO/BTC | -0.02 | 0.79 | 0.97 | 0.27 | 0.55 | 14 | 31 |
|
||||
| GNT/BTC | -0.02 | 0.50 | 2.06 | 1.00 | 0.53 | 18 | 24 |
|
||||
| HOT/BTC | -0.01 | 0.17 | 7.72 | 4.81 | 0.50 | 209 | 7 |
|
||||
| SNM/BTC | -0.03 | 0.71 | 1.06 | 0.42 | 0.45 | 17 | 38 |
|
||||
| APPC/BTC | -0.02 | 0.44 | 2.28 | 1.27 | 0.44 | 25 | 43 |
|
||||
| NEBL/BTC | -0.03 | 0.63 | 1.29 | 0.58 | 0.44 | 19 | 59 |
|
||||
|
||||
### Update cached pairs with the latest data
|
||||
```bash
|
||||
python3 ./freqtrade/main.py edge --refresh-pairs-cached
|
||||
```
|
||||
|
||||
### Precising stoploss range
|
||||
```bash
|
||||
python3 ./freqtrade/main.py edge --stoplosses=-0.01,-0.1,-0.001 #min,max,step
|
||||
```
|
||||
|
||||
### Advanced use of timerange
|
||||
```bash
|
||||
python3 ./freqtrade/main.py 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.
|
||||
|
||||
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 since 2018/01/31: --timerange=20180131-
|
||||
* Use tickframes since 2018/01/31 till 2018/03/01 : --timerange=20180131-20180301
|
||||
* Use tickframes between POSIX timestamps 1527595200 1527618600: --timerange=1527595200-1527618600
|
||||
@@ -27,7 +27,7 @@ like pauses. You can stop your bot, adjust settings and start it again.
|
||||
#### I want to improve the bot with a new strategy
|
||||
|
||||
That's great. We have a nice backtesting and hyperoptimizing setup. See
|
||||
the tutorial [here|Testing-new-strategies-with-Hyperopt](https://github.com/gcarq/freqtrade/blob/develop/docs/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?
|
||||
@@ -68,4 +68,3 @@ but it will give the idea. With only these triggers and guards there is
|
||||
already 8*10^9*10 evaluations. A roughly total of 80 billion evals.
|
||||
Did you run 100 000 evals? Congrats, you've done roughly 1 / 100 000 th
|
||||
of the search space.
|
||||
|
||||
|
||||
456
docs/hyperopt.md
456
docs/hyperopt.md
@@ -1,185 +1,188 @@
|
||||
# Hyperopt
|
||||
|
||||
This page explains how to tune your strategy by finding the optimal
|
||||
parameters with Hyperopt.
|
||||
parameters, a process called hyperparameter optimization. The bot uses several
|
||||
algorithms included in the `scikit-optimize` package to accomplish this. The
|
||||
search will burn all your CPU cores, make your laptop sound like a fighter jet
|
||||
and still take a long time.
|
||||
|
||||
## Table of Contents
|
||||
- [Prepare your Hyperopt](#prepare-hyperopt)
|
||||
- [1. Configure your Guards and Triggers](#1-configure-your-guards-and-triggers)
|
||||
- [2. Update the hyperopt config file](#2-update-the-hyperopt-config-file)
|
||||
- [Advanced Hyperopt notions](#advanced-notions)
|
||||
- [Understand the Guards and Triggers](#understand-the-guards-and-triggers)
|
||||
- [Execute Hyperopt](#execute-hyperopt)
|
||||
- [Hyperopt with MongoDB](#hyperopt-with-mongoDB)
|
||||
- [Understand the hyperopts result](#understand-the-backtesting-result)
|
||||
!!! Bug
|
||||
Hyperopt will crash when used with only 1 CPU Core as found out in [Issue #1133](https://github.com/freqtrade/freqtrade/issues/1133)
|
||||
|
||||
## Prepare Hyperopt
|
||||
Before we start digging in Hyperopt, we recommend you to take a look at
|
||||
your strategy file located into [user_data/strategies/](https://github.com/gcarq/freqtrade/blob/develop/user_data/strategies/test_strategy.py)
|
||||
## Prepare Hyperopting
|
||||
|
||||
### 1. Configure your Guards and Triggers
|
||||
There are two places you need to change in your strategy file to add a
|
||||
new buy strategy for testing:
|
||||
- Inside [populate_buy_trend()](https://github.com/gcarq/freqtrade/blob/develop/user_data/strategies/test_strategy.py#L278-L294).
|
||||
- Inside [hyperopt_space()](https://github.com/gcarq/freqtrade/blob/develop/user_data/strategies/test_strategy.py#L244-L297) known as `SPACE`.
|
||||
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/test_hyperopt.py)
|
||||
|
||||
There you have two different type of indicators: 1. `guards` and 2.
|
||||
`triggers`.
|
||||
1. Guards are conditions like "never buy if ADX < 10", or never buy if
|
||||
current price is over EMA10.
|
||||
2. Triggers are ones that actually trigger buy in specific moment, like
|
||||
"buy when EMA5 crosses over EMA10" or buy when close price touches lower
|
||||
bollinger band.
|
||||
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.
|
||||
|
||||
HyperOpt will, for each eval round, pick just ONE trigger, and possibly
|
||||
multiple guards. So that the constructed strategy will be something like
|
||||
### Checklist on all tasks / possibilities in hyperopt
|
||||
|
||||
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 `indicator_space` - for buy signal optimzation
|
||||
* fill `sell_strategy_generator` - for sell signal optimization
|
||||
* fill `sell_indicator_space` - for sell signal optimzation
|
||||
* fill `roi_space` - for ROI optimization
|
||||
* fill `generate_roi_table` - for ROI optimization (if you need more than 3 entries)
|
||||
* fill `stoploss_space` - stoploss optimization
|
||||
* Optional but recommended
|
||||
* 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
|
||||
|
||||
### 1. Install a Custom Hyperopt File
|
||||
|
||||
Put your hyperopt file into the folder`user_data/hyperopts`.
|
||||
|
||||
Let assume you want a hyperopt file `awesome_hyperopt.py`:
|
||||
Copy the file `user_data/hyperopts/sample_hyperopt.py` into `user_data/hyperopts/awesome_hyperopt.py`
|
||||
|
||||
### 2. Configure your Guards and Triggers
|
||||
|
||||
There are two places you need to change in your hyperopt file to add a new buy hyperopt for testing:
|
||||
|
||||
- Inside `indicator_space()` - the parameters hyperopt shall be optimizing.
|
||||
- Inside `populate_buy_trend()` - applying the parameters.
|
||||
|
||||
There you have two different types of indicators: 1. `guards` and 2. `triggers`.
|
||||
|
||||
1. Guards are conditions like "never buy if ADX < 10", or never buy if current price is over EMA10.
|
||||
2. Triggers are ones that actually trigger buy in specific moment, like "buy when EMA5 crosses over EMA10" or "buy when close price touches lower bollinger band".
|
||||
|
||||
Hyperoptimization will, for each eval round, pick one trigger and possibly
|
||||
multiple guards. The constructed strategy will be something like
|
||||
"*buy exactly when close price touches lower bollinger band, BUT only if
|
||||
ADX > 10*".
|
||||
|
||||
|
||||
If you have updated the buy strategy, means change the content of
|
||||
If you have updated the buy strategy, ie. changed the contents of
|
||||
`populate_buy_trend()` method you have to update the `guards` and
|
||||
`triggers` hyperopts must used.
|
||||
`triggers` hyperopts must use.
|
||||
|
||||
#### Sell optimization
|
||||
|
||||
Similar to the buy-signal above, sell-signals can also be optimized.
|
||||
Place the corresponding settings into the following methods
|
||||
|
||||
* Inside `sell_indicator_space()` - the parameters hyperopt shall be optimizing.
|
||||
* Inside `populate_sell_trend()` - applying the parameters.
|
||||
|
||||
The configuration and rules are the same than for buy signals.
|
||||
To avoid naming collisions in the search-space, please prefix all sell-spaces with `sell-`.
|
||||
|
||||
## Solving a Mystery
|
||||
|
||||
Let's say you are curious: should you use MACD crossings or lower Bollinger
|
||||
Bands to trigger your buys. And you also wonder should you use RSI or ADX to
|
||||
help with those buy decisions. If you decide to use RSI or ADX, which values
|
||||
should I use for them? So let's use hyperparameter optimization to solve this
|
||||
mystery.
|
||||
|
||||
We will start by defining a search space:
|
||||
|
||||
As for an example if your `populate_buy_trend()` method is:
|
||||
```python
|
||||
def populate_buy_trend(dataframe: DataFrame) -> DataFrame:
|
||||
dataframe.loc[
|
||||
(dataframe['rsi'] < 35) &
|
||||
(dataframe['adx'] > 65),
|
||||
'buy'] = 1
|
||||
|
||||
return dataframe
|
||||
def indicator_space() -> List[Dimension]:
|
||||
"""
|
||||
Define your Hyperopt space for searching strategy parameters
|
||||
"""
|
||||
return [
|
||||
Integer(20, 40, name='adx-value'),
|
||||
Integer(20, 40, name='rsi-value'),
|
||||
Categorical([True, False], name='adx-enabled'),
|
||||
Categorical([True, False], name='rsi-enabled'),
|
||||
Categorical(['bb_lower', 'macd_cross_signal'], name='trigger')
|
||||
]
|
||||
```
|
||||
|
||||
Your hyperopt file must contain `guards` to find the right value for
|
||||
`(dataframe['adx'] > 65)` & and `(dataframe['plus_di'] > 0.5)`. That
|
||||
means you will need to enable/disable triggers.
|
||||
Above definition says: I have five parameters I want you to randomly combine
|
||||
to find the best combination. Two of them are integer values (`adx-value`
|
||||
and `rsi-value`) and I want you test in the range of values 20 to 40.
|
||||
Then we have three category variables. First two are either `True` or `False`.
|
||||
We use these to either enable or disable the ADX and RSI guards. The last
|
||||
one we call `trigger` and use it to decide which buy trigger we want to use.
|
||||
|
||||
In our case the `SPACE` and `populate_buy_trend` in your strategy file
|
||||
will look like:
|
||||
```python
|
||||
space = {
|
||||
'rsi': hp.choice('rsi', [
|
||||
{'enabled': False},
|
||||
{'enabled': True, 'value': hp.quniform('rsi-value', 20, 40, 1)}
|
||||
]),
|
||||
'adx': hp.choice('adx', [
|
||||
{'enabled': False},
|
||||
{'enabled': True, 'value': hp.quniform('adx-value', 15, 50, 1)}
|
||||
]),
|
||||
'trigger': hp.choice('trigger', [
|
||||
{'type': 'lower_bb'},
|
||||
{'type': 'faststoch10'},
|
||||
{'type': 'ao_cross_zero'},
|
||||
{'type': 'ema5_cross_ema10'},
|
||||
{'type': 'macd_cross_signal'},
|
||||
{'type': 'sar_reversal'},
|
||||
{'type': 'stochf_cross'},
|
||||
{'type': 'ht_sine'},
|
||||
]),
|
||||
}
|
||||
So let's write the buy strategy using these values:
|
||||
|
||||
...
|
||||
``` python
|
||||
def populate_buy_trend(dataframe: DataFrame) -> DataFrame:
|
||||
conditions = []
|
||||
# GUARDS AND TRENDS
|
||||
if 'adx-enabled' in params and params['adx-enabled']:
|
||||
conditions.append(dataframe['adx'] > params['adx-value'])
|
||||
if 'rsi-enabled' in params and params['rsi-enabled']:
|
||||
conditions.append(dataframe['rsi'] < params['rsi-value'])
|
||||
|
||||
def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:
|
||||
conditions = []
|
||||
# GUARDS AND TRENDS
|
||||
if params['adx']['enabled']:
|
||||
conditions.append(dataframe['adx'] > params['adx']['value'])
|
||||
if params['rsi']['enabled']:
|
||||
conditions.append(dataframe['rsi'] < params['rsi']['value'])
|
||||
# TRIGGERS
|
||||
if 'trigger' in params:
|
||||
if params['trigger'] == 'bb_lower':
|
||||
conditions.append(dataframe['close'] < dataframe['bb_lowerband'])
|
||||
if params['trigger'] == 'macd_cross_signal':
|
||||
conditions.append(qtpylib.crossed_above(
|
||||
dataframe['macd'], dataframe['macdsignal']
|
||||
))
|
||||
|
||||
# TRIGGERS
|
||||
triggers = {
|
||||
'lower_bb': dataframe['tema'] <= dataframe['blower'],
|
||||
'faststoch10': (crossed_above(dataframe['fastd'], 10.0)),
|
||||
'ao_cross_zero': (crossed_above(dataframe['ao'], 0.0)),
|
||||
'ema5_cross_ema10': (crossed_above(dataframe['ema5'], dataframe['ema10'])),
|
||||
'macd_cross_signal': (crossed_above(dataframe['macd'], dataframe['macdsignal'])),
|
||||
'sar_reversal': (crossed_above(dataframe['close'], dataframe['sar'])),
|
||||
'stochf_cross': (crossed_above(dataframe['fastk'], dataframe['fastd'])),
|
||||
'ht_sine': (crossed_above(dataframe['htleadsine'], dataframe['htsine'])),
|
||||
}
|
||||
...
|
||||
dataframe.loc[
|
||||
reduce(lambda x, y: x & y, conditions),
|
||||
'buy'] = 1
|
||||
|
||||
return dataframe
|
||||
|
||||
return populate_buy_trend
|
||||
```
|
||||
|
||||
Hyperopting will now call this `populate_buy_trend` as many times you ask it (`epochs`)
|
||||
with different value combinations. It will then use the given historical data and make
|
||||
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.
|
||||
|
||||
### 2. Update the hyperopt config file
|
||||
Hyperopt is using a dedicated config file. Currently hyperopt
|
||||
cannot use your config file. It is also made on purpose to allow you
|
||||
testing your strategy with different configurations.
|
||||
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 objective function `calculate_loss` in `hyperopt.py`.
|
||||
|
||||
The Hyperopt configuration is located in
|
||||
[user_data/hyperopt_conf.py](https://github.com/gcarq/freqtrade/blob/develop/user_data/hyperopt_conf.py).
|
||||
|
||||
|
||||
## Advanced notions
|
||||
### Understand the Guards and Triggers
|
||||
When you need to add the new guards and triggers to be hyperopt
|
||||
parameters, you do this by adding them into the [hyperopt_space()](https://github.com/gcarq/freqtrade/blob/develop/user_data/strategies/test_strategy.py#L244-L297).
|
||||
|
||||
If it's a trigger, you add one line to the 'trigger' choice group and that's it.
|
||||
|
||||
If it's a guard, you will add a line like this:
|
||||
```
|
||||
'rsi': hp.choice('rsi', [
|
||||
{'enabled': False},
|
||||
{'enabled': True, 'value': hp.quniform('rsi-value', 20, 40, 1)}
|
||||
]),
|
||||
```
|
||||
This says, "*one of the guards is RSI, it can have two values, enabled or
|
||||
disabled. If it is enabled, try different values for it between 20 and 40*".
|
||||
|
||||
So, the part of the strategy builder using the above setting looks like
|
||||
this:
|
||||
|
||||
```
|
||||
if params['rsi']['enabled']:
|
||||
conditions.append(dataframe['rsi'] < params['rsi']['value'])
|
||||
```
|
||||
|
||||
It checks if Hyperopt wants the RSI guard to be enabled for this
|
||||
round `params['rsi']['enabled']` and if it is, then it will add a
|
||||
condition that says RSI must be smaller than the value hyperopt picked
|
||||
for this evaluation, which is given in the `params['rsi']['value']`.
|
||||
|
||||
That's it. Now you can add new parts of strategies to Hyperopt and it
|
||||
will try all the combinations with all different values in the search
|
||||
for best working algo.
|
||||
|
||||
|
||||
### Add a new Indicators
|
||||
If you want to test an indicator that isn't used by the bot currently,
|
||||
you need to add it to the `populate_indicators()` method in `hyperopt.py`.
|
||||
The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators.
|
||||
When you want to test an indicator that isn't used by the bot currently, remember to
|
||||
add it to the `populate_indicators()` method in `hyperopt.py`.
|
||||
|
||||
## Execute Hyperopt
|
||||
Once you have updated your hyperopt configuration you can run it.
|
||||
Because hyperopt tries a lot of combination to find the best parameters
|
||||
it will take time you will have the result (more than 30 mins).
|
||||
|
||||
We strongly recommend to use `screen` to prevent any connection loss.
|
||||
Once you have updated your hyperopt configuration you can run it.
|
||||
Because hyperopt tries a lot of combinations to find the best parameters it will take time you will have the result (more than 30 mins).
|
||||
|
||||
We strongly recommend to use `screen` or `tmux` to prevent any connection loss.
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py -c config.json hyperopt -e 5000
|
||||
python3 ./freqtrade/main.py --hyperopt <hyperoptname> -c config.json hyperopt -e 5000 --spaces all
|
||||
```
|
||||
|
||||
Use `<hyperoptname>` as the name of the custom hyperopt used.
|
||||
|
||||
The `-e` flag will set how many evaluations hyperopt will do. We recommend
|
||||
running at least several thousand evaluations.
|
||||
|
||||
### Execute hyperopt with different ticker-data source
|
||||
The `--spaces all` flag determines that all possible parameters should be optimized. Possibilities are listed below.
|
||||
|
||||
!!! Warning
|
||||
When switching parameters or changing configuration options, the file `user_data/hyperopt_results.pickle` should be removed. It's used to be able to continue interrupted calculations, but does not detect changes to settings or the hyperopt file.
|
||||
|
||||
### Execute Hyperopt with Different Ticker-Data Source
|
||||
|
||||
If you would like to hyperopt parameters using an alternate ticker data that
|
||||
you have on-disk, use the `--datadir PATH` option. Default hyperopt will
|
||||
use data from directory `user_data/data`.
|
||||
|
||||
### Running hyperopt with smaller testset
|
||||
Use the `--timeperiod` argument to change how much of the testset
|
||||
### Running Hyperopt with Smaller Testset
|
||||
|
||||
Use the `--timerange` argument to change how much of the testset
|
||||
you want to use. The last N ticks/timeframes will be used.
|
||||
Example:
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py hyperopt --timeperiod -200
|
||||
python3 ./freqtrade/main.py hyperopt --timerange -200
|
||||
```
|
||||
|
||||
### Running hyperopt with smaller search space
|
||||
### Running Hyperopt with Smaller Search Space
|
||||
|
||||
Use the `--spaces` argument to limit the search space used by hyperopt.
|
||||
Letting Hyperopt optimize everything is a huuuuge search space. Often it
|
||||
might make more sense to start by just searching for initial buy algorithm.
|
||||
@@ -190,126 +193,105 @@ Legal values are:
|
||||
|
||||
- `all`: optimize everything
|
||||
- `buy`: just search for a new buy strategy
|
||||
- `sell`: just search for a new sell strategy
|
||||
- `roi`: just optimize the minimal profit table for your strategy
|
||||
- `stoploss`: search for the best stoploss value
|
||||
- space-separated list of any of the above values for example `--spaces roi stoploss`
|
||||
|
||||
### Hyperopt with MongoDB
|
||||
Hyperopt with MongoDB, is like Hyperopt under steroids. As you saw by
|
||||
executing the previous command is the execution takes a long time.
|
||||
To accelerate it you can use hyperopt with MongoDB.
|
||||
## Understand the Hyperopt Result
|
||||
|
||||
To run hyperopt with MongoDb you will need 3 terminals.
|
||||
Once Hyperopt is completed you can use the result to create a new strategy.
|
||||
Given the following result from hyperopt:
|
||||
|
||||
**Terminal 1: Start MongoDB**
|
||||
```bash
|
||||
cd <freqtrade>
|
||||
source .env/bin/activate
|
||||
python3 scripts/start-mongodb.py
|
||||
```
|
||||
|
||||
**Terminal 2: Start Hyperopt worker**
|
||||
```bash
|
||||
cd <freqtrade>
|
||||
source .env/bin/activate
|
||||
python3 scripts/start-hyperopt-worker.py
|
||||
```
|
||||
|
||||
**Terminal 3: Start Hyperopt with MongoDB**
|
||||
```bash
|
||||
cd <freqtrade>
|
||||
source .env/bin/activate
|
||||
python3 ./freqtrade/main.py -c config.json hyperopt --use-mongodb
|
||||
```
|
||||
|
||||
**Re-run an Hyperopt**
|
||||
To re-run Hyperopt you have to delete the existing MongoDB table.
|
||||
```bash
|
||||
cd <freqtrade>
|
||||
rm -rf .hyperopt/mongodb/
|
||||
```
|
||||
|
||||
## Understand the hyperopts result
|
||||
Once Hyperopt is completed you can use the result to adding new buy
|
||||
signal. Given following result from hyperopt:
|
||||
```
|
||||
Best parameters:
|
||||
{
|
||||
"adx": {
|
||||
"enabled": true,
|
||||
"value": 15.0
|
||||
},
|
||||
"fastd": {
|
||||
"enabled": true,
|
||||
"value": 40.0
|
||||
},
|
||||
"green_candle": {
|
||||
"enabled": true
|
||||
},
|
||||
"mfi": {
|
||||
"enabled": false
|
||||
},
|
||||
"over_sar": {
|
||||
"enabled": false
|
||||
},
|
||||
"rsi": {
|
||||
"enabled": true,
|
||||
"value": 37.0
|
||||
},
|
||||
"trigger": {
|
||||
"type": "lower_bb"
|
||||
},
|
||||
"uptrend_long_ema": {
|
||||
"enabled": true
|
||||
},
|
||||
"uptrend_short_ema": {
|
||||
"enabled": false
|
||||
},
|
||||
"uptrend_sma": {
|
||||
"enabled": false
|
||||
}
|
||||
}
|
||||
|
||||
Best Result:
|
||||
2197 trades. Avg profit 1.84%. Total profit 0.79367541 BTC. Avg duration 241.0 mins.
|
||||
Best result:
|
||||
135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins.
|
||||
with values:
|
||||
{ 'adx-value': 44,
|
||||
'rsi-value': 29,
|
||||
'adx-enabled': False,
|
||||
'rsi-enabled': True,
|
||||
'trigger': 'bb_lower'}
|
||||
```
|
||||
|
||||
You should understand this result like:
|
||||
- You should **consider** the guard "adx" (`"adx"` is `"enabled": true`)
|
||||
and the best value is `15.0` (`"value": 15.0,`)
|
||||
- You should **consider** the guard "fastd" (`"fastd"` is `"enabled":
|
||||
true`) and the best value is `40.0` (`"value": 40.0,`)
|
||||
- You should **consider** to enable the guard "green_candle"
|
||||
(`"green_candle"` is `"enabled": true`) but this guards as no
|
||||
customizable value.
|
||||
- You should **ignore** the guard "mfi" (`"mfi"` is `"enabled": false`)
|
||||
- and so on...
|
||||
|
||||
- The buy trigger that worked best was `bb_lower`.
|
||||
- You should not use ADX because `adx-enabled: False`)
|
||||
- You should **consider** using the RSI indicator (`rsi-enabled: True` and the best value is `29.0` (`rsi-value: 29.0`)
|
||||
|
||||
You have to look inside your strategy file into `buy_strategy_generator()`
|
||||
method, what those values match to.
|
||||
|
||||
So for example you had `adx:` with the `value: 15.0` so we would look
|
||||
at `adx`-block, that translates to the following code block:
|
||||
So for example you had `rsi-value: 29.0` so we would look at `rsi`-block, that translates to the following code block:
|
||||
|
||||
```
|
||||
(dataframe['adx'] > 15.0)
|
||||
(dataframe['rsi'] < 29.0)
|
||||
```
|
||||
|
||||
Translating your whole hyperopt result to as the new buy-signal
|
||||
would be the following:
|
||||
```
|
||||
Translating your whole hyperopt result as the new buy-signal
|
||||
would then look like:
|
||||
|
||||
```python
|
||||
def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:
|
||||
dataframe.loc[
|
||||
(
|
||||
(dataframe['adx'] > 15.0) & # adx-value
|
||||
(dataframe['fastd'] < 40.0) & # fastd-value
|
||||
(dataframe['close'] > dataframe['open']) & # green_candle
|
||||
(dataframe['rsi'] < 37.0) & # rsi-value
|
||||
(dataframe['ema50'] > dataframe['ema100']) # uptrend_long_ema
|
||||
(dataframe['rsi'] < 29.0) & # rsi-value
|
||||
dataframe['close'] < dataframe['bb_lowerband'] # trigger
|
||||
),
|
||||
'buy'] = 1
|
||||
return dataframe
|
||||
```
|
||||
|
||||
## Next step
|
||||
### Understand Hyperopt ROI results
|
||||
|
||||
If you are optimizing ROI, you're result will look as follows and include a ROI table.
|
||||
|
||||
```
|
||||
Best result:
|
||||
135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins.
|
||||
with values:
|
||||
{ 'adx-value': 44,
|
||||
'rsi-value': 29,
|
||||
'adx-enabled': false,
|
||||
'rsi-enabled': True,
|
||||
'trigger': 'bb_lower',
|
||||
'roi_t1': 40,
|
||||
'roi_t2': 57,
|
||||
'roi_t3': 21,
|
||||
'roi_p1': 0.03634636907306948,
|
||||
'roi_p2': 0.055237357937802885,
|
||||
'roi_p3': 0.015163796015548354,
|
||||
'stoploss': -0.37996664668703606
|
||||
}
|
||||
ROI table:
|
||||
{ 0: 0.10674752302642071,
|
||||
21: 0.09158372701087236,
|
||||
78: 0.03634636907306948,
|
||||
118: 0}
|
||||
```
|
||||
|
||||
This would translate to the following ROI table:
|
||||
|
||||
``` python
|
||||
minimal_roi = {
|
||||
"118": 0,
|
||||
"78": 0.0363463,
|
||||
"21": 0.0915,
|
||||
"0": 0.106
|
||||
}
|
||||
```
|
||||
|
||||
### Validate backtest result
|
||||
|
||||
Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.
|
||||
To archive the same results (number of trades, ...) than during hyperopt, please use the command line flag `--disable-max-market-positions`.
|
||||
This setting is the default for hyperopt for speed reasons. You can overwrite this in the configuration by setting `"position_stacking"=false` or by changing the relevant line in your hyperopt file [here](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/optimize/hyperopt.py#L283).
|
||||
|
||||
!!! Note:
|
||||
Dry/live runs will **NOT** use position stacking - therefore it does make sense to also validate the strategy without this as it's closer to reality.
|
||||
|
||||
## Next Step
|
||||
|
||||
Now you have a perfect bot and want to control it from Telegram. Your
|
||||
next step is to learn the [Telegram usage](https://github.com/gcarq/freqtrade/blob/develop/docs/telegram-usage.md).
|
||||
next step is to learn the [Telegram usage](telegram-usage.md).
|
||||
|
||||
BIN
docs/images/logo.png
Normal file
BIN
docs/images/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
@@ -1,32 +1,67 @@
|
||||
# freqtrade documentation
|
||||
Welcome to freqtrade documentation. Please feel free to contribute to
|
||||
this documentation if you see it became outdated by sending us a
|
||||
Pull-request. Do not hesitate to reach us on
|
||||
[Slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE)
|
||||
if you do not find the answer to your questions.
|
||||
# Freqtrade
|
||||
[](https://travis-ci.org/freqtrade/freqtrade)
|
||||
[](https://coveralls.io/github/freqtrade/freqtrade?branch=develop)
|
||||
[](https://codeclimate.com/github/freqtrade/freqtrade/maintainability)
|
||||
|
||||
## Table of Contents
|
||||
- [Pre-requisite](https://github.com/gcarq/freqtrade/blob/develop/docs/pre-requisite.md)
|
||||
- [Setup your Bittrex account](https://github.com/gcarq/freqtrade/blob/develop/docs/pre-requisite.md#setup-your-bittrex-account)
|
||||
- [Setup your Telegram bot](https://github.com/gcarq/freqtrade/blob/develop/docs/pre-requisite.md#setup-your-telegram-bot)
|
||||
- [Bot Installation](https://github.com/gcarq/freqtrade/blob/develop/docs/installation.md)
|
||||
- [Install with Docker (all platforms)](https://github.com/gcarq/freqtrade/blob/develop/docs/installation.md#docker)
|
||||
- [Install on Linux Ubuntu](https://github.com/gcarq/freqtrade/blob/develop/docs/installation.md#21-linux---ubuntu-1604)
|
||||
- [Install on MacOS](https://github.com/gcarq/freqtrade/blob/develop/docs/installation.md#23-macos-installation)
|
||||
- [Install on Windows](https://github.com/gcarq/freqtrade/blob/develop/docs/installation.md#windows)
|
||||
- [Bot Configuration](https://github.com/gcarq/freqtrade/blob/develop/docs/configuration.md)
|
||||
- [Bot usage (Start your bot)](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-usage.md)
|
||||
- [Bot commands](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-usage.md#bot-commands)
|
||||
- [Backtesting commands](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-usage.md#backtesting-commands)
|
||||
- [Hyperopt commands](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-usage.md#hyperopt-commands)
|
||||
- [Bot Optimization](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-optimization.md)
|
||||
- [Change your strategy](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-optimization.md#change-your-strategy)
|
||||
- [Add more Indicator](https://github.com/gcarq/freqtrade/blob/develop/docs/bot-optimization.md#add-more-indicator)
|
||||
- [Test your strategy with Backtesting](https://github.com/gcarq/freqtrade/blob/develop/docs/backtesting.md)
|
||||
- [Find optimal parameters with Hyperopt](https://github.com/gcarq/freqtrade/blob/develop/docs/hyperopt.md)
|
||||
- [Control the bot with telegram](https://github.com/gcarq/freqtrade/blob/develop/docs/telegram-usage.md)
|
||||
- [Contribute to the project](https://github.com/gcarq/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||
- [How to contribute](https://github.com/gcarq/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||
- [Run tests & Check PEP8 compliance](https://github.com/gcarq/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||
- [FAQ](https://github.com/gcarq/freqtrade/blob/develop/docs/faq.md)
|
||||
- [SQL cheatsheet](https://github.com/gcarq/freqtrade/blob/develop/docs/sql_cheatsheet.md)
|
||||
<!-- Place this tag where you want the button to render. -->
|
||||
<a class="github-button" href="https://github.com/freqtrade/freqtrade" data-icon="octicon-star" data-size="large" aria-label="Star freqtrade/freqtrade on GitHub">Star</a>
|
||||
<!-- Place this tag where you want the button to render. -->
|
||||
<a class="github-button" href="https://github.com/freqtrade/freqtrade/fork" data-icon="octicon-repo-forked" data-size="large" aria-label="Fork freqtrade/freqtrade on GitHub">Fork</a>
|
||||
<!-- Place this tag where you want the button to render. -->
|
||||
<a class="github-button" href="https://github.com/freqtrade/freqtrade/archive/master.zip" data-icon="octicon-cloud-download" data-size="large" aria-label="Download freqtrade/freqtrade on GitHub">Download</a>
|
||||
<!-- Place this tag where you want the button to render. -->
|
||||
<a class="github-button" href="https://github.com/freqtrade" data-size="large" aria-label="Follow @freqtrade on GitHub">Follow @freqtrade</a>
|
||||
## Introduction
|
||||
Freqtrade is a cryptocurrency trading bot written in Python.
|
||||
|
||||
!!! 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.
|
||||
|
||||
Always start by running a trading bot in Dry-run and do not engage money before you understand how it works and what profit/loss you should expect.
|
||||
|
||||
We strongly recommend you to have coding and Python knowledge. Do not hesitate to read the source code and understand the mechanism of this bot.
|
||||
|
||||
|
||||
## Features
|
||||
- Based on Python 3.6+: For botting on any operating system - Windows, macOS and Linux
|
||||
- Persistence: Persistence is achieved through sqlite
|
||||
- Dry-run: Run the bot without playing money.
|
||||
- Backtesting: Run a simulation of your buy/sell strategy.
|
||||
- Strategy Optimization by machine learning: Use machine learning to optimize your buy/sell strategy parameters with real exchange data.
|
||||
- Edge position sizing Calculate your win rate, risk reward ratio, the best stoploss and adjust your position size before taking a position for each specific market. Learn more
|
||||
- Whitelist crypto-currencies: Select which crypto-currency you want to trade or use dynamic whitelists.
|
||||
- Blacklist crypto-currencies: Select which crypto-currency you want to avoid.
|
||||
- Manageable via Telegram: Manage the bot with Telegram
|
||||
- Display profit/loss in fiat: Display your profit/loss in 33 fiat.
|
||||
- Daily summary of profit/loss: Provide a daily summary of your profit/loss.
|
||||
- Performance status report: Provide a performance status of your current trades.
|
||||
|
||||
|
||||
## Requirements
|
||||
### Uptodate clock
|
||||
The clock must be accurate, syncronized to a NTP server very frequently to avoid problems with communication to the exchanges.
|
||||
|
||||
### Hardware requirements
|
||||
To run this bot we recommend you a cloud instance with a minimum of:
|
||||
|
||||
- 2GB RAM
|
||||
- 1GB disk space
|
||||
- 2vCPU
|
||||
|
||||
### Software requirements
|
||||
- Python 3.6.x
|
||||
- pip
|
||||
- git
|
||||
- TA-Lib
|
||||
- virtualenv (Recommended)
|
||||
- Docker (Recommended)
|
||||
|
||||
|
||||
## Support
|
||||
Help / Slack
|
||||
For any questions not covered by the documentation or for further information about the bot, we encourage you to join our slack channel.
|
||||
|
||||
Click [here](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE) to join Slack channel.
|
||||
|
||||
## Ready to try?
|
||||
Begin by reading our installation guide [here](installation).
|
||||
@@ -1,26 +1,69 @@
|
||||
# Installation
|
||||
|
||||
This page explains how to prepare your environment for running the bot.
|
||||
|
||||
To understand how to set up the bot please read the [Bot Configuration](https://github.com/gcarq/freqtrade/blob/develop/docs/configuration.md) page.
|
||||
## Prerequisite
|
||||
Before running your bot in production you will need to setup few
|
||||
external API. In production mode, the bot required valid Bittrex API
|
||||
credentials and a Telegram bot (optional but recommended).
|
||||
|
||||
## Table of Contents
|
||||
- [Setup your exchange account](#setup-your-exchange-account)
|
||||
- [Backtesting commands](#setup-your-telegram-bot)
|
||||
|
||||
* [Table of Contents](#table-of-contents)
|
||||
* [Easy Installation - Linux Script](#easy-installation---linux-script)
|
||||
* [Automatic Installation - Docker](#automatic-installation---docker)
|
||||
* [Custom Linux MacOS Installation](#custom-installation)
|
||||
- [Requirements](#requirements)
|
||||
- [Linux - Ubuntu 16.04](#linux---ubuntu-1604)
|
||||
- [MacOS](#macos)
|
||||
- [Setup Config and virtual env](#setup-config-and-virtual-env)
|
||||
* [Windows](#windows)
|
||||
### Setup your exchange account
|
||||
*To be completed, please feel free to complete this section.*
|
||||
|
||||
### Setup your Telegram bot
|
||||
The only things you need is a working Telegram bot and its API token.
|
||||
Below we explain how to create your Telegram Bot, and how to get your
|
||||
Telegram user id.
|
||||
|
||||
<!-- /TOC -->
|
||||
### 1. Create your Telegram bot
|
||||
|
||||
------
|
||||
**1.1. Start a chat with https://telegram.me/BotFather**
|
||||
|
||||
**1.2. Send the message `/newbot`. ** *BotFather response:*
|
||||
```
|
||||
Alright, a new bot. How are we going to call it? Please choose a name for your bot.
|
||||
```
|
||||
|
||||
**1.3. Choose the public name of your bot (e.x. `Freqtrade bot`)**
|
||||
*BotFather response:*
|
||||
```
|
||||
Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.
|
||||
```
|
||||
**1.4. Choose the name id of your bot (e.x "`My_own_freqtrade_bot`")**
|
||||
|
||||
**1.5. Father bot will return you the token (API key)**<br/>
|
||||
Copy it and keep it you will use it for the config parameter `token`.
|
||||
*BotFather response:*
|
||||
```hl_lines="4"
|
||||
Done! Congratulations on your new bot. You will find it at t.me/My_own_freqtrade_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.
|
||||
|
||||
Use this token to access the HTTP API:
|
||||
521095879:AAEcEZEL7ADJ56FtG_qD0bQJSKETbXCBCi0
|
||||
|
||||
For a description of the Bot API, see this page: https://core.telegram.org/bots/api
|
||||
```
|
||||
**1.6. Don't forget to start the conversation with your bot, by clicking /START button**
|
||||
|
||||
### 2. Get your user id
|
||||
**2.1. Talk to https://telegram.me/userinfobot**
|
||||
|
||||
**2.2. Get your "Id", you will use it for the config parameter
|
||||
`chat_id`.**
|
||||
<hr/>
|
||||
## Quick start
|
||||
Freqtrade provides a Linux/MacOS script to install all dependencies and help you to configure the bot.
|
||||
|
||||
```bash
|
||||
git clone git@github.com:freqtrade/freqtrade.git
|
||||
cd freqtrade
|
||||
git checkout develop
|
||||
./setup.sh --install
|
||||
```
|
||||
!!! Note
|
||||
Windows installation is explained [here](#windows).
|
||||
<hr/>
|
||||
## Easy Installation - Linux Script
|
||||
|
||||
If you are on Debian, Ubuntu or MacOS a freqtrade provides a script to Install, Update, Configure, and Reset your bot.
|
||||
@@ -34,21 +77,26 @@ usage:
|
||||
-c,--config Easy config generator (Will override your existing file).
|
||||
```
|
||||
|
||||
### --install
|
||||
** --install **
|
||||
|
||||
This script will install everything you need to run the bot:
|
||||
|
||||
* Mandatory software as: `Python3`, `ta-lib`, `wget`
|
||||
* Setup your virtualenv
|
||||
* Configure your `config.json` file
|
||||
|
||||
This script is a combination of `install script` `--reset`, `--config`
|
||||
|
||||
### --update
|
||||
** --update **
|
||||
|
||||
Update parameter will pull the last version of your current branch and update your virtualenv.
|
||||
|
||||
### --reset
|
||||
** --reset **
|
||||
|
||||
Reset parameter will hard reset your branch (only if you are on `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`.
|
||||
|
||||
------
|
||||
@@ -63,57 +111,86 @@ Start by downloading Docker for your platform:
|
||||
|
||||
Once you have Docker installed, simply create the config file (e.g. `config.json`) and then create a Docker image for `freqtrade` using the Dockerfile in this repo.
|
||||
|
||||
|
||||
### 1. Prepare the Bot
|
||||
|
||||
#### 1.1. Clone the git repository
|
||||
**1.1. Clone the git repository**
|
||||
|
||||
Linux/Mac/Windows with WSL
|
||||
```bash
|
||||
git clone https://github.com/gcarq/freqtrade.git
|
||||
git clone https://github.com/freqtrade/freqtrade.git
|
||||
```
|
||||
|
||||
#### 1.2. (Optional) Checkout the develop branch
|
||||
Windows with docker
|
||||
```bash
|
||||
git clone --config core.autocrlf=input https://github.com/freqtrade/freqtrade.git
|
||||
```
|
||||
|
||||
**1.2. (Optional) Checkout the develop branch**
|
||||
|
||||
```bash
|
||||
git checkout develop
|
||||
```
|
||||
|
||||
#### 1.3. Go into the new directory
|
||||
**1.3. Go into the new directory**
|
||||
|
||||
```bash
|
||||
cd freqtrade
|
||||
```
|
||||
|
||||
#### 1.4. Copy `config.json.example` to `config.json`
|
||||
**1.4. Copy `config.json.example` to `config.json`**
|
||||
|
||||
```bash
|
||||
cp -n config.json.example config.json
|
||||
```
|
||||
|
||||
> To edit the config please refer to the [Bot Configuration](https://github.com/gcarq/freqtrade/blob/develop/docs/configuration.md) page.
|
||||
> To edit the config please refer to the [Bot Configuration](configuration.md) page.
|
||||
|
||||
#### 1.5. Create your database file *(optional - the bot will create it if it is missing)*
|
||||
**1.5. Create your database file *(optional - the bot will create it if it is missing)**
|
||||
|
||||
Production
|
||||
|
||||
```bash
|
||||
touch tradesv3.sqlite
|
||||
````
|
||||
|
||||
Dry-Run
|
||||
|
||||
```bash
|
||||
touch tradesv3.dryrun.sqlite
|
||||
```
|
||||
|
||||
### 2. Download or build the docker image
|
||||
|
||||
### 2. Build the Docker image
|
||||
Either use the prebuilt image from docker hub - or build the image yourself if you would like more control on which version is used.
|
||||
|
||||
Branches / tags available can be checked out on [Dockerhub](https://hub.docker.com/r/freqtradeorg/freqtrade/tags/).
|
||||
|
||||
**2.1. Download the docker image**
|
||||
|
||||
Pull the image from docker hub and (optionally) change the name of the image
|
||||
|
||||
```bash
|
||||
docker pull freqtradeorg/freqtrade:develop
|
||||
# Optionally tag the repository so the run-commands remain shorter
|
||||
docker tag freqtradeorg/freqtrade:develop freqtrade
|
||||
```
|
||||
|
||||
To update the image, simply run the above commands again and restart your running container.
|
||||
|
||||
**2.2. Build the Docker image**
|
||||
|
||||
```bash
|
||||
cd freqtrade
|
||||
docker build -t freqtrade .
|
||||
```
|
||||
|
||||
For security reasons, your configuration file will not be included in the image, you will need to bind mount it. It is also advised to bind mount an SQLite database file (see the "5. Run a restartable docker image" section) to keep it between updates.
|
||||
If you are developing using Docker, use `Dockerfile.develop` to build a dev Docker image, which will also set up develop dependencies:
|
||||
|
||||
```bash
|
||||
docker build -f ./Dockerfile.develop -t freqtrade-dev .
|
||||
```
|
||||
|
||||
For security reasons, your configuration file will not be included in the image, you will need to bind mount it. It is also advised to bind mount an SQLite database file (see the "5. Run a restartable docker image" section) to keep it between updates.
|
||||
|
||||
### 3. Verify the Docker image
|
||||
|
||||
@@ -123,7 +200,6 @@ After the build process you can verify that the image was created with:
|
||||
docker images
|
||||
```
|
||||
|
||||
|
||||
### 4. Run the Docker image
|
||||
|
||||
You can run a one-off container that is immediately deleted upon exiting with the following command (`config.json` must be in the current working directory):
|
||||
@@ -132,14 +208,21 @@ You can run a one-off container that is immediately deleted upon exiting with th
|
||||
docker run --rm -v /etc/localtime:/etc/localtime:ro -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
||||
```
|
||||
|
||||
In this example, the database will be created inside the docker instance and will be lost when you will refresh your image.
|
||||
There is known issue in OSX Docker versions after 17.09.1, whereby /etc/localtime cannot be shared causing Docker to not start. A work-around for this is to start with the following cmd.
|
||||
|
||||
```bash
|
||||
docker run --rm -e TZ=`ls -la /etc/localtime | cut -d/ -f8-9` -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
||||
```
|
||||
|
||||
More information on this docker issue and work-around can be read [here](https://github.com/docker/for-mac/issues/2396).
|
||||
|
||||
In this example, the database will be created inside the docker instance and will be lost when you will refresh your image.
|
||||
|
||||
### 5. Run a restartable docker image
|
||||
|
||||
To run a restartable instance in the background (feel free to place your configuration and database files wherever it feels comfortable on your filesystem).
|
||||
|
||||
#### 5.1. Move your config file and database
|
||||
**5.1. Move your config file and database**
|
||||
|
||||
```bash
|
||||
mkdir ~/.freqtrade
|
||||
@@ -147,7 +230,7 @@ mv config.json ~/.freqtrade
|
||||
mv tradesv3.sqlite ~/.freqtrade
|
||||
```
|
||||
|
||||
#### 5.2. Run the docker image
|
||||
**5.2. Run the docker image**
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
@@ -155,10 +238,12 @@ docker run -d \
|
||||
-v /etc/localtime:/etc/localtime:ro \
|
||||
-v ~/.freqtrade/config.json:/freqtrade/config.json \
|
||||
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
||||
freqtrade
|
||||
freqtrade --db-url sqlite:///tradesv3.sqlite
|
||||
```
|
||||
|
||||
If you are using `dry_run=True` it's not necessary to mount `tradesv3.sqlite`, but you can mount `tradesv3.dryrun.sqlite` if you plan to use the dry run mode with the param `--dry-run-db`.
|
||||
!!! Note
|
||||
db-url defaults to `sqlite:///tradesv3.sqlite` but it defaults to `sqlite://` if `dry_run=True` is being used.
|
||||
To override this behaviour use a custom db-url value: i.e.: `--db-url sqlite:///tradesv3.dryrun.sqlite`
|
||||
|
||||
### 6. Monitor your Docker instance
|
||||
|
||||
@@ -172,27 +257,51 @@ docker stop freqtrade
|
||||
docker start freqtrade
|
||||
```
|
||||
|
||||
You do not need to rebuild the image for configuration changes, it will suffice to edit `config.json` and restart the container.
|
||||
For more information on how to operate Docker, please refer to the [official Docker documentation](https://docs.docker.com/).
|
||||
|
||||
!!! Note
|
||||
You do not need to rebuild the image for configuration changes, it will suffice to edit `config.json` and restart the container.
|
||||
|
||||
### 7. Backtest with docker
|
||||
|
||||
The following assumes that the above steps (1-4) have been completed successfully.
|
||||
Also, backtest-data should be available at `~/.freqtrade/user_data/`.
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name freqtrade \
|
||||
-v /etc/localtime:/etc/localtime:ro \
|
||||
-v ~/.freqtrade/config.json:/freqtrade/config.json \
|
||||
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
||||
-v ~/.freqtrade/user_data/:/freqtrade/user_data/ \
|
||||
freqtrade --strategy AwsomelyProfitableStrategy backtesting
|
||||
```
|
||||
|
||||
Head over to the [Backtesting Documentation](backtesting.md) for more details.
|
||||
|
||||
!!! Note
|
||||
Additional parameters can be appended after the image name (`freqtrade` in the above example).
|
||||
|
||||
------
|
||||
|
||||
## Custom Installation
|
||||
|
||||
We've included/collected install instructions for Ubuntu 16.04, MacOS, and Windows. These are guidelines and your success may vary with other distros.
|
||||
OS Specific steps are listed first, the [Common](#common) section below is necessary for all systems.
|
||||
|
||||
### Requirements
|
||||
|
||||
Click each one for install guide:
|
||||
* [Python 3.6.x](http://docs.python-guide.org/en/latest/starting/installation/), note the bot was not tested on Python >= 3.7.x
|
||||
|
||||
* [Python >= 3.6.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
||||
* [pip](https://pip.pypa.io/en/stable/installing/)
|
||||
* [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
* [virtualenv](https://virtualenv.pypa.io/en/stable/installation/) (Recommended)
|
||||
* [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html)
|
||||
|
||||
|
||||
### Linux - Ubuntu 16.04
|
||||
|
||||
#### 1. Install Python 3.6, Git, and wget
|
||||
#### Install Python 3.6, Git, and wget
|
||||
|
||||
```bash
|
||||
sudo add-apt-repository ppa:jonathonf/python-3.6
|
||||
@@ -200,7 +309,39 @@ sudo apt-get update
|
||||
sudo apt-get install python3.6 python3.6-venv python3.6-dev build-essential autoconf libtool pkg-config make wget git
|
||||
```
|
||||
|
||||
#### 2. Install TA-Lib
|
||||
#### 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 that miniconda3 is installed and available in your environment. Last miniconda3 installation file use python 3.4, we will update to python 3.6 on this installation.
|
||||
It's recommended to use (mini)conda for this as installation/compilation of `numpy`, `scipy` and `pandas` takes a long time.
|
||||
If you have installed it from (mini)conda, you can remove `numpy`, `scipy`, and `pandas` from `requirements.txt` before you install it with `pip`.
|
||||
|
||||
Additional package to install on your Raspbian, `libffi-dev` required by cryptography (from python-telegram-bot).
|
||||
|
||||
``` bash
|
||||
conda config --add channels rpi
|
||||
conda install python=3.6
|
||||
conda create -n freqtrade python=3.6
|
||||
conda activate freqtrade
|
||||
conda install scipy pandas numpy
|
||||
|
||||
sudo apt install libffi-dev
|
||||
python3 -m pip install -r requirements.txt
|
||||
python3 -m pip install -e .
|
||||
```
|
||||
|
||||
### MacOS
|
||||
|
||||
#### Install Python 3.6, git and wget
|
||||
|
||||
```bash
|
||||
brew install python3 git wget
|
||||
```
|
||||
|
||||
### Common
|
||||
|
||||
#### 1. Install TA-Lib
|
||||
|
||||
Official webpage: https://mrjbq7.github.io/ta-lib/install.html
|
||||
|
||||
@@ -208,42 +349,75 @@ Official webpage: https://mrjbq7.github.io/ta-lib/install.html
|
||||
wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz
|
||||
tar xvzf ta-lib-0.4.0-src.tar.gz
|
||||
cd ta-lib
|
||||
./configure --prefix=/usr
|
||||
sed -i.bak "s|0.00000001|0.000000000000000001 |g" src/ta_func/ta_utility.h
|
||||
./configure --prefix=/usr/local
|
||||
make
|
||||
make install
|
||||
sudo make install
|
||||
cd ..
|
||||
rm -rf ./ta-lib*
|
||||
```
|
||||
|
||||
#### 3. [Optional] Install MongoDB
|
||||
!!! Note
|
||||
An already downloaded version of ta-lib is included in the repository, as the sourceforge.net source seems to have problems frequently.
|
||||
|
||||
Install MongoDB if you plan to optimize your strategy with Hyperopt.
|
||||
#### 2. Setup your Python virtual environment (virtualenv)
|
||||
|
||||
!!! Note
|
||||
This step is optional but strongly recommended to keep your system organized
|
||||
|
||||
```bash
|
||||
sudo apt-get install mongodb-org
|
||||
python3 -m venv .env
|
||||
source .env/bin/activate
|
||||
```
|
||||
|
||||
> Complete tutorial from Digital Ocean: [How to Install MongoDB on Ubuntu 16.04](https://www.digitalocean.com/community/tutorials/how-to-install-mongodb-on-ubuntu-16-04).
|
||||
|
||||
#### 4. Install FreqTrade
|
||||
#### 3. Install FreqTrade
|
||||
|
||||
Clone the git repository:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/gcarq/freqtrade.git
|
||||
git clone https://github.com/freqtrade/freqtrade.git
|
||||
|
||||
```
|
||||
|
||||
Optionally checkout the develop branch:
|
||||
Optionally checkout the stable/master branch:
|
||||
|
||||
```bash
|
||||
git checkout develop
|
||||
git checkout master
|
||||
```
|
||||
|
||||
#### 5. Configure `freqtrade` as a `systemd` service
|
||||
#### 4. Initialize the configuration
|
||||
|
||||
```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
|
||||
pip3 install --upgrade pip
|
||||
pip3 install -r requirements.txt
|
||||
pip3 install -e .
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```bash
|
||||
python3.6 ./freqtrade/main.py -c config.json
|
||||
```
|
||||
|
||||
*Note*: If you run the bot on a server, you should consider using [Docker](#automatic-installation---docker) 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
|
||||
|
||||
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.
|
||||
|
||||
After that you can start the daemon with:
|
||||
|
||||
```bash
|
||||
systemctl --user start freqtrade
|
||||
```
|
||||
@@ -254,97 +428,57 @@ For this to be persistent (run when user is logged out) you'll need to enable `l
|
||||
sudo loginctl enable-linger "$USER"
|
||||
```
|
||||
|
||||
|
||||
### MacOS
|
||||
|
||||
#### 1. Install Python 3.6, git, wget and ta-lib
|
||||
|
||||
```bash
|
||||
brew install python3 git wget ta-lib
|
||||
```
|
||||
|
||||
#### 2. [Optional] Install MongoDB
|
||||
|
||||
Install MongoDB if you plan to optimize your strategy with Hyperopt.
|
||||
|
||||
```bash
|
||||
curl -O https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-3.4.10.tgz
|
||||
tar -zxvf mongodb-osx-ssl-x86_64-3.4.10.tgz
|
||||
mkdir -p <path_freqtrade>/env/mongodb
|
||||
cp -R -n mongodb-osx-x86_64-3.4.10/ <path_freqtrade>/env/mongodb
|
||||
export PATH=<path_freqtrade>/env/mongodb/bin:$PATH
|
||||
```
|
||||
|
||||
#### 3. Install FreqTrade
|
||||
|
||||
Clone the git repository:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/gcarq/freqtrade.git
|
||||
```
|
||||
|
||||
Optionally checkout the develop branch:
|
||||
|
||||
```bash
|
||||
git checkout develop
|
||||
```
|
||||
|
||||
|
||||
### Setup Config and virtual env
|
||||
|
||||
#### 1. Initialize the configuration
|
||||
|
||||
```bash
|
||||
cd freqtrade
|
||||
cp config.json.example config.json
|
||||
```
|
||||
|
||||
> *To edit the config please refer to [Bot Configuration](https://github.com/gcarq/freqtrade/blob/develop/docs/configuration.md).*
|
||||
|
||||
|
||||
#### 2. Setup your Python virtual environment (virtualenv)
|
||||
|
||||
```bash
|
||||
python3.6 -m venv .env
|
||||
source .env/bin/activate
|
||||
pip3.6 install --upgrade pip
|
||||
pip3.6 install -r requirements.txt
|
||||
pip3.6 install -e .
|
||||
```
|
||||
|
||||
#### 3. 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.
|
||||
|
||||
```bash
|
||||
python3.6 ./freqtrade/main.py -c config.json
|
||||
```
|
||||
|
||||
------
|
||||
|
||||
## Windows
|
||||
|
||||
We recommend that Windows users use [Docker](#docker) as this will work
|
||||
much easier and smoother (also more secure).
|
||||
We recommend that Windows users use [Docker](#docker) as this will work much easier and smoother (also more secure).
|
||||
|
||||
### Install freqtrade
|
||||
If that is not possible, try using the Windows Linux subsystem (WSL) - for which the Ubuntu instructions should work.
|
||||
If that is not available on your system, feel free to try the instructions below, which led to success for some.
|
||||
|
||||
### Install freqtrade manually
|
||||
|
||||
#### Clone the git repository
|
||||
|
||||
```bash
|
||||
git clone https://github.com/freqtrade/freqtrade.git
|
||||
```
|
||||
|
||||
copy paste `config.json` to ``\path\freqtrade-develop\freqtrade`
|
||||
|
||||
#### Install ta-lib
|
||||
|
||||
Install ta-lib according to the [ta-lib documentation](https://github.com/mrjbq7/ta-lib#windows).
|
||||
|
||||
As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial precompiled windows Wheels [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib), which needs to be downloaded and installed using `pip install TA_Lib‑0.4.17‑cp36‑cp36m‑win32.whl` (make sure to use the version matching your python version)
|
||||
|
||||
```cmd
|
||||
>cd \path\freqtrade-develop
|
||||
>python -m venv .env
|
||||
>cd .env\Scripts
|
||||
>activate.bat
|
||||
>cd \path\freqtrade-develop
|
||||
REM optionally install ta-lib from wheel
|
||||
REM >pip install TA_Lib‑0.4.17‑cp36‑cp36m‑win32.whl
|
||||
>pip install -r requirements.txt
|
||||
>pip install -e .
|
||||
>cd freqtrade
|
||||
>python main.py
|
||||
>python freqtrade\main.py
|
||||
```
|
||||
|
||||
> Thanks [Owdr](https://github.com/Owdr) for the commands. Source: [Issue #222](https://github.com/gcarq/freqtrade/issues/222)
|
||||
> Thanks [Owdr](https://github.com/Owdr) for the commands. Source: [Issue #222](https://github.com/freqtrade/freqtrade/issues/222)
|
||||
|
||||
#### Error during installation under Windows
|
||||
|
||||
``` bash
|
||||
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
|
||||
```
|
||||
|
||||
Unfortunately, many packages requiring compilation don't provide a pre-build wheel. It is therefore mandatory to have a C/C++ compiler installed and available for your python environment to use.
|
||||
|
||||
The easiest way is to download install Microsoft Visual Studio Community [here](https://visualstudio.microsoft.com/downloads/) and make sure to install "Common Tools for Visual C++" to enable building c code on Windows. Unfortunately, this is a heavy download / dependency (~4Gb) so you might want to consider WSL or docker first.
|
||||
|
||||
---
|
||||
|
||||
Now you have an environment ready, the next step is
|
||||
[Bot Configuration](https://github.com/gcarq/freqtrade/blob/develop/docs/configuration.md)...
|
||||
[Bot Configuration](configuration.md).
|
||||
|
||||
52
docs/partials/header.html
Normal file
52
docs/partials/header.html
Normal file
@@ -0,0 +1,52 @@
|
||||
<header class="md-header" data-md-component="header">
|
||||
<nav class="md-header-nav md-grid">
|
||||
<div class="md-flex">
|
||||
<div class="md-flex__cell md-flex__cell--shrink">
|
||||
<a href="{{ config.site_url | default(nav.homepage.url, true) | url }}" title="{{ config.site_name }}"
|
||||
class="md-header-nav__button md-logo">
|
||||
{% if config.theme.logo.icon %}
|
||||
<i class="md-icon">{{ config.theme.logo.icon }}</i>
|
||||
{% else %}
|
||||
<img src="{{ config.theme.logo | url }}" width="24" height="24">
|
||||
{% endif %}
|
||||
</a>
|
||||
</div>
|
||||
<div class="md-flex__cell md-flex__cell--shrink">
|
||||
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
|
||||
</div>
|
||||
<div class="md-flex__cell md-flex__cell--stretch">
|
||||
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
|
||||
{% block site_name %}
|
||||
{% if config.site_name == page.title %}
|
||||
{{ config.site_name }}
|
||||
{% else %}
|
||||
<span class="md-header-nav__topic">
|
||||
{{ config.site_name }}
|
||||
</span>
|
||||
<span class="md-header-nav__topic">
|
||||
{{ page.title }}
|
||||
</span>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="md-flex__cell md-flex__cell--shrink">
|
||||
{% block search_box %}
|
||||
{% if "search" in config["plugins"] %}
|
||||
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
|
||||
{% include "partials/search.html" %}
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
</div>
|
||||
{% if config.repo_url %}
|
||||
<div class="md-flex__cell md-flex__cell--shrink">
|
||||
<div class="md-header-nav__source">
|
||||
{% include "partials/source.html" %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</nav>
|
||||
<!-- Place this tag in your head or just before your close body tag. -->
|
||||
<script async defer src="https://buttons.github.io/buttons.js"></script>
|
||||
</header>
|
||||
@@ -1,10 +1,6 @@
|
||||
# Plotting
|
||||
This page explains how to plot prices, indicator, profits.
|
||||
|
||||
## Table of Contents
|
||||
- [Plot price and indicators](#plot-price-and-indicators)
|
||||
- [Plot profit](#plot-profit)
|
||||
|
||||
## Installation
|
||||
|
||||
Plotting scripts use Plotly library. Install/upgrade it with:
|
||||
@@ -19,30 +15,45 @@ At least version 2.3.0 is required.
|
||||
Usage for the price plotter:
|
||||
|
||||
```
|
||||
script/plot_dataframe.py [-h] [-p pair] [--live]
|
||||
script/plot_dataframe.py [-h] [-p pairs] [--live]
|
||||
```
|
||||
|
||||
Example
|
||||
```
|
||||
python scripts/plot_dataframe.py -p BTC_ETH
|
||||
python scripts/plot_dataframe.py -p BTC/ETH
|
||||
```
|
||||
|
||||
The `-p` pair argument, can be used to specify what
|
||||
pair you would like to plot.
|
||||
The `-p` pairs argument, can be used to specify
|
||||
pairs you would like to plot.
|
||||
|
||||
**Advanced use**
|
||||
|
||||
To plot multiple pairs, separate them with a comma:
|
||||
```
|
||||
python scripts/plot_dataframe.py -p BTC/ETH,XRP/ETH
|
||||
```
|
||||
|
||||
To plot the current live price use the `--live` flag:
|
||||
```
|
||||
python scripts/plot_dataframe.py -p BTC_ETH --live
|
||||
python scripts/plot_dataframe.py -p BTC/ETH --live
|
||||
```
|
||||
|
||||
To plot a timerange (to zoom in):
|
||||
```
|
||||
python scripts/plot_dataframe.py -p BTC_ETH --timerange=100-200
|
||||
python scripts/plot_dataframe.py -p BTC/ETH --timerange=100-200
|
||||
```
|
||||
Timerange doesn't work with live data.
|
||||
|
||||
To plot trades stored in a database use `--db-url` argument:
|
||||
```
|
||||
python scripts/plot_dataframe.py --db-url sqlite:///tradesv3.dry_run.sqlite -p BTC/ETH
|
||||
```
|
||||
|
||||
To plot a test strategy the strategy should have first be backtested.
|
||||
The results may then be plotted with the -s argument:
|
||||
```
|
||||
python scripts/plot_dataframe.py -s Strategy_Name -p BTC/ETH --datadir user_data/data/<exchange_name>/
|
||||
```
|
||||
|
||||
## Plot profit
|
||||
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
# Pre-requisite
|
||||
Before running your bot in production you will need to setup few
|
||||
external API. In production mode, the bot required valid Bittrex API
|
||||
credentials and a Telegram bot (optional but recommended).
|
||||
|
||||
## Table of Contents
|
||||
- [Setup your Bittrex account](#setup-your-bittrex-account)
|
||||
- [Backtesting commands](#setup-your-telegram-bot)
|
||||
|
||||
## Setup your Bittrex account
|
||||
*To be completed, please feel free to complete this section.*
|
||||
|
||||
## Setup your Telegram bot
|
||||
The only things you need is a working Telegram bot and its API token.
|
||||
Below we explain how to create your Telegram Bot, and how to get your
|
||||
Telegram user id.
|
||||
|
||||
### 1. Create your Telegram bot
|
||||
**1.1. Start a chat with https://telegram.me/BotFather**
|
||||
**1.2. Send the message** `/newbot`
|
||||
*BotFather response:*
|
||||
```
|
||||
Alright, a new bot. How are we going to call it? Please choose a name for your bot.
|
||||
```
|
||||
**1.3. Choose the public name of your bot (e.g "`Freqtrade bot`")**
|
||||
*BotFather response:*
|
||||
```
|
||||
Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.
|
||||
```
|
||||
**1.4. Choose the name id of your bot (e.g "`My_own_freqtrade_bot`")**
|
||||
**1.5. Father bot will return you the token (API key)**
|
||||
Copy it and keep it you will use it for the config parameter `token`.
|
||||
*BotFather response:*
|
||||
```
|
||||
Done! Congratulations on your new bot. You will find it at t.me/My_own_freqtrade_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.
|
||||
|
||||
Use this token to access the HTTP API:
|
||||
521095879:AAEcEZEL7ADJ56FtG_qD0bQJSKETbXCBCi0
|
||||
|
||||
For a description of the Bot API, see this page: https://core.telegram.org/bots/api
|
||||
```
|
||||
**1.6. Don't forget to start the conversation with your bot, by clicking /START button**
|
||||
|
||||
### 2. Get your user id
|
||||
**2.1. Talk to https://telegram.me/userinfobot**
|
||||
**2.2. Get your "Id", you will use it for the config parameter
|
||||
`chat_id`.**
|
||||
|
||||
1
docs/requirements-docs.txt
Normal file
1
docs/requirements-docs.txt
Normal file
@@ -0,0 +1 @@
|
||||
mkdocs-material==3.1.0
|
||||
141
docs/sandbox-testing.md
Normal file
141
docs/sandbox-testing.md
Normal file
@@ -0,0 +1,141 @@
|
||||
# Sandbox API testing
|
||||
|
||||
Where an exchange provides a sandbox for risk-free integration, or end-to-end, testing CCXT provides access to these.
|
||||
|
||||
This document is a *light overview of configuring Freqtrade and GDAX sandbox.
|
||||
This can be useful to developers and trader alike as Freqtrade is quite customisable.
|
||||
|
||||
When testing your API connectivity, make sure to use the following URLs.
|
||||
***Website**
|
||||
https://public.sandbox.gdax.com
|
||||
***REST API**
|
||||
https://api-public.sandbox.gdax.com
|
||||
|
||||
---
|
||||
|
||||
# Configure a Sandbox account on Gdax
|
||||
|
||||
Aim of this document section
|
||||
|
||||
- An sanbox account
|
||||
- create 2FA (needed to create an API)
|
||||
- Add test 50BTC to account
|
||||
- Create :
|
||||
- - API-KEY
|
||||
- - API-Secret
|
||||
- - API Password
|
||||
|
||||
## Acccount
|
||||
|
||||
This link will redirect to the sandbox main page to login / create account dialogues:
|
||||
https://public.sandbox.pro.coinbase.com/orders/
|
||||
|
||||
After registration and Email confimation you wil be redirected into your sanbox account. It is easy to verify you're in sandbox by checking the URL bar.
|
||||
> https://public.sandbox.pro.coinbase.com/
|
||||
|
||||
## Enable 2Fa (a prerequisite to creating sandbox API Keys)
|
||||
|
||||
From within sand box site select your profile, top right.
|
||||
>Or as a direct link: https://public.sandbox.pro.coinbase.com/profile
|
||||
|
||||
From the menu panel to the left of the screen select
|
||||
|
||||
> Security: "*View or Update*"
|
||||
|
||||
In the new site select "enable authenticator" as typical google Authenticator.
|
||||
|
||||
- open Google Authenticator on your phone
|
||||
- scan barcode
|
||||
- enter your generated 2fa
|
||||
|
||||
## Enable API Access
|
||||
|
||||
From within sandbox select profile>api>create api-keys
|
||||
>or as a direct link: https://public.sandbox.pro.coinbase.com/profile/api
|
||||
|
||||
Click on "create one" and ensure **view** and **trade** are "checked" and sumbit your 2FA
|
||||
|
||||
- **Copy and paste the Passphase** into a notepade this will be needed later
|
||||
- **Copy and paste the API Secret** popup into a notepad this will needed later
|
||||
- **Copy and paste the API Key** into a notepad this will needed later
|
||||
|
||||
## Add 50 BTC test funds
|
||||
|
||||
To add funds, use the web interface deposit and withdraw buttons.
|
||||
|
||||
To begin select 'Wallets' from the top menu.
|
||||
> Or as a direct link: https://public.sandbox.pro.coinbase.com/wallets
|
||||
|
||||
- Deposits (bottom left of screen)
|
||||
- - Deposit Funds Bitcoin
|
||||
- - - Coinbase BTC Wallet
|
||||
- - - - Max (50 BTC)
|
||||
- - - - - Deposit
|
||||
|
||||
*This process may be repeated for other currencies, ETH as example*
|
||||
|
||||
---
|
||||
|
||||
# Configure Freqtrade to use Gax Sandbox
|
||||
|
||||
The aim of this document section
|
||||
|
||||
- Enable sandbox URLs in Freqtrade
|
||||
- Configure API
|
||||
- - secret
|
||||
- - key
|
||||
- - passphrase
|
||||
|
||||
## Sandbox URLs
|
||||
|
||||
Freqtrade makes use of CCXT which in turn provides a list of URLs to Freqtrade.
|
||||
These include `['test']` and `['api']`.
|
||||
|
||||
- `[Test]` if available will point to an Exchanges sandbox.
|
||||
- `[Api]` normally used, and resolves to live API target on the exchange
|
||||
|
||||
To make use of sandbox / test add "sandbox": true, to your config.json
|
||||
|
||||
```json
|
||||
"exchange": {
|
||||
"name": "gdax",
|
||||
"sandbox": true,
|
||||
"key": "5wowfxemogxeowo;heiohgmd",
|
||||
"secret": "/ZMH1P62rCVmwefewrgcewX8nh4gob+lywxfwfxwwfxwfNsH1ySgvWCUR/w==",
|
||||
"password": "1bkjfkhfhfu6sr",
|
||||
"outdated_offset": 5
|
||||
"pair_whitelist": [
|
||||
"BTC/USD"
|
||||
```
|
||||
|
||||
Also insert your
|
||||
|
||||
- api-key (noted earlier)
|
||||
- api-secret (noted earlier)
|
||||
- password (the passphrase - noted earlier)
|
||||
|
||||
---
|
||||
|
||||
## You should now be ready to test your sandbox
|
||||
|
||||
Ensure Freqtrade logs show the sandbox URL, and trades made are shown in sandbox.
|
||||
** Typically the BTC/USD has the most activity in sandbox to test against.
|
||||
|
||||
## GDAX - Old Candles problem
|
||||
|
||||
It is my experience that GDAX sandbox candles may be 20+- minutes out of date. This can cause trades to fail as one of Freqtrades safety checks.
|
||||
|
||||
To disable this check, add / change the `"outdated_offset"` parameter in the exchange section of your configuration to adjust for this delay.
|
||||
Example based on the above configuration:
|
||||
|
||||
```json
|
||||
"exchange": {
|
||||
"name": "gdax",
|
||||
"sandbox": true,
|
||||
"key": "5wowfxemogxeowo;heiohgmd",
|
||||
"secret": "/ZMH1P62rCVmwefewrgcewX8nh4gob+lywxfwfxwwfxwfNsH1ySgvWCUR/w==",
|
||||
"password": "1bkjfkhfhfu6sr",
|
||||
"outdated_offset": 30
|
||||
"pair_whitelist": [
|
||||
"BTC/USD"
|
||||
```
|
||||
@@ -32,9 +32,12 @@ CREATE TABLE trades (
|
||||
exchange VARCHAR NOT NULL,
|
||||
pair VARCHAR NOT NULL,
|
||||
is_open BOOLEAN NOT NULL,
|
||||
fee FLOAT NOT NULL,
|
||||
fee_open FLOAT NOT NULL,
|
||||
fee_close FLOAT NOT NULL,
|
||||
open_rate FLOAT,
|
||||
open_rate_requested FLOAT,
|
||||
close_rate FLOAT,
|
||||
close_rate_requested FLOAT,
|
||||
close_profit FLOAT,
|
||||
stake_amount FLOAT NOT NULL,
|
||||
amount FLOAT,
|
||||
@@ -56,7 +59,7 @@ SELECT * FROM trades;
|
||||
|
||||
```sql
|
||||
UPDATE trades
|
||||
SET is_open=0, close_date=<close_date>, close_rate=<close_rate>, close_profit=close_rate/open_rate
|
||||
SET is_open=0, close_date=<close_date>, close_rate=<close_rate>, close_profit=close_rate/open_rate-1
|
||||
WHERE id=<trade_ID_to_update>;
|
||||
```
|
||||
|
||||
@@ -71,18 +74,18 @@ WHERE id=31;
|
||||
|
||||
```sql
|
||||
INSERT
|
||||
INTO trades (exchange, pair, is_open, fee, open_rate, stake_amount, amount, open_date)
|
||||
VALUES ('BITTREX', 'BTC_<COIN>', 1, 0.0025, <open_rate>, <stake_amount>, <amount>, '<datetime>')
|
||||
INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date)
|
||||
VALUES ('BITTREX', 'BTC_<COIN>', 1, 0.0025, 0.0025, <open_rate>, <stake_amount>, <amount>, '<datetime>')
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```sql
|
||||
INSERT INTO trades (exchange, pair, is_open, fee, open_rate, stake_amount, amount, open_date) VALUES ('BITTREX', 'BTC_ETC', 1, 0.0025, 0.00258580, 0.002, 0.7715262081, '2017-11-28 12:44:24.000000')
|
||||
INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date) VALUES ('BITTREX', 'BTC_ETC', 1, 0.0025, 0.0025, 0.00258580, 0.002, 0.7715262081, '2017-11-28 12:44:24.000000')
|
||||
```
|
||||
|
||||
## Fix wrong fees in the table
|
||||
If your DB was created before
|
||||
[PR#200](https://github.com/gcarq/freqtrade/pull/200) was merged
|
||||
[PR#200](https://github.com/freqtrade/freqtrade/pull/200) was merged
|
||||
(before 12/23/17).
|
||||
|
||||
```sql
|
||||
|
||||
62
docs/stoploss.md
Normal file
62
docs/stoploss.md
Normal file
@@ -0,0 +1,62 @@
|
||||
# Stop Loss support
|
||||
|
||||
At this stage the bot contains the following stoploss support modes:
|
||||
|
||||
1. static stop loss, defined in either the strategy or configuration.
|
||||
2. trailing stop loss, defined in the configuration.
|
||||
3. trailing stop loss, custom positive loss, defined in configuration.
|
||||
|
||||
!!! Note
|
||||
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. 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).
|
||||
|
||||
!!! Note
|
||||
Stoploss on exchange is only supported for Binance as of now.
|
||||
|
||||
|
||||
## 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
|
||||
will overwrite the strategy definition. This will basically try to sell your asset, the second the loss exceeds the defined loss.
|
||||
|
||||
## Trail 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.
|
||||
To enable this Feauture all you have to do is to define the configuration element:
|
||||
|
||||
``` json
|
||||
"trailing_stop" : True
|
||||
```
|
||||
|
||||
This will now activate an algorithm, which automatically moves your stop loss up every time the price of your asset increases.
|
||||
|
||||
For example, simplified math,
|
||||
|
||||
* you buy an asset at a price of 100$
|
||||
* your stop loss is defined at 2%
|
||||
* which means your stop loss, gets triggered once your asset dropped below 98$
|
||||
* assuming your asset now increases to 102$
|
||||
* your 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$
|
||||
|
||||
basically what this means is that your stop loss will be adjusted to be always be 2% of the highest observed price
|
||||
|
||||
### Custom positive loss
|
||||
|
||||
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,
|
||||
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,
|
||||
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.
|
||||
|
||||
``` json
|
||||
"trailing_stop_positive": 0.01,
|
||||
"trailing_stop_positive_offset": 0.011,
|
||||
```
|
||||
|
||||
The 0.01 would translate to a 1% stop loss, once you hit 1.1% profit.
|
||||
|
||||
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.
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
This page explains how to command your bot with Telegram.
|
||||
|
||||
## Pre-requisite
|
||||
## Prerequisite
|
||||
To control your bot with Telegram, you need first to
|
||||
[set up a Telegram bot](https://github.com/gcarq/freqtrade/blob/develop/docs/pre-requisite.md)
|
||||
[set up a Telegram bot](installation.md)
|
||||
and add your Telegram API keys into your config file.
|
||||
|
||||
## Telegram commands
|
||||
@@ -16,12 +16,14 @@ official commands. You can ask at any moment for help with `/help`.
|
||||
|----------|---------|-------------|
|
||||
| `/start` | | Starts the trader
|
||||
| `/stop` | | Stops the trader
|
||||
| `/reload_conf` | | Reloads the configuration file
|
||||
| `/status` | | Lists all open trades
|
||||
| `/status table` | | List all open trades in a table format
|
||||
| `/count` | | Displays number of trades used and available
|
||||
| `/profit` | | Display a summary of your profit/loss from close trades and some stats about your performance
|
||||
| `/forcesell <trade_id>` | | Instantly sells the given trade (Ignoring `minimum_roi`).
|
||||
| `/forcesell all` | | Instantly sells all open trades (Ignoring `minimum_roi`).
|
||||
| `/forcebuy <pair> [rate]` | | Instantly buys the given pair. Rate is optional. (`forcebuy_enable` must be set to True)
|
||||
| `/performance` | | Show performance of each finished trade grouped by pair
|
||||
| `/balance` | | Show account balance per currency
|
||||
| `/daily <n>` | 7 | Shows profit or loss per day, over the last n days
|
||||
@@ -29,20 +31,24 @@ official commands. You can ask at any moment for help with `/help`.
|
||||
| `/version` | | Show version
|
||||
|
||||
## Telegram commands in action
|
||||
|
||||
Below, example of Telegram message you will receive for each command.
|
||||
|
||||
### /start
|
||||
|
||||
> **Status:** `running`
|
||||
|
||||
### /stop
|
||||
|
||||
> `Stopping trader ...`
|
||||
> **Status:** `stopped`
|
||||
|
||||
## /status
|
||||
|
||||
For each open trade, the bot will send you the following message.
|
||||
|
||||
> **Trade ID:** `123`
|
||||
> **Current Pair:** BTC_CVC
|
||||
> **Current Pair:** CVC/BTC
|
||||
> **Open Since:** `1 days ago`
|
||||
> **Amount:** `26.64180098`
|
||||
> **Open Rate:** `0.00007489`
|
||||
@@ -53,15 +59,17 @@ For each open trade, the bot will send you the following message.
|
||||
> **Open Order:** `None`
|
||||
|
||||
## /status table
|
||||
|
||||
Return the status of all open trades in a table format.
|
||||
```
|
||||
ID Pair Since Profit
|
||||
---- -------- ------- --------
|
||||
67 BTC_SC 1 d 13.33%
|
||||
123 BTC_CVC 1 h 12.95%
|
||||
67 SC/BTC 1 d 13.33%
|
||||
123 CVC/BTC 1 h 12.95%
|
||||
```
|
||||
|
||||
## /count
|
||||
|
||||
Return the number of trades used and available.
|
||||
```
|
||||
current max
|
||||
@@ -70,6 +78,7 @@ current max
|
||||
```
|
||||
|
||||
## /profit
|
||||
|
||||
Return a summary of your profit/loss and performance.
|
||||
|
||||
> **ROI:** Close trades
|
||||
@@ -83,23 +92,31 @@ Return a summary of your profit/loss and performance.
|
||||
> **First Trade opened:** `3 days ago`
|
||||
> **Latest Trade opened:** `2 minutes ago`
|
||||
> **Avg. Duration:** `2:33:45`
|
||||
> **Best Performing:** `BTC_PAY: 50.23%`
|
||||
> **Best Performing:** `PAY/BTC: 50.23%`
|
||||
|
||||
## /forcesell <trade_id>
|
||||
|
||||
> **BITTREX:** Selling BTC/LTC with limit `0.01650000 (profit: ~-4.07%, -0.00008168)`
|
||||
|
||||
## /forcebuy <pair>
|
||||
|
||||
> **BITTREX**: Buying ETH/BTC with limit `0.03400000` (`1.000000 ETH`, `225.290 USD`)
|
||||
|
||||
Note that for this to work, `forcebuy_enable` needs to be set to true.
|
||||
|
||||
## /performance
|
||||
|
||||
Return the performance of each crypto-currency the bot has sold.
|
||||
> Performance:
|
||||
> 1. `BTC_RCN 57.77%`
|
||||
> 2. `BTC_PAY 56.91%`
|
||||
> 3. `BTC_VIB 47.07%`
|
||||
> 4. `BTC_SALT 30.24%`
|
||||
> 5. `BTC_STORJ 27.24%`
|
||||
> 1. `RCN/BTC 57.77%`
|
||||
> 2. `PAY/BTC 56.91%`
|
||||
> 3. `VIB/BTC 47.07%`
|
||||
> 4. `SALT/BTC 30.24%`
|
||||
> 5. `STORJ/BTC 27.24%`
|
||||
> ...
|
||||
|
||||
## /balance
|
||||
|
||||
Return the balance of all crypto-currency your have on the exchange.
|
||||
|
||||
> **Currency:** BTC
|
||||
@@ -113,6 +130,7 @@ Return the balance of all crypto-currency your have on the exchange.
|
||||
> **Pending:** 0.0
|
||||
|
||||
## /daily <n>
|
||||
|
||||
Per default `/daily` will return the 7 last days.
|
||||
The example below if for `/daily 3`:
|
||||
|
||||
@@ -126,15 +144,5 @@ Day Profit BTC Profit USD
|
||||
```
|
||||
|
||||
## /version
|
||||
|
||||
> **Version:** `0.14.3`
|
||||
|
||||
### using proxy with telegram
|
||||
in [freqtrade/freqtrade/rpc/telegram.py](https://github.com/gcarq/freqtrade/blob/develop/freqtrade/rpc/telegram.py) replace
|
||||
```
|
||||
self._updater = Updater(token=self._config['telegram']['token'], workers=0)
|
||||
```
|
||||
|
||||
with
|
||||
```
|
||||
self._updater = Updater(token=self._config['telegram']['token'], request_kwargs={'proxy_url': 'socks5://127.0.0.1:1080/'}, workers=0)
|
||||
```
|
||||
|
||||
75
docs/webhook-config.md
Normal file
75
docs/webhook-config.md
Normal file
@@ -0,0 +1,75 @@
|
||||
# Webhook usage
|
||||
|
||||
This page explains how to configure your bot to talk to webhooks.
|
||||
|
||||
## Configuration
|
||||
|
||||
Enable webhooks by adding a webhook-section to your configuration file, and setting `webhook.enabled` to `true`.
|
||||
|
||||
Sample configuration (tested using IFTTT).
|
||||
|
||||
```json
|
||||
"webhook": {
|
||||
"enabled": true,
|
||||
"url": "https://maker.ifttt.com/trigger/<YOUREVENT>/with/key/<YOURKEY>/",
|
||||
"webhookbuy": {
|
||||
"value1": "Buying {pair}",
|
||||
"value2": "limit {limit:8f}",
|
||||
"value3": "{stake_amount:8f} {stake_currency}"
|
||||
},
|
||||
"webhooksell": {
|
||||
"value1": "Selling {pair}",
|
||||
"value2": "limit {limit:8f}",
|
||||
"value3": "profit: {profit_amount:8f} {stake_currency}"
|
||||
},
|
||||
"webhookstatus": {
|
||||
"value1": "Status: {status}",
|
||||
"value2": "",
|
||||
"value3": ""
|
||||
}
|
||||
},
|
||||
```
|
||||
|
||||
The url in `webhook.url` should point to the correct url for your webhook. If you're using [IFTTT](https://ifttt.com) (as shown in the sample above) please insert our event and key to the url.
|
||||
|
||||
Different payloads can be configured for different events. Not all fields are necessary, but you should configure at least one of the dicts, otherwise the webhook will never be called.
|
||||
|
||||
### Webhookbuy
|
||||
|
||||
The fields in `webhook.webhookbuy` are filled when the bot executes a buy. Parameters are filled using string.format.
|
||||
Possible parameters are:
|
||||
|
||||
* exchange
|
||||
* pair
|
||||
* market_url
|
||||
* limit
|
||||
* stake_amount
|
||||
* stake_amount_fiat
|
||||
* stake_currency
|
||||
* fiat_currency
|
||||
|
||||
### Webhooksell
|
||||
|
||||
The fields in `webhook.webhooksell` are filled when the bot sells a trade. Parameters are filled using string.format.
|
||||
Possible parameters are:
|
||||
|
||||
* exchange
|
||||
* pair
|
||||
* gain
|
||||
* market_url
|
||||
* limit
|
||||
* amount
|
||||
* open_rate
|
||||
* current_rate
|
||||
* profit_amount
|
||||
* profit_percent
|
||||
* profit_fiat
|
||||
* stake_currency
|
||||
* fiat_currency
|
||||
* sell_reason
|
||||
|
||||
### Webhookstatus
|
||||
|
||||
The fields in `webhook.webhookstatus` are used for regular status messages (Started / Stopped / ...). Parameters are filled using string.format.
|
||||
|
||||
The only possible value here is `{status}`.
|
||||
@@ -1,5 +1,5 @@
|
||||
""" FreqTrade bot """
|
||||
__version__ = '0.16.1'
|
||||
__version__ = '0.18.1'
|
||||
|
||||
|
||||
class DependencyException(BaseException):
|
||||
@@ -12,5 +12,14 @@ class DependencyException(BaseException):
|
||||
class OperationalException(BaseException):
|
||||
"""
|
||||
Requires manual intervention.
|
||||
This happens when an exchange returns an unexpected error during runtime.
|
||||
This happens when an exchange returns an unexpected error during runtime
|
||||
or given configuration is invalid.
|
||||
"""
|
||||
|
||||
|
||||
class TemporaryError(BaseException):
|
||||
"""
|
||||
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.
|
||||
"""
|
||||
|
||||
15
freqtrade/__main__.py
Normal file
15
freqtrade/__main__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
__main__.py for Freqtrade
|
||||
To launch Freqtrade as a module
|
||||
|
||||
> python -m freqtrade (with Python >= 3.6)
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
from freqtrade import main
|
||||
|
||||
if __name__ == '__main__':
|
||||
main.set_loggers()
|
||||
main.main(sys.argv[1:])
|
||||
@@ -1,214 +0,0 @@
|
||||
"""
|
||||
Functions to analyze ticker data with indicators and produce buy and sell signals
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from enum import Enum
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
import arrow
|
||||
from pandas import DataFrame, to_datetime
|
||||
|
||||
from freqtrade.exchange import get_ticker_history
|
||||
from freqtrade.persistence import Trade
|
||||
from freqtrade.strategy.resolver import StrategyResolver
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SignalType(Enum):
|
||||
"""
|
||||
Enum to distinguish between buy and sell signals
|
||||
"""
|
||||
BUY = "buy"
|
||||
SELL = "sell"
|
||||
|
||||
|
||||
class Analyze(object):
|
||||
"""
|
||||
Analyze class contains everything the bot need to determine if the situation is good for
|
||||
buying or selling.
|
||||
"""
|
||||
def __init__(self, config: dict) -> None:
|
||||
"""
|
||||
Init Analyze
|
||||
:param config: Bot configuration (use the one from Configuration())
|
||||
"""
|
||||
self.config = config
|
||||
self.strategy = StrategyResolver(self.config).strategy
|
||||
|
||||
@staticmethod
|
||||
def parse_ticker_dataframe(ticker: list) -> DataFrame:
|
||||
"""
|
||||
Analyses the trend for the given ticker history
|
||||
:param ticker: See exchange.get_ticker_history
|
||||
:return: DataFrame
|
||||
"""
|
||||
columns = {'C': 'close', 'V': 'volume', 'O': 'open', 'H': 'high', 'L': 'low', 'T': 'date'}
|
||||
frame = DataFrame(ticker).rename(columns=columns)
|
||||
if 'BV' in frame:
|
||||
frame.drop('BV', axis=1, inplace=True)
|
||||
|
||||
frame['date'] = to_datetime(frame['date'], utc=True, infer_datetime_format=True)
|
||||
|
||||
# group by index and aggregate results to eliminate duplicate ticks
|
||||
frame = frame.groupby(by='date', as_index=False, sort=True).agg({
|
||||
'close': 'last',
|
||||
'high': 'max',
|
||||
'low': 'min',
|
||||
'open': 'first',
|
||||
'volume': 'max',
|
||||
})
|
||||
return frame
|
||||
|
||||
def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
|
||||
"""
|
||||
Adds several different TA indicators to the given DataFrame
|
||||
|
||||
Performance Note: For the best performance be frugal on the number of indicators
|
||||
you are using. Let uncomment only the indicator you are using in your strategies
|
||||
or your hyperopt configuration, otherwise you will waste your memory and CPU usage.
|
||||
"""
|
||||
return self.strategy.populate_indicators(dataframe=dataframe)
|
||||
|
||||
def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the buy signal for the given dataframe
|
||||
:param dataframe: DataFrame
|
||||
:return: DataFrame with buy column
|
||||
"""
|
||||
return self.strategy.populate_buy_trend(dataframe=dataframe)
|
||||
|
||||
def populate_sell_trend(self, dataframe: DataFrame) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the sell signal for the given dataframe
|
||||
:param dataframe: DataFrame
|
||||
:return: DataFrame with buy column
|
||||
"""
|
||||
return self.strategy.populate_sell_trend(dataframe=dataframe)
|
||||
|
||||
def get_ticker_interval(self) -> int:
|
||||
"""
|
||||
Return ticker interval to use
|
||||
:return: Ticker interval value to use
|
||||
"""
|
||||
return self.strategy.ticker_interval
|
||||
|
||||
def analyze_ticker(self, ticker_history: List[Dict]) -> DataFrame:
|
||||
"""
|
||||
Parses the given ticker history and returns a populated DataFrame
|
||||
add several TA indicators and buy signal to it
|
||||
:return DataFrame with ticker data and indicator data
|
||||
"""
|
||||
dataframe = self.parse_ticker_dataframe(ticker_history)
|
||||
dataframe = self.populate_indicators(dataframe)
|
||||
dataframe = self.populate_buy_trend(dataframe)
|
||||
dataframe = self.populate_sell_trend(dataframe)
|
||||
return dataframe
|
||||
|
||||
def get_signal(self, pair: str, interval: int) -> Tuple[bool, bool]:
|
||||
"""
|
||||
Calculates current signal based several technical analysis indicators
|
||||
:param pair: pair in format BTC_ANT or BTC-ANT
|
||||
:param interval: Interval to use (in min)
|
||||
:return: (Buy, Sell) A bool-tuple indicating buy/sell signal
|
||||
"""
|
||||
ticker_hist = get_ticker_history(pair, interval)
|
||||
if not ticker_hist:
|
||||
logger.warning('Empty ticker history for pair %s', pair)
|
||||
return False, False
|
||||
|
||||
try:
|
||||
dataframe = self.analyze_ticker(ticker_hist)
|
||||
except ValueError as error:
|
||||
logger.warning(
|
||||
'Unable to analyze ticker for pair %s: %s',
|
||||
pair,
|
||||
str(error)
|
||||
)
|
||||
return False, False
|
||||
except Exception as error:
|
||||
logger.exception(
|
||||
'Unexpected error when analyzing ticker for pair %s: %s',
|
||||
pair,
|
||||
str(error)
|
||||
)
|
||||
return False, False
|
||||
|
||||
if dataframe.empty:
|
||||
logger.warning('Empty dataframe for pair %s', pair)
|
||||
return False, False
|
||||
|
||||
latest = dataframe.iloc[-1]
|
||||
|
||||
# Check if dataframe is out of date
|
||||
signal_date = arrow.get(latest['date'])
|
||||
if signal_date < arrow.utcnow() - timedelta(minutes=(interval + 5)):
|
||||
logger.warning(
|
||||
'Outdated history for pair %s. Last tick is %s minutes old',
|
||||
pair,
|
||||
(arrow.utcnow() - signal_date).seconds // 60
|
||||
)
|
||||
return False, False
|
||||
|
||||
(buy, sell) = latest[SignalType.BUY.value] == 1, latest[SignalType.SELL.value] == 1
|
||||
logger.debug(
|
||||
'trigger: %s (pair=%s) buy=%s sell=%s',
|
||||
latest['date'],
|
||||
pair,
|
||||
str(buy),
|
||||
str(sell)
|
||||
)
|
||||
return buy, sell
|
||||
|
||||
def should_sell(self, trade: Trade, rate: float, date: datetime, buy: bool, sell: bool) -> bool:
|
||||
"""
|
||||
This function evaluate if on the condition required to trigger a sell has been reached
|
||||
if the threshold is reached and updates the trade record.
|
||||
:return: True if trade should be sold, False otherwise
|
||||
"""
|
||||
# Check if minimal roi has been reached and no longer in buy conditions (avoiding a fee)
|
||||
if self.min_roi_reached(trade=trade, current_rate=rate, current_time=date):
|
||||
logger.debug('Required profit reached. Selling..')
|
||||
return True
|
||||
|
||||
# Experimental: Check if the trade is profitable before selling it (avoid selling at loss)
|
||||
if self.config.get('experimental', {}).get('sell_profit_only', False):
|
||||
logger.debug('Checking if trade is profitable..')
|
||||
if trade.calc_profit(rate=rate) <= 0:
|
||||
return False
|
||||
|
||||
if sell and not buy and self.config.get('experimental', {}).get('use_sell_signal', False):
|
||||
logger.debug('Sell signal received. Selling..')
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def min_roi_reached(self, trade: Trade, current_rate: float, current_time: datetime) -> bool:
|
||||
"""
|
||||
Based an earlier trade and current price and ROI configuration, decides whether bot should
|
||||
sell
|
||||
:return True if bot should sell at current rate
|
||||
"""
|
||||
current_profit = trade.calc_profit_percent(current_rate)
|
||||
if self.strategy.stoploss is not None and current_profit < self.strategy.stoploss:
|
||||
logger.debug('Stop loss hit.')
|
||||
return True
|
||||
|
||||
# Check if time matches and current rate is above threshold
|
||||
time_diff = (current_time.timestamp() - trade.open_date.timestamp()) / 60
|
||||
for duration, threshold in self.strategy.minimal_roi.items():
|
||||
if time_diff <= duration:
|
||||
return False
|
||||
if current_profit > threshold:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def tickerdata_to_dataframe(self, tickerdata: Dict[str, List]) -> Dict[str, DataFrame]:
|
||||
"""
|
||||
Creates a dataframe and populates indicators for given ticker data
|
||||
"""
|
||||
return {pair: self.populate_indicators(self.parse_ticker_dataframe(pair_data))
|
||||
for pair, pair_data in tickerdata.items()}
|
||||
@@ -3,22 +3,35 @@ This module contains the argument manager class
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from typing import List, Tuple, Optional
|
||||
from typing import List, NamedTuple, Optional
|
||||
|
||||
import arrow
|
||||
|
||||
from freqtrade import __version__, constants
|
||||
|
||||
|
||||
class TimeRange(NamedTuple):
|
||||
"""
|
||||
NamedTuple Defining timerange inputs.
|
||||
[start/stop]type defines if [start/stop]ts shall be used.
|
||||
if *type is none, don't use corresponding startvalue.
|
||||
"""
|
||||
starttype: Optional[str] = None
|
||||
stoptype: Optional[str] = None
|
||||
startts: int = 0
|
||||
stopts: int = 0
|
||||
|
||||
|
||||
class Arguments(object):
|
||||
"""
|
||||
Arguments Class. Manage the arguments received by the cli
|
||||
"""
|
||||
|
||||
def __init__(self, args: List[str], description: str):
|
||||
def __init__(self, args: List[str], description: str) -> None:
|
||||
self.args = args
|
||||
self.parsed_arg = None
|
||||
self.parsed_arg: Optional[argparse.Namespace] = None
|
||||
self.parser = argparse.ArgumentParser(description=description)
|
||||
|
||||
def _load_args(self) -> None:
|
||||
@@ -50,16 +63,15 @@ class Arguments(object):
|
||||
"""
|
||||
self.parser.add_argument(
|
||||
'-v', '--verbose',
|
||||
help='be verbose',
|
||||
action='store_const',
|
||||
help='verbose mode (-vv for more, -vvv to get all messages)',
|
||||
action='count',
|
||||
dest='loglevel',
|
||||
const=logging.DEBUG,
|
||||
default=logging.INFO,
|
||||
default=0,
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'--version',
|
||||
action='version',
|
||||
version='%(prog)s {}'.format(__version__),
|
||||
version=f'%(prog)s {__version__}'
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'-c', '--config',
|
||||
@@ -71,9 +83,9 @@ class Arguments(object):
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'-d', '--datadir',
|
||||
help='path to backtest data (default: %(default)s',
|
||||
help='path to backtest data',
|
||||
dest='datadir',
|
||||
default=os.path.join('freqtrade', 'tests', 'testdata'),
|
||||
default=None,
|
||||
type=str,
|
||||
metavar='PATH',
|
||||
)
|
||||
@@ -92,10 +104,19 @@ class Arguments(object):
|
||||
type=str,
|
||||
metavar='PATH',
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'--customhyperopt',
|
||||
help='specify hyperopt class name (default: %(default)s)',
|
||||
dest='hyperopt',
|
||||
default=constants.DEFAULT_HYPEROPT,
|
||||
type=str,
|
||||
metavar='NAME',
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'--dynamic-whitelist',
|
||||
help='dynamically generate and update whitelist \
|
||||
based on 24h BaseVolume (Default 20 currencies)', # noqa
|
||||
help='dynamically generate and update whitelist'
|
||||
' based on 24h BaseVolume (default: %(const)s)'
|
||||
' DEPRECATED.',
|
||||
dest='dynamic_whitelist',
|
||||
const=constants.DYNAMIC_WHITELIST,
|
||||
type=int,
|
||||
@@ -103,11 +124,12 @@ class Arguments(object):
|
||||
nargs='?',
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'--dry-run-db',
|
||||
help='Force dry run to use a local DB "tradesv3.dry_run.sqlite" \
|
||||
instead of memory DB. Work only if dry_run is enabled.',
|
||||
action='store_true',
|
||||
dest='dry_run_db',
|
||||
'--db-url',
|
||||
help='Override trades database URL, this is useful if dry_run is enabled'
|
||||
' or in custom deployments (default: %(default)s)',
|
||||
dest='db_url',
|
||||
type=str,
|
||||
metavar='PATH',
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -115,6 +137,22 @@ class Arguments(object):
|
||||
"""
|
||||
Parses given arguments for Backtesting scripts.
|
||||
"""
|
||||
parser.add_argument(
|
||||
'--eps', '--enable-position-stacking',
|
||||
help='Allow buying the same pair multiple times (position stacking)',
|
||||
action='store_true',
|
||||
dest='position_stacking',
|
||||
default=False
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--dmmp', '--disable-max-market-positions',
|
||||
help='Disable applying `max_open_trades` during backtest '
|
||||
'(same as setting `max_open_trades` to a very high number)',
|
||||
action='store_false',
|
||||
dest='use_max_market_positions',
|
||||
default=True
|
||||
)
|
||||
parser.add_argument(
|
||||
'-l', '--live',
|
||||
help='using live data',
|
||||
@@ -123,11 +161,21 @@ class Arguments(object):
|
||||
)
|
||||
parser.add_argument(
|
||||
'-r', '--refresh-pairs-cached',
|
||||
help='refresh the pairs files in tests/testdata with the latest data from Bittrex. \
|
||||
Use it if you want to run your backtesting with up-to-date data.',
|
||||
help='refresh the pairs files in tests/testdata with the latest data from the '
|
||||
'exchange. Use it if you want to run your backtesting with up-to-date data.',
|
||||
action='store_true',
|
||||
dest='refresh_pairs',
|
||||
)
|
||||
parser.add_argument(
|
||||
'--strategy-list',
|
||||
help='Provide a commaseparated list of strategies to backtest '
|
||||
'Please note that ticker-interval needs to be set either in config '
|
||||
'or via command line. When using this together with --export trades, '
|
||||
'the strategy-name is injected into the filename '
|
||||
'(so backtest-data.json becomes backtest-data-DefaultStrategy.json',
|
||||
nargs='+',
|
||||
dest='strategy_list',
|
||||
)
|
||||
parser.add_argument(
|
||||
'--export',
|
||||
help='export backtest results, argument are: trades\
|
||||
@@ -136,22 +184,53 @@ class Arguments(object):
|
||||
default=None,
|
||||
dest='export',
|
||||
)
|
||||
parser.add_argument(
|
||||
'--export-filename',
|
||||
help='Save backtest results to this filename \
|
||||
requires --export to be set as well\
|
||||
Example --export-filename=user_data/backtest_data/backtest_today.json\
|
||||
(default: %(default)s)',
|
||||
type=str,
|
||||
default=os.path.join('user_data', 'backtest_data', 'backtest-result.json'),
|
||||
dest='exportfilename',
|
||||
metavar='PATH',
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def edge_options(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
Parses given arguments for Backtesting scripts.
|
||||
"""
|
||||
parser.add_argument(
|
||||
'-r', '--refresh-pairs-cached',
|
||||
help='refresh the pairs files in tests/testdata with the latest data from the '
|
||||
'exchange. Use it if you want to run your edge with up-to-date data.',
|
||||
action='store_true',
|
||||
dest='refresh_pairs',
|
||||
)
|
||||
parser.add_argument(
|
||||
'--stoplosses',
|
||||
help='defines a range of stoploss against which edge will assess the strategy '
|
||||
'the format is "min,max,step" (without any space).'
|
||||
'example: --stoplosses=-0.01,-0.1,-0.001',
|
||||
type=str,
|
||||
dest='stoploss_range',
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def optimizer_shared_options(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
Parses given common arguments for Backtesting and Hyperopt scripts.
|
||||
:param parser:
|
||||
:return:
|
||||
"""
|
||||
parser.add_argument(
|
||||
'-i', '--ticker-interval',
|
||||
help='specify ticker interval in minutes (1, 5, 30, 60, 1440)',
|
||||
help='specify ticker interval (1m, 5m, 30m, 1h, 1d)',
|
||||
dest='ticker_interval',
|
||||
type=int,
|
||||
metavar='INT',
|
||||
)
|
||||
parser.add_argument(
|
||||
'--realistic-simulation',
|
||||
help='uses max_open_trades from config to simulate real world limitations',
|
||||
action='store_true',
|
||||
dest='realistic_simulation',
|
||||
type=str,
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--timerange',
|
||||
help='specify what timerange of data to use.',
|
||||
@@ -165,6 +244,22 @@ class Arguments(object):
|
||||
"""
|
||||
Parses given arguments for Hyperopt scripts.
|
||||
"""
|
||||
parser.add_argument(
|
||||
'--eps', '--enable-position-stacking',
|
||||
help='Allow buying the same pair multiple times (position stacking)',
|
||||
action='store_true',
|
||||
dest='position_stacking',
|
||||
default=False
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--dmmp', '--disable-max-market-positions',
|
||||
help='Disable applying `max_open_trades` during backtest '
|
||||
'(same as setting `max_open_trades` to a very high number)',
|
||||
action='store_false',
|
||||
dest='use_max_market_positions',
|
||||
default=True
|
||||
)
|
||||
parser.add_argument(
|
||||
'-e', '--epochs',
|
||||
help='specify number of epochs (default: %(default)d)',
|
||||
@@ -173,17 +268,11 @@ class Arguments(object):
|
||||
type=int,
|
||||
metavar='INT',
|
||||
)
|
||||
parser.add_argument(
|
||||
'--use-mongodb',
|
||||
help='parallelize evaluations with mongodb (requires mongod in PATH)',
|
||||
dest='mongodb',
|
||||
action='store_true',
|
||||
)
|
||||
parser.add_argument(
|
||||
'-s', '--spaces',
|
||||
help='Specify which parameters to hyperopt. Space separate list. \
|
||||
Default: %(default)s',
|
||||
choices=['all', 'buy', 'roi', 'stoploss'],
|
||||
choices=['all', 'buy', 'sell', 'roi', 'stoploss'],
|
||||
default='all',
|
||||
nargs='+',
|
||||
dest='spaces',
|
||||
@@ -194,7 +283,7 @@ class Arguments(object):
|
||||
Builds and attaches all subcommands
|
||||
:return: None
|
||||
"""
|
||||
from freqtrade.optimize import backtesting, hyperopt
|
||||
from freqtrade.optimize import backtesting, hyperopt, edge_cli
|
||||
|
||||
subparsers = self.parser.add_subparsers(dest='subparser')
|
||||
|
||||
@@ -204,6 +293,12 @@ class Arguments(object):
|
||||
self.optimizer_shared_options(backtesting_cmd)
|
||||
self.backtesting_options(backtesting_cmd)
|
||||
|
||||
# Add edge subcommand
|
||||
edge_cmd = subparsers.add_parser('edge', help='edge module')
|
||||
edge_cmd.set_defaults(func=edge_cli.start)
|
||||
self.optimizer_shared_options(edge_cmd)
|
||||
self.edge_options(edge_cmd)
|
||||
|
||||
# Add hyperopt subcommand
|
||||
hyperopt_cmd = subparsers.add_parser('hyperopt', help='hyperopt module')
|
||||
hyperopt_cmd.set_defaults(func=hyperopt.start)
|
||||
@@ -211,17 +306,20 @@ class Arguments(object):
|
||||
self.hyperopt_options(hyperopt_cmd)
|
||||
|
||||
@staticmethod
|
||||
def parse_timerange(text: str) -> Optional[Tuple[List, int, int]]:
|
||||
def parse_timerange(text: Optional[str]) -> TimeRange:
|
||||
"""
|
||||
Parse the value of the argument --timerange to determine what is the range desired
|
||||
:param text: value from --timerange
|
||||
:return: Start and End range period
|
||||
"""
|
||||
if text is None:
|
||||
return None
|
||||
return TimeRange(None, None, 0, 0)
|
||||
syntax = [(r'^-(\d{8})$', (None, 'date')),
|
||||
(r'^(\d{8})-$', ('date', None)),
|
||||
(r'^(\d{8})-(\d{8})$', ('date', 'date')),
|
||||
(r'^-(\d{10})$', (None, 'date')),
|
||||
(r'^(\d{10})-$', ('date', None)),
|
||||
(r'^(\d{10})-(\d{10})$', ('date', 'date')),
|
||||
(r'^(-\d+)$', (None, 'line')),
|
||||
(r'^(\d+)-$', ('line', None)),
|
||||
(r'^(\d+)-(\d+)$', ('index', 'index'))]
|
||||
@@ -231,27 +329,95 @@ class Arguments(object):
|
||||
if match: # Regex has matched
|
||||
rvals = match.groups()
|
||||
index = 0
|
||||
start = None
|
||||
stop = None
|
||||
start: int = 0
|
||||
stop: int = 0
|
||||
if stype[0]:
|
||||
start = rvals[index]
|
||||
if stype[0] != 'date':
|
||||
start = int(start)
|
||||
starts = rvals[index]
|
||||
if stype[0] == 'date' and len(starts) == 8:
|
||||
start = arrow.get(starts, 'YYYYMMDD').timestamp
|
||||
else:
|
||||
start = int(starts)
|
||||
index += 1
|
||||
if stype[1]:
|
||||
stop = rvals[index]
|
||||
if stype[1] != 'date':
|
||||
stop = int(stop)
|
||||
return stype, start, stop
|
||||
stops = rvals[index]
|
||||
if stype[1] == 'date' and len(stops) == 8:
|
||||
stop = arrow.get(stops, 'YYYYMMDD').timestamp
|
||||
else:
|
||||
stop = int(stops)
|
||||
return TimeRange(stype[0], stype[1], start, stop)
|
||||
raise Exception('Incorrect syntax for timerange "%s"' % text)
|
||||
|
||||
def scripts_options(self) -> None:
|
||||
"""
|
||||
Parses given arguments for plot scripts.
|
||||
Parses given arguments for scripts.
|
||||
"""
|
||||
self.parser.add_argument(
|
||||
'-p', '--pair',
|
||||
'-p', '--pairs',
|
||||
help='Show profits for only this pairs. Pairs are comma-separated.',
|
||||
dest='pair',
|
||||
dest='pairs',
|
||||
default=None
|
||||
)
|
||||
|
||||
def testdata_dl_options(self) -> None:
|
||||
"""
|
||||
Parses given arguments for testdata download
|
||||
"""
|
||||
self.parser.add_argument(
|
||||
'--pairs-file',
|
||||
help='File containing a list of pairs to download',
|
||||
dest='pairs_file',
|
||||
default=None,
|
||||
metavar='PATH',
|
||||
)
|
||||
|
||||
self.parser.add_argument(
|
||||
'--export',
|
||||
help='Export files to given dir',
|
||||
dest='export',
|
||||
default=None,
|
||||
metavar='PATH',
|
||||
)
|
||||
|
||||
self.parser.add_argument(
|
||||
'-c', '--config',
|
||||
help='specify configuration file, used for additional exchange parameters',
|
||||
dest='config',
|
||||
default=None,
|
||||
type=str,
|
||||
metavar='PATH',
|
||||
)
|
||||
|
||||
self.parser.add_argument(
|
||||
'--days',
|
||||
help='Download data for number of days',
|
||||
dest='days',
|
||||
type=int,
|
||||
metavar='INT',
|
||||
default=None
|
||||
)
|
||||
|
||||
self.parser.add_argument(
|
||||
'--exchange',
|
||||
help='Exchange name (default: %(default)s). Only valid if no config is provided',
|
||||
dest='exchange',
|
||||
type=str,
|
||||
default='bittrex'
|
||||
)
|
||||
|
||||
self.parser.add_argument(
|
||||
'-t', '--timeframes',
|
||||
help='Specify which tickers to download. Space separated list. \
|
||||
Default: %(default)s',
|
||||
choices=['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h',
|
||||
'6h', '8h', '12h', '1d', '3d', '1w'],
|
||||
default=['1m', '5m'],
|
||||
nargs='+',
|
||||
dest='timeframes',
|
||||
)
|
||||
|
||||
self.parser.add_argument(
|
||||
'--erase',
|
||||
help='Clean all existing data for the selected exchange/pairs/timeframes',
|
||||
dest='erase',
|
||||
action='store_true'
|
||||
)
|
||||
|
||||
@@ -1,29 +1,44 @@
|
||||
"""
|
||||
This module contains the configuration class
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from argparse import Namespace
|
||||
from typing import Dict, Any
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
import ccxt
|
||||
from jsonschema import Draft4Validator, validate
|
||||
from jsonschema.exceptions import ValidationError, best_match
|
||||
|
||||
from freqtrade import constants
|
||||
|
||||
|
||||
from freqtrade import OperationalException, constants
|
||||
from freqtrade.state import RunMode
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def set_loggers(log_level: int = 0) -> None:
|
||||
"""
|
||||
Set the logger level for Third party libs
|
||||
:return: None
|
||||
"""
|
||||
|
||||
logging.getLogger('requests').setLevel(logging.INFO if log_level <= 1 else logging.DEBUG)
|
||||
logging.getLogger("urllib3").setLevel(logging.INFO if log_level <= 1 else logging.DEBUG)
|
||||
logging.getLogger('ccxt.base.exchange').setLevel(
|
||||
logging.INFO if log_level <= 2 else logging.DEBUG)
|
||||
logging.getLogger('telegram').setLevel(logging.INFO)
|
||||
|
||||
|
||||
class Configuration(object):
|
||||
"""
|
||||
Class to read and init the bot configuration
|
||||
Reuse this class for the bot, backtesting, hyperopt and every script that required configuration
|
||||
"""
|
||||
def __init__(self, args: Namespace) -> None:
|
||||
|
||||
def __init__(self, args: Namespace, runmode: RunMode = None) -> None:
|
||||
self.args = args
|
||||
self.config = None
|
||||
self.config: Optional[Dict[str, Any]] = None
|
||||
self.runmode = runmode
|
||||
|
||||
def load_config(self) -> Dict[str, Any]:
|
||||
"""
|
||||
@@ -40,15 +55,28 @@ class Configuration(object):
|
||||
if self.args.strategy_path:
|
||||
config.update({'strategy_path': self.args.strategy_path})
|
||||
|
||||
# Add the hyperopt file to use
|
||||
config.update({'hyperopt': self.args.hyperopt})
|
||||
|
||||
# Load Common configuration
|
||||
config = self._load_common_config(config)
|
||||
|
||||
# Load Backtesting
|
||||
config = self._load_backtesting_config(config)
|
||||
|
||||
# Load Edge
|
||||
config = self._load_edge_config(config)
|
||||
|
||||
# Load Hyperopt
|
||||
config = self._load_hyperopt_config(config)
|
||||
|
||||
# Set runmode
|
||||
if not self.runmode:
|
||||
# Handle real mode, infer dry/live from config
|
||||
self.runmode = RunMode.DRY_RUN if config.get('dry_run', True) else RunMode.LIVE
|
||||
|
||||
config.update({'runmode': self.runmode})
|
||||
|
||||
return config
|
||||
|
||||
def _load_config_file(self, path: str) -> Dict[str, Any]:
|
||||
@@ -61,11 +89,9 @@ class Configuration(object):
|
||||
with open(path) as file:
|
||||
conf = json.load(file)
|
||||
except FileNotFoundError:
|
||||
logger.critical(
|
||||
'Config file "%s" not found. Please create your config file',
|
||||
path
|
||||
)
|
||||
exit(0)
|
||||
raise OperationalException(
|
||||
f'Config file "{path}" not found!'
|
||||
' Please create a config file or check whether it exists.')
|
||||
|
||||
if 'internals' not in conf:
|
||||
conf['internals'] = {}
|
||||
@@ -81,35 +107,68 @@ class Configuration(object):
|
||||
|
||||
# Log level
|
||||
if 'loglevel' in self.args and self.args.loglevel:
|
||||
config.update({'loglevel': self.args.loglevel})
|
||||
logging.basicConfig(
|
||||
level=config['loglevel'],
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
)
|
||||
logger.info('Log level set to %s', logging.getLevelName(config['loglevel']))
|
||||
config.update({'verbosity': self.args.loglevel})
|
||||
else:
|
||||
config.update({'verbosity': 0})
|
||||
logging.basicConfig(
|
||||
level=logging.INFO if config['verbosity'] < 1 else logging.DEBUG,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
)
|
||||
set_loggers(config['verbosity'])
|
||||
logger.info('Verbosity set to %s', config['verbosity'])
|
||||
|
||||
# Add dynamic_whitelist if found
|
||||
if 'dynamic_whitelist' in self.args and self.args.dynamic_whitelist:
|
||||
config.update({'dynamic_whitelist': self.args.dynamic_whitelist})
|
||||
logger.info(
|
||||
'Parameter --dynamic-whitelist detected. '
|
||||
'Using dynamically generated whitelist. '
|
||||
# Update to volumePairList (the previous default)
|
||||
config['pairlist'] = {'method': 'VolumePairList',
|
||||
'config': {'number_assets': self.args.dynamic_whitelist}
|
||||
}
|
||||
logger.warning(
|
||||
'Parameter --dynamic-whitelist has been deprecated, '
|
||||
'and will be completely replaced by the whitelist dict in the future. '
|
||||
'For now: using dynamically generated whitelist based on VolumePairList. '
|
||||
'(not applicable with Backtesting and Hyperopt)'
|
||||
)
|
||||
|
||||
# Add dry_run_db if found and the bot in dry run
|
||||
if self.args.dry_run_db and config.get('dry_run', False):
|
||||
config.update({'dry_run_db': True})
|
||||
logger.info('Parameter --dry-run-db detected ...')
|
||||
if 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_db', False):
|
||||
if config.get('dry_run', False):
|
||||
logger.info('Dry_run will use the DB file: "tradesv3.dry_run.sqlite"')
|
||||
else:
|
||||
logger.info('Dry run is disabled. (--dry_run_db ignored)')
|
||||
if config.get('dry_run', False):
|
||||
logger.info('Dry run is enabled')
|
||||
if config.get('db_url') in [None, constants.DEFAULT_DB_PROD_URL]:
|
||||
# Default to in-memory db for dry_run if not specified
|
||||
config['db_url'] = constants.DEFAULT_DB_DRYRUN_URL
|
||||
else:
|
||||
if not config.get('db_url', None):
|
||||
config['db_url'] = constants.DEFAULT_DB_PROD_URL
|
||||
logger.info('Dry run is disabled')
|
||||
|
||||
if config.get('forcebuy_enable', False):
|
||||
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')
|
||||
|
||||
logger.info(f'Using DB: "{config["db_url"]}"')
|
||||
|
||||
# Check if the exchange set by the user is supported
|
||||
self.check_exchange(config)
|
||||
|
||||
return config
|
||||
|
||||
def _create_datadir(self, config: Dict[str, Any], datadir: Optional[str] = None) -> str:
|
||||
if not datadir:
|
||||
# set datadir
|
||||
exchange_name = config.get('exchange', {}).get('name').lower()
|
||||
datadir = os.path.join('user_data', 'data', exchange_name)
|
||||
|
||||
if not os.path.isdir(datadir):
|
||||
os.makedirs(datadir)
|
||||
logger.info(f'Created data directory: {datadir}')
|
||||
return datadir
|
||||
|
||||
def _load_backtesting_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Extract information for sys.argv and load Backtesting configuration
|
||||
@@ -121,18 +180,25 @@ class Configuration(object):
|
||||
if 'ticker_interval' in self.args and self.args.ticker_interval:
|
||||
config.update({'ticker_interval': self.args.ticker_interval})
|
||||
logger.info('Parameter -i/--ticker-interval detected ...')
|
||||
logger.info('Using ticker_interval: %d ...', config.get('ticker_interval'))
|
||||
logger.info('Using ticker_interval: %s ...', config.get('ticker_interval'))
|
||||
|
||||
# If -l/--live is used we add it to the configuration
|
||||
if 'live' in self.args and self.args.live:
|
||||
config.update({'live': True})
|
||||
logger.info('Parameter -l/--live detected ...')
|
||||
|
||||
# If --realistic-simulation is used we add it to the configuration
|
||||
if 'realistic_simulation' in self.args and self.args.realistic_simulation:
|
||||
config.update({'realistic_simulation': True})
|
||||
logger.info('Parameter --realistic-simulation detected ...')
|
||||
logger.info('Using max_open_trades: %s ...', config.get('max_open_trades'))
|
||||
# If --enable-position-stacking is used we add it to the configuration
|
||||
if 'position_stacking' in self.args and self.args.position_stacking:
|
||||
config.update({'position_stacking': True})
|
||||
logger.info('Parameter --enable-position-stacking detected ...')
|
||||
|
||||
# If --disable-max-market-positions is used we add it to the configuration
|
||||
if 'use_max_market_positions' in self.args and not self.args.use_max_market_positions:
|
||||
config.update({'use_max_market_positions': False})
|
||||
logger.info('Parameter --disable-max-market-positions detected ...')
|
||||
logger.info('max_open_trades set to unlimited ...')
|
||||
else:
|
||||
logger.info('Using max_open_trades: %s ...', config.get('max_open_trades'))
|
||||
|
||||
# If --timerange is used we add it to the configuration
|
||||
if 'timerange' in self.args and self.args.timerange:
|
||||
@@ -141,19 +207,60 @@ class Configuration(object):
|
||||
|
||||
# If --datadir is used we add it to the configuration
|
||||
if 'datadir' in self.args and self.args.datadir:
|
||||
config.update({'datadir': self.args.datadir})
|
||||
logger.info('Parameter --datadir detected: %s ...', self.args.datadir)
|
||||
config.update({'datadir': self._create_datadir(config, self.args.datadir)})
|
||||
else:
|
||||
config.update({'datadir': self._create_datadir(config, None)})
|
||||
logger.info('Using data folder: %s ...', config.get('datadir'))
|
||||
|
||||
# If -r/--refresh-pairs-cached is used we add it to the configuration
|
||||
if 'refresh_pairs' in self.args and self.args.refresh_pairs:
|
||||
config.update({'refresh_pairs': True})
|
||||
logger.info('Parameter -r/--refresh-pairs-cached detected ...')
|
||||
|
||||
if 'strategy_list' in self.args and self.args.strategy_list:
|
||||
config.update({'strategy_list': self.args.strategy_list})
|
||||
logger.info('Using strategy list of %s Strategies', len(self.args.strategy_list))
|
||||
|
||||
if 'ticker_interval' in self.args and self.args.ticker_interval:
|
||||
config.update({'ticker_interval': self.args.ticker_interval})
|
||||
logger.info('Overriding ticker interval with Command line argument')
|
||||
|
||||
# If --export is used we add it to the configuration
|
||||
if 'export' in self.args and self.args.export:
|
||||
config.update({'export': self.args.export})
|
||||
logger.info('Parameter --export detected: %s ...', self.args.export)
|
||||
|
||||
# If --export-filename is used we add it to the configuration
|
||||
if 'export' in config and 'exportfilename' in self.args and self.args.exportfilename:
|
||||
config.update({'exportfilename': self.args.exportfilename})
|
||||
logger.info('Storing backtest results to %s ...', self.args.exportfilename)
|
||||
|
||||
return config
|
||||
|
||||
def _load_edge_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Extract information for sys.argv and load Edge configuration
|
||||
:return: configuration as dictionary
|
||||
"""
|
||||
|
||||
# If --timerange is used we add it to the configuration
|
||||
if 'timerange' in self.args and self.args.timerange:
|
||||
config.update({'timerange': self.args.timerange})
|
||||
logger.info('Parameter --timerange detected: %s ...', self.args.timerange)
|
||||
|
||||
# If --timerange is used we add it to the configuration
|
||||
if 'stoploss_range' in self.args and self.args.stoploss_range:
|
||||
txt_range = eval(self.args.stoploss_range)
|
||||
config['edge'].update({'stoploss_range_min': txt_range[0]})
|
||||
config['edge'].update({'stoploss_range_max': txt_range[1]})
|
||||
config['edge'].update({'stoploss_range_step': txt_range[2]})
|
||||
logger.info('Parameter --stoplosses detected: %s ...', self.args.stoploss_range)
|
||||
|
||||
# If -r/--refresh-pairs-cached is used we add it to the configuration
|
||||
if 'refresh_pairs' in self.args and self.args.refresh_pairs:
|
||||
config.update({'refresh_pairs': True})
|
||||
logger.info('Parameter -r/--refresh-pairs-cached detected ...')
|
||||
|
||||
return config
|
||||
|
||||
def _load_hyperopt_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
|
||||
@@ -161,17 +268,12 @@ class Configuration(object):
|
||||
Extract information for sys.argv and load Hyperopt configuration
|
||||
:return: configuration as dictionary
|
||||
"""
|
||||
# If --realistic-simulation is used we add it to the configuration
|
||||
# If --epochs is used we add it to the configuration
|
||||
if 'epochs' in self.args and self.args.epochs:
|
||||
config.update({'epochs': self.args.epochs})
|
||||
logger.info('Parameter --epochs detected ...')
|
||||
logger.info('Will run Hyperopt with for %s epochs ...', config.get('epochs'))
|
||||
|
||||
# If --mongodb is used we add it to the configuration
|
||||
if 'mongodb' in self.args and self.args.mongodb:
|
||||
config.update({'mongodb': self.args.mongodb})
|
||||
logger.info('Parameter --use-mongodb detected ...')
|
||||
|
||||
# If --spaces is used we add it to the configuration
|
||||
if 'spaces' in self.args and self.args.spaces:
|
||||
config.update({'spaces': self.args.spaces})
|
||||
@@ -186,10 +288,10 @@ class Configuration(object):
|
||||
:return: Returns the config if valid, otherwise throw an exception
|
||||
"""
|
||||
try:
|
||||
validate(conf, constants.CONF_SCHEMA)
|
||||
validate(conf, constants.CONF_SCHEMA, Draft4Validator)
|
||||
return conf
|
||||
except ValidationError as exception:
|
||||
logger.fatal(
|
||||
logger.critical(
|
||||
'Invalid configuration. See config.json.example. Reason: %s',
|
||||
exception
|
||||
)
|
||||
@@ -206,3 +308,27 @@ class Configuration(object):
|
||||
self.config = self.load_config()
|
||||
|
||||
return self.config
|
||||
|
||||
def check_exchange(self, config: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
Check if the exchange name in the config file is supported by Freqtrade
|
||||
:return: True or raised an exception if the exchange if not supported
|
||||
"""
|
||||
exchange = config.get('exchange', {}).get('name').lower()
|
||||
if exchange not in ccxt.exchanges:
|
||||
|
||||
exception_msg = f'Exchange "{exchange}" not supported.\n' \
|
||||
f'The following exchanges are supported: {", ".join(ccxt.exchanges)}'
|
||||
|
||||
logger.critical(exception_msg)
|
||||
raise OperationalException(
|
||||
exception_msg
|
||||
)
|
||||
# Depreciation warning
|
||||
if 'ccxt_rate_limit' in config.get('exchange', {}):
|
||||
logger.warning("`ccxt_rate_limit` has been deprecated in favor of "
|
||||
"`ccxt_config` and `ccxt_async_config` and will be removed "
|
||||
"in a future version.")
|
||||
|
||||
logger.debug('Exchange "%s" supported', exchange)
|
||||
return True
|
||||
|
||||
@@ -9,24 +9,57 @@ TICKER_INTERVAL = 5 # min
|
||||
HYPEROPT_EPOCH = 100 # epochs
|
||||
RETRY_TIMEOUT = 30 # sec
|
||||
DEFAULT_STRATEGY = 'DefaultStrategy'
|
||||
DEFAULT_HYPEROPT = 'DefaultHyperOpts'
|
||||
DEFAULT_DB_PROD_URL = 'sqlite:///tradesv3.sqlite'
|
||||
DEFAULT_DB_DRYRUN_URL = 'sqlite://'
|
||||
UNLIMITED_STAKE_AMOUNT = 'unlimited'
|
||||
DEFAULT_AMOUNT_RESERVE_PERCENT = 0.05
|
||||
REQUIRED_ORDERTIF = ['buy', 'sell']
|
||||
REQUIRED_ORDERTYPES = ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
||||
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
||||
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
||||
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList']
|
||||
|
||||
TICKER_INTERVAL_MINUTES = {
|
||||
'1m': 1,
|
||||
'3m': 3,
|
||||
'5m': 5,
|
||||
'15m': 15,
|
||||
'30m': 30,
|
||||
'1h': 60,
|
||||
'2h': 120,
|
||||
'4h': 240,
|
||||
'6h': 360,
|
||||
'8h': 480,
|
||||
'12h': 720,
|
||||
'1d': 1440,
|
||||
'3d': 4320,
|
||||
'1w': 10080,
|
||||
}
|
||||
|
||||
SUPPORTED_FIAT = [
|
||||
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK",
|
||||
"EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY",
|
||||
"KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN",
|
||||
"RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR", "USD",
|
||||
"BTC", "XBT", "ETH", "XRP", "LTC", "BCH", "USDT"
|
||||
]
|
||||
|
||||
# Required json-schema for user specified config
|
||||
CONF_SCHEMA = {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'max_open_trades': {'type': 'integer', 'minimum': 1},
|
||||
'ticker_interval': {'type': 'integer', 'enum': [1, 5, 30, 60, 1440]},
|
||||
'stake_currency': {'type': 'string', 'enum': ['BTC', 'ETH', 'USDT']},
|
||||
'stake_amount': {'type': 'number', 'minimum': 0.0005},
|
||||
'fiat_display_currency': {'type': 'string', 'enum': ['AUD', 'BRL', 'CAD', 'CHF',
|
||||
'CLP', 'CNY', 'CZK', 'DKK',
|
||||
'EUR', 'GBP', 'HKD', 'HUF',
|
||||
'IDR', 'ILS', 'INR', 'JPY',
|
||||
'KRW', 'MXN', 'MYR', 'NOK',
|
||||
'NZD', 'PHP', 'PKR', 'PLN',
|
||||
'RUB', 'SEK', 'SGD', 'THB',
|
||||
'TRY', 'TWD', 'ZAR', 'USD']},
|
||||
'max_open_trades': {'type': 'integer', 'minimum': -1},
|
||||
'ticker_interval': {'type': 'string', 'enum': list(TICKER_INTERVAL_MINUTES.keys())},
|
||||
'stake_currency': {'type': 'string', 'enum': ['BTC', 'XBT', 'ETH', 'USDT', 'EUR', 'USD']},
|
||||
'stake_amount': {
|
||||
"type": ["number", "string"],
|
||||
"minimum": 0.0005,
|
||||
"pattern": UNLIMITED_STAKE_AMOUNT
|
||||
},
|
||||
'fiat_display_currency': {'type': 'string', 'enum': SUPPORTED_FIAT},
|
||||
'dry_run': {'type': 'boolean'},
|
||||
'process_only_new_candles': {'type': 'boolean'},
|
||||
'minimal_roi': {
|
||||
'type': 'object',
|
||||
'patternProperties': {
|
||||
@@ -35,7 +68,16 @@ CONF_SCHEMA = {
|
||||
'minProperties': 1
|
||||
},
|
||||
'stoploss': {'type': 'number', 'maximum': 0, 'exclusiveMaximum': True},
|
||||
'unfilledtimeout': {'type': 'integer', 'minimum': 0},
|
||||
'trailing_stop': {'type': 'boolean'},
|
||||
'trailing_stop_positive': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
||||
'trailing_stop_positive_offset': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
||||
'unfilledtimeout': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'buy': {'type': 'number', 'minimum': 3},
|
||||
'sell': {'type': 'number', 'minimum': 10}
|
||||
}
|
||||
},
|
||||
'bid_strategy': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
@@ -43,19 +85,65 @@ CONF_SCHEMA = {
|
||||
'type': 'number',
|
||||
'minimum': 0,
|
||||
'maximum': 1,
|
||||
'exclusiveMaximum': False
|
||||
'exclusiveMaximum': False,
|
||||
'use_order_book': {'type': 'boolean'},
|
||||
'order_book_top': {'type': 'number', 'maximum': 20, 'minimum': 1},
|
||||
'check_depth_of_market': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'enabled': {'type': 'boolean'},
|
||||
'bids_to_ask_delta': {'type': 'number', 'minimum': 0},
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
'required': ['ask_last_balance']
|
||||
},
|
||||
'ask_strategy': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'use_order_book': {'type': 'boolean'},
|
||||
'order_book_min': {'type': 'number', 'minimum': 1},
|
||||
'order_book_max': {'type': 'number', 'minimum': 1, 'maximum': 50}
|
||||
}
|
||||
},
|
||||
'order_types': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'buy': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||
'sell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||
'stoploss': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||
'stoploss_on_exchange': {'type': 'boolean'},
|
||||
'stoploss_on_exchange_interval': {'type': 'number'}
|
||||
},
|
||||
'required': ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
||||
},
|
||||
'order_time_in_force': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'buy': {'type': 'string', 'enum': ORDERTIF_POSSIBILITIES},
|
||||
'sell': {'type': 'string', 'enum': ORDERTIF_POSSIBILITIES}
|
||||
},
|
||||
'required': ['buy', 'sell']
|
||||
},
|
||||
'exchange': {'$ref': '#/definitions/exchange'},
|
||||
'edge': {'$ref': '#/definitions/edge'},
|
||||
'experimental': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'use_sell_signal': {'type': 'boolean'},
|
||||
'sell_profit_only': {'type': 'boolean'}
|
||||
'sell_profit_only': {'type': 'boolean'},
|
||||
'ignore_roi_if_buy_signal_true': {'type': 'boolean'}
|
||||
}
|
||||
},
|
||||
'pairlist': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'method': {'type': 'string', 'enum': AVAILABLE_PAIRLISTS},
|
||||
'config': {'type': 'object'}
|
||||
},
|
||||
'required': ['method']
|
||||
},
|
||||
'telegram': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
@@ -65,7 +153,18 @@ CONF_SCHEMA = {
|
||||
},
|
||||
'required': ['enabled', 'token', 'chat_id']
|
||||
},
|
||||
'webhook': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'enabled': {'type': 'boolean'},
|
||||
'webhookbuy': {'type': 'object'},
|
||||
'webhooksell': {'type': 'object'},
|
||||
'webhookstatus': {'type': 'object'},
|
||||
},
|
||||
},
|
||||
'db_url': {'type': 'string'},
|
||||
'initial_state': {'type': 'string', 'enum': ['running', 'stopped']},
|
||||
'forcebuy_enable': {'type': 'boolean'},
|
||||
'internals': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
@@ -79,13 +178,16 @@ CONF_SCHEMA = {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'name': {'type': 'string'},
|
||||
'sandbox': {'type': 'boolean'},
|
||||
'key': {'type': 'string'},
|
||||
'secret': {'type': 'string'},
|
||||
'password': {'type': 'string'},
|
||||
'uid': {'type': 'string'},
|
||||
'pair_whitelist': {
|
||||
'type': 'array',
|
||||
'items': {
|
||||
'type': 'string',
|
||||
'pattern': '^[0-9A-Z]+_[0-9A-Z]+$'
|
||||
'pattern': '^[0-9A-Z]+/[0-9A-Z]+$'
|
||||
},
|
||||
'uniqueItems': True
|
||||
},
|
||||
@@ -93,12 +195,34 @@ CONF_SCHEMA = {
|
||||
'type': 'array',
|
||||
'items': {
|
||||
'type': 'string',
|
||||
'pattern': '^[0-9A-Z]+_[0-9A-Z]+$'
|
||||
'pattern': '^[0-9A-Z]+/[0-9A-Z]+$'
|
||||
},
|
||||
'uniqueItems': True
|
||||
}
|
||||
},
|
||||
'outdated_offset': {'type': 'integer', 'minimum': 1},
|
||||
'ccxt_config': {'type': 'object'},
|
||||
'ccxt_async_config': {'type': 'object'}
|
||||
},
|
||||
'required': ['name', 'key', 'secret', 'pair_whitelist']
|
||||
},
|
||||
'edge': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
"enabled": {'type': 'boolean'},
|
||||
"process_throttle_secs": {'type': 'integer', 'minimum': 600},
|
||||
"calculate_since_number_of_days": {'type': 'integer'},
|
||||
"allowed_risk": {'type': 'number'},
|
||||
"capital_available_percentage": {'type': 'number'},
|
||||
"stoploss_range_min": {'type': 'number'},
|
||||
"stoploss_range_max": {'type': 'number'},
|
||||
"stoploss_range_step": {'type': 'number'},
|
||||
"minimum_winrate": {'type': 'number'},
|
||||
"minimum_expectancy": {'type': 'number'},
|
||||
"min_trade_number": {'type': 'number'},
|
||||
"max_trade_duration_minute": {'type': 'integer'},
|
||||
"remove_pumps": {'type': 'boolean'}
|
||||
},
|
||||
'required': ['process_throttle_secs', 'allowed_risk', 'capital_available_percentage']
|
||||
}
|
||||
},
|
||||
'anyOf': [
|
||||
@@ -108,7 +232,6 @@ CONF_SCHEMA = {
|
||||
'max_open_trades',
|
||||
'stake_currency',
|
||||
'stake_amount',
|
||||
'fiat_display_currency',
|
||||
'dry_run',
|
||||
'bid_strategy',
|
||||
'telegram'
|
||||
|
||||
8
freqtrade/data/__init__.py
Normal file
8
freqtrade/data/__init__.py
Normal file
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
Module to handle data operations for freqtrade
|
||||
"""
|
||||
|
||||
# limit what's imported when using `from freqtrad.data import *``
|
||||
__all__ = [
|
||||
'converter'
|
||||
]
|
||||
106
freqtrade/data/converter.py
Normal file
106
freqtrade/data/converter.py
Normal file
@@ -0,0 +1,106 @@
|
||||
"""
|
||||
Functions to convert data from one format to another
|
||||
"""
|
||||
import logging
|
||||
import pandas as pd
|
||||
from pandas import DataFrame, to_datetime
|
||||
|
||||
from freqtrade.constants import TICKER_INTERVAL_MINUTES
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def parse_ticker_dataframe(ticker: list, ticker_interval: str,
|
||||
fill_missing: bool = True) -> 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_interval: ticker_interval (e.g. 5m). Used to fill up eventual missing data
|
||||
:param fill_missing: fill up missing candles with 0 candles
|
||||
(see ohlcv_fill_up_missing_data for details)
|
||||
:return: DataFrame
|
||||
"""
|
||||
logger.debug("Parsing tickerlist to dataframe")
|
||||
cols = ['date', 'open', 'high', 'low', 'close', 'volume']
|
||||
frame = DataFrame(ticker, columns=cols)
|
||||
|
||||
frame['date'] = to_datetime(frame['date'],
|
||||
unit='ms',
|
||||
utc=True,
|
||||
infer_datetime_format=True)
|
||||
|
||||
# Some exchanges return int values for volume and even for ohlc.
|
||||
# Convert them since TA-LIB indicators used in the strategy assume floats
|
||||
# and fail with exception...
|
||||
frame = frame.astype(dtype={'open': 'float', 'high': 'float', 'low': 'float', 'close': 'float',
|
||||
'volume': 'float'})
|
||||
|
||||
# group by index and aggregate results to eliminate duplicate ticks
|
||||
frame = frame.groupby(by='date', as_index=False, sort=True).agg({
|
||||
'open': 'first',
|
||||
'high': 'max',
|
||||
'low': 'min',
|
||||
'close': 'last',
|
||||
'volume': 'max',
|
||||
})
|
||||
frame.drop(frame.tail(1).index, inplace=True) # eliminate partial candle
|
||||
logger.debug('Dropping last candle')
|
||||
|
||||
if fill_missing:
|
||||
return ohlcv_fill_up_missing_data(frame, ticker_interval)
|
||||
else:
|
||||
return frame
|
||||
|
||||
|
||||
def ohlcv_fill_up_missing_data(dataframe: DataFrame, ticker_interval: str) -> DataFrame:
|
||||
"""
|
||||
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
|
||||
|
||||
"""
|
||||
ohlc_dict = {
|
||||
'open': 'first',
|
||||
'high': 'max',
|
||||
'low': 'min',
|
||||
'close': 'last',
|
||||
'volume': 'sum'
|
||||
}
|
||||
tick_mins = TICKER_INTERVAL_MINUTES[ticker_interval]
|
||||
# Resample to create "NAN" values
|
||||
df = dataframe.resample(f'{tick_mins}min', on='date').agg(ohlc_dict)
|
||||
|
||||
# Forwardfill close for missing columns
|
||||
df['close'] = df['close'].fillna(method='ffill')
|
||||
# Use close for "open, high, low"
|
||||
df.loc[:, ['open', 'high', 'low']] = df[['open', 'high', 'low']].fillna(
|
||||
value={'open': df['close'],
|
||||
'high': df['close'],
|
||||
'low': df['close'],
|
||||
})
|
||||
df.reset_index(inplace=True)
|
||||
logger.debug(f"Missing data fillup: before: {len(dataframe)} - after: {len(df)}")
|
||||
return df
|
||||
|
||||
|
||||
def order_book_to_dataframe(bids: list, asks: list) -> DataFrame:
|
||||
"""
|
||||
Gets order book list, returns dataframe with below format per suggested by creslin
|
||||
-------------------------------------------------------------------
|
||||
b_sum b_size bids asks a_size a_sum
|
||||
-------------------------------------------------------------------
|
||||
"""
|
||||
cols = ['bids', 'b_size']
|
||||
|
||||
bids_frame = DataFrame(bids, columns=cols)
|
||||
# add cumulative sum column
|
||||
bids_frame['b_sum'] = bids_frame['b_size'].cumsum()
|
||||
cols2 = ['asks', 'a_size']
|
||||
asks_frame = DataFrame(asks, columns=cols2)
|
||||
# add cumulative sum column
|
||||
asks_frame['a_sum'] = asks_frame['a_size'].cumsum()
|
||||
|
||||
frame = pd.concat([bids_frame['b_sum'], bids_frame['b_size'], bids_frame['bids'],
|
||||
asks_frame['asks'], asks_frame['a_size'], asks_frame['a_sum']], axis=1,
|
||||
keys=['b_sum', 'b_size', 'bids', 'asks', 'a_size', 'a_sum'])
|
||||
# logger.info('order book %s', frame )
|
||||
return frame
|
||||
97
freqtrade/data/dataprovider.py
Normal file
97
freqtrade/data/dataprovider.py
Normal file
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
Dataprovider
|
||||
Responsible to provide data to the bot
|
||||
including Klines, tickers, historic data
|
||||
Common Interface for bot and strategy to access data.
|
||||
"""
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import List, Tuple
|
||||
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.data.history import load_pair_history
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DataProvider(object):
|
||||
|
||||
def __init__(self, config: dict, exchange: Exchange) -> None:
|
||||
self._config = config
|
||||
self._exchange = exchange
|
||||
|
||||
def refresh(self,
|
||||
pairlist: List[Tuple[str, str]],
|
||||
helping_pairs: List[Tuple[str, str]] = None) -> None:
|
||||
"""
|
||||
Refresh data, called with each cycle
|
||||
"""
|
||||
if helping_pairs:
|
||||
self._exchange.refresh_latest_ohlcv(pairlist + helping_pairs)
|
||||
else:
|
||||
self._exchange.refresh_latest_ohlcv(pairlist)
|
||||
|
||||
@property
|
||||
def available_pairs(self) -> List[Tuple[str, str]]:
|
||||
"""
|
||||
Return a list of tuples containing pair, tick_interval for which data is currently cached.
|
||||
Should be whitelist + open trades.
|
||||
"""
|
||||
return list(self._exchange._klines.keys())
|
||||
|
||||
def ohlcv(self, pair: str, tick_interval: str = None, copy: bool = True) -> DataFrame:
|
||||
"""
|
||||
get ohlcv data for the given pair as DataFrame
|
||||
Please check `available_pairs` to verify which pairs are currently cached.
|
||||
:param pair: pair to get the data for
|
||||
:param tick_interval: ticker_interval to get pair for
|
||||
:param copy: copy dataframe before returning.
|
||||
Use false only for RO operations (where the dataframe is not modified)
|
||||
"""
|
||||
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
||||
if tick_interval:
|
||||
pairtick = (pair, tick_interval)
|
||||
else:
|
||||
pairtick = (pair, self._config['ticker_interval'])
|
||||
|
||||
return self._exchange.klines(pairtick, copy=copy)
|
||||
else:
|
||||
return DataFrame()
|
||||
|
||||
def historic_ohlcv(self, pair: str, ticker_interval: str) -> DataFrame:
|
||||
"""
|
||||
get stored historic ohlcv data
|
||||
:param pair: pair to get the data for
|
||||
:param tick_interval: ticker_interval to get pair for
|
||||
"""
|
||||
return load_pair_history(pair=pair,
|
||||
ticker_interval=ticker_interval,
|
||||
refresh_pairs=False,
|
||||
datadir=Path(self._config['datadir']) if self._config.get(
|
||||
'datadir') else None
|
||||
)
|
||||
|
||||
def ticker(self, pair: str):
|
||||
"""
|
||||
Return last ticker data
|
||||
"""
|
||||
# TODO: Implement me
|
||||
pass
|
||||
|
||||
def orderbook(self, pair: str, max: int):
|
||||
"""
|
||||
return latest orderbook data
|
||||
"""
|
||||
# TODO: Implement me
|
||||
pass
|
||||
|
||||
@property
|
||||
def runmode(self) -> RunMode:
|
||||
"""
|
||||
Get runmode of the bot
|
||||
can be "live", "dry-run", "backtest", "edgecli", "hyperopt" or "other".
|
||||
"""
|
||||
return RunMode(self._config.get('runmode', RunMode.OTHER))
|
||||
235
freqtrade/data/history.py
Normal file
235
freqtrade/data/history.py
Normal file
@@ -0,0 +1,235 @@
|
||||
"""
|
||||
Handle historic data (ohlcv).
|
||||
includes:
|
||||
* load data for a pair (or a list of pairs) from disk
|
||||
* download data from exchange and store to disk
|
||||
"""
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Optional, List, Dict, Tuple, Any
|
||||
|
||||
import arrow
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade import misc, constants, OperationalException
|
||||
from freqtrade.data.converter import parse_ticker_dataframe
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.arguments import TimeRange
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def trim_tickerlist(tickerlist: List[Dict], timerange: TimeRange) -> List[Dict]:
|
||||
"""
|
||||
Trim tickerlist based on given timerange
|
||||
"""
|
||||
if not tickerlist:
|
||||
return tickerlist
|
||||
|
||||
start_index = 0
|
||||
stop_index = len(tickerlist)
|
||||
|
||||
if timerange.starttype == 'line':
|
||||
stop_index = timerange.startts
|
||||
if timerange.starttype == 'index':
|
||||
start_index = timerange.startts
|
||||
elif timerange.starttype == 'date':
|
||||
while (start_index < len(tickerlist) and
|
||||
tickerlist[start_index][0] < timerange.startts * 1000):
|
||||
start_index += 1
|
||||
|
||||
if timerange.stoptype == 'line':
|
||||
start_index = len(tickerlist) + timerange.stopts
|
||||
if timerange.stoptype == 'index':
|
||||
stop_index = timerange.stopts
|
||||
elif timerange.stoptype == 'date':
|
||||
while (stop_index > 0 and
|
||||
tickerlist[stop_index-1][0] > timerange.stopts * 1000):
|
||||
stop_index -= 1
|
||||
|
||||
if start_index > stop_index:
|
||||
raise ValueError(f'The timerange [{timerange.startts},{timerange.stopts}] is incorrect')
|
||||
|
||||
return tickerlist[start_index:stop_index]
|
||||
|
||||
|
||||
def load_tickerdata_file(
|
||||
datadir: Optional[Path], pair: str,
|
||||
ticker_interval: str,
|
||||
timerange: Optional[TimeRange] = None) -> Optional[list]:
|
||||
"""
|
||||
Load a pair from file, either .json.gz or .json
|
||||
:return tickerlist or None if unsuccesful
|
||||
"""
|
||||
path = make_testdata_path(datadir)
|
||||
pair_s = pair.replace('/', '_')
|
||||
file = path.joinpath(f'{pair_s}-{ticker_interval}.json')
|
||||
|
||||
pairdata = misc.file_load_json(file)
|
||||
|
||||
if not pairdata:
|
||||
return None
|
||||
|
||||
if timerange:
|
||||
pairdata = trim_tickerlist(pairdata, timerange)
|
||||
return pairdata
|
||||
|
||||
|
||||
def load_pair_history(pair: str,
|
||||
ticker_interval: str,
|
||||
datadir: Optional[Path],
|
||||
timerange: TimeRange = TimeRange(None, None, 0, 0),
|
||||
refresh_pairs: bool = False,
|
||||
exchange: Optional[Exchange] = None,
|
||||
fill_up_missing: bool = True
|
||||
) -> DataFrame:
|
||||
"""
|
||||
Loads cached ticker history for the given pair.
|
||||
:return: DataFrame with ohlcv data
|
||||
"""
|
||||
|
||||
# If the user force the refresh of pairs
|
||||
if refresh_pairs:
|
||||
if not exchange:
|
||||
raise OperationalException("Exchange needs to be initialized when "
|
||||
"calling load_data with refresh_pairs=True")
|
||||
|
||||
logger.info('Download data for pair and store them in %s', datadir)
|
||||
download_pair_history(datadir=datadir,
|
||||
exchange=exchange,
|
||||
pair=pair,
|
||||
tick_interval=ticker_interval,
|
||||
timerange=timerange)
|
||||
|
||||
pairdata = load_tickerdata_file(datadir, pair, ticker_interval, timerange=timerange)
|
||||
|
||||
if pairdata:
|
||||
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'))
|
||||
return parse_ticker_dataframe(pairdata, ticker_interval, fill_up_missing)
|
||||
else:
|
||||
logger.warning('No data for pair: "%s", Interval: %s. '
|
||||
'Use --refresh-pairs-cached to download the data',
|
||||
pair, ticker_interval)
|
||||
return None
|
||||
|
||||
|
||||
def load_data(datadir: Optional[Path],
|
||||
ticker_interval: str,
|
||||
pairs: List[str],
|
||||
refresh_pairs: bool = False,
|
||||
exchange: Optional[Exchange] = None,
|
||||
timerange: TimeRange = TimeRange(None, None, 0, 0),
|
||||
fill_up_missing: bool = True) -> Dict[str, DataFrame]:
|
||||
"""
|
||||
Loads ticker history data for a list of pairs the given parameters
|
||||
:return: dict(<pair>:<tickerlist>)
|
||||
"""
|
||||
result = {}
|
||||
|
||||
for pair in pairs:
|
||||
hist = load_pair_history(pair=pair, ticker_interval=ticker_interval,
|
||||
datadir=datadir, timerange=timerange,
|
||||
refresh_pairs=refresh_pairs,
|
||||
exchange=exchange,
|
||||
fill_up_missing=fill_up_missing)
|
||||
if hist is not None:
|
||||
result[pair] = hist
|
||||
return result
|
||||
|
||||
|
||||
def make_testdata_path(datadir: Optional[Path]) -> Path:
|
||||
"""Return the path where testdata files are stored"""
|
||||
return datadir or (Path(__file__).parent.parent / "tests" / "testdata").resolve()
|
||||
|
||||
|
||||
def load_cached_data_for_updating(filename: Path, tick_interval: str,
|
||||
timerange: Optional[TimeRange]) -> Tuple[List[Any],
|
||||
Optional[int]]:
|
||||
"""
|
||||
Load cached data and choose what part of the data should be updated
|
||||
"""
|
||||
|
||||
since_ms = None
|
||||
|
||||
# user sets timerange, so find the start time
|
||||
if timerange:
|
||||
if timerange.starttype == 'date':
|
||||
since_ms = timerange.startts * 1000
|
||||
elif timerange.stoptype == 'line':
|
||||
num_minutes = timerange.stopts * constants.TICKER_INTERVAL_MINUTES[tick_interval]
|
||||
since_ms = arrow.utcnow().shift(minutes=num_minutes).timestamp * 1000
|
||||
|
||||
# read the cached file
|
||||
if filename.is_file():
|
||||
with open(filename, "rt") as file:
|
||||
data = misc.json_load(file)
|
||||
# remove the last item, could be incomplete candle
|
||||
if data:
|
||||
data.pop()
|
||||
else:
|
||||
data = []
|
||||
|
||||
if data:
|
||||
if since_ms and since_ms < data[0][0]:
|
||||
# Earlier data than existing data requested, redownload all
|
||||
data = []
|
||||
else:
|
||||
# a part of the data was already downloaded, so download unexist data only
|
||||
since_ms = data[-1][0] + 1
|
||||
|
||||
return (data, since_ms)
|
||||
|
||||
|
||||
def download_pair_history(datadir: Optional[Path],
|
||||
exchange: Exchange,
|
||||
pair: str,
|
||||
tick_interval: str = '5m',
|
||||
timerange: Optional[TimeRange] = None) -> bool:
|
||||
"""
|
||||
Download the latest ticker intervals from the exchange for the pair passed in parameters
|
||||
The data is downloaded starting from the last correct ticker interval data that
|
||||
exists in a cache. If timerange starts earlier than the data in the cache,
|
||||
the full data will be redownloaded
|
||||
|
||||
Based on @Rybolov work: https://github.com/rybolov/freqtrade-data
|
||||
:param pair: pair to download
|
||||
:param tick_interval: ticker interval
|
||||
:param timerange: range of time to download
|
||||
:return: bool with success state
|
||||
|
||||
"""
|
||||
try:
|
||||
path = make_testdata_path(datadir)
|
||||
filepair = pair.replace("/", "_")
|
||||
filename = path.joinpath(f'{filepair}-{tick_interval}.json')
|
||||
|
||||
logger.info('Download the pair: "%s", Interval: %s', pair, tick_interval)
|
||||
|
||||
data, since_ms = load_cached_data_for_updating(filename, tick_interval, timerange)
|
||||
|
||||
logger.debug("Current Start: %s", misc.format_ms_time(data[1][0]) if data else 'None')
|
||||
logger.debug("Current End: %s", misc.format_ms_time(data[-1][0]) if data else 'None')
|
||||
|
||||
# Default since_ms to 30 days if nothing is given
|
||||
new_data = exchange.get_history(pair=pair, tick_interval=tick_interval,
|
||||
since_ms=since_ms if since_ms
|
||||
else
|
||||
int(arrow.utcnow().shift(days=-30).float_timestamp) * 1000)
|
||||
data.extend(new_data)
|
||||
|
||||
logger.debug("New Start: %s", misc.format_ms_time(data[0][0]))
|
||||
logger.debug("New End: %s", misc.format_ms_time(data[-1][0]))
|
||||
|
||||
misc.file_dump_json(filename, data)
|
||||
return True
|
||||
except BaseException:
|
||||
logger.info('Failed to download the pair: "%s", Interval: %s',
|
||||
pair, tick_interval)
|
||||
return False
|
||||
441
freqtrade/edge/__init__.py
Normal file
441
freqtrade/edge/__init__.py
Normal file
@@ -0,0 +1,441 @@
|
||||
# pragma pylint: disable=W0603
|
||||
""" Edge positioning package """
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, NamedTuple
|
||||
|
||||
import arrow
|
||||
import numpy as np
|
||||
import utils_find_1st as utf1st
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade import constants, OperationalException
|
||||
from freqtrade.arguments import Arguments
|
||||
from freqtrade.arguments import TimeRange
|
||||
from freqtrade.data import history
|
||||
from freqtrade.optimize import get_timeframe
|
||||
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.ticker_interval = self.strategy.ticker_interval
|
||||
self.tickerdata_to_dataframe = self.strategy.tickerdata_to_dataframe
|
||||
self.get_timeframe = get_timeframe
|
||||
self.advise_sell = self.strategy.advise_sell
|
||||
self.advise_buy = self.strategy.advise_buy
|
||||
|
||||
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 = Arguments.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']) if self.config.get('datadir') else None,
|
||||
pairs=pairs,
|
||||
ticker_interval=self.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.tickerdata_to_dataframe(data)
|
||||
|
||||
# Print timeframe
|
||||
min_date, max_date = self.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.advise_sell(
|
||||
self.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:
|
||||
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 _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, start_point=0):
|
||||
"""
|
||||
Iterate through ohlc_columns recursively 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 calls itself cutting OHLC, buy_column, sell_colum and date_column
|
||||
Cut from (the exit trade index) + 1
|
||||
Author: https://github.com/mishaker
|
||||
"""
|
||||
|
||||
result: list = []
|
||||
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 of array
|
||||
if open_trade_index == -1 or open_trade_index == len(buy_column) - 1:
|
||||
return []
|
||||
else:
|
||||
open_trade_index += 1 # when a buy signal is seen,
|
||||
# trade opens in reality on the next candle
|
||||
|
||||
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'):
|
||||
return []
|
||||
|
||||
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:
|
||||
return []
|
||||
|
||||
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)
|
||||
|
||||
# Calling again the same function recursively but giving
|
||||
# it a view of exit_index till the end of array
|
||||
return result + self._detect_next_stop_or_sell_point(
|
||||
buy_column[exit_index:],
|
||||
sell_column[exit_index:],
|
||||
date_column[exit_index:],
|
||||
ohlc_columns[exit_index:],
|
||||
stoploss,
|
||||
pair,
|
||||
(start_point + exit_index)
|
||||
)
|
||||
@@ -1,185 +1,730 @@
|
||||
# pragma pylint: disable=W0603
|
||||
""" Cryptocurrency Exchanges support """
|
||||
import enum
|
||||
import logging
|
||||
import inspect
|
||||
from random import randint
|
||||
from typing import List, Dict, Any, Optional
|
||||
from typing import List, Dict, Tuple, Any, Optional
|
||||
from datetime import datetime
|
||||
from math import floor, ceil
|
||||
|
||||
import arrow
|
||||
import requests
|
||||
from cachetools import cached, TTLCache
|
||||
import asyncio
|
||||
import ccxt
|
||||
import ccxt.async_support as ccxt_async
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.exchange.bittrex import Bittrex
|
||||
from freqtrade.exchange.interface import Exchange
|
||||
from freqtrade import constants, OperationalException, DependencyException, TemporaryError
|
||||
from freqtrade.data.converter import parse_ticker_dataframe
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Current selected exchange
|
||||
_API: Exchange = None
|
||||
_CONF: dict = {}
|
||||
|
||||
# Holds all open sell orders for dry_run
|
||||
_DRY_RUN_OPEN_ORDERS: Dict[str, Any] = {}
|
||||
API_RETRY_COUNT = 4
|
||||
|
||||
|
||||
class Exchanges(enum.Enum):
|
||||
"""
|
||||
Maps supported exchange names to correspondent classes.
|
||||
"""
|
||||
BITTREX = Bittrex
|
||||
# Urls to exchange markets, insert quote and base with .format()
|
||||
_EXCHANGE_URLS = {
|
||||
ccxt.bittrex.__name__: '/Market/Index?MarketName={quote}-{base}',
|
||||
ccxt.binance.__name__: '/tradeDetail.html?symbol={base}_{quote}'
|
||||
}
|
||||
|
||||
|
||||
def init(config: dict) -> None:
|
||||
"""
|
||||
Initializes this module with the given config,
|
||||
it does basic validation whether the specified
|
||||
exchange and pairs are valid.
|
||||
:param config: config to use
|
||||
:return: None
|
||||
"""
|
||||
global _CONF, _API
|
||||
|
||||
_CONF.update(config)
|
||||
|
||||
if config['dry_run']:
|
||||
logger.info('Instance is running with dry_run enabled')
|
||||
|
||||
exchange_config = config['exchange']
|
||||
|
||||
# Find matching class for the given exchange name
|
||||
name = exchange_config['name']
|
||||
try:
|
||||
exchange_class = Exchanges[name.upper()].value
|
||||
except KeyError:
|
||||
raise OperationalException('Exchange {} is not supported'.format(name))
|
||||
|
||||
_API = exchange_class(exchange_config)
|
||||
|
||||
# Check if all pairs are available
|
||||
validate_pairs(config['exchange']['pair_whitelist'])
|
||||
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 validate_pairs(pairs: List[str]) -> None:
|
||||
"""
|
||||
Checks if all given pairs are tradable on the current exchange.
|
||||
Raises OperationalException if one pair is not available.
|
||||
:param pairs: list of pairs
|
||||
:return: None
|
||||
"""
|
||||
try:
|
||||
markets = _API.get_markets()
|
||||
except requests.exceptions.RequestException as e:
|
||||
logger.warning('Unable to validate pairs (assuming they are correct). Reason: %s', e)
|
||||
return
|
||||
|
||||
stake_cur = _CONF['stake_currency']
|
||||
for pair in pairs:
|
||||
if not pair.startswith(stake_cur):
|
||||
raise OperationalException(
|
||||
'Pair {} not compatible with stake_currency: {}'.format(pair, stake_cur)
|
||||
)
|
||||
if pair not in markets:
|
||||
raise OperationalException(
|
||||
'Pair {} is not available at {}'.format(pair, _API.name.lower()))
|
||||
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
|
||||
|
||||
|
||||
def buy(pair: str, rate: float, amount: float) -> str:
|
||||
if _CONF['dry_run']:
|
||||
global _DRY_RUN_OPEN_ORDERS
|
||||
order_id = 'dry_run_buy_{}'.format(randint(0, 10**6))
|
||||
_DRY_RUN_OPEN_ORDERS[order_id] = {
|
||||
'pair': pair,
|
||||
'rate': rate,
|
||||
'amount': amount,
|
||||
'type': 'LIMIT_BUY',
|
||||
'remaining': 0.0,
|
||||
'opened': arrow.utcnow().datetime,
|
||||
'closed': arrow.utcnow().datetime,
|
||||
class Exchange(object):
|
||||
|
||||
_conf: Dict = {}
|
||||
|
||||
def __init__(self, config: dict) -> None:
|
||||
"""
|
||||
Initializes this module with the given config,
|
||||
it does basic validation whether the specified
|
||||
exchange and pairs are valid.
|
||||
:return: None
|
||||
"""
|
||||
self._conf.update(config)
|
||||
|
||||
self._cached_ticker: Dict[str, Any] = {}
|
||||
|
||||
# Holds last candle refreshed time of each pair
|
||||
self._pairs_last_refresh_time: Dict[Tuple[str, str], int] = {}
|
||||
|
||||
# Holds candles
|
||||
self._klines: Dict[Tuple[str, str], DataFrame] = {}
|
||||
|
||||
# Holds all open sell orders for dry_run
|
||||
self._dry_run_open_orders: Dict[str, Any] = {}
|
||||
|
||||
if config['dry_run']:
|
||||
logger.info('Instance is running with dry_run enabled')
|
||||
|
||||
exchange_config = config['exchange']
|
||||
self._api: ccxt.Exchange = self._init_ccxt(
|
||||
exchange_config, ccxt_kwargs=exchange_config.get('ccxt_config'))
|
||||
self._api_async: ccxt_async.Exchange = self._init_ccxt(
|
||||
exchange_config, ccxt_async, ccxt_kwargs=exchange_config.get('ccxt_async_config'))
|
||||
|
||||
logger.info('Using Exchange "%s"', self.name)
|
||||
|
||||
self.markets = 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):
|
||||
"""
|
||||
Destructor - clean up async stuff
|
||||
"""
|
||||
logger.debug("Exchange object destroyed, closing async loop")
|
||||
if self._api_async and inspect.iscoroutinefunction(self._api_async.close):
|
||||
asyncio.get_event_loop().run_until_complete(self._api_async.close())
|
||||
|
||||
def _init_ccxt(self, exchange_config: dict, ccxt_module=ccxt,
|
||||
ccxt_kwargs: dict = None) -> ccxt.Exchange:
|
||||
"""
|
||||
Initialize ccxt with given config and return valid
|
||||
ccxt instance.
|
||||
"""
|
||||
# Find matching class for the given exchange name
|
||||
name = exchange_config['name']
|
||||
|
||||
if name not in ccxt_module.exchanges:
|
||||
raise OperationalException(f'Exchange {name} is not supported')
|
||||
|
||||
ex_config = {
|
||||
'apiKey': exchange_config.get('key'),
|
||||
'secret': exchange_config.get('secret'),
|
||||
'password': exchange_config.get('password'),
|
||||
'uid': exchange_config.get('uid', ''),
|
||||
'enableRateLimit': exchange_config.get('ccxt_rate_limit', True)
|
||||
}
|
||||
return order_id
|
||||
if ccxt_kwargs:
|
||||
logger.info('Applying additional ccxt config: %s', ccxt_kwargs)
|
||||
ex_config.update(ccxt_kwargs)
|
||||
try:
|
||||
|
||||
return _API.buy(pair, rate, amount)
|
||||
api = getattr(ccxt_module, name.lower())(ex_config)
|
||||
except (KeyError, AttributeError):
|
||||
raise OperationalException(f'Exchange {name} is not supported')
|
||||
|
||||
self.set_sandbox(api, exchange_config, name)
|
||||
|
||||
def sell(pair: str, rate: float, amount: float) -> str:
|
||||
if _CONF['dry_run']:
|
||||
global _DRY_RUN_OPEN_ORDERS
|
||||
order_id = 'dry_run_sell_{}'.format(randint(0, 10**6))
|
||||
_DRY_RUN_OPEN_ORDERS[order_id] = {
|
||||
'pair': pair,
|
||||
'rate': rate,
|
||||
'amount': amount,
|
||||
'type': 'LIMIT_SELL',
|
||||
'remaining': 0.0,
|
||||
'opened': arrow.utcnow().datetime,
|
||||
'closed': arrow.utcnow().datetime,
|
||||
}
|
||||
return order_id
|
||||
return api
|
||||
|
||||
return _API.sell(pair, rate, amount)
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""exchange Name (from ccxt)"""
|
||||
return self._api.name
|
||||
|
||||
@property
|
||||
def id(self) -> str:
|
||||
"""exchange ccxt id"""
|
||||
return self._api.id
|
||||
|
||||
def get_balance(currency: str) -> float:
|
||||
if _CONF['dry_run']:
|
||||
return 999.9
|
||||
def klines(self, pair_interval: Tuple[str, str], copy=True) -> DataFrame:
|
||||
# create key tuple
|
||||
if pair_interval in self._klines:
|
||||
return self._klines[pair_interval].copy() if copy else self._klines[pair_interval]
|
||||
else:
|
||||
return DataFrame()
|
||||
|
||||
return _API.get_balance(currency)
|
||||
def set_sandbox(self, api, exchange_config: dict, name: str):
|
||||
if exchange_config.get('sandbox'):
|
||||
if api.urls.get('test'):
|
||||
api.urls['api'] = api.urls['test']
|
||||
logger.info("Enabled Sandbox API on %s", name)
|
||||
else:
|
||||
logger.warning(name, "No Sandbox URL in CCXT, exiting. "
|
||||
"Please check your config.json")
|
||||
raise OperationalException(f'Exchange {name} does not provide a sandbox api')
|
||||
|
||||
def _load_async_markets(self) -> None:
|
||||
try:
|
||||
if self._api_async:
|
||||
asyncio.get_event_loop().run_until_complete(self._api_async.load_markets())
|
||||
|
||||
def get_balances():
|
||||
if _CONF['dry_run']:
|
||||
return []
|
||||
except ccxt.BaseError as e:
|
||||
logger.warning('Could not load async markets. Reason: %s', e)
|
||||
return
|
||||
|
||||
return _API.get_balances()
|
||||
def _load_markets(self) -> Dict[str, Any]:
|
||||
""" Initialize markets both sync and async """
|
||||
try:
|
||||
markets = self._api.load_markets()
|
||||
self._load_async_markets()
|
||||
return markets
|
||||
except ccxt.BaseError as e:
|
||||
logger.warning('Unable to initialize markets. Reason: %s', e)
|
||||
return {}
|
||||
|
||||
def validate_pairs(self, pairs: List[str]) -> None:
|
||||
"""
|
||||
Checks if all given pairs are tradable on the current exchange.
|
||||
Raises OperationalException if one pair is not available.
|
||||
:param pairs: list of pairs
|
||||
:return: None
|
||||
"""
|
||||
|
||||
def get_ticker(pair: str, refresh: Optional[bool] = True) -> dict:
|
||||
return _API.get_ticker(pair, refresh)
|
||||
if not self.markets:
|
||||
logger.warning('Unable to validate pairs (assuming they are correct).')
|
||||
# return
|
||||
|
||||
stake_cur = self._conf['stake_currency']
|
||||
for pair in pairs:
|
||||
# Note: ccxt has BaseCurrency/QuoteCurrency format for pairs
|
||||
# TODO: add a support for having coins in BTC/USDT format
|
||||
if not pair.endswith(stake_cur):
|
||||
raise OperationalException(
|
||||
f'Pair {pair} not compatible with stake_currency: {stake_cur}')
|
||||
if self.markets and pair not in self.markets:
|
||||
raise OperationalException(
|
||||
f'Pair {pair} is not available at {self.name}'
|
||||
f'Please remove {pair} from your whitelist.')
|
||||
|
||||
@cached(TTLCache(maxsize=100, ttl=30))
|
||||
def get_ticker_history(pair: str, tick_interval) -> List[Dict]:
|
||||
return _API.get_ticker_history(pair, tick_interval)
|
||||
def validate_timeframes(self, timeframe: List[str]) -> None:
|
||||
"""
|
||||
Checks if ticker interval from config is a supported timeframe on the exchange
|
||||
"""
|
||||
timeframes = self._api.timeframes
|
||||
if timeframe not in timeframes:
|
||||
raise OperationalException(
|
||||
f'Invalid ticker {timeframe}, this Exchange supports {timeframes}')
|
||||
|
||||
def validate_ordertypes(self, order_types: Dict) -> None:
|
||||
"""
|
||||
Checks if order-types configured in strategy/config are supported
|
||||
"""
|
||||
if any(v == 'market' for k, v in order_types.items()):
|
||||
if not self.exchange_has('createMarketOrder'):
|
||||
raise OperationalException(
|
||||
f'Exchange {self.name} does not support market orders.')
|
||||
|
||||
def cancel_order(order_id: str) -> None:
|
||||
if _CONF['dry_run']:
|
||||
return
|
||||
if order_types.get('stoploss_on_exchange'):
|
||||
if self.name != 'Binance':
|
||||
raise OperationalException(
|
||||
'On exchange stoploss is not supported for %s.' % self.name
|
||||
)
|
||||
|
||||
return _API.cancel_order(order_id)
|
||||
def validate_order_time_in_force(self, order_time_in_force: Dict) -> None:
|
||||
"""
|
||||
Checks if order time in force configured in strategy/config are supported
|
||||
"""
|
||||
if any(v != 'gtc' for k, v in order_time_in_force.items()):
|
||||
if self.name != 'Binance':
|
||||
raise OperationalException(
|
||||
f'Time in force policies are not supporetd for {self.name} yet.')
|
||||
|
||||
def exchange_has(self, endpoint: str) -> bool:
|
||||
"""
|
||||
Checks if exchange implements a specific API endpoint.
|
||||
Wrapper around ccxt 'has' attribute
|
||||
:param endpoint: Name of endpoint (e.g. 'fetchOHLCV', 'fetchTickers')
|
||||
:return: bool
|
||||
"""
|
||||
return endpoint in self._api.has and self._api.has[endpoint]
|
||||
|
||||
def get_order(order_id: str) -> Dict:
|
||||
if _CONF['dry_run']:
|
||||
order = _DRY_RUN_OPEN_ORDERS[order_id]
|
||||
order.update({
|
||||
'id': order_id
|
||||
})
|
||||
return order
|
||||
def symbol_amount_prec(self, pair, amount: float):
|
||||
'''
|
||||
Returns the amount to buy or sell to a precision the Exchange accepts
|
||||
Rounded down
|
||||
'''
|
||||
if self._api.markets[pair]['precision']['amount']:
|
||||
symbol_prec = self._api.markets[pair]['precision']['amount']
|
||||
big_amount = amount * pow(10, symbol_prec)
|
||||
amount = floor(big_amount) / pow(10, symbol_prec)
|
||||
return amount
|
||||
|
||||
return _API.get_order(order_id)
|
||||
def symbol_price_prec(self, pair, price: float):
|
||||
'''
|
||||
Returns the price buying or selling with to the precision the Exchange accepts
|
||||
Rounds up
|
||||
'''
|
||||
if self._api.markets[pair]['precision']['price']:
|
||||
symbol_prec = self._api.markets[pair]['precision']['price']
|
||||
big_price = price * pow(10, symbol_prec)
|
||||
price = ceil(big_price) / pow(10, symbol_prec)
|
||||
return price
|
||||
|
||||
def buy(self, pair: str, ordertype: str, amount: float,
|
||||
rate: float, time_in_force) -> Dict:
|
||||
if self._conf['dry_run']:
|
||||
order_id = f'dry_run_buy_{randint(0, 10**6)}'
|
||||
self._dry_run_open_orders[order_id] = {
|
||||
'pair': pair,
|
||||
'price': rate,
|
||||
'amount': amount,
|
||||
'type': ordertype,
|
||||
'side': 'buy',
|
||||
'remaining': 0.0,
|
||||
'datetime': arrow.utcnow().isoformat(),
|
||||
'status': 'closed',
|
||||
'fee': None
|
||||
}
|
||||
return {'id': order_id}
|
||||
|
||||
def get_pair_detail_url(pair: str) -> str:
|
||||
return _API.get_pair_detail_url(pair)
|
||||
try:
|
||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
||||
amount = self.symbol_amount_prec(pair, amount)
|
||||
rate = self.symbol_price_prec(pair, rate) if ordertype != 'market' else None
|
||||
|
||||
if time_in_force == 'gtc':
|
||||
return self._api.create_order(pair, ordertype, 'buy', amount, rate)
|
||||
else:
|
||||
return self._api.create_order(pair, ordertype, 'buy',
|
||||
amount, rate, {'timeInForce': time_in_force})
|
||||
|
||||
def get_markets() -> List[str]:
|
||||
return _API.get_markets()
|
||||
except ccxt.InsufficientFunds as e:
|
||||
raise DependencyException(
|
||||
f'Insufficient funds to create limit buy order on market {pair}.'
|
||||
f'Tried to buy amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not create limit buy order on market {pair}.'
|
||||
f'Tried to buy amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not place buy order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
def sell(self, pair: str, ordertype: str, amount: float,
|
||||
rate: float, time_in_force='gtc') -> Dict:
|
||||
if self._conf['dry_run']:
|
||||
order_id = f'dry_run_sell_{randint(0, 10**6)}'
|
||||
self._dry_run_open_orders[order_id] = {
|
||||
'pair': pair,
|
||||
'price': rate,
|
||||
'amount': amount,
|
||||
'type': ordertype,
|
||||
'side': 'sell',
|
||||
'remaining': 0.0,
|
||||
'datetime': arrow.utcnow().isoformat(),
|
||||
'status': 'closed'
|
||||
}
|
||||
return {'id': order_id}
|
||||
|
||||
def get_market_summaries() -> List[Dict]:
|
||||
return _API.get_market_summaries()
|
||||
try:
|
||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
||||
amount = self.symbol_amount_prec(pair, amount)
|
||||
rate = self.symbol_price_prec(pair, rate) if ordertype != 'market' else None
|
||||
|
||||
if time_in_force == 'gtc':
|
||||
return self._api.create_order(pair, ordertype, 'sell', amount, rate)
|
||||
else:
|
||||
return self._api.create_order(pair, ordertype, 'sell',
|
||||
amount, rate, {'timeInForce': time_in_force})
|
||||
|
||||
def get_name() -> str:
|
||||
return _API.name
|
||||
except ccxt.InsufficientFunds as e:
|
||||
raise DependencyException(
|
||||
f'Insufficient funds to create limit sell order on market {pair}.'
|
||||
f'Tried to sell amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not create limit sell order on market {pair}.'
|
||||
f'Tried to sell amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not place sell order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
def stoploss_limit(self, pair: str, amount: float, stop_price: float, rate: float) -> Dict:
|
||||
"""
|
||||
creates a stoploss limit order.
|
||||
NOTICE: it is not supported by all exchanges. only binance is tested for now.
|
||||
"""
|
||||
|
||||
def get_fee() -> float:
|
||||
return _API.fee
|
||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
||||
amount = self.symbol_amount_prec(pair, amount)
|
||||
rate = self.symbol_price_prec(pair, rate)
|
||||
stop_price = self.symbol_price_prec(pair, stop_price)
|
||||
|
||||
# Ensure rate is less than stop price
|
||||
if stop_price <= rate:
|
||||
raise OperationalException(
|
||||
'In stoploss limit order, stop price should be more than limit price')
|
||||
|
||||
def get_wallet_health() -> List[Dict]:
|
||||
return _API.get_wallet_health()
|
||||
if self._conf['dry_run']:
|
||||
order_id = f'dry_run_buy_{randint(0, 10**6)}'
|
||||
self._dry_run_open_orders[order_id] = {
|
||||
'info': {},
|
||||
'id': order_id,
|
||||
'pair': pair,
|
||||
'price': stop_price,
|
||||
'amount': amount,
|
||||
'type': 'stop_loss_limit',
|
||||
'side': 'sell',
|
||||
'remaining': amount,
|
||||
'datetime': arrow.utcnow().isoformat(),
|
||||
'status': 'open',
|
||||
'fee': None
|
||||
}
|
||||
return self._dry_run_open_orders[order_id]
|
||||
|
||||
try:
|
||||
order = self._api.create_order(pair, 'stop_loss_limit', 'sell',
|
||||
amount, rate, {'stopPrice': stop_price})
|
||||
logger.info('stoploss limit order added for %s. '
|
||||
'stop price: %s. limit: %s' % (pair, stop_price, rate))
|
||||
return order
|
||||
|
||||
except ccxt.InsufficientFunds as e:
|
||||
raise DependencyException(
|
||||
f'Insufficient funds to place stoploss limit order on market {pair}. '
|
||||
f'Tried to put a stoploss amount {amount} with '
|
||||
f'stop {stop_price} and limit {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not place stoploss limit order on market {pair}.'
|
||||
f'Tried to place stoploss amount {amount} with '
|
||||
f'stop {stop_price} and limit {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not place stoploss limit order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_balance(self, currency: str) -> float:
|
||||
if self._conf['dry_run']:
|
||||
return 999.9
|
||||
|
||||
# ccxt exception is already handled by get_balances
|
||||
balances = self.get_balances()
|
||||
balance = balances.get(currency)
|
||||
if balance is None:
|
||||
raise TemporaryError(
|
||||
f'Could not get {currency} balance due to malformed exchange response: {balances}')
|
||||
return balance['free']
|
||||
|
||||
@retrier
|
||||
def get_balances(self) -> dict:
|
||||
if self._conf['dry_run']:
|
||||
return {}
|
||||
|
||||
try:
|
||||
balances = self._api.fetch_balance()
|
||||
# Remove additional info from ccxt results
|
||||
balances.pop("info", None)
|
||||
balances.pop("free", None)
|
||||
balances.pop("total", None)
|
||||
balances.pop("used", None)
|
||||
|
||||
return balances
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get balance due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_tickers(self) -> Dict:
|
||||
try:
|
||||
return self._api.fetch_tickers()
|
||||
except ccxt.NotSupported as e:
|
||||
raise OperationalException(
|
||||
f'Exchange {self._api.name} does not support fetching tickers in batch.'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not load tickers due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_ticker(self, pair: str, refresh: Optional[bool] = True) -> dict:
|
||||
if refresh or pair not in self._cached_ticker.keys():
|
||||
try:
|
||||
if pair not in self._api.markets:
|
||||
raise DependencyException(f"Pair {pair} not available")
|
||||
data = self._api.fetch_ticker(pair)
|
||||
try:
|
||||
self._cached_ticker[pair] = {
|
||||
'bid': float(data['bid']),
|
||||
'ask': float(data['ask']),
|
||||
}
|
||||
except KeyError:
|
||||
logger.debug("Could not cache ticker data for %s", pair)
|
||||
return data
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not load ticker due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
else:
|
||||
logger.info("returning cached ticker-data for %s", pair)
|
||||
return self._cached_ticker[pair]
|
||||
|
||||
def get_history(self, pair: str, tick_interval: str,
|
||||
since_ms: int) -> List:
|
||||
"""
|
||||
Gets candle history using asyncio and returns the list of candles.
|
||||
Handles all async doing.
|
||||
"""
|
||||
return asyncio.get_event_loop().run_until_complete(
|
||||
self._async_get_history(pair=pair, tick_interval=tick_interval,
|
||||
since_ms=since_ms))
|
||||
|
||||
async def _async_get_history(self, pair: str,
|
||||
tick_interval: str,
|
||||
since_ms: int) -> List:
|
||||
# Assume exchange returns 500 candles
|
||||
_LIMIT = 500
|
||||
|
||||
one_call = constants.TICKER_INTERVAL_MINUTES[tick_interval] * 60 * _LIMIT * 1000
|
||||
logger.debug("one_call: %s", one_call)
|
||||
input_coroutines = [self._async_get_candle_history(
|
||||
pair, tick_interval, since) for since in
|
||||
range(since_ms, arrow.utcnow().timestamp * 1000, one_call)]
|
||||
|
||||
tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
|
||||
|
||||
# Combine tickers
|
||||
data: List = []
|
||||
for p, ticker_interval, ticker in tickers:
|
||||
if p == pair:
|
||||
data.extend(ticker)
|
||||
# Sort data again after extending the result - above calls return in "async order"
|
||||
data = sorted(data, key=lambda x: x[0])
|
||||
logger.info("downloaded %s with length %s.", pair, len(data))
|
||||
return data
|
||||
|
||||
def refresh_latest_ohlcv(self, pair_list: List[Tuple[str, str]]) -> List[Tuple[str, List]]:
|
||||
"""
|
||||
Refresh in-memory ohlcv asyncronously and set `_klines` with the result
|
||||
"""
|
||||
logger.debug("Refreshing ohlcv data for %d pairs", len(pair_list))
|
||||
|
||||
input_coroutines = []
|
||||
|
||||
# Gather corotines to run
|
||||
for pair, ticker_interval in set(pair_list):
|
||||
# Calculating ticker interval in second
|
||||
interval_in_sec = constants.TICKER_INTERVAL_MINUTES[ticker_interval] * 60
|
||||
|
||||
if not ((self._pairs_last_refresh_time.get((pair, ticker_interval), 0)
|
||||
+ interval_in_sec) >= arrow.utcnow().timestamp
|
||||
and (pair, ticker_interval) in self._klines):
|
||||
input_coroutines.append(self._async_get_candle_history(pair, ticker_interval))
|
||||
else:
|
||||
logger.debug("Using cached ohlcv data for %s, %s ...", pair, ticker_interval)
|
||||
|
||||
tickers = asyncio.get_event_loop().run_until_complete(
|
||||
asyncio.gather(*input_coroutines, return_exceptions=True))
|
||||
|
||||
# handle caching
|
||||
for res in tickers:
|
||||
if isinstance(res, Exception):
|
||||
logger.warning("Async code raised an exception: %s", res.__class__.__name__)
|
||||
continue
|
||||
pair = res[0]
|
||||
tick_interval = res[1]
|
||||
ticks = res[2]
|
||||
# keeping last candle time as last refreshed time of the pair
|
||||
if ticks:
|
||||
self._pairs_last_refresh_time[(pair, tick_interval)] = ticks[-1][0] // 1000
|
||||
# keeping parsed dataframe in cache
|
||||
self._klines[(pair, tick_interval)] = parse_ticker_dataframe(
|
||||
ticks, tick_interval, fill_missing=True)
|
||||
return tickers
|
||||
|
||||
@retrier_async
|
||||
async def _async_get_candle_history(self, pair: str, tick_interval: str,
|
||||
since_ms: Optional[int] = None) -> Tuple[str, str, List]:
|
||||
"""
|
||||
Asyncronously gets candle histories using fetch_ohlcv
|
||||
returns tuple: (pair, tick_interval, ohlcv_list)
|
||||
"""
|
||||
try:
|
||||
# fetch ohlcv asynchronously
|
||||
logger.debug("fetching %s, %s since %s ...", pair, tick_interval, since_ms)
|
||||
|
||||
data = await self._api_async.fetch_ohlcv(pair, timeframe=tick_interval,
|
||||
since=since_ms)
|
||||
|
||||
# Because some exchange sort Tickers ASC and other DESC.
|
||||
# Ex: Bittrex returns a list of tickers ASC (oldest first, newest last)
|
||||
# when GDAX returns a list of tickers DESC (newest first, oldest last)
|
||||
# Only sort if necessary to save computing time
|
||||
try:
|
||||
if data and data[0][0] > data[-1][0]:
|
||||
data = sorted(data, key=lambda x: x[0])
|
||||
except IndexError:
|
||||
logger.exception("Error loading %s. Result was %s.", pair, data)
|
||||
return pair, tick_interval, []
|
||||
logger.debug("done fetching %s, %s ...", pair, tick_interval)
|
||||
return pair, tick_interval, data
|
||||
|
||||
except ccxt.NotSupported as e:
|
||||
raise OperationalException(
|
||||
f'Exchange {self._api.name} does not support fetching historical candlestick data.'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not load ticker history due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(f'Could not fetch ticker data. Msg: {e}')
|
||||
|
||||
@retrier
|
||||
def cancel_order(self, order_id: str, pair: str) -> None:
|
||||
if self._conf['dry_run']:
|
||||
return
|
||||
|
||||
try:
|
||||
return self._api.cancel_order(order_id, pair)
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not cancel order. Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not cancel order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_order(self, order_id: str, pair: str) -> Dict:
|
||||
if self._conf['dry_run']:
|
||||
order = self._dry_run_open_orders[order_id]
|
||||
order.update({
|
||||
'id': order_id
|
||||
})
|
||||
return order
|
||||
try:
|
||||
return self._api.fetch_order(order_id, pair)
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not get order. Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_order_book(self, pair: str, limit: int = 100) -> dict:
|
||||
"""
|
||||
get order book level 2 from exchange
|
||||
|
||||
Notes:
|
||||
20180619: bittrex doesnt support limits -.-
|
||||
20180619: binance support limits but only on specific range
|
||||
"""
|
||||
try:
|
||||
if self._api.name == 'Binance':
|
||||
limit_range = [5, 10, 20, 50, 100, 500, 1000]
|
||||
# get next-higher step in the limit_range list
|
||||
limit = min(list(filter(lambda x: limit <= x, limit_range)))
|
||||
# above script works like loop below (but with slightly better performance):
|
||||
# for limitx in limit_range:
|
||||
# if limit <= limitx:
|
||||
# limit = limitx
|
||||
# break
|
||||
|
||||
return self._api.fetch_l2_order_book(pair, limit)
|
||||
except ccxt.NotSupported as e:
|
||||
raise OperationalException(
|
||||
f'Exchange {self._api.name} does not support fetching order book.'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get order book due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_trades_for_order(self, order_id: str, pair: str, since: datetime) -> List:
|
||||
if self._conf['dry_run']:
|
||||
return []
|
||||
if not self.exchange_has('fetchMyTrades'):
|
||||
return []
|
||||
try:
|
||||
# Allow 5s offset to catch slight time offsets (discovered in #1185)
|
||||
my_trades = self._api.fetch_my_trades(pair, since.timestamp() - 5)
|
||||
matched_trades = [trade for trade in my_trades if trade['order'] == order_id]
|
||||
|
||||
return matched_trades
|
||||
|
||||
except ccxt.NetworkError as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get trades due to networking error. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
def get_pair_detail_url(self, pair: str) -> str:
|
||||
try:
|
||||
url_base = self._api.urls.get('www')
|
||||
base, quote = pair.split('/')
|
||||
|
||||
return url_base + _EXCHANGE_URLS[self._api.id].format(base=base, quote=quote)
|
||||
except KeyError:
|
||||
logger.warning('Could not get exchange url for %s', self.name)
|
||||
return ""
|
||||
|
||||
@retrier
|
||||
def get_markets(self) -> List[dict]:
|
||||
try:
|
||||
return self._api.fetch_markets()
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not load markets due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_fee(self, symbol='ETH/BTC', type='', side='', amount=1,
|
||||
price=1, taker_or_maker='maker') -> float:
|
||||
try:
|
||||
# validate that markets are loaded before trying to get fee
|
||||
if self._api.markets is None or len(self._api.markets) == 0:
|
||||
self._api.load_markets()
|
||||
|
||||
return self._api.calculate_fee(symbol=symbol, type=type, side=side, amount=amount,
|
||||
price=price, takerOrMaker=taker_or_maker)['rate']
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get fee info due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
import logging
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from bittrex.bittrex import API_V1_1, API_V2_0
|
||||
from bittrex.bittrex import Bittrex as _Bittrex
|
||||
from requests.exceptions import ContentDecodingError
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.exchange.interface import Exchange
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_API: _Bittrex = None
|
||||
_API_V2: _Bittrex = None
|
||||
_EXCHANGE_CONF: dict = {}
|
||||
|
||||
|
||||
class Bittrex(Exchange):
|
||||
"""
|
||||
Bittrex API wrapper.
|
||||
"""
|
||||
# Base URL and API endpoints
|
||||
BASE_URL: str = 'https://www.bittrex.com'
|
||||
PAIR_DETAIL_METHOD: str = BASE_URL + '/Market/Index'
|
||||
|
||||
def __init__(self, config: dict) -> None:
|
||||
global _API, _API_V2, _EXCHANGE_CONF
|
||||
|
||||
_EXCHANGE_CONF.update(config)
|
||||
_API = _Bittrex(
|
||||
api_key=_EXCHANGE_CONF['key'],
|
||||
api_secret=_EXCHANGE_CONF['secret'],
|
||||
calls_per_second=1,
|
||||
api_version=API_V1_1,
|
||||
)
|
||||
_API_V2 = _Bittrex(
|
||||
api_key=_EXCHANGE_CONF['key'],
|
||||
api_secret=_EXCHANGE_CONF['secret'],
|
||||
calls_per_second=1,
|
||||
api_version=API_V2_0,
|
||||
)
|
||||
self.cached_ticker = {}
|
||||
|
||||
@staticmethod
|
||||
def _validate_response(response) -> None:
|
||||
"""
|
||||
Validates the given bittrex response
|
||||
and raises a ContentDecodingError if a non-fatal issue happened.
|
||||
"""
|
||||
temp_error_messages = [
|
||||
'NO_API_RESPONSE',
|
||||
'MIN_TRADE_REQUIREMENT_NOT_MET',
|
||||
]
|
||||
if response['message'] in temp_error_messages:
|
||||
raise ContentDecodingError(response['message'])
|
||||
|
||||
@property
|
||||
def fee(self) -> float:
|
||||
# 0.25 %: See https://bittrex.com/fees
|
||||
return 0.0025
|
||||
|
||||
def buy(self, pair: str, rate: float, amount: float) -> str:
|
||||
data = _API.buy_limit(pair.replace('_', '-'), amount, rate)
|
||||
if not data['success']:
|
||||
Bittrex._validate_response(data)
|
||||
raise OperationalException('{message} params=({pair}, {rate}, {amount})'.format(
|
||||
message=data['message'],
|
||||
pair=pair,
|
||||
rate=rate,
|
||||
amount=amount))
|
||||
return data['result']['uuid']
|
||||
|
||||
def sell(self, pair: str, rate: float, amount: float) -> str:
|
||||
data = _API.sell_limit(pair.replace('_', '-'), amount, rate)
|
||||
if not data['success']:
|
||||
Bittrex._validate_response(data)
|
||||
raise OperationalException('{message} params=({pair}, {rate}, {amount})'.format(
|
||||
message=data['message'],
|
||||
pair=pair,
|
||||
rate=rate,
|
||||
amount=amount))
|
||||
return data['result']['uuid']
|
||||
|
||||
def get_balance(self, currency: str) -> float:
|
||||
data = _API.get_balance(currency)
|
||||
if not data['success']:
|
||||
Bittrex._validate_response(data)
|
||||
raise OperationalException('{message} params=({currency})'.format(
|
||||
message=data['message'],
|
||||
currency=currency))
|
||||
return float(data['result']['Balance'] or 0.0)
|
||||
|
||||
def get_balances(self):
|
||||
data = _API.get_balances()
|
||||
if not data['success']:
|
||||
Bittrex._validate_response(data)
|
||||
raise OperationalException('{message}'.format(message=data['message']))
|
||||
return data['result']
|
||||
|
||||
def get_ticker(self, pair: str, refresh: Optional[bool] = True) -> dict:
|
||||
if refresh or pair not in self.cached_ticker.keys():
|
||||
data = _API.get_ticker(pair.replace('_', '-'))
|
||||
if not data['success']:
|
||||
Bittrex._validate_response(data)
|
||||
raise OperationalException('{message} params=({pair})'.format(
|
||||
message=data['message'],
|
||||
pair=pair))
|
||||
keys = ['Bid', 'Ask', 'Last']
|
||||
if not data.get('result') or\
|
||||
not all(key in data.get('result', {}) for key in keys) or\
|
||||
not all(data.get('result', {})[key] is not None for key in keys):
|
||||
raise ContentDecodingError('Invalid response from Bittrex params=({pair})'.format(
|
||||
pair=pair))
|
||||
# Update the pair
|
||||
self.cached_ticker[pair] = {
|
||||
'bid': float(data['result']['Bid']),
|
||||
'ask': float(data['result']['Ask']),
|
||||
'last': float(data['result']['Last']),
|
||||
}
|
||||
return self.cached_ticker[pair]
|
||||
|
||||
def get_ticker_history(self, pair: str, tick_interval: int) -> List[Dict]:
|
||||
if tick_interval == 1:
|
||||
interval = 'oneMin'
|
||||
elif tick_interval == 5:
|
||||
interval = 'fiveMin'
|
||||
elif tick_interval == 30:
|
||||
interval = 'thirtyMin'
|
||||
elif tick_interval == 60:
|
||||
interval = 'hour'
|
||||
elif tick_interval == 1440:
|
||||
interval = 'Day'
|
||||
else:
|
||||
raise ValueError('Unknown tick_interval: {}'.format(tick_interval))
|
||||
|
||||
data = _API_V2.get_candles(pair.replace('_', '-'), interval)
|
||||
|
||||
# These sanity check are necessary because bittrex cannot keep their API stable.
|
||||
if not data.get('result'):
|
||||
raise ContentDecodingError('Invalid response from Bittrex params=({pair})'.format(
|
||||
pair=pair))
|
||||
|
||||
for prop in ['C', 'V', 'O', 'H', 'L', 'T']:
|
||||
for tick in data['result']:
|
||||
if prop not in tick.keys():
|
||||
raise ContentDecodingError('Required property {} not present '
|
||||
'in response params=({})'.format(prop, pair))
|
||||
|
||||
if not data['success']:
|
||||
Bittrex._validate_response(data)
|
||||
raise OperationalException('{message} params=({pair})'.format(
|
||||
message=data['message'],
|
||||
pair=pair))
|
||||
|
||||
return data['result']
|
||||
|
||||
def get_order(self, order_id: str) -> Dict:
|
||||
data = _API.get_order(order_id)
|
||||
if not data['success']:
|
||||
Bittrex._validate_response(data)
|
||||
raise OperationalException('{message} params=({order_id})'.format(
|
||||
message=data['message'],
|
||||
order_id=order_id))
|
||||
data = data['result']
|
||||
return {
|
||||
'id': data['OrderUuid'],
|
||||
'type': data['Type'],
|
||||
'pair': data['Exchange'].replace('-', '_'),
|
||||
'opened': data['Opened'],
|
||||
'rate': data['PricePerUnit'],
|
||||
'amount': data['Quantity'],
|
||||
'remaining': data['QuantityRemaining'],
|
||||
'closed': data['Closed'],
|
||||
}
|
||||
|
||||
def cancel_order(self, order_id: str) -> None:
|
||||
data = _API.cancel(order_id)
|
||||
if not data['success']:
|
||||
Bittrex._validate_response(data)
|
||||
raise OperationalException('{message} params=({order_id})'.format(
|
||||
message=data['message'],
|
||||
order_id=order_id))
|
||||
|
||||
def get_pair_detail_url(self, pair: str) -> str:
|
||||
return self.PAIR_DETAIL_METHOD + '?MarketName={}'.format(pair.replace('_', '-'))
|
||||
|
||||
def get_markets(self) -> List[str]:
|
||||
data = _API.get_markets()
|
||||
if not data['success']:
|
||||
Bittrex._validate_response(data)
|
||||
raise OperationalException(data['message'])
|
||||
return [m['MarketName'].replace('-', '_') for m in data['result']]
|
||||
|
||||
def get_market_summaries(self) -> List[Dict]:
|
||||
data = _API.get_market_summaries()
|
||||
if not data['success']:
|
||||
Bittrex._validate_response(data)
|
||||
raise OperationalException(data['message'])
|
||||
return data['result']
|
||||
|
||||
def get_wallet_health(self) -> List[Dict]:
|
||||
data = _API_V2.get_wallet_health()
|
||||
if not data['success']:
|
||||
Bittrex._validate_response(data)
|
||||
raise OperationalException(data['message'])
|
||||
return [{
|
||||
'Currency': entry['Health']['Currency'],
|
||||
'IsActive': entry['Health']['IsActive'],
|
||||
'LastChecked': entry['Health']['LastChecked'],
|
||||
'Notice': entry['Currency'].get('Notice'),
|
||||
} for entry in data['result']]
|
||||
@@ -1,172 +0,0 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
|
||||
class Exchange(ABC):
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""
|
||||
Name of the exchange.
|
||||
:return: str representation of the class name
|
||||
"""
|
||||
return self.__class__.__name__
|
||||
|
||||
@property
|
||||
def fee(self) -> float:
|
||||
"""
|
||||
Fee for placing an order
|
||||
:return: percentage in float
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def buy(self, pair: str, rate: float, amount: float) -> str:
|
||||
"""
|
||||
Places a limit buy order.
|
||||
:param pair: Pair as str, format: BTC_ETH
|
||||
:param rate: Rate limit for order
|
||||
:param amount: The amount to purchase
|
||||
:return: order_id of the placed buy order
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def sell(self, pair: str, rate: float, amount: float) -> str:
|
||||
"""
|
||||
Places a limit sell order.
|
||||
:param pair: Pair as str, format: BTC_ETH
|
||||
:param rate: Rate limit for order
|
||||
:param amount: The amount to sell
|
||||
:return: order_id of the placed sell order
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def get_balance(self, currency: str) -> float:
|
||||
"""
|
||||
Gets account balance.
|
||||
:param currency: Currency as str, format: BTC
|
||||
:return: float
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def get_balances(self) -> List[dict]:
|
||||
"""
|
||||
Gets account balances across currencies
|
||||
:return: List of dicts, format: [
|
||||
{
|
||||
'Currency': str,
|
||||
'Balance': float,
|
||||
'Available': float,
|
||||
'Pending': float,
|
||||
}
|
||||
...
|
||||
]
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def get_ticker(self, pair: str, refresh: Optional[bool] = True) -> dict:
|
||||
"""
|
||||
Gets ticker for given pair.
|
||||
:param pair: Pair as str, format: BTC_ETC
|
||||
:param refresh: Shall we query a new value or a cached value is enough
|
||||
:return: dict, format: {
|
||||
'bid': float,
|
||||
'ask': float,
|
||||
'last': float
|
||||
}
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def get_ticker_history(self, pair: str, tick_interval: int) -> List[Dict]:
|
||||
"""
|
||||
Gets ticker history for given pair.
|
||||
:param pair: Pair as str, format: BTC_ETC
|
||||
:param tick_interval: ticker interval in minutes
|
||||
:return: list, format: [
|
||||
{
|
||||
'O': float, (Open)
|
||||
'H': float, (High)
|
||||
'L': float, (Low)
|
||||
'C': float, (Close)
|
||||
'V': float, (Volume)
|
||||
'T': datetime, (Time)
|
||||
'BV': float, (Base Volume)
|
||||
},
|
||||
...
|
||||
]
|
||||
"""
|
||||
|
||||
def get_order(self, order_id: str) -> Dict:
|
||||
"""
|
||||
Get order details for the given order_id.
|
||||
:param order_id: ID as str
|
||||
:return: dict, format: {
|
||||
'id': str,
|
||||
'type': str,
|
||||
'pair': str,
|
||||
'opened': str ISO 8601 datetime,
|
||||
'closed': str ISO 8601 datetime,
|
||||
'rate': float,
|
||||
'amount': float,
|
||||
'remaining': int
|
||||
}
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def cancel_order(self, order_id: str) -> None:
|
||||
"""
|
||||
Cancels order for given order_id.
|
||||
:param order_id: ID as str
|
||||
:return: None
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def get_pair_detail_url(self, pair: str) -> str:
|
||||
"""
|
||||
Returns the market detail url for the given pair.
|
||||
:param pair: Pair as str, format: BTC_ETC
|
||||
:return: URL as str
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def get_markets(self) -> List[str]:
|
||||
"""
|
||||
Returns all available markets.
|
||||
:return: List of all available pairs
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def get_market_summaries(self) -> List[Dict]:
|
||||
"""
|
||||
Returns a 24h market summary for all available markets
|
||||
:return: list, format: [
|
||||
{
|
||||
'MarketName': str,
|
||||
'High': float,
|
||||
'Low': float,
|
||||
'Volume': float,
|
||||
'Last': float,
|
||||
'TimeStamp': datetime,
|
||||
'BaseVolume': float,
|
||||
'Bid': float,
|
||||
'Ask': float,
|
||||
'OpenBuyOrders': int,
|
||||
'OpenSellOrders': int,
|
||||
'PrevDay': float,
|
||||
'Created': datetime
|
||||
},
|
||||
...
|
||||
]
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def get_wallet_health(self) -> List[Dict]:
|
||||
"""
|
||||
Returns a list of all wallet health information
|
||||
:return: list, format: [
|
||||
{
|
||||
'Currency': str,
|
||||
'IsActive': bool,
|
||||
'LastChecked': str,
|
||||
'Notice': str
|
||||
},
|
||||
...
|
||||
"""
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,4 @@
|
||||
from math import exp, pi, sqrt, cos
|
||||
from math import cos, exp, pi, sqrt
|
||||
|
||||
import numpy as np
|
||||
import talib as ta
|
||||
@@ -13,7 +13,7 @@ def went_down(series: Series) -> bool:
|
||||
return series < series.shift(1)
|
||||
|
||||
|
||||
def ehlers_super_smoother(series: Series, smoothing: float = 6) -> type(Series):
|
||||
def ehlers_super_smoother(series: Series, smoothing: float = 6) -> Series:
|
||||
magic = pi * sqrt(2) / smoothing
|
||||
a1 = exp(-magic)
|
||||
coeff2 = 2 * a1 * cos(magic)
|
||||
|
||||
@@ -5,11 +5,15 @@ Read the documentation to know what cli arguments you need.
|
||||
"""
|
||||
import logging
|
||||
import sys
|
||||
from argparse import Namespace
|
||||
from typing import List
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.arguments import Arguments
|
||||
from freqtrade.configuration import Configuration
|
||||
from freqtrade.configuration import Configuration, set_loggers
|
||||
from freqtrade.freqtradebot import FreqtradeBot
|
||||
from freqtrade.state import State
|
||||
from freqtrade.rpc import RPCMessageType
|
||||
|
||||
logger = logging.getLogger('freqtrade')
|
||||
|
||||
@@ -21,7 +25,7 @@ def main(sysargv: List[str]) -> None:
|
||||
"""
|
||||
arguments = Arguments(
|
||||
sysargv,
|
||||
'Simple High Frequency Trading Bot for crypto currencies'
|
||||
'Free, open source crypto trading bot'
|
||||
)
|
||||
args = arguments.get_parsed_arg()
|
||||
|
||||
@@ -35,33 +39,49 @@ def main(sysargv: List[str]) -> None:
|
||||
return_code = 1
|
||||
try:
|
||||
# Load and validate configuration
|
||||
config = Configuration(args).get_config()
|
||||
config = Configuration(args, None).get_config()
|
||||
|
||||
# Init the bot
|
||||
freqtrade = FreqtradeBot(config)
|
||||
|
||||
state = None
|
||||
while 1:
|
||||
while True:
|
||||
state = freqtrade.worker(old_state=state)
|
||||
if state == State.RELOAD_CONF:
|
||||
freqtrade = reconfigure(freqtrade, args)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.info('SIGINT received, aborting ...')
|
||||
return_code = 0
|
||||
except OperationalException as e:
|
||||
logger.error(str(e))
|
||||
return_code = 2
|
||||
except BaseException:
|
||||
logger.exception('Fatal exception!')
|
||||
finally:
|
||||
if freqtrade:
|
||||
freqtrade.clean()
|
||||
freqtrade.rpc.send_msg({
|
||||
'type': RPCMessageType.STATUS_NOTIFICATION,
|
||||
'status': 'process died'
|
||||
})
|
||||
freqtrade.cleanup()
|
||||
sys.exit(return_code)
|
||||
|
||||
|
||||
def set_loggers() -> None:
|
||||
def reconfigure(freqtrade: FreqtradeBot, args: Namespace) -> FreqtradeBot:
|
||||
"""
|
||||
Set the logger level for Third party libs
|
||||
:return: None
|
||||
Cleans up current instance, reloads the configuration and returns the new instance
|
||||
"""
|
||||
logging.getLogger('requests.packages.urllib3').setLevel(logging.INFO)
|
||||
logging.getLogger('telegram').setLevel(logging.INFO)
|
||||
# Clean up current modules
|
||||
freqtrade.cleanup()
|
||||
|
||||
# Create new instance
|
||||
freqtrade = FreqtradeBot(Configuration(args, None).get_config())
|
||||
freqtrade.rpc.send_msg({
|
||||
'type': RPCMessageType.STATUS_NOTIFICATION,
|
||||
'status': 'config reloaded'
|
||||
})
|
||||
return freqtrade
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Various tool function for Freqtrade and scripts
|
||||
"""
|
||||
|
||||
import json
|
||||
import gzip
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
@@ -10,6 +10,7 @@ from typing import Dict
|
||||
|
||||
import numpy as np
|
||||
from pandas import DataFrame
|
||||
import rapidjson
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -37,12 +38,7 @@ def datesarray_to_datetimearray(dates: np.ndarray) -> np.ndarray:
|
||||
An numpy-array of datetimes
|
||||
:return: numpy-array of datetime
|
||||
"""
|
||||
times = []
|
||||
dates = dates.astype(datetime)
|
||||
for index in range(0, dates.size):
|
||||
date = dates[index].to_pydatetime()
|
||||
times.append(date)
|
||||
return np.array(times)
|
||||
return dates.dt.to_pydatetime()
|
||||
|
||||
|
||||
def common_datearray(dfs: Dict[str, DataFrame]) -> np.ndarray:
|
||||
@@ -63,12 +59,57 @@ def common_datearray(dfs: Dict[str, DataFrame]) -> np.ndarray:
|
||||
return np.sort(arr, axis=0)
|
||||
|
||||
|
||||
def file_dump_json(filename, data) -> None:
|
||||
def file_dump_json(filename, data, is_zip=False) -> None:
|
||||
"""
|
||||
Dump JSON data into a file
|
||||
:param filename: file to create
|
||||
:param data: JSON Data to save
|
||||
:return:
|
||||
"""
|
||||
with open(filename, 'w') as fp:
|
||||
json.dump(data, fp, default=str)
|
||||
logger.info(f'dumping json to "{filename}"')
|
||||
|
||||
if is_zip:
|
||||
if not filename.endswith('.gz'):
|
||||
filename = filename + '.gz'
|
||||
with gzip.open(filename, 'w') as fp:
|
||||
rapidjson.dump(data, fp, default=str, number_mode=rapidjson.NM_NATIVE)
|
||||
else:
|
||||
with open(filename, 'w') as fp:
|
||||
rapidjson.dump(data, fp, default=str, number_mode=rapidjson.NM_NATIVE)
|
||||
|
||||
logger.debug(f'done json to "{filename}"')
|
||||
|
||||
|
||||
def json_load(datafile):
|
||||
"""
|
||||
load data with rapidjson
|
||||
Use this to have a consistent experience,
|
||||
sete number_mode to "NM_NATIVE" for greatest speed
|
||||
"""
|
||||
return rapidjson.load(datafile, number_mode=rapidjson.NM_NATIVE)
|
||||
|
||||
|
||||
def file_load_json(file):
|
||||
|
||||
gzipfile = file.with_suffix(file.suffix + '.gz')
|
||||
|
||||
# Try gzip file first, otherwise regular json file.
|
||||
if gzipfile.is_file():
|
||||
logger.debug('Loading ticker data from file %s', gzipfile)
|
||||
with gzip.open(gzipfile) as tickerdata:
|
||||
pairdata = json_load(tickerdata)
|
||||
elif file.is_file():
|
||||
logger.debug('Loading ticker data from file %s', file)
|
||||
with open(file) as tickerdata:
|
||||
pairdata = json_load(tickerdata)
|
||||
else:
|
||||
return None
|
||||
return pairdata
|
||||
|
||||
|
||||
def format_ms_time(date: int) -> str:
|
||||
"""
|
||||
convert MS date to readable format.
|
||||
: epoch-string in ms
|
||||
"""
|
||||
return datetime.fromtimestamp(date/1000.0).strftime('%Y-%m-%dT%H:%M:%S')
|
||||
|
||||
@@ -1,148 +1,49 @@
|
||||
# pragma pylint: disable=missing-docstring
|
||||
|
||||
import gzip
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from typing import Optional, List, Dict, Tuple
|
||||
from datetime import datetime
|
||||
from typing import Dict, Tuple
|
||||
import operator
|
||||
|
||||
from freqtrade import misc
|
||||
from freqtrade.exchange import get_ticker_history
|
||||
from user_data.hyperopt_conf import hyperopt_optimize_conf
|
||||
import arrow
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.optimize.default_hyperopt import DefaultHyperOpts # noqa: F401
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def trim_tickerlist(tickerlist: List[Dict], timerange: Tuple[Tuple, int, int]) -> List[Dict]:
|
||||
stype, start, stop = timerange
|
||||
if stype == (None, 'line'):
|
||||
return tickerlist[stop:]
|
||||
elif stype == ('line', None):
|
||||
return tickerlist[0:start]
|
||||
elif stype == ('index', 'index'):
|
||||
return tickerlist[start:stop]
|
||||
|
||||
return tickerlist
|
||||
|
||||
|
||||
def load_tickerdata_file(
|
||||
datadir: str, pair: str,
|
||||
ticker_interval: int,
|
||||
timerange: Optional[Tuple[Tuple, int, int]] = None) -> Optional[List[Dict]]:
|
||||
def get_timeframe(data: Dict[str, DataFrame]) -> Tuple[arrow.Arrow, arrow.Arrow]:
|
||||
"""
|
||||
Load a pair from file,
|
||||
:return dict OR empty if unsuccesful
|
||||
Get the maximum timeframe for the given backtest data
|
||||
:param data: dictionary with preprocessed backtesting data
|
||||
:return: tuple containing min_date, max_date
|
||||
"""
|
||||
path = make_testdata_path(datadir)
|
||||
file = os.path.join(path, '{pair}-{ticker_interval}.json'.format(
|
||||
pair=pair,
|
||||
ticker_interval=ticker_interval,
|
||||
))
|
||||
gzipfile = file + '.gz'
|
||||
|
||||
# If the file does not exist we download it when None is returned.
|
||||
# If file exists, read the file, load the json
|
||||
if os.path.isfile(gzipfile):
|
||||
logger.debug('Loading ticker data from file %s', gzipfile)
|
||||
with gzip.open(gzipfile) as tickerdata:
|
||||
pairdata = json.load(tickerdata)
|
||||
elif os.path.isfile(file):
|
||||
logger.debug('Loading ticker data from file %s', file)
|
||||
with open(file) as tickerdata:
|
||||
pairdata = json.load(tickerdata)
|
||||
else:
|
||||
return None
|
||||
|
||||
if timerange:
|
||||
pairdata = trim_tickerlist(pairdata, timerange)
|
||||
return pairdata
|
||||
timeframe = [
|
||||
(arrow.get(frame['date'].min()), arrow.get(frame['date'].max()))
|
||||
for frame in data.values()
|
||||
]
|
||||
return min(timeframe, key=operator.itemgetter(0))[0], \
|
||||
max(timeframe, key=operator.itemgetter(1))[1]
|
||||
|
||||
|
||||
def load_data(datadir: str, ticker_interval: int,
|
||||
pairs: Optional[List[str]] = None,
|
||||
refresh_pairs: Optional[bool] = False,
|
||||
timerange: Optional[Tuple[Tuple, int, int]] = None) -> Dict[str, List]:
|
||||
def validate_backtest_data(data: Dict[str, DataFrame], min_date: datetime,
|
||||
max_date: datetime, ticker_interval_mins: int) -> bool:
|
||||
"""
|
||||
Loads ticker history data for the given parameters
|
||||
:return: dict
|
||||
Validates preprocessed backtesting data for missing values and shows warnings about it that.
|
||||
|
||||
:param data: dictionary with preprocessed backtesting data
|
||||
:param min_date: start-date of the data
|
||||
:param max_date: end-date of the data
|
||||
:param ticker_interval_mins: ticker interval in minutes
|
||||
"""
|
||||
result = {}
|
||||
|
||||
_pairs = pairs or hyperopt_optimize_conf()['exchange']['pair_whitelist']
|
||||
|
||||
# If the user force the refresh of pairs
|
||||
if refresh_pairs:
|
||||
logger.info('Download data for all pairs and store them in %s', datadir)
|
||||
download_pairs(datadir, _pairs, ticker_interval)
|
||||
|
||||
for pair in _pairs:
|
||||
pairdata = load_tickerdata_file(datadir, pair, ticker_interval, timerange=timerange)
|
||||
if not pairdata:
|
||||
# download the tickerdata from exchange
|
||||
download_backtesting_testdata(datadir, pair=pair, interval=ticker_interval)
|
||||
# and retry reading the pair
|
||||
pairdata = load_tickerdata_file(datadir, pair, ticker_interval, timerange=timerange)
|
||||
result[pair] = pairdata
|
||||
return result
|
||||
|
||||
|
||||
def make_testdata_path(datadir: str) -> str:
|
||||
"""Return the path where testdata files are stored"""
|
||||
return datadir or os.path.abspath(
|
||||
os.path.join(
|
||||
os.path.dirname(__file__), '..', 'tests', 'testdata'
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def download_pairs(datadir, pairs: List[str], ticker_interval: int) -> bool:
|
||||
"""For each pairs passed in parameters, download the ticker intervals"""
|
||||
for pair in pairs:
|
||||
try:
|
||||
download_backtesting_testdata(datadir, pair=pair, interval=ticker_interval)
|
||||
except BaseException:
|
||||
logger.info(
|
||||
'Failed to download the pair: "%s", Interval: %s min',
|
||||
pair,
|
||||
ticker_interval
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
# FIX: 20180110, suggest rename interval to tick_interval
|
||||
def download_backtesting_testdata(datadir: str, pair: str, interval: int = 5) -> None:
|
||||
"""
|
||||
Download the latest 1 and 5 ticker intervals from Bittrex for the pairs passed in parameters
|
||||
Based on @Rybolov work: https://github.com/rybolov/freqtrade-data
|
||||
"""
|
||||
|
||||
path = make_testdata_path(datadir)
|
||||
logger.info(
|
||||
'Download the pair: "%s", Interval: %s min', pair, interval
|
||||
)
|
||||
|
||||
filename = os.path.join(path, '{pair}-{interval}.json'.format(
|
||||
pair=pair.replace("-", "_"),
|
||||
interval=interval,
|
||||
))
|
||||
|
||||
if os.path.isfile(filename):
|
||||
with open(filename, "rt") as file:
|
||||
data = json.load(file)
|
||||
else:
|
||||
data = []
|
||||
|
||||
logger.debug('Current Start: %s', data[1]['T'] if data else None)
|
||||
logger.debug('Current End: %s', data[-1:][0]['T'] if data else None)
|
||||
|
||||
# Extend data with new ticker history
|
||||
data.extend([
|
||||
row for row in get_ticker_history(pair=pair, tick_interval=int(interval))
|
||||
if row not in data
|
||||
])
|
||||
|
||||
data = sorted(data, key=lambda _data: _data['T'])
|
||||
logger.debug('New Start: %s', data[1]['T'])
|
||||
logger.debug('New End: %s', data[-1:][0]['T'])
|
||||
misc.file_dump_json(filename, data)
|
||||
# total difference in minutes / interval-minutes
|
||||
expected_frames = int((max_date - min_date).total_seconds() // 60 // ticker_interval_mins)
|
||||
found_missing = False
|
||||
for pair, df in data.items():
|
||||
dflen = len(df)
|
||||
if dflen < expected_frames:
|
||||
found_missing = True
|
||||
logger.warning("%s has missing frames: expected %s, got %s, that's %s missing values",
|
||||
pair, expected_frames, dflen, expected_frames - dflen)
|
||||
return found_missing
|
||||
|
||||
@@ -4,27 +4,48 @@
|
||||
This module contains the backtesting logic
|
||||
"""
|
||||
import logging
|
||||
import operator
|
||||
from argparse import Namespace
|
||||
from typing import Dict, Tuple, Any, List, Optional
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, NamedTuple, Optional
|
||||
|
||||
import arrow
|
||||
from pandas import DataFrame
|
||||
from tabulate import tabulate
|
||||
|
||||
import freqtrade.optimize as optimize
|
||||
from freqtrade import exchange
|
||||
from freqtrade.analyze import Analyze
|
||||
from freqtrade import optimize
|
||||
from freqtrade import DependencyException, constants
|
||||
from freqtrade.arguments import Arguments
|
||||
from freqtrade.configuration import Configuration
|
||||
from freqtrade.exchange import Bittrex
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.data import history
|
||||
from freqtrade.misc import file_dump_json
|
||||
from freqtrade.persistence import Trade
|
||||
|
||||
from freqtrade.resolvers import StrategyResolver
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.strategy.interface import SellType, IStrategy
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BacktestResult(NamedTuple):
|
||||
"""
|
||||
NamedTuple Defining BacktestResults inputs.
|
||||
"""
|
||||
pair: str
|
||||
profit_percent: float
|
||||
profit_abs: float
|
||||
open_time: datetime
|
||||
close_time: datetime
|
||||
open_index: int
|
||||
close_index: int
|
||||
trade_duration: float
|
||||
open_at_end: bool
|
||||
open_rate: float
|
||||
close_rate: float
|
||||
sell_reason: SellType
|
||||
|
||||
|
||||
class Backtesting(object):
|
||||
"""
|
||||
Backtesting class, this class contains all the logic to run a backtest
|
||||
@@ -33,62 +54,76 @@ class Backtesting(object):
|
||||
backtesting = Backtesting(config)
|
||||
backtesting.start()
|
||||
"""
|
||||
|
||||
def __init__(self, config: Dict[str, Any]) -> None:
|
||||
self.config = config
|
||||
self.analyze = None
|
||||
self.ticker_interval = None
|
||||
self.tickerdata_to_dataframe = None
|
||||
self.populate_buy_trend = None
|
||||
self.populate_sell_trend = None
|
||||
self._init()
|
||||
|
||||
def _init(self) -> None:
|
||||
"""
|
||||
Init objects required for backtesting
|
||||
:return: None
|
||||
"""
|
||||
self.analyze = Analyze(self.config)
|
||||
self.ticker_interval = self.analyze.strategy.ticker_interval
|
||||
self.tickerdata_to_dataframe = self.analyze.tickerdata_to_dataframe
|
||||
self.populate_buy_trend = self.analyze.populate_buy_trend
|
||||
self.populate_sell_trend = self.analyze.populate_sell_trend
|
||||
exchange._API = Bittrex({'key': '', 'secret': ''})
|
||||
# Reset keys for backtesting
|
||||
self.config['exchange']['key'] = ''
|
||||
self.config['exchange']['secret'] = ''
|
||||
self.config['exchange']['password'] = ''
|
||||
self.config['exchange']['uid'] = ''
|
||||
self.config['dry_run'] = True
|
||||
self.strategylist: List[IStrategy] = []
|
||||
if self.config.get('strategy_list', None):
|
||||
# Force one interval
|
||||
self.ticker_interval = str(self.config.get('ticker_interval'))
|
||||
self.ticker_interval_mins = constants.TICKER_INTERVAL_MINUTES[self.ticker_interval]
|
||||
for strat in list(self.config['strategy_list']):
|
||||
stratconf = deepcopy(self.config)
|
||||
stratconf['strategy'] = strat
|
||||
self.strategylist.append(StrategyResolver(stratconf).strategy)
|
||||
|
||||
@staticmethod
|
||||
def get_timeframe(data: Dict[str, DataFrame]) -> Tuple[arrow.Arrow, arrow.Arrow]:
|
||||
"""
|
||||
Get the maximum timeframe for the given backtest data
|
||||
:param data: dictionary with preprocessed backtesting data
|
||||
:return: tuple containing min_date, max_date
|
||||
"""
|
||||
timeframe = [
|
||||
(arrow.get(min(frame.date)), arrow.get(max(frame.date)))
|
||||
for frame in data.values()
|
||||
]
|
||||
return min(timeframe, key=operator.itemgetter(0))[0], \
|
||||
max(timeframe, key=operator.itemgetter(1))[1]
|
||||
else:
|
||||
# only one strategy
|
||||
self.strategylist.append(StrategyResolver(self.config).strategy)
|
||||
# Load one strategy
|
||||
self._set_strategy(self.strategylist[0])
|
||||
|
||||
def _generate_text_table(self, data: Dict[str, Dict], results: DataFrame) -> str:
|
||||
self.exchange = Exchange(self.config)
|
||||
self.fee = self.exchange.get_fee()
|
||||
|
||||
def _set_strategy(self, strategy):
|
||||
"""
|
||||
Load strategy into backtesting
|
||||
"""
|
||||
self.strategy = strategy
|
||||
self.ticker_interval = self.config.get('ticker_interval')
|
||||
self.ticker_interval_mins = constants.TICKER_INTERVAL_MINUTES[self.ticker_interval]
|
||||
self.tickerdata_to_dataframe = strategy.tickerdata_to_dataframe
|
||||
self.advise_buy = strategy.advise_buy
|
||||
self.advise_sell = strategy.advise_sell
|
||||
|
||||
def _generate_text_table(self, data: Dict[str, Dict], results: DataFrame,
|
||||
skip_nan: bool = False) -> str:
|
||||
"""
|
||||
Generates and returns a text table for the given backtest data and the results dataframe
|
||||
:return: pretty printed table with tabulate as str
|
||||
"""
|
||||
stake_currency = self.config.get('stake_currency')
|
||||
stake_currency = str(self.config.get('stake_currency'))
|
||||
max_open_trades = self.config.get('max_open_trades')
|
||||
|
||||
floatfmt = ('s', 'd', '.2f', '.8f', '.1f')
|
||||
floatfmt = ('s', 'd', '.2f', '.2f', '.8f', '.2f', 'd', '.1f', '.1f')
|
||||
tabular_data = []
|
||||
headers = ['pair', 'buy count', 'avg profit %',
|
||||
'total profit ' + stake_currency, 'avg duration', 'profit', 'loss']
|
||||
headers = ['pair', 'buy count', 'avg profit %', 'cum profit %',
|
||||
'tot profit ' + stake_currency, 'tot profit %', 'avg duration',
|
||||
'profit', 'loss']
|
||||
for pair in data:
|
||||
result = results[results.currency == pair]
|
||||
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_BTC.sum(),
|
||||
result.duration.mean(),
|
||||
len(result[result.profit_BTC > 0]),
|
||||
len(result[result.profit_BTC < 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
|
||||
@@ -96,25 +131,87 @@ class Backtesting(object):
|
||||
'TOTAL',
|
||||
len(results.index),
|
||||
results.profit_percent.mean() * 100.0,
|
||||
results.profit_BTC.sum(),
|
||||
results.duration.mean(),
|
||||
len(results[results.profit_BTC > 0]),
|
||||
len(results[results.profit_BTC < 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])
|
||||
])
|
||||
return tabulate(tabular_data, headers=headers, floatfmt=floatfmt)
|
||||
# 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:
|
||||
"""
|
||||
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: str, results: DataFrame,
|
||||
strategyname: Optional[str] = None) -> None:
|
||||
|
||||
records = [(t.pair, t.profit_percent, t.open_time.timestamp(),
|
||||
t.close_time.timestamp(), t.open_index - 1, t.trade_duration,
|
||||
t.open_rate, t.close_rate, t.open_at_end, t.sell_reason.value)
|
||||
for index, t in results.iterrows()]
|
||||
|
||||
if records:
|
||||
if strategyname:
|
||||
# Inject strategyname to filename
|
||||
recname = Path(recordfilename)
|
||||
recordfilename = str(Path.joinpath(
|
||||
recname.parent, f'{recname.stem}-{strategyname}').with_suffix(recname.suffix))
|
||||
logger.info('Dumping backtest results to %s', recordfilename)
|
||||
file_dump_json(recordfilename, records)
|
||||
|
||||
def _get_sell_trade_entry(
|
||||
self, pair: str, buy_row: DataFrame,
|
||||
partial_ticker: List, trade_count_lock: Dict, args: Dict) -> Optional[Tuple]:
|
||||
partial_ticker: List, trade_count_lock: Dict, args: Dict) -> Optional[BacktestResult]:
|
||||
|
||||
stake_amount = args['stake_amount']
|
||||
max_open_trades = args.get('max_open_trades', 0)
|
||||
trade = Trade(
|
||||
open_rate=buy_row.close,
|
||||
open_rate=buy_row.open,
|
||||
open_date=buy_row.date,
|
||||
stake_amount=stake_amount,
|
||||
amount=stake_amount / buy_row.open,
|
||||
fee=exchange.get_fee()
|
||||
fee_open=self.fee,
|
||||
fee_close=self.fee
|
||||
)
|
||||
|
||||
# calculate win/lose forwards from buy point
|
||||
@@ -124,17 +221,61 @@ class Backtesting(object):
|
||||
trade_count_lock[sell_row.date] = trade_count_lock.get(sell_row.date, 0) + 1
|
||||
|
||||
buy_signal = sell_row.buy
|
||||
if self.analyze.should_sell(trade, sell_row.close, sell_row.date, buy_signal,
|
||||
sell_row.sell):
|
||||
return \
|
||||
sell_row, \
|
||||
(
|
||||
pair,
|
||||
trade.calc_profit_percent(rate=sell_row.close),
|
||||
trade.calc_profit(rate=sell_row.close),
|
||||
(sell_row.date - buy_row.date).seconds // 60
|
||||
), \
|
||||
sell_row.date
|
||||
sell = self.strategy.should_sell(trade, sell_row.open, sell_row.date, buy_signal,
|
||||
sell_row.sell, low=sell_row.low, high=sell_row.high)
|
||||
if sell.sell_flag:
|
||||
|
||||
trade_dur = int((sell_row.date - buy_row.date).total_seconds() // 60)
|
||||
# Special handling if high or low hit STOP_LOSS or ROI
|
||||
if sell.sell_type in (SellType.STOP_LOSS, SellType.TRAILING_STOP_LOSS):
|
||||
# Set close_rate to stoploss
|
||||
closerate = trade.stop_loss
|
||||
elif sell.sell_type == (SellType.ROI):
|
||||
# get next entry in min_roi > to trade duration
|
||||
# Interface.py skips on trade_duration <= duration
|
||||
roi_entry = max(list(filter(lambda x: trade_dur >= x,
|
||||
self.strategy.minimal_roi.keys())))
|
||||
roi = self.strategy.minimal_roi[roi_entry]
|
||||
|
||||
# - (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:
|
||||
closerate = sell_row.open
|
||||
|
||||
return BacktestResult(pair=pair,
|
||||
profit_percent=trade.calc_profit_percent(rate=closerate),
|
||||
profit_abs=trade.calc_profit(rate=closerate),
|
||||
open_time=buy_row.date,
|
||||
close_time=sell_row.date,
|
||||
trade_duration=trade_dur,
|
||||
open_index=buy_row.Index,
|
||||
close_index=sell_row.Index,
|
||||
open_at_end=False,
|
||||
open_rate=buy_row.open,
|
||||
close_rate=closerate,
|
||||
sell_reason=sell.sell_type
|
||||
)
|
||||
if partial_ticker:
|
||||
# no sell condition found - trade stil open at end of backtest period
|
||||
sell_row = partial_ticker[-1]
|
||||
btr = BacktestResult(pair=pair,
|
||||
profit_percent=trade.calc_profit_percent(rate=sell_row.open),
|
||||
profit_abs=trade.calc_profit(rate=sell_row.open),
|
||||
open_time=buy_row.date,
|
||||
close_time=sell_row.date,
|
||||
trade_duration=int((
|
||||
sell_row.date - buy_row.date).total_seconds() // 60),
|
||||
open_index=buy_row.Index,
|
||||
close_index=sell_row.Index,
|
||||
open_at_end=True,
|
||||
open_rate=buy_row.open,
|
||||
close_rate=sell_row.open,
|
||||
sell_reason=SellType.FORCE_SELL
|
||||
)
|
||||
logger.debug('Force_selling still open trade %s with %s perc - %s', btr.pair,
|
||||
btr.profit_percent, btr.profit_abs)
|
||||
return btr
|
||||
return None
|
||||
|
||||
def backtest(self, args: Dict) -> DataFrame:
|
||||
@@ -149,32 +290,56 @@ class Backtesting(object):
|
||||
stake_amount: btc amount to use for each trade
|
||||
processed: a processed dictionary with format {pair, data}
|
||||
max_open_trades: maximum number of concurrent trades (default: 0, disabled)
|
||||
realistic: do we try to simulate realistic trades? (default: True)
|
||||
sell_profit_only: sell if profit only
|
||||
use_sell_signal: act on sell-signal
|
||||
position_stacking: do we allow position stacking? (default: False)
|
||||
:return: DataFrame
|
||||
"""
|
||||
headers = ['date', 'buy', 'open', 'close', 'sell']
|
||||
headers = ['date', 'buy', 'open', 'close', 'sell', 'low', 'high']
|
||||
processed = args['processed']
|
||||
max_open_trades = args.get('max_open_trades', 0)
|
||||
realistic = args.get('realistic', False)
|
||||
record = args.get('record', None)
|
||||
records = []
|
||||
position_stacking = args.get('position_stacking', False)
|
||||
start_date = args['start_date']
|
||||
end_date = args['end_date']
|
||||
trades = []
|
||||
trade_count_lock = {}
|
||||
trade_count_lock: Dict = {}
|
||||
ticker: Dict = {}
|
||||
pairs = []
|
||||
# Create ticker dict
|
||||
for pair, pair_data in processed.items():
|
||||
pair_data['buy'], pair_data['sell'] = 0, 0 # cleanup from previous run
|
||||
|
||||
ticker_data = self.populate_sell_trend(self.populate_buy_trend(pair_data))[headers]
|
||||
ticker = [x for x in ticker_data.itertuples()]
|
||||
ticker_data = self.advise_sell(
|
||||
self.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy()
|
||||
|
||||
# to avoid using data from future, we buy/sell with signal from previous candle
|
||||
ticker_data.loc[:, 'buy'] = ticker_data['buy'].shift(1)
|
||||
ticker_data.loc[:, 'sell'] = ticker_data['sell'].shift(1)
|
||||
|
||||
ticker_data.drop(ticker_data.head(1).index, inplace=True)
|
||||
|
||||
# Convert from Pandas to list for performance reasons
|
||||
# (Looping Pandas is slow.)
|
||||
ticker[pair] = [x for x in ticker_data.itertuples()]
|
||||
pairs.append(pair)
|
||||
|
||||
lock_pair_until: Dict = {}
|
||||
tmp = start_date + timedelta(minutes=self.ticker_interval_mins)
|
||||
index = 0
|
||||
# Loop timerange and test per pair
|
||||
while tmp < end_date:
|
||||
# print(f"time: {tmp}")
|
||||
for i, pair in enumerate(ticker):
|
||||
try:
|
||||
row = ticker[pair][index]
|
||||
except IndexError:
|
||||
# missing Data for one pair ...
|
||||
# Warnings for this are shown by `validate_backtest_data`
|
||||
continue
|
||||
|
||||
lock_pair_until = None
|
||||
for index, row in enumerate(ticker):
|
||||
if row.buy == 0 or row.sell == 1:
|
||||
continue # skip rows where no buy signal or that would immediately sell off
|
||||
|
||||
if realistic:
|
||||
if lock_pair_until is not None and row.date <= lock_pair_until:
|
||||
if not position_stacking:
|
||||
if pair in lock_pair_until and row.date <= lock_pair_until[pair]:
|
||||
continue
|
||||
if max_open_trades > 0:
|
||||
# Check if max_open_trades has already been reached for the given date
|
||||
@@ -183,97 +348,111 @@ class Backtesting(object):
|
||||
|
||||
trade_count_lock[row.date] = trade_count_lock.get(row.date, 0) + 1
|
||||
|
||||
ret = self._get_sell_trade_entry(pair, row, ticker[index + 1:],
|
||||
trade_count_lock, args)
|
||||
trade_entry = self._get_sell_trade_entry(pair, row, ticker[pair][index + 1:],
|
||||
trade_count_lock, args)
|
||||
|
||||
if ret:
|
||||
row2, trade_entry, next_date = ret
|
||||
lock_pair_until = next_date
|
||||
if trade_entry:
|
||||
lock_pair_until[pair] = trade_entry.close_time
|
||||
trades.append(trade_entry)
|
||||
if record:
|
||||
# Note, need to be json.dump friendly
|
||||
# record a tuple of pair, current_profit_percent,
|
||||
# entry-date, duration
|
||||
records.append((pair, trade_entry[1],
|
||||
row.date.strftime('%s'),
|
||||
row2.date.strftime('%s'),
|
||||
index, trade_entry[3]))
|
||||
# For now export inside backtest(), maybe change so that backtest()
|
||||
# returns a tuple like: (dataframe, records, logs, etc)
|
||||
if record and record.find('trades') >= 0:
|
||||
logger.info('Dumping backtest results')
|
||||
file_dump_json('backtest-result.json', records)
|
||||
labels = ['currency', 'profit_percent', 'profit_BTC', 'duration']
|
||||
return DataFrame.from_records(trades, columns=labels)
|
||||
else:
|
||||
# Set lock_pair_until to end of testing period if trade could not be closed
|
||||
# This happens only if the buy-signal was with the last candle
|
||||
lock_pair_until[pair] = end_date
|
||||
|
||||
tmp += timedelta(minutes=self.ticker_interval_mins)
|
||||
index += 1
|
||||
return DataFrame.from_records(trades, columns=BacktestResult._fields)
|
||||
|
||||
def start(self) -> None:
|
||||
"""
|
||||
Run a backtesting end-to-end
|
||||
:return: None
|
||||
"""
|
||||
data = {}
|
||||
data: Dict[str, Any] = {}
|
||||
pairs = self.config['exchange']['pair_whitelist']
|
||||
logger.info('Using stake_currency: %s ...', self.config['stake_currency'])
|
||||
logger.info('Using stake_amount: %s ...', self.config['stake_amount'])
|
||||
|
||||
if self.config.get('live'):
|
||||
logger.info('Downloading data for all pairs in whitelist ...')
|
||||
for pair in pairs:
|
||||
data[pair] = exchange.get_ticker_history(pair, self.ticker_interval)
|
||||
self.exchange.refresh_latest_ohlcv([(pair, self.ticker_interval) for pair in pairs])
|
||||
data = {key[0]: value for key, value in self.exchange._klines.items()}
|
||||
|
||||
else:
|
||||
logger.info('Using local backtesting data (using whitelist in given config) ...')
|
||||
|
||||
timerange = Arguments.parse_timerange(self.config.get('timerange'))
|
||||
data = optimize.load_data(
|
||||
self.config['datadir'],
|
||||
timerange = Arguments.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']) if self.config.get('datadir') else None,
|
||||
pairs=pairs,
|
||||
ticker_interval=self.ticker_interval,
|
||||
refresh_pairs=self.config.get('refresh_pairs', False),
|
||||
exchange=self.exchange,
|
||||
timerange=timerange
|
||||
)
|
||||
|
||||
# Ignore max_open_trades in backtesting, except realistic flag was passed
|
||||
if self.config.get('realistic_simulation', False):
|
||||
if not data:
|
||||
logger.critical("No data found. Terminating.")
|
||||
return
|
||||
# Use max_open_trades in backtesting, except --disable-max-market-positions is set
|
||||
if self.config.get('use_max_market_positions', True):
|
||||
max_open_trades = self.config['max_open_trades']
|
||||
else:
|
||||
logger.info('Ignoring max_open_trades (realistic_simulation not set) ...')
|
||||
logger.info('Ignoring max_open_trades (--disable-max-market-positions was used) ...')
|
||||
max_open_trades = 0
|
||||
all_results = {}
|
||||
|
||||
preprocessed = self.tickerdata_to_dataframe(data)
|
||||
for strat in self.strategylist:
|
||||
logger.info("Running backtesting for Strategy %s", strat.get_strategy_name())
|
||||
self._set_strategy(strat)
|
||||
|
||||
# Print timeframe
|
||||
min_date, max_date = self.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
|
||||
)
|
||||
|
||||
# Execute backtest and print results
|
||||
sell_profit_only = self.config.get('experimental', {}).get('sell_profit_only', False)
|
||||
use_sell_signal = self.config.get('experimental', {}).get('use_sell_signal', False)
|
||||
results = self.backtest(
|
||||
{
|
||||
'stake_amount': self.config.get('stake_amount'),
|
||||
'processed': preprocessed,
|
||||
'max_open_trades': max_open_trades,
|
||||
'realistic': self.config.get('realistic_simulation', False),
|
||||
'sell_profit_only': sell_profit_only,
|
||||
'use_sell_signal': use_sell_signal,
|
||||
'record': self.config.get('export')
|
||||
}
|
||||
)
|
||||
logger.info(
|
||||
'\n==================================== '
|
||||
'BACKTESTING REPORT'
|
||||
' ====================================\n'
|
||||
'%s',
|
||||
self._generate_text_table(
|
||||
data,
|
||||
results
|
||||
min_date, max_date = optimize.get_timeframe(data)
|
||||
# Validate dataframe for missing values (mainly at start and end, as fillup is called)
|
||||
optimize.validate_backtest_data(data, min_date, max_date,
|
||||
constants.TICKER_INTERVAL_MINUTES[self.ticker_interval])
|
||||
logger.info(
|
||||
'Measuring data from %s up to %s (%s days)..',
|
||||
min_date.isoformat(),
|
||||
max_date.isoformat(),
|
||||
(max_date - min_date).days
|
||||
)
|
||||
)
|
||||
# need to reprocess data every time to populate signals
|
||||
preprocessed = self.strategy.tickerdata_to_dataframe(data)
|
||||
|
||||
# Execute backtest and print results
|
||||
all_results[self.strategy.get_strategy_name()] = self.backtest(
|
||||
{
|
||||
'stake_amount': self.config.get('stake_amount'),
|
||||
'processed': preprocessed,
|
||||
'max_open_trades': max_open_trades,
|
||||
'position_stacking': self.config.get('position_stacking', False),
|
||||
'start_date': min_date,
|
||||
'end_date': max_date,
|
||||
}
|
||||
)
|
||||
|
||||
for strategy, results in all_results.items():
|
||||
|
||||
if self.config.get('export', False):
|
||||
self._store_backtest_result(self.config['exportfilename'], results,
|
||||
strategy if len(self.strategylist) > 1 else None)
|
||||
|
||||
print(f"Result for strategy {strategy}")
|
||||
print(' BACKTESTING REPORT '.center(133, '='))
|
||||
print(self._generate_text_table(data, results))
|
||||
|
||||
print(' SELL REASON STATS '.center(133, '='))
|
||||
print(self._generate_text_table_sell_reason(data, results))
|
||||
|
||||
print(' LEFT OPEN TRADES REPORT '.center(133, '='))
|
||||
print(self._generate_text_table(data, results.loc[results.open_at_end], True))
|
||||
print()
|
||||
if len(all_results) > 1:
|
||||
# Print Strategy summary table
|
||||
print(' Strategy Summary '.center(133, '='))
|
||||
print(self._generate_text_table_strategy(all_results))
|
||||
print('\nFor more details, please look at the detail tables above')
|
||||
|
||||
|
||||
def setup_configuration(args: Namespace) -> Dict[str, Any]:
|
||||
@@ -282,13 +461,17 @@ def setup_configuration(args: Namespace) -> Dict[str, Any]:
|
||||
:param args: Cli args from Arguments()
|
||||
:return: Configuration
|
||||
"""
|
||||
configuration = Configuration(args)
|
||||
configuration = Configuration(args, RunMode.BACKTEST)
|
||||
config = configuration.get_config()
|
||||
|
||||
# Ensure we do not use Exchange credentials
|
||||
config['exchange']['key'] = ''
|
||||
config['exchange']['secret'] = ''
|
||||
|
||||
if config['stake_amount'] == constants.UNLIMITED_STAKE_AMOUNT:
|
||||
raise DependencyException('stake amount could not be "%s" for backtesting' %
|
||||
constants.UNLIMITED_STAKE_AMOUNT)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
|
||||
226
freqtrade/optimize/default_hyperopt.py
Normal file
226
freqtrade/optimize/default_hyperopt.py
Normal file
@@ -0,0 +1,226 @@
|
||||
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
|
||||
|
||||
import talib.abstract as ta
|
||||
from pandas import DataFrame
|
||||
from typing import Dict, Any, Callable, List
|
||||
from functools import reduce
|
||||
|
||||
from skopt.space import Categorical, Dimension, Integer, Real
|
||||
|
||||
import freqtrade.vendor.qtpylib.indicators as qtpylib
|
||||
from freqtrade.optimize.hyperopt_interface import IHyperOpt
|
||||
|
||||
class_name = 'DefaultHyperOpts'
|
||||
|
||||
|
||||
class DefaultHyperOpts(IHyperOpt):
|
||||
"""
|
||||
Default hyperopt provided by freqtrade bot.
|
||||
You can override it with your own hyperopt
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
dataframe['adx'] = ta.ADX(dataframe)
|
||||
macd = ta.MACD(dataframe)
|
||||
dataframe['macd'] = macd['macd']
|
||||
dataframe['macdsignal'] = macd['macdsignal']
|
||||
dataframe['mfi'] = ta.MFI(dataframe)
|
||||
dataframe['rsi'] = ta.RSI(dataframe)
|
||||
stoch_fast = ta.STOCHF(dataframe)
|
||||
dataframe['fastd'] = stoch_fast['fastd']
|
||||
dataframe['minus_di'] = ta.MINUS_DI(dataframe)
|
||||
# Bollinger bands
|
||||
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
|
||||
dataframe['bb_lowerband'] = bollinger['lower']
|
||||
dataframe['bb_upperband'] = bollinger['upper']
|
||||
dataframe['sar'] = ta.SAR(dataframe)
|
||||
return dataframe
|
||||
|
||||
@staticmethod
|
||||
def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||
"""
|
||||
Define the buy strategy parameters to be used by hyperopt
|
||||
"""
|
||||
def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Buy strategy Hyperopt will build and use
|
||||
"""
|
||||
conditions = []
|
||||
# GUARDS AND TRENDS
|
||||
if 'mfi-enabled' in params and params['mfi-enabled']:
|
||||
conditions.append(dataframe['mfi'] < params['mfi-value'])
|
||||
if 'fastd-enabled' in params and params['fastd-enabled']:
|
||||
conditions.append(dataframe['fastd'] < params['fastd-value'])
|
||||
if 'adx-enabled' in params and params['adx-enabled']:
|
||||
conditions.append(dataframe['adx'] > params['adx-value'])
|
||||
if 'rsi-enabled' in params and params['rsi-enabled']:
|
||||
conditions.append(dataframe['rsi'] < params['rsi-value'])
|
||||
|
||||
# TRIGGERS
|
||||
if 'trigger' in params:
|
||||
if params['trigger'] == 'bb_lower':
|
||||
conditions.append(dataframe['close'] < dataframe['bb_lowerband'])
|
||||
if params['trigger'] == 'macd_cross_signal':
|
||||
conditions.append(qtpylib.crossed_above(
|
||||
dataframe['macd'], dataframe['macdsignal']
|
||||
))
|
||||
if params['trigger'] == 'sar_reversal':
|
||||
conditions.append(qtpylib.crossed_above(
|
||||
dataframe['close'], dataframe['sar']
|
||||
))
|
||||
|
||||
dataframe.loc[
|
||||
reduce(lambda x, y: x & y, conditions),
|
||||
'buy'] = 1
|
||||
|
||||
return dataframe
|
||||
|
||||
return populate_buy_trend
|
||||
|
||||
@staticmethod
|
||||
def indicator_space() -> List[Dimension]:
|
||||
"""
|
||||
Define your Hyperopt space for searching strategy parameters
|
||||
"""
|
||||
return [
|
||||
Integer(10, 25, name='mfi-value'),
|
||||
Integer(15, 45, name='fastd-value'),
|
||||
Integer(20, 50, name='adx-value'),
|
||||
Integer(20, 40, name='rsi-value'),
|
||||
Categorical([True, False], name='mfi-enabled'),
|
||||
Categorical([True, False], name='fastd-enabled'),
|
||||
Categorical([True, False], name='adx-enabled'),
|
||||
Categorical([True, False], name='rsi-enabled'),
|
||||
Categorical(['bb_lower', 'macd_cross_signal', 'sar_reversal'], name='trigger')
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def sell_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||
"""
|
||||
Define the sell strategy parameters to be used by hyperopt
|
||||
"""
|
||||
def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Sell strategy Hyperopt will build and use
|
||||
"""
|
||||
# print(params)
|
||||
conditions = []
|
||||
# GUARDS AND TRENDS
|
||||
if 'sell-mfi-enabled' in params and params['sell-mfi-enabled']:
|
||||
conditions.append(dataframe['mfi'] > params['sell-mfi-value'])
|
||||
if 'sell-fastd-enabled' in params and params['sell-fastd-enabled']:
|
||||
conditions.append(dataframe['fastd'] > params['sell-fastd-value'])
|
||||
if 'sell-adx-enabled' in params and params['sell-adx-enabled']:
|
||||
conditions.append(dataframe['adx'] < params['sell-adx-value'])
|
||||
if 'sell-rsi-enabled' in params and params['sell-rsi-enabled']:
|
||||
conditions.append(dataframe['rsi'] > params['sell-rsi-value'])
|
||||
|
||||
# TRIGGERS
|
||||
if 'sell-trigger' in params:
|
||||
if params['sell-trigger'] == 'sell-bb_upper':
|
||||
conditions.append(dataframe['close'] > dataframe['bb_upperband'])
|
||||
if params['sell-trigger'] == 'sell-macd_cross_signal':
|
||||
conditions.append(qtpylib.crossed_above(
|
||||
dataframe['macdsignal'], dataframe['macd']
|
||||
))
|
||||
if params['sell-trigger'] == 'sell-sar_reversal':
|
||||
conditions.append(qtpylib.crossed_above(
|
||||
dataframe['sar'], dataframe['close']
|
||||
))
|
||||
|
||||
dataframe.loc[
|
||||
reduce(lambda x, y: x & y, conditions),
|
||||
'sell'] = 1
|
||||
|
||||
return dataframe
|
||||
|
||||
return populate_sell_trend
|
||||
|
||||
@staticmethod
|
||||
def sell_indicator_space() -> List[Dimension]:
|
||||
"""
|
||||
Define your Hyperopt space for searching sell strategy parameters
|
||||
"""
|
||||
return [
|
||||
Integer(75, 100, name='sell-mfi-value'),
|
||||
Integer(50, 100, name='sell-fastd-value'),
|
||||
Integer(50, 100, name='sell-adx-value'),
|
||||
Integer(60, 100, name='sell-rsi-value'),
|
||||
Categorical([True, False], name='sell-mfi-enabled'),
|
||||
Categorical([True, False], name='sell-fastd-enabled'),
|
||||
Categorical([True, False], name='sell-adx-enabled'),
|
||||
Categorical([True, False], name='sell-rsi-enabled'),
|
||||
Categorical(['sell-bb_upper',
|
||||
'sell-macd_cross_signal',
|
||||
'sell-sar_reversal'], name='sell-trigger')
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def generate_roi_table(params: Dict) -> Dict[int, float]:
|
||||
"""
|
||||
Generate the ROI table that will be used by Hyperopt
|
||||
"""
|
||||
roi_table = {}
|
||||
roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3']
|
||||
roi_table[params['roi_t3']] = params['roi_p1'] + params['roi_p2']
|
||||
roi_table[params['roi_t3'] + params['roi_t2']] = params['roi_p1']
|
||||
roi_table[params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0
|
||||
|
||||
return roi_table
|
||||
|
||||
@staticmethod
|
||||
def stoploss_space() -> List[Dimension]:
|
||||
"""
|
||||
Stoploss Value to search
|
||||
"""
|
||||
return [
|
||||
Real(-0.5, -0.02, name='stoploss'),
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def roi_space() -> List[Dimension]:
|
||||
"""
|
||||
Values to search for each ROI steps
|
||||
"""
|
||||
return [
|
||||
Integer(10, 120, name='roi_t1'),
|
||||
Integer(10, 60, name='roi_t2'),
|
||||
Integer(10, 40, name='roi_t3'),
|
||||
Real(0.01, 0.04, name='roi_p1'),
|
||||
Real(0.01, 0.07, name='roi_p2'),
|
||||
Real(0.01, 0.20, name='roi_p3'),
|
||||
]
|
||||
|
||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators. Should be a copy of from strategy
|
||||
must align to populate_indicators in this file
|
||||
Only used when --spaces does not include buy
|
||||
"""
|
||||
dataframe.loc[
|
||||
(
|
||||
(dataframe['close'] < dataframe['bb_lowerband']) &
|
||||
(dataframe['mfi'] < 16) &
|
||||
(dataframe['adx'] > 25) &
|
||||
(dataframe['rsi'] < 21)
|
||||
),
|
||||
'buy'] = 1
|
||||
|
||||
return dataframe
|
||||
|
||||
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators. Should be a copy of from strategy
|
||||
must align to populate_indicators in this file
|
||||
Only used when --spaces does not include sell
|
||||
"""
|
||||
dataframe.loc[
|
||||
(
|
||||
(qtpylib.crossed_above(
|
||||
dataframe['macdsignal'], dataframe['macd']
|
||||
)) &
|
||||
(dataframe['fastd'] > 54)
|
||||
),
|
||||
'sell'] = 1
|
||||
return dataframe
|
||||
109
freqtrade/optimize/edge_cli.py
Normal file
109
freqtrade/optimize/edge_cli.py
Normal file
@@ -0,0 +1,109 @@
|
||||
# pragma pylint: disable=missing-docstring, W0212, too-many-arguments
|
||||
|
||||
"""
|
||||
This module contains the edge backtesting interface
|
||||
"""
|
||||
import logging
|
||||
from argparse import Namespace
|
||||
from typing import Dict, Any
|
||||
from tabulate import tabulate
|
||||
from freqtrade.edge import Edge
|
||||
|
||||
from freqtrade.arguments import Arguments
|
||||
from freqtrade.configuration import Configuration
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.resolvers import StrategyResolver
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class EdgeCli(object):
|
||||
"""
|
||||
EdgeCli class, this class contains all the logic to run edge backtesting
|
||||
|
||||
To run a edge backtest:
|
||||
edge = EdgeCli(config)
|
||||
edge.start()
|
||||
"""
|
||||
|
||||
def __init__(self, config: Dict[str, Any]) -> None:
|
||||
self.config = config
|
||||
|
||||
# Reset keys for edge
|
||||
self.config['exchange']['key'] = ''
|
||||
self.config['exchange']['secret'] = ''
|
||||
self.config['exchange']['password'] = ''
|
||||
self.config['exchange']['uid'] = ''
|
||||
self.config['dry_run'] = True
|
||||
self.exchange = Exchange(self.config)
|
||||
self.strategy = StrategyResolver(self.config).strategy
|
||||
|
||||
self.edge = Edge(config, self.exchange, self.strategy)
|
||||
self.edge._refresh_pairs = self.config.get('refresh_pairs', False)
|
||||
|
||||
self.timerange = Arguments.parse_timerange(None if self.config.get(
|
||||
'timerange') is None else str(self.config.get('timerange')))
|
||||
|
||||
self.edge._timerange = self.timerange
|
||||
|
||||
def _generate_edge_table(self, results: dict) -> str:
|
||||
|
||||
floatfmt = ('s', '.10g', '.2f', '.2f', '.2f', '.2f', 'd', '.d')
|
||||
tabular_data = []
|
||||
headers = ['pair', 'stoploss', 'win rate', 'risk reward ratio',
|
||||
'required risk reward', 'expectancy', 'total number of trades',
|
||||
'average duration (min)']
|
||||
|
||||
for result in results.items():
|
||||
if result[1].nb_trades > 0:
|
||||
tabular_data.append([
|
||||
result[0],
|
||||
result[1].stoploss,
|
||||
result[1].winrate,
|
||||
result[1].risk_reward_ratio,
|
||||
result[1].required_risk_reward,
|
||||
result[1].expectancy,
|
||||
result[1].nb_trades,
|
||||
round(result[1].avg_trade_duration)
|
||||
])
|
||||
|
||||
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
||||
return tabulate(tabular_data, headers=headers, # type: ignore
|
||||
floatfmt=floatfmt, tablefmt="pipe")
|
||||
|
||||
def start(self) -> None:
|
||||
self.edge.calculate()
|
||||
print('') # blank like for readability
|
||||
print(self._generate_edge_table(self.edge._cached_pairs))
|
||||
|
||||
|
||||
def setup_configuration(args: Namespace) -> Dict[str, Any]:
|
||||
"""
|
||||
Prepare the configuration for edge backtesting
|
||||
:param args: Cli args from Arguments()
|
||||
:return: Configuration
|
||||
"""
|
||||
configuration = Configuration(args, RunMode.EDGECLI)
|
||||
config = configuration.get_config()
|
||||
|
||||
# Ensure we do not use Exchange credentials
|
||||
config['exchange']['key'] = ''
|
||||
config['exchange']['secret'] = ''
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def start(args: Namespace) -> None:
|
||||
"""
|
||||
Start Edge script
|
||||
:param args: Cli args from Arguments()
|
||||
:return: None
|
||||
"""
|
||||
# Initialize configuration
|
||||
config = setup_configuration(args)
|
||||
logger.info('Starting freqtrade in Edge mode')
|
||||
|
||||
# Initialize Edge object
|
||||
edge_cli = EdgeCli(config)
|
||||
edge_cli.start()
|
||||
@@ -4,34 +4,35 @@
|
||||
This module contains the hyperopt logic
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import multiprocessing
|
||||
import os
|
||||
import pickle
|
||||
import signal
|
||||
import sys
|
||||
from argparse import Namespace
|
||||
from functools import reduce
|
||||
from math import exp
|
||||
from operator import itemgetter
|
||||
from typing import Dict, Any, Callable
|
||||
from pathlib import Path
|
||||
from pprint import pprint
|
||||
from typing import Any, Dict, List
|
||||
|
||||
import numpy
|
||||
import talib.abstract as ta
|
||||
from hyperopt import STATUS_FAIL, STATUS_OK, Trials, fmin, hp, space_eval, tpe
|
||||
from hyperopt.mongoexp import MongoTrials
|
||||
from joblib import Parallel, delayed, dump, load, wrap_non_picklable_objects
|
||||
from pandas import DataFrame
|
||||
from skopt import Optimizer
|
||||
from skopt.space import Dimension
|
||||
|
||||
import freqtrade.vendor.qtpylib.indicators as qtpylib
|
||||
from freqtrade.arguments import Arguments
|
||||
from freqtrade.configuration import Configuration
|
||||
from freqtrade.optimize import load_data
|
||||
from freqtrade.data.history import load_data
|
||||
from freqtrade.optimize import get_timeframe
|
||||
from freqtrade.optimize.backtesting import Backtesting
|
||||
from user_data.hyperopt_conf import hyperopt_optimize_conf
|
||||
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.resolvers import HyperOptResolver
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_LOSS = 100000 # just a big enough number to be bad result in loss optimization
|
||||
TICKERDATA_PICKLE = os.path.join('user_data', 'hyperopt_tickerdata.pkl')
|
||||
|
||||
|
||||
class Hyperopt(Backtesting):
|
||||
"""
|
||||
@@ -42,13 +43,14 @@ class Hyperopt(Backtesting):
|
||||
hyperopt.start()
|
||||
"""
|
||||
def __init__(self, config: Dict[str, Any]) -> None:
|
||||
|
||||
super().__init__(config)
|
||||
self.config = config
|
||||
self.custom_hyperopt = HyperOptResolver(self.config).hyperopt
|
||||
|
||||
# set TARGET_TRADES to suit your number concurrent trades so its realistic
|
||||
# to the number of days
|
||||
self.target_trades = 600
|
||||
self.total_tries = config.get('epochs', 0)
|
||||
self.current_tries = 0
|
||||
self.current_best_loss = 100
|
||||
|
||||
# max average trade duration in minutes
|
||||
@@ -60,146 +62,37 @@ class Hyperopt(Backtesting):
|
||||
# check that the reported Σ% values do not exceed this!
|
||||
self.expected_max_profit = 3.0
|
||||
|
||||
# Configuration and data used by hyperopt
|
||||
self.processed = None
|
||||
# Previous evaluations
|
||||
self.trials_file = os.path.join('user_data', 'hyperopt_results.pickle')
|
||||
self.trials: List = []
|
||||
|
||||
# Hyperopt Trials
|
||||
self.trials_file = os.path.join('user_data', 'hyperopt_trials.pickle')
|
||||
self.trials = Trials()
|
||||
def get_args(self, params):
|
||||
dimensions = self.hyperopt_space()
|
||||
# Ensure the number of dimensions match
|
||||
# the number of parameters in the list x.
|
||||
if len(params) != len(dimensions):
|
||||
raise ValueError('Mismatch in number of search-space dimensions. '
|
||||
f'len(dimensions)=={len(dimensions)} and len(x)=={len(params)}')
|
||||
|
||||
@staticmethod
|
||||
def populate_indicators(dataframe: DataFrame) -> DataFrame:
|
||||
"""
|
||||
Adds several different TA indicators to the given DataFrame
|
||||
"""
|
||||
dataframe['adx'] = ta.ADX(dataframe)
|
||||
dataframe['ao'] = qtpylib.awesome_oscillator(dataframe)
|
||||
dataframe['cci'] = ta.CCI(dataframe)
|
||||
macd = ta.MACD(dataframe)
|
||||
dataframe['macd'] = macd['macd']
|
||||
dataframe['macdsignal'] = macd['macdsignal']
|
||||
dataframe['macdhist'] = macd['macdhist']
|
||||
dataframe['mfi'] = ta.MFI(dataframe)
|
||||
dataframe['minus_dm'] = ta.MINUS_DM(dataframe)
|
||||
dataframe['minus_di'] = ta.MINUS_DI(dataframe)
|
||||
dataframe['plus_dm'] = ta.PLUS_DM(dataframe)
|
||||
dataframe['plus_di'] = ta.PLUS_DI(dataframe)
|
||||
dataframe['roc'] = ta.ROC(dataframe)
|
||||
dataframe['rsi'] = ta.RSI(dataframe)
|
||||
# Inverse Fisher transform on RSI, values [-1.0, 1.0] (https://goo.gl/2JGGoy)
|
||||
rsi = 0.1 * (dataframe['rsi'] - 50)
|
||||
dataframe['fisher_rsi'] = (numpy.exp(2 * rsi) - 1) / (numpy.exp(2 * rsi) + 1)
|
||||
# Inverse Fisher transform on RSI normalized, value [0.0, 100.0] (https://goo.gl/2JGGoy)
|
||||
dataframe['fisher_rsi_norma'] = 50 * (dataframe['fisher_rsi'] + 1)
|
||||
# Stoch
|
||||
stoch = ta.STOCH(dataframe)
|
||||
dataframe['slowd'] = stoch['slowd']
|
||||
dataframe['slowk'] = stoch['slowk']
|
||||
# Stoch fast
|
||||
stoch_fast = ta.STOCHF(dataframe)
|
||||
dataframe['fastd'] = stoch_fast['fastd']
|
||||
dataframe['fastk'] = stoch_fast['fastk']
|
||||
# Stoch RSI
|
||||
stoch_rsi = ta.STOCHRSI(dataframe)
|
||||
dataframe['fastd_rsi'] = stoch_rsi['fastd']
|
||||
dataframe['fastk_rsi'] = stoch_rsi['fastk']
|
||||
# Bollinger bands
|
||||
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
|
||||
dataframe['bb_lowerband'] = bollinger['lower']
|
||||
dataframe['bb_middleband'] = bollinger['mid']
|
||||
dataframe['bb_upperband'] = bollinger['upper']
|
||||
# EMA - Exponential Moving Average
|
||||
dataframe['ema3'] = ta.EMA(dataframe, timeperiod=3)
|
||||
dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5)
|
||||
dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10)
|
||||
dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)
|
||||
dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)
|
||||
# SAR Parabolic
|
||||
dataframe['sar'] = ta.SAR(dataframe)
|
||||
# SMA - Simple Moving Average
|
||||
dataframe['sma'] = ta.SMA(dataframe, timeperiod=40)
|
||||
# TEMA - Triple Exponential Moving Average
|
||||
dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)
|
||||
# Hilbert Transform Indicator - SineWave
|
||||
hilbert = ta.HT_SINE(dataframe)
|
||||
dataframe['htsine'] = hilbert['sine']
|
||||
dataframe['htleadsine'] = hilbert['leadsine']
|
||||
|
||||
# Pattern Recognition - Bullish candlestick patterns
|
||||
# ------------------------------------
|
||||
"""
|
||||
# Hammer: values [0, 100]
|
||||
dataframe['CDLHAMMER'] = ta.CDLHAMMER(dataframe)
|
||||
# Inverted Hammer: values [0, 100]
|
||||
dataframe['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(dataframe)
|
||||
# Dragonfly Doji: values [0, 100]
|
||||
dataframe['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(dataframe)
|
||||
# Piercing Line: values [0, 100]
|
||||
dataframe['CDLPIERCING'] = ta.CDLPIERCING(dataframe) # values [0, 100]
|
||||
# Morningstar: values [0, 100]
|
||||
dataframe['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(dataframe) # values [0, 100]
|
||||
# Three White Soldiers: values [0, 100]
|
||||
dataframe['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(dataframe) # values [0, 100]
|
||||
"""
|
||||
|
||||
# Pattern Recognition - Bearish candlestick patterns
|
||||
# ------------------------------------
|
||||
"""
|
||||
# Hanging Man: values [0, 100]
|
||||
dataframe['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(dataframe)
|
||||
# Shooting Star: values [0, 100]
|
||||
dataframe['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(dataframe)
|
||||
# Gravestone Doji: values [0, 100]
|
||||
dataframe['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(dataframe)
|
||||
# Dark Cloud Cover: values [0, 100]
|
||||
dataframe['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(dataframe)
|
||||
# Evening Doji Star: values [0, 100]
|
||||
dataframe['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(dataframe)
|
||||
# Evening Star: values [0, 100]
|
||||
dataframe['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(dataframe)
|
||||
"""
|
||||
|
||||
# Pattern Recognition - Bullish/Bearish candlestick patterns
|
||||
# ------------------------------------
|
||||
"""
|
||||
# Three Line Strike: values [0, -100, 100]
|
||||
dataframe['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(dataframe)
|
||||
# Spinning Top: values [0, -100, 100]
|
||||
dataframe['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(dataframe) # values [0, -100, 100]
|
||||
# Engulfing: values [0, -100, 100]
|
||||
dataframe['CDLENGULFING'] = ta.CDLENGULFING(dataframe) # values [0, -100, 100]
|
||||
# Harami: values [0, -100, 100]
|
||||
dataframe['CDLHARAMI'] = ta.CDLHARAMI(dataframe) # values [0, -100, 100]
|
||||
# Three Outside Up/Down: values [0, -100, 100]
|
||||
dataframe['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(dataframe) # values [0, -100, 100]
|
||||
# Three Inside Up/Down: values [0, -100, 100]
|
||||
dataframe['CDL3INSIDE'] = ta.CDL3INSIDE(dataframe) # values [0, -100, 100]
|
||||
"""
|
||||
|
||||
# Chart type
|
||||
# ------------------------------------
|
||||
# Heikinashi stategy
|
||||
heikinashi = qtpylib.heikinashi(dataframe)
|
||||
dataframe['ha_open'] = heikinashi['open']
|
||||
dataframe['ha_close'] = heikinashi['close']
|
||||
dataframe['ha_high'] = heikinashi['high']
|
||||
dataframe['ha_low'] = heikinashi['low']
|
||||
|
||||
return dataframe
|
||||
# Create a dict where the keys are the names of the dimensions
|
||||
# and the values are taken from the list of parameters x.
|
||||
arg_dict = {dim.name: value for dim, value in zip(dimensions, params)}
|
||||
return arg_dict
|
||||
|
||||
def save_trials(self) -> None:
|
||||
"""
|
||||
Save hyperopt trials to file
|
||||
"""
|
||||
logger.info('Saving Trials to \'%s\'', self.trials_file)
|
||||
pickle.dump(self.trials, open(self.trials_file, 'wb'))
|
||||
if self.trials:
|
||||
logger.info('Saving %d evaluations to \'%s\'', len(self.trials), self.trials_file)
|
||||
dump(self.trials, self.trials_file)
|
||||
|
||||
def read_trials(self) -> Trials:
|
||||
def read_trials(self) -> List:
|
||||
"""
|
||||
Read hyperopt trials file
|
||||
"""
|
||||
logger.info('Reading Trials from \'%s\'', self.trials_file)
|
||||
trials = pickle.load(open(self.trials_file, 'rb'))
|
||||
trials = load(self.trials_file)
|
||||
os.remove(self.trials_file)
|
||||
return trials
|
||||
|
||||
@@ -207,22 +100,28 @@ class Hyperopt(Backtesting):
|
||||
"""
|
||||
Display Best hyperopt result
|
||||
"""
|
||||
vals = json.dumps(self.trials.best_trial['misc']['vals'], indent=4)
|
||||
results = self.trials.best_trial['result']['result']
|
||||
logger.info('Best result:\n%s\nwith values:\n%s', results, vals)
|
||||
results = sorted(self.trials, key=itemgetter('loss'))
|
||||
best_result = results[0]
|
||||
logger.info(
|
||||
'Best result:\n%s\nwith values:\n',
|
||||
best_result['result']
|
||||
)
|
||||
pprint(best_result['params'], indent=4)
|
||||
if 'roi_t1' in best_result['params']:
|
||||
logger.info('ROI table:')
|
||||
pprint(self.custom_hyperopt.generate_roi_table(best_result['params']), indent=4)
|
||||
|
||||
def log_results(self, results) -> None:
|
||||
"""
|
||||
Log results if it is better than any previous evaluation
|
||||
"""
|
||||
if results['loss'] < self.current_best_loss:
|
||||
current = results['current_tries']
|
||||
total = results['total_tries']
|
||||
res = results['result']
|
||||
loss = results['loss']
|
||||
self.current_best_loss = results['loss']
|
||||
log_msg = '\n{:5d}/{}: {}. Loss {:.5f}'.format(
|
||||
results['current_tries'],
|
||||
results['total_tries'],
|
||||
results['result'],
|
||||
results['loss']
|
||||
)
|
||||
log_msg = f'\n{current:5d}/{total}: {res}. Loss {loss:.5f}'
|
||||
print(log_msg)
|
||||
else:
|
||||
print('.', end='')
|
||||
@@ -235,103 +134,8 @@ class Hyperopt(Backtesting):
|
||||
trade_loss = 1 - 0.25 * exp(-(trade_count - self.target_trades) ** 2 / 10 ** 5.8)
|
||||
profit_loss = max(0, 1 - total_profit / self.expected_max_profit)
|
||||
duration_loss = 0.4 * min(trade_duration / self.max_accepted_trade_duration, 1)
|
||||
return trade_loss + profit_loss + duration_loss
|
||||
|
||||
@staticmethod
|
||||
def generate_roi_table(params: Dict) -> Dict[int, float]:
|
||||
"""
|
||||
Generate the ROI table thqt will be used by Hyperopt
|
||||
"""
|
||||
roi_table = {}
|
||||
roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3']
|
||||
roi_table[params['roi_t3']] = params['roi_p1'] + params['roi_p2']
|
||||
roi_table[params['roi_t3'] + params['roi_t2']] = params['roi_p1']
|
||||
roi_table[params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0
|
||||
|
||||
return roi_table
|
||||
|
||||
@staticmethod
|
||||
def roi_space() -> Dict[str, Any]:
|
||||
"""
|
||||
Values to search for each ROI steps
|
||||
"""
|
||||
return {
|
||||
'roi_t1': hp.quniform('roi_t1', 10, 120, 20),
|
||||
'roi_t2': hp.quniform('roi_t2', 10, 60, 15),
|
||||
'roi_t3': hp.quniform('roi_t3', 10, 40, 10),
|
||||
'roi_p1': hp.quniform('roi_p1', 0.01, 0.04, 0.01),
|
||||
'roi_p2': hp.quniform('roi_p2', 0.01, 0.07, 0.01),
|
||||
'roi_p3': hp.quniform('roi_p3', 0.01, 0.20, 0.01),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def stoploss_space() -> Dict[str, Any]:
|
||||
"""
|
||||
Stoploss Value to search
|
||||
"""
|
||||
return {
|
||||
'stoploss': hp.quniform('stoploss', -0.5, -0.02, 0.02),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def indicator_space() -> Dict[str, Any]:
|
||||
"""
|
||||
Define your Hyperopt space for searching strategy parameters
|
||||
"""
|
||||
return {
|
||||
'macd_below_zero': hp.choice('macd_below_zero', [
|
||||
{'enabled': False},
|
||||
{'enabled': True}
|
||||
]),
|
||||
'mfi': hp.choice('mfi', [
|
||||
{'enabled': False},
|
||||
{'enabled': True, 'value': hp.quniform('mfi-value', 10, 25, 5)}
|
||||
]),
|
||||
'fastd': hp.choice('fastd', [
|
||||
{'enabled': False},
|
||||
{'enabled': True, 'value': hp.quniform('fastd-value', 15, 45, 5)}
|
||||
]),
|
||||
'adx': hp.choice('adx', [
|
||||
{'enabled': False},
|
||||
{'enabled': True, 'value': hp.quniform('adx-value', 20, 50, 5)}
|
||||
]),
|
||||
'rsi': hp.choice('rsi', [
|
||||
{'enabled': False},
|
||||
{'enabled': True, 'value': hp.quniform('rsi-value', 20, 40, 5)}
|
||||
]),
|
||||
'uptrend_long_ema': hp.choice('uptrend_long_ema', [
|
||||
{'enabled': False},
|
||||
{'enabled': True}
|
||||
]),
|
||||
'uptrend_short_ema': hp.choice('uptrend_short_ema', [
|
||||
{'enabled': False},
|
||||
{'enabled': True}
|
||||
]),
|
||||
'over_sar': hp.choice('over_sar', [
|
||||
{'enabled': False},
|
||||
{'enabled': True}
|
||||
]),
|
||||
'green_candle': hp.choice('green_candle', [
|
||||
{'enabled': False},
|
||||
{'enabled': True}
|
||||
]),
|
||||
'uptrend_sma': hp.choice('uptrend_sma', [
|
||||
{'enabled': False},
|
||||
{'enabled': True}
|
||||
]),
|
||||
'trigger': hp.choice('trigger', [
|
||||
{'type': 'lower_bb'},
|
||||
{'type': 'lower_bb_tema'},
|
||||
{'type': 'faststoch10'},
|
||||
{'type': 'ao_cross_zero'},
|
||||
{'type': 'ema3_cross_ema10'},
|
||||
{'type': 'macd_cross_signal'},
|
||||
{'type': 'sar_reversal'},
|
||||
{'type': 'ht_sine'},
|
||||
{'type': 'heiken_reversal_bull'},
|
||||
{'type': 'di_cross'},
|
||||
]),
|
||||
}
|
||||
result = trade_loss + profit_loss + duration_loss
|
||||
return result
|
||||
|
||||
def has_space(self, space: str) -> bool:
|
||||
"""
|
||||
@@ -341,243 +145,154 @@ class Hyperopt(Backtesting):
|
||||
return True
|
||||
return False
|
||||
|
||||
def hyperopt_space(self) -> Dict[str, Any]:
|
||||
def hyperopt_space(self) -> List[Dimension]:
|
||||
"""
|
||||
Return the space to use during Hyperopt
|
||||
"""
|
||||
spaces = {}
|
||||
spaces: List[Dimension] = []
|
||||
if self.has_space('buy'):
|
||||
spaces = {**spaces, **Hyperopt.indicator_space()}
|
||||
spaces += self.custom_hyperopt.indicator_space()
|
||||
if self.has_space('sell'):
|
||||
spaces += self.custom_hyperopt.sell_indicator_space()
|
||||
# Make sure experimental is enabled
|
||||
if 'experimental' not in self.config:
|
||||
self.config['experimental'] = {}
|
||||
self.config['experimental']['use_sell_signal'] = True
|
||||
if self.has_space('roi'):
|
||||
spaces = {**spaces, **Hyperopt.roi_space()}
|
||||
spaces += self.custom_hyperopt.roi_space()
|
||||
if self.has_space('stoploss'):
|
||||
spaces = {**spaces, **Hyperopt.stoploss_space()}
|
||||
spaces += self.custom_hyperopt.stoploss_space()
|
||||
return spaces
|
||||
|
||||
@staticmethod
|
||||
def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||
"""
|
||||
Define the buy strategy parameters to be used by hyperopt
|
||||
"""
|
||||
def populate_buy_trend(dataframe: DataFrame) -> DataFrame:
|
||||
"""
|
||||
Buy strategy Hyperopt will build and use
|
||||
"""
|
||||
conditions = []
|
||||
# GUARDS AND TRENDS
|
||||
if 'uptrend_long_ema' in params and params['uptrend_long_ema']['enabled']:
|
||||
conditions.append(dataframe['ema50'] > dataframe['ema100'])
|
||||
if 'macd_below_zero' in params and params['macd_below_zero']['enabled']:
|
||||
conditions.append(dataframe['macd'] < 0)
|
||||
if 'uptrend_short_ema' in params and params['uptrend_short_ema']['enabled']:
|
||||
conditions.append(dataframe['ema5'] > dataframe['ema10'])
|
||||
if 'mfi' in params and params['mfi']['enabled']:
|
||||
conditions.append(dataframe['mfi'] < params['mfi']['value'])
|
||||
if 'fastd' in params and params['fastd']['enabled']:
|
||||
conditions.append(dataframe['fastd'] < params['fastd']['value'])
|
||||
if 'adx' in params and params['adx']['enabled']:
|
||||
conditions.append(dataframe['adx'] > params['adx']['value'])
|
||||
if 'rsi' in params and params['rsi']['enabled']:
|
||||
conditions.append(dataframe['rsi'] < params['rsi']['value'])
|
||||
if 'over_sar' in params and params['over_sar']['enabled']:
|
||||
conditions.append(dataframe['close'] > dataframe['sar'])
|
||||
if 'green_candle' in params and params['green_candle']['enabled']:
|
||||
conditions.append(dataframe['close'] > dataframe['open'])
|
||||
if 'uptrend_sma' in params and params['uptrend_sma']['enabled']:
|
||||
prevsma = dataframe['sma'].shift(1)
|
||||
conditions.append(dataframe['sma'] > prevsma)
|
||||
|
||||
# TRIGGERS
|
||||
triggers = {
|
||||
'lower_bb': (
|
||||
dataframe['close'] < dataframe['bb_lowerband']
|
||||
),
|
||||
'lower_bb_tema': (
|
||||
dataframe['tema'] < dataframe['bb_lowerband']
|
||||
),
|
||||
'faststoch10': (qtpylib.crossed_above(
|
||||
dataframe['fastd'], 10.0
|
||||
)),
|
||||
'ao_cross_zero': (qtpylib.crossed_above(
|
||||
dataframe['ao'], 0.0
|
||||
)),
|
||||
'ema3_cross_ema10': (qtpylib.crossed_above(
|
||||
dataframe['ema3'], dataframe['ema10']
|
||||
)),
|
||||
'macd_cross_signal': (qtpylib.crossed_above(
|
||||
dataframe['macd'], dataframe['macdsignal']
|
||||
)),
|
||||
'sar_reversal': (qtpylib.crossed_above(
|
||||
dataframe['close'], dataframe['sar']
|
||||
)),
|
||||
'ht_sine': (qtpylib.crossed_above(
|
||||
dataframe['htleadsine'], dataframe['htsine']
|
||||
)),
|
||||
'heiken_reversal_bull': (
|
||||
(qtpylib.crossed_above(dataframe['ha_close'], dataframe['ha_open'])) &
|
||||
(dataframe['ha_low'] == dataframe['ha_open'])
|
||||
),
|
||||
'di_cross': (qtpylib.crossed_above(
|
||||
dataframe['plus_di'], dataframe['minus_di']
|
||||
)),
|
||||
}
|
||||
conditions.append(triggers.get(params['trigger']['type']))
|
||||
|
||||
dataframe.loc[
|
||||
reduce(lambda x, y: x & y, conditions),
|
||||
'buy'] = 1
|
||||
|
||||
return dataframe
|
||||
|
||||
return populate_buy_trend
|
||||
|
||||
def generate_optimizer(self, params: Dict) -> Dict:
|
||||
def generate_optimizer(self, _params: Dict) -> Dict:
|
||||
params = self.get_args(_params)
|
||||
if self.has_space('roi'):
|
||||
self.analyze.strategy.minimal_roi = self.generate_roi_table(params)
|
||||
self.strategy.minimal_roi = self.custom_hyperopt.generate_roi_table(params)
|
||||
|
||||
if self.has_space('buy'):
|
||||
self.populate_buy_trend = self.buy_strategy_generator(params)
|
||||
self.advise_buy = self.custom_hyperopt.buy_strategy_generator(params)
|
||||
elif hasattr(self.custom_hyperopt, 'populate_buy_trend'):
|
||||
self.advise_buy = self.custom_hyperopt.populate_buy_trend # type: ignore
|
||||
|
||||
if self.has_space('sell'):
|
||||
self.advise_sell = self.custom_hyperopt.sell_strategy_generator(params)
|
||||
elif hasattr(self.custom_hyperopt, 'populate_sell_trend'):
|
||||
self.advise_sell = self.custom_hyperopt.populate_sell_trend # type: ignore
|
||||
|
||||
if self.has_space('stoploss'):
|
||||
self.analyze.strategy.stoploss = params['stoploss']
|
||||
self.strategy.stoploss = params['stoploss']
|
||||
|
||||
processed = load(TICKERDATA_PICKLE)
|
||||
min_date, max_date = get_timeframe(processed)
|
||||
results = self.backtest(
|
||||
{
|
||||
'stake_amount': self.config['stake_amount'],
|
||||
'processed': self.processed,
|
||||
'realistic': self.config.get('realistic_simulation', False),
|
||||
'processed': processed,
|
||||
'position_stacking': self.config.get('position_stacking', True),
|
||||
'start_date': min_date,
|
||||
'end_date': max_date,
|
||||
}
|
||||
)
|
||||
result_explanation = self.format_results(results)
|
||||
|
||||
total_profit = results.profit_percent.sum()
|
||||
trade_count = len(results.index)
|
||||
trade_duration = results.duration.mean()
|
||||
trade_duration = results.trade_duration.mean()
|
||||
|
||||
if trade_count == 0 or trade_duration > self.max_accepted_trade_duration:
|
||||
print('.', end='')
|
||||
if trade_count == 0:
|
||||
return {
|
||||
'status': STATUS_FAIL,
|
||||
'loss': float('inf')
|
||||
'loss': MAX_LOSS,
|
||||
'params': params,
|
||||
'result': result_explanation,
|
||||
}
|
||||
|
||||
loss = self.calculate_loss(total_profit, trade_count, trade_duration)
|
||||
|
||||
self.current_tries += 1
|
||||
|
||||
self.log_results(
|
||||
{
|
||||
'loss': loss,
|
||||
'current_tries': self.current_tries,
|
||||
'total_tries': self.total_tries,
|
||||
'result': result_explanation,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
'loss': loss,
|
||||
'status': STATUS_OK,
|
||||
'params': params,
|
||||
'result': result_explanation,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def format_results(results: DataFrame) -> str:
|
||||
def format_results(self, results: DataFrame) -> str:
|
||||
"""
|
||||
Return the format result in a string
|
||||
"""
|
||||
return ('{:6d} trades. Avg profit {: 5.2f}%. '
|
||||
'Total profit {: 11.8f} BTC ({:.4f}Σ%). Avg duration {:5.1f} mins.').format(
|
||||
len(results.index),
|
||||
results.profit_percent.mean() * 100.0,
|
||||
results.profit_BTC.sum(),
|
||||
results.profit_percent.sum(),
|
||||
results.duration.mean(),
|
||||
)
|
||||
trades = len(results.index)
|
||||
avg_profit = results.profit_percent.mean() * 100.0
|
||||
total_profit = results.profit_abs.sum()
|
||||
stake_cur = self.config['stake_currency']
|
||||
profit = results.profit_percent.sum()
|
||||
duration = results.trade_duration.mean()
|
||||
|
||||
return (f'{trades:6d} trades. Avg profit {avg_profit: 5.2f}%. '
|
||||
f'Total profit {total_profit: 11.8f} {stake_cur} '
|
||||
f'({profit:.4f}Σ%). Avg duration {duration:5.1f} mins.')
|
||||
|
||||
def get_optimizer(self, cpu_count) -> Optimizer:
|
||||
return Optimizer(
|
||||
self.hyperopt_space(),
|
||||
base_estimator="ET",
|
||||
acq_optimizer="auto",
|
||||
n_initial_points=30,
|
||||
acq_optimizer_kwargs={'n_jobs': cpu_count}
|
||||
)
|
||||
|
||||
def run_optimizer_parallel(self, parallel, asked) -> List:
|
||||
return parallel(delayed(
|
||||
wrap_non_picklable_objects(self.generate_optimizer))(v) for v in asked)
|
||||
|
||||
def load_previous_results(self):
|
||||
""" read trials file if we have one """
|
||||
if os.path.exists(self.trials_file) and os.path.getsize(self.trials_file) > 0:
|
||||
self.trials = self.read_trials()
|
||||
logger.info(
|
||||
'Loaded %d previous evaluations from disk.',
|
||||
len(self.trials)
|
||||
)
|
||||
|
||||
def start(self) -> None:
|
||||
timerange = Arguments.parse_timerange(self.config.get('timerange'))
|
||||
timerange = Arguments.parse_timerange(None if self.config.get(
|
||||
'timerange') is None else str(self.config.get('timerange')))
|
||||
data = load_data(
|
||||
datadir=self.config.get('datadir'),
|
||||
datadir=Path(self.config['datadir']) if self.config.get('datadir') else None,
|
||||
pairs=self.config['exchange']['pair_whitelist'],
|
||||
ticker_interval=self.ticker_interval,
|
||||
timerange=timerange
|
||||
)
|
||||
|
||||
if self.has_space('buy'):
|
||||
self.analyze.populate_indicators = Hyperopt.populate_indicators
|
||||
self.processed = self.tickerdata_to_dataframe(data)
|
||||
if self.has_space('buy') or self.has_space('sell'):
|
||||
self.strategy.advise_indicators = \
|
||||
self.custom_hyperopt.populate_indicators # type: ignore
|
||||
dump(self.strategy.tickerdata_to_dataframe(data), TICKERDATA_PICKLE)
|
||||
self.exchange = None # type: ignore
|
||||
self.load_previous_results()
|
||||
|
||||
if self.config.get('mongodb'):
|
||||
logger.info('Using mongodb ...')
|
||||
logger.info(
|
||||
'Start scripts/start-mongodb.sh and start-hyperopt-worker.sh manually!'
|
||||
)
|
||||
|
||||
db_name = 'freqtrade_hyperopt'
|
||||
self.trials = MongoTrials(
|
||||
arg='mongo://127.0.0.1:1234/{}/jobs'.format(db_name),
|
||||
exp_key='exp1'
|
||||
)
|
||||
else:
|
||||
logger.info('Preparing Trials..')
|
||||
signal.signal(signal.SIGINT, self.signal_handler)
|
||||
# read trials file if we have one
|
||||
if os.path.exists(self.trials_file) and os.path.getsize(self.trials_file) > 0:
|
||||
self.trials = self.read_trials()
|
||||
|
||||
self.current_tries = len(self.trials.results)
|
||||
self.total_tries += self.current_tries
|
||||
logger.info(
|
||||
'Continuing with trials. Current: %d, Total: %d',
|
||||
self.current_tries,
|
||||
self.total_tries
|
||||
)
|
||||
cpus = multiprocessing.cpu_count()
|
||||
logger.info(f'Found {cpus} CPU cores. Let\'s make them scream!')
|
||||
|
||||
opt = self.get_optimizer(cpus)
|
||||
EVALS = max(self.total_tries // cpus, 1)
|
||||
try:
|
||||
best_parameters = fmin(
|
||||
fn=self.generate_optimizer,
|
||||
space=self.hyperopt_space(),
|
||||
algo=tpe.suggest,
|
||||
max_evals=self.total_tries,
|
||||
trials=self.trials
|
||||
)
|
||||
with Parallel(n_jobs=cpus) as parallel:
|
||||
for i in range(EVALS):
|
||||
asked = opt.ask(n_points=cpus)
|
||||
f_val = self.run_optimizer_parallel(parallel, asked)
|
||||
opt.tell(asked, [i['loss'] for i in f_val])
|
||||
|
||||
results = sorted(self.trials.results, key=itemgetter('loss'))
|
||||
best_result = results[0]['result']
|
||||
|
||||
except ValueError:
|
||||
best_parameters = {}
|
||||
best_result = 'Sorry, Hyperopt was not able to find good parameters. Please ' \
|
||||
'try with more epochs (param: -e).'
|
||||
|
||||
# Improve best parameter logging display
|
||||
if best_parameters:
|
||||
best_parameters = space_eval(
|
||||
self.hyperopt_space(),
|
||||
best_parameters
|
||||
)
|
||||
|
||||
logger.info('Best parameters:\n%s', json.dumps(best_parameters, indent=4))
|
||||
if 'roi_t1' in best_parameters:
|
||||
logger.info('ROI table:\n%s', self.generate_roi_table(best_parameters))
|
||||
|
||||
logger.info('Best Result:\n%s', best_result)
|
||||
|
||||
# Store trials result to file to resume next time
|
||||
self.save_trials()
|
||||
|
||||
def signal_handler(self, sig, frame) -> None:
|
||||
"""
|
||||
Hyperopt SIGINT handler
|
||||
"""
|
||||
logger.info(
|
||||
'Hyperopt received %s',
|
||||
signal.Signals(sig).name
|
||||
)
|
||||
self.trials += f_val
|
||||
for j in range(cpus):
|
||||
self.log_results({
|
||||
'loss': f_val[j]['loss'],
|
||||
'current_tries': i * cpus + j,
|
||||
'total_tries': self.total_tries,
|
||||
'result': f_val[j]['result'],
|
||||
})
|
||||
except KeyboardInterrupt:
|
||||
print('User interrupted..')
|
||||
|
||||
self.save_trials()
|
||||
self.log_trials_result()
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
def start(args: Namespace) -> None:
|
||||
@@ -588,21 +303,24 @@ def start(args: Namespace) -> None:
|
||||
"""
|
||||
|
||||
# Remove noisy log messages
|
||||
logging.getLogger('hyperopt.mongoexp').setLevel(logging.WARNING)
|
||||
logging.getLogger('hyperopt.tpe').setLevel(logging.WARNING)
|
||||
|
||||
# Initialize configuration
|
||||
# Monkey patch the configuration with hyperopt_conf.py
|
||||
configuration = Configuration(args)
|
||||
configuration = Configuration(args, RunMode.HYPEROPT)
|
||||
logger.info('Starting freqtrade in Hyperopt mode')
|
||||
config = configuration.load_config()
|
||||
|
||||
optimize_config = hyperopt_optimize_conf()
|
||||
config = configuration._load_common_config(optimize_config)
|
||||
config = configuration._load_backtesting_config(config)
|
||||
config = configuration._load_hyperopt_config(config)
|
||||
config['exchange']['key'] = ''
|
||||
config['exchange']['secret'] = ''
|
||||
|
||||
if config.get('strategy') and config.get('strategy') != 'DefaultStrategy':
|
||||
logger.error("Please don't use --strategy for hyperopt.")
|
||||
logger.error(
|
||||
"Read the documentation at "
|
||||
"https://github.com/freqtrade/freqtrade/blob/develop/docs/hyperopt.md "
|
||||
"to understand how to configure hyperopt.")
|
||||
raise ValueError("--strategy configured but not supported for hyperopt")
|
||||
# Initialize backtesting object
|
||||
hyperopt = Hyperopt(config)
|
||||
hyperopt.start()
|
||||
|
||||
80
freqtrade/optimize/hyperopt_interface.py
Normal file
80
freqtrade/optimize/hyperopt_interface.py
Normal file
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
IHyperOpt interface
|
||||
This module defines the interface to apply for hyperopts
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Dict, Any, Callable, List
|
||||
|
||||
from pandas import DataFrame
|
||||
from skopt.space import Dimension
|
||||
|
||||
|
||||
class IHyperOpt(ABC):
|
||||
"""
|
||||
Interface for freqtrade hyperopts
|
||||
Defines the mandatory structure must follow any custom strategies
|
||||
|
||||
Attributes you can use:
|
||||
minimal_roi -> Dict: Minimal ROI designed for the strategy
|
||||
stoploss -> float: optimal stoploss designed for the strategy
|
||||
ticker_interval -> int: value of the ticker interval to use for the strategy
|
||||
"""
|
||||
|
||||
@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
|
||||
@abstractmethod
|
||||
def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||
"""
|
||||
Create a buy strategy generator
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@abstractmethod
|
||||
def sell_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||
"""
|
||||
Create a sell strategy generator
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@abstractmethod
|
||||
def indicator_space() -> List[Dimension]:
|
||||
"""
|
||||
Create an indicator space
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@abstractmethod
|
||||
def sell_indicator_space() -> List[Dimension]:
|
||||
"""
|
||||
Create a sell indicator space
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@abstractmethod
|
||||
def generate_roi_table(params: Dict) -> Dict[int, float]:
|
||||
"""
|
||||
Create an roi table
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@abstractmethod
|
||||
def stoploss_space() -> List[Dimension]:
|
||||
"""
|
||||
Create a stoploss space
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@abstractmethod
|
||||
def roi_space() -> List[Dimension]:
|
||||
"""
|
||||
Create a roi space
|
||||
"""
|
||||
91
freqtrade/pairlist/IPairList.py
Normal file
91
freqtrade/pairlist/IPairList.py
Normal file
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
Static List provider
|
||||
|
||||
Provides lists as configured in config.json
|
||||
|
||||
"""
|
||||
import logging
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import List
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class IPairList(ABC):
|
||||
|
||||
def __init__(self, freqtrade, config: dict) -> None:
|
||||
self._freqtrade = freqtrade
|
||||
self._config = config
|
||||
self._whitelist = self._config['exchange']['pair_whitelist']
|
||||
self._blacklist = self._config['exchange'].get('pair_blacklist', [])
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""
|
||||
Gets name of the class
|
||||
-> no need to overwrite in subclasses
|
||||
"""
|
||||
return self.__class__.__name__
|
||||
|
||||
@property
|
||||
def whitelist(self) -> List[str]:
|
||||
"""
|
||||
Has the current whitelist
|
||||
-> no need to overwrite in subclasses
|
||||
"""
|
||||
return self._whitelist
|
||||
|
||||
@property
|
||||
def blacklist(self) -> List[str]:
|
||||
"""
|
||||
Has the current blacklist
|
||||
-> no need to overwrite in subclasses
|
||||
"""
|
||||
return self._blacklist
|
||||
|
||||
@abstractmethod
|
||||
def short_desc(self) -> str:
|
||||
"""
|
||||
Short whitelist method description - used for startup-messages
|
||||
-> Please overwrite in subclasses
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def refresh_pairlist(self) -> None:
|
||||
"""
|
||||
Refreshes pairlists and assigns them to self._whitelist and self._blacklist respectively
|
||||
-> Please overwrite in subclasses
|
||||
"""
|
||||
|
||||
def _validate_whitelist(self, whitelist: List[str]) -> List[str]:
|
||||
"""
|
||||
Check available markets and remove pair from whitelist if necessary
|
||||
:param whitelist: the sorted list (based on BaseVolume) of pairs the user might want to
|
||||
trade
|
||||
:return: the list of pairs the user wants to trade without the one unavailable or
|
||||
black_listed
|
||||
"""
|
||||
sanitized_whitelist = whitelist
|
||||
markets = self._freqtrade.exchange.get_markets()
|
||||
|
||||
# Filter to markets in stake currency
|
||||
markets = [m for m in markets if m['quote'] == self._config['stake_currency']]
|
||||
known_pairs = set()
|
||||
|
||||
for market in markets:
|
||||
pair = market['symbol']
|
||||
# pair is not int the generated dynamic market, or in the blacklist ... ignore it
|
||||
if pair not in whitelist or pair in self.blacklist:
|
||||
continue
|
||||
# else the pair is valid
|
||||
known_pairs.add(pair)
|
||||
# Market is not active
|
||||
if not market['active']:
|
||||
sanitized_whitelist.remove(pair)
|
||||
logger.info(
|
||||
'Ignoring %s from whitelist. Market is not active.',
|
||||
pair
|
||||
)
|
||||
|
||||
# We need to remove pairs that are unknown
|
||||
return [x for x in sanitized_whitelist if x in known_pairs]
|
||||
30
freqtrade/pairlist/StaticPairList.py
Normal file
30
freqtrade/pairlist/StaticPairList.py
Normal file
@@ -0,0 +1,30 @@
|
||||
"""
|
||||
Static List provider
|
||||
|
||||
Provides lists as configured in config.json
|
||||
|
||||
"""
|
||||
import logging
|
||||
|
||||
from freqtrade.pairlist.IPairList import IPairList
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class StaticPairList(IPairList):
|
||||
|
||||
def __init__(self, freqtrade, config: dict) -> None:
|
||||
super().__init__(freqtrade, config)
|
||||
|
||||
def short_desc(self) -> str:
|
||||
"""
|
||||
Short whitelist method description - used for startup-messages
|
||||
-> Please overwrite in subclasses
|
||||
"""
|
||||
return f"{self.name}: {self.whitelist}"
|
||||
|
||||
def refresh_pairlist(self) -> None:
|
||||
"""
|
||||
Refreshes pairlists and assigns them to self._whitelist and self._blacklist respectively
|
||||
"""
|
||||
self._whitelist = self._validate_whitelist(self._config['exchange']['pair_whitelist'])
|
||||
75
freqtrade/pairlist/VolumePairList.py
Normal file
75
freqtrade/pairlist/VolumePairList.py
Normal file
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
Static List provider
|
||||
|
||||
Provides lists as configured in config.json
|
||||
|
||||
"""
|
||||
import logging
|
||||
from typing import List
|
||||
from cachetools import TTLCache, cached
|
||||
|
||||
from freqtrade.pairlist.IPairList import IPairList
|
||||
from freqtrade import OperationalException
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SORT_VALUES = ['askVolume', 'bidVolume', 'quoteVolume']
|
||||
|
||||
|
||||
class VolumePairList(IPairList):
|
||||
|
||||
def __init__(self, freqtrade, config: dict) -> None:
|
||||
super().__init__(freqtrade, config)
|
||||
self._whitelistconf = self._config.get('pairlist', {}).get('config')
|
||||
if 'number_assets' not in self._whitelistconf:
|
||||
raise OperationalException(
|
||||
f'`number_assets` not specified. Please check your configuration '
|
||||
'for "pairlist.config.number_assets"')
|
||||
self._number_pairs = self._whitelistconf['number_assets']
|
||||
self._sort_key = self._whitelistconf.get('sort_key', 'quoteVolume')
|
||||
|
||||
if not self._freqtrade.exchange.exchange_has('fetchTickers'):
|
||||
raise OperationalException(
|
||||
'Exchange does not support dynamic whitelist.'
|
||||
'Please edit your config and restart the bot'
|
||||
)
|
||||
if not self._validate_keys(self._sort_key):
|
||||
raise OperationalException(
|
||||
f'key {self._sort_key} not in {SORT_VALUES}')
|
||||
|
||||
def _validate_keys(self, key):
|
||||
return key in SORT_VALUES
|
||||
|
||||
def short_desc(self) -> str:
|
||||
"""
|
||||
Short whitelist method description - used for startup-messages
|
||||
-> Please overwrite in subclasses
|
||||
"""
|
||||
return f"{self.name} - top {self._whitelistconf['number_assets']} volume pairs."
|
||||
|
||||
def refresh_pairlist(self) -> None:
|
||||
"""
|
||||
Refreshes pairlists and assigns them to self._whitelist and self._blacklist respectively
|
||||
-> Please overwrite in subclasses
|
||||
"""
|
||||
# Generate dynamic whitelist
|
||||
pairs = self._gen_pair_whitelist(self._config['stake_currency'], self._sort_key)
|
||||
# Validate whitelist to only have active market pairs
|
||||
self._whitelist = self._validate_whitelist(pairs)[:self._number_pairs]
|
||||
|
||||
@cached(TTLCache(maxsize=1, ttl=1800))
|
||||
def _gen_pair_whitelist(self, base_currency: str, key: str) -> List[str]:
|
||||
"""
|
||||
Updates the whitelist with with a dynamically generated list
|
||||
:param base_currency: base currency as str
|
||||
:param key: sort key (defaults to 'quoteVolume')
|
||||
:return: List of pairs
|
||||
"""
|
||||
|
||||
tickers = self._freqtrade.exchange.get_tickers()
|
||||
# check length so that we make sure that '/' is actually in the string
|
||||
tickers = [v for k, v in tickers.items()
|
||||
if len(k.split('/')) == 2 and k.split('/')[1] == base_currency]
|
||||
|
||||
sorted_tickers = sorted(tickers, reverse=True, key=lambda t: t[key])
|
||||
pairs = [s['symbol'] for s in sorted_tickers]
|
||||
return pairs
|
||||
@@ -4,58 +4,142 @@ This module contains the class to persist trades into SQLite
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from decimal import Decimal, getcontext
|
||||
from typing import Dict, Optional
|
||||
from decimal import Decimal
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
import arrow
|
||||
from sqlalchemy import (Boolean, Column, DateTime, Float, Integer, String,
|
||||
create_engine)
|
||||
from sqlalchemy.engine import Engine
|
||||
create_engine, inspect)
|
||||
from sqlalchemy.exc import NoSuchModuleError
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm.scoping import scoped_session
|
||||
from sqlalchemy.orm.session import sessionmaker
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from freqtrade import OperationalException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_CONF = {}
|
||||
_DECL_BASE = declarative_base()
|
||||
_DECL_BASE: Any = declarative_base()
|
||||
_SQL_DOCS_URL = 'http://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls'
|
||||
|
||||
|
||||
def init(config: dict, engine: Optional[Engine] = None) -> None:
|
||||
def init(config: Dict) -> None:
|
||||
"""
|
||||
Initializes this module with the given config,
|
||||
registers all known command handlers
|
||||
and starts polling for message updates
|
||||
:param config: config to use
|
||||
:param engine: database engine for sqlalchemy (Optional)
|
||||
:return: None
|
||||
"""
|
||||
_CONF.update(config)
|
||||
if not engine:
|
||||
if _CONF.get('dry_run', False):
|
||||
# the user wants dry run to use a DB
|
||||
if _CONF.get('dry_run_db', False):
|
||||
engine = create_engine('sqlite:///tradesv3.dry_run.sqlite')
|
||||
# Otherwise dry run will store in memory
|
||||
else:
|
||||
engine = create_engine('sqlite://',
|
||||
connect_args={'check_same_thread': False},
|
||||
poolclass=StaticPool,
|
||||
echo=False)
|
||||
else:
|
||||
engine = create_engine('sqlite:///tradesv3.sqlite')
|
||||
db_url = config.get('db_url', None)
|
||||
kwargs = {}
|
||||
|
||||
# Take care of thread ownership if in-memory db
|
||||
if db_url == 'sqlite://':
|
||||
kwargs.update({
|
||||
'connect_args': {'check_same_thread': False},
|
||||
'poolclass': StaticPool,
|
||||
'echo': False,
|
||||
})
|
||||
|
||||
try:
|
||||
engine = create_engine(db_url, **kwargs)
|
||||
except NoSuchModuleError:
|
||||
raise OperationalException(f'Given value for db_url: \'{db_url}\' '
|
||||
f'is no valid database URL! (See {_SQL_DOCS_URL})')
|
||||
|
||||
session = scoped_session(sessionmaker(bind=engine, autoflush=True, autocommit=True))
|
||||
Trade.session = session()
|
||||
Trade.query = session.query_property()
|
||||
_DECL_BASE.metadata.create_all(engine)
|
||||
check_migrate(engine)
|
||||
|
||||
# Clean dry_run DB
|
||||
if _CONF.get('dry_run', False) and _CONF.get('dry_run_db', False):
|
||||
# Clean dry_run DB if the db is not in-memory
|
||||
if config.get('dry_run', False) and db_url != 'sqlite://':
|
||||
clean_dry_run_db()
|
||||
|
||||
|
||||
def has_column(columns, searchname: str) -> bool:
|
||||
return len(list(filter(lambda x: x["name"] == searchname, columns))) == 1
|
||||
|
||||
|
||||
def get_column_def(columns, column: str, default: str) -> str:
|
||||
return default if not has_column(columns, column) else column
|
||||
|
||||
|
||||
def check_migrate(engine) -> None:
|
||||
"""
|
||||
Checks if migration is necessary and migrates if necessary
|
||||
"""
|
||||
inspector = inspect(engine)
|
||||
|
||||
cols = inspector.get_columns('trades')
|
||||
tabs = inspector.get_table_names()
|
||||
table_back_name = 'trades_bak'
|
||||
for i, table_back_name in enumerate(tabs):
|
||||
table_back_name = f'trades_bak{i}'
|
||||
logger.debug(f'trying {table_back_name}')
|
||||
|
||||
# Check for latest column
|
||||
if not has_column(cols, 'stoploss_last_update'):
|
||||
logger.info(f'Running database migration - backup available as {table_back_name}')
|
||||
|
||||
fee_open = get_column_def(cols, 'fee_open', 'fee')
|
||||
fee_close = get_column_def(cols, 'fee_close', 'fee')
|
||||
open_rate_requested = get_column_def(cols, 'open_rate_requested', 'null')
|
||||
close_rate_requested = get_column_def(cols, 'close_rate_requested', 'null')
|
||||
stop_loss = get_column_def(cols, 'stop_loss', '0.0')
|
||||
initial_stop_loss = get_column_def(cols, 'initial_stop_loss', '0.0')
|
||||
stoploss_order_id = get_column_def(cols, 'stoploss_order_id', 'null')
|
||||
stoploss_last_update = get_column_def(cols, 'stoploss_last_update', 'null')
|
||||
max_rate = get_column_def(cols, 'max_rate', '0.0')
|
||||
sell_reason = get_column_def(cols, 'sell_reason', 'null')
|
||||
strategy = get_column_def(cols, 'strategy', 'null')
|
||||
ticker_interval = get_column_def(cols, 'ticker_interval', 'null')
|
||||
|
||||
# Schema migration necessary
|
||||
engine.execute(f"alter table trades rename to {table_back_name}")
|
||||
# drop indexes on backup table
|
||||
for index in inspector.get_indexes(table_back_name):
|
||||
engine.execute(f"drop index {index['name']}")
|
||||
# let SQLAlchemy create the schema as required
|
||||
_DECL_BASE.metadata.create_all(engine)
|
||||
|
||||
# Copy data back - following the correct schema
|
||||
engine.execute(f"""insert into trades
|
||||
(id, exchange, pair, is_open, fee_open, fee_close, open_rate,
|
||||
open_rate_requested, close_rate, close_rate_requested, close_profit,
|
||||
stake_amount, amount, open_date, close_date, open_order_id,
|
||||
stop_loss, initial_stop_loss, stoploss_order_id, stoploss_last_update,
|
||||
max_rate, sell_reason, strategy,
|
||||
ticker_interval
|
||||
)
|
||||
select id, lower(exchange),
|
||||
case
|
||||
when instr(pair, '_') != 0 then
|
||||
substr(pair, instr(pair, '_') + 1) || '/' ||
|
||||
substr(pair, 1, instr(pair, '_') - 1)
|
||||
else pair
|
||||
end
|
||||
pair,
|
||||
is_open, {fee_open} fee_open, {fee_close} fee_close,
|
||||
open_rate, {open_rate_requested} open_rate_requested, close_rate,
|
||||
{close_rate_requested} close_rate_requested, close_profit,
|
||||
stake_amount, amount, open_date, close_date, open_order_id,
|
||||
{stop_loss} stop_loss, {initial_stop_loss} initial_stop_loss,
|
||||
{stoploss_order_id} stoploss_order_id, {stoploss_last_update} stoploss_last_update,
|
||||
{max_rate} max_rate, {sell_reason} sell_reason,
|
||||
{strategy} strategy, {ticker_interval} ticker_interval
|
||||
from {table_back_name}
|
||||
""")
|
||||
|
||||
# Reread columns - the above recreated the table!
|
||||
inspector = inspect(engine)
|
||||
cols = inspector.get_columns('trades')
|
||||
|
||||
|
||||
def cleanup() -> None:
|
||||
"""
|
||||
Flushes all pending operations to disk.
|
||||
@@ -83,26 +167,80 @@ class Trade(_DECL_BASE):
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
exchange = Column(String, nullable=False)
|
||||
pair = Column(String, nullable=False)
|
||||
is_open = Column(Boolean, nullable=False, default=True)
|
||||
fee = Column(Float, nullable=False, default=0.0)
|
||||
pair = Column(String, nullable=False, index=True)
|
||||
is_open = Column(Boolean, nullable=False, default=True, index=True)
|
||||
fee_open = Column(Float, nullable=False, default=0.0)
|
||||
fee_close = Column(Float, nullable=False, default=0.0)
|
||||
open_rate = Column(Float)
|
||||
open_rate_requested = Column(Float)
|
||||
close_rate = Column(Float)
|
||||
close_rate_requested = Column(Float)
|
||||
close_profit = Column(Float)
|
||||
stake_amount = Column(Float, nullable=False)
|
||||
amount = Column(Float)
|
||||
open_date = Column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
close_date = Column(DateTime)
|
||||
open_order_id = Column(String)
|
||||
# absolute value of the stop loss
|
||||
stop_loss = Column(Float, nullable=True, default=0.0)
|
||||
# absolute value of the initial stop loss
|
||||
initial_stop_loss = Column(Float, nullable=True, default=0.0)
|
||||
# stoploss order id which is on exchange
|
||||
stoploss_order_id = Column(String, nullable=True, index=True)
|
||||
# last update time of the stoploss order on exchange
|
||||
stoploss_last_update = Column(DateTime, nullable=True)
|
||||
# absolute value of the highest reached price
|
||||
max_rate = Column(Float, nullable=True, default=0.0)
|
||||
sell_reason = Column(String, nullable=True)
|
||||
strategy = Column(String, nullable=True)
|
||||
ticker_interval = Column(Integer, nullable=True)
|
||||
|
||||
def __repr__(self):
|
||||
return 'Trade(id={}, pair={}, amount={:.8f}, open_rate={:.8f}, open_since={})'.format(
|
||||
self.id,
|
||||
self.pair,
|
||||
self.amount,
|
||||
self.open_rate,
|
||||
arrow.get(self.open_date).humanize() if self.is_open else 'closed'
|
||||
)
|
||||
open_since = arrow.get(self.open_date).humanize() if self.is_open else 'closed'
|
||||
|
||||
return (f'Trade(id={self.id}, pair={self.pair}, amount={self.amount:.8f}, '
|
||||
f'open_rate={self.open_rate:.8f}, open_since={open_since})')
|
||||
|
||||
def adjust_stop_loss(self, current_price: float, stoploss: float, initial: bool = False):
|
||||
"""this adjusts the stop loss to it's most recently observed setting"""
|
||||
|
||||
if initial and not (self.stop_loss is None or self.stop_loss == 0):
|
||||
# Don't modify if called with initial and nothing to do
|
||||
return
|
||||
|
||||
new_loss = float(current_price * (1 - abs(stoploss)))
|
||||
|
||||
# keeping track of the highest observed rate for this trade
|
||||
if self.max_rate is None:
|
||||
self.max_rate = current_price
|
||||
else:
|
||||
if current_price > self.max_rate:
|
||||
self.max_rate = current_price
|
||||
|
||||
# no stop loss assigned yet
|
||||
if not self.stop_loss:
|
||||
logger.debug("assigning new stop loss")
|
||||
self.stop_loss = new_loss
|
||||
self.initial_stop_loss = new_loss
|
||||
self.stoploss_last_update = datetime.utcnow()
|
||||
|
||||
# evaluate if the stop loss needs to be updated
|
||||
else:
|
||||
if new_loss > self.stop_loss: # stop losses only walk up, never down!
|
||||
self.stop_loss = new_loss
|
||||
self.stoploss_last_update = datetime.utcnow()
|
||||
logger.debug("adjusted stop loss")
|
||||
else:
|
||||
logger.debug("keeping current stop loss")
|
||||
|
||||
logger.debug(
|
||||
f"{self.pair} - current price {current_price:.8f}, "
|
||||
f"bought at {self.open_rate:.8f} and calculated "
|
||||
f"stop loss is at: {self.initial_stop_loss:.8f} initial "
|
||||
f"stop at {self.stop_loss:.8f}. "
|
||||
f"trailing stop loss saved us: "
|
||||
f"{float(self.stop_loss) - float(self.initial_stop_loss):.8f} "
|
||||
f"and max observed rate was {self.max_rate:.8f}")
|
||||
|
||||
def update(self, order: Dict) -> None:
|
||||
"""
|
||||
@@ -110,23 +248,28 @@ class Trade(_DECL_BASE):
|
||||
:param order: order retrieved by exchange.get_order()
|
||||
:return: None
|
||||
"""
|
||||
order_type = order['type']
|
||||
# Ignore open and cancelled orders
|
||||
if not order['closed'] or order['rate'] is None:
|
||||
if order['status'] == 'open' or order['price'] is None:
|
||||
return
|
||||
|
||||
logger.info('Updating trade (id=%d) ...', self.id)
|
||||
logger.info('Updating trade (id=%s) ...', self.id)
|
||||
|
||||
getcontext().prec = 8 # Bittrex do not go above 8 decimal
|
||||
if order['type'] == 'LIMIT_BUY':
|
||||
if order_type in ('market', 'limit') and order['side'] == 'buy':
|
||||
# Update open rate and actual amount
|
||||
self.open_rate = Decimal(order['rate'])
|
||||
self.open_rate = Decimal(order['price'])
|
||||
self.amount = Decimal(order['amount'])
|
||||
logger.info('LIMIT_BUY has been fulfilled for %s.', self)
|
||||
logger.info('%s_BUY has been fulfilled for %s.', order_type.upper(), self)
|
||||
self.open_order_id = None
|
||||
elif order['type'] == 'LIMIT_SELL':
|
||||
self.close(order['rate'])
|
||||
elif order_type in ('market', 'limit') and order['side'] == 'sell':
|
||||
self.close(order['price'])
|
||||
logger.info('%s_SELL has been fulfilled for %s.', order_type.upper(), self)
|
||||
elif order_type == 'stop_loss_limit':
|
||||
self.stoploss_order_id = None
|
||||
logger.info('STOP_LOSS_LIMIT is hit for %s.', self)
|
||||
self.close(order['average'])
|
||||
else:
|
||||
raise ValueError('Unknown order type: {}'.format(order['type']))
|
||||
raise ValueError(f'Unknown order type: {order_type}')
|
||||
cleanup()
|
||||
|
||||
def close(self, rate: float) -> None:
|
||||
@@ -148,15 +291,14 @@ class Trade(_DECL_BASE):
|
||||
self,
|
||||
fee: Optional[float] = None) -> float:
|
||||
"""
|
||||
Calculate the open_rate in BTC
|
||||
Calculate the open_rate including fee.
|
||||
:param fee: fee to use on the open rate (optional).
|
||||
If rate is not set self.fee will be used
|
||||
:return: Price in BTC of the open trade
|
||||
:return: Price in of the open trade incl. Fees
|
||||
"""
|
||||
getcontext().prec = 8
|
||||
|
||||
buy_trade = (Decimal(self.amount) * Decimal(self.open_rate))
|
||||
fees = buy_trade * Decimal(fee or self.fee)
|
||||
fees = buy_trade * Decimal(fee or self.fee_open)
|
||||
return float(buy_trade + fees)
|
||||
|
||||
def calc_close_trade_price(
|
||||
@@ -164,20 +306,19 @@ class Trade(_DECL_BASE):
|
||||
rate: Optional[float] = None,
|
||||
fee: Optional[float] = None) -> float:
|
||||
"""
|
||||
Calculate the close_rate in BTC
|
||||
Calculate the close_rate including fee
|
||||
:param fee: fee to use on the close rate (optional).
|
||||
If rate is not set self.fee will be used
|
||||
:param rate: rate to compare with (optional).
|
||||
If rate is not set self.close_rate will be used
|
||||
:return: Price in BTC of the open trade
|
||||
"""
|
||||
getcontext().prec = 8
|
||||
|
||||
if rate is None and not self.close_rate:
|
||||
return 0.0
|
||||
|
||||
sell_trade = (Decimal(self.amount) * Decimal(rate or self.close_rate))
|
||||
fees = sell_trade * Decimal(fee or self.fee)
|
||||
fees = sell_trade * Decimal(fee or self.fee_close)
|
||||
return float(sell_trade - fees)
|
||||
|
||||
def calc_profit(
|
||||
@@ -185,19 +326,20 @@ class Trade(_DECL_BASE):
|
||||
rate: Optional[float] = None,
|
||||
fee: Optional[float] = None) -> float:
|
||||
"""
|
||||
Calculate the profit in BTC between Close and Open trade
|
||||
Calculate the absolute profit in stake currency between Close and Open trade
|
||||
:param fee: fee to use on the close rate (optional).
|
||||
If rate is not set self.fee will be used
|
||||
:param rate: close rate to compare with (optional).
|
||||
If rate is not set self.close_rate will be used
|
||||
:return: profit in BTC as float
|
||||
:return: profit in stake currency as float
|
||||
"""
|
||||
open_trade_price = self.calc_open_trade_price()
|
||||
close_trade_price = self.calc_close_trade_price(
|
||||
rate=(rate or self.close_rate),
|
||||
fee=(fee or self.fee)
|
||||
fee=(fee or self.fee_close)
|
||||
)
|
||||
return float("{0:.8f}".format(close_trade_price - open_trade_price))
|
||||
profit = close_trade_price - open_trade_price
|
||||
return float(f"{profit:.8f}")
|
||||
|
||||
def calc_profit_percent(
|
||||
self,
|
||||
@@ -210,12 +352,22 @@ class Trade(_DECL_BASE):
|
||||
:param fee: fee to use on the close rate (optional).
|
||||
:return: profit in percentage as float
|
||||
"""
|
||||
getcontext().prec = 8
|
||||
|
||||
open_trade_price = self.calc_open_trade_price()
|
||||
close_trade_price = self.calc_close_trade_price(
|
||||
rate=(rate or self.close_rate),
|
||||
fee=(fee or self.fee)
|
||||
fee=(fee or self.fee_close)
|
||||
)
|
||||
profit_percent = (close_trade_price / open_trade_price) - 1
|
||||
return float(f"{profit_percent:.8f}")
|
||||
|
||||
return float("{0:.8f}".format((close_trade_price / open_trade_price) - 1))
|
||||
@staticmethod
|
||||
def total_open_trades_stakes() -> float:
|
||||
"""
|
||||
Calculates total invested amount in open trades
|
||||
in stake currency
|
||||
"""
|
||||
total_open_stake_amount = Trade.session.query(func.sum(Trade.stake_amount))\
|
||||
.filter(Trade.is_open.is_(True))\
|
||||
.scalar()
|
||||
return total_open_stake_amount or 0
|
||||
|
||||
4
freqtrade/resolvers/__init__.py
Normal file
4
freqtrade/resolvers/__init__.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from freqtrade.resolvers.iresolver import IResolver # noqa: F401
|
||||
from freqtrade.resolvers.hyperopt_resolver import HyperOptResolver # noqa: F401
|
||||
from freqtrade.resolvers.pairlist_resolver import PairListResolver # noqa: F401
|
||||
from freqtrade.resolvers.strategy_resolver import StrategyResolver # noqa: F401
|
||||
74
freqtrade/resolvers/hyperopt_resolver.py
Normal file
74
freqtrade/resolvers/hyperopt_resolver.py
Normal file
@@ -0,0 +1,74 @@
|
||||
# pragma pylint: disable=attribute-defined-outside-init
|
||||
|
||||
"""
|
||||
This module load custom hyperopts
|
||||
"""
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Optional, Dict
|
||||
|
||||
from freqtrade.constants import DEFAULT_HYPEROPT
|
||||
from freqtrade.optimize.hyperopt_interface import IHyperOpt
|
||||
from freqtrade.resolvers import IResolver
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class HyperOptResolver(IResolver):
|
||||
"""
|
||||
This class contains all the logic to load custom hyperopt class
|
||||
"""
|
||||
|
||||
__slots__ = ['hyperopt']
|
||||
|
||||
def __init__(self, config: Optional[Dict] = None) -> None:
|
||||
"""
|
||||
Load the custom class from config parameter
|
||||
:param config: configuration dictionary or None
|
||||
"""
|
||||
config = config or {}
|
||||
|
||||
# Verify the hyperopt is in the configuration, otherwise fallback to the default hyperopt
|
||||
hyperopt_name = config.get('hyperopt') or DEFAULT_HYPEROPT
|
||||
self.hyperopt = self._load_hyperopt(hyperopt_name, extra_dir=config.get('hyperopt_path'))
|
||||
|
||||
if not hasattr(self.hyperopt, 'populate_buy_trend'):
|
||||
logger.warning("Custom Hyperopt does not provide populate_buy_trend. "
|
||||
"Using populate_buy_trend from DefaultStrategy.")
|
||||
if not hasattr(self.hyperopt, 'populate_sell_trend'):
|
||||
logger.warning("Custom Hyperopt does not provide populate_sell_trend. "
|
||||
"Using populate_sell_trend from DefaultStrategy.")
|
||||
|
||||
def _load_hyperopt(
|
||||
self, hyperopt_name: str, extra_dir: Optional[str] = None) -> IHyperOpt:
|
||||
"""
|
||||
Search and loads the specified hyperopt.
|
||||
:param hyperopt_name: name of the module to import
|
||||
:param extra_dir: additional directory to search for the given hyperopt
|
||||
:return: HyperOpt instance or None
|
||||
"""
|
||||
current_path = Path(__file__).parent.parent.joinpath('optimize').resolve()
|
||||
|
||||
abs_paths = [
|
||||
current_path.parent.parent.joinpath('user_data/hyperopts'),
|
||||
current_path,
|
||||
]
|
||||
|
||||
if extra_dir:
|
||||
# Add extra hyperopt directory on top of search paths
|
||||
abs_paths.insert(0, Path(extra_dir))
|
||||
|
||||
for _path in abs_paths:
|
||||
try:
|
||||
hyperopt = self._search_object(directory=_path, object_type=IHyperOpt,
|
||||
object_name=hyperopt_name)
|
||||
if hyperopt:
|
||||
logger.info('Using resolved hyperopt %s from \'%s\'', hyperopt_name, _path)
|
||||
return hyperopt
|
||||
except FileNotFoundError:
|
||||
logger.warning('Path "%s" does not exist', _path.relative_to(Path.cwd()))
|
||||
|
||||
raise ImportError(
|
||||
"Impossible to load Hyperopt '{}'. This class does not exist"
|
||||
" or contains Python code errors".format(hyperopt_name)
|
||||
)
|
||||
61
freqtrade/resolvers/iresolver.py
Normal file
61
freqtrade/resolvers/iresolver.py
Normal file
@@ -0,0 +1,61 @@
|
||||
# pragma pylint: disable=attribute-defined-outside-init
|
||||
|
||||
"""
|
||||
This module load custom objects
|
||||
"""
|
||||
import importlib.util
|
||||
import inspect
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Optional, Type, Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class IResolver(object):
|
||||
"""
|
||||
This class contains all the logic to load custom classes
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def _get_valid_object(object_type, module_path: Path,
|
||||
object_name: str) -> Optional[Type[Any]]:
|
||||
"""
|
||||
Returns the first object with matching object_type and object_name in the path given.
|
||||
:param object_type: object_type (class)
|
||||
:param module_path: absolute path to the module
|
||||
:param object_name: Class name of the object
|
||||
:return: class or None
|
||||
"""
|
||||
|
||||
# Generate spec based on absolute path
|
||||
spec = importlib.util.spec_from_file_location('unknown', str(module_path))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module) # type: ignore # importlib does not use typehints
|
||||
|
||||
valid_objects_gen = (
|
||||
obj for name, obj in inspect.getmembers(module, inspect.isclass)
|
||||
if object_name == name and object_type in obj.__bases__
|
||||
)
|
||||
return next(valid_objects_gen, None)
|
||||
|
||||
@staticmethod
|
||||
def _search_object(directory: Path, object_type, object_name: str,
|
||||
kwargs: dict = {}) -> Optional[Any]:
|
||||
"""
|
||||
Search for the objectname in the given directory
|
||||
:param directory: relative or absolute directory path
|
||||
:return: object instance
|
||||
"""
|
||||
logger.debug('Searching for %s %s in \'%s\'', object_type.__name__, object_name, directory)
|
||||
for entry in directory.iterdir():
|
||||
# Only consider python files
|
||||
if not str(entry).endswith('.py'):
|
||||
logger.debug('Ignoring %s', entry)
|
||||
continue
|
||||
obj = IResolver._get_valid_object(
|
||||
object_type, Path.resolve(directory.joinpath(entry)), object_name
|
||||
)
|
||||
if obj:
|
||||
return obj(**kwargs)
|
||||
return None
|
||||
59
freqtrade/resolvers/pairlist_resolver.py
Normal file
59
freqtrade/resolvers/pairlist_resolver.py
Normal file
@@ -0,0 +1,59 @@
|
||||
# pragma pylint: disable=attribute-defined-outside-init
|
||||
|
||||
"""
|
||||
This module load custom hyperopts
|
||||
"""
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from freqtrade.pairlist.IPairList import IPairList
|
||||
from freqtrade.resolvers import IResolver
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PairListResolver(IResolver):
|
||||
"""
|
||||
This class contains all the logic to load custom hyperopt class
|
||||
"""
|
||||
|
||||
__slots__ = ['pairlist']
|
||||
|
||||
def __init__(self, pairlist_name: str, freqtrade, config: dict) -> None:
|
||||
"""
|
||||
Load the custom class from config parameter
|
||||
:param config: configuration dictionary or None
|
||||
"""
|
||||
self.pairlist = self._load_pairlist(pairlist_name, kwargs={'freqtrade': freqtrade,
|
||||
'config': config})
|
||||
|
||||
def _load_pairlist(
|
||||
self, pairlist_name: str, kwargs: dict) -> IPairList:
|
||||
"""
|
||||
Search and loads the specified pairlist.
|
||||
:param pairlist_name: name of the module to import
|
||||
:param extra_dir: additional directory to search for the given pairlist
|
||||
:return: PairList instance or None
|
||||
"""
|
||||
current_path = Path(__file__).parent.parent.joinpath('pairlist').resolve()
|
||||
|
||||
abs_paths = [
|
||||
current_path.parent.parent.joinpath('user_data/pairlist'),
|
||||
current_path,
|
||||
]
|
||||
|
||||
for _path in abs_paths:
|
||||
try:
|
||||
pairlist = self._search_object(directory=_path, object_type=IPairList,
|
||||
object_name=pairlist_name,
|
||||
kwargs=kwargs)
|
||||
if pairlist:
|
||||
logger.info('Using resolved pairlist %s from \'%s\'', pairlist_name, _path)
|
||||
return pairlist
|
||||
except FileNotFoundError:
|
||||
logger.warning('Path "%s" does not exist', _path.relative_to(Path.cwd()))
|
||||
|
||||
raise ImportError(
|
||||
"Impossible to load Pairlist '{}'. This class does not exist"
|
||||
" or contains Python code errors".format(pairlist_name)
|
||||
)
|
||||
165
freqtrade/resolvers/strategy_resolver.py
Normal file
165
freqtrade/resolvers/strategy_resolver.py
Normal file
@@ -0,0 +1,165 @@
|
||||
# pragma pylint: disable=attribute-defined-outside-init
|
||||
|
||||
"""
|
||||
This module load custom strategies
|
||||
"""
|
||||
import logging
|
||||
import tempfile
|
||||
from base64 import urlsafe_b64decode
|
||||
from collections import OrderedDict
|
||||
from inspect import getfullargspec
|
||||
from pathlib import Path
|
||||
from typing import Dict, Optional
|
||||
|
||||
from freqtrade import constants
|
||||
from freqtrade.resolvers import IResolver
|
||||
from freqtrade.strategy import import_strategy
|
||||
from freqtrade.strategy.interface import IStrategy
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class StrategyResolver(IResolver):
|
||||
"""
|
||||
This class contains all the logic to load custom strategy class
|
||||
"""
|
||||
|
||||
__slots__ = ['strategy']
|
||||
|
||||
def __init__(self, config: Optional[Dict] = None) -> None:
|
||||
"""
|
||||
Load the custom class from config parameter
|
||||
:param config: configuration dictionary or None
|
||||
"""
|
||||
config = config or {}
|
||||
|
||||
# Verify the strategy is in the configuration, otherwise fallback to the default strategy
|
||||
strategy_name = config.get('strategy') or constants.DEFAULT_STRATEGY
|
||||
self.strategy: IStrategy = self._load_strategy(strategy_name,
|
||||
config=config,
|
||||
extra_dir=config.get('strategy_path'))
|
||||
|
||||
# make sure experimental dict is available
|
||||
if 'experimental' not in config:
|
||||
config['experimental'] = {}
|
||||
|
||||
# Set attributes
|
||||
# Check if we need to override configuration
|
||||
# (Attribute name, default, experimental)
|
||||
attributes = [("minimal_roi", None, False),
|
||||
("ticker_interval", None, False),
|
||||
("stoploss", None, False),
|
||||
("trailing_stop", None, False),
|
||||
("trailing_stop_positive", None, False),
|
||||
("trailing_stop_positive_offset", 0.0, False),
|
||||
("process_only_new_candles", None, False),
|
||||
("order_types", None, False),
|
||||
("order_time_in_force", None, False),
|
||||
("use_sell_signal", False, True),
|
||||
("sell_profit_only", False, True),
|
||||
("ignore_roi_if_buy_signal", False, True),
|
||||
]
|
||||
for attribute, default, experimental in attributes:
|
||||
if experimental:
|
||||
self._override_attribute_helper(config['experimental'], attribute, default)
|
||||
else:
|
||||
self._override_attribute_helper(config, attribute, default)
|
||||
|
||||
# Loop this list again to have output combined
|
||||
for attribute, _, exp in attributes:
|
||||
if exp and attribute in config['experimental']:
|
||||
logger.info("Strategy using %s: %s", attribute, config['experimental'][attribute])
|
||||
elif attribute in config:
|
||||
logger.info("Strategy using %s: %s", attribute, config[attribute])
|
||||
|
||||
# Sort and apply type conversions
|
||||
self.strategy.minimal_roi = OrderedDict(sorted(
|
||||
{int(key): value for (key, value) in self.strategy.minimal_roi.items()}.items(),
|
||||
key=lambda t: t[0]))
|
||||
self.strategy.stoploss = float(self.strategy.stoploss)
|
||||
|
||||
self._strategy_sanity_validations()
|
||||
|
||||
def _override_attribute_helper(self, config, attribute: str, default):
|
||||
"""
|
||||
Override attributes in the strategy.
|
||||
Prevalence:
|
||||
- Configuration
|
||||
- Strategy
|
||||
- default (if not None)
|
||||
"""
|
||||
if attribute in config:
|
||||
setattr(self.strategy, attribute, config[attribute])
|
||||
logger.info("Override strategy '%s' with value in config file: %s.",
|
||||
attribute, config[attribute])
|
||||
elif hasattr(self.strategy, attribute):
|
||||
config[attribute] = getattr(self.strategy, attribute)
|
||||
# Explicitly check for None here as other "falsy" values are possible
|
||||
elif default is not None:
|
||||
setattr(self.strategy, attribute, default)
|
||||
config[attribute] = default
|
||||
|
||||
def _strategy_sanity_validations(self):
|
||||
if not all(k in self.strategy.order_types for k in constants.REQUIRED_ORDERTYPES):
|
||||
raise ImportError(f"Impossible to load Strategy '{self.strategy.__class__.__name__}'. "
|
||||
f"Order-types mapping is incomplete.")
|
||||
|
||||
if not all(k in self.strategy.order_time_in_force for k in constants.REQUIRED_ORDERTIF):
|
||||
raise ImportError(f"Impossible to load Strategy '{self.strategy.__class__.__name__}'. "
|
||||
f"Order-time-in-force mapping is incomplete.")
|
||||
|
||||
def _load_strategy(
|
||||
self, strategy_name: str, config: dict, extra_dir: Optional[str] = None) -> IStrategy:
|
||||
"""
|
||||
Search and loads the specified strategy.
|
||||
:param strategy_name: name of the module to import
|
||||
:param config: configuration for the strategy
|
||||
:param extra_dir: additional directory to search for the given strategy
|
||||
:return: Strategy instance or None
|
||||
"""
|
||||
current_path = Path(__file__).parent.parent.joinpath('strategy').resolve()
|
||||
|
||||
abs_paths = [
|
||||
Path.cwd().joinpath('user_data/strategies'),
|
||||
current_path,
|
||||
]
|
||||
|
||||
if extra_dir:
|
||||
# Add extra strategy directory on top of search paths
|
||||
abs_paths.insert(0, Path(extra_dir).resolve())
|
||||
|
||||
if ":" in strategy_name:
|
||||
logger.info("loading base64 endocded strategy")
|
||||
strat = strategy_name.split(":")
|
||||
|
||||
if len(strat) == 2:
|
||||
temp = Path(tempfile.mkdtemp("freq", "strategy"))
|
||||
name = strat[0] + ".py"
|
||||
|
||||
temp.joinpath(name).write_text(urlsafe_b64decode(strat[1]).decode('utf-8'))
|
||||
temp.joinpath("__init__.py").touch()
|
||||
|
||||
strategy_name = strat[0]
|
||||
|
||||
# register temp path with the bot
|
||||
abs_paths.insert(0, temp.resolve())
|
||||
|
||||
for _path in abs_paths:
|
||||
try:
|
||||
strategy = self._search_object(directory=_path, object_type=IStrategy,
|
||||
object_name=strategy_name, kwargs={'config': config})
|
||||
if strategy:
|
||||
logger.info('Using resolved strategy %s from \'%s\'', strategy_name, _path)
|
||||
strategy._populate_fun_len = len(
|
||||
getfullargspec(strategy.populate_indicators).args)
|
||||
strategy._buy_fun_len = len(getfullargspec(strategy.populate_buy_trend).args)
|
||||
strategy._sell_fun_len = len(getfullargspec(strategy.populate_sell_trend).args)
|
||||
|
||||
return import_strategy(strategy, config=config)
|
||||
except FileNotFoundError:
|
||||
logger.warning('Path "%s" does not exist', _path.relative_to(Path.cwd()))
|
||||
|
||||
raise ImportError(
|
||||
"Impossible to load Strategy '{}'. This class does not exist"
|
||||
" or contains Python code errors".format(strategy_name)
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
from .rpc import RPC, RPCMessageType, RPCException # noqa
|
||||
from .rpc_manager import RPCManager # noqa
|
||||
|
||||
@@ -5,9 +5,13 @@ e.g BTC to USD
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Dict, List
|
||||
|
||||
from coinmarketcap import Market
|
||||
|
||||
from freqtrade.constants import SUPPORTED_FIAT
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -32,7 +36,7 @@ class CryptoFiat(object):
|
||||
self.price = 0.0
|
||||
|
||||
# Private attributes
|
||||
self._expiration = 0
|
||||
self._expiration = 0.0
|
||||
|
||||
self.crypto_symbol = crypto_symbol.upper()
|
||||
self.fiat_symbol = fiat_symbol.upper()
|
||||
@@ -63,21 +67,9 @@ class CryptoToFiatConverter(object):
|
||||
This object is also a Singleton
|
||||
"""
|
||||
__instance = None
|
||||
_coinmarketcap = None
|
||||
_coinmarketcap: Market = None
|
||||
|
||||
# Constants
|
||||
SUPPORTED_FIAT = [
|
||||
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK",
|
||||
"EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY",
|
||||
"KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN",
|
||||
"RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR", "USD"
|
||||
]
|
||||
|
||||
CRYPTOMAP = {
|
||||
'BTC': 'bitcoin',
|
||||
'ETH': 'ethereum',
|
||||
'USDT': 'thether'
|
||||
}
|
||||
_cryptomap: Dict = {}
|
||||
|
||||
def __new__(cls):
|
||||
if CryptoToFiatConverter.__instance is None:
|
||||
@@ -89,7 +81,19 @@ class CryptoToFiatConverter(object):
|
||||
return CryptoToFiatConverter.__instance
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._pairs = []
|
||||
self._pairs: List[CryptoFiat] = []
|
||||
self._load_cryptomap()
|
||||
|
||||
def _load_cryptomap(self) -> None:
|
||||
try:
|
||||
coinlistings = self._coinmarketcap.listings()
|
||||
self._cryptomap = dict(map(lambda coin: (coin["symbol"], str(coin["id"])),
|
||||
coinlistings["data"]))
|
||||
except (BaseException) as exception:
|
||||
logger.error(
|
||||
"Could not load FIAT Cryptocurrency map for the following problem: %s",
|
||||
type(exception).__name__
|
||||
)
|
||||
|
||||
def convert_amount(self, crypto_amount: float, crypto_symbol: str, fiat_symbol: str) -> float:
|
||||
"""
|
||||
@@ -99,6 +103,8 @@ class CryptoToFiatConverter(object):
|
||||
:param fiat_symbol: fiat to convert to
|
||||
:return: float, value in fiat of the crypto-currency amount
|
||||
"""
|
||||
if crypto_symbol == fiat_symbol:
|
||||
return crypto_amount
|
||||
price = self.get_price(crypto_symbol=crypto_symbol, fiat_symbol=fiat_symbol)
|
||||
return float(crypto_amount) * float(price)
|
||||
|
||||
@@ -114,7 +120,7 @@ class CryptoToFiatConverter(object):
|
||||
|
||||
# Check if the fiat convertion you want is supported
|
||||
if not self._is_supported_fiat(fiat=fiat_symbol):
|
||||
raise ValueError('The fiat {} is not supported.'.format(fiat_symbol))
|
||||
raise ValueError(f'The fiat {fiat_symbol} is not supported.')
|
||||
|
||||
# Get the pair that interest us and return the price in fiat
|
||||
for pair in self._pairs:
|
||||
@@ -166,7 +172,7 @@ class CryptoToFiatConverter(object):
|
||||
|
||||
fiat = fiat.upper()
|
||||
|
||||
return fiat in self.SUPPORTED_FIAT
|
||||
return fiat in SUPPORTED_FIAT
|
||||
|
||||
def _find_price(self, crypto_symbol: str, fiat_symbol: str) -> float:
|
||||
"""
|
||||
@@ -177,17 +183,24 @@ class CryptoToFiatConverter(object):
|
||||
"""
|
||||
# Check if the fiat convertion you want is supported
|
||||
if not self._is_supported_fiat(fiat=fiat_symbol):
|
||||
raise ValueError('The fiat {} is not supported.'.format(fiat_symbol))
|
||||
raise ValueError(f'The fiat {fiat_symbol} is not supported.')
|
||||
|
||||
# No need to convert if both crypto and fiat are the same
|
||||
if crypto_symbol == fiat_symbol:
|
||||
return 1.0
|
||||
|
||||
if crypto_symbol not in self._cryptomap:
|
||||
# return 0 for unsupported stake currencies (fiat-convert should not break the bot)
|
||||
logger.warning("unsupported crypto-symbol %s - returning 0.0", crypto_symbol)
|
||||
return 0.0
|
||||
|
||||
if crypto_symbol not in self.CRYPTOMAP:
|
||||
raise ValueError(
|
||||
'The crypto symbol {} is not supported.'.format(crypto_symbol))
|
||||
try:
|
||||
return float(
|
||||
self._coinmarketcap.ticker(
|
||||
currency=self.CRYPTOMAP[crypto_symbol],
|
||||
currency=self._cryptomap[crypto_symbol],
|
||||
convert=fiat_symbol
|
||||
)[0]['price_' + fiat_symbol.lower()]
|
||||
)['data']['quotes'][fiat_symbol.upper()]['price']
|
||||
)
|
||||
except BaseException:
|
||||
except BaseException as exception:
|
||||
logger.error("Error in _find_price: %s", exception)
|
||||
return 0.0
|
||||
@@ -2,124 +2,155 @@
|
||||
This module contains class to define a RPC communications
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from abc import abstractmethod
|
||||
from datetime import timedelta, datetime, date
|
||||
from decimal import Decimal
|
||||
from typing import Tuple, Any
|
||||
from enum import Enum
|
||||
from typing import Dict, Any, List, Optional
|
||||
|
||||
import arrow
|
||||
import sqlalchemy as sql
|
||||
from numpy import mean, nan_to_num, NAN
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade import exchange
|
||||
from freqtrade import TemporaryError, DependencyException
|
||||
from freqtrade.misc import shorten_date
|
||||
from freqtrade.persistence import Trade
|
||||
from freqtrade.rpc.fiat_convert import CryptoToFiatConverter
|
||||
from freqtrade.state import State
|
||||
|
||||
from freqtrade.strategy.interface import SellType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RPCMessageType(Enum):
|
||||
STATUS_NOTIFICATION = 'status'
|
||||
WARNING_NOTIFICATION = 'warning'
|
||||
CUSTOM_NOTIFICATION = 'custom'
|
||||
BUY_NOTIFICATION = 'buy'
|
||||
SELL_NOTIFICATION = 'sell'
|
||||
|
||||
def __repr__(self):
|
||||
return self.value
|
||||
|
||||
|
||||
class RPCException(Exception):
|
||||
"""
|
||||
Should be raised with a rpc-formatted message in an _rpc_* method
|
||||
if the required state is wrong, i.e.:
|
||||
|
||||
raise RPCException('*Status:* `no active trade`')
|
||||
"""
|
||||
def __init__(self, message: str) -> None:
|
||||
super().__init__(self)
|
||||
self.message = message
|
||||
|
||||
def __str__(self):
|
||||
return self.message
|
||||
|
||||
|
||||
class RPC(object):
|
||||
"""
|
||||
RPC class can be used to have extra feature, like bot data, and access to DB data
|
||||
"""
|
||||
# Bind _fiat_converter if needed in each RPC handler
|
||||
_fiat_converter: Optional[CryptoToFiatConverter] = None
|
||||
|
||||
def __init__(self, freqtrade) -> None:
|
||||
"""
|
||||
Initializes all enabled rpc modules
|
||||
:param freqtrade: Instance of a freqtrade bot
|
||||
:return: None
|
||||
"""
|
||||
self.freqtrade = freqtrade
|
||||
self._freqtrade = freqtrade
|
||||
|
||||
def rpc_trade_status(self) -> Tuple[bool, Any]:
|
||||
@property
|
||||
def name(self) -> str:
|
||||
""" Returns the lowercase name of the implementation """
|
||||
return self.__class__.__name__.lower()
|
||||
|
||||
@abstractmethod
|
||||
def cleanup(self) -> None:
|
||||
""" Cleanup pending module resources """
|
||||
|
||||
@abstractmethod
|
||||
def send_msg(self, msg: Dict[str, str]) -> None:
|
||||
""" Sends a message to all registered rpc modules """
|
||||
|
||||
def _rpc_trade_status(self) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Below follows the RPC backend it is prefixed with rpc_ to raise awareness that it is
|
||||
a remotely exposed function
|
||||
:return:
|
||||
"""
|
||||
# Fetch open trade
|
||||
trades = Trade.query.filter(Trade.is_open.is_(True)).all()
|
||||
if self.freqtrade.state != State.RUNNING:
|
||||
return True, '*Status:* `trader is not running`'
|
||||
elif not trades:
|
||||
return True, '*Status:* `no active trade`'
|
||||
if not trades:
|
||||
raise RPCException('no active trade')
|
||||
else:
|
||||
result = []
|
||||
results = []
|
||||
for trade in trades:
|
||||
order = None
|
||||
if trade.open_order_id:
|
||||
order = exchange.get_order(trade.open_order_id)
|
||||
order = self._freqtrade.exchange.get_order(trade.open_order_id, trade.pair)
|
||||
# calculate profit and send message to user
|
||||
current_rate = exchange.get_ticker(trade.pair, False)['bid']
|
||||
try:
|
||||
current_rate = self._freqtrade.exchange.get_ticker(trade.pair, False)['bid']
|
||||
except DependencyException:
|
||||
current_rate = NAN
|
||||
current_profit = trade.calc_profit_percent(current_rate)
|
||||
fmt_close_profit = '{:.2f}%'.format(
|
||||
round(trade.close_profit * 100, 2)
|
||||
) if trade.close_profit else None
|
||||
message = "*Trade ID:* `{trade_id}`\n" \
|
||||
"*Current Pair:* [{pair}]({market_url})\n" \
|
||||
"*Open Since:* `{date}`\n" \
|
||||
"*Amount:* `{amount}`\n" \
|
||||
"*Open Rate:* `{open_rate:.8f}`\n" \
|
||||
"*Close Rate:* `{close_rate}`\n" \
|
||||
"*Current Rate:* `{current_rate:.8f}`\n" \
|
||||
"*Close Profit:* `{close_profit}`\n" \
|
||||
"*Current Profit:* `{current_profit:.2f}%`\n" \
|
||||
"*Open Order:* `{open_order}`"\
|
||||
.format(
|
||||
trade_id=trade.id,
|
||||
pair=trade.pair,
|
||||
market_url=exchange.get_pair_detail_url(trade.pair),
|
||||
date=arrow.get(trade.open_date).humanize(),
|
||||
open_rate=trade.open_rate,
|
||||
close_rate=trade.close_rate,
|
||||
current_rate=current_rate,
|
||||
amount=round(trade.amount, 8),
|
||||
close_profit=fmt_close_profit,
|
||||
current_profit=round(current_profit * 100, 2),
|
||||
open_order='({} rem={:.8f})'.format(
|
||||
order['type'], order['remaining']
|
||||
) if order else None,
|
||||
)
|
||||
result.append(message)
|
||||
return False, result
|
||||
fmt_close_profit = (f'{round(trade.close_profit * 100, 2):.2f}%'
|
||||
if trade.close_profit else None)
|
||||
results.append(dict(
|
||||
trade_id=trade.id,
|
||||
pair=trade.pair,
|
||||
market_url=self._freqtrade.exchange.get_pair_detail_url(trade.pair),
|
||||
date=arrow.get(trade.open_date),
|
||||
open_rate=trade.open_rate,
|
||||
close_rate=trade.close_rate,
|
||||
current_rate=current_rate,
|
||||
amount=round(trade.amount, 8),
|
||||
close_profit=fmt_close_profit,
|
||||
current_profit=round(current_profit * 100, 2),
|
||||
open_order='({} {} rem={:.8f})'.format(
|
||||
order['type'], order['side'], order['remaining']
|
||||
) if order else None,
|
||||
))
|
||||
return results
|
||||
|
||||
def rpc_status_table(self) -> Tuple[bool, Any]:
|
||||
def _rpc_status_table(self) -> DataFrame:
|
||||
trades = Trade.query.filter(Trade.is_open.is_(True)).all()
|
||||
if self.freqtrade.state != State.RUNNING:
|
||||
return True, '*Status:* `trader is not running`'
|
||||
elif not trades:
|
||||
return True, '*Status:* `no active order`'
|
||||
if not trades:
|
||||
raise RPCException('no active order')
|
||||
else:
|
||||
trades_list = []
|
||||
for trade in trades:
|
||||
# calculate profit and send message to user
|
||||
current_rate = exchange.get_ticker(trade.pair, False)['bid']
|
||||
try:
|
||||
current_rate = self._freqtrade.exchange.get_ticker(trade.pair, False)['bid']
|
||||
except DependencyException:
|
||||
current_rate = NAN
|
||||
trade_perc = (100 * trade.calc_profit_percent(current_rate))
|
||||
trades_list.append([
|
||||
trade.id,
|
||||
trade.pair,
|
||||
shorten_date(arrow.get(trade.open_date).humanize(only_distance=True)),
|
||||
'{:.2f}%'.format(100 * trade.calc_profit_percent(current_rate))
|
||||
f'{trade_perc:.2f}%'
|
||||
])
|
||||
|
||||
columns = ['ID', 'Pair', 'Since', 'Profit']
|
||||
df_statuses = DataFrame.from_records(trades_list, columns=columns)
|
||||
df_statuses = df_statuses.set_index(columns[0])
|
||||
# The style used throughout is to return a tuple
|
||||
# consisting of (error_occured?, result)
|
||||
# Another approach would be to just return the
|
||||
# result, or raise error
|
||||
return False, df_statuses
|
||||
return df_statuses
|
||||
|
||||
def rpc_daily_profit(
|
||||
def _rpc_daily_profit(
|
||||
self, timescale: int,
|
||||
stake_currency: str, fiat_display_currency: str) -> Tuple[bool, Any]:
|
||||
stake_currency: str, fiat_display_currency: str) -> List[List[Any]]:
|
||||
today = datetime.utcnow().date()
|
||||
profit_days = {}
|
||||
profit_days: Dict[date, Dict] = {}
|
||||
|
||||
if not (isinstance(timescale, int) and timescale > 0):
|
||||
return True, '*Daily [n]:* `must be an integer greater than 0`'
|
||||
raise RPCException('timescale must be an integer greater than 0')
|
||||
|
||||
fiat = self.freqtrade.fiat_converter
|
||||
for day in range(0, timescale):
|
||||
profitday = today - timedelta(days=day)
|
||||
trades = Trade.query \
|
||||
@@ -130,11 +161,11 @@ class RPC(object):
|
||||
.all()
|
||||
curdayprofit = sum(trade.calc_profit() for trade in trades)
|
||||
profit_days[profitday] = {
|
||||
'amount': format(curdayprofit, '.8f'),
|
||||
'amount': f'{curdayprofit:.8f}',
|
||||
'trades': len(trades)
|
||||
}
|
||||
|
||||
stats = [
|
||||
return [
|
||||
[
|
||||
key,
|
||||
'{value:.8f} {symbol}'.format(
|
||||
@@ -142,11 +173,11 @@ class RPC(object):
|
||||
symbol=stake_currency
|
||||
),
|
||||
'{value:.3f} {symbol}'.format(
|
||||
value=fiat.convert_amount(
|
||||
value=self._fiat_converter.convert_amount(
|
||||
value['amount'],
|
||||
stake_currency,
|
||||
fiat_display_currency
|
||||
),
|
||||
) if self._fiat_converter else 0,
|
||||
symbol=fiat_display_currency
|
||||
),
|
||||
'{value} trade{s}'.format(
|
||||
@@ -156,13 +187,10 @@ class RPC(object):
|
||||
]
|
||||
for key, value in profit_days.items()
|
||||
]
|
||||
return False, stats
|
||||
|
||||
def rpc_trade_statistics(
|
||||
self, stake_currency: str, fiat_display_currency: str) -> Tuple[bool, Any]:
|
||||
"""
|
||||
:return: cumulative profit statistics.
|
||||
"""
|
||||
def _rpc_trade_statistics(
|
||||
self, stake_currency: str, fiat_display_currency: str) -> Dict[str, Any]:
|
||||
""" Returns cumulative profit statistics """
|
||||
trades = Trade.query.order_by(Trade.id).all()
|
||||
|
||||
profit_all_coin = []
|
||||
@@ -172,7 +200,7 @@ class RPC(object):
|
||||
durations = []
|
||||
|
||||
for trade in trades:
|
||||
current_rate = None
|
||||
current_rate: float = 0.0
|
||||
|
||||
if not trade.open_rate:
|
||||
continue
|
||||
@@ -185,7 +213,10 @@ class RPC(object):
|
||||
profit_closed_percent.append(profit_percent)
|
||||
else:
|
||||
# Get current rate
|
||||
current_rate = exchange.get_ticker(trade.pair, False)['bid']
|
||||
try:
|
||||
current_rate = self._freqtrade.exchange.get_ticker(trade.pair, False)['bid']
|
||||
except DependencyException:
|
||||
current_rate = NAN
|
||||
profit_percent = trade.calc_profit_percent(rate=current_rate)
|
||||
|
||||
profit_all_coin.append(
|
||||
@@ -200,141 +231,145 @@ class RPC(object):
|
||||
.order_by(sql.text('profit_sum DESC')).first()
|
||||
|
||||
if not best_pair:
|
||||
return True, '*Status:* `no closed trade`'
|
||||
raise RPCException('no closed trade')
|
||||
|
||||
bp_pair, bp_rate = best_pair
|
||||
|
||||
# FIX: we want to keep fiatconverter in a state/environment,
|
||||
# doing this will utilize its caching functionallity, instead we reinitialize it here
|
||||
fiat = self.freqtrade.fiat_converter
|
||||
# Prepare data to display
|
||||
profit_closed_coin = round(sum(profit_closed_coin), 8)
|
||||
profit_closed_percent = round(sum(profit_closed_percent) * 100, 2)
|
||||
profit_closed_fiat = fiat.convert_amount(
|
||||
profit_closed_coin,
|
||||
profit_closed_coin_sum = round(sum(profit_closed_coin), 8)
|
||||
profit_closed_percent = round(nan_to_num(mean(profit_closed_percent)) * 100, 2)
|
||||
profit_closed_fiat = self._fiat_converter.convert_amount(
|
||||
profit_closed_coin_sum,
|
||||
stake_currency,
|
||||
fiat_display_currency
|
||||
)
|
||||
profit_all_coin = round(sum(profit_all_coin), 8)
|
||||
profit_all_percent = round(sum(profit_all_percent) * 100, 2)
|
||||
profit_all_fiat = fiat.convert_amount(
|
||||
profit_all_coin,
|
||||
) if self._fiat_converter else 0
|
||||
|
||||
profit_all_coin_sum = round(sum(profit_all_coin), 8)
|
||||
profit_all_percent = round(nan_to_num(mean(profit_all_percent)) * 100, 2)
|
||||
profit_all_fiat = self._fiat_converter.convert_amount(
|
||||
profit_all_coin_sum,
|
||||
stake_currency,
|
||||
fiat_display_currency
|
||||
)
|
||||
) if self._fiat_converter else 0
|
||||
|
||||
num = float(len(durations) or 1)
|
||||
return (
|
||||
False,
|
||||
{
|
||||
'profit_closed_coin': profit_closed_coin,
|
||||
'profit_closed_percent': profit_closed_percent,
|
||||
'profit_closed_fiat': profit_closed_fiat,
|
||||
'profit_all_coin': profit_all_coin,
|
||||
'profit_all_percent': profit_all_percent,
|
||||
'profit_all_fiat': profit_all_fiat,
|
||||
'trade_count': len(trades),
|
||||
'first_trade_date': arrow.get(trades[0].open_date).humanize(),
|
||||
'latest_trade_date': arrow.get(trades[-1].open_date).humanize(),
|
||||
'avg_duration': str(timedelta(seconds=sum(durations) / num)).split('.')[0],
|
||||
'best_pair': bp_pair,
|
||||
'best_rate': round(bp_rate * 100, 2)
|
||||
}
|
||||
)
|
||||
|
||||
def rpc_balance(self, fiat_display_currency: str) -> Tuple[bool, Any]:
|
||||
"""
|
||||
:return: current account balance per crypto
|
||||
"""
|
||||
balances = [
|
||||
c for c in exchange.get_balances()
|
||||
if c['Balance'] or c['Available'] or c['Pending']
|
||||
]
|
||||
if not balances:
|
||||
return True, '`All balances are zero.`'
|
||||
return {
|
||||
'profit_closed_coin': profit_closed_coin_sum,
|
||||
'profit_closed_percent': profit_closed_percent,
|
||||
'profit_closed_fiat': profit_closed_fiat,
|
||||
'profit_all_coin': profit_all_coin_sum,
|
||||
'profit_all_percent': profit_all_percent,
|
||||
'profit_all_fiat': profit_all_fiat,
|
||||
'trade_count': len(trades),
|
||||
'first_trade_date': arrow.get(trades[0].open_date).humanize(),
|
||||
'latest_trade_date': arrow.get(trades[-1].open_date).humanize(),
|
||||
'avg_duration': str(timedelta(seconds=sum(durations) / num)).split('.')[0],
|
||||
'best_pair': bp_pair,
|
||||
'best_rate': round(bp_rate * 100, 2),
|
||||
}
|
||||
|
||||
def _rpc_balance(self, fiat_display_currency: str) -> Dict:
|
||||
""" Returns current account balance per crypto """
|
||||
output = []
|
||||
total = 0.0
|
||||
for currency in balances:
|
||||
coin = currency['Currency']
|
||||
for coin, balance in self._freqtrade.exchange.get_balances().items():
|
||||
if not balance['total']:
|
||||
continue
|
||||
|
||||
if coin == 'BTC':
|
||||
currency["Rate"] = 1.0
|
||||
rate = 1.0
|
||||
else:
|
||||
if coin == 'USDT':
|
||||
currency["Rate"] = 1.0 / exchange.get_ticker('USDT_BTC', False)['bid']
|
||||
else:
|
||||
currency["Rate"] = exchange.get_ticker('BTC_' + coin, False)['bid']
|
||||
currency['BTC'] = currency["Rate"] * currency["Balance"]
|
||||
total = total + currency['BTC']
|
||||
output.append(
|
||||
{
|
||||
'currency': currency['Currency'],
|
||||
'available': currency['Available'],
|
||||
'balance': currency['Balance'],
|
||||
'pending': currency['Pending'],
|
||||
'est_btc': currency['BTC']
|
||||
}
|
||||
)
|
||||
fiat = self.freqtrade.fiat_converter
|
||||
try:
|
||||
if coin == 'USDT':
|
||||
rate = 1.0 / self._freqtrade.exchange.get_ticker('BTC/USDT', False)['bid']
|
||||
else:
|
||||
rate = self._freqtrade.exchange.get_ticker(coin + '/BTC', False)['bid']
|
||||
except (TemporaryError, DependencyException):
|
||||
continue
|
||||
est_btc: float = rate * balance['total']
|
||||
total = total + est_btc
|
||||
output.append({
|
||||
'currency': coin,
|
||||
'available': balance['free'],
|
||||
'balance': balance['total'],
|
||||
'pending': balance['used'],
|
||||
'est_btc': est_btc,
|
||||
})
|
||||
if total == 0.0:
|
||||
raise RPCException('all balances are zero')
|
||||
|
||||
symbol = fiat_display_currency
|
||||
value = fiat.convert_amount(total, 'BTC', symbol)
|
||||
return False, (output, total, symbol, value)
|
||||
value = self._fiat_converter.convert_amount(total, 'BTC',
|
||||
symbol) if self._fiat_converter else 0
|
||||
return {
|
||||
'currencies': output,
|
||||
'total': total,
|
||||
'symbol': symbol,
|
||||
'value': value,
|
||||
}
|
||||
|
||||
def rpc_start(self) -> (bool, str):
|
||||
"""
|
||||
Handler for start.
|
||||
"""
|
||||
if self.freqtrade.state == State.RUNNING:
|
||||
return True, '*Status:* `already running`'
|
||||
def _rpc_start(self) -> Dict[str, str]:
|
||||
""" Handler for start """
|
||||
if self._freqtrade.state == State.RUNNING:
|
||||
return {'status': 'already running'}
|
||||
|
||||
self.freqtrade.state = State.RUNNING
|
||||
return False, '`Starting trader ...`'
|
||||
self._freqtrade.state = State.RUNNING
|
||||
return {'status': 'starting trader ...'}
|
||||
|
||||
def rpc_stop(self) -> (bool, str):
|
||||
"""
|
||||
Handler for stop.
|
||||
"""
|
||||
if self.freqtrade.state == State.RUNNING:
|
||||
self.freqtrade.state = State.STOPPED
|
||||
return False, '`Stopping trader ...`'
|
||||
def _rpc_stop(self) -> Dict[str, str]:
|
||||
""" Handler for stop """
|
||||
if self._freqtrade.state == State.RUNNING:
|
||||
self._freqtrade.state = State.STOPPED
|
||||
return {'status': 'stopping trader ...'}
|
||||
|
||||
return True, '*Status:* `already stopped`'
|
||||
return {'status': 'already stopped'}
|
||||
|
||||
# FIX: no test for this!!!!
|
||||
def rpc_forcesell(self, trade_id) -> Tuple[bool, Any]:
|
||||
def _rpc_reload_conf(self) -> Dict[str, str]:
|
||||
""" Handler for reload_conf. """
|
||||
self._freqtrade.state = State.RELOAD_CONF
|
||||
return {'status': 'reloading config ...'}
|
||||
|
||||
def _rpc_forcesell(self, trade_id) -> None:
|
||||
"""
|
||||
Handler for forcesell <id>.
|
||||
Sells the given trade at current price
|
||||
:return: error or None
|
||||
"""
|
||||
def _exec_forcesell(trade: Trade) -> None:
|
||||
# Check if there is there is an open order
|
||||
if trade.open_order_id:
|
||||
order = exchange.get_order(trade.open_order_id)
|
||||
order = self._freqtrade.exchange.get_order(trade.open_order_id, trade.pair)
|
||||
|
||||
# Cancel open LIMIT_BUY orders and close trade
|
||||
if order and not order['closed'] and order['type'] == 'LIMIT_BUY':
|
||||
exchange.cancel_order(trade.open_order_id)
|
||||
trade.close(order.get('rate') or trade.open_rate)
|
||||
# TODO: sell amount which has been bought already
|
||||
return
|
||||
if order and order['status'] == 'open' \
|
||||
and order['type'] == 'limit' \
|
||||
and order['side'] == 'buy':
|
||||
self._freqtrade.exchange.cancel_order(trade.open_order_id, trade.pair)
|
||||
trade.close(order.get('price') or trade.open_rate)
|
||||
# Do the best effort, if we don't know 'filled' amount, don't try selling
|
||||
if order['filled'] is None:
|
||||
return
|
||||
trade.amount = order['filled']
|
||||
|
||||
# Ignore trades with an attached LIMIT_SELL order
|
||||
if order and not order['closed'] and order['type'] == 'LIMIT_SELL':
|
||||
if order and order['status'] == 'open' \
|
||||
and order['type'] == 'limit' \
|
||||
and order['side'] == 'sell':
|
||||
return
|
||||
|
||||
# Get current rate and execute sell
|
||||
current_rate = exchange.get_ticker(trade.pair, False)['bid']
|
||||
self.freqtrade.execute_sell(trade, current_rate)
|
||||
current_rate = self._freqtrade.exchange.get_ticker(trade.pair, False)['bid']
|
||||
self._freqtrade.execute_sell(trade, current_rate, SellType.FORCE_SELL)
|
||||
# ---- EOF def _exec_forcesell ----
|
||||
|
||||
if self.freqtrade.state != State.RUNNING:
|
||||
return True, '`trader is not running`'
|
||||
if self._freqtrade.state != State.RUNNING:
|
||||
raise RPCException('trader is not running')
|
||||
|
||||
if trade_id == 'all':
|
||||
# Execute sell for all open orders
|
||||
for trade in Trade.query.filter(Trade.is_open.is_(True)).all():
|
||||
_exec_forcesell(trade)
|
||||
return False, ''
|
||||
Trade.session.flush()
|
||||
return
|
||||
|
||||
# Query for trade
|
||||
trade = Trade.query.filter(
|
||||
@@ -345,18 +380,50 @@ class RPC(object):
|
||||
).first()
|
||||
if not trade:
|
||||
logger.warning('forcesell: Invalid argument received')
|
||||
return True, 'Invalid argument.'
|
||||
raise RPCException('invalid argument')
|
||||
|
||||
_exec_forcesell(trade)
|
||||
return False, ''
|
||||
Trade.session.flush()
|
||||
|
||||
def rpc_performance(self) -> Tuple[bool, Any]:
|
||||
def _rpc_forcebuy(self, pair: str, price: Optional[float]) -> Optional[Trade]:
|
||||
"""
|
||||
Handler for forcebuy <asset> <price>
|
||||
Buys a pair trade at the given or current price
|
||||
"""
|
||||
|
||||
if not self._freqtrade.config.get('forcebuy_enable', False):
|
||||
raise RPCException('Forcebuy not enabled.')
|
||||
|
||||
if self._freqtrade.state != State.RUNNING:
|
||||
raise RPCException('trader is not running')
|
||||
|
||||
# Check pair is in stake currency
|
||||
stake_currency = self._freqtrade.config.get('stake_currency')
|
||||
if not pair.endswith(stake_currency):
|
||||
raise RPCException(
|
||||
f'Wrong pair selected. Please pairs with stake {stake_currency} pairs only')
|
||||
# check if valid pair
|
||||
|
||||
# check if pair already has an open pair
|
||||
trade = Trade.query.filter(Trade.is_open.is_(True)).filter(Trade.pair.is_(pair)).first()
|
||||
if trade:
|
||||
raise RPCException(f'position for {pair} already open - id: {trade.id}')
|
||||
|
||||
# gen stake amount
|
||||
stakeamount = self._freqtrade._get_trade_stake_amount(pair)
|
||||
|
||||
# execute buy
|
||||
if self._freqtrade.execute_buy(pair, stakeamount, price):
|
||||
trade = Trade.query.filter(Trade.is_open.is_(True)).filter(Trade.pair.is_(pair)).first()
|
||||
return trade
|
||||
else:
|
||||
return None
|
||||
|
||||
def _rpc_performance(self) -> List[Dict]:
|
||||
"""
|
||||
Handler for performance.
|
||||
Shows a performance statistic from finished trades
|
||||
"""
|
||||
if self.freqtrade.state != State.RUNNING:
|
||||
return True, '`trader is not running`'
|
||||
|
||||
pair_rates = Trade.session.query(Trade.pair,
|
||||
sql.func.sum(Trade.close_profit).label('profit_sum'),
|
||||
@@ -365,19 +432,22 @@ class RPC(object):
|
||||
.group_by(Trade.pair) \
|
||||
.order_by(sql.text('profit_sum DESC')) \
|
||||
.all()
|
||||
trades = []
|
||||
for (pair, rate, count) in pair_rates:
|
||||
trades.append({'pair': pair, 'profit': round(rate * 100, 2), 'count': count})
|
||||
return [
|
||||
{'pair': pair, 'profit': round(rate * 100, 2), 'count': count}
|
||||
for pair, rate, count in pair_rates
|
||||
]
|
||||
|
||||
return False, trades
|
||||
def _rpc_count(self) -> List[Trade]:
|
||||
""" Returns the number of trades running """
|
||||
if self._freqtrade.state != State.RUNNING:
|
||||
raise RPCException('trader is not running')
|
||||
|
||||
def rpc_count(self) -> Tuple[bool, Any]:
|
||||
"""
|
||||
Returns the number of trades running
|
||||
:return: None
|
||||
"""
|
||||
if self.freqtrade.state != State.RUNNING:
|
||||
return True, '`trader is not running`'
|
||||
return Trade.query.filter(Trade.is_open.is_(True)).all()
|
||||
|
||||
trades = Trade.query.filter(Trade.is_open.is_(True)).all()
|
||||
return False, trades
|
||||
def _rpc_whitelist(self) -> Dict:
|
||||
""" Returns the currently active whitelist"""
|
||||
res = {'method': self._freqtrade.pairlists.name,
|
||||
'length': len(self._freqtrade.pairlists.whitelist),
|
||||
'whitelist': self._freqtrade.active_pair_whitelist
|
||||
}
|
||||
return res
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
This module contains class to manage RPC communications (Telegram, Slack, ...)
|
||||
"""
|
||||
import logging
|
||||
from typing import List, Dict, Any
|
||||
|
||||
from freqtrade.rpc.telegram import Telegram
|
||||
|
||||
from freqtrade.rpc import RPC, RPCMessageType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -14,43 +14,66 @@ class RPCManager(object):
|
||||
Class to manage RPC objects (Telegram, Slack, ...)
|
||||
"""
|
||||
def __init__(self, freqtrade) -> None:
|
||||
"""
|
||||
Initializes all enabled rpc modules
|
||||
:param config: config to use
|
||||
:return: None
|
||||
"""
|
||||
self.freqtrade = freqtrade
|
||||
""" Initializes all enabled rpc modules """
|
||||
self.registered_modules: List[RPC] = []
|
||||
|
||||
self.registered_modules = []
|
||||
self.telegram = None
|
||||
self._init()
|
||||
|
||||
def _init(self) -> None:
|
||||
"""
|
||||
Init RPC modules
|
||||
:return:
|
||||
"""
|
||||
if self.freqtrade.config['telegram'].get('enabled', False):
|
||||
# Enable telegram
|
||||
if freqtrade.config['telegram'].get('enabled', False):
|
||||
logger.info('Enabling rpc.telegram ...')
|
||||
self.registered_modules.append('telegram')
|
||||
self.telegram = Telegram(self.freqtrade)
|
||||
from freqtrade.rpc.telegram import Telegram
|
||||
self.registered_modules.append(Telegram(freqtrade))
|
||||
|
||||
# Enable Webhook
|
||||
if freqtrade.config.get('webhook', {}).get('enabled', False):
|
||||
logger.info('Enabling rpc.webhook ...')
|
||||
from freqtrade.rpc.webhook import Webhook
|
||||
self.registered_modules.append(Webhook(freqtrade))
|
||||
|
||||
def cleanup(self) -> None:
|
||||
"""
|
||||
Stops all enabled rpc modules
|
||||
:return: None
|
||||
"""
|
||||
if 'telegram' in self.registered_modules:
|
||||
logger.info('Cleaning up rpc.telegram ...')
|
||||
self.registered_modules.remove('telegram')
|
||||
self.telegram.cleanup()
|
||||
""" Stops all enabled rpc modules """
|
||||
logger.info('Cleaning up rpc modules ...')
|
||||
while self.registered_modules:
|
||||
mod = self.registered_modules.pop()
|
||||
logger.debug('Cleaning up rpc.%s ...', mod.name)
|
||||
mod.cleanup()
|
||||
del mod
|
||||
|
||||
def send_msg(self, msg: str) -> None:
|
||||
def send_msg(self, msg: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Send given markdown message to all registered rpc modules
|
||||
:param msg: message
|
||||
:return: None
|
||||
Send given message to all registered rpc modules.
|
||||
A message consists of one or more key value pairs of strings.
|
||||
e.g.:
|
||||
{
|
||||
'status': 'stopping bot'
|
||||
}
|
||||
"""
|
||||
logger.info(msg)
|
||||
if 'telegram' in self.registered_modules:
|
||||
self.telegram.send_msg(msg)
|
||||
logger.info('Sending rpc message: %s', msg)
|
||||
for mod in self.registered_modules:
|
||||
logger.debug('Forwarding message to rpc.%s', mod.name)
|
||||
mod.send_msg(msg)
|
||||
|
||||
def startup_messages(self, config, pairlist) -> None:
|
||||
if config.get('dry_run', False):
|
||||
self.send_msg({
|
||||
'type': RPCMessageType.WARNING_NOTIFICATION,
|
||||
'status': 'Dry run is enabled. All trades are simulated.'
|
||||
})
|
||||
stake_currency = config['stake_currency']
|
||||
stake_amount = config['stake_amount']
|
||||
minimal_roi = config['minimal_roi']
|
||||
ticker_interval = config['ticker_interval']
|
||||
exchange_name = config['exchange']['name']
|
||||
strategy_name = config.get('strategy', '')
|
||||
self.send_msg({
|
||||
'type': RPCMessageType.CUSTOM_NOTIFICATION,
|
||||
'status': f'*Exchange:* `{exchange_name}`\n'
|
||||
f'*Stake per trade:* `{stake_amount} {stake_currency}`\n'
|
||||
f'*Minimum ROI:* `{minimal_roi}`\n'
|
||||
f'*Ticker Interval:* `{ticker_interval}`\n'
|
||||
f'*Strategy:* `{strategy_name}`'
|
||||
})
|
||||
self.send_msg({
|
||||
'type': RPCMessageType.STATUS_NOTIFICATION,
|
||||
'status': f'Searching for {stake_currency} pairs to buy and sell '
|
||||
f'based on {pairlist.short_desc()}'
|
||||
})
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
This module manage Telegram communication
|
||||
"""
|
||||
import logging
|
||||
from typing import Any, Callable
|
||||
from typing import Any, Callable, Dict
|
||||
|
||||
from tabulate import tabulate
|
||||
from telegram import Bot, ParseMode, ReplyKeyboardMarkup, Update
|
||||
@@ -12,22 +12,22 @@ from telegram.error import NetworkError, TelegramError
|
||||
from telegram.ext import CommandHandler, Updater
|
||||
|
||||
from freqtrade.__init__ import __version__
|
||||
from freqtrade.rpc.rpc import RPC
|
||||
|
||||
from freqtrade.rpc import RPC, RPCException, RPCMessageType
|
||||
from freqtrade.rpc.fiat_convert import CryptoToFiatConverter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
logger.debug('Included module rpc.telegram ...')
|
||||
|
||||
def authorized_only(command_handler: Callable[[Bot, Update], None]) -> Callable[..., Any]:
|
||||
|
||||
def authorized_only(command_handler: Callable[[Any, Bot, Update], None]) -> Callable[..., Any]:
|
||||
"""
|
||||
Decorator to check if the message comes from the correct chat_id
|
||||
:param command_handler: Telegram CommandHandler
|
||||
:return: decorated function
|
||||
"""
|
||||
def wrapper(self, *args, **kwargs):
|
||||
"""
|
||||
Decorator logic
|
||||
"""
|
||||
""" Decorator logic """
|
||||
update = kwargs.get('update') or args[1]
|
||||
|
||||
# Reject unauthorized messages
|
||||
@@ -54,9 +54,8 @@ def authorized_only(command_handler: Callable[[Bot, Update], None]) -> Callable[
|
||||
|
||||
|
||||
class Telegram(RPC):
|
||||
"""
|
||||
Telegram, this class send messages to Telegram
|
||||
"""
|
||||
""" This class handles all telegram communication """
|
||||
|
||||
def __init__(self, freqtrade) -> None:
|
||||
"""
|
||||
Init the Telegram call, and init the super class RPC
|
||||
@@ -65,21 +64,18 @@ class Telegram(RPC):
|
||||
"""
|
||||
super().__init__(freqtrade)
|
||||
|
||||
self._updater = None
|
||||
self._updater: Updater = None
|
||||
self._config = freqtrade.config
|
||||
self._init()
|
||||
if self._config.get('fiat_display_currency', None):
|
||||
self._fiat_converter = CryptoToFiatConverter()
|
||||
|
||||
def _init(self) -> None:
|
||||
"""
|
||||
Initializes this module with the given config,
|
||||
registers all known command handlers
|
||||
and starts polling for message updates
|
||||
:param config: config to use
|
||||
:return: None
|
||||
"""
|
||||
if not self.is_enabled():
|
||||
return
|
||||
|
||||
self._updater = Updater(token=self._config['telegram']['token'], workers=0)
|
||||
|
||||
# Register command handler and start telegram message polling
|
||||
@@ -90,9 +86,12 @@ class Telegram(RPC):
|
||||
CommandHandler('start', self._start),
|
||||
CommandHandler('stop', self._stop),
|
||||
CommandHandler('forcesell', self._forcesell),
|
||||
CommandHandler('forcebuy', self._forcebuy),
|
||||
CommandHandler('performance', self._performance),
|
||||
CommandHandler('daily', self._daily),
|
||||
CommandHandler('count', self._count),
|
||||
CommandHandler('reload_conf', self._reload_conf),
|
||||
CommandHandler('whitelist', self._whitelist),
|
||||
CommandHandler('help', self._help),
|
||||
CommandHandler('version', self._version),
|
||||
]
|
||||
@@ -114,16 +113,60 @@ class Telegram(RPC):
|
||||
Stops all running telegram threads.
|
||||
:return: None
|
||||
"""
|
||||
if not self.is_enabled():
|
||||
return
|
||||
|
||||
self._updater.stop()
|
||||
|
||||
def is_enabled(self) -> bool:
|
||||
"""
|
||||
Returns True if the telegram module is activated, False otherwise
|
||||
"""
|
||||
return bool(self._config.get('telegram', {}).get('enabled', False))
|
||||
def send_msg(self, msg: Dict[str, Any]) -> None:
|
||||
""" Send a message to telegram channel """
|
||||
|
||||
if msg['type'] == RPCMessageType.BUY_NOTIFICATION:
|
||||
if self._fiat_converter:
|
||||
msg['stake_amount_fiat'] = self._fiat_converter.convert_amount(
|
||||
msg['stake_amount'], msg['stake_currency'], msg['fiat_currency'])
|
||||
else:
|
||||
msg['stake_amount_fiat'] = 0
|
||||
|
||||
message = ("*{exchange}:* Buying [{pair}]({market_url})\n"
|
||||
"with limit `{limit:.8f}\n"
|
||||
"({stake_amount:.6f} {stake_currency}").format(**msg)
|
||||
|
||||
if msg.get('fiat_currency', None):
|
||||
message += ",{stake_amount_fiat:.3f} {fiat_currency}".format(**msg)
|
||||
message += ")`"
|
||||
|
||||
elif msg['type'] == RPCMessageType.SELL_NOTIFICATION:
|
||||
msg['amount'] = round(msg['amount'], 8)
|
||||
msg['profit_percent'] = round(msg['profit_percent'] * 100, 2)
|
||||
|
||||
message = ("*{exchange}:* Selling [{pair}]({market_url})\n"
|
||||
"*Limit:* `{limit:.8f}`\n"
|
||||
"*Amount:* `{amount:.8f}`\n"
|
||||
"*Open Rate:* `{open_rate:.8f}`\n"
|
||||
"*Current Rate:* `{current_rate:.8f}`\n"
|
||||
"*Sell Reason:* `{sell_reason}`\n"
|
||||
"*Profit:* `{profit_percent:.2f}%`").format(**msg)
|
||||
|
||||
# Check if all sell properties are available.
|
||||
# This might not be the case if the message origin is triggered by /forcesell
|
||||
if (all(prop in msg for prop in ['gain', 'fiat_currency', 'stake_currency'])
|
||||
and self._fiat_converter):
|
||||
msg['profit_fiat'] = self._fiat_converter.convert_amount(
|
||||
msg['profit_amount'], msg['stake_currency'], msg['fiat_currency'])
|
||||
message += ('` ({gain}: {profit_amount:.8f} {stake_currency}`'
|
||||
'` / {profit_fiat:.3f} {fiat_currency})`').format(**msg)
|
||||
|
||||
elif msg['type'] == RPCMessageType.STATUS_NOTIFICATION:
|
||||
message = '*Status:* `{status}`'.format(**msg)
|
||||
|
||||
elif msg['type'] == RPCMessageType.WARNING_NOTIFICATION:
|
||||
message = '*Warning:* `{status}`'.format(**msg)
|
||||
|
||||
elif msg['type'] == RPCMessageType.CUSTOM_NOTIFICATION:
|
||||
message = '{status}'.format(**msg)
|
||||
|
||||
else:
|
||||
raise NotImplementedError('Unknown message type: {}'.format(msg['type']))
|
||||
|
||||
self._send_msg(message)
|
||||
|
||||
@authorized_only
|
||||
def _status(self, bot: Bot, update: Update) -> None:
|
||||
@@ -142,13 +185,29 @@ class Telegram(RPC):
|
||||
self._status_table(bot, update)
|
||||
return
|
||||
|
||||
# Fetch open trade
|
||||
(error, trades) = self.rpc_trade_status()
|
||||
if error:
|
||||
self.send_msg(trades, bot=bot)
|
||||
else:
|
||||
for trademsg in trades:
|
||||
self.send_msg(trademsg, bot=bot)
|
||||
try:
|
||||
results = self._rpc_trade_status()
|
||||
# pre format data
|
||||
for result in results:
|
||||
result['date'] = result['date'].humanize()
|
||||
|
||||
messages = [
|
||||
"*Trade ID:* `{trade_id}`\n"
|
||||
"*Current Pair:* [{pair}]({market_url})\n"
|
||||
"*Open Since:* `{date}`\n"
|
||||
"*Amount:* `{amount}`\n"
|
||||
"*Open Rate:* `{open_rate:.8f}`\n"
|
||||
"*Close Rate:* `{close_rate}`\n"
|
||||
"*Current Rate:* `{current_rate:.8f}`\n"
|
||||
"*Close Profit:* `{close_profit}`\n"
|
||||
"*Current Profit:* `{current_profit:.2f}%`\n"
|
||||
"*Open Order:* `{open_order}`".format(**result)
|
||||
for result in results
|
||||
]
|
||||
for msg in messages:
|
||||
self._send_msg(msg, bot=bot)
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _status_table(self, bot: Bot, update: Update) -> None:
|
||||
@@ -159,15 +218,12 @@ class Telegram(RPC):
|
||||
:param update: message update
|
||||
:return: None
|
||||
"""
|
||||
# Fetch open trade
|
||||
(err, df_statuses) = self.rpc_status_table()
|
||||
if err:
|
||||
self.send_msg(df_statuses, bot=bot)
|
||||
else:
|
||||
try:
|
||||
df_statuses = self._rpc_status_table()
|
||||
message = tabulate(df_statuses, headers='keys', tablefmt='simple')
|
||||
message = "<pre>{}</pre>".format(message)
|
||||
|
||||
self.send_msg(message, parse_mode=ParseMode.HTML)
|
||||
self._send_msg(f"<pre>{message}</pre>", parse_mode=ParseMode.HTML)
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _daily(self, bot: Bot, update: Update) -> None:
|
||||
@@ -178,31 +234,29 @@ class Telegram(RPC):
|
||||
:param update: message update
|
||||
:return: None
|
||||
"""
|
||||
stake_cur = self._config['stake_currency']
|
||||
fiat_disp_cur = self._config.get('fiat_display_currency', '')
|
||||
try:
|
||||
timescale = int(update.message.text.replace('/daily', '').strip())
|
||||
except (TypeError, ValueError):
|
||||
timescale = 7
|
||||
(error, stats) = self.rpc_daily_profit(
|
||||
timescale,
|
||||
self._config['stake_currency'],
|
||||
self._config['fiat_display_currency']
|
||||
)
|
||||
if error:
|
||||
self.send_msg(stats, bot=bot)
|
||||
else:
|
||||
stats = tabulate(stats,
|
||||
headers=[
|
||||
'Day',
|
||||
'Profit {}'.format(self._config['stake_currency']),
|
||||
'Profit {}'.format(self._config['fiat_display_currency'])
|
||||
],
|
||||
tablefmt='simple')
|
||||
message = '<b>Daily Profit over the last {} days</b>:\n<pre>{}</pre>'\
|
||||
.format(
|
||||
timescale,
|
||||
stats
|
||||
)
|
||||
self.send_msg(message, bot=bot, parse_mode=ParseMode.HTML)
|
||||
try:
|
||||
stats = self._rpc_daily_profit(
|
||||
timescale,
|
||||
stake_cur,
|
||||
fiat_disp_cur
|
||||
)
|
||||
stats_tab = tabulate(stats,
|
||||
headers=[
|
||||
'Day',
|
||||
f'Profit {stake_cur}',
|
||||
f'Profit {fiat_disp_cur}'
|
||||
],
|
||||
tablefmt='simple')
|
||||
message = f'<b>Daily Profit over the last {timescale} days</b>:\n<pre>{stats_tab}</pre>'
|
||||
self._send_msg(message, bot=bot, parse_mode=ParseMode.HTML)
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _profit(self, bot: Bot, update: Update) -> None:
|
||||
@@ -213,69 +267,64 @@ class Telegram(RPC):
|
||||
:param update: message update
|
||||
:return: None
|
||||
"""
|
||||
(error, stats) = self.rpc_trade_statistics(
|
||||
self._config['stake_currency'],
|
||||
self._config['fiat_display_currency']
|
||||
)
|
||||
if error:
|
||||
self.send_msg(stats, bot=bot)
|
||||
return
|
||||
stake_cur = self._config['stake_currency']
|
||||
fiat_disp_cur = self._config.get('fiat_display_currency', '')
|
||||
|
||||
# Message to display
|
||||
markdown_msg = "*ROI:* Close trades\n" \
|
||||
"∙ `{profit_closed_coin:.8f} {coin} ({profit_closed_percent:.2f}%)`\n" \
|
||||
"∙ `{profit_closed_fiat:.3f} {fiat}`\n" \
|
||||
"*ROI:* All trades\n" \
|
||||
"∙ `{profit_all_coin:.8f} {coin} ({profit_all_percent:.2f}%)`\n" \
|
||||
"∙ `{profit_all_fiat:.3f} {fiat}`\n" \
|
||||
"*Total Trade Count:* `{trade_count}`\n" \
|
||||
"*First Trade opened:* `{first_trade_date}`\n" \
|
||||
"*Latest Trade opened:* `{latest_trade_date}`\n" \
|
||||
"*Avg. Duration:* `{avg_duration}`\n" \
|
||||
"*Best Performing:* `{best_pair}: {best_rate:.2f}%`"\
|
||||
.format(
|
||||
coin=self._config['stake_currency'],
|
||||
fiat=self._config['fiat_display_currency'],
|
||||
profit_closed_coin=stats['profit_closed_coin'],
|
||||
profit_closed_percent=stats['profit_closed_percent'],
|
||||
profit_closed_fiat=stats['profit_closed_fiat'],
|
||||
profit_all_coin=stats['profit_all_coin'],
|
||||
profit_all_percent=stats['profit_all_percent'],
|
||||
profit_all_fiat=stats['profit_all_fiat'],
|
||||
trade_count=stats['trade_count'],
|
||||
first_trade_date=stats['first_trade_date'],
|
||||
latest_trade_date=stats['latest_trade_date'],
|
||||
avg_duration=stats['avg_duration'],
|
||||
best_pair=stats['best_pair'],
|
||||
best_rate=stats['best_rate']
|
||||
)
|
||||
self.send_msg(markdown_msg, bot=bot)
|
||||
try:
|
||||
stats = self._rpc_trade_statistics(
|
||||
stake_cur,
|
||||
fiat_disp_cur)
|
||||
profit_closed_coin = stats['profit_closed_coin']
|
||||
profit_closed_percent = stats['profit_closed_percent']
|
||||
profit_closed_fiat = stats['profit_closed_fiat']
|
||||
profit_all_coin = stats['profit_all_coin']
|
||||
profit_all_percent = stats['profit_all_percent']
|
||||
profit_all_fiat = stats['profit_all_fiat']
|
||||
trade_count = stats['trade_count']
|
||||
first_trade_date = stats['first_trade_date']
|
||||
latest_trade_date = stats['latest_trade_date']
|
||||
avg_duration = stats['avg_duration']
|
||||
best_pair = stats['best_pair']
|
||||
best_rate = stats['best_rate']
|
||||
# Message to display
|
||||
markdown_msg = "*ROI:* Close trades\n" \
|
||||
f"∙ `{profit_closed_coin:.8f} {stake_cur} "\
|
||||
f"({profit_closed_percent:.2f}%)`\n" \
|
||||
f"∙ `{profit_closed_fiat:.3f} {fiat_disp_cur}`\n" \
|
||||
f"*ROI:* All trades\n" \
|
||||
f"∙ `{profit_all_coin:.8f} {stake_cur} ({profit_all_percent:.2f}%)`\n" \
|
||||
f"∙ `{profit_all_fiat:.3f} {fiat_disp_cur}`\n" \
|
||||
f"*Total Trade Count:* `{trade_count}`\n" \
|
||||
f"*First Trade opened:* `{first_trade_date}`\n" \
|
||||
f"*Latest Trade opened:* `{latest_trade_date}`\n" \
|
||||
f"*Avg. Duration:* `{avg_duration}`\n" \
|
||||
f"*Best Performing:* `{best_pair}: {best_rate:.2f}%`"
|
||||
self._send_msg(markdown_msg, bot=bot)
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _balance(self, bot: Bot, update: Update) -> None:
|
||||
"""
|
||||
Handler for /balance
|
||||
"""
|
||||
(error, result) = self.rpc_balance(self._config['fiat_display_currency'])
|
||||
if error:
|
||||
self.send_msg('`All balances are zero.`')
|
||||
return
|
||||
""" Handler for /balance """
|
||||
try:
|
||||
result = self._rpc_balance(self._config.get('fiat_display_currency', ''))
|
||||
output = ''
|
||||
for currency in result['currencies']:
|
||||
if currency['est_btc'] > 0.0001:
|
||||
output += "*{currency}:*\n" \
|
||||
"\t`Available: {available: .8f}`\n" \
|
||||
"\t`Balance: {balance: .8f}`\n" \
|
||||
"\t`Pending: {pending: .8f}`\n" \
|
||||
"\t`Est. BTC: {est_btc: .8f}`\n".format(**currency)
|
||||
else:
|
||||
output += "*{currency}:* not showing <1$ amount \n".format(**currency)
|
||||
|
||||
(currencys, total, symbol, value) = result
|
||||
output = ''
|
||||
for currency in currencys:
|
||||
output += """*Currency*: {currency}
|
||||
*Available*: {available}
|
||||
*Balance*: {balance}
|
||||
*Pending*: {pending}
|
||||
*Est. BTC*: {est_btc: .8f}
|
||||
""".format(**currency)
|
||||
|
||||
output += """*Estimated Value*:
|
||||
*BTC*: {0: .8f}
|
||||
*{1}*: {2: .2f}
|
||||
""".format(total, symbol, value)
|
||||
self.send_msg(output)
|
||||
output += "\n*Estimated Value*:\n" \
|
||||
"\t`BTC: {total: .8f}`\n" \
|
||||
"\t`{symbol}: {value: .2f}`\n".format(**result)
|
||||
self._send_msg(output, bot=bot)
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _start(self, bot: Bot, update: Update) -> None:
|
||||
@@ -286,9 +335,8 @@ class Telegram(RPC):
|
||||
:param update: message update
|
||||
:return: None
|
||||
"""
|
||||
(error, msg) = self.rpc_start()
|
||||
if error:
|
||||
self.send_msg(msg, bot=bot)
|
||||
msg = self._rpc_start()
|
||||
self._send_msg('Status: `{status}`'.format(**msg), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _stop(self, bot: Bot, update: Update) -> None:
|
||||
@@ -299,8 +347,20 @@ class Telegram(RPC):
|
||||
:param update: message update
|
||||
:return: None
|
||||
"""
|
||||
(error, msg) = self.rpc_stop()
|
||||
self.send_msg(msg, bot=bot)
|
||||
msg = self._rpc_stop()
|
||||
self._send_msg('Status: `{status}`'.format(**msg), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _reload_conf(self, bot: Bot, update: Update) -> None:
|
||||
"""
|
||||
Handler for /reload_conf.
|
||||
Triggers a config file reload
|
||||
:param bot: telegram bot
|
||||
:param update: message update
|
||||
:return: None
|
||||
"""
|
||||
msg = self._rpc_reload_conf()
|
||||
self._send_msg('Status: `{status}`'.format(**msg), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _forcesell(self, bot: Bot, update: Update) -> None:
|
||||
@@ -313,10 +373,28 @@ class Telegram(RPC):
|
||||
"""
|
||||
|
||||
trade_id = update.message.text.replace('/forcesell', '').strip()
|
||||
(error, message) = self.rpc_forcesell(trade_id)
|
||||
if error:
|
||||
self.send_msg(message, bot=bot)
|
||||
return
|
||||
try:
|
||||
self._rpc_forcesell(trade_id)
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _forcebuy(self, bot: Bot, update: Update) -> None:
|
||||
"""
|
||||
Handler for /forcebuy <asset> <price>.
|
||||
Buys a pair trade at the given or current price
|
||||
:param bot: telegram bot
|
||||
:param update: message update
|
||||
:return: None
|
||||
"""
|
||||
|
||||
message = update.message.text.replace('/forcebuy', '').strip().split()
|
||||
pair = message[0]
|
||||
price = float(message[1]) if len(message) > 1 else None
|
||||
try:
|
||||
self._rpc_forcebuy(pair, price)
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _performance(self, bot: Bot, update: Update) -> None:
|
||||
@@ -327,19 +405,18 @@ class Telegram(RPC):
|
||||
:param update: message update
|
||||
:return: None
|
||||
"""
|
||||
(error, trades) = self.rpc_performance()
|
||||
if error:
|
||||
self.send_msg(trades, bot=bot)
|
||||
return
|
||||
|
||||
stats = '\n'.join('{index}.\t<code>{pair}\t{profit:.2f}% ({count})</code>'.format(
|
||||
index=i + 1,
|
||||
pair=trade['pair'],
|
||||
profit=trade['profit'],
|
||||
count=trade['count']
|
||||
) for i, trade in enumerate(trades))
|
||||
message = '<b>Performance:</b>\n{}'.format(stats)
|
||||
self.send_msg(message, parse_mode=ParseMode.HTML)
|
||||
try:
|
||||
trades = self._rpc_performance()
|
||||
stats = '\n'.join('{index}.\t<code>{pair}\t{profit:.2f}% ({count})</code>'.format(
|
||||
index=i + 1,
|
||||
pair=trade['pair'],
|
||||
profit=trade['profit'],
|
||||
count=trade['count']
|
||||
) for i, trade in enumerate(trades))
|
||||
message = '<b>Performance:</b>\n{}'.format(stats)
|
||||
self._send_msg(message, parse_mode=ParseMode.HTML)
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _count(self, bot: Bot, update: Update) -> None:
|
||||
@@ -350,19 +427,35 @@ class Telegram(RPC):
|
||||
:param update: message update
|
||||
:return: None
|
||||
"""
|
||||
(error, trades) = self.rpc_count()
|
||||
if error:
|
||||
self.send_msg(trades, bot=bot)
|
||||
return
|
||||
try:
|
||||
trades = self._rpc_count()
|
||||
message = tabulate({
|
||||
'current': [len(trades)],
|
||||
'max': [self._config['max_open_trades']],
|
||||
'total stake': [sum((trade.open_rate * trade.amount) for trade in trades)]
|
||||
}, headers=['current', 'max', 'total stake'], tablefmt='simple')
|
||||
message = "<pre>{}</pre>".format(message)
|
||||
logger.debug(message)
|
||||
self._send_msg(message, parse_mode=ParseMode.HTML)
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
message = tabulate({
|
||||
'current': [len(trades)],
|
||||
'max': [self._config['max_open_trades']],
|
||||
'total stake': [sum((trade.open_rate * trade.amount) for trade in trades)]
|
||||
}, headers=['current', 'max', 'total stake'], tablefmt='simple')
|
||||
message = "<pre>{}</pre>".format(message)
|
||||
logger.debug(message)
|
||||
self.send_msg(message, parse_mode=ParseMode.HTML)
|
||||
@authorized_only
|
||||
def _whitelist(self, bot: Bot, update: Update) -> None:
|
||||
"""
|
||||
Handler for /whitelist
|
||||
Shows the currently active whitelist
|
||||
"""
|
||||
try:
|
||||
whitelist = self._rpc_whitelist()
|
||||
|
||||
message = f"Using whitelist `{whitelist['method']}` with {whitelist['length']} pairs\n"
|
||||
message += f"`{', '.join(whitelist['whitelist'])}`"
|
||||
|
||||
logger.debug(message)
|
||||
self._send_msg(message)
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _help(self, bot: Bot, update: Update) -> None:
|
||||
@@ -385,10 +478,12 @@ class Telegram(RPC):
|
||||
"*/count:* `Show number of trades running compared to allowed number of trades`" \
|
||||
"\n" \
|
||||
"*/balance:* `Show account balance per currency`\n" \
|
||||
"*/reload_conf:* `Reload configuration file` \n" \
|
||||
"*/whitelist:* `Show current whitelist` \n" \
|
||||
"*/help:* `This help message`\n" \
|
||||
"*/version:* `Show version`"
|
||||
|
||||
self.send_msg(message, bot=bot)
|
||||
self._send_msg(message, bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _version(self, bot: Bot, update: Update) -> None:
|
||||
@@ -399,10 +494,10 @@ class Telegram(RPC):
|
||||
:param update: message update
|
||||
:return: None
|
||||
"""
|
||||
self.send_msg('*Version:* `{}`'.format(__version__), bot=bot)
|
||||
self._send_msg('*Version:* `{}`'.format(__version__), bot=bot)
|
||||
|
||||
def send_msg(self, msg: str, bot: Bot = None,
|
||||
parse_mode: ParseMode = ParseMode.MARKDOWN) -> None:
|
||||
def _send_msg(self, msg: str, bot: Bot = None,
|
||||
parse_mode: ParseMode = ParseMode.MARKDOWN) -> None:
|
||||
"""
|
||||
Send given markdown message
|
||||
:param msg: message
|
||||
@@ -410,9 +505,6 @@ class Telegram(RPC):
|
||||
:param parse_mode: telegram parse mode
|
||||
:return: None
|
||||
"""
|
||||
if not self.is_enabled():
|
||||
return
|
||||
|
||||
bot = bot or self._updater.bot
|
||||
|
||||
keyboard = [['/daily', '/profit', '/balance'],
|
||||
|
||||
66
freqtrade/rpc/webhook.py
Normal file
66
freqtrade/rpc/webhook.py
Normal file
@@ -0,0 +1,66 @@
|
||||
"""
|
||||
This module manages webhook communication
|
||||
"""
|
||||
import logging
|
||||
from typing import Any, Dict
|
||||
|
||||
from requests import post, RequestException
|
||||
|
||||
from freqtrade.rpc import RPC, RPCMessageType
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
logger.debug('Included module rpc.webhook ...')
|
||||
|
||||
|
||||
class Webhook(RPC):
|
||||
""" This class handles all webhook communication """
|
||||
|
||||
def __init__(self, freqtrade) -> None:
|
||||
"""
|
||||
Init the Webhook class, and init the super class RPC
|
||||
:param freqtrade: Instance of a freqtrade bot
|
||||
:return: None
|
||||
"""
|
||||
super().__init__(freqtrade)
|
||||
|
||||
self._config = freqtrade.config
|
||||
self._url = self._config['webhook']['url']
|
||||
|
||||
def cleanup(self) -> None:
|
||||
"""
|
||||
Cleanup pending module resources.
|
||||
This will do nothing for webhooks, they will simply not be called anymore
|
||||
"""
|
||||
pass
|
||||
|
||||
def send_msg(self, msg: Dict[str, Any]) -> None:
|
||||
""" Send a message to telegram channel """
|
||||
try:
|
||||
|
||||
if msg['type'] == RPCMessageType.BUY_NOTIFICATION:
|
||||
valuedict = self._config['webhook'].get('webhookbuy', None)
|
||||
elif msg['type'] == RPCMessageType.SELL_NOTIFICATION:
|
||||
valuedict = self._config['webhook'].get('webhooksell', None)
|
||||
elif msg['type'] == RPCMessageType.STATUS_NOTIFICATION:
|
||||
valuedict = self._config['webhook'].get('webhookstatus', None)
|
||||
else:
|
||||
raise NotImplementedError('Unknown message type: {}'.format(msg['type']))
|
||||
if not valuedict:
|
||||
logger.info("Message type %s not configured for webhooks", msg['type'])
|
||||
return
|
||||
|
||||
payload = {key: value.format(**msg) for (key, value) in valuedict.items()}
|
||||
self._send_msg(payload)
|
||||
except KeyError as exc:
|
||||
logger.exception("Problem calling Webhook. Please check your webhook configuration. "
|
||||
"Exception: %s", exc)
|
||||
|
||||
def _send_msg(self, payload: dict) -> None:
|
||||
"""do the actual call to the webhook"""
|
||||
|
||||
try:
|
||||
post(self._url, data=payload)
|
||||
except RequestException as exc:
|
||||
logger.warning("Could not call webhook url. Exception: %s", exc)
|
||||
@@ -3,12 +3,26 @@
|
||||
"""
|
||||
Bot state constant
|
||||
"""
|
||||
import enum
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class State(enum.Enum):
|
||||
class State(Enum):
|
||||
"""
|
||||
Bot running states
|
||||
Bot application states
|
||||
"""
|
||||
RUNNING = 0
|
||||
STOPPED = 1
|
||||
RUNNING = 1
|
||||
STOPPED = 2
|
||||
RELOAD_CONF = 3
|
||||
|
||||
|
||||
class RunMode(Enum):
|
||||
"""
|
||||
Bot running mode (backtest, hyperopt, ...)
|
||||
can be "live", "dry-run", "backtest", "edgecli", "hyperopt".
|
||||
"""
|
||||
LIVE = "live"
|
||||
DRY_RUN = "dry_run"
|
||||
BACKTEST = "backtest"
|
||||
EDGECLI = "edgecli"
|
||||
HYPEROPT = "hyperopt"
|
||||
OTHER = "other" # Used for plotting scripts and test
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import logging
|
||||
import sys
|
||||
from copy import deepcopy
|
||||
|
||||
from freqtrade.strategy.interface import IStrategy
|
||||
# Import Default-Strategy to have hyperopt correctly resolve
|
||||
from freqtrade.strategy.default_strategy import DefaultStrategy # noqa: F401
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def import_strategy(strategy: IStrategy, config: dict) -> IStrategy:
|
||||
"""
|
||||
Imports given Strategy instance to global scope
|
||||
of freqtrade.strategy and returns an instance of it
|
||||
"""
|
||||
|
||||
# Copy all attributes from base class and class
|
||||
|
||||
comb = {**strategy.__class__.__dict__, **strategy.__dict__}
|
||||
|
||||
# Delete '_abc_impl' from dict as deepcopy fails on 3.7 with
|
||||
# `TypeError: can't pickle _abc_data objects``
|
||||
# This will only apply to python 3.7
|
||||
if sys.version_info.major == 3 and sys.version_info.minor == 7 and '_abc_impl' in comb:
|
||||
del comb['_abc_impl']
|
||||
|
||||
attr = deepcopy(comb)
|
||||
# Adjust module name
|
||||
attr['__module__'] = 'freqtrade.strategy'
|
||||
|
||||
name = strategy.__class__.__name__
|
||||
clazz = type(name, (IStrategy,), attr)
|
||||
|
||||
logger.debug(
|
||||
'Imported strategy %s.%s as %s.%s',
|
||||
strategy.__module__, strategy.__class__.__name__,
|
||||
clazz.__module__, strategy.__class__.__name__,
|
||||
)
|
||||
|
||||
# Modify global scope to declare class
|
||||
globals()[name] = clazz
|
||||
|
||||
return clazz(config)
|
||||
|
||||
@@ -16,25 +16,55 @@ class DefaultStrategy(IStrategy):
|
||||
|
||||
# Minimal ROI designed for the strategy
|
||||
minimal_roi = {
|
||||
"40": 0.0,
|
||||
"30": 0.01,
|
||||
"20": 0.02,
|
||||
"0": 0.04
|
||||
"40": 0.0,
|
||||
"30": 0.01,
|
||||
"20": 0.02,
|
||||
"0": 0.04
|
||||
}
|
||||
|
||||
# Optimal stoploss designed for the strategy
|
||||
stoploss = -0.10
|
||||
|
||||
# Optimal ticker interval for the strategy
|
||||
ticker_interval = 5
|
||||
ticker_interval = '5m'
|
||||
|
||||
def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
|
||||
# Optional order type mapping
|
||||
order_types = {
|
||||
'buy': 'limit',
|
||||
'sell': 'limit',
|
||||
'stoploss': 'limit',
|
||||
'stoploss_on_exchange': False
|
||||
}
|
||||
|
||||
# Optional time in force for orders
|
||||
order_time_in_force = {
|
||||
'buy': 'gtc',
|
||||
'sell': 'gtc',
|
||||
}
|
||||
|
||||
def informative_pairs(self):
|
||||
"""
|
||||
Define additional, informative pair/interval combinations to be cached from the exchange.
|
||||
These pair/interval combinations are non-tradeable, unless they are part
|
||||
of the whitelist as well.
|
||||
For more information, please consult the documentation
|
||||
:return: List of tuples in the format (pair, interval)
|
||||
Sample: return [("ETH/USDT", "5m"),
|
||||
("BTC/USDT", "15m"),
|
||||
]
|
||||
"""
|
||||
return []
|
||||
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Adds several different TA indicators to the given DataFrame
|
||||
|
||||
Performance Note: For the best performance be frugal on the number of indicators
|
||||
you are using. Let uncomment only the indicator you are using in your strategies
|
||||
or your hyperopt configuration, otherwise you will waste your memory and CPU usage.
|
||||
:param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe()
|
||||
:param metadata: Additional information, like the currently traded pair
|
||||
:return: a Dataframe with all mandatory indicators for the strategies
|
||||
"""
|
||||
|
||||
# Momentum Indicator
|
||||
@@ -196,10 +226,11 @@ class DefaultStrategy(IStrategy):
|
||||
|
||||
return dataframe
|
||||
|
||||
def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:
|
||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the buy signal for the given dataframe
|
||||
:param dataframe: DataFrame
|
||||
:param metadata: Additional information, like the currently traded pair
|
||||
:return: DataFrame with buy column
|
||||
"""
|
||||
dataframe.loc[
|
||||
@@ -217,10 +248,11 @@ class DefaultStrategy(IStrategy):
|
||||
|
||||
return dataframe
|
||||
|
||||
def populate_sell_trend(self, dataframe: DataFrame) -> DataFrame:
|
||||
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the sell signal for the given dataframe
|
||||
:param dataframe: DataFrame
|
||||
:param metadata: Additional information, like the currently traded pair
|
||||
:return: DataFrame with buy column
|
||||
"""
|
||||
dataframe.loc[
|
||||
|
||||
@@ -2,11 +2,52 @@
|
||||
IStrategy interface
|
||||
This module defines the interface to apply for strategies
|
||||
"""
|
||||
|
||||
import logging
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
from typing import Dict, List, NamedTuple, Tuple
|
||||
import warnings
|
||||
|
||||
import arrow
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade import constants
|
||||
from freqtrade.data.dataprovider import DataProvider
|
||||
from freqtrade.persistence import Trade
|
||||
from freqtrade.wallets import Wallets
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SignalType(Enum):
|
||||
"""
|
||||
Enum to distinguish between buy and sell signals
|
||||
"""
|
||||
BUY = "buy"
|
||||
SELL = "sell"
|
||||
|
||||
|
||||
class SellType(Enum):
|
||||
"""
|
||||
Enum to distinguish between sell reasons
|
||||
"""
|
||||
ROI = "roi"
|
||||
STOP_LOSS = "stop_loss"
|
||||
STOPLOSS_ON_EXCHANGE = "stoploss_on_exchange"
|
||||
TRAILING_STOP_LOSS = "trailing_stop_loss"
|
||||
SELL_SIGNAL = "sell_signal"
|
||||
FORCE_SELL = "force_sell"
|
||||
NONE = ""
|
||||
|
||||
|
||||
class SellCheckTuple(NamedTuple):
|
||||
"""
|
||||
NamedTuple for Sell type + reason
|
||||
"""
|
||||
sell_flag: bool
|
||||
sell_type: SellType
|
||||
|
||||
|
||||
class IStrategy(ABC):
|
||||
"""
|
||||
@@ -16,29 +57,350 @@ class IStrategy(ABC):
|
||||
Attributes you can use:
|
||||
minimal_roi -> Dict: Minimal ROI designed for the strategy
|
||||
stoploss -> float: optimal stoploss designed for the strategy
|
||||
ticker_interval -> int: value of the ticker interval to use for the strategy
|
||||
ticker_interval -> str: value of the ticker interval to use for the strategy
|
||||
"""
|
||||
|
||||
_populate_fun_len: int = 0
|
||||
_buy_fun_len: int = 0
|
||||
_sell_fun_len: int = 0
|
||||
# associated minimal roi
|
||||
minimal_roi: Dict
|
||||
|
||||
# associated stoploss
|
||||
stoploss: float
|
||||
|
||||
# trailing stoploss
|
||||
trailing_stop: bool = False
|
||||
trailing_stop_positive: float
|
||||
trailing_stop_positive_offset: float
|
||||
|
||||
# associated ticker interval
|
||||
ticker_interval: str
|
||||
|
||||
# Optional order types
|
||||
order_types: Dict = {
|
||||
'buy': 'limit',
|
||||
'sell': 'limit',
|
||||
'stoploss': 'limit',
|
||||
'stoploss_on_exchange': False,
|
||||
'stoploss_on_exchange_interval': 60,
|
||||
}
|
||||
|
||||
# Optional time in force
|
||||
order_time_in_force: Dict = {
|
||||
'buy': 'gtc',
|
||||
'sell': 'gtc',
|
||||
}
|
||||
|
||||
# run "populate_indicators" only for new candle
|
||||
process_only_new_candles: bool = False
|
||||
|
||||
# Class level variables (intentional) containing
|
||||
# the dataprovider (dp) (access to other candles, historic data, ...)
|
||||
# and wallets - access to the current balance.
|
||||
dp: DataProvider
|
||||
wallets: Wallets
|
||||
|
||||
def __init__(self, config: dict) -> None:
|
||||
self.config = config
|
||||
# Dict to determine if analysis is necessary
|
||||
self._last_candle_seen_per_pair: Dict[str, datetime] = {}
|
||||
|
||||
@abstractmethod
|
||||
def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
|
||||
def populate_indicators(self, 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()
|
||||
:param metadata: Additional information, like the currently traded pair
|
||||
:return: a Dataframe with all mandatory indicators for the strategies
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:
|
||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the buy signal for the given dataframe
|
||||
:param dataframe: DataFrame
|
||||
:param metadata: Additional information, like the currently traded pair
|
||||
:return: DataFrame with buy column
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def populate_sell_trend(self, dataframe: DataFrame) -> DataFrame:
|
||||
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the sell signal for the given dataframe
|
||||
:param dataframe: DataFrame
|
||||
:param metadata: Additional information, like the currently traded pair
|
||||
:return: DataFrame with sell column
|
||||
"""
|
||||
|
||||
def informative_pairs(self) -> List[Tuple[str, str]]:
|
||||
"""
|
||||
Define additional, informative pair/interval combinations to be cached from the exchange.
|
||||
These pair/interval combinations are non-tradeable, unless they are part
|
||||
of the whitelist as well.
|
||||
For more information, please consult the documentation
|
||||
:return: List of tuples in the format (pair, interval)
|
||||
Sample: return [("ETH/USDT", "5m"),
|
||||
("BTC/USDT", "15m"),
|
||||
]
|
||||
"""
|
||||
return []
|
||||
|
||||
def get_strategy_name(self) -> str:
|
||||
"""
|
||||
Returns strategy class name
|
||||
"""
|
||||
return self.__class__.__name__
|
||||
|
||||
def analyze_ticker(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Parses the given ticker history and returns a populated DataFrame
|
||||
add several TA indicators and buy signal to it
|
||||
:return DataFrame with ticker data and indicator data
|
||||
"""
|
||||
|
||||
pair = str(metadata.get('pair'))
|
||||
|
||||
# Test if seen this pair and last candle before.
|
||||
# always run if process_only_new_candles is set to false
|
||||
if (not self.process_only_new_candles or
|
||||
self._last_candle_seen_per_pair.get(pair, None) != dataframe.iloc[-1]['date']):
|
||||
# Defs that only make change on new candle data.
|
||||
logger.debug("TA Analysis Launched")
|
||||
dataframe = self.advise_indicators(dataframe, metadata)
|
||||
dataframe = self.advise_buy(dataframe, metadata)
|
||||
dataframe = self.advise_sell(dataframe, metadata)
|
||||
self._last_candle_seen_per_pair[pair] = dataframe.iloc[-1]['date']
|
||||
else:
|
||||
logger.debug("Skipping TA Analysis for already analyzed candle")
|
||||
dataframe['buy'] = 0
|
||||
dataframe['sell'] = 0
|
||||
|
||||
# Other Defs in strategy that want to be called every loop here
|
||||
# twitter_sell = self.watch_twitter_feed(dataframe, metadata)
|
||||
logger.debug("Loop Analysis Launched")
|
||||
|
||||
return dataframe
|
||||
|
||||
def get_signal(self, pair: str, interval: str,
|
||||
dataframe: DataFrame) -> Tuple[bool, bool]:
|
||||
"""
|
||||
Calculates current signal based several technical analysis indicators
|
||||
:param pair: pair in format ANT/BTC
|
||||
:param interval: Interval to use (in min)
|
||||
:param dataframe: Dataframe to analyze
|
||||
:return: (Buy, Sell) A bool-tuple indicating buy/sell signal
|
||||
"""
|
||||
if not isinstance(dataframe, DataFrame) or dataframe.empty:
|
||||
logger.warning('Empty ticker history for pair %s', pair)
|
||||
return False, False
|
||||
|
||||
try:
|
||||
dataframe = self.analyze_ticker(dataframe, {'pair': pair})
|
||||
except ValueError as error:
|
||||
logger.warning(
|
||||
'Unable to analyze ticker for pair %s: %s',
|
||||
pair,
|
||||
str(error)
|
||||
)
|
||||
return False, False
|
||||
except Exception as error:
|
||||
logger.exception(
|
||||
'Unexpected error when analyzing ticker for pair %s: %s',
|
||||
pair,
|
||||
str(error)
|
||||
)
|
||||
return False, False
|
||||
|
||||
if dataframe.empty:
|
||||
logger.warning('Empty dataframe for pair %s', pair)
|
||||
return False, False
|
||||
|
||||
latest = dataframe.iloc[-1]
|
||||
|
||||
# Check if dataframe is out of date
|
||||
signal_date = arrow.get(latest['date'])
|
||||
interval_minutes = constants.TICKER_INTERVAL_MINUTES[interval]
|
||||
offset = self.config.get('exchange', {}).get('outdated_offset', 5)
|
||||
if signal_date < (arrow.utcnow().shift(minutes=-(interval_minutes * 2 + offset))):
|
||||
logger.warning(
|
||||
'Outdated history for pair %s. Last tick is %s minutes old',
|
||||
pair,
|
||||
(arrow.utcnow() - signal_date).seconds // 60
|
||||
)
|
||||
return False, False
|
||||
|
||||
(buy, sell) = latest[SignalType.BUY.value] == 1, latest[SignalType.SELL.value] == 1
|
||||
logger.debug(
|
||||
'trigger: %s (pair=%s) buy=%s sell=%s',
|
||||
latest['date'],
|
||||
pair,
|
||||
str(buy),
|
||||
str(sell)
|
||||
)
|
||||
return buy, sell
|
||||
|
||||
def should_sell(self, trade: Trade, rate: float, date: datetime, buy: bool,
|
||||
sell: bool, low: float = None, high: float = None,
|
||||
force_stoploss: float = 0) -> SellCheckTuple:
|
||||
"""
|
||||
This function evaluate if on the condition required to trigger a sell has been reached
|
||||
if the threshold is reached and updates the trade record.
|
||||
:return: True if trade should be sold, False otherwise
|
||||
"""
|
||||
|
||||
# Set current rate to low for backtesting sell
|
||||
current_rate = low or rate
|
||||
current_profit = trade.calc_profit_percent(current_rate)
|
||||
|
||||
stoplossflag = self.stop_loss_reached(current_rate=current_rate, trade=trade,
|
||||
current_time=date, current_profit=current_profit,
|
||||
force_stoploss=force_stoploss)
|
||||
|
||||
if stoplossflag.sell_flag:
|
||||
return stoplossflag
|
||||
|
||||
# Set current rate to low for backtesting sell
|
||||
current_rate = high or rate
|
||||
current_profit = trade.calc_profit_percent(current_rate)
|
||||
experimental = self.config.get('experimental', {})
|
||||
|
||||
if buy and experimental.get('ignore_roi_if_buy_signal', False):
|
||||
logger.debug('Buy signal still active - not selling.')
|
||||
return SellCheckTuple(sell_flag=False, sell_type=SellType.NONE)
|
||||
|
||||
# Check if minimal roi has been reached and no longer in buy conditions (avoiding a fee)
|
||||
if self.min_roi_reached(trade=trade, current_profit=current_profit, current_time=date):
|
||||
logger.debug('Required profit reached. Selling..')
|
||||
return SellCheckTuple(sell_flag=True, sell_type=SellType.ROI)
|
||||
|
||||
if experimental.get('sell_profit_only', False):
|
||||
logger.debug('Checking if trade is profitable..')
|
||||
if trade.calc_profit(rate=rate) <= 0:
|
||||
return SellCheckTuple(sell_flag=False, sell_type=SellType.NONE)
|
||||
if sell and not buy and experimental.get('use_sell_signal', False):
|
||||
logger.debug('Sell signal received. Selling..')
|
||||
return SellCheckTuple(sell_flag=True, sell_type=SellType.SELL_SIGNAL)
|
||||
|
||||
return SellCheckTuple(sell_flag=False, sell_type=SellType.NONE)
|
||||
|
||||
def stop_loss_reached(self, current_rate: float, trade: Trade, current_time: datetime,
|
||||
current_profit: float, force_stoploss: float) -> SellCheckTuple:
|
||||
"""
|
||||
Based on current profit of the trade and configured (trailing) stoploss,
|
||||
decides to sell or not
|
||||
:param current_profit: current profit in percent
|
||||
"""
|
||||
|
||||
trailing_stop = self.config.get('trailing_stop', False)
|
||||
trade.adjust_stop_loss(trade.open_rate, force_stoploss if force_stoploss
|
||||
else self.stoploss, initial=True)
|
||||
|
||||
# evaluate if the stoploss was hit if stoploss is not on exchange
|
||||
if ((self.stoploss is not None) and
|
||||
(trade.stop_loss >= current_rate) and
|
||||
(not self.order_types.get('stoploss_on_exchange'))):
|
||||
selltype = SellType.STOP_LOSS
|
||||
# If Trailing stop (and max-rate did move above open rate)
|
||||
if trailing_stop and trade.open_rate != trade.max_rate:
|
||||
selltype = SellType.TRAILING_STOP_LOSS
|
||||
logger.debug(
|
||||
f"HIT STOP: current price at {current_rate:.6f}, "
|
||||
f"stop loss is {trade.stop_loss:.6f}, "
|
||||
f"initial stop loss was at {trade.initial_stop_loss:.6f}, "
|
||||
f"trade opened at {trade.open_rate:.6f}")
|
||||
logger.debug(f"trailing stop saved {trade.stop_loss - trade.initial_stop_loss:.6f}")
|
||||
|
||||
logger.debug('Stop loss hit.')
|
||||
return SellCheckTuple(sell_flag=True, sell_type=selltype)
|
||||
|
||||
# update the stop loss afterwards, after all by definition it's supposed to be hanging
|
||||
if trailing_stop:
|
||||
|
||||
# check if we have a special stop loss for positive condition
|
||||
# and if profit is positive
|
||||
stop_loss_value = force_stoploss if force_stoploss else self.stoploss
|
||||
|
||||
sl_offset = self.config.get('trailing_stop_positive_offset') or 0.0
|
||||
|
||||
if 'trailing_stop_positive' in self.config and current_profit > sl_offset:
|
||||
|
||||
# Ignore mypy error check in configuration that this is a float
|
||||
stop_loss_value = self.config.get('trailing_stop_positive') # type: ignore
|
||||
logger.debug(f"using positive stop loss mode: {stop_loss_value} "
|
||||
f"with offset {sl_offset:.4g} "
|
||||
f"since we have profit {current_profit:.4f}%")
|
||||
|
||||
trade.adjust_stop_loss(current_rate, stop_loss_value)
|
||||
|
||||
return SellCheckTuple(sell_flag=False, sell_type=SellType.NONE)
|
||||
|
||||
def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool:
|
||||
"""
|
||||
Based an earlier trade and current price and ROI configuration, decides whether bot should
|
||||
sell. Requires current_profit to be in percent!!
|
||||
:return True if bot should sell at current rate
|
||||
"""
|
||||
|
||||
# Check if time matches and current rate is above threshold
|
||||
trade_dur = (current_time.timestamp() - trade.open_date.timestamp()) / 60
|
||||
|
||||
# Get highest entry in ROI dict where key >= trade-duration
|
||||
roi_entry = max(list(filter(lambda x: trade_dur >= x, self.minimal_roi.keys())))
|
||||
threshold = self.minimal_roi[roi_entry]
|
||||
if current_profit > threshold:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def tickerdata_to_dataframe(self, tickerdata: Dict[str, List]) -> Dict[str, DataFrame]:
|
||||
"""
|
||||
Creates a dataframe and populates indicators for given ticker data
|
||||
"""
|
||||
return {pair: self.advise_indicators(pair_data, {'pair': pair})
|
||||
for pair, pair_data in tickerdata.items()}
|
||||
|
||||
def advise_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Populate indicators that will be used in the Buy and Sell strategy
|
||||
This method should not be overridden.
|
||||
:param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe()
|
||||
:param metadata: Additional information, like the currently traded pair
|
||||
:return: a Dataframe with all mandatory indicators for the strategies
|
||||
"""
|
||||
if self._populate_fun_len == 2:
|
||||
warnings.warn("deprecated - check out the Sample strategy to see "
|
||||
"the current function headers!", DeprecationWarning)
|
||||
return self.populate_indicators(dataframe) # type: ignore
|
||||
else:
|
||||
return self.populate_indicators(dataframe, metadata)
|
||||
|
||||
def advise_buy(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the buy signal for the given dataframe
|
||||
This method should not be overridden.
|
||||
:param dataframe: DataFrame
|
||||
:param pair: Additional information, like the currently traded pair
|
||||
:return: DataFrame with buy column
|
||||
"""
|
||||
if self._buy_fun_len == 2:
|
||||
warnings.warn("deprecated - check out the Sample strategy to see "
|
||||
"the current function headers!", DeprecationWarning)
|
||||
return self.populate_buy_trend(dataframe) # type: ignore
|
||||
else:
|
||||
return self.populate_buy_trend(dataframe, metadata)
|
||||
|
||||
def advise_sell(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the sell signal for the given dataframe
|
||||
This method should not be overridden.
|
||||
:param dataframe: DataFrame
|
||||
:param pair: Additional information, like the currently traded pair
|
||||
:return: DataFrame with sell column
|
||||
"""
|
||||
if self._sell_fun_len == 2:
|
||||
warnings.warn("deprecated - check out the Sample strategy to see "
|
||||
"the current function headers!", DeprecationWarning)
|
||||
return self.populate_sell_trend(dataframe) # type: ignore
|
||||
else:
|
||||
return self.populate_sell_trend(dataframe, metadata)
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
# pragma pylint: disable=attribute-defined-outside-init
|
||||
|
||||
"""
|
||||
This module load custom strategies
|
||||
"""
|
||||
import importlib.util
|
||||
import inspect
|
||||
import logging
|
||||
import os
|
||||
from collections import OrderedDict
|
||||
from typing import Optional, Dict, Type
|
||||
|
||||
from freqtrade import constants
|
||||
from freqtrade.strategy.interface import IStrategy
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class StrategyResolver(object):
|
||||
"""
|
||||
This class contains all the logic to load custom strategy class
|
||||
"""
|
||||
|
||||
__slots__ = ['strategy']
|
||||
|
||||
def __init__(self, config: Optional[Dict] = None) -> None:
|
||||
"""
|
||||
Load the custom class from config parameter
|
||||
:param config: configuration dictionary or None
|
||||
"""
|
||||
config = config or {}
|
||||
|
||||
# Verify the strategy is in the configuration, otherwise fallback to the default strategy
|
||||
strategy_name = config.get('strategy') or constants.DEFAULT_STRATEGY
|
||||
self.strategy = self._load_strategy(strategy_name, extra_dir=config.get('strategy_path'))
|
||||
|
||||
# Set attributes
|
||||
# Check if we need to override configuration
|
||||
if 'minimal_roi' in config:
|
||||
self.strategy.minimal_roi = config['minimal_roi']
|
||||
logger.info("Override strategy \'minimal_roi\' with value in config file.")
|
||||
|
||||
if 'stoploss' in config:
|
||||
self.strategy.stoploss = config['stoploss']
|
||||
logger.info(
|
||||
"Override strategy \'stoploss\' with value in config file: %s.", config['stoploss']
|
||||
)
|
||||
|
||||
if 'ticker_interval' in config:
|
||||
self.strategy.ticker_interval = config['ticker_interval']
|
||||
logger.info(
|
||||
"Override strategy \'ticker_interval\' with value in config file: %s.",
|
||||
config['ticker_interval']
|
||||
)
|
||||
|
||||
# Sort and apply type conversions
|
||||
self.strategy.minimal_roi = OrderedDict(sorted(
|
||||
{int(key): value for (key, value) in self.strategy.minimal_roi.items()}.items(),
|
||||
key=lambda t: t[0]))
|
||||
self.strategy.stoploss = float(self.strategy.stoploss)
|
||||
self.strategy.ticker_interval = int(self.strategy.ticker_interval)
|
||||
|
||||
def _load_strategy(
|
||||
self, strategy_name: str, extra_dir: Optional[str] = None) -> Optional[IStrategy]:
|
||||
"""
|
||||
Search and loads the specified strategy.
|
||||
:param strategy_name: name of the module to import
|
||||
:param extra_dir: additional directory to search for the given strategy
|
||||
:return: Strategy instance or None
|
||||
"""
|
||||
current_path = os.path.dirname(os.path.realpath(__file__))
|
||||
abs_paths = [
|
||||
os.path.join(current_path, '..', '..', 'user_data', 'strategies'),
|
||||
current_path,
|
||||
]
|
||||
|
||||
if extra_dir:
|
||||
# Add extra strategy directory on top of search paths
|
||||
abs_paths.insert(0, extra_dir)
|
||||
|
||||
for path in abs_paths:
|
||||
strategy = self._search_strategy(path, strategy_name)
|
||||
if strategy:
|
||||
logger.info('Using resolved strategy %s from \'%s\'', strategy_name, path)
|
||||
return strategy
|
||||
|
||||
raise ImportError(
|
||||
"Impossible to load Strategy '{}'. This class does not exist"
|
||||
" or contains Python code errors".format(strategy_name)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _get_valid_strategies(module_path: str, strategy_name: str) -> Optional[Type[IStrategy]]:
|
||||
"""
|
||||
Returns a list of all possible strategies for the given module_path
|
||||
:param module_path: absolute path to the module
|
||||
:param strategy_name: Class name of the strategy
|
||||
:return: Tuple with (name, class) or None
|
||||
"""
|
||||
|
||||
# Generate spec based on absolute path
|
||||
spec = importlib.util.spec_from_file_location('user_data.strategies', module_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
valid_strategies_gen = (
|
||||
obj for name, obj in inspect.getmembers(module, inspect.isclass)
|
||||
if strategy_name == name and IStrategy in obj.__bases__
|
||||
)
|
||||
return next(valid_strategies_gen, None)
|
||||
|
||||
@staticmethod
|
||||
def _search_strategy(directory: str, strategy_name: str) -> Optional[IStrategy]:
|
||||
"""
|
||||
Search for the strategy_name in the given directory
|
||||
:param directory: relative or absolute directory path
|
||||
:return: name of the strategy class
|
||||
"""
|
||||
logger.debug('Searching for strategy %s in \'%s\'', strategy_name, directory)
|
||||
for entry in os.listdir(directory):
|
||||
# Only consider python files
|
||||
if not entry.endswith('.py'):
|
||||
logger.debug('Ignoring %s', entry)
|
||||
continue
|
||||
strategy = StrategyResolver._get_valid_strategies(
|
||||
os.path.abspath(os.path.join(directory, entry)), strategy_name
|
||||
)
|
||||
if strategy:
|
||||
return strategy()
|
||||
return None
|
||||
File diff suppressed because it is too large
Load Diff
0
freqtrade/tests/data/__init__.py
Normal file
0
freqtrade/tests/data/__init__.py
Normal file
99
freqtrade/tests/data/test_converter.py
Normal file
99
freqtrade/tests/data/test_converter.py
Normal file
@@ -0,0 +1,99 @@
|
||||
# pragma pylint: disable=missing-docstring, C0103
|
||||
import logging
|
||||
|
||||
from freqtrade.data.converter import parse_ticker_dataframe, ohlcv_fill_up_missing_data
|
||||
from freqtrade.data.history import load_pair_history
|
||||
from freqtrade.optimize import validate_backtest_data, get_timeframe
|
||||
from freqtrade.tests.conftest import log_has
|
||||
|
||||
|
||||
def test_dataframe_correct_columns(result):
|
||||
assert result.columns.tolist() == ['date', 'open', 'high', 'low', 'close', 'volume']
|
||||
|
||||
|
||||
def test_parse_ticker_dataframe(ticker_history_list, caplog):
|
||||
columns = ['date', 'open', 'high', 'low', 'close', 'volume']
|
||||
|
||||
caplog.set_level(logging.DEBUG)
|
||||
# Test file with BV data
|
||||
dataframe = parse_ticker_dataframe(ticker_history_list, '5m', fill_missing=True)
|
||||
assert dataframe.columns.tolist() == columns
|
||||
assert log_has('Parsing tickerlist to dataframe', caplog.record_tuples)
|
||||
|
||||
|
||||
def test_ohlcv_fill_up_missing_data(caplog):
|
||||
data = load_pair_history(datadir=None,
|
||||
ticker_interval='1m',
|
||||
refresh_pairs=False,
|
||||
pair='UNITTEST/BTC',
|
||||
fill_up_missing=False)
|
||||
caplog.set_level(logging.DEBUG)
|
||||
data2 = ohlcv_fill_up_missing_data(data, '1m')
|
||||
assert len(data2) > len(data)
|
||||
# Column names should not change
|
||||
assert (data.columns == data2.columns).all()
|
||||
|
||||
assert log_has(f"Missing data fillup: before: {len(data)} - after: {len(data2)}",
|
||||
caplog.record_tuples)
|
||||
|
||||
# Test fillup actually fixes invalid backtest data
|
||||
min_date, max_date = get_timeframe({'UNITTEST/BTC': data})
|
||||
assert validate_backtest_data({'UNITTEST/BTC': data}, min_date, max_date, 1)
|
||||
assert not validate_backtest_data({'UNITTEST/BTC': data2}, min_date, max_date, 1)
|
||||
|
||||
|
||||
def test_ohlcv_fill_up_missing_data2(caplog):
|
||||
ticker_interval = '5m'
|
||||
ticks = [[
|
||||
1511686200000, # 8:50:00
|
||||
8.794e-05, # open
|
||||
8.948e-05, # high
|
||||
8.794e-05, # low
|
||||
8.88e-05, # close
|
||||
2255, # volume (in quote currency)
|
||||
],
|
||||
[
|
||||
1511686500000, # 8:55:00
|
||||
8.88e-05,
|
||||
8.942e-05,
|
||||
8.88e-05,
|
||||
8.893e-05,
|
||||
9911,
|
||||
],
|
||||
[
|
||||
1511687100000, # 9:05:00
|
||||
8.891e-05,
|
||||
8.893e-05,
|
||||
8.875e-05,
|
||||
8.877e-05,
|
||||
2251
|
||||
],
|
||||
[
|
||||
1511687400000, # 9:10:00
|
||||
8.877e-05,
|
||||
8.883e-05,
|
||||
8.895e-05,
|
||||
8.817e-05,
|
||||
123551
|
||||
]
|
||||
]
|
||||
|
||||
# Generate test-data without filling missing
|
||||
data = parse_ticker_dataframe(ticks, ticker_interval, fill_missing=False)
|
||||
assert len(data) == 3
|
||||
caplog.set_level(logging.DEBUG)
|
||||
data2 = ohlcv_fill_up_missing_data(data, ticker_interval)
|
||||
assert len(data2) == 4
|
||||
# 3rd candle has been filled
|
||||
row = data2.loc[2, :]
|
||||
assert row['volume'] == 0
|
||||
# close shoult match close of previous candle
|
||||
assert row['close'] == data.loc[1, 'close']
|
||||
assert row['open'] == row['close']
|
||||
assert row['high'] == row['close']
|
||||
assert row['low'] == row['close']
|
||||
# Column names should not change
|
||||
assert (data.columns == data2.columns).all()
|
||||
|
||||
assert log_has(f"Missing data fillup: before: {len(data)} - after: {len(data2)}",
|
||||
caplog.record_tuples)
|
||||
92
freqtrade/tests/data/test_dataprovider.py
Normal file
92
freqtrade/tests/data/test_dataprovider.py
Normal file
@@ -0,0 +1,92 @@
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.data.dataprovider import DataProvider
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.tests.conftest import get_patched_exchange
|
||||
|
||||
|
||||
def test_ohlcv(mocker, default_conf, ticker_history):
|
||||
default_conf["runmode"] = RunMode.DRY_RUN
|
||||
tick_interval = default_conf["ticker_interval"]
|
||||
exchange = get_patched_exchange(mocker, default_conf)
|
||||
exchange._klines[("XRP/BTC", tick_interval)] = ticker_history
|
||||
exchange._klines[("UNITTEST/BTC", tick_interval)] = ticker_history
|
||||
dp = DataProvider(default_conf, exchange)
|
||||
assert dp.runmode == RunMode.DRY_RUN
|
||||
assert ticker_history.equals(dp.ohlcv("UNITTEST/BTC", tick_interval))
|
||||
assert isinstance(dp.ohlcv("UNITTEST/BTC", tick_interval), DataFrame)
|
||||
assert dp.ohlcv("UNITTEST/BTC", tick_interval) is not ticker_history
|
||||
assert dp.ohlcv("UNITTEST/BTC", tick_interval, copy=False) is ticker_history
|
||||
assert not dp.ohlcv("UNITTEST/BTC", tick_interval).empty
|
||||
assert dp.ohlcv("NONESENSE/AAA", tick_interval).empty
|
||||
|
||||
# Test with and without parameter
|
||||
assert dp.ohlcv("UNITTEST/BTC", tick_interval).equals(dp.ohlcv("UNITTEST/BTC"))
|
||||
|
||||
default_conf["runmode"] = RunMode.LIVE
|
||||
dp = DataProvider(default_conf, exchange)
|
||||
assert dp.runmode == RunMode.LIVE
|
||||
assert isinstance(dp.ohlcv("UNITTEST/BTC", tick_interval), DataFrame)
|
||||
|
||||
default_conf["runmode"] = RunMode.BACKTEST
|
||||
dp = DataProvider(default_conf, exchange)
|
||||
assert dp.runmode == RunMode.BACKTEST
|
||||
assert dp.ohlcv("UNITTEST/BTC", tick_interval).empty
|
||||
|
||||
|
||||
def test_historic_ohlcv(mocker, default_conf, ticker_history):
|
||||
|
||||
historymock = MagicMock(return_value=ticker_history)
|
||||
mocker.patch("freqtrade.data.dataprovider.load_pair_history", historymock)
|
||||
|
||||
# exchange = get_patched_exchange(mocker, default_conf)
|
||||
dp = DataProvider(default_conf, None)
|
||||
data = dp.historic_ohlcv("UNITTEST/BTC", "5m")
|
||||
assert isinstance(data, DataFrame)
|
||||
assert historymock.call_count == 1
|
||||
assert historymock.call_args_list[0][1]["datadir"] is None
|
||||
assert historymock.call_args_list[0][1]["refresh_pairs"] is False
|
||||
assert historymock.call_args_list[0][1]["ticker_interval"] == "5m"
|
||||
|
||||
|
||||
def test_available_pairs(mocker, default_conf, ticker_history):
|
||||
exchange = get_patched_exchange(mocker, default_conf)
|
||||
|
||||
tick_interval = default_conf["ticker_interval"]
|
||||
exchange._klines[("XRP/BTC", tick_interval)] = ticker_history
|
||||
exchange._klines[("UNITTEST/BTC", tick_interval)] = ticker_history
|
||||
dp = DataProvider(default_conf, exchange)
|
||||
|
||||
assert len(dp.available_pairs) == 2
|
||||
assert dp.available_pairs == [
|
||||
("XRP/BTC", tick_interval),
|
||||
("UNITTEST/BTC", tick_interval),
|
||||
]
|
||||
|
||||
|
||||
def test_refresh(mocker, default_conf, ticker_history):
|
||||
refresh_mock = MagicMock()
|
||||
mocker.patch("freqtrade.exchange.Exchange.refresh_latest_ohlcv", refresh_mock)
|
||||
|
||||
exchange = get_patched_exchange(mocker, default_conf, id="binance")
|
||||
tick_interval = default_conf["ticker_interval"]
|
||||
pairs = [("XRP/BTC", tick_interval), ("UNITTEST/BTC", tick_interval)]
|
||||
|
||||
pairs_non_trad = [("ETH/USDT", tick_interval), ("BTC/TUSD", "1h")]
|
||||
|
||||
dp = DataProvider(default_conf, exchange)
|
||||
dp.refresh(pairs)
|
||||
|
||||
assert refresh_mock.call_count == 1
|
||||
assert len(refresh_mock.call_args[0]) == 1
|
||||
assert len(refresh_mock.call_args[0][0]) == len(pairs)
|
||||
assert refresh_mock.call_args[0][0] == pairs
|
||||
|
||||
refresh_mock.reset_mock()
|
||||
dp.refresh(pairs, pairs_non_trad)
|
||||
assert refresh_mock.call_count == 1
|
||||
assert len(refresh_mock.call_args[0]) == 1
|
||||
assert len(refresh_mock.call_args[0][0]) == len(pairs) + len(pairs_non_trad)
|
||||
assert refresh_mock.call_args[0][0] == pairs + pairs_non_trad
|
||||
475
freqtrade/tests/data/test_history.py
Normal file
475
freqtrade/tests/data/test_history.py
Normal file
@@ -0,0 +1,475 @@
|
||||
# pragma pylint: disable=missing-docstring, protected-access, C0103
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import uuid
|
||||
from shutil import copyfile
|
||||
|
||||
import arrow
|
||||
from pandas import DataFrame
|
||||
import pytest
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.arguments import TimeRange
|
||||
from freqtrade.data import history
|
||||
from freqtrade.data.history import (download_pair_history,
|
||||
load_cached_data_for_updating,
|
||||
load_tickerdata_file,
|
||||
make_testdata_path,
|
||||
trim_tickerlist)
|
||||
from freqtrade.misc import file_dump_json
|
||||
from freqtrade.tests.conftest import get_patched_exchange, log_has
|
||||
|
||||
# Change this if modifying UNITTEST/BTC testdatafile
|
||||
_BTC_UNITTEST_LENGTH = 13681
|
||||
|
||||
|
||||
def _backup_file(file: str, copy_file: bool = False) -> None:
|
||||
"""
|
||||
Backup existing file to avoid deleting the user file
|
||||
:param file: complete path to the file
|
||||
:param touch_file: create an empty file in replacement
|
||||
:return: None
|
||||
"""
|
||||
file_swp = file + '.swp'
|
||||
if os.path.isfile(file):
|
||||
os.rename(file, file_swp)
|
||||
|
||||
if copy_file:
|
||||
copyfile(file_swp, file)
|
||||
|
||||
|
||||
def _clean_test_file(file: str) -> None:
|
||||
"""
|
||||
Backup existing file to avoid deleting the user file
|
||||
:param file: complete path to the file
|
||||
:return: None
|
||||
"""
|
||||
file_swp = file + '.swp'
|
||||
# 1. Delete file from the test
|
||||
if os.path.isfile(file):
|
||||
os.remove(file)
|
||||
|
||||
# 2. Rollback to the initial file
|
||||
if os.path.isfile(file_swp):
|
||||
os.rename(file_swp, file)
|
||||
|
||||
|
||||
def test_load_data_30min_ticker(mocker, caplog, default_conf) -> None:
|
||||
ld = history.load_pair_history(pair='UNITTEST/BTC', ticker_interval='30m', datadir=None)
|
||||
assert isinstance(ld, DataFrame)
|
||||
assert not log_has('Download the pair: "UNITTEST/BTC", Interval: 30m', caplog.record_tuples)
|
||||
|
||||
|
||||
def test_load_data_7min_ticker(mocker, caplog, default_conf) -> None:
|
||||
ld = history.load_pair_history(pair='UNITTEST/BTC', ticker_interval='7m', datadir=None)
|
||||
assert not isinstance(ld, DataFrame)
|
||||
assert ld is None
|
||||
assert log_has(
|
||||
'No data for pair: "UNITTEST/BTC", Interval: 7m. '
|
||||
'Use --refresh-pairs-cached to download the data', caplog.record_tuples)
|
||||
|
||||
|
||||
def test_load_data_1min_ticker(ticker_history, mocker, caplog) -> None:
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_history', return_value=ticker_history)
|
||||
file = os.path.join(os.path.dirname(__file__), '..', 'testdata', 'UNITTEST_BTC-1m.json')
|
||||
_backup_file(file, copy_file=True)
|
||||
history.load_data(datadir=None, ticker_interval='1m', pairs=['UNITTEST/BTC'])
|
||||
assert os.path.isfile(file) is True
|
||||
assert not log_has('Download the pair: "UNITTEST/BTC", Interval: 1m', caplog.record_tuples)
|
||||
_clean_test_file(file)
|
||||
|
||||
|
||||
def test_load_data_with_new_pair_1min(ticker_history_list, mocker, caplog, default_conf) -> None:
|
||||
"""
|
||||
Test load_pair_history() with 1 min ticker
|
||||
"""
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_history', return_value=ticker_history_list)
|
||||
exchange = get_patched_exchange(mocker, default_conf)
|
||||
file = os.path.join(os.path.dirname(__file__), '..', 'testdata', 'MEME_BTC-1m.json')
|
||||
|
||||
_backup_file(file)
|
||||
# do not download a new pair if refresh_pairs isn't set
|
||||
history.load_pair_history(datadir=None,
|
||||
ticker_interval='1m',
|
||||
refresh_pairs=False,
|
||||
pair='MEME/BTC')
|
||||
assert os.path.isfile(file) is False
|
||||
assert log_has('No data for pair: "MEME/BTC", Interval: 1m. '
|
||||
'Use --refresh-pairs-cached to download the data',
|
||||
caplog.record_tuples)
|
||||
|
||||
# download a new pair if refresh_pairs is set
|
||||
history.load_pair_history(datadir=None,
|
||||
ticker_interval='1m',
|
||||
refresh_pairs=True,
|
||||
exchange=exchange,
|
||||
pair='MEME/BTC')
|
||||
assert os.path.isfile(file) is True
|
||||
assert log_has('Download the pair: "MEME/BTC", Interval: 1m', caplog.record_tuples)
|
||||
with pytest.raises(OperationalException, match=r'Exchange needs to be initialized when.*'):
|
||||
history.load_pair_history(datadir=None,
|
||||
ticker_interval='1m',
|
||||
refresh_pairs=True,
|
||||
exchange=None,
|
||||
pair='MEME/BTC')
|
||||
_clean_test_file(file)
|
||||
|
||||
|
||||
def test_testdata_path() -> None:
|
||||
assert str(Path('freqtrade') / 'tests' / 'testdata') in str(make_testdata_path(None))
|
||||
|
||||
|
||||
def test_load_cached_data_for_updating(mocker) -> None:
|
||||
datadir = Path(__file__).parent.parent.joinpath('testdata')
|
||||
|
||||
test_data = None
|
||||
test_filename = datadir.joinpath('UNITTEST_BTC-1m.json')
|
||||
with open(test_filename, "rt") as file:
|
||||
test_data = json.load(file)
|
||||
|
||||
# change now time to test 'line' cases
|
||||
# now = last cached item + 1 hour
|
||||
now_ts = test_data[-1][0] / 1000 + 60 * 60
|
||||
mocker.patch('arrow.utcnow', return_value=arrow.get(now_ts))
|
||||
|
||||
# timeframe starts earlier than the cached data
|
||||
# should fully update data
|
||||
timerange = TimeRange('date', None, test_data[0][0] / 1000 - 1, 0)
|
||||
data, start_ts = load_cached_data_for_updating(test_filename,
|
||||
'1m',
|
||||
timerange)
|
||||
assert data == []
|
||||
assert start_ts == test_data[0][0] - 1000
|
||||
|
||||
# same with 'line' timeframe
|
||||
num_lines = (test_data[-1][0] - test_data[1][0]) / 1000 / 60 + 120
|
||||
data, start_ts = load_cached_data_for_updating(test_filename,
|
||||
'1m',
|
||||
TimeRange(None, 'line', 0, -num_lines))
|
||||
assert data == []
|
||||
assert start_ts < test_data[0][0] - 1
|
||||
|
||||
# timeframe starts in the center of the cached data
|
||||
# should return the chached data w/o the last item
|
||||
timerange = TimeRange('date', None, test_data[0][0] / 1000 + 1, 0)
|
||||
data, start_ts = load_cached_data_for_updating(test_filename,
|
||||
'1m',
|
||||
timerange)
|
||||
assert data == test_data[:-1]
|
||||
assert test_data[-2][0] < start_ts < test_data[-1][0]
|
||||
|
||||
# same with 'line' timeframe
|
||||
num_lines = (test_data[-1][0] - test_data[1][0]) / 1000 / 60 + 30
|
||||
timerange = TimeRange(None, 'line', 0, -num_lines)
|
||||
data, start_ts = load_cached_data_for_updating(test_filename,
|
||||
'1m',
|
||||
timerange)
|
||||
assert data == test_data[:-1]
|
||||
assert test_data[-2][0] < start_ts < test_data[-1][0]
|
||||
|
||||
# timeframe starts after the chached data
|
||||
# should return the chached data w/o the last item
|
||||
timerange = TimeRange('date', None, test_data[-1][0] / 1000 + 1, 0)
|
||||
data, start_ts = load_cached_data_for_updating(test_filename,
|
||||
'1m',
|
||||
timerange)
|
||||
assert data == test_data[:-1]
|
||||
assert test_data[-2][0] < start_ts < test_data[-1][0]
|
||||
|
||||
# same with 'line' timeframe
|
||||
num_lines = 30
|
||||
timerange = TimeRange(None, 'line', 0, -num_lines)
|
||||
data, start_ts = load_cached_data_for_updating(test_filename,
|
||||
'1m',
|
||||
timerange)
|
||||
assert data == test_data[:-1]
|
||||
assert test_data[-2][0] < start_ts < test_data[-1][0]
|
||||
|
||||
# no timeframe is set
|
||||
# should return the chached data w/o the last item
|
||||
num_lines = 30
|
||||
timerange = TimeRange(None, 'line', 0, -num_lines)
|
||||
data, start_ts = load_cached_data_for_updating(test_filename,
|
||||
'1m',
|
||||
timerange)
|
||||
assert data == test_data[:-1]
|
||||
assert test_data[-2][0] < start_ts < test_data[-1][0]
|
||||
|
||||
# no datafile exist
|
||||
# should return timestamp start time
|
||||
timerange = TimeRange('date', None, now_ts - 10000, 0)
|
||||
data, start_ts = load_cached_data_for_updating(test_filename.with_name('unexist'),
|
||||
'1m',
|
||||
timerange)
|
||||
assert data == []
|
||||
assert start_ts == (now_ts - 10000) * 1000
|
||||
|
||||
# same with 'line' timeframe
|
||||
num_lines = 30
|
||||
timerange = TimeRange(None, 'line', 0, -num_lines)
|
||||
data, start_ts = load_cached_data_for_updating(test_filename.with_name('unexist'),
|
||||
'1m',
|
||||
timerange)
|
||||
assert data == []
|
||||
assert start_ts == (now_ts - num_lines * 60) * 1000
|
||||
|
||||
# no datafile exist, no timeframe is set
|
||||
# should return an empty array and None
|
||||
data, start_ts = load_cached_data_for_updating(test_filename.with_name('unexist'),
|
||||
'1m',
|
||||
None)
|
||||
assert data == []
|
||||
assert start_ts is None
|
||||
|
||||
|
||||
def test_download_pair_history(ticker_history_list, mocker, default_conf) -> None:
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_history', return_value=ticker_history_list)
|
||||
exchange = get_patched_exchange(mocker, default_conf)
|
||||
file1_1 = os.path.join(os.path.dirname(__file__), '..', 'testdata', 'MEME_BTC-1m.json')
|
||||
file1_5 = os.path.join(os.path.dirname(__file__), '..', 'testdata', 'MEME_BTC-5m.json')
|
||||
file2_1 = os.path.join(os.path.dirname(__file__), '..', 'testdata', 'CFI_BTC-1m.json')
|
||||
file2_5 = os.path.join(os.path.dirname(__file__), '..', 'testdata', 'CFI_BTC-5m.json')
|
||||
|
||||
_backup_file(file1_1)
|
||||
_backup_file(file1_5)
|
||||
_backup_file(file2_1)
|
||||
_backup_file(file2_5)
|
||||
|
||||
assert os.path.isfile(file1_1) is False
|
||||
assert os.path.isfile(file2_1) is False
|
||||
|
||||
assert download_pair_history(datadir=None, exchange=exchange,
|
||||
pair='MEME/BTC',
|
||||
tick_interval='1m')
|
||||
assert download_pair_history(datadir=None, exchange=exchange,
|
||||
pair='CFI/BTC',
|
||||
tick_interval='1m')
|
||||
assert not exchange._pairs_last_refresh_time
|
||||
assert os.path.isfile(file1_1) is True
|
||||
assert os.path.isfile(file2_1) is True
|
||||
|
||||
# clean files freshly downloaded
|
||||
_clean_test_file(file1_1)
|
||||
_clean_test_file(file2_1)
|
||||
|
||||
assert os.path.isfile(file1_5) is False
|
||||
assert os.path.isfile(file2_5) is False
|
||||
|
||||
assert download_pair_history(datadir=None, exchange=exchange,
|
||||
pair='MEME/BTC',
|
||||
tick_interval='5m')
|
||||
assert download_pair_history(datadir=None, exchange=exchange,
|
||||
pair='CFI/BTC',
|
||||
tick_interval='5m')
|
||||
assert not exchange._pairs_last_refresh_time
|
||||
assert os.path.isfile(file1_5) is True
|
||||
assert os.path.isfile(file2_5) is True
|
||||
|
||||
# clean files freshly downloaded
|
||||
_clean_test_file(file1_5)
|
||||
_clean_test_file(file2_5)
|
||||
|
||||
|
||||
def test_download_pair_history2(mocker, default_conf) -> None:
|
||||
tick = [
|
||||
[1509836520000, 0.00162008, 0.00162008, 0.00162008, 0.00162008, 108.14853839],
|
||||
[1509836580000, 0.00161, 0.00161, 0.00161, 0.00161, 82.390199]
|
||||
]
|
||||
json_dump_mock = mocker.patch('freqtrade.misc.file_dump_json', return_value=None)
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_history', return_value=tick)
|
||||
exchange = get_patched_exchange(mocker, default_conf)
|
||||
download_pair_history(None, exchange, pair="UNITTEST/BTC", tick_interval='1m')
|
||||
download_pair_history(None, exchange, pair="UNITTEST/BTC", tick_interval='3m')
|
||||
assert json_dump_mock.call_count == 2
|
||||
|
||||
|
||||
def test_download_backtesting_data_exception(ticker_history, mocker, caplog, default_conf) -> None:
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_history',
|
||||
side_effect=BaseException('File Error'))
|
||||
|
||||
exchange = get_patched_exchange(mocker, default_conf)
|
||||
|
||||
file1_1 = os.path.join(os.path.dirname(__file__), '..', 'testdata', 'MEME_BTC-1m.json')
|
||||
file1_5 = os.path.join(os.path.dirname(__file__), '..', 'testdata', 'MEME_BTC-5m.json')
|
||||
_backup_file(file1_1)
|
||||
_backup_file(file1_5)
|
||||
|
||||
assert not download_pair_history(datadir=None, exchange=exchange,
|
||||
pair='MEME/BTC',
|
||||
tick_interval='1m')
|
||||
# clean files freshly downloaded
|
||||
_clean_test_file(file1_1)
|
||||
_clean_test_file(file1_5)
|
||||
assert log_has('Failed to download the pair: "MEME/BTC", Interval: 1m', caplog.record_tuples)
|
||||
|
||||
|
||||
def test_load_tickerdata_file() -> None:
|
||||
# 7 does not exist in either format.
|
||||
assert not load_tickerdata_file(None, 'UNITTEST/BTC', '7m')
|
||||
# 1 exists only as a .json
|
||||
tickerdata = load_tickerdata_file(None, 'UNITTEST/BTC', '1m')
|
||||
assert _BTC_UNITTEST_LENGTH == len(tickerdata)
|
||||
# 8 .json is empty and will fail if it's loaded. .json.gz is a copy of 1.json
|
||||
tickerdata = load_tickerdata_file(None, 'UNITTEST/BTC', '8m')
|
||||
assert _BTC_UNITTEST_LENGTH == len(tickerdata)
|
||||
|
||||
|
||||
def test_load_partial_missing(caplog) -> None:
|
||||
# Make sure we start fresh - test missing data at start
|
||||
start = arrow.get('2018-01-01T00:00:00')
|
||||
end = arrow.get('2018-01-11T00:00:00')
|
||||
tickerdata = history.load_data(None, '5m', ['UNITTEST/BTC'],
|
||||
refresh_pairs=False,
|
||||
timerange=TimeRange('date', 'date',
|
||||
start.timestamp, end.timestamp))
|
||||
# timedifference in 5 minutes
|
||||
td = ((end - start).total_seconds() // 60 // 5) + 1
|
||||
assert td != len(tickerdata['UNITTEST/BTC'])
|
||||
start_real = tickerdata['UNITTEST/BTC'].iloc[0, 0]
|
||||
assert log_has(f'Missing data at start for pair '
|
||||
f'UNITTEST/BTC, data starts at {start_real.strftime("%Y-%m-%d %H:%M:%S")}',
|
||||
caplog.record_tuples)
|
||||
# Make sure we start fresh - test missing data at end
|
||||
caplog.clear()
|
||||
start = arrow.get('2018-01-10T00:00:00')
|
||||
end = arrow.get('2018-02-20T00:00:00')
|
||||
tickerdata = history.load_data(datadir=None, ticker_interval='5m',
|
||||
pairs=['UNITTEST/BTC'], refresh_pairs=False,
|
||||
timerange=TimeRange('date', 'date',
|
||||
start.timestamp, end.timestamp))
|
||||
# timedifference in 5 minutes
|
||||
td = ((end - start).total_seconds() // 60 // 5) + 1
|
||||
assert td != len(tickerdata['UNITTEST/BTC'])
|
||||
# Shift endtime with +5 - as last candle is dropped (partial candle)
|
||||
end_real = arrow.get(tickerdata['UNITTEST/BTC'].iloc[-1, 0]).shift(minutes=5)
|
||||
assert log_has(f'Missing data at end for pair '
|
||||
f'UNITTEST/BTC, data ends at {end_real.strftime("%Y-%m-%d %H:%M:%S")}',
|
||||
caplog.record_tuples)
|
||||
|
||||
|
||||
def test_init(default_conf, mocker) -> None:
|
||||
exchange = get_patched_exchange(mocker, default_conf)
|
||||
assert {} == history.load_data(
|
||||
datadir='',
|
||||
exchange=exchange,
|
||||
pairs=[],
|
||||
refresh_pairs=True,
|
||||
ticker_interval=default_conf['ticker_interval']
|
||||
)
|
||||
|
||||
|
||||
def test_trim_tickerlist() -> None:
|
||||
file = os.path.join(os.path.dirname(__file__), '..', 'testdata', 'UNITTEST_BTC-1m.json')
|
||||
with open(file) as data_file:
|
||||
ticker_list = json.load(data_file)
|
||||
ticker_list_len = len(ticker_list)
|
||||
|
||||
# Test the pattern ^(-\d+)$
|
||||
# This pattern uses the latest N elements
|
||||
timerange = TimeRange(None, 'line', 0, -5)
|
||||
ticker = trim_tickerlist(ticker_list, timerange)
|
||||
ticker_len = len(ticker)
|
||||
|
||||
assert ticker_len == 5
|
||||
assert ticker_list[0] is not ticker[0] # The first element should be different
|
||||
assert ticker_list[-1] is ticker[-1] # The last element must be the same
|
||||
|
||||
# Test the pattern ^(\d+)-$
|
||||
# This pattern keep X element from the end
|
||||
timerange = TimeRange('line', None, 5, 0)
|
||||
ticker = trim_tickerlist(ticker_list, timerange)
|
||||
ticker_len = len(ticker)
|
||||
|
||||
assert ticker_len == 5
|
||||
assert ticker_list[0] is ticker[0] # The first element must be the same
|
||||
assert ticker_list[-1] is not ticker[-1] # The last element should be different
|
||||
|
||||
# Test the pattern ^(\d+)-(\d+)$
|
||||
# This pattern extract a window
|
||||
timerange = TimeRange('index', 'index', 5, 10)
|
||||
ticker = trim_tickerlist(ticker_list, timerange)
|
||||
ticker_len = len(ticker)
|
||||
|
||||
assert ticker_len == 5
|
||||
assert ticker_list[0] is not ticker[0] # The first element should be different
|
||||
assert ticker_list[5] is ticker[0] # The list starts at the index 5
|
||||
assert ticker_list[9] is ticker[-1] # The list ends at the index 9 (5 elements)
|
||||
|
||||
# Test the pattern ^(\d{8})-(\d{8})$
|
||||
# This pattern extract a window between the dates
|
||||
timerange = TimeRange('date', 'date', ticker_list[5][0] / 1000, ticker_list[10][0] / 1000 - 1)
|
||||
ticker = trim_tickerlist(ticker_list, timerange)
|
||||
ticker_len = len(ticker)
|
||||
|
||||
assert ticker_len == 5
|
||||
assert ticker_list[0] is not ticker[0] # The first element should be different
|
||||
assert ticker_list[5] is ticker[0] # The list starts at the index 5
|
||||
assert ticker_list[9] is ticker[-1] # The list ends at the index 9 (5 elements)
|
||||
|
||||
# Test the pattern ^-(\d{8})$
|
||||
# This pattern extracts elements from the start to the date
|
||||
timerange = TimeRange(None, 'date', 0, ticker_list[10][0] / 1000 - 1)
|
||||
ticker = trim_tickerlist(ticker_list, timerange)
|
||||
ticker_len = len(ticker)
|
||||
|
||||
assert ticker_len == 10
|
||||
assert ticker_list[0] is ticker[0] # The start of the list is included
|
||||
assert ticker_list[9] is ticker[-1] # The element 10 is not included
|
||||
|
||||
# Test the pattern ^(\d{8})-$
|
||||
# This pattern extracts elements from the date to now
|
||||
timerange = TimeRange('date', None, ticker_list[10][0] / 1000 - 1, None)
|
||||
ticker = trim_tickerlist(ticker_list, timerange)
|
||||
ticker_len = len(ticker)
|
||||
|
||||
assert ticker_len == ticker_list_len - 10
|
||||
assert ticker_list[10] is ticker[0] # The first element is element #10
|
||||
assert ticker_list[-1] is ticker[-1] # The last element is the same
|
||||
|
||||
# Test a wrong pattern
|
||||
# This pattern must return the list unchanged
|
||||
timerange = TimeRange(None, None, None, 5)
|
||||
ticker = trim_tickerlist(ticker_list, timerange)
|
||||
ticker_len = len(ticker)
|
||||
|
||||
assert ticker_list_len == ticker_len
|
||||
|
||||
# Test invalid timerange (start after stop)
|
||||
timerange = TimeRange('index', 'index', 10, 5)
|
||||
with pytest.raises(ValueError, match=r'The timerange .* is incorrect'):
|
||||
trim_tickerlist(ticker_list, timerange)
|
||||
|
||||
assert ticker_list_len == ticker_len
|
||||
|
||||
# passing empty list
|
||||
timerange = TimeRange(None, None, None, 5)
|
||||
ticker = trim_tickerlist([], timerange)
|
||||
assert 0 == len(ticker)
|
||||
assert not ticker
|
||||
|
||||
|
||||
def test_file_dump_json_tofile() -> None:
|
||||
file = os.path.join(os.path.dirname(__file__), '..', 'testdata',
|
||||
'test_{id}.json'.format(id=str(uuid.uuid4())))
|
||||
data = {'bar': 'foo'}
|
||||
|
||||
# check the file we will create does not exist
|
||||
assert os.path.isfile(file) is False
|
||||
|
||||
# Create the Json file
|
||||
file_dump_json(file, data)
|
||||
|
||||
# Check the file was create
|
||||
assert os.path.isfile(file) is True
|
||||
|
||||
# Open the Json file created and test the data is in it
|
||||
with open(file) as data_file:
|
||||
json_from_file = json.load(data_file)
|
||||
|
||||
assert 'bar' in json_from_file
|
||||
assert json_from_file['bar'] == 'foo'
|
||||
|
||||
# Remove the file
|
||||
_clean_test_file(file)
|
||||
0
freqtrade/tests/edge/__init__.py
Normal file
0
freqtrade/tests/edge/__init__.py
Normal file
362
freqtrade/tests/edge/test_edge.py
Normal file
362
freqtrade/tests/edge/test_edge.py
Normal file
@@ -0,0 +1,362 @@
|
||||
# pragma pylint: disable=missing-docstring, C0103, C0330
|
||||
# pragma pylint: disable=protected-access, too-many-lines, invalid-name, too-many-arguments
|
||||
|
||||
import logging
|
||||
import math
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import arrow
|
||||
import numpy as np
|
||||
import pytest
|
||||
from pandas import DataFrame, to_datetime
|
||||
|
||||
from freqtrade.data.converter import parse_ticker_dataframe
|
||||
from freqtrade.edge import Edge, PairInfo
|
||||
from freqtrade.strategy.interface import SellType
|
||||
from freqtrade.tests.conftest import get_patched_freqtradebot
|
||||
from freqtrade.tests.optimize import (BTContainer, BTrade,
|
||||
_build_backtest_dataframe,
|
||||
_get_frame_time_from_offset)
|
||||
|
||||
# Cases to be tested:
|
||||
# 1) Open trade should be removed from the end
|
||||
# 2) Two complete trades within dataframe (with sell hit for all)
|
||||
# 3) Entered, sl 1%, candle drops 8% => Trade closed, 1% loss
|
||||
# 4) Entered, sl 3%, candle drops 4%, recovers to 1% => Trade closed, 3% loss
|
||||
# 5) Stoploss and sell are hit. should sell on stoploss
|
||||
####################################################################
|
||||
|
||||
ticker_start_time = arrow.get(2018, 10, 3)
|
||||
ticker_interval_in_minute = 60
|
||||
_ohlc = {'date': 0, 'buy': 1, 'open': 2, 'high': 3, 'low': 4, 'close': 5, 'sell': 6, 'volume': 7}
|
||||
|
||||
|
||||
# Open trade should be removed from the end
|
||||
tc0 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 1]], # enter trade (signal on last candle)
|
||||
stop_loss=-0.99, roi=float('inf'), profit_perc=0.00,
|
||||
trades=[]
|
||||
)
|
||||
|
||||
# Two complete trades within dataframe(with sell hit for all)
|
||||
tc1 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 1], # enter trade (signal on last candle)
|
||||
[2, 5000, 5025, 4975, 4987, 6172, 0, 0], # exit at open
|
||||
[3, 5000, 5025, 4975, 4987, 6172, 1, 0], # no action
|
||||
[4, 5000, 5025, 4975, 4987, 6172, 0, 0], # should enter the trade
|
||||
[5, 5000, 5025, 4975, 4987, 6172, 0, 1], # no action
|
||||
[6, 5000, 5025, 4975, 4987, 6172, 0, 0], # should sell
|
||||
],
|
||||
stop_loss=-0.99, roi=float('inf'), profit_perc=0.00,
|
||||
trades=[BTrade(sell_reason=SellType.SELL_SIGNAL, open_tick=1, close_tick=2),
|
||||
BTrade(sell_reason=SellType.SELL_SIGNAL, open_tick=4, close_tick=6)]
|
||||
)
|
||||
|
||||
# 3) Entered, sl 1%, candle drops 8% => Trade closed, 1% loss
|
||||
tc2 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4600, 4987, 6172, 0, 0], # enter trade, stoploss hit
|
||||
[2, 5000, 5025, 4975, 4987, 6172, 0, 0],
|
||||
],
|
||||
stop_loss=-0.01, roi=float('inf'), profit_perc=-0.01,
|
||||
trades=[BTrade(sell_reason=SellType.STOP_LOSS, open_tick=1, close_tick=1)]
|
||||
)
|
||||
|
||||
# 4) Entered, sl 3 %, candle drops 4%, recovers to 1 % = > Trade closed, 3 % loss
|
||||
tc3 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4800, 4987, 6172, 0, 0], # enter trade, stoploss hit
|
||||
[2, 5000, 5025, 4975, 4987, 6172, 0, 0],
|
||||
],
|
||||
stop_loss=-0.03, roi=float('inf'), profit_perc=-0.03,
|
||||
trades=[BTrade(sell_reason=SellType.STOP_LOSS, open_tick=1, close_tick=1)]
|
||||
)
|
||||
|
||||
# 5) Stoploss and sell are hit. should sell on stoploss
|
||||
tc4 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4800, 4987, 6172, 0, 1], # enter trade, stoploss hit, sell signal
|
||||
[2, 5000, 5025, 4975, 4987, 6172, 0, 0],
|
||||
],
|
||||
stop_loss=-0.03, roi=float('inf'), profit_perc=-0.03,
|
||||
trades=[BTrade(sell_reason=SellType.STOP_LOSS, open_tick=1, close_tick=1)]
|
||||
)
|
||||
|
||||
TESTS = [
|
||||
tc0,
|
||||
tc1,
|
||||
tc2,
|
||||
tc3,
|
||||
tc4
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", TESTS)
|
||||
def test_edge_results(edge_conf, mocker, caplog, data) -> None:
|
||||
"""
|
||||
run functional tests
|
||||
"""
|
||||
freqtrade = get_patched_freqtradebot(mocker, edge_conf)
|
||||
edge = Edge(edge_conf, freqtrade.exchange, freqtrade.strategy)
|
||||
frame = _build_backtest_dataframe(data.data)
|
||||
caplog.set_level(logging.DEBUG)
|
||||
edge.fee = 0
|
||||
|
||||
trades = edge._find_trades_for_stoploss_range(frame, 'TEST/BTC', [data.stop_loss])
|
||||
results = edge._fill_calculable_fields(DataFrame(trades)) if trades else DataFrame()
|
||||
|
||||
print(results)
|
||||
|
||||
assert len(trades) == len(data.trades)
|
||||
|
||||
if not results.empty:
|
||||
assert round(results["profit_percent"].sum(), 3) == round(data.profit_perc, 3)
|
||||
|
||||
for c, trade in enumerate(data.trades):
|
||||
res = results.iloc[c]
|
||||
assert res.exit_type == trade.sell_reason
|
||||
assert res.open_time == _get_frame_time_from_offset(trade.open_tick)
|
||||
assert res.close_time == _get_frame_time_from_offset(trade.close_tick)
|
||||
|
||||
|
||||
def test_adjust(mocker, edge_conf):
|
||||
freqtrade = get_patched_freqtradebot(mocker, edge_conf)
|
||||
edge = Edge(edge_conf, freqtrade.exchange, freqtrade.strategy)
|
||||
mocker.patch('freqtrade.edge.Edge._cached_pairs', mocker.PropertyMock(
|
||||
return_value={
|
||||
'E/F': PairInfo(-0.01, 0.66, 3.71, 0.50, 1.71, 10, 60),
|
||||
'C/D': PairInfo(-0.01, 0.66, 3.71, 0.50, 1.71, 10, 60),
|
||||
'N/O': PairInfo(-0.01, 0.66, 3.71, 0.50, 1.71, 10, 60)
|
||||
}
|
||||
))
|
||||
|
||||
pairs = ['A/B', 'C/D', 'E/F', 'G/H']
|
||||
assert(edge.adjust(pairs) == ['E/F', 'C/D'])
|
||||
|
||||
|
||||
def test_stoploss(mocker, edge_conf):
|
||||
freqtrade = get_patched_freqtradebot(mocker, edge_conf)
|
||||
edge = Edge(edge_conf, freqtrade.exchange, freqtrade.strategy)
|
||||
mocker.patch('freqtrade.edge.Edge._cached_pairs', mocker.PropertyMock(
|
||||
return_value={
|
||||
'E/F': PairInfo(-0.01, 0.66, 3.71, 0.50, 1.71, 10, 60),
|
||||
'C/D': PairInfo(-0.01, 0.66, 3.71, 0.50, 1.71, 10, 60),
|
||||
'N/O': PairInfo(-0.01, 0.66, 3.71, 0.50, 1.71, 10, 60)
|
||||
}
|
||||
))
|
||||
|
||||
assert edge.stoploss('E/F') == -0.01
|
||||
|
||||
|
||||
def test_nonexisting_stoploss(mocker, edge_conf):
|
||||
freqtrade = get_patched_freqtradebot(mocker, edge_conf)
|
||||
edge = Edge(edge_conf, freqtrade.exchange, freqtrade.strategy)
|
||||
mocker.patch('freqtrade.edge.Edge._cached_pairs', mocker.PropertyMock(
|
||||
return_value={
|
||||
'E/F': PairInfo(-0.01, 0.66, 3.71, 0.50, 1.71, 10, 60),
|
||||
}
|
||||
))
|
||||
|
||||
assert edge.stoploss('N/O') == -0.1
|
||||
|
||||
|
||||
def test_stake_amount(mocker, edge_conf):
|
||||
freqtrade = get_patched_freqtradebot(mocker, edge_conf)
|
||||
edge = Edge(edge_conf, freqtrade.exchange, freqtrade.strategy)
|
||||
mocker.patch('freqtrade.edge.Edge._cached_pairs', mocker.PropertyMock(
|
||||
return_value={
|
||||
'E/F': PairInfo(-0.02, 0.66, 3.71, 0.50, 1.71, 10, 60),
|
||||
}
|
||||
))
|
||||
free = 100
|
||||
total = 100
|
||||
in_trade = 25
|
||||
assert edge.stake_amount('E/F', free, total, in_trade) == 31.25
|
||||
|
||||
free = 20
|
||||
total = 100
|
||||
in_trade = 25
|
||||
assert edge.stake_amount('E/F', free, total, in_trade) == 20
|
||||
|
||||
free = 0
|
||||
total = 100
|
||||
in_trade = 25
|
||||
assert edge.stake_amount('E/F', free, total, in_trade) == 0
|
||||
|
||||
|
||||
def test_nonexisting_stake_amount(mocker, edge_conf):
|
||||
freqtrade = get_patched_freqtradebot(mocker, edge_conf)
|
||||
edge = Edge(edge_conf, freqtrade.exchange, freqtrade.strategy)
|
||||
mocker.patch('freqtrade.edge.Edge._cached_pairs', mocker.PropertyMock(
|
||||
return_value={
|
||||
'E/F': PairInfo(-0.11, 0.66, 3.71, 0.50, 1.71, 10, 60),
|
||||
}
|
||||
))
|
||||
# should use strategy stoploss
|
||||
assert edge.stake_amount('N/O', 1, 2, 1) == 0.15
|
||||
|
||||
|
||||
def _validate_ohlc(buy_ohlc_sell_matrice):
|
||||
for index, ohlc in enumerate(buy_ohlc_sell_matrice):
|
||||
# if not high < open < low or not high < close < low
|
||||
if not ohlc[3] >= ohlc[2] >= ohlc[4] or not ohlc[3] >= ohlc[5] >= ohlc[4]:
|
||||
raise Exception('Line ' + str(index + 1) + ' of ohlc has invalid values!')
|
||||
return True
|
||||
|
||||
|
||||
def _build_dataframe(buy_ohlc_sell_matrice):
|
||||
_validate_ohlc(buy_ohlc_sell_matrice)
|
||||
tickers = []
|
||||
for ohlc in buy_ohlc_sell_matrice:
|
||||
ticker = {
|
||||
'date': ticker_start_time.shift(
|
||||
minutes=(
|
||||
ohlc[0] *
|
||||
ticker_interval_in_minute)).timestamp *
|
||||
1000,
|
||||
'buy': ohlc[1],
|
||||
'open': ohlc[2],
|
||||
'high': ohlc[3],
|
||||
'low': ohlc[4],
|
||||
'close': ohlc[5],
|
||||
'sell': ohlc[6]}
|
||||
tickers.append(ticker)
|
||||
|
||||
frame = DataFrame(tickers)
|
||||
frame['date'] = to_datetime(frame['date'],
|
||||
unit='ms',
|
||||
utc=True,
|
||||
infer_datetime_format=True)
|
||||
|
||||
return frame
|
||||
|
||||
|
||||
def _time_on_candle(number):
|
||||
return np.datetime64(ticker_start_time.shift(
|
||||
minutes=(number * ticker_interval_in_minute)).timestamp * 1000, 'ms')
|
||||
|
||||
|
||||
def test_edge_heartbeat_calculate(mocker, edge_conf):
|
||||
freqtrade = get_patched_freqtradebot(mocker, edge_conf)
|
||||
edge = Edge(edge_conf, freqtrade.exchange, freqtrade.strategy)
|
||||
heartbeat = edge_conf['edge']['process_throttle_secs']
|
||||
|
||||
# should not recalculate if heartbeat not reached
|
||||
edge._last_updated = arrow.utcnow().timestamp - heartbeat + 1
|
||||
|
||||
assert edge.calculate() is False
|
||||
|
||||
|
||||
def mocked_load_data(datadir, pairs=[], ticker_interval='0m', refresh_pairs=False,
|
||||
timerange=None, exchange=None):
|
||||
hz = 0.1
|
||||
base = 0.001
|
||||
|
||||
ETHBTC = [
|
||||
[
|
||||
ticker_start_time.shift(minutes=(x * ticker_interval_in_minute)).timestamp * 1000,
|
||||
math.sin(x * hz) / 1000 + base,
|
||||
math.sin(x * hz) / 1000 + base + 0.0001,
|
||||
math.sin(x * hz) / 1000 + base - 0.0001,
|
||||
math.sin(x * hz) / 1000 + base,
|
||||
123.45
|
||||
] for x in range(0, 500)]
|
||||
|
||||
hz = 0.2
|
||||
base = 0.002
|
||||
LTCBTC = [
|
||||
[
|
||||
ticker_start_time.shift(minutes=(x * ticker_interval_in_minute)).timestamp * 1000,
|
||||
math.sin(x * hz) / 1000 + base,
|
||||
math.sin(x * hz) / 1000 + base + 0.0001,
|
||||
math.sin(x * hz) / 1000 + base - 0.0001,
|
||||
math.sin(x * hz) / 1000 + base,
|
||||
123.45
|
||||
] for x in range(0, 500)]
|
||||
|
||||
pairdata = {'NEO/BTC': parse_ticker_dataframe(ETHBTC, '1h', fill_missing=True),
|
||||
'LTC/BTC': parse_ticker_dataframe(LTCBTC, '1h', fill_missing=True)}
|
||||
return pairdata
|
||||
|
||||
|
||||
def test_edge_process_downloaded_data(mocker, edge_conf):
|
||||
edge_conf['datadir'] = None
|
||||
freqtrade = get_patched_freqtradebot(mocker, edge_conf)
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_fee', MagicMock(return_value=0.001))
|
||||
mocker.patch('freqtrade.data.history.load_data', mocked_load_data)
|
||||
edge = Edge(edge_conf, freqtrade.exchange, freqtrade.strategy)
|
||||
|
||||
assert edge.calculate()
|
||||
assert len(edge._cached_pairs) == 2
|
||||
assert edge._last_updated <= arrow.utcnow().timestamp + 2
|
||||
|
||||
|
||||
def test_process_expectancy(mocker, edge_conf):
|
||||
edge_conf['edge']['min_trade_number'] = 2
|
||||
freqtrade = get_patched_freqtradebot(mocker, edge_conf)
|
||||
|
||||
def get_fee():
|
||||
return 0.001
|
||||
|
||||
freqtrade.exchange.get_fee = get_fee
|
||||
edge = Edge(edge_conf, freqtrade.exchange, freqtrade.strategy)
|
||||
|
||||
trades = [
|
||||
{'pair': 'TEST/BTC',
|
||||
'stoploss': -0.9,
|
||||
'profit_percent': '',
|
||||
'profit_abs': '',
|
||||
'open_time': np.datetime64('2018-10-03T00:05:00.000000000'),
|
||||
'close_time': np.datetime64('2018-10-03T00:10:00.000000000'),
|
||||
'open_index': 1,
|
||||
'close_index': 1,
|
||||
'trade_duration': '',
|
||||
'open_rate': 17,
|
||||
'close_rate': 17,
|
||||
'exit_type': 'sell_signal'},
|
||||
|
||||
{'pair': 'TEST/BTC',
|
||||
'stoploss': -0.9,
|
||||
'profit_percent': '',
|
||||
'profit_abs': '',
|
||||
'open_time': np.datetime64('2018-10-03T00:20:00.000000000'),
|
||||
'close_time': np.datetime64('2018-10-03T00:25:00.000000000'),
|
||||
'open_index': 4,
|
||||
'close_index': 4,
|
||||
'trade_duration': '',
|
||||
'open_rate': 20,
|
||||
'close_rate': 20,
|
||||
'exit_type': 'sell_signal'},
|
||||
|
||||
{'pair': 'TEST/BTC',
|
||||
'stoploss': -0.9,
|
||||
'profit_percent': '',
|
||||
'profit_abs': '',
|
||||
'open_time': np.datetime64('2018-10-03T00:30:00.000000000'),
|
||||
'close_time': np.datetime64('2018-10-03T00:40:00.000000000'),
|
||||
'open_index': 6,
|
||||
'close_index': 7,
|
||||
'trade_duration': '',
|
||||
'open_rate': 26,
|
||||
'close_rate': 34,
|
||||
'exit_type': 'sell_signal'}
|
||||
]
|
||||
|
||||
trades_df = DataFrame(trades)
|
||||
trades_df = edge._fill_calculable_fields(trades_df)
|
||||
final = edge._process_expectancy(trades_df)
|
||||
assert len(final) == 1
|
||||
|
||||
assert 'TEST/BTC' in final
|
||||
assert final['TEST/BTC'].stoploss == -0.9
|
||||
assert round(final['TEST/BTC'].winrate, 10) == 0.3333333333
|
||||
assert round(final['TEST/BTC'].risk_reward_ratio, 10) == 306.5384615384
|
||||
assert round(final['TEST/BTC'].required_risk_reward, 10) == 2.0
|
||||
assert round(final['TEST/BTC'].expectancy, 10) == 101.5128205128
|
||||
0
freqtrade/tests/exchange/__init__.py
Normal file
0
freqtrade/tests/exchange/__init__.py
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,349 +0,0 @@
|
||||
# pragma pylint: disable=missing-docstring, C0103, protected-access, unused-argument
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from requests.exceptions import ContentDecodingError
|
||||
|
||||
import freqtrade.exchange.bittrex as btx
|
||||
from freqtrade.exchange.bittrex import Bittrex
|
||||
|
||||
|
||||
# Eat this flake8
|
||||
# +------------------+
|
||||
# | bittrex.Bittrex |
|
||||
# +------------------+
|
||||
# |
|
||||
# (mock Fake_bittrex)
|
||||
# |
|
||||
# +-----------------------------+
|
||||
# | freqtrade.exchange.Bittrex |
|
||||
# +-----------------------------+
|
||||
# Call into Bittrex will flow up to the
|
||||
# external package bittrex.Bittrex.
|
||||
# By inserting a mock, we redirect those
|
||||
# calls.
|
||||
# The faked bittrex API is called just 'fb'
|
||||
# The freqtrade.exchange.Bittrex is a
|
||||
# wrapper, and is called 'wb'
|
||||
|
||||
|
||||
def _stub_config():
|
||||
return {'key': '',
|
||||
'secret': ''}
|
||||
|
||||
|
||||
class FakeBittrex():
|
||||
def __init__(self, success=True):
|
||||
self.success = True # Believe in yourself
|
||||
self.result = None
|
||||
self.get_ticker_call_count = 0
|
||||
# This is really ugly, doing side-effect during instance creation
|
||||
# But we're allowed to in testing-code
|
||||
btx._API = MagicMock()
|
||||
btx._API.buy_limit = self.fake_buysell_limit
|
||||
btx._API.sell_limit = self.fake_buysell_limit
|
||||
btx._API.get_balance = self.fake_get_balance
|
||||
btx._API.get_balances = self.fake_get_balances
|
||||
btx._API.get_ticker = self.fake_get_ticker
|
||||
btx._API.get_order = self.fake_get_order
|
||||
btx._API.cancel = self.fake_cancel_order
|
||||
btx._API.get_markets = self.fake_get_markets
|
||||
btx._API.get_market_summaries = self.fake_get_market_summaries
|
||||
btx._API_V2 = MagicMock()
|
||||
btx._API_V2.get_candles = self.fake_get_candles
|
||||
btx._API_V2.get_wallet_health = self.fake_get_wallet_health
|
||||
|
||||
def fake_buysell_limit(self, pair, amount, limit):
|
||||
return {'success': self.success,
|
||||
'result': {'uuid': '1234'},
|
||||
'message': 'barter'}
|
||||
|
||||
def fake_get_balance(self, cur):
|
||||
return {'success': self.success,
|
||||
'result': {'Balance': 1234},
|
||||
'message': 'unbalanced'}
|
||||
|
||||
def fake_get_balances(self):
|
||||
return {'success': self.success,
|
||||
'result': [{'BTC_ETH': 1234}],
|
||||
'message': 'no balances'}
|
||||
|
||||
def fake_get_ticker(self, pair):
|
||||
self.get_ticker_call_count += 1
|
||||
return self.result or {'success': self.success,
|
||||
'result': {'Bid': 1, 'Ask': 1, 'Last': 1},
|
||||
'message': 'NO_API_RESPONSE'}
|
||||
|
||||
def fake_get_candles(self, pair, interval):
|
||||
return self.result or {'success': self.success,
|
||||
'result': [{'C': 0, 'V': 0, 'O': 0, 'H': 0, 'L': 0, 'T': 0}],
|
||||
'message': 'candles lit'}
|
||||
|
||||
def fake_get_order(self, uuid):
|
||||
return {'success': self.success,
|
||||
'result': {'OrderUuid': 'ABC123',
|
||||
'Type': 'Type',
|
||||
'Exchange': 'BTC_ETH',
|
||||
'Opened': True,
|
||||
'PricePerUnit': 1,
|
||||
'Quantity': 1,
|
||||
'QuantityRemaining': 1,
|
||||
'Closed': True},
|
||||
'message': 'lost'}
|
||||
|
||||
def fake_cancel_order(self, uuid):
|
||||
return self.result or {'success': self.success,
|
||||
'message': 'no such order'}
|
||||
|
||||
def fake_get_markets(self):
|
||||
return self.result or {'success': self.success,
|
||||
'message': 'market gone',
|
||||
'result': [{'MarketName': '-_'}]}
|
||||
|
||||
def fake_get_market_summaries(self):
|
||||
return self.result or {'success': self.success,
|
||||
'message': 'no summary',
|
||||
'result': ['sum']}
|
||||
|
||||
def fake_get_wallet_health(self):
|
||||
return self.result or {'success': self.success,
|
||||
'message': 'bad health',
|
||||
'result': [{'Health': {'Currency': 'BTC_ETH',
|
||||
'IsActive': True,
|
||||
'LastChecked': 0},
|
||||
'Currency': {'Notice': True}}]}
|
||||
|
||||
|
||||
# The freqtrade.exchange.bittrex is called wrap_bittrex
|
||||
# to not confuse naming with bittrex.bittrex
|
||||
def make_wrap_bittrex():
|
||||
conf = _stub_config()
|
||||
wb = btx.Bittrex(conf)
|
||||
return wb
|
||||
|
||||
|
||||
def test_exchange_bittrex_class():
|
||||
conf = _stub_config()
|
||||
b = Bittrex(conf)
|
||||
assert isinstance(b, Bittrex)
|
||||
slots = dir(b)
|
||||
for name in ['fee', 'buy', 'sell', 'get_balance', 'get_balances',
|
||||
'get_ticker', 'get_ticker_history', 'get_order',
|
||||
'cancel_order', 'get_pair_detail_url', 'get_markets',
|
||||
'get_market_summaries', 'get_wallet_health']:
|
||||
assert name in slots
|
||||
# FIX: ensure that the slot is also a method in the class
|
||||
# getattr(b, name) => bound method Bittrex.buy
|
||||
# type(getattr(b, name)) => class 'method'
|
||||
|
||||
|
||||
def test_exchange_bittrex_fee():
|
||||
fee = Bittrex.fee.__get__(Bittrex)
|
||||
assert fee >= 0 and fee < 0.1 # Fee is 0-10 %
|
||||
|
||||
|
||||
def test_exchange_bittrex_buy_good():
|
||||
wb = make_wrap_bittrex()
|
||||
fb = FakeBittrex()
|
||||
uuid = wb.buy('BTC_ETH', 1, 1)
|
||||
assert uuid == fb.fake_buysell_limit(1, 2, 3)['result']['uuid']
|
||||
|
||||
fb.success = False
|
||||
with pytest.raises(btx.OperationalException, match=r'barter.*'):
|
||||
wb.buy('BAD', 1, 1)
|
||||
|
||||
|
||||
def test_exchange_bittrex_sell_good():
|
||||
wb = make_wrap_bittrex()
|
||||
fb = FakeBittrex()
|
||||
uuid = wb.sell('BTC_ETH', 1, 1)
|
||||
assert uuid == fb.fake_buysell_limit(1, 2, 3)['result']['uuid']
|
||||
|
||||
fb.success = False
|
||||
with pytest.raises(btx.OperationalException, match=r'barter.*'):
|
||||
uuid = wb.sell('BAD', 1, 1)
|
||||
|
||||
|
||||
def test_exchange_bittrex_get_balance():
|
||||
wb = make_wrap_bittrex()
|
||||
fb = FakeBittrex()
|
||||
bal = wb.get_balance('BTC_ETH')
|
||||
assert bal == fb.fake_get_balance(1)['result']['Balance']
|
||||
|
||||
fb.success = False
|
||||
with pytest.raises(btx.OperationalException, match=r'unbalanced'):
|
||||
wb.get_balance('BTC_ETH')
|
||||
|
||||
|
||||
def test_exchange_bittrex_get_balances():
|
||||
wb = make_wrap_bittrex()
|
||||
fb = FakeBittrex()
|
||||
bals = wb.get_balances()
|
||||
assert bals == fb.fake_get_balances()['result']
|
||||
|
||||
fb.success = False
|
||||
with pytest.raises(btx.OperationalException, match=r'no balances'):
|
||||
wb.get_balances()
|
||||
|
||||
|
||||
def test_exchange_bittrex_get_ticker():
|
||||
wb = make_wrap_bittrex()
|
||||
fb = FakeBittrex()
|
||||
|
||||
# Poll ticker, which updates the cache
|
||||
tick = wb.get_ticker('BTC_ETH')
|
||||
for x in ['bid', 'ask', 'last']:
|
||||
assert x in tick
|
||||
# Ensure the side-effect was made (update the ticker cache)
|
||||
assert 'BTC_ETH' in wb.cached_ticker.keys()
|
||||
|
||||
# taint the cache, so we can recognize the cache wall utilized
|
||||
wb.cached_ticker['BTC_ETH']['bid'] = 1234
|
||||
# Poll again, getting the cached result
|
||||
fb.get_ticker_call_count = 0
|
||||
tick = wb.get_ticker('BTC_ETH', False)
|
||||
# Ensure the result was from the cache, and that we didn't call exchange
|
||||
assert wb.cached_ticker['BTC_ETH']['bid'] == 1234
|
||||
assert fb.get_ticker_call_count == 0
|
||||
|
||||
|
||||
def test_exchange_bittrex_get_ticker_bad():
|
||||
wb = make_wrap_bittrex()
|
||||
fb = FakeBittrex()
|
||||
fb.result = {'success': True, 'result': {'Bid': 1, 'Ask': 0}} # incomplete result
|
||||
|
||||
with pytest.raises(ContentDecodingError, match=r'.*Invalid response from Bittrex params.*'):
|
||||
wb.get_ticker('BTC_ETH')
|
||||
fb.result = {'success': False, 'message': 'gone bad'}
|
||||
with pytest.raises(btx.OperationalException, match=r'.*gone bad.*'):
|
||||
wb.get_ticker('BTC_ETH')
|
||||
|
||||
fb.result = {'success': True, 'result': {}} # incomplete result
|
||||
with pytest.raises(ContentDecodingError, match=r'.*Invalid response from Bittrex params.*'):
|
||||
wb.get_ticker('BTC_ETH')
|
||||
fb.result = {'success': False, 'message': 'gone bad'}
|
||||
with pytest.raises(btx.OperationalException, match=r'.*gone bad.*'):
|
||||
wb.get_ticker('BTC_ETH')
|
||||
|
||||
fb.result = {'success': True,
|
||||
'result': {'Bid': 1, 'Ask': 0, 'Last': None}} # incomplete result
|
||||
with pytest.raises(ContentDecodingError, match=r'.*Invalid response from Bittrex params.*'):
|
||||
wb.get_ticker('BTC_ETH')
|
||||
|
||||
|
||||
def test_exchange_bittrex_get_ticker_history_intervals():
|
||||
wb = make_wrap_bittrex()
|
||||
FakeBittrex()
|
||||
for tick_interval in [1, 5, 30, 60, 1440]:
|
||||
assert ([{'C': 0, 'V': 0, 'O': 0, 'H': 0, 'L': 0, 'T': 0}] ==
|
||||
wb.get_ticker_history('BTC_ETH', tick_interval))
|
||||
|
||||
|
||||
def test_exchange_bittrex_get_ticker_history():
|
||||
wb = make_wrap_bittrex()
|
||||
fb = FakeBittrex()
|
||||
assert wb.get_ticker_history('BTC_ETH', 5)
|
||||
with pytest.raises(ValueError, match=r'.*Unknown tick_interval.*'):
|
||||
wb.get_ticker_history('BTC_ETH', 2)
|
||||
|
||||
fb.success = False
|
||||
with pytest.raises(btx.OperationalException, match=r'candles lit.*'):
|
||||
wb.get_ticker_history('BTC_ETH', 5)
|
||||
|
||||
fb.success = True
|
||||
with pytest.raises(ContentDecodingError, match=r'.*Invalid response from Bittrex.*'):
|
||||
fb.result = {'bad': 0}
|
||||
wb.get_ticker_history('BTC_ETH', 5)
|
||||
|
||||
with pytest.raises(ContentDecodingError, match=r'.*Required property C not present.*'):
|
||||
fb.result = {'success': True,
|
||||
'result': [{'V': 0, 'O': 0, 'H': 0, 'L': 0, 'T': 0}], # close is missing
|
||||
'message': 'candles lit'}
|
||||
wb.get_ticker_history('BTC_ETH', 5)
|
||||
|
||||
|
||||
def test_exchange_bittrex_get_order():
|
||||
wb = make_wrap_bittrex()
|
||||
fb = FakeBittrex()
|
||||
order = wb.get_order('someUUID')
|
||||
assert order['id'] == 'ABC123'
|
||||
fb.success = False
|
||||
with pytest.raises(btx.OperationalException, match=r'lost'):
|
||||
wb.get_order('someUUID')
|
||||
|
||||
|
||||
def test_exchange_bittrex_cancel_order():
|
||||
wb = make_wrap_bittrex()
|
||||
fb = FakeBittrex()
|
||||
wb.cancel_order('someUUID')
|
||||
with pytest.raises(btx.OperationalException, match=r'no such order'):
|
||||
fb.success = False
|
||||
wb.cancel_order('someUUID')
|
||||
# Note: this can be a bug in exchange.bittrex._validate_response
|
||||
with pytest.raises(KeyError):
|
||||
fb.result = {'success': False} # message is missing!
|
||||
wb.cancel_order('someUUID')
|
||||
with pytest.raises(btx.OperationalException, match=r'foo'):
|
||||
fb.result = {'success': False, 'message': 'foo'}
|
||||
wb.cancel_order('someUUID')
|
||||
|
||||
|
||||
def test_exchange_get_pair_detail_url():
|
||||
wb = make_wrap_bittrex()
|
||||
assert wb.get_pair_detail_url('BTC_ETH')
|
||||
|
||||
|
||||
def test_exchange_get_markets():
|
||||
wb = make_wrap_bittrex()
|
||||
fb = FakeBittrex()
|
||||
x = wb.get_markets()
|
||||
assert x == ['__']
|
||||
with pytest.raises(btx.OperationalException, match=r'market gone'):
|
||||
fb.success = False
|
||||
wb.get_markets()
|
||||
|
||||
|
||||
def test_exchange_get_market_summaries():
|
||||
wb = make_wrap_bittrex()
|
||||
fb = FakeBittrex()
|
||||
assert ['sum'] == wb.get_market_summaries()
|
||||
with pytest.raises(btx.OperationalException, match=r'no summary'):
|
||||
fb.success = False
|
||||
wb.get_market_summaries()
|
||||
|
||||
|
||||
def test_exchange_get_wallet_health():
|
||||
wb = make_wrap_bittrex()
|
||||
fb = FakeBittrex()
|
||||
x = wb.get_wallet_health()
|
||||
assert x[0]['Currency'] == 'BTC_ETH'
|
||||
with pytest.raises(btx.OperationalException, match=r'bad health'):
|
||||
fb.success = False
|
||||
wb.get_wallet_health()
|
||||
|
||||
|
||||
def test_validate_response_success():
|
||||
response = {
|
||||
'message': '',
|
||||
'result': [],
|
||||
}
|
||||
Bittrex._validate_response(response)
|
||||
|
||||
|
||||
def test_validate_response_no_api_response():
|
||||
response = {
|
||||
'message': 'NO_API_RESPONSE',
|
||||
'result': None,
|
||||
}
|
||||
with pytest.raises(ContentDecodingError, match=r'.*NO_API_RESPONSE.*'):
|
||||
Bittrex._validate_response(response)
|
||||
|
||||
|
||||
def test_validate_response_min_trade_requirement_not_met():
|
||||
response = {
|
||||
'message': 'MIN_TRADE_REQUIREMENT_NOT_MET',
|
||||
'result': None,
|
||||
}
|
||||
with pytest.raises(ContentDecodingError, match=r'.*MIN_TRADE_REQUIREMENT_NOT_MET.*'):
|
||||
Bittrex._validate_response(response)
|
||||
46
freqtrade/tests/optimize/__init__.py
Normal file
46
freqtrade/tests/optimize/__init__.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from typing import NamedTuple, List
|
||||
|
||||
import arrow
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.strategy.interface import SellType
|
||||
from freqtrade.constants import TICKER_INTERVAL_MINUTES
|
||||
|
||||
ticker_start_time = arrow.get(2018, 10, 3)
|
||||
tests_ticker_interval = "1h"
|
||||
|
||||
|
||||
class BTrade(NamedTuple):
|
||||
"""
|
||||
Minimalistic Trade result used for functional backtesting
|
||||
"""
|
||||
sell_reason: SellType
|
||||
open_tick: int
|
||||
close_tick: int
|
||||
|
||||
|
||||
class BTContainer(NamedTuple):
|
||||
"""
|
||||
Minimal BacktestContainer defining Backtest inputs and results.
|
||||
"""
|
||||
data: List[float]
|
||||
stop_loss: float
|
||||
roi: float
|
||||
trades: List[BTrade]
|
||||
profit_perc: float
|
||||
|
||||
|
||||
def _get_frame_time_from_offset(offset):
|
||||
return ticker_start_time.shift(minutes=(offset * TICKER_INTERVAL_MINUTES[tests_ticker_interval])
|
||||
).datetime.replace(tzinfo=None)
|
||||
|
||||
|
||||
def _build_backtest_dataframe(ticker_with_signals):
|
||||
columns = ['date', 'open', 'high', 'low', 'close', 'volume', 'buy', 'sell']
|
||||
|
||||
frame = DataFrame.from_records(ticker_with_signals, columns=columns)
|
||||
frame['date'] = frame['date'].apply(_get_frame_time_from_offset)
|
||||
# Ensure floats are in place
|
||||
for column in ['open', 'high', 'low', 'close', 'volume']:
|
||||
frame[column] = frame[column].astype('float64')
|
||||
return frame
|
||||
182
freqtrade/tests/optimize/test_backtest_detail.py
Normal file
182
freqtrade/tests/optimize/test_backtest_detail.py
Normal file
@@ -0,0 +1,182 @@
|
||||
# pragma pylint: disable=missing-docstring, W0212, line-too-long, C0103, C0330, unused-argument
|
||||
import logging
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from pandas import DataFrame
|
||||
import pytest
|
||||
|
||||
|
||||
from freqtrade.optimize import get_timeframe
|
||||
from freqtrade.optimize.backtesting import Backtesting
|
||||
from freqtrade.strategy.interface import SellType
|
||||
from freqtrade.tests.optimize import (BTrade, BTContainer, _build_backtest_dataframe,
|
||||
_get_frame_time_from_offset, tests_ticker_interval)
|
||||
from freqtrade.tests.conftest import patch_exchange
|
||||
|
||||
|
||||
# Test 0 Minus 8% Close
|
||||
# Test with Stop-loss at 1%
|
||||
# TC1: Stop-Loss Triggered 1% loss
|
||||
tc0 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 0], # enter trade (signal on last candle)
|
||||
[2, 4987, 5012, 4600, 4600, 6172, 0, 0], # exit with stoploss hit
|
||||
[3, 4975, 5000, 4980, 4977, 6172, 0, 0],
|
||||
[4, 4977, 4987, 4977, 4995, 6172, 0, 0],
|
||||
[5, 4995, 4995, 4995, 4950, 6172, 0, 0]],
|
||||
stop_loss=-0.01, roi=1, profit_perc=-0.01,
|
||||
trades=[BTrade(sell_reason=SellType.STOP_LOSS, open_tick=1, close_tick=2)]
|
||||
)
|
||||
|
||||
|
||||
# Test 1 Minus 4% Low, minus 1% close
|
||||
# Test with Stop-Loss at 3%
|
||||
# TC2: Stop-Loss Triggered 3% Loss
|
||||
tc1 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 0], # enter trade (signal on last candle)
|
||||
[2, 4987, 5012, 4962, 4975, 6172, 0, 0],
|
||||
[3, 4975, 5000, 4800, 4962, 6172, 0, 0], # exit with stoploss hit
|
||||
[4, 4962, 4987, 4937, 4950, 6172, 0, 0],
|
||||
[5, 4950, 4975, 4925, 4950, 6172, 0, 0]],
|
||||
stop_loss=-0.03, roi=1, profit_perc=-0.03,
|
||||
trades=[BTrade(sell_reason=SellType.STOP_LOSS, open_tick=1, close_tick=3)]
|
||||
)
|
||||
|
||||
|
||||
# Test 3 Candle drops 4%, Recovers 1%.
|
||||
# Entry Criteria Met
|
||||
# Candle drops 20%
|
||||
# Candle Data for test 3
|
||||
# Test with Stop-Loss at 2%
|
||||
# TC3: Trade-A: Stop-Loss Triggered 2% Loss
|
||||
# Trade-B: Stop-Loss Triggered 2% Loss
|
||||
tc2 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 0], # enter trade (signal on last candle)
|
||||
[2, 4987, 5012, 4800, 4975, 6172, 0, 0], # exit with stoploss hit
|
||||
[3, 4975, 5000, 4950, 4962, 6172, 1, 0],
|
||||
[4, 4975, 5000, 4950, 4962, 6172, 0, 0], # enter trade 2 (signal on last candle)
|
||||
[5, 4962, 4987, 4000, 4000, 6172, 0, 0], # exit with stoploss hit
|
||||
[6, 4950, 4975, 4975, 4950, 6172, 0, 0]],
|
||||
stop_loss=-0.02, roi=1, profit_perc=-0.04,
|
||||
trades=[BTrade(sell_reason=SellType.STOP_LOSS, open_tick=1, close_tick=2),
|
||||
BTrade(sell_reason=SellType.STOP_LOSS, open_tick=4, close_tick=5)]
|
||||
)
|
||||
|
||||
# Test 4 Minus 3% / recovery +15%
|
||||
# Candle Data for test 3 – Candle drops 3% Closed 15% up
|
||||
# Test with Stop-loss at 2% ROI 6%
|
||||
# TC4: Stop-Loss Triggered 2% Loss
|
||||
tc3 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 0], # enter trade (signal on last candle)
|
||||
[2, 4987, 5750, 4850, 5750, 6172, 0, 0], # Exit with stoploss hit
|
||||
[3, 4975, 5000, 4950, 4962, 6172, 0, 0],
|
||||
[4, 4962, 4987, 4937, 4950, 6172, 0, 0],
|
||||
[5, 4950, 4975, 4925, 4950, 6172, 0, 0]],
|
||||
stop_loss=-0.02, roi=0.06, profit_perc=-0.02,
|
||||
trades=[BTrade(sell_reason=SellType.STOP_LOSS, open_tick=1, close_tick=2)]
|
||||
)
|
||||
|
||||
# Test 4 / Drops 0.5% Closes +20%
|
||||
# Set stop-loss at 1% ROI 3%
|
||||
# TC5: ROI triggers 3% Gain
|
||||
tc4 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4980, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4980, 4987, 6172, 0, 0], # enter trade (signal on last candle)
|
||||
[2, 4987, 5025, 4975, 4987, 6172, 0, 0],
|
||||
[3, 4975, 6000, 4975, 6000, 6172, 0, 0], # ROI
|
||||
[4, 4962, 4987, 4972, 4950, 6172, 0, 0],
|
||||
[5, 4950, 4975, 4925, 4950, 6172, 0, 0]],
|
||||
stop_loss=-0.01, roi=0.03, profit_perc=0.03,
|
||||
trades=[BTrade(sell_reason=SellType.ROI, open_tick=1, close_tick=3)]
|
||||
)
|
||||
|
||||
# Test 6 / Drops 3% / Recovers 6% Positive / Closes 1% positve
|
||||
# Candle Data for test 6
|
||||
# Set stop-loss at 2% ROI at 5%
|
||||
# TC6: Stop-Loss triggers 2% Loss
|
||||
tc5 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 0], # enter trade (signal on last candle)
|
||||
[2, 4987, 5300, 4850, 5050, 6172, 0, 0], # Exit with stoploss
|
||||
[3, 4975, 5000, 4950, 4962, 6172, 0, 0],
|
||||
[4, 4962, 4987, 4972, 4950, 6172, 0, 0],
|
||||
[5, 4950, 4975, 4925, 4950, 6172, 0, 0]],
|
||||
stop_loss=-0.02, roi=0.05, profit_perc=-0.02,
|
||||
trades=[BTrade(sell_reason=SellType.STOP_LOSS, open_tick=1, close_tick=2)]
|
||||
)
|
||||
|
||||
# Test 7 - 6% Positive / 1% Negative / Close 1% Positve
|
||||
# Candle Data for test 7
|
||||
# Set stop-loss at 2% ROI at 3%
|
||||
# TC7: ROI Triggers 3% Gain
|
||||
tc6 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 0],
|
||||
[2, 4987, 5300, 4950, 5050, 6172, 0, 0],
|
||||
[3, 4975, 5000, 4950, 4962, 6172, 0, 0],
|
||||
[4, 4962, 4987, 4972, 4950, 6172, 0, 0],
|
||||
[5, 4950, 4975, 4925, 4950, 6172, 0, 0]],
|
||||
stop_loss=-0.02, roi=0.03, profit_perc=0.03,
|
||||
trades=[BTrade(sell_reason=SellType.ROI, open_tick=1, close_tick=2)]
|
||||
)
|
||||
|
||||
TESTS = [
|
||||
tc0,
|
||||
tc1,
|
||||
tc2,
|
||||
tc3,
|
||||
tc4,
|
||||
tc5,
|
||||
tc6,
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", TESTS)
|
||||
def test_backtest_results(default_conf, fee, mocker, caplog, data) -> None:
|
||||
"""
|
||||
run functional tests
|
||||
"""
|
||||
default_conf["stoploss"] = data.stop_loss
|
||||
default_conf["minimal_roi"] = {"0": data.roi}
|
||||
default_conf['ticker_interval'] = tests_ticker_interval
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_fee', MagicMock(return_value=0.0))
|
||||
patch_exchange(mocker)
|
||||
frame = _build_backtest_dataframe(data.data)
|
||||
backtesting = Backtesting(default_conf)
|
||||
backtesting.advise_buy = lambda a, m: frame
|
||||
backtesting.advise_sell = lambda a, m: frame
|
||||
caplog.set_level(logging.DEBUG)
|
||||
|
||||
pair = 'UNITTEST/BTC'
|
||||
# Dummy data as we mock the analyze functions
|
||||
data_processed = {pair: DataFrame()}
|
||||
min_date, max_date = get_timeframe({pair: frame})
|
||||
results = backtesting.backtest(
|
||||
{
|
||||
'stake_amount': default_conf['stake_amount'],
|
||||
'processed': data_processed,
|
||||
'max_open_trades': 10,
|
||||
'start_date': min_date,
|
||||
'end_date': max_date,
|
||||
}
|
||||
)
|
||||
print(results.T)
|
||||
|
||||
assert len(results) == len(data.trades)
|
||||
assert round(results["profit_percent"].sum(), 3) == round(data.profit_perc, 3)
|
||||
|
||||
for c, trade in enumerate(data.trades):
|
||||
res = results.iloc[c]
|
||||
assert res.sell_reason == trade.sell_reason
|
||||
assert res.open_time == _get_frame_time_from_offset(trade.open_tick)
|
||||
assert res.close_time == _get_frame_time_from_offset(trade.close_tick)
|
||||
File diff suppressed because it is too large
Load Diff
136
freqtrade/tests/optimize/test_edge_cli.py
Normal file
136
freqtrade/tests/optimize/test_edge_cli.py
Normal file
@@ -0,0 +1,136 @@
|
||||
# pragma pylint: disable=missing-docstring, C0103, C0330
|
||||
# pragma pylint: disable=protected-access, too-many-lines, invalid-name, too-many-arguments
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
import json
|
||||
from typing import List
|
||||
from freqtrade.edge import PairInfo
|
||||
from freqtrade.arguments import Arguments
|
||||
from freqtrade.optimize.edge_cli import (EdgeCli, setup_configuration, start)
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.tests.conftest import log_has, patch_exchange
|
||||
|
||||
|
||||
def get_args(args) -> List[str]:
|
||||
return Arguments(args, '').get_parsed_arg()
|
||||
|
||||
|
||||
def test_setup_configuration_without_arguments(mocker, default_conf, caplog) -> None:
|
||||
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
||||
read_data=json.dumps(default_conf)
|
||||
))
|
||||
|
||||
args = [
|
||||
'--config', 'config.json',
|
||||
'--strategy', 'DefaultStrategy',
|
||||
'edge'
|
||||
]
|
||||
|
||||
config = setup_configuration(get_args(args))
|
||||
assert config['runmode'] == RunMode.EDGECLI
|
||||
|
||||
assert 'max_open_trades' in config
|
||||
assert 'stake_currency' in config
|
||||
assert 'stake_amount' in config
|
||||
assert 'exchange' in config
|
||||
assert 'pair_whitelist' in config['exchange']
|
||||
assert 'datadir' in config
|
||||
assert log_has(
|
||||
'Using data folder: {} ...'.format(config['datadir']),
|
||||
caplog.record_tuples
|
||||
)
|
||||
assert 'ticker_interval' in config
|
||||
assert not log_has('Parameter -i/--ticker-interval detected ...', caplog.record_tuples)
|
||||
|
||||
assert 'refresh_pairs' not in config
|
||||
assert not log_has('Parameter -r/--refresh-pairs-cached detected ...', caplog.record_tuples)
|
||||
|
||||
assert 'timerange' not in config
|
||||
assert 'stoploss_range' not in config
|
||||
|
||||
|
||||
def test_setup_edge_configuration_with_arguments(mocker, edge_conf, caplog) -> None:
|
||||
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
||||
read_data=json.dumps(edge_conf)
|
||||
))
|
||||
mocker.patch('freqtrade.configuration.Configuration._create_datadir', lambda s, c, x: x)
|
||||
|
||||
args = [
|
||||
'--config', 'config.json',
|
||||
'--strategy', 'DefaultStrategy',
|
||||
'--datadir', '/foo/bar',
|
||||
'edge',
|
||||
'--ticker-interval', '1m',
|
||||
'--refresh-pairs-cached',
|
||||
'--timerange', ':100',
|
||||
'--stoplosses=-0.01,-0.10,-0.001'
|
||||
]
|
||||
|
||||
config = setup_configuration(get_args(args))
|
||||
assert 'max_open_trades' in config
|
||||
assert 'stake_currency' in config
|
||||
assert 'stake_amount' in config
|
||||
assert 'exchange' in config
|
||||
assert 'pair_whitelist' in config['exchange']
|
||||
assert 'datadir' in config
|
||||
assert config['runmode'] == RunMode.EDGECLI
|
||||
assert log_has(
|
||||
'Using data folder: {} ...'.format(config['datadir']),
|
||||
caplog.record_tuples
|
||||
)
|
||||
assert 'ticker_interval' in config
|
||||
assert log_has('Parameter -i/--ticker-interval detected ...', caplog.record_tuples)
|
||||
assert log_has(
|
||||
'Using ticker_interval: 1m ...',
|
||||
caplog.record_tuples
|
||||
)
|
||||
|
||||
assert 'refresh_pairs' in config
|
||||
assert log_has('Parameter -r/--refresh-pairs-cached detected ...', caplog.record_tuples)
|
||||
assert 'timerange' in config
|
||||
assert log_has(
|
||||
'Parameter --timerange detected: {} ...'.format(config['timerange']),
|
||||
caplog.record_tuples
|
||||
)
|
||||
|
||||
|
||||
def test_start(mocker, fee, edge_conf, caplog) -> None:
|
||||
start_mock = MagicMock()
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.optimize.edge_cli.EdgeCli.start', start_mock)
|
||||
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
||||
read_data=json.dumps(edge_conf)
|
||||
))
|
||||
args = [
|
||||
'--config', 'config.json',
|
||||
'--strategy', 'DefaultStrategy',
|
||||
'edge'
|
||||
]
|
||||
args = get_args(args)
|
||||
start(args)
|
||||
assert log_has(
|
||||
'Starting freqtrade in Edge mode',
|
||||
caplog.record_tuples
|
||||
)
|
||||
assert start_mock.call_count == 1
|
||||
|
||||
|
||||
def test_edge_init(mocker, edge_conf) -> None:
|
||||
patch_exchange(mocker)
|
||||
edge_cli = EdgeCli(edge_conf)
|
||||
assert edge_cli.config == edge_conf
|
||||
assert callable(edge_cli.edge.calculate)
|
||||
|
||||
|
||||
def test_generate_edge_table(edge_conf, mocker):
|
||||
patch_exchange(mocker)
|
||||
edge_cli = EdgeCli(edge_conf)
|
||||
|
||||
results = {}
|
||||
results['ETH/BTC'] = PairInfo(-0.01, 0.60, 2, 1, 3, 10, 60)
|
||||
|
||||
assert edge_cli._generate_edge_table(results).count(':|') == 7
|
||||
assert edge_cli._generate_edge_table(results).count('| ETH/BTC |') == 1
|
||||
assert edge_cli._generate_edge_table(results).count(
|
||||
'| risk reward ratio | required risk reward | expectancy |') == 1
|
||||
@@ -1,59 +1,75 @@
|
||||
# pragma pylint: disable=missing-docstring,W0212,C0103
|
||||
import json
|
||||
from datetime import datetime
|
||||
import os
|
||||
from copy import deepcopy
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from freqtrade.optimize.__init__ import load_tickerdata_file
|
||||
from freqtrade.data.converter import parse_ticker_dataframe
|
||||
from freqtrade.data.history import load_tickerdata_file
|
||||
from freqtrade.optimize.hyperopt import Hyperopt, start
|
||||
from freqtrade.strategy.resolver import StrategyResolver
|
||||
from freqtrade.tests.conftest import default_conf, log_has
|
||||
from freqtrade.optimize.default_hyperopt import DefaultHyperOpts
|
||||
from freqtrade.resolvers import StrategyResolver, HyperOptResolver
|
||||
from freqtrade.tests.conftest import log_has, patch_exchange
|
||||
from freqtrade.tests.optimize.test_backtesting import get_args
|
||||
|
||||
|
||||
# Avoid to reinit the same object again and again
|
||||
_HYPEROPT = Hyperopt(default_conf())
|
||||
@pytest.fixture(scope='function')
|
||||
def hyperopt(default_conf, mocker):
|
||||
patch_exchange(mocker)
|
||||
return Hyperopt(default_conf)
|
||||
|
||||
|
||||
# Functions for recurrent object patching
|
||||
def create_trials(mocker) -> None:
|
||||
def create_trials(mocker, hyperopt) -> None:
|
||||
"""
|
||||
When creating trials, mock the hyperopt Trials so that *by default*
|
||||
- we don't create any pickle'd files in the filesystem
|
||||
- we might have a pickle'd file so make sure that we return
|
||||
false when looking for it
|
||||
"""
|
||||
_HYPEROPT.trials_file = os.path.join('freqtrade', 'tests', 'optimize', 'ut_trials.pickle')
|
||||
hyperopt.trials_file = os.path.join('freqtrade', 'tests', 'optimize', 'ut_trials.pickle')
|
||||
|
||||
mocker.patch('freqtrade.optimize.hyperopt.os.path.exists', return_value=False)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.os.path.getsize', return_value=1)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.os.remove', return_value=True)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.pickle.dump', return_value=None)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.dump', return_value=None)
|
||||
|
||||
return mocker.Mock(
|
||||
results=[
|
||||
{
|
||||
'loss': 1,
|
||||
'result': 'foo',
|
||||
'status': 'ok'
|
||||
}
|
||||
],
|
||||
best_trial={'misc': {'vals': {'adx': 999}}}
|
||||
return [{'loss': 1, 'result': 'foo', 'params': {}}]
|
||||
|
||||
|
||||
def test_hyperoptresolver(mocker, default_conf, caplog) -> None:
|
||||
|
||||
mocker.patch(
|
||||
'freqtrade.configuration.Configuration._load_config_file',
|
||||
lambda *args, **kwargs: default_conf
|
||||
)
|
||||
hyperopts = DefaultHyperOpts
|
||||
delattr(hyperopts, 'populate_buy_trend')
|
||||
delattr(hyperopts, 'populate_sell_trend')
|
||||
mocker.patch(
|
||||
'freqtrade.resolvers.hyperopt_resolver.HyperOptResolver._load_hyperopt',
|
||||
MagicMock(return_value=hyperopts)
|
||||
)
|
||||
x = HyperOptResolver(default_conf, ).hyperopt
|
||||
assert not hasattr(x, 'populate_buy_trend')
|
||||
assert not hasattr(x, 'populate_sell_trend')
|
||||
assert log_has("Custom Hyperopt does not provide populate_sell_trend. "
|
||||
"Using populate_sell_trend from DefaultStrategy.", caplog.record_tuples)
|
||||
assert log_has("Custom Hyperopt does not provide populate_buy_trend. "
|
||||
"Using populate_buy_trend from DefaultStrategy.", caplog.record_tuples)
|
||||
|
||||
|
||||
# Unit tests
|
||||
def test_start(mocker, default_conf, caplog) -> None:
|
||||
"""
|
||||
Test start() function
|
||||
"""
|
||||
start_mock = MagicMock()
|
||||
mocker.patch(
|
||||
'freqtrade.configuration.Configuration._load_config_file',
|
||||
lambda *args, **kwargs: default_conf
|
||||
)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.Hyperopt.start', start_mock)
|
||||
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
||||
read_data=json.dumps(default_conf)
|
||||
))
|
||||
patch_exchange(mocker)
|
||||
|
||||
args = [
|
||||
'--config', 'config.json',
|
||||
'--strategy', 'DefaultStrategy',
|
||||
@@ -74,11 +90,32 @@ def test_start(mocker, default_conf, caplog) -> None:
|
||||
assert start_mock.call_count == 1
|
||||
|
||||
|
||||
def test_loss_calculation_prefer_correct_trade_count() -> None:
|
||||
"""
|
||||
Test Hyperopt.calculate_loss()
|
||||
"""
|
||||
hyperopt = _HYPEROPT
|
||||
def test_start_failure(mocker, default_conf, caplog) -> None:
|
||||
start_mock = MagicMock()
|
||||
mocker.patch(
|
||||
'freqtrade.configuration.Configuration._load_config_file',
|
||||
lambda *args, **kwargs: default_conf
|
||||
)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.Hyperopt.start', start_mock)
|
||||
patch_exchange(mocker)
|
||||
|
||||
args = [
|
||||
'--config', 'config.json',
|
||||
'--strategy', 'TestStrategy',
|
||||
'hyperopt',
|
||||
'--epochs', '5'
|
||||
]
|
||||
args = get_args(args)
|
||||
StrategyResolver({'strategy': 'DefaultStrategy'})
|
||||
with pytest.raises(ValueError):
|
||||
start(args)
|
||||
assert log_has(
|
||||
"Please don't use --strategy for hyperopt.",
|
||||
caplog.record_tuples
|
||||
)
|
||||
|
||||
|
||||
def test_loss_calculation_prefer_correct_trade_count(hyperopt) -> None:
|
||||
StrategyResolver({'strategy': 'DefaultStrategy'})
|
||||
|
||||
correct = hyperopt.calculate_loss(1, hyperopt.target_trades, 20)
|
||||
@@ -88,20 +125,13 @@ def test_loss_calculation_prefer_correct_trade_count() -> None:
|
||||
assert under > correct
|
||||
|
||||
|
||||
def test_loss_calculation_prefer_shorter_trades() -> None:
|
||||
"""
|
||||
Test Hyperopt.calculate_loss()
|
||||
"""
|
||||
hyperopt = _HYPEROPT
|
||||
|
||||
def test_loss_calculation_prefer_shorter_trades(hyperopt) -> None:
|
||||
shorter = hyperopt.calculate_loss(1, 100, 20)
|
||||
longer = hyperopt.calculate_loss(1, 100, 30)
|
||||
assert shorter < longer
|
||||
|
||||
|
||||
def test_loss_calculation_has_limited_profit() -> None:
|
||||
hyperopt = _HYPEROPT
|
||||
|
||||
def test_loss_calculation_has_limited_profit(hyperopt) -> None:
|
||||
correct = hyperopt.calculate_loss(hyperopt.expected_max_profit, hyperopt.target_trades, 20)
|
||||
over = hyperopt.calculate_loss(hyperopt.expected_max_profit * 2, hyperopt.target_trades, 20)
|
||||
under = hyperopt.calculate_loss(hyperopt.expected_max_profit / 2, hyperopt.target_trades, 20)
|
||||
@@ -109,8 +139,7 @@ def test_loss_calculation_has_limited_profit() -> None:
|
||||
assert under > correct
|
||||
|
||||
|
||||
def test_log_results_if_loss_improves(capsys) -> None:
|
||||
hyperopt = _HYPEROPT
|
||||
def test_log_results_if_loss_improves(hyperopt, capsys) -> None:
|
||||
hyperopt.current_best_loss = 2
|
||||
hyperopt.log_results(
|
||||
{
|
||||
@@ -121,11 +150,10 @@ def test_log_results_if_loss_improves(capsys) -> None:
|
||||
}
|
||||
)
|
||||
out, err = capsys.readouterr()
|
||||
assert ' 1/2: foo. Loss 1.00000'in out
|
||||
assert ' 1/2: foo. Loss 1.00000' in out
|
||||
|
||||
|
||||
def test_no_log_if_loss_does_not_improve(caplog) -> None:
|
||||
hyperopt = _HYPEROPT
|
||||
def test_no_log_if_loss_does_not_improve(hyperopt, caplog) -> None:
|
||||
hyperopt.current_best_loss = 2
|
||||
hyperopt.log_results(
|
||||
{
|
||||
@@ -135,176 +163,34 @@ def test_no_log_if_loss_does_not_improve(caplog) -> None:
|
||||
assert caplog.record_tuples == []
|
||||
|
||||
|
||||
def test_fmin_best_results(mocker, default_conf, caplog) -> None:
|
||||
fmin_result = {
|
||||
"macd_below_zero": 0,
|
||||
"adx": 1,
|
||||
"adx-value": 15.0,
|
||||
"fastd": 1,
|
||||
"fastd-value": 40.0,
|
||||
"green_candle": 1,
|
||||
"mfi": 0,
|
||||
"over_sar": 0,
|
||||
"rsi": 1,
|
||||
"rsi-value": 37.0,
|
||||
"trigger": 2,
|
||||
"uptrend_long_ema": 1,
|
||||
"uptrend_short_ema": 0,
|
||||
"uptrend_sma": 0,
|
||||
"stoploss": -0.1,
|
||||
"roi_t1": 1,
|
||||
"roi_t2": 2,
|
||||
"roi_t3": 3,
|
||||
"roi_p1": 1,
|
||||
"roi_p2": 2,
|
||||
"roi_p3": 3,
|
||||
}
|
||||
|
||||
conf = deepcopy(default_conf)
|
||||
conf.update({'config': 'config.json.example'})
|
||||
conf.update({'epochs': 1})
|
||||
conf.update({'timerange': None})
|
||||
conf.update({'spaces': 'all'})
|
||||
|
||||
mocker.patch('freqtrade.optimize.hyperopt.load_data', MagicMock())
|
||||
mocker.patch('freqtrade.optimize.hyperopt.fmin', return_value=fmin_result)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.hyperopt_optimize_conf', return_value=conf)
|
||||
|
||||
StrategyResolver({'strategy': 'DefaultStrategy'})
|
||||
hyperopt = Hyperopt(conf)
|
||||
hyperopt.trials = create_trials(mocker)
|
||||
hyperopt.tickerdata_to_dataframe = MagicMock()
|
||||
hyperopt.start()
|
||||
|
||||
exists = [
|
||||
'Best parameters:',
|
||||
'"adx": {\n "enabled": true,\n "value": 15.0\n },',
|
||||
'"fastd": {\n "enabled": true,\n "value": 40.0\n },',
|
||||
'"green_candle": {\n "enabled": true\n },',
|
||||
'"macd_below_zero": {\n "enabled": false\n },',
|
||||
'"mfi": {\n "enabled": false\n },',
|
||||
'"over_sar": {\n "enabled": false\n },',
|
||||
'"roi_p1": 1.0,',
|
||||
'"roi_p2": 2.0,',
|
||||
'"roi_p3": 3.0,',
|
||||
'"roi_t1": 1.0,',
|
||||
'"roi_t2": 2.0,',
|
||||
'"roi_t3": 3.0,',
|
||||
'"rsi": {\n "enabled": true,\n "value": 37.0\n },',
|
||||
'"stoploss": -0.1,',
|
||||
'"trigger": {\n "type": "faststoch10"\n },',
|
||||
'"uptrend_long_ema": {\n "enabled": true\n },',
|
||||
'"uptrend_short_ema": {\n "enabled": false\n },',
|
||||
'"uptrend_sma": {\n "enabled": false\n }',
|
||||
'ROI table:\n{0: 6.0, 3.0: 3.0, 5.0: 1.0, 6.0: 0}',
|
||||
'Best Result:\nfoo'
|
||||
]
|
||||
for line in exists:
|
||||
assert line in caplog.text
|
||||
|
||||
|
||||
def test_fmin_throw_value_error(mocker, default_conf, caplog) -> None:
|
||||
mocker.patch('freqtrade.optimize.hyperopt.load_data', MagicMock())
|
||||
mocker.patch('freqtrade.optimize.hyperopt.fmin', side_effect=ValueError())
|
||||
|
||||
conf = deepcopy(default_conf)
|
||||
conf.update({'config': 'config.json.example'})
|
||||
conf.update({'epochs': 1})
|
||||
conf.update({'timerange': None})
|
||||
conf.update({'spaces': 'all'})
|
||||
mocker.patch('freqtrade.optimize.hyperopt.hyperopt_optimize_conf', return_value=conf)
|
||||
StrategyResolver({'strategy': 'DefaultStrategy'})
|
||||
hyperopt = Hyperopt(conf)
|
||||
hyperopt.trials = create_trials(mocker)
|
||||
hyperopt.tickerdata_to_dataframe = MagicMock()
|
||||
|
||||
hyperopt.start()
|
||||
|
||||
exists = [
|
||||
'Best Result:',
|
||||
'Sorry, Hyperopt was not able to find good parameters. Please try with more epochs '
|
||||
'(param: -e).',
|
||||
]
|
||||
|
||||
for line in exists:
|
||||
assert line in caplog.text
|
||||
|
||||
|
||||
def test_resuming_previous_hyperopt_results_succeeds(mocker, default_conf) -> None:
|
||||
trials = create_trials(mocker)
|
||||
|
||||
conf = deepcopy(default_conf)
|
||||
conf.update({'config': 'config.json.example'})
|
||||
conf.update({'epochs': 1})
|
||||
conf.update({'mongodb': False})
|
||||
conf.update({'timerange': None})
|
||||
conf.update({'spaces': 'all'})
|
||||
|
||||
mocker.patch('freqtrade.optimize.hyperopt.os.path.exists', return_value=True)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.len', return_value=len(trials.results))
|
||||
mock_read = mocker.patch(
|
||||
'freqtrade.optimize.hyperopt.Hyperopt.read_trials',
|
||||
return_value=trials
|
||||
)
|
||||
mock_save = mocker.patch(
|
||||
'freqtrade.optimize.hyperopt.Hyperopt.save_trials',
|
||||
return_value=None
|
||||
)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.sorted', return_value=trials.results)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.load_data', MagicMock())
|
||||
mocker.patch('freqtrade.optimize.hyperopt.fmin', return_value={})
|
||||
mocker.patch('freqtrade.optimize.hyperopt.hyperopt_optimize_conf', return_value=conf)
|
||||
|
||||
StrategyResolver({'strategy': 'DefaultStrategy'})
|
||||
hyperopt = Hyperopt(conf)
|
||||
def test_save_trials_saves_trials(mocker, hyperopt, caplog) -> None:
|
||||
trials = create_trials(mocker, hyperopt)
|
||||
mock_dump = mocker.patch('freqtrade.optimize.hyperopt.dump', return_value=None)
|
||||
hyperopt.trials = trials
|
||||
hyperopt.tickerdata_to_dataframe = MagicMock()
|
||||
|
||||
hyperopt.start()
|
||||
|
||||
mock_read.assert_called_once()
|
||||
mock_save.assert_called_once()
|
||||
|
||||
current_tries = hyperopt.current_tries
|
||||
total_tries = hyperopt.total_tries
|
||||
|
||||
assert current_tries == len(trials.results)
|
||||
assert total_tries == (current_tries + len(trials.results))
|
||||
|
||||
|
||||
def test_save_trials_saves_trials(mocker, caplog) -> None:
|
||||
create_trials(mocker)
|
||||
mock_dump = mocker.patch('freqtrade.optimize.hyperopt.pickle.dump', return_value=None)
|
||||
|
||||
hyperopt = _HYPEROPT
|
||||
mocker.patch('freqtrade.optimize.hyperopt.open', return_value=hyperopt.trials_file)
|
||||
|
||||
hyperopt.save_trials()
|
||||
|
||||
trials_file = os.path.join('freqtrade', 'tests', 'optimize', 'ut_trials.pickle')
|
||||
assert log_has(
|
||||
'Saving Trials to \'freqtrade/tests/optimize/ut_trials.pickle\'',
|
||||
'Saving 1 evaluations to \'{}\''.format(trials_file),
|
||||
caplog.record_tuples
|
||||
)
|
||||
mock_dump.assert_called_once()
|
||||
|
||||
|
||||
def test_read_trials_returns_trials_file(mocker, caplog) -> None:
|
||||
trials = create_trials(mocker)
|
||||
mock_load = mocker.patch('freqtrade.optimize.hyperopt.pickle.load', return_value=trials)
|
||||
mock_open = mocker.patch('freqtrade.optimize.hyperopt.open', return_value=mock_load)
|
||||
|
||||
hyperopt = _HYPEROPT
|
||||
def test_read_trials_returns_trials_file(mocker, hyperopt, caplog) -> None:
|
||||
trials = create_trials(mocker, hyperopt)
|
||||
mock_load = mocker.patch('freqtrade.optimize.hyperopt.load', return_value=trials)
|
||||
hyperopt_trial = hyperopt.read_trials()
|
||||
trials_file = os.path.join('freqtrade', 'tests', 'optimize', 'ut_trials.pickle')
|
||||
assert log_has(
|
||||
'Reading Trials from \'freqtrade/tests/optimize/ut_trials.pickle\'',
|
||||
'Reading Trials from \'{}\''.format(trials_file),
|
||||
caplog.record_tuples
|
||||
)
|
||||
assert hyperopt_trial == trials
|
||||
mock_open.assert_called_once()
|
||||
mock_load.assert_called_once()
|
||||
|
||||
|
||||
def test_roi_table_generation() -> None:
|
||||
def test_roi_table_generation(hyperopt) -> None:
|
||||
params = {
|
||||
'roi_t1': 5,
|
||||
'roi_t2': 10,
|
||||
@@ -314,221 +200,165 @@ def test_roi_table_generation() -> None:
|
||||
'roi_p3': 3,
|
||||
}
|
||||
|
||||
hyperopt = _HYPEROPT
|
||||
assert hyperopt.generate_roi_table(params) == {0: 6, 15: 3, 25: 1, 30: 0}
|
||||
assert hyperopt.custom_hyperopt.generate_roi_table(params) == {0: 6, 15: 3, 25: 1, 30: 0}
|
||||
|
||||
|
||||
def test_start_calls_fmin(mocker, default_conf) -> None:
|
||||
trials = create_trials(mocker)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.sorted', return_value=trials.results)
|
||||
def test_start_calls_optimizer(mocker, default_conf, caplog) -> None:
|
||||
dumper = mocker.patch('freqtrade.optimize.hyperopt.dump', MagicMock())
|
||||
mocker.patch('freqtrade.optimize.hyperopt.load_data', MagicMock())
|
||||
mock_fmin = mocker.patch('freqtrade.optimize.hyperopt.fmin', return_value={})
|
||||
|
||||
conf = deepcopy(default_conf)
|
||||
conf.update({'config': 'config.json.example'})
|
||||
conf.update({'epochs': 1})
|
||||
conf.update({'mongodb': False})
|
||||
conf.update({'timerange': None})
|
||||
conf.update({'spaces': 'all'})
|
||||
|
||||
hyperopt = Hyperopt(conf)
|
||||
hyperopt.trials = trials
|
||||
hyperopt.tickerdata_to_dataframe = MagicMock()
|
||||
|
||||
hyperopt.start()
|
||||
mock_fmin.assert_called_once()
|
||||
|
||||
|
||||
def test_start_uses_mongotrials(mocker, default_conf) -> None:
|
||||
mocker.patch('freqtrade.optimize.hyperopt.load_data', MagicMock())
|
||||
mock_fmin = mocker.patch('freqtrade.optimize.hyperopt.fmin', return_value={})
|
||||
mock_mongotrials = mocker.patch(
|
||||
'freqtrade.optimize.hyperopt.MongoTrials',
|
||||
return_value=create_trials(mocker)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.multiprocessing.cpu_count', MagicMock(return_value=1))
|
||||
parallel = mocker.patch(
|
||||
'freqtrade.optimize.hyperopt.Hyperopt.run_optimizer_parallel',
|
||||
MagicMock(return_value=[{'loss': 1, 'result': 'foo result', 'params': {}}])
|
||||
)
|
||||
patch_exchange(mocker)
|
||||
|
||||
conf = deepcopy(default_conf)
|
||||
conf.update({'config': 'config.json.example'})
|
||||
conf.update({'epochs': 1})
|
||||
conf.update({'mongodb': True})
|
||||
conf.update({'timerange': None})
|
||||
conf.update({'spaces': 'all'})
|
||||
mocker.patch('freqtrade.optimize.hyperopt.hyperopt_optimize_conf', return_value=conf)
|
||||
default_conf.update({'config': 'config.json.example'})
|
||||
default_conf.update({'epochs': 1})
|
||||
default_conf.update({'timerange': None})
|
||||
default_conf.update({'spaces': 'all'})
|
||||
|
||||
hyperopt = Hyperopt(conf)
|
||||
hyperopt.tickerdata_to_dataframe = MagicMock()
|
||||
hyperopt = Hyperopt(default_conf)
|
||||
hyperopt.strategy.tickerdata_to_dataframe = MagicMock()
|
||||
|
||||
hyperopt.start()
|
||||
mock_mongotrials.assert_called_once()
|
||||
mock_fmin.assert_called_once()
|
||||
parallel.assert_called_once()
|
||||
|
||||
assert 'Best result:\nfoo result\nwith values:\n\n' in caplog.text
|
||||
assert dumper.called
|
||||
|
||||
|
||||
# test log_trials_result
|
||||
# test buy_strategy_generator def populate_buy_trend
|
||||
# test optimizer if 'ro_t1' in params
|
||||
|
||||
def test_format_results():
|
||||
"""
|
||||
Test Hyperopt.format_results()
|
||||
"""
|
||||
def test_format_results(hyperopt):
|
||||
# Test with BTC as stake_currency
|
||||
trades = [
|
||||
('BTC_ETH', 2, 2, 123),
|
||||
('BTC_LTC', 1, 1, 123),
|
||||
('BTC_XRP', -1, -2, -246)
|
||||
('ETH/BTC', 2, 2, 123),
|
||||
('LTC/BTC', 1, 1, 123),
|
||||
('XPR/BTC', -1, -2, -246)
|
||||
]
|
||||
labels = ['currency', 'profit_percent', 'profit_BTC', 'duration']
|
||||
labels = ['currency', 'profit_percent', 'profit_abs', 'trade_duration']
|
||||
df = pd.DataFrame.from_records(trades, columns=labels)
|
||||
x = Hyperopt.format_results(df)
|
||||
assert x.find(' 66.67%')
|
||||
|
||||
result = hyperopt.format_results(df)
|
||||
assert result.find(' 66.67%')
|
||||
assert result.find('Total profit 1.00000000 BTC')
|
||||
assert result.find('2.0000Σ %')
|
||||
|
||||
# Test with EUR as stake_currency
|
||||
trades = [
|
||||
('ETH/EUR', 2, 2, 123),
|
||||
('LTC/EUR', 1, 1, 123),
|
||||
('XPR/EUR', -1, -2, -246)
|
||||
]
|
||||
df = pd.DataFrame.from_records(trades, columns=labels)
|
||||
result = hyperopt.format_results(df)
|
||||
assert result.find('Total profit 1.00000000 EUR')
|
||||
|
||||
|
||||
def test_signal_handler(mocker):
|
||||
"""
|
||||
Test Hyperopt.signal_handler()
|
||||
"""
|
||||
m = MagicMock()
|
||||
mocker.patch('sys.exit', m)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.Hyperopt.save_trials', m)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.Hyperopt.log_trials_result', m)
|
||||
def test_has_space(hyperopt):
|
||||
hyperopt.config.update({'spaces': ['buy', 'roi']})
|
||||
assert hyperopt.has_space('roi')
|
||||
assert hyperopt.has_space('buy')
|
||||
assert not hyperopt.has_space('stoploss')
|
||||
|
||||
hyperopt = _HYPEROPT
|
||||
hyperopt.signal_handler(9, None)
|
||||
assert m.call_count == 3
|
||||
hyperopt.config.update({'spaces': ['all']})
|
||||
assert hyperopt.has_space('buy')
|
||||
|
||||
|
||||
def test_has_space():
|
||||
"""
|
||||
Test Hyperopt.has_space() method
|
||||
"""
|
||||
_HYPEROPT.config.update({'spaces': ['buy', 'roi']})
|
||||
assert _HYPEROPT.has_space('roi')
|
||||
assert _HYPEROPT.has_space('buy')
|
||||
assert not _HYPEROPT.has_space('stoploss')
|
||||
|
||||
_HYPEROPT.config.update({'spaces': ['all']})
|
||||
assert _HYPEROPT.has_space('buy')
|
||||
|
||||
|
||||
def test_populate_indicators() -> None:
|
||||
"""
|
||||
Test Hyperopt.populate_indicators()
|
||||
"""
|
||||
tick = load_tickerdata_file(None, 'BTC_UNITEST', 1)
|
||||
tickerlist = {'BTC_UNITEST': tick}
|
||||
dataframes = _HYPEROPT.tickerdata_to_dataframe(tickerlist)
|
||||
dataframe = _HYPEROPT.populate_indicators(dataframes['BTC_UNITEST'])
|
||||
def test_populate_indicators(hyperopt) -> None:
|
||||
tick = load_tickerdata_file(None, 'UNITTEST/BTC', '1m')
|
||||
tickerlist = {'UNITTEST/BTC': parse_ticker_dataframe(tick, '1m', fill_missing=True)}
|
||||
dataframes = hyperopt.strategy.tickerdata_to_dataframe(tickerlist)
|
||||
dataframe = hyperopt.custom_hyperopt.populate_indicators(dataframes['UNITTEST/BTC'],
|
||||
{'pair': 'UNITTEST/BTC'})
|
||||
|
||||
# Check if some indicators are generated. We will not test all of them
|
||||
assert 'adx' in dataframe
|
||||
assert 'ao' in dataframe
|
||||
assert 'cci' in dataframe
|
||||
assert 'mfi' in dataframe
|
||||
assert 'rsi' in dataframe
|
||||
|
||||
|
||||
def test_buy_strategy_generator() -> None:
|
||||
"""
|
||||
Test Hyperopt.buy_strategy_generator()
|
||||
"""
|
||||
tick = load_tickerdata_file(None, 'BTC_UNITEST', 1)
|
||||
tickerlist = {'BTC_UNITEST': tick}
|
||||
dataframes = _HYPEROPT.tickerdata_to_dataframe(tickerlist)
|
||||
dataframe = _HYPEROPT.populate_indicators(dataframes['BTC_UNITEST'])
|
||||
def test_buy_strategy_generator(hyperopt) -> None:
|
||||
tick = load_tickerdata_file(None, 'UNITTEST/BTC', '1m')
|
||||
tickerlist = {'UNITTEST/BTC': parse_ticker_dataframe(tick, '1m', fill_missing=True)}
|
||||
dataframes = hyperopt.strategy.tickerdata_to_dataframe(tickerlist)
|
||||
dataframe = hyperopt.custom_hyperopt.populate_indicators(dataframes['UNITTEST/BTC'],
|
||||
{'pair': 'UNITTEST/BTC'})
|
||||
|
||||
populate_buy_trend = _HYPEROPT.buy_strategy_generator(
|
||||
populate_buy_trend = hyperopt.custom_hyperopt.buy_strategy_generator(
|
||||
{
|
||||
'uptrend_long_ema': {
|
||||
'enabled': True
|
||||
},
|
||||
'macd_below_zero': {
|
||||
'enabled': True
|
||||
},
|
||||
'uptrend_short_ema': {
|
||||
'enabled': True
|
||||
},
|
||||
'mfi': {
|
||||
'enabled': True,
|
||||
'value': 20
|
||||
},
|
||||
'fastd': {
|
||||
'enabled': True,
|
||||
'value': 20
|
||||
},
|
||||
'adx': {
|
||||
'enabled': True,
|
||||
'value': 20
|
||||
},
|
||||
'rsi': {
|
||||
'enabled': True,
|
||||
'value': 20
|
||||
},
|
||||
'over_sar': {
|
||||
'enabled': True,
|
||||
},
|
||||
'green_candle': {
|
||||
'enabled': True,
|
||||
},
|
||||
'uptrend_sma': {
|
||||
'enabled': True,
|
||||
},
|
||||
|
||||
'trigger': {
|
||||
'type': 'lower_bb'
|
||||
}
|
||||
'adx-value': 20,
|
||||
'fastd-value': 20,
|
||||
'mfi-value': 20,
|
||||
'rsi-value': 20,
|
||||
'adx-enabled': True,
|
||||
'fastd-enabled': True,
|
||||
'mfi-enabled': True,
|
||||
'rsi-enabled': True,
|
||||
'trigger': 'bb_lower'
|
||||
}
|
||||
)
|
||||
result = populate_buy_trend(dataframe)
|
||||
result = populate_buy_trend(dataframe, {'pair': 'UNITTEST/BTC'})
|
||||
# Check if some indicators are generated. We will not test all of them
|
||||
assert 'buy' in result
|
||||
assert 1 in result['buy']
|
||||
|
||||
|
||||
def test_generate_optimizer(mocker, default_conf) -> None:
|
||||
"""
|
||||
Test Hyperopt.generate_optimizer() function
|
||||
"""
|
||||
conf = deepcopy(default_conf)
|
||||
conf.update({'config': 'config.json.example'})
|
||||
conf.update({'timerange': None})
|
||||
conf.update({'spaces': 'all'})
|
||||
default_conf.update({'config': 'config.json.example'})
|
||||
default_conf.update({'timerange': None})
|
||||
default_conf.update({'spaces': 'all'})
|
||||
|
||||
trades = [
|
||||
('BTC_POWR', 0.023117, 0.000233, 100)
|
||||
('POWR/BTC', 0.023117, 0.000233, 100)
|
||||
]
|
||||
labels = ['currency', 'profit_percent', 'profit_BTC', 'duration']
|
||||
labels = ['currency', 'profit_percent', 'profit_abs', 'trade_duration']
|
||||
backtest_result = pd.DataFrame.from_records(trades, columns=labels)
|
||||
|
||||
mocker.patch(
|
||||
'freqtrade.optimize.hyperopt.Hyperopt.backtest',
|
||||
MagicMock(return_value=backtest_result)
|
||||
)
|
||||
mocker.patch(
|
||||
'freqtrade.optimize.hyperopt.get_timeframe',
|
||||
MagicMock(return_value=(datetime(2017, 12, 10), datetime(2017, 12, 13)))
|
||||
)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.optimize.hyperopt.load', MagicMock())
|
||||
|
||||
optimizer_param = {
|
||||
'adx': {'enabled': False},
|
||||
'fastd': {'enabled': True, 'value': 35.0},
|
||||
'green_candle': {'enabled': True},
|
||||
'macd_below_zero': {'enabled': True},
|
||||
'mfi': {'enabled': False},
|
||||
'over_sar': {'enabled': False},
|
||||
'roi_p1': 0.01,
|
||||
'roi_p2': 0.01,
|
||||
'roi_p3': 0.1,
|
||||
'adx-value': 0,
|
||||
'fastd-value': 35,
|
||||
'mfi-value': 0,
|
||||
'rsi-value': 0,
|
||||
'adx-enabled': False,
|
||||
'fastd-enabled': True,
|
||||
'mfi-enabled': False,
|
||||
'rsi-enabled': False,
|
||||
'trigger': 'macd_cross_signal',
|
||||
'sell-adx-value': 0,
|
||||
'sell-fastd-value': 75,
|
||||
'sell-mfi-value': 0,
|
||||
'sell-rsi-value': 0,
|
||||
'sell-adx-enabled': False,
|
||||
'sell-fastd-enabled': True,
|
||||
'sell-mfi-enabled': False,
|
||||
'sell-rsi-enabled': False,
|
||||
'sell-trigger': 'macd_cross_signal',
|
||||
'roi_t1': 60.0,
|
||||
'roi_t2': 30.0,
|
||||
'roi_t3': 20.0,
|
||||
'rsi': {'enabled': False},
|
||||
'roi_p1': 0.01,
|
||||
'roi_p2': 0.01,
|
||||
'roi_p3': 0.1,
|
||||
'stoploss': -0.4,
|
||||
'trigger': {'type': 'macd_cross_signal'},
|
||||
'uptrend_long_ema': {'enabled': False},
|
||||
'uptrend_short_ema': {'enabled': True},
|
||||
'uptrend_sma': {'enabled': True}
|
||||
}
|
||||
|
||||
response_expected = {
|
||||
'loss': 1.9840569076926293,
|
||||
'result': ' 1 trades. Avg profit 2.31%. Total profit 0.00023300 BTC '
|
||||
'(0.0231Σ%). Avg duration 100.0 mins.',
|
||||
'status': 'ok'
|
||||
'params': optimizer_param
|
||||
}
|
||||
|
||||
hyperopt = Hyperopt(conf)
|
||||
generate_optimizer_value = hyperopt.generate_optimizer(optimizer_param)
|
||||
hyperopt = Hyperopt(default_conf)
|
||||
generate_optimizer_value = hyperopt.generate_optimizer(list(optimizer_param.values()))
|
||||
assert generate_optimizer_value == response_expected
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
# pragma pylint: disable=missing-docstring,W0212
|
||||
|
||||
from user_data.hyperopt_conf import hyperopt_optimize_conf
|
||||
|
||||
|
||||
def test_hyperopt_optimize_conf():
|
||||
hyperopt_conf = hyperopt_optimize_conf()
|
||||
|
||||
assert "max_open_trades" in hyperopt_conf
|
||||
assert "stake_currency" in hyperopt_conf
|
||||
assert "stake_amount" in hyperopt_conf
|
||||
assert "minimal_roi" in hyperopt_conf
|
||||
assert "stoploss" in hyperopt_conf
|
||||
assert "bid_strategy" in hyperopt_conf
|
||||
assert "exchange" in hyperopt_conf
|
||||
assert "pair_whitelist" in hyperopt_conf['exchange']
|
||||
@@ -1,284 +1,65 @@
|
||||
# pragma pylint: disable=missing-docstring, protected-access, C0103
|
||||
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from shutil import copyfile
|
||||
|
||||
from freqtrade import optimize
|
||||
from freqtrade.misc import file_dump_json
|
||||
from freqtrade.optimize.__init__ import make_testdata_path, download_pairs, \
|
||||
download_backtesting_testdata, load_tickerdata_file, trim_tickerlist
|
||||
from freqtrade.tests.conftest import log_has
|
||||
|
||||
# Change this if modifying BTC_UNITEST testdatafile
|
||||
_BTC_UNITTEST_LENGTH = 13681
|
||||
from freqtrade import optimize, constants
|
||||
from freqtrade.arguments import TimeRange
|
||||
from freqtrade.data import history
|
||||
from freqtrade.strategy.default_strategy import DefaultStrategy
|
||||
from freqtrade.tests.conftest import log_has, patch_exchange
|
||||
|
||||
|
||||
def _backup_file(file: str, copy_file: bool = False) -> None:
|
||||
"""
|
||||
Backup existing file to avoid deleting the user file
|
||||
:param file: complete path to the file
|
||||
:param touch_file: create an empty file in replacement
|
||||
:return: None
|
||||
"""
|
||||
file_swp = file + '.swp'
|
||||
if os.path.isfile(file):
|
||||
os.rename(file, file_swp)
|
||||
def test_get_timeframe(default_conf, mocker) -> None:
|
||||
patch_exchange(mocker)
|
||||
strategy = DefaultStrategy(default_conf)
|
||||
|
||||
if copy_file:
|
||||
copyfile(file_swp, file)
|
||||
data = strategy.tickerdata_to_dataframe(
|
||||
history.load_data(
|
||||
datadir=None,
|
||||
ticker_interval='1m',
|
||||
pairs=['UNITTEST/BTC']
|
||||
)
|
||||
)
|
||||
min_date, max_date = optimize.get_timeframe(data)
|
||||
assert min_date.isoformat() == '2017-11-04T23:02:00+00:00'
|
||||
assert max_date.isoformat() == '2017-11-14T22:58:00+00:00'
|
||||
|
||||
|
||||
def _clean_test_file(file: str) -> None:
|
||||
"""
|
||||
Backup existing file to avoid deleting the user file
|
||||
:param file: complete path to the file
|
||||
:return: None
|
||||
"""
|
||||
file_swp = file + '.swp'
|
||||
# 1. Delete file from the test
|
||||
if os.path.isfile(file):
|
||||
os.remove(file)
|
||||
def test_validate_backtest_data_warn(default_conf, mocker, caplog) -> None:
|
||||
patch_exchange(mocker)
|
||||
strategy = DefaultStrategy(default_conf)
|
||||
|
||||
# 2. Rollback to the initial file
|
||||
if os.path.isfile(file_swp):
|
||||
os.rename(file_swp, file)
|
||||
data = strategy.tickerdata_to_dataframe(
|
||||
history.load_data(
|
||||
datadir=None,
|
||||
ticker_interval='1m',
|
||||
pairs=['UNITTEST/BTC'],
|
||||
fill_up_missing=False
|
||||
)
|
||||
)
|
||||
min_date, max_date = optimize.get_timeframe(data)
|
||||
caplog.clear()
|
||||
assert optimize.validate_backtest_data(data, min_date, max_date,
|
||||
constants.TICKER_INTERVAL_MINUTES["1m"])
|
||||
assert len(caplog.record_tuples) == 1
|
||||
assert log_has(
|
||||
"UNITTEST/BTC has missing frames: expected 14396, got 13680, that's 716 missing values",
|
||||
caplog.record_tuples)
|
||||
|
||||
|
||||
def test_load_data_30min_ticker(ticker_history, mocker, caplog) -> None:
|
||||
"""
|
||||
Test load_data() with 30 min ticker
|
||||
"""
|
||||
mocker.patch('freqtrade.optimize.get_ticker_history', return_value=ticker_history)
|
||||
def test_validate_backtest_data(default_conf, mocker, caplog) -> None:
|
||||
patch_exchange(mocker)
|
||||
strategy = DefaultStrategy(default_conf)
|
||||
|
||||
file = 'freqtrade/tests/testdata/BTC_UNITTEST-30.json'
|
||||
_backup_file(file, copy_file=True)
|
||||
optimize.load_data(None, pairs=['BTC_UNITTEST'], ticker_interval=30)
|
||||
assert os.path.isfile(file) is True
|
||||
assert not log_has('Download the pair: "BTC_ETH", Interval: 30 min', caplog.record_tuples)
|
||||
_clean_test_file(file)
|
||||
|
||||
|
||||
def test_load_data_5min_ticker(ticker_history, mocker, caplog) -> None:
|
||||
"""
|
||||
Test load_data() with 5 min ticker
|
||||
"""
|
||||
mocker.patch('freqtrade.optimize.get_ticker_history', return_value=ticker_history)
|
||||
|
||||
file = 'freqtrade/tests/testdata/BTC_ETH-5.json'
|
||||
_backup_file(file, copy_file=True)
|
||||
optimize.load_data(None, pairs=['BTC_ETH'], ticker_interval=5)
|
||||
assert os.path.isfile(file) is True
|
||||
assert not log_has('Download the pair: "BTC_ETH", Interval: 5 min', caplog.record_tuples)
|
||||
_clean_test_file(file)
|
||||
|
||||
|
||||
def test_load_data_1min_ticker(ticker_history, mocker, caplog) -> None:
|
||||
"""
|
||||
Test load_data() with 1 min ticker
|
||||
"""
|
||||
mocker.patch('freqtrade.optimize.get_ticker_history', return_value=ticker_history)
|
||||
|
||||
file = 'freqtrade/tests/testdata/BTC_ETH-1.json'
|
||||
_backup_file(file, copy_file=True)
|
||||
optimize.load_data(None, ticker_interval=1, pairs=['BTC_ETH'])
|
||||
assert os.path.isfile(file) is True
|
||||
assert not log_has('Download the pair: "BTC_ETH", Interval: 1 min', caplog.record_tuples)
|
||||
_clean_test_file(file)
|
||||
|
||||
|
||||
def test_load_data_with_new_pair_1min(ticker_history, mocker, caplog) -> None:
|
||||
"""
|
||||
Test load_data() with 1 min ticker
|
||||
"""
|
||||
mocker.patch('freqtrade.optimize.get_ticker_history', return_value=ticker_history)
|
||||
|
||||
file = 'freqtrade/tests/testdata/BTC_MEME-1.json'
|
||||
_backup_file(file)
|
||||
optimize.load_data(None, ticker_interval=1, pairs=['BTC_MEME'])
|
||||
assert os.path.isfile(file) is True
|
||||
assert log_has('Download the pair: "BTC_MEME", Interval: 1 min', caplog.record_tuples)
|
||||
_clean_test_file(file)
|
||||
|
||||
|
||||
def test_testdata_path() -> None:
|
||||
assert os.path.join('freqtrade', 'tests', 'testdata') in make_testdata_path(None)
|
||||
|
||||
|
||||
def test_download_pairs(ticker_history, mocker) -> None:
|
||||
mocker.patch('freqtrade.optimize.__init__.get_ticker_history', return_value=ticker_history)
|
||||
|
||||
file1_1 = 'freqtrade/tests/testdata/BTC_MEME-1.json'
|
||||
file1_5 = 'freqtrade/tests/testdata/BTC_MEME-5.json'
|
||||
file2_1 = 'freqtrade/tests/testdata/BTC_CFI-1.json'
|
||||
file2_5 = 'freqtrade/tests/testdata/BTC_CFI-5.json'
|
||||
|
||||
_backup_file(file1_1)
|
||||
_backup_file(file1_5)
|
||||
_backup_file(file2_1)
|
||||
_backup_file(file2_5)
|
||||
|
||||
assert os.path.isfile(file1_1) is False
|
||||
assert os.path.isfile(file2_1) is False
|
||||
|
||||
assert download_pairs(None, pairs=['BTC-MEME', 'BTC-CFI'], ticker_interval=1) is True
|
||||
|
||||
assert os.path.isfile(file1_1) is True
|
||||
assert os.path.isfile(file2_1) is True
|
||||
|
||||
# clean files freshly downloaded
|
||||
_clean_test_file(file1_1)
|
||||
_clean_test_file(file2_1)
|
||||
|
||||
assert os.path.isfile(file1_5) is False
|
||||
assert os.path.isfile(file2_5) is False
|
||||
|
||||
assert download_pairs(None, pairs=['BTC-MEME', 'BTC-CFI'], ticker_interval=5) is True
|
||||
|
||||
assert os.path.isfile(file1_5) is True
|
||||
assert os.path.isfile(file2_5) is True
|
||||
|
||||
# clean files freshly downloaded
|
||||
_clean_test_file(file1_5)
|
||||
_clean_test_file(file2_5)
|
||||
|
||||
|
||||
def test_download_pairs_exception(ticker_history, mocker, caplog) -> None:
|
||||
mocker.patch('freqtrade.optimize.__init__.get_ticker_history', return_value=ticker_history)
|
||||
mocker.patch('freqtrade.optimize.__init__.download_backtesting_testdata',
|
||||
side_effect=BaseException('File Error'))
|
||||
|
||||
file1_1 = 'freqtrade/tests/testdata/BTC_MEME-1.json'
|
||||
file1_5 = 'freqtrade/tests/testdata/BTC_MEME-5.json'
|
||||
_backup_file(file1_1)
|
||||
_backup_file(file1_5)
|
||||
|
||||
download_pairs(None, pairs=['BTC-MEME'], ticker_interval=1)
|
||||
# clean files freshly downloaded
|
||||
_clean_test_file(file1_1)
|
||||
_clean_test_file(file1_5)
|
||||
assert log_has('Failed to download the pair: "BTC-MEME", Interval: 1 min', caplog.record_tuples)
|
||||
|
||||
|
||||
def test_download_backtesting_testdata(ticker_history, mocker) -> None:
|
||||
mocker.patch('freqtrade.optimize.__init__.get_ticker_history', return_value=ticker_history)
|
||||
|
||||
# Download a 1 min ticker file
|
||||
file1 = 'freqtrade/tests/testdata/BTC_XEL-1.json'
|
||||
_backup_file(file1)
|
||||
download_backtesting_testdata(None, pair="BTC-XEL", interval=1)
|
||||
assert os.path.isfile(file1) is True
|
||||
_clean_test_file(file1)
|
||||
|
||||
# Download a 5 min ticker file
|
||||
file2 = 'freqtrade/tests/testdata/BTC_STORJ-5.json'
|
||||
_backup_file(file2)
|
||||
|
||||
download_backtesting_testdata(None, pair="BTC-STORJ", interval=5)
|
||||
assert os.path.isfile(file2) is True
|
||||
_clean_test_file(file2)
|
||||
|
||||
|
||||
def test_download_backtesting_testdata2(mocker) -> None:
|
||||
tick = [{'T': 'bar'}, {'T': 'foo'}]
|
||||
json_dump_mock = mocker.patch('freqtrade.misc.file_dump_json', return_value=None)
|
||||
mocker.patch('freqtrade.optimize.__init__.get_ticker_history', return_value=tick)
|
||||
download_backtesting_testdata(None, pair="BTC-UNITEST", interval=1)
|
||||
download_backtesting_testdata(None, pair="BTC-UNITEST", interval=3)
|
||||
assert json_dump_mock.call_count == 2
|
||||
|
||||
|
||||
def test_load_tickerdata_file() -> None:
|
||||
# 7 does not exist in either format.
|
||||
assert not load_tickerdata_file(None, 'BTC_UNITEST', 7)
|
||||
# 1 exists only as a .json
|
||||
tickerdata = load_tickerdata_file(None, 'BTC_UNITEST', 1)
|
||||
assert _BTC_UNITTEST_LENGTH == len(tickerdata)
|
||||
# 8 .json is empty and will fail if it's loaded. .json.gz is a copy of 1.json
|
||||
tickerdata = load_tickerdata_file(None, 'BTC_UNITEST', 8)
|
||||
assert _BTC_UNITTEST_LENGTH == len(tickerdata)
|
||||
|
||||
|
||||
def test_init(default_conf, mocker) -> None:
|
||||
conf = {'exchange': {'pair_whitelist': []}}
|
||||
mocker.patch('freqtrade.optimize.hyperopt_optimize_conf', return_value=conf)
|
||||
assert {} == optimize.load_data(
|
||||
'',
|
||||
pairs=[],
|
||||
refresh_pairs=True,
|
||||
ticker_interval=int(default_conf['ticker_interval'])
|
||||
timerange = TimeRange('index', 'index', 200, 250)
|
||||
data = strategy.tickerdata_to_dataframe(
|
||||
history.load_data(
|
||||
datadir=None,
|
||||
ticker_interval='5m',
|
||||
pairs=['UNITTEST/BTC'],
|
||||
timerange=timerange
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_trim_tickerlist() -> None:
|
||||
with open('freqtrade/tests/testdata/BTC_ETH-1.json') as data_file:
|
||||
ticker_list = json.load(data_file)
|
||||
ticker_list_len = len(ticker_list)
|
||||
|
||||
# Test the pattern ^(-\d+)$
|
||||
# This pattern remove X element from the beginning
|
||||
timerange = ((None, 'line'), None, 5)
|
||||
ticker = trim_tickerlist(ticker_list, timerange)
|
||||
ticker_len = len(ticker)
|
||||
|
||||
assert ticker_list_len == ticker_len + 5
|
||||
assert ticker_list[0] is not ticker[0] # The first element should be different
|
||||
assert ticker_list[-1] is ticker[-1] # The last element must be the same
|
||||
|
||||
# Test the pattern ^(\d+)-$
|
||||
# This pattern keep X element from the end
|
||||
timerange = (('line', None), 5, None)
|
||||
ticker = trim_tickerlist(ticker_list, timerange)
|
||||
ticker_len = len(ticker)
|
||||
|
||||
assert ticker_len == 5
|
||||
assert ticker_list[0] is ticker[0] # The first element must be the same
|
||||
assert ticker_list[-1] is not ticker[-1] # The last element should be different
|
||||
|
||||
# Test the pattern ^(\d+)-(\d+)$
|
||||
# This pattern extract a window
|
||||
timerange = (('index', 'index'), 5, 10)
|
||||
ticker = trim_tickerlist(ticker_list, timerange)
|
||||
ticker_len = len(ticker)
|
||||
|
||||
assert ticker_len == 5
|
||||
assert ticker_list[0] is not ticker[0] # The first element should be different
|
||||
assert ticker_list[5] is ticker[0] # The list starts at the index 5
|
||||
assert ticker_list[9] is ticker[-1] # The list ends at the index 9 (5 elements)
|
||||
|
||||
# Test a wrong pattern
|
||||
# This pattern must return the list unchanged
|
||||
timerange = ((None, None), None, 5)
|
||||
ticker = trim_tickerlist(ticker_list, timerange)
|
||||
ticker_len = len(ticker)
|
||||
|
||||
assert ticker_list_len == ticker_len
|
||||
|
||||
|
||||
def test_file_dump_json() -> None:
|
||||
"""
|
||||
Test file_dump_json()
|
||||
:return: None
|
||||
"""
|
||||
file = 'freqtrade/tests/testdata/test_{id}.json'.format(id=str(uuid.uuid4()))
|
||||
data = {'bar': 'foo'}
|
||||
|
||||
# check the file we will create does not exist
|
||||
assert os.path.isfile(file) is False
|
||||
|
||||
# Create the Json file
|
||||
file_dump_json(file, data)
|
||||
|
||||
# Check the file was create
|
||||
assert os.path.isfile(file) is True
|
||||
|
||||
# Open the Json file created and test the data is in it
|
||||
with open(file) as data_file:
|
||||
json_from_file = json.load(data_file)
|
||||
|
||||
assert 'bar' in json_from_file
|
||||
assert json_from_file['bar'] == 'foo'
|
||||
|
||||
# Remove the file
|
||||
_clean_test_file(file)
|
||||
min_date, max_date = optimize.get_timeframe(data)
|
||||
caplog.clear()
|
||||
assert not optimize.validate_backtest_data(data, min_date, max_date,
|
||||
constants.TICKER_INTERVAL_MINUTES["5m"])
|
||||
assert len(caplog.record_tuples) == 0
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user