mirror of
https://github.com/freqtrade/freqtrade.git
synced 2025-11-29 08:33:07 +00:00
Compare commits
2387 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1593847203 | ||
|
|
7204227022 | ||
|
|
dab4ab78fc | ||
|
|
a74b941b72 | ||
|
|
89bba6f776 | ||
|
|
82f86569ee | ||
|
|
2a95d6855b | ||
|
|
3929ad4e1f | ||
|
|
2f1d9696cd | ||
|
|
0773a65333 | ||
|
|
8201f70a80 | ||
|
|
74b2f11d4f | ||
|
|
514e073c57 | ||
|
|
59e881c59d | ||
|
|
2e1e080022 | ||
|
|
470efd6f40 | ||
|
|
6640f4a1b2 | ||
|
|
e408274fb3 | ||
|
|
a135eaa993 | ||
|
|
87ff7be550 | ||
|
|
7441300270 | ||
|
|
b4f4fae0ca | ||
|
|
336808ec54 | ||
|
|
b26faa13bd | ||
|
|
562e4e63de | ||
|
|
ad5f7e1581 | ||
|
|
3cf95f9f6c | ||
|
|
f0710cafd0 | ||
|
|
73fa5bae96 | ||
|
|
a43d436f98 | ||
|
|
ff5ba64385 | ||
|
|
7e38a07490 | ||
|
|
8872158a6a | ||
|
|
db3e789294 | ||
|
|
4813ff338b | ||
|
|
fbd7dc1d6c | ||
|
|
f07b26f245 | ||
|
|
3acc10dd48 | ||
|
|
e5f06c201f | ||
|
|
bf20cde83d | ||
|
|
364859394b | ||
|
|
657f1b6c45 | ||
|
|
e350bcc2ef | ||
|
|
c2566f2436 | ||
|
|
cac314d4b3 | ||
|
|
b116cc75c4 | ||
|
|
bedbd964fc | ||
|
|
ca4d0067e4 | ||
|
|
8a0d90136c | ||
|
|
5b680f2ece | ||
|
|
1bc63288a3 | ||
|
|
45b2d24b79 | ||
|
|
10ca249293 | ||
|
|
d6b6ded8bd | ||
|
|
a52366c45d | ||
|
|
88c91a8a54 | ||
|
|
14755779de | ||
|
|
20dd3f2d67 | ||
|
|
8a31b4c646 | ||
|
|
78cd75dfef | ||
|
|
b805e4e150 | ||
|
|
6e938b59c8 | ||
|
|
4f17511fdc | ||
|
|
d8630ef847 | ||
|
|
47fabca1d9 | ||
|
|
c48876b196 | ||
|
|
16e10d99b9 | ||
|
|
0adcee9233 | ||
|
|
f41c659cb2 | ||
|
|
4c977b2e01 | ||
|
|
b152585d9b | ||
|
|
fd22c87295 | ||
|
|
93b213ae0b | ||
|
|
30eb23e1aa | ||
|
|
4ec83a2c24 | ||
|
|
9e23ca14d1 | ||
|
|
ebf5738a6e | ||
|
|
c649f9844e | ||
|
|
3208f30c30 | ||
|
|
5e731ec278 | ||
|
|
e55b2a1a1c | ||
|
|
ed8d805797 | ||
|
|
0ebf2e44be | ||
|
|
00a95945e1 | ||
|
|
9d739f98ac | ||
|
|
2588990f4b | ||
|
|
271846dfb6 | ||
|
|
c181fac6c7 | ||
|
|
0ac46eddca | ||
|
|
c735d35265 | ||
|
|
e957894852 | ||
|
|
369335b80c | ||
|
|
2ebddcf45c | ||
|
|
8564affdf0 | ||
|
|
a39d51d7d0 | ||
|
|
750dc8bf56 | ||
|
|
033742b708 | ||
|
|
84ba431d10 | ||
|
|
b6e26c82ea | ||
|
|
e8eb968a6f | ||
|
|
66605a1909 | ||
|
|
1e61263a28 | ||
|
|
bd08874f1f | ||
|
|
ff6a3465a7 | ||
|
|
5b58141f6b | ||
|
|
bf4e9a5dbb | ||
|
|
837d4d82b4 | ||
|
|
a8ffd29e18 | ||
|
|
92fda0f76c | ||
|
|
df62dd65d3 | ||
|
|
d72d388726 | ||
|
|
fda71085e0 | ||
|
|
1a765f1a17 | ||
|
|
06ab51b53d | ||
|
|
7de1631045 | ||
|
|
4c8411e835 | ||
|
|
f348956e4c | ||
|
|
a4dfd77d23 | ||
|
|
89e0c76a3f | ||
|
|
abc504412a | ||
|
|
36d5bb6f99 | ||
|
|
ad89d19955 | ||
|
|
e6e35c2584 | ||
|
|
ace70510f3 | ||
|
|
a320d4ccba | ||
|
|
790e6146f5 | ||
|
|
96bd5a6dc1 | ||
|
|
f5d8741832 | ||
|
|
effcc988c1 | ||
|
|
7ac3fbfdc9 | ||
|
|
4c4134a272 | ||
|
|
b2682bcbf5 | ||
|
|
4111734637 | ||
|
|
6e27c47dee | ||
|
|
18cc3539ca | ||
|
|
76ad5bea0e | ||
|
|
13e80e449c | ||
|
|
023eb19615 | ||
|
|
3e4617be37 | ||
|
|
ed9ec402fd | ||
|
|
56de81a1f9 | ||
|
|
ccb41d1ef9 | ||
|
|
2374cda8d0 | ||
|
|
1b7a09c184 | ||
|
|
37925e7f6c | ||
|
|
762ae3a598 | ||
|
|
9f8a2acf46 | ||
|
|
4fdec9d6e5 | ||
|
|
640d58eb13 | ||
|
|
fa8c61382b | ||
|
|
b6ac898f8f | ||
|
|
57bcff1964 | ||
|
|
939a87ed2e | ||
|
|
16d6914b15 | ||
|
|
05e473642b | ||
|
|
0d592f6c55 | ||
|
|
476adf872a | ||
|
|
9584629f50 | ||
|
|
c1c49183b5 | ||
|
|
8069cd6689 | ||
|
|
1f79ca9539 | ||
|
|
1d8fc97053 | ||
|
|
19f3669fbd | ||
|
|
06024b0ab0 | ||
|
|
6e952a0aa8 | ||
|
|
57dee794d1 | ||
|
|
2c0bb71a6e | ||
|
|
ab8f638e44 | ||
|
|
d250b67f33 | ||
|
|
42b8241541 | ||
|
|
6cc98c1ea9 | ||
|
|
77c367ad1d | ||
|
|
26b3148904 | ||
|
|
27dc9ca799 | ||
|
|
63e87ef85b | ||
|
|
6697b677dc | ||
|
|
baad1a5166 | ||
|
|
7cf7982565 | ||
|
|
f3f6e9d365 | ||
|
|
4228137dff | ||
|
|
3c8d27d098 | ||
|
|
4c1705fb1e | ||
|
|
31389b38f1 | ||
|
|
ff7a3cc885 | ||
|
|
4d1488498c | ||
|
|
10a22e7872 | ||
|
|
e72b6a440b | ||
|
|
b5ca4b7f35 | ||
|
|
c49f4b73dd | ||
|
|
80cbf08a58 | ||
|
|
5e23cc719d | ||
|
|
0680fe2a1a | ||
|
|
bba5f54722 | ||
|
|
85c4546333 | ||
|
|
23b5c0e833 | ||
|
|
cdd1bc425b | ||
|
|
2a9c06c40f | ||
|
|
434e0234c5 | ||
|
|
caf415dc97 | ||
|
|
e9337bf56e | ||
|
|
bcd02a871f | ||
|
|
e1c14bc86c | ||
|
|
69c23c00e0 | ||
|
|
1e19d7e463 | ||
|
|
5e0391aa2b | ||
|
|
2e91ee3849 | ||
|
|
9b32d617db | ||
|
|
2ec8376af9 | ||
|
|
86ef32318c | ||
|
|
4d062d41cb | ||
|
|
e78e42339d | ||
|
|
057ab1b7a6 | ||
|
|
613300c61d | ||
|
|
7d1f66ccf8 | ||
|
|
a7418449f9 | ||
|
|
d68e6f8362 | ||
|
|
c34ce15b14 | ||
|
|
1350d2cd1a | ||
|
|
9db2aca791 | ||
|
|
80d58b7930 | ||
|
|
568ecc201a | ||
|
|
cad7ed5570 | ||
|
|
57bb9281f6 | ||
|
|
5e53e9bcaa | ||
|
|
edfbb56749 | ||
|
|
652a04ac70 | ||
|
|
5e9ab3e261 | ||
|
|
be6fd3af9a | ||
|
|
e272cd485c | ||
|
|
f27528538d | ||
|
|
ad35a3d7ab | ||
|
|
211b9cbe04 | ||
|
|
946b8c29d7 | ||
|
|
33940ae66b | ||
|
|
d2589c4415 | ||
|
|
22733e44bf | ||
|
|
82d4051a39 | ||
|
|
0664a8c0e6 | ||
|
|
9b23376415 | ||
|
|
553a1b90ba | ||
|
|
7ea9da9605 | ||
|
|
9b98e608e6 | ||
|
|
885edc9768 | ||
|
|
e1b8485b51 | ||
|
|
764a35d035 | ||
|
|
e93bbd3831 | ||
|
|
8938c95e00 | ||
|
|
00ab6f572a | ||
|
|
73e9cbdea1 | ||
|
|
78381e9e7b | ||
|
|
75252b6251 | ||
|
|
f95b0ccdab | ||
|
|
38f184e50d | ||
|
|
1f4e5b17b7 | ||
|
|
9ee7e28ef8 | ||
|
|
3ac5b91899 | ||
|
|
4b29c4cdbf | ||
|
|
89729aefe8 | ||
|
|
15aae8a58c | ||
|
|
096c69dc4f | ||
|
|
2c0d2c1532 | ||
|
|
eca8ddabe9 | ||
|
|
c57d5ef1cd | ||
|
|
6bbc0eefed | ||
|
|
8c5b299449 | ||
|
|
9806699592 | ||
|
|
f2e878d9ec | ||
|
|
628c4c996a | ||
|
|
642d20b2f7 | ||
|
|
f6a88c6e9b | ||
|
|
d1fa5f307b | ||
|
|
cd0e813a85 | ||
|
|
dc47a391da | ||
|
|
9f94678478 | ||
|
|
04fea69a28 | ||
|
|
d6a8821596 | ||
|
|
7617dd5029 | ||
|
|
e9d9df3473 | ||
|
|
b6ee3d99b1 | ||
|
|
9a2bd83827 | ||
|
|
f359f869ab | ||
|
|
d6fba7c2f3 | ||
|
|
498bcf213f | ||
|
|
33efb7ace6 | ||
|
|
d74ca78bd8 | ||
|
|
3c91ba134f | ||
|
|
9a83d84109 | ||
|
|
8ae4018e4d | ||
|
|
739901b606 | ||
|
|
03b5be91f7 | ||
|
|
272c977d08 | ||
|
|
75446d8195 | ||
|
|
448b09d7b6 | ||
|
|
704fea616b | ||
|
|
23665c7731 | ||
|
|
4025ec9900 | ||
|
|
6a397f579e | ||
|
|
c31f118d0c | ||
|
|
2f005d6be9 | ||
|
|
45f5394d79 | ||
|
|
7e214d8e4c | ||
|
|
ed10048394 | ||
|
|
43f2ef226c | ||
|
|
42b5a0977e | ||
|
|
3b1252207d | ||
|
|
4ac53f1549 | ||
|
|
21b807aa85 | ||
|
|
28e0398c68 | ||
|
|
637ec60644 | ||
|
|
11bb7e520c | ||
|
|
6ba9316e15 | ||
|
|
60e3e626e4 | ||
|
|
9db915853a | ||
|
|
5237723f22 | ||
|
|
eb07f1fee9 | ||
|
|
8d92f8b362 | ||
|
|
49f0a72121 | ||
|
|
5978b7bb93 | ||
|
|
e09408f9b7 | ||
|
|
83e596c06f | ||
|
|
0268bfdbd4 | ||
|
|
b994f5c273 | ||
|
|
e9de088209 | ||
|
|
d05db077e2 | ||
|
|
d2f2473070 | ||
|
|
47b6b56566 | ||
|
|
27cc73f47e | ||
|
|
cc91ccad3e | ||
|
|
0102413f58 | ||
|
|
665e0570ae | ||
|
|
9391c27b80 | ||
|
|
a75fb3d4be | ||
|
|
2d86510acf | ||
|
|
5c3b14069e | ||
|
|
fe483ad011 | ||
|
|
0ce070acac | ||
|
|
6c0a1fc42c | ||
|
|
d066ab2620 | ||
|
|
3a5bd4c03e | ||
|
|
93b2621651 | ||
|
|
6aa1ec2a4c | ||
|
|
cc9fc41318 | ||
|
|
fe40636ae1 | ||
|
|
577b1fd965 | ||
|
|
0f97a999fb | ||
|
|
cb6e136893 | ||
|
|
5c3fb4d5b3 | ||
|
|
7c6921c743 | ||
|
|
22af7f7881 | ||
|
|
6ffb8b7a70 | ||
|
|
95e725c2b6 | ||
|
|
b18ad7a834 | ||
|
|
cfa76fa600 | ||
|
|
d226fff111 | ||
|
|
0c6164df7e | ||
|
|
d8bc350445 | ||
|
|
242ff26e21 | ||
|
|
ab0adabd39 | ||
|
|
ba4db0da49 | ||
|
|
7aa42f8868 | ||
|
|
3245ebccd4 | ||
|
|
359b0ba088 | ||
|
|
5234f8bf28 | ||
|
|
9a3bad291a | ||
|
|
b1a3e213ae | ||
|
|
2fcddfc866 | ||
|
|
313091eb1c | ||
|
|
508a35fc20 | ||
|
|
9cedbc1345 | ||
|
|
e66fa1cec6 | ||
|
|
1cd8ed0c1a | ||
|
|
74a0f44230 | ||
|
|
dc825c249c | ||
|
|
15a4df4c49 | ||
|
|
f0cf8d6a81 | ||
|
|
7fff1f5ce1 | ||
|
|
c625058f41 | ||
|
|
50b4563912 | ||
|
|
69f29e8907 | ||
|
|
ee6ad51a44 | ||
|
|
e8657d2444 | ||
|
|
a42000e1dd | ||
|
|
c3e19507bf | ||
|
|
27238d97d5 | ||
|
|
e9a75e57b8 | ||
|
|
5cbc073dd1 | ||
|
|
b7da02aab4 | ||
|
|
f3e3a8fcbe | ||
|
|
44fe0478ea | ||
|
|
9dc9bc2346 | ||
|
|
9c1cce6fe2 | ||
|
|
cab394a058 | ||
|
|
9d9ace2b22 | ||
|
|
c2462ee87b | ||
|
|
39f41def54 | ||
|
|
76e45883bd | ||
|
|
19ce7180be | ||
|
|
b00467c8ef | ||
|
|
2cf045c53e | ||
|
|
e2a100c925 | ||
|
|
eda1ec652f | ||
|
|
0135784589 | ||
|
|
5e654620b7 | ||
|
|
16b4ae8396 | ||
|
|
a5f3b68bff | ||
|
|
f163240710 | ||
|
|
c5f455d660 | ||
|
|
c8d191a5c9 | ||
|
|
e6ec8f9f30 | ||
|
|
4d566e8bad | ||
|
|
e6ccc1427c | ||
|
|
52b186eabe | ||
|
|
67ff48ce3e | ||
|
|
045ca8739d | ||
|
|
64b404068f | ||
|
|
dda513c923 | ||
|
|
6c5eff4a7c | ||
|
|
6884ad2211 | ||
|
|
9e4effaa14 | ||
|
|
849d694c27 | ||
|
|
1d781ea9e0 | ||
|
|
acf3b751f0 | ||
|
|
9bdfaf3803 | ||
|
|
f8eb1cd58a | ||
|
|
3b4bbe7a18 | ||
|
|
2bd59de002 | ||
|
|
ac413c65dc | ||
|
|
c01953daf2 | ||
|
|
a9ecdc7764 | ||
|
|
869a5b4901 | ||
|
|
2081d7552f | ||
|
|
e298e77319 | ||
|
|
35580b135a | ||
|
|
f987e6e0f9 | ||
|
|
85f1291597 | ||
|
|
5ea739f943 | ||
|
|
94d2790ab5 | ||
|
|
9aa7db103d | ||
|
|
3398f31b87 | ||
|
|
0e39cc1187 | ||
|
|
e8e05b6876 | ||
|
|
a218946f52 | ||
|
|
2a79c1eed2 | ||
|
|
7dc3e67bba | ||
|
|
3c869a8032 | ||
|
|
edba5a0014 | ||
|
|
b4a0591429 | ||
|
|
adbc0159ae | ||
|
|
a5510d14e9 | ||
|
|
9f5d4a5252 | ||
|
|
42d2ecba68 | ||
|
|
ceb1f91d9d | ||
|
|
3430850421 | ||
|
|
c5726e88e8 | ||
|
|
867a3273ce | ||
|
|
2a236db18f | ||
|
|
242ac4d8f4 | ||
|
|
3e0edc7ee2 | ||
|
|
0bb1127cb6 | ||
|
|
9d2c6c8de2 | ||
|
|
9513115ce0 | ||
|
|
f2cbc5fb8f | ||
|
|
26d76cdb19 | ||
|
|
65a516e229 | ||
|
|
edda122ed0 | ||
|
|
3044b861bd | ||
|
|
13932f55f5 | ||
|
|
3d028f512e | ||
|
|
bb2d8fefd7 | ||
|
|
623e8f6984 | ||
|
|
865e0d3af9 | ||
|
|
45cfdbbda7 | ||
|
|
2b00a5d90a | ||
|
|
bd2ecf8ce3 | ||
|
|
972b8a1726 | ||
|
|
fe631ffd04 | ||
|
|
bde82e9654 | ||
|
|
df481eb642 | ||
|
|
6ff83abb61 | ||
|
|
4fdf8a75cd | ||
|
|
2e49125e87 | ||
|
|
7e56704767 | ||
|
|
95b89e059a | ||
|
|
ef8386c065 | ||
|
|
7af445adf3 | ||
|
|
ee68f743c7 | ||
|
|
e39d911177 | ||
|
|
48ac37a1b8 | ||
|
|
e8f37666ea | ||
|
|
e2e0015119 | ||
|
|
3343b34725 | ||
|
|
e107290230 | ||
|
|
1b66f01ec0 | ||
|
|
f9c7a2cacb | ||
|
|
5ce63cd54a | ||
|
|
03f3d0dc8b | ||
|
|
74578b8752 | ||
|
|
caec5ac941 | ||
|
|
88f823f899 | ||
|
|
9a6a89c238 | ||
|
|
e8614abc5d | ||
|
|
87ae2430df | ||
|
|
dc9fda76f3 | ||
|
|
3b15cce07a | ||
|
|
8cad90f9e6 | ||
|
|
9c60ab796d | ||
|
|
05789c4b92 | ||
|
|
962d487edb | ||
|
|
04335ddd89 | ||
|
|
8b6010255f | ||
|
|
ccdc0ed26d | ||
|
|
3f6c0ba6d6 | ||
|
|
fe9d7b033e | ||
|
|
12e893ff2d | ||
|
|
cda2a2586b | ||
|
|
bf4e3f55f4 | ||
|
|
51ad05efdb | ||
|
|
89f5cf8291 | ||
|
|
949ab2a17c | ||
|
|
08b090c707 | ||
|
|
c64beb3f76 | ||
|
|
aae9c3194f | ||
|
|
20c9c93b3e | ||
|
|
771519e311 | ||
|
|
f91557f549 | ||
|
|
514860ac3b | ||
|
|
9d7ebc65e7 | ||
|
|
6aab3fe25a | ||
|
|
7c0a49a6f9 | ||
|
|
292df115e8 | ||
|
|
9f53e9f5dd | ||
|
|
ee808abfea | ||
|
|
ab3e3797a5 | ||
|
|
7fc156648a | ||
|
|
f0c0f5618b | ||
|
|
7c36e571d2 | ||
|
|
040ba5662c | ||
|
|
2886fa288a | ||
|
|
736deaae32 | ||
|
|
c9e15c2f86 | ||
|
|
d48f03c32e | ||
|
|
1760a8dfbc | ||
|
|
f278fcfc3f | ||
|
|
816d942ded | ||
|
|
423805c9ca | ||
|
|
a7e45c5a73 | ||
|
|
d060d27745 | ||
|
|
75dc174c76 | ||
|
|
d977695d48 | ||
|
|
b6b7dcd61c | ||
|
|
43ef831bf7 | ||
|
|
cabe291006 | ||
|
|
6b3d25b54b | ||
|
|
68adfc6607 | ||
|
|
ba0d7aa09c | ||
|
|
50b572a657 | ||
|
|
9634e516a9 | ||
|
|
c38f3a2b9a | ||
|
|
44780837f1 | ||
|
|
c6bb68bd30 | ||
|
|
8923c02222 | ||
|
|
b4685151ce | ||
|
|
756f44fcbd | ||
|
|
51fbeed71f | ||
|
|
d66fb86449 | ||
|
|
40df303122 | ||
|
|
a504abf00c | ||
|
|
d9c2b7d460 | ||
|
|
0e62b8bd85 | ||
|
|
6d1c54ed92 | ||
|
|
b5789203f2 | ||
|
|
92011f8294 | ||
|
|
b3db1ec1a7 | ||
|
|
5f60fcb602 | ||
|
|
30a7be457c | ||
|
|
93198ed28b | ||
|
|
6af5135802 | ||
|
|
6b233eb862 | ||
|
|
75e3d22043 | ||
|
|
e5da5f7fe7 | ||
|
|
4fcfb1eaca | ||
|
|
bfc68ec792 | ||
|
|
ae8c5eb75f | ||
|
|
513e84880e | ||
|
|
626b9bbf64 | ||
|
|
da7da2ce52 | ||
|
|
3232251fea | ||
|
|
e603cca7a5 | ||
|
|
8f8acf5b06 | ||
|
|
565a543b7b | ||
|
|
5e12b05424 | ||
|
|
a4c8b5bf5d | ||
|
|
cbf09b5ad9 | ||
|
|
2c66b33fd1 | ||
|
|
067c122bf3 | ||
|
|
defa1c027d | ||
|
|
ea179a8e38 | ||
|
|
8a17615b5a | ||
|
|
95920f3b6b | ||
|
|
365b9c3e9c | ||
|
|
3f6eeda3f0 | ||
|
|
3121206afe | ||
|
|
240936eb19 | ||
|
|
1336781f8f | ||
|
|
661cd65bdd | ||
|
|
fb498795ad | ||
|
|
2ae398913d | ||
|
|
d711b8c0e9 | ||
|
|
395414ccde | ||
|
|
9f29ad77bd | ||
|
|
545e5c5bc6 | ||
|
|
1b374fcf7e | ||
|
|
518d7dfde8 | ||
|
|
f8ddb10607 | ||
|
|
0ef13be577 | ||
|
|
c559f95703 | ||
|
|
f7cb75ff93 | ||
|
|
29076acc69 | ||
|
|
99b2be90fd | ||
|
|
f8c72feea8 | ||
|
|
69c2b12879 | ||
|
|
3820a38e79 | ||
|
|
60bc9f4f5e | ||
|
|
a8842f38ca | ||
|
|
667a623310 | ||
|
|
067208bc9d | ||
|
|
70ebd09de4 | ||
|
|
782f4112cd | ||
|
|
447bcf98e1 | ||
|
|
d19b11a00f | ||
|
|
ad6de07d2b | ||
|
|
0e81d7204c | ||
|
|
91b0394433 | ||
|
|
b2ef8f4e14 | ||
|
|
81925dfadf | ||
|
|
098159ad41 | ||
|
|
fe12d2e3b7 | ||
|
|
df1f57392c | ||
|
|
949ca1abf8 | ||
|
|
e52d5e32aa | ||
|
|
aaeeb9c0c6 | ||
|
|
d2958fc0f5 | ||
|
|
f8235aec74 | ||
|
|
13ffb39245 | ||
|
|
75b2db4424 | ||
|
|
14aaf8976f | ||
|
|
fcb0ff1b60 | ||
|
|
31669fde03 | ||
|
|
17b3f01b28 | ||
|
|
cadf573170 | ||
|
|
a12876da92 | ||
|
|
eebf39a1df | ||
|
|
210f66e48b | ||
|
|
91e72ba081 | ||
|
|
be308ff914 | ||
|
|
4ee35438a7 | ||
|
|
11dab2b9ca | ||
|
|
f02adf2a45 | ||
|
|
9e24992835 | ||
|
|
e9e2a83436 | ||
|
|
af51ff4162 | ||
|
|
e8ee087e9d | ||
|
|
8cc477f353 | ||
|
|
c63856dac4 | ||
|
|
8d1a575a9b | ||
|
|
9e8ca8d4bf | ||
|
|
491d742bf9 | ||
|
|
dc35a8022b | ||
|
|
70b1a05d97 | ||
|
|
785c3e9e61 | ||
|
|
9ad9ce0da1 | ||
|
|
042e47543c | ||
|
|
71d612f6e4 | ||
|
|
a4ede02ced | ||
|
|
ea4db0ffb6 | ||
|
|
d785d76370 | ||
|
|
b6462cd51f | ||
|
|
611850bf91 | ||
|
|
ddfadbb69e | ||
|
|
045ac1019e | ||
|
|
ee7ba96e85 | ||
|
|
8e96ac8765 | ||
|
|
acf1e734ec | ||
|
|
0a478bc0dc | ||
|
|
9005447590 | ||
|
|
d300964691 | ||
|
|
407a3bca62 | ||
|
|
310e438706 | ||
|
|
8a2a8ab8b5 | ||
|
|
5e440a4cdc | ||
|
|
3a1b641db1 | ||
|
|
2cffc3228a | ||
|
|
7fa6d804ce | ||
|
|
a398eea244 | ||
|
|
0e87cc8c84 | ||
|
|
764bab8eb9 | ||
|
|
351740fc80 | ||
|
|
9143ea13ad | ||
|
|
4711d66cab | ||
|
|
09967d4ff8 | ||
|
|
e0335705b2 | ||
|
|
4ce3cc66d5 | ||
|
|
fce3d7586f | ||
|
|
cda912bd8c | ||
|
|
84a0f9ea42 | ||
|
|
08fa5136e1 | ||
|
|
7a79b292e4 | ||
|
|
a53e9e3a98 | ||
|
|
f7d5280f47 | ||
|
|
29c56f4447 | ||
|
|
c9207bcc00 | ||
|
|
132f28ad44 | ||
|
|
b2c215029d | ||
|
|
89257832d7 | ||
|
|
219d0b7fb0 | ||
|
|
4e308a1a3e | ||
|
|
3c15e3ebdd | ||
|
|
8655e521d7 | ||
|
|
05deb9e09b | ||
|
|
91886120a7 | ||
|
|
09286d4918 | ||
|
|
161db08745 | ||
|
|
8aaaab4163 | ||
|
|
53db382695 | ||
|
|
1b6051e4df | ||
|
|
8d206f8308 | ||
|
|
b94f3e80c4 | ||
|
|
2a842778e3 | ||
|
|
e525275d10 | ||
|
|
4fa92ec0fa | ||
|
|
69eff89049 | ||
|
|
12677f2d42 | ||
|
|
a94a89086f | ||
|
|
80a71323cc | ||
|
|
fd77f699df | ||
|
|
93cf2cd19b | ||
|
|
585536835a | ||
|
|
f5e437d8c7 | ||
|
|
14c4854987 | ||
|
|
3af5691b91 | ||
|
|
9f26c4ebdc | ||
|
|
11790fbf01 | ||
|
|
f3e6bcb20c | ||
|
|
e0e50115d2 | ||
|
|
b2a22f1afb | ||
|
|
9d3322df8c | ||
|
|
91d1061c73 | ||
|
|
0ffb184eba | ||
|
|
5b9711c002 | ||
|
|
096a6426db | ||
|
|
84baef922c | ||
|
|
51c3a31bb5 | ||
|
|
06fa07e73e | ||
|
|
4da2bfefb7 | ||
|
|
3b30aab8a7 | ||
|
|
c2e9685e04 | ||
|
|
d6f5f6b7ba | ||
|
|
a4ab42560f | ||
|
|
a76136c010 | ||
|
|
e35a349229 | ||
|
|
3d36747b92 | ||
|
|
c0784b7c33 | ||
|
|
828315f675 | ||
|
|
4c4ba08e85 | ||
|
|
94196c84e9 | ||
|
|
9d476b5ab2 | ||
|
|
0a07dfc5cf | ||
|
|
d69f7ae471 | ||
|
|
974d899b33 | ||
|
|
6948e0ba84 | ||
|
|
a325f1ce2b | ||
|
|
997eb7574a | ||
|
|
8873e0072c | ||
|
|
c29389f5f3 | ||
|
|
4b8eaaf7aa | ||
|
|
8d813fa728 | ||
|
|
28e318b646 | ||
|
|
2961efdc18 | ||
|
|
3c589bb877 | ||
|
|
d8dbea9d5b | ||
|
|
f960ea039e | ||
|
|
de80234165 | ||
|
|
906be7be7c | ||
|
|
482847a994 | ||
|
|
58d308fd05 | ||
|
|
59acd5ec7c | ||
|
|
ca739f71fb | ||
|
|
23a70932d2 | ||
|
|
1a34b9b61c | ||
|
|
8f92912852 | ||
|
|
2600cb7b64 | ||
|
|
200b6ea10f | ||
|
|
8c1efec43a | ||
|
|
dd30d74688 | ||
|
|
6f42d6658f | ||
|
|
c4cdd85e80 | ||
|
|
0bd71db5df | ||
|
|
feced71a6d | ||
|
|
444ee274d7 | ||
|
|
bb0b160001 | ||
|
|
241d510096 | ||
|
|
c042d08bb7 | ||
|
|
1ce63b5b42 | ||
|
|
dd0ba183f8 | ||
|
|
933a553dd4 | ||
|
|
af67bbde31 | ||
|
|
6310b40fc6 | ||
|
|
2463a4af2a | ||
|
|
51ad8f5ab4 | ||
|
|
615ce6aa69 | ||
|
|
43b41324e2 | ||
|
|
91b0db138a | ||
|
|
197ce0b670 | ||
|
|
002003292e | ||
|
|
0b367a14f1 | ||
|
|
e5dcd520ba | ||
|
|
90b75afdb1 | ||
|
|
2d60e4b18b | ||
|
|
c5d8499ad2 | ||
|
|
b77c0d2813 | ||
|
|
a636dda07d | ||
|
|
dc5719e1f4 | ||
|
|
d53f63023a | ||
|
|
0221607318 | ||
|
|
a1b5c7242e | ||
|
|
a225672c87 | ||
|
|
4b4fcc7034 | ||
|
|
85094a59e6 | ||
|
|
e02e64fc07 | ||
|
|
176beefa88 | ||
|
|
1a85e3b4cd | ||
|
|
5209ce5bfa | ||
|
|
2c5a499a8b | ||
|
|
6d89da45b0 | ||
|
|
eb328037b7 | ||
|
|
afba31c3f9 | ||
|
|
c4cbe79b48 | ||
|
|
8ba7657007 | ||
|
|
48d8376878 | ||
|
|
74e583a612 | ||
|
|
29619ccf1c | ||
|
|
ab092fc77f | ||
|
|
28d8fc871a | ||
|
|
ad6a249832 | ||
|
|
50c9679e23 | ||
|
|
8eb39178ea | ||
|
|
dd35ba5e81 | ||
|
|
3cc772c8e9 | ||
|
|
247d7475e1 | ||
|
|
51d59e673b | ||
|
|
ae39f6fba5 | ||
|
|
15cf5ac2d7 | ||
|
|
de99942499 | ||
|
|
ccf3c69874 | ||
|
|
8ad5afd3a1 | ||
|
|
0d4a2c6c3a | ||
|
|
02b2de5c73 | ||
|
|
2bc67b4a96 | ||
|
|
9df1c23c71 | ||
|
|
7a47d81b7b | ||
|
|
831e708897 | ||
|
|
757538f114 | ||
|
|
cc4900f66c | ||
|
|
7d02580a2b | ||
|
|
3d3b0938e5 | ||
|
|
9c5773ca0a | ||
|
|
092776442b | ||
|
|
0267976044 | ||
|
|
5864968ce9 | ||
|
|
33bc8a2404 | ||
|
|
dfce202034 | ||
|
|
ea46bb3b84 | ||
|
|
8418dfbaed | ||
|
|
caf4580346 | ||
|
|
a90ced1f38 | ||
|
|
6c0c77b3a1 | ||
|
|
16d4a4723f | ||
|
|
327e653fae | ||
|
|
81f773054d | ||
|
|
7e91a0f4a8 | ||
|
|
9d471f3c9a | ||
|
|
7e46a9833b | ||
|
|
988a0245c2 | ||
|
|
0376630f7a | ||
|
|
c7d0329754 | ||
|
|
bc2e920ae2 | ||
|
|
3721610a63 | ||
|
|
e060516cc7 | ||
|
|
20abd4b833 | ||
|
|
904381058c | ||
|
|
5e64d629a3 | ||
|
|
d71102c45a | ||
|
|
403f7668d5 | ||
|
|
930c25f7f1 | ||
|
|
187d029d20 | ||
|
|
9914198a6c | ||
|
|
c6444a10a8 | ||
|
|
383b24ab84 | ||
|
|
9cbab35de0 | ||
|
|
eeecdd4e5a | ||
|
|
2af663dccb | ||
|
|
0be7e2ef70 | ||
|
|
4d1ce8178c | ||
|
|
c5ccf44750 | ||
|
|
e4380b533b | ||
|
|
62262d0bb5 | ||
|
|
52d92cba90 | ||
|
|
0df5932593 | ||
|
|
d1838dceec | ||
|
|
c6bd143785 | ||
|
|
d51fd1a5d0 | ||
|
|
c4e30862ee | ||
|
|
3dd6fe2703 | ||
|
|
fe796c46c3 | ||
|
|
f200f52a16 | ||
|
|
d59608f764 | ||
|
|
b3e6e710d8 | ||
|
|
8ab07e0451 | ||
|
|
ad55faafa8 | ||
|
|
bbd58e772e | ||
|
|
e8b2ae0b85 | ||
|
|
13620df717 | ||
|
|
fb103dd162 | ||
|
|
3b65c986ee | ||
|
|
cad7d9135a | ||
|
|
b152d1a7ab | ||
|
|
aa8f44f68c | ||
|
|
1810d86555 | ||
|
|
39e8e507d9 | ||
|
|
3eb571f34c | ||
|
|
e8be357624 | ||
|
|
32605fa10a | ||
|
|
0b9b5f3993 | ||
|
|
86aa18efe6 | ||
|
|
76d22bc743 | ||
|
|
01cd30984b | ||
|
|
fceb411154 | ||
|
|
0413598d7b | ||
|
|
3ccfe88ad8 | ||
|
|
065ebd39ef | ||
|
|
bcccdda7c0 | ||
|
|
4c005e7086 | ||
|
|
2a141af42e | ||
|
|
472690a55f | ||
|
|
8cef567abc | ||
|
|
5d22d541f2 | ||
|
|
c3d14ab9b9 | ||
|
|
0488525888 | ||
|
|
b8713a515e | ||
|
|
b976f24672 | ||
|
|
8f1f416a52 | ||
|
|
0d9d23a888 | ||
|
|
a5fb3e08f7 | ||
|
|
59caff8fb1 | ||
|
|
f825e81d0e | ||
|
|
7bea0007c7 | ||
|
|
8dd8addd3a | ||
|
|
e14dd4974f | ||
|
|
7a97995d81 | ||
|
|
e64509f1b4 | ||
|
|
0ac5440fc2 | ||
|
|
fde3411c8b | ||
|
|
8066aba6fe | ||
|
|
5ba0aa8082 | ||
|
|
3e95b7d8a5 | ||
|
|
0f632201e0 | ||
|
|
ebca1e4357 | ||
|
|
a3620c60ad | ||
|
|
9f70ebecf1 | ||
|
|
0fd91e4450 | ||
|
|
fe088dc8c3 | ||
|
|
5a6e20a6aa | ||
|
|
02bfe2dad3 | ||
|
|
50edd4cfdd | ||
|
|
03e60b9ea4 | ||
|
|
0677472c56 | ||
|
|
c1bc1e3137 | ||
|
|
b691fb7f2d | ||
|
|
73ac98da80 | ||
|
|
14b43b504b | ||
|
|
a3c605f147 | ||
|
|
333413d298 | ||
|
|
9de8d7276e | ||
|
|
432b106d58 | ||
|
|
2c7a248307 | ||
|
|
113947132c | ||
|
|
0a253d66d0 | ||
|
|
ae0e001187 | ||
|
|
eab82fdec7 | ||
|
|
da755d1c83 | ||
|
|
1b2581f0cb | ||
|
|
56c8bdbaa2 | ||
|
|
23435512c4 | ||
|
|
6c3a0eb1d6 | ||
|
|
c85cd13ca1 | ||
|
|
e4b994381b | ||
|
|
de2a2473f5 | ||
|
|
e6b036b413 | ||
|
|
08a3d26328 | ||
|
|
bc299067aa | ||
|
|
908a0277e5 | ||
|
|
c2deb1db25 | ||
|
|
16716ad028 | ||
|
|
fef8fe8525 | ||
|
|
3d5268368f | ||
|
|
20b51da180 | ||
|
|
785a7a22bc | ||
|
|
1ac4a7e116 | ||
|
|
327e505273 | ||
|
|
bf1c197a37 | ||
|
|
3c3a902a69 | ||
|
|
0c14176cd7 | ||
|
|
7ee971c3e3 | ||
|
|
098a23adc6 | ||
|
|
10c69387fd | ||
|
|
4b8b2f7c5b | ||
|
|
e1b8ff798f | ||
|
|
05b1854946 | ||
|
|
f58668fd67 | ||
|
|
e8843c31e6 | ||
|
|
05be16e9e1 | ||
|
|
e9b77298a7 | ||
|
|
a0cecc6c52 | ||
|
|
cf6113068c | ||
|
|
0c2c094db6 | ||
|
|
60cf56e235 | ||
|
|
482f5f7a26 | ||
|
|
04382d4b44 | ||
|
|
44b2261c34 | ||
|
|
76b9d781ee | ||
|
|
bd0faaf702 | ||
|
|
e0cd34c9e1 | ||
|
|
6c41ca4b8c | ||
|
|
7add015a75 | ||
|
|
d6b6e59ab8 | ||
|
|
a213674a98 | ||
|
|
41f24898e5 | ||
|
|
d2ad32eef8 | ||
|
|
1fea6d394a | ||
|
|
dcddfce5bc | ||
|
|
e6528be63d | ||
|
|
08ca260e82 | ||
|
|
88eb93da52 | ||
|
|
b35efd96dc | ||
|
|
89db5c6bab | ||
|
|
790838d897 | ||
|
|
4d0cf9ec8e | ||
|
|
299f673a8e | ||
|
|
fa8904978b | ||
|
|
4a144d1c18 | ||
|
|
415c96204a | ||
|
|
7af24dc486 | ||
|
|
e01c0ab4d6 | ||
|
|
8b4827ad85 | ||
|
|
43d5ec2d4a | ||
|
|
75a0998ed2 | ||
|
|
fbd229810f | ||
|
|
d27e791f32 | ||
|
|
50d2950e6b | ||
|
|
96564d0dad | ||
|
|
3e5abd18ca | ||
|
|
545ff6f9f1 | ||
|
|
49b95fe008 | ||
|
|
b8704e12b7 | ||
|
|
639a4d5cf7 | ||
|
|
0e500de1a0 | ||
|
|
c5b244419d | ||
|
|
8ccfc0f316 | ||
|
|
e126c55a5a | ||
|
|
be26ba8f8f | ||
|
|
1493771087 | ||
|
|
192d7ad735 | ||
|
|
12679da5da | ||
|
|
ec49b22af3 | ||
|
|
d23179e25c | ||
|
|
7d62bb8c53 | ||
|
|
c4e55d78d5 | ||
|
|
07a1c48e8c | ||
|
|
7be25313a5 | ||
|
|
55e8092cbf | ||
|
|
e5170582de | ||
|
|
710443d200 | ||
|
|
2a20423be6 | ||
|
|
8096a1fb04 | ||
|
|
2fedae6060 | ||
|
|
b1b4048f97 | ||
|
|
107f00ff8f | ||
|
|
5144e98a82 | ||
|
|
210d70b0c7 | ||
|
|
3ae94520c3 | ||
|
|
cbe25178d7 | ||
|
|
a3b7e1f774 | ||
|
|
bbab5fef0c | ||
|
|
007703156b | ||
|
|
9cae2900d4 | ||
|
|
876cae2807 | ||
|
|
e955b1ae09 | ||
|
|
dadf8adb3e | ||
|
|
4238ee090d | ||
|
|
65f77306d3 | ||
|
|
efbc7cccb1 | ||
|
|
f0206a90b1 | ||
|
|
a8f3f2bc1a | ||
|
|
25822d1717 | ||
|
|
9887cb997e | ||
|
|
7e2be96516 | ||
|
|
2e1269c474 | ||
|
|
b499e74502 | ||
|
|
7536f6adbd | ||
|
|
4be02bc207 | ||
|
|
bbfbd87a9f | ||
|
|
7e103e34f8 | ||
|
|
94e6fb89b3 | ||
|
|
1bdffcc73b | ||
|
|
e993e010f4 | ||
|
|
bc1b5f477d | ||
|
|
6a43128019 | ||
|
|
c474e2ac86 | ||
|
|
7763b4cf5b | ||
|
|
322227bf67 | ||
|
|
27cb1a4174 | ||
|
|
c4fb0fd6ca | ||
|
|
87ff1e8cb0 | ||
|
|
61b24180f0 | ||
|
|
15d2cbd6df | ||
|
|
f7a2428deb | ||
|
|
6c2415d32f | ||
|
|
84d3868994 | ||
|
|
f89b2a18e0 | ||
|
|
8114d790a5 | ||
|
|
082065cd50 | ||
|
|
a65b5f8e02 | ||
|
|
d8f133aaf3 | ||
|
|
8e272e5774 | ||
|
|
ce2a5b2838 | ||
|
|
bcf2bc6f8c | ||
|
|
17800c8ca5 | ||
|
|
5c6039fd8b | ||
|
|
40fe2d2c16 | ||
|
|
1bcf2737fe | ||
|
|
fcdbe846e5 | ||
|
|
d055dc0c6e | ||
|
|
e19c192570 | ||
|
|
b80cef964e | ||
|
|
b43594e4eb | ||
|
|
0908863e07 | ||
|
|
b3644f7fa0 | ||
|
|
d41b8cc96e | ||
|
|
91fb9d0113 | ||
|
|
85ac217abc | ||
|
|
687381f42c | ||
|
|
c91add203d | ||
|
|
1e4f459a26 | ||
|
|
06ad04e5fa | ||
|
|
80bf5c9756 | ||
|
|
0d601fd111 | ||
|
|
01904d3c1e | ||
|
|
0c7d14fe50 | ||
|
|
cdeb649d0b | ||
|
|
79ae3c2f2e | ||
|
|
59818af69c | ||
|
|
44e0500958 | ||
|
|
db59d39e2c | ||
|
|
587d71efb5 | ||
|
|
c7a4a16eec | ||
|
|
0b517584aa | ||
|
|
5a11ffcad8 | ||
|
|
0a184d380e | ||
|
|
6b387d320e | ||
|
|
348513c151 | ||
|
|
0d5e94b147 | ||
|
|
88545d882c | ||
|
|
42ea0a19d2 | ||
|
|
c87d27048b | ||
|
|
700bab7279 | ||
|
|
c3db4ebbc3 | ||
|
|
8aa327cb8a | ||
|
|
4218d569de | ||
|
|
e50eee59cf | ||
|
|
4506832925 | ||
|
|
a0cdc63a5d | ||
|
|
79b4e2dc85 | ||
|
|
edd3fc8825 | ||
|
|
e8796e009c | ||
|
|
044be3b93e | ||
|
|
0436811cf0 | ||
|
|
152e138c17 | ||
|
|
4f5e212f87 | ||
|
|
21bf01a24c | ||
|
|
16a9e6b72f | ||
|
|
700bc087d3 | ||
|
|
8b99348e98 | ||
|
|
045f34e851 | ||
|
|
e5a8030dd7 | ||
|
|
6643b83afe | ||
|
|
98681b78b4 | ||
|
|
f8dd0b0cb3 | ||
|
|
f04d49886b | ||
|
|
3043a8d9c9 | ||
|
|
4459fdf1b1 | ||
|
|
086d690df7 | ||
|
|
05d93cda16 | ||
|
|
6fc6eaf742 | ||
|
|
596cee2dc1 | ||
|
|
1d5c3f34ae | ||
|
|
ca7080c2bb | ||
|
|
21f6493b02 | ||
|
|
a89112a133 | ||
|
|
353437bbd1 | ||
|
|
8e92fc62a3 | ||
|
|
c106534663 | ||
|
|
b92c6cdf35 | ||
|
|
ca5093901b | ||
|
|
ba7a0dde06 | ||
|
|
27798c1683 | ||
|
|
ee312ac230 | ||
|
|
7e82be53cd | ||
|
|
7017e46ba1 | ||
|
|
7166674d6c | ||
|
|
e1daf02735 | ||
|
|
56e6294873 | ||
|
|
1b15e5dd64 | ||
|
|
31a2aac627 | ||
|
|
158569f5e8 | ||
|
|
e83f8941a1 | ||
|
|
d6dbb21a34 | ||
|
|
90ada0649c | ||
|
|
e8429bd230 | ||
|
|
5a30f0462f | ||
|
|
11d39bb0d3 | ||
|
|
a517779dd7 | ||
|
|
eba7327058 | ||
|
|
1b156e0f34 | ||
|
|
c1ee5d69c9 | ||
|
|
1f8dc7f845 | ||
|
|
a07653a6cc | ||
|
|
c9a76be532 | ||
|
|
9d2b6db97b | ||
|
|
12d2db5e7b | ||
|
|
1add8ecd0c | ||
|
|
f23a8a8cd1 | ||
|
|
116d8e853e | ||
|
|
5b84cb39ac | ||
|
|
7f018839f8 | ||
|
|
3716c04ed4 | ||
|
|
7fbdf36c64 | ||
|
|
da5f77c96f | ||
|
|
451d4a400e | ||
|
|
4cbcb5f36f | ||
|
|
026784efac | ||
|
|
cc56d0e0fc | ||
|
|
559d5ebd1d | ||
|
|
3e61ada34a | ||
|
|
8758218b09 | ||
|
|
de38aea164 | ||
|
|
d8286d7a98 | ||
|
|
101ad71be1 | ||
|
|
db17b20e26 | ||
|
|
a581ca66bf | ||
|
|
5d6819bb28 | ||
|
|
7a0d86660e | ||
|
|
1a27ae8a81 | ||
|
|
f907a487c8 | ||
|
|
a75f08cf17 | ||
|
|
89ba649ddb | ||
|
|
63640518da | ||
|
|
a8dcfc05c5 | ||
|
|
dd379c4192 | ||
|
|
911e71cd9b | ||
|
|
b8fb38b92c | ||
|
|
144e053a4e | ||
|
|
a8efb1e1c8 | ||
|
|
0866b5f29f | ||
|
|
38712f8120 | ||
|
|
860e056366 | ||
|
|
c6fed4e493 | ||
|
|
8c40a406b6 | ||
|
|
6f950bbd66 | ||
|
|
aa2cce020e | ||
|
|
0e7ea1dada | ||
|
|
6973087d5b | ||
|
|
25755f6adf | ||
|
|
0d360167f3 | ||
|
|
ba4890d303 | ||
|
|
7cd36239a4 | ||
|
|
06afb3f155 | ||
|
|
557122921a | ||
|
|
475e76b272 | ||
|
|
b0c5286e8a | ||
|
|
bffa9fbfbd | ||
|
|
d217f32bbc | ||
|
|
195bf5a4cc | ||
|
|
813c008af2 | ||
|
|
765eff23f0 | ||
|
|
0eb109f8f7 | ||
|
|
fc3e3c468c | ||
|
|
4b7dfc64c6 | ||
|
|
488bb971ff | ||
|
|
907c2f1e6b | ||
|
|
3f04930f38 | ||
|
|
0300128cb8 | ||
|
|
bf2c0390e7 | ||
|
|
1cd8415723 | ||
|
|
1c53aa5687 | ||
|
|
c7643e142b | ||
|
|
9f5ca82f48 | ||
|
|
6db4e05aef | ||
|
|
2891d7cccb | ||
|
|
cae2185460 | ||
|
|
6347161975 | ||
|
|
b1a01345f9 | ||
|
|
e0a1e5417f | ||
|
|
6df0b39f81 | ||
|
|
68af6d4151 | ||
|
|
583d70ec9c | ||
|
|
2369161bb0 | ||
|
|
9035e0b695 | ||
|
|
4ef309bc6c | ||
|
|
114de8a025 | ||
|
|
442339cd27 | ||
|
|
e6cab6d710 | ||
|
|
472e7f80a0 | ||
|
|
2a682f858e | ||
|
|
c43edf98d4 | ||
|
|
a0415aea83 | ||
|
|
4a916125a0 | ||
|
|
89ff614e1d | ||
|
|
55079831a1 | ||
|
|
d047a9d836 | ||
|
|
cd4cf215e1 | ||
|
|
01b5ece642 | ||
|
|
36dd061be7 | ||
|
|
a77d75eb43 | ||
|
|
707118a636 | ||
|
|
ad9dc349e4 | ||
|
|
09cd7db9b1 | ||
|
|
1af988711b | ||
|
|
cedd38455f | ||
|
|
2965931a78 | ||
|
|
1afe6c1437 | ||
|
|
3240d4e70e | ||
|
|
941fb4ebbb | ||
|
|
ee113ab8ed | ||
|
|
24f86e9ff3 | ||
|
|
04ea66c977 | ||
|
|
9657b1a17f | ||
|
|
e08fda074a | ||
|
|
550fbad53e | ||
|
|
160894c031 | ||
|
|
578180f45b | ||
|
|
b64b6a2583 | ||
|
|
a4d8424268 | ||
|
|
a65c89f090 | ||
|
|
0cc2210f22 | ||
|
|
8df40a6ff9 | ||
|
|
9c64965808 | ||
|
|
0d8b572a17 | ||
|
|
1f3406b29b | ||
|
|
dc7f883751 | ||
|
|
db6ccef6bd | ||
|
|
676e730013 | ||
|
|
08105641d9 | ||
|
|
7322a34fa4 | ||
|
|
4801af4c77 | ||
|
|
d55f2be942 | ||
|
|
cd60d6d99a | ||
|
|
dc0326db27 | ||
|
|
50c7a2445b | ||
|
|
6636f0c71b | ||
|
|
1a41d4e6cd | ||
|
|
9961c0e15b | ||
|
|
5c5b0effc1 | ||
|
|
4dc3a0ca1d | ||
|
|
99cceeea70 | ||
|
|
839734a988 | ||
|
|
90b0f1daa8 | ||
|
|
792390e815 | ||
|
|
9f2e0b11d1 | ||
|
|
3380543878 | ||
|
|
ce317b62f9 | ||
|
|
6ad94684d5 | ||
|
|
fdbbefdddd | ||
|
|
3fe5388d4c | ||
|
|
7108a2e57d | ||
|
|
9c497bf15c | ||
|
|
d7c63347e1 | ||
|
|
adc12ed043 | ||
|
|
9ea887dbd0 | ||
|
|
9967df8f45 | ||
|
|
71b7b2482f | ||
|
|
5273540a93 | ||
|
|
f9fe266364 | ||
|
|
a9ed5da369 | ||
|
|
2e6ded06a9 | ||
|
|
7134273918 | ||
|
|
f75e97e9b0 | ||
|
|
a132517f0a | ||
|
|
3c1ae07f92 | ||
|
|
4ef8a74977 | ||
|
|
51113dae0e | ||
|
|
c04a8a1024 | ||
|
|
bd8edd61fd | ||
|
|
92113ce1c9 | ||
|
|
107c3beb20 | ||
|
|
4e45aa1564 | ||
|
|
e0e5cfa266 | ||
|
|
36dae7cc6c | ||
|
|
c68fe7a685 | ||
|
|
199426460a | ||
|
|
338f2a2322 | ||
|
|
f04089ef1e | ||
|
|
1add432673 | ||
|
|
f15f03428e | ||
|
|
e4e22167bb | ||
|
|
6b144150c7 | ||
|
|
ef15f2bdc6 | ||
|
|
39932627bd | ||
|
|
11f535e79f | ||
|
|
f463817c88 | ||
|
|
b6e8fecbf5 | ||
|
|
d6cf314481 | ||
|
|
fb88953be3 | ||
|
|
15984b5c43 | ||
|
|
c2f6897d8b | ||
|
|
28c796a234 | ||
|
|
d7bebc4385 | ||
|
|
7b367818fc | ||
|
|
9e4dd6f37f | ||
|
|
22144d89fc | ||
|
|
c5ef700eb7 | ||
|
|
17d614c66a | ||
|
|
7406edfd8f | ||
|
|
6451feee0e | ||
|
|
912b06b34b | ||
|
|
9fab7e6122 | ||
|
|
ea83b2b1d0 | ||
|
|
f6a88d71c6 | ||
|
|
4fed263885 | ||
|
|
db2e6f2d1c | ||
|
|
58477dcd82 | ||
|
|
536c8fa454 | ||
|
|
55bdd26439 | ||
|
|
89f44c10a1 | ||
|
|
8b028068bb | ||
|
|
f7766d305b | ||
|
|
1b7ee7cf5a | ||
|
|
09e037c96e | ||
|
|
bfb6dc4a8e | ||
|
|
196a1bcc26 | ||
|
|
73f1d9bb66 | ||
|
|
1988662607 | ||
|
|
3e2c808b4b | ||
|
|
dab4307e04 | ||
|
|
dd03e0acc6 | ||
|
|
e335e6c480 | ||
|
|
0e228acbfb | ||
|
|
201e02e73f | ||
|
|
71447e55aa | ||
|
|
8ad30e2625 | ||
|
|
104f1212e6 | ||
|
|
65a4862d1f | ||
|
|
236c392d28 | ||
|
|
b38c43141c | ||
|
|
9225cdea8a | ||
|
|
26a8cdcc03 | ||
|
|
3e0a71f69f | ||
|
|
4394701de3 | ||
|
|
b6484cb2b4 | ||
|
|
90ece09ee9 | ||
|
|
febcc3dddc | ||
|
|
2da7145132 | ||
|
|
6adc8f7ea7 | ||
|
|
5bbd3c6158 | ||
|
|
1fab884a2f | ||
|
|
04c35b465e | ||
|
|
7e952b028a | ||
|
|
b7686d06a7 | ||
|
|
c30c4ef266 | ||
|
|
469c0b6a55 | ||
|
|
c3e93e7593 | ||
|
|
7bbe8b2483 | ||
|
|
7b968a2401 | ||
|
|
253025c0fe | ||
|
|
7b074765ab | ||
|
|
1a5dbd29e0 | ||
|
|
b87b3dc38a | ||
|
|
6e1da13920 | ||
|
|
406e266bb4 | ||
|
|
2c9a519c5e | ||
|
|
98eeec3145 | ||
|
|
7cb753754b | ||
|
|
11dce91281 | ||
|
|
51aa469f67 | ||
|
|
58ced36445 | ||
|
|
11fd8a59af | ||
|
|
a39cdd3b2b | ||
|
|
53af8f331d | ||
|
|
9f54181494 | ||
|
|
6a5daab520 | ||
|
|
349c0619aa | ||
|
|
6dc2175e1f | ||
|
|
96a34f753b | ||
|
|
04e13eed7d | ||
|
|
5b24ac7898 | ||
|
|
34c7ac8926 | ||
|
|
3404bb1865 | ||
|
|
de95e50804 | ||
|
|
703fdb2bc6 | ||
|
|
5d93946365 | ||
|
|
e7b9bc6808 | ||
|
|
46b347b661 | ||
|
|
fc96da869a | ||
|
|
f93e6ad0f6 | ||
|
|
8d8b4a69b7 | ||
|
|
2cf07e2185 | ||
|
|
e6ae890def | ||
|
|
79cac36b34 | ||
|
|
9385a27ff0 | ||
|
|
f2e4689d0c | ||
|
|
70fabebcb3 | ||
|
|
c272e1ccdf | ||
|
|
fd5012c04e | ||
|
|
bfc57a6f6d | ||
|
|
540d4bef1e | ||
|
|
5149ff7b12 | ||
|
|
01cd68a5aa | ||
|
|
b700c64dc2 | ||
|
|
350c903793 | ||
|
|
39afe4c7bd | ||
|
|
b9435e3cea | ||
|
|
a7329e5cc9 | ||
|
|
a146c5bf78 | ||
|
|
557f849519 | ||
|
|
03dc6d92ae | ||
|
|
3c46870109 | ||
|
|
88dd18e045 | ||
|
|
6b426e78f6 | ||
|
|
70a3c2c648 | ||
|
|
6ea0895803 | ||
|
|
b1a14401c2 | ||
|
|
e0486ea68e | ||
|
|
0ac434da78 | ||
|
|
6e4b159611 | ||
|
|
bc4342b2d0 | ||
|
|
cb271f51d1 | ||
|
|
ea8b8eec1c | ||
|
|
b1964851c9 | ||
|
|
393e4ac90e | ||
|
|
0163edc868 | ||
|
|
3efdd55fb8 | ||
|
|
122cf4c897 | ||
|
|
938d7275ba | ||
|
|
8f9b9d31e2 | ||
|
|
d1fffab235 | ||
|
|
ebebf94750 | ||
|
|
b0ac98a7cd | ||
|
|
a132d6e141 | ||
|
|
a1043121fc | ||
|
|
5ba189ffb4 | ||
|
|
d2c2811249 | ||
|
|
99875afcc0 | ||
|
|
ae8660fe06 | ||
|
|
01c93a2ee3 | ||
|
|
d8549fe09a | ||
|
|
a12e093417 | ||
|
|
2f8088432c | ||
|
|
3cf6c6ee0c | ||
|
|
8993882dcb | ||
|
|
c6c2893e2c | ||
|
|
96a260b027 | ||
|
|
6bb2fad9b0 | ||
|
|
9d95ae9341 | ||
|
|
68743012e4 | ||
|
|
ef2950bca2 | ||
|
|
6f67ea44dc | ||
|
|
26c42bd559 | ||
|
|
c3c745ca19 | ||
|
|
2463f0257e | ||
|
|
e2b83624a3 | ||
|
|
e0310906c7 | ||
|
|
2741c5c330 | ||
|
|
175fc8591e | ||
|
|
3c62586878 | ||
|
|
8b95e12468 | ||
|
|
90a52e4602 | ||
|
|
5677c4882e | ||
|
|
6d17cd50fe | ||
|
|
1cd98665de | ||
|
|
cfcf97b616 | ||
|
|
6efebef714 | ||
|
|
600f660f5e | ||
|
|
003461ec96 | ||
|
|
00b4501c59 | ||
|
|
8142794447 | ||
|
|
ea2ef78ceb | ||
|
|
11dca0bd29 | ||
|
|
dccd6b4a91 | ||
|
|
46b1ecc77d | ||
|
|
8a319e90c6 | ||
|
|
652914a67b | ||
|
|
22f902f0f7 | ||
|
|
131b232155 | ||
|
|
52da64b6dc | ||
|
|
75306b7a6e | ||
|
|
867f9ae362 | ||
|
|
ab23db2fa1 | ||
|
|
349d556339 | ||
|
|
7bfd0ecbb5 | ||
|
|
0f43e0bb7d | ||
|
|
43c2cf8e1c | ||
|
|
00383b9438 | ||
|
|
f36ccdd9fa | ||
|
|
909df0d7bb | ||
|
|
0410654c2c | ||
|
|
0dbe9cb586 | ||
|
|
45e5867736 | ||
|
|
1ccc25b486 | ||
|
|
d6aa63bd97 | ||
|
|
cf1ad3fd8c | ||
|
|
2554ebf273 | ||
|
|
d642e03cd0 | ||
|
|
c8d75fbd8a | ||
|
|
db0644eddf | ||
|
|
a8c4bed4e8 | ||
|
|
a70830a7b7 | ||
|
|
4bb004c6f4 | ||
|
|
6467d3b58e | ||
|
|
194ab5aa92 | ||
|
|
c8b8806fed | ||
|
|
1a677c7441 | ||
|
|
2b78f73fe5 | ||
|
|
31d271084f | ||
|
|
2200a0223b | ||
|
|
1e056ee415 | ||
|
|
4ae743ecb6 | ||
|
|
6c03246ec8 | ||
|
|
f506644a8c | ||
|
|
b83a0f9a9c | ||
|
|
66c2bdd65a | ||
|
|
1be4c59481 | ||
|
|
32e4b0b1b2 | ||
|
|
dad55fe7a8 | ||
|
|
9147e6c5bf | ||
|
|
6c2301ec39 | ||
|
|
7e96d57627 | ||
|
|
de6112adb7 | ||
|
|
46214ce7cd | ||
|
|
ee619f2919 | ||
|
|
269699988b | ||
|
|
4cecf04639 | ||
|
|
e7b81e4d46 | ||
|
|
e1acf0a94d | ||
|
|
b9d7bb2d8e | ||
|
|
90f357db6f | ||
|
|
3c376c8e9b | ||
|
|
b24bbb2cb1 | ||
|
|
97f2c74dd8 | ||
|
|
5665426e6b | ||
|
|
6150679736 | ||
|
|
4804f45156 | ||
|
|
537c03504f | ||
|
|
91642b2bd9 | ||
|
|
f71eda1c2f | ||
|
|
c347013eef | ||
|
|
59bd081e92 | ||
|
|
6166e19405 | ||
|
|
21b31f11b8 | ||
|
|
dd2e05b33f | ||
|
|
40c0207377 | ||
|
|
dc12cacd50 | ||
|
|
99b08fbd13 | ||
|
|
bf2a39b76d | ||
|
|
b84b52202e | ||
|
|
eaf5547b88 | ||
|
|
ea44bbff9f | ||
|
|
cc0c96af50 | ||
|
|
ef3b244c1a | ||
|
|
45ecbc91e8 | ||
|
|
401caaabb4 | ||
|
|
22eb6cb5fa | ||
|
|
65dcb6acea | ||
|
|
b4630c403d | ||
|
|
86313b337a | ||
|
|
87329c689d | ||
|
|
ca3b8ef2e7 | ||
|
|
a0413b5d91 | ||
|
|
d6276a15d2 | ||
|
|
39f60c4740 | ||
|
|
17cf9d33cf | ||
|
|
fa7866291a | ||
|
|
59f905a573 | ||
|
|
060571290a | ||
|
|
30888cf5ca | ||
|
|
eb89b65b59 | ||
|
|
bf56e25404 | ||
|
|
34fa2011be | ||
|
|
a8e787fda8 | ||
|
|
ad692c185e | ||
|
|
d16ccd7e37 | ||
|
|
a92d5f3569 | ||
|
|
95ebd07735 | ||
|
|
6a0f527e0e | ||
|
|
65a82d7ee6 | ||
|
|
2898067318 | ||
|
|
6d2a1cfb44 | ||
|
|
bced53966e | ||
|
|
a429f83f5e | ||
|
|
2f0ad0d28c | ||
|
|
fc4ef2b430 | ||
|
|
e3b0474901 | ||
|
|
cc9f899cd6 | ||
|
|
a022b1a6c1 | ||
|
|
4971b9fc39 | ||
|
|
939bf66a80 | ||
|
|
309a54ba69 | ||
|
|
8568459c74 | ||
|
|
9a2eb46cea | ||
|
|
48e2bd5114 | ||
|
|
a2a70bd6d0 | ||
|
|
3e3fce5f38 | ||
|
|
7c8e26c717 | ||
|
|
8dad8f25cf | ||
|
|
ad85ac3dde | ||
|
|
d3e956f7cc | ||
|
|
3da1b24b6a | ||
|
|
42d2b24d48 | ||
|
|
8685fcd593 | ||
|
|
45aa93e73d | ||
|
|
676cd6ffee | ||
|
|
a9de2f80f2 | ||
|
|
86ec88b8fe | ||
|
|
6b87d94bb0 | ||
|
|
706b30f4d2 | ||
|
|
3bcc60333d | ||
|
|
bf6c435ae6 | ||
|
|
abc4840d16 | ||
|
|
a118003d0a | ||
|
|
ccc91403c5 | ||
|
|
9b0b1c3cc2 | ||
|
|
395aed5f97 | ||
|
|
278e5f4cc6 | ||
|
|
7fa5046575 | ||
|
|
9b8067cbc3 | ||
|
|
e252f0feba | ||
|
|
8e8ec2fba6 | ||
|
|
41e698c482 | ||
|
|
82127d8406 | ||
|
|
5a65b6caee | ||
|
|
ed6a92cd0f | ||
|
|
577ccd32f0 | ||
|
|
72657758d5 | ||
|
|
f9ba0483ca | ||
|
|
d82fb57223 | ||
|
|
5c10e9a7fa | ||
|
|
578ad903bc | ||
|
|
789b445815 | ||
|
|
c299d9249f | ||
|
|
795c2e4aa2 | ||
|
|
031a63d5c2 | ||
|
|
f5ef8f5bc0 | ||
|
|
30f7536cbe | ||
|
|
8abdbc41e1 | ||
|
|
7f229bbf39 | ||
|
|
d4947ba0ee | ||
|
|
2cee716181 | ||
|
|
a7383ad35d | ||
|
|
52cc2d224e | ||
|
|
5db10bdcc7 | ||
|
|
43119efaf0 | ||
|
|
16bf7aa3ab | ||
|
|
b2a623ee16 | ||
|
|
c40406d26e | ||
|
|
87ff5ad1e0 | ||
|
|
aa63f2be1f | ||
|
|
5cb90bdf77 | ||
|
|
4f557af6cb | ||
|
|
5f63797f17 | ||
|
|
bbb32ada4a | ||
|
|
fc33f19b06 | ||
|
|
7efab85b10 | ||
|
|
0ece168833 | ||
|
|
6be4c6af0e | ||
|
|
4f6df73156 | ||
|
|
cd20078bef | ||
|
|
5e0e8de4f6 | ||
|
|
ed5e76adac | ||
|
|
12265b245d | ||
|
|
37b1389f12 | ||
|
|
b679eb1a95 | ||
|
|
2f79cf1304 | ||
|
|
3fe0cb9281 | ||
|
|
9f828224bc | ||
|
|
2153e43969 | ||
|
|
c6d19a4afb | ||
|
|
016e8fde89 | ||
|
|
d87db70ed0 | ||
|
|
c3b9d69919 | ||
|
|
c3a9db6488 | ||
|
|
8bdbfbf194 | ||
|
|
f204af173d | ||
|
|
12ca103f9f | ||
|
|
c2ca899c7e | ||
|
|
902ffa6853 | ||
|
|
f03acce84c | ||
|
|
93ebf163cb | ||
|
|
f736646ac6 | ||
|
|
262113f9ee | ||
|
|
e75cdd4c27 | ||
|
|
559257ed33 | ||
|
|
71e671f053 | ||
|
|
9fbe573cca | ||
|
|
6856848efc | ||
|
|
ff6967de9e | ||
|
|
5c4170951a | ||
|
|
500eb17449 | ||
|
|
ffdc33d964 | ||
|
|
3e4dd5019d | ||
|
|
cb2f422e1c | ||
|
|
4559a38172 | ||
|
|
91dc2b96fc | ||
|
|
fb8555a6cc | ||
|
|
ebf1126351 | ||
|
|
3a81eb7d48 | ||
|
|
3ad4d937c5 | ||
|
|
c35e5ca7dd | ||
|
|
4a6c8f3cb2 | ||
|
|
e7c8e62d75 | ||
|
|
d6d16b4696 | ||
|
|
dc1968b968 | ||
|
|
4fef9448bf | ||
|
|
4bb5345e13 | ||
|
|
d294cab933 | ||
|
|
f139178136 | ||
|
|
4eb0ed9f2f | ||
|
|
7a598f32dc | ||
|
|
b776336ebf | ||
|
|
481df98f58 | ||
|
|
8cb1024ff6 | ||
|
|
41ff2a9276 | ||
|
|
acb99a03e3 | ||
|
|
4b2eb22989 | ||
|
|
a505826ec9 | ||
|
|
54d068de44 | ||
|
|
25d8e93a90 | ||
|
|
9712fb2d57 | ||
|
|
2b49a11b2a | ||
|
|
1bfc667515 | ||
|
|
4c5432be6f | ||
|
|
9dc2a30793 | ||
|
|
13e8f25ca9 | ||
|
|
ac1964edb1 | ||
|
|
dbb1bbf101 | ||
|
|
0ac80aacd1 | ||
|
|
7486cb7c64 | ||
|
|
e3cdc0a05b | ||
|
|
6913bce6a1 | ||
|
|
7010c835d2 | ||
|
|
2aa1b43f01 | ||
|
|
32cbb714f9 | ||
|
|
7f4fd6168a | ||
|
|
647534a4f8 | ||
|
|
31fa857319 | ||
|
|
a363d443bf | ||
|
|
75c522e082 | ||
|
|
ebeaf64fbb | ||
|
|
6afe232c4d | ||
|
|
05df7f3394 | ||
|
|
0cdbe714d2 | ||
|
|
9d6d60dcf0 | ||
|
|
65350ad552 | ||
|
|
b437c3cf0c | ||
|
|
5488c66f53 | ||
|
|
ef48193fad | ||
|
|
9ee1dd99eb | ||
|
|
0307ba7883 | ||
|
|
1a5b0969b9 | ||
|
|
3c399fbe3f | ||
|
|
a9a5c4a052 | ||
|
|
d5498c8712 | ||
|
|
09321ccc9c | ||
|
|
a3fe5f5757 | ||
|
|
dfed713647 | ||
|
|
92dc3c89af | ||
|
|
eb610441b5 | ||
|
|
67eeb145e1 | ||
|
|
a3835b1279 | ||
|
|
5f38d5ee63 | ||
|
|
53eaf85969 | ||
|
|
d54acca53a | ||
|
|
2959156070 | ||
|
|
b0ddb33acc | ||
|
|
62141d3d27 | ||
|
|
478c149bbb | ||
|
|
7b39a3084f | ||
|
|
a6daf0d991 | ||
|
|
54f11ad603 | ||
|
|
40df0dcf3d | ||
|
|
99d256422e | ||
|
|
389feda65f | ||
|
|
5a8f0f3557 | ||
|
|
b9b76977b6 | ||
|
|
27917c2d89 | ||
|
|
0cfdce0d5e | ||
|
|
ab0e657d77 | ||
|
|
34b40500c3 | ||
|
|
a3b0135557 | ||
|
|
8546db9dfd | ||
|
|
ab579587f2 | ||
|
|
ecd75e43b0 | ||
|
|
061f91ba41 | ||
|
|
97b31352c2 | ||
|
|
77d2479c75 | ||
|
|
f0b2798c37 | ||
|
|
8002936fe3 | ||
|
|
f440bb193d | ||
|
|
faa5883f09 | ||
|
|
7251e5bd62 | ||
|
|
7be90f71d3 | ||
|
|
19d3a0cbac | ||
|
|
0ddafeeabf | ||
|
|
b2ad402df4 | ||
|
|
e46dac3fbd | ||
|
|
5c8fbe2c6f | ||
|
|
f11a1b0122 | ||
|
|
8f4cca47e9 | ||
|
|
4fa736114c | ||
|
|
13ac1e1957 | ||
|
|
c28a0374f1 | ||
|
|
93229fc54b | ||
|
|
997190a050 | ||
|
|
707a5fca91 | ||
|
|
6d92b9b910 | ||
|
|
9b38c04579 | ||
|
|
06144a1fc4 | ||
|
|
0d152eb907 | ||
|
|
1a61bf7bff | ||
|
|
87a296f728 | ||
|
|
e98c0621d3 | ||
|
|
40c0b4ef2e | ||
|
|
44142706c3 | ||
|
|
208832e847 | ||
|
|
12066411db | ||
|
|
e5008fbf93 | ||
|
|
d4ffdaffc2 | ||
|
|
bb5a310aec | ||
|
|
ba558b2d75 | ||
|
|
82b344db1b | ||
|
|
f2599ffe90 | ||
|
|
50fc63251e | ||
|
|
b1ef39927c | ||
|
|
b4472a165e | ||
|
|
a87fc5f863 | ||
|
|
2f3f5f19cd | ||
|
|
e11eb4775e | ||
|
|
a15a3ae810 | ||
|
|
daeb172ba1 | ||
|
|
0e5b0ebda6 | ||
|
|
d5254dff7b | ||
|
|
146d6bf7fb | ||
|
|
0a8c1528cf | ||
|
|
941921dd0f | ||
|
|
0ca3a38ba6 | ||
|
|
1678a039ae | ||
|
|
e5406ed3cf | ||
|
|
4d9ca71c82 | ||
|
|
6045f07a9c | ||
|
|
9b22d5cab1 | ||
|
|
753b03d581 | ||
|
|
1e37d8ccb3 | ||
|
|
4038cdf70a | ||
|
|
d09b33ae93 | ||
|
|
0687051ffb | ||
|
|
8641da13b9 | ||
|
|
cc32566c92 | ||
|
|
955e2d2826 | ||
|
|
4e57969e4e | ||
|
|
52012003e9 | ||
|
|
3bdc7b9a88 | ||
|
|
a2a2489a97 | ||
|
|
b2c2b42408 | ||
|
|
f5744cc9bf | ||
|
|
56264ea52a | ||
|
|
1f50bc79bc | ||
|
|
c6d2c1e520 | ||
|
|
8aee009a0a | ||
|
|
5ccd618189 | ||
|
|
5161e1abb3 | ||
|
|
e15f2ef11a | ||
|
|
8dea640e9a | ||
|
|
4005b8d1d2 | ||
|
|
85ac99aee0 | ||
|
|
e085fd9e95 | ||
|
|
f26ed1c8c1 | ||
|
|
4cf7282027 | ||
|
|
0ae81d4115 | ||
|
|
226fc3d99b | ||
|
|
bd29b7d031 | ||
|
|
c8b0c9af0a | ||
|
|
01c4f243d4 | ||
|
|
fe9322ecd5 | ||
|
|
904b3008a9 | ||
|
|
66f1e0f4cd | ||
|
|
e8bfeae048 | ||
|
|
fd7278517d | ||
|
|
b13735e4cc | ||
|
|
a8be277ca0 | ||
|
|
1dfbf6eed6 | ||
|
|
29b9bb96f3 | ||
|
|
14167f826b | ||
|
|
96ea27322d | ||
|
|
71d3a7de40 | ||
|
|
fe3836b497 | ||
|
|
49559f1a1a | ||
|
|
042354d00f | ||
|
|
f0d3901b6b | ||
|
|
9d6f629f6a | ||
|
|
7b99d5ebcb | ||
|
|
8b2174d249 | ||
|
|
ffdca7eea7 | ||
|
|
684727b32e | ||
|
|
3a8b69d69b | ||
|
|
1bba9fcc53 | ||
|
|
f7fc9adc63 | ||
|
|
e60d1788b2 | ||
|
|
a7e13e96e4 | ||
|
|
e644493e02 | ||
|
|
06f4e627fc | ||
|
|
e0775546f6 | ||
|
|
0dc96210b6 | ||
|
|
a95f30ce45 | ||
|
|
83a2427a61 | ||
|
|
184b13f2fb | ||
|
|
9a632d9b7c | ||
|
|
c404e9ffd0 | ||
|
|
b1fe8c5325 | ||
|
|
7307084dfd | ||
|
|
40899d08dd | ||
|
|
00e6749d8b | ||
|
|
05466d318a | ||
|
|
6312d785d8 | ||
|
|
34ff946f4d | ||
|
|
158cb307f6 | ||
|
|
e35daf95c0 | ||
|
|
b448890210 | ||
|
|
be6836b0ef | ||
|
|
60afba5592 | ||
|
|
d043542094 | ||
|
|
89145a7711 | ||
|
|
7744989583 | ||
|
|
35d65bc7d7 | ||
|
|
7fdb099097 | ||
|
|
1f55356744 | ||
|
|
00821036bb | ||
|
|
6b89e86a97 | ||
|
|
65f5aa59e6 | ||
|
|
0eff324ce0 | ||
|
|
676c6a784d | ||
|
|
cc369f41f5 | ||
|
|
6c889895bd | ||
|
|
580ada8c4f | ||
|
|
aa15312670 | ||
|
|
df6f3f6f32 | ||
|
|
2b09e3ca3d | ||
|
|
9a61067367 | ||
|
|
c8617e70a8 | ||
|
|
38b959f1a9 | ||
|
|
50ea4c39da | ||
|
|
ff08416b12 | ||
|
|
8d173efe2d | ||
|
|
aa698a8412 | ||
|
|
e6bfedb58b | ||
|
|
37e6b262eb | ||
|
|
9373d0c915 | ||
|
|
a467d76832 | ||
|
|
937399606e | ||
|
|
c2076af43b | ||
|
|
4de4a70be7 | ||
|
|
8afce7e651 | ||
|
|
2bf7f2feae | ||
|
|
8386496456 | ||
|
|
7f9c76a6fc | ||
|
|
d4d37667e1 | ||
|
|
d4543be8eb | ||
|
|
e38a3051a1 | ||
|
|
c907e80c10 | ||
|
|
a241e950f2 | ||
|
|
39232cbcbb | ||
|
|
a7b60f6780 | ||
|
|
05ab1c2e0a | ||
|
|
8c7e8255bb | ||
|
|
f0e5113a7f | ||
|
|
a830bee9c7 | ||
|
|
bdc0134e88 | ||
|
|
190ecb7ada | ||
|
|
a77d513513 | ||
|
|
7b99daebd7 | ||
|
|
2d4a2fd10b | ||
|
|
a0e6cd93b6 | ||
|
|
b3f42dc51e | ||
|
|
b0cad30796 | ||
|
|
fc360608b7 | ||
|
|
01733c94fa | ||
|
|
68a9b14eca | ||
|
|
738ed93221 | ||
|
|
7166a474ae | ||
|
|
e632539b61 | ||
|
|
e7f6df46e8 | ||
|
|
a123246ac9 | ||
|
|
ddb9933c91 | ||
|
|
9f7f089d8a | ||
|
|
e1f48c2b46 | ||
|
|
d7017ce1e4 | ||
|
|
6666d31ee9 | ||
|
|
29aa159827 | ||
|
|
6bfc37309e | ||
|
|
71c530590e | ||
|
|
d596a877fa | ||
|
|
b9b15e5f32 | ||
|
|
d66e6510e3 | ||
|
|
a233a8cc82 | ||
|
|
d42ebab575 | ||
|
|
51af8c27f6 | ||
|
|
44acf2f471 | ||
|
|
ceb1e4c4f7 | ||
|
|
6db6c3b2cc | ||
|
|
2e02e24e70 | ||
|
|
95a3b5c41e | ||
|
|
3fe06b3548 | ||
|
|
1a83eed38f | ||
|
|
4fa1604230 | ||
|
|
edf2cd0b92 | ||
|
|
b5034cf535 | ||
|
|
29305dd070 | ||
|
|
3c99e3b7c7 | ||
|
|
9a226ec7e6 | ||
|
|
2959600f52 | ||
|
|
ff9231eec4 | ||
|
|
6b8f5963a8 | ||
|
|
a1841c35ae | ||
|
|
aa2d747d8f | ||
|
|
ee613b564c | ||
|
|
2bf5a3843d | ||
|
|
29e84c9e88 | ||
|
|
23666858e2 | ||
|
|
5151a4521f | ||
|
|
6b948cfc7e | ||
|
|
9054165e8a | ||
|
|
11cc33a982 | ||
|
|
e2bcaa4d75 | ||
|
|
94b2d48d02 | ||
|
|
0293a61895 | ||
|
|
7ffe65770e | ||
|
|
cb9849e192 | ||
|
|
299e640170 | ||
|
|
954963b40e | ||
|
|
779bcdd990 | ||
|
|
0ffefe44a7 | ||
|
|
deddbda26e | ||
|
|
1a92bf9e8e | ||
|
|
8741017819 | ||
|
|
35c2b961be | ||
|
|
0d980134e7 | ||
|
|
3ad0686bc7 | ||
|
|
df9410cd15 | ||
|
|
041e9957dd | ||
|
|
6b97af4a03 | ||
|
|
e234158cc9 | ||
|
|
c30fb7f590 | ||
|
|
5c840f333f | ||
|
|
b24a22b0b6 | ||
|
|
47cc04c0a3 | ||
|
|
ccad883256 | ||
|
|
3a2aa54d2a | ||
|
|
d423f58566 | ||
|
|
0bcf50f1b5 | ||
|
|
8d5cc42ef5 | ||
|
|
a772ab323e | ||
|
|
f55d75e7fc | ||
|
|
5865688c16 | ||
|
|
3e4c9c8713 | ||
|
|
36e95bc868 | ||
|
|
3e40f5c588 | ||
|
|
643262bc6a | ||
|
|
f1f311e456 | ||
|
|
c1a22dda46 | ||
|
|
d14134ddce | ||
|
|
48d33b070f | ||
|
|
0eb9dd5fe5 | ||
|
|
4705b7da0e | ||
|
|
c0f276a892 | ||
|
|
e666c6850e | ||
|
|
f9aa3c27be | ||
|
|
5fb8100fc5 | ||
|
|
41add9f8ca | ||
|
|
513b96b61c | ||
|
|
8730852d6e | ||
|
|
ca496c13b8 | ||
|
|
0467004144 | ||
|
|
e14739e102 | ||
|
|
0eaac1cd79 | ||
|
|
5f726d697b | ||
|
|
9c1c962aa7 | ||
|
|
c122eab77b | ||
|
|
617d2338c4 | ||
|
|
c56f288b56 | ||
|
|
51b4d5a57a | ||
|
|
43d30180e8 | ||
|
|
3b805813cd | ||
|
|
21cb4eafe5 | ||
|
|
fa4c8110e7 | ||
|
|
25529ad95f | ||
|
|
dba30bbfed | ||
|
|
4cd70138b6 | ||
|
|
0a2cacbba8 | ||
|
|
d213764d19 | ||
|
|
702153d087 | ||
|
|
8babf0d2b5 | ||
|
|
9c1d4183fd | ||
|
|
c4992bd5f3 | ||
|
|
2da0d479e7 | ||
|
|
628d9577a2 | ||
|
|
6b2f4b12fd | ||
|
|
bc7688a69f | ||
|
|
7b901e180a | ||
|
|
e67ffd2d87 | ||
|
|
045de94b49 | ||
|
|
8624d83be0 | ||
|
|
0634e135df | ||
|
|
962cfc5eb9 | ||
|
|
ca64d8a861 | ||
|
|
35250eb230 | ||
|
|
5dd0a72a52 | ||
|
|
735e78f01d | ||
|
|
ae7c4c33c0 | ||
|
|
c032dd0f45 | ||
|
|
ce46555e77 | ||
|
|
2f98dd0429 | ||
|
|
71f5392f89 | ||
|
|
6d63b8e71e | ||
|
|
f6ca97d1dc | ||
|
|
4e50ec81a0 | ||
|
|
386abc5eba | ||
|
|
04ea6dac83 | ||
|
|
f16913a76d | ||
|
|
03ff87d11c | ||
|
|
460e0711c6 | ||
|
|
b8eb3ecb1d | ||
|
|
2208a21a6c | ||
|
|
2d0aca0d20 | ||
|
|
b7a558b951 | ||
|
|
3c5deb9aaf | ||
|
|
4d64124eef | ||
|
|
e2cbb7e7da | ||
|
|
df79098adc | ||
|
|
13ba5ba0db | ||
|
|
2eb2ace539 | ||
|
|
064f6629ab | ||
|
|
786244c0d3 | ||
|
|
e1ae0d7e90 | ||
|
|
c36fa0c7e2 | ||
|
|
24c587518a | ||
|
|
4c1f2b2a5b | ||
|
|
6bcfe65877 | ||
|
|
28a70eba07 | ||
|
|
285db2f40b | ||
|
|
0fc5445003 | ||
|
|
e8ea2e6f05 | ||
|
|
b792f00553 | ||
|
|
4df44d8b32 | ||
|
|
58c296c1ff | ||
|
|
13de66d559 | ||
|
|
e5498ca20f | ||
|
|
0558b203fe | ||
|
|
38d09f9e78 | ||
|
|
768f62a24a | ||
|
|
7e62a4a79c | ||
|
|
761861f0b7 | ||
|
|
4e291795a6 | ||
|
|
7fe9d9520a | ||
|
|
4c2961f0d9 | ||
|
|
ef26484153 | ||
|
|
79aac473b3 | ||
|
|
5c3177cc79 | ||
|
|
6c75b8a36a | ||
|
|
ee0e381d65 | ||
|
|
8cb7a7e7a5 | ||
|
|
bcf5b5fdcb | ||
|
|
ef18ddd866 | ||
|
|
cee4116b80 | ||
|
|
0c53bd6dd4 | ||
|
|
aff334fdd6 | ||
|
|
185bd1e53c | ||
|
|
006635003e | ||
|
|
f2fd5205ef | ||
|
|
31be4d2454 | ||
|
|
5c18346cd5 | ||
|
|
e0b634ba3b | ||
|
|
a05155cb75 | ||
|
|
455b168366 | ||
|
|
06f486a8eb | ||
|
|
42722b2873 | ||
|
|
ecb5137dbe | ||
|
|
2531961bf8 | ||
|
|
417bf2c935 | ||
|
|
3673dba1e2 | ||
|
|
9b288c6933 | ||
|
|
5fac4f7b45 | ||
|
|
c7b6e19872 | ||
|
|
033e9e09fb | ||
|
|
3dcf3f8a82 | ||
|
|
403ed48c3e | ||
|
|
4d797c9232 | ||
|
|
ec6794b9ba | ||
|
|
634ce87bba | ||
|
|
98bca30dfb | ||
|
|
cc0fae8e4e | ||
|
|
8d8da71f20 | ||
|
|
9a097214a6 | ||
|
|
619945b861 | ||
|
|
71774bce6f | ||
|
|
9c54886f14 | ||
|
|
1252bacb7a | ||
|
|
a1b00f9053 | ||
|
|
e4369e06bc | ||
|
|
29b8b79732 | ||
|
|
2c7c19dfb1 | ||
|
|
b79d967371 | ||
|
|
69bb6ebaf6 | ||
|
|
57b2fb4645 | ||
|
|
bf5d2a68f5 | ||
|
|
7738ebbc0f | ||
|
|
6d7f788989 | ||
|
|
be754244a3 | ||
|
|
e0f426d863 | ||
|
|
e987a915e8 | ||
|
|
a79ff1c6c9 | ||
|
|
2dcb4134cc | ||
|
|
e309f75118 | ||
|
|
643402da1c | ||
|
|
a1d1abfffc | ||
|
|
b5758e67f9 | ||
|
|
2851833726 | ||
|
|
c1ef6940b0 | ||
|
|
2aba9c081c | ||
|
|
eb21170691 | ||
|
|
d9129cb9c5 | ||
|
|
4315c157c7 | ||
|
|
da5bef501e | ||
|
|
4fbba98168 | ||
|
|
87c82dea3d | ||
|
|
c08a2b6638 | ||
|
|
7bc874c7fd | ||
|
|
fac0e4e603 | ||
|
|
199e3d2234 | ||
|
|
5906d37818 | ||
|
|
e495ffec78 | ||
|
|
84ccb85184 | ||
|
|
686949b258 | ||
|
|
3e2f90a32a | ||
|
|
bb31e64752 | ||
|
|
481cf02db9 | ||
|
|
2f225e2340 | ||
|
|
eed1c2344d | ||
|
|
4241caef95 | ||
|
|
2103ae5fdf | ||
|
|
6055906eb1 | ||
|
|
e98edc1a1a | ||
|
|
62382809b2 | ||
|
|
0572336ff7 | ||
|
|
d8feceebb5 | ||
|
|
da4faacd6b | ||
|
|
39c28626aa | ||
|
|
5e8a7a03c3 | ||
|
|
dd2522d8d0 | ||
|
|
fe792882b5 | ||
|
|
d3ead2cd09 | ||
|
|
c879591f45 | ||
|
|
c315f63e4b | ||
|
|
2fb36b116d | ||
|
|
ca388a9acf | ||
|
|
32b02c9925 | ||
|
|
54d5bce445 | ||
|
|
b7afcf3416 | ||
|
|
8ed3658447 | ||
|
|
3aa614b983 | ||
|
|
3953092edd | ||
|
|
ef5a0b9afc |
@@ -1,6 +1,6 @@
|
|||||||
[run]
|
[run]
|
||||||
omit =
|
omit =
|
||||||
scripts/*
|
scripts/*
|
||||||
freqtrade/tests/*
|
|
||||||
freqtrade/vendor/*
|
freqtrade/vendor/*
|
||||||
freqtrade/__main__.py
|
freqtrade/__main__.py
|
||||||
|
tests/*
|
||||||
|
|||||||
17
.dependabot/config.yml
Normal file
17
.dependabot/config.yml
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
version: 1
|
||||||
|
|
||||||
|
update_configs:
|
||||||
|
- package_manager: "python"
|
||||||
|
directory: "/"
|
||||||
|
update_schedule: "weekly"
|
||||||
|
allowed_updates:
|
||||||
|
- match:
|
||||||
|
update_type: "all"
|
||||||
|
target_branch: "develop"
|
||||||
|
|
||||||
|
- package_manager: "docker"
|
||||||
|
directory: "/"
|
||||||
|
update_schedule: "daily"
|
||||||
|
allowed_updates:
|
||||||
|
- match:
|
||||||
|
update_type: "all"
|
||||||
1
.github/ISSUE_TEMPLATE.md
vendored
1
.github/ISSUE_TEMPLATE.md
vendored
@@ -5,6 +5,7 @@ If it hasn't been reported, please create a new issue.
|
|||||||
|
|
||||||
## Step 2: Describe your environment
|
## Step 2: Describe your environment
|
||||||
|
|
||||||
|
* Operating system: ____
|
||||||
* Python Version: _____ (`python -V`)
|
* Python Version: _____ (`python -V`)
|
||||||
* CCXT version: _____ (`pip freeze | grep ccxt`)
|
* CCXT version: _____ (`pip freeze | grep ccxt`)
|
||||||
* Branch: Master | Develop
|
* Branch: Master | Develop
|
||||||
|
|||||||
15
.gitignore
vendored
15
.gitignore
vendored
@@ -1,12 +1,12 @@
|
|||||||
# Freqtrade rules
|
# Freqtrade rules
|
||||||
freqtrade/tests/testdata/*.json
|
|
||||||
hyperopt_conf.py
|
|
||||||
config*.json
|
config*.json
|
||||||
*.sqlite
|
*.sqlite
|
||||||
.hyperopt
|
|
||||||
logfile.txt
|
logfile.txt
|
||||||
hyperopt_trials.pickle
|
user_data/*
|
||||||
user_data/
|
!user_data/strategy/sample_strategy.py
|
||||||
|
!user_data/notebooks
|
||||||
|
user_data/notebooks/*
|
||||||
|
!user_data/notebooks/*example.ipynb
|
||||||
freqtrade-plot.html
|
freqtrade-plot.html
|
||||||
freqtrade-profit-plot.html
|
freqtrade-profit-plot.html
|
||||||
|
|
||||||
@@ -80,7 +80,7 @@ docs/_build/
|
|||||||
target/
|
target/
|
||||||
|
|
||||||
# Jupyter Notebook
|
# Jupyter Notebook
|
||||||
.ipynb_checkpoints
|
*.ipynb_checkpoints
|
||||||
|
|
||||||
# pyenv
|
# pyenv
|
||||||
.python-version
|
.python-version
|
||||||
@@ -92,3 +92,6 @@ target/
|
|||||||
|
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.mypy_cache/
|
.mypy_cache/
|
||||||
|
|
||||||
|
#exceptions
|
||||||
|
!*.gitkeep
|
||||||
|
|||||||
33
.pyup.yml
33
.pyup.yml
@@ -1,33 +0,0 @@
|
|||||||
# autogenerated pyup.io config file
|
|
||||||
# see https://pyup.io/docs/configuration/ for all available options
|
|
||||||
|
|
||||||
# configure updates globally
|
|
||||||
# default: all
|
|
||||||
# allowed: all, insecure, False
|
|
||||||
update: all
|
|
||||||
|
|
||||||
# configure dependency pinning globally
|
|
||||||
# default: True
|
|
||||||
# allowed: True, False
|
|
||||||
pin: True
|
|
||||||
|
|
||||||
schedule: "every day"
|
|
||||||
|
|
||||||
|
|
||||||
search: False
|
|
||||||
# Specify requirement files by hand, default is empty
|
|
||||||
# default: empty
|
|
||||||
# allowed: list
|
|
||||||
requirements:
|
|
||||||
- requirements.txt
|
|
||||||
- requirements-dev.txt
|
|
||||||
- requirements-plot.txt
|
|
||||||
|
|
||||||
|
|
||||||
# configure the branch prefix the bot is using
|
|
||||||
# default: pyup-
|
|
||||||
branch_prefix: pyup/
|
|
||||||
|
|
||||||
# allow to close stale PRs
|
|
||||||
# default: True
|
|
||||||
close_prs: True
|
|
||||||
36
.travis.yml
36
.travis.yml
@@ -10,35 +10,38 @@ services:
|
|||||||
env:
|
env:
|
||||||
global:
|
global:
|
||||||
- IMAGE_NAME=freqtradeorg/freqtrade
|
- IMAGE_NAME=freqtradeorg/freqtrade
|
||||||
addons:
|
|
||||||
apt:
|
|
||||||
packages:
|
|
||||||
- libelf-dev
|
|
||||||
- libdw-dev
|
|
||||||
- binutils-dev
|
|
||||||
install:
|
install:
|
||||||
- cd build_helpers && ./install_ta-lib.sh; cd ..
|
- cd build_helpers && ./install_ta-lib.sh ${HOME}/dependencies/; cd ..
|
||||||
- export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
|
- export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH
|
||||||
- pip install --upgrade pytest-random-order
|
- export TA_LIBRARY_PATH=${HOME}/dependencies/lib
|
||||||
|
- export TA_INCLUDE_PATH=${HOME}/dependencies/lib/include
|
||||||
- pip install -r requirements-dev.txt
|
- pip install -r requirements-dev.txt
|
||||||
- pip install -e .
|
- pip install -e .
|
||||||
jobs:
|
jobs:
|
||||||
|
|
||||||
include:
|
include:
|
||||||
- stage: tests
|
- stage: tests
|
||||||
script:
|
script:
|
||||||
- pytest --cov=freqtrade --cov-config=.coveragerc freqtrade/tests/
|
- pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
||||||
|
# Allow failure for coveralls
|
||||||
|
- coveralls || true
|
||||||
name: pytest
|
name: pytest
|
||||||
- script:
|
- script:
|
||||||
- cp config.json.example config.json
|
- cp config.json.example config.json
|
||||||
- python freqtrade/main.py --datadir freqtrade/tests/testdata backtesting
|
- freqtrade --datadir tests/testdata backtesting
|
||||||
name: backtest
|
name: backtest
|
||||||
- script:
|
- script:
|
||||||
- cp config.json.example config.json
|
- cp config.json.example config.json
|
||||||
- python freqtrade/main.py --datadir freqtrade/tests/testdata hyperopt -e 5
|
- freqtrade --datadir tests/testdata hyperopt -e 5
|
||||||
name: hyperopt
|
name: hyperopt
|
||||||
- script: flake8 freqtrade
|
- script: flake8
|
||||||
name: flake8
|
name: flake8
|
||||||
- script: mypy freqtrade
|
- script:
|
||||||
|
# Test Documentation boxes -
|
||||||
|
# !!! <TYPE>: is not allowed!
|
||||||
|
- grep -Er '^!{3}\s\S+:' docs/*; test $? -ne 0
|
||||||
|
name: doc syntax
|
||||||
|
- script: mypy freqtrade scripts
|
||||||
name: mypy
|
name: mypy
|
||||||
|
|
||||||
- stage: docker
|
- stage: docker
|
||||||
@@ -47,13 +50,10 @@ jobs:
|
|||||||
- build_helpers/publish_docker.sh
|
- build_helpers/publish_docker.sh
|
||||||
name: "Build and test and push docker image"
|
name: "Build and test and push docker image"
|
||||||
|
|
||||||
after_success:
|
|
||||||
- coveralls
|
|
||||||
|
|
||||||
notifications:
|
notifications:
|
||||||
slack:
|
slack:
|
||||||
secure: bKLXmOrx8e2aPZl7W8DA5BdPAXWGpI5UzST33oc1G/thegXcDVmHBTJrBs4sZak6bgAclQQrdZIsRd2eFYzHLalJEaw6pk7hoAw8SvLnZO0ZurWboz7qg2+aZZXfK4eKl/VUe4sM9M4e/qxjkK+yWG7Marg69c4v1ypF7ezUi1fPYILYw8u0paaiX0N5UX8XNlXy+PBlga2MxDjUY70MuajSZhPsY2pDUvYnMY1D/7XN3cFW0g+3O8zXjF0IF4q1Z/1ASQe+eYjKwPQacE+O8KDD+ZJYoTOFBAPllrtpO1jnOPFjNGf3JIbVMZw4bFjIL0mSQaiSUaUErbU3sFZ5Or79rF93XZ81V7uEZ55vD8KMfR2CB1cQJcZcj0v50BxLo0InkFqa0Y8Nra3sbpV4fV5Oe8pDmomPJrNFJnX6ULQhQ1gTCe0M5beKgVms5SITEpt4/Y0CmLUr6iHDT0CUiyMIRWAXdIgbGh1jfaWOMksybeRevlgDsIsNBjXmYI1Sw2ZZR2Eo2u4R6zyfyjOMLwYJ3vgq9IrACv2w5nmf0+oguMWHf6iWi2hiOqhlAN1W74+3HsYQcqnuM3LGOmuCnPprV1oGBqkPXjIFGpy21gNx4vHfO1noLUyJnMnlu2L7SSuN1CdLsnjJ1hVjpJjPfqB4nn8g12x87TqM1bOm+3Q=
|
secure: bKLXmOrx8e2aPZl7W8DA5BdPAXWGpI5UzST33oc1G/thegXcDVmHBTJrBs4sZak6bgAclQQrdZIsRd2eFYzHLalJEaw6pk7hoAw8SvLnZO0ZurWboz7qg2+aZZXfK4eKl/VUe4sM9M4e/qxjkK+yWG7Marg69c4v1ypF7ezUi1fPYILYw8u0paaiX0N5UX8XNlXy+PBlga2MxDjUY70MuajSZhPsY2pDUvYnMY1D/7XN3cFW0g+3O8zXjF0IF4q1Z/1ASQe+eYjKwPQacE+O8KDD+ZJYoTOFBAPllrtpO1jnOPFjNGf3JIbVMZw4bFjIL0mSQaiSUaUErbU3sFZ5Or79rF93XZ81V7uEZ55vD8KMfR2CB1cQJcZcj0v50BxLo0InkFqa0Y8Nra3sbpV4fV5Oe8pDmomPJrNFJnX6ULQhQ1gTCe0M5beKgVms5SITEpt4/Y0CmLUr6iHDT0CUiyMIRWAXdIgbGh1jfaWOMksybeRevlgDsIsNBjXmYI1Sw2ZZR2Eo2u4R6zyfyjOMLwYJ3vgq9IrACv2w5nmf0+oguMWHf6iWi2hiOqhlAN1W74+3HsYQcqnuM3LGOmuCnPprV1oGBqkPXjIFGpy21gNx4vHfO1noLUyJnMnlu2L7SSuN1CdLsnjJ1hVjpJjPfqB4nn8g12x87TqM1bOm+3Q=
|
||||||
cache:
|
cache:
|
||||||
pip: True
|
pip: True
|
||||||
directories:
|
directories:
|
||||||
- /usr/local/lib
|
- $HOME/dependencies
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ Few pointers for contributions:
|
|||||||
- Create your PR against the `develop` branch, not `master`.
|
- Create your PR against the `develop` branch, not `master`.
|
||||||
- New features need to contain unit tests and must be PEP8 conformant (max-line-length = 100).
|
- New features need to contain unit tests and must be PEP8 conformant (max-line-length = 100).
|
||||||
|
|
||||||
If you are unsure, discuss the feature on our [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE)
|
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.
|
or in a [issue](https://github.com/freqtrade/freqtrade/issues) before a PR.
|
||||||
|
|
||||||
## Getting started
|
## Getting started
|
||||||
@@ -28,19 +28,19 @@ make it pass. It means you have introduced a regression.
|
|||||||
#### Test the whole project
|
#### Test the whole project
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pytest freqtrade
|
pytest
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Test only one file
|
#### Test only one file
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pytest freqtrade/tests/test_<file_name>.py
|
pytest tests/test_<file_name>.py
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Test only one method from one file
|
#### Test only one method from one file
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pytest freqtrade/tests/test_<file_name>.py::test_<method_name>
|
pytest tests/test_<file_name>.py::test_<method_name>
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. Test if your code is PEP8 compliant
|
### 2. Test if your code is PEP8 compliant
|
||||||
@@ -114,6 +114,6 @@ Contributors may be given commit privileges. Preference will be given to those w
|
|||||||
1. Access to resources for cross-platform development and testing.
|
1. Access to resources for cross-platform development and testing.
|
||||||
1. Time to devote to the project regularly.
|
1. Time to devote to the project regularly.
|
||||||
|
|
||||||
Beeing a Committer does not grant write permission on `develop` or `master` for security reasons (Users trust FreqTrade with their Exchange API keys).
|
Being a Committer does not grant write permission on `develop` or `master` for security reasons (Users trust FreqTrade with their Exchange API keys).
|
||||||
|
|
||||||
After beeing Committer for some time, a Committer may be named Core Committer and given full repository access.
|
After being Committer for some time, a Committer may be named Core Committer and given full repository access.
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
FROM python:3.7.2-slim-stretch
|
FROM python:3.7.5-slim-stretch
|
||||||
|
|
||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get -y install curl build-essential \
|
&& apt-get -y install curl build-essential libssl-dev \
|
||||||
&& apt-get clean \
|
&& apt-get clean \
|
||||||
&& pip install --upgrade pip
|
&& pip install --upgrade pip
|
||||||
|
|
||||||
@@ -16,9 +16,9 @@ RUN cd /tmp && /tmp/install_ta-lib.sh && rm -r /tmp/*ta-lib*
|
|||||||
ENV LD_LIBRARY_PATH /usr/local/lib
|
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||||
|
|
||||||
# Install dependencies
|
# Install dependencies
|
||||||
COPY requirements.txt /freqtrade/
|
COPY requirements.txt requirements-common.txt requirements-hyperopt.txt /freqtrade/
|
||||||
RUN pip install numpy --no-cache-dir \
|
RUN pip install numpy --no-cache-dir \
|
||||||
&& pip install -r requirements.txt --no-cache-dir
|
&& pip install -r requirements-hyperopt.txt --no-cache-dir
|
||||||
|
|
||||||
# Install and execute
|
# Install and execute
|
||||||
COPY . /freqtrade/
|
COPY . /freqtrade/
|
||||||
|
|||||||
40
Dockerfile.pi
Normal file
40
Dockerfile.pi
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
FROM balenalib/raspberrypi3-debian:stretch
|
||||||
|
|
||||||
|
RUN [ "cross-build-start" ]
|
||||||
|
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get -y install wget curl build-essential libssl-dev libffi-dev \
|
||||||
|
&& apt-get clean
|
||||||
|
|
||||||
|
# Prepare environment
|
||||||
|
RUN mkdir /freqtrade
|
||||||
|
WORKDIR /freqtrade
|
||||||
|
|
||||||
|
# Install TA-lib
|
||||||
|
COPY build_helpers/ta-lib-0.4.0-src.tar.gz /freqtrade/
|
||||||
|
RUN tar -xzf /freqtrade/ta-lib-0.4.0-src.tar.gz \
|
||||||
|
&& cd /freqtrade/ta-lib/ \
|
||||||
|
&& ./configure \
|
||||||
|
&& make \
|
||||||
|
&& make install \
|
||||||
|
&& rm /freqtrade/ta-lib-0.4.0-src.tar.gz
|
||||||
|
|
||||||
|
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||||
|
|
||||||
|
# Install berryconda
|
||||||
|
RUN wget -q https://github.com/jjhelmus/berryconda/releases/download/v2.0.0/Berryconda3-2.0.0-Linux-armv7l.sh \
|
||||||
|
&& bash ./Berryconda3-2.0.0-Linux-armv7l.sh -b \
|
||||||
|
&& rm Berryconda3-2.0.0-Linux-armv7l.sh
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
COPY requirements-common.txt /freqtrade/
|
||||||
|
RUN ~/berryconda3/bin/conda install -y numpy pandas \
|
||||||
|
&& ~/berryconda3/bin/pip install -r requirements-common.txt --no-cache-dir
|
||||||
|
|
||||||
|
# Install and execute
|
||||||
|
COPY . /freqtrade/
|
||||||
|
RUN ~/berryconda3/bin/pip install -e . --no-cache-dir
|
||||||
|
|
||||||
|
RUN [ "cross-build-end" ]
|
||||||
|
|
||||||
|
ENTRYPOINT ["/root/berryconda3/bin/python","./freqtrade/main.py"]
|
||||||
@@ -3,4 +3,4 @@ FROM freqtradeorg/freqtrade:develop
|
|||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get -y install git \
|
&& apt-get -y install git \
|
||||||
&& apt-get clean \
|
&& apt-get clean \
|
||||||
&& pip install git+https://github.com/berlinguyinca/technical
|
&& pip install git+https://github.com/freqtrade/technical
|
||||||
|
|||||||
@@ -2,4 +2,3 @@ include LICENSE
|
|||||||
include README.md
|
include README.md
|
||||||
include config.json.example
|
include config.json.example
|
||||||
recursive-include freqtrade *.py
|
recursive-include freqtrade *.py
|
||||||
include freqtrade/tests/testdata/*.json
|
|
||||||
|
|||||||
46
README.md
46
README.md
@@ -68,39 +68,40 @@ For any other type of installation please refer to [Installation doc](https://ww
|
|||||||
### Bot commands
|
### Bot commands
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: main.py [-h] [-v] [--version] [-c PATH] [-d PATH] [-s NAME]
|
usage: freqtrade [-h] [-v] [--logfile FILE] [--version] [-c PATH] [-d PATH]
|
||||||
[--strategy-path PATH] [--customhyperopt NAME]
|
[-s NAME] [--strategy-path PATH] [--dynamic-whitelist [INT]]
|
||||||
[--dynamic-whitelist [INT]] [--db-url PATH]
|
[--db-url PATH] [--sd-notify]
|
||||||
{backtesting,edge,hyperopt} ...
|
{backtesting,edge,hyperopt} ...
|
||||||
|
|
||||||
Free, open source crypto trading bot
|
Free, open source crypto trading bot
|
||||||
|
|
||||||
positional arguments:
|
positional arguments:
|
||||||
{backtesting,edge,hyperopt}
|
{backtesting,edge,hyperopt}
|
||||||
backtesting backtesting module
|
backtesting Backtesting module.
|
||||||
edge edge module
|
edge Edge module.
|
||||||
hyperopt hyperopt module
|
hyperopt Hyperopt module.
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-v, --verbose verbose mode (-vv for more, -vvv to get all messages)
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
--version show program\'s version number and exit
|
--logfile FILE Log to the file specified
|
||||||
|
--version show program's version number and exit
|
||||||
-c PATH, --config PATH
|
-c PATH, --config PATH
|
||||||
specify configuration file (default: config.json)
|
Specify configuration file (default: None). Multiple
|
||||||
|
--config options may be used.
|
||||||
-d PATH, --datadir PATH
|
-d PATH, --datadir PATH
|
||||||
path to backtest data
|
Path to backtest data.
|
||||||
-s NAME, --strategy NAME
|
-s NAME, --strategy NAME
|
||||||
specify strategy class name (default: DefaultStrategy)
|
Specify strategy class name (default:
|
||||||
--strategy-path PATH specify additional strategy lookup path
|
DefaultStrategy).
|
||||||
--customhyperopt NAME
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
specify hyperopt class name (default:
|
|
||||||
DefaultHyperOpts)
|
|
||||||
--dynamic-whitelist [INT]
|
--dynamic-whitelist [INT]
|
||||||
dynamically generate and update whitelist based on 24h
|
Dynamically generate and update whitelist based on 24h
|
||||||
BaseVolume (default: 20) DEPRECATED.
|
BaseVolume (default: 20). DEPRECATED.
|
||||||
--db-url PATH Override trades database URL, this is useful if
|
--db-url PATH Override trades database URL, this is useful if
|
||||||
dry_run is enabled or in custom deployments (default:
|
dry_run is enabled or in custom deployments (default:
|
||||||
None)
|
None).
|
||||||
|
--sd-notify Notify systemd service manager.
|
||||||
```
|
```
|
||||||
|
|
||||||
### Telegram RPC commands
|
### Telegram RPC commands
|
||||||
@@ -128,7 +129,6 @@ The project is currently setup in two main branches:
|
|||||||
- `master` - This branch contains the latest stable release. The bot 'should' be stable on this branch, and is generally well tested.
|
- `master` - This branch contains the latest stable release. The bot 'should' be stable on this branch, and is generally well tested.
|
||||||
- `feat/*` - These are feature branches, which are being worked on heavily. Please don't use these unless you want to test a specific feature.
|
- `feat/*` - These are feature branches, which are being worked on heavily. Please don't use these unless you want to test a specific feature.
|
||||||
|
|
||||||
|
|
||||||
## A note on Binance
|
## A note on Binance
|
||||||
|
|
||||||
For Binance, please add `"BNB/<STAKE>"` to your blacklist to avoid issues.
|
For Binance, please add `"BNB/<STAKE>"` to your blacklist to avoid issues.
|
||||||
@@ -141,7 +141,7 @@ Accounts having BNB accounts use this to pay for fees - if your first trade happ
|
|||||||
For any questions not covered by the documentation or for further
|
For any questions not covered by the documentation or for further
|
||||||
information about the bot, we encourage you to join our slack channel.
|
information about the bot, we encourage you to join our slack channel.
|
||||||
|
|
||||||
- [Click here to join Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE).
|
- [Click here to join Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE).
|
||||||
|
|
||||||
### [Bugs / Issues](https://github.com/freqtrade/freqtrade/issues?q=is%3Aissue)
|
### [Bugs / Issues](https://github.com/freqtrade/freqtrade/issues?q=is%3Aissue)
|
||||||
|
|
||||||
@@ -172,7 +172,7 @@ 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 neccessity to contribute - maybe start with improving our documentation?
|
||||||
Issues labeled [good first issue](https://github.com/freqtrade/freqtrade/labels/good%20first%20issue) can be good first contributions, and will help get you familiar with the codebase.
|
Issues labeled [good first issue](https://github.com/freqtrade/freqtrade/labels/good%20first%20issue) can be good first contributions, and will help get you familiar with the codebase.
|
||||||
|
|
||||||
**Note** before starting any major new feature work, *please open an issue describing what you are planning to do* or talk to us on [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE). This will ensure that interested parties can give valuable feedback on the feature, and let others know that you are working on it.
|
**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.
|
||||||
|
|
||||||
**Important:** Always create your PR against the `develop` branch, not `master`.
|
**Important:** Always create your PR against the `develop` branch, not `master`.
|
||||||
|
|
||||||
@@ -195,4 +195,4 @@ To run this bot we recommend you a cloud instance with a minimum of:
|
|||||||
- [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
- [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||||
- [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html)
|
- [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html)
|
||||||
- [virtualenv](https://virtualenv.pypa.io/en/stable/installation/) (Recommended)
|
- [virtualenv](https://virtualenv.pypa.io/en/stable/installation/) (Recommended)
|
||||||
- [Docker](https://www.docker.com/products/docker) (Recommended)
|
- [Docker](https://www.docker.com/products/docker) (Recommended)
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
|
import warnings
|
||||||
|
|
||||||
from freqtrade.main import main, set_loggers
|
from freqtrade.main import main
|
||||||
set_loggers()
|
|
||||||
|
warnings.warn(
|
||||||
|
"Deprecated - To continue to run the bot like this, please run `pip install -e .` again.",
|
||||||
|
DeprecationWarning)
|
||||||
main(sys.argv[1:])
|
main(sys.argv[1:])
|
||||||
|
|||||||
@@ -1,8 +1,14 @@
|
|||||||
if [ ! -f "/usr/local/lib/libta_lib.a" ]; then
|
if [ -z "$1" ]; then
|
||||||
|
INSTALL_LOC=/usr/local
|
||||||
|
else
|
||||||
|
INSTALL_LOC=${1}
|
||||||
|
fi
|
||||||
|
echo "Installing to ${INSTALL_LOC}"
|
||||||
|
if [ ! -f "${INSTALL_LOC}/lib/libta_lib.a" ]; then
|
||||||
tar zxvf ta-lib-0.4.0-src.tar.gz
|
tar zxvf ta-lib-0.4.0-src.tar.gz
|
||||||
cd ta-lib \
|
cd ta-lib \
|
||||||
&& sed -i.bak "s|0.00000001|0.000000000000000001 |g" src/ta_func/ta_utility.h \
|
&& sed -i.bak "s|0.00000001|0.000000000000000001 |g" src/ta_func/ta_utility.h \
|
||||||
&& ./configure \
|
&& ./configure --prefix=${INSTALL_LOC}/ \
|
||||||
&& make \
|
&& make \
|
||||||
&& which sudo && sudo make install || make install \
|
&& which sudo && sudo make install || make install \
|
||||||
&& cd ..
|
&& cd ..
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ if [ $? -ne 0 ]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# Run backtest
|
# Run backtest
|
||||||
docker run --rm -it -v $(pwd)/config.json.example:/freqtrade/config.json:ro freqtrade:${TAG} --datadir freqtrade/tests/testdata backtesting
|
docker run --rm -it -v $(pwd)/config.json.example:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} --datadir /tests/testdata backtesting
|
||||||
|
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "failed running backtest"
|
echo "failed running backtest"
|
||||||
|
|||||||
@@ -22,7 +22,10 @@
|
|||||||
"ask_strategy":{
|
"ask_strategy":{
|
||||||
"use_order_book": false,
|
"use_order_book": false,
|
||||||
"order_book_min": 1,
|
"order_book_min": 1,
|
||||||
"order_book_max": 9
|
"order_book_max": 9,
|
||||||
|
"use_sell_signal": true,
|
||||||
|
"sell_profit_only": false,
|
||||||
|
"ignore_roi_if_buy_signal": false
|
||||||
},
|
},
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "bittrex",
|
"name": "bittrex",
|
||||||
@@ -30,7 +33,8 @@
|
|||||||
"secret": "your_exchange_secret",
|
"secret": "your_exchange_secret",
|
||||||
"ccxt_config": {"enableRateLimit": true},
|
"ccxt_config": {"enableRateLimit": true},
|
||||||
"ccxt_async_config": {
|
"ccxt_async_config": {
|
||||||
"enableRateLimit": false
|
"enableRateLimit": true,
|
||||||
|
"rateLimit": 500
|
||||||
},
|
},
|
||||||
"pair_whitelist": [
|
"pair_whitelist": [
|
||||||
"ETH/BTC",
|
"ETH/BTC",
|
||||||
@@ -40,7 +44,7 @@
|
|||||||
"ZEC/BTC",
|
"ZEC/BTC",
|
||||||
"XLM/BTC",
|
"XLM/BTC",
|
||||||
"NXT/BTC",
|
"NXT/BTC",
|
||||||
"POWR/BTC",
|
"TRX/BTC",
|
||||||
"ADA/BTC",
|
"ADA/BTC",
|
||||||
"XMR/BTC"
|
"XMR/BTC"
|
||||||
],
|
],
|
||||||
@@ -48,11 +52,6 @@
|
|||||||
"DOGE/BTC"
|
"DOGE/BTC"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"experimental": {
|
|
||||||
"use_sell_signal": false,
|
|
||||||
"sell_profit_only": false,
|
|
||||||
"ignore_roi_if_buy_signal": false
|
|
||||||
},
|
|
||||||
"edge": {
|
"edge": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"process_throttle_secs": 3600,
|
"process_throttle_secs": 3600,
|
||||||
|
|||||||
@@ -11,8 +11,8 @@
|
|||||||
"sell": 30
|
"sell": 30
|
||||||
},
|
},
|
||||||
"bid_strategy": {
|
"bid_strategy": {
|
||||||
"ask_last_balance": 0.0,
|
|
||||||
"use_order_book": false,
|
"use_order_book": false,
|
||||||
|
"ask_last_balance": 0.0,
|
||||||
"order_book_top": 1,
|
"order_book_top": 1,
|
||||||
"check_depth_of_market": {
|
"check_depth_of_market": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
@@ -22,7 +22,10 @@
|
|||||||
"ask_strategy":{
|
"ask_strategy":{
|
||||||
"use_order_book": false,
|
"use_order_book": false,
|
||||||
"order_book_min": 1,
|
"order_book_min": 1,
|
||||||
"order_book_max": 9
|
"order_book_max": 9,
|
||||||
|
"use_sell_signal": true,
|
||||||
|
"sell_profit_only": false,
|
||||||
|
"ignore_roi_if_buy_signal": false
|
||||||
},
|
},
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "binance",
|
"name": "binance",
|
||||||
@@ -30,7 +33,8 @@
|
|||||||
"secret": "your_exchange_secret",
|
"secret": "your_exchange_secret",
|
||||||
"ccxt_config": {"enableRateLimit": true},
|
"ccxt_config": {"enableRateLimit": true},
|
||||||
"ccxt_async_config": {
|
"ccxt_async_config": {
|
||||||
"enableRateLimit": false
|
"enableRateLimit": true,
|
||||||
|
"rateLimit": 200
|
||||||
},
|
},
|
||||||
"pair_whitelist": [
|
"pair_whitelist": [
|
||||||
"AST/BTC",
|
"AST/BTC",
|
||||||
@@ -50,11 +54,6 @@
|
|||||||
"BNB/BTC"
|
"BNB/BTC"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"experimental": {
|
|
||||||
"use_sell_signal": false,
|
|
||||||
"sell_profit_only": false,
|
|
||||||
"ignore_roi_if_buy_signal": false
|
|
||||||
},
|
|
||||||
"edge": {
|
"edge": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"process_throttle_secs": 3600,
|
"process_throttle_secs": 3600,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
"trailing_stop": false,
|
"trailing_stop": false,
|
||||||
"trailing_stop_positive": 0.005,
|
"trailing_stop_positive": 0.005,
|
||||||
"trailing_stop_positive_offset": 0.0051,
|
"trailing_stop_positive_offset": 0.0051,
|
||||||
|
"trailing_only_offset_is_reached": false,
|
||||||
"minimal_roi": {
|
"minimal_roi": {
|
||||||
"40": 0.0,
|
"40": 0.0,
|
||||||
"30": 0.01,
|
"30": 0.01,
|
||||||
@@ -21,8 +22,8 @@
|
|||||||
"sell": 30
|
"sell": 30
|
||||||
},
|
},
|
||||||
"bid_strategy": {
|
"bid_strategy": {
|
||||||
"ask_last_balance": 0.0,
|
|
||||||
"use_order_book": false,
|
"use_order_book": false,
|
||||||
|
"ask_last_balance": 0.0,
|
||||||
"order_book_top": 1,
|
"order_book_top": 1,
|
||||||
"check_depth_of_market": {
|
"check_depth_of_market": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
@@ -32,33 +33,41 @@
|
|||||||
"ask_strategy":{
|
"ask_strategy":{
|
||||||
"use_order_book": false,
|
"use_order_book": false,
|
||||||
"order_book_min": 1,
|
"order_book_min": 1,
|
||||||
"order_book_max": 9
|
"order_book_max": 9,
|
||||||
|
"use_sell_signal": true,
|
||||||
|
"sell_profit_only": false,
|
||||||
|
"ignore_roi_if_buy_signal": false
|
||||||
},
|
},
|
||||||
"order_types": {
|
"order_types": {
|
||||||
"buy": "limit",
|
"buy": "limit",
|
||||||
"sell": "limit",
|
"sell": "limit",
|
||||||
|
"emergencysell": "market",
|
||||||
"stoploss": "market",
|
"stoploss": "market",
|
||||||
"stoploss_on_exchange": "false",
|
"stoploss_on_exchange": false,
|
||||||
"stoploss_on_exchange_interval": 60
|
"stoploss_on_exchange_interval": 60
|
||||||
},
|
},
|
||||||
"order_time_in_force": {
|
"order_time_in_force": {
|
||||||
"buy": "gtc",
|
"buy": "gtc",
|
||||||
"sell": "gtc",
|
"sell": "gtc"
|
||||||
},
|
},
|
||||||
"pairlist": {
|
"pairlist": {
|
||||||
"method": "VolumePairList",
|
"method": "VolumePairList",
|
||||||
"config": {
|
"config": {
|
||||||
"number_assets": 20,
|
"number_assets": 20,
|
||||||
"sort_key": "quoteVolume"
|
"sort_key": "quoteVolume",
|
||||||
|
"precision_filter": false
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "bittrex",
|
"name": "bittrex",
|
||||||
|
"sandbox": false,
|
||||||
"key": "your_exchange_key",
|
"key": "your_exchange_key",
|
||||||
"secret": "your_exchange_secret",
|
"secret": "your_exchange_secret",
|
||||||
|
"password": "",
|
||||||
"ccxt_config": {"enableRateLimit": true},
|
"ccxt_config": {"enableRateLimit": true},
|
||||||
"ccxt_async_config": {
|
"ccxt_async_config": {
|
||||||
"enableRateLimit": false,
|
"enableRateLimit": false,
|
||||||
|
"rateLimit": 500,
|
||||||
"aiohttp_trust_env": false
|
"aiohttp_trust_env": false
|
||||||
},
|
},
|
||||||
"pair_whitelist": [
|
"pair_whitelist": [
|
||||||
@@ -69,14 +78,15 @@
|
|||||||
"ZEC/BTC",
|
"ZEC/BTC",
|
||||||
"XLM/BTC",
|
"XLM/BTC",
|
||||||
"NXT/BTC",
|
"NXT/BTC",
|
||||||
"POWR/BTC",
|
"TRX/BTC",
|
||||||
"ADA/BTC",
|
"ADA/BTC",
|
||||||
"XMR/BTC"
|
"XMR/BTC"
|
||||||
],
|
],
|
||||||
"pair_blacklist": [
|
"pair_blacklist": [
|
||||||
"DOGE/BTC"
|
"DOGE/BTC"
|
||||||
],
|
],
|
||||||
"outdated_offset": 5
|
"outdated_offset": 5,
|
||||||
|
"markets_refresh_interval": 60
|
||||||
},
|
},
|
||||||
"edge": {
|
"edge": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
@@ -93,22 +103,25 @@
|
|||||||
"max_trade_duration_minute": 1440,
|
"max_trade_duration_minute": 1440,
|
||||||
"remove_pumps": false
|
"remove_pumps": false
|
||||||
},
|
},
|
||||||
"experimental": {
|
|
||||||
"use_sell_signal": false,
|
|
||||||
"sell_profit_only": false,
|
|
||||||
"ignore_roi_if_buy_signal": false
|
|
||||||
},
|
|
||||||
"telegram": {
|
"telegram": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"token": "your_telegram_token",
|
"token": "your_telegram_token",
|
||||||
"chat_id": "your_telegram_chat_id"
|
"chat_id": "your_telegram_chat_id"
|
||||||
},
|
},
|
||||||
|
"api_server": {
|
||||||
|
"enabled": false,
|
||||||
|
"listen_ip_address": "127.0.0.1",
|
||||||
|
"listen_port": 8080,
|
||||||
|
"username": "freqtrader",
|
||||||
|
"password": "SuperSecurePassword"
|
||||||
|
},
|
||||||
"db_url": "sqlite:///tradesv3.sqlite",
|
"db_url": "sqlite:///tradesv3.sqlite",
|
||||||
"initial_state": "running",
|
"initial_state": "running",
|
||||||
"forcebuy_enable": false,
|
"forcebuy_enable": false,
|
||||||
"internals": {
|
"internals": {
|
||||||
"process_throttle_secs": 5
|
"process_throttle_secs": 5,
|
||||||
|
"heartbeat_interval": 60
|
||||||
},
|
},
|
||||||
"strategy": "DefaultStrategy",
|
"strategy": "DefaultStrategy",
|
||||||
"strategy_path": "/some/folder/"
|
"strategy_path": "user_data/strategies/"
|
||||||
}
|
}
|
||||||
|
|||||||
75
config_kraken.json.example
Normal file
75
config_kraken.json.example
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
{
|
||||||
|
"max_open_trades": 5,
|
||||||
|
"stake_currency": "EUR",
|
||||||
|
"stake_amount": 10,
|
||||||
|
"fiat_display_currency": "EUR",
|
||||||
|
"ticker_interval" : "5m",
|
||||||
|
"dry_run": true,
|
||||||
|
"trailing_stop": false,
|
||||||
|
"unfilledtimeout": {
|
||||||
|
"buy": 10,
|
||||||
|
"sell": 30
|
||||||
|
},
|
||||||
|
"bid_strategy": {
|
||||||
|
"use_order_book": false,
|
||||||
|
"ask_last_balance": 0.0,
|
||||||
|
"order_book_top": 1,
|
||||||
|
"check_depth_of_market": {
|
||||||
|
"enabled": false,
|
||||||
|
"bids_to_ask_delta": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ask_strategy":{
|
||||||
|
"use_order_book": false,
|
||||||
|
"order_book_min": 1,
|
||||||
|
"order_book_max": 9,
|
||||||
|
"use_sell_signal": true,
|
||||||
|
"sell_profit_only": false,
|
||||||
|
"ignore_roi_if_buy_signal": false
|
||||||
|
|
||||||
|
},
|
||||||
|
"exchange": {
|
||||||
|
"name": "kraken",
|
||||||
|
"key": "",
|
||||||
|
"secret": "",
|
||||||
|
"ccxt_config": {"enableRateLimit": true},
|
||||||
|
"ccxt_async_config": {
|
||||||
|
"enableRateLimit": true,
|
||||||
|
"rateLimit": 1000
|
||||||
|
},
|
||||||
|
"pair_whitelist": [
|
||||||
|
"ETH/EUR",
|
||||||
|
"BTC/EUR",
|
||||||
|
"BCH/EUR"
|
||||||
|
],
|
||||||
|
"pair_blacklist": [
|
||||||
|
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"edge": {
|
||||||
|
"enabled": false,
|
||||||
|
"process_throttle_secs": 3600,
|
||||||
|
"calculate_since_number_of_days": 7,
|
||||||
|
"capital_available_percentage": 0.5,
|
||||||
|
"allowed_risk": 0.01,
|
||||||
|
"stoploss_range_min": -0.01,
|
||||||
|
"stoploss_range_max": -0.1,
|
||||||
|
"stoploss_range_step": -0.01,
|
||||||
|
"minimum_winrate": 0.60,
|
||||||
|
"minimum_expectancy": 0.20,
|
||||||
|
"min_trade_number": 10,
|
||||||
|
"max_trade_duration_minute": 1440,
|
||||||
|
"remove_pumps": false
|
||||||
|
},
|
||||||
|
"telegram": {
|
||||||
|
"enabled": false,
|
||||||
|
"token": "your_telegram_token",
|
||||||
|
"chat_id": "your_telegram_chat_id"
|
||||||
|
},
|
||||||
|
"initial_state": "running",
|
||||||
|
"forcebuy_enable": false,
|
||||||
|
"internals": {
|
||||||
|
"process_throttle_secs": 5
|
||||||
|
},
|
||||||
|
"download_trades": true
|
||||||
|
}
|
||||||
20
docker-compose.develop.yml
Normal file
20
docker-compose.develop.yml
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
version: '3'
|
||||||
|
services:
|
||||||
|
freqtrade_develop:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: "./Dockerfile.develop"
|
||||||
|
volumes:
|
||||||
|
- ".:/freqtrade"
|
||||||
|
entrypoint:
|
||||||
|
- "freqtrade"
|
||||||
|
|
||||||
|
freqtrade_bash:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: "./Dockerfile.develop"
|
||||||
|
volumes:
|
||||||
|
- ".:/freqtrade"
|
||||||
|
entrypoint:
|
||||||
|
- "/bin/bash"
|
||||||
8
docker-compose.yml
Normal file
8
docker-compose.yml
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
---
|
||||||
|
version: '3'
|
||||||
|
services:
|
||||||
|
freqtrade:
|
||||||
|
image: freqtradeorg/freqtrade:master
|
||||||
|
volumes:
|
||||||
|
- "./user_data:/freqtrade/user_data"
|
||||||
|
- "./config.json:/freqtrade/config.json"
|
||||||
BIN
docs/assets/plot-dataframe.png
Normal file
BIN
docs/assets/plot-dataframe.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 173 KiB |
BIN
docs/assets/plot-profit.png
Normal file
BIN
docs/assets/plot-profit.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 121 KiB |
@@ -1,164 +1,109 @@
|
|||||||
# Backtesting
|
# Backtesting
|
||||||
|
|
||||||
This page explains how to validate your strategy performance by using
|
This page explains how to validate your strategy performance by using Backtesting.
|
||||||
Backtesting.
|
|
||||||
|
Backtesting requires historic data to be available.
|
||||||
|
To learn how to get data for the pairs and exchange you're interested in, head over to the [Data Downloading](data-download.md) section of the documentation.
|
||||||
|
|
||||||
## Test your strategy with Backtesting
|
## Test your strategy with Backtesting
|
||||||
|
|
||||||
Now you have good Buy and Sell strategies, you want to test it against
|
Now you have good Buy and Sell strategies and some historic data, you want to test it against
|
||||||
real data. This is what we call
|
real data. This is what we call
|
||||||
[backtesting](https://en.wikipedia.org/wiki/Backtesting).
|
[backtesting](https://en.wikipedia.org/wiki/Backtesting).
|
||||||
|
|
||||||
Backtesting will use the crypto-currencies (pair) from your config file
|
Backtesting will use the crypto-currencies (pairs) from your config file
|
||||||
and load static tickers located in
|
and load ticker data from `user_data/data/<exchange>` by default.
|
||||||
[/freqtrade/tests/testdata](https://github.com/freqtrade/freqtrade/tree/develop/freqtrade/tests/testdata).
|
If no data is available for the exchange / pair / ticker interval combination, backtesting will
|
||||||
If the 5 min and 1 min ticker for the crypto-currencies to test is not
|
ask you to download them first using `freqtrade download-data`.
|
||||||
already in the `testdata` folder, backtesting will download them
|
For details on downloading, please refer to the [Data Downloading](data-download.md) section in the documentation.
|
||||||
automatically. Testdata files will not be updated until you specify it.
|
|
||||||
|
|
||||||
The result of backtesting will confirm you if your bot has better odds of making a profit than a loss.
|
The result of backtesting will confirm if your bot has better odds of making a profit than a loss.
|
||||||
|
|
||||||
The backtesting is very easy with freqtrade.
|
|
||||||
|
|
||||||
### Run a backtesting against the currencies listed in your config file
|
### Run a backtesting against the currencies listed in your config file
|
||||||
|
|
||||||
#### With 5 min tickers (Per default)
|
#### With 5 min tickers (Per default)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py backtesting
|
freqtrade backtesting
|
||||||
```
|
```
|
||||||
|
|
||||||
#### With 1 min tickers
|
#### With 1 min tickers
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py backtesting --ticker-interval 1m
|
freqtrade backtesting --ticker-interval 1m
|
||||||
```
|
|
||||||
|
|
||||||
#### Update cached pairs with the latest data
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python3 ./freqtrade/main.py backtesting --refresh-pairs-cached
|
|
||||||
```
|
|
||||||
|
|
||||||
#### With live data (do not alter your testdata files)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python3 ./freqtrade/main.py backtesting --live
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Using a different on-disk ticker-data source
|
#### Using a different on-disk ticker-data source
|
||||||
|
|
||||||
|
Assume you downloaded the history data from the Bittrex exchange and kept it in the `user_data/data/bittrex-20180101` directory.
|
||||||
|
You can then use this data for backtesting as follows:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py backtesting --datadir freqtrade/tests/testdata-20180101
|
freqtrade --datadir user_data/data/bittrex-20180101 backtesting
|
||||||
```
|
```
|
||||||
|
|
||||||
#### With a (custom) strategy file
|
#### With a (custom) strategy file
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py -s TestStrategy backtesting
|
freqtrade -s SampleStrategy backtesting
|
||||||
```
|
```
|
||||||
|
|
||||||
Where `-s TestStrategy` refers to the class name within the strategy file `test_strategy.py` found in the `freqtrade/user_data/strategies` directory
|
Where `-s SampleStrategy` refers to the class name within the strategy file `sample_strategy.py` found in the `freqtrade/user_data/strategies` directory.
|
||||||
|
|
||||||
|
#### Comparing multiple Strategies
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade backtesting --strategy-list SampleStrategy1 AwesomeStrategy --ticker-interval 5m
|
||||||
|
```
|
||||||
|
|
||||||
|
Where `SampleStrategy1` and `AwesomeStrategy` refer to class names of strategies.
|
||||||
|
|
||||||
#### Exporting trades to file
|
#### Exporting trades to file
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py backtesting --export trades
|
freqtrade backtesting --export trades
|
||||||
```
|
```
|
||||||
|
|
||||||
The exported trades can be read using the following code for manual analysis, or can be used by the plotting script `plot_dataframe.py` in the scripts folder.
|
The exported trades can be used for [further analysis](#further-backtest-result-analysis), or can be used by the plotting script `plot_dataframe.py` in the scripts directory.
|
||||||
|
|
||||||
``` python
|
|
||||||
import json
|
|
||||||
from pathlib import Path
|
|
||||||
import pandas as pd
|
|
||||||
|
|
||||||
filename=Path('user_data/backtest_data/backtest-result.json')
|
|
||||||
|
|
||||||
with filename.open() as file:
|
|
||||||
data = json.load(file)
|
|
||||||
|
|
||||||
columns = ["pair", "profit", "opents", "closets", "index", "duration",
|
|
||||||
"open_rate", "close_rate", "open_at_end", "sell_reason"]
|
|
||||||
df = pd.DataFrame(data, columns=columns)
|
|
||||||
|
|
||||||
df['opents'] = pd.to_datetime(df['opents'],
|
|
||||||
unit='s',
|
|
||||||
utc=True,
|
|
||||||
infer_datetime_format=True
|
|
||||||
)
|
|
||||||
df['closets'] = pd.to_datetime(df['closets'],
|
|
||||||
unit='s',
|
|
||||||
utc=True,
|
|
||||||
infer_datetime_format=True
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
If you have some ideas for interesting / helpful backtest data analysis, feel free to submit a PR so the community can benefit from it.
|
|
||||||
|
|
||||||
#### Exporting trades to file specifying a custom filename
|
#### Exporting trades to file specifying a custom filename
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py backtesting --export trades --export-filename=backtest_teststrategy.json
|
freqtrade backtesting --export trades --export-filename=backtest_samplestrategy.json
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Running backtest with smaller testset
|
#### Supplying custom fee value
|
||||||
|
|
||||||
Use the `--timerange` argument to change how much of the testset
|
Sometimes your account has certain fee rebates (fee reductions starting with a certain account size or monthly volume), which are not visible to ccxt.
|
||||||
you want to use. The last N ticks/timeframes will be used.
|
To account for this in backtesting, you can use `--fee 0.001` to supply this value to backtesting.
|
||||||
|
This fee must be a percentage, and will be applied twice (once for trade entry, and once for trade exit).
|
||||||
Example:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py backtesting --timerange=-200
|
freqtrade backtesting --fee 0.001
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Advanced use of timerange
|
|
||||||
|
|
||||||
Doing `--timerange=-200` will get the last 200 timeframes
|
#### Running backtest with smaller testset by using timerange
|
||||||
from your inputdata. You can also specify specific dates,
|
|
||||||
or a range span indexed by start and stop.
|
Use the `--timerange` argument to change how much of the testset you want to use.
|
||||||
|
|
||||||
|
|
||||||
|
For example, running backtesting with the `--timerange=20190501-` option will use all available data starting with May 1st, 2019 from your inputdata.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade backtesting --timerange=20190501-
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also specify particular dates or a range span indexed by start and stop.
|
||||||
|
|
||||||
The full timerange specification:
|
The full timerange specification:
|
||||||
|
|
||||||
- Use last 123 tickframes of data: `--timerange=-123`
|
|
||||||
- Use first 123 tickframes of data: `--timerange=123-`
|
|
||||||
- Use tickframes from line 123 through 456: `--timerange=123-456`
|
|
||||||
- Use tickframes till 2018/01/31: `--timerange=-20180131`
|
- Use tickframes till 2018/01/31: `--timerange=-20180131`
|
||||||
- Use tickframes since 2018/01/31: `--timerange=20180131-`
|
- Use tickframes since 2018/01/31: `--timerange=20180131-`
|
||||||
- Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
|
- Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
|
||||||
- Use tickframes between POSIX timestamps 1527595200 1527618600:
|
- Use tickframes between POSIX timestamps 1527595200 1527618600:
|
||||||
`--timerange=1527595200-1527618600`
|
`--timerange=1527595200-1527618600`
|
||||||
|
|
||||||
#### Downloading new set of ticker data
|
|
||||||
|
|
||||||
To download new set of backtesting ticker data, you can use a download script.
|
|
||||||
|
|
||||||
If you are using Binance for example:
|
|
||||||
|
|
||||||
- create a folder `user_data/data/binance` and copy `pairs.json` in that folder.
|
|
||||||
- update the `pairs.json` to contain the currency pairs you are interested in.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
mkdir -p user_data/data/binance
|
|
||||||
cp freqtrade/tests/testdata/pairs.json user_data/data/binance
|
|
||||||
```
|
|
||||||
|
|
||||||
Then run:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python scripts/download_backtest_data.py --exchange binance
|
|
||||||
```
|
|
||||||
|
|
||||||
This will download ticker data for all the currency pairs you defined in `pairs.json`.
|
|
||||||
|
|
||||||
- To use a different folder than the exchange specific default, use `--export user_data/data/some_directory`.
|
|
||||||
- To change the exchange used to download the tickers, use `--exchange`. Default is `bittrex`.
|
|
||||||
- To use `pairs.json` from some other folder, use `--pairs-file some_other_dir/pairs.json`.
|
|
||||||
- To download ticker data for only 10 days, use `--days 10`.
|
|
||||||
- Use `--timeframes` to specify which tickers to download. Default is `--timeframes 1m 5m` which will download 1-minute and 5-minute tickers.
|
|
||||||
|
|
||||||
For help about backtesting usage, please refer to [Backtesting commands](#backtesting-commands).
|
|
||||||
|
|
||||||
## Understand the backtesting result
|
## Understand the backtesting result
|
||||||
|
|
||||||
The most important in the backtesting is to understand the result.
|
The most important in the backtesting is to understand the result.
|
||||||
@@ -203,11 +148,12 @@ A backtesting result will look like that:
|
|||||||
| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 | 0 |
|
| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 | 0 |
|
||||||
```
|
```
|
||||||
|
|
||||||
The 1st table will contain all trades the bot made.
|
The 1st table contains all trades the bot made, including "left open trades".
|
||||||
|
|
||||||
The 2nd table will contain a recap of sell reasons.
|
The 2nd table contains a recap of sell reasons.
|
||||||
|
|
||||||
The 3rd table will contain all trades the bot had to `forcesell` at the end of the backtest period to present a full picture.
|
The 3rd table contains all trades the bot had to `forcesell` at the end of the backtest period to present a full picture.
|
||||||
|
This is necessary to simulate realistic behaviour, since the backtest period has to end at some point, while realistically, you could leave the bot running forever.
|
||||||
These trades are also included in the first table, but are extracted separately for clarity.
|
These trades are also included in the first table, but are extracted separately for clarity.
|
||||||
|
|
||||||
The last line will give you the overall performance of your strategy,
|
The last line will give you the overall performance of your strategy,
|
||||||
@@ -217,22 +163,16 @@ here:
|
|||||||
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 243 |
|
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 243 |
|
||||||
```
|
```
|
||||||
|
|
||||||
We understand the bot has made `429` trades for an average duration of
|
The bot has made `429` trades for an average duration of `4:12:00`, with a performance of `76.20%` (profit), that means it has
|
||||||
`4:12:00`, with a performance of `76.20%` (profit), that means it has
|
|
||||||
earned a total of `0.00762792 BTC` starting with a capital of 0.01 BTC.
|
earned a total of `0.00762792 BTC` starting with a capital of 0.01 BTC.
|
||||||
|
|
||||||
The column `avg profit %` shows the average profit for all trades made while the column `cum profit %` sums all the profits/losses.
|
The column `avg profit %` shows the average profit for all trades made while the column `cum profit %` sums up all the profits/losses.
|
||||||
The column `tot profit %` shows instead the total profit % in relation to allocated capital
|
The column `tot profit %` shows instead the total profit % in relation to allocated capital (`max_open_trades * stake_amount`).
|
||||||
(`max_open_trades * stake_amount`). In the above results we have `max_open_trades=2 stake_amount=0.005` in config
|
In the above results we have `max_open_trades=2` and `stake_amount=0.005` in config so `tot_profit %` will be `(76.20/100) * (0.005 * 2) =~ 0.00762792 BTC`.
|
||||||
so `(76.20/100) * (0.005 * 2) =~ 0.00762792 BTC`.
|
|
||||||
|
|
||||||
As you will see your strategy performance will be influenced by your buy
|
Your strategy performance is influenced by your buy strategy, your sell strategy, and also by the `minimal_roi` and `stop_loss` you have set.
|
||||||
strategy, your sell strategy, and also by the `minimal_roi` and
|
|
||||||
`stop_loss` you have set.
|
|
||||||
|
|
||||||
As for an example if your minimal_roi is only `"0": 0.01`. You cannot
|
For example, if your `minimal_roi` is only `"0": 0.01` you cannot expect the bot to make more profit than 1% (because it will sell every time a trade reaches 1%).
|
||||||
expect the bot to make more profit than 1% (because it will sell every
|
|
||||||
time a trade will reach 1%).
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
"minimal_roi": {
|
"minimal_roi": {
|
||||||
@@ -241,26 +181,49 @@ time a trade will reach 1%).
|
|||||||
```
|
```
|
||||||
|
|
||||||
On the other hand, if you set a too high `minimal_roi` like `"0": 0.55`
|
On the other hand, if you set a too high `minimal_roi` like `"0": 0.55`
|
||||||
(55%), there is a lot of chance that the bot will never reach this
|
(55%), there is almost no chance that the bot will ever reach this profit.
|
||||||
profit. Hence, keep in mind that your performance is a mix of your
|
Hence, keep in mind that your performance is an integral mix of all different elements of the strategy, your configuration, and the crypto-currency pairs you have set up.
|
||||||
strategies, your configuration, and the crypto-currency you have set up.
|
|
||||||
|
### Assumptions made by backtesting
|
||||||
|
|
||||||
|
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.
|
||||||
|
- 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%)
|
||||||
|
- Stoploss sells happen exactly at stoploss price, even if low was lower
|
||||||
|
- Trailing stoploss
|
||||||
|
- High happens first - adjusting stoploss
|
||||||
|
- Low uses the adjusted stoploss (so sells with large high-low difference are backtested correctly)
|
||||||
|
- Sell-reason does not explain if a trade was positive or negative, just what triggered the sell (this can look odd if negative ROI values are used)
|
||||||
|
|
||||||
|
Taking these assumptions, backtesting tries to mirror real trading as closely as possible. However, backtesting will **never** replace running a strategy in dry-run mode.
|
||||||
|
Also, keep in mind that past results don't guarantee future success.
|
||||||
|
|
||||||
|
In addition to the above assumptions, strategy authors should carefully read the [Common Mistakes](strategy-customization.md#common-mistakes-when-developing-strategies) section, to avoid using data in backtesting which is not available in real market conditions.
|
||||||
|
|
||||||
|
### Further backtest-result analysis
|
||||||
|
|
||||||
|
To further analyze your backtest results, you can [export the trades](#exporting-trades-to-file).
|
||||||
|
You can then load the trades to perform further analysis as shown in our [data analysis](data-analysis.md#backtesting) backtesting section.
|
||||||
|
|
||||||
## Backtesting multiple strategies
|
## Backtesting multiple strategies
|
||||||
|
|
||||||
To backtest multiple strategies, a list of Strategies can be provided.
|
To compare multiple strategies, a list of Strategies can be provided to backtesting.
|
||||||
|
|
||||||
This is limited to 1 ticker-interval per run, however, data is only loaded once from disk so if you have multiple
|
This is limited to 1 ticker-interval per run, however, data is only loaded once from disk so if you have multiple
|
||||||
strategies you'd like to compare, this should give a nice runtime boost.
|
strategies you'd like to compare, this will give a nice runtime boost.
|
||||||
|
|
||||||
All listed Strategies need to be in the same folder.
|
All listed Strategies need to be in the same directory.
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade backtesting --timerange 20180401-20180410 --ticker-interval 5m --strategy-list Strategy001 Strategy002 --export trades
|
freqtrade backtesting --timerange 20180401-20180410 --ticker-interval 5m --strategy-list Strategy001 Strategy002 --export trades
|
||||||
```
|
```
|
||||||
|
|
||||||
This will save the results to `user_data/backtest_data/backtest-result-<strategy>.json`, injecting the strategy-name into the target filename.
|
This will save the results to `user_data/backtest_results/backtest-result-<strategy>.json`, injecting the strategy-name into the target filename.
|
||||||
There will be an additional table comparing win/losses of the different strategies (identical to the "Total" row in the first table).
|
There will be an additional table comparing win/losses of the different strategies (identical to the "Total" row in the first table).
|
||||||
Detailed output for all strategies one after the other will be available, so make sure to scroll up.
|
Detailed output for all strategies one after the other will be available, so make sure to scroll up to see the details per strategy.
|
||||||
|
|
||||||
```
|
```
|
||||||
=========================================================== Strategy Summary ===========================================================
|
=========================================================== Strategy Summary ===========================================================
|
||||||
|
|||||||
@@ -2,54 +2,123 @@
|
|||||||
|
|
||||||
This page explains the different parameters of the bot and how to run it.
|
This page explains the different parameters of the bot and how to run it.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
If you've used `setup.sh`, don't forget to activate your virtual environment (`source .env/bin/activate`) before running freqtrade commands.
|
||||||
|
|
||||||
|
|
||||||
## Bot commands
|
## Bot commands
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: main.py [-h] [-v] [--version] [-c PATH] [-d PATH] [-s NAME]
|
usage: freqtrade [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||||
[--strategy-path PATH] [--customhyperopt NAME]
|
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||||
[--dynamic-whitelist [INT]] [--db-url PATH]
|
[--db-url PATH] [--sd-notify]
|
||||||
{backtesting,edge,hyperopt} ...
|
{backtesting,edge,hyperopt,create-userdir,list-exchanges,list-timeframes,download-data,plot-dataframe,plot-profit}
|
||||||
|
...
|
||||||
|
|
||||||
Free, open source crypto trading bot
|
Free, open source crypto trading bot
|
||||||
|
|
||||||
positional arguments:
|
positional arguments:
|
||||||
{backtesting,edge,hyperopt}
|
{backtesting,edge,hyperopt,create-userdir,list-exchanges,list-timeframes,download-data,plot-dataframe,plot-profit}
|
||||||
backtesting backtesting module
|
backtesting Backtesting module.
|
||||||
edge edge module
|
edge Edge module.
|
||||||
hyperopt hyperopt module
|
hyperopt Hyperopt module.
|
||||||
|
create-userdir Create user-data directory.
|
||||||
|
list-exchanges Print available exchanges.
|
||||||
|
list-timeframes Print available ticker intervals (timeframes) for the
|
||||||
|
exchange.
|
||||||
|
download-data Download backtesting data.
|
||||||
|
plot-dataframe Plot candles with indicators.
|
||||||
|
plot-profit Generate plot showing profits.
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-v, --verbose verbose mode (-vv for more, -vvv to get all messages)
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
--version show program\'s version number and exit
|
--logfile FILE Log to the file specified.
|
||||||
|
-V, --version show program's version number and exit
|
||||||
-c PATH, --config PATH
|
-c PATH, --config PATH
|
||||||
specify configuration file (default: config.json)
|
Specify configuration file (default: `config.json`).
|
||||||
|
Multiple --config options may be used. Can be set to
|
||||||
|
`-` to read config from stdin.
|
||||||
-d PATH, --datadir PATH
|
-d PATH, --datadir PATH
|
||||||
path to backtest data
|
Path to directory with historical backtesting data.
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
-s NAME, --strategy NAME
|
-s NAME, --strategy NAME
|
||||||
specify strategy class name (default: DefaultStrategy)
|
Specify strategy class name (default:
|
||||||
--strategy-path PATH specify additional strategy lookup path
|
`DefaultStrategy`).
|
||||||
--customhyperopt NAME
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
specify hyperopt class name (default:
|
--db-url PATH Override trades database URL, this is useful in custom
|
||||||
DefaultHyperOpts)
|
deployments (default: `sqlite:///tradesv3.sqlite` for
|
||||||
--dynamic-whitelist [INT]
|
Live Run mode, `sqlite://` for Dry Run).
|
||||||
dynamically generate and update whitelist based on 24h
|
--sd-notify Notify systemd service manager.
|
||||||
BaseVolume (default: 20) DEPRECATED.
|
|
||||||
--db-url PATH Override trades database URL, this is useful if
|
|
||||||
dry_run is enabled or in custom deployments (default:
|
|
||||||
None)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### How to use a different config file?
|
### How to specify which configuration file be used?
|
||||||
|
|
||||||
The bot allows you to select which config file you want to use. Per
|
The bot allows you to select which configuration file you want to use by means of
|
||||||
default, the bot will load the file `./config.json`
|
the `-c/--config` command line option:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py -c path/far/far/away/config.json
|
freqtrade -c path/far/far/away/config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Per default, the bot loads the `config.json` configuration file from the current
|
||||||
|
working directory.
|
||||||
|
|
||||||
|
### How to use multiple configuration files?
|
||||||
|
|
||||||
|
The bot allows you to use multiple configuration files by specifying multiple
|
||||||
|
`-c/--config` options in the command line. Configuration parameters
|
||||||
|
defined in the latter configuration files override parameters with the same name
|
||||||
|
defined in the previous configuration files specified in the command line earlier.
|
||||||
|
|
||||||
|
For example, you can make a separate configuration file with your key and secrete
|
||||||
|
for the Exchange you use for trading, specify default configuration file with
|
||||||
|
empty key and secrete values while running in the Dry Mode (which does not actually
|
||||||
|
require them):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade -c ./config.json
|
||||||
|
```
|
||||||
|
|
||||||
|
and specify both configuration files when running in the normal Live Trade Mode:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade -c ./config.json -c path/to/secrets/keys.config.json
|
||||||
|
```
|
||||||
|
|
||||||
|
This could help you hide your private Exchange key and Exchange secrete on you local machine
|
||||||
|
by setting appropriate file permissions for the file which contains actual secrets and, additionally,
|
||||||
|
prevent unintended disclosure of sensitive private data when you publish examples
|
||||||
|
of your configuration in the project issues or in the Internet.
|
||||||
|
|
||||||
|
See more details on this technique with examples in the documentation page on
|
||||||
|
[configuration](configuration.md).
|
||||||
|
|
||||||
|
### Where to store custom data
|
||||||
|
|
||||||
|
Freqtrade allows the creation of a user-data directory using `freqtrade create-userdir --userdir someDirectory`.
|
||||||
|
This directory will look as follows:
|
||||||
|
|
||||||
|
```
|
||||||
|
user_data/
|
||||||
|
├── backtest_results
|
||||||
|
├── data
|
||||||
|
├── hyperopts
|
||||||
|
├── hyperopt_results
|
||||||
|
├── plot
|
||||||
|
└── strategies
|
||||||
|
```
|
||||||
|
|
||||||
|
You can add the entry "user_data_dir" setting to your configuration, to always point your bot to this directory.
|
||||||
|
Alternatively, pass in `--userdir` to every command.
|
||||||
|
The bot will fail to start if the directory does not exist, but will create necessary subdirectories.
|
||||||
|
|
||||||
|
This directory should contain your custom strategies, custom hyperopts and hyperopt loss functions, backtesting historical data (downloaded using either backtesting command or the download script) and plot outputs.
|
||||||
|
|
||||||
|
It is recommended to use version control to keep track of changes to your strategies.
|
||||||
|
|
||||||
### How to use **--strategy**?
|
### How to use **--strategy**?
|
||||||
|
|
||||||
This parameter will allow you to load your custom strategy class.
|
This parameter will allow you to load your custom strategy class.
|
||||||
@@ -65,54 +134,29 @@ In `user_data/strategies` you have a file `my_awesome_strategy.py` which has
|
|||||||
a strategy class called `AwesomeStrategy` to load it:
|
a strategy class called `AwesomeStrategy` to load it:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy
|
freqtrade --strategy AwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
If the bot does not find your strategy file, it will display in an error
|
If the bot does not find your strategy file, it will display in an error
|
||||||
message the reason (File not found, or errors in your code).
|
message the reason (File not found, or errors in your code).
|
||||||
|
|
||||||
Learn more about strategy file in [optimize your bot](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-optimization.md).
|
Learn more about strategy file in
|
||||||
|
[Strategy Customization](strategy-customization.md).
|
||||||
|
|
||||||
### How to use **--strategy-path**?
|
### How to use **--strategy-path**?
|
||||||
|
|
||||||
This parameter allows you to add an additional strategy lookup path, which gets
|
This parameter allows you to add an additional strategy lookup path, which gets
|
||||||
checked before the default locations (The passed path must be a folder!):
|
checked before the default locations (The passed path must be a directory!):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy --strategy-path /some/folder
|
freqtrade --strategy AwesomeStrategy --strategy-path /some/directory
|
||||||
```
|
```
|
||||||
|
|
||||||
#### How to install a strategy?
|
#### How to install a strategy?
|
||||||
|
|
||||||
This is very simple. Copy paste your strategy file into the folder
|
This is very simple. Copy paste your strategy file into the directory
|
||||||
`user_data/strategies` or use `--strategy-path`. And voila, the bot is ready to use it.
|
`user_data/strategies` or use `--strategy-path`. And voila, the bot is ready to use it.
|
||||||
|
|
||||||
### How to use **--dynamic-whitelist**?
|
|
||||||
|
|
||||||
!!! danger "DEPRECATED"
|
|
||||||
Dynamic-whitelist is deprecated. Please move your configurations to the configuration as outlined [here](/configuration/#dynamic-pairlists)
|
|
||||||
|
|
||||||
Per default `--dynamic-whitelist` will retrieve the 20 currencies based
|
|
||||||
on BaseVolume. This value can be changed when you run the script.
|
|
||||||
|
|
||||||
**By Default**
|
|
||||||
Get the 20 currencies based on BaseVolume.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python3 ./freqtrade/main.py --dynamic-whitelist
|
|
||||||
```
|
|
||||||
|
|
||||||
**Customize the number of currencies to retrieve**
|
|
||||||
Get the 30 currencies based on BaseVolume.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python3 ./freqtrade/main.py --dynamic-whitelist 30
|
|
||||||
```
|
|
||||||
|
|
||||||
**Exception**
|
|
||||||
`--dynamic-whitelist` must be greater than 0. If you enter 0 or a
|
|
||||||
negative value (e.g -2), `--dynamic-whitelist` will use the default
|
|
||||||
value (20).
|
|
||||||
|
|
||||||
### How to use **--db-url**?
|
### How to use **--db-url**?
|
||||||
|
|
||||||
When you run the bot in Dry-run mode, per default no transactions are
|
When you run the bot in Dry-run mode, per default no transactions are
|
||||||
@@ -121,7 +165,7 @@ using `--db-url`. This can also be used to specify a custom database
|
|||||||
in production mode. Example command:
|
in production mode. Example command:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite
|
freqtrade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite
|
||||||
```
|
```
|
||||||
|
|
||||||
## Backtesting commands
|
## Backtesting commands
|
||||||
@@ -129,59 +173,57 @@ python3 ./freqtrade/main.py -c config.json --db-url sqlite:///tradesv3.dry_run.s
|
|||||||
Backtesting also uses the config specified via `-c/--config`.
|
Backtesting also uses the config specified via `-c/--config`.
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: main.py backtesting [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
usage: freqtrade backtesting [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
||||||
[--eps] [--dmmp] [-l] [-r]
|
[--max_open_trades INT]
|
||||||
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
[--stake_amount STAKE_AMOUNT] [--fee FLOAT]
|
||||||
[--export EXPORT] [--export-filename PATH]
|
[--eps] [--dmmp]
|
||||||
|
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
||||||
|
[--export EXPORT] [--export-filename PATH]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||||
specify ticker interval (1m, 5m, 30m, 1h, 1d)
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
|
`1d`).
|
||||||
--timerange TIMERANGE
|
--timerange TIMERANGE
|
||||||
specify what timerange of data to use.
|
Specify what timerange of data to use.
|
||||||
|
--max_open_trades INT
|
||||||
|
Specify max_open_trades to use.
|
||||||
|
--stake_amount STAKE_AMOUNT
|
||||||
|
Specify stake_amount.
|
||||||
|
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
|
||||||
|
entry and exit).
|
||||||
--eps, --enable-position-stacking
|
--eps, --enable-position-stacking
|
||||||
Allow buying the same pair multiple times (position
|
Allow buying the same pair multiple times (position
|
||||||
stacking)
|
stacking).
|
||||||
--dmmp, --disable-max-market-positions
|
--dmmp, --disable-max-market-positions
|
||||||
Disable applying `max_open_trades` during backtest
|
Disable applying `max_open_trades` during backtest
|
||||||
(same as setting `max_open_trades` to a very high
|
(same as setting `max_open_trades` to a very high
|
||||||
number)
|
number).
|
||||||
-l, --live using live data
|
|
||||||
-r, --refresh-pairs-cached
|
|
||||||
refresh the pairs files in tests/testdata with the
|
|
||||||
latest data from the exchange. Use it if you want to
|
|
||||||
run your backtesting with up-to-date data.
|
|
||||||
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
|
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
|
||||||
Provide a commaseparated list of strategies to
|
Provide a space-separated list of strategies to
|
||||||
backtest Please note that ticker-interval needs to be
|
backtest. Please note that ticker-interval needs to be
|
||||||
set either in config or via command line. When using
|
set either in config or via command line. When using
|
||||||
this together with --export trades, the strategy-name
|
this together with `--export trades`, the strategy-
|
||||||
is injected into the filename (so backtest-data.json
|
name is injected into the filename (so `backtest-
|
||||||
becomes backtest-data-DefaultStrategy.json
|
data.json` becomes `backtest-data-
|
||||||
--export EXPORT export backtest results, argument are: trades Example
|
DefaultStrategy.json`
|
||||||
--export=trades
|
--export EXPORT Export backtest results, argument are: trades.
|
||||||
|
Example: `--export=trades`
|
||||||
--export-filename PATH
|
--export-filename PATH
|
||||||
Save backtest results to this filename requires
|
Save backtest results to the file with this filename
|
||||||
--export to be set as well Example --export-
|
(default: `user_data/backtest_results/backtest-
|
||||||
filename=user_data/backtest_data/backtest_today.json
|
result.json`). Requires `--export` to be set as well.
|
||||||
(default: user_data/backtest_data/backtest-
|
Example: `--export-filename=user_data/backtest_results
|
||||||
result.json)
|
/backtest_today.json`
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### How to use **--refresh-pairs-cached** parameter?
|
### Getting historic data for backtesting
|
||||||
|
|
||||||
The first time your run Backtesting, it will take the pairs you have
|
The first time your run Backtesting, you will need to download some historic data first.
|
||||||
set in your config file and download data from Bittrex.
|
This can be accomplished by using `freqtrade download-data`.
|
||||||
|
Check the corresponding [help page section](backtesting.md#Getting-data-for-backtesting-and-hyperopt) for more details
|
||||||
If for any reason you want to update your data set, you use
|
|
||||||
`--refresh-pairs-cached` to force Backtesting to update the data it has.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Use it only if you want to update your data set. You will not be able to come back to the previous version.
|
|
||||||
|
|
||||||
To test your strategy with latest data, we recommend continuing using
|
|
||||||
the parameter `-l` or `--live`.
|
|
||||||
|
|
||||||
## Hyperopt commands
|
## Hyperopt commands
|
||||||
|
|
||||||
@@ -189,65 +231,104 @@ To optimize your strategy, you can use hyperopt parameter hyperoptimization
|
|||||||
to find optimal parameter values for your stategy.
|
to find optimal parameter values for your stategy.
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade hyperopt [-h] [-i TICKER_INTERVAL] [--eps] [--dmmp]
|
usage: freqtrade hyperopt [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
||||||
[--timerange TIMERANGE] [-e INT]
|
[--max_open_trades INT]
|
||||||
[-s {all,buy,roi,stoploss} [{all,buy,roi,stoploss} ...]]
|
[--stake_amount STAKE_AMOUNT] [--fee FLOAT]
|
||||||
|
[--customhyperopt NAME] [--hyperopt-path PATH]
|
||||||
|
[--eps] [-e INT]
|
||||||
|
[-s {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...]]
|
||||||
|
[--dmmp] [--print-all] [--no-color] [--print-json]
|
||||||
|
[-j JOBS] [--random-state INT] [--min-trades INT]
|
||||||
|
[--continue] [--hyperopt-loss NAME]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||||
specify ticker interval (1m, 5m, 30m, 1h, 1d)
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
|
`1d`).
|
||||||
|
--timerange TIMERANGE
|
||||||
|
Specify what timerange of data to use.
|
||||||
|
--max_open_trades INT
|
||||||
|
Specify max_open_trades to use.
|
||||||
|
--stake_amount STAKE_AMOUNT
|
||||||
|
Specify stake_amount.
|
||||||
|
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
|
||||||
|
entry and exit).
|
||||||
|
--customhyperopt NAME
|
||||||
|
Specify hyperopt class name (default:
|
||||||
|
`DefaultHyperOpt`).
|
||||||
|
--hyperopt-path PATH Specify additional lookup path for Hyperopts and
|
||||||
|
Hyperopt Loss functions.
|
||||||
--eps, --enable-position-stacking
|
--eps, --enable-position-stacking
|
||||||
Allow buying the same pair multiple times (position
|
Allow buying the same pair multiple times (position
|
||||||
stacking)
|
stacking).
|
||||||
|
-e INT, --epochs INT Specify number of epochs (default: 100).
|
||||||
|
-s {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...], --spaces {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...]
|
||||||
|
Specify which parameters to hyperopt. Space-separated
|
||||||
|
list. Default: `all`.
|
||||||
--dmmp, --disable-max-market-positions
|
--dmmp, --disable-max-market-positions
|
||||||
Disable applying `max_open_trades` during backtest
|
Disable applying `max_open_trades` during backtest
|
||||||
(same as setting `max_open_trades` to a very high
|
(same as setting `max_open_trades` to a very high
|
||||||
number)
|
number).
|
||||||
--timerange TIMERANGE
|
--print-all Print all results, not only the best ones.
|
||||||
specify what timerange of data to use.
|
--no-color Disable colorization of hyperopt results. May be
|
||||||
--hyperopt PATH specify hyperopt file (default:
|
useful if you are redirecting output to a file.
|
||||||
freqtrade/optimize/default_hyperopt.py)
|
--print-json Print best result detailization in JSON format.
|
||||||
-e INT, --epochs INT specify number of epochs (default: 100)
|
-j JOBS, --job-workers JOBS
|
||||||
-s {all,buy,roi,stoploss} [{all,buy,roi,stoploss} ...], --spaces {all,buy,roi,stoploss} [{all,buy,roi,stoploss} ...]
|
The number of concurrently running jobs for
|
||||||
Specify which parameters to hyperopt. Space separate
|
hyperoptimization (hyperopt worker processes). If -1
|
||||||
list. Default: all
|
(default), all CPUs are used, for -2, all CPUs but one
|
||||||
|
are used, etc. If 1 is given, no parallel computing
|
||||||
|
code is used at all.
|
||||||
|
--random-state INT Set random state to some positive integer for
|
||||||
|
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.(default:
|
||||||
|
`DefaultHyperOptLoss`).
|
||||||
```
|
```
|
||||||
|
|
||||||
## Edge commands
|
## Edge commands
|
||||||
|
|
||||||
To know your trade expectacny and winrate against historical data, you can use Edge.
|
To know your trade expectancy and winrate against historical data, you can use Edge.
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: main.py edge [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE] [-r]
|
usage: freqtrade edge [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
||||||
[--stoplosses STOPLOSS_RANGE]
|
[--max_open_trades INT] [--stake_amount STAKE_AMOUNT]
|
||||||
|
[--fee FLOAT] [--stoplosses STOPLOSS_RANGE]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||||
specify ticker interval (1m, 5m, 30m, 1h, 1d)
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
|
`1d`).
|
||||||
--timerange TIMERANGE
|
--timerange TIMERANGE
|
||||||
specify what timerange of data to use.
|
Specify what timerange of data to use.
|
||||||
-r, --refresh-pairs-cached
|
--max_open_trades INT
|
||||||
refresh the pairs files in tests/testdata with the
|
Specify max_open_trades to use.
|
||||||
latest data from the exchange. Use it if you want to
|
--stake_amount STAKE_AMOUNT
|
||||||
run your edge with up-to-date data.
|
Specify stake_amount.
|
||||||
|
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
|
||||||
|
entry and exit).
|
||||||
--stoplosses STOPLOSS_RANGE
|
--stoplosses STOPLOSS_RANGE
|
||||||
defines a range of stoploss against which edge will
|
Defines a range of stoploss values against which edge
|
||||||
assess the strategythe format is "min,max,step"
|
will assess the strategy. The format is "min,max,step"
|
||||||
(without any space).example:
|
(without any space). Example:
|
||||||
--stoplosses=-0.01,-0.1,-0.001
|
`--stoplosses=-0.01,-0.1,-0.001`
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
To understand edge and how to read the results, please read the [edge documentation](edge.md).
|
To understand edge and how to read the results, please read the [edge documentation](edge.md).
|
||||||
|
|
||||||
## A parameter missing in the configuration?
|
|
||||||
|
|
||||||
All parameters for `main.py`, `backtesting`, `hyperopt` are referenced
|
|
||||||
in [misc.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/misc.py#L84)
|
|
||||||
|
|
||||||
## Next step
|
## Next step
|
||||||
|
|
||||||
The optimal strategy of the bot will change with time depending of the market trends. The next step is to
|
The optimal strategy of the bot will change with time depending of the market trends. The next step is to
|
||||||
[optimize your bot](bot-optimization.md).
|
[Strategy Customization](strategy-customization.md).
|
||||||
|
|||||||
@@ -1,15 +1,42 @@
|
|||||||
# Configure the bot
|
# Configure the bot
|
||||||
|
|
||||||
This page explains how to configure your `config.json` file.
|
Freqtrade has many configurable features and possibilities.
|
||||||
|
By default, these settings are configured via the configuration file (see below).
|
||||||
|
|
||||||
## Setup config.json
|
## The Freqtrade configuration file
|
||||||
|
|
||||||
We recommend to copy and use the `config.json.example` as a template
|
The bot uses a set of configuration parameters during its operation that all together conform the bot configuration. It normally reads its configuration from a file (Freqtrade configuration file).
|
||||||
|
|
||||||
|
Per default, the bot loads the configuration from the `config.json` file, located in the current working directory.
|
||||||
|
|
||||||
|
You can specify a different configuration file used by the bot with the `-c/--config` command line option.
|
||||||
|
|
||||||
|
In some advanced use cases, multiple configuration files can be specified and used by the bot or the bot can read its configuration parameters from the process standard input stream.
|
||||||
|
|
||||||
|
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.
|
for your bot configuration.
|
||||||
|
|
||||||
The table below will list all configuration parameters.
|
The Freqtrade configuration file is to be written in the JSON format.
|
||||||
|
|
||||||
Mandatory Parameters are marked as **Required**.
|
Additionally to the standard JSON syntax, you may use one-line `// ...` and multi-line `/* ... */` comments in your configuration files and trailing commas in the lists of parameters.
|
||||||
|
|
||||||
|
Do not worry if you are not familiar with JSON format -- simply open the configuration file with an editor of your choice, make some changes to the parameters you need, save your changes and, finally, restart the bot or, if it was previously stopped, run it again with the changes you made to the configuration. The bot validates syntax of the configuration file at startup and will warn you if you made any errors editing it, pointing out problematic lines.
|
||||||
|
|
||||||
|
## Configuration parameters
|
||||||
|
|
||||||
|
The table below will list all configuration parameters available.
|
||||||
|
|
||||||
|
Freqtrade can also load many options via command line (CLI) arguments (check out the commands `--help` output for details).
|
||||||
|
The prevelance for all Options is as follows:
|
||||||
|
|
||||||
|
- CLI arguments override any other option
|
||||||
|
- Configuration files are used in sequence (last file wins), and override Strategy configurations.
|
||||||
|
- Strategy configurations are only used if they are not set via configuration or via command line arguments. These options are market with [Strategy Override](#parameters-in-the-strategy) in the below table.
|
||||||
|
|
||||||
|
Mandatory parameters are marked as **Required**, which means that they are required to be set in one of the possible ways.
|
||||||
|
|
||||||
| Command | Default | Description |
|
| Command | Default | Description |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
@@ -17,44 +44,49 @@ Mandatory Parameters are marked as **Required**.
|
|||||||
| `stake_currency` | BTC | **Required.** Crypto-currency used for trading.
|
| `stake_currency` | BTC | **Required.** Crypto-currency used for trading.
|
||||||
| `stake_amount` | 0.05 | **Required.** Amount of crypto-currency your bot will use for each trade. Per default, the bot will use (0.05 BTC x 3) = 0.15 BTC in total will be always engaged. Set it to `"unlimited"` to allow the bot to use all available balance.
|
| `stake_amount` | 0.05 | **Required.** Amount of crypto-currency your bot will use for each trade. Per default, the bot will use (0.05 BTC x 3) = 0.15 BTC in total will be always engaged. Set it to `"unlimited"` to allow the bot to use all available balance.
|
||||||
| `amount_reserve_percent` | 0.05 | Reserve some amount in min pair stake amount. Default is 5%. The bot will reserve `amount_reserve_percent` + stop-loss value when calculating min pair stake amount in order to avoid possible trade refusals.
|
| `amount_reserve_percent` | 0.05 | Reserve some amount in min pair stake amount. Default is 5%. The bot will reserve `amount_reserve_percent` + stop-loss value when calculating min pair stake amount in order to avoid possible trade refusals.
|
||||||
| `ticker_interval` | [1m, 5m, 30m, 1h, 1d] | The ticker interval to use (1min, 5 min, 30 min, 1 hour or 1 day). Default is 5 minutes. [Strategy Override](#parameters-in-strategy).
|
| `ticker_interval` | [1m, 5m, 15m, 30m, 1h, 1d, ...] | The ticker interval to use (1min, 5 min, 15 min, 30 min, 1 hour or 1 day). Default is 5 minutes. [Strategy Override](#parameters-in-the-strategy).
|
||||||
| `fiat_display_currency` | USD | **Required.** Fiat currency used to show your profits. More information below.
|
| `fiat_display_currency` | USD | **Required.** Fiat currency used to show your profits. More information below.
|
||||||
| `dry_run` | true | **Required.** Define if the bot must be in Dry-run or production mode.
|
| `dry_run` | true | **Required.** Define if the bot must be in Dry-run or production mode.
|
||||||
| `process_only_new_candles` | false | If set to true indicators are processed only once a new candle arrives. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. [Strategy Override](#parameters-in-strategy).
|
| `dry_run_wallet` | 999.9 | Overrides the default amount of 999.9 stake currency units in the wallet used by the bot running in the Dry Run mode if you need it for any reason.
|
||||||
| `minimal_roi` | See below | Set the threshold in percent the bot will use to sell a trade. More information below. [Strategy Override](#parameters-in-strategy).
|
| `process_only_new_candles` | false | If set to true indicators are processed only once a new candle arrives. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. [Strategy Override](#parameters-in-the-strategy).
|
||||||
| `stoploss` | -0.10 | Value of the stoploss in percent used by the bot. More information below. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-strategy).
|
| `minimal_roi` | See below | Set the threshold in percent the bot will use to sell a trade. More information below. [Strategy Override](#parameters-in-the-strategy).
|
||||||
| `trailing_stop` | false | Enables trailing stop-loss (based on `stoploss` in either configuration or strategy file). More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-strategy).
|
| `stoploss` | -0.10 | Value of the stoploss in percent used by the bot. More information below. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
||||||
| `trailing_stop_positive` | 0 | Changes stop-loss once profit has been reached. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-strategy).
|
| `trailing_stop` | false | Enables trailing stop-loss (based on `stoploss` in either configuration or strategy file). More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
||||||
| `trailing_stop_positive_offset` | 0 | Offset on when to apply `trailing_stop_positive`. Percentage value which should be positive. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-strategy).
|
| `trailing_stop_positive` | 0 | Changes stop-loss once profit has been reached. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
||||||
|
| `trailing_stop_positive_offset` | 0 | Offset on when to apply `trailing_stop_positive`. Percentage value which should be positive. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
||||||
|
| `trailing_only_offset_is_reached` | false | Only apply trailing stoploss when the offset is reached. [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
||||||
| `unfilledtimeout.buy` | 10 | **Required.** How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled.
|
| `unfilledtimeout.buy` | 10 | **Required.** How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled.
|
||||||
| `unfilledtimeout.sell` | 10 | **Required.** How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled.
|
| `unfilledtimeout.sell` | 10 | **Required.** How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled.
|
||||||
| `bid_strategy.ask_last_balance` | 0.0 | **Required.** Set the bidding price. More information [below](#understand-ask_last_balance).
|
| `bid_strategy.ask_last_balance` | 0.0 | **Required.** Set the bidding price. More information [below](#understand-ask_last_balance).
|
||||||
| `bid_strategy.use_order_book` | false | Allows buying of pair using the rates in Order Book Bids.
|
| `bid_strategy.use_order_book` | false | Allows buying of pair using the rates in Order Book Bids.
|
||||||
| `bid_strategy.order_book_top` | 0 | Bot will use the top N rate in Order Book Bids. Ie. a value of 2 will allow the bot to pick the 2nd bid rate in Order Book Bids.
|
| `bid_strategy.order_book_top` | 0 | Bot will use the top N rate in Order Book Bids. I.e. a value of 2 will allow the bot to pick the 2nd bid rate in Order Book Bids.
|
||||||
| `bid_strategy. check_depth_of_market.enabled` | false | Does not buy if the % difference of buy orders and sell orders is met in Order Book.
|
| `bid_strategy. check_depth_of_market.enabled` | false | Does not buy if the % difference of buy orders and sell orders is met in Order Book.
|
||||||
| `bid_strategy. check_depth_of_market.bids_to_ask_delta` | 0 | The % difference of buy orders and sell orders found in Order Book. A value lesser than 1 means sell orders is greater, while value greater than 1 means buy orders is higher.
|
| `bid_strategy. check_depth_of_market.bids_to_ask_delta` | 0 | The % difference of buy orders and sell orders found in Order Book. A value lesser than 1 means sell orders is greater, while value greater than 1 means buy orders is higher.
|
||||||
| `ask_strategy.use_order_book` | false | Allows selling of open traded pair using the rates in Order Book Asks.
|
| `ask_strategy.use_order_book` | false | Allows selling of open traded pair using the rates in Order Book Asks.
|
||||||
| `ask_strategy.order_book_min` | 0 | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
| `ask_strategy.order_book_min` | 0 | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
||||||
| `ask_strategy.order_book_max` | 0 | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
| `ask_strategy.order_book_max` | 0 | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
||||||
| `order_types` | None | Configure order-types depending on the action (`"buy"`, `"sell"`, `"stoploss"`, `"stoploss_on_exchange"`). [More information below](#understand-order_types). [Strategy Override](#parameters-in-strategy).
|
| `ask_strategy.use_sell_signal` | true | Use sell signals produced by the strategy in addition to the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy).
|
||||||
| `order_time_in_force` | None | Configure time in force for buy and sell orders. [More information below](#understand-order_time_in_force). [Strategy Override](#parameters-in-strategy).
|
| `ask_strategy.sell_profit_only` | false | Wait until the bot makes a positive profit before taking a sell decision. [Strategy Override](#parameters-in-the-strategy).
|
||||||
| `exchange.name` | bittrex | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename).
|
| `ask_strategy.ignore_roi_if_buy_signal` | false | 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).
|
||||||
| `exchange.key` | key | API key to use for the exchange. Only required when you are in production mode.
|
| `order_types` | None | Configure order-types depending on the action (`"buy"`, `"sell"`, `"stoploss"`, `"stoploss_on_exchange"`). [More information below](#understand-order_types). [Strategy Override](#parameters-in-the-strategy).
|
||||||
| `exchange.secret` | secret | API secret to use for the exchange. Only required when you are in production mode.
|
| `order_time_in_force` | None | Configure time in force for buy and sell orders. [More information below](#understand-order_time_in_force). [Strategy Override](#parameters-in-the-strategy).
|
||||||
| `exchange.pair_whitelist` | [] | List of currency to use by the bot. Can be overrided with `--dynamic-whitelist` param.
|
| `exchange.name` | | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename).
|
||||||
| `exchange.pair_blacklist` | [] | List of currency the bot must avoid. Useful when using `--dynamic-whitelist` param.
|
| `exchange.sandbox` | false | Use the 'sandbox' version of the exchange, where the exchange provides a sandbox for risk-free integration. See [here](sandbox-testing.md) in more details.
|
||||||
| `exchange.ccxt_rate_limit` | True | DEPRECATED!! Have CCXT handle Exchange rate limits. Depending on the exchange, having this to false can lead to temporary bans from the exchange.
|
| `exchange.key` | '' | API key to use for the exchange. Only required when you are in production mode. ***Keep it in secrete, do not disclose publicly.***
|
||||||
|
| `exchange.secret` | '' | API secret to use for the exchange. Only required when you are in production mode. ***Keep it in secrete, do not disclose publicly.***
|
||||||
|
| `exchange.password` | '' | API password to use for the exchange. Only required when you are in production mode and for exchanges that use password for API requests. ***Keep it in secrete, do not disclose publicly.***
|
||||||
|
| `exchange.pair_whitelist` | [] | List of pairs to use by the bot for trading and to check for potential trades during backtesting. Can be overriden by dynamic pairlists (see [below](#dynamic-pairlists)).
|
||||||
|
| `exchange.pair_blacklist` | [] | List of pairs the bot must absolutely avoid for trading and backtesting. Can be overriden by dynamic pairlists (see [below](#dynamic-pairlists)).
|
||||||
| `exchange.ccxt_config` | None | Additional CCXT parameters passed to the regular ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation)
|
| `exchange.ccxt_config` | None | Additional CCXT parameters passed to the regular ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation)
|
||||||
| `exchange.ccxt_async_config` | None | Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation)
|
| `exchange.ccxt_async_config` | None | Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation)
|
||||||
|
| `exchange.markets_refresh_interval` | 60 | The interval in minutes in which markets are reloaded.
|
||||||
| `edge` | false | Please refer to [edge configuration document](edge.md) for detailed explanation.
|
| `edge` | false | Please refer to [edge configuration document](edge.md) for detailed explanation.
|
||||||
| `experimental.use_sell_signal` | false | Use your sell strategy in addition of the `minimal_roi`. [Strategy Override](#parameters-in-strategy).
|
| `experimental.block_bad_exchanges` | true | Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now.
|
||||||
| `experimental.sell_profit_only` | false | Waits until you have made a positive profit before taking a sell decision. [Strategy Override](#parameters-in-strategy).
|
| `pairlist.method` | StaticPairList | Use static or dynamic volume-based pairlist. [More information below](#dynamic-pairlists).
|
||||||
| `experimental.ignore_roi_if_buy_signal` | false | Does not sell if the buy-signal is still active. Takes preference over `minimal_roi` and `use_sell_signal`. [Strategy Override](#parameters-in-strategy).
|
|
||||||
| `pairlist.method` | StaticPairList | Use Static whitelist. [More information below](#dynamic-pairlists).
|
|
||||||
| `pairlist.config` | None | Additional configuration for dynamic pairlists. [More information below](#dynamic-pairlists).
|
| `pairlist.config` | None | Additional configuration for dynamic pairlists. [More information below](#dynamic-pairlists).
|
||||||
| `telegram.enabled` | true | **Required.** Enable or not the usage of Telegram.
|
| `telegram.enabled` | true | **Required.** Enable or not the usage of Telegram.
|
||||||
| `telegram.token` | token | Your Telegram bot token. Only required if `telegram.enabled` is `true`.
|
| `telegram.token` | token | Your Telegram bot token. Only required if `telegram.enabled` is `true`. ***Keep it in secrete, do not disclose publicly.***
|
||||||
| `telegram.chat_id` | chat_id | Your personal Telegram account id. Only required if `telegram.enabled` is `true`.
|
| `telegram.chat_id` | chat_id | Your personal Telegram account id. Only required if `telegram.enabled` is `true`. ***Keep it in secrete, do not disclose publicly.***
|
||||||
| `webhook.enabled` | false | Enable usage of Webhook notifications
|
| `webhook.enabled` | false | Enable usage of Webhook notifications
|
||||||
| `webhook.url` | false | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details.
|
| `webhook.url` | false | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details.
|
||||||
| `webhook.webhookbuy` | false | Payload to send on buy. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details.
|
| `webhook.webhookbuy` | false | Payload to send on buy. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details.
|
||||||
@@ -64,16 +96,20 @@ Mandatory Parameters are marked as **Required**.
|
|||||||
| `initial_state` | running | Defines the initial application state. More information below.
|
| `initial_state` | running | Defines the initial application state. More information below.
|
||||||
| `forcebuy_enable` | false | Enables the RPC Commands to force a buy. More information below.
|
| `forcebuy_enable` | false | Enables the RPC Commands to force a buy. More information below.
|
||||||
| `strategy` | DefaultStrategy | Defines Strategy class to use.
|
| `strategy` | DefaultStrategy | Defines Strategy class to use.
|
||||||
| `strategy_path` | null | Adds an additional strategy lookup path (must be a folder).
|
| `strategy_path` | null | Adds an additional strategy lookup path (must be a directory).
|
||||||
| `internals.process_throttle_secs` | 5 | **Required.** Set the process throttle. Value in second.
|
| `internals.process_throttle_secs` | 5 | **Required.** Set the process throttle. Value in second.
|
||||||
|
| `internals.heartbeat_interval` | 60 | Print heartbeat message every X seconds. Set to 0 to disable heartbeat messages.
|
||||||
|
| `internals.sd_notify` | false | Enables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See [here](installation.md#7-optional-configure-freqtrade-as-a-systemd-service) for more details.
|
||||||
|
| `logfile` | | Specify Logfile. Uses a rolling strategy of 10 files, with 1Mb per file.
|
||||||
|
| `user_data_dir` | cwd()/user_data | Directory containing user data. Defaults to `./user_data/`.
|
||||||
|
|
||||||
### Parameters in strategy
|
### Parameters in the strategy
|
||||||
|
|
||||||
The following parameters can be set in either configuration or strategy.
|
The following parameters can be set in either configuration file or strategy.
|
||||||
Values in the configuration are always overwriting values set in the strategy.
|
Values set in the configuration file always overwrite values set in the strategy.
|
||||||
|
|
||||||
* `minimal_roi`
|
|
||||||
* `ticker_interval`
|
* `ticker_interval`
|
||||||
|
* `minimal_roi`
|
||||||
* `stoploss`
|
* `stoploss`
|
||||||
* `trailing_stop`
|
* `trailing_stop`
|
||||||
* `trailing_stop_positive`
|
* `trailing_stop_positive`
|
||||||
@@ -81,13 +117,13 @@ Values in the configuration are always overwriting values set in the strategy.
|
|||||||
* `process_only_new_candles`
|
* `process_only_new_candles`
|
||||||
* `order_types`
|
* `order_types`
|
||||||
* `order_time_in_force`
|
* `order_time_in_force`
|
||||||
* `use_sell_signal` (experimental)
|
* `use_sell_signal` (ask_strategy)
|
||||||
* `sell_profit_only` (experimental)
|
* `sell_profit_only` (ask_strategy)
|
||||||
* `ignore_roi_if_buy_signal` (experimental)
|
* `ignore_roi_if_buy_signal` (ask_strategy)
|
||||||
|
|
||||||
### Understand stake_amount
|
### Understand stake_amount
|
||||||
|
|
||||||
`stake_amount` is an amount of crypto-currency your bot will use for each trade.
|
The `stake_amount` configuration parameter is an amount of crypto-currency your bot will use for each trade.
|
||||||
The minimal value is 0.0005. If there is not enough crypto-currency in
|
The minimal value is 0.0005. If there is not enough crypto-currency in
|
||||||
the account an exception is generated.
|
the account an exception is generated.
|
||||||
To allow the bot to trade all the available `stake_currency` in your account set
|
To allow the bot to trade all the available `stake_currency` in your account set
|
||||||
@@ -96,7 +132,7 @@ To allow the bot to trade all the available `stake_currency` in your account set
|
|||||||
"stake_amount" : "unlimited",
|
"stake_amount" : "unlimited",
|
||||||
```
|
```
|
||||||
|
|
||||||
In this case a trade amount is calclulated as:
|
In this case a trade amount is calclulated as:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
currency_balanse / (max_open_trades - current_open_trades)
|
currency_balanse / (max_open_trades - current_open_trades)
|
||||||
@@ -104,7 +140,7 @@ currency_balanse / (max_open_trades - current_open_trades)
|
|||||||
|
|
||||||
### Understand minimal_roi
|
### Understand minimal_roi
|
||||||
|
|
||||||
`minimal_roi` is a JSON object where the key is a duration
|
The `minimal_roi` configuration parameter is a JSON object where the key is a duration
|
||||||
in minutes and the value is the minimum ROI in percent.
|
in minutes and the value is the minimum ROI in percent.
|
||||||
See the example below:
|
See the example below:
|
||||||
|
|
||||||
@@ -117,89 +153,136 @@ See the example below:
|
|||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
|
||||||
Most of the strategy files already include the optimal `minimal_roi`
|
Most of the strategy files already include the optimal `minimal_roi` value.
|
||||||
value. This parameter is optional. If you use it, it will take over the
|
This parameter can be set in either Strategy or Configuration file. If you use it in the configuration file, it will override the
|
||||||
`minimal_roi` value from the strategy file.
|
`minimal_roi` value from the strategy file.
|
||||||
|
If it is not set in either Strategy or Configuration, a default of 1000% `{"0": 10}` is used, and minimal roi is disabled unless your trade generates 1000% profit.
|
||||||
|
|
||||||
### Understand stoploss
|
### Understand stoploss
|
||||||
|
|
||||||
`stoploss` is loss in percentage that should trigger a sale.
|
Go to the [stoploss documentation](stoploss.md) for more details.
|
||||||
For example value `-0.10` will cause immediate sell if the
|
|
||||||
profit dips below -10% for a given trade. This parameter is optional.
|
|
||||||
|
|
||||||
Most of the strategy files already include the optimal `stoploss`
|
|
||||||
value. This parameter is optional. If you use it, it will take over the
|
|
||||||
`stoploss` value from the strategy file.
|
|
||||||
|
|
||||||
### Understand trailing stoploss
|
### Understand trailing stoploss
|
||||||
|
|
||||||
Go to the [trailing stoploss Documentation](stoploss.md) for details on trailing stoploss.
|
Go to the [trailing stoploss Documentation](stoploss.md#trailing-stop-loss) for details on trailing stoploss.
|
||||||
|
|
||||||
### Understand initial_state
|
### Understand initial_state
|
||||||
|
|
||||||
`initial_state` is an optional field that defines the initial application state.
|
The `initial_state` configuration parameter is an optional field that defines the initial application state.
|
||||||
Possible values are `running` or `stopped`. (default=`running`)
|
Possible values are `running` or `stopped`. (default=`running`)
|
||||||
If the value is `stopped` the bot has to be started with `/start` first.
|
If the value is `stopped` the bot has to be started with `/start` first.
|
||||||
|
|
||||||
### Understand forcebuy_enable
|
### Understand forcebuy_enable
|
||||||
|
|
||||||
`forcebuy_enable` enables the usage of forcebuy commands via Telegram.
|
The `forcebuy_enable` configuration parameter enables the usage of forcebuy commands via Telegram.
|
||||||
This is disabled for security reasons by default, and will show a warning message on startup if enabled.
|
This is disabled for security reasons by default, and will show a warning message on startup if enabled.
|
||||||
You send `/forcebuy ETH/BTC` to the bot, who buys the pair and holds it until a regular sell-signal appears (ROI, stoploss, /forcesell).
|
For example, you can send `/forcebuy ETH/BTC` Telegram command when this feature if enabled to the bot,
|
||||||
|
who then buys the pair and holds it until a regular sell-signal (ROI, stoploss, /forcesell) appears.
|
||||||
|
|
||||||
|
This can be dangerous with some strategies, so use with care.
|
||||||
|
|
||||||
Can be dangerous with some strategies, so use with care
|
|
||||||
See [the telegram documentation](telegram-usage.md) for details on usage.
|
See [the telegram documentation](telegram-usage.md) for details on usage.
|
||||||
|
|
||||||
### Understand process_throttle_secs
|
### Understand process_throttle_secs
|
||||||
|
|
||||||
`process_throttle_secs` is an optional field that defines in seconds how long the bot should wait
|
The `process_throttle_secs` configuration parameter is an optional field that defines in seconds how long the bot should wait
|
||||||
before asking the strategy if we should buy or a sell an asset. After each wait period, the strategy is asked again for
|
before asking the strategy if we should buy or a sell an asset. After each wait period, the strategy is asked again for
|
||||||
every opened trade wether or not we should sell, and for all the remaining pairs (either the dynamic list of pairs or
|
every opened trade wether or not we should sell, and for all the remaining pairs (either the dynamic list of pairs or
|
||||||
the static list of pairs) if we should buy.
|
the static list of pairs) if we should buy.
|
||||||
|
|
||||||
### Understand ask_last_balance
|
### Understand ask_last_balance
|
||||||
|
|
||||||
`ask_last_balance` sets the bidding price. Value `0.0` will use `ask` price, `1.0` will
|
The `ask_last_balance` configuration parameter sets the bidding price. Value `0.0` will use `ask` price, `1.0` will
|
||||||
use the `last` price and values between those interpolate between ask and last
|
use the `last` price and values between those interpolate between ask and last
|
||||||
price. Using `ask` price will guarantee quick success in bid, but bot will also
|
price. Using `ask` price will guarantee quick success in bid, but bot will also
|
||||||
end up paying more then would probably have been necessary.
|
end up paying more then would probably have been necessary.
|
||||||
|
|
||||||
### Understand order_types
|
### Understand order_types
|
||||||
|
|
||||||
`order_types` contains a dict mapping order-types to market-types as well as stoploss on or off exchange type and stoploss on exchange update interval in seconds. This allows to buy using limit orders, sell using limit-orders, and create stoploss orders using market. It also allows to set the stoploss "on exchange" which means stoploss order would be placed immediately once the buy order is fulfilled. In case stoploss on exchange and `trailing_stop` are both set, then the bot will use `stoploss_on_exchange_interval` to check it periodically and update it if necessary (e.x. in case of trailing stoploss).
|
The `order_types` configuration parameter maps actions (`buy`, `sell`, `stoploss`) to order-types (`market`, `limit`, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.
|
||||||
This can be set in the configuration or in the strategy. Configuration overwrites strategy configurations.
|
|
||||||
|
|
||||||
If this is configured, all 4 values (`"buy"`, `"sell"`, `"stoploss"` and `"stoploss_on_exchange"`) need to be present, otherwise the bot warn about it and will fail to start.
|
This allows to buy using limit orders, sell using
|
||||||
The below is the default which is used if this is not configured in either Strategy or configuration.
|
limit-orders, and create stoplosses using using market orders. It also allows to set the
|
||||||
|
stoploss "on exchange" which means stoploss order would be placed immediately once
|
||||||
|
the buy order is fulfilled.
|
||||||
|
If `stoploss_on_exchange` and `trailing_stop` are both set, then the bot will use `stoploss_on_exchange_interval` to check and update the stoploss on exchange periodically.
|
||||||
|
`order_types` can be set in the configuration file or in the strategy.
|
||||||
|
`order_types` set in the configuration file overwrites values set in the strategy as a whole, so you need to configure the whole `order_types` dictionary in one place.
|
||||||
|
|
||||||
|
If this is configured, the following 4 values (`buy`, `sell`, `stoploss` and
|
||||||
|
`stoploss_on_exchange`) need to be present, otherwise the bot will fail to start.
|
||||||
|
|
||||||
|
`emergencysell` is an optional value, which defaults to `market` and is used when creating stoploss on exchange orders fails.
|
||||||
|
The below is the default which is used if this is not configured in either strategy or configuration file.
|
||||||
|
|
||||||
|
Syntax for Strategy:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
"order_types": {
|
order_types = {
|
||||||
"buy": "limit",
|
"buy": "limit",
|
||||||
"sell": "limit",
|
"sell": "limit",
|
||||||
|
"emergencysell": "market",
|
||||||
"stoploss": "market",
|
"stoploss": "market",
|
||||||
"stoploss_on_exchange": False,
|
"stoploss_on_exchange": False,
|
||||||
"stoploss_on_exchange_interval": 60
|
"stoploss_on_exchange_interval": 60
|
||||||
},
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Configuration:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"order_types": {
|
||||||
|
"buy": "limit",
|
||||||
|
"sell": "limit",
|
||||||
|
"emergencysell": "market",
|
||||||
|
"stoploss": "market",
|
||||||
|
"stoploss_on_exchange": false,
|
||||||
|
"stoploss_on_exchange_interval": 60
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Not all exchanges support "market" orders.
|
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."`
|
The following message will be shown if your exchange does not support market orders:
|
||||||
|
`"Exchange <yourexchange> does not support market orders."`
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
stoploss on exchange interval is not mandatory. Do not change it's value if you are unsure of what you are doing. For more information about how stoploss works please read [the stoploss documentation](stoploss.md).
|
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 order.
|
||||||
|
|
||||||
|
!!! 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.
|
||||||
|
|
||||||
### Understand order_time_in_force
|
### Understand order_time_in_force
|
||||||
`order_time_in_force` defines the policy by which the order is executed on the exchange. Three commonly used time in force are:<br/>
|
|
||||||
**GTC (Goog Till Canceled):**
|
The `order_time_in_force` configuration parameter defines the policy by which the order
|
||||||
This is most of the time the default time in force. It means the order will remain on exchange till it is canceled by user. It can be fully or partially fulfilled. If partially fulfilled, the remaining will stay on the exchange till cancelled.<br/>
|
is executed on the exchange. Three commonly used time in force are:
|
||||||
|
|
||||||
|
**GTC (Good Till Canceled):**
|
||||||
|
|
||||||
|
This is most of the time the default time in force. It means the order will remain
|
||||||
|
on exchange till it is canceled by user. It can be fully or partially fulfilled.
|
||||||
|
If partially fulfilled, the remaining will stay on the exchange till cancelled.
|
||||||
|
|
||||||
**FOK (Full Or Kill):**
|
**FOK (Full Or Kill):**
|
||||||
It means if the order is not executed immediately AND fully then it is canceled by the exchange.<br/>
|
|
||||||
|
It means if the order is not executed immediately AND fully then it is canceled by the exchange.
|
||||||
|
|
||||||
**IOC (Immediate Or Canceled):**
|
**IOC (Immediate Or Canceled):**
|
||||||
It is the same as FOK (above) except it can be partially fulfilled. The remaining part is automatically cancelled by the exchange.
|
|
||||||
<br/>
|
It is the same as FOK (above) except it can be partially fulfilled. The remaining part
|
||||||
`order_time_in_force` contains a dict buy and sell time in force policy. This can be set in the configuration or in the strategy. Configuration overwrites strategy configurations.<br/>
|
is automatically cancelled by the exchange.
|
||||||
possible values are: `gtc` (default), `fok` or `ioc`.<br/>
|
|
||||||
|
The `order_time_in_force` parameter contains a dict with buy and sell time in force policy values.
|
||||||
|
This can be set in the configuration file or in the strategy.
|
||||||
|
Values set in the configuration file overwrites values set in the strategy.
|
||||||
|
|
||||||
|
The possible values are: `gtc` (default), `fok` or `ioc`.
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
"order_time_in_force": {
|
"order_time_in_force": {
|
||||||
"buy": "gtc",
|
"buy": "gtc",
|
||||||
@@ -208,11 +291,12 @@ possible values are: `gtc` (default), `fok` or `ioc`.<br/>
|
|||||||
```
|
```
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
This is an ongoing work. For now it is supported only for binance and only for buy orders. Please don't change the default value unless you know what you are doing.
|
This is an ongoing work. For now it is supported only for binance and only for buy orders.
|
||||||
|
Please don't change the default value unless you know what you are doing.
|
||||||
|
|
||||||
### What values for exchange.name?
|
### Exchange configuration
|
||||||
|
|
||||||
Freqtrade is based on [CCXT library](https://github.com/ccxt/ccxt) that supports 115 cryptocurrency
|
Freqtrade is based on [CCXT library](https://github.com/ccxt/ccxt) that supports over 100 cryptocurrency
|
||||||
exchange markets and trading APIs. The complete up-to-date list can be found in the
|
exchange markets and trading APIs. The complete up-to-date list can be found in the
|
||||||
[CCXT repo homepage](https://github.com/ccxt/ccxt/tree/master/python). However, the bot was tested
|
[CCXT repo homepage](https://github.com/ccxt/ccxt/tree/master/python). However, the bot was tested
|
||||||
with only Bittrex and Binance.
|
with only Bittrex and Binance.
|
||||||
@@ -224,35 +308,84 @@ The bot was tested with the following exchanges:
|
|||||||
|
|
||||||
Feel free to test other exchanges and submit your PR to improve the bot.
|
Feel free to test other exchanges and submit your PR to improve the bot.
|
||||||
|
|
||||||
### What values for fiat_display_currency?
|
#### Sample exchange configuration
|
||||||
|
|
||||||
|
A exchange configuration for "binance" would look as follows:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"exchange": {
|
||||||
|
"name": "binance",
|
||||||
|
"key": "your_exchange_key",
|
||||||
|
"secret": "your_exchange_secret",
|
||||||
|
"ccxt_config": {"enableRateLimit": true},
|
||||||
|
"ccxt_async_config": {
|
||||||
|
"enableRateLimit": true,
|
||||||
|
"rateLimit": 200
|
||||||
|
},
|
||||||
|
```
|
||||||
|
|
||||||
|
This configuration enables binance, as well as rate limiting to avoid bans from the exchange.
|
||||||
|
`"rateLimit": 200` defines a wait-event of 0.2s between each call. This can also be completely disabled by setting `"enableRateLimit"` to false.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Optimal settings for rate limiting depend on the exchange and the size of the whitelist, so an ideal parameter will vary on many other settings.
|
||||||
|
We try to provide sensible defaults per exchange where possible, if you encounter bans please make sure that `"enableRateLimit"` is enabled and increase the `"rateLimit"` parameter step by step.
|
||||||
|
|
||||||
|
#### Advanced FreqTrade Exchange configuration
|
||||||
|
|
||||||
|
Advanced options can be configured using the `_ft_has_params` setting, which will override Defaults and exchange-specific behaviours.
|
||||||
|
|
||||||
|
Available options are listed in the exchange-class as `_ft_has_default`.
|
||||||
|
|
||||||
|
For example, to test the order type `FOK` with Kraken, and modify candle_limit to 200 (so you only get 200 candles per call):
|
||||||
|
|
||||||
|
```json
|
||||||
|
"exchange": {
|
||||||
|
"name": "kraken",
|
||||||
|
"_ft_has_params": {
|
||||||
|
"order_time_in_force": ["gtc", "fok"],
|
||||||
|
"ohlcv_candle_limit": 200
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Warning
|
||||||
|
Please make sure to fully understand the impacts of these settings before modifying them.
|
||||||
|
|
||||||
|
### What values can be used for fiat_display_currency?
|
||||||
|
|
||||||
|
The `fiat_display_currency` configuration parameter sets the base currency to use for the
|
||||||
|
conversion from coin to fiat in the bot Telegram reports.
|
||||||
|
|
||||||
|
The valid values are:
|
||||||
|
|
||||||
`fiat_display_currency` set the base currency to use for the conversion from coin to fiat in Telegram.
|
|
||||||
The valid values are:<br/>
|
|
||||||
```json
|
```json
|
||||||
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR", "USD"
|
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR", "USD"
|
||||||
```
|
```
|
||||||
In addition to FIAT currencies, a range of cryto currencies are supported.
|
|
||||||
|
In addition to fiat currencies, a range of cryto currencies are supported.
|
||||||
|
|
||||||
The valid values are:
|
The valid values are:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
"BTC", "ETH", "XRP", "LTC", "BCH", "USDT"
|
"BTC", "ETH", "XRP", "LTC", "BCH", "USDT"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Switch to dry-run mode
|
## Switch to Dry-run mode
|
||||||
|
|
||||||
We recommend starting the bot in dry-run mode to see how your bot will
|
We recommend starting the bot in the Dry-run mode to see how your bot will
|
||||||
behave and how is the performance of your strategy. In Dry-run mode the
|
behave and what is the performance of your strategy. In the Dry-run mode the
|
||||||
bot does not engage your money. It only runs a live simulation without
|
bot does not engage your money. It only runs a live simulation without
|
||||||
creating trades.
|
creating trades on the exchange.
|
||||||
|
|
||||||
1. Edit your `config.json` file
|
1. Edit your `config.json` configuration file.
|
||||||
2. Switch dry-run to true and specify db_url for a persistent db
|
2. Switch `dry-run` to `true` and specify `db_url` for a persistence database.
|
||||||
|
|
||||||
```json
|
```json
|
||||||
"dry_run": true,
|
"dry_run": true,
|
||||||
"db_url": "sqlite:///tradesv3.dryrun.sqlite",
|
"db_url": "sqlite:///tradesv3.dryrun.sqlite",
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Remove your Exchange API key (change them by fake api credentials)
|
3. Remove your Exchange API key and secrete (change them by empty values or fake credentials):
|
||||||
|
|
||||||
```json
|
```json
|
||||||
"exchange": {
|
"exchange": {
|
||||||
@@ -263,37 +396,45 @@ creating trades.
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Once you will be happy with your bot performance, you can switch it to
|
Once you will be happy with your bot performance running in the Dry-run mode,
|
||||||
production mode.
|
you can switch it to production mode.
|
||||||
|
|
||||||
### Dynamic Pairlists
|
### Dynamic Pairlists
|
||||||
|
|
||||||
Dynamic pairlists select pairs for you based on the logic configured.
|
Dynamic pairlists select pairs for you based on the logic configured.
|
||||||
The bot runs against all pairs (with that stake) on the exchange, and a number of assets (`number_assets`) is selected based on the selected criteria.
|
The bot runs against all pairs (with that stake) on the exchange, and a number of assets
|
||||||
|
(`number_assets`) is selected based on the selected criteria.
|
||||||
|
|
||||||
By default, a Static Pairlist is used (configured as `"pair_whitelist"` under the `"exchange"` section of this configuration).
|
By default, the `StaticPairList` method is used.
|
||||||
|
The Pairlist method is configured as `pair_whitelist` parameter under the `exchange`
|
||||||
|
section of the configuration.
|
||||||
|
|
||||||
**Available Pairlist methods:**
|
**Available Pairlist methods:**
|
||||||
|
|
||||||
* `"StaticPairList"`
|
* `StaticPairList`
|
||||||
* uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`
|
* It uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`.
|
||||||
* `"VolumePairList"`
|
* `VolumePairList`
|
||||||
* Formerly available as `--dynamic-whitelist [<number_assets>]`
|
* It selects `number_assets` top pairs based on `sort_key`, which can be one of
|
||||||
* Selects `number_assets` top pairs based on `sort_key`, which can be one of `askVolume`, `bidVolume` and `quoteVolume`, defaults to `quoteVolume`.
|
`askVolume`, `bidVolume` and `quoteVolume`, defaults to `quoteVolume`.
|
||||||
|
* There is a possibility to filter low-value coins that would not allow setting a stop loss
|
||||||
|
(set `precision_filter` parameter to `true` for this).
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
"pairlist": {
|
"pairlist": {
|
||||||
"method": "VolumePairList",
|
"method": "VolumePairList",
|
||||||
"config": {
|
"config": {
|
||||||
"number_assets": 20,
|
"number_assets": 20,
|
||||||
"sort_key": "quoteVolume"
|
"sort_key": "quoteVolume",
|
||||||
|
"precision_filter": false
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
|
||||||
## Switch to production mode
|
## Switch to production mode
|
||||||
|
|
||||||
In production mode, the bot will engage your money. Be careful a wrong
|
In production mode, the bot will engage your money. Be careful, since a wrong
|
||||||
strategy can lose all your money. Be aware of what you are doing when
|
strategy can lose all your money. Be aware of what you are doing when
|
||||||
you run it in production mode.
|
you run it in production mode.
|
||||||
|
|
||||||
|
|||||||
94
docs/data-analysis.md
Normal file
94
docs/data-analysis.md
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
# Analyzing bot data with Jupyter notebooks
|
||||||
|
|
||||||
|
You can analyze the results of backtests and trading history easily using Jupyter notebooks. Sample notebooks are located at `user_data/notebooks/`.
|
||||||
|
|
||||||
|
## Pro tips
|
||||||
|
|
||||||
|
* See [jupyter.org](https://jupyter.org/documentation) for usage instructions.
|
||||||
|
* Don't forget to start a Jupyter notebook server from within your conda or venv environment or use [nb_conda_kernels](https://github.com/Anaconda-Platform/nb_conda_kernels)*
|
||||||
|
* Copy the example notebook before use so your changes don't get clobbered with the next freqtrade update.
|
||||||
|
|
||||||
|
## Fine print
|
||||||
|
|
||||||
|
Some tasks don't work especially well in notebooks. For example, anything using asynchronous execution is a problem for Jupyter. Also, freqtrade's primary entry point is the shell cli, so using pure python in a notebook bypasses arguments that provide required objects and parameters to helper functions. You may need to set those values or create expected objects manually.
|
||||||
|
|
||||||
|
## Recommended workflow
|
||||||
|
|
||||||
|
| Task | Tool |
|
||||||
|
--- | ---
|
||||||
|
Bot operations | CLI
|
||||||
|
Repetitive tasks | Shell scripts
|
||||||
|
Data analysis & visualization | Notebook
|
||||||
|
|
||||||
|
1. Use the CLI to
|
||||||
|
* download historical data
|
||||||
|
* run a backtest
|
||||||
|
* run with real-time data
|
||||||
|
* export results
|
||||||
|
|
||||||
|
1. Collect these actions in shell scripts
|
||||||
|
* save complicated commands with arguments
|
||||||
|
* execute multi-step operations
|
||||||
|
* automate testing strategies and preparing data for analysis
|
||||||
|
|
||||||
|
1. Use a notebook to
|
||||||
|
* visualize data
|
||||||
|
* munge and plot to generate insights
|
||||||
|
|
||||||
|
## Example utility snippets
|
||||||
|
|
||||||
|
### Change directory to root
|
||||||
|
|
||||||
|
Jupyter notebooks execute from the notebook directory. The following snippet searches for the project root, so relative paths remain consistent.
|
||||||
|
|
||||||
|
```python
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# Change directory
|
||||||
|
# Modify this cell to insure that the output shows the correct path.
|
||||||
|
# Define all paths relative to the project root shown in the cell output
|
||||||
|
project_root = "somedir/freqtrade"
|
||||||
|
i=0
|
||||||
|
try:
|
||||||
|
os.chdirdir(project_root)
|
||||||
|
assert Path('LICENSE').is_file()
|
||||||
|
except:
|
||||||
|
while i<4 and (not Path('LICENSE').is_file()):
|
||||||
|
os.chdir(Path(Path.cwd(), '../'))
|
||||||
|
i+=1
|
||||||
|
project_root = Path.cwd()
|
||||||
|
print(Path.cwd())
|
||||||
|
```
|
||||||
|
|
||||||
|
### Load multiple configuration files
|
||||||
|
|
||||||
|
This option can be useful to inspect the results of passing in multiple configs.
|
||||||
|
This will also run through the whole Configuration initialization, so the configuration is completely initialized to be passed to other methods.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
import json
|
||||||
|
from freqtrade.configuration import Configuration
|
||||||
|
|
||||||
|
# Load config from multiple files
|
||||||
|
config = Configuration.from_files(["config1.json", "config2.json"])
|
||||||
|
|
||||||
|
# Show the config in memory
|
||||||
|
print(json.dumps(config['original_config'], indent=2))
|
||||||
|
```
|
||||||
|
|
||||||
|
For Interactive environments, have an additional configuration specifying `user_data_dir` and pass this in last, so you don't have to change directories while running the bot.
|
||||||
|
Best avoid relative paths, since this starts at the storage location of the jupyter notebook, unless the directory is changed.
|
||||||
|
|
||||||
|
``` json
|
||||||
|
{
|
||||||
|
"user_data_dir": "~/.freqtrade/"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Further Data analysis documentation
|
||||||
|
|
||||||
|
* [Strategy debugging](strategy_analysis_example.md) - also available as Jupyter notebook (`user_data/notebooks/strategy_analysis_example.ipynb`)
|
||||||
|
* [Plotting](plotting.md)
|
||||||
|
|
||||||
|
Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.
|
||||||
88
docs/data-download.md
Normal file
88
docs/data-download.md
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
# Data Downloading
|
||||||
|
|
||||||
|
## Getting data for backtesting and hyperopt
|
||||||
|
|
||||||
|
To download data (candles / OHLCV) needed for backtesting and hyperoptimization use the `freqtrade download-data` command.
|
||||||
|
|
||||||
|
If no additional parameter is specified, freqtrade will download data for `"1m"` and `"5m"` timeframes for the last 30 days.
|
||||||
|
Exchange and pairs will come from `config.json` (if specified using `-c/--config`).
|
||||||
|
Otherwise `--exchange` becomes mandatory.
|
||||||
|
|
||||||
|
!!! 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.
|
||||||
|
Be carefull though: If the number is too small (which would result in a few missing days), the whole dataset will be removed and only xx days will be downloaded.
|
||||||
|
|
||||||
|
### Pairs file
|
||||||
|
|
||||||
|
In alternative to the whitelist from `config.json`, a `pairs.json` file can be used.
|
||||||
|
|
||||||
|
If you are using Binance for example:
|
||||||
|
|
||||||
|
- create a directory `user_data/data/binance` and copy or create the `pairs.json` file in that directory.
|
||||||
|
- update the `pairs.json` file to contain the currency pairs you are interested in.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p user_data/data/binance
|
||||||
|
cp freqtrade/tests/testdata/pairs.json user_data/data/binance
|
||||||
|
```
|
||||||
|
|
||||||
|
The format of the `pairs.json` file is a simple json list.
|
||||||
|
Mixing different stake-currencies is allowed for this file, since it's only used for downloading.
|
||||||
|
|
||||||
|
``` json
|
||||||
|
[
|
||||||
|
"ETH/BTC",
|
||||||
|
"ETH/USDT",
|
||||||
|
"BTC/USDT",
|
||||||
|
"XRP/ETH"
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Start download
|
||||||
|
|
||||||
|
Then run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade download-data --exchange binance
|
||||||
|
```
|
||||||
|
|
||||||
|
This will download ticker data for all the currency pairs you defined in `pairs.json`.
|
||||||
|
|
||||||
|
### Other Notes
|
||||||
|
|
||||||
|
- To use a different directory than the exchange specific default, use `--datadir user_data/data/some_directory`.
|
||||||
|
- To change the exchange used to download the tickers, please use a different configuration file (you'll probably need to adjust ratelimits etc.)
|
||||||
|
- To use `pairs.json` from some other directory, use `--pairs-file some_other_dir/pairs.json`.
|
||||||
|
- To download ticker data for only 10 days, use `--days 10` (defaults to 30 days).
|
||||||
|
- Use `--timeframes` to specify which tickers to download. Default is `--timeframes 1m 5m` which will download 1-minute and 5-minute tickers.
|
||||||
|
- To use exchange, timeframe and list of pairs as defined in your configuration file, use the `-c/--config` option. With this, the script uses the whitelist defined in the config as the list of currency pairs to download data for and does not require the pairs.json file. You can combine `-c/--config` with most other options.
|
||||||
|
|
||||||
|
### Trades (tick) data
|
||||||
|
|
||||||
|
By default, `download-data` subcommand downloads Candles (OHLCV) data. Some exchanges also provide historic trade-data via their API.
|
||||||
|
This data can be useful if you need many different timeframes, since it is only downloaded once, and then resampled locally to the desired timeframes.
|
||||||
|
|
||||||
|
Since this data is large by default, the files use gzip by default. They are stored in your data-directory with the naming convention of `<pair>-trades.json.gz` (`ETH_BTC-trades.json.gz`). Incremental mode is also supported, as for historic OHLCV data, so downloading the data once per week with `--days 8` will create an incremental data-repository.
|
||||||
|
|
||||||
|
To use this mode, simply add `--dl-trades` to your call. This will swap the download method to download trades, and resamples the data locally.
|
||||||
|
|
||||||
|
Example call:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade download-data --exchange binance --pairs XRP/ETH ETH/BTC --days 20 --dl-trades
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
While this method uses async calls, it will be slow, since it requires the result of the previous call to generate the next request to the exchange.
|
||||||
|
|
||||||
|
!!! Warning
|
||||||
|
The historic trades are not available during Freqtrade dry-run and live trade modes because all exchanges tested provide this data with a delay of few 100 candles, so it's not suitable for real-time trading.
|
||||||
|
|
||||||
|
### Historic Kraken data
|
||||||
|
|
||||||
|
The Kraken API does only provide 720 historic candles, which is sufficient for FreqTrade dry-run and live trade modes, but is a problem for backtesting.
|
||||||
|
To download data for the Kraken exchange, using `--dl-trades` is mandatory, otherwise the bot will download the same 720 candles over and over, and you'll not have enough backtest data.
|
||||||
|
|
||||||
|
## Next step
|
||||||
|
|
||||||
|
Great, you now have backtest data downloaded, so you can now start [backtesting](backtesting.md) your strategy.
|
||||||
26
docs/deprecated.md
Normal file
26
docs/deprecated.md
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
# Deprecated features
|
||||||
|
|
||||||
|
This page contains description of the command line arguments, configuration parameters
|
||||||
|
and the bot features that were declared as DEPRECATED by the bot development team
|
||||||
|
and are no longer supported. Please avoid their usage in your configuration.
|
||||||
|
|
||||||
|
## Removed features
|
||||||
|
|
||||||
|
### the `--refresh-pairs-cached` command line option
|
||||||
|
|
||||||
|
`--refresh-pairs-cached` in the context of backtesting, hyperopt and edge allows to refresh candle data for backtesting.
|
||||||
|
Since this leads to much confusion, and slows down backtesting (while not being part of backtesting) this has been singled out
|
||||||
|
as a seperate freqtrade subcommand `freqtrade download-data`.
|
||||||
|
|
||||||
|
This command line option was deprecated in 2019.7-dev (develop branch) and removed in 2019.9 (master branch).
|
||||||
|
|
||||||
|
### The **--dynamic-whitelist** command line option
|
||||||
|
|
||||||
|
This command line option was deprecated in 2018 and removed freqtrade 2019.6-dev (develop branch)
|
||||||
|
and in freqtrade 2019.7 (master branch).
|
||||||
|
|
||||||
|
### the `--live` command line option
|
||||||
|
|
||||||
|
`--live` in the context of backtesting allowed to download the latest tick data for backtesting.
|
||||||
|
Did only download the latest 500 candles, so was ineffective in getting good backtest data.
|
||||||
|
Removed in 2019-7-dev (develop branch) and in freqtrade 2019-8 (master branch)
|
||||||
@@ -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.
|
This page is intended for developers of FreqTrade, people who want to contribute to the FreqTrade codebase or documentation, or people who want to understand the source code of the application they're running.
|
||||||
|
|
||||||
All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We [track issues](https://github.com/freqtrade/freqtrade/issues) on [GitHub](https://github.com) and also have a dev channel in [slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE) where you can ask questions.
|
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.
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
@@ -12,11 +12,74 @@ Special fields for the documentation (like Note boxes, ...) can be found [here](
|
|||||||
|
|
||||||
## Developer setup
|
## Developer setup
|
||||||
|
|
||||||
To configure a development environment, use best use the `setup.sh` script and answer "y" when asked "Do you want to install dependencies for dev [y/N]? ".
|
To configure a development environment, best use the `setup.sh` script and answer "y" when asked "Do you want to install dependencies for dev [y/N]? ".
|
||||||
Alternatively (if your system is not supported by the setup.sh script), follow the manual installation process and run `pip3 install -r requirements-dev.txt`.
|
Alternatively (if your system is not supported by the setup.sh script), follow the manual installation process and run `pip3 install -e .[all]`.
|
||||||
|
|
||||||
This will install all required tools for development, including `pytest`, `flake8`, `mypy`, and `coveralls`.
|
This will install all required tools for development, including `pytest`, `flake8`, `mypy`, and `coveralls`.
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
|
||||||
|
New code should be covered by basic unittests. Depending on the complexity of the feature, Reviewers may request more in-depth unittests.
|
||||||
|
If necessary, the Freqtrade team can assist and give guidance with writing good tests (however please don't expect anyone to write the tests for you).
|
||||||
|
|
||||||
|
#### Checking log content in tests
|
||||||
|
|
||||||
|
Freqtrade uses 2 main methods to check log content in tests, `log_has()` and `log_has_re()` (to check using regex, in case of dynamic log-messages).
|
||||||
|
These are available from `conftest.py` and can be imported in any test module.
|
||||||
|
|
||||||
|
A sample check looks as follows:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
from tests.conftest import log_has, log_has_re
|
||||||
|
|
||||||
|
def test_method_to_test(caplog):
|
||||||
|
method_to_test()
|
||||||
|
|
||||||
|
assert log_has("This event happened", caplog)
|
||||||
|
# Check regex with trailing number ...
|
||||||
|
assert log_has_re(r"This dynamic event happened and produced \d+", caplog)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
### Local docker usage
|
||||||
|
|
||||||
|
The fastest and easiest way to start up is to use docker-compose.develop which gives developers the ability to start the bot up with all the required dependencies, *without* needing to install any freqtrade specific dependencies on your local machine.
|
||||||
|
|
||||||
|
#### Install
|
||||||
|
* [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||||
|
* [docker](https://docs.docker.com/install/)
|
||||||
|
* [docker-compose](https://docs.docker.com/compose/install/)
|
||||||
|
|
||||||
|
#### Starting the bot
|
||||||
|
##### Use the develop dockerfile
|
||||||
|
``` bash
|
||||||
|
rm docker-compose.yml && mv docker-compose.develop.yml docker-compose.yml
|
||||||
|
```
|
||||||
|
#### Docker Compose
|
||||||
|
|
||||||
|
##### Starting
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
docker-compose up
|
||||||
|
```
|
||||||
|

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

|
||||||
|
|
||||||
|
|
||||||
## Modules
|
## Modules
|
||||||
|
|
||||||
### Dynamic Pairlist
|
### Dynamic Pairlist
|
||||||
@@ -81,11 +144,65 @@ Please also run `self._validate_whitelist(pairs)` and to check and remove pairs
|
|||||||
This is a simple method used by `VolumePairList` - however serves as a good example.
|
This is a simple method used by `VolumePairList` - however serves as a good example.
|
||||||
It implements caching (`@cached(TTLCache(maxsize=1, ttl=1800))`) as well as a configuration option to allow different (but similar) strategies to work with the same PairListProvider.
|
It implements caching (`@cached(TTLCache(maxsize=1, ttl=1800))`) as well as a configuration option to allow different (but similar) strategies to work with the same PairListProvider.
|
||||||
|
|
||||||
|
## Implement a new Exchange (WIP)
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
This section is a Work in Progress and is not a complete guide on how to test a new exchange with FreqTrade.
|
||||||
|
|
||||||
|
Most exchanges supported by CCXT should work out of the box.
|
||||||
|
|
||||||
|
### Stoploss On Exchange
|
||||||
|
|
||||||
|
Check if the new exchange supports Stoploss on Exchange orders through their API.
|
||||||
|
|
||||||
|
Since CCXT does not provide unification for Stoploss On Exchange yet, we'll need to implement the exchange-specific parameters ourselfs. Best look at `binance.py` for an example implementation of this. You'll need to dig through the documentation of the Exchange's API on how exactly this can be done. [CCXT Issues](https://github.com/ccxt/ccxt/issues) may also provide great help, since others may have implemented something similar for their projects.
|
||||||
|
|
||||||
|
### Incomplete candles
|
||||||
|
|
||||||
|
While fetching OHLCV data, we're may end up getting incomplete candles (Depending on the exchange).
|
||||||
|
To demonstrate this, we'll use daily candles (`"1d"`) to keep things simple.
|
||||||
|
We query the api (`ct.fetch_ohlcv()`) for the timeframe and look at the date of the last entry. If this entry changes or shows the date of a "incomplete" candle, then we should drop this since having incomplete candles is problematic because indicators assume that only complete candles are passed to them, and will generate a lot of false buy signals. By default, we're therefore removing the last candle assuming it's incomplete.
|
||||||
|
|
||||||
|
To check how the new exchange behaves, you can use the following snippet:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
import ccxt
|
||||||
|
from datetime import datetime
|
||||||
|
from freqtrade.data.converter import parse_ticker_dataframe
|
||||||
|
ct = ccxt.binance()
|
||||||
|
timeframe = "1d"
|
||||||
|
pair = "XLM/BTC" # Make sure to use a pair that exists on that exchange!
|
||||||
|
raw = ct.fetch_ohlcv(pair, timeframe=timeframe)
|
||||||
|
|
||||||
|
# convert to dataframe
|
||||||
|
df1 = parse_ticker_dataframe(raw, timeframe, pair=pair, drop_incomplete=False)
|
||||||
|
|
||||||
|
print(df1["date"].tail(1))
|
||||||
|
print(datetime.utcnow())
|
||||||
|
```
|
||||||
|
|
||||||
|
``` output
|
||||||
|
19 2019-06-08 00:00:00+00:00
|
||||||
|
2019-06-09 12:30:27.873327
|
||||||
|
```
|
||||||
|
|
||||||
|
The output will show the last entry from the Exchange as well as the current UTC date.
|
||||||
|
If the day shows the same day, then the last candle can be assumed as incomplete and should be dropped (leave the setting `"ohlcv_partial_candle"` from the exchange-class untouched / True). Otherwise, set `"ohlcv_partial_candle"` to `False` to not drop Candles (shown in the example above).
|
||||||
|
|
||||||
|
## Updating example notebooks
|
||||||
|
|
||||||
|
To keep the jupyter notebooks aligned with the documentation, the following should be ran after updating a example notebook.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace user_data/notebooks/strategy_analysis_example.ipynb
|
||||||
|
jupyter nbconvert --ClearOutputPreprocessor.enabled=True --to markdown user_data/notebooks/strategy_analysis_example.ipynb --stdout > docs/strategy_analysis_example.md
|
||||||
|
```
|
||||||
|
|
||||||
## Creating a release
|
## Creating a release
|
||||||
|
|
||||||
This part of the documentation is aimed at maintainers, and shows how to create a release.
|
This part of the documentation is aimed at maintainers, and shows how to create a release.
|
||||||
|
|
||||||
### create release branch
|
### Create release branch
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
# make sure you're in develop branch
|
# make sure you're in develop branch
|
||||||
@@ -95,11 +212,14 @@ git checkout develop
|
|||||||
git checkout -b new_release
|
git checkout -b new_release
|
||||||
```
|
```
|
||||||
|
|
||||||
* edit `freqtrade/__init__.py` and add the desired version (for example `0.18.0`)
|
* Edit `freqtrade/__init__.py` and add the version matching the current date (for example `2019.7` for July 2019). Minor versions can be `2019.7-1` should we need to do a second release that month.
|
||||||
* Commit this part
|
* Commit this part
|
||||||
* push that branch to the remote and create a PR
|
* push that branch to the remote and create a PR against the master branch
|
||||||
|
|
||||||
### create changelog from git commits
|
### Create changelog from git commits
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Make sure that both master and develop are up-todate!.
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
# Needs to be done before merging / pulling that branch.
|
# Needs to be done before merging / pulling that branch.
|
||||||
@@ -108,10 +228,14 @@ git log --oneline --no-decorate --no-merges master..develop
|
|||||||
|
|
||||||
### Create github release / tag
|
### Create github release / tag
|
||||||
|
|
||||||
* Use the version-number specified as tag.
|
Once the PR against master is merged (best right after merging):
|
||||||
|
|
||||||
|
* Use the button "Draft a new release" in the Github UI (subsection releases)
|
||||||
|
* Use the version-number specified as tag.
|
||||||
* Use "master" as reference (this step comes after the above PR is merged).
|
* Use "master" as reference (this step comes after the above PR is merged).
|
||||||
* use the above changelog as release comment (as codeblock)
|
* Use the above changelog as release comment (as codeblock)
|
||||||
|
|
||||||
### After-release
|
### After-release
|
||||||
|
|
||||||
* update version in develop to next valid version and postfix that with `-dev` (`0.18.0 -> 0.18.1-dev`)
|
* Update version in develop by postfixing that with `-dev` (`2019.6 -> 2019.6-dev`).
|
||||||
|
* Create a PR against develop to update that branch.
|
||||||
|
|||||||
208
docs/docker.md
Normal file
208
docs/docker.md
Normal file
@@ -0,0 +1,208 @@
|
|||||||
|
# Using FreqTrade with Docker
|
||||||
|
|
||||||
|
## Install Docker
|
||||||
|
|
||||||
|
Start by downloading and installing Docker CE for your platform:
|
||||||
|
|
||||||
|
* [Mac](https://docs.docker.com/docker-for-mac/install/)
|
||||||
|
* [Windows](https://docs.docker.com/docker-for-windows/install/)
|
||||||
|
* [Linux](https://docs.docker.com/install/)
|
||||||
|
|
||||||
|
Once you have Docker installed, simply prepare the config file (e.g. `config.json`) and run the image for `freqtrade` as explained below.
|
||||||
|
|
||||||
|
## Download the official FreqTrade docker image
|
||||||
|
|
||||||
|
Pull the image from docker hub.
|
||||||
|
|
||||||
|
Branches / tags available can be checked out on [Dockerhub](https://hub.docker.com/r/freqtradeorg/freqtrade/tags/).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker pull freqtradeorg/freqtrade:develop
|
||||||
|
# Optionally tag the repository so the run-commands remain shorter
|
||||||
|
docker tag freqtradeorg/freqtrade:develop freqtrade
|
||||||
|
```
|
||||||
|
|
||||||
|
To update the image, simply run the above commands again and restart your running container.
|
||||||
|
|
||||||
|
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 `master`, `develop` and `latest` are automatically rebuild once a week to keep the base image uptodate.
|
||||||
|
In addition to that, every merge to `develop` will trigger a rebuild for `develop` and `latest`.
|
||||||
|
|
||||||
|
### 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
|
||||||
|
|
||||||
|
Production
|
||||||
|
|
||||||
|
```bash
|
||||||
|
touch tradesv3.sqlite
|
||||||
|
````
|
||||||
|
|
||||||
|
Dry-Run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
touch tradesv3.dryrun.sqlite
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Make sure to use the path to this 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/Dockerfile.technical) which adds the [technical](https://github.com/freqtrade/technical) module to the image.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -t freqtrade -f Dockerfile.technical .
|
||||||
|
```
|
||||||
|
|
||||||
|
If you are developing using Docker, use `Dockerfile.develop` to build a dev Docker image, which will also set up develop dependencies:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -f Dockerfile.develop -t freqtrade-dev .
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
For security reasons, your configuration file will not be included in the image, you will need to bind mount it. It is also advised to bind mount an SQLite database file (see the "5. Run a restartable docker image" section) to keep it between updates.
|
||||||
|
|
||||||
|
#### 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 will refresh your image.
|
||||||
|
|
||||||
|
#### Adjust timezone
|
||||||
|
|
||||||
|
By default, the container will use UTC timezone.
|
||||||
|
Should you find this irritating please add the following to your docker 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
|
||||||
|
|
||||||
|
There is known issue in OSX Docker versions after 17.09.1, whereby `/etc/localtime` cannot be shared causing Docker to not start. A work-around for this is to start with the following cmd.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run --rm -e TZ=`ls -la /etc/localtime | cut -d/ -f8-9` -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
||||||
|
```
|
||||||
|
|
||||||
|
More information on this docker issue and work-around can be read [here](https://github.com/docker/for-mac/issues/2396).
|
||||||
|
|
||||||
|
### 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).
|
||||||
|
|
||||||
|
#### 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
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 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 --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
db-url defaults to `sqlite:///tradesv3.sqlite` but it defaults to `sqlite://` if `dry_run=True` is being used.
|
||||||
|
To override this behaviour use a custom db-url value: i.e.: `--db-url sqlite:///tradesv3.dryrun.sqlite`
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
All available bot command line parameters can be added to the end of the `docker run` command.
|
||||||
|
|
||||||
|
### 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 --strategy AwsomelyProfitableStrategy backtesting
|
||||||
|
```
|
||||||
|
|
||||||
|
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).
|
||||||
217
docs/edge.md
217
docs/edge.md
@@ -3,165 +3,213 @@
|
|||||||
This page explains how to use Edge Positioning module in your bot in order to enter into a trade only if the trade has a reasonable win rate and risk reward ratio, and consequently adjust your position size and stoploss.
|
This page explains how to use Edge Positioning module in your bot in order to enter into a trade only if the trade has a reasonable win rate and risk reward ratio, and consequently adjust your position size and stoploss.
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
Edge positioning is not compatible with dynamic whitelist. it overrides dynamic whitelist.
|
Edge positioning is not compatible with dynamic (volume-based) whitelist.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Edge won't consider anything else than buy/sell/stoploss signals. So trailing stoploss, ROI, and everything else will be ignored in its calculation.
|
Edge does not consider anything else than buy/sell/stoploss signals. So trailing stoploss, ROI, and everything else are ignored in its calculation.
|
||||||
|
|
||||||
## Introduction
|
## Introduction
|
||||||
Trading is all about probability. No one can claim that he has a strategy working all the time. You have to assume that sometimes you lose.<br/><br/>
|
Trading is all about probability. No one can claim that he has a strategy working all the time. You have to assume that sometimes you lose.
|
||||||
But it doesn't mean there is no rule, it only means rules should work "most of the time". Let's play a game: we toss a coin, heads: I give you 10$, tails: You give me 10$. Is it an interesting game ? no, it is quite boring, isn't it?<br/><br/>
|
|
||||||
But let's say the probability that we have heads is 80%, and the probability that we have tails is 20%. Now it is becoming interesting ...
|
But it doesn't mean there is no rule, it only means rules should work "most of the time". Let's play a game: we toss a coin, heads: I give you 10$, tails: you give me 10$. Is it an interesting game? No, it's quite boring, isn't it?
|
||||||
That means 10$ x 80% versus 10$ x 20%. 8$ versus 2$. That means over time you will win 8$ risking only 2$ on each toss of coin.<br/><br/>
|
|
||||||
Let's complicate it more: you win 80% of the time but only 2$, I win 20% of the time but 8$. The calculation is: 80% * 2$ versus 20% * 8$. It is becoming boring again because overtime you win $1.6$ (80% x 2$) and me $1.6 (20% * 8$) too.<br/><br/>
|
But let's say the probability that we have heads is 80% (because our coin has the displaced distribution of mass or other defect), and the probability that we have tails is 20%. Now it is becoming interesting...
|
||||||
The question is: How do you calculate that? how do you know if you wanna play?
|
|
||||||
|
That means 10$ X 80% versus 10$ X 20%. 8$ versus 2$. That means over time you will win 8$ risking only 2$ on each toss of coin.
|
||||||
|
|
||||||
|
Let's complicate it more: you win 80% of the time but only 2$, I win 20% of the time but 8$. The calculation is: 80% X 2$ versus 20% X 8$. It is becoming boring again because overtime you win $1.6$ (80% X 2$) and me $1.6 (20% X 8$) too.
|
||||||
|
|
||||||
|
The question is: How do you calculate that? How do you know if you wanna play?
|
||||||
|
|
||||||
The answer comes to two factors:
|
The answer comes to two factors:
|
||||||
- Win Rate
|
- Win Rate
|
||||||
- Risk Reward Ratio
|
- Risk Reward Ratio
|
||||||
|
|
||||||
|
|
||||||
### Win Rate
|
### Win Rate
|
||||||
Means over X trades what is the percentage of winning trades to total number of trades (note that we don't consider how much you gained but only If you won or not).
|
Win Rate (*W*) is is the mean over some amount of trades (*N*) what is the percentage of winning trades to total number of trades (note that we don't consider how much you gained but only if you won or not).
|
||||||
|
|
||||||
|
W = (Number of winning trades) / (Total number of trades) = (Number of winning trades) / N
|
||||||
|
|
||||||
`W = (Number of winning trades) / (Total number of trades)`
|
Complementary Loss Rate (*L*) is defined as
|
||||||
|
|
||||||
|
L = (Number of losing trades) / (Total number of trades) = (Number of losing trades) / N
|
||||||
|
|
||||||
|
or, which is the same, as
|
||||||
|
|
||||||
|
L = 1 – W
|
||||||
|
|
||||||
### Risk Reward Ratio
|
### Risk Reward Ratio
|
||||||
Risk Reward Ratio is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose:
|
Risk Reward Ratio (*R*) is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose:
|
||||||
|
|
||||||
`R = Profit / Loss`
|
R = Profit / Loss
|
||||||
|
|
||||||
Over time, on many trades, you can calculate your risk reward by dividing your average profit on winning trades by your average loss on losing trades:
|
Over time, on many trades, you can calculate your risk reward by dividing your average profit on winning trades by your average loss on losing trades:
|
||||||
|
|
||||||
`Average profit = (Sum of profits) / (Number of winning trades)`
|
Average profit = (Sum of profits) / (Number of winning trades)
|
||||||
|
|
||||||
`Average loss = (Sum of losses) / (Number of losing trades)`
|
Average loss = (Sum of losses) / (Number of losing trades)
|
||||||
|
|
||||||
`R = (Average profit) / (Average loss)`
|
R = (Average profit) / (Average loss)
|
||||||
|
|
||||||
### Expectancy
|
### Expectancy
|
||||||
|
At this point we can combine *W* and *R* to create an expectancy ratio. This is a simple process of multiplying the risk reward ratio by the percentage of winning trades and subtracting the percentage of losing trades, which is calculated as follows:
|
||||||
|
|
||||||
At this point we can combine W and R to create an expectancy ratio. This is a simple process of multiplying the risk reward ratio by the percentage of winning trades, and subtracting the percentage of losing trades, which is calculated as follows:
|
Expectancy Ratio = (Risk Reward Ratio X Win Rate) – Loss Rate = (R X W) – L
|
||||||
|
|
||||||
Expectancy Ratio = (Risk Reward Ratio x Win Rate) – Loss Rate
|
|
||||||
|
|
||||||
So lets say your Win rate is 28% and your Risk Reward Ratio is 5:
|
So lets say your Win rate is 28% and your Risk Reward Ratio is 5:
|
||||||
|
|
||||||
`Expectancy = (5 * 0.28) - 0.72 = 0.68`
|
Expectancy = (5 X 0.28) – 0.72 = 0.68
|
||||||
|
|
||||||
Superficially, this means that on average you expect this strategy’s trades to return .68 times the size of your losers. This is important for two reasons: First, it may seem obvious, but you know right away that you have a positive return. Second, you now have a number you can compare to other candidate systems to make decisions about which ones you employ.
|
Superficially, this means that on average you expect this strategy’s trades to return .68 times the size of your loses. This is important for two reasons: First, it may seem obvious, but you know right away that you have a positive return. Second, you now have a number you can compare to other candidate systems to make decisions about which ones you employ.
|
||||||
|
|
||||||
It is important to remember that any system with an expectancy greater than 0 is profitable using past data. The key is finding one that will be profitable in the future.
|
It is important to remember that any system with an expectancy greater than 0 is profitable using past data. The key is finding one that will be profitable in the future.
|
||||||
|
|
||||||
You can also use this number to evaluate the effectiveness of modifications to this system.
|
You can also use this value to evaluate the effectiveness of modifications to this system.
|
||||||
|
|
||||||
**NOTICE:** It's important to keep in mind that Edge is testing your expectancy using historical data , there's no guarantee that you will have a similar edge in the future. It's still vital to do this testing in order to build confidence in your methodology, but be wary of "curve-fitting" your approach to the historical data as things are unlikely to play out the exact same way for future trades.
|
**NOTICE:** It's important to keep in mind that Edge is testing your expectancy using historical data, there's no guarantee that you will have a similar edge in the future. It's still vital to do this testing in order to build confidence in your methodology, but be wary of "curve-fitting" your approach to the historical data as things are unlikely to play out the exact same way for future trades.
|
||||||
|
|
||||||
## How does it work?
|
## How does it work?
|
||||||
If enabled in config, Edge will go through historical data with a range of stoplosses in order to find buy and sell/stoploss signals. It then calculates win rate and expectancy over X trades for each stoploss. Here is an example:
|
If enabled in config, Edge will go through historical data with a range of stoplosses in order to find buy and sell/stoploss signals. It then calculates win rate and expectancy over *N* trades for each stoploss. Here is an example:
|
||||||
|
|
||||||
| Pair | Stoploss | Win Rate | Risk Reward Ratio | Expectancy |
|
| Pair | Stoploss | Win Rate | Risk Reward Ratio | Expectancy |
|
||||||
|----------|:-------------:|-------------:|------------------:|-----------:|
|
|----------|:-------------:|-------------:|------------------:|-----------:|
|
||||||
| XZC/ETH | -0.03 | 0.52 |1.359670 | 0.228 |
|
|
||||||
| XZC/ETH | -0.01 | 0.50 |1.176384 | 0.088 |
|
| XZC/ETH | -0.01 | 0.50 |1.176384 | 0.088 |
|
||||||
| XZC/ETH | -0.02 | 0.51 |1.115941 | 0.079 |
|
| XZC/ETH | -0.02 | 0.51 |1.115941 | 0.079 |
|
||||||
|
| XZC/ETH | -0.03 | 0.52 |1.359670 | 0.228 |
|
||||||
|
| XZC/ETH | -0.04 | 0.51 |1.234539 | 0.117 |
|
||||||
|
|
||||||
The goal here is to find the best stoploss for the strategy in order to have the maximum expectancy. In the above example stoploss at 3% leads to the maximum expectancy according to historical data.
|
The goal here is to find the best stoploss for the strategy in order to have the maximum expectancy. In the above example stoploss at 3% leads to the maximum expectancy according to historical data.
|
||||||
|
|
||||||
Edge then forces stoploss to your strategy dynamically.
|
Edge module then forces stoploss value it evaluated to your strategy dynamically.
|
||||||
|
|
||||||
### Position size
|
### Position size
|
||||||
Edge dictates the stake amount for each trade to the bot according to the following factors:
|
Edge also dictates the stake amount for each trade to the bot according to the following factors:
|
||||||
|
|
||||||
- Allowed capital at risk
|
- Allowed capital at risk
|
||||||
- Stoploss
|
- Stoploss
|
||||||
|
|
||||||
Allowed capital at risk is calculated as follows:
|
Allowed capital at risk is calculated as follows:
|
||||||
|
|
||||||
**allowed capital at risk** = **capital_available_percentage** X **allowed risk per trade**
|
Allowed capital at risk = (Capital available_percentage) X (Allowed risk per trade)
|
||||||
|
|
||||||
**Stoploss** is calculated as described above against historical data.
|
Stoploss is calculated as described above against historical data.
|
||||||
|
|
||||||
Your position size then will be:
|
Your position size then will be:
|
||||||
|
|
||||||
**position size** = **allowed capital at risk** / **stoploss**
|
Position size = (Allowed capital at risk) / Stoploss
|
||||||
|
|
||||||
Example:<br/>
|
Example:
|
||||||
Let's say the stake currency is ETH and you have 10 ETH on the exchange, your **capital_available_percentage** is 50% and you would allow 1% of risk for each trade. thus your available capital for trading is **10 x 0.5 = 5 ETH** and allowed capital at risk would be **5 x 0.01 = 0.05 ETH**. <br/>
|
|
||||||
Let's assume Edge has calculated that for **XLM/ETH** market your stoploss should be at 2%. So your position size will be **0.05 / 0.02 = 2.5ETH**.<br/>
|
Let's say the stake currency is ETH and you have 10 ETH on the exchange, your capital available percentage is 50% and you would allow 1% of risk for each trade. thus your available capital for trading is **10 x 0.5 = 5 ETH** and allowed capital at risk would be **5 x 0.01 = 0.05 ETH**.
|
||||||
Bot takes a position of 2.5ETH on XLM/ETH (call it trade 1). Up next, you receive another buy signal while trade 1 is still open. This time on BTC/ETH market. Edge calculated stoploss for this market at 4%. So your position size would be 0.05 / 0.04 = 1.25ETH (call it trade 2).<br/>
|
|
||||||
Note that available capital for trading didn’t change for trade 2 even if you had already trade 1. The available capital doesn’t mean the free amount on your wallet.<br/>
|
Let's assume Edge has calculated that for **XLM/ETH** market your stoploss should be at 2%. So your position size will be **0.05 / 0.02 = 2.5 ETH**.
|
||||||
Now you have two trades open. The Bot receives yet another buy signal for another market: **ADA/ETH**. This time the stoploss is calculated at 1%. So your position size is **0.05 / 0.01 = 5ETH**. But there are already 4ETH blocked in two previous trades. So the position size for this third trade would be 1ETH.<br/>
|
|
||||||
Available capital doesn’t change before a position is sold. Let’s assume that trade 1 receives a sell signal and it is sold with a profit of 1ETH. Your total capital on exchange would be 11 ETH and the available capital for trading becomes 5.5ETH. <br/>
|
Bot takes a position of 2.5 ETH on XLM/ETH (call it trade 1). Up next, you receive another buy signal while trade 1 is still open. This time on **BTC/ETH** market. Edge calculated stoploss for this market at 4%. So your position size would be 0.05 / 0.04 = 1.25 ETH (call it trade 2).
|
||||||
So the Bot receives another buy signal for trade 4 with a stoploss at 2% then your position size would be **0.055 / 0.02 = 2.75**.
|
|
||||||
|
Note that available capital for trading didn’t change for trade 2 even if you had already trade 1. The available capital doesn’t mean the free amount on your wallet.
|
||||||
|
|
||||||
|
Now you have two trades open. The bot receives yet another buy signal for another market: **ADA/ETH**. This time the stoploss is calculated at 1%. So your position size is **0.05 / 0.01 = 5 ETH**. But there are already 3.75 ETH blocked in two previous trades. So the position size for this third trade would be **5 – 3.75 = 1.25 ETH**.
|
||||||
|
|
||||||
|
Available capital doesn’t change before a position is sold. Let’s assume that trade 1 receives a sell signal and it is sold with a profit of 1 ETH. Your total capital on exchange would be 11 ETH and the available capital for trading becomes 5.5 ETH.
|
||||||
|
|
||||||
|
So the Bot receives another buy signal for trade 4 with a stoploss at 2% then your position size would be **0.055 / 0.02 = 2.75 ETH**.
|
||||||
|
|
||||||
## Configurations
|
## Configurations
|
||||||
Edge has following configurations:
|
Edge module has following configuration options:
|
||||||
|
|
||||||
#### enabled
|
#### enabled
|
||||||
If true, then Edge will run periodically.<br/>
|
If true, then Edge will run periodically.
|
||||||
(default to false)
|
|
||||||
|
(defaults to false)
|
||||||
|
|
||||||
#### process_throttle_secs
|
#### process_throttle_secs
|
||||||
How often should Edge run in seconds? <br/>
|
How often should Edge run in seconds?
|
||||||
(default to 3600 so one hour)
|
|
||||||
|
(defaults to 3600 so one hour)
|
||||||
|
|
||||||
#### calculate_since_number_of_days
|
#### calculate_since_number_of_days
|
||||||
Number of days of data against which Edge calculates Win Rate, Risk Reward and Expectancy
|
Number of days of data against which Edge calculates Win Rate, Risk Reward and Expectancy
|
||||||
Note that it downloads historical data so increasing this number would lead to slowing down the bot.<br/>
|
Note that it downloads historical data so increasing this number would lead to slowing down the bot.
|
||||||
(default to 7)
|
|
||||||
|
(defaults to 7)
|
||||||
|
|
||||||
#### capital_available_percentage
|
#### capital_available_percentage
|
||||||
This is the percentage of the total capital on exchange in stake currency. <br/>
|
This is the percentage of the total capital on exchange in stake currency.
|
||||||
As an example if you have 10 ETH available in your wallet on the exchange and this value is 0.5 (which is 50%), then the bot will use a maximum amount of 5 ETH for trading and considers it as available capital.<br/>
|
|
||||||
(default to 0.5)
|
As an example if you have 10 ETH available in your wallet on the exchange and this value is 0.5 (which is 50%), then the bot will use a maximum amount of 5 ETH for trading and considers it as available capital.
|
||||||
|
|
||||||
|
(defaults to 0.5)
|
||||||
|
|
||||||
#### allowed_risk
|
#### allowed_risk
|
||||||
Percentage of allowed risk per trade.<br/>
|
Percentage of allowed risk per trade.
|
||||||
(default to 0.01 [1%])
|
|
||||||
|
(defaults to 0.01 so 1%)
|
||||||
|
|
||||||
#### stoploss_range_min
|
#### stoploss_range_min
|
||||||
Minimum stoploss.<br/>
|
|
||||||
(default to -0.01)
|
Minimum stoploss.
|
||||||
|
|
||||||
|
(defaults to -0.01)
|
||||||
|
|
||||||
#### stoploss_range_max
|
#### stoploss_range_max
|
||||||
Maximum stoploss.<br/>
|
|
||||||
(default to -0.10)
|
Maximum stoploss.
|
||||||
|
|
||||||
|
(defaults to -0.10)
|
||||||
|
|
||||||
#### stoploss_range_step
|
#### stoploss_range_step
|
||||||
As an example if this is set to -0.01 then Edge will test the strategy for [-0.01, -0,02, -0,03 ..., -0.09, -0.10] ranges.
|
|
||||||
Note than having a smaller step means having a bigger range which could lead to slow calculation. <br/>
|
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.
|
||||||
if you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10. <br/>
|
Note than having a smaller step means having a bigger range which could lead to slow calculation.
|
||||||
(default to -0.01)
|
|
||||||
|
If you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10.
|
||||||
|
|
||||||
|
(defaults to -0.01)
|
||||||
|
|
||||||
#### minimum_winrate
|
#### minimum_winrate
|
||||||
It filters pairs which don't have at least minimum_winrate.
|
|
||||||
This comes handy if you want to be conservative and don't comprise win rate in favor of risk reward ratio.<br/>
|
It filters out pairs which don't have at least minimum_winrate.
|
||||||
(default to 0.60)
|
|
||||||
|
This comes handy if you want to be conservative and don't comprise win rate in favour of risk reward ratio.
|
||||||
|
|
||||||
|
(defaults to 0.60)
|
||||||
|
|
||||||
#### minimum_expectancy
|
#### minimum_expectancy
|
||||||
It filters paris which have an expectancy lower than this number .
|
|
||||||
Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return.<br/>
|
It filters out pairs which have the expectancy lower than this number.
|
||||||
(default to 0.20)
|
|
||||||
|
Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return.
|
||||||
|
|
||||||
|
(defaults to 0.20)
|
||||||
|
|
||||||
#### min_trade_number
|
#### min_trade_number
|
||||||
When calculating W and R and E (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable. Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something. <br/>
|
|
||||||
(default to 10, it is highly recommended not to decrease this number)
|
When calculating *W*, *R* and *E* (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable.
|
||||||
|
|
||||||
|
Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something.
|
||||||
|
|
||||||
|
(defaults to 10, it is highly recommended not to decrease this number)
|
||||||
|
|
||||||
#### max_trade_duration_minute
|
#### max_trade_duration_minute
|
||||||
Edge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign.<br/>
|
|
||||||
**NOTICE:** While configuring this value, you should take into consideration your ticker interval. as an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. default value is set assuming your strategy interval is relatively small (1m or 5m, etc).<br/>
|
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.
|
||||||
(default to 1 day, 1440 = 60 * 24)
|
|
||||||
|
**NOTICE:** While configuring this value, you should take into consideration your ticker interval. As an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. Default value is set assuming your strategy interval is relatively small (1m or 5m, etc.).
|
||||||
|
|
||||||
|
(defaults to 1 day, i.e. to 60 * 24 = 1440 minutes)
|
||||||
|
|
||||||
#### remove_pumps
|
#### remove_pumps
|
||||||
Edge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off.<br/>
|
|
||||||
(default to false)
|
|
||||||
|
|
||||||
|
Edge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off.
|
||||||
|
|
||||||
|
(defaults to false)
|
||||||
|
|
||||||
## Running Edge independently
|
## Running Edge independently
|
||||||
|
|
||||||
You can run Edge independently in order to see in details the result. Here is an example:
|
You can run Edge independently in order to see in details the result. Here is an example:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py edge
|
freqtrade edge
|
||||||
```
|
```
|
||||||
|
|
||||||
An example of its output:
|
An example of its output:
|
||||||
@@ -185,28 +233,27 @@ An example of its output:
|
|||||||
| NEBL/BTC | -0.03 | 0.63 | 1.29 | 0.58 | 0.44 | 19 | 59 |
|
| NEBL/BTC | -0.03 | 0.63 | 1.29 | 0.58 | 0.44 | 19 | 59 |
|
||||||
|
|
||||||
### Update cached pairs with the latest data
|
### Update cached pairs with the latest data
|
||||||
```bash
|
|
||||||
python3 ./freqtrade/main.py edge --refresh-pairs-cached
|
Edge requires historic data the same way as backtesting does.
|
||||||
```
|
Please refer to the [download section](backtesting.md#Getting-data-for-backtesting-and-hyperopt) of the documentation for details.
|
||||||
|
|
||||||
### Precising stoploss range
|
### Precising stoploss range
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py edge --stoplosses=-0.01,-0.1,-0.001 #min,max,step
|
freqtrade edge --stoplosses=-0.01,-0.1,-0.001 #min,max,step
|
||||||
```
|
```
|
||||||
|
|
||||||
### Advanced use of timerange
|
### Advanced use of timerange
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py edge --timerange=20181110-20181113
|
freqtrade edge --timerange=20181110-20181113
|
||||||
```
|
```
|
||||||
|
|
||||||
Doing --timerange=-200 will get the last 200 timeframes from your inputdata. You can also specify specific dates, or a range span indexed by start and stop.
|
Doing `--timerange=-20190901` will get all available data until September 1st (excluding September 1st 2019).
|
||||||
|
|
||||||
The full timerange specification:
|
The full timerange specification:
|
||||||
|
|
||||||
* Use last 123 tickframes of data: --timerange=-123
|
* Use tickframes till 2018/01/31: `--timerange=-20180131`
|
||||||
* Use first 123 tickframes of data: --timerange=123-
|
* Use tickframes since 2018/01/31: `--timerange=20180131-`
|
||||||
* Use tickframes from line 123 through 456: --timerange=123-456
|
* Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
|
||||||
* Use tickframes till 2018/01/31: --timerange=-20180131
|
* Use tickframes between POSIX timestamps 1527595200 1527618600: `--timerange=1527595200-1527618600`
|
||||||
* Use tickframes since 2018/01/31: --timerange=20180131-
|
|
||||||
* Use tickframes since 2018/01/31 till 2018/03/01 : --timerange=20180131-20180301
|
|
||||||
* Use tickframes between POSIX timestamps 1527595200 1527618600: --timerange=1527595200-1527618600
|
|
||||||
|
|||||||
79
docs/faq.md
79
docs/faq.md
@@ -1,12 +1,25 @@
|
|||||||
# freqtrade FAQ
|
# Freqtrade FAQ
|
||||||
|
|
||||||
#### I have waited 5 minutes, why hasn't the bot made any trades yet?!
|
## Freqtrade common issues
|
||||||
|
|
||||||
|
### The bot does not start
|
||||||
|
|
||||||
|
Running the bot with `freqtrade --config config.json` does show the output `freqtrade: command not found`.
|
||||||
|
|
||||||
|
This could have the following reasons:
|
||||||
|
|
||||||
|
* 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?!
|
||||||
|
|
||||||
Depending on the buy strategy, the amount of whitelisted coins, the
|
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 good entry
|
||||||
position for a trade. Be patient!
|
position for a trade. Be patient!
|
||||||
|
|
||||||
#### 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
|
I understand your disappointment but unfortunately 12 trades is just
|
||||||
not enough to say anything. If you run backtesting, you can see that our
|
not enough to say anything. If you run backtesting, you can see that our
|
||||||
@@ -17,54 +30,82 @@ 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
|
gamble, which should leave you with modest wins on monthly basis but
|
||||||
you can't say much from few trades.
|
you can't say much from few trades.
|
||||||
|
|
||||||
#### I’d like to change the stake amount. Can I just stop the bot with
|
### 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?
|
||||||
/stop and then change the config.json and run it again?
|
|
||||||
|
|
||||||
Not quite. Trades are persisted to a database but the configuration is
|
Not quite. Trades are persisted to a database but the configuration is
|
||||||
currently only read when the bot is killed and restarted. `/stop` more
|
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.
|
like pauses. You can stop your bot, adjust settings and start it again.
|
||||||
|
|
||||||
#### I want to improve the bot with a new strategy
|
### I want to improve the bot with a new strategy
|
||||||
|
|
||||||
That's great. We have a nice backtesting and hyperoptimizing setup. See
|
That's great. We have a nice backtesting and hyperoptimization setup. See
|
||||||
the tutorial [here|Testing-new-strategies-with-Hyperopt](bot-usage.md#hyperopt-commands).
|
the tutorial [here|Testing-new-strategies-with-Hyperopt](bot-usage.md#hyperopt-commands).
|
||||||
|
|
||||||
#### Is there a setting to only SELL the coins being held and not
|
### Is there a setting to only SELL the coins being held and not perform anymore BUYS?
|
||||||
perform anymore BUYS?
|
|
||||||
|
|
||||||
You can use the `/forcesell all` command from Telegram.
|
You can use the `/forcesell all` command from Telegram.
|
||||||
|
|
||||||
|
### I get the message "RESTRICTED_MARKET"
|
||||||
|
|
||||||
|
Currently known to happen for US Bittrex users.
|
||||||
|
Bittrex split its exchange into US and International versions.
|
||||||
|
The International version has more pairs available, however the API always returns all pairs, so there is currently no automated way to detect if you're affected by the restriction.
|
||||||
|
|
||||||
|
If you have restricted pairs in your whitelist, you'll get a warning message in the log on FreqTrade startup for each restricted pair.
|
||||||
|
If you're an "International" Customer on the Bittrex exchange, then this warning will probably not impact you.
|
||||||
|
If you're a US customer, the bot will fail to create orders for these pairs, and you should remove them from your Whitelist.
|
||||||
|
|
||||||
|
## Hyperopt module
|
||||||
|
|
||||||
### How many epoch do I need to get a good Hyperopt result?
|
### How many epoch do I need to get a good Hyperopt result?
|
||||||
Per default Hyperopts without `-e` or `--epochs` parameter will only
|
|
||||||
run 100 epochs, means 100 evals of your triggers, guards, .... Too few
|
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
|
||||||
to find a great result (unless if you are very lucky), so you probably
|
to find a great result (unless if you are very lucky), so you probably
|
||||||
have to run it for 10.000 or more. But it will take an eternity to
|
have to run it for 10.000 or more. But it will take an eternity to
|
||||||
compute.
|
compute.
|
||||||
|
|
||||||
We recommend you to run it at least 10.000 epochs:
|
We recommend you to run it at least 10.000 epochs:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py hyperopt -e 10000
|
freqtrade hyperopt -e 10000
|
||||||
```
|
```
|
||||||
|
|
||||||
or if you want intermediate result to see
|
or if you want intermediate result to see
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
for i in {1..100}; do python3 ./freqtrade/main.py hyperopt -e 100; done
|
for i in {1..100}; do freqtrade hyperopt -e 100; done
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Why it is so long to run hyperopt?
|
### Why it is so long to run hyperopt?
|
||||||
|
|
||||||
Finding a great Hyperopt results takes time.
|
Finding a great Hyperopt results takes time.
|
||||||
|
|
||||||
If you wonder why it takes a while to find great hyperopt results
|
If you wonder why it takes a while to find great hyperopt results
|
||||||
|
|
||||||
This answer was written during the under the release 0.15.1, when we had
|
This answer was written during the under the release 0.15.1, when we had:
|
||||||
:
|
|
||||||
- 8 triggers
|
- 8 triggers
|
||||||
- 9 guards: let's say we evaluate even 10 values from each
|
- 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
|
- 1 stoploss calculation: let's say we want 10 values from that too to be evaluated
|
||||||
be evaluated
|
|
||||||
|
|
||||||
The following calculation is still very rough and not very precise
|
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
|
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.
|
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
|
Did you run 100 000 evals? Congrats, you've done roughly 1 / 100 000 th
|
||||||
of the search space.
|
of the search space.
|
||||||
|
|
||||||
|
## Edge module
|
||||||
|
|
||||||
|
### Edge implements interesting approach for controlling position size, is there any theory behind it?
|
||||||
|
|
||||||
|
The Edge module is mostly a result of brainstorming of [@mishaker](https://github.com/mishaker) and [@creslinux](https://github.com/creslinux) freqtrade team members.
|
||||||
|
|
||||||
|
You can find further info on expectancy, winrate, risk management and position size in the following sources:
|
||||||
|
|
||||||
|
- https://www.tradeciety.com/ultimate-math-guide-for-traders/
|
||||||
|
- http://www.vantharp.com/tharp-concepts/expectancy.asp
|
||||||
|
- https://samuraitradingacademy.com/trading-expectancy/
|
||||||
|
- https://www.learningmarkets.com/determining-expectancy-in-your-trading/
|
||||||
|
- http://www.lonestocktrader.com/make-money-trading-positive-expectancy/
|
||||||
|
- https://www.babypips.com/trading/trade-expectancy-matter
|
||||||
|
|||||||
286
docs/hyperopt.md
286
docs/hyperopt.md
@@ -6,35 +6,43 @@ algorithms included in the `scikit-optimize` package to accomplish this. The
|
|||||||
search will burn all your CPU cores, make your laptop sound like a fighter jet
|
search will burn all your CPU cores, make your laptop sound like a fighter jet
|
||||||
and still take a long time.
|
and still take a long time.
|
||||||
|
|
||||||
|
Hyperopt requires historic data to be available, just as backtesting does.
|
||||||
|
To learn how to get data for the pairs and exchange you're interrested in, head over to the [Data Downloading](data-download.md) section of the documentation.
|
||||||
|
|
||||||
!!! Bug
|
!!! Bug
|
||||||
Hyperopt will crash when used with only 1 CPU Core as found out in [Issue #1133](https://github.com/freqtrade/freqtrade/issues/1133)
|
Hyperopt can crash when used with only 1 CPU Core as found out in [Issue #1133](https://github.com/freqtrade/freqtrade/issues/1133)
|
||||||
|
|
||||||
## Prepare Hyperopting
|
## Prepare Hyperopting
|
||||||
|
|
||||||
Before we start digging into Hyperopt, we recommend you to take a look at
|
Before we start digging into Hyperopt, we recommend you to take a look at
|
||||||
an example hyperopt file located into [user_data/hyperopts/](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/test_hyperopt.py)
|
the sample hyperopt file located in [user_data/hyperopts/](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/sample_hyperopt.py).
|
||||||
|
|
||||||
Configuring hyperopt is similar to writing your own strategy, and many tasks will be similar and a lot of code can be copied across from the strategy.
|
Configuring hyperopt is similar to writing your own strategy, and many tasks will be similar and a lot of code can be copied across from the strategy.
|
||||||
|
|
||||||
### Checklist on all tasks / possibilities in hyperopt
|
### Checklist on all tasks / possibilities in hyperopt
|
||||||
|
|
||||||
Depending on the space you want to optimize, only some of the below are required.
|
Depending on the space you want to optimize, only some of the below are required:
|
||||||
|
|
||||||
* fill `populate_indicators` - probably a copy from your strategy
|
* fill `populate_indicators` - probably a copy from your strategy
|
||||||
* fill `buy_strategy_generator` - for buy signal optimization
|
* fill `buy_strategy_generator` - for buy signal optimization
|
||||||
* fill `indicator_space` - for buy signal optimzation
|
* fill `indicator_space` - for buy signal optimzation
|
||||||
* fill `sell_strategy_generator` - for sell signal optimization
|
* fill `sell_strategy_generator` - for sell signal optimization
|
||||||
* fill `sell_indicator_space` - for sell signal optimzation
|
* fill `sell_indicator_space` - for sell signal optimzation
|
||||||
* fill `roi_space` - for ROI optimization
|
|
||||||
* fill `generate_roi_table` - for ROI optimization (if you need more than 3 entries)
|
Optional, but recommended:
|
||||||
* fill `stoploss_space` - stoploss optimization
|
|
||||||
* Optional but recommended
|
* copy `populate_buy_trend` from your strategy - otherwise default-strategy will be used
|
||||||
* copy `populate_buy_trend` from your strategy - otherwise default-strategy will be used
|
* copy `populate_sell_trend` from your strategy - otherwise default-strategy will be used
|
||||||
* copy `populate_sell_trend` from your strategy - otherwise default-strategy will be used
|
|
||||||
|
Rarely you may also need to override:
|
||||||
|
|
||||||
|
* `roi_space` - for custom ROI optimization (if you need the ranges for the ROI parameters in the optimization hyperspace that differ from default)
|
||||||
|
* `generate_roi_table` - for custom ROI optimization (if you need more than 4 entries in the ROI table)
|
||||||
|
* `stoploss_space` - for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default)
|
||||||
|
|
||||||
### 1. Install a Custom Hyperopt File
|
### 1. Install a Custom Hyperopt File
|
||||||
|
|
||||||
Put your hyperopt file into the folder`user_data/hyperopts`.
|
Put your hyperopt file into the directory `user_data/hyperopts`.
|
||||||
|
|
||||||
Let assume you want a hyperopt file `awesome_hyperopt.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`
|
Copy the file `user_data/hyperopts/sample_hyperopt.py` into `user_data/hyperopts/awesome_hyperopt.py`
|
||||||
@@ -56,13 +64,13 @@ multiple guards. The constructed strategy will be something like
|
|||||||
"*buy exactly when close price touches lower bollinger band, BUT only if
|
"*buy exactly when close price touches lower bollinger band, BUT only if
|
||||||
ADX > 10*".
|
ADX > 10*".
|
||||||
|
|
||||||
If you have updated the buy strategy, ie. changed the contents of
|
If you have updated the buy strategy, i.e. changed the contents of
|
||||||
`populate_buy_trend()` method you have to update the `guards` and
|
`populate_buy_trend()` method, you have to update the `guards` and
|
||||||
`triggers` hyperopts must use.
|
`triggers` your hyperopt must use correspondingly.
|
||||||
|
|
||||||
#### Sell optimization
|
#### Sell optimization
|
||||||
|
|
||||||
Similar to the buy-signal above, sell-signals can also be optimized.
|
Similar to the buy-signal above, sell-signals can also be optimized.
|
||||||
Place the corresponding settings into the following methods
|
Place the corresponding settings into the following methods
|
||||||
|
|
||||||
* Inside `sell_indicator_space()` - the parameters hyperopt shall be optimizing.
|
* Inside `sell_indicator_space()` - the parameters hyperopt shall be optimizing.
|
||||||
@@ -71,6 +79,11 @@ Place the corresponding settings into the following methods
|
|||||||
The configuration and rules are the same than for buy signals.
|
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-`.
|
To avoid naming collisions in the search-space, please prefix all sell-spaces with `sell-`.
|
||||||
|
|
||||||
|
#### Using ticker-interval as part of the Strategy
|
||||||
|
|
||||||
|
The Strategy exposes the ticker-interval as `self.ticker_interval`. The same value is available as class-attribute `HyperoptName.ticker_interval`.
|
||||||
|
In the case of the linked sample-value this would be `SampleHyperOpt.ticker_interval`.
|
||||||
|
|
||||||
## Solving a Mystery
|
## Solving a Mystery
|
||||||
|
|
||||||
Let's say you are curious: should you use MACD crossings or lower Bollinger
|
Let's say you are curious: should you use MACD crossings or lower Bollinger
|
||||||
@@ -122,9 +135,10 @@ So let's write the buy strategy using these values:
|
|||||||
dataframe['macd'], dataframe['macdsignal']
|
dataframe['macd'], dataframe['macdsignal']
|
||||||
))
|
))
|
||||||
|
|
||||||
dataframe.loc[
|
if conditions:
|
||||||
reduce(lambda x, y: x & y, conditions),
|
dataframe.loc[
|
||||||
'buy'] = 1
|
reduce(lambda x, y: x & y, conditions),
|
||||||
|
'buy'] = 1
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
|
|
||||||
@@ -138,21 +152,94 @@ it will end with telling you which paramter combination produced the best profit
|
|||||||
|
|
||||||
The search for best parameters starts with a few random combinations and then uses a
|
The search for best parameters starts with a few random combinations and then uses a
|
||||||
regressor algorithm (currently ExtraTreesRegressor) to quickly find a parameter combination
|
regressor algorithm (currently ExtraTreesRegressor) to quickly find a parameter combination
|
||||||
that minimizes the value of the objective function `calculate_loss` in `hyperopt.py`.
|
that minimizes the value of the [loss function](#loss-functions).
|
||||||
|
|
||||||
The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators.
|
The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators.
|
||||||
When you want to test an indicator that isn't used by the bot currently, remember to
|
When you want to test an indicator that isn't used by the bot currently, remember to
|
||||||
add it to the `populate_indicators()` method in `hyperopt.py`.
|
add it to the `populate_indicators()` method in `hyperopt.py`.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
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)
|
||||||
|
* `OnlyProfitHyperOptLoss` (which takes only amount of profit into consideration)
|
||||||
|
* `SharpeHyperOptLoss` (optimizes Sharpe Ratio calculated on the trade returns)
|
||||||
|
|
||||||
|
### Creating and using a custom loss function
|
||||||
|
|
||||||
|
To use a custom loss function class, make sure that the function `hyperopt_loss_function` is defined in your custom hyperopt loss class.
|
||||||
|
For the sample below, you then need to add the command line parameter `--hyperopt-loss SuperDuperHyperOptLoss` to your hyperopt call so this fuction is being used.
|
||||||
|
|
||||||
|
A sample of this can be found below, which is identical to the Default Hyperopt loss implementation. A full sample can be found [user_data/hyperopts/](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/sample_hyperopt_loss.py)
|
||||||
|
|
||||||
|
``` python
|
||||||
|
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
||||||
|
|
||||||
|
TARGET_TRADES = 600
|
||||||
|
EXPECTED_MAX_PROFIT = 3.0
|
||||||
|
MAX_ACCEPTED_TRADE_DURATION = 300
|
||||||
|
|
||||||
|
class SuperDuperHyperOptLoss(IHyperOptLoss):
|
||||||
|
"""
|
||||||
|
Defines the default loss function for hyperopt
|
||||||
|
"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def hyperopt_loss_function(results: DataFrame, trade_count: int,
|
||||||
|
min_date: datetime, max_date: datetime,
|
||||||
|
*args, **kwargs) -> float:
|
||||||
|
"""
|
||||||
|
Objective function, returns smaller number for better results
|
||||||
|
This is the legacy algorithm (used until now in freqtrade).
|
||||||
|
Weights are distributed as follows:
|
||||||
|
* 0.4 to trade duration
|
||||||
|
* 0.25: Avoiding trade loss
|
||||||
|
* 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above
|
||||||
|
"""
|
||||||
|
total_profit = results.profit_percent.sum()
|
||||||
|
trade_duration = results.trade_duration.mean()
|
||||||
|
|
||||||
|
trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8)
|
||||||
|
profit_loss = max(0, 1 - total_profit / EXPECTED_MAX_PROFIT)
|
||||||
|
duration_loss = 0.4 * min(trade_duration / MAX_ACCEPTED_TRADE_DURATION, 1)
|
||||||
|
result = trade_loss + profit_loss + duration_loss
|
||||||
|
return result
|
||||||
|
```
|
||||||
|
|
||||||
|
Currently, the arguments are:
|
||||||
|
|
||||||
|
* `results`: DataFrame containing the result
|
||||||
|
The following columns are available in results (corresponds to the output-file of backtesting when used with `--export trades`):
|
||||||
|
`pair, profit_percent, profit_abs, open_time, close_time, open_index, close_index, trade_duration, open_at_end, open_rate, close_rate, sell_reason`
|
||||||
|
* `trade_count`: Amount of trades (identical to `len(results)`)
|
||||||
|
* `min_date`: Start date of the hyperopting TimeFrame
|
||||||
|
* `min_date`: End date of the hyperopting TimeFrame
|
||||||
|
|
||||||
|
This function needs to return a floating point number (`float`). Smaller numbers will be interpreted as better results. The parameters and balancing for this is up to you.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
This function is called once per iteration - so please make sure to have this as optimized as possible to not slow hyperopt down unnecessarily.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Please keep the arguments `*args` and `**kwargs` in the interface to allow us to extend this interface later.
|
||||||
|
|
||||||
## Execute Hyperopt
|
## Execute Hyperopt
|
||||||
|
|
||||||
Once you have updated your hyperopt configuration you can run it.
|
Once you have updated your hyperopt configuration you can run it.
|
||||||
Because hyperopt tries a lot of combinations to find the best parameters it will take time you will have the result (more than 30 mins).
|
Because hyperopt tries a lot of combinations to find the best parameters it will take time to get a good result. More time usually results in better results.
|
||||||
|
|
||||||
We strongly recommend to use `screen` or `tmux` to prevent any connection loss.
|
We strongly recommend to use `screen` or `tmux` to prevent any connection loss.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py --hyperopt <hyperoptname> -c config.json hyperopt -e 5000 --spaces all
|
freqtrade -c config.json hyperopt --customhyperopt <hyperoptname> -e 5000 --spaces all
|
||||||
```
|
```
|
||||||
|
|
||||||
Use `<hyperoptname>` as the name of the custom hyperopt used.
|
Use `<hyperoptname>` as the name of the custom hyperopt used.
|
||||||
@@ -162,8 +249,11 @@ running at least several thousand evaluations.
|
|||||||
|
|
||||||
The `--spaces all` flag determines that all possible parameters should be optimized. Possibilities are listed below.
|
The `--spaces all` flag 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
|
!!! Warning
|
||||||
When switching parameters or changing configuration options, the file `user_data/hyperopt_results.pickle` should be removed. It's used to be able to continue interrupted calculations, but does not detect changes to settings or the hyperopt file.
|
When switching parameters or changing configuration options, make sure to not use the argument `--continue` so temporary results can be removed.
|
||||||
|
|
||||||
### Execute Hyperopt with Different Ticker-Data Source
|
### Execute Hyperopt with Different Ticker-Data Source
|
||||||
|
|
||||||
@@ -173,12 +263,11 @@ use data from directory `user_data/data`.
|
|||||||
|
|
||||||
### Running Hyperopt with Smaller Testset
|
### Running Hyperopt with Smaller Testset
|
||||||
|
|
||||||
Use the `--timerange` argument to change how much of the testset
|
Use the `--timerange` argument to change how much of the testset you want to use.
|
||||||
you want to use. The last N ticks/timeframes will be used.
|
For example, to use one month of data, pass the following parameter to the hyperopt call:
|
||||||
Example:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py hyperopt --timerange -200
|
freqtrade hyperopt --timerange 20180401-20180501
|
||||||
```
|
```
|
||||||
|
|
||||||
### Running Hyperopt with Smaller Search Space
|
### Running Hyperopt with Smaller Search Space
|
||||||
@@ -191,12 +280,33 @@ new buy strategy you have.
|
|||||||
|
|
||||||
Legal values are:
|
Legal values are:
|
||||||
|
|
||||||
- `all`: optimize everything
|
* `all`: optimize everything
|
||||||
- `buy`: just search for a new buy strategy
|
* `buy`: just search for a new buy strategy
|
||||||
- `sell`: just search for a new sell strategy
|
* `sell`: just search for a new sell strategy
|
||||||
- `roi`: just optimize the minimal profit table for your strategy
|
* `roi`: just optimize the minimal profit table for your strategy
|
||||||
- `stoploss`: search for the best stoploss value
|
* `stoploss`: search for the best stoploss value
|
||||||
- space-separated list of any of the above values for example `--spaces roi stoploss`
|
* space-separated list of any of the above values for example `--spaces roi stoploss`
|
||||||
|
|
||||||
|
### Position stacking and disabling max market positions
|
||||||
|
|
||||||
|
In some situations, you may need to run Hyperopt (and Backtesting) with the
|
||||||
|
`--eps`/`--enable-position-staking` and `--dmmp`/`--disable-max-market-positions` arguments.
|
||||||
|
|
||||||
|
By default, hyperopt emulates the behavior of the Freqtrade Live Run/Dry Run, where only one
|
||||||
|
open trade is allowed for every traded pair. The total number of trades open for all pairs
|
||||||
|
is also limited by the `max_open_trades` setting. During Hyperopt/Backtesting this may lead to
|
||||||
|
some potential trades to be hidden (or masked) by previosly open trades.
|
||||||
|
|
||||||
|
The `--eps`/`--enable-position-stacking` argument allows emulation of buying the same pair multiple times,
|
||||||
|
while `--dmmp`/`--disable-max-market-positions` disables applying `max_open_trades`
|
||||||
|
during Hyperopt/Backtesting (which is equal to setting `max_open_trades` to a very high
|
||||||
|
number).
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Dry/live runs will **NOT** use position stacking - therefore it does make sense to also validate the strategy without this as it's closer to reality.
|
||||||
|
|
||||||
|
You can also enable position stacking in the configuration file by explicitly setting
|
||||||
|
`"position_stacking"=true`.
|
||||||
|
|
||||||
## Understand the Hyperopt Result
|
## Understand the Hyperopt Result
|
||||||
|
|
||||||
@@ -205,8 +315,10 @@ Given the following result from hyperopt:
|
|||||||
|
|
||||||
```
|
```
|
||||||
Best result:
|
Best result:
|
||||||
135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins.
|
|
||||||
with values:
|
44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins. Objective: 1.94367
|
||||||
|
|
||||||
|
Buy hyperspace params:
|
||||||
{ 'adx-value': 44,
|
{ 'adx-value': 44,
|
||||||
'rsi-value': 29,
|
'rsi-value': 29,
|
||||||
'adx-enabled': False,
|
'adx-enabled': False,
|
||||||
@@ -225,7 +337,7 @@ method, what those values match to.
|
|||||||
|
|
||||||
So for example you had `rsi-value: 29.0` so we would look at `rsi`-block, that translates to the following code block:
|
So for example you had `rsi-value: 29.0` so we would look at `rsi`-block, that translates to the following code block:
|
||||||
|
|
||||||
```
|
``` python
|
||||||
(dataframe['rsi'] < 29.0)
|
(dataframe['rsi'] < 29.0)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -243,53 +355,103 @@ def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:
|
|||||||
return dataframe
|
return dataframe
|
||||||
```
|
```
|
||||||
|
|
||||||
|
By default, hyperopt prints colorized results -- epochs with positive profit are printed in the green color. This highlighting helps you find epochs that can be interesting for later analysis. Epochs with zero total profit or with negative profits (losses) are printed in the normal color. If you do not need colorization of results (for instance, when you are redirecting hyperopt output to a file) you can switch colorization off by specifying the `--no-color` option in the command line.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
### Understand Hyperopt ROI results
|
### Understand Hyperopt ROI results
|
||||||
|
|
||||||
If you are optimizing ROI, you're result will look as follows and include a ROI table.
|
If you are optimizing ROI (i.e. if optimization search-space contains 'all' or 'roi'), your result will look as follows and include a ROI table:
|
||||||
|
|
||||||
```
|
```
|
||||||
Best result:
|
Best result:
|
||||||
135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins.
|
|
||||||
with values:
|
44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins. Objective: 1.94367
|
||||||
|
|
||||||
|
Buy hyperspace params:
|
||||||
{ 'adx-value': 44,
|
{ 'adx-value': 44,
|
||||||
'rsi-value': 29,
|
'rsi-value': 29,
|
||||||
'adx-enabled': false,
|
'adx-enabled': False,
|
||||||
'rsi-enabled': True,
|
'rsi-enabled': True,
|
||||||
'trigger': 'bb_lower',
|
'trigger': 'bb_lower'}
|
||||||
'roi_t1': 40,
|
|
||||||
'roi_t2': 57,
|
|
||||||
'roi_t3': 21,
|
|
||||||
'roi_p1': 0.03634636907306948,
|
|
||||||
'roi_p2': 0.055237357937802885,
|
|
||||||
'roi_p3': 0.015163796015548354,
|
|
||||||
'stoploss': -0.37996664668703606
|
|
||||||
}
|
|
||||||
ROI table:
|
ROI table:
|
||||||
{ 0: 0.10674752302642071,
|
{ 0: 0.10674,
|
||||||
21: 0.09158372701087236,
|
21: 0.09158,
|
||||||
78: 0.03634636907306948,
|
78: 0.03634,
|
||||||
118: 0}
|
118: 0}
|
||||||
```
|
```
|
||||||
|
|
||||||
This would translate to the following ROI table:
|
In order to use this best ROI table found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the `minimal_roi` attribute of your custom strategy:
|
||||||
|
|
||||||
``` python
|
```
|
||||||
minimal_roi = {
|
# Minimal ROI designed for the strategy.
|
||||||
"118": 0,
|
# This attribute will be overridden if the config file contains "minimal_roi"
|
||||||
"78": 0.0363463,
|
minimal_roi = {
|
||||||
"21": 0.0915,
|
0: 0.10674,
|
||||||
"0": 0.106
|
21: 0.09158,
|
||||||
|
78: 0.03634,
|
||||||
|
118: 0
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
As stated in the comment, you can also use it as the value of the `minimal_roi` setting in the configuration file.
|
||||||
|
|
||||||
### Validate backtest result
|
#### Default ROI Search Space
|
||||||
|
|
||||||
|
If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace for you -- it's the hyperspace of components for the ROI tables. By default, each ROI table generated by the Freqtrade consists of 4 rows (steps). Hyperopt implements adaptive ranges for ROI tables with ranges for values in the ROI steps that depend on the ticker_interval used. By default the values can vary in the following ranges (for some of the most used ticker intervals, values are rounded to 5 digits after the decimal point):
|
||||||
|
|
||||||
|
| # step | 1m | | 5m | | 1h | | 1d | |
|
||||||
|
|---|---|---|---|---|---|---|---|---|
|
||||||
|
| 1 | 0 | 0.01161...0.11992 | 0 | 0.03...0.31 | 0 | 0.06883...0.71124 | 0 | 0.12178...1.25835 |
|
||||||
|
| 2 | 2...8 | 0.00774...0.04255 | 10...40 | 0.02...0.11 | 120...480 | 0.04589...0.25238 | 2880...11520 | 0.08118...0.44651 |
|
||||||
|
| 3 | 4...20 | 0.00387...0.01547 | 20...100 | 0.01...0.04 | 240...1200 | 0.02294...0.09177 | 5760...28800 | 0.04059...0.16237 |
|
||||||
|
| 4 | 6...44 | 0.0 | 30...220 | 0.0 | 360...2640 | 0.0 | 8640...63360 | 0.0 |
|
||||||
|
|
||||||
|
These ranges should be sufficient in most cases. The minutes in the steps (ROI dict keys) are scaled linearly depending on the ticker interval used. The ROI values in the steps (ROI dict values) are scaled logarithmically depending on the ticker interval used.
|
||||||
|
|
||||||
|
If you have the `generate_roi_table()` and `roi_space()` methods in your custom hyperopt file, remove them in order to utilize these adaptive ROI tables and the ROI hyperoptimization space generated by Freqtrade by default.
|
||||||
|
|
||||||
|
Override the `roi_space()` method if you need components of the ROI tables to vary in other ranges. Override the `generate_roi_table()` and `roi_space()` methods and implement your own custom approach for generation of the ROI tables during hyperoptimization if you need a different structure of the ROI tables or other amount of rows (steps). A sample for these methods can be found in [user_data/hyperopts/sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/sample_hyperopt_advanced.py).
|
||||||
|
|
||||||
|
### Understand Hyperopt Stoploss results
|
||||||
|
|
||||||
|
If you are optimizing stoploss values (i.e. if optimization search-space contains 'all' or 'stoploss'), your result will look as follows and include stoploss:
|
||||||
|
|
||||||
|
```
|
||||||
|
Best result:
|
||||||
|
|
||||||
|
44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins. Objective: 1.94367
|
||||||
|
|
||||||
|
Buy hyperspace params:
|
||||||
|
{ 'adx-value': 44,
|
||||||
|
'rsi-value': 29,
|
||||||
|
'adx-enabled': False,
|
||||||
|
'rsi-enabled': True,
|
||||||
|
'trigger': 'bb_lower'}
|
||||||
|
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:
|
||||||
|
|
||||||
|
```
|
||||||
|
# Optimal stoploss designed for the strategy
|
||||||
|
# This attribute will be overridden if the config file contains "stoploss"
|
||||||
|
stoploss = -0.27996
|
||||||
|
```
|
||||||
|
As stated in the comment, you can also use it as the value of the `stoploss` setting in the configuration file.
|
||||||
|
|
||||||
|
#### Default Stoploss Search Space
|
||||||
|
|
||||||
|
If you are optimizing stoploss values, Freqtrade creates the 'stoploss' optimization hyperspace for you. By default, the stoploss values in that hyperspace can vary in the range -0.35...-0.02, which is sufficient in most cases.
|
||||||
|
|
||||||
|
If you have the `stoploss_space()` method in your custom hyperopt file, remove it in order to utilize Stoploss hyperoptimization space generated by Freqtrade by default.
|
||||||
|
|
||||||
|
Override the `stoploss_space()` method and define the desired range in it if you need stoploss values to vary in other range during hyperoptimization. A sample for this method can be found in [user_data/hyperopts/sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/sample_hyperopt_advanced.py).
|
||||||
|
|
||||||
|
### Validate backtesting results
|
||||||
|
|
||||||
Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.
|
Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.
|
||||||
To archive the same results (number of trades, ...) than during hyperopt, please use the command line flag `--disable-max-market-positions`.
|
|
||||||
This setting is the default for hyperopt for speed reasons. You can overwrite this in the configuration by setting `"position_stacking"=false` or by changing the relevant line in your hyperopt file [here](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/optimize/hyperopt.py#L283).
|
|
||||||
|
|
||||||
!!! Note:
|
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.
|
||||||
Dry/live runs will **NOT** use position stacking - therefore it does make sense to also validate the strategy without this as it's closer to reality.
|
|
||||||
|
|
||||||
## Next Step
|
## Next Step
|
||||||
|
|
||||||
|
|||||||
@@ -19,29 +19,31 @@ Freqtrade is a cryptocurrency trading bot written in Python.
|
|||||||
|
|
||||||
Always start by running a trading bot in Dry-run and do not engage money before you understand how it works and what profit/loss you should expect.
|
Always start by running a trading bot in Dry-run and do not engage money before you understand how it works and what profit/loss you should expect.
|
||||||
|
|
||||||
We strongly recommend you to have coding and Python knowledge. Do not hesitate to read the source code and understand the mechanism of this bot.
|
We strongly recommend you to have basic coding skills and Python knowledge. Do not hesitate to read the source code and understand the mechanisms of this bot, algorithms and techniques implemented in it.
|
||||||
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
- Based on Python 3.6+: For botting on any operating system - Windows, macOS and Linux
|
|
||||||
- Persistence: Persistence is achieved through sqlite
|
|
||||||
- Dry-run: Run the bot without playing money.
|
|
||||||
- Backtesting: Run a simulation of your buy/sell strategy.
|
|
||||||
- Strategy Optimization by machine learning: Use machine learning to optimize your buy/sell strategy parameters with real exchange data.
|
|
||||||
- Edge position sizing Calculate your win rate, risk reward ratio, the best stoploss and adjust your position size before taking a position for each specific market. Learn more
|
|
||||||
- Whitelist crypto-currencies: Select which crypto-currency you want to trade or use dynamic whitelists.
|
|
||||||
- Blacklist crypto-currencies: Select which crypto-currency you want to avoid.
|
|
||||||
- Manageable via Telegram: Manage the bot with Telegram
|
|
||||||
- Display profit/loss in fiat: Display your profit/loss in 33 fiat.
|
|
||||||
- Daily summary of profit/loss: Provide a daily summary of your profit/loss.
|
|
||||||
- Performance status report: Provide a performance status of your current trades.
|
|
||||||
|
|
||||||
|
- Based on Python 3.6+: For botting on any operating system — Windows, macOS and Linux.
|
||||||
|
- Persistence: Persistence is achieved through sqlite database.
|
||||||
|
- Dry-run mode: Run the bot without playing money.
|
||||||
|
- Backtesting: Run a simulation of your buy/sell strategy with historical data.
|
||||||
|
- Strategy Optimization by machine learning: Use machine learning to optimize your buy/sell strategy parameters with real exchange data.
|
||||||
|
- Edge position sizing: Calculate your win rate, risk reward ratio, the best stoploss and adjust your position size before taking a position for each specific market.
|
||||||
|
- Whitelist crypto-currencies: Select which crypto-currency you want to trade or use dynamic whitelists based on market (pair) trade volume.
|
||||||
|
- Blacklist crypto-currencies: Select which crypto-currency you want to avoid.
|
||||||
|
- Manageable via Telegram or REST APi: Manage the bot with Telegram or via the builtin REST API.
|
||||||
|
- Display profit/loss in fiat: Display your profit/loss in any of 33 fiat currencies supported.
|
||||||
|
- Daily summary of profit/loss: Receive the daily summary of your profit/loss.
|
||||||
|
- Performance status report: Receive the performance status of your current trades.
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
### Uptodate clock
|
|
||||||
The clock must be accurate, syncronized to a NTP server very frequently to avoid problems with communication to the exchanges.
|
### Up to date clock
|
||||||
|
|
||||||
|
The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges.
|
||||||
|
|
||||||
### Hardware requirements
|
### Hardware requirements
|
||||||
|
|
||||||
To run this bot we recommend you a cloud instance with a minimum of:
|
To run this bot we recommend you a cloud instance with a minimum of:
|
||||||
|
|
||||||
- 2GB RAM
|
- 2GB RAM
|
||||||
@@ -49,19 +51,21 @@ To run this bot we recommend you a cloud instance with a minimum of:
|
|||||||
- 2vCPU
|
- 2vCPU
|
||||||
|
|
||||||
### Software requirements
|
### Software requirements
|
||||||
|
|
||||||
- Python 3.6.x
|
- Python 3.6.x
|
||||||
- pip
|
- pip (pip3)
|
||||||
- git
|
- git
|
||||||
- TA-Lib
|
- TA-Lib
|
||||||
- virtualenv (Recommended)
|
- virtualenv (Recommended)
|
||||||
- Docker (Recommended)
|
- Docker (Recommended)
|
||||||
|
|
||||||
|
|
||||||
## Support
|
## Support
|
||||||
Help / Slack
|
|
||||||
For any questions not covered by the documentation or for further information about the bot, we encourage you to join our slack channel.
|
|
||||||
|
|
||||||
Click [here](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE) to join Slack channel.
|
Help / Slack
|
||||||
|
For any questions not covered by the documentation or for further information about the bot, we encourage you to join our Slack channel.
|
||||||
|
|
||||||
|
Click [here](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE) to join Slack channel.
|
||||||
|
|
||||||
## Ready to try?
|
## Ready to try?
|
||||||
Begin by reading our installation guide [here](installation).
|
|
||||||
|
Begin by reading our installation guide [here](installation).
|
||||||
|
|||||||
@@ -1,72 +1,49 @@
|
|||||||
# Installation
|
# Installation
|
||||||
|
|
||||||
This page explains how to prepare your environment for running the bot.
|
This page explains how to prepare your environment for running the bot.
|
||||||
|
|
||||||
## Prerequisite
|
## Prerequisite
|
||||||
Before running your bot in production you will need to setup few
|
|
||||||
external API. In production mode, the bot required valid Bittrex API
|
|
||||||
credentials and a Telegram bot (optional but recommended).
|
|
||||||
|
|
||||||
- [Setup your exchange account](#setup-your-exchange-account)
|
### Requirements
|
||||||
- [Backtesting commands](#setup-your-telegram-bot)
|
|
||||||
|
Click each one for install guide:
|
||||||
|
|
||||||
|
* [Python >= 3.6.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
||||||
|
* [pip](https://pip.pypa.io/en/stable/installing/)
|
||||||
|
* [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||||
|
* [virtualenv](https://virtualenv.pypa.io/en/stable/installation/) (Recommended)
|
||||||
|
* [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html) (install instructions below)
|
||||||
|
|
||||||
|
### API keys
|
||||||
|
|
||||||
|
Before running your bot in production you will need to setup few
|
||||||
|
external API. In production mode, the bot will require valid Exchange API
|
||||||
|
credentials. We also recommend a [Telegram bot](telegram-usage.md#setup-your-telegram-bot) (optional but recommended).
|
||||||
|
|
||||||
### Setup your exchange account
|
### Setup your exchange account
|
||||||
*To be completed, please feel free to complete this section.*
|
|
||||||
|
|
||||||
### Setup your Telegram bot
|
You will need to create API Keys (Usually you get `key` and `secret`) from the Exchange website and insert this into the appropriate fields in the configuration or when asked by the installation script.
|
||||||
The only things you need is a working Telegram bot and its API token.
|
|
||||||
Below we explain how to create your Telegram Bot, and how to get your
|
|
||||||
Telegram user id.
|
|
||||||
|
|
||||||
### 1. Create your Telegram bot
|
|
||||||
|
|
||||||
**1.1. Start a chat with https://telegram.me/BotFather**
|
|
||||||
|
|
||||||
**1.2. Send the message `/newbot`. ** *BotFather response:*
|
|
||||||
```
|
|
||||||
Alright, a new bot. How are we going to call it? Please choose a name for your bot.
|
|
||||||
```
|
|
||||||
|
|
||||||
**1.3. Choose the public name of your bot (e.x. `Freqtrade bot`)**
|
|
||||||
*BotFather response:*
|
|
||||||
```
|
|
||||||
Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.
|
|
||||||
```
|
|
||||||
**1.4. Choose the name id of your bot (e.x "`My_own_freqtrade_bot`")**
|
|
||||||
|
|
||||||
**1.5. Father bot will return you the token (API key)**<br/>
|
|
||||||
Copy it and keep it you will use it for the config parameter `token`.
|
|
||||||
*BotFather response:*
|
|
||||||
```hl_lines="4"
|
|
||||||
Done! Congratulations on your new bot. You will find it at t.me/My_own_freqtrade_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.
|
|
||||||
|
|
||||||
Use this token to access the HTTP API:
|
|
||||||
521095879:AAEcEZEL7ADJ56FtG_qD0bQJSKETbXCBCi0
|
|
||||||
|
|
||||||
For a description of the Bot API, see this page: https://core.telegram.org/bots/api
|
|
||||||
```
|
|
||||||
**1.6. Don't forget to start the conversation with your bot, by clicking /START button**
|
|
||||||
|
|
||||||
### 2. Get your user id
|
|
||||||
**2.1. Talk to https://telegram.me/userinfobot**
|
|
||||||
|
|
||||||
**2.2. Get your "Id", you will use it for the config parameter
|
|
||||||
`chat_id`.**
|
|
||||||
<hr/>
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
Freqtrade provides a Linux/MacOS script to install all dependencies and help you to configure the bot.
|
Freqtrade provides a Linux/MacOS script to install all dependencies and help you to configure the bot.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Python3.6 or higher and the corresponding pip are assumed to be available. The install-script will warn and stop if that's not the case.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone git@github.com:freqtrade/freqtrade.git
|
git clone git@github.com:freqtrade/freqtrade.git
|
||||||
cd freqtrade
|
cd freqtrade
|
||||||
git checkout develop
|
git checkout develop
|
||||||
./setup.sh --install
|
./setup.sh --install
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Windows installation is explained [here](#windows).
|
Windows installation is explained [here](#windows).
|
||||||
<hr/>
|
|
||||||
## Easy Installation - Linux Script
|
## Easy Installation - Linux Script
|
||||||
|
|
||||||
If you are on Debian, Ubuntu or MacOS a freqtrade provides a script to Install, Update, Configure, and Reset your bot.
|
If you are on Debian, Ubuntu or MacOS freqtrade provides a script to Install, Update, Configure, and Reset your bot.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ ./setup.sh
|
$ ./setup.sh
|
||||||
@@ -81,7 +58,7 @@ usage:
|
|||||||
|
|
||||||
This script will install everything you need to run the bot:
|
This script will install everything you need to run the bot:
|
||||||
|
|
||||||
* Mandatory software as: `Python3`, `ta-lib`, `wget`
|
* Mandatory software as: `ta-lib`
|
||||||
* Setup your virtualenv
|
* Setup your virtualenv
|
||||||
* Configure your `config.json` file
|
* Configure your `config.json` file
|
||||||
|
|
||||||
@@ -101,221 +78,29 @@ Config parameter is a `config.json` configurator. This script will ask you quest
|
|||||||
|
|
||||||
------
|
------
|
||||||
|
|
||||||
## Automatic Installation - Docker
|
|
||||||
|
|
||||||
Start by downloading Docker for your platform:
|
|
||||||
|
|
||||||
* [Mac](https://www.docker.com/products/docker#/mac)
|
|
||||||
* [Windows](https://www.docker.com/products/docker#/windows)
|
|
||||||
* [Linux](https://www.docker.com/products/docker#/linux)
|
|
||||||
|
|
||||||
Once you have Docker installed, simply create the config file (e.g. `config.json`) and then create a Docker image for `freqtrade` using the Dockerfile in this repo.
|
|
||||||
|
|
||||||
### 1. Prepare the Bot
|
|
||||||
|
|
||||||
**1.1. Clone the git repository**
|
|
||||||
|
|
||||||
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
|
|
||||||
```
|
|
||||||
|
|
||||||
**1.2. (Optional) Checkout the develop branch**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git checkout develop
|
|
||||||
```
|
|
||||||
|
|
||||||
**1.3. Go into the new directory**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd freqtrade
|
|
||||||
```
|
|
||||||
|
|
||||||
**1.4. Copy `config.json.example` to `config.json`**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cp -n config.json.example config.json
|
|
||||||
```
|
|
||||||
|
|
||||||
> To edit the config please refer to the [Bot Configuration](configuration.md) page.
|
|
||||||
|
|
||||||
**1.5. Create your database file *(optional - the bot will create it if it is missing)**
|
|
||||||
|
|
||||||
Production
|
|
||||||
|
|
||||||
```bash
|
|
||||||
touch tradesv3.sqlite
|
|
||||||
````
|
|
||||||
|
|
||||||
Dry-Run
|
|
||||||
|
|
||||||
```bash
|
|
||||||
touch tradesv3.dryrun.sqlite
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. Download or build the docker image
|
|
||||||
|
|
||||||
Either use the prebuilt image from docker hub - or build the image yourself if you would like more control on which version is used.
|
|
||||||
|
|
||||||
Branches / tags available can be checked out on [Dockerhub](https://hub.docker.com/r/freqtradeorg/freqtrade/tags/).
|
|
||||||
|
|
||||||
**2.1. Download the docker image**
|
|
||||||
|
|
||||||
Pull the image from docker hub and (optionally) change the name of the image
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker pull freqtradeorg/freqtrade:develop
|
|
||||||
# Optionally tag the repository so the run-commands remain shorter
|
|
||||||
docker tag freqtradeorg/freqtrade:develop freqtrade
|
|
||||||
```
|
|
||||||
|
|
||||||
To update the image, simply run the above commands again and restart your running container.
|
|
||||||
|
|
||||||
**2.2. Build the Docker image**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd freqtrade
|
|
||||||
docker build -t freqtrade .
|
|
||||||
```
|
|
||||||
|
|
||||||
If you are developing using Docker, use `Dockerfile.develop` to build a dev Docker image, which will also set up develop dependencies:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker build -f ./Dockerfile.develop -t freqtrade-dev .
|
|
||||||
```
|
|
||||||
|
|
||||||
For security reasons, your configuration file will not be included in the image, you will need to bind mount it. It is also advised to bind mount an SQLite database file (see the "5. Run a restartable docker image" section) to keep it between updates.
|
|
||||||
|
|
||||||
### 3. Verify the Docker image
|
|
||||||
|
|
||||||
After the build process you can verify that the image was created with:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker images
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4. Run the Docker image
|
|
||||||
|
|
||||||
You can run a one-off container that is immediately deleted upon exiting with the following command (`config.json` must be in the current working directory):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker run --rm -v /etc/localtime:/etc/localtime:ro -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
|
||||||
```
|
|
||||||
|
|
||||||
There is known issue in OSX Docker versions after 17.09.1, whereby /etc/localtime cannot be shared causing Docker to not start. A work-around for this is to start with the following cmd.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker run --rm -e TZ=`ls -la /etc/localtime | cut -d/ -f8-9` -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
|
||||||
```
|
|
||||||
|
|
||||||
More information on this docker issue and work-around can be read [here](https://github.com/docker/for-mac/issues/2396).
|
|
||||||
|
|
||||||
In this example, the database will be created inside the docker instance and will be lost when you will refresh your image.
|
|
||||||
|
|
||||||
### 5. Run a restartable docker image
|
|
||||||
|
|
||||||
To run a restartable instance in the background (feel free to place your configuration and database files wherever it feels comfortable on your filesystem).
|
|
||||||
|
|
||||||
**5.1. Move your config file and database**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
mkdir ~/.freqtrade
|
|
||||||
mv config.json ~/.freqtrade
|
|
||||||
mv tradesv3.sqlite ~/.freqtrade
|
|
||||||
```
|
|
||||||
|
|
||||||
**5.2. Run the docker image**
|
|
||||||
|
|
||||||
```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 \
|
|
||||||
freqtrade --db-url sqlite:///tradesv3.sqlite
|
|
||||||
```
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
db-url defaults to `sqlite:///tradesv3.sqlite` but it defaults to `sqlite://` if `dry_run=True` is being used.
|
|
||||||
To override this behaviour use a custom db-url value: i.e.: `--db-url sqlite:///tradesv3.dryrun.sqlite`
|
|
||||||
|
|
||||||
### 6. Monitor your Docker instance
|
|
||||||
|
|
||||||
You can then 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.
|
|
||||||
|
|
||||||
### 7. Backtest with docker
|
|
||||||
|
|
||||||
The following assumes that the above steps (1-4) have been completed successfully.
|
|
||||||
Also, backtest-data should be available at `~/.freqtrade/user_data/`.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker run -d \
|
|
||||||
--name freqtrade \
|
|
||||||
-v /etc/localtime:/etc/localtime:ro \
|
|
||||||
-v ~/.freqtrade/config.json:/freqtrade/config.json \
|
|
||||||
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
|
||||||
-v ~/.freqtrade/user_data/:/freqtrade/user_data/ \
|
|
||||||
freqtrade --strategy AwsomelyProfitableStrategy backtesting
|
|
||||||
```
|
|
||||||
|
|
||||||
Head over to the [Backtesting Documentation](backtesting.md) for more details.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Additional parameters can be appended after the image name (`freqtrade` in the above example).
|
|
||||||
|
|
||||||
------
|
|
||||||
|
|
||||||
## Custom Installation
|
## 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 16.04, MacOS, and Windows. These are guidelines and your success may vary with other distros.
|
||||||
OS Specific steps are listed first, the [Common](#common) section below is necessary for all systems.
|
OS Specific steps are listed first, the [Common](#common) section below is necessary for all systems.
|
||||||
|
|
||||||
### Requirements
|
!!! Note
|
||||||
|
Python3.6 or higher and the corresponding pip are assumed to be available.
|
||||||
Click each one for install guide:
|
|
||||||
|
|
||||||
* [Python >= 3.6.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
|
||||||
* [pip](https://pip.pypa.io/en/stable/installing/)
|
|
||||||
* [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
|
||||||
* [virtualenv](https://virtualenv.pypa.io/en/stable/installation/) (Recommended)
|
|
||||||
* [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html)
|
|
||||||
|
|
||||||
### Linux - Ubuntu 16.04
|
### Linux - Ubuntu 16.04
|
||||||
|
|
||||||
#### Install Python 3.6, Git, and wget
|
#### Install necessary dependencies
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo add-apt-repository ppa:jonathonf/python-3.6
|
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install python3.6 python3.6-venv python3.6-dev build-essential autoconf libtool pkg-config make wget git
|
sudo apt-get install build-essential git
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Raspberry Pi / Raspbian
|
#### Raspberry Pi / Raspbian
|
||||||
|
|
||||||
Before installing FreqTrade on a Raspberry Pi running the official Raspbian Image, make sure you have at least Python 3.6 installed. The default image only provides Python 3.5. Probably the easiest way to get a recent version of python is [miniconda](https://repo.continuum.io/miniconda/).
|
Before installing FreqTrade on a Raspberry Pi running the official Raspbian Image, make sure you have at least Python 3.6 installed. The default image only provides Python 3.5. Probably the easiest way to get a recent version of python is [miniconda](https://repo.continuum.io/miniconda/).
|
||||||
|
|
||||||
The following assumes that miniconda3 is installed and available in your environment. Last miniconda3 installation file use python 3.4, we will update to python 3.6 on this installation.
|
The following assumes that miniconda3 is installed and available in your environment. Since the last miniconda3 installation file uses python 3.4, we will update to python 3.6 on this installation.
|
||||||
It's recommended to use (mini)conda for this as installation/compilation of `numpy`, `scipy` and `pandas` takes a long time.
|
It's recommended to use (mini)conda for this as installation/compilation of `numpy` and `pandas` takes a long time.
|
||||||
If you have installed it from (mini)conda, you can remove `numpy`, `scipy`, and `pandas` from `requirements.txt` before you install it with `pip`.
|
|
||||||
|
|
||||||
Additional package to install on your Raspbian, `libffi-dev` required by cryptography (from python-telegram-bot).
|
Additional package to install on your Raspbian, `libffi-dev` required by cryptography (from python-telegram-bot).
|
||||||
|
|
||||||
@@ -324,20 +109,16 @@ conda config --add channels rpi
|
|||||||
conda install python=3.6
|
conda install python=3.6
|
||||||
conda create -n freqtrade python=3.6
|
conda create -n freqtrade python=3.6
|
||||||
conda activate freqtrade
|
conda activate freqtrade
|
||||||
conda install scipy pandas numpy
|
conda install pandas numpy
|
||||||
|
|
||||||
sudo apt install libffi-dev
|
sudo apt install libffi-dev
|
||||||
python3 -m pip install -r requirements.txt
|
python3 -m pip install -r requirements-common.txt
|
||||||
python3 -m pip install -e .
|
python3 -m pip install -e .
|
||||||
```
|
```
|
||||||
|
|
||||||
### MacOS
|
!!! Note
|
||||||
|
This does not install hyperopt dependencies. To install these, please use `python3 -m pip install -e .[hyperopt]`.
|
||||||
#### Install Python 3.6, git and wget
|
We do not advise to run hyperopt on a Raspberry Pi, since this is a very resource-heavy operation, which should be done on powerful machine.
|
||||||
|
|
||||||
```bash
|
|
||||||
brew install python3 git wget
|
|
||||||
```
|
|
||||||
|
|
||||||
### Common
|
### Common
|
||||||
|
|
||||||
@@ -379,7 +160,7 @@ git clone https://github.com/freqtrade/freqtrade.git
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Optionally checkout the stable/master branch:
|
Optionally checkout the master branch to get the latest stable release:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git checkout master
|
git checkout master
|
||||||
@@ -397,9 +178,8 @@ cp config.json.example config.json
|
|||||||
#### 5. Install python dependencies
|
#### 5. Install python dependencies
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
pip3 install --upgrade pip
|
python3 -m pip install --upgrade pip
|
||||||
pip3 install -r requirements.txt
|
python3 -m pip install -e .
|
||||||
pip3 install -e .
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 6. Run the Bot
|
#### 6. Run the Bot
|
||||||
@@ -407,10 +187,10 @@ pip3 install -e .
|
|||||||
If this is the first time you run the bot, ensure you are running it in Dry-run `"dry_run": true,` otherwise it will start to buy and sell coins.
|
If this is the first time you run the bot, ensure you are running it in Dry-run `"dry_run": true,` otherwise it will start to buy and sell coins.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3.6 ./freqtrade/main.py -c config.json
|
freqtrade -c config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
*Note*: If you run the bot on a server, you should consider using [Docker](#automatic-installation---docker) a terminal multiplexer like `screen` or [`tmux`](https://en.wikipedia.org/wiki/Tmux) to avoid that the bot is stopped on logout.
|
*Note*: If you run the bot on a server, you should consider using [Docker](docker.md) or a terminal multiplexer like `screen` or [`tmux`](https://en.wikipedia.org/wiki/Tmux) to avoid that the bot is stopped on logout.
|
||||||
|
|
||||||
#### 7. [Optional] Configure `freqtrade` as a `systemd` service
|
#### 7. [Optional] Configure `freqtrade` as a `systemd` service
|
||||||
|
|
||||||
@@ -428,11 +208,34 @@ For this to be persistent (run when user is logged out) you'll need to enable `l
|
|||||||
sudo loginctl enable-linger "$USER"
|
sudo loginctl enable-linger "$USER"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
If you run the bot as a service, you can use systemd service manager as a software watchdog monitoring freqtrade bot
|
||||||
|
state and restarting it in the case of failures. If the `internals.sd_notify` parameter is set to true in the
|
||||||
|
configuration or the `--sd-notify` command line option is used, the bot will send keep-alive ping messages to systemd
|
||||||
|
using the sd_notify (systemd notifications) protocol and will also tell systemd its current state (Running or Stopped)
|
||||||
|
when it changes.
|
||||||
|
|
||||||
|
The `freqtrade.service.watchdog` file contains an example of the service unit configuration file which uses systemd
|
||||||
|
as the watchdog.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
The sd_notify communication between the bot and the systemd service manager will not work if the bot runs in a Docker container.
|
||||||
|
|
||||||
------
|
------
|
||||||
|
|
||||||
|
## Using Conda
|
||||||
|
|
||||||
|
Freqtrade can also be installed using Anaconda (or Miniconda).
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
conda env create -f environment.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
This requires the [ta-lib](#1-install-ta-lib) C-library to be installed first.
|
||||||
|
|
||||||
## Windows
|
## Windows
|
||||||
|
|
||||||
We recommend that Windows users use [Docker](#docker) as this will work much easier and smoother (also more secure).
|
We recommend that Windows users use [Docker](docker.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.
|
If that is not possible, try using the Windows Linux subsystem (WSL) - for which the Ubuntu instructions should work.
|
||||||
If that is not available on your system, feel free to try the instructions below, which led to success for some.
|
If that is not available on your system, feel free to try the instructions below, which led to success for some.
|
||||||
@@ -445,8 +248,6 @@ If that is not available on your system, feel free to try the instructions below
|
|||||||
git clone https://github.com/freqtrade/freqtrade.git
|
git clone https://github.com/freqtrade/freqtrade.git
|
||||||
```
|
```
|
||||||
|
|
||||||
copy paste `config.json` to ``\path\freqtrade-develop\freqtrade`
|
|
||||||
|
|
||||||
#### Install ta-lib
|
#### Install ta-lib
|
||||||
|
|
||||||
Install ta-lib according to the [ta-lib documentation](https://github.com/mrjbq7/ta-lib#windows).
|
Install ta-lib according to the [ta-lib documentation](https://github.com/mrjbq7/ta-lib#windows).
|
||||||
@@ -456,14 +257,12 @@ As compiling from source on windows has heavy dependencies (requires a partial v
|
|||||||
```cmd
|
```cmd
|
||||||
>cd \path\freqtrade-develop
|
>cd \path\freqtrade-develop
|
||||||
>python -m venv .env
|
>python -m venv .env
|
||||||
>cd .env\Scripts
|
>.env\Scripts\activate.bat
|
||||||
>activate.bat
|
|
||||||
>cd \path\freqtrade-develop
|
|
||||||
REM optionally install ta-lib from wheel
|
REM optionally install ta-lib from wheel
|
||||||
REM >pip install TA_Lib‑0.4.17‑cp36‑cp36m‑win32.whl
|
REM >pip install TA_Lib‑0.4.17‑cp36‑cp36m‑win32.whl
|
||||||
>pip install -r requirements.txt
|
>pip install -r requirements.txt
|
||||||
>pip install -e .
|
>pip install -e .
|
||||||
>python freqtrade\main.py
|
>freqtrade
|
||||||
```
|
```
|
||||||
|
|
||||||
> Thanks [Owdr](https://github.com/Owdr) for the commands. Source: [Issue #222](https://github.com/freqtrade/freqtrade/issues/222)
|
> Thanks [Owdr](https://github.com/Owdr) for the commands. Source: [Issue #222](https://github.com/freqtrade/freqtrade/issues/222)
|
||||||
@@ -476,7 +275,7 @@ error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++
|
|||||||
|
|
||||||
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-build wheel. It is therefore mandatory to have a C/C++ compiler installed and available for your python environment to use.
|
||||||
|
|
||||||
The easiest way is to download install Microsoft Visual Studio Community [here](https://visualstudio.microsoft.com/downloads/) and make sure to install "Common Tools for Visual C++" to enable building c code on Windows. Unfortunately, this is a heavy download / dependency (~4Gb) so you might want to consider WSL or docker first.
|
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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -49,4 +49,6 @@
|
|||||||
</nav>
|
</nav>
|
||||||
<!-- Place this tag in your head or just before your close body tag. -->
|
<!-- Place this tag in your head or just before your close body tag. -->
|
||||||
<script async defer src="https://buttons.github.io/buttons.js"></script>
|
<script async defer src="https://buttons.github.io/buttons.js"></script>
|
||||||
</header>
|
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
|
||||||
|
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
|
||||||
|
</header>
|
||||||
|
|||||||
191
docs/plotting.md
191
docs/plotting.md
@@ -1,88 +1,183 @@
|
|||||||
# Plotting
|
# Plotting
|
||||||
This page explains how to plot prices, indicator, profits.
|
|
||||||
|
|
||||||
## Installation
|
This page explains how to plot prices, indicators and profits.
|
||||||
|
|
||||||
Plotting scripts use Plotly library. Install/upgrade it with:
|
## Installation / Setup
|
||||||
|
|
||||||
|
Plotting modules use the Plotly library. You can install / upgrade this by running the following command:
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
pip install -U -r requirements-plot.txt
|
||||||
```
|
```
|
||||||
pip install --upgrade plotly
|
|
||||||
```
|
|
||||||
|
|
||||||
At least version 2.3.0 is required.
|
|
||||||
|
|
||||||
## Plot price and indicators
|
## Plot price and indicators
|
||||||
Usage for the price plotter:
|
|
||||||
|
The `freqtrade plot-dataframe` subcommand shows an interactive graph with three subplots:
|
||||||
|
|
||||||
|
* Main plot with candlestics and indicators following price (sma/ema)
|
||||||
|
* Volume bars
|
||||||
|
* Additional indicators as specified by `--indicators2`
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Possible arguments:
|
||||||
|
|
||||||
```
|
```
|
||||||
script/plot_dataframe.py [-h] [-p pairs] [--live]
|
usage: freqtrade plot-dataframe [-h] [-p PAIRS [PAIRS ...]]
|
||||||
|
[--indicators1 INDICATORS1 [INDICATORS1 ...]]
|
||||||
|
[--indicators2 INDICATORS2 [INDICATORS2 ...]]
|
||||||
|
[--plot-limit INT] [--db-url PATH]
|
||||||
|
[--trade-source {DB,file}] [--export EXPORT]
|
||||||
|
[--export-filename PATH]
|
||||||
|
[--timerange TIMERANGE]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||||
|
Show profits for only these pairs. Pairs are space-
|
||||||
|
separated.
|
||||||
|
--indicators1 INDICATORS1 [INDICATORS1 ...]
|
||||||
|
Set indicators from your strategy you want in the
|
||||||
|
first row of the graph. Space-separated list. Example:
|
||||||
|
`ema3 ema5`. Default: `['sma', 'ema3', 'ema5']`.
|
||||||
|
--indicators2 INDICATORS2 [INDICATORS2 ...]
|
||||||
|
Set indicators from your strategy you want in the
|
||||||
|
third row of the graph. Space-separated list. Example:
|
||||||
|
`fastd fastk`. Default: `['macd', 'macdsignal']`.
|
||||||
|
--plot-limit INT Specify tick limit for plotting. Notice: too high
|
||||||
|
values cause huge files. Default: 750.
|
||||||
|
--db-url PATH Override trades database URL, this is useful in custom
|
||||||
|
deployments (default: `sqlite:///tradesv3.sqlite` for
|
||||||
|
Live Run mode, `sqlite://` for Dry Run).
|
||||||
|
--trade-source {DB,file}
|
||||||
|
Specify the source for trades (Can be DB or file
|
||||||
|
(backtest file)) Default: file
|
||||||
|
--export EXPORT Export backtest results, argument are: trades.
|
||||||
|
Example: `--export=trades`
|
||||||
|
--export-filename PATH
|
||||||
|
Save backtest results to the file with this filename
|
||||||
|
(default: `user_data/backtest_results/backtest-
|
||||||
|
result.json`). Requires `--export` to be set as well.
|
||||||
|
Example: `--export-filename=user_data/backtest_results
|
||||||
|
/backtest_today.json`
|
||||||
|
--timerange TIMERANGE
|
||||||
|
Specify what timerange of data to use.
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Example
|
Example:
|
||||||
```
|
|
||||||
python scripts/plot_dataframe.py -p BTC/ETH
|
``` bash
|
||||||
|
freqtrade plot-dataframe -p BTC/ETH
|
||||||
```
|
```
|
||||||
|
|
||||||
The `-p` pairs argument, can be used to specify
|
The `-p/--pairs` argument can be used to specify pairs you would like to plot.
|
||||||
pairs you would like to plot.
|
|
||||||
|
|
||||||
**Advanced use**
|
!!! Note
|
||||||
|
The `freqtrade plot-dataframe` subcommand generates one plot-file per pair.
|
||||||
|
|
||||||
To plot multiple pairs, separate them with a comma:
|
Specify custom indicators.
|
||||||
```
|
Use `--indicators1` for the main plot and `--indicators2` for the subplot below (if values are in a different range than prices).
|
||||||
python scripts/plot_dataframe.py -p BTC/ETH,XRP/ETH
|
|
||||||
|
!!! tip
|
||||||
|
You will almost certainly want to specify a custom strategy! This can be done by adding `-s Classname` / `--strategy ClassName` to the command.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade --strategy AwesomeStrategy plot-dataframe -p BTC/ETH --indicators1 sma ema --indicators2 macd
|
||||||
```
|
```
|
||||||
|
|
||||||
To plot the current live price use the `--live` flag:
|
### Further usage examples
|
||||||
```
|
|
||||||
python scripts/plot_dataframe.py -p BTC/ETH --live
|
To plot multiple pairs, separate them with a space:
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade --strategy AwesomeStrategy plot-dataframe -p BTC/ETH XRP/ETH
|
||||||
```
|
```
|
||||||
|
|
||||||
To plot a timerange (to zoom in):
|
To plot a timerange (to zoom in)
|
||||||
```
|
|
||||||
python scripts/plot_dataframe.py -p BTC/ETH --timerange=100-200
|
|
||||||
```
|
|
||||||
Timerange doesn't work with live data.
|
|
||||||
|
|
||||||
To plot trades stored in a database use `--db-url` argument:
|
``` bash
|
||||||
```
|
freqtrade --strategy AwesomeStrategy plot-dataframe -p BTC/ETH --timerange=20180801-20180805
|
||||||
python scripts/plot_dataframe.py --db-url sqlite:///tradesv3.dry_run.sqlite -p BTC/ETH
|
|
||||||
```
|
```
|
||||||
|
|
||||||
To plot a test strategy the strategy should have first be backtested.
|
To plot trades stored in a database use `--db-url` in combination with `--trade-source DB`:
|
||||||
The results may then be plotted with the -s argument:
|
|
||||||
|
``` bash
|
||||||
|
freqtrade --strategy AwesomeStrategy plot-dataframe --db-url sqlite:///tradesv3.dry_run.sqlite -p BTC/ETH --trade-source DB
|
||||||
```
|
```
|
||||||
python scripts/plot_dataframe.py -s Strategy_Name -p BTC/ETH --datadir user_data/data/<exchange_name>/
|
|
||||||
|
To plot trades from a backtesting result, use `--export-filename <filename>`
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade --strategy AwesomeStrategy plot-dataframe --export-filename user_data/backtest_results/backtest-result.json -p BTC/ETH
|
||||||
```
|
```
|
||||||
|
|
||||||
## Plot profit
|
## Plot profit
|
||||||
|
|
||||||
The profit plotter show a picture with three plots:
|

|
||||||
|
|
||||||
|
The `freqtrade plot-profit` subcommand shows an interactive graph with three plots:
|
||||||
|
|
||||||
1) Average closing price for all pairs
|
1) Average closing price for all pairs
|
||||||
2) The summarized profit made by backtesting.
|
2) The summarized profit made by backtesting.
|
||||||
Note that this is not the real-world profit, but
|
Note that this is not the real-world profit, but more of an estimate.
|
||||||
more of an estimate.
|
3) Profit for each individual pair
|
||||||
3) Each pair individually profit
|
|
||||||
|
|
||||||
The first graph is good to get a grip of how the overall market
|
The first graph is good to get a grip of how the overall market progresses.
|
||||||
progresses.
|
|
||||||
|
|
||||||
The second graph will show how you algorithm works or doesnt.
|
The second graph will show if your algorithm works or doesn't.
|
||||||
Perhaps you want an algorithm that steadily makes small profits,
|
Perhaps you want an algorithm that steadily makes small profits, or one that acts less often, but makes big swings.
|
||||||
or one that acts less seldom, but makes big swings.
|
|
||||||
|
|
||||||
The third graph can be useful to spot outliers, events in pairs
|
The third graph can be useful to spot outliers, events in pairs that cause profit spikes.
|
||||||
that makes profit spikes.
|
|
||||||
|
|
||||||
Usage for the profit plotter:
|
Possible options for the `freqtrade plot-profit` subcommand:
|
||||||
|
|
||||||
```
|
```
|
||||||
script/plot_profit.py [-h] [-p pair] [--datadir directory] [--ticker_interval num]
|
usage: freqtrade plot-profit [-h] [-p PAIRS [PAIRS ...]]
|
||||||
|
[--timerange TIMERANGE] [--export EXPORT]
|
||||||
|
[--export-filename PATH] [--db-url PATH]
|
||||||
|
[--trade-source {DB,file}]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||||
|
Show profits for only these pairs. Pairs are space-
|
||||||
|
separated.
|
||||||
|
--timerange TIMERANGE
|
||||||
|
Specify what timerange of data to use.
|
||||||
|
--export EXPORT Export backtest results, argument are: trades.
|
||||||
|
Example: `--export=trades`
|
||||||
|
--export-filename PATH
|
||||||
|
Save backtest results to the file with this filename
|
||||||
|
(default: `user_data/backtest_results/backtest-
|
||||||
|
result.json`). Requires `--export` to be set as well.
|
||||||
|
Example: `--export-filename=user_data/backtest_results
|
||||||
|
/backtest_today.json`
|
||||||
|
--db-url PATH Override trades database URL, this is useful in custom
|
||||||
|
deployments (default: `sqlite:///tradesv3.sqlite` for
|
||||||
|
Live Run mode, `sqlite://` for Dry Run).
|
||||||
|
--trade-source {DB,file}
|
||||||
|
Specify the source for trades (Can be DB or file
|
||||||
|
(backtest file)) Default: file
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The `-p` pair argument, can be used to plot a single pair
|
The `-p/--pairs` argument, can be used to limit the pairs that are considered for this calculation.
|
||||||
|
|
||||||
Example
|
Examples:
|
||||||
|
|
||||||
|
Use custom backtest-export file
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade plot-profit -p LTC/BTC --export-filename user_data/backtest_results/backtest-result-Strategy005.json
|
||||||
```
|
```
|
||||||
python3 scripts/plot_profit.py --datadir ../freqtrade/freqtrade/tests/testdata-20171221/ -p BTC_LTC
|
|
||||||
|
Use custom database
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade plot-profit -p LTC/BTC --db-url sqlite:///tradesv3.sqlite --trade-source DB
|
||||||
|
```
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade --datadir user_data/data/binance_save/ plot-profit -p LTC/BTC
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
mkdocs-material==3.1.0
|
mkdocs-material==4.4.3
|
||||||
|
mdx_truly_sane_lists==1.2
|
||||||
|
|||||||
192
docs/rest-api.md
Normal file
192
docs/rest-api.md
Normal file
@@ -0,0 +1,192 @@
|
|||||||
|
# REST API Usage
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
Enable the rest API by adding the api_server section to your configuration and setting `api_server.enabled` to `true`.
|
||||||
|
|
||||||
|
Sample configuration:
|
||||||
|
|
||||||
|
``` json
|
||||||
|
"api_server": {
|
||||||
|
"enabled": true,
|
||||||
|
"listen_ip_address": "127.0.0.1",
|
||||||
|
"listen_port": 8080,
|
||||||
|
"username": "Freqtrader",
|
||||||
|
"password": "SuperSecret1!"
|
||||||
|
},
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Danger Security warning
|
||||||
|
By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet and choose a strong, unique password, since others will potentially be able to control your bot.
|
||||||
|
|
||||||
|
!!! Danger Password selection
|
||||||
|
Please make sure to select a very strong, unique password to protect your bot from unauthorized access.
|
||||||
|
|
||||||
|
You can then access the API by going to `http://127.0.0.1:8080/api/v1/version` to check if the API is running correctly.
|
||||||
|
|
||||||
|
To generate a secure password, either use a password manager, or use the below code snipped.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
import secrets
|
||||||
|
secrets.token_hex()
|
||||||
|
```
|
||||||
|
|
||||||
|
### Configuration with docker
|
||||||
|
|
||||||
|
If you run your bot using docker, you'll need to have the bot listen to incomming connections. The security is then handled by docker.
|
||||||
|
|
||||||
|
``` json
|
||||||
|
"api_server": {
|
||||||
|
"enabled": true,
|
||||||
|
"listen_ip_address": "0.0.0.0",
|
||||||
|
"listen_port": 8080
|
||||||
|
},
|
||||||
|
```
|
||||||
|
|
||||||
|
Add the following to your docker command:
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
-p 127.0.0.1:8080:8080
|
||||||
|
```
|
||||||
|
|
||||||
|
A complete sample-command may then look as follows:
|
||||||
|
|
||||||
|
```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 \
|
||||||
|
-p 127.0.0.1:8080:8080 \
|
||||||
|
freqtrade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Danger "Security warning"
|
||||||
|
By using `-p 8080:8080` the API is available to everyone connecting to the server under the correct port, so others may be able to control your bot.
|
||||||
|
|
||||||
|
## Consuming the API
|
||||||
|
|
||||||
|
You can consume the API by using the script `scripts/rest_client.py`.
|
||||||
|
The client script only requires the `requests` module, so FreqTrade does not need to be installed on the system.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
python3 scripts/rest_client.py <command> [optional parameters]
|
||||||
|
```
|
||||||
|
|
||||||
|
By default, the script assumes `127.0.0.1` (localhost) and port `8080` to be used, however you can specify a configuration file to override this behaviour.
|
||||||
|
|
||||||
|
### Minimalistic client config
|
||||||
|
|
||||||
|
``` json
|
||||||
|
{
|
||||||
|
"api_server": {
|
||||||
|
"enabled": true,
|
||||||
|
"listen_ip_address": "0.0.0.0",
|
||||||
|
"listen_port": 8080
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
python3 scripts/rest_client.py --config rest_config.json <command> [optional parameters]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Available commands
|
||||||
|
|
||||||
|
| Command | Default | Description |
|
||||||
|
|----------|---------|-------------|
|
||||||
|
| `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_conf` | | Reloads the configuration file
|
||||||
|
| `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
|
||||||
|
| `forcesell <trade_id>` | | Instantly sells the given trade (Ignoring `minimum_roi`).
|
||||||
|
| `forcesell all` | | Instantly sells all open trades (Ignoring `minimum_roi`).
|
||||||
|
| `forcebuy <pair> [rate]` | | Instantly buys the given pair. Rate is optional. (`forcebuy_enable` must be set to True)
|
||||||
|
| `performance` | | Show performance of each finished trade grouped by pair
|
||||||
|
| `balance` | | Show account balance per currency
|
||||||
|
| `daily <n>` | 7 | Shows profit or loss per day, over the last n days
|
||||||
|
| `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
|
||||||
|
|
||||||
|
Possible commands can be listed from the rest-client script using the `help` command.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
python3 scripts/rest_client.py help
|
||||||
|
```
|
||||||
|
|
||||||
|
``` output
|
||||||
|
Possible commands:
|
||||||
|
balance
|
||||||
|
Get the account balance
|
||||||
|
:returns: json object
|
||||||
|
|
||||||
|
blacklist
|
||||||
|
Show the current blacklist
|
||||||
|
:param add: List of coins to add (example: "BNB/BTC")
|
||||||
|
:returns: json object
|
||||||
|
|
||||||
|
count
|
||||||
|
Returns the amount of open trades
|
||||||
|
:returns: json object
|
||||||
|
|
||||||
|
daily
|
||||||
|
Returns the amount of open trades
|
||||||
|
:returns: json object
|
||||||
|
|
||||||
|
edge
|
||||||
|
Returns information about edge
|
||||||
|
:returns: json object
|
||||||
|
|
||||||
|
forcebuy
|
||||||
|
Buy an asset
|
||||||
|
:param pair: Pair to buy (ETH/BTC)
|
||||||
|
:param price: Optional - price to buy
|
||||||
|
:returns: json object of the trade
|
||||||
|
|
||||||
|
forcesell
|
||||||
|
Force-sell a trade
|
||||||
|
:param tradeid: Id of the trade (can be received via status command)
|
||||||
|
:returns: json object
|
||||||
|
|
||||||
|
performance
|
||||||
|
Returns the performance of the different coins
|
||||||
|
:returns: json object
|
||||||
|
|
||||||
|
profit
|
||||||
|
Returns the profit summary
|
||||||
|
:returns: json object
|
||||||
|
|
||||||
|
reload_conf
|
||||||
|
Reload configuration
|
||||||
|
:returns: json object
|
||||||
|
|
||||||
|
start
|
||||||
|
Start the bot if it's in stopped state.
|
||||||
|
:returns: json object
|
||||||
|
|
||||||
|
status
|
||||||
|
Get the status of open trades
|
||||||
|
:returns: json object
|
||||||
|
|
||||||
|
stop
|
||||||
|
Stop the bot. Use start to restart
|
||||||
|
:returns: json object
|
||||||
|
|
||||||
|
stopbuy
|
||||||
|
Stop buying (but handle sells gracefully).
|
||||||
|
use reload_conf to reset
|
||||||
|
:returns: json object
|
||||||
|
|
||||||
|
version
|
||||||
|
Returns the version of the bot
|
||||||
|
:returns: json object containing the version
|
||||||
|
|
||||||
|
whitelist
|
||||||
|
Show the current whitelist
|
||||||
|
:returns: json object
|
||||||
|
```
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
# SQL Helper
|
# SQL Helper
|
||||||
This page constains some help if you want to edit your sqlite db.
|
This page contains some help if you want to edit your sqlite db.
|
||||||
|
|
||||||
## Install sqlite3
|
## Install sqlite3
|
||||||
**Ubuntu/Debian installation**
|
**Ubuntu/Debian installation**
|
||||||
@@ -44,6 +44,14 @@ CREATE TABLE trades (
|
|||||||
open_date DATETIME NOT NULL,
|
open_date DATETIME NOT NULL,
|
||||||
close_date DATETIME,
|
close_date DATETIME,
|
||||||
open_order_id VARCHAR,
|
open_order_id VARCHAR,
|
||||||
|
stop_loss FLOAT,
|
||||||
|
initial_stop_loss FLOAT,
|
||||||
|
stoploss_order_id VARCHAR,
|
||||||
|
stoploss_last_update DATETIME,
|
||||||
|
max_rate FLOAT,
|
||||||
|
sell_reason VARCHAR,
|
||||||
|
strategy VARCHAR,
|
||||||
|
ticker_interval INTEGER,
|
||||||
PRIMARY KEY (id),
|
PRIMARY KEY (id),
|
||||||
CHECK (is_open IN (0, 1))
|
CHECK (is_open IN (0, 1))
|
||||||
);
|
);
|
||||||
@@ -55,38 +63,45 @@ CREATE TABLE trades (
|
|||||||
SELECT * FROM trades;
|
SELECT * FROM trades;
|
||||||
```
|
```
|
||||||
|
|
||||||
## Fix trade still open after a /forcesell
|
## 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.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
This should not be necessary after /forcesell, as forcesell orders are closed automatically by the bot on the next iteration.
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
UPDATE trades
|
UPDATE trades
|
||||||
SET is_open=0, close_date=<close_date>, close_rate=<close_rate>, close_profit=close_rate/open_rate-1
|
SET is_open=0, close_date=<close_date>, close_rate=<close_rate>, close_profit=close_rate/open_rate-1, sell_reason=<sell_reason>
|
||||||
WHERE id=<trade_ID_to_update>;
|
WHERE id=<trade_ID_to_update>;
|
||||||
```
|
```
|
||||||
|
|
||||||
**Example:**
|
##### Example
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
UPDATE trades
|
UPDATE trades
|
||||||
SET is_open=0, close_date='2017-12-20 03:08:45.103418', close_rate=0.19638016, close_profit=0.0496
|
SET is_open=0, close_date='2017-12-20 03:08:45.103418', close_rate=0.19638016, close_profit=0.0496, sell_reason='force_sell'
|
||||||
WHERE id=31;
|
WHERE id=31;
|
||||||
```
|
```
|
||||||
|
|
||||||
## Insert manually a new trade
|
## Insert manually a new trade
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
INSERT
|
INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date)
|
||||||
INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date)
|
VALUES ('bittrex', 'ETH/BTC', 1, 0.0025, 0.0025, <open_rate>, <stake_amount>, <amount>, '<datetime>')
|
||||||
VALUES ('BITTREX', 'BTC_<COIN>', 1, 0.0025, 0.0025, <open_rate>, <stake_amount>, <amount>, '<datetime>')
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Example:**
|
##### Example:
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date) VALUES ('BITTREX', 'BTC_ETC', 1, 0.0025, 0.0025, 0.00258580, 0.002, 0.7715262081, '2017-11-28 12:44:24.000000')
|
INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date)
|
||||||
|
VALUES ('bittrex', 'ETH/BTC', 1, 0.0025, 0.0025, 0.00258580, 0.002, 0.7715262081, '2017-11-28 12:44:24.000000')
|
||||||
```
|
```
|
||||||
|
|
||||||
## Fix wrong fees in the table
|
## Fix wrong fees in the table
|
||||||
If your DB was created before
|
If your DB was created before [PR#200](https://github.com/freqtrade/freqtrade/pull/200) was merged (before 12/23/17).
|
||||||
[PR#200](https://github.com/freqtrade/freqtrade/pull/200) was merged
|
|
||||||
(before 12/23/17).
|
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
UPDATE trades SET fee=0.0025 WHERE fee=0.005;
|
UPDATE trades SET fee=0.0025 WHERE fee=0.005;
|
||||||
|
|||||||
@@ -1,4 +1,13 @@
|
|||||||
# Stop Loss support
|
# Stop Loss
|
||||||
|
|
||||||
|
The `stoploss` configuration parameter is loss in percentage that should trigger a sale.
|
||||||
|
For example, value `-0.10` will cause immediate sell if the profit dips below -10% for a given trade. This parameter is optional.
|
||||||
|
|
||||||
|
Most of the strategy files already include the optimal `stoploss`
|
||||||
|
value. This parameter is optional. If you use it in the configuration file, it will take over the
|
||||||
|
`stoploss` value from the strategy file.
|
||||||
|
|
||||||
|
## Stop Loss support
|
||||||
|
|
||||||
At this stage the bot contains the following stoploss support modes:
|
At this stage the bot contains the following stoploss support modes:
|
||||||
|
|
||||||
@@ -16,13 +25,12 @@ In case of stoploss on exchange there is another parameter called `stoploss_on_e
|
|||||||
!!! Note
|
!!! Note
|
||||||
Stoploss on exchange is only supported for Binance as of now.
|
Stoploss on exchange is only supported for Binance as of now.
|
||||||
|
|
||||||
|
|
||||||
## Static Stop Loss
|
## Static Stop Loss
|
||||||
|
|
||||||
This is very simple, basically you define a stop loss of x in your strategy file or alternative in the configuration, which
|
This is very simple, basically you define a stop loss of x in your strategy file or alternative in the configuration, which
|
||||||
will overwrite the strategy definition. This will basically try to sell your asset, the second the loss exceeds the defined loss.
|
will overwrite the strategy definition. This will basically try to sell your asset, the second the loss exceeds the defined loss.
|
||||||
|
|
||||||
## Trail Stop Loss
|
## Trailing Stop Loss
|
||||||
|
|
||||||
The initial value for this stop loss, is defined in your strategy or configuration. Just as you would define your Stop Loss normally.
|
The initial value for this stop loss, is defined in your strategy or configuration. Just as you would define your Stop Loss normally.
|
||||||
To enable this Feauture all you have to do is to define the configuration element:
|
To enable this Feauture all you have to do is to define the configuration element:
|
||||||
@@ -55,8 +63,21 @@ Both values can be configured in the main configuration file and requires `"trai
|
|||||||
``` json
|
``` json
|
||||||
"trailing_stop_positive": 0.01,
|
"trailing_stop_positive": 0.01,
|
||||||
"trailing_stop_positive_offset": 0.011,
|
"trailing_stop_positive_offset": 0.011,
|
||||||
|
"trailing_only_offset_is_reached": false
|
||||||
```
|
```
|
||||||
|
|
||||||
The 0.01 would translate to a 1% stop loss, once you hit 1.1% profit.
|
The 0.01 would translate to a 1% stop loss, once you hit 1.1% profit.
|
||||||
|
|
||||||
You should also make sure to have this value (`trailing_stop_positive_offset`) lower than your minimal ROI, otherwise minimal ROI will apply first and sell your trade.
|
You should also make sure to have this value (`trailing_stop_positive_offset`) lower than your minimal ROI, otherwise minimal ROI will apply first and sell your trade.
|
||||||
|
|
||||||
|
If `"trailing_only_offset_is_reached": true` then the trailing stoploss is only activated once the offset is reached. Until then, the stoploss remains at the configured`stoploss`.
|
||||||
|
|
||||||
|
## Changing stoploss on open trades
|
||||||
|
|
||||||
|
A stoploss on an open trade can be changed by changing the value in the configuration or strategy and use the `/reload_conf` command (alternatively, completely stopping and restarting the bot also works).
|
||||||
|
|
||||||
|
The new stoploss value will be applied to open trades (and corresponding log-messages will be generated).
|
||||||
|
|
||||||
|
### Limitations
|
||||||
|
|
||||||
|
Stoploss values cannot be changed if `trailing_stop` is enabled and the stoploss has already been adjusted, or if [Edge](edge.md) is enabled (since Edge would recalculate stoploss based on the current market situation).
|
||||||
|
|||||||
@@ -5,8 +5,7 @@ indicators.
|
|||||||
|
|
||||||
## Install a custom strategy file
|
## Install a custom strategy file
|
||||||
|
|
||||||
This is very simple. Copy paste your strategy file into the folder
|
This is very simple. Copy paste your strategy file into the directory `user_data/strategies`.
|
||||||
`user_data/strategies`.
|
|
||||||
|
|
||||||
Let assume you have a class called `AwesomeStrategy` in the file `awesome-strategy.py`:
|
Let assume you have a class called `AwesomeStrategy` in the file `awesome-strategy.py`:
|
||||||
|
|
||||||
@@ -14,7 +13,7 @@ Let assume you have a class called `AwesomeStrategy` in the file `awesome-strate
|
|||||||
2. Start the bot with the param `--strategy AwesomeStrategy` (the parameter is the class name)
|
2. Start the bot with the param `--strategy AwesomeStrategy` (the parameter is the class name)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy
|
freqtrade --strategy AwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
## Change your strategy
|
## Change your strategy
|
||||||
@@ -22,10 +21,10 @@ python3 ./freqtrade/main.py --strategy AwesomeStrategy
|
|||||||
The bot includes a default strategy file. However, we recommend you to
|
The bot includes a default strategy file. However, we recommend you to
|
||||||
use your own file to not have to lose your parameters every time the default
|
use your own file to not have to lose your parameters every time the default
|
||||||
strategy file will be updated on Github. Put your custom strategy file
|
strategy file will be updated on Github. Put your custom strategy file
|
||||||
into the folder `user_data/strategies`.
|
into the directory `user_data/strategies`.
|
||||||
|
|
||||||
Best copy the test-strategy and modify this copy to avoid having bot-updates override your changes.
|
Best copy the test-strategy and modify this copy to avoid having bot-updates override your changes.
|
||||||
`cp user_data/strategies/test_strategy.py user_data/strategies/awesome-strategy.py`
|
`cp user_data/strategies/sample_strategy.py user_data/strategies/awesome-strategy.py`
|
||||||
|
|
||||||
### Anatomy of a strategy
|
### Anatomy of a strategy
|
||||||
|
|
||||||
@@ -37,22 +36,32 @@ A strategy file contains all the information needed to build a good strategy:
|
|||||||
- Minimal ROI recommended
|
- Minimal ROI recommended
|
||||||
- Stoploss strongly recommended
|
- Stoploss strongly recommended
|
||||||
|
|
||||||
The bot also include a sample strategy called `TestStrategy` you can update: `user_data/strategies/test_strategy.py`.
|
The bot also include a sample strategy called `SampleStrategy` you can update: `user_data/strategies/sample_strategy.py`.
|
||||||
You can test it with the parameter: `--strategy TestStrategy`
|
You can test it with the parameter: `--strategy SampleStrategy`
|
||||||
|
|
||||||
|
Additionally, there is an attribute called `INTERFACE_VERSION`, which defines the version of the strategy interface the bot should use.
|
||||||
|
The current version is 2 - which is also the default when it's not set explicitly in the strategy.
|
||||||
|
|
||||||
|
Future versions will require this to be set.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy
|
freqtrade --strategy AwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
**For the following section we will use the [user_data/strategies/test_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/strategies/test_strategy.py)
|
**For the following section we will use the [user_data/strategies/sample_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/strategies/sample_strategy.py)
|
||||||
file as reference.**
|
file as reference.**
|
||||||
|
|
||||||
!!! Note: Strategies and Backtesting
|
!!! Note Strategies and Backtesting
|
||||||
To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware
|
To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware
|
||||||
that during backtesting the full time-interval is passed to the `populate_*()` methods at once.
|
that during backtesting the full time-interval is passed to the `populate_*()` methods at once.
|
||||||
It is therefore best to use vectorized operations (across the whole dataframe, not loops) and
|
It is therefore best to use vectorized operations (across the whole dataframe, not loops) and
|
||||||
avoid index referencing (`df.iloc[-1]`), but instead use `df.shift()` to get to the previous candle.
|
avoid index referencing (`df.iloc[-1]`), but instead use `df.shift()` to get to the previous candle.
|
||||||
|
|
||||||
|
!!! Warning Using future data
|
||||||
|
Since backtesting passes the full time interval to the `populate_*()` methods, the strategy author
|
||||||
|
needs to take care to avoid having the strategy utilize data from the future.
|
||||||
|
Some common patterns for this are listed in the [Common Mistakes](#common-mistakes-when-developing-strategies) section of this document.
|
||||||
|
|
||||||
### Customize Indicators
|
### Customize Indicators
|
||||||
|
|
||||||
Buy and sell strategies need indicators. You can add more indicators by extending the list contained in the method `populate_indicators()` from your strategy file.
|
Buy and sell strategies need indicators. You can add more indicators by extending the list contained in the method `populate_indicators()` from your strategy file.
|
||||||
@@ -104,9 +113,8 @@ def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame
|
|||||||
return dataframe
|
return dataframe
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
!!! Note "Want more indicator examples?"
|
!!! Note "Want more indicator examples?"
|
||||||
Look into the [user_data/strategies/test_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/strategies/test_strategy.py).<br/>
|
Look into the [user_data/strategies/sample_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/strategies/sample_strategy.py).
|
||||||
Then uncomment indicators you need.
|
Then uncomment indicators you need.
|
||||||
|
|
||||||
### Buy signal rules
|
### Buy signal rules
|
||||||
@@ -117,7 +125,7 @@ It's important to always return the dataframe without removing/modifying the col
|
|||||||
|
|
||||||
This will method will also define a new column, `"buy"`, which needs to contain 1 for buys, and 0 for "no action".
|
This will method will also define a new column, `"buy"`, which needs to contain 1 for buys, and 0 for "no action".
|
||||||
|
|
||||||
Sample from `user_data/strategies/test_strategy.py`:
|
Sample from `user_data/strategies/sample_strategy.py`:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
@@ -129,15 +137,19 @@ def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|||||||
"""
|
"""
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(
|
(
|
||||||
(dataframe['adx'] > 30) &
|
(qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30
|
||||||
(dataframe['tema'] <= dataframe['bb_middleband']) &
|
(dataframe['tema'] <= dataframe['bb_middleband']) & # Guard
|
||||||
(dataframe['tema'] > dataframe['tema'].shift(1))
|
(dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
),
|
),
|
||||||
'buy'] = 1
|
'buy'] = 1
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
```
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Buying requires sellers to buy from - therefore volume needs to be > 0 (`dataframe['volume'] > 0`) to make sure that the bot does not buy/sell in no-activity periods.
|
||||||
|
|
||||||
### Sell signal rules
|
### Sell signal rules
|
||||||
|
|
||||||
Edit the method `populate_sell_trend()` into your strategy file to update your sell strategy.
|
Edit the method `populate_sell_trend()` into your strategy file to update your sell strategy.
|
||||||
@@ -147,7 +159,7 @@ It's important to always return the dataframe without removing/modifying the col
|
|||||||
|
|
||||||
This will method will also define a new column, `"sell"`, which needs to contain 1 for sells, and 0 for "no action".
|
This will method will also define a new column, `"sell"`, which needs to contain 1 for sells, and 0 for "no action".
|
||||||
|
|
||||||
Sample from `user_data/strategies/test_strategy.py`:
|
Sample from `user_data/strategies/sample_strategy.py`:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
@@ -159,9 +171,10 @@ def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame
|
|||||||
"""
|
"""
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(
|
(
|
||||||
(dataframe['adx'] > 70) &
|
(qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70
|
||||||
(dataframe['tema'] > dataframe['bb_middleband']) &
|
(dataframe['tema'] > dataframe['bb_middleband']) & # Guard
|
||||||
(dataframe['tema'] < dataframe['tema'].shift(1))
|
(dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
),
|
),
|
||||||
'sell'] = 1
|
'sell'] = 1
|
||||||
return dataframe
|
return dataframe
|
||||||
@@ -212,9 +225,12 @@ stoploss = -0.10
|
|||||||
```
|
```
|
||||||
|
|
||||||
This would signify a stoploss of -10%.
|
This would signify a stoploss of -10%.
|
||||||
If your exchange supports it, it's recommended to also set `"stoploss_on_exchange"` in the order dict, so your stoploss is on the exchange and cannot be missed for network-problems (or other problems).
|
|
||||||
|
|
||||||
For more information on order_types please look [here](https://github.com/freqtrade/freqtrade/blob/develop/docs/configuration.md#understand-order_types).
|
For the full documentation on stoploss features, look at the dedicated [stoploss page](stoploss.md).
|
||||||
|
|
||||||
|
If your exchange supports it, it's recommended to also set `"stoploss_on_exchange"` in the order_types dictionary, so your stoploss is on the exchange and cannot be missed due to network problems, high load or other reasons.
|
||||||
|
|
||||||
|
For more information on order_types please look [here](configuration.md#understand-order_types).
|
||||||
|
|
||||||
### Ticker interval
|
### Ticker interval
|
||||||
|
|
||||||
@@ -234,9 +250,9 @@ Instead, have a look at the section [Storing information](#Storing-information)
|
|||||||
|
|
||||||
### Storing information
|
### Storing information
|
||||||
|
|
||||||
Storing information can be accomplished by crating a new dictionary within the strategy class.
|
Storing information can be accomplished by creating a new dictionary within the strategy class.
|
||||||
|
|
||||||
The name of the variable can be choosen at will, but should be prefixed with `cust_` to avoid naming collisions with predefined strategy variables.
|
The name of the variable can be chosen at will, but should be prefixed with `cust_` to avoid naming collisions with predefined strategy variables.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
class Awesomestrategy(IStrategy):
|
class Awesomestrategy(IStrategy):
|
||||||
@@ -250,48 +266,61 @@ class Awesomestrategy(IStrategy):
|
|||||||
self.cust_info[metadata["pair"]["crosstime"] = 1
|
self.cust_info[metadata["pair"]["crosstime"] = 1
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Warning:
|
!!! Warning
|
||||||
The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash.
|
The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash.
|
||||||
|
|
||||||
!!! Note:
|
!!! Note
|
||||||
If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.
|
If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.
|
||||||
|
|
||||||
### Additional data (DataProvider)
|
### Additional data (DataProvider)
|
||||||
|
|
||||||
The strategy provides access to the `DataProvider`. This allows you to get additional data to use in your strategy.
|
The strategy provides access to the `DataProvider`. This allows you to get additional data to use in your strategy.
|
||||||
|
|
||||||
!!!Note:
|
|
||||||
The DataProvier is currently not available during backtesting / hyperopt, but this is planned for the future.
|
|
||||||
|
|
||||||
All methods return `None` in case of failure (do not raise an exception).
|
All methods return `None` in case of failure (do not raise an exception).
|
||||||
|
|
||||||
Please always check if the `DataProvider` is available to avoid failures during backtesting.
|
Please always check the mode of operation to select the correct method to get data (samples see below).
|
||||||
|
|
||||||
#### Possible options for DataProvider
|
#### Possible options for DataProvider
|
||||||
|
|
||||||
- `available_pairs` - Property with tuples listing cached pairs with their intervals. (pair, interval)
|
- `available_pairs` - Property with tuples listing cached pairs with their intervals (pair, interval).
|
||||||
- `ohlcv(pair, ticker_interval)` - Currently cached ticker data for all pairs in the whitelist, returns DataFrame or empty DataFrame
|
- `ohlcv(pair, ticker_interval)` - Currently cached ticker data for the pair, returns DataFrame or empty DataFrame.
|
||||||
- `historic_ohlcv(pair, ticker_interval)` - Data stored on disk
|
- `historic_ohlcv(pair, ticker_interval)` - Returns historical data stored on disk.
|
||||||
|
- `get_pair_dataframe(pair, ticker_interval)` - This is a universal method, which returns either historical data (for backtesting) or cached live data (for the Dry-Run and Live-Run modes).
|
||||||
|
- `orderbook(pair, maximum)` - Returns latest orderbook data for the pair, a dict with bids/asks with a total of `maximum` entries.
|
||||||
|
- `market(pair)` - Returns market data for the pair: fees, limits, precisions, activity flag, etc. See [ccxt documentation](https://github.com/ccxt/ccxt/wiki/Manual#markets) for more details on Market data structure.
|
||||||
- `runmode` - Property containing the current runmode.
|
- `runmode` - Property containing the current runmode.
|
||||||
|
|
||||||
#### ohlcv / historic_ohlcv
|
#### Example: fetch live ohlcv / historic data for the first informative pair
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
if self.dp:
|
if self.dp:
|
||||||
if dp.runmode == 'live':
|
inf_pair, inf_timeframe = self.informative_pairs()[0]
|
||||||
if ('ETH/BTC', ticker_interval) in self.dp.available_pairs:
|
informative = self.dp.get_pair_dataframe(pair=inf_pair,
|
||||||
data_eth = self.dp.ohlcv(pair='ETH/BTC',
|
ticker_interval=inf_timeframe)
|
||||||
ticker_interval=ticker_interval)
|
|
||||||
else:
|
|
||||||
# Get historic ohlcv data (cached on disk).
|
|
||||||
history_eth = self.dp.historic_ohlcv(pair='ETH/BTC',
|
|
||||||
ticker_interval='1h')
|
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Warning: Warning about backtesting
|
!!! Warning Warning about backtesting
|
||||||
Be carefull when using dataprovider in backtesting. `historic_ohlcv()` provides the full time-range in one go,
|
Be carefull when using dataprovider in backtesting. `historic_ohlcv()` (and `get_pair_dataframe()`
|
||||||
|
for the backtesting runmode) provides the full time-range in one go,
|
||||||
so please be aware of it and make sure to not "look into the future" to avoid surprises when running in dry/live mode).
|
so please be aware of it and make sure to not "look into the future" to avoid surprises when running in dry/live mode).
|
||||||
|
|
||||||
|
!!! Warning Warning in hyperopt
|
||||||
|
This option cannot currently be used during hyperopt.
|
||||||
|
|
||||||
|
#### Orderbook
|
||||||
|
|
||||||
|
``` python
|
||||||
|
if self.dp:
|
||||||
|
if self.dp.runmode in ('live', 'dry_run'):
|
||||||
|
ob = self.dp.orderbook(metadata['pair'], 1)
|
||||||
|
dataframe['best_bid'] = ob['bids'][0][0]
|
||||||
|
dataframe['best_ask'] = ob['asks'][0][0]
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Warning
|
||||||
|
The order book is not part of the historic data which means backtesting and hyperopt will not work if this
|
||||||
|
method is used.
|
||||||
|
|
||||||
#### Available Pairs
|
#### Available Pairs
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
@@ -317,17 +346,17 @@ def informative_pairs(self):
|
|||||||
]
|
]
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Warning:
|
!!! Warning
|
||||||
As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short.
|
As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short.
|
||||||
All intervals and all pairs can be specified as long as they are available (and active) on the used exchange.
|
All intervals and all pairs can be specified as long as they are available (and active) on the used exchange.
|
||||||
It is however better to use resampling to longer time-intervals when possible
|
It is however better to use resampling to longer time-intervals when possible
|
||||||
to avoid hammering the exchange with too many requests and risk beeing blocked.
|
to avoid hammering the exchange with too many requests and risk being blocked.
|
||||||
|
|
||||||
### Additional data - Wallets
|
### Additional data (Wallets)
|
||||||
|
|
||||||
The strategy provides access to the `Wallets` object. This contains the current balances on the exchange.
|
The strategy provides access to the `Wallets` object. This contains the current balances on the exchange.
|
||||||
|
|
||||||
!!!NOTE:
|
!!! Note
|
||||||
Wallets is not available during backtesting / hyperopt.
|
Wallets is not available during backtesting / hyperopt.
|
||||||
|
|
||||||
Please always check if `Wallets` is available to avoid failures during backtesting.
|
Please always check if `Wallets` is available to avoid failures during backtesting.
|
||||||
@@ -345,26 +374,62 @@ if self.wallets:
|
|||||||
- `get_used(asset)` - currently tied up balance (open orders)
|
- `get_used(asset)` - currently tied up balance (open orders)
|
||||||
- `get_total(asset)` - total available balance - sum of the 2 above
|
- `get_total(asset)` - total available balance - sum of the 2 above
|
||||||
|
|
||||||
### Where is the default strategy?
|
### Print created dataframe
|
||||||
|
|
||||||
The default buy strategy is located in the file
|
To inspect the created dataframe, you can issue a print-statement in either `populate_buy_trend()` or `populate_sell_trend()`.
|
||||||
[freqtrade/default_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/strategy/default_strategy.py).
|
You may also want to print the pair so it's clear what data is currently shown.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
dataframe.loc[
|
||||||
|
(
|
||||||
|
#>> whatever condition<<<
|
||||||
|
),
|
||||||
|
'buy'] = 1
|
||||||
|
|
||||||
|
# Print the Analyzed pair
|
||||||
|
print(f"result for {metadata['pair']}")
|
||||||
|
|
||||||
|
# Inspect the last 5 rows
|
||||||
|
print(dataframe.tail())
|
||||||
|
|
||||||
|
return dataframe
|
||||||
|
```
|
||||||
|
|
||||||
|
Printing more than a few rows is also possible (simply use `print(dataframe)` instead of `print(dataframe.tail())`), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds).
|
||||||
|
|
||||||
|
### Where can i find a strategy template?
|
||||||
|
|
||||||
|
The strategy template is located in the file
|
||||||
|
[user_data/strategies/sample_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/strategies/sample_strategy.py).
|
||||||
|
|
||||||
### Specify custom strategy location
|
### Specify custom strategy location
|
||||||
|
|
||||||
If you want to use a strategy from a different folder you can pass `--strategy-path`
|
If you want to use a strategy from a different directory you can pass `--strategy-path`
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy --strategy-path /some/folder
|
freqtrade --strategy AwesomeStrategy --strategy-path /some/directory
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Common mistakes when developing strategies
|
||||||
|
|
||||||
|
Backtesting analyzes the whole time-range at once for performance reasons. Because of this, strategy authors need to make sure that strategies do not look-ahead into the future.
|
||||||
|
This is a common pain-point, which can cause huge differences between backtesting and dry/live run methods, since they all use data which is not available during dry/live runs, so these strategies will perform well during backtesting, but will fail / perform badly in real conditions.
|
||||||
|
|
||||||
|
The following lists some common patterns which should be avoided to prevent frustration:
|
||||||
|
|
||||||
|
- don't use `shift(-1)`. This uses data from the future, which is not available.
|
||||||
|
- don't use `.iloc[-1]` or any other absolute position in the dataframe, this will be different between dry-run and backtesting.
|
||||||
|
- don't use `dataframe['volume'].mean()`. This uses the full DataFrame for backtesting, including data from the future. Use `dataframe['volume'].rolling(<window>).mean()` instead
|
||||||
|
- don't use `.resample('1h')`. This uses the left border of the interval, so moves data from an hour to the start of the hour. Use `.resample('1h', label='right')` instead.
|
||||||
|
|
||||||
### Further strategy ideas
|
### Further strategy ideas
|
||||||
|
|
||||||
To get additional Ideas for strategies, head over to our [strategy repository](https://github.com/freqtrade/freqtrade-strategies). Feel free to use them as they are - but results will depend on the current market situation, pairs used etc. - therefore please backtest the strategy for your exchange/desired pairs first, evaluate carefully, use at your own risk.
|
To get additional Ideas for strategies, head over to our [strategy repository](https://github.com/freqtrade/freqtrade-strategies). Feel free to use them as they are - but results will depend on the current market situation, pairs used etc. - therefore please backtest the strategy for your exchange/desired pairs first, evaluate carefully, use at your own risk.
|
||||||
Feel free to use any of them as inspiration for your own strategies.
|
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're happy to accept Pull Requests containing new Strategies to that repo.
|
||||||
|
|
||||||
We also got a *strategy-sharing* channel in our [Slack community](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE) which is a great place to get and/or share ideas.
|
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
|
## Next step
|
||||||
|
|
||||||
142
docs/strategy_analysis_example.md
Normal file
142
docs/strategy_analysis_example.md
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
# Strategy analysis example
|
||||||
|
|
||||||
|
Debugging a strategy can be time-consuming. FreqTrade offers helper functions to visualize raw data.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from pathlib import Path
|
||||||
|
# Customize these according to your needs.
|
||||||
|
|
||||||
|
# Define some constants
|
||||||
|
ticker_interval = "5m"
|
||||||
|
# Name of the strategy class
|
||||||
|
strategy_name = 'SampleStrategy'
|
||||||
|
# Path to user data
|
||||||
|
user_data_dir = Path('user_data')
|
||||||
|
# Location of the strategy
|
||||||
|
strategy_location = user_data_dir / 'strategies'
|
||||||
|
# Location of the data
|
||||||
|
data_location = Path(user_data_dir, 'data', 'binance')
|
||||||
|
# Pair to analyze - Only use one pair here
|
||||||
|
pair = "BTC_USDT"
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Load data using values set above
|
||||||
|
from freqtrade.data.history import load_pair_history
|
||||||
|
|
||||||
|
candles = load_pair_history(datadir=data_location,
|
||||||
|
ticker_interval=ticker_interval,
|
||||||
|
pair=pair)
|
||||||
|
|
||||||
|
# Confirm success
|
||||||
|
print("Loaded " + str(len(candles)) + f" rows of data for {pair} from {data_location}")
|
||||||
|
candles.head()
|
||||||
|
```
|
||||||
|
|
||||||
|
## Load and run strategy
|
||||||
|
* Rerun each time the strategy file is changed
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Load strategy using values set above
|
||||||
|
from freqtrade.resolvers import StrategyResolver
|
||||||
|
strategy = StrategyResolver({'strategy': strategy_name,
|
||||||
|
'user_data_dir': user_data_dir,
|
||||||
|
'strategy_path': strategy_location}).strategy
|
||||||
|
|
||||||
|
# Generate buy/sell signals using strategy
|
||||||
|
df = strategy.analyze_ticker(candles, {'pair': pair})
|
||||||
|
df.tail()
|
||||||
|
```
|
||||||
|
|
||||||
|
### Display the trade details
|
||||||
|
|
||||||
|
* Note that using `data.head()` would also work, however most indicators have some "startup" data at the top of the dataframe.
|
||||||
|
* Some possible problems
|
||||||
|
* Columns with NaN values at the end of the dataframe
|
||||||
|
* Columns used in `crossed*()` functions with completely different units
|
||||||
|
* Comparison with full backtest
|
||||||
|
* having 200 buy signals as output for one pair from `analyze_ticker()` does not necessarily mean that 200 trades will be made during backtesting.
|
||||||
|
* Assuming you use only one condition such as, `df['rsi'] < 30` as buy condition, this will generate multiple "buy" signals for each pair in sequence (until rsi returns > 29). The bot will only buy on the first of these signals (and also only if a trade-slot ("max_open_trades") is still available), or on one of the middle signals, as soon as a "slot" becomes available.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Report results
|
||||||
|
print(f"Generated {df['buy'].sum()} buy signals")
|
||||||
|
data = df.set_index('date', drop=False)
|
||||||
|
data.tail()
|
||||||
|
```
|
||||||
|
|
||||||
|
## Load existing objects into a Jupyter notebook
|
||||||
|
|
||||||
|
The following cells assume that you have already generated data using the cli.
|
||||||
|
They will allow you to drill deeper into your results, and perform analysis which otherwise would make the output very difficult to digest due to information overload.
|
||||||
|
|
||||||
|
### Load backtest results to pandas dataframe
|
||||||
|
|
||||||
|
Analyze a trades dataframe (also used below for plotting)
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from freqtrade.data.btanalysis import load_backtest_data
|
||||||
|
|
||||||
|
# Load backtest results
|
||||||
|
trades = load_backtest_data(user_data_dir / "backtest_results/backtest-result.json")
|
||||||
|
|
||||||
|
# Show value-counts per pair
|
||||||
|
trades.groupby("pair")["sell_reason"].value_counts()
|
||||||
|
```
|
||||||
|
|
||||||
|
### Load live trading results into a pandas dataframe
|
||||||
|
|
||||||
|
In case you did already some trading and want to analyze your performance
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from freqtrade.data.btanalysis import load_trades_from_db
|
||||||
|
|
||||||
|
# Fetch trades from database
|
||||||
|
trades = load_trades_from_db("sqlite:///tradesv3.sqlite")
|
||||||
|
|
||||||
|
# Display results
|
||||||
|
trades.groupby("pair")["sell_reason"].value_counts()
|
||||||
|
```
|
||||||
|
|
||||||
|
## Plot results
|
||||||
|
|
||||||
|
Freqtrade offers interactive plotting capabilities based on plotly.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from freqtrade.plot.plotting import generate_candlestick_graph
|
||||||
|
# Limit graph period to keep plotly quick and reactive
|
||||||
|
|
||||||
|
data_red = data['2019-06-01':'2019-06-10']
|
||||||
|
# Generate candlestick graph
|
||||||
|
graph = generate_candlestick_graph(pair=pair,
|
||||||
|
data=data_red,
|
||||||
|
trades=trades,
|
||||||
|
indicators1=['sma20', 'ema50', 'ema55'],
|
||||||
|
indicators2=['rsi', 'macd', 'macdsignal', 'macdhist']
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Show graph inline
|
||||||
|
# graph.show()
|
||||||
|
|
||||||
|
# Render graph in a seperate window
|
||||||
|
graph.show(renderer="browser")
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.
|
||||||
13
docs/stylesheets/ft.extra.css
Normal file
13
docs/stylesheets/ft.extra.css
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
.rst-versions {
|
||||||
|
font-size: .7rem;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rst-versions.rst-badge .rst-current-version {
|
||||||
|
font-size: .7rem;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rst-versions .rst-other-versions {
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
@@ -1,13 +1,48 @@
|
|||||||
# Telegram usage
|
# Telegram usage
|
||||||
|
|
||||||
This page explains how to command your bot with Telegram.
|
## Setup your Telegram bot
|
||||||
|
|
||||||
## Prerequisite
|
Below we explain how to create your Telegram Bot, and how to get your
|
||||||
To control your bot with Telegram, you need first to
|
Telegram user id.
|
||||||
[set up a Telegram bot](installation.md)
|
|
||||||
and add your Telegram API keys into your config file.
|
### 1. Create your Telegram bot
|
||||||
|
|
||||||
|
Start a chat with the [Telegram BotFather](https://telegram.me/BotFather)
|
||||||
|
|
||||||
|
Send the message `/newbot`.
|
||||||
|
|
||||||
|
*BotFather response:*
|
||||||
|
|
||||||
|
> Alright, a new bot. How are we going to call it? Please choose a name for your bot.
|
||||||
|
|
||||||
|
Choose the public name of your bot (e.x. `Freqtrade bot`)
|
||||||
|
|
||||||
|
*BotFather response:*
|
||||||
|
|
||||||
|
> Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.
|
||||||
|
|
||||||
|
Choose the name id of your bot and send it to the BotFather (e.g. "`My_own_freqtrade_bot`")
|
||||||
|
|
||||||
|
*BotFather response:*
|
||||||
|
|
||||||
|
> Done! Congratulations on your new bot. You will find it at `t.me/yourbots_name_bot`. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.
|
||||||
|
|
||||||
|
> Use this token to access the HTTP API: `22222222:APITOKEN`
|
||||||
|
|
||||||
|
> For a description of the Bot API, see this page: https://core.telegram.org/bots/api Father bot will return you the token (API key)
|
||||||
|
|
||||||
|
Copy the API Token (`22222222:APITOKEN` in the above example) and keep use it for the config parameter `token`.
|
||||||
|
|
||||||
|
Don't forget to start the conversation with your bot, by clicking `/START` button
|
||||||
|
|
||||||
|
### 2. 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`.
|
||||||
|
|
||||||
## Telegram commands
|
## Telegram commands
|
||||||
|
|
||||||
Per default, the Telegram bot shows predefined commands. Some commands
|
Per default, the Telegram bot shows predefined commands. Some commands
|
||||||
are only available by sending them to the bot. The table below list the
|
are only available by sending them to the bot. The table below list the
|
||||||
official commands. You can ask at any moment for help with `/help`.
|
official commands. You can ask at any moment for help with `/help`.
|
||||||
@@ -16,6 +51,7 @@ official commands. You can ask at any moment for help with `/help`.
|
|||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| `/start` | | Starts the trader
|
| `/start` | | Starts the trader
|
||||||
| `/stop` | | Stops the trader
|
| `/stop` | | Stops the trader
|
||||||
|
| `/stopbuy` | | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
||||||
| `/reload_conf` | | Reloads the configuration file
|
| `/reload_conf` | | Reloads the configuration file
|
||||||
| `/status` | | Lists all open trades
|
| `/status` | | Lists all open trades
|
||||||
| `/status table` | | List all open trades in a table format
|
| `/status table` | | List all open trades in a table format
|
||||||
@@ -27,6 +63,9 @@ official commands. You can ask at any moment for help with `/help`.
|
|||||||
| `/performance` | | Show performance of each finished trade grouped by pair
|
| `/performance` | | Show performance of each finished trade grouped by pair
|
||||||
| `/balance` | | Show account balance per currency
|
| `/balance` | | Show account balance per currency
|
||||||
| `/daily <n>` | 7 | Shows profit or loss per day, over the last n days
|
| `/daily <n>` | 7 | Shows profit or loss per day, over the last n days
|
||||||
|
| `/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.
|
||||||
| `/help` | | Show help message
|
| `/help` | | Show help message
|
||||||
| `/version` | | Show version
|
| `/version` | | Show version
|
||||||
|
|
||||||
@@ -43,22 +82,34 @@ Below, example of Telegram message you will receive for each command.
|
|||||||
> `Stopping trader ...`
|
> `Stopping trader ...`
|
||||||
> **Status:** `stopped`
|
> **Status:** `stopped`
|
||||||
|
|
||||||
## /status
|
### /stopbuy
|
||||||
|
|
||||||
|
> **status:** `Setting max_open_trades to 0. Run /reload_conf to reset.`
|
||||||
|
|
||||||
|
Prevents the bot from opening new trades by temporarily setting "max_open_trades" to 0. Open trades will be handled via their regular rules (ROI / Sell-signal, stoploss, ...).
|
||||||
|
|
||||||
|
After this, give the bot time to close off open trades (can be checked via `/status table`).
|
||||||
|
Once all positions are sold, run `/stop` to completely stop the bot.
|
||||||
|
|
||||||
|
`/reload_conf` resets "max_open_trades" to the value set in the configuration and resets this command.
|
||||||
|
|
||||||
|
!!! warning
|
||||||
|
The stop-buy signal is ONLY active while the bot is running, and is not persisted anyway, so restarting the bot will cause this to reset.
|
||||||
|
|
||||||
|
### /status
|
||||||
|
|
||||||
For each open trade, the bot will send you the following message.
|
For each open trade, the bot will send you the following message.
|
||||||
|
|
||||||
> **Trade ID:** `123`
|
> **Trade ID:** `123` `(since 1 days ago)`
|
||||||
> **Current Pair:** CVC/BTC
|
> **Current Pair:** CVC/BTC
|
||||||
> **Open Since:** `1 days ago`
|
> **Open Since:** `1 days ago`
|
||||||
> **Amount:** `26.64180098`
|
> **Amount:** `26.64180098`
|
||||||
> **Open Rate:** `0.00007489`
|
> **Open Rate:** `0.00007489`
|
||||||
> **Close Rate:** `None`
|
> **Current Rate:** `0.00007489`
|
||||||
> **Current Rate:** `0.00007489`
|
> **Current Profit:** `12.95%`
|
||||||
> **Close Profit:** `None`
|
> **Stoploss:** `0.00007389 (-0.02%)`
|
||||||
> **Current Profit:** `12.95%`
|
|
||||||
> **Open Order:** `None`
|
|
||||||
|
|
||||||
## /status table
|
### /status table
|
||||||
|
|
||||||
Return the status of all open trades in a table format.
|
Return the status of all open trades in a table format.
|
||||||
```
|
```
|
||||||
@@ -68,7 +119,7 @@ Return the status of all open trades in a table format.
|
|||||||
123 CVC/BTC 1 h 12.95%
|
123 CVC/BTC 1 h 12.95%
|
||||||
```
|
```
|
||||||
|
|
||||||
## /count
|
### /count
|
||||||
|
|
||||||
Return the number of trades used and available.
|
Return the number of trades used and available.
|
||||||
```
|
```
|
||||||
@@ -77,59 +128,61 @@ current max
|
|||||||
2 10
|
2 10
|
||||||
```
|
```
|
||||||
|
|
||||||
## /profit
|
### /profit
|
||||||
|
|
||||||
Return a summary of your profit/loss and performance.
|
Return a summary of your profit/loss and performance.
|
||||||
|
|
||||||
> **ROI:** Close trades
|
> **ROI:** Close trades
|
||||||
> ∙ `0.00485701 BTC (258.45%)`
|
> ∙ `0.00485701 BTC (258.45%)`
|
||||||
> ∙ `62.968 USD`
|
> ∙ `62.968 USD`
|
||||||
> **ROI:** All trades
|
> **ROI:** All trades
|
||||||
> ∙ `0.00255280 BTC (143.43%)`
|
> ∙ `0.00255280 BTC (143.43%)`
|
||||||
> ∙ `33.095 EUR`
|
> ∙ `33.095 EUR`
|
||||||
>
|
>
|
||||||
> **Total Trade Count:** `138`
|
> **Total Trade Count:** `138`
|
||||||
> **First Trade opened:** `3 days ago`
|
> **First Trade opened:** `3 days ago`
|
||||||
> **Latest Trade opened:** `2 minutes ago`
|
> **Latest Trade opened:** `2 minutes ago`
|
||||||
> **Avg. Duration:** `2:33:45`
|
> **Avg. Duration:** `2:33:45`
|
||||||
> **Best Performing:** `PAY/BTC: 50.23%`
|
> **Best Performing:** `PAY/BTC: 50.23%`
|
||||||
|
|
||||||
## /forcesell <trade_id>
|
### /forcesell <trade_id>
|
||||||
|
|
||||||
> **BITTREX:** Selling BTC/LTC with limit `0.01650000 (profit: ~-4.07%, -0.00008168)`
|
> **BITTREX:** Selling BTC/LTC with limit `0.01650000 (profit: ~-4.07%, -0.00008168)`
|
||||||
|
|
||||||
## /forcebuy <pair>
|
### /forcebuy <pair>
|
||||||
|
|
||||||
> **BITTREX**: Buying ETH/BTC with limit `0.03400000` (`1.000000 ETH`, `225.290 USD`)
|
> **BITTREX:** Buying ETH/BTC with limit `0.03400000` (`1.000000 ETH`, `225.290 USD`)
|
||||||
|
|
||||||
Note that for this to work, `forcebuy_enable` needs to be set to true.
|
Note that for this to work, `forcebuy_enable` needs to be set to true.
|
||||||
|
|
||||||
## /performance
|
[More details](configuration.md/#understand-forcebuy_enable)
|
||||||
|
|
||||||
|
### /performance
|
||||||
|
|
||||||
Return the performance of each crypto-currency the bot has sold.
|
Return the performance of each crypto-currency the bot has sold.
|
||||||
> Performance:
|
> Performance:
|
||||||
> 1. `RCN/BTC 57.77%`
|
> 1. `RCN/BTC 57.77%`
|
||||||
> 2. `PAY/BTC 56.91%`
|
> 2. `PAY/BTC 56.91%`
|
||||||
> 3. `VIB/BTC 47.07%`
|
> 3. `VIB/BTC 47.07%`
|
||||||
> 4. `SALT/BTC 30.24%`
|
> 4. `SALT/BTC 30.24%`
|
||||||
> 5. `STORJ/BTC 27.24%`
|
> 5. `STORJ/BTC 27.24%`
|
||||||
> ...
|
> ...
|
||||||
|
|
||||||
## /balance
|
### /balance
|
||||||
|
|
||||||
Return the balance of all crypto-currency your have on the exchange.
|
Return the balance of all crypto-currency your have on the exchange.
|
||||||
|
|
||||||
> **Currency:** BTC
|
> **Currency:** BTC
|
||||||
> **Available:** 3.05890234
|
> **Available:** 3.05890234
|
||||||
> **Balance:** 3.05890234
|
> **Balance:** 3.05890234
|
||||||
> **Pending:** 0.0
|
> **Pending:** 0.0
|
||||||
|
|
||||||
> **Currency:** CVC
|
> **Currency:** CVC
|
||||||
> **Available:** 86.64180098
|
> **Available:** 86.64180098
|
||||||
> **Balance:** 86.64180098
|
> **Balance:** 86.64180098
|
||||||
> **Pending:** 0.0
|
> **Pending:** 0.0
|
||||||
|
|
||||||
## /daily <n>
|
### /daily <n>
|
||||||
|
|
||||||
Per default `/daily` will return the 7 last days.
|
Per default `/daily` will return the 7 last days.
|
||||||
The example below if for `/daily 3`:
|
The example below if for `/daily 3`:
|
||||||
@@ -143,6 +196,38 @@ Day Profit BTC Profit USD
|
|||||||
2018-01-01 0.00269130 BTC 34.986 USD
|
2018-01-01 0.00269130 BTC 34.986 USD
|
||||||
```
|
```
|
||||||
|
|
||||||
## /version
|
### /whitelist
|
||||||
|
|
||||||
|
Shows the current whitelist
|
||||||
|
|
||||||
|
> Using whitelist `StaticPairList` with 22 pairs
|
||||||
|
> `IOTA/BTC, NEO/BTC, TRX/BTC, VET/BTC, ADA/BTC, ETC/BTC, NCASH/BTC, DASH/BTC, XRP/BTC, XVG/BTC, EOS/BTC, LTC/BTC, OMG/BTC, BTG/BTC, LSK/BTC, ZEC/BTC, HOT/BTC, IOTX/BTC, XMR/BTC, AST/BTC, XLM/BTC, NANO/BTC`
|
||||||
|
|
||||||
|
### /blacklist [pair]
|
||||||
|
|
||||||
|
Shows the current blacklist.
|
||||||
|
If Pair is set, then this pair will be added to the pairlist.
|
||||||
|
Also supports multiple pairs, seperated by a space.
|
||||||
|
Use `/reload_conf` to reset the blacklist.
|
||||||
|
|
||||||
|
> Using blacklist `StaticPairList` with 2 pairs
|
||||||
|
>`DODGE/BTC`, `HOT/BTC`.
|
||||||
|
|
||||||
|
### /edge
|
||||||
|
|
||||||
|
Shows pairs validated by Edge along with their corresponding winrate, expectancy and stoploss values.
|
||||||
|
|
||||||
|
> **Edge only validated following pairs:**
|
||||||
|
```
|
||||||
|
Pair Winrate Expectancy Stoploss
|
||||||
|
-------- --------- ------------ ----------
|
||||||
|
DOCK/ETH 0.522727 0.881821 -0.03
|
||||||
|
PHX/ETH 0.677419 0.560488 -0.03
|
||||||
|
HOT/ETH 0.733333 0.490492 -0.03
|
||||||
|
HC/ETH 0.588235 0.280988 -0.02
|
||||||
|
ARDR/ETH 0.366667 0.143059 -0.01
|
||||||
|
```
|
||||||
|
|
||||||
|
### /version
|
||||||
|
|
||||||
> **Version:** `0.14.3`
|
> **Version:** `0.14.3`
|
||||||
|
|||||||
126
docs/utils.md
Normal file
126
docs/utils.md
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
# Utility Subcommands
|
||||||
|
|
||||||
|
Besides the Live-Trade and Dry-Run run modes, the `backtesting`, `edge` and `hyperopt` optimization subcommands, and the `download-data` subcommand which prepares historical data, the bot contains a number of utility subcommands. They are described in this section.
|
||||||
|
|
||||||
|
## List Exchanges
|
||||||
|
|
||||||
|
Use the `list-exchanges` subcommand to see the exchanges available for the bot.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade list-exchanges [-h] [-1] [-a]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
-1, --one-column Print output in one column.
|
||||||
|
-a, --all Print all exchanges known to the ccxt library.
|
||||||
|
```
|
||||||
|
|
||||||
|
* Example: see exchanges available for the bot:
|
||||||
|
```
|
||||||
|
$ freqtrade list-exchanges
|
||||||
|
Exchanges available for Freqtrade: _1btcxe, acx, allcoin, bequant, bibox, binance, binanceje, binanceus, bitbank, bitfinex, bitfinex2, bitkk, bitlish, bitmart, bittrex, bitz, bleutrade, btcalpha, btcmarkets, btcturk, buda, cex, cobinhood, coinbaseprime, coinbasepro, coinex, cointiger, coss, crex24, digifinex, dsx, dx, ethfinex, fcoin, fcoinjp, gateio, gdax, gemini, hitbtc2, huobipro, huobiru, idex, kkex, kraken, kucoin, kucoin2, kuna, lbank, mandala, mercado, oceanex, okcoincny, okcoinusd, okex, okex3, poloniex, rightbtc, theocean, tidebit, upbit, zb
|
||||||
|
```
|
||||||
|
|
||||||
|
* Example: see all exchanges supported by the ccxt library (including 'bad' ones, i.e. those that are known to not work with Freqtrade):
|
||||||
|
```
|
||||||
|
$ freqtrade list-exchanges -a
|
||||||
|
All exchanges supported by the ccxt library: _1btcxe, acx, adara, allcoin, anxpro, bcex, bequant, bibox, bigone, binance, binanceje, binanceus, bit2c, bitbank, bitbay, bitfinex, bitfinex2, bitflyer, bitforex, bithumb, bitkk, bitlish, bitmart, bitmex, bitso, bitstamp, bitstamp1, bittrex, bitz, bl3p, bleutrade, braziliex, btcalpha, btcbox, btcchina, btcmarkets, btctradeim, btctradeua, btcturk, buda, bxinth, cex, chilebit, cobinhood, coinbase, coinbaseprime, coinbasepro, coincheck, coinegg, coinex, coinexchange, coinfalcon, coinfloor, coingi, coinmarketcap, coinmate, coinone, coinspot, cointiger, coolcoin, coss, crex24, crypton, deribit, digifinex, dsx, dx, ethfinex, exmo, exx, fcoin, fcoinjp, flowbtc, foxbit, fybse, gateio, gdax, gemini, hitbtc, hitbtc2, huobipro, huobiru, ice3x, idex, independentreserve, indodax, itbit, kkex, kraken, kucoin, kucoin2, kuna, lakebtc, latoken, lbank, liquid, livecoin, luno, lykke, mandala, mercado, mixcoins, negociecoins, nova, oceanex, okcoincny, okcoinusd, okex, okex3, paymium, poloniex, rightbtc, southxchange, stronghold, surbitcoin, theocean, therock, tidebit, tidex, upbit, vaultoro, vbtc, virwox, xbtce, yobit, zaif, zb
|
||||||
|
```
|
||||||
|
|
||||||
|
## List Timeframes
|
||||||
|
|
||||||
|
Use the `list-timeframes` subcommand to see the list of ticker intervals (timeframes) available for the exchange.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade list-timeframes [-h] [--exchange EXCHANGE] [-1]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||||
|
config is provided.
|
||||||
|
-1, --one-column Print output in one column.
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
* Example: see the timeframes for the 'binance' exchange, set in the configuration file:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ freqtrade -c config_binance.json list-timeframes
|
||||||
|
...
|
||||||
|
Timeframes available for the exchange `binance`: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M
|
||||||
|
```
|
||||||
|
|
||||||
|
* Example: enumerate exchanges available for Freqtrade and print timeframes supported by each of them:
|
||||||
|
```
|
||||||
|
$ for i in `freqtrade list-exchanges -1`; do freqtrade list-timeframes --exchange $i; done
|
||||||
|
```
|
||||||
|
|
||||||
|
## List pairs/list markets
|
||||||
|
|
||||||
|
The `list-pairs` and `list-markets` subcommands allow to see the pairs/markets available on exchange.
|
||||||
|
|
||||||
|
Pairs are markets with the '/' character between the base currency part and the quote currency part in the market symbol.
|
||||||
|
For example, in the 'ETH/BTC' pair 'ETH' is the base currency, while 'BTC' is the quote currency.
|
||||||
|
|
||||||
|
For pairs traded by Freqtrade the pair quote currency is defined by the value of the `stake_currency` configuration setting.
|
||||||
|
|
||||||
|
You can print info about any pair/market with these subcommands - and you can filter output by quote-currency using `--quote BTC`, or by base-currency using `--base ETH` options correspondingly.
|
||||||
|
|
||||||
|
These subcommands have same usage and same set of available options:
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade list-markets [-h] [--exchange EXCHANGE] [--print-list]
|
||||||
|
[--print-json] [-1] [--print-csv]
|
||||||
|
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
||||||
|
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]
|
||||||
|
[-a]
|
||||||
|
|
||||||
|
usage: freqtrade list-pairs [-h] [--exchange EXCHANGE] [--print-list]
|
||||||
|
[--print-json] [-1] [--print-csv]
|
||||||
|
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
||||||
|
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||||
|
config is provided.
|
||||||
|
--print-list Print list of pairs or market symbols. By default data
|
||||||
|
is printed in the tabular format.
|
||||||
|
--print-json Print list of pairs or market symbols in JSON format.
|
||||||
|
-1, --one-column Print output in one column.
|
||||||
|
--print-csv Print exchange pair or market data in the csv format.
|
||||||
|
--base BASE_CURRENCY [BASE_CURRENCY ...]
|
||||||
|
Specify base currency(-ies). Space-separated list.
|
||||||
|
--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]
|
||||||
|
Specify quote currency(-ies). Space-separated list.
|
||||||
|
-a, --all Print all pairs or market symbols. By default only
|
||||||
|
active ones are shown.
|
||||||
|
```
|
||||||
|
|
||||||
|
By default, only active pairs/markets are shown. Active pairs/markets are those that can currently be traded
|
||||||
|
on the exchange. The see the list of all pairs/markets (not only the active ones), use the `-a`/`-all` option.
|
||||||
|
|
||||||
|
Pairs/markets are sorted by its symbol string in the printed output.
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
* Print the list of active pairs with quote currency USD on exchange, specified in the default
|
||||||
|
configuration file (i.e. pairs on the "Bittrex" exchange) in JSON format:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ freqtrade list-pairs --quote USD --print-json
|
||||||
|
```
|
||||||
|
|
||||||
|
* Print the list of all pairs on the exchange, specified in the `config_binance.json` configuration file
|
||||||
|
(i.e. on the "Binance" exchange) with base currencies BTC or ETH and quote currencies USDT or USD, as the
|
||||||
|
human-readable list with summary:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ freqtrade -c config_binance.json list-pairs --all --base BTC ETH --quote USDT USD --print-list
|
||||||
|
```
|
||||||
|
|
||||||
|
* Print all markets on exchange "Kraken", in the tabular format:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ freqtrade list-markets --exchange kraken --all
|
||||||
|
```
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
# Webhook usage
|
# Webhook usage
|
||||||
|
|
||||||
This page explains how to configure your bot to talk to webhooks.
|
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
Enable webhooks by adding a webhook-section to your configuration file, and setting `webhook.enabled` to `true`.
|
Enable webhooks by adding a webhook-section to your configuration file, and setting `webhook.enabled` to `true`.
|
||||||
@@ -39,34 +37,32 @@ Different payloads can be configured for different events. Not all fields are ne
|
|||||||
The fields in `webhook.webhookbuy` are filled when the bot executes a buy. Parameters are filled using string.format.
|
The fields in `webhook.webhookbuy` are filled when the bot executes a buy. Parameters are filled using string.format.
|
||||||
Possible parameters are:
|
Possible parameters are:
|
||||||
|
|
||||||
* exchange
|
* `exchange`
|
||||||
* pair
|
* `pair`
|
||||||
* market_url
|
* `limit`
|
||||||
* limit
|
* `stake_amount`
|
||||||
* stake_amount
|
* `stake_currency`
|
||||||
* stake_amount_fiat
|
* `fiat_currency`
|
||||||
* stake_currency
|
* `order_type`
|
||||||
* fiat_currency
|
|
||||||
|
|
||||||
### Webhooksell
|
### Webhooksell
|
||||||
|
|
||||||
The fields in `webhook.webhooksell` are filled when the bot sells a trade. Parameters are filled using string.format.
|
The fields in `webhook.webhooksell` are filled when the bot sells a trade. Parameters are filled using string.format.
|
||||||
Possible parameters are:
|
Possible parameters are:
|
||||||
|
|
||||||
* exchange
|
* `exchange`
|
||||||
* pair
|
* `pair`
|
||||||
* gain
|
* `gain`
|
||||||
* market_url
|
* `limit`
|
||||||
* limit
|
* `amount`
|
||||||
* amount
|
* `open_rate`
|
||||||
* open_rate
|
* `current_rate`
|
||||||
* current_rate
|
* `profit_amount`
|
||||||
* profit_amount
|
* `profit_percent`
|
||||||
* profit_percent
|
* `stake_currency`
|
||||||
* profit_fiat
|
* `fiat_currency`
|
||||||
* stake_currency
|
* `sell_reason`
|
||||||
* fiat_currency
|
* `order_type`
|
||||||
* sell_reason
|
|
||||||
|
|
||||||
### Webhookstatus
|
### Webhookstatus
|
||||||
|
|
||||||
|
|||||||
60
environment.yml
Normal file
60
environment.yml
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
name: freqtrade
|
||||||
|
channels:
|
||||||
|
- defaults
|
||||||
|
- conda-forge
|
||||||
|
dependencies:
|
||||||
|
# Required for app
|
||||||
|
- python>=3.6
|
||||||
|
- pip
|
||||||
|
- wheel
|
||||||
|
- numpy
|
||||||
|
- pandas
|
||||||
|
- SQLAlchemy
|
||||||
|
- arrow
|
||||||
|
- requests
|
||||||
|
- urllib3
|
||||||
|
- wrapt
|
||||||
|
- jsonschema
|
||||||
|
- tabulate
|
||||||
|
- python-rapidjson
|
||||||
|
- flask
|
||||||
|
- python-dotenv
|
||||||
|
- cachetools
|
||||||
|
- python-telegram-bot
|
||||||
|
# Optional for plotting
|
||||||
|
- plotly
|
||||||
|
# Optional for hyperopt
|
||||||
|
- scipy
|
||||||
|
- scikit-optimize
|
||||||
|
- scikit-learn
|
||||||
|
- filelock
|
||||||
|
- joblib
|
||||||
|
# Optional for development
|
||||||
|
- flake8
|
||||||
|
- pytest
|
||||||
|
- pytest-mock
|
||||||
|
- pytest-asyncio
|
||||||
|
- pytest-cov
|
||||||
|
- coveralls
|
||||||
|
- mypy
|
||||||
|
# Useful for jupyter
|
||||||
|
- jupyter
|
||||||
|
- ipykernel
|
||||||
|
- isort
|
||||||
|
- yapf
|
||||||
|
- pip:
|
||||||
|
# Required for app
|
||||||
|
- cython
|
||||||
|
- coinmarketcap
|
||||||
|
- ccxt
|
||||||
|
- TA-Lib
|
||||||
|
- py_find_1st
|
||||||
|
- sdnotify
|
||||||
|
# Optional for develpment
|
||||||
|
- flake8-tidy-imports
|
||||||
|
- flake8-type-annotations
|
||||||
|
- pytest-random-order
|
||||||
|
- -e .
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -6,7 +6,7 @@ After=network.target
|
|||||||
# Set WorkingDirectory and ExecStart to your file paths accordingly
|
# Set WorkingDirectory and ExecStart to your file paths accordingly
|
||||||
# NOTE: %h will be resolved to /home/<username>
|
# NOTE: %h will be resolved to /home/<username>
|
||||||
WorkingDirectory=%h/freqtrade
|
WorkingDirectory=%h/freqtrade
|
||||||
ExecStart=/usr/bin/freqtrade --dynamic-whitelist 40
|
ExecStart=/usr/bin/freqtrade
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
|
|||||||
30
freqtrade.service.watchdog
Normal file
30
freqtrade.service.watchdog
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Freqtrade Daemon
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
# Set WorkingDirectory and ExecStart to your file paths accordingly
|
||||||
|
# NOTE: %h will be resolved to /home/<username>
|
||||||
|
WorkingDirectory=%h/freqtrade
|
||||||
|
ExecStart=/usr/bin/freqtrade --sd-notify
|
||||||
|
|
||||||
|
Restart=always
|
||||||
|
#Restart=on-failure
|
||||||
|
|
||||||
|
# Note that we use Type=notify here
|
||||||
|
Type=notify
|
||||||
|
|
||||||
|
# Currently required if Type=notify
|
||||||
|
NotifyAccess=all
|
||||||
|
|
||||||
|
StartLimitInterval=1min
|
||||||
|
StartLimitBurst=5
|
||||||
|
|
||||||
|
TimeoutStartSec=1min
|
||||||
|
|
||||||
|
# Use here (process_throttle_secs * 2) or longer time interval
|
||||||
|
WatchdogSec=20
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
|
|
||||||
@@ -1,23 +1,42 @@
|
|||||||
""" FreqTrade bot """
|
""" FreqTrade bot """
|
||||||
__version__ = '0.18.1'
|
__version__ = '2019.10'
|
||||||
|
|
||||||
|
if __version__ == 'develop':
|
||||||
|
|
||||||
|
try:
|
||||||
|
import subprocess
|
||||||
|
__version__ = 'develop-' + subprocess.check_output(
|
||||||
|
['git', 'log', '--format="%h"', '-n 1'],
|
||||||
|
stderr=subprocess.DEVNULL).decode("utf-8").rstrip().strip('"')
|
||||||
|
except Exception:
|
||||||
|
# git not available, ignore
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class DependencyException(BaseException):
|
class DependencyException(Exception):
|
||||||
"""
|
"""
|
||||||
Indicates that a assumed dependency is not met.
|
Indicates that an assumed dependency is not met.
|
||||||
This could happen when there is currently not enough money on the account.
|
This could happen when there is currently not enough money on the account.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class OperationalException(BaseException):
|
class OperationalException(Exception):
|
||||||
"""
|
"""
|
||||||
Requires manual intervention.
|
Requires manual intervention and will usually stop the bot.
|
||||||
This happens when an exchange returns an unexpected error during runtime
|
This happens when an exchange returns an unexpected error during runtime
|
||||||
or given configuration is invalid.
|
or given configuration is invalid.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class TemporaryError(BaseException):
|
class InvalidOrderException(Exception):
|
||||||
|
"""
|
||||||
|
This is returned when the order is not valid. Example:
|
||||||
|
If stoploss on exchange order is hit, then trying to cancel the order
|
||||||
|
should return this exception.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class TemporaryError(Exception):
|
||||||
"""
|
"""
|
||||||
Temporary network or exchange related error.
|
Temporary network or exchange related error.
|
||||||
This could happen when an exchange is congested, unavailable, or the user
|
This could happen when an exchange is congested, unavailable, or the user
|
||||||
|
|||||||
@@ -6,10 +6,7 @@ To launch Freqtrade as a module
|
|||||||
> python -m freqtrade (with Python >= 3.6)
|
> python -m freqtrade (with Python >= 3.6)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import sys
|
|
||||||
|
|
||||||
from freqtrade import main
|
from freqtrade import main
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main.set_loggers()
|
main.main()
|
||||||
main.main(sys.argv[1:])
|
|
||||||
|
|||||||
@@ -1,423 +0,0 @@
|
|||||||
"""
|
|
||||||
This module contains the argument manager class
|
|
||||||
"""
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
from typing import List, NamedTuple, Optional
|
|
||||||
|
|
||||||
import arrow
|
|
||||||
|
|
||||||
from freqtrade import __version__, constants
|
|
||||||
|
|
||||||
|
|
||||||
class TimeRange(NamedTuple):
|
|
||||||
"""
|
|
||||||
NamedTuple Defining timerange inputs.
|
|
||||||
[start/stop]type defines if [start/stop]ts shall be used.
|
|
||||||
if *type is none, don't use corresponding startvalue.
|
|
||||||
"""
|
|
||||||
starttype: Optional[str] = None
|
|
||||||
stoptype: Optional[str] = None
|
|
||||||
startts: int = 0
|
|
||||||
stopts: int = 0
|
|
||||||
|
|
||||||
|
|
||||||
class Arguments(object):
|
|
||||||
"""
|
|
||||||
Arguments Class. Manage the arguments received by the cli
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, args: List[str], description: str) -> None:
|
|
||||||
self.args = args
|
|
||||||
self.parsed_arg: Optional[argparse.Namespace] = None
|
|
||||||
self.parser = argparse.ArgumentParser(description=description)
|
|
||||||
|
|
||||||
def _load_args(self) -> None:
|
|
||||||
self.common_args_parser()
|
|
||||||
self._build_subcommands()
|
|
||||||
|
|
||||||
def get_parsed_arg(self) -> argparse.Namespace:
|
|
||||||
"""
|
|
||||||
Return the list of arguments
|
|
||||||
:return: List[str] List of arguments
|
|
||||||
"""
|
|
||||||
if self.parsed_arg is None:
|
|
||||||
self._load_args()
|
|
||||||
self.parsed_arg = self.parse_args()
|
|
||||||
|
|
||||||
return self.parsed_arg
|
|
||||||
|
|
||||||
def parse_args(self) -> argparse.Namespace:
|
|
||||||
"""
|
|
||||||
Parses given arguments and returns an argparse Namespace instance.
|
|
||||||
"""
|
|
||||||
parsed_arg = self.parser.parse_args(self.args)
|
|
||||||
|
|
||||||
return parsed_arg
|
|
||||||
|
|
||||||
def common_args_parser(self) -> None:
|
|
||||||
"""
|
|
||||||
Parses given common arguments and returns them as a parsed object.
|
|
||||||
"""
|
|
||||||
self.parser.add_argument(
|
|
||||||
'-v', '--verbose',
|
|
||||||
help='verbose mode (-vv for more, -vvv to get all messages)',
|
|
||||||
action='count',
|
|
||||||
dest='loglevel',
|
|
||||||
default=0,
|
|
||||||
)
|
|
||||||
self.parser.add_argument(
|
|
||||||
'--version',
|
|
||||||
action='version',
|
|
||||||
version=f'%(prog)s {__version__}'
|
|
||||||
)
|
|
||||||
self.parser.add_argument(
|
|
||||||
'-c', '--config',
|
|
||||||
help='specify configuration file (default: %(default)s)',
|
|
||||||
dest='config',
|
|
||||||
default='config.json',
|
|
||||||
type=str,
|
|
||||||
metavar='PATH',
|
|
||||||
)
|
|
||||||
self.parser.add_argument(
|
|
||||||
'-d', '--datadir',
|
|
||||||
help='path to backtest data',
|
|
||||||
dest='datadir',
|
|
||||||
default=None,
|
|
||||||
type=str,
|
|
||||||
metavar='PATH',
|
|
||||||
)
|
|
||||||
self.parser.add_argument(
|
|
||||||
'-s', '--strategy',
|
|
||||||
help='specify strategy class name (default: %(default)s)',
|
|
||||||
dest='strategy',
|
|
||||||
default='DefaultStrategy',
|
|
||||||
type=str,
|
|
||||||
metavar='NAME',
|
|
||||||
)
|
|
||||||
self.parser.add_argument(
|
|
||||||
'--strategy-path',
|
|
||||||
help='specify additional strategy lookup path',
|
|
||||||
dest='strategy_path',
|
|
||||||
type=str,
|
|
||||||
metavar='PATH',
|
|
||||||
)
|
|
||||||
self.parser.add_argument(
|
|
||||||
'--customhyperopt',
|
|
||||||
help='specify hyperopt class name (default: %(default)s)',
|
|
||||||
dest='hyperopt',
|
|
||||||
default=constants.DEFAULT_HYPEROPT,
|
|
||||||
type=str,
|
|
||||||
metavar='NAME',
|
|
||||||
)
|
|
||||||
self.parser.add_argument(
|
|
||||||
'--dynamic-whitelist',
|
|
||||||
help='dynamically generate and update whitelist'
|
|
||||||
' based on 24h BaseVolume (default: %(const)s)'
|
|
||||||
' DEPRECATED.',
|
|
||||||
dest='dynamic_whitelist',
|
|
||||||
const=constants.DYNAMIC_WHITELIST,
|
|
||||||
type=int,
|
|
||||||
metavar='INT',
|
|
||||||
nargs='?',
|
|
||||||
)
|
|
||||||
self.parser.add_argument(
|
|
||||||
'--db-url',
|
|
||||||
help='Override trades database URL, this is useful if dry_run is enabled'
|
|
||||||
' or in custom deployments (default: %(default)s)',
|
|
||||||
dest='db_url',
|
|
||||||
type=str,
|
|
||||||
metavar='PATH',
|
|
||||||
)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def backtesting_options(parser: argparse.ArgumentParser) -> None:
|
|
||||||
"""
|
|
||||||
Parses given arguments for Backtesting scripts.
|
|
||||||
"""
|
|
||||||
parser.add_argument(
|
|
||||||
'--eps', '--enable-position-stacking',
|
|
||||||
help='Allow buying the same pair multiple times (position stacking)',
|
|
||||||
action='store_true',
|
|
||||||
dest='position_stacking',
|
|
||||||
default=False
|
|
||||||
)
|
|
||||||
|
|
||||||
parser.add_argument(
|
|
||||||
'--dmmp', '--disable-max-market-positions',
|
|
||||||
help='Disable applying `max_open_trades` during backtest '
|
|
||||||
'(same as setting `max_open_trades` to a very high number)',
|
|
||||||
action='store_false',
|
|
||||||
dest='use_max_market_positions',
|
|
||||||
default=True
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
'-l', '--live',
|
|
||||||
help='using live data',
|
|
||||||
action='store_true',
|
|
||||||
dest='live',
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
'-r', '--refresh-pairs-cached',
|
|
||||||
help='refresh the pairs files in tests/testdata with the latest data from the '
|
|
||||||
'exchange. Use it if you want to run your backtesting with up-to-date data.',
|
|
||||||
action='store_true',
|
|
||||||
dest='refresh_pairs',
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
'--strategy-list',
|
|
||||||
help='Provide a commaseparated list of strategies to backtest '
|
|
||||||
'Please note that ticker-interval needs to be set either in config '
|
|
||||||
'or via command line. When using this together with --export trades, '
|
|
||||||
'the strategy-name is injected into the filename '
|
|
||||||
'(so backtest-data.json becomes backtest-data-DefaultStrategy.json',
|
|
||||||
nargs='+',
|
|
||||||
dest='strategy_list',
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
'--export',
|
|
||||||
help='export backtest results, argument are: trades\
|
|
||||||
Example --export=trades',
|
|
||||||
type=str,
|
|
||||||
default=None,
|
|
||||||
dest='export',
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
'--export-filename',
|
|
||||||
help='Save backtest results to this filename \
|
|
||||||
requires --export to be set as well\
|
|
||||||
Example --export-filename=user_data/backtest_data/backtest_today.json\
|
|
||||||
(default: %(default)s)',
|
|
||||||
type=str,
|
|
||||||
default=os.path.join('user_data', 'backtest_data', 'backtest-result.json'),
|
|
||||||
dest='exportfilename',
|
|
||||||
metavar='PATH',
|
|
||||||
)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def edge_options(parser: argparse.ArgumentParser) -> None:
|
|
||||||
"""
|
|
||||||
Parses given arguments for Backtesting scripts.
|
|
||||||
"""
|
|
||||||
parser.add_argument(
|
|
||||||
'-r', '--refresh-pairs-cached',
|
|
||||||
help='refresh the pairs files in tests/testdata with the latest data from the '
|
|
||||||
'exchange. Use it if you want to run your edge with up-to-date data.',
|
|
||||||
action='store_true',
|
|
||||||
dest='refresh_pairs',
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
'--stoplosses',
|
|
||||||
help='defines a range of stoploss against which edge will assess the strategy '
|
|
||||||
'the format is "min,max,step" (without any space).'
|
|
||||||
'example: --stoplosses=-0.01,-0.1,-0.001',
|
|
||||||
type=str,
|
|
||||||
dest='stoploss_range',
|
|
||||||
)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def optimizer_shared_options(parser: argparse.ArgumentParser) -> None:
|
|
||||||
"""
|
|
||||||
Parses given common arguments for Backtesting and Hyperopt scripts.
|
|
||||||
:param parser:
|
|
||||||
:return:
|
|
||||||
"""
|
|
||||||
parser.add_argument(
|
|
||||||
'-i', '--ticker-interval',
|
|
||||||
help='specify ticker interval (1m, 5m, 30m, 1h, 1d)',
|
|
||||||
dest='ticker_interval',
|
|
||||||
type=str,
|
|
||||||
)
|
|
||||||
|
|
||||||
parser.add_argument(
|
|
||||||
'--timerange',
|
|
||||||
help='specify what timerange of data to use.',
|
|
||||||
default=None,
|
|
||||||
type=str,
|
|
||||||
dest='timerange',
|
|
||||||
)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def hyperopt_options(parser: argparse.ArgumentParser) -> None:
|
|
||||||
"""
|
|
||||||
Parses given arguments for Hyperopt scripts.
|
|
||||||
"""
|
|
||||||
parser.add_argument(
|
|
||||||
'--eps', '--enable-position-stacking',
|
|
||||||
help='Allow buying the same pair multiple times (position stacking)',
|
|
||||||
action='store_true',
|
|
||||||
dest='position_stacking',
|
|
||||||
default=False
|
|
||||||
)
|
|
||||||
|
|
||||||
parser.add_argument(
|
|
||||||
'--dmmp', '--disable-max-market-positions',
|
|
||||||
help='Disable applying `max_open_trades` during backtest '
|
|
||||||
'(same as setting `max_open_trades` to a very high number)',
|
|
||||||
action='store_false',
|
|
||||||
dest='use_max_market_positions',
|
|
||||||
default=True
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
'-e', '--epochs',
|
|
||||||
help='specify number of epochs (default: %(default)d)',
|
|
||||||
dest='epochs',
|
|
||||||
default=constants.HYPEROPT_EPOCH,
|
|
||||||
type=int,
|
|
||||||
metavar='INT',
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
'-s', '--spaces',
|
|
||||||
help='Specify which parameters to hyperopt. Space separate list. \
|
|
||||||
Default: %(default)s',
|
|
||||||
choices=['all', 'buy', 'sell', 'roi', 'stoploss'],
|
|
||||||
default='all',
|
|
||||||
nargs='+',
|
|
||||||
dest='spaces',
|
|
||||||
)
|
|
||||||
|
|
||||||
def _build_subcommands(self) -> None:
|
|
||||||
"""
|
|
||||||
Builds and attaches all subcommands
|
|
||||||
:return: None
|
|
||||||
"""
|
|
||||||
from freqtrade.optimize import backtesting, hyperopt, edge_cli
|
|
||||||
|
|
||||||
subparsers = self.parser.add_subparsers(dest='subparser')
|
|
||||||
|
|
||||||
# Add backtesting subcommand
|
|
||||||
backtesting_cmd = subparsers.add_parser('backtesting', help='backtesting module')
|
|
||||||
backtesting_cmd.set_defaults(func=backtesting.start)
|
|
||||||
self.optimizer_shared_options(backtesting_cmd)
|
|
||||||
self.backtesting_options(backtesting_cmd)
|
|
||||||
|
|
||||||
# Add edge subcommand
|
|
||||||
edge_cmd = subparsers.add_parser('edge', help='edge module')
|
|
||||||
edge_cmd.set_defaults(func=edge_cli.start)
|
|
||||||
self.optimizer_shared_options(edge_cmd)
|
|
||||||
self.edge_options(edge_cmd)
|
|
||||||
|
|
||||||
# Add hyperopt subcommand
|
|
||||||
hyperopt_cmd = subparsers.add_parser('hyperopt', help='hyperopt module')
|
|
||||||
hyperopt_cmd.set_defaults(func=hyperopt.start)
|
|
||||||
self.optimizer_shared_options(hyperopt_cmd)
|
|
||||||
self.hyperopt_options(hyperopt_cmd)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def parse_timerange(text: Optional[str]) -> TimeRange:
|
|
||||||
"""
|
|
||||||
Parse the value of the argument --timerange to determine what is the range desired
|
|
||||||
:param text: value from --timerange
|
|
||||||
:return: Start and End range period
|
|
||||||
"""
|
|
||||||
if text is None:
|
|
||||||
return TimeRange(None, None, 0, 0)
|
|
||||||
syntax = [(r'^-(\d{8})$', (None, 'date')),
|
|
||||||
(r'^(\d{8})-$', ('date', None)),
|
|
||||||
(r'^(\d{8})-(\d{8})$', ('date', 'date')),
|
|
||||||
(r'^-(\d{10})$', (None, 'date')),
|
|
||||||
(r'^(\d{10})-$', ('date', None)),
|
|
||||||
(r'^(\d{10})-(\d{10})$', ('date', 'date')),
|
|
||||||
(r'^(-\d+)$', (None, 'line')),
|
|
||||||
(r'^(\d+)-$', ('line', None)),
|
|
||||||
(r'^(\d+)-(\d+)$', ('index', 'index'))]
|
|
||||||
for rex, stype in syntax:
|
|
||||||
# Apply the regular expression to text
|
|
||||||
match = re.match(rex, text)
|
|
||||||
if match: # Regex has matched
|
|
||||||
rvals = match.groups()
|
|
||||||
index = 0
|
|
||||||
start: int = 0
|
|
||||||
stop: int = 0
|
|
||||||
if stype[0]:
|
|
||||||
starts = rvals[index]
|
|
||||||
if stype[0] == 'date' and len(starts) == 8:
|
|
||||||
start = arrow.get(starts, 'YYYYMMDD').timestamp
|
|
||||||
else:
|
|
||||||
start = int(starts)
|
|
||||||
index += 1
|
|
||||||
if stype[1]:
|
|
||||||
stops = rvals[index]
|
|
||||||
if stype[1] == 'date' and len(stops) == 8:
|
|
||||||
stop = arrow.get(stops, 'YYYYMMDD').timestamp
|
|
||||||
else:
|
|
||||||
stop = int(stops)
|
|
||||||
return TimeRange(stype[0], stype[1], start, stop)
|
|
||||||
raise Exception('Incorrect syntax for timerange "%s"' % text)
|
|
||||||
|
|
||||||
def scripts_options(self) -> None:
|
|
||||||
"""
|
|
||||||
Parses given arguments for scripts.
|
|
||||||
"""
|
|
||||||
self.parser.add_argument(
|
|
||||||
'-p', '--pairs',
|
|
||||||
help='Show profits for only this pairs. Pairs are comma-separated.',
|
|
||||||
dest='pairs',
|
|
||||||
default=None
|
|
||||||
)
|
|
||||||
|
|
||||||
def testdata_dl_options(self) -> None:
|
|
||||||
"""
|
|
||||||
Parses given arguments for testdata download
|
|
||||||
"""
|
|
||||||
self.parser.add_argument(
|
|
||||||
'--pairs-file',
|
|
||||||
help='File containing a list of pairs to download',
|
|
||||||
dest='pairs_file',
|
|
||||||
default=None,
|
|
||||||
metavar='PATH',
|
|
||||||
)
|
|
||||||
|
|
||||||
self.parser.add_argument(
|
|
||||||
'--export',
|
|
||||||
help='Export files to given dir',
|
|
||||||
dest='export',
|
|
||||||
default=None,
|
|
||||||
metavar='PATH',
|
|
||||||
)
|
|
||||||
|
|
||||||
self.parser.add_argument(
|
|
||||||
'-c', '--config',
|
|
||||||
help='specify configuration file, used for additional exchange parameters',
|
|
||||||
dest='config',
|
|
||||||
default=None,
|
|
||||||
type=str,
|
|
||||||
metavar='PATH',
|
|
||||||
)
|
|
||||||
|
|
||||||
self.parser.add_argument(
|
|
||||||
'--days',
|
|
||||||
help='Download data for number of days',
|
|
||||||
dest='days',
|
|
||||||
type=int,
|
|
||||||
metavar='INT',
|
|
||||||
default=None
|
|
||||||
)
|
|
||||||
|
|
||||||
self.parser.add_argument(
|
|
||||||
'--exchange',
|
|
||||||
help='Exchange name (default: %(default)s). Only valid if no config is provided',
|
|
||||||
dest='exchange',
|
|
||||||
type=str,
|
|
||||||
default='bittrex'
|
|
||||||
)
|
|
||||||
|
|
||||||
self.parser.add_argument(
|
|
||||||
'-t', '--timeframes',
|
|
||||||
help='Specify which tickers to download. Space separated list. \
|
|
||||||
Default: %(default)s',
|
|
||||||
choices=['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h',
|
|
||||||
'6h', '8h', '12h', '1d', '3d', '1w'],
|
|
||||||
default=['1m', '5m'],
|
|
||||||
nargs='+',
|
|
||||||
dest='timeframes',
|
|
||||||
)
|
|
||||||
|
|
||||||
self.parser.add_argument(
|
|
||||||
'--erase',
|
|
||||||
help='Clean all existing data for the selected exchange/pairs/timeframes',
|
|
||||||
dest='erase',
|
|
||||||
action='store_true'
|
|
||||||
)
|
|
||||||
@@ -1,334 +0,0 @@
|
|||||||
"""
|
|
||||||
This module contains the configuration class
|
|
||||||
"""
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import os
|
|
||||||
from argparse import Namespace
|
|
||||||
from typing import Any, Dict, Optional
|
|
||||||
|
|
||||||
import ccxt
|
|
||||||
from jsonschema import Draft4Validator, validate
|
|
||||||
from jsonschema.exceptions import ValidationError, best_match
|
|
||||||
|
|
||||||
from freqtrade import OperationalException, constants
|
|
||||||
from freqtrade.state import RunMode
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def set_loggers(log_level: int = 0) -> None:
|
|
||||||
"""
|
|
||||||
Set the logger level for Third party libs
|
|
||||||
:return: None
|
|
||||||
"""
|
|
||||||
|
|
||||||
logging.getLogger('requests').setLevel(logging.INFO if log_level <= 1 else logging.DEBUG)
|
|
||||||
logging.getLogger("urllib3").setLevel(logging.INFO if log_level <= 1 else logging.DEBUG)
|
|
||||||
logging.getLogger('ccxt.base.exchange').setLevel(
|
|
||||||
logging.INFO if log_level <= 2 else logging.DEBUG)
|
|
||||||
logging.getLogger('telegram').setLevel(logging.INFO)
|
|
||||||
|
|
||||||
|
|
||||||
class Configuration(object):
|
|
||||||
"""
|
|
||||||
Class to read and init the bot configuration
|
|
||||||
Reuse this class for the bot, backtesting, hyperopt and every script that required configuration
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, args: Namespace, runmode: RunMode = None) -> None:
|
|
||||||
self.args = args
|
|
||||||
self.config: Optional[Dict[str, Any]] = None
|
|
||||||
self.runmode = runmode
|
|
||||||
|
|
||||||
def load_config(self) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Extract information for sys.argv and load the bot configuration
|
|
||||||
:return: Configuration dictionary
|
|
||||||
"""
|
|
||||||
logger.info('Using config: %s ...', self.args.config)
|
|
||||||
config = self._load_config_file(self.args.config)
|
|
||||||
|
|
||||||
# Set strategy if not specified in config and or if it's non default
|
|
||||||
if self.args.strategy != constants.DEFAULT_STRATEGY or not config.get('strategy'):
|
|
||||||
config.update({'strategy': self.args.strategy})
|
|
||||||
|
|
||||||
if self.args.strategy_path:
|
|
||||||
config.update({'strategy_path': self.args.strategy_path})
|
|
||||||
|
|
||||||
# Add the hyperopt file to use
|
|
||||||
config.update({'hyperopt': self.args.hyperopt})
|
|
||||||
|
|
||||||
# Load Common configuration
|
|
||||||
config = self._load_common_config(config)
|
|
||||||
|
|
||||||
# Load Backtesting
|
|
||||||
config = self._load_backtesting_config(config)
|
|
||||||
|
|
||||||
# Load Edge
|
|
||||||
config = self._load_edge_config(config)
|
|
||||||
|
|
||||||
# Load Hyperopt
|
|
||||||
config = self._load_hyperopt_config(config)
|
|
||||||
|
|
||||||
# Set runmode
|
|
||||||
if not self.runmode:
|
|
||||||
# Handle real mode, infer dry/live from config
|
|
||||||
self.runmode = RunMode.DRY_RUN if config.get('dry_run', True) else RunMode.LIVE
|
|
||||||
|
|
||||||
config.update({'runmode': self.runmode})
|
|
||||||
|
|
||||||
return config
|
|
||||||
|
|
||||||
def _load_config_file(self, path: str) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Loads a config file from the given path
|
|
||||||
:param path: path as str
|
|
||||||
:return: configuration as dictionary
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
with open(path) as file:
|
|
||||||
conf = json.load(file)
|
|
||||||
except FileNotFoundError:
|
|
||||||
raise OperationalException(
|
|
||||||
f'Config file "{path}" not found!'
|
|
||||||
' Please create a config file or check whether it exists.')
|
|
||||||
|
|
||||||
if 'internals' not in conf:
|
|
||||||
conf['internals'] = {}
|
|
||||||
logger.info('Validating configuration ...')
|
|
||||||
|
|
||||||
return self._validate_config(conf)
|
|
||||||
|
|
||||||
def _load_common_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Extract information for sys.argv and load common configuration
|
|
||||||
:return: configuration as dictionary
|
|
||||||
"""
|
|
||||||
|
|
||||||
# Log level
|
|
||||||
if 'loglevel' in self.args and self.args.loglevel:
|
|
||||||
config.update({'verbosity': self.args.loglevel})
|
|
||||||
else:
|
|
||||||
config.update({'verbosity': 0})
|
|
||||||
logging.basicConfig(
|
|
||||||
level=logging.INFO if config['verbosity'] < 1 else logging.DEBUG,
|
|
||||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
|
||||||
)
|
|
||||||
set_loggers(config['verbosity'])
|
|
||||||
logger.info('Verbosity set to %s', config['verbosity'])
|
|
||||||
|
|
||||||
# Add dynamic_whitelist if found
|
|
||||||
if 'dynamic_whitelist' in self.args and self.args.dynamic_whitelist:
|
|
||||||
# Update to volumePairList (the previous default)
|
|
||||||
config['pairlist'] = {'method': 'VolumePairList',
|
|
||||||
'config': {'number_assets': self.args.dynamic_whitelist}
|
|
||||||
}
|
|
||||||
logger.warning(
|
|
||||||
'Parameter --dynamic-whitelist has been deprecated, '
|
|
||||||
'and will be completely replaced by the whitelist dict in the future. '
|
|
||||||
'For now: using dynamically generated whitelist based on VolumePairList. '
|
|
||||||
'(not applicable with Backtesting and Hyperopt)'
|
|
||||||
)
|
|
||||||
|
|
||||||
if self.args.db_url and self.args.db_url != constants.DEFAULT_DB_PROD_URL:
|
|
||||||
config.update({'db_url': self.args.db_url})
|
|
||||||
logger.info('Parameter --db-url detected ...')
|
|
||||||
|
|
||||||
if config.get('dry_run', False):
|
|
||||||
logger.info('Dry run is enabled')
|
|
||||||
if config.get('db_url') in [None, constants.DEFAULT_DB_PROD_URL]:
|
|
||||||
# Default to in-memory db for dry_run if not specified
|
|
||||||
config['db_url'] = constants.DEFAULT_DB_DRYRUN_URL
|
|
||||||
else:
|
|
||||||
if not config.get('db_url', None):
|
|
||||||
config['db_url'] = constants.DEFAULT_DB_PROD_URL
|
|
||||||
logger.info('Dry run is disabled')
|
|
||||||
|
|
||||||
if config.get('forcebuy_enable', False):
|
|
||||||
logger.warning('`forcebuy` RPC message enabled.')
|
|
||||||
|
|
||||||
# Setting max_open_trades to infinite if -1
|
|
||||||
if config.get('max_open_trades') == -1:
|
|
||||||
config['max_open_trades'] = float('inf')
|
|
||||||
|
|
||||||
logger.info(f'Using DB: "{config["db_url"]}"')
|
|
||||||
|
|
||||||
# Check if the exchange set by the user is supported
|
|
||||||
self.check_exchange(config)
|
|
||||||
|
|
||||||
return config
|
|
||||||
|
|
||||||
def _create_datadir(self, config: Dict[str, Any], datadir: Optional[str] = None) -> str:
|
|
||||||
if not datadir:
|
|
||||||
# set datadir
|
|
||||||
exchange_name = config.get('exchange', {}).get('name').lower()
|
|
||||||
datadir = os.path.join('user_data', 'data', exchange_name)
|
|
||||||
|
|
||||||
if not os.path.isdir(datadir):
|
|
||||||
os.makedirs(datadir)
|
|
||||||
logger.info(f'Created data directory: {datadir}')
|
|
||||||
return datadir
|
|
||||||
|
|
||||||
def _load_backtesting_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Extract information for sys.argv and load Backtesting configuration
|
|
||||||
:return: configuration as dictionary
|
|
||||||
"""
|
|
||||||
|
|
||||||
# If -i/--ticker-interval is used we override the configuration parameter
|
|
||||||
# (that will override the strategy configuration)
|
|
||||||
if 'ticker_interval' in self.args and self.args.ticker_interval:
|
|
||||||
config.update({'ticker_interval': self.args.ticker_interval})
|
|
||||||
logger.info('Parameter -i/--ticker-interval detected ...')
|
|
||||||
logger.info('Using ticker_interval: %s ...', config.get('ticker_interval'))
|
|
||||||
|
|
||||||
# If -l/--live is used we add it to the configuration
|
|
||||||
if 'live' in self.args and self.args.live:
|
|
||||||
config.update({'live': True})
|
|
||||||
logger.info('Parameter -l/--live detected ...')
|
|
||||||
|
|
||||||
# If --enable-position-stacking is used we add it to the configuration
|
|
||||||
if 'position_stacking' in self.args and self.args.position_stacking:
|
|
||||||
config.update({'position_stacking': True})
|
|
||||||
logger.info('Parameter --enable-position-stacking detected ...')
|
|
||||||
|
|
||||||
# If --disable-max-market-positions is used we add it to the configuration
|
|
||||||
if 'use_max_market_positions' in self.args and not self.args.use_max_market_positions:
|
|
||||||
config.update({'use_max_market_positions': False})
|
|
||||||
logger.info('Parameter --disable-max-market-positions detected ...')
|
|
||||||
logger.info('max_open_trades set to unlimited ...')
|
|
||||||
else:
|
|
||||||
logger.info('Using max_open_trades: %s ...', config.get('max_open_trades'))
|
|
||||||
|
|
||||||
# If --timerange is used we add it to the configuration
|
|
||||||
if 'timerange' in self.args and self.args.timerange:
|
|
||||||
config.update({'timerange': self.args.timerange})
|
|
||||||
logger.info('Parameter --timerange detected: %s ...', self.args.timerange)
|
|
||||||
|
|
||||||
# If --datadir is used we add it to the configuration
|
|
||||||
if 'datadir' in self.args and self.args.datadir:
|
|
||||||
config.update({'datadir': self._create_datadir(config, self.args.datadir)})
|
|
||||||
else:
|
|
||||||
config.update({'datadir': self._create_datadir(config, None)})
|
|
||||||
logger.info('Using data folder: %s ...', config.get('datadir'))
|
|
||||||
|
|
||||||
# If -r/--refresh-pairs-cached is used we add it to the configuration
|
|
||||||
if 'refresh_pairs' in self.args and self.args.refresh_pairs:
|
|
||||||
config.update({'refresh_pairs': True})
|
|
||||||
logger.info('Parameter -r/--refresh-pairs-cached detected ...')
|
|
||||||
|
|
||||||
if 'strategy_list' in self.args and self.args.strategy_list:
|
|
||||||
config.update({'strategy_list': self.args.strategy_list})
|
|
||||||
logger.info('Using strategy list of %s Strategies', len(self.args.strategy_list))
|
|
||||||
|
|
||||||
if 'ticker_interval' in self.args and self.args.ticker_interval:
|
|
||||||
config.update({'ticker_interval': self.args.ticker_interval})
|
|
||||||
logger.info('Overriding ticker interval with Command line argument')
|
|
||||||
|
|
||||||
# If --export is used we add it to the configuration
|
|
||||||
if 'export' in self.args and self.args.export:
|
|
||||||
config.update({'export': self.args.export})
|
|
||||||
logger.info('Parameter --export detected: %s ...', self.args.export)
|
|
||||||
|
|
||||||
# If --export-filename is used we add it to the configuration
|
|
||||||
if 'export' in config and 'exportfilename' in self.args and self.args.exportfilename:
|
|
||||||
config.update({'exportfilename': self.args.exportfilename})
|
|
||||||
logger.info('Storing backtest results to %s ...', self.args.exportfilename)
|
|
||||||
|
|
||||||
return config
|
|
||||||
|
|
||||||
def _load_edge_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Extract information for sys.argv and load Edge configuration
|
|
||||||
:return: configuration as dictionary
|
|
||||||
"""
|
|
||||||
|
|
||||||
# If --timerange is used we add it to the configuration
|
|
||||||
if 'timerange' in self.args and self.args.timerange:
|
|
||||||
config.update({'timerange': self.args.timerange})
|
|
||||||
logger.info('Parameter --timerange detected: %s ...', self.args.timerange)
|
|
||||||
|
|
||||||
# If --timerange is used we add it to the configuration
|
|
||||||
if 'stoploss_range' in self.args and self.args.stoploss_range:
|
|
||||||
txt_range = eval(self.args.stoploss_range)
|
|
||||||
config['edge'].update({'stoploss_range_min': txt_range[0]})
|
|
||||||
config['edge'].update({'stoploss_range_max': txt_range[1]})
|
|
||||||
config['edge'].update({'stoploss_range_step': txt_range[2]})
|
|
||||||
logger.info('Parameter --stoplosses detected: %s ...', self.args.stoploss_range)
|
|
||||||
|
|
||||||
# If -r/--refresh-pairs-cached is used we add it to the configuration
|
|
||||||
if 'refresh_pairs' in self.args and self.args.refresh_pairs:
|
|
||||||
config.update({'refresh_pairs': True})
|
|
||||||
logger.info('Parameter -r/--refresh-pairs-cached detected ...')
|
|
||||||
|
|
||||||
return config
|
|
||||||
|
|
||||||
def _load_hyperopt_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Extract information for sys.argv and load Hyperopt configuration
|
|
||||||
:return: configuration as dictionary
|
|
||||||
"""
|
|
||||||
# If --epochs is used we add it to the configuration
|
|
||||||
if 'epochs' in self.args and self.args.epochs:
|
|
||||||
config.update({'epochs': self.args.epochs})
|
|
||||||
logger.info('Parameter --epochs detected ...')
|
|
||||||
logger.info('Will run Hyperopt with for %s epochs ...', config.get('epochs'))
|
|
||||||
|
|
||||||
# If --spaces is used we add it to the configuration
|
|
||||||
if 'spaces' in self.args and self.args.spaces:
|
|
||||||
config.update({'spaces': self.args.spaces})
|
|
||||||
logger.info('Parameter -s/--spaces detected: %s', config.get('spaces'))
|
|
||||||
|
|
||||||
return config
|
|
||||||
|
|
||||||
def _validate_config(self, conf: Dict[str, Any]) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Validate the configuration follow the Config Schema
|
|
||||||
:param conf: Config in JSON format
|
|
||||||
:return: Returns the config if valid, otherwise throw an exception
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
validate(conf, constants.CONF_SCHEMA, Draft4Validator)
|
|
||||||
return conf
|
|
||||||
except ValidationError as exception:
|
|
||||||
logger.critical(
|
|
||||||
'Invalid configuration. See config.json.example. Reason: %s',
|
|
||||||
exception
|
|
||||||
)
|
|
||||||
raise ValidationError(
|
|
||||||
best_match(Draft4Validator(constants.CONF_SCHEMA).iter_errors(conf)).message
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_config(self) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Return the config. Use this method to get the bot config
|
|
||||||
:return: Dict: Bot config
|
|
||||||
"""
|
|
||||||
if self.config is None:
|
|
||||||
self.config = self.load_config()
|
|
||||||
|
|
||||||
return self.config
|
|
||||||
|
|
||||||
def check_exchange(self, config: Dict[str, Any]) -> bool:
|
|
||||||
"""
|
|
||||||
Check if the exchange name in the config file is supported by Freqtrade
|
|
||||||
:return: True or raised an exception if the exchange if not supported
|
|
||||||
"""
|
|
||||||
exchange = config.get('exchange', {}).get('name').lower()
|
|
||||||
if exchange not in ccxt.exchanges:
|
|
||||||
|
|
||||||
exception_msg = f'Exchange "{exchange}" not supported.\n' \
|
|
||||||
f'The following exchanges are supported: {", ".join(ccxt.exchanges)}'
|
|
||||||
|
|
||||||
logger.critical(exception_msg)
|
|
||||||
raise OperationalException(
|
|
||||||
exception_msg
|
|
||||||
)
|
|
||||||
# Depreciation warning
|
|
||||||
if 'ccxt_rate_limit' in config.get('exchange', {}):
|
|
||||||
logger.warning("`ccxt_rate_limit` has been deprecated in favor of "
|
|
||||||
"`ccxt_config` and `ccxt_async_config` and will be removed "
|
|
||||||
"in a future version.")
|
|
||||||
|
|
||||||
logger.debug('Exchange "%s" supported', exchange)
|
|
||||||
return True
|
|
||||||
4
freqtrade/configuration/__init__.py
Normal file
4
freqtrade/configuration/__init__.py
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
from freqtrade.configuration.arguments import Arguments # noqa: F401
|
||||||
|
from freqtrade.configuration.timerange import TimeRange # noqa: F401
|
||||||
|
from freqtrade.configuration.configuration import Configuration # noqa: F401
|
||||||
|
from freqtrade.configuration.config_validation import validate_config_consistency # noqa: F401
|
||||||
196
freqtrade/configuration/arguments.py
Normal file
196
freqtrade/configuration/arguments.py
Normal file
@@ -0,0 +1,196 @@
|
|||||||
|
"""
|
||||||
|
This module contains the argument manager class
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
from functools import partial
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from freqtrade import constants
|
||||||
|
from freqtrade.configuration.cli_options import AVAILABLE_CLI_OPTIONS
|
||||||
|
|
||||||
|
ARGS_COMMON = ["verbosity", "logfile", "version", "config", "datadir", "user_data_dir"]
|
||||||
|
|
||||||
|
ARGS_STRATEGY = ["strategy", "strategy_path"]
|
||||||
|
|
||||||
|
ARGS_MAIN = ARGS_COMMON + ARGS_STRATEGY + ["db_url", "sd_notify"]
|
||||||
|
|
||||||
|
ARGS_COMMON_OPTIMIZE = ["ticker_interval", "timerange",
|
||||||
|
"max_open_trades", "stake_amount", "fee"]
|
||||||
|
|
||||||
|
ARGS_BACKTEST = ARGS_COMMON_OPTIMIZE + ["position_stacking", "use_max_market_positions",
|
||||||
|
"strategy_list", "export", "exportfilename"]
|
||||||
|
|
||||||
|
ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
|
||||||
|
"position_stacking", "epochs", "spaces",
|
||||||
|
"use_max_market_positions", "print_all",
|
||||||
|
"print_colorized", "print_json", "hyperopt_jobs",
|
||||||
|
"hyperopt_random_state", "hyperopt_min_trades",
|
||||||
|
"hyperopt_continue", "hyperopt_loss"]
|
||||||
|
|
||||||
|
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
|
||||||
|
|
||||||
|
ARGS_LIST_EXCHANGES = ["print_one_column", "list_exchanges_all"]
|
||||||
|
|
||||||
|
ARGS_LIST_TIMEFRAMES = ["exchange", "print_one_column"]
|
||||||
|
|
||||||
|
ARGS_LIST_PAIRS = ["exchange", "print_list", "list_pairs_print_json", "print_one_column",
|
||||||
|
"print_csv", "base_currencies", "quote_currencies", "list_pairs_all"]
|
||||||
|
|
||||||
|
ARGS_CREATE_USERDIR = ["user_data_dir"]
|
||||||
|
|
||||||
|
ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "download_trades", "exchange",
|
||||||
|
"timeframes", "erase"]
|
||||||
|
|
||||||
|
ARGS_PLOT_DATAFRAME = ["pairs", "indicators1", "indicators2", "plot_limit", "db_url",
|
||||||
|
"trade_source", "export", "exportfilename", "timerange", "ticker_interval"]
|
||||||
|
|
||||||
|
ARGS_PLOT_PROFIT = ["pairs", "timerange", "export", "exportfilename", "db_url",
|
||||||
|
"trade_source", "ticker_interval"]
|
||||||
|
|
||||||
|
NO_CONF_REQURIED = ["download-data", "list-timeframes", "list-markets", "list-pairs",
|
||||||
|
"plot-dataframe", "plot-profit"]
|
||||||
|
|
||||||
|
NO_CONF_ALLOWED = ["create-userdir", "list-exchanges"]
|
||||||
|
|
||||||
|
|
||||||
|
class Arguments:
|
||||||
|
"""
|
||||||
|
Arguments Class. Manage the arguments received by the cli
|
||||||
|
"""
|
||||||
|
def __init__(self, args: Optional[List[str]]) -> None:
|
||||||
|
self.args = args
|
||||||
|
self._parsed_arg: Optional[argparse.Namespace] = None
|
||||||
|
self.parser = argparse.ArgumentParser(description='Free, open source crypto trading bot')
|
||||||
|
|
||||||
|
def _load_args(self) -> None:
|
||||||
|
self._build_args(optionlist=ARGS_MAIN)
|
||||||
|
self._build_subcommands()
|
||||||
|
|
||||||
|
def get_parsed_arg(self) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Return the list of arguments
|
||||||
|
:return: List[str] List of arguments
|
||||||
|
"""
|
||||||
|
if self._parsed_arg is None:
|
||||||
|
self._load_args()
|
||||||
|
self._parsed_arg = self._parse_args()
|
||||||
|
|
||||||
|
return vars(self._parsed_arg)
|
||||||
|
|
||||||
|
def _parse_args(self) -> argparse.Namespace:
|
||||||
|
"""
|
||||||
|
Parses given arguments and returns an argparse Namespace instance.
|
||||||
|
"""
|
||||||
|
parsed_arg = self.parser.parse_args(self.args)
|
||||||
|
|
||||||
|
# When no config is provided, but a config exists, use that configuration!
|
||||||
|
subparser = parsed_arg.subparser if 'subparser' in parsed_arg else None
|
||||||
|
|
||||||
|
# Workaround issue in argparse with action='append' and default value
|
||||||
|
# (see https://bugs.python.org/issue16399)
|
||||||
|
# Allow no-config for certain commands (like downloading / plotting)
|
||||||
|
if (parsed_arg.config is None
|
||||||
|
and subparser not in NO_CONF_ALLOWED
|
||||||
|
and ((Path.cwd() / constants.DEFAULT_CONFIG).is_file()
|
||||||
|
or (subparser not in NO_CONF_REQURIED))):
|
||||||
|
parsed_arg.config = [constants.DEFAULT_CONFIG]
|
||||||
|
|
||||||
|
return parsed_arg
|
||||||
|
|
||||||
|
def _build_args(self, optionlist, parser=None):
|
||||||
|
parser = parser or self.parser
|
||||||
|
|
||||||
|
for val in optionlist:
|
||||||
|
opt = AVAILABLE_CLI_OPTIONS[val]
|
||||||
|
parser.add_argument(*opt.cli, dest=val, **opt.kwargs)
|
||||||
|
|
||||||
|
def _build_subcommands(self) -> None:
|
||||||
|
"""
|
||||||
|
Builds and attaches all subcommands.
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
from freqtrade.optimize import start_backtesting, start_hyperopt, start_edge
|
||||||
|
from freqtrade.utils import (start_create_userdir, start_download_data,
|
||||||
|
start_list_exchanges, start_list_timeframes,
|
||||||
|
start_list_markets)
|
||||||
|
|
||||||
|
subparsers = self.parser.add_subparsers(dest='subparser')
|
||||||
|
|
||||||
|
# Add backtesting subcommand
|
||||||
|
backtesting_cmd = subparsers.add_parser('backtesting', help='Backtesting module.')
|
||||||
|
backtesting_cmd.set_defaults(func=start_backtesting)
|
||||||
|
self._build_args(optionlist=ARGS_BACKTEST, parser=backtesting_cmd)
|
||||||
|
|
||||||
|
# Add edge subcommand
|
||||||
|
edge_cmd = subparsers.add_parser('edge', help='Edge module.')
|
||||||
|
edge_cmd.set_defaults(func=start_edge)
|
||||||
|
self._build_args(optionlist=ARGS_EDGE, parser=edge_cmd)
|
||||||
|
|
||||||
|
# Add hyperopt subcommand
|
||||||
|
hyperopt_cmd = subparsers.add_parser('hyperopt', help='Hyperopt module.')
|
||||||
|
hyperopt_cmd.set_defaults(func=start_hyperopt)
|
||||||
|
self._build_args(optionlist=ARGS_HYPEROPT, parser=hyperopt_cmd)
|
||||||
|
|
||||||
|
# add create-userdir subcommand
|
||||||
|
create_userdir_cmd = subparsers.add_parser('create-userdir',
|
||||||
|
help="Create user-data directory.")
|
||||||
|
create_userdir_cmd.set_defaults(func=start_create_userdir)
|
||||||
|
self._build_args(optionlist=ARGS_CREATE_USERDIR, parser=create_userdir_cmd)
|
||||||
|
|
||||||
|
# Add list-exchanges subcommand
|
||||||
|
list_exchanges_cmd = subparsers.add_parser(
|
||||||
|
'list-exchanges',
|
||||||
|
help='Print available exchanges.'
|
||||||
|
)
|
||||||
|
list_exchanges_cmd.set_defaults(func=start_list_exchanges)
|
||||||
|
self._build_args(optionlist=ARGS_LIST_EXCHANGES, parser=list_exchanges_cmd)
|
||||||
|
|
||||||
|
# Add list-timeframes subcommand
|
||||||
|
list_timeframes_cmd = subparsers.add_parser(
|
||||||
|
'list-timeframes',
|
||||||
|
help='Print available ticker intervals (timeframes) for the exchange.'
|
||||||
|
)
|
||||||
|
list_timeframes_cmd.set_defaults(func=start_list_timeframes)
|
||||||
|
self._build_args(optionlist=ARGS_LIST_TIMEFRAMES, parser=list_timeframes_cmd)
|
||||||
|
|
||||||
|
# Add list-markets subcommand
|
||||||
|
list_markets_cmd = subparsers.add_parser(
|
||||||
|
'list-markets',
|
||||||
|
help='Print markets on exchange.'
|
||||||
|
)
|
||||||
|
list_markets_cmd.set_defaults(func=partial(start_list_markets, pairs_only=False))
|
||||||
|
self._build_args(optionlist=ARGS_LIST_PAIRS, parser=list_markets_cmd)
|
||||||
|
|
||||||
|
# Add list-pairs subcommand
|
||||||
|
list_pairs_cmd = subparsers.add_parser(
|
||||||
|
'list-pairs',
|
||||||
|
help='Print pairs on exchange.'
|
||||||
|
)
|
||||||
|
list_pairs_cmd.set_defaults(func=partial(start_list_markets, pairs_only=True))
|
||||||
|
self._build_args(optionlist=ARGS_LIST_PAIRS, parser=list_pairs_cmd)
|
||||||
|
|
||||||
|
# Add download-data subcommand
|
||||||
|
download_data_cmd = subparsers.add_parser(
|
||||||
|
'download-data',
|
||||||
|
help='Download backtesting data.'
|
||||||
|
)
|
||||||
|
download_data_cmd.set_defaults(func=start_download_data)
|
||||||
|
self._build_args(optionlist=ARGS_DOWNLOAD_DATA, parser=download_data_cmd)
|
||||||
|
|
||||||
|
# Add Plotting subcommand
|
||||||
|
from freqtrade.plot.plot_utils import start_plot_dataframe, start_plot_profit
|
||||||
|
plot_dataframe_cmd = subparsers.add_parser(
|
||||||
|
'plot-dataframe',
|
||||||
|
help='Plot candles with indicators.'
|
||||||
|
)
|
||||||
|
plot_dataframe_cmd.set_defaults(func=start_plot_dataframe)
|
||||||
|
self._build_args(optionlist=ARGS_PLOT_DATAFRAME, parser=plot_dataframe_cmd)
|
||||||
|
|
||||||
|
# Plot profit
|
||||||
|
plot_profit_cmd = subparsers.add_parser(
|
||||||
|
'plot-profit',
|
||||||
|
help='Generate plot showing profits.'
|
||||||
|
)
|
||||||
|
plot_profit_cmd.set_defaults(func=start_plot_profit)
|
||||||
|
self._build_args(optionlist=ARGS_PLOT_PROFIT, parser=plot_profit_cmd)
|
||||||
60
freqtrade/configuration/check_exchange.py
Normal file
60
freqtrade/configuration/check_exchange.py
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import logging
|
||||||
|
from typing import Any, Dict
|
||||||
|
|
||||||
|
from freqtrade import OperationalException
|
||||||
|
from freqtrade.exchange import (available_exchanges, get_exchange_bad_reason,
|
||||||
|
is_exchange_known_ccxt, is_exchange_bad,
|
||||||
|
is_exchange_officially_supported)
|
||||||
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
||||||
|
"""
|
||||||
|
Check if the exchange name in the config file is supported by Freqtrade
|
||||||
|
:param check_for_bad: if True, check the exchange against the list of known 'bad'
|
||||||
|
exchanges
|
||||||
|
:return: False if exchange is 'bad', i.e. is known to work with the bot with
|
||||||
|
critical issues or does not work at all, crashes, etc. True otherwise.
|
||||||
|
raises an exception if the exchange if not supported by ccxt
|
||||||
|
and thus is not known for the Freqtrade at all.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if config['runmode'] in [RunMode.PLOT] and not config.get('exchange', {}).get('name'):
|
||||||
|
# Skip checking exchange in plot mode, since it requires no exchange
|
||||||
|
return True
|
||||||
|
logger.info("Checking exchange...")
|
||||||
|
|
||||||
|
exchange = config.get('exchange', {}).get('name').lower()
|
||||||
|
if not exchange:
|
||||||
|
raise OperationalException(
|
||||||
|
f'This command requires a configured exchange. You should either use '
|
||||||
|
f'`--exchange <exchange_name>` or specify a configuration file via `--config`.\n'
|
||||||
|
f'The following exchanges are available for Freqtrade: '
|
||||||
|
f'{", ".join(available_exchanges())}'
|
||||||
|
)
|
||||||
|
|
||||||
|
if not is_exchange_known_ccxt(exchange):
|
||||||
|
raise OperationalException(
|
||||||
|
f'Exchange "{exchange}" is not known to the ccxt library '
|
||||||
|
f'and therefore not available for the bot.\n'
|
||||||
|
f'The following exchanges are available for Freqtrade: '
|
||||||
|
f'{", ".join(available_exchanges())}'
|
||||||
|
)
|
||||||
|
|
||||||
|
if check_for_bad and is_exchange_bad(exchange):
|
||||||
|
raise OperationalException(f'Exchange "{exchange}" is known to not work with the bot yet. '
|
||||||
|
f'Reason: {get_exchange_bad_reason(exchange)}')
|
||||||
|
|
||||||
|
if is_exchange_officially_supported(exchange):
|
||||||
|
logger.info(f'Exchange "{exchange}" is officially supported '
|
||||||
|
f'by the Freqtrade development team.')
|
||||||
|
else:
|
||||||
|
logger.warning(f'Exchange "{exchange}" is known to the the ccxt library, '
|
||||||
|
f'available for the bot, but not officially supported '
|
||||||
|
f'by the Freqtrade development team. '
|
||||||
|
f'It may work flawlessly (please report back) or have serious issues. '
|
||||||
|
f'Use it at your own discretion.')
|
||||||
|
|
||||||
|
return True
|
||||||
364
freqtrade/configuration/cli_options.py
Normal file
364
freqtrade/configuration/cli_options.py
Normal file
@@ -0,0 +1,364 @@
|
|||||||
|
"""
|
||||||
|
Definition of cli arguments used in arguments.py
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
from freqtrade import __version__, constants
|
||||||
|
|
||||||
|
|
||||||
|
def check_int_positive(value: str) -> int:
|
||||||
|
try:
|
||||||
|
uint = int(value)
|
||||||
|
if uint <= 0:
|
||||||
|
raise ValueError
|
||||||
|
except ValueError:
|
||||||
|
raise argparse.ArgumentTypeError(
|
||||||
|
f"{value} is invalid for this parameter, should be a positive integer value"
|
||||||
|
)
|
||||||
|
return uint
|
||||||
|
|
||||||
|
|
||||||
|
class Arg:
|
||||||
|
# Optional CLI arguments
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.cli = args
|
||||||
|
self.kwargs = kwargs
|
||||||
|
|
||||||
|
|
||||||
|
# List of available command line options
|
||||||
|
AVAILABLE_CLI_OPTIONS = {
|
||||||
|
# Common options
|
||||||
|
"verbosity": Arg(
|
||||||
|
'-v', '--verbose',
|
||||||
|
help='Verbose mode (-vv for more, -vvv to get all messages).',
|
||||||
|
action='count',
|
||||||
|
default=0,
|
||||||
|
),
|
||||||
|
"logfile": Arg(
|
||||||
|
'--logfile',
|
||||||
|
help='Log to the file specified.',
|
||||||
|
metavar='FILE',
|
||||||
|
),
|
||||||
|
"version": Arg(
|
||||||
|
'-V', '--version',
|
||||||
|
action='version',
|
||||||
|
version=f'%(prog)s {__version__}',
|
||||||
|
),
|
||||||
|
"config": Arg(
|
||||||
|
'-c', '--config',
|
||||||
|
help=f'Specify configuration file (default: `{constants.DEFAULT_CONFIG}`). '
|
||||||
|
f'Multiple --config options may be used. '
|
||||||
|
f'Can be set to `-` to read config from stdin.',
|
||||||
|
action='append',
|
||||||
|
metavar='PATH',
|
||||||
|
),
|
||||||
|
"datadir": Arg(
|
||||||
|
'-d', '--datadir',
|
||||||
|
help='Path to directory with historical backtesting data.',
|
||||||
|
metavar='PATH',
|
||||||
|
),
|
||||||
|
"user_data_dir": Arg(
|
||||||
|
'--userdir', '--user-data-dir',
|
||||||
|
help='Path to userdata directory.',
|
||||||
|
metavar='PATH',
|
||||||
|
),
|
||||||
|
# Main options
|
||||||
|
"strategy": Arg(
|
||||||
|
'-s', '--strategy',
|
||||||
|
help='Specify strategy class name (default: `%(default)s`).',
|
||||||
|
metavar='NAME',
|
||||||
|
default='DefaultStrategy',
|
||||||
|
),
|
||||||
|
"strategy_path": Arg(
|
||||||
|
'--strategy-path',
|
||||||
|
help='Specify additional strategy lookup path.',
|
||||||
|
metavar='PATH',
|
||||||
|
),
|
||||||
|
"db_url": Arg(
|
||||||
|
'--db-url',
|
||||||
|
help=f'Override trades database URL, this is useful in custom deployments '
|
||||||
|
f'(default: `{constants.DEFAULT_DB_PROD_URL}` for Live Run mode, '
|
||||||
|
f'`{constants.DEFAULT_DB_DRYRUN_URL}` for Dry Run).',
|
||||||
|
metavar='PATH',
|
||||||
|
),
|
||||||
|
"sd_notify": Arg(
|
||||||
|
'--sd-notify',
|
||||||
|
help='Notify systemd service manager.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
# Optimize common
|
||||||
|
"ticker_interval": Arg(
|
||||||
|
'-i', '--ticker-interval',
|
||||||
|
help='Specify ticker interval (`1m`, `5m`, `30m`, `1h`, `1d`).',
|
||||||
|
),
|
||||||
|
"timerange": Arg(
|
||||||
|
'--timerange',
|
||||||
|
help='Specify what timerange of data to use.',
|
||||||
|
),
|
||||||
|
"max_open_trades": Arg(
|
||||||
|
'--max_open_trades',
|
||||||
|
help='Specify max_open_trades to use.',
|
||||||
|
type=int,
|
||||||
|
metavar='INT',
|
||||||
|
),
|
||||||
|
"stake_amount": Arg(
|
||||||
|
'--stake_amount',
|
||||||
|
help='Specify stake_amount.',
|
||||||
|
type=float,
|
||||||
|
),
|
||||||
|
# Backtesting
|
||||||
|
"position_stacking": Arg(
|
||||||
|
'--eps', '--enable-position-stacking',
|
||||||
|
help='Allow buying the same pair multiple times (position stacking).',
|
||||||
|
action='store_true',
|
||||||
|
default=False,
|
||||||
|
),
|
||||||
|
"use_max_market_positions": Arg(
|
||||||
|
'--dmmp', '--disable-max-market-positions',
|
||||||
|
help='Disable applying `max_open_trades` during backtest '
|
||||||
|
'(same as setting `max_open_trades` to a very high number).',
|
||||||
|
action='store_false',
|
||||||
|
default=True,
|
||||||
|
),
|
||||||
|
"strategy_list": Arg(
|
||||||
|
'--strategy-list',
|
||||||
|
help='Provide a space-separated list of strategies to backtest. '
|
||||||
|
'Please note that ticker-interval needs to be set either in config '
|
||||||
|
'or via command line. When using this together with `--export trades`, '
|
||||||
|
'the strategy-name is injected into the filename '
|
||||||
|
'(so `backtest-data.json` becomes `backtest-data-DefaultStrategy.json`',
|
||||||
|
nargs='+',
|
||||||
|
),
|
||||||
|
"export": Arg(
|
||||||
|
'--export',
|
||||||
|
help='Export backtest results, argument are: trades. '
|
||||||
|
'Example: `--export=trades`',
|
||||||
|
),
|
||||||
|
"exportfilename": Arg(
|
||||||
|
'--export-filename',
|
||||||
|
help='Save backtest results to the file with this filename (default: `%(default)s`). '
|
||||||
|
'Requires `--export` to be set as well. '
|
||||||
|
'Example: `--export-filename=user_data/backtest_results/backtest_today.json`',
|
||||||
|
metavar='PATH',
|
||||||
|
),
|
||||||
|
"fee": Arg(
|
||||||
|
'--fee',
|
||||||
|
help='Specify fee ratio. Will be applied twice (on trade entry and exit).',
|
||||||
|
type=float,
|
||||||
|
metavar='FLOAT',
|
||||||
|
),
|
||||||
|
# Edge
|
||||||
|
"stoploss_range": Arg(
|
||||||
|
'--stoplosses',
|
||||||
|
help='Defines a range of stoploss values against which edge will assess the strategy. '
|
||||||
|
'The format is "min,max,step" (without any space). '
|
||||||
|
'Example: `--stoplosses=-0.01,-0.1,-0.001`',
|
||||||
|
),
|
||||||
|
# Hyperopt
|
||||||
|
"hyperopt": Arg(
|
||||||
|
'--customhyperopt',
|
||||||
|
help='Specify hyperopt class name (default: `%(default)s`).',
|
||||||
|
metavar='NAME',
|
||||||
|
default=constants.DEFAULT_HYPEROPT,
|
||||||
|
),
|
||||||
|
"hyperopt_path": Arg(
|
||||||
|
'--hyperopt-path',
|
||||||
|
help='Specify additional lookup path for Hyperopts and Hyperopt Loss functions.',
|
||||||
|
metavar='PATH',
|
||||||
|
),
|
||||||
|
"epochs": Arg(
|
||||||
|
'-e', '--epochs',
|
||||||
|
help='Specify number of epochs (default: %(default)d).',
|
||||||
|
type=check_int_positive,
|
||||||
|
metavar='INT',
|
||||||
|
default=constants.HYPEROPT_EPOCH,
|
||||||
|
),
|
||||||
|
"spaces": Arg(
|
||||||
|
'-s', '--spaces',
|
||||||
|
help='Specify which parameters to hyperopt. Space-separated list. '
|
||||||
|
'Default: `%(default)s`.',
|
||||||
|
choices=['all', 'buy', 'sell', 'roi', 'stoploss'],
|
||||||
|
nargs='+',
|
||||||
|
default='all',
|
||||||
|
),
|
||||||
|
"print_all": Arg(
|
||||||
|
'--print-all',
|
||||||
|
help='Print all results, not only the best ones.',
|
||||||
|
action='store_true',
|
||||||
|
default=False,
|
||||||
|
),
|
||||||
|
"print_colorized": Arg(
|
||||||
|
'--no-color',
|
||||||
|
help='Disable colorization of hyperopt results. May be useful if you are '
|
||||||
|
'redirecting output to a file.',
|
||||||
|
action='store_false',
|
||||||
|
default=True,
|
||||||
|
),
|
||||||
|
"print_json": Arg(
|
||||||
|
'--print-json',
|
||||||
|
help='Print best result detailization in JSON format.',
|
||||||
|
action='store_true',
|
||||||
|
default=False,
|
||||||
|
),
|
||||||
|
"hyperopt_jobs": Arg(
|
||||||
|
'-j', '--job-workers',
|
||||||
|
help='The number of concurrently running jobs for hyperoptimization '
|
||||||
|
'(hyperopt worker processes). '
|
||||||
|
'If -1 (default), all CPUs are used, for -2, all CPUs but one are used, etc. '
|
||||||
|
'If 1 is given, no parallel computing code is used at all.',
|
||||||
|
type=int,
|
||||||
|
metavar='JOBS',
|
||||||
|
default=-1,
|
||||||
|
),
|
||||||
|
"hyperopt_random_state": Arg(
|
||||||
|
'--random-state',
|
||||||
|
help='Set random state to some positive integer for reproducible hyperopt results.',
|
||||||
|
type=check_int_positive,
|
||||||
|
metavar='INT',
|
||||||
|
),
|
||||||
|
"hyperopt_min_trades": Arg(
|
||||||
|
'--min-trades',
|
||||||
|
help="Set minimal desired number of trades for evaluations in the hyperopt "
|
||||||
|
"optimization path (default: 1).",
|
||||||
|
type=check_int_positive,
|
||||||
|
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.'
|
||||||
|
'(default: `%(default)s`).',
|
||||||
|
metavar='NAME',
|
||||||
|
default=constants.DEFAULT_HYPEROPT_LOSS,
|
||||||
|
),
|
||||||
|
# List exchanges
|
||||||
|
"print_one_column": Arg(
|
||||||
|
'-1', '--one-column',
|
||||||
|
help='Print output in one column.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"list_exchanges_all": Arg(
|
||||||
|
'-a', '--all',
|
||||||
|
help='Print all exchanges known to the ccxt library.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
# List pairs / markets
|
||||||
|
"list_pairs_all": Arg(
|
||||||
|
'-a', '--all',
|
||||||
|
help='Print all pairs or market symbols. By default only active '
|
||||||
|
'ones are shown.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"print_list": Arg(
|
||||||
|
'--print-list',
|
||||||
|
help='Print list of pairs or market symbols. By default data is '
|
||||||
|
'printed in the tabular format.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"list_pairs_print_json": Arg(
|
||||||
|
'--print-json',
|
||||||
|
help='Print list of pairs or market symbols in JSON format.',
|
||||||
|
action='store_true',
|
||||||
|
default=False,
|
||||||
|
),
|
||||||
|
"print_csv": Arg(
|
||||||
|
'--print-csv',
|
||||||
|
help='Print exchange pair or market data in the csv format.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"quote_currencies": Arg(
|
||||||
|
'--quote',
|
||||||
|
help='Specify quote currency(-ies). Space-separated list.',
|
||||||
|
nargs='+',
|
||||||
|
metavar='QUOTE_CURRENCY',
|
||||||
|
),
|
||||||
|
"base_currencies": Arg(
|
||||||
|
'--base',
|
||||||
|
help='Specify base currency(-ies). Space-separated list.',
|
||||||
|
nargs='+',
|
||||||
|
metavar='BASE_CURRENCY',
|
||||||
|
),
|
||||||
|
# Script options
|
||||||
|
"pairs": Arg(
|
||||||
|
'-p', '--pairs',
|
||||||
|
help='Show profits for only these pairs. Pairs are space-separated.',
|
||||||
|
nargs='+',
|
||||||
|
),
|
||||||
|
# Download data
|
||||||
|
"pairs_file": Arg(
|
||||||
|
'--pairs-file',
|
||||||
|
help='File containing a list of pairs to download.',
|
||||||
|
metavar='FILE',
|
||||||
|
),
|
||||||
|
"days": Arg(
|
||||||
|
'--days',
|
||||||
|
help='Download data for given number of days.',
|
||||||
|
type=check_int_positive,
|
||||||
|
metavar='INT',
|
||||||
|
),
|
||||||
|
"download_trades": Arg(
|
||||||
|
'--dl-trades',
|
||||||
|
help='Download trades instead of OHLCV data. The bot will resample trades to the '
|
||||||
|
'desired timeframe as specified as --timeframes/-t.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"exchange": Arg(
|
||||||
|
'--exchange',
|
||||||
|
help=f'Exchange name (default: `{constants.DEFAULT_EXCHANGE}`). '
|
||||||
|
f'Only valid if no config is provided.',
|
||||||
|
),
|
||||||
|
"timeframes": Arg(
|
||||||
|
'-t', '--timeframes',
|
||||||
|
help=f'Specify which tickers to download. Space-separated list. '
|
||||||
|
f'Default: `1m 5m`.',
|
||||||
|
choices=['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h',
|
||||||
|
'6h', '8h', '12h', '1d', '3d', '1w'],
|
||||||
|
default=['1m', '5m'],
|
||||||
|
nargs='+',
|
||||||
|
),
|
||||||
|
"erase": Arg(
|
||||||
|
'--erase',
|
||||||
|
help='Clean all existing data for the selected exchange/pairs/timeframes.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
# Plot dataframe
|
||||||
|
"indicators1": Arg(
|
||||||
|
'--indicators1',
|
||||||
|
help='Set indicators from your strategy you want in the first row of the graph. '
|
||||||
|
'Space-separated list. Example: `ema3 ema5`. Default: `%(default)s`.',
|
||||||
|
default=['sma', 'ema3', 'ema5'],
|
||||||
|
nargs='+',
|
||||||
|
),
|
||||||
|
"indicators2": Arg(
|
||||||
|
'--indicators2',
|
||||||
|
help='Set indicators from your strategy you want in the third row of the graph. '
|
||||||
|
'Space-separated list. Example: `fastd fastk`. Default: `%(default)s`.',
|
||||||
|
default=['macd', 'macdsignal'],
|
||||||
|
nargs='+',
|
||||||
|
),
|
||||||
|
"plot_limit": Arg(
|
||||||
|
'--plot-limit',
|
||||||
|
help='Specify tick limit for plotting. Notice: too high values cause huge files. '
|
||||||
|
'Default: %(default)s.',
|
||||||
|
type=check_int_positive,
|
||||||
|
metavar='INT',
|
||||||
|
default=750,
|
||||||
|
),
|
||||||
|
"trade_source": Arg(
|
||||||
|
'--trade-source',
|
||||||
|
help='Specify the source for trades (Can be DB or file (backtest file)) '
|
||||||
|
'Default: %(default)s',
|
||||||
|
choices=["DB", "file"],
|
||||||
|
default="file",
|
||||||
|
),
|
||||||
|
}
|
||||||
113
freqtrade/configuration/config_validation.py
Normal file
113
freqtrade/configuration/config_validation.py
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
import logging
|
||||||
|
from typing import Any, Dict
|
||||||
|
|
||||||
|
from jsonschema import Draft4Validator, validators
|
||||||
|
from jsonschema.exceptions import ValidationError, best_match
|
||||||
|
|
||||||
|
from freqtrade import constants, OperationalException
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _extend_validator(validator_class):
|
||||||
|
"""
|
||||||
|
Extended validator for the Freqtrade configuration JSON Schema.
|
||||||
|
Currently it only handles defaults for subschemas.
|
||||||
|
"""
|
||||||
|
validate_properties = validator_class.VALIDATORS['properties']
|
||||||
|
|
||||||
|
def set_defaults(validator, properties, instance, schema):
|
||||||
|
for prop, subschema in properties.items():
|
||||||
|
if 'default' in subschema:
|
||||||
|
instance.setdefault(prop, subschema['default'])
|
||||||
|
|
||||||
|
for error in validate_properties(
|
||||||
|
validator, properties, instance, schema,
|
||||||
|
):
|
||||||
|
yield error
|
||||||
|
|
||||||
|
return validators.extend(
|
||||||
|
validator_class, {'properties': set_defaults}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
FreqtradeValidator = _extend_validator(Draft4Validator)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_config_schema(conf: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Validate the configuration follow the Config Schema
|
||||||
|
:param conf: Config in JSON format
|
||||||
|
:return: Returns the config if valid, otherwise throw an exception
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
FreqtradeValidator(constants.CONF_SCHEMA).validate(conf)
|
||||||
|
return conf
|
||||||
|
except ValidationError as e:
|
||||||
|
logger.critical(
|
||||||
|
f"Invalid configuration. See config.json.example. Reason: {e}"
|
||||||
|
)
|
||||||
|
raise ValidationError(
|
||||||
|
best_match(Draft4Validator(constants.CONF_SCHEMA).iter_errors(conf)).message
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_config_consistency(conf: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Validate the configuration consistency.
|
||||||
|
Should be ran after loading both configuration and strategy,
|
||||||
|
since strategies can set certain configuration settings too.
|
||||||
|
:param conf: Config in JSON format
|
||||||
|
:return: Returns None if everything is ok, otherwise throw an OperationalException
|
||||||
|
"""
|
||||||
|
# validating trailing stoploss
|
||||||
|
_validate_trailing_stoploss(conf)
|
||||||
|
_validate_edge(conf)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_trailing_stoploss(conf: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
if conf.get('stoploss') == 0.0:
|
||||||
|
raise OperationalException(
|
||||||
|
'The config stoploss needs to be different from 0 to avoid problems with sell orders.'
|
||||||
|
)
|
||||||
|
# Skip if trailing stoploss is not activated
|
||||||
|
if not conf.get('trailing_stop', False):
|
||||||
|
return
|
||||||
|
|
||||||
|
tsl_positive = float(conf.get('trailing_stop_positive', 0))
|
||||||
|
tsl_offset = float(conf.get('trailing_stop_positive_offset', 0))
|
||||||
|
tsl_only_offset = conf.get('trailing_only_offset_is_reached', False)
|
||||||
|
|
||||||
|
if tsl_only_offset:
|
||||||
|
if tsl_positive == 0.0:
|
||||||
|
raise OperationalException(
|
||||||
|
'The config trailing_only_offset_is_reached needs '
|
||||||
|
'trailing_stop_positive_offset to be more than 0 in your config.')
|
||||||
|
if tsl_positive > 0 and 0 < tsl_offset <= tsl_positive:
|
||||||
|
raise OperationalException(
|
||||||
|
'The config trailing_stop_positive_offset needs '
|
||||||
|
'to be greater than trailing_stop_positive in your config.')
|
||||||
|
|
||||||
|
# Fetch again without default
|
||||||
|
if 'trailing_stop_positive' in conf and float(conf['trailing_stop_positive']) == 0.0:
|
||||||
|
raise OperationalException(
|
||||||
|
'The config trailing_stop_positive needs to be different from 0 '
|
||||||
|
'to avoid problems with sell orders.'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_edge(conf: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Edge and Dynamic whitelist should not both be enabled, since edge overrides dynamic whitelists.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not conf.get('edge', {}).get('enabled'):
|
||||||
|
return
|
||||||
|
|
||||||
|
if conf.get('pairlist', {}).get('method') == 'VolumePairList':
|
||||||
|
raise OperationalException(
|
||||||
|
"Edge and VolumePairList are incompatible, "
|
||||||
|
"Edge will override whatever pairs VolumePairlist selects."
|
||||||
|
)
|
||||||
388
freqtrade/configuration/configuration.py
Normal file
388
freqtrade/configuration/configuration.py
Normal file
@@ -0,0 +1,388 @@
|
|||||||
|
"""
|
||||||
|
This module contains the configuration class
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import warnings
|
||||||
|
from copy import deepcopy
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Callable, Dict, List, Optional
|
||||||
|
|
||||||
|
from freqtrade import OperationalException, constants
|
||||||
|
from freqtrade.configuration.check_exchange import check_exchange
|
||||||
|
from freqtrade.configuration.config_validation import (validate_config_consistency,
|
||||||
|
validate_config_schema)
|
||||||
|
from freqtrade.configuration.deprecated_settings import process_temporary_deprecated_settings
|
||||||
|
from freqtrade.configuration.directory_operations import (create_datadir,
|
||||||
|
create_userdata_dir)
|
||||||
|
from freqtrade.configuration.load_config import load_config_file
|
||||||
|
from freqtrade.loggers import setup_logging
|
||||||
|
from freqtrade.misc import deep_merge_dicts, json_load
|
||||||
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class Configuration:
|
||||||
|
"""
|
||||||
|
Class to read and init the bot configuration
|
||||||
|
Reuse this class for the bot, backtesting, hyperopt and every script that required configuration
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, args: Dict[str, Any], runmode: RunMode = None) -> None:
|
||||||
|
self.args = args
|
||||||
|
self.config: Optional[Dict[str, Any]] = None
|
||||||
|
self.runmode = runmode
|
||||||
|
|
||||||
|
def get_config(self) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Return the config. Use this method to get the bot config
|
||||||
|
:return: Dict: Bot config
|
||||||
|
"""
|
||||||
|
if self.config is None:
|
||||||
|
self.config = self.load_config()
|
||||||
|
|
||||||
|
return self.config
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def from_files(files: List[str]) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Iterate through the config files passed in, loading all of them
|
||||||
|
and merging their contents.
|
||||||
|
Files are loaded in sequence, parameters in later configuration files
|
||||||
|
override the same parameter from an earlier file (last definition wins).
|
||||||
|
Runs through the whole Configuration initialization, so all expected config entries
|
||||||
|
are available to interactive environments.
|
||||||
|
:param files: List of file paths
|
||||||
|
:return: configuration dictionary
|
||||||
|
"""
|
||||||
|
c = Configuration({"config": files}, RunMode.OTHER)
|
||||||
|
return c.get_config()
|
||||||
|
|
||||||
|
def load_from_files(self, files: List[str]) -> Dict[str, Any]:
|
||||||
|
|
||||||
|
# Keep this method as staticmethod, so it can be used from interactive environments
|
||||||
|
config: Dict[str, Any] = {}
|
||||||
|
|
||||||
|
if not files:
|
||||||
|
return deepcopy(constants.MINIMAL_CONFIG)
|
||||||
|
|
||||||
|
# We expect here a list of config filenames
|
||||||
|
for path in files:
|
||||||
|
logger.info(f'Using config: {path} ...')
|
||||||
|
|
||||||
|
# Merge config options, overwriting old values
|
||||||
|
config = deep_merge_dicts(load_config_file(path), config)
|
||||||
|
|
||||||
|
# Normalize config
|
||||||
|
if 'internals' not in config:
|
||||||
|
config['internals'] = {}
|
||||||
|
# TODO: This can be deleted along with removal of deprecated
|
||||||
|
# experimental settings
|
||||||
|
if 'ask_strategy' not in config:
|
||||||
|
config['ask_strategy'] = {}
|
||||||
|
|
||||||
|
# validate configuration before returning
|
||||||
|
logger.info('Validating configuration ...')
|
||||||
|
validate_config_schema(config)
|
||||||
|
|
||||||
|
return config
|
||||||
|
|
||||||
|
def load_config(self) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Extract information for sys.argv and load the bot configuration
|
||||||
|
:return: Configuration dictionary
|
||||||
|
"""
|
||||||
|
# Load all configs
|
||||||
|
config: Dict[str, Any] = self.load_from_files(self.args["config"])
|
||||||
|
|
||||||
|
# Keep a copy of the original configuration file
|
||||||
|
config['original_config'] = deepcopy(config)
|
||||||
|
|
||||||
|
self._process_common_options(config)
|
||||||
|
|
||||||
|
self._process_optimize_options(config)
|
||||||
|
|
||||||
|
self._process_plot_options(config)
|
||||||
|
|
||||||
|
self._process_runmode(config)
|
||||||
|
|
||||||
|
# Check if the exchange set by the user is supported
|
||||||
|
check_exchange(config, config.get('experimental', {}).get('block_bad_exchanges', True))
|
||||||
|
|
||||||
|
self._resolve_pairs_list(config)
|
||||||
|
|
||||||
|
process_temporary_deprecated_settings(config)
|
||||||
|
|
||||||
|
validate_config_consistency(config)
|
||||||
|
|
||||||
|
return config
|
||||||
|
|
||||||
|
def _process_logging_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Extract information for sys.argv and load logging configuration:
|
||||||
|
the -v/--verbose, --logfile options
|
||||||
|
"""
|
||||||
|
# Log level
|
||||||
|
config.update({'verbosity': self.args.get("verbosity", 0)})
|
||||||
|
|
||||||
|
if 'logfile' in self.args and self.args["logfile"]:
|
||||||
|
config.update({'logfile': self.args["logfile"]})
|
||||||
|
|
||||||
|
setup_logging(config)
|
||||||
|
|
||||||
|
def _process_common_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
self._process_logging_options(config)
|
||||||
|
|
||||||
|
# Set strategy if not specified in config and or if it's non default
|
||||||
|
if self.args.get("strategy") != constants.DEFAULT_STRATEGY or not config.get('strategy'):
|
||||||
|
config.update({'strategy': self.args.get("strategy")})
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='strategy_path',
|
||||||
|
logstring='Using additional Strategy lookup path: {}')
|
||||||
|
|
||||||
|
if ('db_url' in self.args and self.args["db_url"] and
|
||||||
|
self.args["db_url"] != constants.DEFAULT_DB_PROD_URL):
|
||||||
|
config.update({'db_url': self.args["db_url"]})
|
||||||
|
logger.info('Parameter --db-url detected ...')
|
||||||
|
|
||||||
|
if config.get('dry_run', False):
|
||||||
|
logger.info('Dry run is enabled')
|
||||||
|
if config.get('db_url') in [None, constants.DEFAULT_DB_PROD_URL]:
|
||||||
|
# Default to in-memory db for dry_run if not specified
|
||||||
|
config['db_url'] = constants.DEFAULT_DB_DRYRUN_URL
|
||||||
|
else:
|
||||||
|
if not config.get('db_url', None):
|
||||||
|
config['db_url'] = constants.DEFAULT_DB_PROD_URL
|
||||||
|
logger.info('Dry run is disabled')
|
||||||
|
|
||||||
|
logger.info(f'Using DB: "{config["db_url"]}"')
|
||||||
|
|
||||||
|
if config.get('forcebuy_enable', False):
|
||||||
|
logger.warning('`forcebuy` RPC message enabled.')
|
||||||
|
|
||||||
|
# Setting max_open_trades to infinite if -1
|
||||||
|
if config.get('max_open_trades') == -1:
|
||||||
|
config['max_open_trades'] = float('inf')
|
||||||
|
|
||||||
|
# Support for sd_notify
|
||||||
|
if 'sd_notify' in self.args and self.args["sd_notify"]:
|
||||||
|
config['internals'].update({'sd_notify': True})
|
||||||
|
|
||||||
|
def _process_datadir_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Extract information for sys.argv and load directory configurations
|
||||||
|
--user-data, --datadir
|
||||||
|
"""
|
||||||
|
# Check exchange parameter here - otherwise `datadir` might be wrong.
|
||||||
|
if "exchange" in self.args and self.args["exchange"]:
|
||||||
|
config['exchange']['name'] = self.args["exchange"]
|
||||||
|
logger.info(f"Using exchange {config['exchange']['name']}")
|
||||||
|
|
||||||
|
if 'user_data_dir' in self.args and self.args["user_data_dir"]:
|
||||||
|
config.update({'user_data_dir': self.args["user_data_dir"]})
|
||||||
|
elif 'user_data_dir' not in config:
|
||||||
|
# Default to cwd/user_data (legacy option ...)
|
||||||
|
config.update({'user_data_dir': str(Path.cwd() / "user_data")})
|
||||||
|
|
||||||
|
# reset to user_data_dir so this contains the absolute path.
|
||||||
|
config['user_data_dir'] = create_userdata_dir(config['user_data_dir'], create_dir=False)
|
||||||
|
logger.info('Using user-data directory: %s ...', config['user_data_dir'])
|
||||||
|
|
||||||
|
config.update({'datadir': create_datadir(config, self.args.get("datadir", None))})
|
||||||
|
logger.info('Using data directory: %s ...', config.get('datadir'))
|
||||||
|
|
||||||
|
if self.args.get('exportfilename'):
|
||||||
|
self._args_to_config(config, argname='exportfilename',
|
||||||
|
logstring='Storing backtest results to {} ...')
|
||||||
|
else:
|
||||||
|
config['exportfilename'] = (config['user_data_dir']
|
||||||
|
/ 'backtest_results/backtest-result.json')
|
||||||
|
|
||||||
|
def _process_optimize_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
# This will override the strategy configuration
|
||||||
|
self._args_to_config(config, argname='ticker_interval',
|
||||||
|
logstring='Parameter -i/--ticker-interval detected ... '
|
||||||
|
'Using ticker_interval: {} ...')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='position_stacking',
|
||||||
|
logstring='Parameter --enable-position-stacking detected ...')
|
||||||
|
|
||||||
|
if 'use_max_market_positions' in self.args and not self.args["use_max_market_positions"]:
|
||||||
|
config.update({'use_max_market_positions': False})
|
||||||
|
logger.info('Parameter --disable-max-market-positions detected ...')
|
||||||
|
logger.info('max_open_trades set to unlimited ...')
|
||||||
|
elif 'max_open_trades' in self.args and self.args["max_open_trades"]:
|
||||||
|
config.update({'max_open_trades': self.args["max_open_trades"]})
|
||||||
|
logger.info('Parameter --max_open_trades detected, '
|
||||||
|
'overriding max_open_trades to: %s ...', config.get('max_open_trades'))
|
||||||
|
else:
|
||||||
|
logger.info('Using max_open_trades: %s ...', config.get('max_open_trades'))
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='stake_amount',
|
||||||
|
logstring='Parameter --stake_amount detected, '
|
||||||
|
'overriding stake_amount to: {} ...')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='fee',
|
||||||
|
logstring='Parameter --fee detected, '
|
||||||
|
'setting fee to: {} ...')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='timerange',
|
||||||
|
logstring='Parameter --timerange detected: {} ...')
|
||||||
|
|
||||||
|
self._process_datadir_options(config)
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='strategy_list',
|
||||||
|
logstring='Using strategy list of {} strategies', logfun=len)
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='ticker_interval',
|
||||||
|
logstring='Overriding ticker interval with Command line argument')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='export',
|
||||||
|
logstring='Parameter --export detected: {} ...')
|
||||||
|
|
||||||
|
# Edge section:
|
||||||
|
if 'stoploss_range' in self.args and self.args["stoploss_range"]:
|
||||||
|
txt_range = eval(self.args["stoploss_range"])
|
||||||
|
config['edge'].update({'stoploss_range_min': txt_range[0]})
|
||||||
|
config['edge'].update({'stoploss_range_max': txt_range[1]})
|
||||||
|
config['edge'].update({'stoploss_range_step': txt_range[2]})
|
||||||
|
logger.info('Parameter --stoplosses detected: %s ...', self.args["stoploss_range"])
|
||||||
|
|
||||||
|
# Hyperopt section
|
||||||
|
self._args_to_config(config, argname='hyperopt',
|
||||||
|
logstring='Using Hyperopt class name: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_path',
|
||||||
|
logstring='Using additional Hyperopt lookup path: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='epochs',
|
||||||
|
logstring='Parameter --epochs detected ... '
|
||||||
|
'Will run Hyperopt with for {} epochs ...'
|
||||||
|
)
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='spaces',
|
||||||
|
logstring='Parameter -s/--spaces detected: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='print_all',
|
||||||
|
logstring='Parameter --print-all detected ...')
|
||||||
|
|
||||||
|
if 'print_colorized' in self.args and not self.args["print_colorized"]:
|
||||||
|
logger.info('Parameter --no-color detected ...')
|
||||||
|
config.update({'print_colorized': False})
|
||||||
|
else:
|
||||||
|
config.update({'print_colorized': True})
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='print_json',
|
||||||
|
logstring='Parameter --print-json detected ...')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_jobs',
|
||||||
|
logstring='Parameter -j/--job-workers detected: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_random_state',
|
||||||
|
logstring='Parameter --random-state detected: {}')
|
||||||
|
|
||||||
|
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: {}')
|
||||||
|
|
||||||
|
def _process_plot_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='pairs',
|
||||||
|
logstring='Using pairs {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='indicators1',
|
||||||
|
logstring='Using indicators1: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='indicators2',
|
||||||
|
logstring='Using indicators2: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='plot_limit',
|
||||||
|
logstring='Limiting plot to: {}')
|
||||||
|
self._args_to_config(config, argname='trade_source',
|
||||||
|
logstring='Using trades from: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='erase',
|
||||||
|
logstring='Erase detected. Deleting existing data.')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='timeframes',
|
||||||
|
logstring='timeframes --timeframes: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='days',
|
||||||
|
logstring='Detected --days: {}')
|
||||||
|
self._args_to_config(config, argname='download_trades',
|
||||||
|
logstring='Detected --dl-trades: {}')
|
||||||
|
|
||||||
|
def _process_runmode(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
if not self.runmode:
|
||||||
|
# Handle real mode, infer dry/live from config
|
||||||
|
self.runmode = RunMode.DRY_RUN if config.get('dry_run', True) else RunMode.LIVE
|
||||||
|
logger.info(f"Runmode set to {self.runmode}.")
|
||||||
|
|
||||||
|
config.update({'runmode': self.runmode})
|
||||||
|
|
||||||
|
def _args_to_config(self, config: Dict[str, Any], argname: str,
|
||||||
|
logstring: str, logfun: Optional[Callable] = None,
|
||||||
|
deprecated_msg: Optional[str] = None) -> None:
|
||||||
|
"""
|
||||||
|
:param config: Configuration dictionary
|
||||||
|
:param argname: Argumentname in self.args - will be copied to config dict.
|
||||||
|
:param logstring: Logging String
|
||||||
|
:param logfun: logfun is applied to the configuration entry before passing
|
||||||
|
that entry to the log string using .format().
|
||||||
|
sample: logfun=len (prints the length of the found
|
||||||
|
configuration instead of the content)
|
||||||
|
"""
|
||||||
|
if (argname in self.args and self.args[argname] is not None
|
||||||
|
and self.args[argname] is not False):
|
||||||
|
|
||||||
|
config.update({argname: self.args[argname]})
|
||||||
|
if logfun:
|
||||||
|
logger.info(logstring.format(logfun(config[argname])))
|
||||||
|
else:
|
||||||
|
logger.info(logstring.format(config[argname]))
|
||||||
|
if deprecated_msg:
|
||||||
|
warnings.warn(f"DEPRECATED: {deprecated_msg}", DeprecationWarning)
|
||||||
|
|
||||||
|
def _resolve_pairs_list(self, config: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Helper for download script.
|
||||||
|
Takes first found:
|
||||||
|
* -p (pairs argument)
|
||||||
|
* --pairs-file
|
||||||
|
* whitelist from config
|
||||||
|
"""
|
||||||
|
|
||||||
|
if "pairs" in config:
|
||||||
|
return
|
||||||
|
|
||||||
|
if "pairs_file" in self.args and self.args["pairs_file"]:
|
||||||
|
pairs_file = Path(self.args["pairs_file"])
|
||||||
|
logger.info(f'Reading pairs file "{pairs_file}".')
|
||||||
|
# Download pairs from the pairs file if no config is specified
|
||||||
|
# or if pairs file is specified explicitely
|
||||||
|
if not pairs_file.exists():
|
||||||
|
raise OperationalException(f'No pairs file found with path "{pairs_file}".')
|
||||||
|
with pairs_file.open('r') as f:
|
||||||
|
config['pairs'] = json_load(f)
|
||||||
|
config['pairs'].sort()
|
||||||
|
return
|
||||||
|
|
||||||
|
if "config" in self.args and self.args["config"]:
|
||||||
|
logger.info("Using pairlist from configuration.")
|
||||||
|
config['pairs'] = config.get('exchange', {}).get('pair_whitelist')
|
||||||
|
else:
|
||||||
|
# Fall back to /dl_path/pairs.json
|
||||||
|
pairs_file = Path(config['datadir']) / "pairs.json"
|
||||||
|
if pairs_file.exists():
|
||||||
|
with pairs_file.open('r') as f:
|
||||||
|
config['pairs'] = json_load(f)
|
||||||
|
if 'pairs' in config:
|
||||||
|
config['pairs'].sort()
|
||||||
59
freqtrade/configuration/deprecated_settings.py
Normal file
59
freqtrade/configuration/deprecated_settings.py
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
"""
|
||||||
|
Functions to handle deprecated settings
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any, Dict
|
||||||
|
|
||||||
|
from freqtrade import OperationalException
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def check_conflicting_settings(config: Dict[str, Any],
|
||||||
|
section1: str, name1: str,
|
||||||
|
section2: str, name2: str):
|
||||||
|
section1_config = config.get(section1, {})
|
||||||
|
section2_config = config.get(section2, {})
|
||||||
|
if name1 in section1_config and name2 in section2_config:
|
||||||
|
raise OperationalException(
|
||||||
|
f"Conflicting settings `{section1}.{name1}` and `{section2}.{name2}` "
|
||||||
|
"(DEPRECATED) detected in the configuration file. "
|
||||||
|
"This deprecated setting will be removed in the next versions of Freqtrade. "
|
||||||
|
f"Please delete it from your configuration and use the `{section1}.{name1}` "
|
||||||
|
"setting instead."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def process_deprecated_setting(config: Dict[str, Any],
|
||||||
|
section1: str, name1: str,
|
||||||
|
section2: str, name2: str):
|
||||||
|
section2_config = config.get(section2, {})
|
||||||
|
|
||||||
|
if name2 in section2_config:
|
||||||
|
logger.warning(
|
||||||
|
"DEPRECATED: "
|
||||||
|
f"The `{section2}.{name2}` setting is deprecated and "
|
||||||
|
"will be removed in the next versions of Freqtrade. "
|
||||||
|
f"Please use the `{section1}.{name1}` setting in your configuration instead."
|
||||||
|
)
|
||||||
|
section1_config = config.get(section1, {})
|
||||||
|
section1_config[name1] = section2_config[name2]
|
||||||
|
|
||||||
|
|
||||||
|
def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
check_conflicting_settings(config, 'ask_strategy', 'use_sell_signal',
|
||||||
|
'experimental', 'use_sell_signal')
|
||||||
|
check_conflicting_settings(config, 'ask_strategy', 'sell_profit_only',
|
||||||
|
'experimental', 'sell_profit_only')
|
||||||
|
check_conflicting_settings(config, 'ask_strategy', 'ignore_roi_if_buy_signal',
|
||||||
|
'experimental', 'ignore_roi_if_buy_signal')
|
||||||
|
|
||||||
|
process_deprecated_setting(config, 'ask_strategy', 'use_sell_signal',
|
||||||
|
'experimental', 'use_sell_signal')
|
||||||
|
process_deprecated_setting(config, 'ask_strategy', 'sell_profit_only',
|
||||||
|
'experimental', 'sell_profit_only')
|
||||||
|
process_deprecated_setting(config, 'ask_strategy', 'ignore_roi_if_buy_signal',
|
||||||
|
'experimental', 'ignore_roi_if_buy_signal')
|
||||||
50
freqtrade/configuration/directory_operations.py
Normal file
50
freqtrade/configuration/directory_operations.py
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import logging
|
||||||
|
from typing import Any, Dict, Optional
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from freqtrade import OperationalException
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def create_datadir(config: Dict[str, Any], datadir: Optional[str] = None) -> str:
|
||||||
|
|
||||||
|
folder = Path(datadir) if datadir else Path(f"{config['user_data_dir']}/data")
|
||||||
|
if not datadir:
|
||||||
|
# set datadir
|
||||||
|
exchange_name = config.get('exchange', {}).get('name').lower()
|
||||||
|
folder = folder.joinpath(exchange_name)
|
||||||
|
|
||||||
|
if not folder.is_dir():
|
||||||
|
folder.mkdir(parents=True)
|
||||||
|
logger.info(f'Created data directory: {datadir}')
|
||||||
|
return str(folder)
|
||||||
|
|
||||||
|
|
||||||
|
def create_userdata_dir(directory: str, create_dir=False) -> Path:
|
||||||
|
"""
|
||||||
|
Create userdata directory structure.
|
||||||
|
if create_dir is True, then the parent-directory will be created if it does not exist.
|
||||||
|
Sub-directories will always be created if the parent directory exists.
|
||||||
|
Raises OperationalException if given a non-existing directory.
|
||||||
|
:param directory: Directory to check
|
||||||
|
:param create_dir: Create directory if it does not exist.
|
||||||
|
:return: Path object containing the directory
|
||||||
|
"""
|
||||||
|
sub_dirs = ["backtest_results", "data", "hyperopts", "hyperopt_results", "plot", "strategies", ]
|
||||||
|
folder = Path(directory)
|
||||||
|
if not folder.is_dir():
|
||||||
|
if create_dir:
|
||||||
|
folder.mkdir(parents=True)
|
||||||
|
logger.info(f'Created user-data directory: {folder}')
|
||||||
|
else:
|
||||||
|
raise OperationalException(
|
||||||
|
f"Directory `{folder}` does not exist. "
|
||||||
|
"Please use `freqtrade create-userdir` to create a user directory")
|
||||||
|
|
||||||
|
# Create required subdirectories
|
||||||
|
for f in sub_dirs:
|
||||||
|
subfolder = folder / f
|
||||||
|
if not subfolder.is_dir():
|
||||||
|
subfolder.mkdir(parents=False)
|
||||||
|
return folder
|
||||||
33
freqtrade/configuration/load_config.py
Normal file
33
freqtrade/configuration/load_config.py
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
"""
|
||||||
|
This module contain functions to load the configuration file
|
||||||
|
"""
|
||||||
|
import rapidjson
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
from typing import Any, Dict
|
||||||
|
|
||||||
|
from freqtrade import OperationalException
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
CONFIG_PARSE_MODE = rapidjson.PM_COMMENTS | rapidjson.PM_TRAILING_COMMAS
|
||||||
|
|
||||||
|
|
||||||
|
def load_config_file(path: str) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Loads a config file from the given path
|
||||||
|
:param path: path as str
|
||||||
|
:return: configuration as dictionary
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# Read config from stdin if requested in the options
|
||||||
|
with open(path) if path != '-' else sys.stdin as file:
|
||||||
|
config = rapidjson.load(file, parse_mode=CONFIG_PARSE_MODE)
|
||||||
|
except FileNotFoundError:
|
||||||
|
raise OperationalException(
|
||||||
|
f'Config file "{path}" not found!'
|
||||||
|
' Please create a config file or check whether it exists.')
|
||||||
|
|
||||||
|
return config
|
||||||
75
freqtrade/configuration/timerange.py
Normal file
75
freqtrade/configuration/timerange.py
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
"""
|
||||||
|
This module contains the argument manager class
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import arrow
|
||||||
|
|
||||||
|
|
||||||
|
class TimeRange:
|
||||||
|
"""
|
||||||
|
object defining timerange inputs.
|
||||||
|
[start/stop]type defines if [start/stop]ts shall be used.
|
||||||
|
if *type is None, don't use corresponding startvalue.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, starttype: Optional[str] = None, stoptype: Optional[str] = None,
|
||||||
|
startts: int = 0, stopts: int = 0):
|
||||||
|
|
||||||
|
self.starttype: Optional[str] = starttype
|
||||||
|
self.stoptype: Optional[str] = stoptype
|
||||||
|
self.startts: int = startts
|
||||||
|
self.stopts: int = stopts
|
||||||
|
|
||||||
|
def __eq__(self, other):
|
||||||
|
"""Override the default Equals behavior"""
|
||||||
|
return (self.starttype == other.starttype and self.stoptype == other.stoptype
|
||||||
|
and self.startts == other.startts and self.stopts == other.stopts)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def parse_timerange(text: Optional[str]):
|
||||||
|
"""
|
||||||
|
Parse the value of the argument --timerange to determine what is the range desired
|
||||||
|
:param text: value from --timerange
|
||||||
|
:return: Start and End range period
|
||||||
|
"""
|
||||||
|
if text is None:
|
||||||
|
return TimeRange(None, None, 0, 0)
|
||||||
|
syntax = [(r'^-(\d{8})$', (None, 'date')),
|
||||||
|
(r'^(\d{8})-$', ('date', None)),
|
||||||
|
(r'^(\d{8})-(\d{8})$', ('date', 'date')),
|
||||||
|
(r'^-(\d{10})$', (None, 'date')),
|
||||||
|
(r'^(\d{10})-$', ('date', None)),
|
||||||
|
(r'^(\d{10})-(\d{10})$', ('date', 'date')),
|
||||||
|
(r'^-(\d{13})$', (None, 'date')),
|
||||||
|
(r'^(\d{13})-$', ('date', None)),
|
||||||
|
(r'^(\d{13})-(\d{13})$', ('date', 'date')),
|
||||||
|
]
|
||||||
|
for rex, stype in syntax:
|
||||||
|
# Apply the regular expression to text
|
||||||
|
match = re.match(rex, text)
|
||||||
|
if match: # Regex has matched
|
||||||
|
rvals = match.groups()
|
||||||
|
index = 0
|
||||||
|
start: int = 0
|
||||||
|
stop: int = 0
|
||||||
|
if stype[0]:
|
||||||
|
starts = rvals[index]
|
||||||
|
if stype[0] == 'date' and len(starts) == 8:
|
||||||
|
start = arrow.get(starts, 'YYYYMMDD').timestamp
|
||||||
|
elif len(starts) == 13:
|
||||||
|
start = int(starts) // 1000
|
||||||
|
else:
|
||||||
|
start = int(starts)
|
||||||
|
index += 1
|
||||||
|
if stype[1]:
|
||||||
|
stops = rvals[index]
|
||||||
|
if stype[1] == 'date' and len(stops) == 8:
|
||||||
|
stop = arrow.get(stops, 'YYYYMMDD').timestamp
|
||||||
|
elif len(stops) == 13:
|
||||||
|
stop = int(stops) // 1000
|
||||||
|
else:
|
||||||
|
stop = int(stops)
|
||||||
|
return TimeRange(stype[0], stype[1], start, stop)
|
||||||
|
raise Exception('Incorrect syntax for timerange "%s"' % text)
|
||||||
@@ -3,13 +3,15 @@
|
|||||||
"""
|
"""
|
||||||
bot constants
|
bot constants
|
||||||
"""
|
"""
|
||||||
DYNAMIC_WHITELIST = 20 # pairs
|
DEFAULT_CONFIG = 'config.json'
|
||||||
|
DEFAULT_EXCHANGE = 'bittrex'
|
||||||
PROCESS_THROTTLE_SECS = 5 # sec
|
PROCESS_THROTTLE_SECS = 5 # sec
|
||||||
TICKER_INTERVAL = 5 # min
|
DEFAULT_TICKER_INTERVAL = 5 # min
|
||||||
HYPEROPT_EPOCH = 100 # epochs
|
HYPEROPT_EPOCH = 100 # epochs
|
||||||
RETRY_TIMEOUT = 30 # sec
|
RETRY_TIMEOUT = 30 # sec
|
||||||
DEFAULT_STRATEGY = 'DefaultStrategy'
|
DEFAULT_STRATEGY = 'DefaultStrategy'
|
||||||
DEFAULT_HYPEROPT = 'DefaultHyperOpts'
|
DEFAULT_HYPEROPT = 'DefaultHyperOpt'
|
||||||
|
DEFAULT_HYPEROPT_LOSS = 'DefaultHyperOptLoss'
|
||||||
DEFAULT_DB_PROD_URL = 'sqlite:///tradesv3.sqlite'
|
DEFAULT_DB_PROD_URL = 'sqlite:///tradesv3.sqlite'
|
||||||
DEFAULT_DB_DRYRUN_URL = 'sqlite://'
|
DEFAULT_DB_DRYRUN_URL = 'sqlite://'
|
||||||
UNLIMITED_STAKE_AMOUNT = 'unlimited'
|
UNLIMITED_STAKE_AMOUNT = 'unlimited'
|
||||||
@@ -19,23 +21,14 @@ REQUIRED_ORDERTYPES = ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
|||||||
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
||||||
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
||||||
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList']
|
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList']
|
||||||
|
DRY_RUN_WALLET = 999.9
|
||||||
|
MATH_CLOSE_PREC = 1e-14 # Precision used for float comparisons
|
||||||
|
|
||||||
TICKER_INTERVAL_MINUTES = {
|
TICKER_INTERVALS = [
|
||||||
'1m': 1,
|
'1m', '3m', '5m', '15m', '30m',
|
||||||
'3m': 3,
|
'1h', '2h', '4h', '6h', '8h', '12h',
|
||||||
'5m': 5,
|
'1d', '3d', '1w',
|
||||||
'15m': 15,
|
]
|
||||||
'30m': 30,
|
|
||||||
'1h': 60,
|
|
||||||
'2h': 120,
|
|
||||||
'4h': 240,
|
|
||||||
'6h': 360,
|
|
||||||
'8h': 480,
|
|
||||||
'12h': 720,
|
|
||||||
'1d': 1440,
|
|
||||||
'3d': 4320,
|
|
||||||
'1w': 10080,
|
|
||||||
}
|
|
||||||
|
|
||||||
SUPPORTED_FIAT = [
|
SUPPORTED_FIAT = [
|
||||||
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK",
|
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK",
|
||||||
@@ -45,12 +38,26 @@ SUPPORTED_FIAT = [
|
|||||||
"BTC", "XBT", "ETH", "XRP", "LTC", "BCH", "USDT"
|
"BTC", "XBT", "ETH", "XRP", "LTC", "BCH", "USDT"
|
||||||
]
|
]
|
||||||
|
|
||||||
|
MINIMAL_CONFIG = {
|
||||||
|
'stake_currency': '',
|
||||||
|
'dry_run': True,
|
||||||
|
'exchange': {
|
||||||
|
'name': '',
|
||||||
|
'key': '',
|
||||||
|
'secret': '',
|
||||||
|
'pair_whitelist': [],
|
||||||
|
'ccxt_async_config': {
|
||||||
|
'enableRateLimit': True,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
# Required json-schema for user specified config
|
# Required json-schema for user specified config
|
||||||
CONF_SCHEMA = {
|
CONF_SCHEMA = {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'max_open_trades': {'type': 'integer', 'minimum': -1},
|
'max_open_trades': {'type': 'integer', 'minimum': -1},
|
||||||
'ticker_interval': {'type': 'string', 'enum': list(TICKER_INTERVAL_MINUTES.keys())},
|
'ticker_interval': {'type': 'string', 'enum': TICKER_INTERVALS},
|
||||||
'stake_currency': {'type': 'string', 'enum': ['BTC', 'XBT', 'ETH', 'USDT', 'EUR', 'USD']},
|
'stake_currency': {'type': 'string', 'enum': ['BTC', 'XBT', 'ETH', 'USDT', 'EUR', 'USD']},
|
||||||
'stake_amount': {
|
'stake_amount': {
|
||||||
"type": ["number", "string"],
|
"type": ["number", "string"],
|
||||||
@@ -59,6 +66,7 @@ CONF_SCHEMA = {
|
|||||||
},
|
},
|
||||||
'fiat_display_currency': {'type': 'string', 'enum': SUPPORTED_FIAT},
|
'fiat_display_currency': {'type': 'string', 'enum': SUPPORTED_FIAT},
|
||||||
'dry_run': {'type': 'boolean'},
|
'dry_run': {'type': 'boolean'},
|
||||||
|
'dry_run_wallet': {'type': 'number'},
|
||||||
'process_only_new_candles': {'type': 'boolean'},
|
'process_only_new_candles': {'type': 'boolean'},
|
||||||
'minimal_roi': {
|
'minimal_roi': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
@@ -67,10 +75,12 @@ CONF_SCHEMA = {
|
|||||||
},
|
},
|
||||||
'minProperties': 1
|
'minProperties': 1
|
||||||
},
|
},
|
||||||
|
'amount_reserve_percent': {'type': 'number', 'minimum': 0.0, 'maximum': 0.5},
|
||||||
'stoploss': {'type': 'number', 'maximum': 0, 'exclusiveMaximum': True},
|
'stoploss': {'type': 'number', 'maximum': 0, 'exclusiveMaximum': True},
|
||||||
'trailing_stop': {'type': 'boolean'},
|
'trailing_stop': {'type': 'boolean'},
|
||||||
'trailing_stop_positive': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
'trailing_stop_positive': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
||||||
'trailing_stop_positive_offset': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
'trailing_stop_positive_offset': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
||||||
|
'trailing_only_offset_is_reached': {'type': 'boolean'},
|
||||||
'unfilledtimeout': {
|
'unfilledtimeout': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
@@ -104,7 +114,10 @@ CONF_SCHEMA = {
|
|||||||
'properties': {
|
'properties': {
|
||||||
'use_order_book': {'type': 'boolean'},
|
'use_order_book': {'type': 'boolean'},
|
||||||
'order_book_min': {'type': 'number', 'minimum': 1},
|
'order_book_min': {'type': 'number', 'minimum': 1},
|
||||||
'order_book_max': {'type': 'number', 'minimum': 1, 'maximum': 50}
|
'order_book_max': {'type': 'number', 'minimum': 1, 'maximum': 50},
|
||||||
|
'use_sell_signal': {'type': 'boolean'},
|
||||||
|
'sell_profit_only': {'type': 'boolean'},
|
||||||
|
'ignore_roi_if_buy_signal': {'type': 'boolean'}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
'order_types': {
|
'order_types': {
|
||||||
@@ -112,6 +125,7 @@ CONF_SCHEMA = {
|
|||||||
'properties': {
|
'properties': {
|
||||||
'buy': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
'buy': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||||
'sell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
'sell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||||
|
'emergencysell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||||
'stoploss': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
'stoploss': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||||
'stoploss_on_exchange': {'type': 'boolean'},
|
'stoploss_on_exchange': {'type': 'boolean'},
|
||||||
'stoploss_on_exchange_interval': {'type': 'number'}
|
'stoploss_on_exchange_interval': {'type': 'number'}
|
||||||
@@ -133,7 +147,8 @@ CONF_SCHEMA = {
|
|||||||
'properties': {
|
'properties': {
|
||||||
'use_sell_signal': {'type': 'boolean'},
|
'use_sell_signal': {'type': 'boolean'},
|
||||||
'sell_profit_only': {'type': 'boolean'},
|
'sell_profit_only': {'type': 'boolean'},
|
||||||
'ignore_roi_if_buy_signal_true': {'type': 'boolean'}
|
'ignore_roi_if_buy_signal': {'type': 'boolean'},
|
||||||
|
'block_bad_exchanges': {'type': 'boolean'}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
'pairlist': {
|
'pairlist': {
|
||||||
@@ -162,6 +177,21 @@ CONF_SCHEMA = {
|
|||||||
'webhookstatus': {'type': 'object'},
|
'webhookstatus': {'type': 'object'},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
'api_server': {
|
||||||
|
'type': 'object',
|
||||||
|
'properties': {
|
||||||
|
'enabled': {'type': 'boolean'},
|
||||||
|
'listen_ip_address': {'format': 'ipv4'},
|
||||||
|
'listen_port': {
|
||||||
|
'type': 'integer',
|
||||||
|
"minimum": 1024,
|
||||||
|
"maximum": 65535
|
||||||
|
},
|
||||||
|
'username': {'type': 'string'},
|
||||||
|
'password': {'type': 'string'},
|
||||||
|
},
|
||||||
|
'required': ['enabled', 'listen_ip_address', 'listen_port', 'username', 'password']
|
||||||
|
},
|
||||||
'db_url': {'type': 'string'},
|
'db_url': {'type': 'string'},
|
||||||
'initial_state': {'type': 'string', 'enum': ['running', 'stopped']},
|
'initial_state': {'type': 'string', 'enum': ['running', 'stopped']},
|
||||||
'forcebuy_enable': {'type': 'boolean'},
|
'forcebuy_enable': {'type': 'boolean'},
|
||||||
@@ -169,7 +199,8 @@ CONF_SCHEMA = {
|
|||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'process_throttle_secs': {'type': 'number'},
|
'process_throttle_secs': {'type': 'number'},
|
||||||
'interval': {'type': 'integer'}
|
'interval': {'type': 'integer'},
|
||||||
|
'sd_notify': {'type': 'boolean'},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -178,10 +209,10 @@ CONF_SCHEMA = {
|
|||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'name': {'type': 'string'},
|
'name': {'type': 'string'},
|
||||||
'sandbox': {'type': 'boolean'},
|
'sandbox': {'type': 'boolean', 'default': False},
|
||||||
'key': {'type': 'string'},
|
'key': {'type': 'string', 'default': ''},
|
||||||
'secret': {'type': 'string'},
|
'secret': {'type': 'string', 'default': ''},
|
||||||
'password': {'type': 'string'},
|
'password': {'type': 'string', 'default': ''},
|
||||||
'uid': {'type': 'string'},
|
'uid': {'type': 'string'},
|
||||||
'pair_whitelist': {
|
'pair_whitelist': {
|
||||||
'type': 'array',
|
'type': 'array',
|
||||||
@@ -200,10 +231,11 @@ CONF_SCHEMA = {
|
|||||||
'uniqueItems': True
|
'uniqueItems': True
|
||||||
},
|
},
|
||||||
'outdated_offset': {'type': 'integer', 'minimum': 1},
|
'outdated_offset': {'type': 'integer', 'minimum': 1},
|
||||||
|
'markets_refresh_interval': {'type': 'integer'},
|
||||||
'ccxt_config': {'type': 'object'},
|
'ccxt_config': {'type': 'object'},
|
||||||
'ccxt_async_config': {'type': 'object'}
|
'ccxt_async_config': {'type': 'object'}
|
||||||
},
|
},
|
||||||
'required': ['name', 'key', 'secret', 'pair_whitelist']
|
'required': ['name', 'pair_whitelist']
|
||||||
},
|
},
|
||||||
'edge': {
|
'edge': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
@@ -234,6 +266,6 @@ CONF_SCHEMA = {
|
|||||||
'stake_amount',
|
'stake_amount',
|
||||||
'dry_run',
|
'dry_run',
|
||||||
'bid_strategy',
|
'bid_strategy',
|
||||||
'telegram'
|
'unfilledtimeout',
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
Module to handle data operations for freqtrade
|
Module to handle data operations for freqtrade
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# limit what's imported when using `from freqtrad.data import *``
|
# limit what's imported when using `from freqtrade.data import *`
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'converter'
|
'converter'
|
||||||
]
|
]
|
||||||
|
|||||||
172
freqtrade/data/btanalysis.py
Normal file
172
freqtrade/data/btanalysis.py
Normal file
@@ -0,0 +1,172 @@
|
|||||||
|
"""
|
||||||
|
Helpers when analyzing backtest data
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
import pytz
|
||||||
|
|
||||||
|
from freqtrade import persistence
|
||||||
|
from freqtrade.misc import json_load
|
||||||
|
from freqtrade.persistence import Trade
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# must align with columns in backtest.py
|
||||||
|
BT_DATA_COLUMNS = ["pair", "profitperc", "open_time", "close_time", "index", "duration",
|
||||||
|
"open_rate", "close_rate", "open_at_end", "sell_reason"]
|
||||||
|
|
||||||
|
|
||||||
|
def load_backtest_data(filename) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Load backtest data file.
|
||||||
|
:param filename: pathlib.Path object, or string pointing to the file.
|
||||||
|
:return: a dataframe with the analysis results
|
||||||
|
"""
|
||||||
|
if isinstance(filename, str):
|
||||||
|
filename = Path(filename)
|
||||||
|
|
||||||
|
if not filename.is_file():
|
||||||
|
raise ValueError(f"File {filename} does not exist.")
|
||||||
|
|
||||||
|
with filename.open() as file:
|
||||||
|
data = json_load(file)
|
||||||
|
|
||||||
|
df = pd.DataFrame(data, columns=BT_DATA_COLUMNS)
|
||||||
|
|
||||||
|
df['open_time'] = pd.to_datetime(df['open_time'],
|
||||||
|
unit='s',
|
||||||
|
utc=True,
|
||||||
|
infer_datetime_format=True
|
||||||
|
)
|
||||||
|
df['close_time'] = pd.to_datetime(df['close_time'],
|
||||||
|
unit='s',
|
||||||
|
utc=True,
|
||||||
|
infer_datetime_format=True
|
||||||
|
)
|
||||||
|
df['profitabs'] = df['close_rate'] - df['open_rate']
|
||||||
|
df = df.sort_values("open_time").reset_index(drop=True)
|
||||||
|
return df
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_result_multi(results: pd.DataFrame, freq: str, max_open_trades: int) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Find overlapping trades by expanding each trade once per period it was open
|
||||||
|
and then counting overlaps
|
||||||
|
:param results: Results Dataframe - can be loaded
|
||||||
|
:param freq: Frequency used for the backtest
|
||||||
|
:param max_open_trades: parameter max_open_trades used during backtest run
|
||||||
|
:return: dataframe with open-counts per time-period in freq
|
||||||
|
"""
|
||||||
|
dates = [pd.Series(pd.date_range(row[1].open_time, row[1].close_time, freq=freq))
|
||||||
|
for row in results[['open_time', 'close_time']].iterrows()]
|
||||||
|
deltas = [len(x) for x in dates]
|
||||||
|
dates = pd.Series(pd.concat(dates).values, name='date')
|
||||||
|
df2 = pd.DataFrame(np.repeat(results.values, deltas, axis=0), columns=results.columns)
|
||||||
|
|
||||||
|
df2 = pd.concat([dates, df2], axis=1)
|
||||||
|
df2 = df2.set_index('date')
|
||||||
|
df_final = df2.resample(freq)[['pair']].count()
|
||||||
|
return df_final[df_final['pair'] > max_open_trades]
|
||||||
|
|
||||||
|
|
||||||
|
def load_trades_from_db(db_url: str) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Load trades from a DB (using dburl)
|
||||||
|
:param db_url: Sqlite url (default format sqlite:///tradesv3.dry-run.sqlite)
|
||||||
|
:return: Dataframe containing Trades
|
||||||
|
"""
|
||||||
|
trades: pd.DataFrame = pd.DataFrame([], columns=BT_DATA_COLUMNS)
|
||||||
|
persistence.init(db_url, clean_open_orders=False)
|
||||||
|
|
||||||
|
columns = ["pair", "open_time", "close_time", "profit", "profitperc",
|
||||||
|
"open_rate", "close_rate", "amount", "duration", "sell_reason",
|
||||||
|
"fee_open", "fee_close", "open_rate_requested", "close_rate_requested",
|
||||||
|
"stake_amount", "max_rate", "min_rate", "id", "exchange",
|
||||||
|
"stop_loss", "initial_stop_loss", "strategy", "ticker_interval"]
|
||||||
|
|
||||||
|
trades = pd.DataFrame([(t.pair,
|
||||||
|
t.open_date.replace(tzinfo=pytz.UTC),
|
||||||
|
t.close_date.replace(tzinfo=pytz.UTC) if t.close_date else None,
|
||||||
|
t.calc_profit(), t.calc_profit_percent(),
|
||||||
|
t.open_rate, t.close_rate, t.amount,
|
||||||
|
(round((t.close_date.timestamp() - t.open_date.timestamp()) / 60, 2)
|
||||||
|
if t.close_date else None),
|
||||||
|
t.sell_reason,
|
||||||
|
t.fee_open, t.fee_close,
|
||||||
|
t.open_rate_requested,
|
||||||
|
t.close_rate_requested,
|
||||||
|
t.stake_amount,
|
||||||
|
t.max_rate,
|
||||||
|
t.min_rate,
|
||||||
|
t.id, t.exchange,
|
||||||
|
t.stop_loss, t.initial_stop_loss,
|
||||||
|
t.strategy, t.ticker_interval
|
||||||
|
)
|
||||||
|
for t in Trade.query.all()],
|
||||||
|
columns=columns)
|
||||||
|
|
||||||
|
return trades
|
||||||
|
|
||||||
|
|
||||||
|
def load_trades(source: str, db_url: str, exportfilename: str) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Based on configuration option "trade_source":
|
||||||
|
* loads data from DB (using `db_url`)
|
||||||
|
* loads data from backtestfile (using `exportfilename`)
|
||||||
|
"""
|
||||||
|
if source == "DB":
|
||||||
|
return load_trades_from_db(db_url)
|
||||||
|
elif source == "file":
|
||||||
|
return load_backtest_data(Path(exportfilename))
|
||||||
|
|
||||||
|
|
||||||
|
def extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Compare trades and backtested pair DataFrames to get trades performed on backtested period
|
||||||
|
:return: the DataFrame of a trades of period
|
||||||
|
"""
|
||||||
|
trades = trades.loc[(trades['open_time'] >= dataframe.iloc[0]['date']) &
|
||||||
|
(trades['close_time'] <= dataframe.iloc[-1]['date'])]
|
||||||
|
return trades
|
||||||
|
|
||||||
|
|
||||||
|
def combine_tickers_with_mean(tickers: Dict[str, pd.DataFrame], column: str = "close"):
|
||||||
|
"""
|
||||||
|
Combine multiple dataframes "column"
|
||||||
|
:param tickers: Dict of Dataframes, dict key should be pair.
|
||||||
|
:param column: Column in the original dataframes to use
|
||||||
|
:return: DataFrame with the column renamed to the dict key, and a column
|
||||||
|
named mean, containing the mean of all pairs.
|
||||||
|
"""
|
||||||
|
df_comb = pd.concat([tickers[pair].set_index('date').rename(
|
||||||
|
{column: pair}, axis=1)[pair] for pair in tickers], axis=1)
|
||||||
|
|
||||||
|
df_comb['mean'] = df_comb.mean(axis=1)
|
||||||
|
|
||||||
|
return df_comb
|
||||||
|
|
||||||
|
|
||||||
|
def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str,
|
||||||
|
timeframe: str) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Adds a column `col_name` with the cumulative profit for the given trades array.
|
||||||
|
:param df: DataFrame with date index
|
||||||
|
:param trades: DataFrame containing trades (requires columns close_time and profitperc)
|
||||||
|
:param col_name: Column name that will be assigned the results
|
||||||
|
:param timeframe: Timeframe used during the operations
|
||||||
|
:return: Returns df with one additional column, col_name, containing the cumulative profit.
|
||||||
|
"""
|
||||||
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
ticker_minutes = timeframe_to_minutes(timeframe)
|
||||||
|
# Resample to ticker_interval to make sure trades match candles
|
||||||
|
_trades_sum = trades.resample(f'{ticker_minutes}min', on='close_time')[['profitperc']].sum()
|
||||||
|
df.loc[:, col_name] = _trades_sum.cumsum()
|
||||||
|
# Set first value to 0
|
||||||
|
df.loc[df.iloc[0].name, col_name] = 0
|
||||||
|
# FFill to get continuous
|
||||||
|
df[col_name] = df[col_name].ffill()
|
||||||
|
return df
|
||||||
@@ -2,22 +2,25 @@
|
|||||||
Functions to convert data from one format to another
|
Functions to convert data from one format to another
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from pandas import DataFrame, to_datetime
|
from pandas import DataFrame, to_datetime
|
||||||
|
|
||||||
from freqtrade.constants import TICKER_INTERVAL_MINUTES
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def parse_ticker_dataframe(ticker: list, ticker_interval: str,
|
def parse_ticker_dataframe(ticker: list, ticker_interval: str, pair: str, *,
|
||||||
fill_missing: bool = True) -> DataFrame:
|
fill_missing: bool = True,
|
||||||
|
drop_incomplete: bool = True) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Converts a ticker-list (format ccxt.fetch_ohlcv) to a Dataframe
|
Converts a ticker-list (format ccxt.fetch_ohlcv) to a Dataframe
|
||||||
:param ticker: ticker list, as returned by exchange.async_get_candle_history
|
:param ticker: ticker list, as returned by exchange.async_get_candle_history
|
||||||
:param ticker_interval: ticker_interval (e.g. 5m). Used to fill up eventual missing data
|
:param ticker_interval: ticker_interval (e.g. 5m). Used to fill up eventual missing data
|
||||||
|
:param pair: Pair this data is for (used to warn if fillup was necessary)
|
||||||
:param fill_missing: fill up missing candles with 0 candles
|
:param fill_missing: fill up missing candles with 0 candles
|
||||||
(see ohlcv_fill_up_missing_data for details)
|
(see ohlcv_fill_up_missing_data for details)
|
||||||
|
:param drop_incomplete: Drop the last candle of the dataframe, assuming it's incomplete
|
||||||
:return: DataFrame
|
:return: DataFrame
|
||||||
"""
|
"""
|
||||||
logger.debug("Parsing tickerlist to dataframe")
|
logger.debug("Parsing tickerlist to dataframe")
|
||||||
@@ -43,21 +46,25 @@ def parse_ticker_dataframe(ticker: list, ticker_interval: str,
|
|||||||
'close': 'last',
|
'close': 'last',
|
||||||
'volume': 'max',
|
'volume': 'max',
|
||||||
})
|
})
|
||||||
frame.drop(frame.tail(1).index, inplace=True) # eliminate partial candle
|
# eliminate partial candle
|
||||||
logger.debug('Dropping last candle')
|
if drop_incomplete:
|
||||||
|
frame.drop(frame.tail(1).index, inplace=True)
|
||||||
|
logger.debug('Dropping last candle')
|
||||||
|
|
||||||
if fill_missing:
|
if fill_missing:
|
||||||
return ohlcv_fill_up_missing_data(frame, ticker_interval)
|
return ohlcv_fill_up_missing_data(frame, ticker_interval, pair)
|
||||||
else:
|
else:
|
||||||
return frame
|
return frame
|
||||||
|
|
||||||
|
|
||||||
def ohlcv_fill_up_missing_data(dataframe: DataFrame, ticker_interval: str) -> DataFrame:
|
def ohlcv_fill_up_missing_data(dataframe: DataFrame, ticker_interval: str, pair: str) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Fills up missing data with 0 volume rows,
|
Fills up missing data with 0 volume rows,
|
||||||
using the previous close as price for "open", "high" "low" and "close", volume is set to 0
|
using the previous close as price for "open", "high" "low" and "close", volume is set to 0
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
|
||||||
ohlc_dict = {
|
ohlc_dict = {
|
||||||
'open': 'first',
|
'open': 'first',
|
||||||
'high': 'max',
|
'high': 'max',
|
||||||
@@ -65,9 +72,9 @@ def ohlcv_fill_up_missing_data(dataframe: DataFrame, ticker_interval: str) -> Da
|
|||||||
'close': 'last',
|
'close': 'last',
|
||||||
'volume': 'sum'
|
'volume': 'sum'
|
||||||
}
|
}
|
||||||
tick_mins = TICKER_INTERVAL_MINUTES[ticker_interval]
|
ticker_minutes = timeframe_to_minutes(ticker_interval)
|
||||||
# Resample to create "NAN" values
|
# Resample to create "NAN" values
|
||||||
df = dataframe.resample(f'{tick_mins}min', on='date').agg(ohlc_dict)
|
df = dataframe.resample(f'{ticker_minutes}min', on='date').agg(ohlc_dict)
|
||||||
|
|
||||||
# Forwardfill close for missing columns
|
# Forwardfill close for missing columns
|
||||||
df['close'] = df['close'].fillna(method='ffill')
|
df['close'] = df['close'].fillna(method='ffill')
|
||||||
@@ -78,7 +85,10 @@ def ohlcv_fill_up_missing_data(dataframe: DataFrame, ticker_interval: str) -> Da
|
|||||||
'low': df['close'],
|
'low': df['close'],
|
||||||
})
|
})
|
||||||
df.reset_index(inplace=True)
|
df.reset_index(inplace=True)
|
||||||
logger.debug(f"Missing data fillup: before: {len(dataframe)} - after: {len(df)}")
|
len_before = len(dataframe)
|
||||||
|
len_after = len(df)
|
||||||
|
if len_before != len_after:
|
||||||
|
logger.info(f"Missing data fillup for {pair}: before: {len_before} - after: {len_after}")
|
||||||
return df
|
return df
|
||||||
|
|
||||||
|
|
||||||
@@ -104,3 +114,25 @@ def order_book_to_dataframe(bids: list, asks: list) -> DataFrame:
|
|||||||
keys=['b_sum', 'b_size', 'bids', 'asks', 'a_size', 'a_sum'])
|
keys=['b_sum', 'b_size', 'bids', 'asks', 'a_size', 'a_sum'])
|
||||||
# logger.info('order book %s', frame )
|
# logger.info('order book %s', frame )
|
||||||
return frame
|
return frame
|
||||||
|
|
||||||
|
|
||||||
|
def trades_to_ohlcv(trades: list, timeframe: str) -> list:
|
||||||
|
"""
|
||||||
|
Converts trades list to ohlcv list
|
||||||
|
:param trades: List of trades, as returned by ccxt.fetch_trades.
|
||||||
|
:param timeframe: Ticker timeframe to resample data to
|
||||||
|
:return: ohlcv timeframe as list (as returned by ccxt.fetch_ohlcv)
|
||||||
|
"""
|
||||||
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
ticker_minutes = timeframe_to_minutes(timeframe)
|
||||||
|
df = pd.DataFrame(trades)
|
||||||
|
df['datetime'] = pd.to_datetime(df['datetime'])
|
||||||
|
df = df.set_index('datetime')
|
||||||
|
|
||||||
|
df_new = df['price'].resample(f'{ticker_minutes}min').ohlc()
|
||||||
|
df_new['volume'] = df['amount'].resample(f'{ticker_minutes}min').sum()
|
||||||
|
df_new['date'] = df_new.index.astype("int64") // 10 ** 6
|
||||||
|
# Drop 0 volume rows
|
||||||
|
df_new = df_new.dropna()
|
||||||
|
columns = ["date", "open", "high", "low", "close", "volume"]
|
||||||
|
return list(zip(*[df_new[x].values.tolist() for x in columns]))
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Common Interface for bot and strategy to access data.
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import List, Tuple
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@ from freqtrade.state import RunMode
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class DataProvider(object):
|
class DataProvider:
|
||||||
|
|
||||||
def __init__(self, config: dict, exchange: Exchange) -> None:
|
def __init__(self, config: dict, exchange: Exchange) -> None:
|
||||||
self._config = config
|
self._config = config
|
||||||
@@ -37,43 +37,62 @@ class DataProvider(object):
|
|||||||
@property
|
@property
|
||||||
def available_pairs(self) -> List[Tuple[str, str]]:
|
def available_pairs(self) -> List[Tuple[str, str]]:
|
||||||
"""
|
"""
|
||||||
Return a list of tuples containing pair, tick_interval for which data is currently cached.
|
Return a list of tuples containing pair, ticker_interval for which data is currently cached.
|
||||||
Should be whitelist + open trades.
|
Should be whitelist + open trades.
|
||||||
"""
|
"""
|
||||||
return list(self._exchange._klines.keys())
|
return list(self._exchange._klines.keys())
|
||||||
|
|
||||||
def ohlcv(self, pair: str, tick_interval: str = None, copy: bool = True) -> DataFrame:
|
def ohlcv(self, pair: str, ticker_interval: str = None, copy: bool = True) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
get ohlcv data for the given pair as DataFrame
|
Get ohlcv data for the given pair as DataFrame
|
||||||
Please check `available_pairs` to verify which pairs are currently cached.
|
Please use the `available_pairs` method to verify which pairs are currently cached.
|
||||||
:param pair: pair to get the data for
|
:param pair: pair to get the data for
|
||||||
:param tick_interval: ticker_interval to get pair for
|
:param ticker_interval: ticker interval to get data for
|
||||||
:param copy: copy dataframe before returning.
|
:param copy: copy dataframe before returning if True.
|
||||||
Use false only for RO operations (where the dataframe is not modified)
|
Use False only for read-only operations (where the dataframe is not modified)
|
||||||
"""
|
"""
|
||||||
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
||||||
if tick_interval:
|
return self._exchange.klines((pair, ticker_interval or self._config['ticker_interval']),
|
||||||
pairtick = (pair, tick_interval)
|
copy=copy)
|
||||||
else:
|
|
||||||
pairtick = (pair, self._config['ticker_interval'])
|
|
||||||
|
|
||||||
return self._exchange.klines(pairtick, copy=copy)
|
|
||||||
else:
|
else:
|
||||||
return DataFrame()
|
return DataFrame()
|
||||||
|
|
||||||
def historic_ohlcv(self, pair: str, ticker_interval: str) -> DataFrame:
|
def historic_ohlcv(self, pair: str, ticker_interval: str = None) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
get stored historic ohlcv data
|
Get stored historic ohlcv data
|
||||||
:param pair: pair to get the data for
|
:param pair: pair to get the data for
|
||||||
:param tick_interval: ticker_interval to get pair for
|
:param ticker_interval: ticker interval to get data for
|
||||||
"""
|
"""
|
||||||
return load_pair_history(pair=pair,
|
return load_pair_history(pair=pair,
|
||||||
ticker_interval=ticker_interval,
|
ticker_interval=ticker_interval or self._config['ticker_interval'],
|
||||||
refresh_pairs=False,
|
datadir=Path(self._config['datadir'])
|
||||||
datadir=Path(self._config['datadir']) if self._config.get(
|
|
||||||
'datadir') else None
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def get_pair_dataframe(self, pair: str, ticker_interval: str = None) -> DataFrame:
|
||||||
|
"""
|
||||||
|
Return pair ohlcv data, either live or cached historical -- depending
|
||||||
|
on the runmode.
|
||||||
|
:param pair: pair to get the data for
|
||||||
|
:param ticker_interval: ticker interval to get data for
|
||||||
|
"""
|
||||||
|
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
||||||
|
# Get live ohlcv data.
|
||||||
|
data = self.ohlcv(pair=pair, ticker_interval=ticker_interval)
|
||||||
|
else:
|
||||||
|
# Get historic ohlcv data (cached on disk).
|
||||||
|
data = self.historic_ohlcv(pair=pair, ticker_interval=ticker_interval)
|
||||||
|
if len(data) == 0:
|
||||||
|
logger.warning(f"No data found for ({pair}, {ticker_interval}).")
|
||||||
|
return data
|
||||||
|
|
||||||
|
def market(self, pair: str) -> Optional[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Return market data for the pair
|
||||||
|
:param pair: Pair to get the data for
|
||||||
|
:return: Market data dict from ccxt or None if market info is not available for the pair
|
||||||
|
"""
|
||||||
|
return self._exchange.markets.get(pair)
|
||||||
|
|
||||||
def ticker(self, pair: str):
|
def ticker(self, pair: str):
|
||||||
"""
|
"""
|
||||||
Return last ticker data
|
Return last ticker data
|
||||||
@@ -81,12 +100,14 @@ class DataProvider(object):
|
|||||||
# TODO: Implement me
|
# TODO: Implement me
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def orderbook(self, pair: str, max: int):
|
def orderbook(self, pair: str, maximum: int) -> Dict[str, List]:
|
||||||
"""
|
"""
|
||||||
return latest orderbook data
|
fetch latest orderbook data
|
||||||
|
:param pair: pair to get the data for
|
||||||
|
:param maximum: Maximum number of orderbook entries to query
|
||||||
|
:return: dict including bids/asks with a total of `maximum` entries.
|
||||||
"""
|
"""
|
||||||
# TODO: Implement me
|
return self._exchange.get_order_book(pair, maximum)
|
||||||
pass
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def runmode(self) -> RunMode:
|
def runmode(self) -> RunMode:
|
||||||
|
|||||||
@@ -1,21 +1,24 @@
|
|||||||
"""
|
"""
|
||||||
Handle historic data (ohlcv).
|
Handle historic data (ohlcv).
|
||||||
includes:
|
|
||||||
|
Includes:
|
||||||
* load data for a pair (or a list of pairs) from disk
|
* load data for a pair (or a list of pairs) from disk
|
||||||
* download data from exchange and store to disk
|
* download data from exchange and store to disk
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import operator
|
||||||
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional, List, Dict, Tuple, Any
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
import arrow
|
import arrow
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
from freqtrade import misc, constants, OperationalException
|
from freqtrade import OperationalException, misc
|
||||||
from freqtrade.data.converter import parse_ticker_dataframe
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.data.converter import parse_ticker_dataframe, trades_to_ohlcv
|
||||||
from freqtrade.arguments import TimeRange
|
from freqtrade.exchange import Exchange, timeframe_to_minutes
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -30,20 +33,12 @@ def trim_tickerlist(tickerlist: List[Dict], timerange: TimeRange) -> List[Dict]:
|
|||||||
start_index = 0
|
start_index = 0
|
||||||
stop_index = len(tickerlist)
|
stop_index = len(tickerlist)
|
||||||
|
|
||||||
if timerange.starttype == 'line':
|
if timerange.starttype == 'date':
|
||||||
stop_index = timerange.startts
|
|
||||||
if timerange.starttype == 'index':
|
|
||||||
start_index = timerange.startts
|
|
||||||
elif timerange.starttype == 'date':
|
|
||||||
while (start_index < len(tickerlist) and
|
while (start_index < len(tickerlist) and
|
||||||
tickerlist[start_index][0] < timerange.startts * 1000):
|
tickerlist[start_index][0] < timerange.startts * 1000):
|
||||||
start_index += 1
|
start_index += 1
|
||||||
|
|
||||||
if timerange.stoptype == 'line':
|
if timerange.stoptype == 'date':
|
||||||
start_index = len(tickerlist) + timerange.stopts
|
|
||||||
if timerange.stoptype == 'index':
|
|
||||||
stop_index = timerange.stopts
|
|
||||||
elif timerange.stoptype == 'date':
|
|
||||||
while (stop_index > 0 and
|
while (stop_index > 0 and
|
||||||
tickerlist[stop_index-1][0] > timerange.stopts * 1000):
|
tickerlist[stop_index-1][0] > timerange.stopts * 1000):
|
||||||
stop_index -= 1
|
stop_index -= 1
|
||||||
@@ -54,84 +49,127 @@ def trim_tickerlist(tickerlist: List[Dict], timerange: TimeRange) -> List[Dict]:
|
|||||||
return tickerlist[start_index:stop_index]
|
return tickerlist[start_index:stop_index]
|
||||||
|
|
||||||
|
|
||||||
def load_tickerdata_file(
|
def load_tickerdata_file(datadir: Path, pair: str, ticker_interval: str,
|
||||||
datadir: Optional[Path], pair: str,
|
timerange: Optional[TimeRange] = None) -> Optional[list]:
|
||||||
ticker_interval: str,
|
|
||||||
timerange: Optional[TimeRange] = None) -> Optional[list]:
|
|
||||||
"""
|
"""
|
||||||
Load a pair from file, either .json.gz or .json
|
Load a pair from file, either .json.gz or .json
|
||||||
:return tickerlist or None if unsuccesful
|
:return: tickerlist or None if unsuccessful
|
||||||
"""
|
"""
|
||||||
path = make_testdata_path(datadir)
|
filename = pair_data_filename(datadir, pair, ticker_interval)
|
||||||
pair_s = pair.replace('/', '_')
|
pairdata = misc.file_load_json(filename)
|
||||||
file = path.joinpath(f'{pair_s}-{ticker_interval}.json')
|
|
||||||
|
|
||||||
pairdata = misc.file_load_json(file)
|
|
||||||
|
|
||||||
if not pairdata:
|
if not pairdata:
|
||||||
return None
|
return []
|
||||||
|
|
||||||
if timerange:
|
if timerange:
|
||||||
pairdata = trim_tickerlist(pairdata, timerange)
|
pairdata = trim_tickerlist(pairdata, timerange)
|
||||||
return pairdata
|
return pairdata
|
||||||
|
|
||||||
|
|
||||||
|
def store_tickerdata_file(datadir: Path, pair: str,
|
||||||
|
ticker_interval: str, data: list, is_zip: bool = False):
|
||||||
|
"""
|
||||||
|
Stores tickerdata to file
|
||||||
|
"""
|
||||||
|
filename = pair_data_filename(datadir, pair, ticker_interval)
|
||||||
|
misc.file_dump_json(filename, data, is_zip=is_zip)
|
||||||
|
|
||||||
|
|
||||||
|
def load_trades_file(datadir: Path, pair: str,
|
||||||
|
timerange: Optional[TimeRange] = None) -> List[Dict]:
|
||||||
|
"""
|
||||||
|
Load a pair from file, either .json.gz or .json
|
||||||
|
:return: tradelist or empty list if unsuccesful
|
||||||
|
"""
|
||||||
|
filename = pair_trades_filename(datadir, pair)
|
||||||
|
tradesdata = misc.file_load_json(filename)
|
||||||
|
if not tradesdata:
|
||||||
|
return []
|
||||||
|
|
||||||
|
return tradesdata
|
||||||
|
|
||||||
|
|
||||||
|
def store_trades_file(datadir: Path, pair: str,
|
||||||
|
data: list, is_zip: bool = True):
|
||||||
|
"""
|
||||||
|
Stores tickerdata to file
|
||||||
|
"""
|
||||||
|
filename = pair_trades_filename(datadir, pair)
|
||||||
|
misc.file_dump_json(filename, data, is_zip=is_zip)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_pairdata(pair, pairdata, timerange: TimeRange):
|
||||||
|
if timerange.starttype == 'date' and pairdata[0][0] > timerange.startts * 1000:
|
||||||
|
logger.warning('Missing data at start for pair %s, data starts at %s',
|
||||||
|
pair, arrow.get(pairdata[0][0] // 1000).strftime('%Y-%m-%d %H:%M:%S'))
|
||||||
|
if timerange.stoptype == 'date' and pairdata[-1][0] < timerange.stopts * 1000:
|
||||||
|
logger.warning('Missing data at end for pair %s, data ends at %s',
|
||||||
|
pair, arrow.get(pairdata[-1][0] // 1000).strftime('%Y-%m-%d %H:%M:%S'))
|
||||||
|
|
||||||
|
|
||||||
def load_pair_history(pair: str,
|
def load_pair_history(pair: str,
|
||||||
ticker_interval: str,
|
ticker_interval: str,
|
||||||
datadir: Optional[Path],
|
datadir: Path,
|
||||||
timerange: TimeRange = TimeRange(None, None, 0, 0),
|
timerange: Optional[TimeRange] = None,
|
||||||
refresh_pairs: bool = False,
|
refresh_pairs: bool = False,
|
||||||
exchange: Optional[Exchange] = None,
|
exchange: Optional[Exchange] = None,
|
||||||
fill_up_missing: bool = True
|
fill_up_missing: bool = True,
|
||||||
|
drop_incomplete: bool = True
|
||||||
) -> DataFrame:
|
) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Loads cached ticker history for the given pair.
|
Loads cached ticker history for the given pair.
|
||||||
|
:param pair: Pair to load data for
|
||||||
|
:param ticker_interval: Ticker-interval (e.g. "5m")
|
||||||
|
:param datadir: Path to the data storage location.
|
||||||
|
:param timerange: Limit data to be loaded to this timerange
|
||||||
|
:param refresh_pairs: Refresh pairs from exchange.
|
||||||
|
(Note: Requires exchange to be passed as well.)
|
||||||
|
:param exchange: Exchange object (needed when using "refresh_pairs")
|
||||||
|
:param fill_up_missing: Fill missing values with "No action"-candles
|
||||||
|
:param drop_incomplete: Drop last candle assuming it may be incomplete.
|
||||||
:return: DataFrame with ohlcv data
|
:return: DataFrame with ohlcv data
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# If the user force the refresh of pairs
|
# The user forced the refresh of pairs
|
||||||
if refresh_pairs:
|
if refresh_pairs:
|
||||||
if not exchange:
|
|
||||||
raise OperationalException("Exchange needs to be initialized when "
|
|
||||||
"calling load_data with refresh_pairs=True")
|
|
||||||
|
|
||||||
logger.info('Download data for pair and store them in %s', datadir)
|
|
||||||
download_pair_history(datadir=datadir,
|
download_pair_history(datadir=datadir,
|
||||||
exchange=exchange,
|
exchange=exchange,
|
||||||
pair=pair,
|
pair=pair,
|
||||||
tick_interval=ticker_interval,
|
ticker_interval=ticker_interval,
|
||||||
timerange=timerange)
|
timerange=timerange)
|
||||||
|
|
||||||
pairdata = load_tickerdata_file(datadir, pair, ticker_interval, timerange=timerange)
|
pairdata = load_tickerdata_file(datadir, pair, ticker_interval, timerange=timerange)
|
||||||
|
|
||||||
if pairdata:
|
if pairdata:
|
||||||
if timerange.starttype == 'date' and pairdata[0][0] > timerange.startts * 1000:
|
if timerange:
|
||||||
logger.warning('Missing data at start for pair %s, data starts at %s',
|
_validate_pairdata(pair, pairdata, timerange)
|
||||||
pair, arrow.get(pairdata[0][0] // 1000).strftime('%Y-%m-%d %H:%M:%S'))
|
return parse_ticker_dataframe(pairdata, ticker_interval, pair=pair,
|
||||||
if timerange.stoptype == 'date' and pairdata[-1][0] < timerange.stopts * 1000:
|
fill_missing=fill_up_missing,
|
||||||
logger.warning('Missing data at end for pair %s, data ends at %s',
|
drop_incomplete=drop_incomplete)
|
||||||
pair,
|
|
||||||
arrow.get(pairdata[-1][0] // 1000).strftime('%Y-%m-%d %H:%M:%S'))
|
|
||||||
return parse_ticker_dataframe(pairdata, ticker_interval, fill_up_missing)
|
|
||||||
else:
|
else:
|
||||||
logger.warning('No data for pair: "%s", Interval: %s. '
|
logger.warning(
|
||||||
'Use --refresh-pairs-cached to download the data',
|
f'No history data for pair: "{pair}", interval: {ticker_interval}. '
|
||||||
pair, ticker_interval)
|
'Use `freqtrade download-data` to download the data'
|
||||||
|
)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def load_data(datadir: Optional[Path],
|
def load_data(datadir: Path,
|
||||||
ticker_interval: str,
|
ticker_interval: str,
|
||||||
pairs: List[str],
|
pairs: List[str],
|
||||||
refresh_pairs: bool = False,
|
refresh_pairs: bool = False,
|
||||||
exchange: Optional[Exchange] = None,
|
exchange: Optional[Exchange] = None,
|
||||||
timerange: TimeRange = TimeRange(None, None, 0, 0),
|
timerange: Optional[TimeRange] = None,
|
||||||
fill_up_missing: bool = True) -> Dict[str, DataFrame]:
|
fill_up_missing: bool = True,
|
||||||
|
) -> Dict[str, DataFrame]:
|
||||||
"""
|
"""
|
||||||
Loads ticker history data for a list of pairs the given parameters
|
Loads ticker history data for a list of pairs
|
||||||
:return: dict(<pair>:<tickerlist>)
|
:return: dict(<pair>:<tickerlist>)
|
||||||
|
TODO: refresh_pairs is still used by edge to keep the data uptodate.
|
||||||
|
This should be replaced in the future. Instead, writing the current candles to disk
|
||||||
|
from dataprovider should be implemented, as this would avoid loading ohlcv data twice.
|
||||||
|
exchange and refresh_pairs are then not needed here nor in load_pair_history.
|
||||||
"""
|
"""
|
||||||
result = {}
|
result: Dict[str, DataFrame] = {}
|
||||||
|
|
||||||
for pair in pairs:
|
for pair in pairs:
|
||||||
hist = load_pair_history(pair=pair, ticker_interval=ticker_interval,
|
hist = load_pair_history(pair=pair, ticker_interval=ticker_interval,
|
||||||
@@ -144,16 +182,27 @@ def load_data(datadir: Optional[Path],
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def make_testdata_path(datadir: Optional[Path]) -> Path:
|
def pair_data_filename(datadir: Path, pair: str, ticker_interval: str) -> Path:
|
||||||
"""Return the path where testdata files are stored"""
|
pair_s = pair.replace("/", "_")
|
||||||
return datadir or (Path(__file__).parent.parent / "tests" / "testdata").resolve()
|
filename = datadir.joinpath(f'{pair_s}-{ticker_interval}.json')
|
||||||
|
return filename
|
||||||
|
|
||||||
|
|
||||||
def load_cached_data_for_updating(filename: Path, tick_interval: str,
|
def pair_trades_filename(datadir: Path, pair: str) -> Path:
|
||||||
timerange: Optional[TimeRange]) -> Tuple[List[Any],
|
pair_s = pair.replace("/", "_")
|
||||||
Optional[int]]:
|
filename = datadir.joinpath(f'{pair_s}-trades.json.gz')
|
||||||
|
return filename
|
||||||
|
|
||||||
|
|
||||||
|
def _load_cached_data_for_updating(datadir: Path, pair: str, ticker_interval: str,
|
||||||
|
timerange: Optional[TimeRange]) -> Tuple[List[Any],
|
||||||
|
Optional[int]]:
|
||||||
"""
|
"""
|
||||||
Load cached data and choose what part of the data should be updated
|
Load cached data to download more data.
|
||||||
|
If timerange is passed in, checks whether data from an before the stored data will be
|
||||||
|
downloaded.
|
||||||
|
If that's the case then what's available should be completely overwritten.
|
||||||
|
Only used by download_pair_history().
|
||||||
"""
|
"""
|
||||||
|
|
||||||
since_ms = None
|
since_ms = None
|
||||||
@@ -163,16 +212,15 @@ def load_cached_data_for_updating(filename: Path, tick_interval: str,
|
|||||||
if timerange.starttype == 'date':
|
if timerange.starttype == 'date':
|
||||||
since_ms = timerange.startts * 1000
|
since_ms = timerange.startts * 1000
|
||||||
elif timerange.stoptype == 'line':
|
elif timerange.stoptype == 'line':
|
||||||
num_minutes = timerange.stopts * constants.TICKER_INTERVAL_MINUTES[tick_interval]
|
num_minutes = timerange.stopts * timeframe_to_minutes(ticker_interval)
|
||||||
since_ms = arrow.utcnow().shift(minutes=num_minutes).timestamp * 1000
|
since_ms = arrow.utcnow().shift(minutes=num_minutes).timestamp * 1000
|
||||||
|
|
||||||
# read the cached file
|
# read the cached file
|
||||||
if filename.is_file():
|
# Intentionally don't pass timerange in - since we need to load the full dataset.
|
||||||
with open(filename, "rt") as file:
|
data = load_tickerdata_file(datadir, pair, ticker_interval)
|
||||||
data = misc.json_load(file)
|
# remove the last item, could be incomplete candle
|
||||||
# remove the last item, could be incomplete candle
|
if data:
|
||||||
if data:
|
data.pop()
|
||||||
data.pop()
|
|
||||||
else:
|
else:
|
||||||
data = []
|
data = []
|
||||||
|
|
||||||
@@ -187,10 +235,10 @@ def load_cached_data_for_updating(filename: Path, tick_interval: str,
|
|||||||
return (data, since_ms)
|
return (data, since_ms)
|
||||||
|
|
||||||
|
|
||||||
def download_pair_history(datadir: Optional[Path],
|
def download_pair_history(datadir: Path,
|
||||||
exchange: Exchange,
|
exchange: Optional[Exchange],
|
||||||
pair: str,
|
pair: str,
|
||||||
tick_interval: str = '5m',
|
ticker_interval: str = '5m',
|
||||||
timerange: Optional[TimeRange] = None) -> bool:
|
timerange: Optional[TimeRange] = None) -> bool:
|
||||||
"""
|
"""
|
||||||
Download the latest ticker intervals from the exchange for the pair passed in parameters
|
Download the latest ticker intervals from the exchange for the pair passed in parameters
|
||||||
@@ -199,37 +247,196 @@ def download_pair_history(datadir: Optional[Path],
|
|||||||
the full data will be redownloaded
|
the full data will be redownloaded
|
||||||
|
|
||||||
Based on @Rybolov work: https://github.com/rybolov/freqtrade-data
|
Based on @Rybolov work: https://github.com/rybolov/freqtrade-data
|
||||||
|
|
||||||
:param pair: pair to download
|
:param pair: pair to download
|
||||||
:param tick_interval: ticker interval
|
:param ticker_interval: ticker interval
|
||||||
:param timerange: range of time to download
|
:param timerange: range of time to download
|
||||||
:return: bool with success state
|
:return: bool with success state
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
if not exchange:
|
||||||
|
raise OperationalException(
|
||||||
|
"Exchange needs to be initialized when downloading pair history data"
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
path = make_testdata_path(datadir)
|
logger.info(
|
||||||
filepair = pair.replace("/", "_")
|
f'Download history data for pair: "{pair}", interval: {ticker_interval} '
|
||||||
filename = path.joinpath(f'{filepair}-{tick_interval}.json')
|
f'and store in {datadir}.'
|
||||||
|
)
|
||||||
|
|
||||||
logger.info('Download the pair: "%s", Interval: %s', pair, tick_interval)
|
data, since_ms = _load_cached_data_for_updating(datadir, pair, ticker_interval, timerange)
|
||||||
|
|
||||||
data, since_ms = load_cached_data_for_updating(filename, tick_interval, timerange)
|
|
||||||
|
|
||||||
logger.debug("Current Start: %s", misc.format_ms_time(data[1][0]) if data else 'None')
|
logger.debug("Current Start: %s", misc.format_ms_time(data[1][0]) if data else 'None')
|
||||||
logger.debug("Current End: %s", misc.format_ms_time(data[-1][0]) if data else 'None')
|
logger.debug("Current End: %s", misc.format_ms_time(data[-1][0]) if data else 'None')
|
||||||
|
|
||||||
# Default since_ms to 30 days if nothing is given
|
# Default since_ms to 30 days if nothing is given
|
||||||
new_data = exchange.get_history(pair=pair, tick_interval=tick_interval,
|
new_data = exchange.get_historic_ohlcv(pair=pair, ticker_interval=ticker_interval,
|
||||||
since_ms=since_ms if since_ms
|
since_ms=since_ms if since_ms
|
||||||
else
|
else
|
||||||
int(arrow.utcnow().shift(days=-30).float_timestamp) * 1000)
|
int(arrow.utcnow().shift(
|
||||||
|
days=-30).float_timestamp) * 1000)
|
||||||
data.extend(new_data)
|
data.extend(new_data)
|
||||||
|
|
||||||
logger.debug("New Start: %s", misc.format_ms_time(data[0][0]))
|
logger.debug("New Start: %s", misc.format_ms_time(data[0][0]))
|
||||||
logger.debug("New End: %s", misc.format_ms_time(data[-1][0]))
|
logger.debug("New End: %s", misc.format_ms_time(data[-1][0]))
|
||||||
|
|
||||||
misc.file_dump_json(filename, data)
|
store_tickerdata_file(datadir, pair, ticker_interval, data=data)
|
||||||
return True
|
return True
|
||||||
except BaseException:
|
|
||||||
logger.info('Failed to download the pair: "%s", Interval: %s',
|
except Exception as e:
|
||||||
pair, tick_interval)
|
logger.error(
|
||||||
|
f'Failed to download history data for pair: "{pair}", interval: {ticker_interval}. '
|
||||||
|
f'Error: {e}'
|
||||||
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes: List[str],
|
||||||
|
dl_path: Path, timerange: Optional[TimeRange] = None,
|
||||||
|
erase=False) -> List[str]:
|
||||||
|
"""
|
||||||
|
Refresh stored ohlcv data for backtesting and hyperopt operations.
|
||||||
|
Used by freqtrade download-data
|
||||||
|
:return: Pairs not available
|
||||||
|
"""
|
||||||
|
pairs_not_available = []
|
||||||
|
for pair in pairs:
|
||||||
|
if pair not in exchange.markets:
|
||||||
|
pairs_not_available.append(pair)
|
||||||
|
logger.info(f"Skipping pair {pair}...")
|
||||||
|
continue
|
||||||
|
for ticker_interval in timeframes:
|
||||||
|
|
||||||
|
dl_file = pair_data_filename(dl_path, pair, ticker_interval)
|
||||||
|
if erase and dl_file.exists():
|
||||||
|
logger.info(
|
||||||
|
f'Deleting existing data for pair {pair}, interval {ticker_interval}.')
|
||||||
|
dl_file.unlink()
|
||||||
|
|
||||||
|
logger.info(f'Downloading pair {pair}, interval {ticker_interval}.')
|
||||||
|
download_pair_history(datadir=dl_path, exchange=exchange,
|
||||||
|
pair=pair, ticker_interval=str(ticker_interval),
|
||||||
|
timerange=timerange)
|
||||||
|
return pairs_not_available
|
||||||
|
|
||||||
|
|
||||||
|
def download_trades_history(datadir: Path,
|
||||||
|
exchange: Exchange,
|
||||||
|
pair: str,
|
||||||
|
timerange: Optional[TimeRange] = None) -> bool:
|
||||||
|
"""
|
||||||
|
Download trade history from the exchange.
|
||||||
|
Appends to previously downloaded trades data.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
|
||||||
|
since = timerange.startts * 1000 if timerange and timerange.starttype == 'date' else None
|
||||||
|
|
||||||
|
trades = load_trades_file(datadir, pair)
|
||||||
|
|
||||||
|
from_id = trades[-1]['id'] if trades else None
|
||||||
|
|
||||||
|
logger.debug("Current Start: %s", trades[0]['datetime'] if trades else 'None')
|
||||||
|
logger.debug("Current End: %s", trades[-1]['datetime'] if trades else 'None')
|
||||||
|
|
||||||
|
new_trades = exchange.get_historic_trades(pair=pair,
|
||||||
|
since=since if since else
|
||||||
|
int(arrow.utcnow().shift(
|
||||||
|
days=-30).float_timestamp) * 1000,
|
||||||
|
# until=xxx,
|
||||||
|
from_id=from_id,
|
||||||
|
)
|
||||||
|
trades.extend(new_trades[1])
|
||||||
|
store_trades_file(datadir, pair, trades)
|
||||||
|
|
||||||
|
logger.debug("New Start: %s", trades[0]['datetime'])
|
||||||
|
logger.debug("New End: %s", trades[-1]['datetime'])
|
||||||
|
logger.info(f"New Amount of trades: {len(trades)}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(
|
||||||
|
f'Failed to download historic trades for pair: "{pair}". '
|
||||||
|
f'Error: {e}'
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def refresh_backtest_trades_data(exchange: Exchange, pairs: List[str], datadir: Path,
|
||||||
|
timerange: TimeRange, erase=False) -> List[str]:
|
||||||
|
"""
|
||||||
|
Refresh stored trades data.
|
||||||
|
Used by freqtrade download-data
|
||||||
|
:return: Pairs not available
|
||||||
|
"""
|
||||||
|
pairs_not_available = []
|
||||||
|
for pair in pairs:
|
||||||
|
if pair not in exchange.markets:
|
||||||
|
pairs_not_available.append(pair)
|
||||||
|
logger.info(f"Skipping pair {pair}...")
|
||||||
|
continue
|
||||||
|
|
||||||
|
dl_file = pair_trades_filename(datadir, pair)
|
||||||
|
if erase and dl_file.exists():
|
||||||
|
logger.info(
|
||||||
|
f'Deleting existing data for pair {pair}.')
|
||||||
|
dl_file.unlink()
|
||||||
|
|
||||||
|
logger.info(f'Downloading trades for pair {pair}.')
|
||||||
|
download_trades_history(datadir=datadir, exchange=exchange,
|
||||||
|
pair=pair,
|
||||||
|
timerange=timerange)
|
||||||
|
return pairs_not_available
|
||||||
|
|
||||||
|
|
||||||
|
def convert_trades_to_ohlcv(pairs: List[str], timeframes: List[str],
|
||||||
|
datadir: Path, timerange: TimeRange, erase=False) -> None:
|
||||||
|
"""
|
||||||
|
Convert stored trades data to ohlcv data
|
||||||
|
"""
|
||||||
|
for pair in pairs:
|
||||||
|
trades = load_trades_file(datadir, pair)
|
||||||
|
for timeframe in timeframes:
|
||||||
|
ohlcv_file = pair_data_filename(datadir, pair, timeframe)
|
||||||
|
if erase and ohlcv_file.exists():
|
||||||
|
logger.info(f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
||||||
|
ohlcv_file.unlink()
|
||||||
|
ohlcv = trades_to_ohlcv(trades, timeframe)
|
||||||
|
# Store ohlcv
|
||||||
|
store_tickerdata_file(datadir, pair, timeframe, data=ohlcv)
|
||||||
|
|
||||||
|
|
||||||
|
def get_timeframe(data: Dict[str, DataFrame]) -> Tuple[arrow.Arrow, arrow.Arrow]:
|
||||||
|
"""
|
||||||
|
Get the maximum timeframe for the given backtest data
|
||||||
|
:param data: dictionary with preprocessed backtesting data
|
||||||
|
:return: tuple containing min_date, max_date
|
||||||
|
"""
|
||||||
|
timeframe = [
|
||||||
|
(arrow.get(frame['date'].min()), arrow.get(frame['date'].max()))
|
||||||
|
for frame in data.values()
|
||||||
|
]
|
||||||
|
return min(timeframe, key=operator.itemgetter(0))[0], \
|
||||||
|
max(timeframe, key=operator.itemgetter(1))[1]
|
||||||
|
|
||||||
|
|
||||||
|
def validate_backtest_data(data: DataFrame, pair: str, min_date: datetime,
|
||||||
|
max_date: datetime, ticker_interval_mins: int) -> bool:
|
||||||
|
"""
|
||||||
|
Validates preprocessed backtesting data for missing values and shows warnings about it that.
|
||||||
|
|
||||||
|
:param data: preprocessed backtesting data (as DataFrame)
|
||||||
|
:param pair: pair used for log output.
|
||||||
|
:param min_date: start-date of the data
|
||||||
|
:param max_date: end-date of the data
|
||||||
|
:param ticker_interval_mins: ticker interval in minutes
|
||||||
|
"""
|
||||||
|
# total difference in minutes / interval-minutes
|
||||||
|
expected_frames = int((max_date - min_date).total_seconds() // 60 // ticker_interval_mins)
|
||||||
|
found_missing = False
|
||||||
|
dflen = len(data)
|
||||||
|
if dflen < expected_frames:
|
||||||
|
found_missing = True
|
||||||
|
logger.warning("%s has missing frames: expected %s, got %s, that's %s missing values",
|
||||||
|
pair, expected_frames, dflen, expected_frames - dflen)
|
||||||
|
return found_missing
|
||||||
|
|||||||
@@ -10,10 +10,8 @@ import utils_find_1st as utf1st
|
|||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
from freqtrade import constants, OperationalException
|
from freqtrade import constants, OperationalException
|
||||||
from freqtrade.arguments import Arguments
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.arguments import TimeRange
|
|
||||||
from freqtrade.data import history
|
from freqtrade.data import history
|
||||||
from freqtrade.optimize import get_timeframe
|
|
||||||
from freqtrade.strategy.interface import SellType
|
from freqtrade.strategy.interface import SellType
|
||||||
|
|
||||||
|
|
||||||
@@ -30,7 +28,7 @@ class PairInfo(NamedTuple):
|
|||||||
avg_trade_duration: float
|
avg_trade_duration: float
|
||||||
|
|
||||||
|
|
||||||
class Edge():
|
class Edge:
|
||||||
"""
|
"""
|
||||||
Calculates Win Rate, Risk Reward Ratio, Expectancy
|
Calculates Win Rate, Risk Reward Ratio, Expectancy
|
||||||
against historical data for a give set of markets and a strategy
|
against historical data for a give set of markets and a strategy
|
||||||
@@ -47,11 +45,6 @@ class Edge():
|
|||||||
self.config = config
|
self.config = config
|
||||||
self.exchange = exchange
|
self.exchange = exchange
|
||||||
self.strategy = strategy
|
self.strategy = strategy
|
||||||
self.ticker_interval = self.strategy.ticker_interval
|
|
||||||
self.tickerdata_to_dataframe = self.strategy.tickerdata_to_dataframe
|
|
||||||
self.get_timeframe = get_timeframe
|
|
||||||
self.advise_sell = self.strategy.advise_sell
|
|
||||||
self.advise_buy = self.strategy.advise_buy
|
|
||||||
|
|
||||||
self.edge_config = self.config.get('edge', {})
|
self.edge_config = self.config.get('edge', {})
|
||||||
self._cached_pairs: Dict[str, Any] = {} # Keeps a list of pairs
|
self._cached_pairs: Dict[str, Any] = {} # Keeps a list of pairs
|
||||||
@@ -82,10 +75,12 @@ class Edge():
|
|||||||
self._stoploss_range_step
|
self._stoploss_range_step
|
||||||
)
|
)
|
||||||
|
|
||||||
self._timerange: TimeRange = Arguments.parse_timerange("%s-" % arrow.now().shift(
|
self._timerange: TimeRange = TimeRange.parse_timerange("%s-" % arrow.now().shift(
|
||||||
days=-1 * self._since_number_of_days).format('YYYYMMDD'))
|
days=-1 * self._since_number_of_days).format('YYYYMMDD'))
|
||||||
|
if config.get('fee'):
|
||||||
self.fee = self.exchange.get_fee()
|
self.fee = config['fee']
|
||||||
|
else:
|
||||||
|
self.fee = self.exchange.get_fee()
|
||||||
|
|
||||||
def calculate(self) -> bool:
|
def calculate(self) -> bool:
|
||||||
pairs = self.config['exchange']['pair_whitelist']
|
pairs = self.config['exchange']['pair_whitelist']
|
||||||
@@ -100,9 +95,9 @@ class Edge():
|
|||||||
logger.info('Using local backtesting data (using whitelist in given config) ...')
|
logger.info('Using local backtesting data (using whitelist in given config) ...')
|
||||||
|
|
||||||
data = history.load_data(
|
data = history.load_data(
|
||||||
datadir=Path(self.config['datadir']) if self.config.get('datadir') else None,
|
datadir=Path(self.config['datadir']),
|
||||||
pairs=pairs,
|
pairs=pairs,
|
||||||
ticker_interval=self.ticker_interval,
|
ticker_interval=self.strategy.ticker_interval,
|
||||||
refresh_pairs=self._refresh_pairs,
|
refresh_pairs=self._refresh_pairs,
|
||||||
exchange=self.exchange,
|
exchange=self.exchange,
|
||||||
timerange=self._timerange
|
timerange=self._timerange
|
||||||
@@ -114,10 +109,10 @@ class Edge():
|
|||||||
logger.critical("No data found. Edge is stopped ...")
|
logger.critical("No data found. Edge is stopped ...")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
preprocessed = self.tickerdata_to_dataframe(data)
|
preprocessed = self.strategy.tickerdata_to_dataframe(data)
|
||||||
|
|
||||||
# Print timeframe
|
# Print timeframe
|
||||||
min_date, max_date = self.get_timeframe(preprocessed)
|
min_date, max_date = history.get_timeframe(preprocessed)
|
||||||
logger.info(
|
logger.info(
|
||||||
'Measuring data from %s up to %s (%s days) ...',
|
'Measuring data from %s up to %s (%s days) ...',
|
||||||
min_date.isoformat(),
|
min_date.isoformat(),
|
||||||
@@ -132,13 +127,14 @@ class Edge():
|
|||||||
pair_data = pair_data.sort_values(by=['date'])
|
pair_data = pair_data.sort_values(by=['date'])
|
||||||
pair_data = pair_data.reset_index(drop=True)
|
pair_data = pair_data.reset_index(drop=True)
|
||||||
|
|
||||||
ticker_data = self.advise_sell(
|
ticker_data = self.strategy.advise_sell(
|
||||||
self.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy()
|
self.strategy.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy()
|
||||||
|
|
||||||
trades += self._find_trades_for_stoploss_range(ticker_data, pair, self._stoploss_range)
|
trades += self._find_trades_for_stoploss_range(ticker_data, pair, self._stoploss_range)
|
||||||
|
|
||||||
# If no trade found then exit
|
# If no trade found then exit
|
||||||
if len(trades) == 0:
|
if len(trades) == 0:
|
||||||
|
logger.info("No trades found.")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Fill missing, calculable columns, profit, duration , abs etc.
|
# Fill missing, calculable columns, profit, duration , abs etc.
|
||||||
@@ -203,6 +199,22 @@ class Edge():
|
|||||||
|
|
||||||
return self._final_pairs
|
return self._final_pairs
|
||||||
|
|
||||||
|
def accepted_pairs(self) -> list:
|
||||||
|
"""
|
||||||
|
return a list of accepted pairs along with their winrate, expectancy and stoploss
|
||||||
|
"""
|
||||||
|
final = []
|
||||||
|
for pair, info in self._cached_pairs.items():
|
||||||
|
if info.expectancy > float(self.edge_config.get('minimum_expectancy', 0.2)) and \
|
||||||
|
info.winrate > float(self.edge_config.get('minimum_winrate', 0.60)):
|
||||||
|
final.append({
|
||||||
|
'Pair': pair,
|
||||||
|
'Winrate': info.winrate,
|
||||||
|
'Expectancy': info.expectancy,
|
||||||
|
'Stoploss': info.stoploss,
|
||||||
|
})
|
||||||
|
return final
|
||||||
|
|
||||||
def _fill_calculable_fields(self, result: DataFrame) -> DataFrame:
|
def _fill_calculable_fields(self, result: DataFrame) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
The result frame contains a number of columns that are calculable
|
The result frame contains a number of columns that are calculable
|
||||||
@@ -351,91 +363,93 @@ class Edge():
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
def _detect_next_stop_or_sell_point(self, buy_column, sell_column, date_column,
|
def _detect_next_stop_or_sell_point(self, buy_column, sell_column, date_column,
|
||||||
ohlc_columns, stoploss, pair, start_point=0):
|
ohlc_columns, stoploss, pair):
|
||||||
"""
|
"""
|
||||||
Iterate through ohlc_columns recursively in order to find the next trade
|
Iterate through ohlc_columns in order to find the next trade
|
||||||
Next trade opens from the first buy signal noticed to
|
Next trade opens from the first buy signal noticed to
|
||||||
The sell or stoploss signal after it.
|
The sell or stoploss signal after it.
|
||||||
It then calls itself cutting OHLC, buy_column, sell_colum and date_column
|
It then cuts OHLC, buy_column, sell_column and date_column.
|
||||||
Cut from (the exit trade index) + 1
|
Cut from (the exit trade index) + 1.
|
||||||
|
|
||||||
Author: https://github.com/mishaker
|
Author: https://github.com/mishaker
|
||||||
"""
|
"""
|
||||||
|
|
||||||
result: list = []
|
result: list = []
|
||||||
open_trade_index = utf1st.find_1st(buy_column, 1, utf1st.cmp_equal)
|
start_point = 0
|
||||||
|
|
||||||
# return empty if we don't find trade entry (i.e. buy==1) or
|
while True:
|
||||||
# we find a buy but at the of array
|
open_trade_index = utf1st.find_1st(buy_column, 1, utf1st.cmp_equal)
|
||||||
if open_trade_index == -1 or open_trade_index == len(buy_column) - 1:
|
|
||||||
return []
|
|
||||||
else:
|
|
||||||
open_trade_index += 1 # when a buy signal is seen,
|
|
||||||
# trade opens in reality on the next candle
|
|
||||||
|
|
||||||
stop_price_percentage = stoploss + 1
|
# Return empty if we don't find trade entry (i.e. buy==1) or
|
||||||
open_price = ohlc_columns[open_trade_index, 0]
|
# we find a buy but at the end of array
|
||||||
stop_price = (open_price * stop_price_percentage)
|
if open_trade_index == -1 or open_trade_index == len(buy_column) - 1:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
# When a buy signal is seen,
|
||||||
|
# trade opens in reality on the next candle
|
||||||
|
open_trade_index += 1
|
||||||
|
|
||||||
# Searching for the index where stoploss is hit
|
stop_price_percentage = stoploss + 1
|
||||||
stop_index = utf1st.find_1st(
|
open_price = ohlc_columns[open_trade_index, 0]
|
||||||
ohlc_columns[open_trade_index:, 2], stop_price, utf1st.cmp_smaller)
|
stop_price = (open_price * stop_price_percentage)
|
||||||
|
|
||||||
# If we don't find it then we assume stop_index will be far in future (infinite number)
|
# Searching for the index where stoploss is hit
|
||||||
if stop_index == -1:
|
stop_index = utf1st.find_1st(
|
||||||
stop_index = float('inf')
|
ohlc_columns[open_trade_index:, 2], stop_price, utf1st.cmp_smaller)
|
||||||
|
|
||||||
# Searching for the index where sell is hit
|
# If we don't find it then we assume stop_index will be far in future (infinite number)
|
||||||
sell_index = utf1st.find_1st(sell_column[open_trade_index:], 1, utf1st.cmp_equal)
|
if stop_index == -1:
|
||||||
|
stop_index = float('inf')
|
||||||
|
|
||||||
# If we don't find it then we assume sell_index will be far in future (infinite number)
|
# Searching for the index where sell is hit
|
||||||
if sell_index == -1:
|
sell_index = utf1st.find_1st(sell_column[open_trade_index:], 1, utf1st.cmp_equal)
|
||||||
sell_index = float('inf')
|
|
||||||
|
|
||||||
# Check if we don't find any stop or sell point (in that case trade remains open)
|
# If we don't find it then we assume sell_index will be far in future (infinite number)
|
||||||
# It is not interesting for Edge to consider it so we simply ignore the trade
|
if sell_index == -1:
|
||||||
# And stop iterating there is no more entry
|
sell_index = float('inf')
|
||||||
if stop_index == sell_index == float('inf'):
|
|
||||||
return []
|
|
||||||
|
|
||||||
if stop_index <= sell_index:
|
# Check if we don't find any stop or sell point (in that case trade remains open)
|
||||||
exit_index = open_trade_index + stop_index
|
# It is not interesting for Edge to consider it so we simply ignore the trade
|
||||||
exit_type = SellType.STOP_LOSS
|
# And stop iterating there is no more entry
|
||||||
exit_price = stop_price
|
if stop_index == sell_index == float('inf'):
|
||||||
elif stop_index > sell_index:
|
break
|
||||||
# if exit is SELL then we exit at the next candle
|
|
||||||
exit_index = open_trade_index + sell_index + 1
|
|
||||||
|
|
||||||
# check if we have the next candle
|
if stop_index <= sell_index:
|
||||||
if len(ohlc_columns) - 1 < exit_index:
|
exit_index = open_trade_index + stop_index
|
||||||
return []
|
exit_type = SellType.STOP_LOSS
|
||||||
|
exit_price = stop_price
|
||||||
|
elif stop_index > sell_index:
|
||||||
|
# If exit is SELL then we exit at the next candle
|
||||||
|
exit_index = open_trade_index + sell_index + 1
|
||||||
|
|
||||||
exit_type = SellType.SELL_SIGNAL
|
# Check if we have the next candle
|
||||||
exit_price = ohlc_columns[exit_index, 0]
|
if len(ohlc_columns) - 1 < exit_index:
|
||||||
|
break
|
||||||
|
|
||||||
trade = {'pair': pair,
|
exit_type = SellType.SELL_SIGNAL
|
||||||
'stoploss': stoploss,
|
exit_price = ohlc_columns[exit_index, 0]
|
||||||
'profit_percent': '',
|
|
||||||
'profit_abs': '',
|
|
||||||
'open_time': date_column[open_trade_index],
|
|
||||||
'close_time': date_column[exit_index],
|
|
||||||
'open_index': start_point + open_trade_index,
|
|
||||||
'close_index': start_point + exit_index,
|
|
||||||
'trade_duration': '',
|
|
||||||
'open_rate': round(open_price, 15),
|
|
||||||
'close_rate': round(exit_price, 15),
|
|
||||||
'exit_type': exit_type
|
|
||||||
}
|
|
||||||
|
|
||||||
result.append(trade)
|
trade = {'pair': pair,
|
||||||
|
'stoploss': stoploss,
|
||||||
|
'profit_percent': '',
|
||||||
|
'profit_abs': '',
|
||||||
|
'open_time': date_column[open_trade_index],
|
||||||
|
'close_time': date_column[exit_index],
|
||||||
|
'open_index': start_point + open_trade_index,
|
||||||
|
'close_index': start_point + exit_index,
|
||||||
|
'trade_duration': '',
|
||||||
|
'open_rate': round(open_price, 15),
|
||||||
|
'close_rate': round(exit_price, 15),
|
||||||
|
'exit_type': exit_type
|
||||||
|
}
|
||||||
|
|
||||||
# Calling again the same function recursively but giving
|
result.append(trade)
|
||||||
# it a view of exit_index till the end of array
|
|
||||||
return result + self._detect_next_stop_or_sell_point(
|
# Giving a view of exit_index till the end of array
|
||||||
buy_column[exit_index:],
|
buy_column = buy_column[exit_index:]
|
||||||
sell_column[exit_index:],
|
sell_column = sell_column[exit_index:]
|
||||||
date_column[exit_index:],
|
date_column = date_column[exit_index:]
|
||||||
ohlc_columns[exit_index:],
|
ohlc_columns = ohlc_columns[exit_index:]
|
||||||
stoploss,
|
start_point += exit_index
|
||||||
pair,
|
|
||||||
(start_point + exit_index)
|
return result
|
||||||
)
|
|
||||||
|
|||||||
@@ -1,730 +1,16 @@
|
|||||||
# pragma pylint: disable=W0603
|
from freqtrade.exchange.exchange import Exchange, MAP_EXCHANGE_CHILDCLASS # noqa: F401
|
||||||
""" Cryptocurrency Exchanges support """
|
from freqtrade.exchange.exchange import (get_exchange_bad_reason, # noqa: F401
|
||||||
import logging
|
is_exchange_bad,
|
||||||
import inspect
|
is_exchange_known_ccxt,
|
||||||
from random import randint
|
is_exchange_officially_supported,
|
||||||
from typing import List, Dict, Tuple, Any, Optional
|
ccxt_exchanges,
|
||||||
from datetime import datetime
|
available_exchanges)
|
||||||
from math import floor, ceil
|
from freqtrade.exchange.exchange import (timeframe_to_seconds, # noqa: F401
|
||||||
|
timeframe_to_minutes,
|
||||||
import arrow
|
timeframe_to_msecs,
|
||||||
import asyncio
|
timeframe_to_next_date,
|
||||||
import ccxt
|
timeframe_to_prev_date)
|
||||||
import ccxt.async_support as ccxt_async
|
from freqtrade.exchange.exchange import (market_is_active, # noqa: F401
|
||||||
from pandas import DataFrame
|
symbol_is_pair)
|
||||||
|
from freqtrade.exchange.kraken import Kraken # noqa: F401
|
||||||
from freqtrade import constants, OperationalException, DependencyException, TemporaryError
|
from freqtrade.exchange.binance import Binance # noqa: F401
|
||||||
from freqtrade.data.converter import parse_ticker_dataframe
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
API_RETRY_COUNT = 4
|
|
||||||
|
|
||||||
|
|
||||||
# Urls to exchange markets, insert quote and base with .format()
|
|
||||||
_EXCHANGE_URLS = {
|
|
||||||
ccxt.bittrex.__name__: '/Market/Index?MarketName={quote}-{base}',
|
|
||||||
ccxt.binance.__name__: '/tradeDetail.html?symbol={base}_{quote}'
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def retrier_async(f):
|
|
||||||
async def wrapper(*args, **kwargs):
|
|
||||||
count = kwargs.pop('count', API_RETRY_COUNT)
|
|
||||||
try:
|
|
||||||
return await f(*args, **kwargs)
|
|
||||||
except (TemporaryError, DependencyException) as ex:
|
|
||||||
logger.warning('%s() returned exception: "%s"', f.__name__, ex)
|
|
||||||
if count > 0:
|
|
||||||
count -= 1
|
|
||||||
kwargs.update({'count': count})
|
|
||||||
logger.warning('retrying %s() still for %s times', f.__name__, count)
|
|
||||||
return await wrapper(*args, **kwargs)
|
|
||||||
else:
|
|
||||||
logger.warning('Giving up retrying: %s()', f.__name__)
|
|
||||||
raise ex
|
|
||||||
return wrapper
|
|
||||||
|
|
||||||
|
|
||||||
def retrier(f):
|
|
||||||
def wrapper(*args, **kwargs):
|
|
||||||
count = kwargs.pop('count', API_RETRY_COUNT)
|
|
||||||
try:
|
|
||||||
return f(*args, **kwargs)
|
|
||||||
except (TemporaryError, DependencyException) as ex:
|
|
||||||
logger.warning('%s() returned exception: "%s"', f.__name__, ex)
|
|
||||||
if count > 0:
|
|
||||||
count -= 1
|
|
||||||
kwargs.update({'count': count})
|
|
||||||
logger.warning('retrying %s() still for %s times', f.__name__, count)
|
|
||||||
return wrapper(*args, **kwargs)
|
|
||||||
else:
|
|
||||||
logger.warning('Giving up retrying: %s()', f.__name__)
|
|
||||||
raise ex
|
|
||||||
return wrapper
|
|
||||||
|
|
||||||
|
|
||||||
class Exchange(object):
|
|
||||||
|
|
||||||
_conf: Dict = {}
|
|
||||||
|
|
||||||
def __init__(self, config: dict) -> None:
|
|
||||||
"""
|
|
||||||
Initializes this module with the given config,
|
|
||||||
it does basic validation whether the specified
|
|
||||||
exchange and pairs are valid.
|
|
||||||
:return: None
|
|
||||||
"""
|
|
||||||
self._conf.update(config)
|
|
||||||
|
|
||||||
self._cached_ticker: Dict[str, Any] = {}
|
|
||||||
|
|
||||||
# Holds last candle refreshed time of each pair
|
|
||||||
self._pairs_last_refresh_time: Dict[Tuple[str, str], int] = {}
|
|
||||||
|
|
||||||
# Holds candles
|
|
||||||
self._klines: Dict[Tuple[str, str], DataFrame] = {}
|
|
||||||
|
|
||||||
# Holds all open sell orders for dry_run
|
|
||||||
self._dry_run_open_orders: Dict[str, Any] = {}
|
|
||||||
|
|
||||||
if config['dry_run']:
|
|
||||||
logger.info('Instance is running with dry_run enabled')
|
|
||||||
|
|
||||||
exchange_config = config['exchange']
|
|
||||||
self._api: ccxt.Exchange = self._init_ccxt(
|
|
||||||
exchange_config, ccxt_kwargs=exchange_config.get('ccxt_config'))
|
|
||||||
self._api_async: ccxt_async.Exchange = self._init_ccxt(
|
|
||||||
exchange_config, ccxt_async, ccxt_kwargs=exchange_config.get('ccxt_async_config'))
|
|
||||||
|
|
||||||
logger.info('Using Exchange "%s"', self.name)
|
|
||||||
|
|
||||||
self.markets = self._load_markets()
|
|
||||||
# Check if all pairs are available
|
|
||||||
self.validate_pairs(config['exchange']['pair_whitelist'])
|
|
||||||
self.validate_ordertypes(config.get('order_types', {}))
|
|
||||||
self.validate_order_time_in_force(config.get('order_time_in_force', {}))
|
|
||||||
if config.get('ticker_interval'):
|
|
||||||
# Check if timeframe is available
|
|
||||||
self.validate_timeframes(config['ticker_interval'])
|
|
||||||
|
|
||||||
def __del__(self):
|
|
||||||
"""
|
|
||||||
Destructor - clean up async stuff
|
|
||||||
"""
|
|
||||||
logger.debug("Exchange object destroyed, closing async loop")
|
|
||||||
if self._api_async and inspect.iscoroutinefunction(self._api_async.close):
|
|
||||||
asyncio.get_event_loop().run_until_complete(self._api_async.close())
|
|
||||||
|
|
||||||
def _init_ccxt(self, exchange_config: dict, ccxt_module=ccxt,
|
|
||||||
ccxt_kwargs: dict = None) -> ccxt.Exchange:
|
|
||||||
"""
|
|
||||||
Initialize ccxt with given config and return valid
|
|
||||||
ccxt instance.
|
|
||||||
"""
|
|
||||||
# Find matching class for the given exchange name
|
|
||||||
name = exchange_config['name']
|
|
||||||
|
|
||||||
if name not in ccxt_module.exchanges:
|
|
||||||
raise OperationalException(f'Exchange {name} is not supported')
|
|
||||||
|
|
||||||
ex_config = {
|
|
||||||
'apiKey': exchange_config.get('key'),
|
|
||||||
'secret': exchange_config.get('secret'),
|
|
||||||
'password': exchange_config.get('password'),
|
|
||||||
'uid': exchange_config.get('uid', ''),
|
|
||||||
'enableRateLimit': exchange_config.get('ccxt_rate_limit', True)
|
|
||||||
}
|
|
||||||
if ccxt_kwargs:
|
|
||||||
logger.info('Applying additional ccxt config: %s', ccxt_kwargs)
|
|
||||||
ex_config.update(ccxt_kwargs)
|
|
||||||
try:
|
|
||||||
|
|
||||||
api = getattr(ccxt_module, name.lower())(ex_config)
|
|
||||||
except (KeyError, AttributeError):
|
|
||||||
raise OperationalException(f'Exchange {name} is not supported')
|
|
||||||
|
|
||||||
self.set_sandbox(api, exchange_config, name)
|
|
||||||
|
|
||||||
return api
|
|
||||||
|
|
||||||
@property
|
|
||||||
def name(self) -> str:
|
|
||||||
"""exchange Name (from ccxt)"""
|
|
||||||
return self._api.name
|
|
||||||
|
|
||||||
@property
|
|
||||||
def id(self) -> str:
|
|
||||||
"""exchange ccxt id"""
|
|
||||||
return self._api.id
|
|
||||||
|
|
||||||
def klines(self, pair_interval: Tuple[str, str], copy=True) -> DataFrame:
|
|
||||||
# create key tuple
|
|
||||||
if pair_interval in self._klines:
|
|
||||||
return self._klines[pair_interval].copy() if copy else self._klines[pair_interval]
|
|
||||||
else:
|
|
||||||
return DataFrame()
|
|
||||||
|
|
||||||
def set_sandbox(self, api, exchange_config: dict, name: str):
|
|
||||||
if exchange_config.get('sandbox'):
|
|
||||||
if api.urls.get('test'):
|
|
||||||
api.urls['api'] = api.urls['test']
|
|
||||||
logger.info("Enabled Sandbox API on %s", name)
|
|
||||||
else:
|
|
||||||
logger.warning(name, "No Sandbox URL in CCXT, exiting. "
|
|
||||||
"Please check your config.json")
|
|
||||||
raise OperationalException(f'Exchange {name} does not provide a sandbox api')
|
|
||||||
|
|
||||||
def _load_async_markets(self) -> None:
|
|
||||||
try:
|
|
||||||
if self._api_async:
|
|
||||||
asyncio.get_event_loop().run_until_complete(self._api_async.load_markets())
|
|
||||||
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
logger.warning('Could not load async markets. Reason: %s', e)
|
|
||||||
return
|
|
||||||
|
|
||||||
def _load_markets(self) -> Dict[str, Any]:
|
|
||||||
""" Initialize markets both sync and async """
|
|
||||||
try:
|
|
||||||
markets = self._api.load_markets()
|
|
||||||
self._load_async_markets()
|
|
||||||
return markets
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
logger.warning('Unable to initialize markets. Reason: %s', e)
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def validate_pairs(self, pairs: List[str]) -> None:
|
|
||||||
"""
|
|
||||||
Checks if all given pairs are tradable on the current exchange.
|
|
||||||
Raises OperationalException if one pair is not available.
|
|
||||||
:param pairs: list of pairs
|
|
||||||
:return: None
|
|
||||||
"""
|
|
||||||
|
|
||||||
if not self.markets:
|
|
||||||
logger.warning('Unable to validate pairs (assuming they are correct).')
|
|
||||||
# return
|
|
||||||
|
|
||||||
stake_cur = self._conf['stake_currency']
|
|
||||||
for pair in pairs:
|
|
||||||
# Note: ccxt has BaseCurrency/QuoteCurrency format for pairs
|
|
||||||
# TODO: add a support for having coins in BTC/USDT format
|
|
||||||
if not pair.endswith(stake_cur):
|
|
||||||
raise OperationalException(
|
|
||||||
f'Pair {pair} not compatible with stake_currency: {stake_cur}')
|
|
||||||
if self.markets and pair not in self.markets:
|
|
||||||
raise OperationalException(
|
|
||||||
f'Pair {pair} is not available at {self.name}'
|
|
||||||
f'Please remove {pair} from your whitelist.')
|
|
||||||
|
|
||||||
def validate_timeframes(self, timeframe: List[str]) -> None:
|
|
||||||
"""
|
|
||||||
Checks if ticker interval from config is a supported timeframe on the exchange
|
|
||||||
"""
|
|
||||||
timeframes = self._api.timeframes
|
|
||||||
if timeframe not in timeframes:
|
|
||||||
raise OperationalException(
|
|
||||||
f'Invalid ticker {timeframe}, this Exchange supports {timeframes}')
|
|
||||||
|
|
||||||
def validate_ordertypes(self, order_types: Dict) -> None:
|
|
||||||
"""
|
|
||||||
Checks if order-types configured in strategy/config are supported
|
|
||||||
"""
|
|
||||||
if any(v == 'market' for k, v in order_types.items()):
|
|
||||||
if not self.exchange_has('createMarketOrder'):
|
|
||||||
raise OperationalException(
|
|
||||||
f'Exchange {self.name} does not support market orders.')
|
|
||||||
|
|
||||||
if order_types.get('stoploss_on_exchange'):
|
|
||||||
if self.name != 'Binance':
|
|
||||||
raise OperationalException(
|
|
||||||
'On exchange stoploss is not supported for %s.' % self.name
|
|
||||||
)
|
|
||||||
|
|
||||||
def validate_order_time_in_force(self, order_time_in_force: Dict) -> None:
|
|
||||||
"""
|
|
||||||
Checks if order time in force configured in strategy/config are supported
|
|
||||||
"""
|
|
||||||
if any(v != 'gtc' for k, v in order_time_in_force.items()):
|
|
||||||
if self.name != 'Binance':
|
|
||||||
raise OperationalException(
|
|
||||||
f'Time in force policies are not supporetd for {self.name} yet.')
|
|
||||||
|
|
||||||
def exchange_has(self, endpoint: str) -> bool:
|
|
||||||
"""
|
|
||||||
Checks if exchange implements a specific API endpoint.
|
|
||||||
Wrapper around ccxt 'has' attribute
|
|
||||||
:param endpoint: Name of endpoint (e.g. 'fetchOHLCV', 'fetchTickers')
|
|
||||||
:return: bool
|
|
||||||
"""
|
|
||||||
return endpoint in self._api.has and self._api.has[endpoint]
|
|
||||||
|
|
||||||
def symbol_amount_prec(self, pair, amount: float):
|
|
||||||
'''
|
|
||||||
Returns the amount to buy or sell to a precision the Exchange accepts
|
|
||||||
Rounded down
|
|
||||||
'''
|
|
||||||
if self._api.markets[pair]['precision']['amount']:
|
|
||||||
symbol_prec = self._api.markets[pair]['precision']['amount']
|
|
||||||
big_amount = amount * pow(10, symbol_prec)
|
|
||||||
amount = floor(big_amount) / pow(10, symbol_prec)
|
|
||||||
return amount
|
|
||||||
|
|
||||||
def symbol_price_prec(self, pair, price: float):
|
|
||||||
'''
|
|
||||||
Returns the price buying or selling with to the precision the Exchange accepts
|
|
||||||
Rounds up
|
|
||||||
'''
|
|
||||||
if self._api.markets[pair]['precision']['price']:
|
|
||||||
symbol_prec = self._api.markets[pair]['precision']['price']
|
|
||||||
big_price = price * pow(10, symbol_prec)
|
|
||||||
price = ceil(big_price) / pow(10, symbol_prec)
|
|
||||||
return price
|
|
||||||
|
|
||||||
def buy(self, pair: str, ordertype: str, amount: float,
|
|
||||||
rate: float, time_in_force) -> Dict:
|
|
||||||
if self._conf['dry_run']:
|
|
||||||
order_id = f'dry_run_buy_{randint(0, 10**6)}'
|
|
||||||
self._dry_run_open_orders[order_id] = {
|
|
||||||
'pair': pair,
|
|
||||||
'price': rate,
|
|
||||||
'amount': amount,
|
|
||||||
'type': ordertype,
|
|
||||||
'side': 'buy',
|
|
||||||
'remaining': 0.0,
|
|
||||||
'datetime': arrow.utcnow().isoformat(),
|
|
||||||
'status': 'closed',
|
|
||||||
'fee': None
|
|
||||||
}
|
|
||||||
return {'id': order_id}
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
|
||||||
amount = self.symbol_amount_prec(pair, amount)
|
|
||||||
rate = self.symbol_price_prec(pair, rate) if ordertype != 'market' else None
|
|
||||||
|
|
||||||
if time_in_force == 'gtc':
|
|
||||||
return self._api.create_order(pair, ordertype, 'buy', amount, rate)
|
|
||||||
else:
|
|
||||||
return self._api.create_order(pair, ordertype, 'buy',
|
|
||||||
amount, rate, {'timeInForce': time_in_force})
|
|
||||||
|
|
||||||
except ccxt.InsufficientFunds as e:
|
|
||||||
raise DependencyException(
|
|
||||||
f'Insufficient funds to create limit buy order on market {pair}.'
|
|
||||||
f'Tried to buy amount {amount} at rate {rate} (total {rate*amount}).'
|
|
||||||
f'Message: {e}')
|
|
||||||
except ccxt.InvalidOrder as e:
|
|
||||||
raise DependencyException(
|
|
||||||
f'Could not create limit buy order on market {pair}.'
|
|
||||||
f'Tried to buy amount {amount} at rate {rate} (total {rate*amount}).'
|
|
||||||
f'Message: {e}')
|
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not place buy order due to {e.__class__.__name__}. Message: {e}')
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(e)
|
|
||||||
|
|
||||||
def sell(self, pair: str, ordertype: str, amount: float,
|
|
||||||
rate: float, time_in_force='gtc') -> Dict:
|
|
||||||
if self._conf['dry_run']:
|
|
||||||
order_id = f'dry_run_sell_{randint(0, 10**6)}'
|
|
||||||
self._dry_run_open_orders[order_id] = {
|
|
||||||
'pair': pair,
|
|
||||||
'price': rate,
|
|
||||||
'amount': amount,
|
|
||||||
'type': ordertype,
|
|
||||||
'side': 'sell',
|
|
||||||
'remaining': 0.0,
|
|
||||||
'datetime': arrow.utcnow().isoformat(),
|
|
||||||
'status': 'closed'
|
|
||||||
}
|
|
||||||
return {'id': order_id}
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
|
||||||
amount = self.symbol_amount_prec(pair, amount)
|
|
||||||
rate = self.symbol_price_prec(pair, rate) if ordertype != 'market' else None
|
|
||||||
|
|
||||||
if time_in_force == 'gtc':
|
|
||||||
return self._api.create_order(pair, ordertype, 'sell', amount, rate)
|
|
||||||
else:
|
|
||||||
return self._api.create_order(pair, ordertype, 'sell',
|
|
||||||
amount, rate, {'timeInForce': time_in_force})
|
|
||||||
|
|
||||||
except ccxt.InsufficientFunds as e:
|
|
||||||
raise DependencyException(
|
|
||||||
f'Insufficient funds to create limit sell order on market {pair}.'
|
|
||||||
f'Tried to sell amount {amount} at rate {rate} (total {rate*amount}).'
|
|
||||||
f'Message: {e}')
|
|
||||||
except ccxt.InvalidOrder as e:
|
|
||||||
raise DependencyException(
|
|
||||||
f'Could not create limit sell order on market {pair}.'
|
|
||||||
f'Tried to sell amount {amount} at rate {rate} (total {rate*amount}).'
|
|
||||||
f'Message: {e}')
|
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not place sell order due to {e.__class__.__name__}. Message: {e}')
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(e)
|
|
||||||
|
|
||||||
def stoploss_limit(self, pair: str, amount: float, stop_price: float, rate: float) -> Dict:
|
|
||||||
"""
|
|
||||||
creates a stoploss limit order.
|
|
||||||
NOTICE: it is not supported by all exchanges. only binance is tested for now.
|
|
||||||
"""
|
|
||||||
|
|
||||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
|
||||||
amount = self.symbol_amount_prec(pair, amount)
|
|
||||||
rate = self.symbol_price_prec(pair, rate)
|
|
||||||
stop_price = self.symbol_price_prec(pair, stop_price)
|
|
||||||
|
|
||||||
# Ensure rate is less than stop price
|
|
||||||
if stop_price <= rate:
|
|
||||||
raise OperationalException(
|
|
||||||
'In stoploss limit order, stop price should be more than limit price')
|
|
||||||
|
|
||||||
if self._conf['dry_run']:
|
|
||||||
order_id = f'dry_run_buy_{randint(0, 10**6)}'
|
|
||||||
self._dry_run_open_orders[order_id] = {
|
|
||||||
'info': {},
|
|
||||||
'id': order_id,
|
|
||||||
'pair': pair,
|
|
||||||
'price': stop_price,
|
|
||||||
'amount': amount,
|
|
||||||
'type': 'stop_loss_limit',
|
|
||||||
'side': 'sell',
|
|
||||||
'remaining': amount,
|
|
||||||
'datetime': arrow.utcnow().isoformat(),
|
|
||||||
'status': 'open',
|
|
||||||
'fee': None
|
|
||||||
}
|
|
||||||
return self._dry_run_open_orders[order_id]
|
|
||||||
|
|
||||||
try:
|
|
||||||
order = self._api.create_order(pair, 'stop_loss_limit', 'sell',
|
|
||||||
amount, rate, {'stopPrice': stop_price})
|
|
||||||
logger.info('stoploss limit order added for %s. '
|
|
||||||
'stop price: %s. limit: %s' % (pair, stop_price, rate))
|
|
||||||
return order
|
|
||||||
|
|
||||||
except ccxt.InsufficientFunds as e:
|
|
||||||
raise DependencyException(
|
|
||||||
f'Insufficient funds to place stoploss limit order on market {pair}. '
|
|
||||||
f'Tried to put a stoploss amount {amount} with '
|
|
||||||
f'stop {stop_price} and limit {rate} (total {rate*amount}).'
|
|
||||||
f'Message: {e}')
|
|
||||||
except ccxt.InvalidOrder as e:
|
|
||||||
raise DependencyException(
|
|
||||||
f'Could not place stoploss limit order on market {pair}.'
|
|
||||||
f'Tried to place stoploss amount {amount} with '
|
|
||||||
f'stop {stop_price} and limit {rate} (total {rate*amount}).'
|
|
||||||
f'Message: {e}')
|
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not place stoploss limit order due to {e.__class__.__name__}. Message: {e}')
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(e)
|
|
||||||
|
|
||||||
@retrier
|
|
||||||
def get_balance(self, currency: str) -> float:
|
|
||||||
if self._conf['dry_run']:
|
|
||||||
return 999.9
|
|
||||||
|
|
||||||
# ccxt exception is already handled by get_balances
|
|
||||||
balances = self.get_balances()
|
|
||||||
balance = balances.get(currency)
|
|
||||||
if balance is None:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not get {currency} balance due to malformed exchange response: {balances}')
|
|
||||||
return balance['free']
|
|
||||||
|
|
||||||
@retrier
|
|
||||||
def get_balances(self) -> dict:
|
|
||||||
if self._conf['dry_run']:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
try:
|
|
||||||
balances = self._api.fetch_balance()
|
|
||||||
# Remove additional info from ccxt results
|
|
||||||
balances.pop("info", None)
|
|
||||||
balances.pop("free", None)
|
|
||||||
balances.pop("total", None)
|
|
||||||
balances.pop("used", None)
|
|
||||||
|
|
||||||
return balances
|
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not get balance due to {e.__class__.__name__}. Message: {e}')
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(e)
|
|
||||||
|
|
||||||
@retrier
|
|
||||||
def get_tickers(self) -> Dict:
|
|
||||||
try:
|
|
||||||
return self._api.fetch_tickers()
|
|
||||||
except ccxt.NotSupported as e:
|
|
||||||
raise OperationalException(
|
|
||||||
f'Exchange {self._api.name} does not support fetching tickers in batch.'
|
|
||||||
f'Message: {e}')
|
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not load tickers due to {e.__class__.__name__}. Message: {e}')
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(e)
|
|
||||||
|
|
||||||
@retrier
|
|
||||||
def get_ticker(self, pair: str, refresh: Optional[bool] = True) -> dict:
|
|
||||||
if refresh or pair not in self._cached_ticker.keys():
|
|
||||||
try:
|
|
||||||
if pair not in self._api.markets:
|
|
||||||
raise DependencyException(f"Pair {pair} not available")
|
|
||||||
data = self._api.fetch_ticker(pair)
|
|
||||||
try:
|
|
||||||
self._cached_ticker[pair] = {
|
|
||||||
'bid': float(data['bid']),
|
|
||||||
'ask': float(data['ask']),
|
|
||||||
}
|
|
||||||
except KeyError:
|
|
||||||
logger.debug("Could not cache ticker data for %s", pair)
|
|
||||||
return data
|
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not load ticker due to {e.__class__.__name__}. Message: {e}')
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(e)
|
|
||||||
else:
|
|
||||||
logger.info("returning cached ticker-data for %s", pair)
|
|
||||||
return self._cached_ticker[pair]
|
|
||||||
|
|
||||||
def get_history(self, pair: str, tick_interval: str,
|
|
||||||
since_ms: int) -> List:
|
|
||||||
"""
|
|
||||||
Gets candle history using asyncio and returns the list of candles.
|
|
||||||
Handles all async doing.
|
|
||||||
"""
|
|
||||||
return asyncio.get_event_loop().run_until_complete(
|
|
||||||
self._async_get_history(pair=pair, tick_interval=tick_interval,
|
|
||||||
since_ms=since_ms))
|
|
||||||
|
|
||||||
async def _async_get_history(self, pair: str,
|
|
||||||
tick_interval: str,
|
|
||||||
since_ms: int) -> List:
|
|
||||||
# Assume exchange returns 500 candles
|
|
||||||
_LIMIT = 500
|
|
||||||
|
|
||||||
one_call = constants.TICKER_INTERVAL_MINUTES[tick_interval] * 60 * _LIMIT * 1000
|
|
||||||
logger.debug("one_call: %s", one_call)
|
|
||||||
input_coroutines = [self._async_get_candle_history(
|
|
||||||
pair, tick_interval, since) for since in
|
|
||||||
range(since_ms, arrow.utcnow().timestamp * 1000, one_call)]
|
|
||||||
|
|
||||||
tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
|
|
||||||
|
|
||||||
# Combine tickers
|
|
||||||
data: List = []
|
|
||||||
for p, ticker_interval, ticker in tickers:
|
|
||||||
if p == pair:
|
|
||||||
data.extend(ticker)
|
|
||||||
# Sort data again after extending the result - above calls return in "async order"
|
|
||||||
data = sorted(data, key=lambda x: x[0])
|
|
||||||
logger.info("downloaded %s with length %s.", pair, len(data))
|
|
||||||
return data
|
|
||||||
|
|
||||||
def refresh_latest_ohlcv(self, pair_list: List[Tuple[str, str]]) -> List[Tuple[str, List]]:
|
|
||||||
"""
|
|
||||||
Refresh in-memory ohlcv asyncronously and set `_klines` with the result
|
|
||||||
"""
|
|
||||||
logger.debug("Refreshing ohlcv data for %d pairs", len(pair_list))
|
|
||||||
|
|
||||||
input_coroutines = []
|
|
||||||
|
|
||||||
# Gather corotines to run
|
|
||||||
for pair, ticker_interval in set(pair_list):
|
|
||||||
# Calculating ticker interval in second
|
|
||||||
interval_in_sec = constants.TICKER_INTERVAL_MINUTES[ticker_interval] * 60
|
|
||||||
|
|
||||||
if not ((self._pairs_last_refresh_time.get((pair, ticker_interval), 0)
|
|
||||||
+ interval_in_sec) >= arrow.utcnow().timestamp
|
|
||||||
and (pair, ticker_interval) in self._klines):
|
|
||||||
input_coroutines.append(self._async_get_candle_history(pair, ticker_interval))
|
|
||||||
else:
|
|
||||||
logger.debug("Using cached ohlcv data for %s, %s ...", pair, ticker_interval)
|
|
||||||
|
|
||||||
tickers = asyncio.get_event_loop().run_until_complete(
|
|
||||||
asyncio.gather(*input_coroutines, return_exceptions=True))
|
|
||||||
|
|
||||||
# handle caching
|
|
||||||
for res in tickers:
|
|
||||||
if isinstance(res, Exception):
|
|
||||||
logger.warning("Async code raised an exception: %s", res.__class__.__name__)
|
|
||||||
continue
|
|
||||||
pair = res[0]
|
|
||||||
tick_interval = res[1]
|
|
||||||
ticks = res[2]
|
|
||||||
# keeping last candle time as last refreshed time of the pair
|
|
||||||
if ticks:
|
|
||||||
self._pairs_last_refresh_time[(pair, tick_interval)] = ticks[-1][0] // 1000
|
|
||||||
# keeping parsed dataframe in cache
|
|
||||||
self._klines[(pair, tick_interval)] = parse_ticker_dataframe(
|
|
||||||
ticks, tick_interval, fill_missing=True)
|
|
||||||
return tickers
|
|
||||||
|
|
||||||
@retrier_async
|
|
||||||
async def _async_get_candle_history(self, pair: str, tick_interval: str,
|
|
||||||
since_ms: Optional[int] = None) -> Tuple[str, str, List]:
|
|
||||||
"""
|
|
||||||
Asyncronously gets candle histories using fetch_ohlcv
|
|
||||||
returns tuple: (pair, tick_interval, ohlcv_list)
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
# fetch ohlcv asynchronously
|
|
||||||
logger.debug("fetching %s, %s since %s ...", pair, tick_interval, since_ms)
|
|
||||||
|
|
||||||
data = await self._api_async.fetch_ohlcv(pair, timeframe=tick_interval,
|
|
||||||
since=since_ms)
|
|
||||||
|
|
||||||
# Because some exchange sort Tickers ASC and other DESC.
|
|
||||||
# Ex: Bittrex returns a list of tickers ASC (oldest first, newest last)
|
|
||||||
# when GDAX returns a list of tickers DESC (newest first, oldest last)
|
|
||||||
# Only sort if necessary to save computing time
|
|
||||||
try:
|
|
||||||
if data and data[0][0] > data[-1][0]:
|
|
||||||
data = sorted(data, key=lambda x: x[0])
|
|
||||||
except IndexError:
|
|
||||||
logger.exception("Error loading %s. Result was %s.", pair, data)
|
|
||||||
return pair, tick_interval, []
|
|
||||||
logger.debug("done fetching %s, %s ...", pair, tick_interval)
|
|
||||||
return pair, tick_interval, data
|
|
||||||
|
|
||||||
except ccxt.NotSupported as e:
|
|
||||||
raise OperationalException(
|
|
||||||
f'Exchange {self._api.name} does not support fetching historical candlestick data.'
|
|
||||||
f'Message: {e}')
|
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not load ticker history due to {e.__class__.__name__}. Message: {e}')
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(f'Could not fetch ticker data. Msg: {e}')
|
|
||||||
|
|
||||||
@retrier
|
|
||||||
def cancel_order(self, order_id: str, pair: str) -> None:
|
|
||||||
if self._conf['dry_run']:
|
|
||||||
return
|
|
||||||
|
|
||||||
try:
|
|
||||||
return self._api.cancel_order(order_id, pair)
|
|
||||||
except ccxt.InvalidOrder as e:
|
|
||||||
raise DependencyException(
|
|
||||||
f'Could not cancel order. Message: {e}')
|
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not cancel order due to {e.__class__.__name__}. Message: {e}')
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(e)
|
|
||||||
|
|
||||||
@retrier
|
|
||||||
def get_order(self, order_id: str, pair: str) -> Dict:
|
|
||||||
if self._conf['dry_run']:
|
|
||||||
order = self._dry_run_open_orders[order_id]
|
|
||||||
order.update({
|
|
||||||
'id': order_id
|
|
||||||
})
|
|
||||||
return order
|
|
||||||
try:
|
|
||||||
return self._api.fetch_order(order_id, pair)
|
|
||||||
except ccxt.InvalidOrder as e:
|
|
||||||
raise DependencyException(
|
|
||||||
f'Could not get order. Message: {e}')
|
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not get order due to {e.__class__.__name__}. Message: {e}')
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(e)
|
|
||||||
|
|
||||||
@retrier
|
|
||||||
def get_order_book(self, pair: str, limit: int = 100) -> dict:
|
|
||||||
"""
|
|
||||||
get order book level 2 from exchange
|
|
||||||
|
|
||||||
Notes:
|
|
||||||
20180619: bittrex doesnt support limits -.-
|
|
||||||
20180619: binance support limits but only on specific range
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
if self._api.name == 'Binance':
|
|
||||||
limit_range = [5, 10, 20, 50, 100, 500, 1000]
|
|
||||||
# get next-higher step in the limit_range list
|
|
||||||
limit = min(list(filter(lambda x: limit <= x, limit_range)))
|
|
||||||
# above script works like loop below (but with slightly better performance):
|
|
||||||
# for limitx in limit_range:
|
|
||||||
# if limit <= limitx:
|
|
||||||
# limit = limitx
|
|
||||||
# break
|
|
||||||
|
|
||||||
return self._api.fetch_l2_order_book(pair, limit)
|
|
||||||
except ccxt.NotSupported as e:
|
|
||||||
raise OperationalException(
|
|
||||||
f'Exchange {self._api.name} does not support fetching order book.'
|
|
||||||
f'Message: {e}')
|
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not get order book due to {e.__class__.__name__}. Message: {e}')
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(e)
|
|
||||||
|
|
||||||
@retrier
|
|
||||||
def get_trades_for_order(self, order_id: str, pair: str, since: datetime) -> List:
|
|
||||||
if self._conf['dry_run']:
|
|
||||||
return []
|
|
||||||
if not self.exchange_has('fetchMyTrades'):
|
|
||||||
return []
|
|
||||||
try:
|
|
||||||
# Allow 5s offset to catch slight time offsets (discovered in #1185)
|
|
||||||
my_trades = self._api.fetch_my_trades(pair, since.timestamp() - 5)
|
|
||||||
matched_trades = [trade for trade in my_trades if trade['order'] == order_id]
|
|
||||||
|
|
||||||
return matched_trades
|
|
||||||
|
|
||||||
except ccxt.NetworkError as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not get trades due to networking error. Message: {e}')
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(e)
|
|
||||||
|
|
||||||
def get_pair_detail_url(self, pair: str) -> str:
|
|
||||||
try:
|
|
||||||
url_base = self._api.urls.get('www')
|
|
||||||
base, quote = pair.split('/')
|
|
||||||
|
|
||||||
return url_base + _EXCHANGE_URLS[self._api.id].format(base=base, quote=quote)
|
|
||||||
except KeyError:
|
|
||||||
logger.warning('Could not get exchange url for %s', self.name)
|
|
||||||
return ""
|
|
||||||
|
|
||||||
@retrier
|
|
||||||
def get_markets(self) -> List[dict]:
|
|
||||||
try:
|
|
||||||
return self._api.fetch_markets()
|
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not load markets due to {e.__class__.__name__}. Message: {e}')
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(e)
|
|
||||||
|
|
||||||
@retrier
|
|
||||||
def get_fee(self, symbol='ETH/BTC', type='', side='', amount=1,
|
|
||||||
price=1, taker_or_maker='maker') -> float:
|
|
||||||
try:
|
|
||||||
# validate that markets are loaded before trying to get fee
|
|
||||||
if self._api.markets is None or len(self._api.markets) == 0:
|
|
||||||
self._api.load_markets()
|
|
||||||
|
|
||||||
return self._api.calculate_fee(symbol=symbol, type=type, side=side, amount=amount,
|
|
||||||
price=price, takerOrMaker=taker_or_maker)['rate']
|
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not get fee info due to {e.__class__.__name__}. Message: {e}')
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(e)
|
|
||||||
|
|||||||
85
freqtrade/exchange/binance.py
Normal file
85
freqtrade/exchange/binance.py
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
""" Binance exchange subclass """
|
||||||
|
import logging
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
import ccxt
|
||||||
|
|
||||||
|
from freqtrade import (DependencyException, InvalidOrderException,
|
||||||
|
OperationalException, TemporaryError)
|
||||||
|
from freqtrade.exchange import Exchange
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class Binance(Exchange):
|
||||||
|
|
||||||
|
_ft_has: Dict = {
|
||||||
|
"stoploss_on_exchange": True,
|
||||||
|
"order_time_in_force": ['gtc', 'fok', 'ioc'],
|
||||||
|
"trades_pagination": "id",
|
||||||
|
"trades_pagination_arg": "fromId",
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_order_book(self, pair: str, limit: int = 100) -> dict:
|
||||||
|
"""
|
||||||
|
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().get_order_book(pair, limit)
|
||||||
|
|
||||||
|
def stoploss_limit(self, pair: str, amount: float, stop_price: float, rate: float) -> Dict:
|
||||||
|
"""
|
||||||
|
creates a stoploss limit order.
|
||||||
|
this stoploss-limit is binance-specific.
|
||||||
|
It may work with a limited number of other exchanges, but this has not been tested yet.
|
||||||
|
|
||||||
|
"""
|
||||||
|
ordertype = "stop_loss_limit"
|
||||||
|
|
||||||
|
stop_price = self.symbol_price_prec(pair, stop_price)
|
||||||
|
|
||||||
|
# Ensure rate is less than stop price
|
||||||
|
if stop_price <= rate:
|
||||||
|
raise OperationalException(
|
||||||
|
'In stoploss limit order, stop price should be more than limit price')
|
||||||
|
|
||||||
|
if self._config['dry_run']:
|
||||||
|
dry_order = self.dry_run_order(
|
||||||
|
pair, ordertype, "sell", amount, stop_price)
|
||||||
|
return dry_order
|
||||||
|
|
||||||
|
try:
|
||||||
|
params = self._params.copy()
|
||||||
|
params.update({'stopPrice': stop_price})
|
||||||
|
|
||||||
|
amount = self.symbol_amount_prec(pair, amount)
|
||||||
|
|
||||||
|
rate = self.symbol_price_prec(pair, rate)
|
||||||
|
|
||||||
|
order = self._api.create_order(pair, ordertype, 'sell',
|
||||||
|
amount, rate, params)
|
||||||
|
logger.info('stoploss limit order added for %s. '
|
||||||
|
'stop price: %s. limit: %s', pair, stop_price, rate)
|
||||||
|
return order
|
||||||
|
except ccxt.InsufficientFunds as e:
|
||||||
|
raise DependencyException(
|
||||||
|
f'Insufficient funds to create {ordertype} sell order on market {pair}.'
|
||||||
|
f'Tried to sell amount {amount} at rate {rate}. '
|
||||||
|
f'Message: {e}') from e
|
||||||
|
except ccxt.InvalidOrder as e:
|
||||||
|
# Errors:
|
||||||
|
# `binance Order would trigger immediately.`
|
||||||
|
raise InvalidOrderException(
|
||||||
|
f'Could not create {ordertype} sell order on market {pair}. '
|
||||||
|
f'Tried to sell amount {amount} at rate {rate}. '
|
||||||
|
f'Message: {e}') from e
|
||||||
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||||
|
raise TemporaryError(
|
||||||
|
f'Could not place sell order due to {e.__class__.__name__}. Message: {e}') from e
|
||||||
|
except ccxt.BaseError as e:
|
||||||
|
raise OperationalException(e) from e
|
||||||
1125
freqtrade/exchange/exchange.py
Normal file
1125
freqtrade/exchange/exchange.py
Normal file
File diff suppressed because it is too large
Load Diff
50
freqtrade/exchange/kraken.py
Normal file
50
freqtrade/exchange/kraken.py
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
""" Kraken exchange subclass """
|
||||||
|
import logging
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
import ccxt
|
||||||
|
|
||||||
|
from freqtrade import OperationalException, TemporaryError
|
||||||
|
from freqtrade.exchange import Exchange
|
||||||
|
from freqtrade.exchange.exchange import retrier
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class Kraken(Exchange):
|
||||||
|
|
||||||
|
_params: Dict = {"trading_agreement": "agree"}
|
||||||
|
_ft_has: Dict = {
|
||||||
|
"trades_pagination": "id",
|
||||||
|
"trades_pagination_arg": "since",
|
||||||
|
}
|
||||||
|
|
||||||
|
@retrier
|
||||||
|
def get_balances(self) -> dict:
|
||||||
|
if self._config['dry_run']:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
try:
|
||||||
|
balances = self._api.fetch_balance()
|
||||||
|
# Remove additional info from ccxt results
|
||||||
|
balances.pop("info", None)
|
||||||
|
balances.pop("free", None)
|
||||||
|
balances.pop("total", None)
|
||||||
|
balances.pop("used", None)
|
||||||
|
|
||||||
|
orders = self._api.fetch_open_orders()
|
||||||
|
order_list = [(x["symbol"].split("/")[0 if x["side"] == "sell" else 1],
|
||||||
|
x["remaining"],
|
||||||
|
# Don't remove the below comment, this can be important for debuggung
|
||||||
|
# x["side"], x["amount"],
|
||||||
|
) for x in orders]
|
||||||
|
for bal in balances:
|
||||||
|
balances[bal]['used'] = sum(order[1] for order in order_list if order[0] == bal)
|
||||||
|
balances[bal]['free'] = balances[bal]['total'] - balances[bal]['used']
|
||||||
|
|
||||||
|
return balances
|
||||||
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||||
|
raise TemporaryError(
|
||||||
|
f'Could not get balance due to {e.__class__.__name__}. Message: {e}') from e
|
||||||
|
except ccxt.BaseError as e:
|
||||||
|
raise OperationalException(e) from e
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,40 +0,0 @@
|
|||||||
from math import cos, exp, pi, sqrt
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import talib as ta
|
|
||||||
from pandas import Series
|
|
||||||
|
|
||||||
|
|
||||||
def went_up(series: Series) -> bool:
|
|
||||||
return series > series.shift(1)
|
|
||||||
|
|
||||||
|
|
||||||
def went_down(series: Series) -> bool:
|
|
||||||
return series < series.shift(1)
|
|
||||||
|
|
||||||
|
|
||||||
def ehlers_super_smoother(series: Series, smoothing: float = 6) -> Series:
|
|
||||||
magic = pi * sqrt(2) / smoothing
|
|
||||||
a1 = exp(-magic)
|
|
||||||
coeff2 = 2 * a1 * cos(magic)
|
|
||||||
coeff3 = -a1 * a1
|
|
||||||
coeff1 = (1 - coeff2 - coeff3) / 2
|
|
||||||
|
|
||||||
filtered = series.copy()
|
|
||||||
|
|
||||||
for i in range(2, len(series)):
|
|
||||||
filtered.iloc[i] = coeff1 * (series.iloc[i] + series.iloc[i-1]) + \
|
|
||||||
coeff2 * filtered.iloc[i-1] + coeff3 * filtered.iloc[i-2]
|
|
||||||
|
|
||||||
return filtered
|
|
||||||
|
|
||||||
|
|
||||||
def fishers_inverse(series: Series, smoothing: float = 0) -> np.ndarray:
|
|
||||||
""" Does a smoothed fishers inverse transformation.
|
|
||||||
Can be used with any oscillator that goes from 0 to 100 like RSI or MFI """
|
|
||||||
v1 = 0.1 * (series - 50)
|
|
||||||
if smoothing > 0:
|
|
||||||
v2 = ta.WMA(v1.values, timeperiod=smoothing)
|
|
||||||
else:
|
|
||||||
v2 = v1
|
|
||||||
return (np.exp(2 * v2)-1) / (np.exp(2 * v2) + 1)
|
|
||||||
50
freqtrade/loggers.py
Normal file
50
freqtrade/loggers.py
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from logging.handlers import RotatingFileHandler
|
||||||
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _set_loggers(verbosity: int = 0) -> None:
|
||||||
|
"""
|
||||||
|
Set the logging level for third party libraries
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
|
||||||
|
logging.getLogger('requests').setLevel(
|
||||||
|
logging.INFO if verbosity <= 1 else logging.DEBUG
|
||||||
|
)
|
||||||
|
logging.getLogger("urllib3").setLevel(
|
||||||
|
logging.INFO if verbosity <= 1 else logging.DEBUG
|
||||||
|
)
|
||||||
|
logging.getLogger('ccxt.base.exchange').setLevel(
|
||||||
|
logging.INFO if verbosity <= 2 else logging.DEBUG
|
||||||
|
)
|
||||||
|
logging.getLogger('telegram').setLevel(logging.INFO)
|
||||||
|
|
||||||
|
|
||||||
|
def setup_logging(config: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Process -v/--verbose, --logfile options
|
||||||
|
"""
|
||||||
|
# Log level
|
||||||
|
verbosity = config['verbosity']
|
||||||
|
|
||||||
|
# Log to stdout, not stderr
|
||||||
|
log_handlers: List[logging.Handler] = [logging.StreamHandler(sys.stdout)]
|
||||||
|
|
||||||
|
if config.get('logfile'):
|
||||||
|
log_handlers.append(RotatingFileHandler(config['logfile'],
|
||||||
|
maxBytes=1024 * 1024, # 1Mb
|
||||||
|
backupCount=10))
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO if verbosity < 1 else logging.DEBUG,
|
||||||
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||||
|
handlers=log_handlers
|
||||||
|
)
|
||||||
|
_set_loggers(verbosity)
|
||||||
|
logger.info('Verbosity set to %s', verbosity)
|
||||||
@@ -3,87 +3,62 @@
|
|||||||
Main Freqtrade bot script.
|
Main Freqtrade bot script.
|
||||||
Read the documentation to know what cli arguments you need.
|
Read the documentation to know what cli arguments you need.
|
||||||
"""
|
"""
|
||||||
import logging
|
|
||||||
import sys
|
import sys
|
||||||
from argparse import Namespace
|
# check min. python version
|
||||||
from typing import List
|
if sys.version_info < (3, 6):
|
||||||
|
sys.exit("Freqtrade requires Python version >= 3.6")
|
||||||
|
|
||||||
|
# flake8: noqa E402
|
||||||
|
import logging
|
||||||
|
from typing import Any, List
|
||||||
|
|
||||||
from freqtrade import OperationalException
|
from freqtrade import OperationalException
|
||||||
from freqtrade.arguments import Arguments
|
from freqtrade.configuration import Arguments
|
||||||
from freqtrade.configuration import Configuration, set_loggers
|
from freqtrade.worker import Worker
|
||||||
from freqtrade.freqtradebot import FreqtradeBot
|
|
||||||
from freqtrade.state import State
|
|
||||||
from freqtrade.rpc import RPCMessageType
|
|
||||||
|
|
||||||
logger = logging.getLogger('freqtrade')
|
logger = logging.getLogger('freqtrade')
|
||||||
|
|
||||||
|
|
||||||
def main(sysargv: List[str]) -> None:
|
def main(sysargv: List[str] = None) -> None:
|
||||||
"""
|
"""
|
||||||
This function will initiate the bot and start the trading loop.
|
This function will initiate the bot and start the trading loop.
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
arguments = Arguments(
|
|
||||||
sysargv,
|
|
||||||
'Free, open source crypto trading bot'
|
|
||||||
)
|
|
||||||
args = arguments.get_parsed_arg()
|
|
||||||
|
|
||||||
# A subcommand has been issued.
|
return_code: Any = 1
|
||||||
# Means if Backtesting or Hyperopt have been called we exit the bot
|
worker = None
|
||||||
if hasattr(args, 'func'):
|
|
||||||
args.func(args)
|
|
||||||
return
|
|
||||||
|
|
||||||
freqtrade = None
|
|
||||||
return_code = 1
|
|
||||||
try:
|
try:
|
||||||
# Load and validate configuration
|
arguments = Arguments(sysargv)
|
||||||
config = Configuration(args, None).get_config()
|
args = arguments.get_parsed_arg()
|
||||||
|
|
||||||
# Init the bot
|
# A subcommand has been issued.
|
||||||
freqtrade = FreqtradeBot(config)
|
# Means if Backtesting or Hyperopt have been called we exit the bot
|
||||||
|
if 'func' in args:
|
||||||
state = None
|
args['func'](args)
|
||||||
while True:
|
# TODO: fetch return_code as returned by the command function here
|
||||||
state = freqtrade.worker(old_state=state)
|
return_code = 0
|
||||||
if state == State.RELOAD_CONF:
|
else:
|
||||||
freqtrade = reconfigure(freqtrade, args)
|
# Load and run worker
|
||||||
|
worker = Worker(args)
|
||||||
|
worker.run()
|
||||||
|
|
||||||
|
except SystemExit as e:
|
||||||
|
return_code = e
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
logger.info('SIGINT received, aborting ...')
|
logger.info('SIGINT received, aborting ...')
|
||||||
return_code = 0
|
return_code = 0
|
||||||
except OperationalException as e:
|
except OperationalException as e:
|
||||||
logger.error(str(e))
|
logger.error(str(e))
|
||||||
return_code = 2
|
return_code = 2
|
||||||
except BaseException:
|
except Exception:
|
||||||
logger.exception('Fatal exception!')
|
logger.exception('Fatal exception!')
|
||||||
finally:
|
finally:
|
||||||
if freqtrade:
|
if worker:
|
||||||
freqtrade.rpc.send_msg({
|
worker.exit()
|
||||||
'type': RPCMessageType.STATUS_NOTIFICATION,
|
|
||||||
'status': 'process died'
|
|
||||||
})
|
|
||||||
freqtrade.cleanup()
|
|
||||||
sys.exit(return_code)
|
sys.exit(return_code)
|
||||||
|
|
||||||
|
|
||||||
def reconfigure(freqtrade: FreqtradeBot, args: Namespace) -> FreqtradeBot:
|
|
||||||
"""
|
|
||||||
Cleans up current instance, reloads the configuration and returns the new instance
|
|
||||||
"""
|
|
||||||
# Clean up current modules
|
|
||||||
freqtrade.cleanup()
|
|
||||||
|
|
||||||
# Create new instance
|
|
||||||
freqtrade = FreqtradeBot(Configuration(args, None).get_config())
|
|
||||||
freqtrade.rpc.send_msg({
|
|
||||||
'type': RPCMessageType.STATUS_NOTIFICATION,
|
|
||||||
'status': 'config reloaded'
|
|
||||||
})
|
|
||||||
return freqtrade
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
set_loggers()
|
main()
|
||||||
main(sys.argv[1:])
|
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
"""
|
"""
|
||||||
Various tool function for Freqtrade and scripts
|
Various tool function for Freqtrade and scripts
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import gzip
|
import gzip
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Dict
|
from pathlib import Path
|
||||||
|
from typing.io import IO
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from pandas import DataFrame
|
|
||||||
import rapidjson
|
import rapidjson
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -41,25 +40,7 @@ def datesarray_to_datetimearray(dates: np.ndarray) -> np.ndarray:
|
|||||||
return dates.dt.to_pydatetime()
|
return dates.dt.to_pydatetime()
|
||||||
|
|
||||||
|
|
||||||
def common_datearray(dfs: Dict[str, DataFrame]) -> np.ndarray:
|
def file_dump_json(filename: Path, data, is_zip=False) -> None:
|
||||||
"""
|
|
||||||
Return dates from Dataframe
|
|
||||||
:param dfs: Dict with format pair: pair_data
|
|
||||||
:return: List of dates
|
|
||||||
"""
|
|
||||||
alldates = {}
|
|
||||||
for pair, pair_data in dfs.items():
|
|
||||||
dates = datesarray_to_datetimearray(pair_data['date'])
|
|
||||||
for date in dates:
|
|
||||||
alldates[date] = 1
|
|
||||||
lst = []
|
|
||||||
for date, _ in alldates.items():
|
|
||||||
lst.append(date)
|
|
||||||
arr = np.array(lst)
|
|
||||||
return np.sort(arr, axis=0)
|
|
||||||
|
|
||||||
|
|
||||||
def file_dump_json(filename, data, is_zip=False) -> None:
|
|
||||||
"""
|
"""
|
||||||
Dump JSON data into a file
|
Dump JSON data into a file
|
||||||
:param filename: file to create
|
:param filename: file to create
|
||||||
@@ -69,8 +50,8 @@ def file_dump_json(filename, data, is_zip=False) -> None:
|
|||||||
logger.info(f'dumping json to "{filename}"')
|
logger.info(f'dumping json to "{filename}"')
|
||||||
|
|
||||||
if is_zip:
|
if is_zip:
|
||||||
if not filename.endswith('.gz'):
|
if filename.suffix != '.gz':
|
||||||
filename = filename + '.gz'
|
filename = filename.with_suffix('.gz')
|
||||||
with gzip.open(filename, 'w') as fp:
|
with gzip.open(filename, 'w') as fp:
|
||||||
rapidjson.dump(data, fp, default=str, number_mode=rapidjson.NM_NATIVE)
|
rapidjson.dump(data, fp, default=str, number_mode=rapidjson.NM_NATIVE)
|
||||||
else:
|
else:
|
||||||
@@ -80,7 +61,7 @@ def file_dump_json(filename, data, is_zip=False) -> None:
|
|||||||
logger.debug(f'done json to "{filename}"')
|
logger.debug(f'done json to "{filename}"')
|
||||||
|
|
||||||
|
|
||||||
def json_load(datafile):
|
def json_load(datafile: IO):
|
||||||
"""
|
"""
|
||||||
load data with rapidjson
|
load data with rapidjson
|
||||||
Use this to have a consistent experience,
|
Use this to have a consistent experience,
|
||||||
@@ -91,8 +72,10 @@ def json_load(datafile):
|
|||||||
|
|
||||||
def file_load_json(file):
|
def file_load_json(file):
|
||||||
|
|
||||||
gzipfile = file.with_suffix(file.suffix + '.gz')
|
if file.suffix != ".gz":
|
||||||
|
gzipfile = file.with_suffix(file.suffix + '.gz')
|
||||||
|
else:
|
||||||
|
gzipfile = file
|
||||||
# Try gzip file first, otherwise regular json file.
|
# Try gzip file first, otherwise regular json file.
|
||||||
if gzipfile.is_file():
|
if gzipfile.is_file():
|
||||||
logger.debug('Loading ticker data from file %s', gzipfile)
|
logger.debug('Loading ticker data from file %s', gzipfile)
|
||||||
@@ -113,3 +96,34 @@ def format_ms_time(date: int) -> str:
|
|||||||
: epoch-string in ms
|
: epoch-string in ms
|
||||||
"""
|
"""
|
||||||
return datetime.fromtimestamp(date/1000.0).strftime('%Y-%m-%dT%H:%M:%S')
|
return datetime.fromtimestamp(date/1000.0).strftime('%Y-%m-%dT%H:%M:%S')
|
||||||
|
|
||||||
|
|
||||||
|
def deep_merge_dicts(source, destination):
|
||||||
|
"""
|
||||||
|
Values from Source override destination, destination is returned (and modified!!)
|
||||||
|
Sample:
|
||||||
|
>>> a = { 'first' : { 'rows' : { 'pass' : 'dog', 'number' : '1' } } }
|
||||||
|
>>> b = { 'first' : { 'rows' : { 'fail' : 'cat', 'number' : '5' } } }
|
||||||
|
>>> merge(b, a) == { 'first' : { 'rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }
|
||||||
|
True
|
||||||
|
"""
|
||||||
|
for key, value in source.items():
|
||||||
|
if isinstance(value, dict):
|
||||||
|
# get node or create one
|
||||||
|
node = destination.setdefault(key, {})
|
||||||
|
deep_merge_dicts(value, node)
|
||||||
|
else:
|
||||||
|
destination[key] = value
|
||||||
|
|
||||||
|
return destination
|
||||||
|
|
||||||
|
|
||||||
|
def round_dict(d, n):
|
||||||
|
"""
|
||||||
|
Rounds float values in the dict to n digits after the decimal point.
|
||||||
|
"""
|
||||||
|
return {k: (round(v, n) if isinstance(v, float) else v) for k, v in d.items()}
|
||||||
|
|
||||||
|
|
||||||
|
def plural(num, singular: str, plural: str = None) -> str:
|
||||||
|
return singular if (num == 1 or num == -1) else plural or singular + 's'
|
||||||
|
|||||||
@@ -1,49 +1,102 @@
|
|||||||
# pragma pylint: disable=missing-docstring
|
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from datetime import datetime
|
from typing import Any, Dict
|
||||||
from typing import Dict, Tuple
|
|
||||||
import operator
|
|
||||||
|
|
||||||
import arrow
|
from freqtrade import DependencyException, constants, OperationalException
|
||||||
from pandas import DataFrame
|
from freqtrade.state import RunMode
|
||||||
|
from freqtrade.utils import setup_utils_configuration
|
||||||
|
|
||||||
from freqtrade.optimize.default_hyperopt import DefaultHyperOpts # noqa: F401
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def get_timeframe(data: Dict[str, DataFrame]) -> Tuple[arrow.Arrow, arrow.Arrow]:
|
def setup_configuration(args: Dict[str, Any], method: RunMode) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Get the maximum timeframe for the given backtest data
|
Prepare the configuration for the Hyperopt module
|
||||||
:param data: dictionary with preprocessed backtesting data
|
:param args: Cli args from Arguments()
|
||||||
:return: tuple containing min_date, max_date
|
:return: Configuration
|
||||||
"""
|
"""
|
||||||
timeframe = [
|
config = setup_utils_configuration(args, method)
|
||||||
(arrow.get(frame['date'].min()), arrow.get(frame['date'].max()))
|
|
||||||
for frame in data.values()
|
if method == RunMode.BACKTEST:
|
||||||
]
|
if config['stake_amount'] == constants.UNLIMITED_STAKE_AMOUNT:
|
||||||
return min(timeframe, key=operator.itemgetter(0))[0], \
|
raise DependencyException('stake amount could not be "%s" for backtesting' %
|
||||||
max(timeframe, key=operator.itemgetter(1))[1]
|
constants.UNLIMITED_STAKE_AMOUNT)
|
||||||
|
|
||||||
|
return config
|
||||||
|
|
||||||
|
|
||||||
def validate_backtest_data(data: Dict[str, DataFrame], min_date: datetime,
|
def start_backtesting(args: Dict[str, Any]) -> None:
|
||||||
max_date: datetime, ticker_interval_mins: int) -> bool:
|
|
||||||
"""
|
"""
|
||||||
Validates preprocessed backtesting data for missing values and shows warnings about it that.
|
Start Backtesting script
|
||||||
|
:param args: Cli args from Arguments()
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
# Import here to avoid loading backtesting module when it's not used
|
||||||
|
from freqtrade.optimize.backtesting import Backtesting
|
||||||
|
|
||||||
:param data: dictionary with preprocessed backtesting data
|
# Initialize configuration
|
||||||
:param min_date: start-date of the data
|
config = setup_configuration(args, RunMode.BACKTEST)
|
||||||
:param max_date: end-date of the data
|
|
||||||
:param ticker_interval_mins: ticker interval in minutes
|
logger.info('Starting freqtrade in Backtesting mode')
|
||||||
|
|
||||||
|
# Initialize backtesting object
|
||||||
|
backtesting = Backtesting(config)
|
||||||
|
backtesting.start()
|
||||||
|
|
||||||
|
|
||||||
|
def start_hyperopt(args: Dict[str, Any]) -> None:
|
||||||
"""
|
"""
|
||||||
# total difference in minutes / interval-minutes
|
Start hyperopt script
|
||||||
expected_frames = int((max_date - min_date).total_seconds() // 60 // ticker_interval_mins)
|
:param args: Cli args from Arguments()
|
||||||
found_missing = False
|
:return: None
|
||||||
for pair, df in data.items():
|
"""
|
||||||
dflen = len(df)
|
# Import here to avoid loading hyperopt module when it's not used
|
||||||
if dflen < expected_frames:
|
try:
|
||||||
found_missing = True
|
from filelock import FileLock, Timeout
|
||||||
logger.warning("%s has missing frames: expected %s, got %s, that's %s missing values",
|
from freqtrade.optimize.hyperopt import Hyperopt
|
||||||
pair, expected_frames, dflen, expected_frames - dflen)
|
except ImportError as e:
|
||||||
return found_missing
|
raise OperationalException(
|
||||||
|
f"{e}. Please ensure that the hyperopt dependencies are installed.") from e
|
||||||
|
# Initialize configuration
|
||||||
|
config = setup_configuration(args, RunMode.HYPEROPT)
|
||||||
|
|
||||||
|
logger.info('Starting freqtrade in Hyperopt mode')
|
||||||
|
|
||||||
|
lock = FileLock(Hyperopt.get_lock_filename(config))
|
||||||
|
|
||||||
|
try:
|
||||||
|
with lock.acquire(timeout=1):
|
||||||
|
|
||||||
|
# Remove noisy log messages
|
||||||
|
logging.getLogger('hyperopt.tpe').setLevel(logging.WARNING)
|
||||||
|
logging.getLogger('filelock').setLevel(logging.WARNING)
|
||||||
|
|
||||||
|
# Initialize backtesting object
|
||||||
|
hyperopt = Hyperopt(config)
|
||||||
|
hyperopt.start()
|
||||||
|
|
||||||
|
except Timeout:
|
||||||
|
logger.info("Another running instance of freqtrade Hyperopt detected.")
|
||||||
|
logger.info("Simultaneous execution of multiple Hyperopt commands is not supported. "
|
||||||
|
"Hyperopt module is resource hungry. Please run your Hyperopts sequentially "
|
||||||
|
"or on separate machines.")
|
||||||
|
logger.info("Quitting now.")
|
||||||
|
# TODO: return False here in order to help freqtrade to exit
|
||||||
|
# with non-zero exit code...
|
||||||
|
# Same in Edge and Backtesting start() functions.
|
||||||
|
|
||||||
|
|
||||||
|
def start_edge(args: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Start Edge script
|
||||||
|
:param args: Cli args from Arguments()
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
from freqtrade.optimize.edge_cli import EdgeCli
|
||||||
|
# Initialize configuration
|
||||||
|
config = setup_configuration(args, RunMode.EDGE)
|
||||||
|
logger.info('Starting freqtrade in Edge mode')
|
||||||
|
|
||||||
|
# Initialize Edge object
|
||||||
|
edge_cli = EdgeCli(config)
|
||||||
|
edge_cli.start()
|
||||||
|
|||||||
@@ -4,26 +4,24 @@
|
|||||||
This module contains the backtesting logic
|
This module contains the backtesting logic
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
from argparse import Namespace
|
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, List, NamedTuple, Optional
|
from typing import Any, Dict, List, NamedTuple, Optional
|
||||||
|
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
from tabulate import tabulate
|
|
||||||
|
|
||||||
from freqtrade import optimize
|
from freqtrade import OperationalException
|
||||||
from freqtrade import DependencyException, constants
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.arguments import Arguments
|
|
||||||
from freqtrade.configuration import Configuration
|
|
||||||
from freqtrade.exchange import Exchange
|
|
||||||
from freqtrade.data import history
|
from freqtrade.data import history
|
||||||
|
from freqtrade.data.dataprovider import DataProvider
|
||||||
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
from freqtrade.misc import file_dump_json
|
from freqtrade.misc import file_dump_json
|
||||||
from freqtrade.persistence import Trade
|
from freqtrade.persistence import Trade
|
||||||
from freqtrade.resolvers import StrategyResolver
|
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode
|
||||||
from freqtrade.strategy.interface import SellType, IStrategy
|
from freqtrade.strategy.interface import IStrategy, SellType
|
||||||
|
from tabulate import tabulate
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -46,7 +44,7 @@ class BacktestResult(NamedTuple):
|
|||||||
sell_reason: SellType
|
sell_reason: SellType
|
||||||
|
|
||||||
|
|
||||||
class Backtesting(object):
|
class Backtesting:
|
||||||
"""
|
"""
|
||||||
Backtesting class, this class contains all the logic to run a backtest
|
Backtesting class, this class contains all the logic to run a backtest
|
||||||
|
|
||||||
@@ -65,34 +63,45 @@ class Backtesting(object):
|
|||||||
self.config['exchange']['uid'] = ''
|
self.config['exchange']['uid'] = ''
|
||||||
self.config['dry_run'] = True
|
self.config['dry_run'] = True
|
||||||
self.strategylist: List[IStrategy] = []
|
self.strategylist: List[IStrategy] = []
|
||||||
|
self.exchange = ExchangeResolver(self.config['exchange']['name'], self.config).exchange
|
||||||
|
|
||||||
|
if config.get('fee'):
|
||||||
|
self.fee = config['fee']
|
||||||
|
else:
|
||||||
|
self.fee = self.exchange.get_fee()
|
||||||
|
|
||||||
|
if self.config.get('runmode') != RunMode.HYPEROPT:
|
||||||
|
self.dataprovider = DataProvider(self.config, self.exchange)
|
||||||
|
IStrategy.dp = self.dataprovider
|
||||||
|
|
||||||
if self.config.get('strategy_list', None):
|
if self.config.get('strategy_list', None):
|
||||||
# Force one interval
|
|
||||||
self.ticker_interval = str(self.config.get('ticker_interval'))
|
|
||||||
self.ticker_interval_mins = constants.TICKER_INTERVAL_MINUTES[self.ticker_interval]
|
|
||||||
for strat in list(self.config['strategy_list']):
|
for strat in list(self.config['strategy_list']):
|
||||||
stratconf = deepcopy(self.config)
|
stratconf = deepcopy(self.config)
|
||||||
stratconf['strategy'] = strat
|
stratconf['strategy'] = strat
|
||||||
self.strategylist.append(StrategyResolver(stratconf).strategy)
|
self.strategylist.append(StrategyResolver(stratconf).strategy)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# only one strategy
|
# No strategy list specified, only one strategy
|
||||||
self.strategylist.append(StrategyResolver(self.config).strategy)
|
self.strategylist.append(StrategyResolver(self.config).strategy)
|
||||||
# Load one strategy
|
|
||||||
self._set_strategy(self.strategylist[0])
|
|
||||||
|
|
||||||
self.exchange = Exchange(self.config)
|
if "ticker_interval" not in self.config:
|
||||||
self.fee = self.exchange.get_fee()
|
raise OperationalException("Ticker-interval needs to be set in either configuration "
|
||||||
|
"or as cli argument `--ticker-interval 5m`")
|
||||||
|
self.ticker_interval = str(self.config.get('ticker_interval'))
|
||||||
|
self.ticker_interval_mins = timeframe_to_minutes(self.ticker_interval)
|
||||||
|
|
||||||
|
# Load one (first) strategy
|
||||||
|
self._set_strategy(self.strategylist[0])
|
||||||
|
|
||||||
def _set_strategy(self, strategy):
|
def _set_strategy(self, strategy):
|
||||||
"""
|
"""
|
||||||
Load strategy into backtesting
|
Load strategy into backtesting
|
||||||
"""
|
"""
|
||||||
self.strategy = strategy
|
self.strategy = strategy
|
||||||
self.ticker_interval = self.config.get('ticker_interval')
|
# Set stoploss_on_exchange to false for backtesting,
|
||||||
self.ticker_interval_mins = constants.TICKER_INTERVAL_MINUTES[self.ticker_interval]
|
# since a "perfect" stoploss-sell is assumed anyway
|
||||||
self.tickerdata_to_dataframe = strategy.tickerdata_to_dataframe
|
# And the regular "stoploss" function would not apply to that case
|
||||||
self.advise_buy = strategy.advise_buy
|
self.strategy.order_types['stoploss_on_exchange'] = False
|
||||||
self.advise_sell = strategy.advise_sell
|
|
||||||
|
|
||||||
def _generate_text_table(self, data: Dict[str, Dict], results: DataFrame,
|
def _generate_text_table(self, data: Dict[str, Dict], results: DataFrame,
|
||||||
skip_nan: bool = False) -> str:
|
skip_nan: bool = False) -> str:
|
||||||
@@ -140,8 +149,8 @@ class Backtesting(object):
|
|||||||
len(results[results.profit_abs < 0])
|
len(results[results.profit_abs < 0])
|
||||||
])
|
])
|
||||||
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
||||||
return tabulate(tabular_data, headers=headers, # type: ignore
|
return tabulate(tabular_data, headers=headers,
|
||||||
floatfmt=floatfmt, tablefmt="pipe")
|
floatfmt=floatfmt, tablefmt="pipe") # type: ignore
|
||||||
|
|
||||||
def _generate_text_table_sell_reason(self, data: Dict[str, Dict], results: DataFrame) -> str:
|
def _generate_text_table_sell_reason(self, data: Dict[str, Dict], results: DataFrame) -> str:
|
||||||
"""
|
"""
|
||||||
@@ -179,10 +188,10 @@ class Backtesting(object):
|
|||||||
len(results[results.profit_abs < 0])
|
len(results[results.profit_abs < 0])
|
||||||
])
|
])
|
||||||
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
||||||
return tabulate(tabular_data, headers=headers, # type: ignore
|
return tabulate(tabular_data, headers=headers,
|
||||||
floatfmt=floatfmt, tablefmt="pipe")
|
floatfmt=floatfmt, tablefmt="pipe") # type: ignore
|
||||||
|
|
||||||
def _store_backtest_result(self, recordfilename: str, results: DataFrame,
|
def _store_backtest_result(self, recordfilename: Path, results: DataFrame,
|
||||||
strategyname: Optional[str] = None) -> None:
|
strategyname: Optional[str] = None) -> None:
|
||||||
|
|
||||||
records = [(t.pair, t.profit_percent, t.open_time.timestamp(),
|
records = [(t.pair, t.profit_percent, t.open_time.timestamp(),
|
||||||
@@ -193,53 +202,82 @@ class Backtesting(object):
|
|||||||
if records:
|
if records:
|
||||||
if strategyname:
|
if strategyname:
|
||||||
# Inject strategyname to filename
|
# Inject strategyname to filename
|
||||||
recname = Path(recordfilename)
|
recordfilename = Path.joinpath(
|
||||||
recordfilename = str(Path.joinpath(
|
recordfilename.parent,
|
||||||
recname.parent, f'{recname.stem}-{strategyname}').with_suffix(recname.suffix))
|
f'{recordfilename.stem}-{strategyname}').with_suffix(recordfilename.suffix)
|
||||||
logger.info('Dumping backtest results to %s', recordfilename)
|
logger.info(f'Dumping backtest results to {recordfilename}')
|
||||||
file_dump_json(recordfilename, records)
|
file_dump_json(recordfilename, records)
|
||||||
|
|
||||||
|
def _get_ticker_list(self, processed) -> Dict[str, DataFrame]:
|
||||||
|
"""
|
||||||
|
Helper function to convert a processed tickerlist into a list for performance reasons.
|
||||||
|
|
||||||
|
Used by backtest() - so keep this optimized for performance.
|
||||||
|
"""
|
||||||
|
headers = ['date', 'buy', 'open', 'close', 'sell', 'low', 'high']
|
||||||
|
ticker: Dict = {}
|
||||||
|
# Create ticker dict
|
||||||
|
for pair, pair_data in processed.items():
|
||||||
|
pair_data['buy'], pair_data['sell'] = 0, 0 # cleanup from previous run
|
||||||
|
|
||||||
|
ticker_data = self.strategy.advise_sell(
|
||||||
|
self.strategy.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy()
|
||||||
|
|
||||||
|
# to avoid using data from future, we buy/sell with signal from previous candle
|
||||||
|
ticker_data.loc[:, 'buy'] = ticker_data['buy'].shift(1)
|
||||||
|
ticker_data.loc[:, 'sell'] = ticker_data['sell'].shift(1)
|
||||||
|
|
||||||
|
ticker_data.drop(ticker_data.head(1).index, inplace=True)
|
||||||
|
|
||||||
|
# Convert from Pandas to list for performance reasons
|
||||||
|
# (Looping Pandas is slow.)
|
||||||
|
ticker[pair] = [x for x in ticker_data.itertuples()]
|
||||||
|
return ticker
|
||||||
|
|
||||||
def _get_sell_trade_entry(
|
def _get_sell_trade_entry(
|
||||||
self, pair: str, buy_row: DataFrame,
|
self, pair: str, buy_row: DataFrame,
|
||||||
partial_ticker: List, trade_count_lock: Dict, args: Dict) -> Optional[BacktestResult]:
|
partial_ticker: List, trade_count_lock: Dict,
|
||||||
|
stake_amount: float, max_open_trades: int) -> Optional[BacktestResult]:
|
||||||
|
|
||||||
stake_amount = args['stake_amount']
|
|
||||||
max_open_trades = args.get('max_open_trades', 0)
|
|
||||||
trade = Trade(
|
trade = Trade(
|
||||||
|
pair=pair,
|
||||||
open_rate=buy_row.open,
|
open_rate=buy_row.open,
|
||||||
open_date=buy_row.date,
|
open_date=buy_row.date,
|
||||||
stake_amount=stake_amount,
|
stake_amount=stake_amount,
|
||||||
amount=stake_amount / buy_row.open,
|
amount=stake_amount / buy_row.open,
|
||||||
fee_open=self.fee,
|
fee_open=self.fee,
|
||||||
fee_close=self.fee
|
fee_close=self.fee,
|
||||||
|
is_open=True,
|
||||||
)
|
)
|
||||||
|
logger.debug(f"{pair} - Backtesting emulates creation of new trade: {trade}.")
|
||||||
# calculate win/lose forwards from buy point
|
# calculate win/lose forwards from buy point
|
||||||
for sell_row in partial_ticker:
|
for sell_row in partial_ticker:
|
||||||
if max_open_trades > 0:
|
if max_open_trades > 0:
|
||||||
# Increase trade_count_lock for every iteration
|
# Increase trade_count_lock for every iteration
|
||||||
trade_count_lock[sell_row.date] = trade_count_lock.get(sell_row.date, 0) + 1
|
trade_count_lock[sell_row.date] = trade_count_lock.get(sell_row.date, 0) + 1
|
||||||
|
|
||||||
buy_signal = sell_row.buy
|
sell = self.strategy.should_sell(trade, sell_row.open, sell_row.date, sell_row.buy,
|
||||||
sell = self.strategy.should_sell(trade, sell_row.open, sell_row.date, buy_signal,
|
|
||||||
sell_row.sell, low=sell_row.low, high=sell_row.high)
|
sell_row.sell, low=sell_row.low, high=sell_row.high)
|
||||||
if sell.sell_flag:
|
if sell.sell_flag:
|
||||||
|
|
||||||
trade_dur = int((sell_row.date - buy_row.date).total_seconds() // 60)
|
trade_dur = int((sell_row.date - buy_row.date).total_seconds() // 60)
|
||||||
# Special handling if high or low hit STOP_LOSS or ROI
|
# Special handling if high or low hit STOP_LOSS or ROI
|
||||||
if sell.sell_type in (SellType.STOP_LOSS, SellType.TRAILING_STOP_LOSS):
|
if sell.sell_type in (SellType.STOP_LOSS, SellType.TRAILING_STOP_LOSS):
|
||||||
# Set close_rate to stoploss
|
# Set close_rate to stoploss
|
||||||
closerate = trade.stop_loss
|
closerate = trade.stop_loss
|
||||||
elif sell.sell_type == (SellType.ROI):
|
elif sell.sell_type == (SellType.ROI):
|
||||||
# get next entry in min_roi > to trade duration
|
roi = self.strategy.min_roi_reached_entry(trade_dur)
|
||||||
# Interface.py skips on trade_duration <= duration
|
if roi is not None:
|
||||||
roi_entry = max(list(filter(lambda x: trade_dur >= x,
|
# - (Expected abs profit + open_rate + open_fee) / (fee_close -1)
|
||||||
self.strategy.minimal_roi.keys())))
|
closerate = - (trade.open_rate * roi + trade.open_rate *
|
||||||
roi = self.strategy.minimal_roi[roi_entry]
|
(1 + trade.fee_open)) / (trade.fee_close - 1)
|
||||||
|
|
||||||
# - (Expected abs profit + open_rate + open_fee) / (fee_close -1)
|
# Use the maximum between closerate and low as we
|
||||||
closerate = - (trade.open_rate * roi + trade.open_rate *
|
# cannot sell outside of a candle.
|
||||||
(1 + trade.fee_open)) / (trade.fee_close - 1)
|
# Applies when using {"xx": -1} as roi to force sells after xx minutes
|
||||||
|
closerate = max(closerate, sell_row.low)
|
||||||
|
else:
|
||||||
|
# This should not be reached...
|
||||||
|
closerate = sell_row.open
|
||||||
else:
|
else:
|
||||||
closerate = sell_row.open
|
closerate = sell_row.open
|
||||||
|
|
||||||
@@ -259,23 +297,25 @@ class Backtesting(object):
|
|||||||
if partial_ticker:
|
if partial_ticker:
|
||||||
# no sell condition found - trade stil open at end of backtest period
|
# no sell condition found - trade stil open at end of backtest period
|
||||||
sell_row = partial_ticker[-1]
|
sell_row = partial_ticker[-1]
|
||||||
btr = BacktestResult(pair=pair,
|
bt_res = BacktestResult(pair=pair,
|
||||||
profit_percent=trade.calc_profit_percent(rate=sell_row.open),
|
profit_percent=trade.calc_profit_percent(rate=sell_row.open),
|
||||||
profit_abs=trade.calc_profit(rate=sell_row.open),
|
profit_abs=trade.calc_profit(rate=sell_row.open),
|
||||||
open_time=buy_row.date,
|
open_time=buy_row.date,
|
||||||
close_time=sell_row.date,
|
close_time=sell_row.date,
|
||||||
trade_duration=int((
|
trade_duration=int((
|
||||||
sell_row.date - buy_row.date).total_seconds() // 60),
|
sell_row.date - buy_row.date).total_seconds() // 60),
|
||||||
open_index=buy_row.Index,
|
open_index=buy_row.Index,
|
||||||
close_index=sell_row.Index,
|
close_index=sell_row.Index,
|
||||||
open_at_end=True,
|
open_at_end=True,
|
||||||
open_rate=buy_row.open,
|
open_rate=buy_row.open,
|
||||||
close_rate=sell_row.open,
|
close_rate=sell_row.open,
|
||||||
sell_reason=SellType.FORCE_SELL
|
sell_reason=SellType.FORCE_SELL
|
||||||
)
|
)
|
||||||
logger.debug('Force_selling still open trade %s with %s perc - %s', btr.pair,
|
logger.debug(f"{pair} - Force selling still open trade, "
|
||||||
btr.profit_percent, btr.profit_abs)
|
f"profit percent: {bt_res.profit_percent}, "
|
||||||
return btr
|
f"profit abs: {bt_res.profit_abs}")
|
||||||
|
|
||||||
|
return bt_res
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def backtest(self, args: Dict) -> DataFrame:
|
def backtest(self, args: Dict) -> DataFrame:
|
||||||
@@ -293,74 +333,77 @@ class Backtesting(object):
|
|||||||
position_stacking: do we allow position stacking? (default: False)
|
position_stacking: do we allow position stacking? (default: False)
|
||||||
:return: DataFrame
|
:return: DataFrame
|
||||||
"""
|
"""
|
||||||
headers = ['date', 'buy', 'open', 'close', 'sell', 'low', 'high']
|
# Arguments are long and noisy, so this is commented out.
|
||||||
|
# Uncomment if you need to debug the backtest() method.
|
||||||
|
# logger.debug(f"Start backtest, args: {args}")
|
||||||
processed = args['processed']
|
processed = args['processed']
|
||||||
|
stake_amount = args['stake_amount']
|
||||||
max_open_trades = args.get('max_open_trades', 0)
|
max_open_trades = args.get('max_open_trades', 0)
|
||||||
position_stacking = args.get('position_stacking', False)
|
position_stacking = args.get('position_stacking', False)
|
||||||
start_date = args['start_date']
|
start_date = args['start_date']
|
||||||
end_date = args['end_date']
|
end_date = args['end_date']
|
||||||
trades = []
|
trades = []
|
||||||
trade_count_lock: Dict = {}
|
trade_count_lock: Dict = {}
|
||||||
ticker: Dict = {}
|
|
||||||
pairs = []
|
|
||||||
# Create ticker dict
|
|
||||||
for pair, pair_data in processed.items():
|
|
||||||
pair_data['buy'], pair_data['sell'] = 0, 0 # cleanup from previous run
|
|
||||||
|
|
||||||
ticker_data = self.advise_sell(
|
# Dict of ticker-lists for performance (looping lists is a lot faster than dataframes)
|
||||||
self.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy()
|
ticker: Dict = self._get_ticker_list(processed)
|
||||||
|
|
||||||
# to avoid using data from future, we buy/sell with signal from previous candle
|
|
||||||
ticker_data.loc[:, 'buy'] = ticker_data['buy'].shift(1)
|
|
||||||
ticker_data.loc[:, 'sell'] = ticker_data['sell'].shift(1)
|
|
||||||
|
|
||||||
ticker_data.drop(ticker_data.head(1).index, inplace=True)
|
|
||||||
|
|
||||||
# Convert from Pandas to list for performance reasons
|
|
||||||
# (Looping Pandas is slow.)
|
|
||||||
ticker[pair] = [x for x in ticker_data.itertuples()]
|
|
||||||
pairs.append(pair)
|
|
||||||
|
|
||||||
lock_pair_until: Dict = {}
|
lock_pair_until: Dict = {}
|
||||||
|
# Indexes per pair, so some pairs are allowed to have a missing start.
|
||||||
|
indexes: Dict = {}
|
||||||
tmp = start_date + timedelta(minutes=self.ticker_interval_mins)
|
tmp = start_date + timedelta(minutes=self.ticker_interval_mins)
|
||||||
index = 0
|
|
||||||
# Loop timerange and test per pair
|
# Loop timerange and get candle for each pair at that point in time
|
||||||
while tmp < end_date:
|
while tmp < end_date:
|
||||||
# print(f"time: {tmp}")
|
|
||||||
for i, pair in enumerate(ticker):
|
for i, pair in enumerate(ticker):
|
||||||
|
if pair not in indexes:
|
||||||
|
indexes[pair] = 0
|
||||||
|
|
||||||
try:
|
try:
|
||||||
row = ticker[pair][index]
|
row = ticker[pair][indexes[pair]]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
# missing Data for one pair ...
|
# missing Data for one pair at the end.
|
||||||
# Warnings for this are shown by `validate_backtest_data`
|
# Warnings for this are shown during data loading
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# Waits until the time-counter reaches the start of the data for this pair.
|
||||||
|
if row.date > tmp.datetime:
|
||||||
|
continue
|
||||||
|
|
||||||
|
indexes[pair] += 1
|
||||||
|
|
||||||
if row.buy == 0 or row.sell == 1:
|
if row.buy == 0 or row.sell == 1:
|
||||||
continue # skip rows where no buy signal or that would immediately sell off
|
continue # skip rows where no buy signal or that would immediately sell off
|
||||||
|
|
||||||
if not position_stacking:
|
if (not position_stacking and pair in lock_pair_until
|
||||||
if pair in lock_pair_until and row.date <= lock_pair_until[pair]:
|
and row.date <= lock_pair_until[pair]):
|
||||||
continue
|
# without positionstacking, we can only have one open trade per pair.
|
||||||
|
continue
|
||||||
|
|
||||||
if max_open_trades > 0:
|
if max_open_trades > 0:
|
||||||
# Check if max_open_trades has already been reached for the given date
|
# Check if max_open_trades has already been reached for the given date
|
||||||
if not trade_count_lock.get(row.date, 0) < max_open_trades:
|
if not trade_count_lock.get(row.date, 0) < max_open_trades:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
trade_count_lock[row.date] = trade_count_lock.get(row.date, 0) + 1
|
trade_count_lock[row.date] = trade_count_lock.get(row.date, 0) + 1
|
||||||
|
|
||||||
trade_entry = self._get_sell_trade_entry(pair, row, ticker[pair][index + 1:],
|
# since indexes has been incremented before, we need to go one step back to
|
||||||
trade_count_lock, args)
|
# also check the buying candle for sell conditions.
|
||||||
|
trade_entry = self._get_sell_trade_entry(pair, row, ticker[pair][indexes[pair]-1:],
|
||||||
|
trade_count_lock, stake_amount,
|
||||||
|
max_open_trades)
|
||||||
|
|
||||||
if trade_entry:
|
if trade_entry:
|
||||||
|
logger.debug(f"{pair} - Locking pair till "
|
||||||
|
f"close_time={trade_entry.close_time}")
|
||||||
lock_pair_until[pair] = trade_entry.close_time
|
lock_pair_until[pair] = trade_entry.close_time
|
||||||
trades.append(trade_entry)
|
trades.append(trade_entry)
|
||||||
else:
|
else:
|
||||||
# Set lock_pair_until to end of testing period if trade could not be closed
|
# Set lock_pair_until to end of testing period if trade could not be closed
|
||||||
# This happens only if the buy-signal was with the last candle
|
lock_pair_until[pair] = end_date.datetime
|
||||||
lock_pair_until[pair] = end_date
|
|
||||||
|
|
||||||
|
# Move time one configured time_interval ahead.
|
||||||
tmp += timedelta(minutes=self.ticker_interval_mins)
|
tmp += timedelta(minutes=self.ticker_interval_mins)
|
||||||
index += 1
|
|
||||||
return DataFrame.from_records(trades, columns=BacktestResult._fields)
|
return DataFrame.from_records(trades, columns=BacktestResult._fields)
|
||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
@@ -373,24 +416,14 @@ class Backtesting(object):
|
|||||||
logger.info('Using stake_currency: %s ...', self.config['stake_currency'])
|
logger.info('Using stake_currency: %s ...', self.config['stake_currency'])
|
||||||
logger.info('Using stake_amount: %s ...', self.config['stake_amount'])
|
logger.info('Using stake_amount: %s ...', self.config['stake_amount'])
|
||||||
|
|
||||||
if self.config.get('live'):
|
timerange = TimeRange.parse_timerange(None if self.config.get(
|
||||||
logger.info('Downloading data for all pairs in whitelist ...')
|
'timerange') is None else str(self.config.get('timerange')))
|
||||||
self.exchange.refresh_latest_ohlcv([(pair, self.ticker_interval) for pair in pairs])
|
data = history.load_data(
|
||||||
data = {key[0]: value for key, value in self.exchange._klines.items()}
|
datadir=Path(self.config['datadir']),
|
||||||
|
pairs=pairs,
|
||||||
else:
|
ticker_interval=self.ticker_interval,
|
||||||
logger.info('Using local backtesting data (using whitelist in given config) ...')
|
timerange=timerange,
|
||||||
|
)
|
||||||
timerange = Arguments.parse_timerange(None if self.config.get(
|
|
||||||
'timerange') is None else str(self.config.get('timerange')))
|
|
||||||
data = history.load_data(
|
|
||||||
datadir=Path(self.config['datadir']) if self.config.get('datadir') else None,
|
|
||||||
pairs=pairs,
|
|
||||||
ticker_interval=self.ticker_interval,
|
|
||||||
refresh_pairs=self.config.get('refresh_pairs', False),
|
|
||||||
exchange=self.exchange,
|
|
||||||
timerange=timerange
|
|
||||||
)
|
|
||||||
|
|
||||||
if not data:
|
if not data:
|
||||||
logger.critical("No data found. Terminating.")
|
logger.critical("No data found. Terminating.")
|
||||||
@@ -403,20 +436,19 @@ class Backtesting(object):
|
|||||||
max_open_trades = 0
|
max_open_trades = 0
|
||||||
all_results = {}
|
all_results = {}
|
||||||
|
|
||||||
|
min_date, max_date = history.get_timeframe(data)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
'Backtesting with data from %s up to %s (%s days)..',
|
||||||
|
min_date.isoformat(),
|
||||||
|
max_date.isoformat(),
|
||||||
|
(max_date - min_date).days
|
||||||
|
)
|
||||||
|
|
||||||
for strat in self.strategylist:
|
for strat in self.strategylist:
|
||||||
logger.info("Running backtesting for Strategy %s", strat.get_strategy_name())
|
logger.info("Running backtesting for Strategy %s", strat.get_strategy_name())
|
||||||
self._set_strategy(strat)
|
self._set_strategy(strat)
|
||||||
|
|
||||||
min_date, max_date = optimize.get_timeframe(data)
|
|
||||||
# Validate dataframe for missing values (mainly at start and end, as fillup is called)
|
|
||||||
optimize.validate_backtest_data(data, min_date, max_date,
|
|
||||||
constants.TICKER_INTERVAL_MINUTES[self.ticker_interval])
|
|
||||||
logger.info(
|
|
||||||
'Measuring data from %s up to %s (%s days)..',
|
|
||||||
min_date.isoformat(),
|
|
||||||
max_date.isoformat(),
|
|
||||||
(max_date - min_date).days
|
|
||||||
)
|
|
||||||
# need to reprocess data every time to populate signals
|
# need to reprocess data every time to populate signals
|
||||||
preprocessed = self.strategy.tickerdata_to_dataframe(data)
|
preprocessed = self.strategy.tickerdata_to_dataframe(data)
|
||||||
|
|
||||||
@@ -435,7 +467,7 @@ class Backtesting(object):
|
|||||||
for strategy, results in all_results.items():
|
for strategy, results in all_results.items():
|
||||||
|
|
||||||
if self.config.get('export', False):
|
if self.config.get('export', False):
|
||||||
self._store_backtest_result(self.config['exportfilename'], results,
|
self._store_backtest_result(Path(self.config['exportfilename']), results,
|
||||||
strategy if len(self.strategylist) > 1 else None)
|
strategy if len(self.strategylist) > 1 else None)
|
||||||
|
|
||||||
print(f"Result for strategy {strategy}")
|
print(f"Result for strategy {strategy}")
|
||||||
@@ -453,38 +485,3 @@ class Backtesting(object):
|
|||||||
print(' Strategy Summary '.center(133, '='))
|
print(' Strategy Summary '.center(133, '='))
|
||||||
print(self._generate_text_table_strategy(all_results))
|
print(self._generate_text_table_strategy(all_results))
|
||||||
print('\nFor more details, please look at the detail tables above')
|
print('\nFor more details, please look at the detail tables above')
|
||||||
|
|
||||||
|
|
||||||
def setup_configuration(args: Namespace) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Prepare the configuration for the backtesting
|
|
||||||
:param args: Cli args from Arguments()
|
|
||||||
:return: Configuration
|
|
||||||
"""
|
|
||||||
configuration = Configuration(args, RunMode.BACKTEST)
|
|
||||||
config = configuration.get_config()
|
|
||||||
|
|
||||||
# Ensure we do not use Exchange credentials
|
|
||||||
config['exchange']['key'] = ''
|
|
||||||
config['exchange']['secret'] = ''
|
|
||||||
|
|
||||||
if config['stake_amount'] == constants.UNLIMITED_STAKE_AMOUNT:
|
|
||||||
raise DependencyException('stake amount could not be "%s" for backtesting' %
|
|
||||||
constants.UNLIMITED_STAKE_AMOUNT)
|
|
||||||
|
|
||||||
return config
|
|
||||||
|
|
||||||
|
|
||||||
def start(args: Namespace) -> None:
|
|
||||||
"""
|
|
||||||
Start Backtesting script
|
|
||||||
:param args: Cli args from Arguments()
|
|
||||||
:return: None
|
|
||||||
"""
|
|
||||||
# Initialize configuration
|
|
||||||
config = setup_configuration(args)
|
|
||||||
logger.info('Starting freqtrade in Backtesting mode')
|
|
||||||
|
|
||||||
# Initialize backtesting object
|
|
||||||
backtesting = Backtesting(config)
|
|
||||||
backtesting.start()
|
|
||||||
|
|||||||
@@ -1,52 +1,61 @@
|
|||||||
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
|
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
|
||||||
|
|
||||||
|
from functools import reduce
|
||||||
|
from typing import Any, Callable, Dict, List
|
||||||
|
|
||||||
import talib.abstract as ta
|
import talib.abstract as ta
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
from typing import Dict, Any, Callable, List
|
from skopt.space import Categorical, Dimension, Integer
|
||||||
from functools import reduce
|
|
||||||
|
|
||||||
from skopt.space import Categorical, Dimension, Integer, Real
|
|
||||||
|
|
||||||
import freqtrade.vendor.qtpylib.indicators as qtpylib
|
import freqtrade.vendor.qtpylib.indicators as qtpylib
|
||||||
from freqtrade.optimize.hyperopt_interface import IHyperOpt
|
from freqtrade.optimize.hyperopt_interface import IHyperOpt
|
||||||
|
|
||||||
class_name = 'DefaultHyperOpts'
|
|
||||||
|
|
||||||
|
class DefaultHyperOpt(IHyperOpt):
|
||||||
class DefaultHyperOpts(IHyperOpt):
|
|
||||||
"""
|
"""
|
||||||
Default hyperopt provided by freqtrade bot.
|
Default hyperopt provided by the Freqtrade bot.
|
||||||
You can override it with your own hyperopt
|
You can override it with your own Hyperopt
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
"""
|
||||||
|
Add several indicators needed for buy and sell strategies defined below.
|
||||||
|
"""
|
||||||
|
# ADX
|
||||||
dataframe['adx'] = ta.ADX(dataframe)
|
dataframe['adx'] = ta.ADX(dataframe)
|
||||||
|
# MACD
|
||||||
macd = ta.MACD(dataframe)
|
macd = ta.MACD(dataframe)
|
||||||
dataframe['macd'] = macd['macd']
|
dataframe['macd'] = macd['macd']
|
||||||
dataframe['macdsignal'] = macd['macdsignal']
|
dataframe['macdsignal'] = macd['macdsignal']
|
||||||
|
# MFI
|
||||||
dataframe['mfi'] = ta.MFI(dataframe)
|
dataframe['mfi'] = ta.MFI(dataframe)
|
||||||
|
# RSI
|
||||||
dataframe['rsi'] = ta.RSI(dataframe)
|
dataframe['rsi'] = ta.RSI(dataframe)
|
||||||
|
# Stochastic Fast
|
||||||
stoch_fast = ta.STOCHF(dataframe)
|
stoch_fast = ta.STOCHF(dataframe)
|
||||||
dataframe['fastd'] = stoch_fast['fastd']
|
dataframe['fastd'] = stoch_fast['fastd']
|
||||||
|
# Minus-DI
|
||||||
dataframe['minus_di'] = ta.MINUS_DI(dataframe)
|
dataframe['minus_di'] = ta.MINUS_DI(dataframe)
|
||||||
# Bollinger bands
|
# Bollinger bands
|
||||||
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
|
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
|
||||||
dataframe['bb_lowerband'] = bollinger['lower']
|
dataframe['bb_lowerband'] = bollinger['lower']
|
||||||
dataframe['bb_upperband'] = bollinger['upper']
|
dataframe['bb_upperband'] = bollinger['upper']
|
||||||
|
# SAR
|
||||||
dataframe['sar'] = ta.SAR(dataframe)
|
dataframe['sar'] = ta.SAR(dataframe)
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
|
def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||||
"""
|
"""
|
||||||
Define the buy strategy parameters to be used by hyperopt
|
Define the buy strategy parameters to be used by Hyperopt.
|
||||||
"""
|
"""
|
||||||
def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Buy strategy Hyperopt will build and use
|
Buy strategy Hyperopt will build and use.
|
||||||
"""
|
"""
|
||||||
conditions = []
|
conditions = []
|
||||||
|
|
||||||
# GUARDS AND TRENDS
|
# GUARDS AND TRENDS
|
||||||
if 'mfi-enabled' in params and params['mfi-enabled']:
|
if 'mfi-enabled' in params and params['mfi-enabled']:
|
||||||
conditions.append(dataframe['mfi'] < params['mfi-value'])
|
conditions.append(dataframe['mfi'] < params['mfi-value'])
|
||||||
@@ -70,9 +79,10 @@ class DefaultHyperOpts(IHyperOpt):
|
|||||||
dataframe['close'], dataframe['sar']
|
dataframe['close'], dataframe['sar']
|
||||||
))
|
))
|
||||||
|
|
||||||
dataframe.loc[
|
if conditions:
|
||||||
reduce(lambda x, y: x & y, conditions),
|
dataframe.loc[
|
||||||
'buy'] = 1
|
reduce(lambda x, y: x & y, conditions),
|
||||||
|
'buy'] = 1
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
|
|
||||||
@@ -81,7 +91,7 @@ class DefaultHyperOpts(IHyperOpt):
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def indicator_space() -> List[Dimension]:
|
def indicator_space() -> List[Dimension]:
|
||||||
"""
|
"""
|
||||||
Define your Hyperopt space for searching strategy parameters
|
Define your Hyperopt space for searching buy strategy parameters.
|
||||||
"""
|
"""
|
||||||
return [
|
return [
|
||||||
Integer(10, 25, name='mfi-value'),
|
Integer(10, 25, name='mfi-value'),
|
||||||
@@ -98,14 +108,14 @@ class DefaultHyperOpts(IHyperOpt):
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def sell_strategy_generator(params: Dict[str, Any]) -> Callable:
|
def sell_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||||
"""
|
"""
|
||||||
Define the sell strategy parameters to be used by hyperopt
|
Define the sell strategy parameters to be used by Hyperopt.
|
||||||
"""
|
"""
|
||||||
def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Sell strategy Hyperopt will build and use
|
Sell strategy Hyperopt will build and use.
|
||||||
"""
|
"""
|
||||||
# print(params)
|
|
||||||
conditions = []
|
conditions = []
|
||||||
|
|
||||||
# GUARDS AND TRENDS
|
# GUARDS AND TRENDS
|
||||||
if 'sell-mfi-enabled' in params and params['sell-mfi-enabled']:
|
if 'sell-mfi-enabled' in params and params['sell-mfi-enabled']:
|
||||||
conditions.append(dataframe['mfi'] > params['sell-mfi-value'])
|
conditions.append(dataframe['mfi'] > params['sell-mfi-value'])
|
||||||
@@ -129,9 +139,10 @@ class DefaultHyperOpts(IHyperOpt):
|
|||||||
dataframe['sar'], dataframe['close']
|
dataframe['sar'], dataframe['close']
|
||||||
))
|
))
|
||||||
|
|
||||||
dataframe.loc[
|
if conditions:
|
||||||
reduce(lambda x, y: x & y, conditions),
|
dataframe.loc[
|
||||||
'sell'] = 1
|
reduce(lambda x, y: x & y, conditions),
|
||||||
|
'sell'] = 1
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
|
|
||||||
@@ -140,7 +151,7 @@ class DefaultHyperOpts(IHyperOpt):
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def sell_indicator_space() -> List[Dimension]:
|
def sell_indicator_space() -> List[Dimension]:
|
||||||
"""
|
"""
|
||||||
Define your Hyperopt space for searching sell strategy parameters
|
Define your Hyperopt space for searching sell strategy parameters.
|
||||||
"""
|
"""
|
||||||
return [
|
return [
|
||||||
Integer(75, 100, name='sell-mfi-value'),
|
Integer(75, 100, name='sell-mfi-value'),
|
||||||
@@ -156,47 +167,11 @@ class DefaultHyperOpts(IHyperOpt):
|
|||||||
'sell-sar_reversal'], name='sell-trigger')
|
'sell-sar_reversal'], name='sell-trigger')
|
||||||
]
|
]
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def generate_roi_table(params: Dict) -> Dict[int, float]:
|
|
||||||
"""
|
|
||||||
Generate the ROI table that will be used by Hyperopt
|
|
||||||
"""
|
|
||||||
roi_table = {}
|
|
||||||
roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3']
|
|
||||||
roi_table[params['roi_t3']] = params['roi_p1'] + params['roi_p2']
|
|
||||||
roi_table[params['roi_t3'] + params['roi_t2']] = params['roi_p1']
|
|
||||||
roi_table[params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0
|
|
||||||
|
|
||||||
return roi_table
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def stoploss_space() -> List[Dimension]:
|
|
||||||
"""
|
|
||||||
Stoploss Value to search
|
|
||||||
"""
|
|
||||||
return [
|
|
||||||
Real(-0.5, -0.02, name='stoploss'),
|
|
||||||
]
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def roi_space() -> List[Dimension]:
|
|
||||||
"""
|
|
||||||
Values to search for each ROI steps
|
|
||||||
"""
|
|
||||||
return [
|
|
||||||
Integer(10, 120, name='roi_t1'),
|
|
||||||
Integer(10, 60, name='roi_t2'),
|
|
||||||
Integer(10, 40, name='roi_t3'),
|
|
||||||
Real(0.01, 0.04, name='roi_p1'),
|
|
||||||
Real(0.01, 0.07, name='roi_p2'),
|
|
||||||
Real(0.01, 0.20, name='roi_p3'),
|
|
||||||
]
|
|
||||||
|
|
||||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Based on TA indicators. Should be a copy of from strategy
|
Based on TA indicators. Should be a copy of same method from strategy.
|
||||||
must align to populate_indicators in this file
|
Must align to populate_indicators in this file.
|
||||||
Only used when --spaces does not include buy
|
Only used when --spaces does not include buy space.
|
||||||
"""
|
"""
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(
|
(
|
||||||
@@ -211,9 +186,9 @@ class DefaultHyperOpts(IHyperOpt):
|
|||||||
|
|
||||||
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Based on TA indicators. Should be a copy of from strategy
|
Based on TA indicators. Should be a copy of same method from strategy.
|
||||||
must align to populate_indicators in this file
|
Must align to populate_indicators in this file.
|
||||||
Only used when --spaces does not include sell
|
Only used when --spaces does not include sell space.
|
||||||
"""
|
"""
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(
|
(
|
||||||
@@ -223,4 +198,5 @@ class DefaultHyperOpts(IHyperOpt):
|
|||||||
(dataframe['fastd'] > 54)
|
(dataframe['fastd'] > 54)
|
||||||
),
|
),
|
||||||
'sell'] = 1
|
'sell'] = 1
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
|
|||||||
52
freqtrade/optimize/default_hyperopt_loss.py
Normal file
52
freqtrade/optimize/default_hyperopt_loss.py
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
"""
|
||||||
|
DefaultHyperOptLoss
|
||||||
|
This module defines the default HyperoptLoss class which is being used for
|
||||||
|
Hyperoptimization.
|
||||||
|
"""
|
||||||
|
from math import exp
|
||||||
|
|
||||||
|
from pandas import DataFrame
|
||||||
|
|
||||||
|
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
||||||
|
|
||||||
|
|
||||||
|
# Set TARGET_TRADES to suit your number concurrent trades so its realistic
|
||||||
|
# to the number of days
|
||||||
|
TARGET_TRADES = 600
|
||||||
|
|
||||||
|
# This is assumed to be expected avg profit * expected trade count.
|
||||||
|
# For example, for 0.35% avg per trade (or 0.0035 as ratio) and 1100 trades,
|
||||||
|
# expected max profit = 3.85
|
||||||
|
# Check that the reported Σ% values do not exceed this!
|
||||||
|
# Note, this is ratio. 3.85 stated above means 385Σ%.
|
||||||
|
EXPECTED_MAX_PROFIT = 3.0
|
||||||
|
|
||||||
|
# Max average trade duration in minutes.
|
||||||
|
# If eval ends with higher value, we consider it a failed eval.
|
||||||
|
MAX_ACCEPTED_TRADE_DURATION = 300
|
||||||
|
|
||||||
|
|
||||||
|
class DefaultHyperOptLoss(IHyperOptLoss):
|
||||||
|
"""
|
||||||
|
Defines the default loss function for hyperopt
|
||||||
|
"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def hyperopt_loss_function(results: DataFrame, trade_count: int,
|
||||||
|
*args, **kwargs) -> float:
|
||||||
|
"""
|
||||||
|
Objective function, returns smaller number for better results
|
||||||
|
This is the Default algorithm
|
||||||
|
Weights are distributed as follows:
|
||||||
|
* 0.4 to trade duration
|
||||||
|
* 0.25: Avoiding trade loss
|
||||||
|
* 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above
|
||||||
|
"""
|
||||||
|
total_profit = results.profit_percent.sum()
|
||||||
|
trade_duration = results.trade_duration.mean()
|
||||||
|
|
||||||
|
trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8)
|
||||||
|
profit_loss = max(0, 1 - total_profit / EXPECTED_MAX_PROFIT)
|
||||||
|
duration_loss = 0.4 * min(trade_duration / MAX_ACCEPTED_TRADE_DURATION, 1)
|
||||||
|
result = trade_loss + profit_loss + duration_loss
|
||||||
|
return result
|
||||||
@@ -4,21 +4,19 @@
|
|||||||
This module contains the edge backtesting interface
|
This module contains the edge backtesting interface
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
from argparse import Namespace
|
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
from tabulate import tabulate
|
from tabulate import tabulate
|
||||||
|
from freqtrade import constants
|
||||||
from freqtrade.edge import Edge
|
from freqtrade.edge import Edge
|
||||||
|
|
||||||
from freqtrade.arguments import Arguments
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.configuration import Configuration
|
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
from freqtrade.resolvers import StrategyResolver
|
from freqtrade.resolvers import StrategyResolver
|
||||||
from freqtrade.state import RunMode
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class EdgeCli(object):
|
class EdgeCli:
|
||||||
"""
|
"""
|
||||||
EdgeCli class, this class contains all the logic to run edge backtesting
|
EdgeCli class, this class contains all the logic to run edge backtesting
|
||||||
|
|
||||||
@@ -35,14 +33,16 @@ class EdgeCli(object):
|
|||||||
self.config['exchange']['secret'] = ''
|
self.config['exchange']['secret'] = ''
|
||||||
self.config['exchange']['password'] = ''
|
self.config['exchange']['password'] = ''
|
||||||
self.config['exchange']['uid'] = ''
|
self.config['exchange']['uid'] = ''
|
||||||
|
self.config['stake_amount'] = constants.UNLIMITED_STAKE_AMOUNT
|
||||||
self.config['dry_run'] = True
|
self.config['dry_run'] = True
|
||||||
self.exchange = Exchange(self.config)
|
self.exchange = Exchange(self.config)
|
||||||
self.strategy = StrategyResolver(self.config).strategy
|
self.strategy = StrategyResolver(self.config).strategy
|
||||||
|
|
||||||
self.edge = Edge(config, self.exchange, self.strategy)
|
self.edge = Edge(config, self.exchange, self.strategy)
|
||||||
self.edge._refresh_pairs = self.config.get('refresh_pairs', False)
|
# Set refresh_pairs to false for edge-cli (it must be true for edge)
|
||||||
|
self.edge._refresh_pairs = False
|
||||||
|
|
||||||
self.timerange = Arguments.parse_timerange(None if self.config.get(
|
self.timerange = TimeRange.parse_timerange(None if self.config.get(
|
||||||
'timerange') is None else str(self.config.get('timerange')))
|
'timerange') is None else str(self.config.get('timerange')))
|
||||||
|
|
||||||
self.edge._timerange = self.timerange
|
self.edge._timerange = self.timerange
|
||||||
@@ -69,41 +69,11 @@ class EdgeCli(object):
|
|||||||
])
|
])
|
||||||
|
|
||||||
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
||||||
return tabulate(tabular_data, headers=headers, # type: ignore
|
return tabulate(tabular_data, headers=headers,
|
||||||
floatfmt=floatfmt, tablefmt="pipe")
|
floatfmt=floatfmt, tablefmt="pipe") # type: ignore
|
||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
self.edge.calculate()
|
result = self.edge.calculate()
|
||||||
print('') # blank like for readability
|
if result:
|
||||||
print(self._generate_edge_table(self.edge._cached_pairs))
|
print('') # blank line for readability
|
||||||
|
print(self._generate_edge_table(self.edge._cached_pairs))
|
||||||
|
|
||||||
def setup_configuration(args: Namespace) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Prepare the configuration for edge backtesting
|
|
||||||
:param args: Cli args from Arguments()
|
|
||||||
:return: Configuration
|
|
||||||
"""
|
|
||||||
configuration = Configuration(args, RunMode.EDGECLI)
|
|
||||||
config = configuration.get_config()
|
|
||||||
|
|
||||||
# Ensure we do not use Exchange credentials
|
|
||||||
config['exchange']['key'] = ''
|
|
||||||
config['exchange']['secret'] = ''
|
|
||||||
|
|
||||||
return config
|
|
||||||
|
|
||||||
|
|
||||||
def start(args: Namespace) -> None:
|
|
||||||
"""
|
|
||||||
Start Edge script
|
|
||||||
:param args: Cli args from Arguments()
|
|
||||||
:return: None
|
|
||||||
"""
|
|
||||||
# Initialize configuration
|
|
||||||
config = setup_configuration(args)
|
|
||||||
logger.info('Starting freqtrade in Edge mode')
|
|
||||||
|
|
||||||
# Initialize Edge object
|
|
||||||
edge_cli = EdgeCli(config)
|
|
||||||
edge_cli.start()
|
|
||||||
|
|||||||
@@ -5,36 +5,46 @@ This module contains the hyperopt logic
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import multiprocessing
|
|
||||||
import os
|
|
||||||
import sys
|
import sys
|
||||||
from argparse import Namespace
|
|
||||||
from math import exp
|
from collections import OrderedDict
|
||||||
from operator import itemgetter
|
from operator import itemgetter
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from pprint import pprint
|
from pprint import pprint
|
||||||
from typing import Any, Dict, List
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from joblib import Parallel, delayed, dump, load, wrap_non_picklable_objects
|
import rapidjson
|
||||||
|
|
||||||
|
from colorama import init as colorama_init
|
||||||
|
from colorama import Fore, Style
|
||||||
|
from joblib import Parallel, delayed, dump, load, wrap_non_picklable_objects, cpu_count
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
from skopt import Optimizer
|
from skopt import Optimizer
|
||||||
from skopt.space import Dimension
|
from skopt.space import Dimension
|
||||||
|
|
||||||
from freqtrade.arguments import Arguments
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.configuration import Configuration
|
from freqtrade.data.history import load_data, get_timeframe
|
||||||
from freqtrade.data.history import load_data
|
from freqtrade.misc import round_dict
|
||||||
from freqtrade.optimize import get_timeframe
|
|
||||||
from freqtrade.optimize.backtesting import Backtesting
|
from freqtrade.optimize.backtesting import Backtesting
|
||||||
from freqtrade.state import RunMode
|
# Import IHyperOpt and IHyperOptLoss to allow unpickling classes from these modules
|
||||||
from freqtrade.resolvers import HyperOptResolver
|
from freqtrade.optimize.hyperopt_interface import IHyperOpt # noqa: F4
|
||||||
|
from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss # noqa: F4
|
||||||
|
from freqtrade.resolvers.hyperopt_resolver import HyperOptResolver, HyperOptLossResolver
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
INITIAL_POINTS = 30
|
||||||
|
|
||||||
|
# Keep no more than 2*SKOPT_MODELS_MAX_NUM models
|
||||||
|
# in the skopt models list
|
||||||
|
SKOPT_MODELS_MAX_NUM = 10
|
||||||
|
|
||||||
MAX_LOSS = 100000 # just a big enough number to be bad result in loss optimization
|
MAX_LOSS = 100000 # just a big enough number to be bad result in loss optimization
|
||||||
TICKERDATA_PICKLE = os.path.join('user_data', 'hyperopt_tickerdata.pkl')
|
|
||||||
|
|
||||||
|
|
||||||
class Hyperopt(Backtesting):
|
class Hyperopt:
|
||||||
"""
|
"""
|
||||||
Hyperopt class, this class contains all the logic to run a hyperopt simulation
|
Hyperopt class, this class contains all the logic to run a hyperopt simulation
|
||||||
|
|
||||||
@@ -43,31 +53,75 @@ class Hyperopt(Backtesting):
|
|||||||
hyperopt.start()
|
hyperopt.start()
|
||||||
"""
|
"""
|
||||||
def __init__(self, config: Dict[str, Any]) -> None:
|
def __init__(self, config: Dict[str, Any]) -> None:
|
||||||
super().__init__(config)
|
|
||||||
self.config = config
|
self.config = config
|
||||||
|
|
||||||
self.custom_hyperopt = HyperOptResolver(self.config).hyperopt
|
self.custom_hyperopt = HyperOptResolver(self.config).hyperopt
|
||||||
|
|
||||||
# set TARGET_TRADES to suit your number concurrent trades so its realistic
|
self.backtesting = Backtesting(self.config)
|
||||||
# to the number of days
|
|
||||||
self.target_trades = 600
|
self.custom_hyperoptloss = HyperOptLossResolver(self.config).hyperoptloss
|
||||||
self.total_tries = config.get('epochs', 0)
|
self.calculate_loss = self.custom_hyperoptloss.hyperopt_loss_function
|
||||||
|
|
||||||
|
self.trials_file = (self.config['user_data_dir'] /
|
||||||
|
'hyperopt_results' / 'hyperopt_results.pickle')
|
||||||
|
self.tickerdata_pickle = (self.config['user_data_dir'] /
|
||||||
|
'hyperopt_results' / 'hyperopt_tickerdata.pkl')
|
||||||
|
self.total_epochs = config.get('epochs', 0)
|
||||||
|
|
||||||
self.current_best_loss = 100
|
self.current_best_loss = 100
|
||||||
|
|
||||||
# max average trade duration in minutes
|
if not self.config.get('hyperopt_continue'):
|
||||||
# if eval ends with higher value, we consider it a failed eval
|
self.clean_hyperopt()
|
||||||
self.max_accepted_trade_duration = 300
|
else:
|
||||||
|
logger.info("Continuing on previous hyperopt results.")
|
||||||
# this is expexted avg profit * expected trade count
|
|
||||||
# for example 3.5%, 1100 trades, self.expected_max_profit = 3.85
|
|
||||||
# check that the reported Σ% values do not exceed this!
|
|
||||||
self.expected_max_profit = 3.0
|
|
||||||
|
|
||||||
# Previous evaluations
|
# Previous evaluations
|
||||||
self.trials_file = os.path.join('user_data', 'hyperopt_results.pickle')
|
|
||||||
self.trials: List = []
|
self.trials: List = []
|
||||||
|
|
||||||
|
# Populate functions here (hasattr is slow so should not be run during "regular" operations)
|
||||||
|
if hasattr(self.custom_hyperopt, 'populate_indicators'):
|
||||||
|
self.backtesting.strategy.advise_indicators = \
|
||||||
|
self.custom_hyperopt.populate_indicators # type: ignore
|
||||||
|
if hasattr(self.custom_hyperopt, 'populate_buy_trend'):
|
||||||
|
self.backtesting.strategy.advise_buy = \
|
||||||
|
self.custom_hyperopt.populate_buy_trend # type: ignore
|
||||||
|
if hasattr(self.custom_hyperopt, 'populate_sell_trend'):
|
||||||
|
self.backtesting.strategy.advise_sell = \
|
||||||
|
self.custom_hyperopt.populate_sell_trend # type: ignore
|
||||||
|
|
||||||
|
# Use max_open_trades for hyperopt as well, except --disable-max-market-positions is set
|
||||||
|
if self.config.get('use_max_market_positions', True):
|
||||||
|
self.max_open_trades = self.config['max_open_trades']
|
||||||
|
else:
|
||||||
|
logger.debug('Ignoring max_open_trades (--disable-max-market-positions was used) ...')
|
||||||
|
self.max_open_trades = 0
|
||||||
|
self.position_stacking = self.config.get('position_stacking', False)
|
||||||
|
|
||||||
|
if self.has_space('sell'):
|
||||||
|
# Make sure use_sell_signal is enabled
|
||||||
|
if 'ask_strategy' not in self.config:
|
||||||
|
self.config['ask_strategy'] = {}
|
||||||
|
self.config['ask_strategy']['use_sell_signal'] = True
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_lock_filename(config) -> str:
|
||||||
|
|
||||||
|
return str(config['user_data_dir'] / 'hyperopt.lock')
|
||||||
|
|
||||||
|
def clean_hyperopt(self):
|
||||||
|
"""
|
||||||
|
Remove hyperopt pickle files to restart hyperopt.
|
||||||
|
"""
|
||||||
|
for f in [self.tickerdata_pickle, self.trials_file]:
|
||||||
|
p = Path(f)
|
||||||
|
if p.is_file():
|
||||||
|
logger.info(f"Removing `{p}`.")
|
||||||
|
p.unlink()
|
||||||
|
|
||||||
def get_args(self, params):
|
def get_args(self, params):
|
||||||
dimensions = self.hyperopt_space()
|
|
||||||
|
dimensions = self.dimensions
|
||||||
|
|
||||||
# Ensure the number of dimensions match
|
# Ensure the number of dimensions match
|
||||||
# the number of parameters in the list x.
|
# the number of parameters in the list x.
|
||||||
if len(params) != len(dimensions):
|
if len(params) != len(dimensions):
|
||||||
@@ -84,16 +138,16 @@ class Hyperopt(Backtesting):
|
|||||||
Save hyperopt trials to file
|
Save hyperopt trials to file
|
||||||
"""
|
"""
|
||||||
if self.trials:
|
if self.trials:
|
||||||
logger.info('Saving %d evaluations to \'%s\'', len(self.trials), self.trials_file)
|
logger.info("Saving %d evaluations to '%s'", len(self.trials), self.trials_file)
|
||||||
dump(self.trials, self.trials_file)
|
dump(self.trials, self.trials_file)
|
||||||
|
|
||||||
def read_trials(self) -> List:
|
def read_trials(self) -> List:
|
||||||
"""
|
"""
|
||||||
Read hyperopt trials file
|
Read hyperopt trials file
|
||||||
"""
|
"""
|
||||||
logger.info('Reading Trials from \'%s\'', self.trials_file)
|
logger.info("Reading Trials from '%s'", self.trials_file)
|
||||||
trials = load(self.trials_file)
|
trials = load(self.trials_file)
|
||||||
os.remove(self.trials_file)
|
self.trials_file.unlink()
|
||||||
return trials
|
return trials
|
||||||
|
|
||||||
def log_trials_result(self) -> None:
|
def log_trials_result(self) -> None:
|
||||||
@@ -102,149 +156,222 @@ class Hyperopt(Backtesting):
|
|||||||
"""
|
"""
|
||||||
results = sorted(self.trials, key=itemgetter('loss'))
|
results = sorted(self.trials, key=itemgetter('loss'))
|
||||||
best_result = results[0]
|
best_result = results[0]
|
||||||
logger.info(
|
params = best_result['params']
|
||||||
'Best result:\n%s\nwith values:\n',
|
log_str = self.format_results_logstring(best_result)
|
||||||
best_result['result']
|
print(f"\nBest result:\n\n{log_str}\n")
|
||||||
)
|
|
||||||
pprint(best_result['params'], indent=4)
|
if self.config.get('print_json'):
|
||||||
if 'roi_t1' in best_result['params']:
|
result_dict: Dict = {}
|
||||||
logger.info('ROI table:')
|
if self.has_space('buy') or self.has_space('sell'):
|
||||||
pprint(self.custom_hyperopt.generate_roi_table(best_result['params']), indent=4)
|
result_dict['params'] = {}
|
||||||
|
if self.has_space('buy'):
|
||||||
|
result_dict['params'].update({p.name: params.get(p.name)
|
||||||
|
for p in self.hyperopt_space('buy')})
|
||||||
|
if self.has_space('sell'):
|
||||||
|
result_dict['params'].update({p.name: params.get(p.name)
|
||||||
|
for p in self.hyperopt_space('sell')})
|
||||||
|
if self.has_space('roi'):
|
||||||
|
# Convert keys in min_roi dict to strings because
|
||||||
|
# rapidjson cannot dump dicts with integer keys...
|
||||||
|
# OrderedDict is used to keep the numeric order of the items
|
||||||
|
# in the dict.
|
||||||
|
result_dict['minimal_roi'] = OrderedDict(
|
||||||
|
(str(k), v) for k, v in self.custom_hyperopt.generate_roi_table(params).items()
|
||||||
|
)
|
||||||
|
if self.has_space('stoploss'):
|
||||||
|
result_dict['stoploss'] = params.get('stoploss')
|
||||||
|
print(rapidjson.dumps(result_dict, default=str, number_mode=rapidjson.NM_NATIVE))
|
||||||
|
else:
|
||||||
|
if self.has_space('buy'):
|
||||||
|
print('Buy hyperspace params:')
|
||||||
|
pprint({p.name: params.get(p.name) for p in self.hyperopt_space('buy')},
|
||||||
|
indent=4)
|
||||||
|
if self.has_space('sell'):
|
||||||
|
print('Sell hyperspace params:')
|
||||||
|
pprint({p.name: params.get(p.name) for p in self.hyperopt_space('sell')},
|
||||||
|
indent=4)
|
||||||
|
if self.has_space('roi'):
|
||||||
|
print("ROI table:")
|
||||||
|
# Round printed values to 5 digits after the decimal point
|
||||||
|
pprint(round_dict(self.custom_hyperopt.generate_roi_table(params), 5), indent=4)
|
||||||
|
if self.has_space('stoploss'):
|
||||||
|
# Also round to 5 digits after the decimal point
|
||||||
|
print(f"Stoploss: {round(params.get('stoploss'), 5)}")
|
||||||
|
|
||||||
def log_results(self, results) -> None:
|
def log_results(self, results) -> None:
|
||||||
"""
|
"""
|
||||||
Log results if it is better than any previous evaluation
|
Log results if it is better than any previous evaluation
|
||||||
"""
|
"""
|
||||||
if results['loss'] < self.current_best_loss:
|
print_all = self.config.get('print_all', False)
|
||||||
current = results['current_tries']
|
is_best_loss = results['loss'] < self.current_best_loss
|
||||||
total = results['total_tries']
|
if print_all or is_best_loss:
|
||||||
res = results['result']
|
if is_best_loss:
|
||||||
loss = results['loss']
|
self.current_best_loss = results['loss']
|
||||||
self.current_best_loss = results['loss']
|
log_str = self.format_results_logstring(results)
|
||||||
log_msg = f'\n{current:5d}/{total}: {res}. Loss {loss:.5f}'
|
# Colorize output
|
||||||
print(log_msg)
|
if self.config.get('print_colorized', False):
|
||||||
|
if results['total_profit'] > 0:
|
||||||
|
log_str = Fore.GREEN + log_str
|
||||||
|
if print_all and is_best_loss:
|
||||||
|
log_str = Style.BRIGHT + log_str
|
||||||
|
if print_all:
|
||||||
|
print(log_str)
|
||||||
|
else:
|
||||||
|
print('\n' + log_str)
|
||||||
else:
|
else:
|
||||||
print('.', end='')
|
print('.', end='')
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
|
|
||||||
def calculate_loss(self, total_profit: float, trade_count: int, trade_duration: float) -> float:
|
def format_results_logstring(self, results) -> str:
|
||||||
"""
|
# Output human-friendly index here (starting from 1)
|
||||||
Objective function, returns smaller number for more optimal results
|
current = results['current_epoch'] + 1
|
||||||
"""
|
total = self.total_epochs
|
||||||
trade_loss = 1 - 0.25 * exp(-(trade_count - self.target_trades) ** 2 / 10 ** 5.8)
|
res = results['results_explanation']
|
||||||
profit_loss = max(0, 1 - total_profit / self.expected_max_profit)
|
loss = results['loss']
|
||||||
duration_loss = 0.4 * min(trade_duration / self.max_accepted_trade_duration, 1)
|
log_str = f'{current:5d}/{total}: {res} Objective: {loss:.5f}'
|
||||||
result = trade_loss + profit_loss + duration_loss
|
log_str = f'*{log_str}' if results['is_initial_point'] else f' {log_str}'
|
||||||
return result
|
return log_str
|
||||||
|
|
||||||
def has_space(self, space: str) -> bool:
|
def has_space(self, space: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Tell if a space value is contained in the configuration
|
Tell if a space value is contained in the configuration
|
||||||
"""
|
"""
|
||||||
if space in self.config['spaces'] or 'all' in self.config['spaces']:
|
return any(s in self.config['spaces'] for s in [space, 'all'])
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
def hyperopt_space(self) -> List[Dimension]:
|
def hyperopt_space(self, space: Optional[str] = None) -> List[Dimension]:
|
||||||
"""
|
"""
|
||||||
Return the space to use during Hyperopt
|
Return the dimensions in the hyperoptimization space.
|
||||||
|
:param space: Defines hyperspace to return dimensions for.
|
||||||
|
If None, then the self.has_space() will be used to return dimensions
|
||||||
|
for all hyperspaces used.
|
||||||
"""
|
"""
|
||||||
spaces: List[Dimension] = []
|
spaces: List[Dimension] = []
|
||||||
if self.has_space('buy'):
|
if space == 'buy' or (space is None and self.has_space('buy')):
|
||||||
|
logger.debug("Hyperopt has 'buy' space")
|
||||||
spaces += self.custom_hyperopt.indicator_space()
|
spaces += self.custom_hyperopt.indicator_space()
|
||||||
if self.has_space('sell'):
|
if space == 'sell' or (space is None and self.has_space('sell')):
|
||||||
|
logger.debug("Hyperopt has 'sell' space")
|
||||||
spaces += self.custom_hyperopt.sell_indicator_space()
|
spaces += self.custom_hyperopt.sell_indicator_space()
|
||||||
# Make sure experimental is enabled
|
if space == 'roi' or (space is None and self.has_space('roi')):
|
||||||
if 'experimental' not in self.config:
|
logger.debug("Hyperopt has 'roi' space")
|
||||||
self.config['experimental'] = {}
|
|
||||||
self.config['experimental']['use_sell_signal'] = True
|
|
||||||
if self.has_space('roi'):
|
|
||||||
spaces += self.custom_hyperopt.roi_space()
|
spaces += self.custom_hyperopt.roi_space()
|
||||||
if self.has_space('stoploss'):
|
if space == 'stoploss' or (space is None and self.has_space('stoploss')):
|
||||||
|
logger.debug("Hyperopt has 'stoploss' space")
|
||||||
spaces += self.custom_hyperopt.stoploss_space()
|
spaces += self.custom_hyperopt.stoploss_space()
|
||||||
return spaces
|
return spaces
|
||||||
|
|
||||||
def generate_optimizer(self, _params: Dict) -> Dict:
|
def generate_optimizer(self, _params: Dict, iteration=None) -> Dict:
|
||||||
|
"""
|
||||||
|
Used Optimize function. Called once per epoch to optimize whatever is configured.
|
||||||
|
Keep this function as optimized as possible!
|
||||||
|
"""
|
||||||
params = self.get_args(_params)
|
params = self.get_args(_params)
|
||||||
|
|
||||||
if self.has_space('roi'):
|
if self.has_space('roi'):
|
||||||
self.strategy.minimal_roi = self.custom_hyperopt.generate_roi_table(params)
|
self.backtesting.strategy.minimal_roi = \
|
||||||
|
self.custom_hyperopt.generate_roi_table(params)
|
||||||
|
|
||||||
if self.has_space('buy'):
|
if self.has_space('buy'):
|
||||||
self.advise_buy = self.custom_hyperopt.buy_strategy_generator(params)
|
self.backtesting.strategy.advise_buy = \
|
||||||
elif hasattr(self.custom_hyperopt, 'populate_buy_trend'):
|
self.custom_hyperopt.buy_strategy_generator(params)
|
||||||
self.advise_buy = self.custom_hyperopt.populate_buy_trend # type: ignore
|
|
||||||
|
|
||||||
if self.has_space('sell'):
|
if self.has_space('sell'):
|
||||||
self.advise_sell = self.custom_hyperopt.sell_strategy_generator(params)
|
self.backtesting.strategy.advise_sell = \
|
||||||
elif hasattr(self.custom_hyperopt, 'populate_sell_trend'):
|
self.custom_hyperopt.sell_strategy_generator(params)
|
||||||
self.advise_sell = self.custom_hyperopt.populate_sell_trend # type: ignore
|
|
||||||
|
|
||||||
if self.has_space('stoploss'):
|
if self.has_space('stoploss'):
|
||||||
self.strategy.stoploss = params['stoploss']
|
self.backtesting.strategy.stoploss = params['stoploss']
|
||||||
|
|
||||||
|
processed = load(self.tickerdata_pickle)
|
||||||
|
|
||||||
processed = load(TICKERDATA_PICKLE)
|
|
||||||
min_date, max_date = get_timeframe(processed)
|
min_date, max_date = get_timeframe(processed)
|
||||||
results = self.backtest(
|
|
||||||
|
results = self.backtesting.backtest(
|
||||||
{
|
{
|
||||||
'stake_amount': self.config['stake_amount'],
|
'stake_amount': self.config['stake_amount'],
|
||||||
'processed': processed,
|
'processed': processed,
|
||||||
'position_stacking': self.config.get('position_stacking', True),
|
'max_open_trades': self.max_open_trades,
|
||||||
|
'position_stacking': self.position_stacking,
|
||||||
'start_date': min_date,
|
'start_date': min_date,
|
||||||
'end_date': max_date,
|
'end_date': max_date,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
result_explanation = self.format_results(results)
|
results_explanation = self.format_results(results)
|
||||||
|
|
||||||
total_profit = results.profit_percent.sum()
|
|
||||||
trade_count = len(results.index)
|
trade_count = len(results.index)
|
||||||
trade_duration = results.trade_duration.mean()
|
total_profit = results.profit_abs.sum()
|
||||||
|
|
||||||
if trade_count == 0:
|
# If this evaluation contains too short amount of trades to be
|
||||||
|
# interesting -- consider it as 'bad' (assigned max. loss value)
|
||||||
|
# in order to cast this hyperspace point away from optimization
|
||||||
|
# path. We do not want to optimize 'hodl' strategies.
|
||||||
|
if trade_count < self.config['hyperopt_min_trades']:
|
||||||
return {
|
return {
|
||||||
'loss': MAX_LOSS,
|
'loss': MAX_LOSS,
|
||||||
'params': params,
|
'params': params,
|
||||||
'result': result_explanation,
|
'results_explanation': results_explanation,
|
||||||
|
'total_profit': total_profit,
|
||||||
}
|
}
|
||||||
|
|
||||||
loss = self.calculate_loss(total_profit, trade_count, trade_duration)
|
loss = self.calculate_loss(results=results, trade_count=trade_count,
|
||||||
|
min_date=min_date.datetime, max_date=max_date.datetime)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'loss': loss,
|
'loss': loss,
|
||||||
'params': params,
|
'params': params,
|
||||||
'result': result_explanation,
|
'results_explanation': results_explanation,
|
||||||
|
'total_profit': total_profit,
|
||||||
}
|
}
|
||||||
|
|
||||||
def format_results(self, results: DataFrame) -> str:
|
def format_results(self, results: DataFrame) -> str:
|
||||||
"""
|
"""
|
||||||
Return the format result in a string
|
Return the formatted results explanation in a string
|
||||||
"""
|
"""
|
||||||
trades = len(results.index)
|
trades = len(results.index)
|
||||||
avg_profit = results.profit_percent.mean() * 100.0
|
avg_profit = results.profit_percent.mean() * 100.0
|
||||||
total_profit = results.profit_abs.sum()
|
total_profit = results.profit_abs.sum()
|
||||||
stake_cur = self.config['stake_currency']
|
stake_cur = self.config['stake_currency']
|
||||||
profit = results.profit_percent.sum()
|
profit = results.profit_percent.sum() * 100.0
|
||||||
duration = results.trade_duration.mean()
|
duration = results.trade_duration.mean()
|
||||||
|
|
||||||
return (f'{trades:6d} trades. Avg profit {avg_profit: 5.2f}%. '
|
return (f'{trades:6d} trades. Avg profit {avg_profit: 5.2f}%. '
|
||||||
f'Total profit {total_profit: 11.8f} {stake_cur} '
|
f'Total profit {total_profit: 11.8f} {stake_cur} '
|
||||||
f'({profit:.4f}Σ%). Avg duration {duration:5.1f} mins.')
|
f'({profit: 7.2f}Σ%). Avg duration {duration:5.1f} mins.')
|
||||||
|
|
||||||
def get_optimizer(self, cpu_count) -> Optimizer:
|
def get_optimizer(self, dimensions, cpu_count) -> Optimizer:
|
||||||
return Optimizer(
|
return Optimizer(
|
||||||
self.hyperopt_space(),
|
dimensions,
|
||||||
base_estimator="ET",
|
base_estimator="ET",
|
||||||
acq_optimizer="auto",
|
acq_optimizer="auto",
|
||||||
n_initial_points=30,
|
n_initial_points=INITIAL_POINTS,
|
||||||
acq_optimizer_kwargs={'n_jobs': cpu_count}
|
acq_optimizer_kwargs={'n_jobs': cpu_count},
|
||||||
|
random_state=self.config.get('hyperopt_random_state', None)
|
||||||
)
|
)
|
||||||
|
|
||||||
def run_optimizer_parallel(self, parallel, asked) -> List:
|
def fix_optimizer_models_list(self):
|
||||||
|
"""
|
||||||
|
WORKAROUND: Since skopt is not actively supported, this resolves problems with skopt
|
||||||
|
memory usage, see also: https://github.com/scikit-optimize/scikit-optimize/pull/746
|
||||||
|
|
||||||
|
This may cease working when skopt updates if implementation of this intrinsic
|
||||||
|
part changes.
|
||||||
|
"""
|
||||||
|
n = len(self.opt.models) - SKOPT_MODELS_MAX_NUM
|
||||||
|
# Keep no more than 2*SKOPT_MODELS_MAX_NUM models in the skopt models list,
|
||||||
|
# remove the old ones. These are actually of no use, the current model
|
||||||
|
# from the estimator is the only one used in the skopt optimizer.
|
||||||
|
# Freqtrade code also does not inspect details of the models.
|
||||||
|
if n >= SKOPT_MODELS_MAX_NUM:
|
||||||
|
logger.debug(f"Fixing skopt models list, removing {n} old items...")
|
||||||
|
del self.opt.models[0:n]
|
||||||
|
|
||||||
|
def run_optimizer_parallel(self, parallel, asked, i) -> List:
|
||||||
return parallel(delayed(
|
return parallel(delayed(
|
||||||
wrap_non_picklable_objects(self.generate_optimizer))(v) for v in asked)
|
wrap_non_picklable_objects(self.generate_optimizer))(v, i) for v in asked)
|
||||||
|
|
||||||
def load_previous_results(self):
|
def load_previous_results(self):
|
||||||
""" read trials file if we have one """
|
""" read trials file if we have one """
|
||||||
if os.path.exists(self.trials_file) and os.path.getsize(self.trials_file) > 0:
|
if self.trials_file.is_file() and self.trials_file.stat().st_size > 0:
|
||||||
self.trials = self.read_trials()
|
self.trials = self.read_trials()
|
||||||
logger.info(
|
logger.info(
|
||||||
'Loaded %d previous evaluations from disk.',
|
'Loaded %d previous evaluations from disk.',
|
||||||
@@ -252,75 +379,68 @@ class Hyperopt(Backtesting):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
timerange = Arguments.parse_timerange(None if self.config.get(
|
timerange = TimeRange.parse_timerange(None if self.config.get(
|
||||||
'timerange') is None else str(self.config.get('timerange')))
|
'timerange') is None else str(self.config.get('timerange')))
|
||||||
data = load_data(
|
data = load_data(
|
||||||
datadir=Path(self.config['datadir']) if self.config.get('datadir') else None,
|
datadir=Path(self.config['datadir']),
|
||||||
pairs=self.config['exchange']['pair_whitelist'],
|
pairs=self.config['exchange']['pair_whitelist'],
|
||||||
ticker_interval=self.ticker_interval,
|
ticker_interval=self.backtesting.ticker_interval,
|
||||||
timerange=timerange
|
timerange=timerange
|
||||||
)
|
)
|
||||||
|
|
||||||
if self.has_space('buy') or self.has_space('sell'):
|
if not data:
|
||||||
self.strategy.advise_indicators = \
|
logger.critical("No data found. Terminating.")
|
||||||
self.custom_hyperopt.populate_indicators # type: ignore
|
return
|
||||||
dump(self.strategy.tickerdata_to_dataframe(data), TICKERDATA_PICKLE)
|
|
||||||
self.exchange = None # type: ignore
|
min_date, max_date = get_timeframe(data)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
'Hyperopting with data from %s up to %s (%s days)..',
|
||||||
|
min_date.isoformat(),
|
||||||
|
max_date.isoformat(),
|
||||||
|
(max_date - min_date).days
|
||||||
|
)
|
||||||
|
|
||||||
|
preprocessed = self.backtesting.strategy.tickerdata_to_dataframe(data)
|
||||||
|
|
||||||
|
dump(preprocessed, self.tickerdata_pickle)
|
||||||
|
|
||||||
|
# We don't need exchange instance anymore while running hyperopt
|
||||||
|
self.backtesting.exchange = None # type: ignore
|
||||||
|
|
||||||
self.load_previous_results()
|
self.load_previous_results()
|
||||||
|
|
||||||
cpus = multiprocessing.cpu_count()
|
cpus = cpu_count()
|
||||||
logger.info(f'Found {cpus} CPU cores. Let\'s make them scream!')
|
logger.info(f"Found {cpus} CPU cores. Let's make them scream!")
|
||||||
|
config_jobs = self.config.get('hyperopt_jobs', -1)
|
||||||
|
logger.info(f'Number of parallel jobs set as: {config_jobs}')
|
||||||
|
|
||||||
|
self.dimensions = self.hyperopt_space()
|
||||||
|
self.opt = self.get_optimizer(self.dimensions, config_jobs)
|
||||||
|
|
||||||
|
if self.config.get('print_colorized', False):
|
||||||
|
colorama_init(autoreset=True)
|
||||||
|
|
||||||
opt = self.get_optimizer(cpus)
|
|
||||||
EVALS = max(self.total_tries // cpus, 1)
|
|
||||||
try:
|
try:
|
||||||
with Parallel(n_jobs=cpus) as parallel:
|
with Parallel(n_jobs=config_jobs) as parallel:
|
||||||
|
jobs = parallel._effective_n_jobs()
|
||||||
|
logger.info(f'Effective number of parallel workers used: {jobs}')
|
||||||
|
EVALS = max(self.total_epochs // jobs, 1)
|
||||||
for i in range(EVALS):
|
for i in range(EVALS):
|
||||||
asked = opt.ask(n_points=cpus)
|
asked = self.opt.ask(n_points=jobs)
|
||||||
f_val = self.run_optimizer_parallel(parallel, asked)
|
f_val = self.run_optimizer_parallel(parallel, asked, i)
|
||||||
opt.tell(asked, [i['loss'] for i in f_val])
|
self.opt.tell(asked, [v['loss'] for v in f_val])
|
||||||
|
self.fix_optimizer_models_list()
|
||||||
self.trials += f_val
|
for j in range(jobs):
|
||||||
for j in range(cpus):
|
current = i * jobs + j
|
||||||
self.log_results({
|
val = f_val[j]
|
||||||
'loss': f_val[j]['loss'],
|
val['current_epoch'] = current
|
||||||
'current_tries': i * cpus + j,
|
val['is_initial_point'] = current < INITIAL_POINTS
|
||||||
'total_tries': self.total_tries,
|
self.log_results(val)
|
||||||
'result': f_val[j]['result'],
|
self.trials.append(val)
|
||||||
})
|
logger.debug(f"Optimizer epoch evaluated: {val}")
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print('User interrupted..')
|
print('User interrupted..')
|
||||||
|
|
||||||
self.save_trials()
|
self.save_trials()
|
||||||
self.log_trials_result()
|
self.log_trials_result()
|
||||||
|
|
||||||
|
|
||||||
def start(args: Namespace) -> None:
|
|
||||||
"""
|
|
||||||
Start Backtesting script
|
|
||||||
:param args: Cli args from Arguments()
|
|
||||||
:return: None
|
|
||||||
"""
|
|
||||||
|
|
||||||
# Remove noisy log messages
|
|
||||||
logging.getLogger('hyperopt.tpe').setLevel(logging.WARNING)
|
|
||||||
|
|
||||||
# Initialize configuration
|
|
||||||
# Monkey patch the configuration with hyperopt_conf.py
|
|
||||||
configuration = Configuration(args, RunMode.HYPEROPT)
|
|
||||||
logger.info('Starting freqtrade in Hyperopt mode')
|
|
||||||
config = configuration.load_config()
|
|
||||||
|
|
||||||
config['exchange']['key'] = ''
|
|
||||||
config['exchange']['secret'] = ''
|
|
||||||
|
|
||||||
if config.get('strategy') and config.get('strategy') != 'DefaultStrategy':
|
|
||||||
logger.error("Please don't use --strategy for hyperopt.")
|
|
||||||
logger.error(
|
|
||||||
"Read the documentation at "
|
|
||||||
"https://github.com/freqtrade/freqtrade/blob/develop/docs/hyperopt.md "
|
|
||||||
"to understand how to configure hyperopt.")
|
|
||||||
raise ValueError("--strategy configured but not supported for hyperopt")
|
|
||||||
# Initialize backtesting object
|
|
||||||
hyperopt = Hyperopt(config)
|
|
||||||
hyperopt.start()
|
|
||||||
|
|||||||
@@ -2,79 +2,196 @@
|
|||||||
IHyperOpt interface
|
IHyperOpt interface
|
||||||
This module defines the interface to apply for hyperopts
|
This module defines the interface to apply for hyperopts
|
||||||
"""
|
"""
|
||||||
|
import logging
|
||||||
|
import math
|
||||||
|
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from typing import Dict, Any, Callable, List
|
from typing import Dict, Any, Callable, List
|
||||||
|
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
from skopt.space import Dimension
|
from skopt.space import Dimension, Integer, Real
|
||||||
|
|
||||||
|
from freqtrade import OperationalException
|
||||||
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
from freqtrade.misc import round_dict
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _format_exception_message(method: str, space: str) -> str:
|
||||||
|
return (f"The '{space}' space is included into the hyperoptimization "
|
||||||
|
f"but {method}() method is not found in your "
|
||||||
|
f"custom Hyperopt class. You should either implement this "
|
||||||
|
f"method or remove the '{space}' space from hyperoptimization.")
|
||||||
|
|
||||||
|
|
||||||
class IHyperOpt(ABC):
|
class IHyperOpt(ABC):
|
||||||
"""
|
"""
|
||||||
Interface for freqtrade hyperopts
|
Interface for freqtrade hyperopts
|
||||||
Defines the mandatory structure must follow any custom strategies
|
Defines the mandatory structure must follow any custom hyperopts
|
||||||
|
|
||||||
Attributes you can use:
|
Class attributes you can use:
|
||||||
minimal_roi -> Dict: Minimal ROI designed for the strategy
|
|
||||||
stoploss -> float: optimal stoploss designed for the strategy
|
|
||||||
ticker_interval -> int: value of the ticker interval to use for the strategy
|
ticker_interval -> int: value of the ticker interval to use for the strategy
|
||||||
"""
|
"""
|
||||||
|
ticker_interval: str
|
||||||
|
|
||||||
|
def __init__(self, config: dict) -> None:
|
||||||
|
self.config = config
|
||||||
|
|
||||||
|
# Assign ticker_interval to be used in hyperopt
|
||||||
|
IHyperOpt.ticker_interval = str(config['ticker_interval'])
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Populate indicators that will be used in the Buy and Sell strategy
|
Populate indicators that will be used in the Buy and Sell strategy.
|
||||||
:param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe()
|
:param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe().
|
||||||
:return: a Dataframe with all mandatory indicators for the strategies
|
:return: A Dataframe with all mandatory indicators for the strategies.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@abstractmethod
|
|
||||||
def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
|
def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||||
"""
|
"""
|
||||||
Create a buy strategy generator
|
Create a buy strategy generator.
|
||||||
"""
|
"""
|
||||||
|
raise OperationalException(_format_exception_message('buy_strategy_generator', 'buy'))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@abstractmethod
|
|
||||||
def sell_strategy_generator(params: Dict[str, Any]) -> Callable:
|
def sell_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||||
"""
|
"""
|
||||||
Create a sell strategy generator
|
Create a sell strategy generator.
|
||||||
"""
|
"""
|
||||||
|
raise OperationalException(_format_exception_message('sell_strategy_generator', 'sell'))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@abstractmethod
|
|
||||||
def indicator_space() -> List[Dimension]:
|
def indicator_space() -> List[Dimension]:
|
||||||
"""
|
"""
|
||||||
Create an indicator space
|
Create an indicator space.
|
||||||
"""
|
"""
|
||||||
|
raise OperationalException(_format_exception_message('indicator_space', 'buy'))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@abstractmethod
|
|
||||||
def sell_indicator_space() -> List[Dimension]:
|
def sell_indicator_space() -> List[Dimension]:
|
||||||
"""
|
"""
|
||||||
Create a sell indicator space
|
Create a sell indicator space.
|
||||||
"""
|
"""
|
||||||
|
raise OperationalException(_format_exception_message('sell_indicator_space', 'sell'))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@abstractmethod
|
|
||||||
def generate_roi_table(params: Dict) -> Dict[int, float]:
|
def generate_roi_table(params: Dict) -> Dict[int, float]:
|
||||||
"""
|
"""
|
||||||
Create an roi table
|
Create a ROI table.
|
||||||
|
|
||||||
|
Generates the ROI table that will be used by Hyperopt.
|
||||||
|
You may override it in your custom Hyperopt class.
|
||||||
"""
|
"""
|
||||||
|
roi_table = {}
|
||||||
|
roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3']
|
||||||
|
roi_table[params['roi_t3']] = params['roi_p1'] + params['roi_p2']
|
||||||
|
roi_table[params['roi_t3'] + params['roi_t2']] = params['roi_p1']
|
||||||
|
roi_table[params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0
|
||||||
|
|
||||||
|
return roi_table
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@abstractmethod
|
|
||||||
def stoploss_space() -> List[Dimension]:
|
|
||||||
"""
|
|
||||||
Create a stoploss space
|
|
||||||
"""
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
@abstractmethod
|
|
||||||
def roi_space() -> List[Dimension]:
|
def roi_space() -> List[Dimension]:
|
||||||
"""
|
"""
|
||||||
Create a roi space
|
Create a ROI space.
|
||||||
|
|
||||||
|
Defines values to search for each ROI steps.
|
||||||
|
|
||||||
|
This method implements adaptive roi hyperspace with varied
|
||||||
|
ranges for parameters which automatically adapts to the
|
||||||
|
ticker interval used.
|
||||||
|
|
||||||
|
It's used by Freqtrade by default, if no custom roi_space method is defined.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
# Default scaling coefficients for the roi hyperspace. Can be changed
|
||||||
|
# to adjust resulting ranges of the ROI tables.
|
||||||
|
# Increase if you need wider ranges in the roi hyperspace, decrease if shorter
|
||||||
|
# ranges are needed.
|
||||||
|
roi_t_alpha = 1.0
|
||||||
|
roi_p_alpha = 1.0
|
||||||
|
|
||||||
|
ticker_interval_mins = timeframe_to_minutes(IHyperOpt.ticker_interval)
|
||||||
|
|
||||||
|
# We define here limits for the ROI space parameters automagically adapted to the
|
||||||
|
# ticker_interval used by the bot:
|
||||||
|
#
|
||||||
|
# * 'roi_t' (limits for the time intervals in the ROI tables) components
|
||||||
|
# are scaled linearly.
|
||||||
|
# * 'roi_p' (limits for the ROI value steps) components are scaled logarithmically.
|
||||||
|
#
|
||||||
|
# The scaling is designed so that it maps exactly to the legacy Freqtrade roi_space()
|
||||||
|
# method for the 5m ticker interval.
|
||||||
|
roi_t_scale = ticker_interval_mins / 5
|
||||||
|
roi_p_scale = math.log1p(ticker_interval_mins) / math.log1p(5)
|
||||||
|
roi_limits = {
|
||||||
|
'roi_t1_min': int(10 * roi_t_scale * roi_t_alpha),
|
||||||
|
'roi_t1_max': int(120 * roi_t_scale * roi_t_alpha),
|
||||||
|
'roi_t2_min': int(10 * roi_t_scale * roi_t_alpha),
|
||||||
|
'roi_t2_max': int(60 * roi_t_scale * roi_t_alpha),
|
||||||
|
'roi_t3_min': int(10 * roi_t_scale * roi_t_alpha),
|
||||||
|
'roi_t3_max': int(40 * roi_t_scale * roi_t_alpha),
|
||||||
|
'roi_p1_min': 0.01 * roi_p_scale * roi_p_alpha,
|
||||||
|
'roi_p1_max': 0.04 * roi_p_scale * roi_p_alpha,
|
||||||
|
'roi_p2_min': 0.01 * roi_p_scale * roi_p_alpha,
|
||||||
|
'roi_p2_max': 0.07 * roi_p_scale * roi_p_alpha,
|
||||||
|
'roi_p3_min': 0.01 * roi_p_scale * roi_p_alpha,
|
||||||
|
'roi_p3_max': 0.20 * roi_p_scale * roi_p_alpha,
|
||||||
|
}
|
||||||
|
logger.debug(f"Using roi space limits: {roi_limits}")
|
||||||
|
p = {
|
||||||
|
'roi_t1': roi_limits['roi_t1_min'],
|
||||||
|
'roi_t2': roi_limits['roi_t2_min'],
|
||||||
|
'roi_t3': roi_limits['roi_t3_min'],
|
||||||
|
'roi_p1': roi_limits['roi_p1_min'],
|
||||||
|
'roi_p2': roi_limits['roi_p2_min'],
|
||||||
|
'roi_p3': roi_limits['roi_p3_min'],
|
||||||
|
}
|
||||||
|
logger.info(f"Min roi table: {round_dict(IHyperOpt.generate_roi_table(p), 5)}")
|
||||||
|
p = {
|
||||||
|
'roi_t1': roi_limits['roi_t1_max'],
|
||||||
|
'roi_t2': roi_limits['roi_t2_max'],
|
||||||
|
'roi_t3': roi_limits['roi_t3_max'],
|
||||||
|
'roi_p1': roi_limits['roi_p1_max'],
|
||||||
|
'roi_p2': roi_limits['roi_p2_max'],
|
||||||
|
'roi_p3': roi_limits['roi_p3_max'],
|
||||||
|
}
|
||||||
|
logger.info(f"Max roi table: {round_dict(IHyperOpt.generate_roi_table(p), 5)}")
|
||||||
|
|
||||||
|
return [
|
||||||
|
Integer(roi_limits['roi_t1_min'], roi_limits['roi_t1_max'], name='roi_t1'),
|
||||||
|
Integer(roi_limits['roi_t2_min'], roi_limits['roi_t2_max'], name='roi_t2'),
|
||||||
|
Integer(roi_limits['roi_t3_min'], roi_limits['roi_t3_max'], name='roi_t3'),
|
||||||
|
Real(roi_limits['roi_p1_min'], roi_limits['roi_p1_max'], name='roi_p1'),
|
||||||
|
Real(roi_limits['roi_p2_min'], roi_limits['roi_p2_max'], name='roi_p2'),
|
||||||
|
Real(roi_limits['roi_p3_min'], roi_limits['roi_p3_max'], name='roi_p3'),
|
||||||
|
]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def stoploss_space() -> List[Dimension]:
|
||||||
|
"""
|
||||||
|
Create a stoploss space.
|
||||||
|
|
||||||
|
Defines range of stoploss values to search.
|
||||||
|
You may override it in your custom Hyperopt class.
|
||||||
|
"""
|
||||||
|
return [
|
||||||
|
Real(-0.35, -0.02, name='stoploss'),
|
||||||
|
]
|
||||||
|
|
||||||
|
# This is needed for proper unpickling the class attribute ticker_interval
|
||||||
|
# which is set to the actual value by the resolver.
|
||||||
|
# Why do I still need such shamanic mantras in modern python?
|
||||||
|
def __getstate__(self):
|
||||||
|
state = self.__dict__.copy()
|
||||||
|
state['ticker_interval'] = self.ticker_interval
|
||||||
|
return state
|
||||||
|
|
||||||
|
def __setstate__(self, state):
|
||||||
|
self.__dict__.update(state)
|
||||||
|
IHyperOpt.ticker_interval = state['ticker_interval']
|
||||||
|
|||||||
25
freqtrade/optimize/hyperopt_loss_interface.py
Normal file
25
freqtrade/optimize/hyperopt_loss_interface.py
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
"""
|
||||||
|
IHyperOptLoss interface
|
||||||
|
This module defines the interface for the loss-function for hyperopts
|
||||||
|
"""
|
||||||
|
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from pandas import DataFrame
|
||||||
|
|
||||||
|
|
||||||
|
class IHyperOptLoss(ABC):
|
||||||
|
"""
|
||||||
|
Interface for freqtrade hyperopts Loss functions.
|
||||||
|
Defines the custom loss function (`hyperopt_loss_function()` which is evaluated every epoch.)
|
||||||
|
"""
|
||||||
|
ticker_interval: str
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
@abstractmethod
|
||||||
|
def hyperopt_loss_function(results: DataFrame, trade_count: int,
|
||||||
|
min_date: datetime, max_date: datetime, *args, **kwargs) -> float:
|
||||||
|
"""
|
||||||
|
Objective function, returns smaller number for better results
|
||||||
|
"""
|
||||||
38
freqtrade/optimize/hyperopt_loss_onlyprofit.py
Normal file
38
freqtrade/optimize/hyperopt_loss_onlyprofit.py
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
"""
|
||||||
|
OnlyProfitHyperOptLoss
|
||||||
|
|
||||||
|
This module defines the alternative HyperOptLoss class which can be used for
|
||||||
|
Hyperoptimization.
|
||||||
|
"""
|
||||||
|
from pandas import DataFrame
|
||||||
|
|
||||||
|
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
||||||
|
|
||||||
|
|
||||||
|
# This is assumed to be expected avg profit * expected trade count.
|
||||||
|
# For example, for 0.35% avg per trade (or 0.0035 as ratio) and 1100 trades,
|
||||||
|
# expected max profit = 3.85
|
||||||
|
#
|
||||||
|
# Note, this is ratio. 3.85 stated above means 385Σ%, 3.0 means 300Σ%.
|
||||||
|
#
|
||||||
|
# In this implementation it's only used in calculation of the resulting value
|
||||||
|
# of the objective function as a normalization coefficient and does not
|
||||||
|
# represent any limit for profits as in the Freqtrade legacy default loss function.
|
||||||
|
EXPECTED_MAX_PROFIT = 3.0
|
||||||
|
|
||||||
|
|
||||||
|
class OnlyProfitHyperOptLoss(IHyperOptLoss):
|
||||||
|
"""
|
||||||
|
Defines the loss function for hyperopt.
|
||||||
|
|
||||||
|
This implementation takes only profit into account.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def hyperopt_loss_function(results: DataFrame, trade_count: int,
|
||||||
|
*args, **kwargs) -> float:
|
||||||
|
"""
|
||||||
|
Objective function, returns smaller number for better results.
|
||||||
|
"""
|
||||||
|
total_profit = results.profit_percent.sum()
|
||||||
|
return 1 - total_profit / EXPECTED_MAX_PROFIT
|
||||||
45
freqtrade/optimize/hyperopt_loss_sharpe.py
Normal file
45
freqtrade/optimize/hyperopt_loss_sharpe.py
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
"""
|
||||||
|
SharpeHyperOptLoss
|
||||||
|
|
||||||
|
This module defines the alternative HyperOptLoss class which can be used for
|
||||||
|
Hyperoptimization.
|
||||||
|
"""
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from pandas import DataFrame
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
||||||
|
|
||||||
|
|
||||||
|
class SharpeHyperOptLoss(IHyperOptLoss):
|
||||||
|
"""
|
||||||
|
Defines the loss function for hyperopt.
|
||||||
|
|
||||||
|
This implementation uses the Sharpe Ratio calculation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def hyperopt_loss_function(results: DataFrame, trade_count: int,
|
||||||
|
min_date: datetime, max_date: datetime,
|
||||||
|
*args, **kwargs) -> float:
|
||||||
|
"""
|
||||||
|
Objective function, returns smaller number for more optimal results.
|
||||||
|
|
||||||
|
Uses Sharpe Ratio calculation.
|
||||||
|
"""
|
||||||
|
total_profit = results.profit_percent
|
||||||
|
days_period = (max_date - min_date).days
|
||||||
|
|
||||||
|
# adding slippage of 0.1% per trade
|
||||||
|
total_profit = total_profit - 0.0005
|
||||||
|
expected_yearly_return = total_profit.sum() / days_period
|
||||||
|
|
||||||
|
if (np.std(total_profit) != 0.):
|
||||||
|
sharp_ratio = expected_yearly_return / np.std(total_profit) * np.sqrt(365)
|
||||||
|
else:
|
||||||
|
# Define high (negative) sharpe ratio to be clear that this is NOT optimal.
|
||||||
|
sharp_ratio = -20.
|
||||||
|
|
||||||
|
# print(expected_yearly_return, np.std(total_profit), sharp_ratio)
|
||||||
|
return -sharp_ratio
|
||||||
@@ -8,6 +8,9 @@ import logging
|
|||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
|
from freqtrade.exchange import market_is_active
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@@ -60,32 +63,27 @@ class IPairList(ABC):
|
|||||||
def _validate_whitelist(self, whitelist: List[str]) -> List[str]:
|
def _validate_whitelist(self, whitelist: List[str]) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Check available markets and remove pair from whitelist if necessary
|
Check available markets and remove pair from whitelist if necessary
|
||||||
:param whitelist: the sorted list (based on BaseVolume) of pairs the user might want to
|
:param whitelist: the sorted list of pairs the user might want to trade
|
||||||
trade
|
:return: the list of pairs the user wants to trade without those unavailable or
|
||||||
:return: the list of pairs the user wants to trade without the one unavailable or
|
|
||||||
black_listed
|
black_listed
|
||||||
"""
|
"""
|
||||||
sanitized_whitelist = whitelist
|
markets = self._freqtrade.exchange.markets
|
||||||
markets = self._freqtrade.exchange.get_markets()
|
|
||||||
|
|
||||||
# Filter to markets in stake currency
|
sanitized_whitelist = set()
|
||||||
markets = [m for m in markets if m['quote'] == self._config['stake_currency']]
|
for pair in whitelist:
|
||||||
known_pairs = set()
|
# pair is not in the generated dynamic market, or in the blacklist ... ignore it
|
||||||
|
if (pair in self.blacklist or pair not in markets
|
||||||
for market in markets:
|
or not pair.endswith(self._config['stake_currency'])):
|
||||||
pair = market['symbol']
|
logger.warning(f"Pair {pair} is not compatible with exchange "
|
||||||
# pair is not int the generated dynamic market, or in the blacklist ... ignore it
|
f"{self._freqtrade.exchange.name} or contained in "
|
||||||
if pair not in whitelist or pair in self.blacklist:
|
f"your blacklist. Removing it from whitelist..")
|
||||||
continue
|
continue
|
||||||
# else the pair is valid
|
# Check if market is active
|
||||||
known_pairs.add(pair)
|
market = markets[pair]
|
||||||
# Market is not active
|
if not market_is_active(market):
|
||||||
if not market['active']:
|
logger.info(f"Ignoring {pair} from whitelist. Market is not active.")
|
||||||
sanitized_whitelist.remove(pair)
|
continue
|
||||||
logger.info(
|
sanitized_whitelist.add(pair)
|
||||||
'Ignoring %s from whitelist. Market is not active.',
|
|
||||||
pair
|
|
||||||
)
|
|
||||||
|
|
||||||
# We need to remove pairs that are unknown
|
# We need to remove pairs that are unknown
|
||||||
return [x for x in sanitized_whitelist if x in known_pairs]
|
return list(sanitized_whitelist)
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
"""
|
"""
|
||||||
Static List provider
|
Volume PairList provider
|
||||||
|
|
||||||
Provides lists as configured in config.json
|
Provides lists as configured in config.json
|
||||||
|
|
||||||
@@ -26,6 +26,7 @@ class VolumePairList(IPairList):
|
|||||||
'for "pairlist.config.number_assets"')
|
'for "pairlist.config.number_assets"')
|
||||||
self._number_pairs = self._whitelistconf['number_assets']
|
self._number_pairs = self._whitelistconf['number_assets']
|
||||||
self._sort_key = self._whitelistconf.get('sort_key', 'quoteVolume')
|
self._sort_key = self._whitelistconf.get('sort_key', 'quoteVolume')
|
||||||
|
self._precision_filter = self._whitelistconf.get('precision_filter', False)
|
||||||
|
|
||||||
if not self._freqtrade.exchange.exchange_has('fetchTickers'):
|
if not self._freqtrade.exchange.exchange_has('fetchTickers'):
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
@@ -52,9 +53,8 @@ class VolumePairList(IPairList):
|
|||||||
-> Please overwrite in subclasses
|
-> Please overwrite in subclasses
|
||||||
"""
|
"""
|
||||||
# Generate dynamic whitelist
|
# Generate dynamic whitelist
|
||||||
pairs = self._gen_pair_whitelist(self._config['stake_currency'], self._sort_key)
|
self._whitelist = self._gen_pair_whitelist(
|
||||||
# Validate whitelist to only have active market pairs
|
self._config['stake_currency'], self._sort_key)[:self._number_pairs]
|
||||||
self._whitelist = self._validate_whitelist(pairs)[:self._number_pairs]
|
|
||||||
|
|
||||||
@cached(TTLCache(maxsize=1, ttl=1800))
|
@cached(TTLCache(maxsize=1, ttl=1800))
|
||||||
def _gen_pair_whitelist(self, base_currency: str, key: str) -> List[str]:
|
def _gen_pair_whitelist(self, base_currency: str, key: str) -> List[str]:
|
||||||
@@ -68,8 +68,29 @@ class VolumePairList(IPairList):
|
|||||||
tickers = self._freqtrade.exchange.get_tickers()
|
tickers = self._freqtrade.exchange.get_tickers()
|
||||||
# check length so that we make sure that '/' is actually in the string
|
# check length so that we make sure that '/' is actually in the string
|
||||||
tickers = [v for k, v in tickers.items()
|
tickers = [v for k, v in tickers.items()
|
||||||
if len(k.split('/')) == 2 and k.split('/')[1] == base_currency]
|
if (len(k.split('/')) == 2 and k.split('/')[1] == base_currency
|
||||||
|
and v[key] is not None)]
|
||||||
sorted_tickers = sorted(tickers, reverse=True, key=lambda t: t[key])
|
sorted_tickers = sorted(tickers, reverse=True, key=lambda t: t[key])
|
||||||
pairs = [s['symbol'] for s in sorted_tickers]
|
# Validate whitelist to only have active market pairs
|
||||||
|
valid_pairs = self._validate_whitelist([s['symbol'] for s in sorted_tickers])
|
||||||
|
valid_tickers = [t for t in sorted_tickers if t["symbol"] in valid_pairs]
|
||||||
|
|
||||||
|
if self._freqtrade.strategy.stoploss is not None and self._precision_filter:
|
||||||
|
|
||||||
|
stop_prices = [self._freqtrade.get_target_bid(t["symbol"], t)
|
||||||
|
* (1 - abs(self._freqtrade.strategy.stoploss)) for t in valid_tickers]
|
||||||
|
rates = [sp * 0.99 for sp in stop_prices]
|
||||||
|
logger.debug("\n".join([f"{sp} : {r}" for sp, r in zip(stop_prices[:10], rates[:10])]))
|
||||||
|
for i, t in enumerate(valid_tickers):
|
||||||
|
sp = self._freqtrade.exchange.symbol_price_prec(t["symbol"], stop_prices[i])
|
||||||
|
r = self._freqtrade.exchange.symbol_price_prec(t["symbol"], rates[i])
|
||||||
|
logger.debug(f"{t['symbol']} - {sp} : {r}")
|
||||||
|
if sp <= r:
|
||||||
|
logger.info(f"Removed {t['symbol']} from whitelist, "
|
||||||
|
f"because stop price {sp} would be <= stop limit {r}")
|
||||||
|
valid_tickers.remove(t)
|
||||||
|
|
||||||
|
pairs = [s['symbol'] for s in valid_tickers]
|
||||||
|
logger.info(f"Searching pairs: {self._whitelist}")
|
||||||
|
|
||||||
return pairs
|
return pairs
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
This module contains the class to persist trades into SQLite
|
This module contains the class to persist trades into SQLite
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from typing import Any, Dict, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
import arrow
|
import arrow
|
||||||
from sqlalchemy import (Boolean, Column, DateTime, Float, Integer, String,
|
from sqlalchemy import (Boolean, Column, DateTime, Float, Integer, String,
|
||||||
@@ -19,21 +18,24 @@ from sqlalchemy.pool import StaticPool
|
|||||||
|
|
||||||
from freqtrade import OperationalException
|
from freqtrade import OperationalException
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
_DECL_BASE: Any = declarative_base()
|
_DECL_BASE: Any = declarative_base()
|
||||||
_SQL_DOCS_URL = 'http://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls'
|
_SQL_DOCS_URL = 'http://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls'
|
||||||
|
|
||||||
|
|
||||||
def init(config: Dict) -> None:
|
def init(db_url: str, clean_open_orders: bool = False) -> None:
|
||||||
"""
|
"""
|
||||||
Initializes this module with the given config,
|
Initializes this module with the given config,
|
||||||
registers all known command handlers
|
registers all known command handlers
|
||||||
and starts polling for message updates
|
and starts polling for message updates
|
||||||
:param config: config to use
|
:param db_url: Database to use
|
||||||
|
:param clean_open_orders: Remove open orders from the database.
|
||||||
|
Useful for dry-run or if all orders have been reset on the exchange.
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
db_url = config.get('db_url', None)
|
|
||||||
kwargs = {}
|
kwargs = {}
|
||||||
|
|
||||||
# Take care of thread ownership if in-memory db
|
# Take care of thread ownership if in-memory db
|
||||||
@@ -47,8 +49,8 @@ def init(config: Dict) -> None:
|
|||||||
try:
|
try:
|
||||||
engine = create_engine(db_url, **kwargs)
|
engine = create_engine(db_url, **kwargs)
|
||||||
except NoSuchModuleError:
|
except NoSuchModuleError:
|
||||||
raise OperationalException(f'Given value for db_url: \'{db_url}\' '
|
raise OperationalException(f"Given value for db_url: '{db_url}' "
|
||||||
f'is no valid database URL! (See {_SQL_DOCS_URL})')
|
f"is no valid database URL! (See {_SQL_DOCS_URL})")
|
||||||
|
|
||||||
session = scoped_session(sessionmaker(bind=engine, autoflush=True, autocommit=True))
|
session = scoped_session(sessionmaker(bind=engine, autoflush=True, autocommit=True))
|
||||||
Trade.session = session()
|
Trade.session = session()
|
||||||
@@ -57,7 +59,7 @@ def init(config: Dict) -> None:
|
|||||||
check_migrate(engine)
|
check_migrate(engine)
|
||||||
|
|
||||||
# Clean dry_run DB if the db is not in-memory
|
# Clean dry_run DB if the db is not in-memory
|
||||||
if config.get('dry_run', False) and db_url != 'sqlite://':
|
if clean_open_orders and db_url != 'sqlite://':
|
||||||
clean_dry_run_db()
|
clean_dry_run_db()
|
||||||
|
|
||||||
|
|
||||||
@@ -83,7 +85,7 @@ def check_migrate(engine) -> None:
|
|||||||
logger.debug(f'trying {table_back_name}')
|
logger.debug(f'trying {table_back_name}')
|
||||||
|
|
||||||
# Check for latest column
|
# Check for latest column
|
||||||
if not has_column(cols, 'stoploss_last_update'):
|
if not has_column(cols, 'stop_loss_pct'):
|
||||||
logger.info(f'Running database migration - backup available as {table_back_name}')
|
logger.info(f'Running database migration - backup available as {table_back_name}')
|
||||||
|
|
||||||
fee_open = get_column_def(cols, 'fee_open', 'fee')
|
fee_open = get_column_def(cols, 'fee_open', 'fee')
|
||||||
@@ -91,10 +93,13 @@ def check_migrate(engine) -> None:
|
|||||||
open_rate_requested = get_column_def(cols, 'open_rate_requested', 'null')
|
open_rate_requested = get_column_def(cols, 'open_rate_requested', 'null')
|
||||||
close_rate_requested = get_column_def(cols, 'close_rate_requested', 'null')
|
close_rate_requested = get_column_def(cols, 'close_rate_requested', 'null')
|
||||||
stop_loss = get_column_def(cols, 'stop_loss', '0.0')
|
stop_loss = get_column_def(cols, 'stop_loss', '0.0')
|
||||||
|
stop_loss_pct = get_column_def(cols, 'stop_loss_pct', 'null')
|
||||||
initial_stop_loss = get_column_def(cols, 'initial_stop_loss', '0.0')
|
initial_stop_loss = get_column_def(cols, 'initial_stop_loss', '0.0')
|
||||||
|
initial_stop_loss_pct = get_column_def(cols, 'initial_stop_loss_pct', 'null')
|
||||||
stoploss_order_id = get_column_def(cols, 'stoploss_order_id', 'null')
|
stoploss_order_id = get_column_def(cols, 'stoploss_order_id', 'null')
|
||||||
stoploss_last_update = get_column_def(cols, 'stoploss_last_update', 'null')
|
stoploss_last_update = get_column_def(cols, 'stoploss_last_update', 'null')
|
||||||
max_rate = get_column_def(cols, 'max_rate', '0.0')
|
max_rate = get_column_def(cols, 'max_rate', '0.0')
|
||||||
|
min_rate = get_column_def(cols, 'min_rate', 'null')
|
||||||
sell_reason = get_column_def(cols, 'sell_reason', 'null')
|
sell_reason = get_column_def(cols, 'sell_reason', 'null')
|
||||||
strategy = get_column_def(cols, 'strategy', 'null')
|
strategy = get_column_def(cols, 'strategy', 'null')
|
||||||
ticker_interval = get_column_def(cols, 'ticker_interval', 'null')
|
ticker_interval = get_column_def(cols, 'ticker_interval', 'null')
|
||||||
@@ -112,8 +117,9 @@ def check_migrate(engine) -> None:
|
|||||||
(id, exchange, pair, is_open, fee_open, fee_close, open_rate,
|
(id, exchange, pair, is_open, fee_open, fee_close, open_rate,
|
||||||
open_rate_requested, close_rate, close_rate_requested, close_profit,
|
open_rate_requested, close_rate, close_rate_requested, close_profit,
|
||||||
stake_amount, amount, open_date, close_date, open_order_id,
|
stake_amount, amount, open_date, close_date, open_order_id,
|
||||||
stop_loss, initial_stop_loss, stoploss_order_id, stoploss_last_update,
|
stop_loss, stop_loss_pct, initial_stop_loss, initial_stop_loss_pct,
|
||||||
max_rate, sell_reason, strategy,
|
stoploss_order_id, stoploss_last_update,
|
||||||
|
max_rate, min_rate, sell_reason, strategy,
|
||||||
ticker_interval
|
ticker_interval
|
||||||
)
|
)
|
||||||
select id, lower(exchange),
|
select id, lower(exchange),
|
||||||
@@ -128,9 +134,11 @@ def check_migrate(engine) -> None:
|
|||||||
open_rate, {open_rate_requested} open_rate_requested, close_rate,
|
open_rate, {open_rate_requested} open_rate_requested, close_rate,
|
||||||
{close_rate_requested} close_rate_requested, close_profit,
|
{close_rate_requested} close_rate_requested, close_profit,
|
||||||
stake_amount, amount, open_date, close_date, open_order_id,
|
stake_amount, amount, open_date, close_date, open_order_id,
|
||||||
{stop_loss} stop_loss, {initial_stop_loss} initial_stop_loss,
|
{stop_loss} stop_loss, {stop_loss_pct} stop_loss_pct,
|
||||||
|
{initial_stop_loss} initial_stop_loss,
|
||||||
|
{initial_stop_loss_pct} initial_stop_loss_pct,
|
||||||
{stoploss_order_id} stoploss_order_id, {stoploss_last_update} stoploss_last_update,
|
{stoploss_order_id} stoploss_order_id, {stoploss_last_update} stoploss_last_update,
|
||||||
{max_rate} max_rate, {sell_reason} sell_reason,
|
{max_rate} max_rate, {min_rate} min_rate, {sell_reason} sell_reason,
|
||||||
{strategy} strategy, {ticker_interval} ticker_interval
|
{strategy} strategy, {ticker_interval} ticker_interval
|
||||||
from {table_back_name}
|
from {table_back_name}
|
||||||
""")
|
""")
|
||||||
@@ -183,64 +191,98 @@ class Trade(_DECL_BASE):
|
|||||||
open_order_id = Column(String)
|
open_order_id = Column(String)
|
||||||
# absolute value of the stop loss
|
# absolute value of the stop loss
|
||||||
stop_loss = Column(Float, nullable=True, default=0.0)
|
stop_loss = Column(Float, nullable=True, default=0.0)
|
||||||
|
# percentage value of the stop loss
|
||||||
|
stop_loss_pct = Column(Float, nullable=True)
|
||||||
# absolute value of the initial stop loss
|
# absolute value of the initial stop loss
|
||||||
initial_stop_loss = Column(Float, nullable=True, default=0.0)
|
initial_stop_loss = Column(Float, nullable=True, default=0.0)
|
||||||
|
# percentage value of the initial stop loss
|
||||||
|
initial_stop_loss_pct = Column(Float, nullable=True)
|
||||||
# stoploss order id which is on exchange
|
# stoploss order id which is on exchange
|
||||||
stoploss_order_id = Column(String, nullable=True, index=True)
|
stoploss_order_id = Column(String, nullable=True, index=True)
|
||||||
# last update time of the stoploss order on exchange
|
# last update time of the stoploss order on exchange
|
||||||
stoploss_last_update = Column(DateTime, nullable=True)
|
stoploss_last_update = Column(DateTime, nullable=True)
|
||||||
# absolute value of the highest reached price
|
# absolute value of the highest reached price
|
||||||
max_rate = Column(Float, nullable=True, default=0.0)
|
max_rate = Column(Float, nullable=True, default=0.0)
|
||||||
|
# Lowest price reached
|
||||||
|
min_rate = Column(Float, nullable=True)
|
||||||
sell_reason = Column(String, nullable=True)
|
sell_reason = Column(String, nullable=True)
|
||||||
strategy = Column(String, nullable=True)
|
strategy = Column(String, nullable=True)
|
||||||
ticker_interval = Column(Integer, nullable=True)
|
ticker_interval = Column(Integer, nullable=True)
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
open_since = arrow.get(self.open_date).humanize() if self.is_open else 'closed'
|
open_since = self.open_date.strftime('%Y-%m-%d %H:%M:%S') if self.is_open else 'closed'
|
||||||
|
|
||||||
return (f'Trade(id={self.id}, pair={self.pair}, amount={self.amount:.8f}, '
|
return (f'Trade(id={self.id}, pair={self.pair}, amount={self.amount:.8f}, '
|
||||||
f'open_rate={self.open_rate:.8f}, open_since={open_since})')
|
f'open_rate={self.open_rate:.8f}, open_since={open_since})')
|
||||||
|
|
||||||
def adjust_stop_loss(self, current_price: float, stoploss: float, initial: bool = False):
|
def to_json(self) -> Dict[str, Any]:
|
||||||
"""this adjusts the stop loss to it's most recently observed setting"""
|
return {
|
||||||
|
'trade_id': self.id,
|
||||||
|
'pair': self.pair,
|
||||||
|
'open_date_hum': arrow.get(self.open_date).humanize(),
|
||||||
|
'open_date': self.open_date.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
'close_date_hum': (arrow.get(self.close_date).humanize()
|
||||||
|
if self.close_date else None),
|
||||||
|
'close_date': (self.close_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
if self.close_date else None),
|
||||||
|
'open_rate': self.open_rate,
|
||||||
|
'close_rate': self.close_rate,
|
||||||
|
'amount': round(self.amount, 8),
|
||||||
|
'stake_amount': round(self.stake_amount, 8),
|
||||||
|
'stop_loss': self.stop_loss,
|
||||||
|
'stop_loss_pct': (self.stop_loss_pct * 100) if self.stop_loss_pct else None,
|
||||||
|
'initial_stop_loss': self.initial_stop_loss,
|
||||||
|
'initial_stop_loss_pct': (self.initial_stop_loss_pct * 100
|
||||||
|
if self.initial_stop_loss_pct else None),
|
||||||
|
}
|
||||||
|
|
||||||
|
def adjust_min_max_rates(self, current_price: float):
|
||||||
|
"""
|
||||||
|
Adjust the max_rate and min_rate.
|
||||||
|
"""
|
||||||
|
self.max_rate = max(current_price, self.max_rate or self.open_rate)
|
||||||
|
self.min_rate = min(current_price, self.min_rate or self.open_rate)
|
||||||
|
|
||||||
|
def adjust_stop_loss(self, current_price: float, stoploss: float, initial: bool = False):
|
||||||
|
"""
|
||||||
|
This adjusts the stop loss to it's most recently observed setting
|
||||||
|
:param current_price: Current rate the asset is traded
|
||||||
|
:param stoploss: Stoploss as factor (sample -0.05 -> -5% below current price).
|
||||||
|
:param initial: Called to initiate stop_loss.
|
||||||
|
Skips everything if self.stop_loss is already set.
|
||||||
|
"""
|
||||||
if initial and not (self.stop_loss is None or self.stop_loss == 0):
|
if initial and not (self.stop_loss is None or self.stop_loss == 0):
|
||||||
# Don't modify if called with initial and nothing to do
|
# Don't modify if called with initial and nothing to do
|
||||||
return
|
return
|
||||||
|
|
||||||
new_loss = float(current_price * (1 - abs(stoploss)))
|
new_loss = float(current_price * (1 - abs(stoploss)))
|
||||||
|
|
||||||
# keeping track of the highest observed rate for this trade
|
|
||||||
if self.max_rate is None:
|
|
||||||
self.max_rate = current_price
|
|
||||||
else:
|
|
||||||
if current_price > self.max_rate:
|
|
||||||
self.max_rate = current_price
|
|
||||||
|
|
||||||
# no stop loss assigned yet
|
# no stop loss assigned yet
|
||||||
if not self.stop_loss:
|
if not self.stop_loss:
|
||||||
logger.debug("assigning new stop loss")
|
logger.debug(f"{self.pair} - Assigning new stoploss...")
|
||||||
self.stop_loss = new_loss
|
self.stop_loss = new_loss
|
||||||
|
self.stop_loss_pct = -1 * abs(stoploss)
|
||||||
self.initial_stop_loss = new_loss
|
self.initial_stop_loss = new_loss
|
||||||
|
self.initial_stop_loss_pct = -1 * abs(stoploss)
|
||||||
self.stoploss_last_update = datetime.utcnow()
|
self.stoploss_last_update = datetime.utcnow()
|
||||||
|
|
||||||
# evaluate if the stop loss needs to be updated
|
# evaluate if the stop loss needs to be updated
|
||||||
else:
|
else:
|
||||||
if new_loss > self.stop_loss: # stop losses only walk up, never down!
|
if new_loss > self.stop_loss: # stop losses only walk up, never down!
|
||||||
|
logger.debug(f"{self.pair} - Adjusting stoploss...")
|
||||||
self.stop_loss = new_loss
|
self.stop_loss = new_loss
|
||||||
|
self.stop_loss_pct = -1 * abs(stoploss)
|
||||||
self.stoploss_last_update = datetime.utcnow()
|
self.stoploss_last_update = datetime.utcnow()
|
||||||
logger.debug("adjusted stop loss")
|
|
||||||
else:
|
else:
|
||||||
logger.debug("keeping current stop loss")
|
logger.debug(f"{self.pair} - Keeping current stoploss...")
|
||||||
|
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"{self.pair} - current price {current_price:.8f}, "
|
f"{self.pair} - Stoploss adjusted. current_price={current_price:.8f}, "
|
||||||
f"bought at {self.open_rate:.8f} and calculated "
|
f"open_rate={self.open_rate:.8f}, max_rate={self.max_rate:.8f}, "
|
||||||
f"stop loss is at: {self.initial_stop_loss:.8f} initial "
|
f"initial_stop_loss={self.initial_stop_loss:.8f}, "
|
||||||
f"stop at {self.stop_loss:.8f}. "
|
f"stop_loss={self.stop_loss:.8f}. "
|
||||||
f"trailing stop loss saved us: "
|
f"Trailing stoploss saved us: "
|
||||||
f"{float(self.stop_loss) - float(self.initial_stop_loss):.8f} "
|
f"{float(self.stop_loss) - float(self.initial_stop_loss):.8f}.")
|
||||||
f"and max observed rate was {self.max_rate:.8f}")
|
|
||||||
|
|
||||||
def update(self, order: Dict) -> None:
|
def update(self, order: Dict) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -266,6 +308,7 @@ class Trade(_DECL_BASE):
|
|||||||
logger.info('%s_SELL has been fulfilled for %s.', order_type.upper(), self)
|
logger.info('%s_SELL has been fulfilled for %s.', order_type.upper(), self)
|
||||||
elif order_type == 'stop_loss_limit':
|
elif order_type == 'stop_loss_limit':
|
||||||
self.stoploss_order_id = None
|
self.stoploss_order_id = None
|
||||||
|
self.close_rate_requested = self.stop_loss
|
||||||
logger.info('STOP_LOSS_LIMIT is hit for %s.', self)
|
logger.info('STOP_LOSS_LIMIT is hit for %s.', self)
|
||||||
self.close(order['average'])
|
self.close(order['average'])
|
||||||
else:
|
else:
|
||||||
@@ -287,24 +330,19 @@ class Trade(_DECL_BASE):
|
|||||||
self
|
self
|
||||||
)
|
)
|
||||||
|
|
||||||
def calc_open_trade_price(
|
def calc_open_trade_price(self, fee: Optional[float] = None) -> float:
|
||||||
self,
|
|
||||||
fee: Optional[float] = None) -> float:
|
|
||||||
"""
|
"""
|
||||||
Calculate the open_rate including fee.
|
Calculate the open_rate including fee.
|
||||||
:param fee: fee to use on the open rate (optional).
|
:param fee: fee to use on the open rate (optional).
|
||||||
If rate is not set self.fee will be used
|
If rate is not set self.fee will be used
|
||||||
:return: Price in of the open trade incl. Fees
|
:return: Price in of the open trade incl. Fees
|
||||||
"""
|
"""
|
||||||
|
|
||||||
buy_trade = (Decimal(self.amount) * Decimal(self.open_rate))
|
buy_trade = (Decimal(self.amount) * Decimal(self.open_rate))
|
||||||
fees = buy_trade * Decimal(fee or self.fee_open)
|
fees = buy_trade * Decimal(fee or self.fee_open)
|
||||||
return float(buy_trade + fees)
|
return float(buy_trade + fees)
|
||||||
|
|
||||||
def calc_close_trade_price(
|
def calc_close_trade_price(self, rate: Optional[float] = None,
|
||||||
self,
|
fee: Optional[float] = None) -> float:
|
||||||
rate: Optional[float] = None,
|
|
||||||
fee: Optional[float] = None) -> float:
|
|
||||||
"""
|
"""
|
||||||
Calculate the close_rate including fee
|
Calculate the close_rate including fee
|
||||||
:param fee: fee to use on the close rate (optional).
|
:param fee: fee to use on the close rate (optional).
|
||||||
@@ -313,7 +351,6 @@ class Trade(_DECL_BASE):
|
|||||||
If rate is not set self.close_rate will be used
|
If rate is not set self.close_rate will be used
|
||||||
:return: Price in BTC of the open trade
|
:return: Price in BTC of the open trade
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if rate is None and not self.close_rate:
|
if rate is None and not self.close_rate:
|
||||||
return 0.0
|
return 0.0
|
||||||
|
|
||||||
@@ -321,10 +358,8 @@ class Trade(_DECL_BASE):
|
|||||||
fees = sell_trade * Decimal(fee or self.fee_close)
|
fees = sell_trade * Decimal(fee or self.fee_close)
|
||||||
return float(sell_trade - fees)
|
return float(sell_trade - fees)
|
||||||
|
|
||||||
def calc_profit(
|
def calc_profit(self, rate: Optional[float] = None,
|
||||||
self,
|
fee: Optional[float] = None) -> float:
|
||||||
rate: Optional[float] = None,
|
|
||||||
fee: Optional[float] = None) -> float:
|
|
||||||
"""
|
"""
|
||||||
Calculate the absolute profit in stake currency between Close and Open trade
|
Calculate the absolute profit in stake currency between Close and Open trade
|
||||||
:param fee: fee to use on the close rate (optional).
|
:param fee: fee to use on the close rate (optional).
|
||||||
@@ -341,10 +376,8 @@ class Trade(_DECL_BASE):
|
|||||||
profit = close_trade_price - open_trade_price
|
profit = close_trade_price - open_trade_price
|
||||||
return float(f"{profit:.8f}")
|
return float(f"{profit:.8f}")
|
||||||
|
|
||||||
def calc_profit_percent(
|
def calc_profit_percent(self, rate: Optional[float] = None,
|
||||||
self,
|
fee: Optional[float] = None) -> float:
|
||||||
rate: Optional[float] = None,
|
|
||||||
fee: Optional[float] = None) -> float:
|
|
||||||
"""
|
"""
|
||||||
Calculates the profit in percentage (including fee).
|
Calculates the profit in percentage (including fee).
|
||||||
:param rate: rate to compare with (optional).
|
:param rate: rate to compare with (optional).
|
||||||
@@ -352,7 +385,6 @@ class Trade(_DECL_BASE):
|
|||||||
:param fee: fee to use on the close rate (optional).
|
:param fee: fee to use on the close rate (optional).
|
||||||
:return: profit in percentage as float
|
:return: profit in percentage as float
|
||||||
"""
|
"""
|
||||||
|
|
||||||
open_trade_price = self.calc_open_trade_price()
|
open_trade_price = self.calc_open_trade_price()
|
||||||
close_trade_price = self.calc_close_trade_price(
|
close_trade_price = self.calc_close_trade_price(
|
||||||
rate=(rate or self.close_rate),
|
rate=(rate or self.close_rate),
|
||||||
@@ -371,3 +403,29 @@ class Trade(_DECL_BASE):
|
|||||||
.filter(Trade.is_open.is_(True))\
|
.filter(Trade.is_open.is_(True))\
|
||||||
.scalar()
|
.scalar()
|
||||||
return total_open_stake_amount or 0
|
return total_open_stake_amount or 0
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_open_trades() -> List[Any]:
|
||||||
|
"""
|
||||||
|
Query trades from persistence layer
|
||||||
|
"""
|
||||||
|
return Trade.query.filter(Trade.is_open.is_(True)).all()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def stoploss_reinitialization(desired_stoploss):
|
||||||
|
"""
|
||||||
|
Adjust initial Stoploss to desired stoploss for all open trades.
|
||||||
|
"""
|
||||||
|
for trade in Trade.get_open_trades():
|
||||||
|
logger.info("Found open trade: %s", trade)
|
||||||
|
|
||||||
|
# skip case if trailing-stop changed the stoploss already.
|
||||||
|
if (trade.stop_loss == trade.initial_stop_loss
|
||||||
|
and trade.initial_stop_loss_pct != desired_stoploss):
|
||||||
|
# Stoploss value got changed
|
||||||
|
|
||||||
|
logger.info(f"Stoploss for {trade} needs adjustment...")
|
||||||
|
# Force reset of stoploss
|
||||||
|
trade.stop_loss = None
|
||||||
|
trade.adjust_stop_loss(trade.open_rate, desired_stoploss)
|
||||||
|
logger.info(f"New stoploss: {trade.stop_loss}.")
|
||||||
|
|||||||
36
freqtrade/plot/plot_utils.py
Normal file
36
freqtrade/plot/plot_utils.py
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
from typing import Any, Dict
|
||||||
|
|
||||||
|
from freqtrade import OperationalException
|
||||||
|
from freqtrade.state import RunMode
|
||||||
|
from freqtrade.utils import setup_utils_configuration
|
||||||
|
|
||||||
|
|
||||||
|
def validate_plot_args(args: Dict[str, Any]):
|
||||||
|
if not args.get('datadir') and not args.get('config'):
|
||||||
|
raise OperationalException(
|
||||||
|
"You need to specify either `--datadir` or `--config` "
|
||||||
|
"for plot-profit and plot-dataframe.")
|
||||||
|
|
||||||
|
|
||||||
|
def start_plot_dataframe(args: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Entrypoint for dataframe plotting
|
||||||
|
"""
|
||||||
|
# Import here to avoid errors if plot-dependencies are not installed.
|
||||||
|
from freqtrade.plot.plotting import load_and_plot_trades
|
||||||
|
validate_plot_args(args)
|
||||||
|
config = setup_utils_configuration(args, RunMode.PLOT)
|
||||||
|
|
||||||
|
load_and_plot_trades(config)
|
||||||
|
|
||||||
|
|
||||||
|
def start_plot_profit(args: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Entrypoint for plot_profit
|
||||||
|
"""
|
||||||
|
# Import here to avoid errors if plot-dependencies are not installed.
|
||||||
|
from freqtrade.plot.plotting import plot_profit
|
||||||
|
validate_plot_args(args)
|
||||||
|
config = setup_utils_configuration(args, RunMode.PLOT)
|
||||||
|
|
||||||
|
plot_profit(config)
|
||||||
390
freqtrade/plot/plotting.py
Normal file
390
freqtrade/plot/plotting.py
Normal file
@@ -0,0 +1,390 @@
|
|||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
from freqtrade.configuration import TimeRange
|
||||||
|
from freqtrade.data import history
|
||||||
|
from freqtrade.data.btanalysis import (combine_tickers_with_mean,
|
||||||
|
create_cum_profit,
|
||||||
|
extract_trades_of_period, load_trades)
|
||||||
|
from freqtrade.resolvers import StrategyResolver
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
from plotly.subplots import make_subplots
|
||||||
|
from plotly.offline import plot
|
||||||
|
import plotly.graph_objects as go
|
||||||
|
except ImportError:
|
||||||
|
logger.exception("Module plotly not found \n Please install using `pip3 install plotly`")
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
def init_plotscript(config):
|
||||||
|
"""
|
||||||
|
Initialize objects needed for plotting
|
||||||
|
:return: Dict with tickers, trades and pairs
|
||||||
|
"""
|
||||||
|
|
||||||
|
if "pairs" in config:
|
||||||
|
pairs = config["pairs"]
|
||||||
|
else:
|
||||||
|
pairs = config["exchange"]["pair_whitelist"]
|
||||||
|
|
||||||
|
# Set timerange to use
|
||||||
|
timerange = TimeRange.parse_timerange(config.get("timerange"))
|
||||||
|
|
||||||
|
tickers = history.load_data(
|
||||||
|
datadir=Path(str(config.get("datadir"))),
|
||||||
|
pairs=pairs,
|
||||||
|
ticker_interval=config.get('ticker_interval', '5m'),
|
||||||
|
timerange=timerange,
|
||||||
|
)
|
||||||
|
|
||||||
|
trades = load_trades(config['trade_source'],
|
||||||
|
db_url=config.get('db_url'),
|
||||||
|
exportfilename=config.get('exportfilename'),
|
||||||
|
)
|
||||||
|
|
||||||
|
return {"tickers": tickers,
|
||||||
|
"trades": trades,
|
||||||
|
"pairs": pairs,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def add_indicators(fig, row, indicators: List[str], data: pd.DataFrame) -> make_subplots:
|
||||||
|
"""
|
||||||
|
Generator all the indicator selected by the user for a specific row
|
||||||
|
:param fig: Plot figure to append to
|
||||||
|
:param row: row number for this plot
|
||||||
|
:param indicators: List of indicators present in the dataframe
|
||||||
|
:param data: candlestick DataFrame
|
||||||
|
"""
|
||||||
|
for indicator in indicators:
|
||||||
|
if indicator in data:
|
||||||
|
scatter = go.Scatter(
|
||||||
|
x=data['date'],
|
||||||
|
y=data[indicator].values,
|
||||||
|
mode='lines',
|
||||||
|
name=indicator
|
||||||
|
)
|
||||||
|
fig.add_trace(scatter, row, 1)
|
||||||
|
else:
|
||||||
|
logger.info(
|
||||||
|
'Indicator "%s" ignored. Reason: This indicator is not found '
|
||||||
|
'in your strategy.',
|
||||||
|
indicator
|
||||||
|
)
|
||||||
|
|
||||||
|
return fig
|
||||||
|
|
||||||
|
|
||||||
|
def add_profit(fig, row, data: pd.DataFrame, column: str, name: str) -> make_subplots:
|
||||||
|
"""
|
||||||
|
Add profit-plot
|
||||||
|
:param fig: Plot figure to append to
|
||||||
|
:param row: row number for this plot
|
||||||
|
:param data: candlestick DataFrame
|
||||||
|
:param column: Column to use for plot
|
||||||
|
:param name: Name to use
|
||||||
|
:return: fig with added profit plot
|
||||||
|
"""
|
||||||
|
profit = go.Scatter(
|
||||||
|
x=data.index,
|
||||||
|
y=data[column],
|
||||||
|
name=name,
|
||||||
|
)
|
||||||
|
fig.add_trace(profit, row, 1)
|
||||||
|
|
||||||
|
return fig
|
||||||
|
|
||||||
|
|
||||||
|
def plot_trades(fig, trades: pd.DataFrame) -> make_subplots:
|
||||||
|
"""
|
||||||
|
Add trades to "fig"
|
||||||
|
"""
|
||||||
|
# Trades can be empty
|
||||||
|
if trades is not None and len(trades) > 0:
|
||||||
|
trade_buys = go.Scatter(
|
||||||
|
x=trades["open_time"],
|
||||||
|
y=trades["open_rate"],
|
||||||
|
mode='markers',
|
||||||
|
name='trade_buy',
|
||||||
|
marker=dict(
|
||||||
|
symbol='square-open',
|
||||||
|
size=11,
|
||||||
|
line=dict(width=2),
|
||||||
|
color='green'
|
||||||
|
)
|
||||||
|
)
|
||||||
|
# Create description for sell summarizing the trade
|
||||||
|
desc = trades.apply(lambda row: f"{round(row['profitperc'], 3)}%, {row['sell_reason']}, "
|
||||||
|
f"{row['duration']}min",
|
||||||
|
axis=1)
|
||||||
|
trade_sells = go.Scatter(
|
||||||
|
x=trades["close_time"],
|
||||||
|
y=trades["close_rate"],
|
||||||
|
text=desc,
|
||||||
|
mode='markers',
|
||||||
|
name='trade_sell',
|
||||||
|
marker=dict(
|
||||||
|
symbol='square-open',
|
||||||
|
size=11,
|
||||||
|
line=dict(width=2),
|
||||||
|
color='red'
|
||||||
|
)
|
||||||
|
)
|
||||||
|
fig.add_trace(trade_buys, 1, 1)
|
||||||
|
fig.add_trace(trade_sells, 1, 1)
|
||||||
|
else:
|
||||||
|
logger.warning("No trades found.")
|
||||||
|
return fig
|
||||||
|
|
||||||
|
|
||||||
|
def generate_candlestick_graph(pair: str, data: pd.DataFrame, trades: pd.DataFrame = None,
|
||||||
|
indicators1: List[str] = [],
|
||||||
|
indicators2: List[str] = [],) -> go.Figure:
|
||||||
|
"""
|
||||||
|
Generate the graph from the data generated by Backtesting or from DB
|
||||||
|
Volume will always be ploted in row2, so Row 1 and 3 are to our disposal for custom indicators
|
||||||
|
:param pair: Pair to Display on the graph
|
||||||
|
:param data: OHLCV DataFrame containing indicators and buy/sell signals
|
||||||
|
:param trades: All trades created
|
||||||
|
:param indicators1: List containing Main plot indicators
|
||||||
|
:param indicators2: List containing Sub plot indicators
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Define the graph
|
||||||
|
fig = make_subplots(
|
||||||
|
rows=3,
|
||||||
|
cols=1,
|
||||||
|
shared_xaxes=True,
|
||||||
|
row_width=[1, 1, 4],
|
||||||
|
vertical_spacing=0.0001,
|
||||||
|
)
|
||||||
|
fig['layout'].update(title=pair)
|
||||||
|
fig['layout']['yaxis1'].update(title='Price')
|
||||||
|
fig['layout']['yaxis2'].update(title='Volume')
|
||||||
|
fig['layout']['yaxis3'].update(title='Other')
|
||||||
|
fig['layout']['xaxis']['rangeslider'].update(visible=False)
|
||||||
|
|
||||||
|
# Common information
|
||||||
|
candles = go.Candlestick(
|
||||||
|
x=data.date,
|
||||||
|
open=data.open,
|
||||||
|
high=data.high,
|
||||||
|
low=data.low,
|
||||||
|
close=data.close,
|
||||||
|
name='Price'
|
||||||
|
)
|
||||||
|
fig.add_trace(candles, 1, 1)
|
||||||
|
|
||||||
|
if 'buy' in data.columns:
|
||||||
|
df_buy = data[data['buy'] == 1]
|
||||||
|
if len(df_buy) > 0:
|
||||||
|
buys = go.Scatter(
|
||||||
|
x=df_buy.date,
|
||||||
|
y=df_buy.close,
|
||||||
|
mode='markers',
|
||||||
|
name='buy',
|
||||||
|
marker=dict(
|
||||||
|
symbol='triangle-up-dot',
|
||||||
|
size=9,
|
||||||
|
line=dict(width=1),
|
||||||
|
color='green',
|
||||||
|
)
|
||||||
|
)
|
||||||
|
fig.add_trace(buys, 1, 1)
|
||||||
|
else:
|
||||||
|
logger.warning("No buy-signals found.")
|
||||||
|
|
||||||
|
if 'sell' in data.columns:
|
||||||
|
df_sell = data[data['sell'] == 1]
|
||||||
|
if len(df_sell) > 0:
|
||||||
|
sells = go.Scatter(
|
||||||
|
x=df_sell.date,
|
||||||
|
y=df_sell.close,
|
||||||
|
mode='markers',
|
||||||
|
name='sell',
|
||||||
|
marker=dict(
|
||||||
|
symbol='triangle-down-dot',
|
||||||
|
size=9,
|
||||||
|
line=dict(width=1),
|
||||||
|
color='red',
|
||||||
|
)
|
||||||
|
)
|
||||||
|
fig.add_trace(sells, 1, 1)
|
||||||
|
else:
|
||||||
|
logger.warning("No sell-signals found.")
|
||||||
|
|
||||||
|
# TODO: Figure out why scattergl causes problems plotly/plotly.js#2284
|
||||||
|
if 'bb_lowerband' in data and 'bb_upperband' in data:
|
||||||
|
bb_lower = go.Scatter(
|
||||||
|
x=data.date,
|
||||||
|
y=data.bb_lowerband,
|
||||||
|
showlegend=False,
|
||||||
|
line={'color': 'rgba(255,255,255,0)'},
|
||||||
|
)
|
||||||
|
bb_upper = go.Scatter(
|
||||||
|
x=data.date,
|
||||||
|
y=data.bb_upperband,
|
||||||
|
name='Bollinger Band',
|
||||||
|
fill="tonexty",
|
||||||
|
fillcolor="rgba(0,176,246,0.2)",
|
||||||
|
line={'color': 'rgba(255,255,255,0)'},
|
||||||
|
)
|
||||||
|
fig.add_trace(bb_lower, 1, 1)
|
||||||
|
fig.add_trace(bb_upper, 1, 1)
|
||||||
|
if 'bb_upperband' in indicators1 and 'bb_lowerband' in indicators1:
|
||||||
|
indicators1.remove('bb_upperband')
|
||||||
|
indicators1.remove('bb_lowerband')
|
||||||
|
|
||||||
|
# Add indicators to main plot
|
||||||
|
fig = add_indicators(fig=fig, row=1, indicators=indicators1, data=data)
|
||||||
|
|
||||||
|
fig = plot_trades(fig, trades)
|
||||||
|
|
||||||
|
# Volume goes to row 2
|
||||||
|
volume = go.Bar(
|
||||||
|
x=data['date'],
|
||||||
|
y=data['volume'],
|
||||||
|
name='Volume',
|
||||||
|
marker_color='DarkSlateGrey',
|
||||||
|
marker_line_color='DarkSlateGrey'
|
||||||
|
)
|
||||||
|
fig.add_trace(volume, 2, 1)
|
||||||
|
|
||||||
|
# Add indicators to separate row
|
||||||
|
fig = add_indicators(fig=fig, row=3, indicators=indicators2, data=data)
|
||||||
|
|
||||||
|
return fig
|
||||||
|
|
||||||
|
|
||||||
|
def generate_profit_graph(pairs: str, tickers: Dict[str, pd.DataFrame],
|
||||||
|
trades: pd.DataFrame, timeframe: str) -> go.Figure:
|
||||||
|
# Combine close-values for all pairs, rename columns to "pair"
|
||||||
|
df_comb = combine_tickers_with_mean(tickers, "close")
|
||||||
|
|
||||||
|
# Add combined cumulative profit
|
||||||
|
df_comb = create_cum_profit(df_comb, trades, 'cum_profit', timeframe)
|
||||||
|
|
||||||
|
# Plot the pairs average close prices, and total profit growth
|
||||||
|
avgclose = go.Scatter(
|
||||||
|
x=df_comb.index,
|
||||||
|
y=df_comb['mean'],
|
||||||
|
name='Avg close price',
|
||||||
|
)
|
||||||
|
|
||||||
|
fig = make_subplots(rows=3, cols=1, shared_xaxes=True,
|
||||||
|
row_width=[1, 1, 1],
|
||||||
|
vertical_spacing=0.05,
|
||||||
|
subplot_titles=["AVG Close Price", "Combined Profit", "Profit per pair"])
|
||||||
|
fig['layout'].update(title="Freqtrade Profit plot")
|
||||||
|
fig['layout']['yaxis1'].update(title='Price')
|
||||||
|
fig['layout']['yaxis2'].update(title='Profit')
|
||||||
|
fig['layout']['yaxis3'].update(title='Profit')
|
||||||
|
fig['layout']['xaxis']['rangeslider'].update(visible=False)
|
||||||
|
|
||||||
|
fig.add_trace(avgclose, 1, 1)
|
||||||
|
fig = add_profit(fig, 2, df_comb, 'cum_profit', 'Profit')
|
||||||
|
|
||||||
|
for pair in pairs:
|
||||||
|
profit_col = f'cum_profit_{pair}'
|
||||||
|
df_comb = create_cum_profit(df_comb, trades[trades['pair'] == pair], profit_col, timeframe)
|
||||||
|
|
||||||
|
fig = add_profit(fig, 3, df_comb, profit_col, f"Profit {pair}")
|
||||||
|
|
||||||
|
return fig
|
||||||
|
|
||||||
|
|
||||||
|
def generate_plot_filename(pair, ticker_interval) -> str:
|
||||||
|
"""
|
||||||
|
Generate filenames per pair/ticker_interval to be used for storing plots
|
||||||
|
"""
|
||||||
|
pair_name = pair.replace("/", "_")
|
||||||
|
file_name = 'freqtrade-plot-' + pair_name + '-' + ticker_interval + '.html'
|
||||||
|
|
||||||
|
logger.info('Generate plot file for %s', pair)
|
||||||
|
|
||||||
|
return file_name
|
||||||
|
|
||||||
|
|
||||||
|
def store_plot_file(fig, filename: str, directory: Path, auto_open: bool = False) -> None:
|
||||||
|
"""
|
||||||
|
Generate a plot html file from pre populated fig plotly object
|
||||||
|
:param fig: Plotly Figure to plot
|
||||||
|
:param pair: Pair to plot (used as filename and Plot title)
|
||||||
|
:param ticker_interval: Used as part of the filename
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
directory.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
_filename = directory.joinpath(filename)
|
||||||
|
plot(fig, filename=str(_filename),
|
||||||
|
auto_open=auto_open)
|
||||||
|
logger.info(f"Stored plot as {_filename}")
|
||||||
|
|
||||||
|
|
||||||
|
def load_and_plot_trades(config: Dict[str, Any]):
|
||||||
|
"""
|
||||||
|
From configuration provided
|
||||||
|
- Initializes plot-script
|
||||||
|
- Get tickers data
|
||||||
|
- Generate Dafaframes populated with indicators and signals based on configured strategy
|
||||||
|
- Load trades excecuted during the selected period
|
||||||
|
- Generate Plotly plot objects
|
||||||
|
- Generate plot files
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
strategy = StrategyResolver(config).strategy
|
||||||
|
|
||||||
|
plot_elements = init_plotscript(config)
|
||||||
|
trades = plot_elements['trades']
|
||||||
|
pair_counter = 0
|
||||||
|
for pair, data in plot_elements["tickers"].items():
|
||||||
|
pair_counter += 1
|
||||||
|
logger.info("analyse pair %s", pair)
|
||||||
|
tickers = {}
|
||||||
|
tickers[pair] = data
|
||||||
|
|
||||||
|
dataframe = strategy.analyze_ticker(tickers[pair], {'pair': pair})
|
||||||
|
trades_pair = trades.loc[trades['pair'] == pair]
|
||||||
|
trades_pair = extract_trades_of_period(dataframe, trades_pair)
|
||||||
|
|
||||||
|
fig = generate_candlestick_graph(
|
||||||
|
pair=pair,
|
||||||
|
data=dataframe,
|
||||||
|
trades=trades_pair,
|
||||||
|
indicators1=config["indicators1"],
|
||||||
|
indicators2=config["indicators2"],
|
||||||
|
)
|
||||||
|
|
||||||
|
store_plot_file(fig, filename=generate_plot_filename(pair, config['ticker_interval']),
|
||||||
|
directory=config['user_data_dir'] / "plot")
|
||||||
|
|
||||||
|
logger.info('End of plotting process. %s plots generated', pair_counter)
|
||||||
|
|
||||||
|
|
||||||
|
def plot_profit(config: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Plots the total profit for all pairs.
|
||||||
|
Note, the profit calculation isn't realistic.
|
||||||
|
But should be somewhat proportional, and therefor useful
|
||||||
|
in helping out to find a good algorithm.
|
||||||
|
"""
|
||||||
|
plot_elements = init_plotscript(config)
|
||||||
|
trades = load_trades(config['trade_source'],
|
||||||
|
db_url=str(config.get('db_url')),
|
||||||
|
exportfilename=str(config.get('exportfilename')),
|
||||||
|
)
|
||||||
|
# Filter trades to relevant pairs
|
||||||
|
trades = trades[trades['pair'].isin(plot_elements["pairs"])]
|
||||||
|
# Create an average close price of all the pairs that were involved.
|
||||||
|
# this could be useful to gauge the overall market trend
|
||||||
|
fig = generate_profit_graph(plot_elements["pairs"], plot_elements["tickers"],
|
||||||
|
trades, config.get('ticker_interval', '5m'))
|
||||||
|
store_plot_file(fig, filename='freqtrade-profit-plot.html',
|
||||||
|
directory=config['user_data_dir'] / "plot", auto_open=True)
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
from freqtrade.resolvers.iresolver import IResolver # noqa: F401
|
from freqtrade.resolvers.iresolver import IResolver # noqa: F401
|
||||||
from freqtrade.resolvers.hyperopt_resolver import HyperOptResolver # noqa: F401
|
from freqtrade.resolvers.exchange_resolver import ExchangeResolver # noqa: F401
|
||||||
|
# Don't import HyperoptResolver to avoid loading the whole Optimize tree
|
||||||
|
# from freqtrade.resolvers.hyperopt_resolver import HyperOptResolver # noqa: F401
|
||||||
from freqtrade.resolvers.pairlist_resolver import PairListResolver # noqa: F401
|
from freqtrade.resolvers.pairlist_resolver import PairListResolver # noqa: F401
|
||||||
from freqtrade.resolvers.strategy_resolver import StrategyResolver # noqa: F401
|
from freqtrade.resolvers.strategy_resolver import StrategyResolver # noqa: F401
|
||||||
|
|||||||
60
freqtrade/resolvers/exchange_resolver.py
Normal file
60
freqtrade/resolvers/exchange_resolver.py
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
"""
|
||||||
|
This module loads custom exchanges
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from freqtrade.exchange import Exchange, MAP_EXCHANGE_CHILDCLASS
|
||||||
|
import freqtrade.exchange as exchanges
|
||||||
|
from freqtrade.resolvers import IResolver
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class ExchangeResolver(IResolver):
|
||||||
|
"""
|
||||||
|
This class contains all the logic to load a custom exchange class
|
||||||
|
"""
|
||||||
|
|
||||||
|
__slots__ = ['exchange']
|
||||||
|
|
||||||
|
def __init__(self, exchange_name: str, config: dict, validate: bool = True) -> None:
|
||||||
|
"""
|
||||||
|
Load the custom class from config parameter
|
||||||
|
:param config: configuration dictionary
|
||||||
|
"""
|
||||||
|
# Map exchange name to avoid duplicate classes for identical exchanges
|
||||||
|
exchange_name = MAP_EXCHANGE_CHILDCLASS.get(exchange_name, exchange_name)
|
||||||
|
exchange_name = exchange_name.title()
|
||||||
|
try:
|
||||||
|
self.exchange = self._load_exchange(exchange_name, kwargs={'config': config,
|
||||||
|
'validate': validate})
|
||||||
|
except ImportError:
|
||||||
|
logger.info(
|
||||||
|
f"No {exchange_name} specific subclass found. Using the generic class instead.")
|
||||||
|
if not hasattr(self, "exchange"):
|
||||||
|
self.exchange = Exchange(config, validate=validate)
|
||||||
|
|
||||||
|
def _load_exchange(
|
||||||
|
self, exchange_name: str, kwargs: dict) -> Exchange:
|
||||||
|
"""
|
||||||
|
Loads the specified exchange.
|
||||||
|
Only checks for exchanges exported in freqtrade.exchanges
|
||||||
|
:param exchange_name: name of the module to import
|
||||||
|
:return: Exchange instance or None
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
ex_class = getattr(exchanges, exchange_name)
|
||||||
|
|
||||||
|
exchange = ex_class(**kwargs)
|
||||||
|
if exchange:
|
||||||
|
logger.info(f"Using resolved exchange '{exchange_name}'...")
|
||||||
|
return exchange
|
||||||
|
except AttributeError:
|
||||||
|
# Pass and raise ImportError instead
|
||||||
|
pass
|
||||||
|
|
||||||
|
raise ImportError(
|
||||||
|
f"Impossible to load Exchange '{exchange_name}'. This class does not exist "
|
||||||
|
"or contains Python code errors."
|
||||||
|
)
|
||||||
@@ -7,8 +7,10 @@ import logging
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional, Dict
|
from typing import Optional, Dict
|
||||||
|
|
||||||
from freqtrade.constants import DEFAULT_HYPEROPT
|
from freqtrade import OperationalException
|
||||||
|
from freqtrade.constants import DEFAULT_HYPEROPT, DEFAULT_HYPEROPT_LOSS
|
||||||
from freqtrade.optimize.hyperopt_interface import IHyperOpt
|
from freqtrade.optimize.hyperopt_interface import IHyperOpt
|
||||||
|
from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss
|
||||||
from freqtrade.resolvers import IResolver
|
from freqtrade.resolvers import IResolver
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -21,7 +23,56 @@ class HyperOptResolver(IResolver):
|
|||||||
|
|
||||||
__slots__ = ['hyperopt']
|
__slots__ = ['hyperopt']
|
||||||
|
|
||||||
def __init__(self, config: Optional[Dict] = None) -> None:
|
def __init__(self, config: Dict) -> None:
|
||||||
|
"""
|
||||||
|
Load the custom class from config parameter
|
||||||
|
:param config: configuration dictionary
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Verify the hyperopt is in the configuration, otherwise fallback to the default hyperopt
|
||||||
|
hyperopt_name = config.get('hyperopt') or DEFAULT_HYPEROPT
|
||||||
|
self.hyperopt = self._load_hyperopt(hyperopt_name, config,
|
||||||
|
extra_dir=config.get('hyperopt_path'))
|
||||||
|
|
||||||
|
if not hasattr(self.hyperopt, 'populate_buy_trend'):
|
||||||
|
logger.warning("Hyperopt class does not provide populate_buy_trend() method. "
|
||||||
|
"Using populate_buy_trend from the strategy.")
|
||||||
|
if not hasattr(self.hyperopt, 'populate_sell_trend'):
|
||||||
|
logger.warning("Hyperopt class does not provide populate_sell_trend() method. "
|
||||||
|
"Using populate_sell_trend from the strategy.")
|
||||||
|
|
||||||
|
def _load_hyperopt(
|
||||||
|
self, hyperopt_name: str, config: Dict, extra_dir: Optional[str] = None) -> IHyperOpt:
|
||||||
|
"""
|
||||||
|
Search and loads the specified hyperopt.
|
||||||
|
:param hyperopt_name: name of the module to import
|
||||||
|
:param config: configuration dictionary
|
||||||
|
:param extra_dir: additional directory to search for the given hyperopt
|
||||||
|
:return: HyperOpt instance or None
|
||||||
|
"""
|
||||||
|
current_path = Path(__file__).parent.parent.joinpath('optimize').resolve()
|
||||||
|
|
||||||
|
abs_paths = self.build_search_paths(config, current_path=current_path,
|
||||||
|
user_subdir='hyperopts', extra_dir=extra_dir)
|
||||||
|
|
||||||
|
hyperopt = self._load_object(paths=abs_paths, object_type=IHyperOpt,
|
||||||
|
object_name=hyperopt_name, kwargs={'config': config})
|
||||||
|
if hyperopt:
|
||||||
|
return hyperopt
|
||||||
|
raise OperationalException(
|
||||||
|
f"Impossible to load Hyperopt '{hyperopt_name}'. This class does not exist "
|
||||||
|
"or contains Python code errors."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class HyperOptLossResolver(IResolver):
|
||||||
|
"""
|
||||||
|
This class contains all the logic to load custom hyperopt loss class
|
||||||
|
"""
|
||||||
|
|
||||||
|
__slots__ = ['hyperoptloss']
|
||||||
|
|
||||||
|
def __init__(self, config: Dict = None) -> None:
|
||||||
"""
|
"""
|
||||||
Load the custom class from config parameter
|
Load the custom class from config parameter
|
||||||
:param config: configuration dictionary or None
|
:param config: configuration dictionary or None
|
||||||
@@ -29,46 +80,38 @@ class HyperOptResolver(IResolver):
|
|||||||
config = config or {}
|
config = config or {}
|
||||||
|
|
||||||
# Verify the hyperopt is in the configuration, otherwise fallback to the default hyperopt
|
# Verify the hyperopt is in the configuration, otherwise fallback to the default hyperopt
|
||||||
hyperopt_name = config.get('hyperopt') or DEFAULT_HYPEROPT
|
hyperopt_name = config.get('hyperopt_loss') or DEFAULT_HYPEROPT_LOSS
|
||||||
self.hyperopt = self._load_hyperopt(hyperopt_name, extra_dir=config.get('hyperopt_path'))
|
self.hyperoptloss = self._load_hyperoptloss(
|
||||||
|
hyperopt_name, config, extra_dir=config.get('hyperopt_path'))
|
||||||
|
|
||||||
if not hasattr(self.hyperopt, 'populate_buy_trend'):
|
# Assign ticker_interval to be used in hyperopt
|
||||||
logger.warning("Custom Hyperopt does not provide populate_buy_trend. "
|
self.hyperoptloss.__class__.ticker_interval = str(config['ticker_interval'])
|
||||||
"Using populate_buy_trend from DefaultStrategy.")
|
|
||||||
if not hasattr(self.hyperopt, 'populate_sell_trend'):
|
|
||||||
logger.warning("Custom Hyperopt does not provide populate_sell_trend. "
|
|
||||||
"Using populate_sell_trend from DefaultStrategy.")
|
|
||||||
|
|
||||||
def _load_hyperopt(
|
if not hasattr(self.hyperoptloss, 'hyperopt_loss_function'):
|
||||||
self, hyperopt_name: str, extra_dir: Optional[str] = None) -> IHyperOpt:
|
raise OperationalException(
|
||||||
|
f"Found hyperopt {hyperopt_name} does not implement `hyperopt_loss_function`.")
|
||||||
|
|
||||||
|
def _load_hyperoptloss(
|
||||||
|
self, hyper_loss_name: str, config: Dict,
|
||||||
|
extra_dir: Optional[str] = None) -> IHyperOptLoss:
|
||||||
"""
|
"""
|
||||||
Search and loads the specified hyperopt.
|
Search and loads the specified hyperopt loss class.
|
||||||
:param hyperopt_name: name of the module to import
|
:param hyper_loss_name: name of the module to import
|
||||||
|
:param config: configuration dictionary
|
||||||
:param extra_dir: additional directory to search for the given hyperopt
|
:param extra_dir: additional directory to search for the given hyperopt
|
||||||
:return: HyperOpt instance or None
|
:return: HyperOptLoss instance or None
|
||||||
"""
|
"""
|
||||||
current_path = Path(__file__).parent.parent.joinpath('optimize').resolve()
|
current_path = Path(__file__).parent.parent.joinpath('optimize').resolve()
|
||||||
|
|
||||||
abs_paths = [
|
abs_paths = self.build_search_paths(config, current_path=current_path,
|
||||||
current_path.parent.parent.joinpath('user_data/hyperopts'),
|
user_subdir='hyperopts', extra_dir=extra_dir)
|
||||||
current_path,
|
|
||||||
]
|
|
||||||
|
|
||||||
if extra_dir:
|
hyperoptloss = self._load_object(paths=abs_paths, object_type=IHyperOptLoss,
|
||||||
# Add extra hyperopt directory on top of search paths
|
object_name=hyper_loss_name)
|
||||||
abs_paths.insert(0, Path(extra_dir))
|
if hyperoptloss:
|
||||||
|
return hyperoptloss
|
||||||
|
|
||||||
for _path in abs_paths:
|
raise OperationalException(
|
||||||
try:
|
f"Impossible to load HyperoptLoss '{hyper_loss_name}'. This class does not exist "
|
||||||
hyperopt = self._search_object(directory=_path, object_type=IHyperOpt,
|
"or contains Python code errors."
|
||||||
object_name=hyperopt_name)
|
|
||||||
if hyperopt:
|
|
||||||
logger.info('Using resolved hyperopt %s from \'%s\'', hyperopt_name, _path)
|
|
||||||
return hyperopt
|
|
||||||
except FileNotFoundError:
|
|
||||||
logger.warning('Path "%s" does not exist', _path.relative_to(Path.cwd()))
|
|
||||||
|
|
||||||
raise ImportError(
|
|
||||||
"Impossible to load Hyperopt '{}'. This class does not exist"
|
|
||||||
" or contains Python code errors".format(hyperopt_name)
|
|
||||||
)
|
)
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user