Compare commits
948 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
766c786d90 | ||
|
eac98dbbd6 | ||
|
a9b4d6de33 | ||
|
4d7f3e570b | ||
|
5ab8cc56a4 | ||
|
9005cd25b8 | ||
|
8f529f48da | ||
|
91b6c02947 | ||
|
3a83492999 | ||
|
f98bd40955 | ||
|
6fc165c133 | ||
|
d10e00b61b | ||
|
c0df15af29 | ||
|
9b8148356e | ||
|
04058b1a33 | ||
|
1314e75bc6 | ||
|
cb749b578d | ||
|
fb99cf1459 | ||
|
d4e9037e6e | ||
|
afdcd2c0af | ||
|
9422062cbd | ||
|
b976baae3f | ||
|
c22cccb55b | ||
|
9a3c425cf4 | ||
|
16f9675356 | ||
|
37acaa685b | ||
|
31e0b09643 | ||
|
371b374ea6 | ||
|
bec9b580b0 | ||
|
e94e2dd383 | ||
|
c42241986e | ||
|
c998577d4a | ||
|
fd379d36ac | ||
|
5c0f98b518 | ||
|
06cae1b60c | ||
|
5f5f75e147 | ||
|
992d6b8018 | ||
|
7c80eeea95 | ||
|
86b3306a3b | ||
|
7c99e6f0e6 | ||
|
20591b539a | ||
|
cd8d4da466 | ||
|
a68a546dd9 | ||
|
c785bce7e6 | ||
|
d05cbe239a | ||
|
792c8503f9 | ||
|
10104927c9 | ||
|
611dbdc522 | ||
|
3386ca9999 | ||
|
994b4013ad | ||
|
8b5f8937cc | ||
|
7f8dbce367 | ||
|
6a8e495102 | ||
|
296a6bd43c | ||
|
eb95d970e9 | ||
|
d21eff0d52 | ||
|
3ea33d1737 | ||
|
6d40814dbf | ||
|
a8bae3a381 | ||
|
389db2fe7d | ||
|
3a2bac4ae3 | ||
|
53c208197d | ||
|
572f5f9186 | ||
|
9f338ba6ed | ||
|
3fefb6f1c8 | ||
|
d74376726a | ||
|
baef8b4f79 | ||
|
bf5868c96d | ||
|
f72d53351c | ||
|
0b65fe6afe | ||
|
9147106259 | ||
|
baa1142afa | ||
|
9d4cdcad10 | ||
|
6d1fba1409 | ||
|
f3de0dd3eb | ||
|
d289fe44cb | ||
|
950c5c0113 | ||
|
adb3fb123e | ||
|
47a06c6213 | ||
|
ac43591c44 | ||
|
60ea32e398 | ||
|
6007d5182a | ||
|
1f6a71fdd9 | ||
|
951c6ac1d4 | ||
|
71f45021b9 | ||
|
e328182bd7 | ||
|
4d7ffa8c81 | ||
|
b062b836cc | ||
|
63a579dbab | ||
|
dbc25f00ac | ||
|
0c6c5162e8 | ||
|
689c19620c | ||
|
f159c46438 | ||
|
bc0550358f | ||
|
d78fd3fa8f | ||
|
6c29964bcc | ||
|
59efc5f083 | ||
|
f1809286cf | ||
|
a34753fcb1 | ||
|
ddecf3ef98 | ||
|
5102dfd6df | ||
|
61d225a575 | ||
|
8631a54514 | ||
|
5f17dd06a5 | ||
|
47f391e43e | ||
|
378a252ad1 | ||
|
cc428d7e36 | ||
|
c8df3c4730 | ||
|
de26867ad2 | ||
|
4d2c59b7ec | ||
|
eb9d137d5b | ||
|
ee6d340aa7 | ||
|
3bc59d427c | ||
|
3cf506fa5d | ||
|
784630e2f2 | ||
|
f3319e1382 | ||
|
bd5f46e4c2 | ||
|
2e7faa782c | ||
|
3a9583403b | ||
|
4f126bea35 | ||
|
bf182dc01e | ||
|
124cb5c5bf | ||
|
54ab61d18a | ||
|
9e66417e85 | ||
|
b43ef474ad | ||
|
7a628432a8 | ||
|
c9e477214f | ||
|
6ca2b2d52d | ||
|
e69dac2704 | ||
|
a9ca72c1b8 | ||
|
dfe9247c65 | ||
|
91f8667881 | ||
|
3d57a108d8 | ||
|
a906093153 | ||
|
f7b055a58c | ||
|
95732e8991 | ||
|
c0f170fdb9 | ||
|
5c34140a19 | ||
|
65d91a3a58 | ||
|
573de1cf08 | ||
|
67d84e7514 | ||
|
e3f3f36298 | ||
|
eaaaddac86 | ||
|
c010cdf894 | ||
|
c9ed2137bb | ||
|
67306d943a | ||
|
9a93a0876a | ||
|
844df96ec7 | ||
|
614a996597 | ||
|
cce4d7e42c | ||
|
1cf6e2c957 | ||
|
0704cfb05b | ||
|
07bc0c3fce | ||
|
d1804dee6b | ||
|
9e84dd9274 | ||
|
a7e3f9ef70 | ||
|
a33f4fd9ca | ||
|
9e435fba0b | ||
|
7d06e61461 | ||
|
66391b80ae | ||
|
5ca2cd3a1e | ||
|
634d6f3898 | ||
|
26c3463403 | ||
|
cff50f9f66 | ||
|
ca0bb7bbb8 | ||
|
e6176d43f3 | ||
|
3dc37dd79d | ||
|
336dd1a29c | ||
|
84ced92002 | ||
|
29f4dd1dcd | ||
|
718f2b24d2 | ||
|
b2ab553a31 | ||
|
eb20f6e7d0 | ||
|
346542e5cd | ||
|
68d148e72d | ||
|
1717121f10 | ||
|
790f833653 | ||
|
29ce323649 | ||
|
776ce57f55 | ||
|
54a50b1fb4 | ||
|
9f873305eb | ||
|
9350f505bc | ||
|
e23898d17b | ||
|
9ee1d88355 | ||
|
73a29e6d74 | ||
|
a18d66e108 | ||
|
f37ea4ba24 | ||
|
4b86700a0f | ||
|
5e4c4cae06 | ||
|
86d0700884 | ||
|
6594278509 | ||
|
eac74a9dec | ||
|
619b855d5f | ||
|
a862f19f82 | ||
|
1e38fec61b | ||
|
31829d5250 | ||
|
11f36fbaee | ||
|
67ced6a53c | ||
|
e5840abaf9 | ||
|
885da85fce | ||
|
9e3224ccc0 | ||
|
12de29dd3e | ||
|
512e163355 | ||
|
bd7600ff06 | ||
|
04624aae40 | ||
|
0affacd39a | ||
|
9feabe707f | ||
|
704cf14383 | ||
|
2fdda8e448 | ||
|
b8899b39ec | ||
|
9d7e0514ff | ||
|
b607740dd1 | ||
|
238e9aabb1 | ||
|
f97e810429 | ||
|
0925a3cd19 | ||
|
a2fdb9d2f6 | ||
|
f6e56027b1 | ||
|
625da69fcb | ||
|
dcc7d559ee | ||
|
ecea6c9526 | ||
|
accc59aa1b | ||
|
8366e67fee | ||
|
003552d78c | ||
|
d4e42987e2 | ||
|
f80ffe279b | ||
|
ea22588649 | ||
|
fe8898c7f8 | ||
|
0d4cf32086 | ||
|
30087697e0 | ||
|
8dca3c84f8 | ||
|
0fc504fc4e | ||
|
25b872a9c8 | ||
|
a328bf58f4 | ||
|
f492609115 | ||
|
092ebf845d | ||
|
87b896879f | ||
|
10840ec170 | ||
|
b3e929d14b | ||
|
8cf3dbb682 | ||
|
7d2b9447d0 | ||
|
4b910426ff | ||
|
a87c273903 | ||
|
1508e08ea5 | ||
|
48f7997a77 | ||
|
5bf739b917 | ||
|
be4a4be7a3 | ||
|
4cbbb80bc3 | ||
|
516e56bfaa | ||
|
0b98f19f2c | ||
|
f11fd2fee1 | ||
|
67193bca3d | ||
|
7cef5ac217 | ||
|
1713841d0b | ||
|
721d0fb2a8 | ||
|
74bcd82c3d | ||
|
65d91b7cbb | ||
|
5599490aa2 | ||
|
b39de171c8 | ||
|
0981287c62 | ||
|
2016eea212 | ||
|
a6e6ce16b1 | ||
|
b7d4ff9c21 | ||
|
7833d9935c | ||
|
79ed89e487 | ||
|
38af1b2a5d | ||
|
36d60fa8a8 | ||
|
b1fe5940fa | ||
|
cd1a8e2c42 | ||
|
be28b42bfa | ||
|
4dadfd199d | ||
|
39579b6e5d | ||
|
9d37ac9955 | ||
|
9c0850ff50 | ||
|
78dff3d510 | ||
|
2787ba0809 | ||
|
277f3ff47b | ||
|
5bd14bcccf | ||
|
bbc049c838 | ||
|
d25fe58574 | ||
|
8eb0130200 | ||
|
fae631c026 | ||
|
08a1f74748 | ||
|
537c20ed87 | ||
|
3a46f02682 | ||
|
e587c005de | ||
|
bc110cfe8f | ||
|
3b67863914 | ||
|
a2873096c8 | ||
|
5716202e45 | ||
|
fe27206926 | ||
|
a1755364e1 | ||
|
e7e687c8ec | ||
|
5423c21be0 | ||
|
f39dde121a | ||
|
18a24d75ef | ||
|
3cb559994e | ||
|
c1b8ad7232 | ||
|
fabb31e1bc | ||
|
f120c8d6c7 | ||
|
f24626e139 | ||
|
43091a26ce | ||
|
8b24878023 | ||
|
5b2902fcbc | ||
|
16baca5eeb | ||
|
d901a86165 | ||
|
75e4758936 | ||
|
cc39cf97dd | ||
|
4531c924da | ||
|
fb3d82ccb9 | ||
|
fdd4b40c34 | ||
|
daa1727e2b | ||
|
3fdfc06a1e | ||
|
ecadfdd98e | ||
|
6b44545d37 | ||
|
799e6be2eb | ||
|
621105df9a | ||
|
bf92099486 | ||
|
5b3ffd5141 | ||
|
5e6897b278 | ||
|
e92bcb00f6 | ||
|
8d3f096a97 | ||
|
d7daa86434 | ||
|
bd0af1b300 | ||
|
7d2395ddb7 | ||
|
fc0d14c1b5 | ||
|
676dd0d664 | ||
|
9d5961e224 | ||
|
277342f167 | ||
|
8574751a07 | ||
|
f8639fe938 | ||
|
5f8610b28f | ||
|
22d64553c9 | ||
|
ea4238e860 | ||
|
11e2915621 | ||
|
6892c08e9b | ||
|
b2c1098316 | ||
|
f7b54c2415 | ||
|
f235ab8cf4 | ||
|
18795844d8 | ||
|
a414b57d54 | ||
|
8f6aefb591 | ||
|
768a24c375 | ||
|
b9f3410d8b | ||
|
ca9fd08991 | ||
|
4e7f914e92 | ||
|
266031a6be | ||
|
8441d0f60f | ||
|
d1fda28d2e | ||
|
011ba1d9ae | ||
|
3c85d5201f | ||
|
f320cb0d7a | ||
|
4c0edd0461 | ||
|
c8dde63227 | ||
|
69901c1314 | ||
|
39fec25ae0 | ||
|
dc92808335 | ||
|
ca9036ee1d | ||
|
e240f0b372 | ||
|
8366e2fd89 | ||
|
9f5c4ead15 | ||
|
66d5271ada | ||
|
ba869a330f | ||
|
8965b8a18d | ||
|
bf48df92c1 | ||
|
e763aa04bd | ||
|
36fba4826f | ||
|
4813eec308 | ||
|
aace993842 | ||
|
834cf384f6 | ||
|
a9b586d338 | ||
|
44f295110b | ||
|
bdd895b8da | ||
|
a3139dd9d4 | ||
|
4cf16fa8d1 | ||
|
3bea9255e7 | ||
|
dad427461d | ||
|
a4bfd0b0aa | ||
|
be555895b2 | ||
|
7c6357cc45 | ||
|
657b002a81 | ||
|
9cd1be8f93 | ||
|
7eab33de08 | ||
|
8a2fbf6592 | ||
|
1436dc58f5 | ||
|
14647fb5f0 | ||
|
3ee7fe64ba | ||
|
181b88dc75 | ||
|
aa4ac87fd4 | ||
|
b45c2fb1d0 | ||
|
6107878f4e | ||
|
aab8e36e78 | ||
|
c784e5780e | ||
|
95fd3824da | ||
|
201cc67e05 | ||
|
76594d5dde | ||
|
ca99d484fc | ||
|
33f330256b | ||
|
af53dfbfab | ||
|
f5817063b7 | ||
|
25f8e0cc57 | ||
|
5708098256 | ||
|
7126aa9514 | ||
|
f1af2972e2 | ||
|
e6b3e64534 | ||
|
d9a86158f4 | ||
|
ad7b29cc1d | ||
|
118a22d010 | ||
|
9725b8e17c | ||
|
f897b683c7 | ||
|
82bc6973fe | ||
|
c37bc307e2 | ||
|
b5289d5f0e | ||
|
de2cc9708d | ||
|
f047297995 | ||
|
3ab5514697 | ||
|
81410fb404 | ||
|
e873cafdc4 | ||
|
effc96e92b | ||
|
5849d07497 | ||
|
57a4044eb0 | ||
|
bb51da8297 | ||
|
75a5161650 | ||
|
a3f9cd2c26 | ||
|
946fb09455 | ||
|
e2d15f4082 | ||
|
32189d27c8 | ||
|
9f34aebdaa | ||
|
b606936eb7 | ||
|
98c88fa58e | ||
|
3426e99b8b | ||
|
64d6c7bb65 | ||
|
0e2a43ab4d | ||
|
c993831a04 | ||
|
d4799e6aa3 | ||
|
a93bb6853b | ||
|
eb952d77be | ||
|
f13e9ce5ed | ||
|
b36f333b2f | ||
|
f06b58dc91 | ||
|
089c463cfb | ||
|
9d6f3a89ef | ||
|
768d7fa196 | ||
|
9947dcd1da | ||
|
ad746627b3 | ||
|
397a15cb61 | ||
|
4351a26b4c | ||
|
12e84bda1e | ||
|
6d0f16920f | ||
|
dce2364672 | ||
|
dcdf4a0503 | ||
|
32cde1cb7d | ||
|
8f958ef723 | ||
|
8d9c66a638 | ||
|
be57ceb252 | ||
|
5e3d2401f5 | ||
|
2cd54a5933 | ||
|
8ebd6ad200 | ||
|
2e5b9fd4b2 | ||
|
e29d918ea5 | ||
|
fc97266dd4 | ||
|
59091ef2b7 | ||
|
47cd856fea | ||
|
5133675988 | ||
|
9484ee6690 | ||
|
bb06365c50 | ||
|
1f703dc341 | ||
|
00d4820bc1 | ||
|
9f6c2a583f | ||
|
8dbef6bbea | ||
|
fe0afb9883 | ||
|
2a66c33a4e | ||
|
ff7ba23477 | ||
|
05be33ccd4 | ||
|
56975db2ed | ||
|
2b85e7eac3 | ||
|
816703b8e1 | ||
|
f39a534fc0 | ||
|
246b4a57a4 | ||
|
04878c3ce1 | ||
|
3447f1ae53 | ||
|
a0bd2ce837 | ||
|
b6b9c8e5cc | ||
|
f01d86060a | ||
|
1fd652d3de | ||
|
647e6509a4 | ||
|
0c0eb8236d | ||
|
51fbd0698c | ||
|
245c19f5e9 | ||
|
aa27c9ace2 | ||
|
143423145c | ||
|
c556d1b37e | ||
|
8f61b68b2a | ||
|
058d40a72c | ||
|
71e46794b4 | ||
|
f37af9d98a | ||
|
7f453033a4 | ||
|
2fbbeb970b | ||
|
22595e6f92 | ||
|
01cb676f2c | ||
|
9e063b9fc8 | ||
|
9b4a81c0a4 | ||
|
c09c23eab1 | ||
|
d039ce1fb3 | ||
|
4f8bc73d1a | ||
|
3c4fe66d86 | ||
|
4bc24ece41 | ||
|
c1fffb9925 | ||
|
d6cc3d7374 | ||
|
5dfa1807a3 | ||
|
36b7edc342 | ||
|
de0c5f9133 | ||
|
cec771b593 | ||
|
5f70d1f9a7 | ||
|
95b24ba8a9 | ||
|
202ca88e23 | ||
|
14d44b2cd6 | ||
|
dda5bcbc8d | ||
|
5da41160bf | ||
|
a22fd7eb3b | ||
|
275cfb3a9c | ||
|
f17c7f0609 | ||
|
b7de18608d | ||
|
99abe52043 | ||
|
5f8e67d2b2 | ||
|
18de9cc5e5 | ||
|
90070f0dc5 | ||
|
1791495475 | ||
|
4b6f5b92b5 | ||
|
e7a035eefe | ||
|
d6c9391924 | ||
|
323c0657f8 | ||
|
6a74c57c3d | ||
|
e40d97e05e | ||
|
5d3f59df90 | ||
|
a00f852cf9 | ||
|
03c5714399 | ||
|
e1d42ba78c | ||
|
56529180eb | ||
|
ff286bd80c | ||
|
a47d8dbe56 | ||
|
829a47b187 | ||
|
4cb331b5ad | ||
|
b7703e6428 | ||
|
37d2e476df | ||
|
f448564073 | ||
|
ecce5265f5 | ||
|
fefa500963 | ||
|
966c6b308f | ||
|
1f7d681ddb | ||
|
dbd50fdff6 | ||
|
cfbd1c4c43 | ||
|
662ec32073 | ||
|
26855800a3 | ||
|
4600bb807c | ||
|
9538fa1d72 | ||
|
91b4c80d35 | ||
|
afb795b6f5 | ||
|
380cca2252 | ||
|
3357350628 | ||
|
c34150552f | ||
|
05686998bb | ||
|
7cbd89657f | ||
|
89573348b6 | ||
|
af1b3721fb | ||
|
95c3c45ec9 | ||
|
46ec6f498c | ||
|
ab7807cee5 | ||
|
1353c59f18 | ||
|
5d038552ae | ||
|
c69ce28b76 | ||
|
fefb4b23d0 | ||
|
4aa6ebee04 | ||
|
57461a59f3 | ||
|
81d08c4def | ||
|
22ff67c8f8 | ||
|
31449987c0 | ||
|
cff0527919 | ||
|
fce31447ed | ||
|
98118f5e95 | ||
|
dddbc799f9 | ||
|
83f6259594 | ||
|
0b68402c10 | ||
|
1d56c87a34 | ||
|
53231d94a9 | ||
|
76539bc700 | ||
|
d0d9921b42 | ||
|
c14c0f60a1 | ||
|
8180393bbc | ||
|
7f621416a1 | ||
|
6810192992 | ||
|
8ae604d473 | ||
|
0d349cb355 | ||
|
8f1d2ff070 | ||
|
46389e343b | ||
|
b9980330a5 | ||
|
0104c9fde6 | ||
|
99b67348b2 | ||
|
ceb50a7807 | ||
|
bd98ff6332 | ||
|
006436a18d | ||
|
730c9ce471 | ||
|
d959eeb97d | ||
|
312533fded | ||
|
82335027b7 | ||
|
1ec99e6b76 | ||
|
d325236f96 | ||
|
421265243c | ||
|
16899b9df1 | ||
|
9427b5e924 | ||
|
87a34b4306 | ||
|
56629d882e | ||
|
7c7a8190ab | ||
|
be4807d85c | ||
|
83b4cd7b39 | ||
|
ec33011255 | ||
|
29c6a9263d | ||
|
7e4fe23bf9 | ||
|
f12a8afd41 | ||
|
2e1551a2eb | ||
|
f8fab5c4f8 | ||
|
6b672cd0b9 | ||
|
191616e4e5 | ||
|
109824c9a8 | ||
|
fb86d8f8ff | ||
|
73f0e6e704 | ||
|
4d60a4cf4e | ||
|
8ffd6f2469 | ||
|
89ea8dbef2 | ||
|
e8e3ca0c3c | ||
|
83861fabde | ||
|
5ed85963a9 | ||
|
aa0c3dced8 | ||
|
fa0fcfb492 | ||
|
97e58a42f4 | ||
|
f88fe5d950 | ||
|
7a8b274a44 | ||
|
37849f8496 | ||
|
52c9a2c37f | ||
|
dd42d61d03 | ||
|
181d3a3808 | ||
|
bf6682d37f | ||
|
854d0c481f | ||
|
4a215821cd | ||
|
9621734adc | ||
|
853bd06841 | ||
|
3f2addb729 | ||
|
320dca19cb | ||
|
f092a92399 | ||
|
d00a955af9 | ||
|
d6bd018da4 | ||
|
8c88173b74 | ||
|
23947cf30b | ||
|
e52c181a2a | ||
|
6ebc2f3897 | ||
|
ef4ab601a9 | ||
|
26176d4c91 | ||
|
0612658ec7 | ||
|
34120f6eb8 | ||
|
7b4c1ec3ce | ||
|
da16474b25 | ||
|
7243c8ee56 | ||
|
ab85c5bb49 | ||
|
05f0cc787c | ||
|
164105acf2 | ||
|
c09b641860 | ||
|
08b52926c8 | ||
|
4eb96cfc4f | ||
|
2d6bfe1592 | ||
|
2424ac94c2 | ||
|
2640dfee93 | ||
|
916776bb53 | ||
|
13da8f9368 | ||
|
5f483acdd0 | ||
|
59e846d554 | ||
|
4bc693c17c | ||
|
d85fd3060a | ||
|
52c147c88e | ||
|
2a1835b165 | ||
|
88b2f3f0d1 | ||
|
6063f2f91f | ||
|
42d9e3a28f | ||
|
5243214a36 | ||
|
2af1c80fd5 | ||
|
8e03fee868 | ||
|
b8f6f09de8 | ||
|
7d2bd00f0c | ||
|
b58d6d38b5 | ||
|
d1dab23283 | ||
|
cf89a773da | ||
|
887d78171c | ||
|
ac55215fca | ||
|
d56da41679 | ||
|
894853b300 | ||
|
74d8a985e2 | ||
|
7e64a91720 | ||
|
aed44ef6b3 | ||
|
a8c6c3e2fa | ||
|
8cbc2ce18d | ||
|
a87fd6fcc7 | ||
|
21b22760a7 | ||
|
6c3753ac7f | ||
|
81fb0c5726 | ||
|
16572f90e3 | ||
|
e73203acb8 | ||
|
a262618809 | ||
|
0d11f0bd75 | ||
|
78874fa865 | ||
|
38fc5d680b | ||
|
4d4471480b | ||
|
aaa6468983 | ||
|
55838b574c | ||
|
684de9c7d0 | ||
|
3ca97223f2 | ||
|
d8ff79a2fa | ||
|
f4d39f2a12 | ||
|
19fcbc92a7 | ||
|
0539bd5280 | ||
|
86725847ed | ||
|
ffa6797958 | ||
|
e1e2829ef3 | ||
|
8e8f328bba | ||
|
5cb3735a57 | ||
|
28d6c3419b | ||
|
58a92dc3da | ||
|
72f61f4682 | ||
|
5c8779b155 | ||
|
6c913fa617 | ||
|
9c54c9a2bf | ||
|
e602ac3406 | ||
|
69e8da30e5 | ||
|
09af776b66 | ||
|
442e9d20e1 | ||
|
835614517b | ||
|
0309b06b54 | ||
|
f29b04b4d2 | ||
|
4146b45c6e | ||
|
066ea45ce0 | ||
|
95d11bd0d2 | ||
|
2831a78d0e | ||
|
df5e6aa58b | ||
|
3439e6c5c4 | ||
|
299dfe560a | ||
|
b8c12f6576 | ||
|
2e7367d647 | ||
|
50e7418d24 | ||
|
9999017953 | ||
|
2f91f87ad3 | ||
|
71410a5a1e | ||
|
cd8610cb24 | ||
|
ffcc47d8dd | ||
|
cf1a726198 | ||
|
a143f7bc43 | ||
|
66efb5ccf1 | ||
|
42d9e2e7dc | ||
|
fd6018f67a | ||
|
adffd402ea | ||
|
7a092271c5 | ||
|
5f63fdd8ad | ||
|
64e680d7ee | ||
|
1156f5e686 | ||
|
0daf77f313 | ||
|
cd2866eaec | ||
|
7a9768ffa6 | ||
|
7caa6cfe31 | ||
|
e513871fd5 | ||
|
6eab20e337 | ||
|
2d04c2dd4f | ||
|
f6da9e358a | ||
|
3e7c9bd485 | ||
|
06293b2489 | ||
|
f799a81c44 | ||
|
667f1b8b8c | ||
|
340f25bd42 | ||
|
b7eec3fc82 | ||
|
8975558595 | ||
|
7997298538 | ||
|
1c27aaab72 | ||
|
cf2ae788d7 | ||
|
5d3a67d324 | ||
|
b80a219d03 | ||
|
380e6628e0 | ||
|
2591a34db4 | ||
|
7a9208a8d7 | ||
|
cd940daaf4 | ||
|
f64ed6b878 | ||
|
8cdc795a44 | ||
|
685d18940a | ||
|
ec713ff5ae | ||
|
8ae193f638 | ||
|
07da21e633 | ||
|
8165cc11df | ||
|
2ed20eee4e | ||
|
8962b6d5c9 | ||
|
077374ac42 | ||
|
886abe36c9 | ||
|
d7bbda9659 | ||
|
6a0ab83684 | ||
|
46f3ec1d0a | ||
|
7c1402ef11 | ||
|
f231a08202 | ||
|
a0718ad8cb | ||
|
fd9c8df049 | ||
|
5f5fc513fa | ||
|
43532a2ffa | ||
|
ecddaa663b | ||
|
5f0d1d609e | ||
|
0b0b9c5d45 | ||
|
10651599dd | ||
|
2a383f8785 | ||
|
5aa0d3e05c | ||
|
a39898a5b3 | ||
|
44e374878c | ||
|
f299c4188b | ||
|
38cbf2f902 | ||
|
94bc5356b7 | ||
|
e39c2f4a96 | ||
|
9d2b3b2edb | ||
|
623cee61e6 | ||
|
2a2856e2dd | ||
|
8363faf358 | ||
|
80569c5f21 | ||
|
a33865e8c2 | ||
|
a2bc9d60a0 | ||
|
491af5a0cb | ||
|
fa7dc742d0 | ||
|
3d911557d1 | ||
|
23bad8fd9f | ||
|
028dd8be3e | ||
|
62859455f7 | ||
|
8fdcb600bc | ||
|
cedddd02da | ||
|
f43bd250a2 | ||
|
53984a059f | ||
|
59b00ad662 | ||
|
f676156ec7 | ||
|
23278e52db | ||
|
e8f2c09f08 | ||
|
d1db847612 | ||
|
7f0afe1244 | ||
|
6bb045f565 | ||
|
48750b0ef8 | ||
|
1b5cb3427e | ||
|
52502193c4 | ||
|
72337a0ab7 | ||
|
72cf3147b8 | ||
|
1628a0a4f0 | ||
|
299285a7bb | ||
|
8c2f763193 | ||
|
14e87ed4a1 | ||
|
a4a8abfdc0 | ||
|
fa1d1679f0 | ||
|
378b214a56 | ||
|
584d095295 | ||
|
11f1ce2d9f | ||
|
1e782781a6 | ||
|
b86a602ad4 | ||
|
4b53c2bca4 | ||
|
355afc082e | ||
|
14c66afecc | ||
|
0538af8875 | ||
|
1ef702479b | ||
|
09e9141e51 | ||
|
d23ea36c05 | ||
|
f4ab2dab4c | ||
|
65e4c052f1 | ||
|
2d6bc9aadc | ||
|
482213fbb3 | ||
|
06759234b6 | ||
|
40b61bbfe3 | ||
|
234f6c2f5e | ||
|
688442507e | ||
|
64de911e16 | ||
|
56647bb498 | ||
|
52b6f6b940 | ||
|
0574a40693 | ||
|
8d4f7ce84f | ||
|
80890e0f59 | ||
|
887b2fdb5e | ||
|
301598bac9 | ||
|
c9b3766fa3 | ||
|
63e1cba597 | ||
|
2d343c8f73 | ||
|
cb74c9bcde | ||
|
176006da29 | ||
|
66b77d2f53 | ||
|
62110dc2fc | ||
|
350fcc071e | ||
|
b38f68b3b0 | ||
|
becccca3d1 | ||
|
ba10bd7756 | ||
|
4b6b7f8343 | ||
|
a3d0889dab | ||
|
816c8295f1 | ||
|
f82d39e1b0 | ||
|
bb4993dc20 | ||
|
c0654f3caf | ||
|
c59a1be154 | ||
|
1de248fe38 | ||
|
6a59740f83 | ||
|
32e6ea314c | ||
|
18bbfdd341 | ||
|
f227f6a755 | ||
|
bf0e75e2a5 | ||
|
b93ad8840a | ||
|
482f1faa88 | ||
|
f5dc10e4ae | ||
|
677078350f | ||
|
d528c44974 | ||
|
133ca9c770 | ||
|
a38b33cd9c | ||
|
9dfbc1a7ff | ||
|
d2111c088b | ||
|
7bce2cd29d | ||
|
6977ffdbf9 | ||
|
c410599a52 | ||
|
2be8e8070a | ||
|
ace2879265 | ||
|
0ea56548e4 | ||
|
ce228f19dc | ||
|
9df366d943 | ||
|
253b7b763e | ||
|
201e714343 | ||
|
287604efd2 | ||
|
7623691a5f | ||
|
17e605e130 | ||
|
fe588e5722 | ||
|
700529fe06 | ||
|
f174c74094 | ||
|
f3e1eddc91 | ||
|
5e0fa21d60 | ||
|
dd4d458ca8 | ||
|
6d8fadd560 | ||
|
1dee0eed75 | ||
|
48347b49fd | ||
|
15bb0af1b3 | ||
|
627e221b65 | ||
|
f3de74f817 | ||
|
6e70ae6e95 | ||
|
5769b9244f | ||
|
8de9c46110 | ||
|
3cb1a9a5a9 | ||
|
c42a924df8 | ||
|
ff96cf154c | ||
|
7a652b07d5 | ||
|
b736691e0e | ||
|
44ad0f631c | ||
|
28411da83e | ||
|
1b4b10f8cd |
@@ -3,13 +3,15 @@ FROM freqtradeorg/freqtrade:develop
|
||||
# Install dependencies
|
||||
COPY requirements-dev.txt /freqtrade/
|
||||
RUN apt-get update \
|
||||
&& apt-get -y install git sudo vim \
|
||||
&& apt-get -y install git mercurial sudo vim \
|
||||
&& apt-get clean \
|
||||
&& pip install autopep8 -r docs/requirements-docs.txt -r requirements-dev.txt --no-cache-dir \
|
||||
&& useradd -u 1000 -U -m ftuser \
|
||||
&& mkdir -p /home/ftuser/.vscode-server /home/ftuser/.vscode-server-insiders /home/ftuser/commandhistory \
|
||||
&& echo "export PROMPT_COMMAND='history -a'" >> /home/ftuser/.bashrc \
|
||||
&& echo "export HISTFILE=~/commandhistory/.bash_history" >> /home/ftuser/.bashrc \
|
||||
&& mv /root/.local /home/ftuser/.local/ \
|
||||
&& chown ftuser:ftuser -R /home/ftuser/.local/ \
|
||||
&& chown ftuser: -R /home/ftuser/
|
||||
|
||||
USER ftuser
|
||||
|
@@ -7,8 +7,8 @@ services:
|
||||
dockerfile: ".devcontainer/Dockerfile"
|
||||
volumes:
|
||||
# Allow git usage within container
|
||||
- "/home/${USER}/.ssh:/home/ftuser/.ssh:ro"
|
||||
- "/home/${USER}/.gitconfig:/home/ftuser/.gitconfig:ro"
|
||||
- "${HOME}/.ssh:/home/ftuser/.ssh:ro"
|
||||
- "${HOME}/.gitconfig:/home/ftuser/.gitconfig:ro"
|
||||
- ..:/freqtrade:cached
|
||||
# Persist bash-history
|
||||
- freqtrade-vscode-server:/home/ftuser/.vscode-server
|
||||
|
164
.github/workflows/ci.yml
vendored
164
.github/workflows/ci.yml
vendored
@@ -14,43 +14,36 @@ on:
|
||||
- cron: '0 5 * * 4'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
build_linux:
|
||||
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ ubuntu-18.04, macos-latest ]
|
||||
python-version: [3.7, 3.8]
|
||||
os: [ ubuntu-18.04, ubuntu-20.04 ]
|
||||
python-version: [3.7, 3.8, 3.9]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v1
|
||||
uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Cache_dependencies
|
||||
uses: actions/cache@v1
|
||||
uses: actions/cache@v2
|
||||
id: cache
|
||||
with:
|
||||
path: ~/dependencies/
|
||||
key: ${{ runner.os }}-dependencies
|
||||
|
||||
- name: pip cache (linux)
|
||||
uses: actions/cache@preview
|
||||
uses: actions/cache@v2
|
||||
if: startsWith(matrix.os, 'ubuntu')
|
||||
with:
|
||||
path: ~/.cache/pip
|
||||
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
||||
|
||||
- name: pip cache (macOS)
|
||||
uses: actions/cache@preview
|
||||
if: startsWith(matrix.os, 'macOS')
|
||||
with:
|
||||
path: ~/Library/Caches/pip
|
||||
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
||||
|
||||
- name: TA binary *nix
|
||||
if: steps.cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
@@ -68,9 +61,15 @@ jobs:
|
||||
- name: Tests
|
||||
run: |
|
||||
pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
||||
if: matrix.python-version != '3.9'
|
||||
|
||||
- name: Tests incl. ccxt compatibility tests
|
||||
run: |
|
||||
pytest --random-order --cov=freqtrade --cov-config=.coveragerc --longrun
|
||||
if: matrix.python-version == '3.9'
|
||||
|
||||
- name: Coveralls
|
||||
if: (startsWith(matrix.os, 'ubuntu') && matrix.python-version == '3.8')
|
||||
if: (startsWith(matrix.os, 'ubuntu-20') && matrix.python-version == '3.8')
|
||||
env:
|
||||
# Coveralls token. Not used as secret due to github not providing secrets to forked repositories
|
||||
COVERALLS_REPO_TOKEN: 6D1m0xupS3FgutfuGao8keFf9Hc0FpIXu
|
||||
@@ -80,20 +79,24 @@ jobs:
|
||||
|
||||
- name: Backtesting
|
||||
run: |
|
||||
cp config.json.example config.json
|
||||
cp config_bittrex.json.example config.json
|
||||
freqtrade create-userdir --userdir user_data
|
||||
freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
|
||||
|
||||
- name: Hyperopt
|
||||
run: |
|
||||
cp config.json.example config.json
|
||||
cp config_bittrex.json.example config.json
|
||||
freqtrade create-userdir --userdir user_data
|
||||
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --print-all
|
||||
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --print-all
|
||||
|
||||
- name: Flake8
|
||||
run: |
|
||||
flake8
|
||||
|
||||
- name: Sort imports (isort)
|
||||
run: |
|
||||
isort --check .
|
||||
|
||||
- name: Mypy
|
||||
run: |
|
||||
mypy freqtrade scripts
|
||||
@@ -109,6 +112,99 @@ jobs:
|
||||
channel: '#notifications'
|
||||
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||
|
||||
build_macos:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ macos-latest ]
|
||||
python-version: [3.7, 3.8, 3.9]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Cache_dependencies
|
||||
uses: actions/cache@v2
|
||||
id: cache
|
||||
with:
|
||||
path: ~/dependencies/
|
||||
key: ${{ runner.os }}-dependencies
|
||||
|
||||
- name: pip cache (macOS)
|
||||
uses: actions/cache@v2
|
||||
if: startsWith(matrix.os, 'macOS')
|
||||
with:
|
||||
path: ~/Library/Caches/pip
|
||||
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
||||
|
||||
- name: TA binary *nix
|
||||
if: steps.cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
cd build_helpers && ./install_ta-lib.sh ${HOME}/dependencies/; cd ..
|
||||
|
||||
- name: Installation - macOS
|
||||
run: |
|
||||
brew install hdf5 c-blosc
|
||||
python -m pip install --upgrade pip
|
||||
export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH
|
||||
export TA_LIBRARY_PATH=${HOME}/dependencies/lib
|
||||
export TA_INCLUDE_PATH=${HOME}/dependencies/include
|
||||
pip install -r requirements-dev.txt
|
||||
pip install -e .
|
||||
|
||||
- name: Tests
|
||||
run: |
|
||||
pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
||||
|
||||
- name: Coveralls
|
||||
if: (startsWith(matrix.os, 'ubuntu-20') && matrix.python-version == '3.8')
|
||||
env:
|
||||
# Coveralls token. Not used as secret due to github not providing secrets to forked repositories
|
||||
COVERALLS_REPO_TOKEN: 6D1m0xupS3FgutfuGao8keFf9Hc0FpIXu
|
||||
run: |
|
||||
# Allow failure for coveralls
|
||||
coveralls -v || true
|
||||
|
||||
- name: Backtesting
|
||||
run: |
|
||||
cp config_bittrex.json.example config.json
|
||||
freqtrade create-userdir --userdir user_data
|
||||
freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
|
||||
|
||||
- name: Hyperopt
|
||||
run: |
|
||||
cp config_bittrex.json.example config.json
|
||||
freqtrade create-userdir --userdir user_data
|
||||
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --print-all
|
||||
|
||||
- name: Flake8
|
||||
run: |
|
||||
flake8
|
||||
|
||||
- name: Sort imports (isort)
|
||||
run: |
|
||||
isort --check .
|
||||
|
||||
- name: Mypy
|
||||
run: |
|
||||
mypy freqtrade scripts
|
||||
|
||||
- name: Slack Notification
|
||||
uses: homoluctus/slatify@v1.8.0
|
||||
if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
|
||||
with:
|
||||
type: ${{ job.status }}
|
||||
job_name: '*Freqtrade CI ${{ matrix.os }}*'
|
||||
mention: 'here'
|
||||
mention_if: 'failure'
|
||||
channel: '#notifications'
|
||||
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||
|
||||
|
||||
build_windows:
|
||||
|
||||
runs-on: ${{ matrix.os }}
|
||||
@@ -121,7 +217,7 @@ jobs:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v1
|
||||
uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
@@ -142,15 +238,15 @@ jobs:
|
||||
|
||||
- name: Backtesting
|
||||
run: |
|
||||
cp config.json.example config.json
|
||||
cp config_bittrex.json.example config.json
|
||||
freqtrade create-userdir --userdir user_data
|
||||
freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
|
||||
|
||||
- name: Hyperopt
|
||||
run: |
|
||||
cp config.json.example config.json
|
||||
cp config_bittrex.json.example config.json
|
||||
freqtrade create-userdir --userdir user_data
|
||||
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --print-all
|
||||
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --print-all
|
||||
|
||||
- name: Flake8
|
||||
run: |
|
||||
@@ -172,7 +268,7 @@ jobs:
|
||||
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||
|
||||
docs_check:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
@@ -180,6 +276,17 @@ jobs:
|
||||
run: |
|
||||
./tests/test_docs.sh
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: 3.8
|
||||
|
||||
- name: Documentation build
|
||||
run: |
|
||||
pip install -r docs/requirements-docs.txt
|
||||
pip install mkdocs
|
||||
mkdocs build
|
||||
|
||||
- name: Slack Notification
|
||||
uses: homoluctus/slatify@v1.8.0
|
||||
if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
|
||||
@@ -190,7 +297,7 @@ jobs:
|
||||
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||
|
||||
cleanup-prior-runs:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- name: Cleanup previous runs on this branch
|
||||
uses: rokroskar/workflow-run-cleanup-action@v0.2.2
|
||||
@@ -200,8 +307,8 @@ jobs:
|
||||
|
||||
# Notify on slack only once - when CI completes (and after deploy) in case it's successfull
|
||||
notify-complete:
|
||||
needs: [ build, build_windows, docs_check ]
|
||||
runs-on: ubuntu-latest
|
||||
needs: [ build_linux, build_macos, build_windows, docs_check ]
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- name: Slack Notification
|
||||
uses: homoluctus/slatify@v1.8.0
|
||||
@@ -213,14 +320,15 @@ jobs:
|
||||
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||
|
||||
deploy:
|
||||
needs: [ build, build_windows, docs_check ]
|
||||
runs-on: ubuntu-18.04
|
||||
needs: [ build_linux, build_macos, build_windows, docs_check ]
|
||||
runs-on: ubuntu-20.04
|
||||
|
||||
if: (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'release') && github.repository == 'freqtrade/freqtrade'
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v1
|
||||
uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: 3.8
|
||||
|
||||
|
@@ -4,5 +4,5 @@ build:
|
||||
image: latest
|
||||
|
||||
python:
|
||||
version: 3.6
|
||||
setup_py_install: false
|
||||
version: 3.8
|
||||
setup_py_install: false
|
||||
|
10
.travis.yml
10
.travis.yml
@@ -1,9 +1,9 @@
|
||||
os:
|
||||
- linux
|
||||
dist: xenial
|
||||
dist: bionic
|
||||
language: python
|
||||
python:
|
||||
- 3.6
|
||||
- 3.8
|
||||
services:
|
||||
- docker
|
||||
env:
|
||||
@@ -26,14 +26,14 @@ jobs:
|
||||
# - coveralls || true
|
||||
name: pytest
|
||||
- script:
|
||||
- cp config.json.example config.json
|
||||
- cp config_bittrex.json.example config.json
|
||||
- freqtrade create-userdir --userdir user_data
|
||||
- freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
|
||||
name: backtest
|
||||
- script:
|
||||
- cp config.json.example config.json
|
||||
- cp config_bittrex.json.example config.json
|
||||
- freqtrade create-userdir --userdir user_data
|
||||
- freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt
|
||||
- freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily
|
||||
name: hyperopt
|
||||
- script: flake8
|
||||
name: flake8
|
||||
|
@@ -12,8 +12,7 @@ Few pointers for contributions:
|
||||
- New features need to contain unit tests, must conform to PEP8 (max-line-length = 100) and should be documented with the introduction PR.
|
||||
- PR's can be declared as `[WIP]` - which signify Work in Progress Pull Requests (which are not finished).
|
||||
|
||||
If you are unsure, discuss the feature on our [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE)
|
||||
or in a [issue](https://github.com/freqtrade/freqtrade/issues) before a PR.
|
||||
If you are unsure, discuss the feature on our [discord server](https://discord.gg/MA9v74M), on [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/zt-l9d9iqgl-9cVBIeBkCBa8j6upSmd_NA) or in a [issue](https://github.com/freqtrade/freqtrade/issues) before a PR.
|
||||
|
||||
## Getting started
|
||||
|
||||
@@ -65,6 +64,14 @@ Guide for installing them is [here](http://flake8.pycqa.org/en/latest/user/using
|
||||
mypy freqtrade
|
||||
```
|
||||
|
||||
### 4. Ensure all imports are correct
|
||||
|
||||
#### Run isort
|
||||
|
||||
``` bash
|
||||
isort .
|
||||
```
|
||||
|
||||
## (Core)-Committer Guide
|
||||
|
||||
### Process: Pull Requests
|
||||
|
33
Dockerfile
33
Dockerfile
@@ -1,24 +1,41 @@
|
||||
FROM python:3.8.6-slim-buster
|
||||
FROM python:3.8.6-slim-buster as base
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get -y install curl build-essential libssl-dev sqlite3 \
|
||||
&& apt-get clean \
|
||||
&& pip install --upgrade pip
|
||||
# Setup env
|
||||
ENV LANG C.UTF-8
|
||||
ENV LC_ALL C.UTF-8
|
||||
ENV PYTHONDONTWRITEBYTECODE 1
|
||||
ENV PYTHONFAULTHANDLER 1
|
||||
ENV PATH=/root/.local/bin:$PATH
|
||||
|
||||
# Prepare environment
|
||||
RUN mkdir /freqtrade
|
||||
WORKDIR /freqtrade
|
||||
|
||||
# Install dependencies
|
||||
FROM base as python-deps
|
||||
RUN apt-get update \
|
||||
&& apt-get -y install curl build-essential libssl-dev git \
|
||||
&& apt-get clean \
|
||||
&& pip install --upgrade pip
|
||||
|
||||
# Install TA-lib
|
||||
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 requirements-hyperopt.txt /freqtrade/
|
||||
RUN pip install numpy --no-cache-dir \
|
||||
&& pip install -r requirements-hyperopt.txt --no-cache-dir
|
||||
RUN pip install --user --no-cache-dir numpy \
|
||||
&& pip install --user --no-cache-dir -r requirements-hyperopt.txt
|
||||
|
||||
# Copy dependencies to runtime-image
|
||||
FROM base as runtime-image
|
||||
COPY --from=python-deps /usr/local/lib /usr/local/lib
|
||||
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||
|
||||
COPY --from=python-deps /root/.local /root/.local
|
||||
|
||||
|
||||
|
||||
# Install and execute
|
||||
COPY . /freqtrade/
|
||||
|
@@ -1,25 +1,43 @@
|
||||
FROM --platform=linux/arm/v7 python:3.7.7-slim-buster
|
||||
FROM --platform=linux/arm/v7 python:3.7.9-slim-buster as base
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get -y install curl build-essential libssl-dev libffi-dev libatlas3-base libgfortran5 sqlite3 \
|
||||
&& apt-get clean \
|
||||
&& pip install --upgrade pip \
|
||||
&& echo "[global]\nextra-index-url=https://www.piwheels.org/simple" > /etc/pip.conf
|
||||
# Setup env
|
||||
ENV LANG C.UTF-8
|
||||
ENV LC_ALL C.UTF-8
|
||||
ENV PYTHONDONTWRITEBYTECODE 1
|
||||
ENV PYTHONFAULTHANDLER 1
|
||||
ENV PATH=/root/.local/bin:$PATH
|
||||
|
||||
# Prepare environment
|
||||
RUN mkdir /freqtrade
|
||||
WORKDIR /freqtrade
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get -y install libatlas3-base curl sqlite3 \
|
||||
&& apt-get clean
|
||||
|
||||
# Install dependencies
|
||||
FROM base as python-deps
|
||||
RUN apt-get -y install build-essential libssl-dev libffi-dev libgfortran5 \
|
||||
&& apt-get clean \
|
||||
&& pip install --upgrade pip \
|
||||
&& echo "[global]\nextra-index-url=https://www.piwheels.org/simple" > /etc/pip.conf
|
||||
|
||||
# Install TA-lib
|
||||
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 numpy --no-cache-dir \
|
||||
&& pip install -r requirements.txt --no-cache-dir
|
||||
RUN pip install --user --no-cache-dir numpy \
|
||||
&& pip install --user --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy dependencies to runtime-image
|
||||
FROM base as runtime-image
|
||||
COPY --from=python-deps /usr/local/lib /usr/local/lib
|
||||
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||
|
||||
COPY --from=python-deps /root/.local /root/.local
|
||||
|
||||
# Install and execute
|
||||
COPY . /freqtrade/
|
||||
|
@@ -1,5 +1,4 @@
|
||||
include LICENSE
|
||||
include README.md
|
||||
include config.json.example
|
||||
recursive-include freqtrade *.py
|
||||
recursive-include freqtrade/templates/ *.j2 *.ipynb
|
||||
|
38
README.md
38
README.md
@@ -37,7 +37,7 @@ 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] **Based on Python 3.7+**: 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.
|
||||
@@ -55,9 +55,8 @@ Please find the complete documentation on our [website](https://www.freqtrade.io
|
||||
Freqtrade provides a Linux/macOS script to install all dependencies and help you to configure the bot.
|
||||
|
||||
```bash
|
||||
git clone git@github.com:freqtrade/freqtrade.git
|
||||
git clone -b develop https://github.com/freqtrade/freqtrade.git
|
||||
cd freqtrade
|
||||
git checkout develop
|
||||
./setup.sh --install
|
||||
```
|
||||
|
||||
@@ -111,17 +110,17 @@ optional arguments:
|
||||
|
||||
Telegram is not mandatory. However, this is a great way to control your bot. More details and the full command list on our [documentation](https://www.freqtrade.io/en/latest/telegram-usage/)
|
||||
|
||||
- `/start`: Starts the trader
|
||||
- `/stop`: Stops the trader
|
||||
- `/status [table]`: Lists all open trades
|
||||
- `/count`: Displays number of open trades
|
||||
- `/start`: Starts the trader.
|
||||
- `/stop`: Stops the trader.
|
||||
- `/stopbuy`: Stop entering new trades.
|
||||
- `/status <trade_id>|[table]`: Lists all or specific open trades.
|
||||
- `/profit`: Lists cumulative profit from all finished trades
|
||||
- `/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
|
||||
- `/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
|
||||
|
||||
@@ -133,12 +132,13 @@ The project is currently setup in two main branches:
|
||||
|
||||
## Support
|
||||
|
||||
### Help / Slack
|
||||
### Help / Discord / Slack
|
||||
|
||||
For any questions not covered by the documentation or for further
|
||||
information about the bot, we encourage you to join our slack channel.
|
||||
For any questions not covered by the documentation or for further information about the bot, or to simply engage with like-minded individuals, we encourage you to join our slack channel.
|
||||
|
||||
- [Click here to join Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE).
|
||||
Please check out our [discord server](https://discord.gg/MA9v74M).
|
||||
|
||||
You can also join our [Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/zt-l9d9iqgl-9cVBIeBkCBa8j6upSmd_NA).
|
||||
|
||||
### [Bugs / Issues](https://github.com/freqtrade/freqtrade/issues?q=is%3Aissue)
|
||||
|
||||
@@ -166,10 +166,10 @@ 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?
|
||||
Coding is not a necessity to contribute - maybe start with improving our documentation?
|
||||
Issues labeled [good first issue](https://github.com/freqtrade/freqtrade/labels/good%20first%20issue) can be good first contributions, and will help get you familiar with the codebase.
|
||||
|
||||
**Note** before starting any major new feature work, *please open an issue describing what you are planning to do* or talk to us on [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE). This will ensure that interested parties can give valuable feedback on the feature, and let others know that you are working on it.
|
||||
**Note** before starting any major new feature work, *please open an issue describing what you are planning to do* or talk to us on [discord](https://discord.gg/MA9v74M) or [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/zt-k9o2v5ut-jX8Mc4CwNM8CDc2Dyg96YA). 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 `stable`.
|
||||
|
||||
@@ -177,7 +177,7 @@ Issues labeled [good first issue](https://github.com/freqtrade/freqtrade/labels/
|
||||
|
||||
### Up-to-date clock
|
||||
|
||||
The clock must be accurate, syncronized to a NTP server very frequently to avoid problems with communication to the exchanges.
|
||||
The clock must be accurate, synchronized to a NTP server very frequently to avoid problems with communication to the exchanges.
|
||||
|
||||
### Min hardware required
|
||||
|
||||
@@ -187,7 +187,7 @@ To run this bot we recommend you a cloud instance with a minimum of:
|
||||
|
||||
### Software requirements
|
||||
|
||||
- [Python 3.6.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
||||
- [Python 3.7.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
||||
- [pip](https://pip.pypa.io/en/stable/installing/)
|
||||
- [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
- [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html)
|
||||
|
Binary file not shown.
Binary file not shown.
BIN
build_helpers/TA_Lib-0.4.19-cp37-cp37m-win_amd64.whl
Normal file
BIN
build_helpers/TA_Lib-0.4.19-cp37-cp37m-win_amd64.whl
Normal file
Binary file not shown.
BIN
build_helpers/TA_Lib-0.4.19-cp38-cp38-win_amd64.whl
Normal file
BIN
build_helpers/TA_Lib-0.4.19-cp38-cp38-win_amd64.whl
Normal file
Binary file not shown.
@@ -7,10 +7,10 @@ python -m pip install --upgrade pip
|
||||
$pyv = python -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"
|
||||
|
||||
if ($pyv -eq '3.7') {
|
||||
pip install build_helpers\TA_Lib-0.4.18-cp37-cp37m-win_amd64.whl
|
||||
pip install build_helpers\TA_Lib-0.4.19-cp37-cp37m-win_amd64.whl
|
||||
}
|
||||
if ($pyv -eq '3.8') {
|
||||
pip install build_helpers\TA_Lib-0.4.18-cp38-cp38-win_amd64.whl
|
||||
pip install build_helpers\TA_Lib-0.4.19-cp38-cp38-win_amd64.whl
|
||||
}
|
||||
|
||||
pip install -r requirements-dev.txt
|
||||
|
@@ -30,7 +30,7 @@ if [ $? -ne 0 ]; then
|
||||
fi
|
||||
|
||||
# Run backtest
|
||||
docker run --rm -v $(pwd)/config.json.example:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy DefaultStrategy
|
||||
docker run --rm -v $(pwd)/config_bittrex.json.example:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy DefaultStrategy
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "failed running backtest"
|
||||
|
@@ -84,12 +84,13 @@
|
||||
"enabled": false,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8080,
|
||||
"verbosity": "info",
|
||||
"verbosity": "error",
|
||||
"jwt_secret_key": "somethingrandom",
|
||||
"CORS_origins": [],
|
||||
"username": "",
|
||||
"password": ""
|
||||
"username": "freqtrader",
|
||||
"password": "SuperSecurePassword"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"forcebuy_enable": false,
|
||||
"internals": {
|
||||
|
@@ -5,15 +5,15 @@
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"timeframe": "5m",
|
||||
"dry_run": false,
|
||||
"dry_run": true,
|
||||
"cancel_open_orders_on_exit": false,
|
||||
"unfilledtimeout": {
|
||||
"buy": 10,
|
||||
"sell": 30
|
||||
},
|
||||
"bid_strategy": {
|
||||
"ask_last_balance": 0.0,
|
||||
"use_order_book": false,
|
||||
"ask_last_balance": 0.0,
|
||||
"order_book_top": 1,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
@@ -79,12 +79,13 @@
|
||||
"enabled": false,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8080,
|
||||
"verbosity": "info",
|
||||
"verbosity": "error",
|
||||
"jwt_secret_key": "somethingrandom",
|
||||
"CORS_origins": [],
|
||||
"username": "",
|
||||
"password": ""
|
||||
"username": "freqtrader",
|
||||
"password": "SuperSecurePassword"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"forcebuy_enable": false,
|
||||
"internals": {
|
@@ -7,7 +7,7 @@
|
||||
"amount_reserve_percent": 0.05,
|
||||
"amend_last_stake_amount": false,
|
||||
"last_stake_amount_min_ratio": 0.5,
|
||||
"dry_run": false,
|
||||
"dry_run": true,
|
||||
"cancel_open_orders_on_exit": false,
|
||||
"timeframe": "5m",
|
||||
"trailing_stop": false,
|
||||
@@ -42,6 +42,7 @@
|
||||
"order_book_max": 1,
|
||||
"use_sell_signal": true,
|
||||
"sell_profit_only": false,
|
||||
"sell_profit_offset": 0.0,
|
||||
"ignore_roi_if_buy_signal": false
|
||||
},
|
||||
"order_types": {
|
||||
@@ -67,10 +68,43 @@
|
||||
{"method": "AgeFilter", "min_days_listed": 10},
|
||||
{"method": "PrecisionFilter"},
|
||||
{"method": "PriceFilter", "low_price_ratio": 0.01, "min_price": 0.00000010},
|
||||
{"method": "SpreadFilter", "max_spread_ratio": 0.005}
|
||||
{"method": "SpreadFilter", "max_spread_ratio": 0.005},
|
||||
{
|
||||
"method": "RangeStabilityFilter",
|
||||
"lookback_days": 10,
|
||||
"min_rate_of_change": 0.01,
|
||||
"refresh_period": 1440
|
||||
}
|
||||
],
|
||||
"protections": [
|
||||
{
|
||||
"method": "StoplossGuard",
|
||||
"lookback_period_candles": 60,
|
||||
"trade_limit": 4,
|
||||
"stop_duration_candles": 60,
|
||||
"only_per_pair": false
|
||||
},
|
||||
{
|
||||
"method": "CooldownPeriod",
|
||||
"stop_duration_candles": 20
|
||||
},
|
||||
{
|
||||
"method": "MaxDrawdown",
|
||||
"lookback_period_candles": 200,
|
||||
"trade_limit": 20,
|
||||
"stop_duration_candles": 10,
|
||||
"max_allowed_drawdown": 0.2
|
||||
},
|
||||
{
|
||||
"method": "LowProfitPairs",
|
||||
"lookback_period_candles": 360,
|
||||
"trade_limit": 1,
|
||||
"stop_duration_candles": 2,
|
||||
"required_profit": 0.02
|
||||
}
|
||||
],
|
||||
"exchange": {
|
||||
"name": "bittrex",
|
||||
"name": "binance",
|
||||
"sandbox": false,
|
||||
"key": "your_exchange_key",
|
||||
"secret": "your_exchange_secret",
|
||||
@@ -82,16 +116,21 @@
|
||||
"aiohttp_trust_env": false
|
||||
},
|
||||
"pair_whitelist": [
|
||||
"ALGO/BTC",
|
||||
"ATOM/BTC",
|
||||
"BAT/BTC",
|
||||
"BCH/BTC",
|
||||
"BRD/BTC",
|
||||
"EOS/BTC",
|
||||
"ETH/BTC",
|
||||
"IOTA/BTC",
|
||||
"LINK/BTC",
|
||||
"LTC/BTC",
|
||||
"ETC/BTC",
|
||||
"DASH/BTC",
|
||||
"ZEC/BTC",
|
||||
"XLM/BTC",
|
||||
"NXT/BTC",
|
||||
"TRX/BTC",
|
||||
"ADA/BTC",
|
||||
"XMR/BTC"
|
||||
"NEO/BTC",
|
||||
"NXS/BTC",
|
||||
"XMR/BTC",
|
||||
"XRP/BTC",
|
||||
"XTZ/BTC"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"DOGE/BTC"
|
||||
@@ -114,7 +153,7 @@
|
||||
"remove_pumps": false
|
||||
},
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"enabled": false,
|
||||
"token": "your_telegram_token",
|
||||
"chat_id": "your_telegram_chat_id",
|
||||
"notification_settings": {
|
||||
@@ -131,12 +170,14 @@
|
||||
"enabled": false,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8080,
|
||||
"verbosity": "info",
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "somethingrandom",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "SuperSecurePassword"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"db_url": "sqlite:///tradesv3.sqlite",
|
||||
"initial_state": "running",
|
||||
"forcebuy_enable": false,
|
||||
|
@@ -27,12 +27,11 @@
|
||||
"use_sell_signal": true,
|
||||
"sell_profit_only": false,
|
||||
"ignore_roi_if_buy_signal": false
|
||||
|
||||
},
|
||||
"exchange": {
|
||||
"name": "kraken",
|
||||
"key": "",
|
||||
"secret": "",
|
||||
"key": "your_exchange_key",
|
||||
"secret": "your_exchange_key",
|
||||
"ccxt_config": {"enableRateLimit": true},
|
||||
"ccxt_async_config": {
|
||||
"enableRateLimit": true,
|
||||
@@ -90,12 +89,13 @@
|
||||
"enabled": false,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8080,
|
||||
"verbosity": "info",
|
||||
"verbosity": "error",
|
||||
"jwt_secret_key": "somethingrandom",
|
||||
"CORS_origins": [],
|
||||
"username": "",
|
||||
"password": ""
|
||||
"username": "freqtrader",
|
||||
"password": "SuperSecurePassword"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"forcebuy_enable": false,
|
||||
"internals": {
|
||||
|
@@ -9,7 +9,7 @@ services:
|
||||
# Build step - only needed when additional dependencies are needed
|
||||
# build:
|
||||
# context: .
|
||||
# dockerfile: "./Dockerfile.technical"
|
||||
# dockerfile: "./docker/Dockerfile.technical"
|
||||
restart: unless-stopped
|
||||
container_name: freqtrade
|
||||
volumes:
|
||||
|
@@ -5,6 +5,3 @@ FROM freqtradeorg/freqtrade:${sourceimage}
|
||||
COPY requirements-plot.txt /freqtrade/
|
||||
|
||||
RUN pip install -r requirements-plot.txt --no-cache-dir
|
||||
|
||||
# Empty the ENTRYPOINT to allow all commands
|
||||
ENTRYPOINT []
|
||||
|
@@ -27,9 +27,9 @@ class MyAwesomeHyperOpt2(MyAwesomeHyperOpt):
|
||||
and then quickly switch between hyperopt classes, running optimization process with hyperopt class you need in each particular case:
|
||||
|
||||
```
|
||||
$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt ...
|
||||
$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --strategy MyAwesomeStrategy ...
|
||||
or
|
||||
$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt2 ...
|
||||
$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt2 --hyperopt-loss SharpeHyperOptLossDaily --strategy MyAwesomeStrategy ...
|
||||
```
|
||||
|
||||
## Creating and using a custom loss function
|
||||
@@ -77,7 +77,7 @@ Currently, the arguments are:
|
||||
|
||||
* `results`: DataFrame containing the result
|
||||
The following columns are available in results (corresponds to the output-file of backtesting when used with `--export trades`):
|
||||
`pair, profit_percent, profit_abs, open_time, close_time, open_index, close_index, trade_duration, open_at_end, open_rate, close_rate, sell_reason`
|
||||
`pair, profit_percent, profit_abs, open_date, open_rate, open_fee, close_date, close_rate, close_fee, amount, trade_duration, open_at_end, sell_reason`
|
||||
* `trade_count`: Amount of trades (identical to `len(results)`)
|
||||
* `min_date`: Start date of the hyperopting TimeFrame
|
||||
* `min_date`: End date of the hyperopting TimeFrame
|
||||
|
@@ -162,11 +162,16 @@ A backtesting result will look like that:
|
||||
|-----------------------+---------------------|
|
||||
| Backtesting from | 2019-01-01 00:00:00 |
|
||||
| Backtesting to | 2019-05-01 00:00:00 |
|
||||
| Max open trades | 3 |
|
||||
| | |
|
||||
| Total trades | 429 |
|
||||
| First trade | 2019-01-01 18:30:00 |
|
||||
| First trade Pair | EOS/USDT |
|
||||
| Total Profit % | 152.41% |
|
||||
| Trades per day | 3.575 |
|
||||
| | |
|
||||
| Best Pair | LSK/BTC 26.26% |
|
||||
| Worst Pair | ZEC/BTC -10.18% |
|
||||
| Best Trade | LSK/BTC 4.25% |
|
||||
| Worst Trade | ZEC/BTC -10.25% |
|
||||
| Best day | 25.27% |
|
||||
| Worst day | -30.67% |
|
||||
| Avg. Duration Winners | 4:23:00 |
|
||||
@@ -233,11 +238,16 @@ It contains some useful key metrics about performance of your strategy on backte
|
||||
|-----------------------+---------------------|
|
||||
| Backtesting from | 2019-01-01 00:00:00 |
|
||||
| Backtesting to | 2019-05-01 00:00:00 |
|
||||
| Max open trades | 3 |
|
||||
| | |
|
||||
| Total trades | 429 |
|
||||
| First trade | 2019-01-01 18:30:00 |
|
||||
| First trade Pair | EOS/USDT |
|
||||
| Total Profit % | 152.41% |
|
||||
| Trades per day | 3.575 |
|
||||
| | |
|
||||
| Best Pair | LSK/BTC 26.26% |
|
||||
| Worst Pair | ZEC/BTC -10.18% |
|
||||
| Best Trade | LSK/BTC 4.25% |
|
||||
| Worst Trade | ZEC/BTC -10.25% |
|
||||
| Best day | 25.27% |
|
||||
| Worst day | -30.67% |
|
||||
| Avg. Duration Winners | 4:23:00 |
|
||||
@@ -251,16 +261,17 @@ It contains some useful key metrics about performance of your strategy on backte
|
||||
|
||||
```
|
||||
|
||||
- `Total trades`: Identical to the total trades of the backtest output table.
|
||||
- `First trade`: First trade entered.
|
||||
- `First trade pair`: Which pair was part of the first trade.
|
||||
- `Backtesting from` / `Backtesting to`: Backtesting range (usually defined with the `--timerange` option).
|
||||
- `Max open trades`: Setting of `max_open_trades` (or `--max-open-trades`) - to clearly see settings for this.
|
||||
- `Total trades`: Identical to the total trades of the backtest output table.
|
||||
- `Total Profit %`: Total profit per stake amount. Aligned to the TOTAL column of the first table.
|
||||
- `Trades per day`: Total trades divided by the backtesting duration in days (this will give you information about how many trades to expect from the strategy).
|
||||
- `Best Pair` / `Worst Pair`: Best and worst performing pair, and it's corresponding `Cum Profit %`.
|
||||
- `Best Trade` / `Worst Trade`: Biggest winning trade and biggest losing trade
|
||||
- `Best day` / `Worst day`: Best and worst day based on daily profit.
|
||||
- `Avg. Duration Winners` / `Avg. Duration Loser`: Average durations for winning and losing trades.
|
||||
- `Max Drawdown`: Maximum drawdown experienced. For example, the value of 50% means that from highest to subsequent lowest point, a 50% drop was experienced).
|
||||
- `Drawdown Start` / `Drawdown End`: Start and end datetimes for this largest drawdown (can also be visualized via the `plot-dataframe` sub-command).
|
||||
- `Drawdown Start` / `Drawdown End`: Start and end datetime for this largest drawdown (can also be visualized via the `plot-dataframe` sub-command).
|
||||
- `Market change`: Change of the market during the backtest period. Calculated as average of all pairs changes from the first to the last candle using the "close" column.
|
||||
|
||||
### Assumptions made by backtesting
|
||||
@@ -268,18 +279,24 @@ It contains some useful key metrics about performance of your strategy on backte
|
||||
Since backtesting lacks some detailed information about what happens within a candle, it needs to take a few assumptions:
|
||||
|
||||
- Buys happen at open-price
|
||||
- Sell signal sells happen at open-price of the following candle
|
||||
- Low happens before high for stoploss, protecting capital first
|
||||
- Sell-signal sells happen at open-price of the consecutive candle
|
||||
- Sell-signal is favored over Stoploss, because sell-signals are assumed to trigger on candle's open
|
||||
- ROI
|
||||
- sells are compared to high - but the ROI value is used (e.g. ROI = 2%, high=5% - so the sell will be at 2%)
|
||||
- sells are never "below the candle", so a ROI of 2% may result in a sell at 2.4% if low was at 2.4% profit
|
||||
- Forcesells caused by `<N>=-1` ROI entries use low as sell value, unless N falls on the candle open (e.g. `120: -1` for 1h candles)
|
||||
- Stoploss sells happen exactly at stoploss price, even if low was lower
|
||||
- Stoploss sells happen exactly at stoploss price, even if low was lower, but the loss will be `2 * fees` higher than the stoploss price
|
||||
- Stoploss is evaluated before ROI within one candle. So you can often see more trades with the `stoploss` sell reason comparing to the results obtained with the same strategy in the Dry Run/Live Trade modes
|
||||
- Low happens before high for stoploss, protecting capital first
|
||||
- Trailing stoploss
|
||||
- High happens first - adjusting stoploss
|
||||
- Low uses the adjusted stoploss (so sells with large high-low difference are backtested correctly)
|
||||
- ROI applies before trailing-stop, ensuring profits are "top-capped" at ROI if both ROI and trailing stop applies
|
||||
- Sell-reason does not explain if a trade was positive or negative, just what triggered the sell (this can look odd if negative ROI values are used)
|
||||
- Stoploss (and trailing stoploss) is evaluated before ROI within one candle. So you can often see more trades with the `stoploss` and/or `trailing_stop` sell reason comparing to the results obtained with the same strategy in the Dry Run/Live Trade modes.
|
||||
- Evaluation sequence (if multiple signals happen on the same candle)
|
||||
- ROI (if not stoploss)
|
||||
- Sell-signal
|
||||
- Stoploss
|
||||
|
||||
Taking these assumptions, backtesting tries to mirror real trading as closely as possible. However, backtesting will **never** replace running a strategy in dry-run mode.
|
||||
Also, keep in mind that past results don't guarantee future success.
|
||||
|
@@ -49,8 +49,9 @@ This loop will be repeated again and again until the bot is stopped.
|
||||
[backtesting](backtesting.md) or [hyperopt](hyperopt.md) do only part of the above logic, since most of the trading operations are fully simulated.
|
||||
|
||||
* Load historic data for configured pairlist.
|
||||
* Calculate indicators (calls `populate_indicators()`).
|
||||
* Calls `populate_buy_trend()` and `populate_sell_trend()`
|
||||
* Calls `bot_loop_start()` once.
|
||||
* Calculate indicators (calls `populate_indicators()` once per pair).
|
||||
* Calculate buy / sell signals (calls `populate_buy_trend()` and `populate_sell_trend()` once per pair)
|
||||
* Loops per candle simulating entry and exit points.
|
||||
* Generate backtest report output
|
||||
|
||||
|
@@ -213,9 +213,11 @@ Backtesting also uses the config specified via `-c/--config`.
|
||||
usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH] [-s NAME]
|
||||
[--strategy-path PATH] [-i TIMEFRAME]
|
||||
[--timerange TIMERANGE] [--max-open-trades INT]
|
||||
[--timerange TIMERANGE]
|
||||
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||
[--max-open-trades INT]
|
||||
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
|
||||
[--eps] [--dmmp]
|
||||
[--eps] [--dmmp] [--enable-protections]
|
||||
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
||||
[--export EXPORT] [--export-filename PATH]
|
||||
|
||||
@@ -226,6 +228,9 @@ optional arguments:
|
||||
`1d`).
|
||||
--timerange TIMERANGE
|
||||
Specify what timerange of data to use.
|
||||
--data-format-ohlcv {json,jsongz,hdf5}
|
||||
Storage format for downloaded candle (OHLCV) data.
|
||||
(default: `None`).
|
||||
--max-open-trades INT
|
||||
Override the value of the `max_open_trades`
|
||||
configuration setting.
|
||||
@@ -241,6 +246,10 @@ optional arguments:
|
||||
Disable applying `max_open_trades` during backtest
|
||||
(same as setting `max_open_trades` to a very high
|
||||
number).
|
||||
--enable-protections, --enableprotections
|
||||
Enable protections for backtesting.Will slow
|
||||
backtesting down by a considerable amount, but will
|
||||
include configured protections
|
||||
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
|
||||
Provide a space-separated list of strategies to
|
||||
backtest. Please note that ticker-interval needs to be
|
||||
@@ -296,14 +305,15 @@ to find optimal parameter values for your strategy.
|
||||
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||
[-i TIMEFRAME] [--timerange TIMERANGE]
|
||||
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||
[--max-open-trades INT]
|
||||
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
|
||||
[--hyperopt NAME] [--hyperopt-path PATH] [--eps]
|
||||
[-e INT]
|
||||
[--dmmp] [--enable-protections] [-e INT]
|
||||
[--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]]
|
||||
[--dmmp] [--print-all] [--no-color] [--print-json]
|
||||
[-j JOBS] [--random-state INT] [--min-trades INT]
|
||||
[--continue] [--hyperopt-loss NAME]
|
||||
[--print-all] [--no-color] [--print-json] [-j JOBS]
|
||||
[--random-state INT] [--min-trades INT]
|
||||
[--hyperopt-loss NAME]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
@@ -312,6 +322,9 @@ optional arguments:
|
||||
`1d`).
|
||||
--timerange TIMERANGE
|
||||
Specify what timerange of data to use.
|
||||
--data-format-ohlcv {json,jsongz,hdf5}
|
||||
Storage format for downloaded candle (OHLCV) data.
|
||||
(default: `None`).
|
||||
--max-open-trades INT
|
||||
Override the value of the `max_open_trades`
|
||||
configuration setting.
|
||||
@@ -327,14 +340,18 @@ optional arguments:
|
||||
--eps, --enable-position-stacking
|
||||
Allow buying the same pair multiple times (position
|
||||
stacking).
|
||||
-e INT, --epochs INT Specify number of epochs (default: 100).
|
||||
--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]
|
||||
Specify which parameters to hyperopt. Space-separated
|
||||
list.
|
||||
--dmmp, --disable-max-market-positions
|
||||
Disable applying `max_open_trades` during backtest
|
||||
(same as setting `max_open_trades` to a very high
|
||||
number).
|
||||
--enable-protections, --enableprotections
|
||||
Enable protections for backtesting.Will slow
|
||||
backtesting down by a considerable amount, but will
|
||||
include configured protections
|
||||
-e INT, --epochs INT Specify number of epochs (default: 100).
|
||||
--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]
|
||||
Specify which parameters to hyperopt. Space-separated
|
||||
list.
|
||||
--print-all Print all results, not only the best ones.
|
||||
--no-color Disable colorization of hyperopt results. May be
|
||||
useful if you are redirecting output to a file.
|
||||
@@ -349,18 +366,14 @@ optional arguments:
|
||||
reproducible hyperopt results.
|
||||
--min-trades INT Set minimal desired number of trades for evaluations
|
||||
in the hyperopt optimization path (default: 1).
|
||||
--continue Continue hyperopt from previous runs. By default,
|
||||
temporary files will be removed and hyperopt will
|
||||
start from scratch.
|
||||
--hyperopt-loss NAME Specify the class name of the hyperopt loss function
|
||||
class (IHyperOptLoss). Different functions can
|
||||
generate completely different results, since the
|
||||
target for optimization is different. Built-in
|
||||
Hyperopt-loss-functions are: DefaultHyperOptLoss,
|
||||
OnlyProfitHyperOptLoss, SharpeHyperOptLoss,
|
||||
SharpeHyperOptLossDaily, SortinoHyperOptLoss,
|
||||
SortinoHyperOptLossDaily.(default:
|
||||
`DefaultHyperOptLoss`).
|
||||
Hyperopt-loss-functions are:
|
||||
ShortTradeDurHyperOptLoss, OnlyProfitHyperOptLoss,
|
||||
SharpeHyperOptLoss, SharpeHyperOptLossDaily,
|
||||
SortinoHyperOptLoss, SortinoHyperOptLossDaily
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
|
@@ -16,8 +16,7 @@ In some advanced use cases, multiple configuration files can be specified and us
|
||||
If you used the [Quick start](installation.md/#quick-start) method for installing
|
||||
the bot, the installation script should have already created the default configuration file (`config.json`) for you.
|
||||
|
||||
If default configuration file is not created we recommend you to copy and use the `config.json.example` as a template
|
||||
for your bot configuration.
|
||||
If default configuration file is not created we recommend you to use `freqtrade new-config --config config.json` to generate a basic configuration file.
|
||||
|
||||
The Freqtrade configuration file is to be written in the JSON format.
|
||||
|
||||
@@ -59,8 +58,8 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
||||
| `trailing_stop_positive` | Changes stoploss once profit has been reached. More details in the [stoploss documentation](stoploss.md#trailing-stop-loss-custom-positive-loss). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Float
|
||||
| `trailing_stop_positive_offset` | Offset on when to apply `trailing_stop_positive`. Percentage value which should be positive. More details in the [stoploss documentation](stoploss.md#trailing-stop-loss-only-once-the-trade-has-reached-a-certain-offset). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0` (no offset).* <br> **Datatype:** Float
|
||||
| `trailing_only_offset_is_reached` | Only apply trailing stoploss when the offset is reached. [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||
| `unfilledtimeout.buy` | **Required.** How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
||||
| `unfilledtimeout.sell` | **Required.** How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
||||
| `unfilledtimeout.buy` | **Required.** How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
||||
| `unfilledtimeout.sell` | **Required.** How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
||||
| `bid_strategy.price_side` | Select the side of the spread the bot should look at to get the buy rate. [More information below](#buy-price-side).<br> *Defaults to `bid`.* <br> **Datatype:** String (either `ask` or `bid`).
|
||||
| `bid_strategy.ask_last_balance` | **Required.** Set the bidding price. More information [below](#buy-price-without-orderbook-enabled).
|
||||
| `bid_strategy.use_order_book` | Enable buying using the rates in [Order Book Bids](#buy-price-with-orderbook-enabled). <br> **Datatype:** Boolean
|
||||
@@ -72,8 +71,10 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
||||
| `ask_strategy.order_book_min` | Bot will scan from the top min to max Order Book Asks searching for a profitable rate. <br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
|
||||
| `ask_strategy.order_book_max` | Bot will scan from the top min to max Order Book Asks searching for a profitable rate. <br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
|
||||
| `ask_strategy.use_sell_signal` | Use sell signals produced by the strategy in addition to the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `true`.* <br> **Datatype:** Boolean
|
||||
| `ask_strategy.sell_profit_only` | Wait until the bot makes a positive profit before taking a sell decision. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||
| `ask_strategy.sell_profit_only` | Wait until the bot reaches `ask_strategy.sell_profit_offset` before taking a sell decision. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||
| `ask_strategy.sell_profit_offset` | Sell-signal is only active above this value. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0`.* <br> **Datatype:** Float (as ratio)
|
||||
| `ask_strategy.ignore_roi_if_buy_signal` | Do not sell if the buy signal is still active. This setting takes preference over `minimal_roi` and `use_sell_signal`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||
| `ask_strategy.ignore_buying_expired_candle_after` | Specifies the number of seconds until a buy signal is no longer used. <br> **Datatype:** Integer
|
||||
| `order_types` | Configure order-types depending on the action (`"buy"`, `"sell"`, `"stoploss"`, `"stoploss_on_exchange"`). [More information below](#understand-order_types). [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Dict
|
||||
| `order_time_in_force` | Configure time in force for buy and sell orders. [More information below](#understand-order_time_in_force). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
|
||||
| `exchange.name` | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename). <br> **Datatype:** String
|
||||
@@ -81,15 +82,17 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
||||
| `exchange.key` | API key to use for the exchange. Only required when you are in production mode.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||
| `exchange.secret` | API secret to use for the exchange. Only required when you are in production mode.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||
| `exchange.password` | API password to use for the exchange. Only required when you are in production mode and for exchanges that use password for API requests.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||
| `exchange.pair_whitelist` | List of pairs to use by the bot for trading and to check for potential trades during backtesting. Not used by VolumePairList (see [below](#pairlists-and-pairlist-handlers)). <br> **Datatype:** List
|
||||
| `exchange.pair_whitelist` | List of pairs to use by the bot for trading and to check for potential trades during backtesting. Supports regex pairs as `.*/BTC`. Not used by VolumePairList (see [below](#pairlists-and-pairlist-handlers)). <br> **Datatype:** List
|
||||
| `exchange.pair_blacklist` | List of pairs the bot must absolutely avoid for trading and backtesting (see [below](#pairlists-and-pairlist-handlers)). <br> **Datatype:** List
|
||||
| `exchange.ccxt_config` | Additional CCXT parameters passed to both ccxt instances (sync and async). This is usually the correct place for ccxt configurations. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict
|
||||
| `exchange.ccxt_sync_config` | Additional CCXT parameters passed to the regular (sync) ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict
|
||||
| `exchange.ccxt_async_config` | Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict
|
||||
| `exchange.markets_refresh_interval` | The interval in minutes in which markets are reloaded. <br>*Defaults to `60` minutes.* <br> **Datatype:** Positive Integer
|
||||
| `exchange.skip_pair_validation` | Skip pairlist validation on startup.<br>*Defaults to `false`<br> **Datatype:** Boolean
|
||||
| `edge.*` | Please refer to [edge configuration document](edge.md) for detailed explanation.
|
||||
| `experimental.block_bad_exchanges` | Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now. <br>*Defaults to `true`.* <br> **Datatype:** Boolean
|
||||
| `pairlists` | Define one or more pairlists to be used. [More information below](#pairlists-and-pairlist-handlers). <br>*Defaults to `StaticPairList`.* <br> **Datatype:** List of Dicts
|
||||
| `protections` | Define one or more protections to be used. [More information below](#protections). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** List of Dicts
|
||||
| `telegram.enabled` | Enable the usage of Telegram. <br> **Datatype:** Boolean
|
||||
| `telegram.token` | Your Telegram bot token. Only required if `telegram.enabled` is `true`. <br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||
| `telegram.chat_id` | Your personal Telegram account id. Only required if `telegram.enabled` is `true`. <br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||
@@ -106,6 +109,7 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
||||
| `api_server.verbosity` | Logging verbosity. `info` will print all RPC Calls, while "error" will only display errors. <br>**Datatype:** Enum, either `info` or `error`. Defaults to `info`.
|
||||
| `api_server.username` | Username for API server. See the [API Server documentation](rest-api.md) for more details. <br>**Keep it in secret, do not disclose publicly.**<br> **Datatype:** String
|
||||
| `api_server.password` | Password for API server. See the [API Server documentation](rest-api.md) for more details. <br>**Keep it in secret, do not disclose publicly.**<br> **Datatype:** String
|
||||
| `bot_name` | Name of the bot. Passed via API to a client - can be shown to distinguish / name bots.<br> *Defaults to `freqtrade`*<br> **Datatype:** String
|
||||
| `db_url` | Declares database URL to use. NOTE: This defaults to `sqlite:///tradesv3.dryrun.sqlite` if `dry_run` is `true`, and to `sqlite:///tradesv3.sqlite` for production instances. <br> **Datatype:** String, SQLAlchemy connect string
|
||||
| `initial_state` | Defines the initial application state. More information below. <br>*Defaults to `stopped`.* <br> **Datatype:** Enum, either `stopped` or `running`
|
||||
| `forcebuy_enable` | Enables the RPC Commands to force a buy. More information below. <br> **Datatype:** Boolean
|
||||
@@ -139,9 +143,12 @@ Values set in the configuration file always overwrite values set in the strategy
|
||||
* `stake_amount`
|
||||
* `unfilledtimeout`
|
||||
* `disable_dataframe_checks`
|
||||
* `protections`
|
||||
* `use_sell_signal` (ask_strategy)
|
||||
* `sell_profit_only` (ask_strategy)
|
||||
* `sell_profit_offset` (ask_strategy)
|
||||
* `ignore_roi_if_buy_signal` (ask_strategy)
|
||||
* `ignore_buying_expired_candle_after` (ask_strategy)
|
||||
|
||||
### Configuring amount per trade
|
||||
|
||||
@@ -176,7 +183,7 @@ In the example above this would mean:
|
||||
This option only applies with [Static stake amount](#static-stake-amount) - since [Dynamic stake amount](#dynamic-stake-amount) divides the balances evenly.
|
||||
|
||||
!!! Note
|
||||
The minimum last stake amount can be configured using `amend_last_stake_amount` - which defaults to 0.5 (50%). This means that the minimum stake amount that's ever used is `stake_amount * 0.5`. This avoids very low stake amounts, that are close to the minimum tradable amount for the pair and can be refused by the exchange.
|
||||
The minimum last stake amount can be configured using `last_stake_amount_min_ratio` - which defaults to 0.5 (50%). This means that the minimum stake amount that's ever used is `stake_amount * 0.5`. This avoids very low stake amounts, that are close to the minimum tradable amount for the pair and can be refused by the exchange.
|
||||
|
||||
#### Static stake amount
|
||||
|
||||
@@ -270,6 +277,22 @@ before asking the strategy if we should buy or a sell an asset. After each wait
|
||||
every opened trade wether or not we should sell, and for all the remaining pairs (either the dynamic list of pairs or
|
||||
the static list of pairs) if we should buy.
|
||||
|
||||
### Ignoring expired candles
|
||||
|
||||
When working with larger timeframes (for example 1h or more) and using a low `max_open_trades` value, the last candle can be processed as soon as a trade slot becomes available. When processing the last candle, this can lead to a situation where it may not be desirable to use the buy signal on that candle. For example, when using a condition in your strategy where you use a cross-over, that point may have passed too long ago for you to start a trade on it.
|
||||
|
||||
In these situations, you can enable the functionality to ignore candles that are beyond a specified period by setting `ask_strategy.ignore_buying_expired_candle_after` to a positive number, indicating the number of seconds after which the buy signal becomes expired.
|
||||
|
||||
For example, if your strategy is using a 1h timeframe, and you only want to buy within the first 5 minutes when a new candle comes in, you can add the following configuration to your strategy:
|
||||
|
||||
``` json
|
||||
"ask_strategy":{
|
||||
"ignore_buying_expired_candle_after": 300,
|
||||
"price_side": "bid",
|
||||
// ...
|
||||
},
|
||||
```
|
||||
|
||||
### Understand order_types
|
||||
|
||||
The `order_types` configuration parameter maps actions (`buy`, `sell`, `stoploss`, `emergencysell`) to order-types (`market`, `limit`, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.
|
||||
@@ -313,22 +336,21 @@ Configuration:
|
||||
}
|
||||
```
|
||||
|
||||
!!! Note
|
||||
!!! Note "Market order support"
|
||||
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."`
|
||||
`"Exchange <yourexchange> does not support market orders."` and the bot will refuse to start.
|
||||
|
||||
!!! Note
|
||||
Stoploss on exchange interval is not mandatory. Do not change its value if you are
|
||||
!!! Warning "Using market orders"
|
||||
Please carefully read the section [Market order pricing](#market-order-pricing) section when using market orders.
|
||||
|
||||
!!! Note "Stoploss on exchange"
|
||||
`stoploss_on_exchange_interval` is not mandatory. Do not change its value if you are
|
||||
unsure of what you are doing. For more information about how stoploss works please
|
||||
refer to [the stoploss documentation](stoploss.md).
|
||||
|
||||
!!! Note
|
||||
If `stoploss_on_exchange` is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order.
|
||||
|
||||
!!! Warning "Using market orders"
|
||||
Please read the section [Market order pricing](#market-order-pricing) section when using market orders.
|
||||
|
||||
!!! Warning "Warning: stoploss_on_exchange failures"
|
||||
If stoploss on exchange creation fails for some reason, then an "emergency sell" is initiated. By default, this will sell the asset using a market order. The order-type for the emergency-sell can be changed by setting the `emergencysell` value in the `order_types` dictionary - however this is not advised.
|
||||
|
||||
@@ -574,144 +596,8 @@ Assuming both buy and sell are using market orders, a configuration similar to t
|
||||
```
|
||||
|
||||
Obviously, if only one side is using limit orders, different pricing combinations can be used.
|
||||
|
||||
## Pairlists and Pairlist Handlers
|
||||
|
||||
Pairlist Handlers define the list of pairs (pairlist) that the bot should trade. They are configured in the `pairlists` section of the configuration settings.
|
||||
|
||||
In your configuration, you can use Static Pairlist (defined by the [`StaticPairList`](#static-pair-list) Pairlist Handler) and Dynamic Pairlist (defined by the [`VolumePairList`](#volume-pair-list) Pairlist Handler).
|
||||
|
||||
Additionaly, [`AgeFilter`](#agefilter), [`PrecisionFilter`](#precisionfilter), [`PriceFilter`](#pricefilter), [`ShuffleFilter`](#shufflefilter) and [`SpreadFilter`](#spreadfilter) act as Pairlist Filters, removing certain pairs and/or moving their positions in the pairlist.
|
||||
|
||||
If multiple Pairlist Handlers are used, they are chained and a combination of all Pairlist Handlers forms the resulting pairlist the bot uses for trading and backtesting. Pairlist Handlers are executed in the sequence they are configured. You should always configure either `StaticPairList` or `VolumePairList` as the starting Pairlist Handler.
|
||||
|
||||
Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the `pair_blacklist` configuration setting) are also always removed from the resulting pairlist.
|
||||
|
||||
### Available Pairlist Handlers
|
||||
|
||||
* [`StaticPairList`](#static-pair-list) (default, if not configured differently)
|
||||
* [`VolumePairList`](#volume-pair-list)
|
||||
* [`AgeFilter`](#agefilter)
|
||||
* [`PrecisionFilter`](#precisionfilter)
|
||||
* [`PriceFilter`](#pricefilter)
|
||||
* [`ShuffleFilter`](#shufflefilter)
|
||||
* [`SpreadFilter`](#spreadfilter)
|
||||
|
||||
!!! Tip "Testing pairlists"
|
||||
Pairlist configurations can be quite tricky to get right. Best use the [`test-pairlist`](utils.md#test-pairlist) utility subcommand to test your configuration quickly.
|
||||
|
||||
#### Static Pair List
|
||||
|
||||
By default, the `StaticPairList` method is used, which uses a statically defined pair whitelist from the configuration.
|
||||
|
||||
It uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`.
|
||||
|
||||
```json
|
||||
"pairlists": [
|
||||
{"method": "StaticPairList"}
|
||||
],
|
||||
```
|
||||
|
||||
#### Volume Pair List
|
||||
|
||||
`VolumePairList` employs sorting/filtering of pairs by their trading volume. It selects `number_assets` top pairs with sorting based on the `sort_key` (which can only be `quoteVolume`).
|
||||
|
||||
When used in the chain of Pairlist Handlers in a non-leading position (after StaticPairList and other Pairlist Filters), `VolumePairList` considers outputs of previous Pairlist Handlers, adding its sorting/selection of the pairs by the trading volume.
|
||||
|
||||
When used on the leading position of the chain of Pairlist Handlers, it does not consider `pair_whitelist` configuration setting, but selects the top assets from all available markets (with matching stake-currency) on the exchange.
|
||||
|
||||
The `refresh_period` setting allows to define the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes).
|
||||
|
||||
`VolumePairList` is based on the ticker data from exchange, as reported by the ccxt library:
|
||||
|
||||
* The `quoteVolume` is the amount of quote (stake) currency traded (bought or sold) in last 24 hours.
|
||||
|
||||
```json
|
||||
"pairlists": [{
|
||||
"method": "VolumePairList",
|
||||
"number_assets": 20,
|
||||
"sort_key": "quoteVolume",
|
||||
"refresh_period": 1800,
|
||||
}],
|
||||
```
|
||||
|
||||
#### AgeFilter
|
||||
|
||||
Removes pairs that have been listed on the exchange for less than `min_days_listed` days (defaults to `10`).
|
||||
|
||||
When pairs are first listed on an exchange they can suffer huge price drops and volatility
|
||||
in the first few days while the pair goes through its price-discovery period. Bots can often
|
||||
be caught out buying before the pair has finished dropping in price.
|
||||
|
||||
This filter allows freqtrade to ignore pairs until they have been listed for at least `min_days_listed` days.
|
||||
|
||||
#### PrecisionFilter
|
||||
|
||||
Filters low-value coins which would not allow setting stoplosses.
|
||||
|
||||
#### PriceFilter
|
||||
|
||||
The `PriceFilter` allows filtering of pairs by price. Currently the following price filters are supported:
|
||||
|
||||
* `min_price`
|
||||
* `max_price`
|
||||
* `low_price_ratio`
|
||||
|
||||
The `min_price` setting removes pairs where the price is below the specified price. This is useful if you wish to avoid trading very low-priced pairs.
|
||||
This option is disabled by default, and will only apply if set to > 0.
|
||||
|
||||
The `max_price` setting removes pairs where the price is above the specified price. This is useful if you wish to trade only low-priced pairs.
|
||||
This option is disabled by default, and will only apply if set to > 0.
|
||||
|
||||
The `low_price_ratio` setting removes pairs where a raise of 1 price unit (pip) is above the `low_price_ratio` ratio.
|
||||
This option is disabled by default, and will only apply if set to > 0.
|
||||
|
||||
For `PriceFiler` at least one of its `min_price`, `max_price` or `low_price_ratio` settings must be applied.
|
||||
|
||||
Calculation example:
|
||||
|
||||
Min price precision for SHITCOIN/BTC is 8 decimals. If its price is 0.00000011 - one price step above would be 0.00000012, which is ~9% higher than the previous price value. You may filter out this pair by using PriceFilter with `low_price_ratio` set to 0.09 (9%) or with `min_price` set to 0.00000011, correspondingly.
|
||||
|
||||
!!! Warning "Low priced pairs"
|
||||
Low priced pairs with high "1 pip movements" are dangerous since they are often illiquid and it may also be impossible to place the desired stoploss, which can often result in high losses since price needs to be rounded to the next tradable price - so instead of having a stoploss of -5%, you could end up with a stoploss of -9% simply due to price rounding.
|
||||
|
||||
#### ShuffleFilter
|
||||
|
||||
Shuffles (randomizes) pairs in the pairlist. It can be used for preventing the bot from trading some of the pairs more frequently then others when you want all pairs be treated with the same priority.
|
||||
|
||||
!!! Tip
|
||||
You may set the `seed` value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If `seed` is not set, the pairs are shuffled in the non-repeatable random order.
|
||||
|
||||
#### SpreadFilter
|
||||
|
||||
Removes pairs that have a difference between asks and bids above the specified ratio, `max_spread_ratio` (defaults to `0.005`).
|
||||
|
||||
Example:
|
||||
|
||||
If `DOGE/BTC` maximum bid is 0.00000026 and minimum ask is 0.00000027, the ratio is calculated as: `1 - bid/ask ~= 0.037` which is `> 0.005` and this pair will be filtered out.
|
||||
|
||||
### Full example of Pairlist Handlers
|
||||
|
||||
The below example blacklists `BNB/BTC`, uses `VolumePairList` with `20` assets, sorting pairs by `quoteVolume` and applies both [`PrecisionFilter`](#precisionfilter) and [`PriceFilter`](#price-filter), filtering all assets where 1 priceunit is > 1%. Then the `SpreadFilter` is applied and pairs are finally shuffled with the random seed set to some predefined value.
|
||||
|
||||
```json
|
||||
"exchange": {
|
||||
"pair_whitelist": [],
|
||||
"pair_blacklist": ["BNB/BTC"]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "VolumePairList",
|
||||
"number_assets": 20,
|
||||
"sort_key": "quoteVolume",
|
||||
},
|
||||
{"method": "AgeFilter", "min_days_listed": 10},
|
||||
{"method": "PrecisionFilter"},
|
||||
{"method": "PriceFilter", "low_price_ratio": 0.01},
|
||||
{"method": "SpreadFilter", "max_spread_ratio": 0.005},
|
||||
{"method": "ShuffleFilter", "seed": 42}
|
||||
],
|
||||
```
|
||||
--8<-- "includes/pairlists.md"
|
||||
--8<-- "includes/protections.md"
|
||||
|
||||
## Switch to Dry-run mode
|
||||
|
||||
@@ -806,32 +692,6 @@ 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](bot-usage.md).
|
||||
|
@@ -8,7 +8,7 @@ If no additional parameter is specified, freqtrade will download data for `"1m"`
|
||||
Exchange and pairs will come from `config.json` (if specified using `-c/--config`).
|
||||
Otherwise `--exchange` becomes mandatory.
|
||||
|
||||
You can use a relative timerange (`--days 20`) or an absolute starting point (`--timerange 20200101`). For incremental downloads, the relative approach should be used.
|
||||
You can use a relative timerange (`--days 20`) or an absolute starting point (`--timerange 20200101-`). For incremental downloads, the relative approach should be used.
|
||||
|
||||
!!! Tip "Tip: Updating existing data"
|
||||
If you already have backtesting data available in your data-directory and would like to refresh this data up to today, use `--days xx` with a number slightly higher than the missing number of days. Freqtrade will keep the available data and only download the missing data.
|
||||
@@ -308,10 +308,13 @@ Since this data is large by default, the files use gzip by default. They are sto
|
||||
|
||||
To use this mode, simply add `--dl-trades` to your call. This will swap the download method to download trades, and resamples the data locally.
|
||||
|
||||
!!! Warning "do not use"
|
||||
You should not use this unless you're a kraken user. Most other exchanges provide OHLCV data with sufficient history.
|
||||
|
||||
Example call:
|
||||
|
||||
```bash
|
||||
freqtrade download-data --exchange binance --pairs XRP/ETH ETH/BTC --days 20 --dl-trades
|
||||
freqtrade download-data --exchange kraken --pairs XRP/EUR ETH/EUR --days 20 --dl-trades
|
||||
```
|
||||
|
||||
!!! Note
|
||||
|
@@ -2,7 +2,7 @@
|
||||
|
||||
This page is intended for developers of Freqtrade, people who want to contribute to the Freqtrade codebase or documentation, or people who want to understand the source code of the application they're running.
|
||||
|
||||
All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We [track issues](https://github.com/freqtrade/freqtrade/issues) on [GitHub](https://github.com) and also have a dev channel in [slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE) where you can ask questions.
|
||||
All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We [track issues](https://github.com/freqtrade/freqtrade/issues) on [GitHub](https://github.com) and also have a dev channel on [discord](https://discord.gg/MA9v74M) or [slack](https://join.slack.com/t/highfrequencybot/shared_invite/zt-l9d9iqgl-9cVBIeBkCBa8j6upSmd_NA) where you can ask questions.
|
||||
|
||||
## Documentation
|
||||
|
||||
@@ -94,9 +94,11 @@ Below is an outline of exception inheritance hierarchy:
|
||||
+---+ StrategyError
|
||||
```
|
||||
|
||||
## Modules
|
||||
---
|
||||
|
||||
### Dynamic Pairlist
|
||||
## Plugins
|
||||
|
||||
### Pairlists
|
||||
|
||||
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.
|
||||
@@ -119,6 +121,9 @@ The base-class provides an instance of the exchange (`self._exchange`) the pairl
|
||||
self._pairlist_pos = pairlist_pos
|
||||
```
|
||||
|
||||
!!! Tip
|
||||
Don't forget to register your pairlist in `constants.py` under the variable `AVAILABLE_PAIRLISTS` - otherwise it will not be selectable.
|
||||
|
||||
Now, let's step through the methods which require actions:
|
||||
|
||||
#### Pairlist configuration
|
||||
@@ -170,6 +175,66 @@ In `VolumePairList`, this implements different methods of sorting, does early va
|
||||
return pairs
|
||||
```
|
||||
|
||||
### Protections
|
||||
|
||||
Best read the [Protection documentation](configuration.md#protections) to understand protections.
|
||||
This Guide is directed towards Developers who want to develop a new protection.
|
||||
|
||||
No protection should use datetime directly, but use the provided `date_now` variable for date calculations. This preserves the ability to backtest protections.
|
||||
|
||||
!!! Tip "Writing a new Protection"
|
||||
Best copy one of the existing Protections to have a good example.
|
||||
Don't forget to register your protection in `constants.py` under the variable `AVAILABLE_PROTECTIONS` - otherwise it will not be selectable.
|
||||
|
||||
#### Implementation of a new protection
|
||||
|
||||
All Protection implementations must have `IProtection` as parent class.
|
||||
For that reason, they must implement the following methods:
|
||||
|
||||
* `short_desc()`
|
||||
* `global_stop()`
|
||||
* `stop_per_pair()`.
|
||||
|
||||
`global_stop()` and `stop_per_pair()` must return a ProtectionReturn tuple, which consists of:
|
||||
|
||||
* lock pair - boolean
|
||||
* lock until - datetime - until when should the pair be locked (will be rounded up to the next new candle)
|
||||
* reason - string, used for logging and storage in the database
|
||||
|
||||
The `until` portion should be calculated using the provided `calculate_lock_end()` method.
|
||||
|
||||
All Protections should use `"stop_duration"` / `"stop_duration_candles"` to define how long a a pair (or all pairs) should be locked.
|
||||
The content of this is made available as `self._stop_duration` to the each Protection.
|
||||
|
||||
If your protection requires a look-back period, please use `"lookback_period"` / `"lockback_period_candles"` to keep all protections aligned.
|
||||
|
||||
#### Global vs. local stops
|
||||
|
||||
Protections can have 2 different ways to stop trading for a limited :
|
||||
|
||||
* Per pair (local)
|
||||
* For all Pairs (globally)
|
||||
|
||||
##### Protections - per pair
|
||||
|
||||
Protections that implement the per pair approach must set `has_local_stop=True`.
|
||||
The method `stop_per_pair()` will be called whenever a trade closed (sell order completed).
|
||||
|
||||
##### Protections - global protection
|
||||
|
||||
These Protections should do their evaluation across all pairs, and consequently will also lock all pairs from trading (called a global PairLock).
|
||||
Global protection must set `has_global_stop=True` to be evaluated for global stops.
|
||||
The method `global_stop()` will be called whenever a trade closed (sell order completed).
|
||||
|
||||
##### Protections - calculating lock end time
|
||||
|
||||
Protections should calculate the lock end time based on the last trade it considers.
|
||||
This avoids re-locking should the lookback-period be longer than the actual lock period.
|
||||
|
||||
The `IProtection` parent class provides a helper method for this in `calculate_lock_end()`.
|
||||
|
||||
---
|
||||
|
||||
## Implement a new Exchange (WIP)
|
||||
|
||||
!!! Note
|
||||
@@ -177,6 +242,9 @@ In `VolumePairList`, this implements different methods of sorting, does early va
|
||||
|
||||
Most exchanges supported by CCXT should work out of the box.
|
||||
|
||||
To quickly test the public endpoints of an exchange, add a configuration for your exchange to `test_ccxt_compat.py` and run these tests with `pytest --longrun tests/exchange/test_ccxt_compat.py`.
|
||||
Completing these tests successfully a good basis point (it's a requirement, actually), however these won't guarantee correct exchange functioning, as this only tests public endpoints, but no private endpoint (like generate order or similar).
|
||||
|
||||
### Stoploss On Exchange
|
||||
|
||||
Check if the new exchange supports Stoploss on Exchange orders through their API.
|
||||
|
201
docs/docker.md
201
docs/docker.md
@@ -1,201 +0,0 @@
|
||||
## Freqtrade with docker without docker-compose
|
||||
|
||||
!!! Warning
|
||||
The below documentation is provided for completeness and assumes that you are familiar with running docker containers. If you're just starting out with Docker, we recommend to follow the [Quickstart](docker.md) instructions.
|
||||
|
||||
### Download the official Freqtrade docker image
|
||||
|
||||
Pull the image from docker hub.
|
||||
|
||||
Branches / tags available can be checked out on [Dockerhub tags page](https://hub.docker.com/r/freqtradeorg/freqtrade/tags/).
|
||||
|
||||
```bash
|
||||
docker pull freqtradeorg/freqtrade:stable
|
||||
# Optionally tag the repository so the run-commands remain shorter
|
||||
docker tag freqtradeorg/freqtrade:stable freqtrade
|
||||
```
|
||||
|
||||
To update the image, simply run the above commands again and restart your running container.
|
||||
|
||||
Should you require additional libraries, please [build the image yourself](#build-your-own-docker-image).
|
||||
|
||||
!!! Note "Docker image update frequency"
|
||||
The official docker images with tags `stable`, `develop` and `latest` are automatically rebuild once a week to keep the base image up-to-date.
|
||||
In addition to that, every merge to `develop` will trigger a rebuild for `develop` and `latest`.
|
||||
|
||||
### Prepare the configuration files
|
||||
|
||||
Even though you will use docker, you'll still need some files from the github repository.
|
||||
|
||||
#### Clone the git repository
|
||||
|
||||
Linux/Mac/Windows with WSL
|
||||
|
||||
```bash
|
||||
git clone https://github.com/freqtrade/freqtrade.git
|
||||
```
|
||||
|
||||
Windows with docker
|
||||
|
||||
```bash
|
||||
git clone --config core.autocrlf=input https://github.com/freqtrade/freqtrade.git
|
||||
```
|
||||
|
||||
#### Copy `config.json.example` to `config.json`
|
||||
|
||||
```bash
|
||||
cd freqtrade
|
||||
cp -n config.json.example config.json
|
||||
```
|
||||
|
||||
> To understand the configuration options, please refer to the [Bot Configuration](configuration.md) page.
|
||||
|
||||
#### Create your database file
|
||||
|
||||
=== "Dry-Run"
|
||||
``` bash
|
||||
touch tradesv3.dryrun.sqlite
|
||||
```
|
||||
|
||||
=== "Production"
|
||||
``` bash
|
||||
touch tradesv3.sqlite
|
||||
```
|
||||
|
||||
|
||||
!!! Warning "Database File Path"
|
||||
Make sure to use the path to the correct database file when starting the bot in Docker.
|
||||
|
||||
### Build your own Docker image
|
||||
|
||||
Best start by pulling the official docker image from dockerhub as explained [here](#download-the-official-docker-image) to speed up building.
|
||||
|
||||
To add additional libraries to your docker image, best check out [Dockerfile.technical](https://github.com/freqtrade/freqtrade/blob/develop/docker/Dockerfile.technical) which adds the [technical](https://github.com/freqtrade/technical) module to the image.
|
||||
|
||||
```bash
|
||||
docker build -t freqtrade -f docker/Dockerfile.technical .
|
||||
```
|
||||
|
||||
If you are developing using Docker, use `docker/Dockerfile.develop` to build a dev Docker image, which will also set up develop dependencies:
|
||||
|
||||
```bash
|
||||
docker build -f docker/Dockerfile.develop -t freqtrade-dev .
|
||||
```
|
||||
|
||||
!!! Warning "Include your config file manually"
|
||||
For security reasons, your configuration file will not be included in the image, you will need to bind mount it. It is also advised to bind mount an SQLite database file (see [5. Run a restartable docker image](#run-a-restartable-docker-image)") to keep it between updates.
|
||||
|
||||
#### Verify the Docker image
|
||||
|
||||
After the build process you can verify that the image was created with:
|
||||
|
||||
```bash
|
||||
docker images
|
||||
```
|
||||
|
||||
The output should contain the freqtrade image.
|
||||
|
||||
### 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):
|
||||
|
||||
```bash
|
||||
docker run --rm -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
||||
```
|
||||
|
||||
!!! Warning
|
||||
In this example, the database will be created inside the docker instance and will be lost when you refresh your image.
|
||||
|
||||
#### Adjust timezone
|
||||
|
||||
By default, the container will use UTC timezone.
|
||||
If you would like to change the timezone use the following commands:
|
||||
|
||||
=== "Linux"
|
||||
``` bash
|
||||
-v /etc/timezone:/etc/timezone:ro
|
||||
|
||||
# Complete command:
|
||||
docker run --rm -v /etc/timezone:/etc/timezone:ro -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
||||
```
|
||||
|
||||
=== "MacOS"
|
||||
```bash
|
||||
docker run --rm -e TZ=`ls -la /etc/localtime | cut -d/ -f8-9` -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
||||
```
|
||||
|
||||
!!! Note "MacOS Issues"
|
||||
The OSX Docker versions after 17.09.1 have a known issue whereby `/etc/localtime` cannot be shared causing Docker to not start.<br>
|
||||
A work-around for this is to start with the MacOS command above
|
||||
More information on this docker issue and work-around can be read [here](https://github.com/docker/for-mac/issues/2396).
|
||||
|
||||
### 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).
|
||||
|
||||
#### 1. Move your config file and database
|
||||
|
||||
The following will assume that you place your configuration / database files to `~/.freqtrade`, which is a hidden directory in your home directory. Feel free to use a different directory and replace the directory in the upcomming commands.
|
||||
|
||||
```bash
|
||||
mkdir ~/.freqtrade
|
||||
mv config.json ~/.freqtrade
|
||||
mv tradesv3.sqlite ~/.freqtrade
|
||||
```
|
||||
|
||||
#### 2. Run the docker image
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name freqtrade \
|
||||
-v ~/.freqtrade/config.json:/freqtrade/config.json \
|
||||
-v ~/.freqtrade/user_data/:/freqtrade/user_data \
|
||||
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
||||
freqtrade trade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy
|
||||
```
|
||||
|
||||
!!! Note
|
||||
When using docker, it's best to specify `--db-url` explicitly to ensure that the database URL and the mounted database file match.
|
||||
|
||||
!!! Note
|
||||
All available bot command line parameters can be added to the end of the `docker run` command.
|
||||
|
||||
!!! Note
|
||||
You can define a [restart policy](https://docs.docker.com/config/containers/start-containers-automatically/) in docker. It can be useful in some cases to use the `--restart unless-stopped` flag (crash of freqtrade or reboot of your system).
|
||||
|
||||
### Monitor your Docker instance
|
||||
|
||||
You can use the following commands to monitor and manage your container:
|
||||
|
||||
```bash
|
||||
docker logs freqtrade
|
||||
docker logs -f freqtrade
|
||||
docker restart freqtrade
|
||||
docker stop freqtrade
|
||||
docker start freqtrade
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
### Backtest with docker
|
||||
|
||||
The following assumes that the download/setup of the docker image 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 backtesting --strategy AwsomelyProfitableStrategy
|
||||
```
|
||||
|
||||
Head over to the [Backtesting Documentation](backtesting.md) for more details.
|
||||
|
||||
!!! Note
|
||||
Additional bot command line parameters can be appended after the image name (`freqtrade` in the above example).
|
@@ -8,9 +8,7 @@ Start by downloading and installing Docker CE for your platform:
|
||||
* [Windows](https://docs.docker.com/docker-for-windows/install/)
|
||||
* [Linux](https://docs.docker.com/install/)
|
||||
|
||||
Optionally, [`docker-compose`](https://docs.docker.com/compose/install/) should be installed and available to follow the [docker quick start guide](#docker-quick-start).
|
||||
|
||||
Once you have Docker installed, simply prepare the config file (e.g. `config.json`) and run the image for `freqtrade` as explained below.
|
||||
To simplify running freqtrade, please install [`docker-compose`](https://docs.docker.com/compose/install/) should be installed and available to follow the below [docker quick start guide](#docker-quick-start).
|
||||
|
||||
## Freqtrade with docker-compose
|
||||
|
||||
@@ -71,7 +69,7 @@ The last 2 steps in the snippet create the directory with `user_data`, as well a
|
||||
!!! Question "How to edit the bot configuration?"
|
||||
You can edit the configuration at any time, which is available as `user_data/config.json` (within the directory `ft_userdata`) when using the above configuration.
|
||||
|
||||
You can also change the both Strategy and commands by editing the `docker-compose.yml` file.
|
||||
You can also change the both Strategy and commands by editing the command section of your `docker-compose.yml` file.
|
||||
|
||||
#### Adding a custom strategy
|
||||
|
||||
@@ -83,7 +81,8 @@ The `SampleStrategy` is run by default.
|
||||
|
||||
!!! Warning "`SampleStrategy` is just a demo!"
|
||||
The `SampleStrategy` is there for your reference and give you ideas for your own strategy.
|
||||
Please always backtest the strategy and use dry-run for some time before risking real money!
|
||||
Please always backtest your strategy and use dry-run for some time before risking real money!
|
||||
You will find more information about Strategy development in the [Strategy documentation](strategy-customization.md).
|
||||
|
||||
Once this is done, you're ready to launch the bot in trading mode (Dry-run or Live-trading, depending on your answer to the corresponding question you made above).
|
||||
|
||||
@@ -91,18 +90,23 @@ Once this is done, you're ready to launch the bot in trading mode (Dry-run or Li
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
#### Monitoring the bot
|
||||
|
||||
You can check for running instances with `docker-compose ps`.
|
||||
This should list the service `freqtrade` as `running`. If that's not the case, best check the logs (see next point).
|
||||
|
||||
#### Docker-compose logs
|
||||
|
||||
Logs will be located at: `user_data/logs/freqtrade.log`.
|
||||
You can check the latest log with the command `docker-compose logs -f`.
|
||||
Logs will be written to: `user_data/logs/freqtrade.log`.
|
||||
You can also check the latest log with the command `docker-compose logs -f`.
|
||||
|
||||
#### Database
|
||||
|
||||
The database will be at: `user_data/tradesv3.sqlite`
|
||||
The database will be located at: `user_data/tradesv3.sqlite`
|
||||
|
||||
#### Updating freqtrade with docker-compose
|
||||
|
||||
To update freqtrade when using `docker-compose` is as simple as running the following 2 commands:
|
||||
Updating freqtrade when using `docker-compose` is as simple as running the following 2 commands:
|
||||
|
||||
``` bash
|
||||
# Download the latest image
|
||||
@@ -120,10 +124,10 @@ This will first pull the latest image, and will then restart the container with
|
||||
|
||||
Advanced users may edit the docker-compose file further to include all possible options or arguments.
|
||||
|
||||
All possible freqtrade arguments will be available by running `docker-compose run --rm freqtrade <command> <optional arguments>`.
|
||||
All freqtrade arguments will be available by running `docker-compose run --rm freqtrade <command> <optional arguments>`.
|
||||
|
||||
!!! Note "`docker-compose run --rm`"
|
||||
Including `--rm` will clean up the container after completion, and is highly recommended for all modes except trading mode (running with `freqtrade trade` command).
|
||||
Including `--rm` will remove the container after completion, and is highly recommended for all modes except trading mode (running with `freqtrade trade` command).
|
||||
|
||||
#### Example: Download data with docker-compose
|
||||
|
||||
@@ -172,19 +176,19 @@ docker-compose run --rm freqtrade plot-dataframe --strategy AwesomeStrategy -p B
|
||||
|
||||
The output will be stored in the `user_data/plot` directory, and can be opened with any modern browser.
|
||||
|
||||
## Data analayis using docker compose
|
||||
## Data analysis using docker compose
|
||||
|
||||
Freqtrade provides a docker-compose file which starts up a jupyter lab server.
|
||||
You can run this server using the following command:
|
||||
|
||||
``` bash
|
||||
docker-compose --rm -f docker/docker-compose-jupyter.yml up
|
||||
docker-compose -f docker/docker-compose-jupyter.yml up
|
||||
```
|
||||
|
||||
This will create a dockercontainer running jupyter lab, which will be accessible using `https://127.0.0.1:8888/lab`.
|
||||
This will create a docker-container running jupyter lab, which will be accessible using `https://127.0.0.1:8888/lab`.
|
||||
Please use the link that's printed in the console after startup for simplified login.
|
||||
|
||||
Since part of this image is built on your machine, it is recommended to rebuild the image from time to time to keep freqtrade (and dependencies) uptodate.
|
||||
Since part of this image is built on your machine, it is recommended to rebuild the image from time to time to keep freqtrade (and dependencies) up-to-date.
|
||||
|
||||
``` bash
|
||||
docker-compose -f docker/docker-compose-jupyter.yml build --no-cache
|
||||
|
52
docs/edge.md
52
docs/edge.md
@@ -1,6 +1,6 @@
|
||||
# Edge positioning
|
||||
|
||||
The `Edge Positioning` module uses probability to calculate your win rate and risk reward ration. It will use these statistics to control your strategy trade entry points, position side and, stoploss.
|
||||
The `Edge Positioning` module uses probability to calculate your win rate and risk reward ratio. It will use these statistics to control your strategy trade entry points, position size and, stoploss.
|
||||
|
||||
!!! Warning
|
||||
`Edge positioning` is not compatible with dynamic (volume-based) whitelist.
|
||||
@@ -23,8 +23,8 @@ The Edge Positioning module seeks to improve a strategy's winning probability an
|
||||
We raise the following question[^1]:
|
||||
|
||||
!!! Question "Which trade is a better option?"
|
||||
a) A trade with 80% of chance of losing $100 and 20% chance of winning $200<br/>
|
||||
b) A trade with 100% of chance of losing $30
|
||||
a) A trade with 80% of chance of losing 100\$ and 20% chance of winning 200\$<br/>
|
||||
b) A trade with 100% of chance of losing 30\$
|
||||
|
||||
???+ Info "Answer"
|
||||
The expected value of *a)* is smaller than the expected value of *b)*.<br/>
|
||||
@@ -34,8 +34,8 @@ We raise the following question[^1]:
|
||||
Another way to look at it is to ask a similar question:
|
||||
|
||||
!!! Question "Which trade is a better option?"
|
||||
a) A trade with 80% of chance of winning 100 and 20% chance of losing $200<br/>
|
||||
b) A trade with 100% of chance of winning $30
|
||||
a) A trade with 80% of chance of winning 100\$ and 20% chance of losing 200\$<br/>
|
||||
b) A trade with 100% of chance of winning 30\$
|
||||
|
||||
Edge positioning tries to answer the hard questions about risk/reward and position size automatically, seeking to minimizes the chances of losing of a given strategy.
|
||||
|
||||
@@ -55,7 +55,7 @@ Similarly, we can discover the set of losing trades $T_{lose}$ as follows:
|
||||
$$ T_{lose} = \{o \in O | o \leq 0\} $$
|
||||
|
||||
!!! Example
|
||||
In a section where a strategy made three transactions $O = \{3.5, -1, 15, 0\}$:<br>
|
||||
In a section where a strategy made four transactions $O = \{3.5, -1, 15, 0\}$:<br>
|
||||
$T_{win} = \{3.5, 15\}$<br>
|
||||
$T_{lose} = \{-1, 0\}$<br>
|
||||
|
||||
@@ -82,20 +82,34 @@ Risk Reward Ratio ($R$) is a formula used to measure the expected gains of a giv
|
||||
$$ R = \frac{\text{potential_profit}}{\text{potential_loss}} $$
|
||||
|
||||
???+ Example "Worked example of $R$ calculation"
|
||||
Let's say that you think that the price of *stonecoin* today is $10.0. You believe that, because they will start mining stonecoin, it will go up to $15.0 tomorrow. There is the risk that the stone is too hard, and the GPUs can't mine it, so the price might go to $0 tomorrow. You are planning to invest $100.<br>
|
||||
Your potential profit is calculated as:<br>
|
||||
Let's say that you think that the price of *stonecoin* today is 10.0\$. You believe that, because they will start mining stonecoin, it will go up to 15.0\$ tomorrow. There is the risk that the stone is too hard, and the GPUs can't mine it, so the price might go to 0\$ tomorrow. You are planning to invest 100\$, which will give you 10 shares (100 / 10).
|
||||
|
||||
Your potential profit is calculated as:
|
||||
|
||||
$\begin{aligned}
|
||||
\text{potential_profit} &= (\text{potential_price} - \text{cost_per_unit}) * \frac{\text{investment}}{\text{cost_per_unit}} \\
|
||||
&= (15 - 10) * \frac{100}{15}\\
|
||||
&= 33.33
|
||||
\end{aligned}$<br>
|
||||
Since the price might go to $0, the $100 dolars invested could turn into 0. We can compute the Risk Reward Ratio as follows:<br>
|
||||
\text{potential_profit} &= (\text{potential_price} - \text{entry_price}) * \frac{\text{investment}}{\text{entry_price}} \\
|
||||
&= (15 - 10) * (100 / 10) \\
|
||||
&= 50
|
||||
\end{aligned}$
|
||||
|
||||
Since the price might go to 0\$, the 100\$ dollars invested could turn into 0.
|
||||
|
||||
We do however use a stoploss of 15% - so in the worst case, we'll sell 15% below entry price (or at 8.5$\).
|
||||
|
||||
$\begin{aligned}
|
||||
\text{potential_loss} &= (\text{entry_price} - \text{stoploss}) * \frac{\text{investment}}{\text{entry_price}} \\
|
||||
&= (10 - 8.5) * (100 / 10)\\
|
||||
&= 15
|
||||
\end{aligned}$
|
||||
|
||||
We can compute the Risk Reward Ratio as follows:
|
||||
|
||||
$\begin{aligned}
|
||||
R &= \frac{\text{potential_profit}}{\text{potential_loss}}\\
|
||||
&= \frac{33.33}{100}\\
|
||||
&= 0.333...
|
||||
&= \frac{50}{15}\\
|
||||
&= 3.33
|
||||
\end{aligned}$<br>
|
||||
What it effectivelly means is that the strategy have the potential to make $0.33 for each $1 invested.
|
||||
What it effectively means is that the strategy have the potential to make 3.33\$ for each 1\$ invested.
|
||||
|
||||
On a long horizon, that is, on many trades, we can calculate the risk reward by dividing the strategy' average profit on winning trades by the strategy' average loss on losing trades. We can calculate the average profit, $\mu_{win}$, as follows:
|
||||
|
||||
@@ -127,7 +141,7 @@ $$E = R * W - L$$
|
||||
$E = R * W - L = 5 * 0.28 - 0.72 = 0.68$
|
||||
<br>
|
||||
|
||||
The expectancy worked out in the example above means that, on average, this strategy' trades will return 1.68 times the size of its losses. Said another way, the strategy makes $1.68 for every $1 it loses, on average.
|
||||
The expectancy worked out in the example above means that, on average, this strategy' trades will return 1.68 times the size of its losses. Said another way, the strategy makes 1.68\$ for every 1\$ it loses, on average.
|
||||
|
||||
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.
|
||||
|
||||
@@ -192,7 +206,7 @@ Let's say the stake currency is **ETH** and there is $10$ **ETH** on the wallet.
|
||||
|
||||
- The strategy detects a sell signal in the **XLM/ETH** market. The bot exits **Trade 1** for a profit of $1$ **ETH**. The total capital in the wallet becomes $11$ **ETH** and the available capital for trading becomes $5.5$ **ETH**.
|
||||
|
||||
- **Trade 4** The strategy detects a new buy signal int the **XLM/ETH** market. `Edge Positioning` calculates the stoploss of $2%$, and the position size of $0.055 / 0.02 = 2.75$ **ETH**.
|
||||
- **Trade 4** The strategy detects a new buy signal int the **XLM/ETH** market. `Edge Positioning` calculates the stoploss of $2\%$, and the position size of $0.055 / 0.02 = 2.75$ **ETH**.
|
||||
|
||||
## Configurations
|
||||
|
||||
@@ -208,7 +222,7 @@ Edge module has following configuration options:
|
||||
| `stoploss_range_max` | Maximum stoploss. <br>*Defaults to `-0.10`.* <br> **Datatype:** Float
|
||||
| `stoploss_range_step` | As an example if this is set to -0.01 then Edge will test the strategy for `[-0.01, -0,02, -0,03 ..., -0.09, -0.10]` ranges. <br> **Note** than having a smaller step means having a bigger range which could lead to slow calculation. <br> If you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10. <br>*Defaults to `-0.001`.* <br> **Datatype:** Float
|
||||
| `minimum_winrate` | It filters out pairs which don't have at least minimum_winrate. <br>This comes handy if you want to be conservative and don't comprise win rate in favour of risk reward ratio. <br>*Defaults to `0.60`.* <br> **Datatype:** Float
|
||||
| `minimum_expectancy` | It filters out pairs which have the expectancy lower than this number. <br>Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return. <br>*Defaults to `0.20`.* <br> **Datatype:** Float
|
||||
| `minimum_expectancy` | It filters out pairs which have the expectancy lower than this number. <br>Having an expectancy of 0.20 means if you put 10\$ on a trade you expect a 12\$ return. <br>*Defaults to `0.20`.* <br> **Datatype:** Float
|
||||
| `min_trade_number` | When calculating *W*, *R* and *E* (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable. <br>Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something. <br>*Defaults to `10` (it is highly recommended not to decrease this number).* <br> **Datatype:** Integer
|
||||
| `max_trade_duration_minute` | Edge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign.<br>**NOTICE:** While configuring this value, you should take into consideration your timeframe. As an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. Default value is set assuming your strategy interval is relatively small (1m or 5m, etc.).<br>*Defaults to `1440` (one day).* <br> **Datatype:** Integer
|
||||
| `remove_pumps` | Edge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off.<br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||
|
@@ -23,7 +23,8 @@ Binance has been split into 3, and users must use the correct ccxt exchange ID f
|
||||
## Kraken
|
||||
|
||||
!!! Tip "Stoploss on Exchange"
|
||||
Kraken supports `stoploss_on_exchange` and uses stop-loss-market orders. It provides great advantages, so we recommend to benefit from it, however since the resulting order is a stoploss-market order, sell-rates are not guaranteed, which makes this feature less secure than on other exchanges. This limitation is based on kraken's policy [source](https://blog.kraken.com/post/1234/announcement-delisting-pairs-and-temporary-suspension-of-advanced-order-types/) and [source2](https://blog.kraken.com/post/1494/kraken-enables-advanced-orders-and-adds-10-currency-pairs/) - which has stoploss-limit orders disabled.
|
||||
Kraken supports `stoploss_on_exchange` and can use both stop-loss-market and stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it.
|
||||
You can use either `"limit"` or `"market"` in the `order_types.stoploss` configuration setting to decide which type to use.
|
||||
|
||||
### Historic Kraken data
|
||||
|
||||
@@ -75,8 +76,7 @@ print(res)
|
||||
|
||||
!!! Tip "Stoploss on Exchange"
|
||||
FTX supports `stoploss_on_exchange` and can use both stop-loss-market and stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it.
|
||||
You can use either `"limit"` or `"market"` in the `order_types.stoploss` configuration setting to decide.
|
||||
|
||||
You can use either `"limit"` or `"market"` in the `order_types.stoploss` configuration setting to decide which type of stoploss shall be used.
|
||||
|
||||
### Using subaccounts
|
||||
|
||||
@@ -99,10 +99,10 @@ To use subaccounts with FTX, you need to edit the configuration and add the foll
|
||||
|
||||
Should you experience constant errors with Nonce (like `InvalidNonce`), it is best to regenerate the API keys. Resetting Nonce is difficult and it's usually easier to regenerate the API keys.
|
||||
|
||||
|
||||
## Random notes for other exchanges
|
||||
|
||||
* The Ocean (exchange id: `theocean`) exchange uses Web3 functionality and requires `web3` python package to be installed:
|
||||
|
||||
```shell
|
||||
$ pip3 install web3
|
||||
```
|
||||
|
58
docs/faq.md
58
docs/faq.md
@@ -2,30 +2,30 @@
|
||||
|
||||
## Beginner Tips & Tricks
|
||||
|
||||
* When you work with your strategy & hyperopt file you should use a proper code editor like vscode or Pycharm. A good code editor will provide syntax highlighting as well as line numbers, making it easy to find syntax errors (most likely, pointed out by Freqtrade during startup).
|
||||
* When you work with your strategy & hyperopt file you should use a proper code editor like VSCode or PyCharm. A good code editor will provide syntax highlighting as well as line numbers, making it easy to find syntax errors (most likely pointed out by Freqtrade during startup).
|
||||
|
||||
## Freqtrade common issues
|
||||
|
||||
### The bot does not start
|
||||
|
||||
Running the bot with `freqtrade trade --config config.json` does show the output `freqtrade: command not found`.
|
||||
Running the bot with `freqtrade trade --config config.json` shows the output `freqtrade: command not found`.
|
||||
|
||||
This could have the following reasons:
|
||||
This could be caused by the following reasons:
|
||||
|
||||
* The virtual environment is not active
|
||||
* run `source .env/bin/activate` to activate the virtual environment
|
||||
* The virtual environment is not active.
|
||||
* Run `source .env/bin/activate` to activate the virtual environment.
|
||||
* The installation did not work correctly.
|
||||
* Please check the [Installation documentation](installation.md).
|
||||
|
||||
### I have waited 5 minutes, why hasn't the bot made any trades yet?!
|
||||
### I have waited 5 minutes, why hasn't the bot made any trades yet?
|
||||
|
||||
* Depending on the buy strategy, the amount of whitelisted coins, the
|
||||
situation of the market etc, it can take up to hours to find good entry
|
||||
situation of the market etc, it can take up to hours to find a good entry
|
||||
position for a trade. Be patient!
|
||||
|
||||
* Or it may because of a configuration error? Best check the logs, it's usually telling you if the bot is simply not getting buy signals (only heartbeat messages), or if there is something wrong (errors / exceptions in the log).
|
||||
* It may be because of a configuration error. It's best to check the logs, they usually tell you if the bot is simply not getting buy signals (only heartbeat messages), or if there is something wrong (errors / exceptions in the log).
|
||||
|
||||
### I have made 12 trades already, why is my total profit negative?!
|
||||
### I have made 12 trades already, why is my total profit negative?
|
||||
|
||||
I understand your disappointment but unfortunately 12 trades is just
|
||||
not enough to say anything. If you run backtesting, you can see that our
|
||||
@@ -36,11 +36,9 @@ of course constantly aim to improve the bot but it will _always_ be a
|
||||
gamble, which should leave you with modest wins on monthly basis but
|
||||
you can't say much from few trades.
|
||||
|
||||
### I’d like to change the stake amount. Can I just stop the bot with /stop and then change the config.json and run it again?
|
||||
### I’d like to make changes to the config. Can I do that without having to kill the bot?
|
||||
|
||||
Not quite. Trades are persisted to a database but the configuration is
|
||||
currently only read when the bot is killed and restarted. `/stop` more
|
||||
like pauses. You can stop your bot, adjust settings and start it again.
|
||||
Yes. You can edit your config, use the `/stop` command in Telegram, followed by `/reload_config` and the bot will run with the new config.
|
||||
|
||||
### I want to improve the bot with a new strategy
|
||||
|
||||
@@ -49,7 +47,7 @@ the tutorial [here|Testing-new-strategies-with-Hyperopt](bot-usage.md#hyperopt-c
|
||||
|
||||
### Is there a setting to only SELL the coins being held and not perform anymore BUYS?
|
||||
|
||||
You can use the `/forcesell all` command from Telegram.
|
||||
You can use the `/stopbuy` command in Telegram to prevent future buys, followed by `/forcesell all` (sell all open trades).
|
||||
|
||||
### I want to run multiple bots on the same machine
|
||||
|
||||
@@ -59,7 +57,7 @@ Please look at the [advanced setup documentation Page](advanced-setup.md#running
|
||||
|
||||
This message is just a warning that the latest candles had missing candles in them.
|
||||
Depending on the exchange, this can indicate that the pair didn't have a trade for the timeframe you are using - and the exchange does only return candles with volume.
|
||||
On low volume pairs, this is a rather common occurance.
|
||||
On low volume pairs, this is a rather common occurrence.
|
||||
|
||||
If this happens for all pairs in the pairlist, this might indicate a recent exchange downtime. Please check your exchange's public channels for details.
|
||||
|
||||
@@ -73,7 +71,7 @@ Read [the Bittrex section about restricted markets](exchanges.md#restricted-mark
|
||||
|
||||
### I'm getting the "Exchange Bittrex does not support market orders." message and cannot run my strategy
|
||||
|
||||
As the message says, Bittrex does not support market orders and you have one of the [order types](configuration.md/#understand-order_types) set to "market". Probably your strategy was written with other exchanges in mind and sets "market" orders for "stoploss" orders, which is correct and preferable for most of the exchanges supporting market orders (but not for Bittrex).
|
||||
As the message says, Bittrex does not support market orders and you have one of the [order types](configuration.md/#understand-order_types) set to "market". Your strategy was probably written with other exchanges in mind and sets "market" orders for "stoploss" orders, which is correct and preferable for most of the exchanges supporting market orders (but not for Bittrex).
|
||||
|
||||
To fix it for Bittrex, redefine order types in the strategy to use "limit" instead of "market":
|
||||
|
||||
@@ -85,7 +83,7 @@ To fix it for Bittrex, redefine order types in the strategy to use "limit" inste
|
||||
}
|
||||
```
|
||||
|
||||
Same fix should be done in the configuration file, if order types are defined in your custom config rather than in the strategy.
|
||||
The same fix should be applied in the configuration file, if order types are defined in your custom config rather than in the strategy.
|
||||
|
||||
### How do I search the bot logs for something?
|
||||
|
||||
@@ -127,10 +125,10 @@ On Windows, the `--logfile` option is also supported by Freqtrade and you can us
|
||||
|
||||
## Hyperopt module
|
||||
|
||||
### How many epoch do I need to get a good Hyperopt result?
|
||||
### How many epochs do I need to get a good Hyperopt result?
|
||||
|
||||
Per default Hyperopt called without the `-e`/`--epochs` command line option will only
|
||||
run 100 epochs, means 100 evals of your triggers, guards, ... Too few
|
||||
run 100 epochs, means 100 evaluations of your triggers, guards, ... Too few
|
||||
to find a great result (unless if you are very lucky), so you probably
|
||||
have to run it for 10.000 or more. But it will take an eternity to
|
||||
compute.
|
||||
@@ -140,38 +138,32 @@ Since hyperopt uses Bayesian search, running for too many epochs may not produce
|
||||
It's therefore recommended to run between 500-1000 epochs over and over until you hit at least 10.000 epochs in total (or are satisfied with the result). You can best judge by looking at the results - if the bot keeps discovering better strategies, it's best to keep on going.
|
||||
|
||||
```bash
|
||||
freqtrade hyperopt -e 1000
|
||||
```
|
||||
|
||||
or if you want intermediate result to see
|
||||
|
||||
```bash
|
||||
for i in {1..100}; do freqtrade hyperopt -e 1000; done
|
||||
freqtrade hyperopt --hyperopt SampleHyperopt --hyperopt-loss SharpeHyperOptLossDaily --strategy SampleStrategy -e 1000
|
||||
```
|
||||
|
||||
### Why does it take a long time to run hyperopt?
|
||||
|
||||
* Discovering a great strategy with Hyperopt takes time. Study www.freqtrade.io, the Freqtrade Documentation page, join the Freqtrade [Slack community](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE) - or the Freqtrade [discord community](https://discord.gg/X89cVG). While you patiently wait for the most advanced, free crypto bot in the world, to hand you a possible golden strategy specially designed just for you.
|
||||
* Discovering a great strategy with Hyperopt takes time. Study www.freqtrade.io, the Freqtrade Documentation page, join the Freqtrade [Slack community](https://join.slack.com/t/highfrequencybot/shared_invite/zt-l9d9iqgl-9cVBIeBkCBa8j6upSmd_NA) - or the Freqtrade [discord community](https://discord.gg/X89cVG). While you patiently wait for the most advanced, free crypto bot in the world, to hand you a possible golden strategy specially designed just for you.
|
||||
|
||||
* If you wonder why it can take from 20 minutes to days to do 1000 epochs here are some answers:
|
||||
|
||||
This answer was written during the release 0.15.1, when we had:
|
||||
|
||||
- 8 triggers
|
||||
- 9 guards: let's say we evaluate even 10 values from each
|
||||
- 1 stoploss calculation: let's say we want 10 values from that too to be evaluated
|
||||
* 8 triggers
|
||||
* 9 guards: let's say we evaluate even 10 values from each
|
||||
* 1 stoploss calculation: let's say we want 10 values from that too to be evaluated
|
||||
|
||||
The following calculation is still very rough and not very precise
|
||||
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
|
||||
already 8\*10^9\*10 evaluations. A roughly total of 80 billion evaluations.
|
||||
Did you run 100 000 evaluations? Congrats, you've done roughly 1 / 100 000 th
|
||||
of the search space, assuming that the bot never tests the same parameters more than once.
|
||||
|
||||
* The time it takes to run 1000 hyperopt epochs depends on things like: The available cpu, hard-disk, ram, timeframe, timerange, indicator settings, indicator count, amount of coins that hyperopt test strategies on and the resulting trade count - which can be 650 trades in a year or 10.0000 trades depending if the strategy aims for big profits by trading rarely or for many low profit trades.
|
||||
|
||||
Example: 4% profit 650 times vs 0,3% profit a trade 10.000 times in a year. If we assume you set the --timerange to 365 days.
|
||||
|
||||
Example:
|
||||
Example:
|
||||
`freqtrade --config config.json --strategy SampleStrategy --hyperopt SampleHyperopt -e 1000 --timerange 20190601-20200601`
|
||||
|
||||
## Edge module
|
||||
|
138
docs/hyperopt.md
138
docs/hyperopt.md
@@ -37,12 +37,20 @@ pip install -r requirements-hyperopt.txt
|
||||
Before we start digging into Hyperopt, we recommend you to take a look at
|
||||
the sample hyperopt file located in [user_data/hyperopts/](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt.py).
|
||||
|
||||
Configuring hyperopt is similar to writing your own strategy, and many tasks will be similar and a lot of code can be copied across from the strategy.
|
||||
Configuring hyperopt is similar to writing your own strategy, and many tasks will be similar.
|
||||
|
||||
The simplest way to get started is to use `freqtrade new-hyperopt --hyperopt AwesomeHyperopt`.
|
||||
This will create a new hyperopt file from a template, which will be located under `user_data/hyperopts/AwesomeHyperopt.py`.
|
||||
!!! Tip "About this page"
|
||||
For this page, we will be using a fictional strategy called `AwesomeStrategy` - which will be optimized using the `AwesomeHyperopt` class.
|
||||
|
||||
### Checklist on all tasks / possibilities in hyperopt
|
||||
The simplest way to get started is to use the following, command, which will create a new hyperopt file from a template, which will be located under `user_data/hyperopts/AwesomeHyperopt.py`.
|
||||
|
||||
``` bash
|
||||
freqtrade new-hyperopt --hyperopt AwesomeHyperopt
|
||||
```
|
||||
|
||||
### Hyperopt checklist
|
||||
|
||||
Checklist on all tasks / possibilities in hyperopt
|
||||
|
||||
Depending on the space you want to optimize, only some of the below are required:
|
||||
|
||||
@@ -54,17 +62,15 @@ Depending on the space you want to optimize, only some of the below are required
|
||||
!!! Note
|
||||
`populate_indicators` needs to create all indicators any of thee spaces may use, otherwise hyperopt will not work.
|
||||
|
||||
Optional - can also be loaded from a strategy:
|
||||
Optional in hyperopt - can also be loaded from a strategy (recommended):
|
||||
|
||||
* copy `populate_indicators` from your strategy - otherwise default-strategy will be used
|
||||
* copy `populate_buy_trend` from your strategy - otherwise default-strategy will be used
|
||||
* copy `populate_sell_trend` from your strategy - otherwise default-strategy will be used
|
||||
|
||||
!!! Note
|
||||
Assuming the optional methods are not in your hyperopt file, please use `--strategy AweSomeStrategy` which contains these methods so hyperopt can use these methods instead.
|
||||
* `populate_indicators` - fallback to create indicators
|
||||
* `populate_buy_trend` - fallback if not optimizing for buy space. should come from strategy
|
||||
* `populate_sell_trend` - fallback if not optimizing for sell space. should come from strategy
|
||||
|
||||
!!! Note
|
||||
You always have to provide a strategy to Hyperopt, even if your custom Hyperopt class contains all methods.
|
||||
Assuming the optional methods are not in your hyperopt file, please use `--strategy AweSomeStrategy` which contains these methods so hyperopt can use these methods instead.
|
||||
|
||||
Rarely you may also need to override:
|
||||
|
||||
@@ -80,36 +86,41 @@ Rarely you may also need to override:
|
||||
# Have a working strategy at hand.
|
||||
freqtrade new-hyperopt --hyperopt EmptyHyperopt
|
||||
|
||||
freqtrade hyperopt --hyperopt EmptyHyperopt --spaces roi stoploss trailing --strategy MyWorkingStrategy --config config.json -e 100
|
||||
freqtrade hyperopt --hyperopt EmptyHyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi stoploss trailing --strategy MyWorkingStrategy --config config.json -e 100
|
||||
```
|
||||
|
||||
### 1. Install a Custom Hyperopt File
|
||||
### Create a Custom Hyperopt File
|
||||
|
||||
Put your hyperopt file into the directory `user_data/hyperopts`.
|
||||
Let assume you want a hyperopt file `AwesomeHyperopt.py`:
|
||||
|
||||
Let assume you want a hyperopt file `awesome_hyperopt.py`:
|
||||
Copy the file `user_data/hyperopts/sample_hyperopt.py` into `user_data/hyperopts/awesome_hyperopt.py`
|
||||
``` bash
|
||||
freqtrade new-hyperopt --hyperopt AwesomeHyperopt
|
||||
```
|
||||
|
||||
### 2. Configure your Guards and Triggers
|
||||
This command will create a new hyperopt file from a template, allowing you to get started quickly.
|
||||
|
||||
### Configure your Guards and Triggers
|
||||
|
||||
There are two places you need to change in your hyperopt file to add a new buy hyperopt for testing:
|
||||
|
||||
* Inside `indicator_space()` - the parameters hyperopt shall be optimizing.
|
||||
* Inside `populate_buy_trend()` - applying the parameters.
|
||||
* Within `buy_strategy_generator()` - populate the nested `populate_buy_trend()` to apply the parameters.
|
||||
|
||||
There you have two different types of indicators: 1. `guards` and 2. `triggers`.
|
||||
|
||||
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
|
||||
!!! Hint "Guards and Triggers"
|
||||
Technically, there is no difference between Guards and Triggers.
|
||||
However, this guide will make this distinction to make it clear that signals should not be "sticking".
|
||||
Sticking signals are signals that are active for multiple candles. This can lead into buying a signal late (right before the signal disappears - which means that the chance of success is a lot lower than right at the beginning).
|
||||
|
||||
Hyper-optimization will, for each epoch round, pick one trigger and possibly
|
||||
multiple guards. The constructed strategy will be something like "*buy exactly when close price touches lower Bollinger band, BUT only if
|
||||
ADX > 10*".
|
||||
|
||||
If you have updated the buy strategy, i.e. changed the contents of
|
||||
`populate_buy_trend()` method, you have to update the `guards` and
|
||||
`triggers` your hyperopt must use correspondingly.
|
||||
If you have updated the buy strategy, i.e. changed the contents of `populate_buy_trend()` method, you have to update the `guards` and `triggers` your hyperopt must use correspondingly.
|
||||
|
||||
#### Sell optimization
|
||||
|
||||
@@ -117,7 +128,7 @@ 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.
|
||||
* Within `sell_strategy_generator()` - populate the nested method `populate_sell_trend()` to apply the parameters.
|
||||
|
||||
The configuration and rules are the same than for buy signals.
|
||||
To avoid naming collisions in the search-space, please prefix all sell-spaces with `sell-`.
|
||||
@@ -126,7 +137,7 @@ To avoid naming collisions in the search-space, please prefix all sell-spaces wi
|
||||
|
||||
The Strategy class exposes the timeframe value as the `self.timeframe` attribute.
|
||||
The same value is available as class-attribute `HyperoptName.timeframe`.
|
||||
In the case of the linked sample-value this would be `SampleHyperOpt.timeframe`.
|
||||
In the case of the linked sample-value this would be `AwesomeHyperopt.timeframe`.
|
||||
|
||||
## Solving a Mystery
|
||||
|
||||
@@ -154,7 +165,7 @@ We will start by defining a search space:
|
||||
|
||||
Above definition says: I have five parameters I want you to randomly combine
|
||||
to find the best combination. Two of them are integer values (`adx-value`
|
||||
and `rsi-value`) and I want you test in the range of values 20 to 40.
|
||||
and `rsi-value`) and I want you test in the range of values 20 to 40.
|
||||
Then we have three category variables. First two are either `True` or `False`.
|
||||
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.
|
||||
@@ -162,6 +173,11 @@ one we call `trigger` and use it to decide which buy trigger we want to use.
|
||||
So let's write the buy strategy using these values:
|
||||
|
||||
```python
|
||||
@staticmethod
|
||||
def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||
"""
|
||||
Define the buy strategy parameters to be used by Hyperopt.
|
||||
"""
|
||||
def populate_buy_trend(dataframe: DataFrame) -> DataFrame:
|
||||
conditions = []
|
||||
# GUARDS AND TRENDS
|
||||
@@ -192,27 +208,25 @@ So let's write the buy strategy using these values:
|
||||
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 parameter combination produced the best profits.
|
||||
Hyperopt will now call `populate_buy_trend()` many times (`epochs`) with different value combinations.
|
||||
It will use the given historical data and make buys based on the buy signals generated with the above function.
|
||||
Based on the results, hyperopt will tell you which parameter combination produced the best results (based on the configured [loss function](#loss-functions)).
|
||||
|
||||
The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators.
|
||||
When you want to test an indicator that isn't used by the bot currently, remember to
|
||||
add it to the `populate_indicators()` method in your custom hyperopt file.
|
||||
!!! Note
|
||||
The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators.
|
||||
When you want to test an indicator that isn't used by the bot currently, remember to
|
||||
add it to the `populate_indicators()` method in your strategy or hyperopt file.
|
||||
|
||||
## Loss-functions
|
||||
|
||||
Each hyperparameter tuning requires a target. This is usually defined as a loss function (sometimes also called objective function), which should decrease for more desirable results, and increase for bad results.
|
||||
|
||||
By default, Freqtrade uses a loss function, which has been with freqtrade since the beginning and optimizes mostly for short trade duration and avoiding losses.
|
||||
|
||||
A different loss function can be specified by using the `--hyperopt-loss <Class-name>` argument.
|
||||
A loss function must be specified via the `--hyperopt-loss <Class-name>` argument (or optionally via the configuration under the `"hyperopt_loss"` key).
|
||||
This class should be in its own file within the `user_data/hyperopts/` directory.
|
||||
|
||||
Currently, the following loss functions are builtin:
|
||||
|
||||
* `DefaultHyperOptLoss` (default legacy Freqtrade hyperoptimization loss function)
|
||||
* `ShortTradeDurHyperOptLoss` (default legacy Freqtrade hyperoptimization loss function) - Mostly for short trade duration and avoiding losses.
|
||||
* `OnlyProfitHyperOptLoss` (which takes only amount of profit into consideration)
|
||||
* `SharpeHyperOptLoss` (optimizes Sharpe Ratio calculated on trade returns relative to standard deviation)
|
||||
* `SharpeHyperOptLossDaily` (optimizes Sharpe Ratio calculated on **daily** trade returns relative to standard deviation)
|
||||
@@ -229,21 +243,20 @@ Because hyperopt tries a lot of combinations to find the best parameters it will
|
||||
We strongly recommend to use `screen` or `tmux` to prevent any connection loss.
|
||||
|
||||
```bash
|
||||
freqtrade hyperopt --config config.json --hyperopt <hyperoptname> -e 500 --spaces all
|
||||
freqtrade hyperopt --config config.json --hyperopt <hyperoptname> --hyperopt-loss <hyperoptlossname> --strategy <strategyname> -e 500 --spaces all
|
||||
```
|
||||
|
||||
Use `<hyperoptname>` as the name of the custom hyperopt used.
|
||||
|
||||
The `-e` option will set how many evaluations hyperopt will do. We recommend
|
||||
running at least several thousand evaluations.
|
||||
The `-e` option will set how many evaluations hyperopt will do. Since hyperopt uses Bayesian search, running too many epochs at once may not produce greater results. Experience has shown that best results are usually not improving much after 500-1000 epochs.
|
||||
Doing multiple runs (executions) with a few 1000 epochs and different random state will most likely produce different results.
|
||||
|
||||
The `--spaces all` option determines that all possible parameters should be optimized. Possibilities are listed below.
|
||||
|
||||
!!! Note
|
||||
By default, hyperopt will erase previous results and start from scratch. Continuation can be archived by using `--continue`.
|
||||
|
||||
!!! Warning
|
||||
When switching parameters or changing configuration options, make sure to not use the argument `--continue` so temporary results can be removed.
|
||||
Hyperopt will store hyperopt results with the timestamp of the hyperopt start time.
|
||||
Reading commands (`hyperopt-list`, `hyperopt-show`) can use `--hyperopt-filename <filename>` to read and display older hyperopt results.
|
||||
You can find a list of filenames with `ls -l user_data/hyperopt_results/`.
|
||||
|
||||
### Execute Hyperopt with different historical data source
|
||||
|
||||
@@ -251,13 +264,13 @@ If you would like to hyperopt parameters using an alternate historical data set
|
||||
you have on-disk, use the `--datadir PATH` option. By default, hyperopt
|
||||
uses data from directory `user_data/data`.
|
||||
|
||||
### Running Hyperopt with Smaller Testset
|
||||
### Running Hyperopt with a smaller test-set
|
||||
|
||||
Use the `--timerange` argument to change how much of the testset you want to use.
|
||||
Use the `--timerange` argument to change how much of the test-set you want to use.
|
||||
For example, to use one month of data, pass the following parameter to the hyperopt call:
|
||||
|
||||
```bash
|
||||
freqtrade hyperopt --timerange 20180401-20180501
|
||||
freqtrade hyperopt --hyperopt <hyperoptname> --strategy <strategyname> --timerange 20180401-20180501
|
||||
```
|
||||
|
||||
### Running Hyperopt using methods from a strategy
|
||||
@@ -265,16 +278,15 @@ freqtrade hyperopt --timerange 20180401-20180501
|
||||
Hyperopt can reuse `populate_indicators`, `populate_buy_trend`, `populate_sell_trend` from your strategy, assuming these methods are **not** in your custom hyperopt file, and a strategy is provided.
|
||||
|
||||
```bash
|
||||
freqtrade hyperopt --strategy SampleStrategy --hyperopt SampleHyperopt
|
||||
freqtrade hyperopt --hyperopt AwesomeHyperopt --hyperopt-loss SharpeHyperOptLossDaily --strategy AwesomeStrategy
|
||||
```
|
||||
|
||||
### Running Hyperopt with Smaller Search Space
|
||||
|
||||
Use the `--spaces` option 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.
|
||||
Or maybe you just want to optimize your stoploss or roi table for that awesome
|
||||
new buy strategy you have.
|
||||
Letting Hyperopt optimize everything is a huuuuge search space.
|
||||
Often it might make more sense to start by just searching for initial buy algorithm.
|
||||
Or maybe you just want to optimize your stoploss or roi table for that awesome new buy strategy you have.
|
||||
|
||||
Legal values are:
|
||||
|
||||
@@ -318,7 +330,7 @@ The initial state for generation of these random values (random state) is contro
|
||||
|
||||
If you have not set this value explicitly in the command line options, Hyperopt seeds the random state with some random value for you. The random state value for each Hyperopt run is shown in the log, so you can copy and paste it into the `--random-state` command line option to repeat the set of the initial random epochs used.
|
||||
|
||||
If you have not changed anything in the command line options, configuration, timerange, Strategy and Hyperopt classes, historical data and the Loss Function -- you should obtain same hyperoptimization results with same random state value used.
|
||||
If you have not changed anything in the command line options, configuration, timerange, Strategy and Hyperopt classes, historical data and the Loss Function -- you should obtain same hyper-optimization results with same random state value used.
|
||||
|
||||
## Understand the Hyperopt Result
|
||||
|
||||
@@ -371,7 +383,7 @@ By default, hyperopt prints colorized results -- epochs with positive profit are
|
||||
You can use the `--print-all` command line option if you would like to see all results in the hyperopt output, not only the best ones. When `--print-all` is used, current best results are also colorized by default -- they are printed in bold (bright) style. This can also be switched off with the `--no-color` command line option.
|
||||
|
||||
!!! Note "Windows and color output"
|
||||
Windows does not support color-output nativly, therefore it is automatically disabled. To have color-output for hyperopt running under windows, please consider using WSL.
|
||||
Windows does not support color-output natively, therefore it is automatically disabled. To have color-output for hyperopt running under windows, please consider using WSL.
|
||||
|
||||
### Understand Hyperopt ROI results
|
||||
|
||||
@@ -419,7 +431,9 @@ These ranges should be sufficient in most cases. The minutes in the steps (ROI d
|
||||
|
||||
If you have the `generate_roi_table()` and `roi_space()` methods in your custom hyperopt file, remove them in order to utilize these adaptive ROI tables and the ROI hyperoptimization space generated by Freqtrade by default.
|
||||
|
||||
Override the `roi_space()` method if you need components of the ROI tables to vary in other ranges. Override the `generate_roi_table()` and `roi_space()` methods and implement your own custom approach for generation of the ROI tables during hyperoptimization if you need a different structure of the ROI tables or other amount of rows (steps). A sample for these methods can be found in [user_data/hyperopts/sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_advanced.py).
|
||||
Override the `roi_space()` method if you need components of the ROI tables to vary in other ranges. Override the `generate_roi_table()` and `roi_space()` methods and implement your own custom approach for generation of the ROI tables during hyperoptimization if you need a different structure of the ROI tables or other amount of rows (steps).
|
||||
|
||||
A sample for these methods can be found in [sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_advanced.py).
|
||||
|
||||
### Understand Hyperopt Stoploss results
|
||||
|
||||
@@ -441,7 +455,7 @@ Stoploss: -0.27996
|
||||
|
||||
In order to use this best stoploss value found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the `stoploss` attribute of your custom strategy:
|
||||
|
||||
```
|
||||
``` python
|
||||
# Optimal stoploss designed for the strategy
|
||||
# This attribute will be overridden if the config file contains "stoploss"
|
||||
stoploss = -0.27996
|
||||
@@ -475,7 +489,7 @@ Trailing stop:
|
||||
|
||||
In order to use these best trailing stop parameters found by Hyperopt in backtesting and for live trades/dry-run, copy-paste them as the values of the corresponding attributes of your custom strategy:
|
||||
|
||||
```
|
||||
``` python
|
||||
# Trailing stop
|
||||
# These attributes will be overridden if the config file contains corresponding values.
|
||||
trailing_stop = True
|
||||
@@ -494,10 +508,14 @@ Override the `trailing_space()` method and define the desired range in it if you
|
||||
|
||||
## Show details of Hyperopt results
|
||||
|
||||
After you run Hyperopt for the desired amount of epochs, you can later list all results for analysis, select only best or profitable once, and show the details for any of the epochs previously evaluated. This can be done with the `hyperopt-list` and `hyperopt-show` subcommands. The usage of these subcommands is described in the [Utils](utils.md#list-hyperopt-results) chapter.
|
||||
After you run Hyperopt for the desired amount of epochs, you can later list all results for analysis, select only best or profitable once, and show the details for any of the epochs previously evaluated. This can be done with the `hyperopt-list` and `hyperopt-show` sub-commands. The usage of these sub-commands is described in the [Utils](utils.md#list-hyperopt-results) chapter.
|
||||
|
||||
## Validate backtesting results
|
||||
|
||||
Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.
|
||||
|
||||
To achieve same results (number of trades, their durations, profit, etc.) than during Hyperopt, please use same set of arguments `--dmmp`/`--disable-max-market-positions` and `--eps`/`--enable-position-stacking` for Backtesting.
|
||||
To achieve same results (number of trades, their durations, profit, etc.) than during Hyperopt, please use same configuration and parameters (timerange, timeframe, ...) used for hyperopt `--dmmp`/`--disable-max-market-positions` and `--eps`/`--enable-position-stacking` for Backtesting.
|
||||
|
||||
Should results don't match, please double-check to make sure you transferred all conditions correctly.
|
||||
Pay special care to the stoploss (and trailing stoploss) parameters, as these are often set in configuration files, which override changes to the strategy.
|
||||
You should also carefully review the log of your backtest to ensure that there were no parameters inadvertently set by the configuration (like `stoploss` or `trailing_stop`).
|
||||
|
194
docs/includes/pairlists.md
Normal file
194
docs/includes/pairlists.md
Normal file
@@ -0,0 +1,194 @@
|
||||
## Pairlists and Pairlist Handlers
|
||||
|
||||
Pairlist Handlers define the list of pairs (pairlist) that the bot should trade. They are configured in the `pairlists` section of the configuration settings.
|
||||
|
||||
In your configuration, you can use Static Pairlist (defined by the [`StaticPairList`](#static-pair-list) Pairlist Handler) and Dynamic Pairlist (defined by the [`VolumePairList`](#volume-pair-list) Pairlist Handler).
|
||||
|
||||
Additionally, [`AgeFilter`](#agefilter), [`PrecisionFilter`](#precisionfilter), [`PriceFilter`](#pricefilter), [`ShuffleFilter`](#shufflefilter) and [`SpreadFilter`](#spreadfilter) act as Pairlist Filters, removing certain pairs and/or moving their positions in the pairlist.
|
||||
|
||||
If multiple Pairlist Handlers are used, they are chained and a combination of all Pairlist Handlers forms the resulting pairlist the bot uses for trading and backtesting. Pairlist Handlers are executed in the sequence they are configured. You should always configure either `StaticPairList` or `VolumePairList` as the starting Pairlist Handler.
|
||||
|
||||
Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the `pair_blacklist` configuration setting) are also always removed from the resulting pairlist.
|
||||
|
||||
### Pair blacklist
|
||||
|
||||
The pair blacklist (configured via `exchange.pair_blacklist` in the configuration) disallows certain pairs from trading.
|
||||
This can be as simple as excluding `DOGE/BTC` - which will remove exactly this pair.
|
||||
|
||||
The pair-blacklist does also support wildcards (in regex-style) - so `BNB/.*` will exclude ALL pairs that start with BNB.
|
||||
You may also use something like `.*DOWN/BTC` or `.*UP/BTC` to exclude leveraged tokens (check Pair naming conventions for your exchange!)
|
||||
|
||||
### Available Pairlist Handlers
|
||||
|
||||
* [`StaticPairList`](#static-pair-list) (default, if not configured differently)
|
||||
* [`VolumePairList`](#volume-pair-list)
|
||||
* [`AgeFilter`](#agefilter)
|
||||
* [`PerformanceFilter`](#performancefilter)
|
||||
* [`PrecisionFilter`](#precisionfilter)
|
||||
* [`PriceFilter`](#pricefilter)
|
||||
* [`ShuffleFilter`](#shufflefilter)
|
||||
* [`SpreadFilter`](#spreadfilter)
|
||||
* [`RangeStabilityFilter`](#rangestabilityfilter)
|
||||
|
||||
!!! Tip "Testing pairlists"
|
||||
Pairlist configurations can be quite tricky to get right. Best use the [`test-pairlist`](utils.md#test-pairlist) utility sub-command to test your configuration quickly.
|
||||
|
||||
#### Static Pair List
|
||||
|
||||
By default, the `StaticPairList` method is used, which uses a statically defined pair whitelist from the configuration. The pairlist also supports wildcards (in regex-style) - so `.*/BTC` will include all pairs with BTC as a stake.
|
||||
|
||||
It uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`.
|
||||
|
||||
```json
|
||||
"pairlists": [
|
||||
{"method": "StaticPairList"}
|
||||
],
|
||||
```
|
||||
|
||||
By default, only currently enabled pairs are allowed.
|
||||
To skip pair validation against active markets, set `"allow_inactive": true` within the `StaticPairList` configuration.
|
||||
This can be useful for backtesting expired pairs (like quarterly spot-markets).
|
||||
This option must be configured along with `exchange.skip_pair_validation` in the exchange configuration.
|
||||
|
||||
#### Volume Pair List
|
||||
|
||||
`VolumePairList` employs sorting/filtering of pairs by their trading volume. It selects `number_assets` top pairs with sorting based on the `sort_key` (which can only be `quoteVolume`).
|
||||
|
||||
When used in the chain of Pairlist Handlers in a non-leading position (after StaticPairList and other Pairlist Filters), `VolumePairList` considers outputs of previous Pairlist Handlers, adding its sorting/selection of the pairs by the trading volume.
|
||||
|
||||
When used on the leading position of the chain of Pairlist Handlers, it does not consider `pair_whitelist` configuration setting, but selects the top assets from all available markets (with matching stake-currency) on the exchange.
|
||||
|
||||
The `refresh_period` setting allows to define the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes).
|
||||
|
||||
`VolumePairList` is based on the ticker data from exchange, as reported by the ccxt library:
|
||||
|
||||
* The `quoteVolume` is the amount of quote (stake) currency traded (bought or sold) in last 24 hours.
|
||||
|
||||
```json
|
||||
"pairlists": [{
|
||||
"method": "VolumePairList",
|
||||
"number_assets": 20,
|
||||
"sort_key": "quoteVolume",
|
||||
"refresh_period": 1800
|
||||
}],
|
||||
```
|
||||
|
||||
!!! Note
|
||||
`VolumePairList` does not support backtesting mode.
|
||||
|
||||
#### AgeFilter
|
||||
|
||||
Removes pairs that have been listed on the exchange for less than `min_days_listed` days (defaults to `10`).
|
||||
|
||||
When pairs are first listed on an exchange they can suffer huge price drops and volatility
|
||||
in the first few days while the pair goes through its price-discovery period. Bots can often
|
||||
be caught out buying before the pair has finished dropping in price.
|
||||
|
||||
This filter allows freqtrade to ignore pairs until they have been listed for at least `min_days_listed` days.
|
||||
|
||||
#### PerformanceFilter
|
||||
|
||||
Sorts pairs by past trade performance, as follows:
|
||||
1. Positive performance.
|
||||
2. No closed trades yet.
|
||||
3. Negative performance.
|
||||
|
||||
Trade count is used as a tie breaker.
|
||||
|
||||
!!! Note
|
||||
`PerformanceFilter` does not support backtesting mode.
|
||||
|
||||
#### PrecisionFilter
|
||||
|
||||
Filters low-value coins which would not allow setting stoplosses.
|
||||
|
||||
#### PriceFilter
|
||||
|
||||
The `PriceFilter` allows filtering of pairs by price. Currently the following price filters are supported:
|
||||
|
||||
* `min_price`
|
||||
* `max_price`
|
||||
* `low_price_ratio`
|
||||
|
||||
The `min_price` setting removes pairs where the price is below the specified price. This is useful if you wish to avoid trading very low-priced pairs.
|
||||
This option is disabled by default, and will only apply if set to > 0.
|
||||
|
||||
The `max_price` setting removes pairs where the price is above the specified price. This is useful if you wish to trade only low-priced pairs.
|
||||
This option is disabled by default, and will only apply if set to > 0.
|
||||
|
||||
The `low_price_ratio` setting removes pairs where a raise of 1 price unit (pip) is above the `low_price_ratio` ratio.
|
||||
This option is disabled by default, and will only apply if set to > 0.
|
||||
|
||||
For `PriceFiler` at least one of its `min_price`, `max_price` or `low_price_ratio` settings must be applied.
|
||||
|
||||
Calculation example:
|
||||
|
||||
Min price precision for SHITCOIN/BTC is 8 decimals. If its price is 0.00000011 - one price step above would be 0.00000012, which is ~9% higher than the previous price value. You may filter out this pair by using PriceFilter with `low_price_ratio` set to 0.09 (9%) or with `min_price` set to 0.00000011, correspondingly.
|
||||
|
||||
!!! Warning "Low priced pairs"
|
||||
Low priced pairs with high "1 pip movements" are dangerous since they are often illiquid and it may also be impossible to place the desired stoploss, which can often result in high losses since price needs to be rounded to the next tradable price - so instead of having a stoploss of -5%, you could end up with a stoploss of -9% simply due to price rounding.
|
||||
|
||||
#### ShuffleFilter
|
||||
|
||||
Shuffles (randomizes) pairs in the pairlist. It can be used for preventing the bot from trading some of the pairs more frequently then others when you want all pairs be treated with the same priority.
|
||||
|
||||
!!! Tip
|
||||
You may set the `seed` value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If `seed` is not set, the pairs are shuffled in the non-repeatable random order.
|
||||
|
||||
#### SpreadFilter
|
||||
|
||||
Removes pairs that have a difference between asks and bids above the specified ratio, `max_spread_ratio` (defaults to `0.005`).
|
||||
|
||||
Example:
|
||||
|
||||
If `DOGE/BTC` maximum bid is 0.00000026 and minimum ask is 0.00000027, the ratio is calculated as: `1 - bid/ask ~= 0.037` which is `> 0.005` and this pair will be filtered out.
|
||||
|
||||
#### RangeStabilityFilter
|
||||
|
||||
Removes pairs where the difference between lowest low and highest high over `lookback_days` days is below `min_rate_of_change`. Since this is a filter that requires additional data, the results are cached for `refresh_period`.
|
||||
|
||||
In the below example:
|
||||
If the trading range over the last 10 days is <1%, remove the pair from the whitelist.
|
||||
|
||||
```json
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "RangeStabilityFilter",
|
||||
"lookback_days": 10,
|
||||
"min_rate_of_change": 0.01,
|
||||
"refresh_period": 1440
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
!!! Tip
|
||||
This Filter can be used to automatically remove stable coin pairs, which have a very low trading range, and are therefore extremely difficult to trade with profit.
|
||||
|
||||
### Full example of Pairlist Handlers
|
||||
|
||||
The below example blacklists `BNB/BTC`, uses `VolumePairList` with `20` assets, sorting pairs by `quoteVolume` and applies both [`PrecisionFilter`](#precisionfilter) and [`PriceFilter`](#price-filter), filtering all assets where 1 price unit is > 1%. Then the `SpreadFilter` is applied and pairs are finally shuffled with the random seed set to some predefined value.
|
||||
|
||||
```json
|
||||
"exchange": {
|
||||
"pair_whitelist": [],
|
||||
"pair_blacklist": ["BNB/BTC"]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "VolumePairList",
|
||||
"number_assets": 20,
|
||||
"sort_key": "quoteVolume",
|
||||
},
|
||||
{"method": "AgeFilter", "min_days_listed": 10},
|
||||
{"method": "PrecisionFilter"},
|
||||
{"method": "PriceFilter", "low_price_ratio": 0.01},
|
||||
{"method": "SpreadFilter", "max_spread_ratio": 0.005},
|
||||
{
|
||||
"method": "RangeStabilityFilter",
|
||||
"lookback_days": 10,
|
||||
"min_rate_of_change": 0.01,
|
||||
"refresh_period": 1440
|
||||
},
|
||||
{"method": "ShuffleFilter", "seed": 42}
|
||||
],
|
||||
```
|
213
docs/includes/protections.md
Normal file
213
docs/includes/protections.md
Normal file
@@ -0,0 +1,213 @@
|
||||
## Protections
|
||||
|
||||
!!! Warning "Beta feature"
|
||||
This feature is still in it's testing phase. Should you notice something you think is wrong please let us know via Discord, Slack or via Github Issue.
|
||||
|
||||
Protections will protect your strategy from unexpected events and market conditions by temporarily stop trading for either one pair, or for all pairs.
|
||||
All protection end times are rounded up to the next candle to avoid sudden, unexpected intra-candle buys.
|
||||
|
||||
!!! Note
|
||||
Not all Protections will work for all strategies, and parameters will need to be tuned for your strategy to improve performance.
|
||||
To align your protection with your strategy, you can define protections in the strategy.
|
||||
|
||||
!!! Tip
|
||||
Each Protection can be configured multiple times with different parameters, to allow different levels of protection (short-term / long-term).
|
||||
|
||||
!!! Note "Backtesting"
|
||||
Protections are supported by backtesting and hyperopt, but must be explicitly enabled by using the `--enable-protections` flag.
|
||||
|
||||
### Available Protections
|
||||
|
||||
* [`StoplossGuard`](#stoploss-guard) Stop trading if a certain amount of stoploss occurred within a certain time window.
|
||||
* [`MaxDrawdown`](#maxdrawdown) Stop trading if max-drawdown is reached.
|
||||
* [`LowProfitPairs`](#low-profit-pairs) Lock pairs with low profits
|
||||
* [`CooldownPeriod`](#cooldown-period) Don't enter a trade right after selling a trade.
|
||||
|
||||
### Common settings to all Protections
|
||||
|
||||
| Parameter| Description |
|
||||
|------------|-------------|
|
||||
| `method` | Protection name to use. <br> **Datatype:** String, selected from [available Protections](#available-protections)
|
||||
| `stop_duration_candles` | For how many candles should the lock be set? <br> **Datatype:** Positive integer (in candles)
|
||||
| `stop_duration` | how many minutes should protections be locked. <br>Cannot be used together with `stop_duration_candles`. <br> **Datatype:** Float (in minutes)
|
||||
| `lookback_period_candles` | Only trades that completed within the last `lookback_period_candles` candles will be considered. This setting may be ignored by some Protections. <br> **Datatype:** Positive integer (in candles).
|
||||
| `lookback_period` | Only trades that completed after `current_time - lookback_period` will be considered. <br>Cannot be used together with `lookback_period_candles`. <br>This setting may be ignored by some Protections. <br> **Datatype:** Float (in minutes)
|
||||
| `trade_limit` | Number of trades required at minimum (not used by all Protections). <br> **Datatype:** Positive integer
|
||||
|
||||
!!! Note "Durations"
|
||||
Durations (`stop_duration*` and `lookback_period*` can be defined in either minutes or candles).
|
||||
For more flexibility when testing different timeframes, all below examples will use the "candle" definition.
|
||||
|
||||
#### Stoploss Guard
|
||||
|
||||
`StoplossGuard` selects all trades within `lookback_period` in minutes (or in candles when using `lookback_period_candles`), and determines if the amount of trades that resulted in stoploss are above `trade_limit` - in which case trading will stop for `stop_duration` in minutes (or in candles when using `stop_duration_candles`).
|
||||
This applies across all pairs, unless `only_per_pair` is set to true, which will then only look at one pair at a time.
|
||||
|
||||
The below example stops trading for all pairs for 4 candles after the last trade if the bot hit stoploss 4 times within the last 24 candles.
|
||||
|
||||
```json
|
||||
"protections": [
|
||||
{
|
||||
"method": "StoplossGuard",
|
||||
"lookback_period_candles": 24,
|
||||
"trade_limit": 4,
|
||||
"stop_duration_candles": 4,
|
||||
"only_per_pair": false
|
||||
}
|
||||
],
|
||||
```
|
||||
|
||||
!!! Note
|
||||
`StoplossGuard` considers all trades with the results `"stop_loss"`, `"stoploss_on_exchange"` and `"trailing_stop_loss"` if the resulting profit was negative.
|
||||
`trade_limit` and `lookback_period` will need to be tuned for your strategy.
|
||||
|
||||
#### MaxDrawdown
|
||||
|
||||
`MaxDrawdown` uses all trades within `lookback_period` in minutes (or in candles when using `lookback_period_candles`) to determine the maximum drawdown. If the drawdown is below `max_allowed_drawdown`, trading will stop for `stop_duration` in minutes (or in candles when using `stop_duration_candles`) after the last trade - assuming that the bot needs some time to let markets recover.
|
||||
|
||||
The below sample stops trading for 12 candles if max-drawdown is > 20% considering all pairs - with a minimum of `trade_limit` trades - within the last 48 candles. If desired, `lookback_period` and/or `stop_duration` can be used.
|
||||
|
||||
```json
|
||||
"protections": [
|
||||
{
|
||||
"method": "MaxDrawdown",
|
||||
"lookback_period_candles": 48,
|
||||
"trade_limit": 20,
|
||||
"stop_duration_candles": 12,
|
||||
"max_allowed_drawdown": 0.2
|
||||
},
|
||||
],
|
||||
```
|
||||
|
||||
#### Low Profit Pairs
|
||||
|
||||
`LowProfitPairs` uses all trades for a pair within `lookback_period` in minutes (or in candles when using `lookback_period_candles`) to determine the overall profit ratio.
|
||||
If that ratio is below `required_profit`, that pair will be locked for `stop_duration` in minutes (or in candles when using `stop_duration_candles`).
|
||||
|
||||
The below example will stop trading a pair for 60 minutes if the pair does not have a required profit of 2% (and a minimum of 2 trades) within the last 6 candles.
|
||||
|
||||
```json
|
||||
"protections": [
|
||||
{
|
||||
"method": "LowProfitPairs",
|
||||
"lookback_period_candles": 6,
|
||||
"trade_limit": 2,
|
||||
"stop_duration": 60,
|
||||
"required_profit": 0.02
|
||||
}
|
||||
],
|
||||
```
|
||||
|
||||
#### Cooldown Period
|
||||
|
||||
`CooldownPeriod` locks a pair for `stop_duration` in minutes (or in candles when using `stop_duration_candles`) after selling, avoiding a re-entry for this pair for `stop_duration` minutes.
|
||||
|
||||
The below example will stop trading a pair for 2 candles after closing a trade, allowing this pair to "cool down".
|
||||
|
||||
```json
|
||||
"protections": [
|
||||
{
|
||||
"method": "CooldownPeriod",
|
||||
"stop_duration_candles": 2
|
||||
}
|
||||
],
|
||||
```
|
||||
|
||||
!!! Note
|
||||
This Protection applies only at pair-level, and will never lock all pairs globally.
|
||||
This Protection does not consider `lookback_period` as it only looks at the latest trade.
|
||||
|
||||
### Full example of Protections
|
||||
|
||||
All protections can be combined at will, also with different parameters, creating a increasing wall for under-performing pairs.
|
||||
All protections are evaluated in the sequence they are defined.
|
||||
|
||||
The below example assumes a timeframe of 1 hour:
|
||||
|
||||
* Locks each pair after selling for an additional 5 candles (`CooldownPeriod`), giving other pairs a chance to get filled.
|
||||
* Stops trading for 4 hours (`4 * 1h candles`) if the last 2 days (`48 * 1h candles`) had 20 trades, which caused a max-drawdown of more than 20%. (`MaxDrawdown`).
|
||||
* Stops trading if more than 4 stoploss occur for all pairs within a 1 day (`24 * 1h candles`) limit (`StoplossGuard`).
|
||||
* Locks all pairs that had 4 Trades within the last 6 hours (`6 * 1h candles`) with a combined profit ratio of below 0.02 (<2%) (`LowProfitPairs`).
|
||||
* Locks all pairs for 2 candles that had a profit of below 0.01 (<1%) within the last 24h (`24 * 1h candles`), a minimum of 4 trades.
|
||||
|
||||
```json
|
||||
"timeframe": "1h",
|
||||
"protections": [
|
||||
{
|
||||
"method": "CooldownPeriod",
|
||||
"stop_duration_candles": 5
|
||||
},
|
||||
{
|
||||
"method": "MaxDrawdown",
|
||||
"lookback_period_candles": 48,
|
||||
"trade_limit": 20,
|
||||
"stop_duration_candles": 4,
|
||||
"max_allowed_drawdown": 0.2
|
||||
},
|
||||
{
|
||||
"method": "StoplossGuard",
|
||||
"lookback_period_candles": 24,
|
||||
"trade_limit": 4,
|
||||
"stop_duration_candles": 2,
|
||||
"only_per_pair": false
|
||||
},
|
||||
{
|
||||
"method": "LowProfitPairs",
|
||||
"lookback_period_candles": 6,
|
||||
"trade_limit": 2,
|
||||
"stop_duration_candles": 60,
|
||||
"required_profit": 0.02
|
||||
},
|
||||
{
|
||||
"method": "LowProfitPairs",
|
||||
"lookback_period_candles": 24,
|
||||
"trade_limit": 4,
|
||||
"stop_duration_candles": 2,
|
||||
"required_profit": 0.01
|
||||
}
|
||||
],
|
||||
```
|
||||
|
||||
You can use the same in your strategy, the syntax is only slightly different:
|
||||
|
||||
``` python
|
||||
from freqtrade.strategy import IStrategy
|
||||
|
||||
class AwesomeStrategy(IStrategy)
|
||||
timeframe = '1h'
|
||||
protections = [
|
||||
{
|
||||
"method": "CooldownPeriod",
|
||||
"stop_duration_candles": 5
|
||||
},
|
||||
{
|
||||
"method": "MaxDrawdown",
|
||||
"lookback_period_candles": 48,
|
||||
"trade_limit": 20,
|
||||
"stop_duration_candles": 4,
|
||||
"max_allowed_drawdown": 0.2
|
||||
},
|
||||
{
|
||||
"method": "StoplossGuard",
|
||||
"lookback_period_candles": 24,
|
||||
"trade_limit": 4,
|
||||
"stop_duration_candles": 2,
|
||||
"only_per_pair": False
|
||||
},
|
||||
{
|
||||
"method": "LowProfitPairs",
|
||||
"lookback_period_candles": 6,
|
||||
"trade_limit": 2,
|
||||
"stop_duration_candles": 60,
|
||||
"required_profit": 0.02
|
||||
},
|
||||
{
|
||||
"method": "LowProfitPairs",
|
||||
"lookback_period_candles": 24,
|
||||
"trade_limit": 4,
|
||||
"stop_duration_candles": 2,
|
||||
"required_profit": 0.01
|
||||
}
|
||||
]
|
||||
# ...
|
||||
```
|
@@ -14,7 +14,7 @@
|
||||
|
||||
## Introduction
|
||||
|
||||
Freqtrade is a crypto-currency algorithmic trading software developed in python (3.6+) and supported on Windows, macOS and Linux.
|
||||
Freqtrade is a crypto-currency algorithmic trading software developed in python (3.7+) and supported on Windows, macOS and Linux.
|
||||
|
||||
!!! Danger "DISCLAIMER"
|
||||
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.
|
||||
@@ -51,7 +51,7 @@ To run this bot we recommend you a linux cloud instance with a minimum of:
|
||||
|
||||
Alternatively
|
||||
|
||||
- Python 3.6.x
|
||||
- Python 3.7+
|
||||
- pip (pip3)
|
||||
- git
|
||||
- TA-Lib
|
||||
@@ -59,11 +59,14 @@ Alternatively
|
||||
|
||||
## Support
|
||||
|
||||
### Help / Slack
|
||||
For any questions not covered by the documentation or for further information about the bot, we encourage you to join our passionate Slack community.
|
||||
### Help / Discord / Slack
|
||||
|
||||
Click [here](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE) to join the Freqtrade Slack channel.
|
||||
For any questions not covered by the documentation or for further information about the bot, or to simply engage with like-minded individuals, we encourage you to join our slack channel.
|
||||
|
||||
Please check out our [discord server](https://discord.gg/MA9v74M).
|
||||
|
||||
You can also join our [Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/zt-l9d9iqgl-9cVBIeBkCBa8j6upSmd_NA).
|
||||
|
||||
## Ready to try?
|
||||
|
||||
Begin by reading our installation guide [for docker](docker.md), or for [installation without docker](installation.md).
|
||||
Begin by reading our installation guide [for docker](docker_quickstart.md) (recommended), or for [installation without docker](installation.md).
|
||||
|
@@ -2,7 +2,7 @@
|
||||
|
||||
This page explains how to prepare your environment for running the bot.
|
||||
|
||||
Please consider using the prebuilt [docker images](docker.md) to get started quickly while trying out freqtrade evaluating how it operates.
|
||||
Please consider using the prebuilt [docker images](docker_quickstart.md) to get started quickly while evaluating how freqtrade works.
|
||||
|
||||
## Prerequisite
|
||||
|
||||
@@ -10,7 +10,7 @@ Please consider using the prebuilt [docker images](docker.md) to get started qui
|
||||
|
||||
Click each one for install guide:
|
||||
|
||||
* [Python >= 3.6.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
||||
* [Python >= 3.7.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
||||
* [pip](https://pip.pypa.io/en/stable/installing/)
|
||||
* [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
* [virtualenv](https://virtualenv.pypa.io/en/stable/installation.html) (Recommended)
|
||||
@@ -34,7 +34,8 @@ The easiest way to install and run Freqtrade is to clone the bot Github reposito
|
||||
When cloning the repository the default working branch has the name `develop`. This branch contains all last features (can be considered as relatively stable, thanks to automated tests). The `stable` branch contains the code of the last release (done usually once per month on an approximately one week old snapshot of the `develop` branch to prevent packaging bugs, so potentially it's more stable).
|
||||
|
||||
!!! Note
|
||||
Python3.6 or higher and the corresponding `pip` are assumed to be available. The install-script will warn you and stop if that's not the case. `git` is also needed to clone the Freqtrade repository.
|
||||
Python3.7 or higher and the corresponding `pip` are assumed to be available. The install-script will warn you and stop if that's not the case. `git` is also needed to clone the Freqtrade repository.
|
||||
Also, python headers (`python<yourversion>-dev` / `python<yourversion>-devel`) must be available for the installation to complete successfully.
|
||||
|
||||
This can be achieved with the following commands:
|
||||
|
||||
@@ -63,7 +64,7 @@ usage:
|
||||
** --install **
|
||||
|
||||
With this option, the script will install the bot and most dependencies:
|
||||
You will need to have git and python3.6+ installed beforehand for this to work.
|
||||
You will need to have git and python3.7+ installed beforehand for this to work.
|
||||
|
||||
* Mandatory software as: `ta-lib`
|
||||
* Setup your virtualenv under `.env/`
|
||||
@@ -90,13 +91,13 @@ Each time you open a new terminal, you must run `source .env/bin/activate`.
|
||||
|
||||
## Custom Installation
|
||||
|
||||
We've included/collected install instructions for Ubuntu 16.04, MacOS, and Windows. These are guidelines and your success may vary with other distros.
|
||||
We've included/collected install instructions for Ubuntu, MacOS, and Windows. These are guidelines and your success may vary with other distros.
|
||||
OS Specific steps are listed first, the [Common](#common) section below is necessary for all systems.
|
||||
|
||||
!!! Note
|
||||
Python3.6 or higher and the corresponding pip are assumed to be available.
|
||||
Python3.7 or higher and the corresponding pip are assumed to be available.
|
||||
|
||||
=== "Ubuntu 16.04"
|
||||
=== "Ubuntu/Debian"
|
||||
#### Install necessary dependencies
|
||||
|
||||
```bash
|
||||
@@ -105,13 +106,17 @@ OS Specific steps are listed first, the [Common](#common) section below is neces
|
||||
```
|
||||
|
||||
=== "RaspberryPi/Raspbian"
|
||||
The following assumes the latest [Raspbian Buster lite image](https://www.raspberrypi.org/downloads/raspbian/) from at least September 2019.
|
||||
The following assumes the latest [Raspbian Buster lite image](https://www.raspberrypi.org/downloads/raspbian/).
|
||||
This image comes with python3.7 preinstalled, making it easy to get freqtrade up and running.
|
||||
|
||||
Tested using a Raspberry Pi 3 with the Raspbian Buster lite image, all updates applied.
|
||||
|
||||
|
||||
``` bash
|
||||
sudo apt-get install python3-venv libatlas-base-dev
|
||||
sudo apt-get install python3-venv libatlas-base-dev cmake
|
||||
# Use pywheels.org to speed up installation
|
||||
sudo echo "[global]\nextra-index-url=https://www.piwheels.org/simple" > tee /etc/pip.conf
|
||||
|
||||
git clone https://github.com/freqtrade/freqtrade.git
|
||||
cd freqtrade
|
||||
|
||||
@@ -120,6 +125,7 @@ OS Specific steps are listed first, the [Common](#common) section below is neces
|
||||
|
||||
!!! Note "Installation duration"
|
||||
Depending on your internet speed and the Raspberry Pi version, installation can take multiple hours to complete.
|
||||
Due to this, we recommend to use the prebuild docker-image for Raspberry, by following the [Docker quickstart documentation](docker_quickstart.md)
|
||||
|
||||
!!! Note
|
||||
The above does not install hyperopt dependencies. To install these, please use `python3 -m pip install -e .[hyperopt]`.
|
||||
@@ -204,7 +210,7 @@ If this is the first time you run the bot, ensure you are running it in Dry-run
|
||||
freqtrade trade -c config.json
|
||||
```
|
||||
|
||||
*Note*: If you run the bot on a server, you should consider using [Docker](docker.md) or a terminal multiplexer like `screen` or [`tmux`](https://en.wikipedia.org/wiki/Tmux) to avoid that the bot is stopped on logout.
|
||||
*Note*: If you run the bot on a server, you should consider using [Docker compose](docker_quickstart.md) or a terminal multiplexer like `screen` or [`tmux`](https://en.wikipedia.org/wiki/Tmux) to avoid that the bot is stopped on logout.
|
||||
|
||||
#### 7. (Optional) Post-installation Tasks
|
||||
|
||||
@@ -239,6 +245,19 @@ open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10
|
||||
|
||||
If this file is inexistent, then you're probably on a different version of MacOS, so you may need to consult the internet for specific resolution details.
|
||||
|
||||
### MacOS installation error with python 3.9
|
||||
|
||||
When using python 3.9 on macOS, it's currently necessary to install some os-level modules to allow dependencies to compile.
|
||||
The errors you'll see happen during installation and are related to the installation of `tables` or `blosc`.
|
||||
|
||||
You can install the necessary libraries with the following command:
|
||||
|
||||
``` bash
|
||||
brew install hdf5 c-blosc
|
||||
```
|
||||
|
||||
After this, please run the installation (script) again.
|
||||
|
||||
-----
|
||||
|
||||
Now you have an environment ready, the next step is
|
||||
|
@@ -1,54 +1,51 @@
|
||||
{#-
|
||||
This file was automatically generated - do not edit
|
||||
-#}
|
||||
{% set site_url = config.site_url | d(nav.homepage.url, true) | url %}
|
||||
{% if not config.use_directory_urls and site_url[0] == site_url[-1] == "." %}
|
||||
{% set site_url = site_url ~ "/index.html" %}
|
||||
{% endif %}
|
||||
<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 %}
|
||||
<nav class="md-header-nav md-grid" aria-label="{{ lang.t('header.title') }}">
|
||||
<a href="{{ site_url }}" title="{{ config.site_name | e }}" class="md-header-nav__button md-logo"
|
||||
aria-label="{{ config.site_name }}">
|
||||
{% include "partials/logo.html" %}
|
||||
</a>
|
||||
<label class="md-header-nav__button md-icon" for="__drawer">
|
||||
{% include ".icons/material/menu" ~ ".svg" %}
|
||||
</label>
|
||||
<div class="md-header-nav__title" data-md-component="header-title">
|
||||
<div class="md-header-nav__ellipsis">
|
||||
<div class="md-header-nav__topic">
|
||||
<span class="md-ellipsis">
|
||||
{{ config.site_name }}
|
||||
</span>
|
||||
</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>
|
||||
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
|
||||
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
|
||||
<div class="md-header-nav__topic">
|
||||
<span class="md-ellipsis">
|
||||
{% if page and page.meta and page.meta.title %}
|
||||
{{ page.meta.title }}
|
||||
{% else %}
|
||||
{{ page.title }}
|
||||
{% endif %}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% if "search" in config["plugins"] %}
|
||||
<label class="md-header-nav__button md-icon" for="__search">
|
||||
{% include ".icons/material/magnify.svg" %}
|
||||
</label>
|
||||
{% include "partials/search.html" %}
|
||||
{% endif %}
|
||||
{% if config.repo_url %}
|
||||
<div class="md-header-nav__source">
|
||||
{% include "partials/source.html" %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</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>
|
||||
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
|
||||
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
|
||||
</header>
|
||||
|
@@ -168,6 +168,7 @@ Additional features when using plot_config include:
|
||||
|
||||
* Specify colors per indicator
|
||||
* Specify additional subplots
|
||||
* Specify indicator pairs to fill area in between
|
||||
|
||||
The sample plot configuration below specifies fixed colors for the indicators. Otherwise consecutive plots may produce different colorschemes each time, making comparisons difficult.
|
||||
It also allows multiple subplots to display both MACD and RSI at the same time.
|
||||
@@ -183,23 +184,34 @@ Sample configuration with inline comments explaining the process:
|
||||
'ema50': {'color': '#CCCCCC'},
|
||||
# By omitting color, a random color is selected.
|
||||
'sar': {},
|
||||
# fill area between senkou_a and senkou_b
|
||||
'senkou_a': {
|
||||
'color': 'green', #optional
|
||||
'fill_to': 'senkou_b',
|
||||
'fill_label': 'Ichimoku Cloud' #optional,
|
||||
'fill_color': 'rgba(255,76,46,0.2)', #optional
|
||||
},
|
||||
# plot senkou_b, too. Not only the area to it.
|
||||
'senkou_b': {}
|
||||
},
|
||||
'subplots': {
|
||||
# Create subplot MACD
|
||||
"MACD": {
|
||||
'macd': {'color': 'blue'},
|
||||
'macdsignal': {'color': 'orange'},
|
||||
'macd': {'color': 'blue', 'fill_to': 'macdhist'},
|
||||
'macdsignal': {'color': 'orange'}
|
||||
},
|
||||
# Additional subplot RSI
|
||||
"RSI": {
|
||||
'rsi': {'color': 'red'},
|
||||
'rsi': {'color': 'red'}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
!!! Note
|
||||
The above configuration assumes that `ema10`, `ema50`, `macd`, `macdsignal` and `rsi` are columns in the DataFrame created by the strategy.
|
||||
The above configuration assumes that `ema10`, `ema50`, `senkou_a`, `senkou_b`,
|
||||
`macd`, `macdsignal`, `macdhist` and `rsi` are columns in the DataFrame created by the strategy.
|
||||
|
||||
## Plot profit
|
||||
|
||||
|
3
docs/plugins.md
Normal file
3
docs/plugins.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# Plugins
|
||||
--8<-- "includes/pairlists.md"
|
||||
--8<-- "includes/protections.md"
|
@@ -1,2 +1,3 @@
|
||||
mkdocs-material==5.5.13
|
||||
mkdocs-material==6.2.5
|
||||
mdx_truly_sane_lists==1.2
|
||||
pymdown-extensions==8.1
|
||||
|
@@ -11,7 +11,8 @@ Sample configuration:
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8080,
|
||||
"verbosity": "info",
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "somethingrandom",
|
||||
"CORS_origins": [],
|
||||
"username": "Freqtrader",
|
||||
@@ -104,32 +105,43 @@ By default, the script assumes `127.0.0.1` (localhost) and port `8080` to be use
|
||||
python3 scripts/rest_client.py --config rest_config.json <command> [optional parameters]
|
||||
```
|
||||
|
||||
## Available commands
|
||||
## Available endpoints
|
||||
|
||||
| Command | Description |
|
||||
|----------|-------------|
|
||||
| `ping` | Simple command testing the API Readiness - requires no authentication.
|
||||
| `start` | Starts the trader
|
||||
| `stop` | Stops the trader
|
||||
| `start` | Starts the trader.
|
||||
| `stop` | Stops the trader.
|
||||
| `stopbuy` | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
||||
| `reload_config` | Reloads the configuration file
|
||||
| `reload_config` | Reloads the configuration file.
|
||||
| `trades` | List last trades.
|
||||
| `delete_trade <trade_id>` | Remove trade from the database. Tries to close open orders. Requires manual handling of this trade on the exchange.
|
||||
| `show_config` | Shows part of the current configuration with relevant settings to operation
|
||||
| `logs` | Shows last log messages
|
||||
| `status` | Lists all open trades
|
||||
| `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
|
||||
| `show_config` | Shows part of the current configuration with relevant settings to operation.
|
||||
| `logs` | Shows last log messages.
|
||||
| `status` | Lists all open trades.
|
||||
| `count` | Displays number of trades used and available.
|
||||
| `locks` | Displays currently locked pairs.
|
||||
| `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>` | Shows profit or loss per day, over the last n days (n defaults to 7)
|
||||
| `whitelist` | Show the current whitelist
|
||||
| `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 (n defaults to 7).
|
||||
| `stats` | Display a summary of profit / loss reasons as well as average holding times.
|
||||
| `whitelist` | Show the current whitelist.
|
||||
| `blacklist [pair]` | Show the current blacklist, or adds a pair to the blacklist.
|
||||
| `edge` | Show validated pairs by Edge if it is enabled.
|
||||
| `version` | Show version
|
||||
| `pair_candles` | Returns dataframe for a pair / timeframe combination while the bot is running. **Alpha**
|
||||
| `pair_history` | Returns an analyzed dataframe for a given timerange, analyzed by a given strategy. **Alpha**
|
||||
| `plot_config` | Get plot config from the strategy (or nothing if not configured). **Alpha**
|
||||
| `strategies` | List strategies in strategy directory. **Alpha**
|
||||
| `strategy <strategy>` | Get specific Strategy content. **Alpha**
|
||||
| `available_pairs` | List available backtest data. **Alpha**
|
||||
| `version` | Show version.
|
||||
|
||||
!!! Warning "Alpha status"
|
||||
Endpoints labeled with *Alpha status* above may change at any time without notice.
|
||||
|
||||
Possible commands can be listed from the rest-client script using the `help` command.
|
||||
|
||||
@@ -140,6 +152,12 @@ python3 scripts/rest_client.py help
|
||||
``` output
|
||||
Possible commands:
|
||||
|
||||
available_pairs
|
||||
Return available pair (backtest data) based on timeframe / stake_currency selection
|
||||
|
||||
:param timeframe: Only pairs with this timeframe available.
|
||||
:param stake_currency: Only pairs that include this timeframe
|
||||
|
||||
balance
|
||||
Get the account balance.
|
||||
|
||||
@@ -179,9 +197,27 @@ logs
|
||||
|
||||
:param limit: Limits log messages to the last <limit> logs. No limit to get all the trades.
|
||||
|
||||
pair_candles
|
||||
Return live dataframe for <pair><timeframe>.
|
||||
|
||||
:param pair: Pair to get data for
|
||||
:param timeframe: Only pairs with this timeframe available.
|
||||
:param limit: Limit result to the last n candles.
|
||||
|
||||
pair_history
|
||||
Return historic, analyzed dataframe
|
||||
|
||||
:param pair: Pair to get data for
|
||||
:param timeframe: Only pairs with this timeframe available.
|
||||
:param strategy: Strategy to analyze and get values for
|
||||
:param timerange: Timerange to get data for (same format than --timerange endpoints)
|
||||
|
||||
performance
|
||||
Return the performance of the different coins.
|
||||
|
||||
plot_config
|
||||
Return plot configuration if the strategy defines one.
|
||||
|
||||
profit
|
||||
Return the profit summary.
|
||||
|
||||
@@ -195,6 +231,9 @@ show_config
|
||||
start
|
||||
Start the bot if it's in the stopped state.
|
||||
|
||||
stats
|
||||
Return the stats report (durations, sell-reasons).
|
||||
|
||||
status
|
||||
Get the status of open trades.
|
||||
|
||||
@@ -204,6 +243,14 @@ stop
|
||||
stopbuy
|
||||
Stop buying (but handle sells gracefully). Use `reload_config` to reset.
|
||||
|
||||
strategies
|
||||
Lists available strategies
|
||||
|
||||
strategy
|
||||
Get strategy details
|
||||
|
||||
:param strategy: Strategy class name
|
||||
|
||||
trades
|
||||
Return trades history.
|
||||
|
||||
@@ -215,9 +262,13 @@ version
|
||||
whitelist
|
||||
Show the current whitelist.
|
||||
|
||||
|
||||
```
|
||||
|
||||
## OpenAPI interface
|
||||
|
||||
To enable the builtin openAPI interface (Swagger UI), specify `"enable_openapi": true` in the api_server configuration.
|
||||
This will enable the Swagger UI at the `/docs` endpoint. By default, that's running at http://localhost:8080/docs/ - but it'll depend on your settings.
|
||||
|
||||
## Advanced API usage using JWT tokens
|
||||
|
||||
!!! Note
|
||||
|
@@ -43,52 +43,6 @@ sqlite3
|
||||
.schema <table_name>
|
||||
```
|
||||
|
||||
### Trade table structure
|
||||
|
||||
```sql
|
||||
CREATE TABLE trades(
|
||||
id INTEGER NOT NULL,
|
||||
exchange VARCHAR NOT NULL,
|
||||
pair VARCHAR NOT NULL,
|
||||
is_open BOOLEAN NOT NULL,
|
||||
fee_open FLOAT NOT NULL,
|
||||
fee_open_cost FLOAT,
|
||||
fee_open_currency VARCHAR,
|
||||
fee_close FLOAT NOT NULL,
|
||||
fee_close_cost FLOAT,
|
||||
fee_close_currency VARCHAR,
|
||||
open_rate FLOAT,
|
||||
open_rate_requested FLOAT,
|
||||
open_trade_price FLOAT,
|
||||
close_rate FLOAT,
|
||||
close_rate_requested FLOAT,
|
||||
close_profit FLOAT,
|
||||
close_profit_abs FLOAT,
|
||||
stake_amount FLOAT NOT NULL,
|
||||
amount FLOAT,
|
||||
open_date DATETIME NOT NULL,
|
||||
close_date DATETIME,
|
||||
open_order_id VARCHAR,
|
||||
stop_loss FLOAT,
|
||||
stop_loss_pct FLOAT,
|
||||
initial_stop_loss FLOAT,
|
||||
initial_stop_loss_pct FLOAT,
|
||||
stoploss_order_id VARCHAR,
|
||||
stoploss_last_update DATETIME,
|
||||
max_rate FLOAT,
|
||||
min_rate FLOAT,
|
||||
sell_reason VARCHAR,
|
||||
strategy VARCHAR,
|
||||
timeframe INTEGER,
|
||||
PRIMARY KEY (id),
|
||||
CHECK (is_open IN (0, 1))
|
||||
);
|
||||
CREATE INDEX ix_trades_stoploss_order_id ON trades (stoploss_order_id);
|
||||
CREATE INDEX ix_trades_pair ON trades (pair);
|
||||
CREATE INDEX ix_trades_is_open ON trades (is_open);
|
||||
|
||||
```
|
||||
|
||||
## Get all trades in the table
|
||||
|
||||
```sql
|
||||
@@ -98,11 +52,11 @@ SELECT * FROM trades;
|
||||
## Fix trade still open after a manual sell on the exchange
|
||||
|
||||
!!! Warning
|
||||
Manually selling a pair on the exchange will not be detected by the bot and it will try to sell anyway. Whenever possible, forcesell <tradeid> should be used to accomplish the same thing.
|
||||
It is strongly advised to backup your database file before making any manual changes.
|
||||
Manually selling a pair on the exchange will not be detected by the bot and it will try to sell anyway. Whenever possible, forcesell <tradeid> should be used to accomplish the same thing.
|
||||
It is strongly advised to backup your database file before making any manual changes.
|
||||
|
||||
!!! Note
|
||||
This should not be necessary after /forcesell, as forcesell orders are closed automatically by the bot on the next iteration.
|
||||
This should not be necessary after /forcesell, as forcesell orders are closed automatically by the bot on the next iteration.
|
||||
|
||||
```sql
|
||||
UPDATE trades
|
||||
@@ -128,23 +82,12 @@ SET is_open=0,
|
||||
WHERE id=31;
|
||||
```
|
||||
|
||||
## Manually insert a new trade
|
||||
|
||||
```sql
|
||||
INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date)
|
||||
VALUES ('binance', 'ETH/BTC', 1, 0.0025, 0.0025, <open_rate>, <stake_amount>, <amount>, '<datetime>')
|
||||
```
|
||||
|
||||
### Insert trade example
|
||||
|
||||
```sql
|
||||
INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date)
|
||||
VALUES ('binance', 'ETH/BTC', 1, 0.0025, 0.0025, 0.00258580, 0.002, 0.7715262081, '2020-06-28 12:44:24.000000')
|
||||
```
|
||||
|
||||
## Remove trade from the database
|
||||
|
||||
Maybe you'd like to remove a trade from the database, because something went wrong.
|
||||
!!! Tip "Use RPC Methods to delete trades"
|
||||
Consider using `/delete <tradeid>` via telegram or rest API. That's the recommended way to deleting trades.
|
||||
|
||||
If you'd still like to remove a trade from the database directly, you can use the below query.
|
||||
|
||||
```sql
|
||||
DELETE FROM trades WHERE id = <tradeid>;
|
||||
|
@@ -23,11 +23,12 @@ These modes can be configured with these values:
|
||||
```
|
||||
|
||||
!!! Note
|
||||
Stoploss on exchange is only supported for Binance (stop-loss-limit), Kraken (stop-loss-market) and FTX (stop limit and stop-market) as of now.
|
||||
<ins>Do not set too low stoploss value if using stop loss on exchange!</ins>
|
||||
If set to low/tight then you have greater risk of missing fill on the order and stoploss will not work
|
||||
Stoploss on exchange is only supported for Binance (stop-loss-limit), Kraken (stop-loss-market, stop-loss-limit) and FTX (stop limit and stop-market) as of now.
|
||||
<ins>Do not set too low/tight stoploss value if using stop loss on exchange!</ins>
|
||||
If set to low/tight then you have greater risk of missing fill on the order and stoploss will not work.
|
||||
|
||||
### stoploss_on_exchange and stoploss_on_exchange_limit_ratio
|
||||
|
||||
Enable or Disable stop loss on exchange.
|
||||
If the stoploss is *on exchange* it means a stoploss limit order is placed on the exchange immediately after buy order happens successfully. This will protect you against sudden crashes in market as the order will be in the queue immediately and if market goes down then the order has more chance of being fulfilled.
|
||||
|
||||
@@ -35,18 +36,23 @@ If `stoploss_on_exchange` uses limit orders, the exchange needs 2 prices, the st
|
||||
`stoploss` defines the stop-price where the limit order is placed - and limit should be slightly below this.
|
||||
If an exchange supports both limit and market stoploss orders, then the value of `stoploss` will be used to determine the stoploss type.
|
||||
|
||||
Calculation example: we bought the asset at 100$.
|
||||
Stop-price is 95$, then limit would be `95 * 0.99 = 94.05$` - so the limit order fill can happen between 95$ and 94.05$.
|
||||
Calculation example: we bought the asset at 100\$.
|
||||
Stop-price is 95\$, then limit would be `95 * 0.99 = 94.05$` - so the limit order fill can happen between 95$ and 94.05$.
|
||||
|
||||
For example, assuming the stoploss is on exchange, and trailing stoploss is enabled, and the market is going up, then the bot automatically cancels the previous stoploss order and puts a new one with a stop value higher than the previous stoploss order.
|
||||
|
||||
!!! Note
|
||||
If `stoploss_on_exchange` is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order.
|
||||
|
||||
### stoploss_on_exchange_interval
|
||||
|
||||
In case of stoploss on exchange there is another parameter called `stoploss_on_exchange_interval`. This configures the interval in seconds at which the bot will check the stoploss and update it if necessary.
|
||||
The bot cannot do these every 5 seconds (at each iteration), otherwise it would get banned by the exchange.
|
||||
So this parameter will tell the bot how often it should update the stoploss order. The default value is 60 (1 minute).
|
||||
This same logic will reapply a stoploss order on the exchange should you cancel it accidentally.
|
||||
|
||||
### emergencysell
|
||||
|
||||
`emergencysell` is an optional value, which defaults to `market` and is used when creating stop loss on exchange orders fails.
|
||||
The below is the default which is used if not changed in strategy or configuration file.
|
||||
|
||||
@@ -72,6 +78,7 @@ At this stage the bot contains the following stoploss support modes:
|
||||
2. Trailing stop loss.
|
||||
3. Trailing stop loss, custom positive loss.
|
||||
4. Trailing stop loss only once the trade has reached a certain offset.
|
||||
5. [Custom stoploss function](strategy-advanced.md#custom-stoploss)
|
||||
|
||||
### Static Stop Loss
|
||||
|
||||
@@ -84,6 +91,7 @@ Example of stop loss:
|
||||
```
|
||||
|
||||
For example, simplified math:
|
||||
|
||||
* the bot buys an asset at a price of 100$
|
||||
* the stop loss is defined at -10%
|
||||
* the stop loss would get triggered once the asset drops below 90$
|
||||
@@ -107,7 +115,7 @@ For example, simplified math:
|
||||
* the stop loss would get triggered once the asset drops below 90$
|
||||
* assuming the asset now increases to 102$
|
||||
* the stop loss will now be -10% of 102$ = 91.8$
|
||||
* now the asset drops in value to 101$, the stop loss will still be 91.8$ and would trigger at 91.8$.
|
||||
* now the asset drops in value to 101\$, the stop loss will still be 91.8$ and would trigger at 91.8$.
|
||||
|
||||
In summary: The stoploss will be adjusted to be always be -10% of the highest observed price.
|
||||
|
||||
@@ -133,8 +141,8 @@ For example, simplified math:
|
||||
* the stop loss is defined at -10%
|
||||
* the stop loss would get triggered once the asset drops below 90$
|
||||
* assuming the asset now increases to 102$
|
||||
* the stop loss will now be -2% of 102$ = 99.96$ (99.96$ stop loss will be locked in and will follow asset price increasements with -2%)
|
||||
* now the asset drops in value to 101$, the stop loss will still be 99.96$ and would trigger at 99.96$
|
||||
* the stop loss will now be -2% of 102$ = 99.96$ (99.96$ stop loss will be locked in and will follow asset price increments with -2%)
|
||||
* now the asset drops in value to 101\$, the stop loss will still be 99.96$ and would trigger at 99.96$
|
||||
|
||||
The 0.02 would translate to a -2% stop loss.
|
||||
Before this, `stoploss` is used for the trailing stoploss.
|
||||
@@ -151,7 +159,7 @@ This option can be used with or without `trailing_stop_positive`, but uses `trai
|
||||
trailing_only_offset_is_reached = True
|
||||
```
|
||||
|
||||
Configuration (offset is buyprice + 3%):
|
||||
Configuration (offset is buy-price + 3%):
|
||||
|
||||
``` python
|
||||
stoploss = -0.10
|
||||
@@ -169,7 +177,7 @@ For example, simplified math:
|
||||
* stoploss will remain at 90$ unless asset increases to or above our configured offset
|
||||
* assuming the asset now increases to 103$ (where we have the offset configured)
|
||||
* the stop loss will now be -2% of 103$ = 100.94$
|
||||
* now the asset drops in value to 101$, the stop loss will still be 100.94$ and would trigger at 100.94$
|
||||
* now the asset drops in value to 101\$, the stop loss will still be 100.94$ and would trigger at 100.94$
|
||||
|
||||
!!! Tip
|
||||
Make sure to have this value (`trailing_stop_positive_offset`) lower than minimal ROI, otherwise minimal ROI will apply first and sell the trade.
|
||||
|
@@ -8,11 +8,185 @@ If you're just getting started, please be familiar with the methods described in
|
||||
!!! Note
|
||||
All callback methods described below should only be implemented in a strategy if they are actually used.
|
||||
|
||||
!!! Tip
|
||||
You can get a strategy template containing all below methods by running `freqtrade new-strategy --strategy MyAwesomeStrategy --template advanced`
|
||||
|
||||
## Custom stoploss
|
||||
|
||||
A stoploss can only ever move upwards - so if you set it to an absolute profit of 2%, you can never move it below this price.
|
||||
Also, the traditional `stoploss` value serves as an absolute lower level and will be instated as the initial stoploss.
|
||||
|
||||
The usage of the custom stoploss method must be enabled by setting `use_custom_stoploss=True` on the strategy object.
|
||||
The method must return a stoploss value (float / number) with a relative ratio below the current price.
|
||||
E.g. `current_profit = 0.05` (5% profit) - stoploss returns `0.02` - then you "locked in" a profit of 3% (`0.05 - 0.02 = 0.03`).
|
||||
|
||||
To simulate a regular trailing stoploss of 4% (trailing 4% behind the maximum reached price) you would use the following very simple method:
|
||||
|
||||
``` python
|
||||
# additional imports required
|
||||
from datetime import datetime
|
||||
from freqtrade.persistence import Trade
|
||||
|
||||
class AwesomeStrategy(IStrategy):
|
||||
|
||||
# ... populate_* methods
|
||||
|
||||
use_custom_stoploss = True
|
||||
|
||||
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float,
|
||||
current_profit: float, **kwargs) -> float:
|
||||
"""
|
||||
Custom stoploss logic, returning the new distance relative to current_rate (as ratio).
|
||||
e.g. returning -0.05 would create a stoploss 5% below current_rate.
|
||||
The custom stoploss can never be below self.stoploss, which serves as a hard maximum loss.
|
||||
|
||||
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
||||
|
||||
When not implemented by a strategy, returns the initial stoploss value
|
||||
Only called when use_custom_stoploss is set to True.
|
||||
|
||||
:param pair: Pair that's currently analyzed
|
||||
:param trade: trade object.
|
||||
:param current_time: datetime object, containing the current datetime
|
||||
:param current_rate: Rate, calculated based on pricing settings in ask_strategy.
|
||||
:param current_profit: Current profit (as ratio), calculated based on current_rate.
|
||||
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
||||
:return float: New stoploss value, relative to the currentrate
|
||||
"""
|
||||
return -0.04
|
||||
```
|
||||
|
||||
Stoploss on exchange works similar to `trailing_stop`, and the stoploss on exchange is updated as configured in `stoploss_on_exchange_interval` ([More details about stoploss on exchange](stoploss.md#stop-loss-on-exchange-freqtrade)).
|
||||
|
||||
!!! Note "Use of dates"
|
||||
All time-based calculations should be done based on `current_time` - using `datetime.now()` or `datetime.utcnow()` is discouraged, as this will break backtesting support.
|
||||
|
||||
!!! Tip "Trailing stoploss"
|
||||
It's recommended to disable `trailing_stop` when using custom stoploss values. Both can work in tandem, but you might encounter the trailing stop to move the price higher while your custom function would not want this, causing conflicting behavior.
|
||||
|
||||
### Custom stoploss examples
|
||||
|
||||
The next section will show some examples on what's possible with the custom stoploss function.
|
||||
Of course, many more things are possible, and all examples can be combined at will.
|
||||
|
||||
#### Time based trailing stop
|
||||
|
||||
Use the initial stoploss for the first 60 minutes, after this change to 10% trailing stoploss, and after 2 hours (120 minutes) we use a 5% trailing stoploss.
|
||||
|
||||
``` python
|
||||
from datetime import datetime, timedelta
|
||||
from freqtrade.persistence import Trade
|
||||
|
||||
class AwesomeStrategy(IStrategy):
|
||||
|
||||
# ... populate_* methods
|
||||
|
||||
use_custom_stoploss = True
|
||||
|
||||
def custom_stoploss(self, pair: str, trade: Trade, current_time: datetime, current_rate: float,
|
||||
current_profit: float, **kwargs) -> float:
|
||||
|
||||
# Make sure you have the longest interval first - these conditions are evaluated from top to bottom.
|
||||
if current_time - timedelta(minutes=120) > trade.open_date:
|
||||
return -0.05
|
||||
elif current_time - timedelta(minutes=60) > trade.open_date:
|
||||
return -0.10
|
||||
return 1
|
||||
```
|
||||
|
||||
#### Different stoploss per pair
|
||||
|
||||
Use a different stoploss depending on the pair.
|
||||
In this example, we'll trail the highest price with 10% trailing stoploss for `ETH/BTC` and `XRP/BTC`, with 5% trailing stoploss for `LTC/BTC` and with 15% for all other pairs.
|
||||
|
||||
``` python
|
||||
from datetime import datetime
|
||||
from freqtrade.persistence import Trade
|
||||
|
||||
class AwesomeStrategy(IStrategy):
|
||||
|
||||
# ... populate_* methods
|
||||
|
||||
use_custom_stoploss = True
|
||||
|
||||
def custom_stoploss(self, pair: str, trade: Trade, current_time: datetime, current_rate: float,
|
||||
current_profit: float, **kwargs) -> float:
|
||||
|
||||
if pair in ('ETH/BTC', 'XRP/BTC'):
|
||||
return -0.10
|
||||
elif pair in ('LTC/BTC'):
|
||||
return -0.05
|
||||
return -0.15
|
||||
```
|
||||
|
||||
#### Trailing stoploss with positive offset
|
||||
|
||||
Use the initial stoploss until the profit is above 4%, then use a trailing stoploss of 50% of the current profit with a minimum of 2.5% and a maximum of 5%.
|
||||
|
||||
Please note that the stoploss can only increase, values lower than the current stoploss are ignored.
|
||||
|
||||
``` python
|
||||
from datetime import datetime, timedelta
|
||||
from freqtrade.persistence import Trade
|
||||
|
||||
class AwesomeStrategy(IStrategy):
|
||||
|
||||
# ... populate_* methods
|
||||
|
||||
use_custom_stoploss = True
|
||||
|
||||
def custom_stoploss(self, pair: str, trade: Trade, current_time: datetime, current_rate: float,
|
||||
current_profit: float, **kwargs) -> float:
|
||||
|
||||
if current_profit < 0.04:
|
||||
return -1 # return a value bigger than the inital stoploss to keep using the inital stoploss
|
||||
|
||||
# After reaching the desired offset, allow the stoploss to trail by half the profit
|
||||
desired_stoploss = current_profit / 2
|
||||
|
||||
# Use a minimum of 2.5% and a maximum of 5%
|
||||
return max(min(desired_stoploss, 0.05), 0.025)
|
||||
```
|
||||
|
||||
#### Absolute stoploss
|
||||
|
||||
The below example sets absolute profit levels based on the current profit.
|
||||
|
||||
* Use the regular stoploss until 20% profit is reached
|
||||
* Once profit is > 40%, stoploss will be at 25%, locking in at least 25% of the profit.
|
||||
* Once profit is > 25% - stoploss will be 15%.
|
||||
* Once profit is > 20% - stoploss will be set to 7%.
|
||||
|
||||
``` python
|
||||
from datetime import datetime
|
||||
from freqtrade.persistence import Trade
|
||||
|
||||
class AwesomeStrategy(IStrategy):
|
||||
|
||||
# ... populate_* methods
|
||||
|
||||
use_custom_stoploss = True
|
||||
|
||||
def custom_stoploss(self, pair: str, trade: Trade, current_time: datetime, current_rate: float,
|
||||
current_profit: float, **kwargs) -> float:
|
||||
|
||||
# Calculate as `-desired_stop_from_open + current_profit` to get the distance between current_profit and initial price
|
||||
if current_profit > 0.40:
|
||||
return (-0.25 + current_profit)
|
||||
if current_profit > 0.25:
|
||||
return (-0.15 + current_profit)
|
||||
if current_profit > 0.20:
|
||||
return (-0.7 + current_profit)
|
||||
return 1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Custom order timeout rules
|
||||
|
||||
Simple, timebased order-timeouts can be configured either via strategy or in the configuration in the `unfilledtimeout` section.
|
||||
Simple, time-based order-timeouts can be configured either via strategy or in the configuration in the `unfilledtimeout` section.
|
||||
|
||||
However, freqtrade also offers a custom callback for both ordertypes, which allows you to decide based on custom criteria if a order did time out or not.
|
||||
However, freqtrade also offers a custom callback for both order types, which allows you to decide based on custom criteria if a order did time out or not.
|
||||
|
||||
!!! Note
|
||||
Unfilled order timeouts are not relevant during backtesting or hyperopt, and are only relevant during real (live) trading. Therefore these methods are only called in these circumstances.
|
||||
@@ -28,7 +202,7 @@ The function must return either `True` (cancel order) or `False` (keep order ali
|
||||
from datetime import datetime, timedelta
|
||||
from freqtrade.persistence import Trade
|
||||
|
||||
class Awesomestrategy(IStrategy):
|
||||
class AwesomeStrategy(IStrategy):
|
||||
|
||||
# ... populate_* methods
|
||||
|
||||
@@ -67,7 +241,7 @@ class Awesomestrategy(IStrategy):
|
||||
from datetime import datetime
|
||||
from freqtrade.persistence import Trade
|
||||
|
||||
class Awesomestrategy(IStrategy):
|
||||
class AwesomeStrategy(IStrategy):
|
||||
|
||||
# ... populate_* methods
|
||||
|
||||
@@ -95,6 +269,8 @@ class Awesomestrategy(IStrategy):
|
||||
return False
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Bot loop start callback
|
||||
|
||||
A simple callback which is called once at the start of every bot throttling iteration.
|
||||
@@ -103,7 +279,7 @@ This can be used to perform calculations which are pair independent (apply to al
|
||||
``` python
|
||||
import requests
|
||||
|
||||
class Awesomestrategy(IStrategy):
|
||||
class AwesomeStrategy(IStrategy):
|
||||
|
||||
# ... populate_* methods
|
||||
|
||||
@@ -128,7 +304,7 @@ class Awesomestrategy(IStrategy):
|
||||
`confirm_trade_entry()` can be used to abort a trade entry at the latest second (maybe because the price is not what we expect).
|
||||
|
||||
``` python
|
||||
class Awesomestrategy(IStrategy):
|
||||
class AwesomeStrategy(IStrategy):
|
||||
|
||||
# ... populate_* methods
|
||||
|
||||
@@ -164,7 +340,7 @@ class Awesomestrategy(IStrategy):
|
||||
from freqtrade.persistence import Trade
|
||||
|
||||
|
||||
class Awesomestrategy(IStrategy):
|
||||
class AwesomeStrategy(IStrategy):
|
||||
|
||||
# ... populate_* methods
|
||||
|
||||
@@ -200,6 +376,8 @@ class Awesomestrategy(IStrategy):
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Derived strategies
|
||||
|
||||
The strategies can be derived from other strategies. This avoids duplication of your custom strategy code. You can use this technique to override small parts of your main strategy, leaving the rest untouched:
|
||||
@@ -219,4 +397,30 @@ class MyAwesomeStrategy2(MyAwesomeStrategy):
|
||||
trailing_stop = True
|
||||
```
|
||||
|
||||
Both attributes and methods may be overriden, altering behavior of the original strategy in a way you need.
|
||||
Both attributes and methods may be overridden, altering behavior of the original strategy in a way you need.
|
||||
|
||||
## 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!
|
||||
|
@@ -147,7 +147,7 @@ Let's try to backtest 1 month (January 2019) of 5m candles using an example stra
|
||||
freqtrade backtesting --timerange 20190101-20190201 --timeframe 5m
|
||||
```
|
||||
|
||||
Assuming `startup_candle_count` is set to 100, backtesting knows it needs 100 candles to generate valid buy signals. It will load data from `20190101 - (100 * 5m)` - which is ~2019-12-31 15:30:00.
|
||||
Assuming `startup_candle_count` is set to 100, backtesting knows it needs 100 candles to generate valid buy signals. It will load data from `20190101 - (100 * 5m)` - which is ~2018-12-31 15:30:00.
|
||||
If this data is available, indicators will be calculated with this extended timerange. The instable startup period (up to 2019-01-01 00:00:00) will then be removed before starting backtesting.
|
||||
|
||||
!!! Note
|
||||
@@ -309,15 +309,20 @@ Storing information can be accomplished by creating a new dictionary within the
|
||||
The name of the variable can be chosen at will, but should be prefixed with `cust_` to avoid naming collisions with predefined strategy variables.
|
||||
|
||||
```python
|
||||
class Awesomestrategy(IStrategy):
|
||||
class AwesomeStrategy(IStrategy):
|
||||
# Create custom dictionary
|
||||
cust_info = {}
|
||||
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
# Check if the entry already exists
|
||||
if not metadata["pair"] in self._cust_info:
|
||||
# Create empty entry for this pair
|
||||
self._cust_info[metadata["pair"]] = {}
|
||||
|
||||
if "crosstime" in self.cust_info[metadata["pair"]:
|
||||
self.cust_info[metadata["pair"]["crosstime"] += 1
|
||||
self.cust_info[metadata["pair"]]["crosstime"] += 1
|
||||
else:
|
||||
self.cust_info[metadata["pair"]["crosstime"] = 1
|
||||
self.cust_info[metadata["pair"]]["crosstime"] = 1
|
||||
```
|
||||
|
||||
!!! Warning
|
||||
@@ -648,7 +653,7 @@ The following example queries for the current pair and trades from today, howeve
|
||||
if self.config['runmode'].value in ('live', 'dry_run'):
|
||||
trades = Trade.get_trades([Trade.pair == metadata['pair'],
|
||||
Trade.open_date > datetime.utcnow() - timedelta(days=1),
|
||||
Trade.is_open == False,
|
||||
Trade.is_open.is_(False),
|
||||
]).order_by(Trade.close_date).all()
|
||||
# Summarize profit for this pair.
|
||||
curdayprofit = sum(trade.close_profit for trade in trades)
|
||||
@@ -688,18 +693,18 @@ Locked pairs will show the message `Pair <pair> is currently locked.`.
|
||||
|
||||
Sometimes it may be desired to lock a pair after certain events happen (e.g. multiple losing trades in a row).
|
||||
|
||||
Freqtrade has an easy method to do this from within the strategy, by calling `self.lock_pair(pair, until)`.
|
||||
`until` must be a datetime object in the future, after which trading will be reenabled for that pair.
|
||||
Freqtrade has an easy method to do this from within the strategy, by calling `self.lock_pair(pair, until, [reason])`.
|
||||
`until` must be a datetime object in the future, after which trading will be re-enabled for that pair, while `reason` is an optional string detailing why the pair was locked.
|
||||
|
||||
Locks can also be lifted manually, by calling `self.unlock_pair(pair)`.
|
||||
|
||||
To verify if a pair is currently locked, use `self.is_pair_locked(pair)`.
|
||||
|
||||
!!! Note
|
||||
Locked pairs are not persisted, so a restart of the bot, or calling `/reload_config` will reset locked pairs.
|
||||
Locked pairs will always be rounded up to the next candle. So assuming a `5m` timeframe, a lock with `until` set to 10:18 will lock the pair until the candle from 10:15-10:20 will be finished.
|
||||
|
||||
!!! Warning
|
||||
Locking pairs is not functioning during backtesting.
|
||||
Locking pairs is not available during backtesting.
|
||||
|
||||
#### Pair locking example
|
||||
|
||||
@@ -714,7 +719,7 @@ if self.config['runmode'].value in ('live', 'dry_run'):
|
||||
# fetch closed trades for the last 2 days
|
||||
trades = Trade.get_trades([Trade.pair == metadata['pair'],
|
||||
Trade.open_date > datetime.utcnow() - timedelta(days=2),
|
||||
Trade.is_open == False,
|
||||
Trade.is_open.is_(False),
|
||||
]).all()
|
||||
# Analyze the conditions you'd like to lock the pair .... will probably be different for every strategy
|
||||
sumprofit = sum(trade.close_profit for trade in trades)
|
||||
@@ -765,8 +770,6 @@ To get additional Ideas for strategies, head over to our [strategy repository](h
|
||||
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/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE) which is a great place to get and/or share ideas.
|
||||
|
||||
## Next step
|
||||
|
||||
Now you have a perfect strategy you probably want to backtest it.
|
||||
|
@@ -35,12 +35,30 @@ Copy the API Token (`22222222:APITOKEN` in the above example) and keep use it fo
|
||||
|
||||
Don't forget to start the conversation with your bot, by clicking `/START` button
|
||||
|
||||
### 2. Get your user id
|
||||
### 2. Telegram user_id
|
||||
|
||||
#### Get your user id
|
||||
|
||||
Talk to the [userinfobot](https://telegram.me/userinfobot)
|
||||
|
||||
Get your "Id", you will use it for the config parameter `chat_id`.
|
||||
|
||||
#### Use Group id
|
||||
|
||||
You can use bots in telegram groups by just adding them to the group. You can find the group id by first adding a [RawDataBot](https://telegram.me/rawdatabot) to your group. The Group id is shown as id in the `"chat"` section, which the RawDataBot will send to you:
|
||||
|
||||
``` json
|
||||
"chat":{
|
||||
"id":-1001332619709
|
||||
}
|
||||
```
|
||||
|
||||
For the Freqtrade configuration, you can then use the the full value (including `-` if it's there) as string:
|
||||
|
||||
```json
|
||||
"chat_id": "-1001332619709"
|
||||
```
|
||||
|
||||
## Control telegram noise
|
||||
|
||||
Freqtrade provides means to control the verbosity of your telegram bot.
|
||||
@@ -69,6 +87,41 @@ Example configuration showing the different settings:
|
||||
},
|
||||
```
|
||||
|
||||
## Create a custom keyboard (command shortcut buttons)
|
||||
|
||||
Telegram allows us to create a custom keyboard with buttons for commands.
|
||||
The default custom keyboard looks like this.
|
||||
|
||||
```python
|
||||
[
|
||||
["/daily", "/profit", "/balance"], # row 1, 3 commands
|
||||
["/status", "/status table", "/performance"], # row 2, 3 commands
|
||||
["/count", "/start", "/stop", "/help"] # row 3, 4 commands
|
||||
]
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
You can create your own keyboard in `config.json`:
|
||||
|
||||
``` json
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "your_telegram_token",
|
||||
"chat_id": "your_telegram_chat_id",
|
||||
"keyboard": [
|
||||
["/daily", "/stats", "/balance", "/profit"],
|
||||
["/status table", "/performance"],
|
||||
["/reload_config", "/count", "/logs"]
|
||||
]
|
||||
},
|
||||
```
|
||||
|
||||
!!! Note "Supported Commands"
|
||||
Only the following commands are allowed. Command arguments are not supported!
|
||||
|
||||
`/start`, `/stop`, `/status`, `/status table`, `/trades`, `/profit`, `/performance`, `/daily`, `/stats`, `/count`, `/locks`, `/balance`, `/stopbuy`, `/reload_config`, `/show_config`, `/logs`, `/whitelist`, `/blacklist`, `/edge`, `/help`, `/version`
|
||||
|
||||
## Telegram commands
|
||||
|
||||
Per default, the Telegram bot shows predefined commands. Some commands
|
||||
@@ -84,10 +137,12 @@ official commands. You can ask at any moment for help with `/help`.
|
||||
| `/show_config` | Shows part of the current configuration with relevant settings to operation
|
||||
| `/logs [limit]` | Show last log messages.
|
||||
| `/status` | Lists all open trades
|
||||
| `/status <trade_id>` | Lists one or more specific trade. Separate multiple <trade_id> with a blank space.
|
||||
| `/status table` | List all open trades in a table format. Pending buy orders are marked with an asterisk (*) Pending sell orders are marked with a double asterisk (**)
|
||||
| `/trades [limit]` | List all recently closed trades in a table format.
|
||||
| `/delete <trade_id>` | Delete a specific trade from the Database. Tries to close open orders. Requires manual handling of this trade on the exchange.
|
||||
| `/count` | Displays number of trades used and available
|
||||
| `/locks` | Show currently locked pairs.
|
||||
| `/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`).
|
||||
@@ -95,6 +150,7 @@ official commands. You can ask at any moment for help with `/help`.
|
||||
| `/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 (n defaults to 7)
|
||||
| `/stats` | Shows Wins / losses by Sell reason as well as Avg. holding durations for buys and sells
|
||||
| `/whitelist` | Show the current whitelist
|
||||
| `/blacklist [pair]` | Show the current blacklist, or adds a pair to the blacklist.
|
||||
| `/edge` | Show validated pairs by Edge if it is enabled.
|
||||
@@ -189,7 +245,7 @@ Return a summary of your profit/loss and performance.
|
||||
|
||||
Note that for this to work, `forcebuy_enable` needs to be set to true.
|
||||
|
||||
[More details](configuration.md/#understand-forcebuy_enable)
|
||||
[More details](configuration.md#understand-forcebuy_enable)
|
||||
|
||||
### /performance
|
||||
|
||||
|
31
docs/updating.md
Normal file
31
docs/updating.md
Normal file
@@ -0,0 +1,31 @@
|
||||
# How to update
|
||||
|
||||
To update your freqtrade installation, please use one of the below methods, corresponding to your installation method.
|
||||
|
||||
## docker-compose
|
||||
|
||||
!!! Note "Legacy installations using the `master` image"
|
||||
We're switching from master to stable for the release Images - please adjust your docker-file and replace `freqtradeorg/freqtrade:master` with `freqtradeorg/freqtrade:stable`
|
||||
|
||||
``` bash
|
||||
docker-compose pull
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
## Installation via setup script
|
||||
|
||||
``` bash
|
||||
./setup.sh --update
|
||||
```
|
||||
|
||||
!!! Note
|
||||
Make sure to run this command with your virtual environment disabled!
|
||||
|
||||
## Plain native installation
|
||||
|
||||
Please ensure that you're also updating dependencies - otherwise things might break without you noticing.
|
||||
|
||||
``` bash
|
||||
git pull
|
||||
pip install -U -r requirements.txt
|
||||
```
|
@@ -423,7 +423,7 @@ freqtrade test-pairlist --config config.json --quote USDT BTC
|
||||
|
||||
## List Hyperopt results
|
||||
|
||||
You can list the hyperoptimization epochs the Hyperopt module evaluated previously with the `hyperopt-list` subcommand.
|
||||
You can list the hyperoptimization epochs the Hyperopt module evaluated previously with the `hyperopt-list` sub-command.
|
||||
|
||||
```
|
||||
usage: freqtrade hyperopt-list [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
@@ -432,10 +432,11 @@ usage: freqtrade hyperopt-list [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[--max-trades INT] [--min-avg-time FLOAT]
|
||||
[--max-avg-time FLOAT] [--min-avg-profit FLOAT]
|
||||
[--max-avg-profit FLOAT]
|
||||
[--min-total-profit FLOAT] [--max-total-profit FLOAT]
|
||||
[--min-total-profit FLOAT]
|
||||
[--max-total-profit FLOAT]
|
||||
[--min-objective FLOAT] [--max-objective FLOAT]
|
||||
[--no-color] [--print-json] [--no-details]
|
||||
[--export-csv FILE]
|
||||
[--hyperopt-filename PATH] [--export-csv FILE]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
@@ -443,24 +444,27 @@ optional arguments:
|
||||
--profitable Select only profitable epochs.
|
||||
--min-trades INT Select epochs with more than INT trades.
|
||||
--max-trades INT Select epochs with less than INT trades.
|
||||
--min-avg-time FLOAT Select epochs on above average time.
|
||||
--max-avg-time FLOAT Select epochs on under average time.
|
||||
--min-avg-time FLOAT Select epochs above average time.
|
||||
--max-avg-time FLOAT Select epochs below average time.
|
||||
--min-avg-profit FLOAT
|
||||
Select epochs on above average profit.
|
||||
Select epochs above average profit.
|
||||
--max-avg-profit FLOAT
|
||||
Select epochs on below average profit.
|
||||
Select epochs below average profit.
|
||||
--min-total-profit FLOAT
|
||||
Select epochs on above total profit.
|
||||
Select epochs above total profit.
|
||||
--max-total-profit FLOAT
|
||||
Select epochs on below total profit.
|
||||
Select epochs below total profit.
|
||||
--min-objective FLOAT
|
||||
Select epochs on above objective (- is added by default).
|
||||
Select epochs above objective.
|
||||
--max-objective FLOAT
|
||||
Select epochs on below objective (- is added by default).
|
||||
Select epochs below objective.
|
||||
--no-color Disable colorization of hyperopt results. May be
|
||||
useful if you are redirecting output to a file.
|
||||
--print-json Print best result detailization in JSON format.
|
||||
--print-json Print output in JSON format.
|
||||
--no-details Do not print best epoch details.
|
||||
--hyperopt-filename FILENAME
|
||||
Hyperopt result filename.Example: `--hyperopt-
|
||||
filename=hyperopt_results_2020-09-27_16-20-48.pickle`
|
||||
--export-csv FILE Export to CSV-File. This will disable table print.
|
||||
Example: --export-csv hyperopt.csv
|
||||
|
||||
@@ -480,7 +484,11 @@ Common arguments:
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
```
|
||||
|
||||
|
||||
!!! Note
|
||||
`hyperopt-list` will automatically use the latest available hyperopt results file.
|
||||
You can override this using the `--hyperopt-filename` argument, and specify another, available filename (without path!).
|
||||
|
||||
### Examples
|
||||
|
||||
List all results, print details of the best result at the end:
|
||||
@@ -501,17 +509,41 @@ You can show the details of any hyperoptimization epoch previously evaluated by
|
||||
usage: freqtrade hyperopt-show [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH] [--best]
|
||||
[--profitable] [-n INT] [--print-json]
|
||||
[--no-header]
|
||||
[--hyperopt-filename PATH] [--no-header]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
--best Select only best epochs.
|
||||
--profitable Select only profitable epochs.
|
||||
-n INT, --index INT Specify the index of the epoch to print details for.
|
||||
--print-json Print best result detailization in JSON format.
|
||||
--print-json Print output in JSON format.
|
||||
--hyperopt-filename FILENAME
|
||||
Hyperopt result filename.Example: `--hyperopt-
|
||||
filename=hyperopt_results_2020-09-27_16-20-48.pickle`
|
||||
--no-header Do not print epoch details header.
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified. Special values are:
|
||||
'syslog', 'journald'. See the documentation for more
|
||||
details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default:
|
||||
`userdir/config.json` or `config.json` whichever
|
||||
exists). Multiple --config options may be used. Can be
|
||||
set to `-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
|
||||
```
|
||||
|
||||
!!! Note
|
||||
`hyperopt-show` will automatically use the latest available hyperopt results file.
|
||||
You can override this using the `--hyperopt-filename` argument, and specify another, available filename (without path!).
|
||||
|
||||
### Examples
|
||||
|
||||
Print details for the epoch 168 (the number of the epoch is shown by the `hyperopt-list` subcommand or by Hyperopt itself during hyperoptimization run):
|
||||
|
@@ -1,4 +1,4 @@
|
||||
We **strongly** recommend that Windows users use [Docker](docker.md) as this will work much easier and smoother (also more secure).
|
||||
We **strongly** recommend that Windows users use [Docker](docker_quickstart.md) as this will work much easier and smoother (also more secure).
|
||||
|
||||
If that is not possible, try using the Windows Linux subsystem (WSL) - for which the Ubuntu instructions should work.
|
||||
Otherwise, try the instructions below.
|
||||
@@ -21,7 +21,7 @@ git clone https://github.com/freqtrade/freqtrade.git
|
||||
|
||||
Install ta-lib according to the [ta-lib documentation](https://github.com/mrjbq7/ta-lib#windows).
|
||||
|
||||
As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial precompiled windows Wheels [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib), which needs to be downloaded and installed using `pip install TA_Lib‑0.4.18‑cp38‑cp38‑win_amd64.whl` (make sure to use the version matching your python version)
|
||||
As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial precompiled windows Wheels [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib), which needs to be downloaded and installed using `pip install TA_Lib‑0.4.19‑cp38‑cp38‑win_amd64.whl` (make sure to use the version matching your python version)
|
||||
|
||||
Freqtrade provides these dependencies for the latest 2 Python versions (3.7 and 3.8) and for 64bit Windows.
|
||||
Other versions must be downloaded from the above link.
|
||||
@@ -32,7 +32,7 @@ python -m venv .env
|
||||
.env\Scripts\activate.ps1
|
||||
# optionally install ta-lib from wheel
|
||||
# Eventually adjust the below filename to match the downloaded wheel
|
||||
pip install build_helpes/TA_Lib‑0.4.18‑cp38‑cp38‑win_amd64.whl
|
||||
pip install build_helpers/TA_Lib-0.4.19-cp38-cp38-win_amd64.whl
|
||||
pip install -r requirements.txt
|
||||
pip install -e .
|
||||
freqtrade
|
||||
@@ -50,8 +50,8 @@ freqtrade
|
||||
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.
|
||||
Unfortunately, many packages requiring compilation don't provide a pre-built wheel. It is therefore mandatory to have a C/C++ compiler installed and available for your python environment to use.
|
||||
|
||||
The easiest way is to download install Microsoft Visual Studio Community [here](https://visualstudio.microsoft.com/downloads/) and make sure to install "Common Tools for Visual C++" to enable building c code on Windows. Unfortunately, this is a heavy download / dependency (~4Gb) so you might want to consider WSL or [docker](docker.md) first.
|
||||
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 compose](docker_quickstart.md) first.
|
||||
|
||||
---
|
||||
|
@@ -4,7 +4,7 @@ channels:
|
||||
- conda-forge
|
||||
dependencies:
|
||||
# Required for app
|
||||
- python>=3.6
|
||||
- python>=3.7
|
||||
- pip
|
||||
- wheel
|
||||
- numpy
|
||||
|
@@ -1,5 +1,5 @@
|
||||
""" Freqtrade bot """
|
||||
__version__ = '2020.9.1'
|
||||
__version__ = '2021.1'
|
||||
|
||||
if __version__ == 'develop':
|
||||
|
||||
|
@@ -3,10 +3,11 @@
|
||||
__main__.py for Freqtrade
|
||||
To launch Freqtrade as a module
|
||||
|
||||
> python -m freqtrade (with Python >= 3.6)
|
||||
> python -m freqtrade (with Python >= 3.7)
|
||||
"""
|
||||
|
||||
from freqtrade import main
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main.main()
|
||||
|
@@ -8,23 +8,15 @@ Note: Be careful with file-scoped imports in these subfiles.
|
||||
"""
|
||||
from freqtrade.commands.arguments import Arguments
|
||||
from freqtrade.commands.build_config_commands import start_new_config
|
||||
from freqtrade.commands.data_commands import (start_convert_data,
|
||||
start_download_data,
|
||||
from freqtrade.commands.data_commands import (start_convert_data, start_download_data,
|
||||
start_list_data)
|
||||
from freqtrade.commands.deploy_commands import (start_create_userdir,
|
||||
start_new_hyperopt,
|
||||
from freqtrade.commands.deploy_commands import (start_create_userdir, start_new_hyperopt,
|
||||
start_new_strategy)
|
||||
from freqtrade.commands.hyperopt_commands import (start_hyperopt_list,
|
||||
start_hyperopt_show)
|
||||
from freqtrade.commands.list_commands import (start_list_exchanges,
|
||||
start_list_hyperopts,
|
||||
start_list_markets,
|
||||
start_list_strategies,
|
||||
start_list_timeframes,
|
||||
start_show_trades)
|
||||
from freqtrade.commands.optimize_commands import (start_backtesting,
|
||||
start_edge, start_hyperopt)
|
||||
from freqtrade.commands.hyperopt_commands import start_hyperopt_list, start_hyperopt_show
|
||||
from freqtrade.commands.list_commands import (start_list_exchanges, start_list_hyperopts,
|
||||
start_list_markets, start_list_strategies,
|
||||
start_list_timeframes, start_show_trades)
|
||||
from freqtrade.commands.optimize_commands import start_backtesting, start_edge, start_hyperopt
|
||||
from freqtrade.commands.pairlist_commands import start_test_pairlist
|
||||
from freqtrade.commands.plot_commands import (start_plot_dataframe,
|
||||
start_plot_profit)
|
||||
from freqtrade.commands.plot_commands import start_plot_dataframe, start_plot_profit
|
||||
from freqtrade.commands.trade_commands import start_trading
|
||||
|
@@ -9,6 +9,7 @@ from typing import Any, Dict, List, Optional
|
||||
from freqtrade.commands.cli_options import AVAILABLE_CLI_OPTIONS
|
||||
from freqtrade.constants import DEFAULT_CONFIG
|
||||
|
||||
|
||||
ARGS_COMMON = ["verbosity", "logfile", "version", "config", "datadir", "user_data_dir"]
|
||||
|
||||
ARGS_STRATEGY = ["strategy", "strategy_path"]
|
||||
@@ -19,14 +20,16 @@ ARGS_COMMON_OPTIMIZE = ["timeframe", "timerange", "dataformat_ohlcv",
|
||||
"max_open_trades", "stake_amount", "fee"]
|
||||
|
||||
ARGS_BACKTEST = ARGS_COMMON_OPTIMIZE + ["position_stacking", "use_max_market_positions",
|
||||
"enable_protections",
|
||||
"strategy_list", "export", "exportfilename"]
|
||||
|
||||
ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
|
||||
"position_stacking", "epochs", "spaces",
|
||||
"use_max_market_positions", "print_all",
|
||||
"position_stacking", "use_max_market_positions",
|
||||
"enable_protections",
|
||||
"epochs", "spaces", "print_all",
|
||||
"print_colorized", "print_json", "hyperopt_jobs",
|
||||
"hyperopt_random_state", "hyperopt_min_trades",
|
||||
"hyperopt_continue", "hyperopt_loss"]
|
||||
"hyperopt_loss"]
|
||||
|
||||
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
|
||||
|
||||
@@ -41,7 +44,8 @@ ARGS_LIST_TIMEFRAMES = ["exchange", "print_one_column"]
|
||||
ARGS_LIST_PAIRS = ["exchange", "print_list", "list_pairs_print_json", "print_one_column",
|
||||
"print_csv", "base_currencies", "quote_currencies", "list_pairs_all"]
|
||||
|
||||
ARGS_TEST_PAIRLIST = ["config", "quote_currencies", "print_one_column", "list_pairs_print_json"]
|
||||
ARGS_TEST_PAIRLIST = ["verbosity", "config", "quote_currencies", "print_one_column",
|
||||
"list_pairs_print_json"]
|
||||
|
||||
ARGS_CREATE_USERDIR = ["user_data_dir", "reset"]
|
||||
|
||||
@@ -75,10 +79,10 @@ ARGS_HYPEROPT_LIST = ["hyperopt_list_best", "hyperopt_list_profitable",
|
||||
"hyperopt_list_min_total_profit", "hyperopt_list_max_total_profit",
|
||||
"hyperopt_list_min_objective", "hyperopt_list_max_objective",
|
||||
"print_colorized", "print_json", "hyperopt_list_no_details",
|
||||
"export_csv"]
|
||||
"hyperoptexportfilename", "export_csv"]
|
||||
|
||||
ARGS_HYPEROPT_SHOW = ["hyperopt_list_best", "hyperopt_list_profitable", "hyperopt_show_index",
|
||||
"print_json", "hyperopt_show_no_header"]
|
||||
"print_json", "hyperoptexportfilename", "hyperopt_show_no_header"]
|
||||
|
||||
NO_CONF_REQURIED = ["convert-data", "convert-trade-data", "download-data", "list-timeframes",
|
||||
"list-markets", "list-pairs", "list-strategies", "list-data",
|
||||
@@ -161,16 +165,14 @@ class Arguments:
|
||||
self.parser = argparse.ArgumentParser(description='Free, open source crypto trading bot')
|
||||
self._build_args(optionlist=['version'], parser=self.parser)
|
||||
|
||||
from freqtrade.commands import (start_create_userdir, start_convert_data,
|
||||
start_download_data, start_list_data,
|
||||
start_hyperopt_list, start_hyperopt_show,
|
||||
from freqtrade.commands import (start_backtesting, start_convert_data, start_create_userdir,
|
||||
start_download_data, start_edge, start_hyperopt,
|
||||
start_hyperopt_list, start_hyperopt_show, start_list_data,
|
||||
start_list_exchanges, start_list_hyperopts,
|
||||
start_list_markets, start_list_strategies,
|
||||
start_list_timeframes, start_new_config,
|
||||
start_new_hyperopt, start_new_strategy,
|
||||
start_plot_dataframe, start_plot_profit, start_show_trades,
|
||||
start_backtesting, start_hyperopt, start_edge,
|
||||
start_test_pairlist, start_trading)
|
||||
start_list_timeframes, start_new_config, start_new_hyperopt,
|
||||
start_new_strategy, start_plot_dataframe, start_plot_profit,
|
||||
start_show_trades, start_test_pairlist, start_trading)
|
||||
|
||||
subparsers = self.parser.add_subparsers(dest='command',
|
||||
# Use custom message when no subhandler is added
|
||||
|
@@ -1,13 +1,15 @@
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from questionary import Separator, prompt
|
||||
|
||||
from freqtrade.constants import UNLIMITED_STAKE_AMOUNT
|
||||
from freqtrade.exchange import available_exchanges, MAP_EXCHANGE_CHILDCLASS
|
||||
from freqtrade.misc import render_template
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange import MAP_EXCHANGE_CHILDCLASS, available_exchanges
|
||||
from freqtrade.misc import render_template
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -46,7 +48,7 @@ def ask_user_config() -> Dict[str, Any]:
|
||||
Interactive questions built using https://github.com/tmbo/questionary
|
||||
:returns: Dict with keys to put into template
|
||||
"""
|
||||
questions = [
|
||||
questions: List[Dict[str, Any]] = [
|
||||
{
|
||||
"type": "confirm",
|
||||
"name": "dry_run",
|
||||
|
@@ -4,6 +4,7 @@ Definition of cli arguments used in arguments.py
|
||||
from argparse import ArgumentTypeError
|
||||
|
||||
from freqtrade import __version__, constants
|
||||
from freqtrade.constants import HYPEROPT_LOSS_BUILTIN
|
||||
|
||||
|
||||
def check_int_positive(value: str) -> int:
|
||||
@@ -143,6 +144,14 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
action='store_false',
|
||||
default=True,
|
||||
),
|
||||
"enable_protections": Arg(
|
||||
'--enable-protections', '--enableprotections',
|
||||
help='Enable protections for backtesting.'
|
||||
'Will slow backtesting down by a considerable amount, but will include '
|
||||
'configured protections',
|
||||
action='store_true',
|
||||
default=False,
|
||||
),
|
||||
"strategy_list": Arg(
|
||||
'--strategy-list',
|
||||
help='Provide a space-separated list of strategies to backtest. '
|
||||
@@ -252,23 +261,19 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
metavar='INT',
|
||||
default=1,
|
||||
),
|
||||
"hyperopt_continue": Arg(
|
||||
"--continue",
|
||||
help="Continue hyperopt from previous runs. "
|
||||
"By default, temporary files will be removed and hyperopt will start from scratch.",
|
||||
default=False,
|
||||
action='store_true',
|
||||
),
|
||||
"hyperopt_loss": Arg(
|
||||
'--hyperopt-loss',
|
||||
help='Specify the class name of the hyperopt loss function class (IHyperOptLoss). '
|
||||
'Different functions can generate completely different results, '
|
||||
'since the target for optimization is different. Built-in Hyperopt-loss-functions are: '
|
||||
'DefaultHyperOptLoss, OnlyProfitHyperOptLoss, SharpeHyperOptLoss, SharpeHyperOptLossDaily, '
|
||||
'SortinoHyperOptLoss, SortinoHyperOptLossDaily.'
|
||||
'(default: `%(default)s`).',
|
||||
f'{", ".join(HYPEROPT_LOSS_BUILTIN)}',
|
||||
metavar='NAME',
|
||||
default=constants.DEFAULT_HYPEROPT_LOSS,
|
||||
),
|
||||
"hyperoptexportfilename": Arg(
|
||||
'--hyperopt-filename',
|
||||
help='Hyperopt result filename.'
|
||||
'Example: `--hyperopt-filename=hyperopt_results_2020-09-27_16-20-48.pickle`',
|
||||
metavar='FILENAME',
|
||||
),
|
||||
# List exchanges
|
||||
"print_one_column": Arg(
|
||||
@@ -357,13 +362,11 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
'--data-format-ohlcv',
|
||||
help='Storage format for downloaded candle (OHLCV) data. (default: `%(default)s`).',
|
||||
choices=constants.AVAILABLE_DATAHANDLERS,
|
||||
default='json'
|
||||
),
|
||||
"dataformat_trades": Arg(
|
||||
'--data-format-trades',
|
||||
help='Storage format for downloaded trades data. (default: `%(default)s`).',
|
||||
choices=constants.AVAILABLE_DATAHANDLERS,
|
||||
default='jsongz'
|
||||
),
|
||||
"exchange": Arg(
|
||||
'--exchange',
|
||||
|
@@ -1,21 +1,20 @@
|
||||
import logging
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, List
|
||||
|
||||
import arrow
|
||||
|
||||
from freqtrade.configuration import TimeRange, setup_utils_configuration
|
||||
from freqtrade.data.converter import (convert_ohlcv_format,
|
||||
convert_trades_format)
|
||||
from freqtrade.data.history import (convert_trades_to_ohlcv,
|
||||
refresh_backtest_ohlcv_data,
|
||||
from freqtrade.data.converter import convert_ohlcv_format, convert_trades_format
|
||||
from freqtrade.data.history import (convert_trades_to_ohlcv, refresh_backtest_ohlcv_data,
|
||||
refresh_backtest_trades_data)
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange import timeframe_to_minutes
|
||||
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
||||
from freqtrade.resolvers import ExchangeResolver
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -30,26 +29,31 @@ def start_download_data(args: Dict[str, Any]) -> None:
|
||||
"You can only specify one or the other.")
|
||||
timerange = TimeRange()
|
||||
if 'days' in config:
|
||||
time_since = arrow.utcnow().shift(days=-config['days']).strftime("%Y%m%d")
|
||||
time_since = (datetime.now() - timedelta(days=config['days'])).strftime("%Y%m%d")
|
||||
timerange = TimeRange.parse_timerange(f'{time_since}-')
|
||||
|
||||
if 'timerange' in config:
|
||||
timerange = timerange.parse_timerange(config['timerange'])
|
||||
|
||||
# Remove stake-currency to skip checks which are not relevant for datadownload
|
||||
config['stake_currency'] = ''
|
||||
|
||||
if 'pairs' not in config:
|
||||
raise OperationalException(
|
||||
"Downloading data requires a list of pairs. "
|
||||
"Please check the documentation on how to configure this.")
|
||||
|
||||
logger.info(f"About to download pairs: {config['pairs']}, "
|
||||
f"intervals: {config['timeframes']} to {config['datadir']}")
|
||||
|
||||
pairs_not_available: List[str] = []
|
||||
|
||||
# Init exchange
|
||||
exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config, validate=False)
|
||||
# Manual validations of relevant settings
|
||||
exchange.validate_pairs(config['pairs'])
|
||||
expanded_pairs = expand_pairlist(config['pairs'], list(exchange.markets))
|
||||
|
||||
logger.info(f"About to download pairs: {expanded_pairs}, "
|
||||
f"intervals: {config['timeframes']} to {config['datadir']}")
|
||||
|
||||
for timeframe in config['timeframes']:
|
||||
exchange.validate_timeframes(timeframe)
|
||||
|
||||
@@ -57,20 +61,20 @@ def start_download_data(args: Dict[str, Any]) -> None:
|
||||
|
||||
if config.get('download_trades'):
|
||||
pairs_not_available = refresh_backtest_trades_data(
|
||||
exchange, pairs=config['pairs'], datadir=config['datadir'],
|
||||
exchange, pairs=expanded_pairs, datadir=config['datadir'],
|
||||
timerange=timerange, erase=bool(config.get('erase')),
|
||||
data_format=config['dataformat_trades'])
|
||||
|
||||
# Convert downloaded trade data to different timeframes
|
||||
convert_trades_to_ohlcv(
|
||||
pairs=config['pairs'], timeframes=config['timeframes'],
|
||||
pairs=expanded_pairs, timeframes=config['timeframes'],
|
||||
datadir=config['datadir'], timerange=timerange, erase=bool(config.get('erase')),
|
||||
data_format_ohlcv=config['dataformat_ohlcv'],
|
||||
data_format_trades=config['dataformat_trades'],
|
||||
)
|
||||
)
|
||||
else:
|
||||
pairs_not_available = refresh_backtest_ohlcv_data(
|
||||
exchange, pairs=config['pairs'], timeframes=config['timeframes'],
|
||||
exchange, pairs=expanded_pairs, timeframes=config['timeframes'],
|
||||
datadir=config['datadir'], timerange=timerange, erase=bool(config.get('erase')),
|
||||
data_format=config['dataformat_ohlcv'])
|
||||
|
||||
@@ -105,8 +109,9 @@ def start_list_data(args: Dict[str, Any]) -> None:
|
||||
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||
|
||||
from freqtrade.data.history.idatahandler import get_datahandler
|
||||
from tabulate import tabulate
|
||||
|
||||
from freqtrade.data.history.idatahandler import get_datahandler
|
||||
dhc = get_datahandler(config['datadir'], config['dataformat_ohlcv'])
|
||||
|
||||
paircombs = dhc.ohlcv_get_available_data(config['datadir'])
|
||||
|
@@ -4,13 +4,13 @@ from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
from freqtrade.configuration import setup_utils_configuration
|
||||
from freqtrade.configuration.directory_operations import (copy_sample_files,
|
||||
create_userdata_dir)
|
||||
from freqtrade.configuration.directory_operations import copy_sample_files, create_userdata_dir
|
||||
from freqtrade.constants import USERPATH_HYPEROPTS, USERPATH_STRATEGIES
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.misc import render_template, render_template_with_fallback
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -133,7 +133,7 @@ def start_new_hyperopt(args: Dict[str, Any]) -> None:
|
||||
|
||||
if new_path.exists():
|
||||
raise OperationalException(f"`{new_path}` already exists. "
|
||||
"Please choose another Strategy Name.")
|
||||
"Please choose another Hyperopt Name.")
|
||||
deploy_new_hyperopt(args['hyperopt'], new_path, args['template'])
|
||||
else:
|
||||
raise OperationalException("`new-hyperopt` requires --hyperopt to be set.")
|
||||
|
@@ -5,9 +5,11 @@ from typing import Any, Dict, List
|
||||
from colorama import init as colorama_init
|
||||
|
||||
from freqtrade.configuration import setup_utils_configuration
|
||||
from freqtrade.data.btanalysis import get_latest_hyperopt_file
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -40,8 +42,9 @@ def start_hyperopt_list(args: Dict[str, Any]) -> None:
|
||||
'filter_max_objective': config.get('hyperopt_list_max_objective', None),
|
||||
}
|
||||
|
||||
results_file = (config['user_data_dir'] /
|
||||
'hyperopt_results' / 'hyperopt_results.pickle')
|
||||
results_file = get_latest_hyperopt_file(
|
||||
config['user_data_dir'] / 'hyperopt_results',
|
||||
config.get('hyperoptexportfilename'))
|
||||
|
||||
# Previous evaluations
|
||||
epochs = Hyperopt.load_previous_results(results_file)
|
||||
@@ -80,8 +83,10 @@ def start_hyperopt_show(args: Dict[str, Any]) -> None:
|
||||
|
||||
print_json = config.get('print_json', False)
|
||||
no_header = config.get('hyperopt_show_no_header', False)
|
||||
results_file = (config['user_data_dir'] /
|
||||
'hyperopt_results' / 'hyperopt_results.pickle')
|
||||
results_file = get_latest_hyperopt_file(
|
||||
config['user_data_dir'] / 'hyperopt_results',
|
||||
config.get('hyperoptexportfilename'))
|
||||
|
||||
n = config.get('hyperopt_show_index', -1)
|
||||
|
||||
filteroptions = {
|
||||
|
@@ -5,20 +5,20 @@ from collections import OrderedDict
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from colorama import init as colorama_init
|
||||
from colorama import Fore, Style
|
||||
import rapidjson
|
||||
from colorama import Fore, Style
|
||||
from colorama import init as colorama_init
|
||||
from tabulate import tabulate
|
||||
|
||||
from freqtrade.configuration import setup_utils_configuration
|
||||
from freqtrade.constants import USERPATH_HYPEROPTS, USERPATH_STRATEGIES
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange import (available_exchanges, ccxt_exchanges,
|
||||
market_is_active)
|
||||
from freqtrade.exchange import available_exchanges, ccxt_exchanges, market_is_active
|
||||
from freqtrade.misc import plural
|
||||
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -203,15 +203,16 @@ def start_show_trades(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Show trades
|
||||
"""
|
||||
from freqtrade.persistence import init, Trade
|
||||
import json
|
||||
|
||||
from freqtrade.persistence import Trade, init_db
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||
|
||||
if 'db_url' not in config:
|
||||
raise OperationalException("--db-url is required for this command.")
|
||||
|
||||
logger.info(f'Using DB: "{config["db_url"]}"')
|
||||
init(config['db_url'], clean_open_orders=False)
|
||||
init_db(config['db_url'], clean_open_orders=False)
|
||||
tfilter = []
|
||||
|
||||
if config.get('trade_ids'):
|
||||
|
@@ -6,6 +6,7 @@ from freqtrade.configuration import setup_utils_configuration
|
||||
from freqtrade.exceptions import DependencyException, OperationalException
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -58,6 +59,7 @@ def start_hyperopt(args: Dict[str, Any]) -> None:
|
||||
# Import here to avoid loading hyperopt module when it's not used
|
||||
try:
|
||||
from filelock import FileLock, Timeout
|
||||
|
||||
from freqtrade.optimize.hyperopt import Hyperopt
|
||||
except ImportError as e:
|
||||
raise OperationalException(
|
||||
@@ -98,6 +100,7 @@ def start_edge(args: Dict[str, Any]) -> None:
|
||||
:return: None
|
||||
"""
|
||||
from freqtrade.optimize.edge_cli import EdgeCli
|
||||
|
||||
# Initialize configuration
|
||||
config = setup_optimize_configuration(args, RunMode.EDGE)
|
||||
logger.info('Starting freqtrade in Edge mode')
|
||||
|
@@ -7,6 +7,7 @@ from freqtrade.configuration import setup_utils_configuration
|
||||
from freqtrade.resolvers import ExchangeResolver
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -14,7 +15,7 @@ def start_test_pairlist(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Test Pairlist configuration
|
||||
"""
|
||||
from freqtrade.pairlist.pairlistmanager import PairListManager
|
||||
from freqtrade.plugins.pairlistmanager import PairListManager
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_EXCHANGE)
|
||||
|
||||
exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config, validate=False)
|
||||
|
@@ -1,5 +1,4 @@
|
||||
import logging
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
|
@@ -1,7 +1,7 @@
|
||||
# flake8: noqa: F401
|
||||
|
||||
from freqtrade.configuration.config_setup import setup_utils_configuration
|
||||
from freqtrade.configuration.check_exchange import check_exchange, remove_credentials
|
||||
from freqtrade.configuration.timerange import TimeRange
|
||||
from freqtrade.configuration.configuration import Configuration
|
||||
from freqtrade.configuration.config_setup import setup_utils_configuration
|
||||
from freqtrade.configuration.config_validation import validate_config_consistency
|
||||
from freqtrade.configuration.configuration import Configuration
|
||||
from freqtrade.configuration.timerange import TimeRange
|
||||
|
@@ -2,11 +2,11 @@ import logging
|
||||
from typing import Any, Dict
|
||||
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange import (available_exchanges, get_exchange_bad_reason,
|
||||
is_exchange_bad, is_exchange_known_ccxt,
|
||||
is_exchange_officially_supported)
|
||||
from freqtrade.exchange import (available_exchanges, get_exchange_bad_reason, is_exchange_bad,
|
||||
is_exchange_known_ccxt, is_exchange_officially_supported)
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
@@ -1,10 +1,12 @@
|
||||
import logging
|
||||
from typing import Any, Dict
|
||||
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
from .check_exchange import remove_credentials
|
||||
from .config_validation import validate_config_consistency
|
||||
from .configuration import Configuration
|
||||
from .check_exchange import remove_credentials
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
@@ -9,6 +9,7 @@ from freqtrade import constants
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -53,7 +54,7 @@ def validate_config_schema(conf: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return conf
|
||||
except ValidationError as e:
|
||||
logger.critical(
|
||||
f"Invalid configuration. See config.json.example. Reason: {e}"
|
||||
f"Invalid configuration. Reason: {e}"
|
||||
)
|
||||
raise ValidationError(
|
||||
best_match(Draft4Validator(conf_schema).iter_errors(conf)).message
|
||||
@@ -73,6 +74,7 @@ def validate_config_consistency(conf: Dict[str, Any]) -> None:
|
||||
_validate_trailing_stoploss(conf)
|
||||
_validate_edge(conf)
|
||||
_validate_whitelist(conf)
|
||||
_validate_protections(conf)
|
||||
_validate_unlimited_amount(conf)
|
||||
|
||||
# validate configuration before returning
|
||||
@@ -136,6 +138,10 @@ def _validate_edge(conf: Dict[str, Any]) -> None:
|
||||
"Edge and VolumePairList are incompatible, "
|
||||
"Edge will override whatever pairs VolumePairlist selects."
|
||||
)
|
||||
if not conf.get('ask_strategy', {}).get('use_sell_signal', True):
|
||||
raise OperationalException(
|
||||
"Edge requires `use_sell_signal` to be True, otherwise no sells will happen."
|
||||
)
|
||||
|
||||
|
||||
def _validate_whitelist(conf: Dict[str, Any]) -> None:
|
||||
@@ -150,3 +156,22 @@ def _validate_whitelist(conf: Dict[str, Any]) -> None:
|
||||
if (pl.get('method') == 'StaticPairList'
|
||||
and not conf.get('exchange', {}).get('pair_whitelist')):
|
||||
raise OperationalException("StaticPairList requires pair_whitelist to be set.")
|
||||
|
||||
|
||||
def _validate_protections(conf: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Validate protection configuration validity
|
||||
"""
|
||||
|
||||
for prot in conf.get('protections', []):
|
||||
if ('stop_duration' in prot and 'stop_duration_candles' in prot):
|
||||
raise OperationalException(
|
||||
"Protections must specify either `stop_duration` or `stop_duration_candles`.\n"
|
||||
f"Please fix the protection {prot.get('method')}"
|
||||
)
|
||||
|
||||
if ('lookback_period' in prot and 'lookback_period_candles' in prot):
|
||||
raise OperationalException(
|
||||
"Protections must specify either `lookback_period` or `lookback_period_candles`.\n"
|
||||
f"Please fix the protection {prot.get('method')}"
|
||||
)
|
||||
|
@@ -10,14 +10,14 @@ from typing import Any, Callable, Dict, List, Optional
|
||||
from freqtrade import constants
|
||||
from freqtrade.configuration.check_exchange import check_exchange
|
||||
from freqtrade.configuration.deprecated_settings import process_temporary_deprecated_settings
|
||||
from freqtrade.configuration.directory_operations import (create_datadir,
|
||||
create_userdata_dir)
|
||||
from freqtrade.configuration.directory_operations import create_datadir, create_userdata_dir
|
||||
from freqtrade.configuration.load_config import load_config_file
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.loggers import setup_logging
|
||||
from freqtrade.misc import deep_merge_dicts, json_load
|
||||
from freqtrade.state import NON_UTIL_MODES, TRADING_MODES, RunMode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -211,6 +211,9 @@ class Configuration:
|
||||
self._args_to_config(config, argname='position_stacking',
|
||||
logstring='Parameter --enable-position-stacking detected ...')
|
||||
|
||||
self._args_to_config(
|
||||
config, argname='enable_protections',
|
||||
logstring='Parameter --enable-protections detected, enabling Protections. ...')
|
||||
# Setting max_open_trades to infinite if -1
|
||||
if config.get('max_open_trades') == -1:
|
||||
config['max_open_trades'] = float('inf')
|
||||
@@ -263,6 +266,9 @@ class Configuration:
|
||||
self._args_to_config(config, argname='hyperopt_path',
|
||||
logstring='Using additional Hyperopt lookup path: {}')
|
||||
|
||||
self._args_to_config(config, argname='hyperoptexportfilename',
|
||||
logstring='Using hyperopt file: {}')
|
||||
|
||||
self._args_to_config(config, argname='epochs',
|
||||
logstring='Parameter --epochs detected ... '
|
||||
'Will run Hyperopt with for {} epochs ...'
|
||||
@@ -295,9 +301,6 @@ class Configuration:
|
||||
self._args_to_config(config, argname='hyperopt_min_trades',
|
||||
logstring='Parameter --min-trades detected: {}')
|
||||
|
||||
self._args_to_config(config, argname='hyperopt_continue',
|
||||
logstring='Hyperopt continue: {}')
|
||||
|
||||
self._args_to_config(config, argname='hyperopt_loss',
|
||||
logstring='Using Hyperopt loss class name: {}')
|
||||
|
||||
|
@@ -26,6 +26,24 @@ def check_conflicting_settings(config: Dict[str, Any],
|
||||
)
|
||||
|
||||
|
||||
def process_removed_setting(config: Dict[str, Any],
|
||||
section1: str, name1: str,
|
||||
section2: str, name2: str) -> None:
|
||||
"""
|
||||
:param section1: Removed section
|
||||
:param name1: Removed setting name
|
||||
:param section2: new section for this key
|
||||
:param name2: new setting name
|
||||
"""
|
||||
section1_config = config.get(section1, {})
|
||||
if name1 in section1_config:
|
||||
raise OperationalException(
|
||||
f"Setting `{section1}.{name1}` has been moved to `{section2}.{name2}. "
|
||||
f"Please delete it from your configuration and use the `{section2}.{name2}` "
|
||||
"setting instead."
|
||||
)
|
||||
|
||||
|
||||
def process_deprecated_setting(config: Dict[str, Any],
|
||||
section1: str, name1: str,
|
||||
section2: str, name2: str) -> None:
|
||||
@@ -44,19 +62,18 @@ def process_deprecated_setting(config: Dict[str, Any],
|
||||
|
||||
def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
|
||||
|
||||
check_conflicting_settings(config, 'ask_strategy', 'use_sell_signal',
|
||||
'experimental', 'use_sell_signal')
|
||||
check_conflicting_settings(config, 'ask_strategy', 'sell_profit_only',
|
||||
'experimental', 'sell_profit_only')
|
||||
check_conflicting_settings(config, 'ask_strategy', 'ignore_roi_if_buy_signal',
|
||||
'experimental', 'ignore_roi_if_buy_signal')
|
||||
# Kept for future deprecated / moved settings
|
||||
# check_conflicting_settings(config, 'ask_strategy', 'use_sell_signal',
|
||||
# 'experimental', 'use_sell_signal')
|
||||
# process_deprecated_setting(config, 'ask_strategy', 'use_sell_signal',
|
||||
# 'experimental', 'use_sell_signal')
|
||||
|
||||
process_deprecated_setting(config, 'ask_strategy', 'use_sell_signal',
|
||||
'experimental', 'use_sell_signal')
|
||||
process_deprecated_setting(config, 'ask_strategy', 'sell_profit_only',
|
||||
'experimental', 'sell_profit_only')
|
||||
process_deprecated_setting(config, 'ask_strategy', 'ignore_roi_if_buy_signal',
|
||||
'experimental', 'ignore_roi_if_buy_signal')
|
||||
process_removed_setting(config, 'experimental', 'use_sell_signal',
|
||||
'ask_strategy', 'use_sell_signal')
|
||||
process_removed_setting(config, 'experimental', 'sell_profit_only',
|
||||
'ask_strategy', 'sell_profit_only')
|
||||
process_removed_setting(config, 'experimental', 'ignore_roi_if_buy_signal',
|
||||
'ask_strategy', 'ignore_roi_if_buy_signal')
|
||||
|
||||
if (config.get('edge', {}).get('enabled', False)
|
||||
and 'capital_available_percentage' in config.get('edge', {})):
|
||||
|
@@ -3,8 +3,9 @@ import shutil
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.constants import USER_DATA_FILES
|
||||
from freqtrade.exceptions import OperationalException
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
@@ -11,6 +11,7 @@ import rapidjson
|
||||
|
||||
from freqtrade.exceptions import OperationalException
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
@@ -52,11 +52,11 @@ class TimeRange:
|
||||
:return: None (Modifies the object in place)
|
||||
"""
|
||||
if (not self.starttype or (startup_candles
|
||||
and min_date.timestamp >= self.startts)):
|
||||
and min_date.int_timestamp >= self.startts)):
|
||||
# If no startts was defined, or backtest-data starts at the defined backtest-date
|
||||
logger.warning("Moving start-date by %s candles to account for startup time.",
|
||||
startup_candles)
|
||||
self.startts = (min_date.timestamp + timeframe_secs * startup_candles)
|
||||
self.startts = (min_date.int_timestamp + timeframe_secs * startup_candles)
|
||||
self.starttype = 'date'
|
||||
|
||||
@staticmethod
|
||||
@@ -89,7 +89,7 @@ class TimeRange:
|
||||
if stype[0]:
|
||||
starts = rvals[index]
|
||||
if stype[0] == 'date' and len(starts) == 8:
|
||||
start = arrow.get(starts, 'YYYYMMDD').timestamp
|
||||
start = arrow.get(starts, 'YYYYMMDD').int_timestamp
|
||||
elif len(starts) == 13:
|
||||
start = int(starts) // 1000
|
||||
else:
|
||||
@@ -98,7 +98,7 @@ class TimeRange:
|
||||
if stype[1]:
|
||||
stops = rvals[index]
|
||||
if stype[1] == 'date' and len(stops) == 8:
|
||||
stop = arrow.get(stops, 'YYYYMMDD').timestamp
|
||||
stop = arrow.get(stops, 'YYYYMMDD').int_timestamp
|
||||
elif len(stops) == 13:
|
||||
stop = int(stops) // 1000
|
||||
else:
|
||||
|
@@ -11,7 +11,6 @@ DEFAULT_EXCHANGE = 'bittrex'
|
||||
PROCESS_THROTTLE_SECS = 5 # sec
|
||||
HYPEROPT_EPOCH = 100 # epochs
|
||||
RETRY_TIMEOUT = 30 # sec
|
||||
DEFAULT_HYPEROPT_LOSS = 'DefaultHyperOptLoss'
|
||||
DEFAULT_DB_PROD_URL = 'sqlite:///tradesv3.sqlite'
|
||||
DEFAULT_DB_DRYRUN_URL = 'sqlite:///tradesv3.dryrun.sqlite'
|
||||
UNLIMITED_STAKE_AMOUNT = 'unlimited'
|
||||
@@ -21,9 +20,14 @@ REQUIRED_ORDERTYPES = ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
||||
ORDERBOOK_SIDES = ['ask', 'bid']
|
||||
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
||||
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
||||
HYPEROPT_LOSS_BUILTIN = ['ShortTradeDurHyperOptLoss', 'OnlyProfitHyperOptLoss',
|
||||
'SharpeHyperOptLoss', 'SharpeHyperOptLossDaily',
|
||||
'SortinoHyperOptLoss', 'SortinoHyperOptLossDaily']
|
||||
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList',
|
||||
'AgeFilter', 'PrecisionFilter', 'PriceFilter',
|
||||
'ShuffleFilter', 'SpreadFilter']
|
||||
'AgeFilter', 'PerformanceFilter', 'PrecisionFilter',
|
||||
'PriceFilter', 'RangeStabilityFilter', 'ShuffleFilter',
|
||||
'SpreadFilter']
|
||||
AVAILABLE_PROTECTIONS = ['CooldownPeriod', 'LowProfitPairs', 'MaxDrawdown', 'StoplossGuard']
|
||||
AVAILABLE_DATAHANDLERS = ['json', 'jsongz', 'hdf5']
|
||||
DRY_RUN_WALLET = 1000
|
||||
DATETIME_PRINT_FORMAT = '%Y-%m-%d %H:%M:%S'
|
||||
@@ -112,6 +116,7 @@ CONF_SCHEMA = {
|
||||
'trailing_stop_positive': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
||||
'trailing_stop_positive_offset': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
||||
'trailing_only_offset_is_reached': {'type': 'boolean'},
|
||||
'bot_name': {'type': 'string'},
|
||||
'unfilledtimeout': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
@@ -150,6 +155,7 @@ CONF_SCHEMA = {
|
||||
'order_book_max': {'type': 'integer', 'minimum': 1, 'maximum': 50},
|
||||
'use_sell_signal': {'type': 'boolean'},
|
||||
'sell_profit_only': {'type': 'boolean'},
|
||||
'sell_profit_offset': {'type': 'number', 'minimum': 0.0},
|
||||
'ignore_roi_if_buy_signal': {'type': 'boolean'}
|
||||
}
|
||||
},
|
||||
@@ -180,9 +186,6 @@ CONF_SCHEMA = {
|
||||
'experimental': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'use_sell_signal': {'type': 'boolean'},
|
||||
'sell_profit_only': {'type': 'boolean'},
|
||||
'ignore_roi_if_buy_signal': {'type': 'boolean'},
|
||||
'block_bad_exchanges': {'type': 'boolean'}
|
||||
}
|
||||
},
|
||||
@@ -192,7 +195,21 @@ CONF_SCHEMA = {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'method': {'type': 'string', 'enum': AVAILABLE_PAIRLISTS},
|
||||
'config': {'type': 'object'}
|
||||
},
|
||||
'required': ['method'],
|
||||
}
|
||||
},
|
||||
'protections': {
|
||||
'type': 'array',
|
||||
'items': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'method': {'type': 'string', 'enum': AVAILABLE_PROTECTIONS},
|
||||
'stop_duration': {'type': 'number', 'minimum': 0.0},
|
||||
'stop_duration_candles': {'type': 'number', 'minimum': 0},
|
||||
'trade_limit': {'type': 'number', 'minimum': 1},
|
||||
'lookback_period': {'type': 'number', 'minimum': 1},
|
||||
'lookback_period_candles': {'type': 'number', 'minimum': 1},
|
||||
},
|
||||
'required': ['method'],
|
||||
}
|
||||
@@ -363,3 +380,6 @@ CANCEL_REASON = {
|
||||
# List of pairs with their timeframes
|
||||
PairWithTimeframe = Tuple[str, str]
|
||||
ListPairsWithTimeframes = List[PairWithTimeframe]
|
||||
|
||||
# Type for trades list
|
||||
TradeList = List[List]
|
||||
|
@@ -2,17 +2,17 @@
|
||||
Helpers when analyzing backtest data
|
||||
"""
|
||||
import logging
|
||||
from datetime import timezone
|
||||
from pathlib import Path
|
||||
from typing import Dict, Union, Tuple, Any, Optional
|
||||
from typing import Any, Dict, Optional, Tuple, Union
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from datetime import timezone
|
||||
|
||||
from freqtrade import persistence
|
||||
from freqtrade.constants import LAST_BT_RESULT_FN
|
||||
from freqtrade.misc import json_load
|
||||
from freqtrade.persistence import Trade
|
||||
from freqtrade.persistence import Trade, init_db
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -21,10 +21,11 @@ BT_DATA_COLUMNS = ["pair", "profit_percent", "open_date", "close_date", "index",
|
||||
"open_rate", "close_rate", "open_at_end", "sell_reason"]
|
||||
|
||||
|
||||
def get_latest_backtest_filename(directory: Union[Path, str]) -> str:
|
||||
def get_latest_optimize_filename(directory: Union[Path, str], variant: str) -> str:
|
||||
"""
|
||||
Get latest backtest export based on '.last_result.json'.
|
||||
:param directory: Directory to search for last result
|
||||
:param variant: 'backtest' or 'hyperopt' - the method to return
|
||||
:return: string containing the filename of the latest backtest result
|
||||
:raises: ValueError in the following cases:
|
||||
* Directory does not exist
|
||||
@@ -44,10 +45,57 @@ def get_latest_backtest_filename(directory: Union[Path, str]) -> str:
|
||||
with filename.open() as file:
|
||||
data = json_load(file)
|
||||
|
||||
if 'latest_backtest' not in data:
|
||||
if f'latest_{variant}' not in data:
|
||||
raise ValueError(f"Invalid '{LAST_BT_RESULT_FN}' format.")
|
||||
|
||||
return data['latest_backtest']
|
||||
return data[f'latest_{variant}']
|
||||
|
||||
|
||||
def get_latest_backtest_filename(directory: Union[Path, str]) -> str:
|
||||
"""
|
||||
Get latest backtest export based on '.last_result.json'.
|
||||
:param directory: Directory to search for last result
|
||||
:return: string containing the filename of the latest backtest result
|
||||
:raises: ValueError in the following cases:
|
||||
* Directory does not exist
|
||||
* `directory/.last_result.json` does not exist
|
||||
* `directory/.last_result.json` has the wrong content
|
||||
"""
|
||||
return get_latest_optimize_filename(directory, 'backtest')
|
||||
|
||||
|
||||
def get_latest_hyperopt_filename(directory: Union[Path, str]) -> str:
|
||||
"""
|
||||
Get latest hyperopt export based on '.last_result.json'.
|
||||
:param directory: Directory to search for last result
|
||||
:return: string containing the filename of the latest hyperopt result
|
||||
:raises: ValueError in the following cases:
|
||||
* Directory does not exist
|
||||
* `directory/.last_result.json` does not exist
|
||||
* `directory/.last_result.json` has the wrong content
|
||||
"""
|
||||
try:
|
||||
return get_latest_optimize_filename(directory, 'hyperopt')
|
||||
except ValueError:
|
||||
# Return default (legacy) pickle filename
|
||||
return 'hyperopt_results.pickle'
|
||||
|
||||
|
||||
def get_latest_hyperopt_file(directory: Union[Path, str], predef_filename: str = None) -> Path:
|
||||
"""
|
||||
Get latest hyperopt export based on '.last_result.json'.
|
||||
:param directory: Directory to search for last result
|
||||
:return: string containing the filename of the latest hyperopt result
|
||||
:raises: ValueError in the following cases:
|
||||
* Directory does not exist
|
||||
* `directory/.last_result.json` does not exist
|
||||
* `directory/.last_result.json` has the wrong content
|
||||
"""
|
||||
if isinstance(directory, str):
|
||||
directory = Path(directory)
|
||||
if predef_filename:
|
||||
return directory / predef_filename
|
||||
return directory / get_latest_hyperopt_filename(directory)
|
||||
|
||||
|
||||
def load_backtest_stats(filename: Union[Path, str]) -> Dict[str, Any]:
|
||||
@@ -169,7 +217,7 @@ def load_trades_from_db(db_url: str, strategy: Optional[str] = None) -> pd.DataF
|
||||
Can also serve as protection to load the correct result.
|
||||
:return: Dataframe containing Trades
|
||||
"""
|
||||
persistence.init(db_url, clean_open_orders=False)
|
||||
init_db(db_url, clean_open_orders=False)
|
||||
|
||||
columns = ["pair", "open_date", "close_date", "profit", "profit_percent",
|
||||
"open_rate", "close_rate", "amount", "trade_duration", "sell_reason",
|
||||
@@ -299,7 +347,7 @@ def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str,
|
||||
# Resample to timeframe to make sure trades match candles
|
||||
_trades_sum = trades.resample(f'{timeframe_minutes}min', on='close_date'
|
||||
)[['profit_percent']].sum()
|
||||
df.loc[:, col_name] = _trades_sum.cumsum()
|
||||
df.loc[:, col_name] = _trades_sum['profit_percent'].cumsum()
|
||||
# Set first value to 0
|
||||
df.loc[df.iloc[0].name, col_name] = 0
|
||||
# FFill to get continuous
|
||||
|
@@ -10,8 +10,8 @@ from typing import Any, Dict, List
|
||||
import pandas as pd
|
||||
from pandas import DataFrame, to_datetime
|
||||
|
||||
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS,
|
||||
DEFAULT_TRADES_COLUMNS)
|
||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, TradeList
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -168,7 +168,7 @@ def trades_remove_duplicates(trades: List[List]) -> List[List]:
|
||||
return [i for i, _ in itertools.groupby(sorted(trades, key=itemgetter(0)))]
|
||||
|
||||
|
||||
def trades_dict_to_list(trades: List[Dict]) -> List[List]:
|
||||
def trades_dict_to_list(trades: List[Dict]) -> TradeList:
|
||||
"""
|
||||
Convert fetch_trades result into a List (to be more memory efficient).
|
||||
:param trades: List of trades, as returned by ccxt.fetch_trades.
|
||||
@@ -177,16 +177,18 @@ def trades_dict_to_list(trades: List[Dict]) -> List[List]:
|
||||
return [[t[col] for col in DEFAULT_TRADES_COLUMNS] for t in trades]
|
||||
|
||||
|
||||
def trades_to_ohlcv(trades: List, timeframe: str) -> DataFrame:
|
||||
def trades_to_ohlcv(trades: TradeList, timeframe: str) -> DataFrame:
|
||||
"""
|
||||
Converts trades list to OHLCV list
|
||||
TODO: This should get a dedicated test
|
||||
:param trades: List of trades, as returned by ccxt.fetch_trades.
|
||||
:param timeframe: Timeframe to resample data to
|
||||
:return: OHLCV Dataframe.
|
||||
:raises: ValueError if no trades are provided
|
||||
"""
|
||||
from freqtrade.exchange import timeframe_to_minutes
|
||||
timeframe_minutes = timeframe_to_minutes(timeframe)
|
||||
if not trades:
|
||||
raise ValueError('Trade-list empty.')
|
||||
df = pd.DataFrame(trades, columns=DEFAULT_TRADES_COLUMNS)
|
||||
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms',
|
||||
utc=True,)
|
||||
|
@@ -8,7 +8,6 @@ import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from arrow import Arrow
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.constants import ListPairsWithTimeframes, PairWithTimeframe
|
||||
@@ -17,6 +16,7 @@ from freqtrade.exceptions import ExchangeError, OperationalException
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ class DataProvider:
|
||||
:param timeframe: Timeframe to get data for
|
||||
:param dataframe: analyzed dataframe
|
||||
"""
|
||||
self.__cached_pairs[(pair, timeframe)] = (dataframe, Arrow.utcnow().datetime)
|
||||
self.__cached_pairs[(pair, timeframe)] = (dataframe, datetime.now(timezone.utc))
|
||||
|
||||
def add_pairlisthandler(self, pairlists) -> None:
|
||||
"""
|
||||
@@ -87,7 +87,8 @@ class DataProvider:
|
||||
"""
|
||||
return load_pair_history(pair=pair,
|
||||
timeframe=timeframe or self._config['timeframe'],
|
||||
datadir=self._config['datadir']
|
||||
datadir=self._config['datadir'],
|
||||
data_format=self._config.get('dataformat_ohlcv', 'json')
|
||||
)
|
||||
|
||||
def get_pair_dataframe(self, pair: str, timeframe: str = None) -> DataFrame:
|
||||
|
@@ -5,10 +5,8 @@ Includes:
|
||||
* load data for a pair (or a list of pairs) from disk
|
||||
* download data from exchange and store to disk
|
||||
"""
|
||||
|
||||
from .history_utils import (convert_trades_to_ohlcv, # noqa: F401
|
||||
get_timerange, load_data, load_pair_history,
|
||||
refresh_backtest_ohlcv_data,
|
||||
refresh_backtest_trades_data, refresh_data,
|
||||
# flake8: noqa: F401
|
||||
from .history_utils import (convert_trades_to_ohlcv, get_timerange, load_data, load_pair_history,
|
||||
refresh_backtest_ohlcv_data, refresh_backtest_trades_data, refresh_data,
|
||||
validate_backtest_data)
|
||||
from .idatahandler import get_datahandler # noqa: F401
|
||||
from .idatahandler import get_datahandler
|
||||
|
@@ -3,15 +3,16 @@ import re
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from freqtrade import misc
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS,
|
||||
DEFAULT_TRADES_COLUMNS,
|
||||
ListPairsWithTimeframes)
|
||||
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS,
|
||||
ListPairsWithTimeframes, TradeList)
|
||||
|
||||
from .idatahandler import IDataHandler
|
||||
|
||||
from .idatahandler import IDataHandler, TradeList
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -175,7 +176,8 @@ class HDF5DataHandler(IDataHandler):
|
||||
if timerange.stoptype == 'date':
|
||||
where.append(f"timestamp < {timerange.stopts * 1e3}")
|
||||
|
||||
trades = pd.read_hdf(filename, key=key, mode="r", where=where)
|
||||
trades: pd.DataFrame = pd.read_hdf(filename, key=key, mode="r", where=where)
|
||||
trades[['id', 'type']] = trades[['id', 'type']].replace({np.nan: None})
|
||||
return trades.values.tolist()
|
||||
|
||||
def trades_purge(self, pair: str) -> bool:
|
||||
|
@@ -9,15 +9,14 @@ from pandas import DataFrame
|
||||
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS
|
||||
from freqtrade.data.converter import (clean_ohlcv_dataframe,
|
||||
ohlcv_to_dataframe,
|
||||
trades_remove_duplicates,
|
||||
trades_to_ohlcv)
|
||||
from freqtrade.data.converter import (clean_ohlcv_dataframe, ohlcv_to_dataframe,
|
||||
trades_remove_duplicates, trades_to_ohlcv)
|
||||
from freqtrade.data.history.idatahandler import IDataHandler, get_datahandler
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.misc import format_ms_time
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -215,10 +214,9 @@ def _download_pair_history(datadir: Path,
|
||||
data_handler.ohlcv_store(pair, timeframe, data=data)
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f'Failed to download history data for pair: "{pair}", timeframe: {timeframe}. '
|
||||
f'Error: {e}'
|
||||
except Exception:
|
||||
logger.exception(
|
||||
f'Failed to download history data for pair: "{pair}", timeframe: {timeframe}.'
|
||||
)
|
||||
return False
|
||||
|
||||
@@ -305,10 +303,9 @@ def _download_trades_history(exchange: Exchange,
|
||||
logger.info(f"New Amount of trades: {len(trades)}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
except Exception:
|
||||
logger.exception(
|
||||
f'Failed to download historic trades for pair: "{pair}". '
|
||||
f'Error: {e}'
|
||||
)
|
||||
return False
|
||||
|
||||
@@ -357,9 +354,12 @@ def convert_trades_to_ohlcv(pairs: List[str], timeframes: List[str],
|
||||
if erase:
|
||||
if data_handler_ohlcv.ohlcv_purge(pair, timeframe):
|
||||
logger.info(f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
||||
ohlcv = trades_to_ohlcv(trades, timeframe)
|
||||
# Store ohlcv
|
||||
data_handler_ohlcv.ohlcv_store(pair, timeframe, data=ohlcv)
|
||||
try:
|
||||
ohlcv = trades_to_ohlcv(trades, timeframe)
|
||||
# Store ohlcv
|
||||
data_handler_ohlcv.ohlcv_store(pair, timeframe, data=ohlcv)
|
||||
except ValueError:
|
||||
logger.exception(f'Could not convert {pair} to OHLCV.')
|
||||
|
||||
|
||||
def get_timerange(data: Dict[str, DataFrame]) -> Tuple[arrow.Arrow, arrow.Arrow]:
|
||||
|
@@ -13,15 +13,12 @@ from typing import List, Optional, Type
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.constants import ListPairsWithTimeframes
|
||||
from freqtrade.data.converter import (clean_ohlcv_dataframe,
|
||||
trades_remove_duplicates, trim_dataframe)
|
||||
from freqtrade.constants import ListPairsWithTimeframes, TradeList
|
||||
from freqtrade.data.converter import clean_ohlcv_dataframe, trades_remove_duplicates, trim_dataframe
|
||||
from freqtrade.exchange import timeframe_to_seconds
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Type for trades list
|
||||
TradeList = List[List]
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class IDataHandler(ABC):
|
||||
|
@@ -8,11 +8,11 @@ from pandas import DataFrame, read_json, to_datetime
|
||||
|
||||
from freqtrade import misc
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS,
|
||||
ListPairsWithTimeframes)
|
||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, ListPairsWithTimeframes, TradeList
|
||||
from freqtrade.data.converter import trades_dict_to_list
|
||||
|
||||
from .idatahandler import IDataHandler, TradeList
|
||||
from .idatahandler import IDataHandler
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
@@ -9,11 +9,13 @@ import utils_find_1st as utf1st
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.constants import UNLIMITED_STAKE_AMOUNT, DATETIME_PRINT_FORMAT
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.constants import DATETIME_PRINT_FORMAT, UNLIMITED_STAKE_AMOUNT
|
||||
from freqtrade.data.history import get_timerange, load_data, refresh_data
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
||||
from freqtrade.strategy.interface import SellType
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -79,14 +81,16 @@ class Edge:
|
||||
if config.get('fee'):
|
||||
self.fee = config['fee']
|
||||
else:
|
||||
self.fee = self.exchange.get_fee(symbol=self.config['exchange']['pair_whitelist'][0])
|
||||
self.fee = self.exchange.get_fee(symbol=expand_pairlist(
|
||||
self.config['exchange']['pair_whitelist'], list(self.exchange.markets))[0])
|
||||
|
||||
def calculate(self) -> bool:
|
||||
pairs = self.config['exchange']['pair_whitelist']
|
||||
pairs = expand_pairlist(self.config['exchange']['pair_whitelist'],
|
||||
list(self.exchange.markets))
|
||||
heartbeat = self.edge_config.get('process_throttle_secs')
|
||||
|
||||
if (self._last_updated > 0) and (
|
||||
self._last_updated + heartbeat > arrow.utcnow().timestamp):
|
||||
self._last_updated + heartbeat > arrow.utcnow().int_timestamp):
|
||||
return False
|
||||
|
||||
data: Dict[str, Any] = {}
|
||||
@@ -145,7 +149,7 @@ class Edge:
|
||||
# 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
|
||||
self._last_updated = arrow.utcnow().int_timestamp
|
||||
|
||||
return True
|
||||
|
||||
@@ -309,8 +313,10 @@ class Edge:
|
||||
|
||||
# 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']
|
||||
df['average_win'] = np.where(df['nb_win_trades'] == 0, 0.0,
|
||||
df['profit_sum'] / df['nb_win_trades'])
|
||||
df['average_loss'] = np.where(df['nb_loss_trades'] == 0, 0.0,
|
||||
df['loss_sum'] / df['nb_loss_trades'])
|
||||
|
||||
# Win rate = number of profitable trades / number of trades
|
||||
df['winrate'] = df['nb_win_trades'] / df['nb_trades']
|
||||
|
@@ -1,19 +1,17 @@
|
||||
# flake8: noqa: F401
|
||||
# isort: off
|
||||
from freqtrade.exchange.common import MAP_EXCHANGE_CHILDCLASS
|
||||
from freqtrade.exchange.exchange import Exchange
|
||||
from freqtrade.exchange.exchange import (get_exchange_bad_reason,
|
||||
is_exchange_bad,
|
||||
is_exchange_known_ccxt,
|
||||
is_exchange_officially_supported,
|
||||
ccxt_exchanges,
|
||||
available_exchanges)
|
||||
from freqtrade.exchange.exchange import (timeframe_to_seconds,
|
||||
timeframe_to_minutes,
|
||||
timeframe_to_msecs,
|
||||
timeframe_to_next_date,
|
||||
timeframe_to_prev_date)
|
||||
from freqtrade.exchange.exchange import (market_is_active)
|
||||
from freqtrade.exchange.kraken import Kraken
|
||||
from freqtrade.exchange.binance import Binance
|
||||
# isort: on
|
||||
from freqtrade.exchange.bibox import Bibox
|
||||
from freqtrade.exchange.binance import Binance
|
||||
from freqtrade.exchange.bittrex import Bittrex
|
||||
from freqtrade.exchange.bybit import Bybit
|
||||
from freqtrade.exchange.exchange import (available_exchanges, ccxt_exchanges,
|
||||
get_exchange_bad_reason, is_exchange_bad,
|
||||
is_exchange_known_ccxt, is_exchange_officially_supported,
|
||||
market_is_active, timeframe_to_minutes, timeframe_to_msecs,
|
||||
timeframe_to_next_date, timeframe_to_prev_date,
|
||||
timeframe_to_seconds)
|
||||
from freqtrade.exchange.ftx import Ftx
|
||||
from freqtrade.exchange.kraken import Kraken
|
||||
|
@@ -4,6 +4,7 @@ from typing import Dict
|
||||
|
||||
from freqtrade.exchange import Exchange
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
@@ -4,12 +4,12 @@ from typing import Dict
|
||||
|
||||
import ccxt
|
||||
|
||||
from freqtrade.exceptions import (DDosProtection, InsufficientFundsError,
|
||||
InvalidOrderException, OperationalException,
|
||||
TemporaryError)
|
||||
from freqtrade.exceptions import (DDosProtection, InsufficientFundsError, InvalidOrderException,
|
||||
OperationalException, TemporaryError)
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.exchange.common import retrier
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -18,22 +18,12 @@ class Binance(Exchange):
|
||||
_ft_has: Dict = {
|
||||
"stoploss_on_exchange": True,
|
||||
"order_time_in_force": ['gtc', 'fok', 'ioc'],
|
||||
"ohlcv_candle_limit": 1000,
|
||||
"trades_pagination": "id",
|
||||
"trades_pagination_arg": "fromId",
|
||||
"l2_limit_range": [5, 10, 20, 50, 100, 500, 1000],
|
||||
}
|
||||
|
||||
def fetch_l2_order_book(self, pair: str, limit: int = 100) -> dict:
|
||||
"""
|
||||
get order book level 2 from exchange
|
||||
|
||||
20180619: binance support limits but only on specific range
|
||||
"""
|
||||
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)))
|
||||
|
||||
return super().fetch_l2_order_book(pair, limit)
|
||||
|
||||
def stoploss_adjust(self, stop_loss: float, order: Dict) -> bool:
|
||||
"""
|
||||
Verify stop_loss against stoploss-order value (limit or price)
|
||||
|
23
freqtrade/exchange/bittrex.py
Normal file
23
freqtrade/exchange/bittrex.py
Normal file
@@ -0,0 +1,23 @@
|
||||
""" Bittrex exchange subclass """
|
||||
import logging
|
||||
from typing import Dict
|
||||
|
||||
from freqtrade.exchange import Exchange
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Bittrex(Exchange):
|
||||
"""
|
||||
Bittrex exchange class. Contains adjustments needed for Freqtrade to work
|
||||
with this exchange.
|
||||
|
||||
Please note that this exchange is not included in the list of exchanges
|
||||
officially supported by the Freqtrade development team. So some features
|
||||
may still not work as expected.
|
||||
"""
|
||||
|
||||
_ft_has: Dict = {
|
||||
"l2_limit_range": [1, 25, 500],
|
||||
}
|
24
freqtrade/exchange/bybit.py
Normal file
24
freqtrade/exchange/bybit.py
Normal file
@@ -0,0 +1,24 @@
|
||||
""" Bybit exchange subclass """
|
||||
import logging
|
||||
from typing import Dict
|
||||
|
||||
from freqtrade.exchange import Exchange
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Bybit(Exchange):
|
||||
"""
|
||||
Bybit exchange class. Contains adjustments needed for Freqtrade to work
|
||||
with this exchange.
|
||||
|
||||
Please note that this exchange is not included in the list of exchanges
|
||||
officially supported by the Freqtrade development team. So some features
|
||||
may still not work as expected.
|
||||
"""
|
||||
|
||||
# fetchCurrencies API point requires authentication for Bybit,
|
||||
_ft_has: Dict = {
|
||||
"ohlcv_candle_limit": 200,
|
||||
}
|
@@ -3,8 +3,8 @@ import logging
|
||||
import time
|
||||
from functools import wraps
|
||||
|
||||
from freqtrade.exceptions import (DDosProtection, RetryableOrderError,
|
||||
TemporaryError)
|
||||
from freqtrade.exceptions import DDosProtection, RetryableOrderError, TemporaryError
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -21,6 +21,7 @@ BAD_EXCHANGES = {
|
||||
"hitbtc": "This API cannot be used with Freqtrade. "
|
||||
"Use `hitbtc2` exchange id to access this exchange.",
|
||||
"phemex": "Does not provide history. ",
|
||||
"poloniex": "Does not provide fetch_order endpoint to fetch both open and closed orders.",
|
||||
**dict.fromkeys([
|
||||
'adara',
|
||||
'anxpro',
|
||||
|
@@ -13,19 +13,20 @@ from typing import Any, Dict, List, Optional, Tuple
|
||||
import arrow
|
||||
import ccxt
|
||||
import ccxt.async_support as ccxt_async
|
||||
from ccxt.base.decimal_to_precision import (ROUND_DOWN, ROUND_UP, TICK_SIZE,
|
||||
TRUNCATE, decimal_to_precision)
|
||||
from ccxt.base.decimal_to_precision import (ROUND_DOWN, ROUND_UP, TICK_SIZE, TRUNCATE,
|
||||
decimal_to_precision)
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.constants import ListPairsWithTimeframes
|
||||
from freqtrade.data.converter import ohlcv_to_dataframe, trades_dict_to_list
|
||||
from freqtrade.exceptions import (DDosProtection, ExchangeError,
|
||||
InsufficientFundsError,
|
||||
InvalidOrderException, OperationalException,
|
||||
RetryableOrderError, TemporaryError)
|
||||
from freqtrade.exchange.common import (API_FETCH_ORDER_RETRY_COUNT,
|
||||
BAD_EXCHANGES, retrier, retrier_async)
|
||||
from freqtrade.exceptions import (DDosProtection, ExchangeError, InsufficientFundsError,
|
||||
InvalidOrderException, OperationalException, RetryableOrderError,
|
||||
TemporaryError)
|
||||
from freqtrade.exchange.common import (API_FETCH_ORDER_RETRY_COUNT, BAD_EXCHANGES, retrier,
|
||||
retrier_async)
|
||||
from freqtrade.misc import deep_merge_dicts, safe_value_fallback2
|
||||
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
||||
|
||||
|
||||
CcxtModuleType = Any
|
||||
|
||||
@@ -53,7 +54,7 @@ class Exchange:
|
||||
"ohlcv_partial_candle": True,
|
||||
"trades_pagination": "time", # Possible are "time" or "id"
|
||||
"trades_pagination_arg": "since",
|
||||
|
||||
"l2_limit_range": None,
|
||||
}
|
||||
_ft_has: Dict = {}
|
||||
|
||||
@@ -124,7 +125,8 @@ class Exchange:
|
||||
|
||||
# Check if all pairs are available
|
||||
self.validate_stakecurrency(config['stake_currency'])
|
||||
self.validate_pairs(config['exchange']['pair_whitelist'])
|
||||
if not exchange_config.get('skip_pair_validation'):
|
||||
self.validate_pairs(config['exchange']['pair_whitelist'])
|
||||
self.validate_ordertypes(config.get('order_types', {}))
|
||||
self.validate_order_time_in_force(config.get('order_time_in_force', {}))
|
||||
self.validate_required_startup_candles(config.get('startup_candle_count', 0))
|
||||
@@ -207,7 +209,7 @@ class Exchange:
|
||||
return self._api.precisionMode
|
||||
|
||||
def get_markets(self, base_currencies: List[str] = None, quote_currencies: List[str] = None,
|
||||
pairs_only: bool = False, active_only: bool = False) -> Dict:
|
||||
pairs_only: bool = False, active_only: bool = False) -> Dict[str, Any]:
|
||||
"""
|
||||
Return exchange ccxt markets, filtered out by base currency and quote currency
|
||||
if this was requested in parameters.
|
||||
@@ -282,7 +284,7 @@ class Exchange:
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
self._api_async.load_markets(reload=reload))
|
||||
|
||||
except ccxt.BaseError as e:
|
||||
except (asyncio.TimeoutError, ccxt.BaseError) as e:
|
||||
logger.warning('Could not load async markets. Reason: %s', e)
|
||||
return
|
||||
|
||||
@@ -291,7 +293,7 @@ class Exchange:
|
||||
try:
|
||||
self._api.load_markets()
|
||||
self._load_async_markets()
|
||||
self._last_markets_refresh = arrow.utcnow().timestamp
|
||||
self._last_markets_refresh = arrow.utcnow().int_timestamp
|
||||
except ccxt.BaseError as e:
|
||||
logger.warning('Unable to initialize markets. Reason: %s', e)
|
||||
|
||||
@@ -300,14 +302,14 @@ class Exchange:
|
||||
# Check whether markets have to be reloaded
|
||||
if (self._last_markets_refresh > 0) and (
|
||||
self._last_markets_refresh + self.markets_refresh_interval
|
||||
> arrow.utcnow().timestamp):
|
||||
> arrow.utcnow().int_timestamp):
|
||||
return None
|
||||
logger.debug("Performing scheduled market reload..")
|
||||
try:
|
||||
self._api.load_markets(reload=True)
|
||||
# Also reload async markets to avoid issues with newly listed pairs
|
||||
self._load_async_markets(reload=True)
|
||||
self._last_markets_refresh = arrow.utcnow().timestamp
|
||||
self._last_markets_refresh = arrow.utcnow().int_timestamp
|
||||
except ccxt.BaseError:
|
||||
logger.exception("Could not reload markets.")
|
||||
|
||||
@@ -334,8 +336,9 @@ class Exchange:
|
||||
if not self.markets:
|
||||
logger.warning('Unable to validate pairs (assuming they are correct).')
|
||||
return
|
||||
extended_pairs = expand_pairlist(pairs, list(self.markets), keep_invalid=True)
|
||||
invalid_pairs = []
|
||||
for pair in pairs:
|
||||
for pair in extended_pairs:
|
||||
# Note: ccxt has BaseCurrency/QuoteCurrency format for pairs
|
||||
# TODO: add a support for having coins in BTC/USDT format
|
||||
if self.markets and pair not in self.markets:
|
||||
@@ -501,7 +504,7 @@ class Exchange:
|
||||
'side': side,
|
||||
'remaining': _amount,
|
||||
'datetime': arrow.utcnow().isoformat(),
|
||||
'timestamp': int(arrow.utcnow().timestamp * 1000),
|
||||
'timestamp': int(arrow.utcnow().int_timestamp * 1000),
|
||||
'status': "closed" if ordertype == "market" else "open",
|
||||
'fee': None,
|
||||
'info': {}
|
||||
@@ -523,7 +526,7 @@ class Exchange:
|
||||
'rate': self.get_fee(pair)
|
||||
}
|
||||
})
|
||||
if closed_order["type"] in ["stop_loss_limit"]:
|
||||
if closed_order["type"] in ["stop_loss_limit", "stop-loss-limit"]:
|
||||
closed_order["info"].update({"stopPrice": closed_order["price"]})
|
||||
self._dry_run_open_orders[closed_order["id"]] = closed_order
|
||||
|
||||
@@ -657,7 +660,8 @@ class Exchange:
|
||||
@retrier
|
||||
def fetch_ticker(self, pair: str) -> dict:
|
||||
try:
|
||||
if pair not in self._api.markets or not self._api.markets[pair].get('active'):
|
||||
if (pair not in self._api.markets or
|
||||
self._api.markets[pair].get('active', False) is False):
|
||||
raise ExchangeError(f"Pair {pair} not available")
|
||||
data = self._api.fetch_ticker(pair)
|
||||
return data
|
||||
@@ -678,15 +682,31 @@ class Exchange:
|
||||
:param pair: Pair to download
|
||||
:param timeframe: Timeframe to get data for
|
||||
:param since_ms: Timestamp in milliseconds to get history from
|
||||
:returns List with candle (OHLCV) data
|
||||
:return: List with candle (OHLCV) data
|
||||
"""
|
||||
return asyncio.get_event_loop().run_until_complete(
|
||||
self._async_get_historic_ohlcv(pair=pair, timeframe=timeframe,
|
||||
since_ms=since_ms))
|
||||
|
||||
def get_historic_ohlcv_as_df(self, pair: str, timeframe: str,
|
||||
since_ms: int) -> DataFrame:
|
||||
"""
|
||||
Minimal wrapper around get_historic_ohlcv - converting the result into a dataframe
|
||||
:param pair: Pair to download
|
||||
:param timeframe: Timeframe to get data for
|
||||
:param since_ms: Timestamp in milliseconds to get history from
|
||||
:return: OHLCV DataFrame
|
||||
"""
|
||||
ticks = self.get_historic_ohlcv(pair, timeframe, since_ms=since_ms)
|
||||
return ohlcv_to_dataframe(ticks, timeframe, pair=pair, fill_missing=True,
|
||||
drop_incomplete=self._ohlcv_partial_candle)
|
||||
|
||||
async def _async_get_historic_ohlcv(self, pair: str,
|
||||
timeframe: str,
|
||||
since_ms: int) -> List:
|
||||
"""
|
||||
Download historic ohlcv
|
||||
"""
|
||||
|
||||
one_call = timeframe_to_msecs(timeframe) * self._ohlcv_candle_limit
|
||||
logger.debug(
|
||||
@@ -696,27 +716,36 @@ class Exchange:
|
||||
)
|
||||
input_coroutines = [self._async_get_candle_history(
|
||||
pair, timeframe, since) for since in
|
||||
range(since_ms, arrow.utcnow().timestamp * 1000, one_call)]
|
||||
range(since_ms, arrow.utcnow().int_timestamp * 1000, one_call)]
|
||||
|
||||
results = await asyncio.gather(*input_coroutines, return_exceptions=True)
|
||||
|
||||
# Combine gathered results
|
||||
data: List = []
|
||||
for p, timeframe, res in results:
|
||||
for res in results:
|
||||
if isinstance(res, Exception):
|
||||
logger.warning("Async code raised an exception: %s", res.__class__.__name__)
|
||||
continue
|
||||
# Deconstruct tuple if it's not an exception
|
||||
p, _, new_data = res
|
||||
if p == pair:
|
||||
data.extend(res)
|
||||
data.extend(new_data)
|
||||
# Sort data again after extending the result - above calls return in "async order"
|
||||
data = sorted(data, key=lambda x: x[0])
|
||||
logger.info("Downloaded data for %s with length %s.", pair, len(data))
|
||||
return data
|
||||
|
||||
def refresh_latest_ohlcv(self, pair_list: ListPairsWithTimeframes) -> List[Tuple[str, List]]:
|
||||
def refresh_latest_ohlcv(self, pair_list: ListPairsWithTimeframes, *,
|
||||
since_ms: Optional[int] = None, cache: bool = True
|
||||
) -> Dict[Tuple[str, str], DataFrame]:
|
||||
"""
|
||||
Refresh in-memory OHLCV asynchronously and set `_klines` with the result
|
||||
Loops asynchronously over pair_list and downloads all pairs async (semi-parallel).
|
||||
Only used in the dataprovider.refresh() method.
|
||||
:param pair_list: List of 2 element tuples containing pair, interval to refresh
|
||||
:return: TODO: return value is only used in the tests, get rid of it
|
||||
:param since_ms: time since when to download, in milliseconds
|
||||
:param cache: Assign result to _klines. Usefull for one-off downloads like for pairlists
|
||||
:return: Dict of [{(pair, timeframe): Dataframe}]
|
||||
"""
|
||||
logger.debug("Refreshing candle (OHLCV) data for %d pairs", len(pair_list))
|
||||
|
||||
@@ -726,7 +755,8 @@ class Exchange:
|
||||
for pair, timeframe in set(pair_list):
|
||||
if (not ((pair, timeframe) in self._klines)
|
||||
or self._now_is_time_to_refresh(pair, timeframe)):
|
||||
input_coroutines.append(self._async_get_candle_history(pair, timeframe))
|
||||
input_coroutines.append(self._async_get_candle_history(pair, timeframe,
|
||||
since_ms=since_ms))
|
||||
else:
|
||||
logger.debug(
|
||||
"Using cached candle (OHLCV) data for pair %s, timeframe %s ...",
|
||||
@@ -736,30 +766,32 @@ class Exchange:
|
||||
results = asyncio.get_event_loop().run_until_complete(
|
||||
asyncio.gather(*input_coroutines, return_exceptions=True))
|
||||
|
||||
results_df = {}
|
||||
# handle caching
|
||||
for res in results:
|
||||
if isinstance(res, Exception):
|
||||
logger.warning("Async code raised an exception: %s", res.__class__.__name__)
|
||||
continue
|
||||
pair = res[0]
|
||||
timeframe = res[1]
|
||||
ticks = res[2]
|
||||
# Deconstruct tuple (has 3 elements)
|
||||
pair, timeframe, ticks = res
|
||||
# keeping last candle time as last refreshed time of the pair
|
||||
if ticks:
|
||||
self._pairs_last_refresh_time[(pair, timeframe)] = ticks[-1][0] // 1000
|
||||
# keeping parsed dataframe in cache
|
||||
self._klines[(pair, timeframe)] = ohlcv_to_dataframe(
|
||||
ticks, timeframe, pair=pair, fill_missing=True,
|
||||
drop_incomplete=self._ohlcv_partial_candle)
|
||||
|
||||
return results
|
||||
ohlcv_df = ohlcv_to_dataframe(
|
||||
ticks, timeframe, pair=pair, fill_missing=True,
|
||||
drop_incomplete=self._ohlcv_partial_candle)
|
||||
results_df[(pair, timeframe)] = ohlcv_df
|
||||
if cache:
|
||||
self._klines[(pair, timeframe)] = ohlcv_df
|
||||
return results_df
|
||||
|
||||
def _now_is_time_to_refresh(self, pair: str, timeframe: str) -> bool:
|
||||
# Timeframe in seconds
|
||||
interval_in_sec = timeframe_to_seconds(timeframe)
|
||||
|
||||
return not ((self._pairs_last_refresh_time.get((pair, timeframe), 0)
|
||||
+ interval_in_sec) >= arrow.utcnow().timestamp)
|
||||
+ interval_in_sec) >= arrow.utcnow().int_timestamp)
|
||||
|
||||
@retrier_async
|
||||
async def _async_get_candle_history(self, pair: str, timeframe: str,
|
||||
@@ -777,7 +809,8 @@ class Exchange:
|
||||
)
|
||||
|
||||
data = await self._api_async.fetch_ohlcv(pair, timeframe=timeframe,
|
||||
since=since_ms)
|
||||
since=since_ms,
|
||||
limit=self._ohlcv_candle_limit)
|
||||
|
||||
# Some exchanges sort OHLCV in ASC order and others in DESC.
|
||||
# Ex: Bittrex returns the list of OHLCV in ASC order (oldest first, newest last)
|
||||
@@ -905,7 +938,7 @@ class Exchange:
|
||||
while True:
|
||||
t = await self._async_fetch_trades(pair, since=since)
|
||||
if len(t):
|
||||
since = t[-1][1]
|
||||
since = t[-1][0]
|
||||
trades.extend(t)
|
||||
# Reached the end of the defined-download period
|
||||
if until and t[-1][0] > until:
|
||||
@@ -1069,6 +1102,16 @@ class Exchange:
|
||||
return self.fetch_stoploss_order(order_id, pair)
|
||||
return self.fetch_order(order_id, pair)
|
||||
|
||||
@staticmethod
|
||||
def get_next_limit_in_list(limit: int, limit_range: Optional[List[int]]):
|
||||
"""
|
||||
Get next greater value in the list.
|
||||
Used by fetch_l2_order_book if the api only supports a limited range
|
||||
"""
|
||||
if not limit_range:
|
||||
return limit
|
||||
return min([x for x in limit_range if limit <= x] + [max(limit_range)])
|
||||
|
||||
@retrier
|
||||
def fetch_l2_order_book(self, pair: str, limit: int = 100) -> dict:
|
||||
"""
|
||||
@@ -1077,9 +1120,10 @@ class Exchange:
|
||||
Returns a dict in the format
|
||||
{'asks': [price, volume], 'bids': [price, volume]}
|
||||
"""
|
||||
limit1 = self.get_next_limit_in_list(limit, self._ft_has['l2_limit_range'])
|
||||
try:
|
||||
|
||||
return self._api.fetch_l2_order_book(pair, limit)
|
||||
return self._api.fetch_l2_order_book(pair, limit1)
|
||||
except ccxt.NotSupported as e:
|
||||
raise OperationalException(
|
||||
f'Exchange {self._api.name} does not support fetching order book.'
|
||||
|
@@ -4,12 +4,12 @@ from typing import Any, Dict
|
||||
|
||||
import ccxt
|
||||
|
||||
from freqtrade.exceptions import (DDosProtection, InsufficientFundsError,
|
||||
InvalidOrderException, OperationalException,
|
||||
TemporaryError)
|
||||
from freqtrade.exceptions import (DDosProtection, InsufficientFundsError, InvalidOrderException,
|
||||
OperationalException, TemporaryError)
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.exchange.common import API_FETCH_ORDER_RETRY_COUNT, retrier
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
@@ -4,12 +4,12 @@ from typing import Any, Dict
|
||||
|
||||
import ccxt
|
||||
|
||||
from freqtrade.exceptions import (DDosProtection, InsufficientFundsError,
|
||||
InvalidOrderException, OperationalException,
|
||||
TemporaryError)
|
||||
from freqtrade.exceptions import (DDosProtection, InsufficientFundsError, InvalidOrderException,
|
||||
OperationalException, TemporaryError)
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.exchange.common import retrier
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ class Kraken(Exchange):
|
||||
_params: Dict = {"trading_agreement": "agree"}
|
||||
_ft_has: Dict = {
|
||||
"stoploss_on_exchange": True,
|
||||
"ohlcv_candle_limit": 720,
|
||||
"trades_pagination": "id",
|
||||
"trades_pagination_arg": "since",
|
||||
}
|
||||
@@ -47,7 +48,7 @@ class Kraken(Exchange):
|
||||
|
||||
orders = self._api.fetch_open_orders()
|
||||
order_list = [(x["symbol"].split("/")[0 if x["side"] == "sell" else 1],
|
||||
x["remaining"],
|
||||
x["remaining"] if x["side"] == "sell" else x["remaining"] * x["price"],
|
||||
# Don't remove the below comment, this can be important for debuggung
|
||||
# x["side"], x["amount"],
|
||||
) for x in orders]
|
||||
@@ -69,7 +70,8 @@ class Kraken(Exchange):
|
||||
Verify stop_loss against stoploss-order value (limit or price)
|
||||
Returns True if adjustment is necessary.
|
||||
"""
|
||||
return order['type'] == 'stop-loss' and stop_loss > float(order['price'])
|
||||
return (order['type'] in ('stop-loss', 'stop-loss-limit')
|
||||
and stop_loss > float(order['price']))
|
||||
|
||||
@retrier(retries=0)
|
||||
def stoploss(self, pair: str, amount: float, stop_price: float, order_types: Dict) -> Dict:
|
||||
@@ -77,8 +79,15 @@ class Kraken(Exchange):
|
||||
Creates a stoploss market order.
|
||||
Stoploss market orders is the only stoploss type supported by kraken.
|
||||
"""
|
||||
params = self._params.copy()
|
||||
|
||||
ordertype = "stop-loss"
|
||||
if order_types.get('stoploss', 'market') == 'limit':
|
||||
ordertype = "stop-loss-limit"
|
||||
limit_price_pct = order_types.get('stoploss_on_exchange_limit_ratio', 0.99)
|
||||
limit_rate = stop_price * limit_price_pct
|
||||
params['price2'] = self.price_to_precision(pair, limit_rate)
|
||||
else:
|
||||
ordertype = "stop-loss"
|
||||
|
||||
stop_price = self.price_to_precision(pair, stop_price)
|
||||
|
||||
@@ -88,8 +97,6 @@ class Kraken(Exchange):
|
||||
return dry_order
|
||||
|
||||
try:
|
||||
params = self._params.copy()
|
||||
|
||||
amount = self.amount_to_precision(pair, amount)
|
||||
|
||||
order = self._api.create_order(symbol=pair, type=ordertype, side='sell',
|
||||
|
@@ -4,7 +4,7 @@ Freqtrade is the main module of this bot. It contains the class Freqtrade()
|
||||
import copy
|
||||
import logging
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from math import isclose
|
||||
from threading import Lock
|
||||
from typing import Any, Dict, List, Optional
|
||||
@@ -12,17 +12,19 @@ from typing import Any, Dict, List, Optional
|
||||
import arrow
|
||||
from cachetools import TTLCache
|
||||
|
||||
from freqtrade import __version__, constants, persistence
|
||||
from freqtrade import __version__, constants
|
||||
from freqtrade.configuration import validate_config_consistency
|
||||
from freqtrade.data.converter import order_book_to_dataframe
|
||||
from freqtrade.data.dataprovider import DataProvider
|
||||
from freqtrade.edge import Edge
|
||||
from freqtrade.exceptions import (DependencyException, ExchangeError, InsufficientFundsError,
|
||||
InvalidOrderException, PricingError)
|
||||
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_next_date
|
||||
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds
|
||||
from freqtrade.misc import safe_value_fallback, safe_value_fallback2
|
||||
from freqtrade.pairlist.pairlistmanager import PairListManager
|
||||
from freqtrade.persistence import Order, Trade
|
||||
from freqtrade.mixins import LoggingMixin
|
||||
from freqtrade.persistence import Order, PairLocks, Trade, cleanup_db, init_db
|
||||
from freqtrade.plugins.pairlistmanager import PairListManager
|
||||
from freqtrade.plugins.protectionmanager import ProtectionManager
|
||||
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||
from freqtrade.rpc import RPCManager, RPCMessageType
|
||||
from freqtrade.state import State
|
||||
@@ -30,10 +32,11 @@ from freqtrade.strategy.interface import IStrategy, SellType
|
||||
from freqtrade.strategy.strategy_wrapper import strategy_safe_wrapper
|
||||
from freqtrade.wallets import Wallets
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class FreqtradeBot:
|
||||
class FreqtradeBot(LoggingMixin):
|
||||
"""
|
||||
Freqtrade is the main class of the bot.
|
||||
This is from here the bot start its logic.
|
||||
@@ -57,8 +60,8 @@ class FreqtradeBot:
|
||||
# Cache values for 1800 to avoid frequent polling of the exchange for prices
|
||||
# Caching only applies to RPC methods, so prices for open trades are still
|
||||
# refreshed once every iteration.
|
||||
self._sell_rate_cache = TTLCache(maxsize=100, ttl=1800)
|
||||
self._buy_rate_cache = TTLCache(maxsize=100, ttl=1800)
|
||||
self._sell_rate_cache: TTLCache = TTLCache(maxsize=100, ttl=1800)
|
||||
self._buy_rate_cache: TTLCache = TTLCache(maxsize=100, ttl=1800)
|
||||
|
||||
self.strategy: IStrategy = StrategyResolver.load_strategy(self.config)
|
||||
|
||||
@@ -67,14 +70,18 @@ class FreqtradeBot:
|
||||
|
||||
self.exchange = ExchangeResolver.load_exchange(self.config['exchange']['name'], self.config)
|
||||
|
||||
persistence.init(self.config.get('db_url', None), clean_open_orders=self.config['dry_run'])
|
||||
init_db(self.config.get('db_url', None), clean_open_orders=self.config['dry_run'])
|
||||
|
||||
self.wallets = Wallets(self.config, self.exchange)
|
||||
|
||||
PairLocks.timeframe = self.config['timeframe']
|
||||
|
||||
self.pairlists = PairListManager(self.exchange, self.config)
|
||||
|
||||
self.dataprovider = DataProvider(self.config, self.exchange, self.pairlists)
|
||||
|
||||
self.protections = ProtectionManager(self.config)
|
||||
|
||||
# Attach Dataprovider to Strategy baseclass
|
||||
IStrategy.dp = self.dataprovider
|
||||
# Attach Wallets to Strategy baseclass
|
||||
@@ -98,6 +105,7 @@ class FreqtradeBot:
|
||||
self.rpc: RPCManager = RPCManager(self)
|
||||
# Protect sell-logic from forcesell and viceversa
|
||||
self._sell_lock = Lock()
|
||||
LoggingMixin.__init__(self, logger, timeframe_to_seconds(self.strategy.timeframe))
|
||||
|
||||
def notify_status(self, msg: str) -> None:
|
||||
"""
|
||||
@@ -122,14 +130,14 @@ class FreqtradeBot:
|
||||
self.check_for_open_trades()
|
||||
|
||||
self.rpc.cleanup()
|
||||
persistence.cleanup()
|
||||
cleanup_db()
|
||||
|
||||
def startup(self) -> None:
|
||||
"""
|
||||
Called on startup and after reloading the bot - triggers notifications and
|
||||
performs startup tasks
|
||||
"""
|
||||
self.rpc.startup_messages(self.config, self.pairlists)
|
||||
self.rpc.startup_messages(self.config, self.pairlists, self.protections)
|
||||
if not self.edge:
|
||||
# Adjust stoploss if it was changed
|
||||
Trade.stoploss_reinitialization(self.strategy.stoploss)
|
||||
@@ -192,7 +200,7 @@ class FreqtradeBot:
|
||||
Notify the user when the bot is stopped
|
||||
and there are still open trades active.
|
||||
"""
|
||||
open_trades = Trade.get_trades([Trade.is_open == 1]).all()
|
||||
open_trades = Trade.get_trades([Trade.is_open.is_(True)]).all()
|
||||
|
||||
if len(open_trades) != 0:
|
||||
msg = {
|
||||
@@ -238,6 +246,10 @@ class FreqtradeBot:
|
||||
Updates open orders based on order list kept in the database.
|
||||
Mainly updates the state of orders - but may also close trades
|
||||
"""
|
||||
if self.config['dry_run']:
|
||||
# Updating open orders in dry-run does not make sense and will fail.
|
||||
return
|
||||
|
||||
orders = Order.get_open_orders()
|
||||
logger.info(f"Updating {len(orders)} open orders.")
|
||||
for order in orders:
|
||||
@@ -248,6 +260,7 @@ class FreqtradeBot:
|
||||
self.update_trade_state(order.trade, order.order_id, fo)
|
||||
|
||||
except ExchangeError as e:
|
||||
|
||||
logger.warning(f"Error updating Order {order.order_id} due to {e}")
|
||||
|
||||
def update_closed_trades_without_assigned_fees(self):
|
||||
@@ -255,6 +268,10 @@ class FreqtradeBot:
|
||||
Update closed trades without close fees assigned.
|
||||
Only acts when Orders are in the database, otherwise the last orderid is unknown.
|
||||
"""
|
||||
if self.config['dry_run']:
|
||||
# Updating open orders in dry-run does not make sense and will fail.
|
||||
return
|
||||
|
||||
trades: List[Trade] = Trade.get_sold_trades_without_assigned_fees()
|
||||
for trade in trades:
|
||||
|
||||
@@ -344,27 +361,35 @@ class FreqtradeBot:
|
||||
whitelist = copy.deepcopy(self.active_pair_whitelist)
|
||||
if not whitelist:
|
||||
logger.info("Active pair whitelist is empty.")
|
||||
else:
|
||||
# Remove pairs for currently opened trades from the whitelist
|
||||
for trade in Trade.get_open_trades():
|
||||
if trade.pair in whitelist:
|
||||
whitelist.remove(trade.pair)
|
||||
logger.debug('Ignoring %s in pair whitelist', trade.pair)
|
||||
return trades_created
|
||||
# Remove pairs for currently opened trades from the whitelist
|
||||
for trade in Trade.get_open_trades():
|
||||
if trade.pair in whitelist:
|
||||
whitelist.remove(trade.pair)
|
||||
logger.debug('Ignoring %s in pair whitelist', trade.pair)
|
||||
|
||||
if not whitelist:
|
||||
logger.info("No currency pair in active pair whitelist, "
|
||||
"but checking to sell open trades.")
|
||||
if not whitelist:
|
||||
logger.info("No currency pair in active pair whitelist, "
|
||||
"but checking to sell open trades.")
|
||||
return trades_created
|
||||
if PairLocks.is_global_lock():
|
||||
lock = PairLocks.get_pair_longest_lock('*')
|
||||
if lock:
|
||||
self.log_once(f"Global pairlock active until "
|
||||
f"{lock.lock_end_time.strftime(constants.DATETIME_PRINT_FORMAT)}. "
|
||||
"Not creating new trades.", logger.info)
|
||||
else:
|
||||
# Create entity and execute trade for each pair from whitelist
|
||||
for pair in whitelist:
|
||||
try:
|
||||
trades_created += self.create_trade(pair)
|
||||
except DependencyException as exception:
|
||||
logger.warning('Unable to create trade for %s: %s', pair, exception)
|
||||
self.log_once("Global pairlock active. Not creating new trades.", logger.info)
|
||||
return trades_created
|
||||
# Create entity and execute trade for each pair from whitelist
|
||||
for pair in whitelist:
|
||||
try:
|
||||
trades_created += self.create_trade(pair)
|
||||
except DependencyException as exception:
|
||||
logger.warning('Unable to create trade for %s: %s', pair, exception)
|
||||
|
||||
if not trades_created:
|
||||
logger.debug("Found no buy signals for whitelisted currencies. "
|
||||
"Trying again...")
|
||||
if not trades_created:
|
||||
logger.debug("Found no buy signals for whitelisted currencies. Trying again...")
|
||||
|
||||
return trades_created
|
||||
|
||||
@@ -516,8 +541,7 @@ class FreqtradeBot:
|
||||
# reserve some percent defined in config (5% default) + stoploss
|
||||
amount_reserve_percent = 1.0 - self.config.get('amount_reserve_percent',
|
||||
constants.DEFAULT_AMOUNT_RESERVE_PERCENT)
|
||||
if self.strategy.stoploss is not None:
|
||||
amount_reserve_percent += self.strategy.stoploss
|
||||
amount_reserve_percent += self.strategy.stoploss
|
||||
# it should not be more than 50%
|
||||
amount_reserve_percent = max(amount_reserve_percent, 0.5)
|
||||
|
||||
@@ -538,9 +562,15 @@ class FreqtradeBot:
|
||||
logger.debug(f"create_trade for pair {pair}")
|
||||
|
||||
analyzed_df, _ = self.dataprovider.get_analyzed_dataframe(pair, self.strategy.timeframe)
|
||||
if self.strategy.is_pair_locked(
|
||||
pair, analyzed_df.iloc[-1]['date'] if len(analyzed_df) > 0 else None):
|
||||
logger.info(f"Pair {pair} is currently locked.")
|
||||
nowtime = analyzed_df.iloc[-1]['date'] if len(analyzed_df) > 0 else None
|
||||
if self.strategy.is_pair_locked(pair, nowtime):
|
||||
lock = PairLocks.get_pair_longest_lock(pair, nowtime)
|
||||
if lock:
|
||||
self.log_once(f"Pair {pair} is still locked until "
|
||||
f"{lock.lock_end_time.strftime(constants.DATETIME_PRINT_FORMAT)}.",
|
||||
logger.info)
|
||||
else:
|
||||
self.log_once(f"Pair {pair} is still locked.", logger.info)
|
||||
return False
|
||||
|
||||
# get_free_open_trades is checked before create_trade is called
|
||||
@@ -613,6 +643,9 @@ class FreqtradeBot:
|
||||
# Calculate price
|
||||
buy_limit_requested = self.get_buy_rate(pair, True)
|
||||
|
||||
if not buy_limit_requested:
|
||||
raise PricingError('Could not determine buy price.')
|
||||
|
||||
min_stake_amount = self._get_min_pair_stake_amount(pair, buy_limit_requested)
|
||||
if min_stake_amount is not None and min_stake_amount > stake_amount:
|
||||
logger.warning(
|
||||
@@ -936,8 +969,8 @@ class FreqtradeBot:
|
||||
self.update_trade_state(trade, trade.stoploss_order_id, stoploss_order,
|
||||
stoploss_order=True)
|
||||
# Lock pair for one candle to prevent immediate rebuys
|
||||
self.strategy.lock_pair(trade.pair,
|
||||
timeframe_to_next_date(self.config['timeframe']))
|
||||
self.strategy.lock_pair(trade.pair, datetime.now(timezone.utc),
|
||||
reason='Auto lock')
|
||||
self._notify_sell(trade, "stoploss")
|
||||
return True
|
||||
|
||||
@@ -1263,7 +1296,8 @@ class FreqtradeBot:
|
||||
Trade.session.flush()
|
||||
|
||||
# Lock pair for one candle to prevent immediate rebuys
|
||||
self.strategy.lock_pair(trade.pair, timeframe_to_next_date(self.config['timeframe']))
|
||||
self.strategy.lock_pair(trade.pair, datetime.now(timezone.utc),
|
||||
reason='Auto lock')
|
||||
|
||||
self._notify_sell(trade, order_type)
|
||||
|
||||
@@ -1389,7 +1423,7 @@ class FreqtradeBot:
|
||||
abs_tol=constants.MATH_CLOSE_PREC):
|
||||
order['amount'] = new_amount
|
||||
order.pop('filled', None)
|
||||
trade.recalc_open_trade_price()
|
||||
trade.recalc_open_trade_value()
|
||||
except DependencyException as exception:
|
||||
logger.warning("Could not update trade amount: %s", exception)
|
||||
|
||||
@@ -1401,6 +1435,8 @@ class FreqtradeBot:
|
||||
|
||||
# Updating wallets when order is closed
|
||||
if not trade.is_open:
|
||||
self.protections.stop_per_pair(trade.pair)
|
||||
self.protections.global_stop()
|
||||
self.wallets.update()
|
||||
return False
|
||||
|
||||
@@ -1442,13 +1478,16 @@ class FreqtradeBot:
|
||||
fee_cost, fee_currency, fee_rate = self.exchange.extract_cost_curr_rate(order)
|
||||
logger.info(f"Fee for Trade {trade} [{order.get('side')}]: "
|
||||
f"{fee_cost:.8g} {fee_currency} - rate: {fee_rate}")
|
||||
|
||||
trade.update_fee(fee_cost, fee_currency, fee_rate, order.get('side', ''))
|
||||
if trade_base_currency == fee_currency:
|
||||
# Apply fee to amount
|
||||
return self.apply_fee_conditional(trade, trade_base_currency,
|
||||
amount=order_amount, fee_abs=fee_cost)
|
||||
return order_amount
|
||||
if fee_rate is None or fee_rate < 0.02:
|
||||
# Reject all fees that report as > 2%.
|
||||
# These are most likely caused by a parsing bug in ccxt
|
||||
# due to multiple trades (https://github.com/ccxt/ccxt/issues/8025)
|
||||
trade.update_fee(fee_cost, fee_currency, fee_rate, order.get('side', ''))
|
||||
if trade_base_currency == fee_currency:
|
||||
# Apply fee to amount
|
||||
return self.apply_fee_conditional(trade, trade_base_currency,
|
||||
amount=order_amount, fee_abs=fee_cost)
|
||||
return order_amount
|
||||
return self.fee_detection_from_trades(trade, order, order_amount)
|
||||
|
||||
def fee_detection_from_trades(self, trade: Trade, order: Dict, order_amount: float) -> float:
|
||||
|
@@ -1,12 +1,12 @@
|
||||
import logging
|
||||
import sys
|
||||
from logging import Formatter
|
||||
from logging.handlers import (BufferingHandler, RotatingFileHandler,
|
||||
SysLogHandler)
|
||||
from logging.handlers import BufferingHandler, RotatingFileHandler, SysLogHandler
|
||||
from typing import Any, Dict
|
||||
|
||||
from freqtrade.exceptions import OperationalException
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
LOGFORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
|
||||
@@ -37,6 +37,13 @@ def _set_loggers(verbosity: int = 0, api_verbosity: str = 'info') -> None:
|
||||
)
|
||||
|
||||
|
||||
def get_existing_handlers(handlertype):
|
||||
"""
|
||||
Returns Existing handler or None (if the handler has not yet been added to the root handlers).
|
||||
"""
|
||||
return next((h for h in logging.root.handlers if isinstance(h, handlertype)), None)
|
||||
|
||||
|
||||
def setup_logging_pre() -> None:
|
||||
"""
|
||||
Early setup for logging.
|
||||
@@ -71,18 +78,24 @@ def setup_logging(config: Dict[str, Any]) -> None:
|
||||
# config['logfilename']), which defaults to '/dev/log', applicable for most
|
||||
# of the systems.
|
||||
address = (s[1], int(s[2])) if len(s) > 2 else s[1] if len(s) > 1 else '/dev/log'
|
||||
handler = SysLogHandler(address=address)
|
||||
handler_sl = get_existing_handlers(SysLogHandler)
|
||||
if handler_sl:
|
||||
logging.root.removeHandler(handler_sl)
|
||||
handler_sl = SysLogHandler(address=address)
|
||||
# No datetime field for logging into syslog, to allow syslog
|
||||
# to perform reduction of repeating messages if this is set in the
|
||||
# syslog config. The messages should be equal for this.
|
||||
handler.setFormatter(Formatter('%(name)s - %(levelname)s - %(message)s'))
|
||||
logging.root.addHandler(handler)
|
||||
handler_sl.setFormatter(Formatter('%(name)s - %(levelname)s - %(message)s'))
|
||||
logging.root.addHandler(handler_sl)
|
||||
elif s[0] == 'journald':
|
||||
try:
|
||||
from systemd.journal import JournaldLogHandler
|
||||
except ImportError:
|
||||
raise OperationalException("You need the systemd python package be installed in "
|
||||
"order to use logging to journald.")
|
||||
handler_jd = get_existing_handlers(JournaldLogHandler)
|
||||
if handler_jd:
|
||||
logging.root.removeHandler(handler_jd)
|
||||
handler_jd = JournaldLogHandler()
|
||||
# No datetime field for logging into journald, to allow syslog
|
||||
# to perform reduction of repeating messages if this is set in the
|
||||
@@ -90,6 +103,9 @@ def setup_logging(config: Dict[str, Any]) -> None:
|
||||
handler_jd.setFormatter(Formatter('%(name)s - %(levelname)s - %(message)s'))
|
||||
logging.root.addHandler(handler_jd)
|
||||
else:
|
||||
handler_rf = get_existing_handlers(RotatingFileHandler)
|
||||
if handler_rf:
|
||||
logging.root.removeHandler(handler_rf)
|
||||
handler_rf = RotatingFileHandler(logfile,
|
||||
maxBytes=1024 * 1024 * 10, # 10Mb
|
||||
backupCount=10)
|
||||
|
@@ -7,9 +7,10 @@ import logging
|
||||
import sys
|
||||
from typing import Any, List
|
||||
|
||||
|
||||
# check min. python version
|
||||
if sys.version_info < (3, 6):
|
||||
sys.exit("Freqtrade requires Python version >= 3.6")
|
||||
if sys.version_info < (3, 7):
|
||||
sys.exit("Freqtrade requires Python version >= 3.7")
|
||||
|
||||
from freqtrade.commands import Arguments
|
||||
from freqtrade.exceptions import FreqtradeException, OperationalException
|
||||
|
@@ -12,6 +12,7 @@ from typing.io import IO
|
||||
import numpy as np
|
||||
import rapidjson
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -41,7 +42,7 @@ def datesarray_to_datetimearray(dates: np.ndarray) -> np.ndarray:
|
||||
return dates.dt.to_pydatetime()
|
||||
|
||||
|
||||
def file_dump_json(filename: Path, data: Any, is_zip: bool = False) -> None:
|
||||
def file_dump_json(filename: Path, data: Any, is_zip: bool = False, log: bool = True) -> None:
|
||||
"""
|
||||
Dump JSON data into a file
|
||||
:param filename: file to create
|
||||
@@ -52,12 +53,14 @@ def file_dump_json(filename: Path, data: Any, is_zip: bool = False) -> None:
|
||||
if is_zip:
|
||||
if filename.suffix != '.gz':
|
||||
filename = filename.with_suffix('.gz')
|
||||
logger.info(f'dumping json to "{filename}"')
|
||||
if log:
|
||||
logger.info(f'dumping json to "{filename}"')
|
||||
|
||||
with gzip.open(filename, 'w') as fp:
|
||||
rapidjson.dump(data, fp, default=str, number_mode=rapidjson.NM_NATIVE)
|
||||
with gzip.open(filename, 'w') as fpz:
|
||||
rapidjson.dump(data, fpz, default=str, number_mode=rapidjson.NM_NATIVE)
|
||||
else:
|
||||
logger.info(f'dumping json to "{filename}"')
|
||||
if log:
|
||||
logger.info(f'dumping json to "{filename}"')
|
||||
with open(filename, 'w') as fp:
|
||||
rapidjson.dump(data, fp, default=str, number_mode=rapidjson.NM_NATIVE)
|
||||
|
||||
|
2
freqtrade/mixins/__init__.py
Normal file
2
freqtrade/mixins/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
# flake8: noqa: F401
|
||||
from freqtrade.mixins.logging_mixin import LoggingMixin
|
38
freqtrade/mixins/logging_mixin.py
Normal file
38
freqtrade/mixins/logging_mixin.py
Normal file
@@ -0,0 +1,38 @@
|
||||
from typing import Callable
|
||||
|
||||
from cachetools import TTLCache, cached
|
||||
|
||||
|
||||
class LoggingMixin():
|
||||
"""
|
||||
Logging Mixin
|
||||
Shows similar messages only once every `refresh_period`.
|
||||
"""
|
||||
# Disable output completely
|
||||
show_output = True
|
||||
|
||||
def __init__(self, logger, refresh_period: int = 3600):
|
||||
"""
|
||||
:param refresh_period: in seconds - Show identical messages in this intervals
|
||||
"""
|
||||
self.logger = logger
|
||||
self.refresh_period = refresh_period
|
||||
self._log_cache: TTLCache = TTLCache(maxsize=1024, ttl=self.refresh_period)
|
||||
|
||||
def log_once(self, message: str, logmethod: Callable) -> None:
|
||||
"""
|
||||
Logs message - not more often than "refresh_period" to avoid log spamming
|
||||
Logs the log-message as debug as well to simplify debugging.
|
||||
:param message: String containing the message to be sent to the function.
|
||||
:param logmethod: Function that'll be called. Most likely `logger.info`.
|
||||
:return: None.
|
||||
"""
|
||||
@cached(cache=self._log_cache)
|
||||
def _log_once(message: str):
|
||||
logmethod(message)
|
||||
|
||||
# Log as debug first
|
||||
self.logger.debug(message)
|
||||
# Call hidden function.
|
||||
if self.show_output:
|
||||
_log_once(message)
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user