mirror of
https://github.com/freqtrade/freqtrade.git
synced 2025-11-29 08:33:07 +00:00
Compare commits
1511 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c53dcb0af | ||
|
|
ded2d3c293 | ||
|
|
29745bb4ec | ||
|
|
2f76eaf358 | ||
|
|
0e4ef33d6a | ||
|
|
18c73ceb90 | ||
|
|
8431b54b21 | ||
|
|
5fc357ee10 | ||
|
|
a9f7e9fb7a | ||
|
|
aa335d8485 | ||
|
|
82f7798f48 | ||
|
|
ce80bbe24c | ||
|
|
da195d0272 | ||
|
|
4eae02b723 | ||
|
|
081b21fe82 | ||
|
|
ed053d240e | ||
|
|
0ca3157a8b | ||
|
|
4934456751 | ||
|
|
0f4dcaa403 | ||
|
|
4b560880fd | ||
|
|
1495c93083 | ||
|
|
21c6855705 | ||
|
|
a7d6dc9d3a | ||
|
|
ed7207d4c8 | ||
|
|
bb9235c715 | ||
|
|
9e85376a2d | ||
|
|
a379c19e9a | ||
|
|
2bd4008cb2 | ||
|
|
d21ae4edd3 | ||
|
|
1da008b3af | ||
|
|
703458f365 | ||
|
|
4b0a4c936a | ||
|
|
216094a761 | ||
|
|
4efd8b96e5 | ||
|
|
b61f43835d | ||
|
|
017a94adc1 | ||
|
|
b20bea8492 | ||
|
|
54694dd3a4 | ||
|
|
8dd9b5c6fb | ||
|
|
16a50fbe4e | ||
|
|
32897ce769 | ||
|
|
51f074ba4b | ||
|
|
0ba804d051 | ||
|
|
611a594a46 | ||
|
|
8a7fe3f1d6 | ||
|
|
054484ad73 | ||
|
|
ac3e061508 | ||
|
|
ddf86d6342 | ||
|
|
ba29a2ffe4 | ||
|
|
b33e47a49e | ||
|
|
298e8b2332 | ||
|
|
78f8ba1226 | ||
|
|
17e03559dc | ||
|
|
2825206d37 | ||
|
|
cd20d5b5c5 | ||
|
|
ebf6dad3f6 | ||
|
|
683406b57d | ||
|
|
406dfe21f8 | ||
|
|
346d381ab8 | ||
|
|
d7980fa0b6 | ||
|
|
fc7b9846ae | ||
|
|
15e695a9bd | ||
|
|
110fbd3f06 | ||
|
|
f0428be91e | ||
|
|
0b03c6c786 | ||
|
|
150a497cb4 | ||
|
|
3d666ea68e | ||
|
|
ee733210ca | ||
|
|
86342efa7a | ||
|
|
05967442c3 | ||
|
|
d6b587678e | ||
|
|
668d42447f | ||
|
|
32c9b5f415 | ||
|
|
f42ce8fc2a | ||
|
|
6b142d716f | ||
|
|
26a7af85ea | ||
|
|
69b0767165 | ||
|
|
f862b4d0f0 | ||
|
|
a88bfa8ded | ||
|
|
fffd47e3d8 | ||
|
|
7a3c3c4ddf | ||
|
|
eafccb445c | ||
|
|
b040cbffdd | ||
|
|
153434561d | ||
|
|
36b2ed172c | ||
|
|
e0e0bad7c1 | ||
|
|
8f9b5095b5 | ||
|
|
5b996920f2 | ||
|
|
bcec070ad7 | ||
|
|
c3d7411668 | ||
|
|
997c426228 | ||
|
|
7a52334c9f | ||
|
|
111f018c85 | ||
|
|
64da877161 | ||
|
|
f0e6a9e0e3 | ||
|
|
a373e48939 | ||
|
|
f2cd4fdafe | ||
|
|
9991c892ac | ||
|
|
8e7512161a | ||
|
|
5e09913e3d | ||
|
|
cceb00c406 | ||
|
|
585b8332ad | ||
|
|
066f324060 | ||
|
|
8e1e20bf0d | ||
|
|
0ac592ad40 | ||
|
|
17269c88be | ||
|
|
8204107315 | ||
|
|
9e7d367b5c | ||
|
|
12b9257c6d | ||
|
|
37f698d9c1 | ||
|
|
e7c17df844 | ||
|
|
28ec8b5bc2 | ||
|
|
200b8e48bf | ||
|
|
2a8ad9e35b | ||
|
|
be8ad0f022 | ||
|
|
a77efc3949 | ||
|
|
418ca00305 | ||
|
|
03f02294d1 | ||
|
|
0a7a1290e3 | ||
|
|
28f73ecb3d | ||
|
|
6ab7f93ce7 | ||
|
|
d1511a1085 | ||
|
|
0775ac081a | ||
|
|
646a9d12b2 | ||
|
|
e7be742c58 | ||
|
|
8d002a8f28 | ||
|
|
af3eea3805 | ||
|
|
4dc0631a4b | ||
|
|
a3415e52c0 | ||
|
|
1b337fe5e1 | ||
|
|
50350a09cd | ||
|
|
1bf8d8cff3 | ||
|
|
62d50f512d | ||
|
|
8c64be3cfd | ||
|
|
cc0a733f1f | ||
|
|
1b645d64c8 | ||
|
|
a374df7622 | ||
|
|
cbf710a4f8 | ||
|
|
f05818a86e | ||
|
|
cab748588c | ||
|
|
63ad95a474 | ||
|
|
e9da4d8505 | ||
|
|
26a2292f6d | ||
|
|
5fb14e769b | ||
|
|
c7c7a1c2aa | ||
|
|
1242263d25 | ||
|
|
31c598f88a | ||
|
|
6cb4830534 | ||
|
|
067267f4cf | ||
|
|
99db53417c | ||
|
|
737c07c5b6 | ||
|
|
097cdcb57a | ||
|
|
175591e524 | ||
|
|
e7ddd81251 | ||
|
|
a183162d8b | ||
|
|
a6bb7595e8 | ||
|
|
210d468a9b | ||
|
|
5f8fcebb88 | ||
|
|
f23f659ac5 | ||
|
|
99eeb2e605 | ||
|
|
f26171082c | ||
|
|
2acd2542ac | ||
|
|
f26c40082d | ||
|
|
b3dbb81838 | ||
|
|
5e5ef21f61 | ||
|
|
be4a4180ae | ||
|
|
f7322358cf | ||
|
|
671b98ecad | ||
|
|
ed04f7f39d | ||
|
|
cbb187e9b9 | ||
|
|
03cdfe8cae | ||
|
|
37f8139432 | ||
|
|
79891671e9 | ||
|
|
65489c894d | ||
|
|
b36a1d3260 | ||
|
|
8a1d02e185 | ||
|
|
8c2ff2f46e | ||
|
|
e492d47621 | ||
|
|
98baae9456 | ||
|
|
e3cf6188a1 | ||
|
|
8cf8ab089e | ||
|
|
ed1d450099 | ||
|
|
41494f28da | ||
|
|
19b1a6c638 | ||
|
|
471bd4d889 | ||
|
|
084efc98d7 | ||
|
|
1d2ef5c2ce | ||
|
|
fd45ebd0e9 | ||
|
|
258d4bd6ae | ||
|
|
b8aa727edf | ||
|
|
eac01960a7 | ||
|
|
a5bd4e329a | ||
|
|
5ce665f279 | ||
|
|
9aac080414 | ||
|
|
8b639b5026 | ||
|
|
7f119a28e7 | ||
|
|
5f88c4aad9 | ||
|
|
dfe3d78767 | ||
|
|
633996216a | ||
|
|
09b302abf7 | ||
|
|
c92f233c15 | ||
|
|
751157b4ea | ||
|
|
5f62a9e4d8 | ||
|
|
a8855bf795 | ||
|
|
c22b00b303 | ||
|
|
67c5115b41 | ||
|
|
ab4b1cc8fe | ||
|
|
716785c65f | ||
|
|
baa7fd6c79 | ||
|
|
9045f796e0 | ||
|
|
988c1744af | ||
|
|
cd6d276119 | ||
|
|
d085a2bd3e | ||
|
|
dddccf8f1a | ||
|
|
8b3fb3d6d5 | ||
|
|
80b450d4e6 | ||
|
|
0bc71403ff | ||
|
|
cb6b3e17a9 | ||
|
|
e7157faddd | ||
|
|
a33d408780 | ||
|
|
42474b7144 | ||
|
|
933564591d | ||
|
|
599e18b920 | ||
|
|
547d65b065 | ||
|
|
e4e8a611be | ||
|
|
2b190e5638 | ||
|
|
acab56793f | ||
|
|
2c976bdd24 | ||
|
|
3aee8d2b2a | ||
|
|
841c379797 | ||
|
|
b6a12044ba | ||
|
|
8e087cb639 | ||
|
|
bcb5913291 | ||
|
|
be53c0885d | ||
|
|
91047830fd | ||
|
|
6e0655b3b7 | ||
|
|
edc0d7f2c7 | ||
|
|
1d18e0a11a | ||
|
|
b167fb071a | ||
|
|
3b9899dfd4 | ||
|
|
f94d46316e | ||
|
|
569a547b3f | ||
|
|
6c306c0013 | ||
|
|
9b050523e9 | ||
|
|
f9a92c2879 | ||
|
|
ab194c7d75 | ||
|
|
904a9c5dc7 | ||
|
|
38243c52fd | ||
|
|
c8c48156dd | ||
|
|
f4d18034d9 | ||
|
|
17c11b2afa | ||
|
|
68904296e7 | ||
|
|
d4499338e0 | ||
|
|
6174a5dd55 | ||
|
|
e26bbc7de8 | ||
|
|
62c1ff776e | ||
|
|
baea06eac7 | ||
|
|
6ac73f7cde | ||
|
|
66619204ba | ||
|
|
1d7fb2ffac | ||
|
|
c42c5a1f85 | ||
|
|
5b62ad876e | ||
|
|
ec460ab9c9 | ||
|
|
2eb6513251 | ||
|
|
c449e39280 | ||
|
|
1c57a4ac35 | ||
|
|
334ac8b10c | ||
|
|
d801dec6aa | ||
|
|
08aedc18e1 | ||
|
|
e4bdb92521 | ||
|
|
11f7ab61b9 | ||
|
|
df9bfb6c2e | ||
|
|
ab9506df48 | ||
|
|
136ef077b2 | ||
|
|
e8a8f416f3 | ||
|
|
8c76f45030 | ||
|
|
96f550c6aa | ||
|
|
37ef5c38f0 | ||
|
|
66a273b31b | ||
|
|
52e24c3a25 | ||
|
|
7a2d917c66 | ||
|
|
025350ebff | ||
|
|
411e035005 | ||
|
|
800997437a | ||
|
|
75d5ff69ef | ||
|
|
a241c2af0d | ||
|
|
d1729a624d | ||
|
|
e51a720193 | ||
|
|
ff1d36434d | ||
|
|
904ae5af91 | ||
|
|
42e8e1c16a | ||
|
|
9fb493d2f4 | ||
|
|
031157f215 | ||
|
|
c65d217d1e | ||
|
|
0a13f7e1c7 | ||
|
|
173375de7c | ||
|
|
27d81bb68c | ||
|
|
044105e8e0 | ||
|
|
48f8a62335 | ||
|
|
71f99ba79c | ||
|
|
95492958f9 | ||
|
|
661c8251c5 | ||
|
|
83067c1edc | ||
|
|
c5ed004c9e | ||
|
|
04b51a982e | ||
|
|
e810597eec | ||
|
|
692d6afbd9 | ||
|
|
59fa02e11a | ||
|
|
6ef6a24841 | ||
|
|
eba55c2783 | ||
|
|
085aa3084e | ||
|
|
de2d04f06b | ||
|
|
12654cb810 | ||
|
|
4b15873ee1 | ||
|
|
748fe94603 | ||
|
|
86a5dfa62e | ||
|
|
0b4800835c | ||
|
|
5caeca7509 | ||
|
|
7ff61f12e9 | ||
|
|
ae35649366 | ||
|
|
a01b34a004 | ||
|
|
02b9da8aba | ||
|
|
ed0c7a6aaf | ||
|
|
25cb935eee | ||
|
|
c74d766275 | ||
|
|
37985310d5 | ||
|
|
c3b4a4dde1 | ||
|
|
d7262c0b4e | ||
|
|
870966dcd0 | ||
|
|
85beb3b6a9 | ||
|
|
bf69b055eb | ||
|
|
31c7189b8b | ||
|
|
eaf3fd80c5 | ||
|
|
1059586226 | ||
|
|
b610e8c7e6 | ||
|
|
e632720c02 | ||
|
|
1f042f5e32 | ||
|
|
54b63e89f8 | ||
|
|
3f65c31883 | ||
|
|
31ab32f0b9 | ||
|
|
bc5c91f681 | ||
|
|
076ef0407b | ||
|
|
b0150d548a | ||
|
|
60acbc97ab | ||
|
|
dd47bd04cd | ||
|
|
da57396d07 | ||
|
|
d3a3765819 | ||
|
|
f90676cfc5 | ||
|
|
ad2289c34c | ||
|
|
ca77dbe8da | ||
|
|
6c6efd7214 | ||
|
|
7f099d41fa | ||
|
|
60109aaa1f | ||
|
|
ef057c16cb | ||
|
|
39e728a7c2 | ||
|
|
28f0c00281 | ||
|
|
bc78316aa5 | ||
|
|
b8a6c55b10 | ||
|
|
6df1dd1ef2 | ||
|
|
c8638ce82f | ||
|
|
1a61d89bcc | ||
|
|
eb0b0350e0 | ||
|
|
4ec7fcd836 | ||
|
|
f6a66cd3de | ||
|
|
871019c8b9 | ||
|
|
581907305a | ||
|
|
54b0fbca59 | ||
|
|
1e44f93c31 | ||
|
|
3eca80217c | ||
|
|
6f01d7f8ea | ||
|
|
500d16620b | ||
|
|
6550e1fa99 | ||
|
|
80ad37ad93 | ||
|
|
3287cdd47a | ||
|
|
12e86ee4bd | ||
|
|
97d0f93d3c | ||
|
|
861f10dca6 | ||
|
|
2a1385f94b | ||
|
|
e9af6b393f | ||
|
|
2124661cee | ||
|
|
1593847203 | ||
|
|
e8a08011be | ||
|
|
691cec7956 | ||
|
|
241d947564 | ||
|
|
880834b902 | ||
|
|
f435384bf0 | ||
|
|
3149c12a14 | ||
|
|
6a9a2e7f88 | ||
|
|
5b87393a95 | ||
|
|
5a27b10579 | ||
|
|
a80e49bd81 | ||
|
|
ffed13b979 | ||
|
|
9f0f1096e1 | ||
|
|
9a42afe0be | ||
|
|
b6616d7a13 | ||
|
|
7be378aaa9 | ||
|
|
734a9d5d87 | ||
|
|
ce6b869f84 | ||
|
|
dc5f1b2878 | ||
|
|
a041b8bf72 | ||
|
|
4fa12ffda0 | ||
|
|
5dcf28cafb | ||
|
|
365a408df5 | ||
|
|
7204227022 | ||
|
|
dab4ab78fc | ||
|
|
a74b941b72 | ||
|
|
89bba6f776 | ||
|
|
82f86569ee | ||
|
|
9e988783de | ||
|
|
bba8e61409 | ||
|
|
dee9b84322 | ||
|
|
ad98d61939 | ||
|
|
14758dbe10 | ||
|
|
d89a7d5235 | ||
|
|
640423c362 | ||
|
|
fd9c02603c | ||
|
|
44289e4c58 | ||
|
|
6928c685a8 | ||
|
|
dd408aa5d6 | ||
|
|
dac88c6aed | ||
|
|
78fe5a46c1 | ||
|
|
7a96d3c9ae | ||
|
|
b7b1e66c6e | ||
|
|
5ed7771148 | ||
|
|
c2076d86a4 | ||
|
|
b37c5e4878 | ||
|
|
26a5800a7f | ||
|
|
01efebc42f | ||
|
|
ab117527c9 | ||
|
|
f20f5cebbe | ||
|
|
0c3a8ddfb9 | ||
|
|
669a6cf119 | ||
|
|
6fe7b13e37 | ||
|
|
9c180e587b | ||
|
|
a368646745 | ||
|
|
de2cc58b0c | ||
|
|
d803d86f4d | ||
|
|
5254059fe4 | ||
|
|
d706571e6f | ||
|
|
907baea8b2 | ||
|
|
062536438e | ||
|
|
4ff035537b | ||
|
|
466a3b87fc | ||
|
|
b947f3c2a5 | ||
|
|
069da224bc | ||
|
|
e82460bde6 | ||
|
|
61c037f2cf | ||
|
|
f98290ba6e | ||
|
|
73343b3387 | ||
|
|
3a6020dcd7 | ||
|
|
596a269dfd | ||
|
|
7329fce87c | ||
|
|
4059116787 | ||
|
|
1561322af2 | ||
|
|
44d0a6f2b8 | ||
|
|
60b99469b9 | ||
|
|
46b975a491 | ||
|
|
70ad909b16 | ||
|
|
2af3ce3ecc | ||
|
|
132a4da7cf | ||
|
|
73f5bff9c5 | ||
|
|
223f0cd4d3 | ||
|
|
c4cb098d14 | ||
|
|
2bc74882e9 | ||
|
|
2ba388074e | ||
|
|
33164ac78e | ||
|
|
86624411c6 | ||
|
|
5cdae17d19 | ||
|
|
bd4a23beeb | ||
|
|
5c2682e2c9 | ||
|
|
6382a4cd04 | ||
|
|
704121c197 | ||
|
|
9c7696a8ce | ||
|
|
9e7e051eb4 | ||
|
|
616fe08bce | ||
|
|
141c454187 | ||
|
|
17fce00a5e | ||
|
|
0b8d04d75e | ||
|
|
e5487441ba | ||
|
|
48d83715a5 | ||
|
|
8b4fea4b71 | ||
|
|
4c1f0c3c59 | ||
|
|
13ae339a2e | ||
|
|
73a03565e5 | ||
|
|
bf20f3b7d8 | ||
|
|
20dabd9c41 | ||
|
|
32df73c056 | ||
|
|
ef1885c38b | ||
|
|
f5351e60e7 | ||
|
|
bfec9d974b | ||
|
|
3a7553eef6 | ||
|
|
d0521d33ce | ||
|
|
9155598ca4 | ||
|
|
ea6b94fd0c | ||
|
|
2a95d6855b | ||
|
|
3929ad4e1f | ||
|
|
2f1d9696cd | ||
|
|
2e896462c1 | ||
|
|
e63377980e | ||
|
|
41f97a73c9 | ||
|
|
0773a65333 | ||
|
|
8201f70a80 | ||
|
|
45b83cc544 | ||
|
|
b3e028e853 | ||
|
|
74b2f11d4f | ||
|
|
514e073c57 | ||
|
|
59e881c59d | ||
|
|
2e1e080022 | ||
|
|
13255b370c | ||
|
|
e1edf36307 | ||
|
|
470efd6f40 | ||
|
|
6640f4a1b2 | ||
|
|
e408274fb3 | ||
|
|
4ce278a06e | ||
|
|
a135eaa993 | ||
|
|
87ff7be550 | ||
|
|
7441300270 | ||
|
|
b4f4fae0ca | ||
|
|
336808ec54 | ||
|
|
b26faa13bd | ||
|
|
562e4e63de | ||
|
|
ad5f7e1581 | ||
|
|
3cf95f9f6c | ||
|
|
f0710cafd0 | ||
|
|
73fa5bae96 | ||
|
|
a43d436f98 | ||
|
|
ff5ba64385 | ||
|
|
7e38a07490 | ||
|
|
8872158a6a | ||
|
|
db3e789294 | ||
|
|
4813ff338b | ||
|
|
fbd7dc1d6c | ||
|
|
f07b26f245 | ||
|
|
3acc10dd48 | ||
|
|
e5f06c201f | ||
|
|
bf20cde83d | ||
|
|
364859394b | ||
|
|
657f1b6c45 | ||
|
|
e350bcc2ef | ||
|
|
c2566f2436 | ||
|
|
cac314d4b3 | ||
|
|
b116cc75c4 | ||
|
|
bedbd964fc | ||
|
|
1c503f39b2 | ||
|
|
ca4d0067e4 | ||
|
|
8a0d90136c | ||
|
|
5b680f2ece | ||
|
|
1bc63288a3 | ||
|
|
45b2d24b79 | ||
|
|
10ca249293 | ||
|
|
d6b6ded8bd | ||
|
|
2d34c0f52d | ||
|
|
f3cfe147b5 | ||
|
|
a52366c45d | ||
|
|
88c91a8a54 | ||
|
|
14755779de | ||
|
|
20dd3f2d67 | ||
|
|
8a31b4c646 | ||
|
|
78cd75dfef | ||
|
|
b805e4e150 | ||
|
|
df43b1f533 | ||
|
|
6e938b59c8 | ||
|
|
4f17511fdc | ||
|
|
d8630ef847 | ||
|
|
47fabca1d9 | ||
|
|
c48876b196 | ||
|
|
16e10d99b9 | ||
|
|
0adcee9233 | ||
|
|
f41c659cb2 | ||
|
|
4c977b2e01 | ||
|
|
b152585d9b | ||
|
|
fd22c87295 | ||
|
|
93b213ae0b | ||
|
|
30eb23e1aa | ||
|
|
4ec83a2c24 | ||
|
|
9e23ca14d1 | ||
|
|
ebf5738a6e | ||
|
|
c649f9844e | ||
|
|
3208f30c30 | ||
|
|
5e731ec278 | ||
|
|
e55b2a1a1c | ||
|
|
ed8d805797 | ||
|
|
0ebf2e44be | ||
|
|
00a95945e1 | ||
|
|
9d739f98ac | ||
|
|
2588990f4b | ||
|
|
271846dfb6 | ||
|
|
c181fac6c7 | ||
|
|
0ac46eddca | ||
|
|
c735d35265 | ||
|
|
e957894852 | ||
|
|
369335b80c | ||
|
|
2ebddcf45c | ||
|
|
8564affdf0 | ||
|
|
a39d51d7d0 | ||
|
|
750dc8bf56 | ||
|
|
033742b708 | ||
|
|
84ba431d10 | ||
|
|
b6e26c82ea | ||
|
|
e8eb968a6f | ||
|
|
66605a1909 | ||
|
|
1e61263a28 | ||
|
|
bd08874f1f | ||
|
|
ff6a3465a7 | ||
|
|
5b58141f6b | ||
|
|
bf4e9a5dbb | ||
|
|
837d4d82b4 | ||
|
|
a8ffd29e18 | ||
|
|
92fda0f76c | ||
|
|
df62dd65d3 | ||
|
|
d72d388726 | ||
|
|
fda71085e0 | ||
|
|
1a765f1a17 | ||
|
|
06ab51b53d | ||
|
|
7de1631045 | ||
|
|
4c8411e835 | ||
|
|
f348956e4c | ||
|
|
a4dfd77d23 | ||
|
|
89e0c76a3f | ||
|
|
abc504412a | ||
|
|
36d5bb6f99 | ||
|
|
ad89d19955 | ||
|
|
e6e35c2584 | ||
|
|
ace70510f3 | ||
|
|
cb4d6efb29 | ||
|
|
f1cddfdc62 | ||
|
|
6fb96183c0 | ||
|
|
a5c83b66df | ||
|
|
a320d4ccba | ||
|
|
790e6146f5 | ||
|
|
89283ef486 | ||
|
|
96bd5a6dc1 | ||
|
|
f5d8741832 | ||
|
|
effcc988c1 | ||
|
|
7ac3fbfdc9 | ||
|
|
4c4134a272 | ||
|
|
b2682bcbf5 | ||
|
|
4111734637 | ||
|
|
6e27c47dee | ||
|
|
18cc3539ca | ||
|
|
76ad5bea0e | ||
|
|
13e80e449c | ||
|
|
023eb19615 | ||
|
|
3e4617be37 | ||
|
|
ed9ec402fd | ||
|
|
56de81a1f9 | ||
|
|
ccb41d1ef9 | ||
|
|
2374cda8d0 | ||
|
|
1b7a09c184 | ||
|
|
37925e7f6c | ||
|
|
762ae3a598 | ||
|
|
9f8a2acf46 | ||
|
|
4fdec9d6e5 | ||
|
|
640d58eb13 | ||
|
|
fa8c61382b | ||
|
|
b6ac898f8f | ||
|
|
57bcff1964 | ||
|
|
939a87ed2e | ||
|
|
16d6914b15 | ||
|
|
05e473642b | ||
|
|
0d592f6c55 | ||
|
|
476adf872a | ||
|
|
9584629f50 | ||
|
|
c1c49183b5 | ||
|
|
8069cd6689 | ||
|
|
1f79ca9539 | ||
|
|
1d8fc97053 | ||
|
|
19f3669fbd | ||
|
|
06024b0ab0 | ||
|
|
6e952a0aa8 | ||
|
|
57dee794d1 | ||
|
|
2c0bb71a6e | ||
|
|
ab8f638e44 | ||
|
|
d250b67f33 | ||
|
|
42b8241541 | ||
|
|
6cc98c1ea9 | ||
|
|
77c367ad1d | ||
|
|
26b3148904 | ||
|
|
27dc9ca799 | ||
|
|
63e87ef85b | ||
|
|
6697b677dc | ||
|
|
baad1a5166 | ||
|
|
7cf7982565 | ||
|
|
f3f6e9d365 | ||
|
|
4228137dff | ||
|
|
3c8d27d098 | ||
|
|
2c200873c1 | ||
|
|
ff1fa17dc3 | ||
|
|
08e6d8a780 | ||
|
|
4c1705fb1e | ||
|
|
31389b38f1 | ||
|
|
ff7a3cc885 | ||
|
|
4d1488498c | ||
|
|
10a22e7872 | ||
|
|
e72b6a440b | ||
|
|
b5ca4b7f35 | ||
|
|
c49f4b73dd | ||
|
|
80cbf08a58 | ||
|
|
5e23cc719d | ||
|
|
0680fe2a1a | ||
|
|
bba5f54722 | ||
|
|
85c4546333 | ||
|
|
c4105436eb | ||
|
|
23b5c0e833 | ||
|
|
cdd1bc425b | ||
|
|
2a9c06c40f | ||
|
|
434e0234c5 | ||
|
|
caf415dc97 | ||
|
|
e9337bf56e | ||
|
|
bcd02a871f | ||
|
|
e1c14bc86c | ||
|
|
69c23c00e0 | ||
|
|
1e19d7e463 | ||
|
|
5e0391aa2b | ||
|
|
2e91ee3849 | ||
|
|
9b32d617db | ||
|
|
2ec8376af9 | ||
|
|
86ef32318c | ||
|
|
4d062d41cb | ||
|
|
e78e42339d | ||
|
|
057ab1b7a6 | ||
|
|
613300c61d | ||
|
|
7d1f66ccf8 | ||
|
|
a7418449f9 | ||
|
|
d68e6f8362 | ||
|
|
c34ce15b14 | ||
|
|
1350d2cd1a | ||
|
|
9db2aca791 | ||
|
|
80d58b7930 | ||
|
|
568ecc201a | ||
|
|
cad7ed5570 | ||
|
|
57bb9281f6 | ||
|
|
5e53e9bcaa | ||
|
|
edfbb56749 | ||
|
|
652a04ac70 | ||
|
|
5e9ab3e261 | ||
|
|
be6fd3af9a | ||
|
|
e272cd485c | ||
|
|
f27528538d | ||
|
|
ad35a3d7ab | ||
|
|
211b9cbe04 | ||
|
|
946b8c29d7 | ||
|
|
33940ae66b | ||
|
|
d2589c4415 | ||
|
|
22733e44bf | ||
|
|
82d4051a39 | ||
|
|
0664a8c0e6 | ||
|
|
9b23376415 | ||
|
|
553a1b90ba | ||
|
|
7ea9da9605 | ||
|
|
9b98e608e6 | ||
|
|
885edc9768 | ||
|
|
e1b8485b51 | ||
|
|
764a35d035 | ||
|
|
e93bbd3831 | ||
|
|
8938c95e00 | ||
|
|
00ab6f572a | ||
|
|
73e9cbdea1 | ||
|
|
78381e9e7b | ||
|
|
95299d94c4 | ||
|
|
75252b6251 | ||
|
|
f95b0ccdab | ||
|
|
38f184e50d | ||
|
|
1f4e5b17b7 | ||
|
|
9ee7e28ef8 | ||
|
|
3ac5b91899 | ||
|
|
4b29c4cdbf | ||
|
|
89729aefe8 | ||
|
|
15aae8a58c | ||
|
|
096c69dc4f | ||
|
|
2c0d2c1532 | ||
|
|
eca8ddabe9 | ||
|
|
c57d5ef1cd | ||
|
|
6bbc0eefed | ||
|
|
8c5b299449 | ||
|
|
9806699592 | ||
|
|
543b19b376 | ||
|
|
f2e878d9ec | ||
|
|
b73426b91f | ||
|
|
628c4c996a | ||
|
|
642d20b2f7 | ||
|
|
f6a88c6e9b | ||
|
|
d1fa5f307b | ||
|
|
cd0e813a85 | ||
|
|
dc47a391da | ||
|
|
9f94678478 | ||
|
|
04fea69a28 | ||
|
|
d6a8821596 | ||
|
|
7617dd5029 | ||
|
|
e9d9df3473 | ||
|
|
b6ee3d99b1 | ||
|
|
9a2bd83827 | ||
|
|
f359f869ab | ||
|
|
d6fba7c2f3 | ||
|
|
498bcf213f | ||
|
|
33efb7ace6 | ||
|
|
d74ca78bd8 | ||
|
|
3c91ba134f | ||
|
|
9a83d84109 | ||
|
|
8ae4018e4d | ||
|
|
739901b606 | ||
|
|
03b5be91f7 | ||
|
|
272c977d08 | ||
|
|
75446d8195 | ||
|
|
52ff391c8a | ||
|
|
344a0a094f | ||
|
|
2710226326 | ||
|
|
381b0d3d07 | ||
|
|
52523bcd8b | ||
|
|
0d13e2cb2e | ||
|
|
014881e550 | ||
|
|
67b82638db | ||
|
|
09f18d07b0 | ||
|
|
9ef874e979 | ||
|
|
0aa73d5b35 | ||
|
|
ad2fa61765 | ||
|
|
e8106f3792 | ||
|
|
db3b974479 | ||
|
|
d62a4d3566 | ||
|
|
1b25b5f590 | ||
|
|
03add90c94 | ||
|
|
0f2e277f80 | ||
|
|
8664e7f7d3 | ||
|
|
cb37f43277 | ||
|
|
2a535b72ff | ||
|
|
cd2336887c | ||
|
|
448b09d7b6 | ||
|
|
704fea616b | ||
|
|
23665c7731 | ||
|
|
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 | ||
|
|
a5fb3e08f7 | ||
|
|
59caff8fb1 | ||
|
|
f825e81d0e | ||
|
|
7bea0007c7 | ||
|
|
8dd8addd3a | ||
|
|
e14dd4974f | ||
|
|
7a97995d81 | ||
|
|
03e60b9ea4 | ||
|
|
c1bc1e3137 | ||
|
|
73ac98da80 | ||
|
|
14b43b504b | ||
|
|
a3c605f147 | ||
|
|
333413d298 | ||
|
|
9de8d7276e | ||
|
|
432b106d58 | ||
|
|
2c7a248307 | ||
|
|
113947132c | ||
|
|
0a253d66d0 | ||
|
|
ae0e001187 | ||
|
|
eab82fdec7 | ||
|
|
da755d1c83 | ||
|
|
1b2581f0cb | ||
|
|
56c8bdbaa2 | ||
|
|
23435512c4 | ||
|
|
6c3a0eb1d6 | ||
|
|
c85cd13ca1 |
@@ -1,6 +1,7 @@
|
|||||||
[run]
|
[run]
|
||||||
omit =
|
omit =
|
||||||
scripts/*
|
scripts/*
|
||||||
freqtrade/tests/*
|
freqtrade/templates/*
|
||||||
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
|
||||||
|
|||||||
235
.github/workflows/ci.yml
vendored
Normal file
235
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
name: Freqtrade CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
- develop
|
||||||
|
- github_actions_tests
|
||||||
|
tags:
|
||||||
|
pull_request:
|
||||||
|
schedule:
|
||||||
|
- cron: '0 5 * * 4'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [ ubuntu-18.04, macos-latest ]
|
||||||
|
python-version: [3.7]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v1
|
||||||
|
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v1
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
|
- name: Cache_dependencies
|
||||||
|
uses: actions/cache@v1
|
||||||
|
id: cache
|
||||||
|
with:
|
||||||
|
path: ~/dependencies/
|
||||||
|
key: ${{ runner.os }}-dependencies
|
||||||
|
|
||||||
|
- name: pip cache (linux)
|
||||||
|
uses: actions/cache@preview
|
||||||
|
if: startsWith(matrix.os, 'ubuntu')
|
||||||
|
with:
|
||||||
|
path: ~/.cache/pip
|
||||||
|
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
||||||
|
|
||||||
|
- name: pip cache (macOS)
|
||||||
|
uses: actions/cache@preview
|
||||||
|
if: startsWith(matrix.os, 'macOS')
|
||||||
|
with:
|
||||||
|
path: ~/Library/Caches/pip
|
||||||
|
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
||||||
|
|
||||||
|
- name: TA binary *nix
|
||||||
|
if: steps.cache.outputs.cache-hit != 'true'
|
||||||
|
run: |
|
||||||
|
cd build_helpers && ./install_ta-lib.sh ${HOME}/dependencies/; cd ..
|
||||||
|
|
||||||
|
- name: Installation - *nix
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH
|
||||||
|
export TA_LIBRARY_PATH=${HOME}/dependencies/lib
|
||||||
|
export TA_INCLUDE_PATH=${HOME}/dependencies/include
|
||||||
|
pip install -r requirements-dev.txt
|
||||||
|
pip install -e .
|
||||||
|
|
||||||
|
- name: Tests
|
||||||
|
env:
|
||||||
|
COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN }}
|
||||||
|
COVERALLS_SERVICE_NAME: travis-ci
|
||||||
|
TRAVIS: "true"
|
||||||
|
run: |
|
||||||
|
pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
||||||
|
# Allow failure for coveralls
|
||||||
|
# Fake travis environment to get coveralls working correctly
|
||||||
|
export TRAVIS_PULL_REQUEST="https://github.com/${GITHUB_REPOSITORY}/pull/$(cat $GITHUB_EVENT_PATH | jq -r .number)"
|
||||||
|
export TRAVIS_BRANCH=${GITHUB_REF#"ref/heads"}
|
||||||
|
export CI_BRANCH=${GITHUB_REF#"ref/heads"}
|
||||||
|
echo "${TRAVIS_BRANCH}"
|
||||||
|
coveralls || true
|
||||||
|
|
||||||
|
- name: Backtesting
|
||||||
|
run: |
|
||||||
|
cp config.json.example config.json
|
||||||
|
freqtrade create-userdir --userdir user_data
|
||||||
|
freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
|
||||||
|
|
||||||
|
- name: Hyperopt
|
||||||
|
run: |
|
||||||
|
cp config.json.example config.json
|
||||||
|
freqtrade create-userdir --userdir user_data
|
||||||
|
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt
|
||||||
|
|
||||||
|
- name: Flake8
|
||||||
|
run: |
|
||||||
|
flake8
|
||||||
|
|
||||||
|
- name: Mypy
|
||||||
|
run: |
|
||||||
|
mypy freqtrade scripts
|
||||||
|
|
||||||
|
- name: Slack Notification
|
||||||
|
uses: homoluctus/slatify@v1.8.0
|
||||||
|
if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
|
||||||
|
with:
|
||||||
|
type: ${{ job.status }}
|
||||||
|
job_name: '*Freqtrade CI ${{ matrix.os }}*'
|
||||||
|
mention: 'here'
|
||||||
|
mention_if: 'failure'
|
||||||
|
channel: '#notifications'
|
||||||
|
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
|
|
||||||
|
build_windows:
|
||||||
|
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [ windows-latest ]
|
||||||
|
python-version: [3.7]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v1
|
||||||
|
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v1
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
|
- name: Pip cache (Windows)
|
||||||
|
uses: actions/cache@preview
|
||||||
|
if: startsWith(runner.os, 'Windows')
|
||||||
|
with:
|
||||||
|
path: ~\AppData\Local\pip\Cache
|
||||||
|
key: ${{ runner.os }}-pip
|
||||||
|
restore-keys: ${{ runner.os }}-pip
|
||||||
|
|
||||||
|
- name: Installation
|
||||||
|
run: |
|
||||||
|
./build_helpers/install_windows.ps1
|
||||||
|
|
||||||
|
- name: Tests
|
||||||
|
run: |
|
||||||
|
pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
||||||
|
|
||||||
|
- name: Backtesting
|
||||||
|
run: |
|
||||||
|
cp config.json.example config.json
|
||||||
|
freqtrade create-userdir --userdir user_data
|
||||||
|
freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
|
||||||
|
|
||||||
|
- name: Hyperopt
|
||||||
|
run: |
|
||||||
|
cp config.json.example config.json
|
||||||
|
freqtrade create-userdir --userdir user_data
|
||||||
|
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt
|
||||||
|
|
||||||
|
- name: Flake8
|
||||||
|
run: |
|
||||||
|
flake8
|
||||||
|
|
||||||
|
- name: Mypy
|
||||||
|
run: |
|
||||||
|
mypy freqtrade scripts
|
||||||
|
|
||||||
|
- name: Slack Notification
|
||||||
|
uses: homoluctus/slatify@v1.8.0
|
||||||
|
if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
|
||||||
|
with:
|
||||||
|
type: ${{ job.status }}
|
||||||
|
job_name: '*Freqtrade CI windows*'
|
||||||
|
mention: 'here'
|
||||||
|
mention_if: 'failure'
|
||||||
|
channel: '#notifications'
|
||||||
|
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
|
|
||||||
|
docs_check:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v1
|
||||||
|
|
||||||
|
- name: Documentation syntax
|
||||||
|
run: |
|
||||||
|
./tests/test_docs.sh
|
||||||
|
|
||||||
|
- name: Slack Notification
|
||||||
|
uses: homoluctus/slatify@v1.8.0
|
||||||
|
if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
|
||||||
|
with:
|
||||||
|
type: ${{ job.status }}
|
||||||
|
job_name: '*Freqtrade Docs*'
|
||||||
|
channel: '#notifications'
|
||||||
|
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
|
|
||||||
|
deploy:
|
||||||
|
needs: [ build, build_windows, docs_check ]
|
||||||
|
runs-on: ubuntu-18.04
|
||||||
|
if: (github.event_name == 'push' || github.event_name == 'schedule') && github.repository == 'freqtrade/freqtrade'
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v1
|
||||||
|
|
||||||
|
- name: Extract branch name
|
||||||
|
shell: bash
|
||||||
|
run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})"
|
||||||
|
id: extract_branch
|
||||||
|
|
||||||
|
- name: Build and test and push docker image
|
||||||
|
env:
|
||||||
|
IMAGE_NAME: freqtradeorg/freqtrade
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
BRANCH_NAME: ${{ steps.extract_branch.outputs.branch }}
|
||||||
|
run: |
|
||||||
|
build_helpers/publish_docker.sh
|
||||||
|
|
||||||
|
- name: Build raspberry image for ${{ steps.extract_branch.outputs.branch }}_pi
|
||||||
|
uses: elgohr/Publish-Docker-Github-Action@2.7
|
||||||
|
with:
|
||||||
|
name: freqtradeorg/freqtrade:${{ steps.extract_branch.outputs.branch }}_pi
|
||||||
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
dockerfile: Dockerfile.pi
|
||||||
|
# cache: true
|
||||||
|
cache: ${{ github.event_name != 'schedule' }}
|
||||||
|
tag_names: true
|
||||||
|
|
||||||
|
- name: Slack Notification
|
||||||
|
uses: homoluctus/slatify@v1.8.0
|
||||||
|
if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
|
||||||
|
with:
|
||||||
|
type: ${{ job.status }}
|
||||||
|
job_name: '*Freqtrade CI Deploy*'
|
||||||
|
mention: 'here'
|
||||||
|
mention_if: 'failure'
|
||||||
|
channel: '#notifications'
|
||||||
|
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
|
|
||||||
18
.github/workflows/docker_update_readme.yml
vendored
Normal file
18
.github/workflows/docker_update_readme.yml
vendored
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
name: Update Docker Hub Description
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
dockerHubDescription:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v1
|
||||||
|
- name: Docker Hub Description
|
||||||
|
uses: peter-evans/dockerhub-description@v2.1.0
|
||||||
|
env:
|
||||||
|
DOCKERHUB_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
DOCKERHUB_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
DOCKERHUB_REPOSITORY: freqtradeorg/freqtrade
|
||||||
|
|
||||||
16
.gitignore
vendored
16
.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,8 +80,7 @@ docs/_build/
|
|||||||
target/
|
target/
|
||||||
|
|
||||||
# Jupyter Notebook
|
# Jupyter Notebook
|
||||||
.ipynb_checkpoints
|
*.ipynb_checkpoints
|
||||||
*.ipynb
|
|
||||||
|
|
||||||
# pyenv
|
# pyenv
|
||||||
.python-version
|
.python-version
|
||||||
@@ -93,3 +92,6 @@ target/
|
|||||||
|
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.mypy_cache/
|
.mypy_cache/
|
||||||
|
|
||||||
|
#exceptions
|
||||||
|
!*.gitkeep
|
||||||
|
|||||||
37
.pyup.yml
37
.pyup.yml
@@ -1,37 +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
|
|
||||||
|
|
||||||
# update schedule
|
|
||||||
# default: empty
|
|
||||||
# allowed: "every day", "every week", ..
|
|
||||||
schedule: "every week"
|
|
||||||
|
|
||||||
|
|
||||||
search: False
|
|
||||||
# Specify requirement files by hand, default is empty
|
|
||||||
# default: empty
|
|
||||||
# allowed: list
|
|
||||||
requirements:
|
|
||||||
- requirements.txt
|
|
||||||
- requirements-dev.txt
|
|
||||||
- requirements-plot.txt
|
|
||||||
- requirements-common.txt
|
|
||||||
|
|
||||||
|
|
||||||
# configure the branch prefix the bot is using
|
|
||||||
# default: pyup-
|
|
||||||
branch_prefix: pyup/
|
|
||||||
|
|
||||||
# allow to close stale PRs
|
|
||||||
# default: True
|
|
||||||
close_prs: True
|
|
||||||
42
.travis.yml
42
.travis.yml
@@ -10,15 +10,11 @@ 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
|
||||||
|
- 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:
|
||||||
@@ -26,28 +22,36 @@ jobs:
|
|||||||
include:
|
include:
|
||||||
- stage: tests
|
- stage: tests
|
||||||
script:
|
script:
|
||||||
- pytest --random-order --cov=freqtrade --cov-config=.coveragerc freqtrade/tests/
|
- pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
||||||
# Allow failure for coveralls
|
# Allow failure for coveralls
|
||||||
- coveralls || true
|
# - coveralls || true
|
||||||
name: pytest
|
name: pytest
|
||||||
- script:
|
- script:
|
||||||
- cp config.json.example config.json
|
- cp config.json.example config.json
|
||||||
- freqtrade --datadir freqtrade/tests/testdata backtesting
|
- freqtrade create-userdir --userdir user_data
|
||||||
|
- freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
|
||||||
name: backtest
|
name: backtest
|
||||||
- script:
|
- script:
|
||||||
- cp config.json.example config.json
|
- cp config.json.example config.json
|
||||||
- freqtrade --datadir freqtrade/tests/testdata hyperopt -e 5
|
- freqtrade create-userdir --userdir user_data
|
||||||
|
- freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt
|
||||||
name: hyperopt
|
name: hyperopt
|
||||||
- script: flake8 freqtrade scripts
|
- script: flake8
|
||||||
name: flake8
|
name: flake8
|
||||||
|
- script:
|
||||||
|
# Test Documentation boxes -
|
||||||
|
# !!! <TYPE>: is not allowed!
|
||||||
|
# !!! <TYPE> "title" - Title needs to be quoted!
|
||||||
|
- grep -Er '^!{3}\s\S+:|^!{3}\s\S+\s[^"]' docs/*; test $? -ne 0
|
||||||
|
name: doc syntax
|
||||||
- script: mypy freqtrade scripts
|
- script: mypy freqtrade scripts
|
||||||
name: mypy
|
name: mypy
|
||||||
|
|
||||||
- stage: docker
|
# - stage: docker
|
||||||
if: branch in (master, develop, feat/improve_travis) AND (type in (push, cron))
|
# if: branch in (master, develop, feat/improve_travis) AND (type in (push, cron))
|
||||||
script:
|
# script:
|
||||||
- build_helpers/publish_docker.sh
|
# - build_helpers/publish_docker.sh
|
||||||
name: "Build and test and push docker image"
|
# name: "Build and test and push docker image"
|
||||||
|
|
||||||
notifications:
|
notifications:
|
||||||
slack:
|
slack:
|
||||||
@@ -55,4 +59,4 @@ notifications:
|
|||||||
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/enQtNjU5ODcwNjI1MDU3LWEyODBiNzkzNzcyNzU0MWYyYzE5NjIyOTQxMzBmMGUxOTIzM2YyN2Y4NWY1YTEwZDgwYTRmMzE2NmM5ZmY2MTg)
|
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,4 +1,4 @@
|
|||||||
FROM python:3.7.3-slim-stretch
|
FROM python:3.7.5-slim-stretch
|
||||||
|
|
||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get -y install curl build-essential libssl-dev \
|
&& apt-get -y install curl build-essential libssl-dev \
|
||||||
@@ -16,11 +16,13 @@ RUN cd /tmp && /tmp/install_ta-lib.sh && rm -r /tmp/*ta-lib*
|
|||||||
ENV LD_LIBRARY_PATH /usr/local/lib
|
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||||
|
|
||||||
# Install dependencies
|
# Install dependencies
|
||||||
COPY requirements.txt requirements-common.txt /freqtrade/
|
COPY requirements.txt requirements-common.txt requirements-hyperopt.txt /freqtrade/
|
||||||
RUN pip install numpy --no-cache-dir \
|
RUN pip install numpy --no-cache-dir \
|
||||||
&& pip install -r requirements.txt --no-cache-dir
|
&& pip install -r requirements-hyperopt.txt --no-cache-dir
|
||||||
|
|
||||||
# Install and execute
|
# Install and execute
|
||||||
COPY . /freqtrade/
|
COPY . /freqtrade/
|
||||||
RUN pip install -e . --no-cache-dir
|
RUN pip install -e . --no-cache-dir
|
||||||
ENTRYPOINT ["freqtrade"]
|
ENTRYPOINT ["freqtrade"]
|
||||||
|
# Default to trade mode
|
||||||
|
CMD [ "trade" ]
|
||||||
|
|||||||
@@ -22,13 +22,13 @@ RUN tar -xzf /freqtrade/ta-lib-0.4.0-src.tar.gz \
|
|||||||
ENV LD_LIBRARY_PATH /usr/local/lib
|
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||||
|
|
||||||
# Install berryconda
|
# Install berryconda
|
||||||
RUN wget https://github.com/jjhelmus/berryconda/releases/download/v2.0.0/Berryconda3-2.0.0-Linux-armv7l.sh \
|
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 \
|
&& bash ./Berryconda3-2.0.0-Linux-armv7l.sh -b \
|
||||||
&& rm Berryconda3-2.0.0-Linux-armv7l.sh
|
&& rm Berryconda3-2.0.0-Linux-armv7l.sh
|
||||||
|
|
||||||
# Install dependencies
|
# Install dependencies
|
||||||
COPY requirements-common.txt /freqtrade/
|
COPY requirements-common.txt /freqtrade/
|
||||||
RUN ~/berryconda3/bin/conda install -y numpy pandas scipy \
|
RUN ~/berryconda3/bin/conda install -y numpy pandas \
|
||||||
&& ~/berryconda3/bin/pip install -r requirements-common.txt --no-cache-dir
|
&& ~/berryconda3/bin/pip install -r requirements-common.txt --no-cache-dir
|
||||||
|
|
||||||
# Install and execute
|
# Install and execute
|
||||||
@@ -38,3 +38,4 @@ RUN ~/berryconda3/bin/pip install -e . --no-cache-dir
|
|||||||
RUN [ "cross-build-end" ]
|
RUN [ "cross-build-end" ]
|
||||||
|
|
||||||
ENTRYPOINT ["/root/berryconda3/bin/python","./freqtrade/main.py"]
|
ENTRYPOINT ["/root/berryconda3/bin/python","./freqtrade/main.py"]
|
||||||
|
CMD [ "trade" ]
|
||||||
|
|||||||
@@ -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
|
|
||||||
|
|||||||
12
README.md
12
README.md
@@ -62,7 +62,6 @@ git checkout develop
|
|||||||
|
|
||||||
For any other type of installation please refer to [Installation doc](https://www.freqtrade.io/en/latest/installation/).
|
For any other type of installation please refer to [Installation doc](https://www.freqtrade.io/en/latest/installation/).
|
||||||
|
|
||||||
|
|
||||||
## Basic Usage
|
## Basic Usage
|
||||||
|
|
||||||
### Bot commands
|
### Bot commands
|
||||||
@@ -106,7 +105,7 @@ optional arguments:
|
|||||||
|
|
||||||
### Telegram RPC commands
|
### Telegram RPC commands
|
||||||
|
|
||||||
Telegram is not mandatory. However, this is a great way to control your bot. More details on our [documentation](https://www.freqtrade.io/en/latest/telegram-usage/)
|
Telegram is not mandatory. However, this is a great way to control your bot. More details and the full command list on our [documentation](https://www.freqtrade.io/en/latest/telegram-usage/)
|
||||||
|
|
||||||
- `/start`: Starts the trader
|
- `/start`: Starts the trader
|
||||||
- `/stop`: Stops the trader
|
- `/stop`: Stops the trader
|
||||||
@@ -129,11 +128,6 @@ The project is currently setup in two main branches:
|
|||||||
- `master` - This branch contains the latest stable release. The bot 'should' be stable on this branch, and is generally well tested.
|
- `master` - This branch contains the latest stable release. The bot 'should' be stable on this branch, and is generally well tested.
|
||||||
- `feat/*` - These are feature branches, which are being worked on heavily. Please don't use these unless you want to test a specific feature.
|
- `feat/*` - These are feature branches, which are being worked on heavily. Please don't use these unless you want to test a specific feature.
|
||||||
|
|
||||||
## A note on Binance
|
|
||||||
|
|
||||||
For Binance, please add `"BNB/<STAKE>"` to your blacklist to avoid issues.
|
|
||||||
Accounts having BNB accounts use this to pay for fees - if your first trade happens to be on `BNB`, further trades will consume this position and make the initial BNB order unsellable as the expected amount is not there anymore.
|
|
||||||
|
|
||||||
## Support
|
## Support
|
||||||
|
|
||||||
### Help / Slack
|
### Help / Slack
|
||||||
@@ -141,7 +135,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/enQtNjU5ODcwNjI1MDU3LWEyODBiNzkzNzcyNzU0MWYyYzE5NjIyOTQxMzBmMGUxOTIzM2YyN2Y4NWY1YTEwZDgwYTRmMzE2NmM5ZmY2MTg).
|
- [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 +166,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/enQtNjU5ODcwNjI1MDU3LWEyODBiNzkzNzcyNzU0MWYyYzE5NjIyOTQxMzBmMGUxOTIzM2YyN2Y4NWY1YTEwZDgwYTRmMzE2NmM5ZmY2MTg). 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`.
|
||||||
|
|
||||||
|
|||||||
BIN
build_helpers/TA_Lib-0.4.17-cp37-cp37m-win_amd64.whl
Normal file
BIN
build_helpers/TA_Lib-0.4.17-cp37-cp37m-win_amd64.whl
Normal file
Binary file not shown.
@@ -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 ..
|
||||||
|
|||||||
8
build_helpers/install_windows.ps1
Normal file
8
build_helpers/install_windows.ps1
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
# Downloads don't work automatically, since the URL is regenerated via javascript.
|
||||||
|
# Downloaded from https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib
|
||||||
|
# Invoke-WebRequest -Uri "https://download.lfd.uci.edu/pythonlibs/xxxxxxx/TA_Lib-0.4.17-cp37-cp37m-win_amd64.whl" -OutFile "TA_Lib-0.4.17-cp37-cp37m-win_amd64.whl"
|
||||||
|
|
||||||
|
pip install build_helpers\TA_Lib-0.4.17-cp37-cp37m-win_amd64.whl
|
||||||
|
|
||||||
|
pip install -r requirements-dev.txt
|
||||||
|
pip install -e .
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# - export TAG=`if [ "$TRAVIS_BRANCH" == "develop" ]; then echo "latest"; else echo $TRAVIS_BRANCH ; fi`
|
|
||||||
# Replace / with _ to create a valid tag
|
|
||||||
TAG=$(echo "${TRAVIS_BRANCH}" | sed -e "s/\//_/")
|
|
||||||
|
|
||||||
|
# Replace / with _ to create a valid tag
|
||||||
|
TAG=$(echo "${BRANCH_NAME}" | sed -e "s/\//_/g")
|
||||||
|
echo "Running for ${TAG}"
|
||||||
|
|
||||||
# Add commit and commit_message to docker container
|
# Add commit and commit_message to docker container
|
||||||
echo "${TRAVIS_COMMIT} ${TRAVIS_COMMIT_MESSAGE}" > freqtrade_commit
|
echo "${GITHUB_SHA}" > freqtrade_commit
|
||||||
|
|
||||||
if [ "${TRAVIS_EVENT_TYPE}" = "cron" ]; then
|
if [ "${GITHUB_EVENT_NAME}" = "schedule" ]; then
|
||||||
echo "event ${TRAVIS_EVENT_TYPE}: full rebuild - skipping cache"
|
echo "event ${GITHUB_EVENT_NAME}: full rebuild - skipping cache"
|
||||||
docker build -t freqtrade:${TAG} .
|
docker build -t freqtrade:${TAG} .
|
||||||
else
|
else
|
||||||
echo "event ${TRAVIS_EVENT_TYPE}: building with cache"
|
echo "event ${GITHUB_EVENT_NAME}: building with cache"
|
||||||
# Pull last build to avoid rebuilding the whole image
|
# Pull last build to avoid rebuilding the whole image
|
||||||
docker pull ${IMAGE_NAME}:${TAG}
|
docker pull ${IMAGE_NAME}:${TAG}
|
||||||
docker build --cache-from ${IMAGE_NAME}:${TAG} -t freqtrade:${TAG} .
|
docker build --cache-from ${IMAGE_NAME}:${TAG} -t freqtrade:${TAG} .
|
||||||
@@ -23,7 +23,7 @@ if [ $? -ne 0 ]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# Run backtest
|
# Run backtest
|
||||||
docker run --rm -it -v $(pwd)/config.json.example:/freqtrade/config.json:ro freqtrade:${TAG} --datadir freqtrade/tests/testdata backtesting
|
docker run --rm -v $(pwd)/config.json.example:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy DefaultStrategy
|
||||||
|
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "failed running backtest"
|
echo "failed running backtest"
|
||||||
@@ -38,12 +38,12 @@ if [ $? -ne 0 ]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# Tag as latest for develop builds
|
# Tag as latest for develop builds
|
||||||
if [ "${TRAVIS_BRANCH}" = "develop" ]; then
|
if [ "${TAG}" = "develop" ]; then
|
||||||
docker tag freqtrade:$TAG ${IMAGE_NAME}:latest
|
docker tag freqtrade:$TAG ${IMAGE_NAME}:latest
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Login
|
# Login
|
||||||
echo "$DOCKER_PASS" | docker login -u $DOCKER_USER --password-stdin
|
docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD
|
||||||
|
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "failed login"
|
echo "failed login"
|
||||||
|
|||||||
@@ -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",
|
||||||
@@ -41,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"
|
||||||
],
|
],
|
||||||
@@ -49,11 +52,9 @@
|
|||||||
"DOGE/BTC"
|
"DOGE/BTC"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"experimental": {
|
"pairlists": [
|
||||||
"use_sell_signal": false,
|
{"method": "StaticPairList"}
|
||||||
"sell_profit_only": false,
|
],
|
||||||
"ignore_roi_if_buy_signal": false
|
|
||||||
},
|
|
||||||
"edge": {
|
"edge": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"process_throttle_secs": 3600,
|
"process_throttle_secs": 3600,
|
||||||
@@ -70,7 +71,7 @@
|
|||||||
"remove_pumps": false
|
"remove_pumps": false
|
||||||
},
|
},
|
||||||
"telegram": {
|
"telegram": {
|
||||||
"enabled": true,
|
"enabled": false,
|
||||||
"token": "your_telegram_token",
|
"token": "your_telegram_token",
|
||||||
"chat_id": "your_telegram_chat_id"
|
"chat_id": "your_telegram_chat_id"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -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",
|
||||||
@@ -34,28 +37,29 @@
|
|||||||
"rateLimit": 200
|
"rateLimit": 200
|
||||||
},
|
},
|
||||||
"pair_whitelist": [
|
"pair_whitelist": [
|
||||||
"AST/BTC",
|
"ALGO/BTC",
|
||||||
"ETC/BTC",
|
"ATOM/BTC",
|
||||||
"ETH/BTC",
|
"BAT/BTC",
|
||||||
|
"BCH/BTC",
|
||||||
|
"BRD/BTC",
|
||||||
"EOS/BTC",
|
"EOS/BTC",
|
||||||
|
"ETH/BTC",
|
||||||
"IOTA/BTC",
|
"IOTA/BTC",
|
||||||
|
"LINK/BTC",
|
||||||
"LTC/BTC",
|
"LTC/BTC",
|
||||||
"MTH/BTC",
|
"NEO/BTC",
|
||||||
"NCASH/BTC",
|
"NXS/BTC",
|
||||||
"TNT/BTC",
|
|
||||||
"XMR/BTC",
|
"XMR/BTC",
|
||||||
"XLM/BTC",
|
"XRP/BTC",
|
||||||
"XRP/BTC"
|
"XTZ/BTC"
|
||||||
],
|
],
|
||||||
"pair_blacklist": [
|
"pair_blacklist": [
|
||||||
"BNB/BTC"
|
"BNB/BTC"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"experimental": {
|
"pairlists": [
|
||||||
"use_sell_signal": false,
|
{"method": "StaticPairList"}
|
||||||
"sell_profit_only": false,
|
],
|
||||||
"ignore_roi_if_buy_signal": false
|
|
||||||
},
|
|
||||||
"edge": {
|
"edge": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"process_throttle_secs": 3600,
|
"process_throttle_secs": 3600,
|
||||||
|
|||||||
@@ -33,11 +33,15 @@
|
|||||||
"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
|
||||||
@@ -46,14 +50,18 @@
|
|||||||
"buy": "gtc",
|
"buy": "gtc",
|
||||||
"sell": "gtc"
|
"sell": "gtc"
|
||||||
},
|
},
|
||||||
"pairlist": {
|
"pairlists": [
|
||||||
|
{"method": "StaticPairList"},
|
||||||
|
{
|
||||||
"method": "VolumePairList",
|
"method": "VolumePairList",
|
||||||
"config": {
|
|
||||||
"number_assets": 20,
|
"number_assets": 20,
|
||||||
"sort_key": "quoteVolume",
|
"sort_key": "quoteVolume",
|
||||||
"precision_filter": false
|
"refresh_period": 1800
|
||||||
}
|
|
||||||
},
|
},
|
||||||
|
{"method": "PrecisionFilter"},
|
||||||
|
{"method": "PriceFilter", "low_price_ratio": 0.01
|
||||||
|
}
|
||||||
|
],
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "bittrex",
|
"name": "bittrex",
|
||||||
"sandbox": false,
|
"sandbox": false,
|
||||||
@@ -74,7 +82,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"
|
||||||
],
|
],
|
||||||
@@ -99,11 +107,6 @@
|
|||||||
"max_trade_duration_minute": 1440,
|
"max_trade_duration_minute": 1440,
|
||||||
"remove_pumps": false
|
"remove_pumps": false
|
||||||
},
|
},
|
||||||
"experimental": {
|
|
||||||
"use_sell_signal": false,
|
|
||||||
"sell_profit_only": false,
|
|
||||||
"ignore_roi_if_buy_signal": false
|
|
||||||
},
|
|
||||||
"telegram": {
|
"telegram": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"token": "your_telegram_token",
|
"token": "your_telegram_token",
|
||||||
@@ -120,7 +123,8 @@
|
|||||||
"initial_state": "running",
|
"initial_state": "running",
|
||||||
"forcebuy_enable": false,
|
"forcebuy_enable": false,
|
||||||
"internals": {
|
"internals": {
|
||||||
"process_throttle_secs": 5
|
"process_throttle_secs": 5,
|
||||||
|
"heartbeat_interval": 60
|
||||||
},
|
},
|
||||||
"strategy": "DefaultStrategy",
|
"strategy": "DefaultStrategy",
|
||||||
"strategy_path": "user_data/strategies/"
|
"strategy_path": "user_data/strategies/"
|
||||||
|
|||||||
@@ -22,7 +22,11 @@
|
|||||||
"ask_strategy":{
|
"ask_strategy":{
|
||||||
"use_order_book": false,
|
"use_order_book": false,
|
||||||
"order_book_min": 1,
|
"order_book_min": 1,
|
||||||
"order_book_max": 9
|
"order_book_max": 9,
|
||||||
|
"use_sell_signal": true,
|
||||||
|
"sell_profit_only": false,
|
||||||
|
"ignore_roi_if_buy_signal": false
|
||||||
|
|
||||||
},
|
},
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "kraken",
|
"name": "kraken",
|
||||||
@@ -34,14 +38,34 @@
|
|||||||
"rateLimit": 1000
|
"rateLimit": 1000
|
||||||
},
|
},
|
||||||
"pair_whitelist": [
|
"pair_whitelist": [
|
||||||
"ETH/EUR",
|
"ADA/EUR",
|
||||||
|
"ATOM/EUR",
|
||||||
|
"BAT/EUR",
|
||||||
|
"BCH/EUR",
|
||||||
"BTC/EUR",
|
"BTC/EUR",
|
||||||
"BCH/EUR"
|
"DAI/EUR",
|
||||||
|
"DASH/EUR",
|
||||||
|
"EOS/EUR",
|
||||||
|
"ETC/EUR",
|
||||||
|
"ETH/EUR",
|
||||||
|
"LINK/EUR",
|
||||||
|
"LTC/EUR",
|
||||||
|
"QTUM/EUR",
|
||||||
|
"REP/EUR",
|
||||||
|
"WAVES/EUR",
|
||||||
|
"XLM/EUR",
|
||||||
|
"XMR/EUR",
|
||||||
|
"XRP/EUR",
|
||||||
|
"XTZ/EUR",
|
||||||
|
"ZEC/EUR"
|
||||||
],
|
],
|
||||||
"pair_blacklist": [
|
"pair_blacklist": [
|
||||||
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"pairlists": [
|
||||||
|
{"method": "StaticPairList"}
|
||||||
|
],
|
||||||
"edge": {
|
"edge": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"process_throttle_secs": 3600,
|
"process_throttle_secs": 3600,
|
||||||
@@ -66,5 +90,6 @@
|
|||||||
"forcebuy_enable": false,
|
"forcebuy_enable": false,
|
||||||
"internals": {
|
"internals": {
|
||||||
"process_throttle_secs": 5
|
"process_throttle_secs": 5
|
||||||
}
|
},
|
||||||
|
"download_trades": true
|
||||||
}
|
}
|
||||||
|
|||||||
20
docker-compose.develop.yml
Normal file
20
docker-compose.develop.yml
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
version: '3'
|
||||||
|
services:
|
||||||
|
freqtrade_develop:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: "./Dockerfile.develop"
|
||||||
|
volumes:
|
||||||
|
- ".:/freqtrade"
|
||||||
|
entrypoint:
|
||||||
|
- "freqtrade"
|
||||||
|
|
||||||
|
freqtrade_bash:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: "./Dockerfile.develop"
|
||||||
|
volumes:
|
||||||
|
- ".:/freqtrade"
|
||||||
|
entrypoint:
|
||||||
|
- "/bin/bash"
|
||||||
8
docker-compose.yml
Normal file
8
docker-compose.yml
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
---
|
||||||
|
version: '3'
|
||||||
|
services:
|
||||||
|
freqtrade:
|
||||||
|
image: freqtradeorg/freqtrade:master
|
||||||
|
volumes:
|
||||||
|
- "./user_data:/freqtrade/user_data"
|
||||||
|
- "./config.json:/freqtrade/config.json"
|
||||||
63
docs/advanced-hyperopt.md
Normal file
63
docs/advanced-hyperopt.md
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
# Advanced Hyperopt
|
||||||
|
|
||||||
|
This page explains some advanced Hyperopt topics that may require higher
|
||||||
|
coding skills and Python knowledge than creation of an ordinal hyperoptimization
|
||||||
|
class.
|
||||||
|
|
||||||
|
## Creating and using a custom loss function
|
||||||
|
|
||||||
|
To use a custom loss function class, make sure that the function `hyperopt_loss_function` is defined in your custom hyperopt loss class.
|
||||||
|
For the sample below, you then need to add the command line parameter `--hyperopt-loss SuperDuperHyperOptLoss` to your hyperopt call so this function is being used.
|
||||||
|
|
||||||
|
A sample of this can be found below, which is identical to the Default Hyperopt loss implementation. A full sample can be found in [userdata/hyperopts](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_loss.py).
|
||||||
|
|
||||||
|
``` python
|
||||||
|
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
||||||
|
|
||||||
|
TARGET_TRADES = 600
|
||||||
|
EXPECTED_MAX_PROFIT = 3.0
|
||||||
|
MAX_ACCEPTED_TRADE_DURATION = 300
|
||||||
|
|
||||||
|
class SuperDuperHyperOptLoss(IHyperOptLoss):
|
||||||
|
"""
|
||||||
|
Defines the default loss function for hyperopt
|
||||||
|
"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def hyperopt_loss_function(results: DataFrame, trade_count: int,
|
||||||
|
min_date: datetime, max_date: datetime,
|
||||||
|
*args, **kwargs) -> float:
|
||||||
|
"""
|
||||||
|
Objective function, returns smaller number for better results
|
||||||
|
This is the legacy algorithm (used until now in freqtrade).
|
||||||
|
Weights are distributed as follows:
|
||||||
|
* 0.4 to trade duration
|
||||||
|
* 0.25: Avoiding trade loss
|
||||||
|
* 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above
|
||||||
|
"""
|
||||||
|
total_profit = results.profit_percent.sum()
|
||||||
|
trade_duration = results.trade_duration.mean()
|
||||||
|
|
||||||
|
trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8)
|
||||||
|
profit_loss = max(0, 1 - total_profit / EXPECTED_MAX_PROFIT)
|
||||||
|
duration_loss = 0.4 * min(trade_duration / MAX_ACCEPTED_TRADE_DURATION, 1)
|
||||||
|
result = trade_loss + profit_loss + duration_loss
|
||||||
|
return result
|
||||||
|
```
|
||||||
|
|
||||||
|
Currently, the arguments are:
|
||||||
|
|
||||||
|
* `results`: DataFrame containing the result
|
||||||
|
The following columns are available in results (corresponds to the output-file of backtesting when used with `--export trades`):
|
||||||
|
`pair, profit_percent, profit_abs, open_time, close_time, open_index, close_index, trade_duration, open_at_end, open_rate, close_rate, sell_reason`
|
||||||
|
* `trade_count`: Amount of trades (identical to `len(results)`)
|
||||||
|
* `min_date`: Start date of the hyperopting TimeFrame
|
||||||
|
* `min_date`: End date of the hyperopting TimeFrame
|
||||||
|
|
||||||
|
This function needs to return a floating point number (`float`). Smaller numbers will be interpreted as better results. The parameters and balancing for this is up to you.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
This function is called once per iteration - so please make sure to have this as optimized as possible to not slow hyperopt down unnecessarily.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Please keep the arguments `*args` and `**kwargs` in the interface to allow us to extend this interface later.
|
||||||
92
docs/advanced-setup.md
Normal file
92
docs/advanced-setup.md
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
# Advanced Post-installation Tasks
|
||||||
|
|
||||||
|
This page explains some advanced tasks and configuration options that can be performed after the bot installation and may be uselful in some environments.
|
||||||
|
|
||||||
|
If you do not know what things mentioned here mean, you probably do not need it.
|
||||||
|
|
||||||
|
## Configure the bot running as a systemd service
|
||||||
|
|
||||||
|
Copy the `freqtrade.service` file to your systemd user directory (usually `~/.config/systemd/user`) and update `WorkingDirectory` and `ExecStart` to match your setup.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Certain systems (like Raspbian) don't load service unit files from the user directory. In this case, copy `freqtrade.service` into `/etc/systemd/user/` (requires superuser permissions).
|
||||||
|
|
||||||
|
After that you can start the daemon with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
systemctl --user start freqtrade
|
||||||
|
```
|
||||||
|
|
||||||
|
For this to be persistent (run when user is logged out) you'll need to enable `linger` for your freqtrade user.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo loginctl enable-linger "$USER"
|
||||||
|
```
|
||||||
|
|
||||||
|
If you run the bot as a service, you can use systemd service manager as a software watchdog monitoring freqtrade bot
|
||||||
|
state and restarting it in the case of failures. If the `internals.sd_notify` parameter is set to true in the
|
||||||
|
configuration or the `--sd-notify` command line option is used, the bot will send keep-alive ping messages to systemd
|
||||||
|
using the sd_notify (systemd notifications) protocol and will also tell systemd its current state (Running or Stopped)
|
||||||
|
when it changes.
|
||||||
|
|
||||||
|
The `freqtrade.service.watchdog` file contains an example of the service unit configuration file which uses systemd
|
||||||
|
as the watchdog.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
The sd_notify communication between the bot and the systemd service manager will not work if the bot runs in a Docker container.
|
||||||
|
|
||||||
|
## Advanced Logging
|
||||||
|
|
||||||
|
On many Linux systems the bot can be configured to send its log messages to `syslog` or `journald` system services. Logging to a remote `syslog` server is also available on Windows. The special values for the `--logfilename` command line option can be used for this.
|
||||||
|
|
||||||
|
### Logging to syslog
|
||||||
|
|
||||||
|
To send Freqtrade log messages to a local or remote `syslog` service use the `--logfilename` command line option with the value in the following format:
|
||||||
|
|
||||||
|
* `--logfilename syslog:<syslog_address>` -- send log messages to `syslog` service using the `<syslog_address>` as the syslog address.
|
||||||
|
|
||||||
|
The syslog address can be either a Unix domain socket (socket filename) or a UDP socket specification, consisting of IP address and UDP port, separated by the `:` character.
|
||||||
|
|
||||||
|
So, the following are the examples of possible usages:
|
||||||
|
|
||||||
|
* `--logfilename syslog:/dev/log` -- log to syslog (rsyslog) using the `/dev/log` socket, suitable for most systems.
|
||||||
|
* `--logfilename syslog` -- same as above, the shortcut for `/dev/log`.
|
||||||
|
* `--logfilename syslog:/var/run/syslog` -- log to syslog (rsyslog) using the `/var/run/syslog` socket. Use this on MacOS.
|
||||||
|
* `--logfilename syslog:localhost:514` -- log to local syslog using UDP socket, if it listens on port 514.
|
||||||
|
* `--logfilename syslog:<ip>:514` -- log to remote syslog at IP address and port 514. This may be used on Windows for remote logging to an external syslog server.
|
||||||
|
|
||||||
|
Log messages are send to `syslog` with the `user` facility. So you can see them with the following commands:
|
||||||
|
|
||||||
|
* `tail -f /var/log/user`, or
|
||||||
|
* install a comprehensive graphical viewer (for instance, 'Log File Viewer' for Ubuntu).
|
||||||
|
|
||||||
|
On many systems `syslog` (`rsyslog`) fetches data from `journald` (and vice versa), so both `--logfilename syslog` or `--logfilename journald` can be used and the messages be viewed with both `journalctl` and a syslog viewer utility. You can combine this in any way which suites you better.
|
||||||
|
|
||||||
|
For `rsyslog` the messages from the bot can be redirected into a separate dedicated log file. To achieve this, add
|
||||||
|
```
|
||||||
|
if $programname startswith "freqtrade" then -/var/log/freqtrade.log
|
||||||
|
```
|
||||||
|
to one of the rsyslog configuration files, for example at the end of the `/etc/rsyslog.d/50-default.conf`.
|
||||||
|
|
||||||
|
For `syslog` (`rsyslog`), the reduction mode can be switched on. This will reduce the number of repeating messages. For instance, multiple bot Heartbeat messages will be reduced to a single message when nothing else happens with the bot. To achieve this, set in `/etc/rsyslog.conf`:
|
||||||
|
```
|
||||||
|
# Filter duplicated messages
|
||||||
|
$RepeatedMsgReduction on
|
||||||
|
```
|
||||||
|
|
||||||
|
### Logging to journald
|
||||||
|
|
||||||
|
This needs the `systemd` python package installed as the dependency, which is not available on Windows. Hence, the whole journald logging functionality is not available for a bot running on Windows.
|
||||||
|
|
||||||
|
To send Freqtrade log messages to `journald` system service use the `--logfilename` command line option with the value in the following format:
|
||||||
|
|
||||||
|
* `--logfilename journald` -- send log messages to `journald`.
|
||||||
|
|
||||||
|
Log messages are send to `journald` with the `user` facility. So you can see them with the following commands:
|
||||||
|
|
||||||
|
* `journalctl -f` -- shows Freqtrade log messages sent to `journald` along with other log messages fetched by `journald`.
|
||||||
|
* `journalctl -f -u freqtrade.service` -- this command can be used when the bot is run as a `systemd` service.
|
||||||
|
|
||||||
|
There are many other options in the `journalctl` utility to filter the messages, see manual pages for this utility.
|
||||||
|
|
||||||
|
On many systems `syslog` (`rsyslog`) fetches data from `journald` (and vice versa), so both `--logfilename syslog` or `--logfilename journald` can be used and the messages be viewed with both `journalctl` and a syslog viewer utility. You can combine this in any way which suites you better.
|
||||||
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,26 +1,27 @@
|
|||||||
# 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 ticker data from `user_data/data/<exchange>` by default.
|
||||||
and load static tickers located in
|
If no data is available for the exchange / pair / ticker interval combination, backtesting will ask you to download them first using `freqtrade download-data`.
|
||||||
[/freqtrade/tests/testdata](https://github.com/freqtrade/freqtrade/tree/develop/freqtrade/tests/testdata).
|
For details on downloading, please refer to the [Data Downloading](data-download.md) section in the documentation.
|
||||||
If the 5 min and 1 min ticker for the crypto-currencies to test is not
|
|
||||||
already in the `testdata` directory, backtesting will download them
|
|
||||||
automatically. Testdata files will not be updated until you specify it.
|
|
||||||
|
|
||||||
The result of backtesting will confirm you if your bot 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.
|
!!! Tip "Using dynamic pairlists for backtesting"
|
||||||
|
While using dynamic pairlists during backtesting is not possible, a dynamic pairlist using current data can be generated via the [`test-pairlist`](utils.md#test-pairlist) command, and needs to be specified as `"pair_whitelist"` attribute in the configuration.
|
||||||
|
|
||||||
### Run a backtesting against the currencies listed in your config file
|
### Run a backtesting against the currencies listed in your config file
|
||||||
|
|
||||||
#### With 5 min tickers (Per default)
|
#### With 5 min tickers (Per default)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -33,31 +34,30 @@ freqtrade backtesting
|
|||||||
freqtrade backtesting --ticker-interval 1m
|
freqtrade backtesting --ticker-interval 1m
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Update cached pairs with the latest data
|
|
||||||
|
|
||||||
```bash
|
|
||||||
freqtrade backtesting --refresh-pairs-cached
|
|
||||||
```
|
|
||||||
|
|
||||||
#### With live data (do not alter your testdata files)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
freqtrade 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
|
||||||
freqtrade 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
|
||||||
freqtrade -s TestStrategy backtesting
|
freqtrade backtesting -s SampleStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
@@ -70,68 +70,43 @@ The exported trades can be used for [further analysis](#further-backtest-result-
|
|||||||
#### Exporting trades to file specifying a custom filename
|
#### Exporting trades to file specifying a custom filename
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade backtesting --export trades --export-filename=backtest_teststrategy.json
|
freqtrade backtesting --export trades --export-filename=backtest_samplestrategy.json
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Running backtest with smaller testset
|
Please also read about the [strategy startup period](strategy-customization.md#strategy-startup-period).
|
||||||
|
|
||||||
Use the `--timerange` argument to change how much of the testset
|
#### Supplying custom fee value
|
||||||
you want to use. The last N ticks/timeframes will be used.
|
|
||||||
|
|
||||||
Example:
|
Sometimes your account has certain fee rebates (fee reductions starting with a certain account size or monthly volume), which are not visible to ccxt.
|
||||||
|
To account for this in backtesting, you can use `--fee 0.001` to supply this value to backtesting.
|
||||||
|
This fee must be a percentage, and will be applied twice (once for trade entry, and once for trade exit).
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade 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 directory `user_data/data/binance` and copy `pairs.json` in that directory.
|
|
||||||
- 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 directory than the exchange specific default, use `--datadir 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 directory, 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.
|
|
||||||
- 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 other options.
|
|
||||||
|
|
||||||
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.
|
||||||
@@ -176,11 +151,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,
|
||||||
@@ -190,22 +166,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": {
|
||||||
@@ -214,22 +184,39 @@ 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
|
### Further backtest-result analysis
|
||||||
|
|
||||||
To further analyze your backtest results, you can [export the trades](#exporting-trades-to-file).
|
To further analyze your backtest results, you can [export the trades](#exporting-trades-to-file).
|
||||||
You can then load the trades to perform further analysis as shown in our [data analysis](data-analysis.md#backtesting) backtesting section.
|
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 directory.
|
All listed Strategies need to be in the same directory.
|
||||||
|
|
||||||
@@ -237,9 +224,9 @@ All listed Strategies need to be in the same directory.
|
|||||||
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,79 +2,109 @@
|
|||||||
|
|
||||||
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:
|
!!! Note
|
||||||
If you've used `setup.sh`, don't forget to activate your virtual environment (`source .env/bin/activate`) before running freqtrade commands.
|
If you've used `setup.sh`, don't forget to activate your virtual environment (`source .env/bin/activate`) before running freqtrade commands.
|
||||||
|
|
||||||
|
|
||||||
## Bot commands
|
## Bot commands
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade [-h] [-v] [--logfile FILE] [--version] [-c PATH] [-d PATH]
|
usage: freqtrade [-h] [-V]
|
||||||
[-s NAME] [--strategy-path PATH] [--db-url PATH]
|
{trade,backtesting,edge,hyperopt,create-userdir,list-exchanges,list-timeframes,download-data,plot-dataframe,plot-profit}
|
||||||
[--sd-notify]
|
...
|
||||||
{backtesting,edge,hyperopt} ...
|
|
||||||
|
|
||||||
Free, open source crypto trading bot
|
Free, open source crypto trading bot
|
||||||
|
|
||||||
positional arguments:
|
positional arguments:
|
||||||
{backtesting,edge,hyperopt}
|
{trade,backtesting,edge,hyperopt,create-userdir,list-exchanges,list-timeframes,download-data,plot-dataframe,plot-profit}
|
||||||
|
trade Trade module.
|
||||||
backtesting Backtesting module.
|
backtesting Backtesting module.
|
||||||
edge Edge module.
|
edge Edge module.
|
||||||
hyperopt Hyperopt module.
|
hyperopt Hyperopt module.
|
||||||
|
create-userdir Create user-data directory.
|
||||||
|
list-exchanges Print available exchanges.
|
||||||
|
list-timeframes Print available ticker intervals (timeframes) for the
|
||||||
|
exchange.
|
||||||
|
download-data Download backtesting data.
|
||||||
|
plot-dataframe Plot candles with indicators.
|
||||||
|
plot-profit Generate plot showing profits.
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
|
-V, --version show program's version number and exit
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
### Bot trading commands
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade trade [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||||
|
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||||
|
[--db-url PATH] [--sd-notify] [--dry-run]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--db-url PATH Override trades database URL, this is useful in custom
|
||||||
|
deployments (default: `sqlite:///tradesv3.sqlite` for
|
||||||
|
Live Run mode, `sqlite://` for Dry Run).
|
||||||
|
--sd-notify Notify systemd service manager.
|
||||||
|
--dry-run Enforce dry-run for trading (removes Exchange secrets
|
||||||
|
and simulates trades).
|
||||||
|
|
||||||
|
Common arguments:
|
||||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
--logfile FILE Log to the file specified
|
--logfile FILE Log to the file specified.
|
||||||
-V, --version show program's version number and exit
|
-V, --version show program's version number and exit
|
||||||
-c PATH, --config PATH
|
-c PATH, --config PATH
|
||||||
Specify configuration file (default: None). Multiple
|
Specify configuration file (default: `config.json`).
|
||||||
--config options may be used. Can be set to '-' to
|
Multiple --config options may be used. Can be set to
|
||||||
read config from stdin.
|
`-` 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.
|
||||||
|
|
||||||
|
Strategy arguments:
|
||||||
-s NAME, --strategy NAME
|
-s NAME, --strategy NAME
|
||||||
Specify strategy class name (default:
|
Specify strategy class name which will be used by the
|
||||||
DefaultStrategy).
|
bot.
|
||||||
--strategy-path PATH Specify additional strategy lookup path.
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
--db-url PATH Override trades database URL, this is useful if
|
|
||||||
dry_run is enabled or in custom deployments (default:
|
|
||||||
None).
|
|
||||||
--sd-notify Notify systemd service manager.
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### How to use a different configuration file?
|
### How to specify which configuration file be used?
|
||||||
|
|
||||||
The bot allows you to select which configuration 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
|
||||||
freqtrade -c path/far/far/away/config.json
|
freqtrade trade -c path/far/far/away/config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Per default, the bot loads the `config.json` configuration file from the current
|
||||||
|
working directory.
|
||||||
|
|
||||||
### How to use multiple configuration files?
|
### How to use multiple configuration files?
|
||||||
|
|
||||||
The bot allows you to use multiple configuration files by specifying multiple
|
The bot allows you to use multiple configuration files by specifying multiple
|
||||||
`-c/--config` configuration options in the command line. Configuration parameters
|
`-c/--config` options in the command line. Configuration parameters
|
||||||
defined in the last configuration file override parameters with the same name
|
defined in the latter configuration files override parameters with the same name
|
||||||
defined in the previous configuration file specified in the command line.
|
defined in the previous configuration files specified in the command line earlier.
|
||||||
|
|
||||||
For example, you can make a separate configuration file with your key and secrete
|
For example, you can make a separate configuration file with your key and secret
|
||||||
for the Exchange you use for trading, specify default configuration file with
|
for the Exchange you use for trading, specify default configuration file with
|
||||||
empty key and secrete values while running in the Dry Mode (which does not actually
|
empty key and secret values while running in the Dry Mode (which does not actually
|
||||||
require them):
|
require them):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade -c ./config.json
|
freqtrade trade -c ./config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
and specify both configuration files when running in the normal Live Trade Mode:
|
and specify both configuration files when running in the normal Live Trade Mode:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade -c ./config.json -c path/to/secrets/keys.config.json
|
freqtrade trade -c ./config.json -c path/to/secrets/keys.config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
This could help you hide your private Exchange key and Exchange secrete on you local machine
|
This could help you hide your private Exchange key and Exchange secret on you local machine
|
||||||
by setting appropriate file permissions for the file which contains actual secrets and, additionally,
|
by setting appropriate file permissions for the file which contains actual secrets and, additionally,
|
||||||
prevent unintended disclosure of sensitive private data when you publish examples
|
prevent unintended disclosure of sensitive private data when you publish examples
|
||||||
of your configuration in the project issues or in the Internet.
|
of your configuration in the project issues or in the Internet.
|
||||||
@@ -82,6 +112,29 @@ of your configuration in the project issues or in the Internet.
|
|||||||
See more details on this technique with examples in the documentation page on
|
See more details on this technique with examples in the documentation page on
|
||||||
[configuration](configuration.md).
|
[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.
|
||||||
@@ -97,7 +150,7 @@ In `user_data/strategies` you have a file `my_awesome_strategy.py` which has
|
|||||||
a strategy class called `AwesomeStrategy` to load it:
|
a strategy class called `AwesomeStrategy` to load it:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade --strategy AwesomeStrategy
|
freqtrade trade --strategy AwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
If the bot does not find your strategy file, it will display in an error
|
If the bot does not find your strategy file, it will display in an error
|
||||||
@@ -110,8 +163,9 @@ Learn more about strategy file in
|
|||||||
|
|
||||||
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 directory!):
|
checked before the default locations (The passed path must be a directory!):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade --strategy AwesomeStrategy --strategy-path /some/directory
|
freqtrade trade --strategy AwesomeStrategy --strategy-path /some/directory
|
||||||
```
|
```
|
||||||
|
|
||||||
#### How to install a strategy?
|
#### How to install a strategy?
|
||||||
@@ -127,7 +181,7 @@ using `--db-url`. This can also be used to specify a custom database
|
|||||||
in production mode. Example command:
|
in production mode. Example command:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite
|
freqtrade trade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite
|
||||||
```
|
```
|
||||||
|
|
||||||
## Backtesting commands
|
## Backtesting commands
|
||||||
@@ -135,82 +189,15 @@ freqtrade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite
|
|||||||
Backtesting also uses the config specified via `-c/--config`.
|
Backtesting also uses the config specified via `-c/--config`.
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade backtesting [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
[--max_open_trades MAX_OPEN_TRADES]
|
[-d PATH] [--userdir PATH] [-s NAME]
|
||||||
[--stake_amount STAKE_AMOUNT] [-r] [--eps] [--dmmp]
|
[--strategy-path PATH] [-i TICKER_INTERVAL]
|
||||||
[-l]
|
[--timerange TIMERANGE] [--max_open_trades INT]
|
||||||
|
[--stake_amount STAKE_AMOUNT] [--fee FLOAT]
|
||||||
|
[--eps] [--dmmp]
|
||||||
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
||||||
[--export EXPORT] [--export-filename PATH]
|
[--export EXPORT] [--export-filename PATH]
|
||||||
|
|
||||||
optional arguments:
|
|
||||||
-h, --help show this help message and exit
|
|
||||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
|
||||||
Specify ticker interval (1m, 5m, 30m, 1h, 1d).
|
|
||||||
--timerange TIMERANGE
|
|
||||||
Specify what timerange of data to use.
|
|
||||||
--max_open_trades MAX_OPEN_TRADES
|
|
||||||
Specify max_open_trades to use.
|
|
||||||
--stake_amount STAKE_AMOUNT
|
|
||||||
Specify stake_amount.
|
|
||||||
-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 optimization commands with up-to-date data.
|
|
||||||
--eps, --enable-position-stacking
|
|
||||||
Allow buying the same pair multiple times (position
|
|
||||||
stacking).
|
|
||||||
--dmmp, --disable-max-market-positions
|
|
||||||
Disable applying `max_open_trades` during backtest
|
|
||||||
(same as setting `max_open_trades` to a very high
|
|
||||||
number).
|
|
||||||
-l, --live Use live data.
|
|
||||||
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
|
|
||||||
Provide a commaseparated list of strategies to
|
|
||||||
backtest Please note that ticker-interval needs to be
|
|
||||||
set either in config or via command line. When using
|
|
||||||
this together with --export trades, the strategy-name
|
|
||||||
is injected into the filename (so backtest-data.json
|
|
||||||
becomes backtest-data-DefaultStrategy.json
|
|
||||||
--export EXPORT Export backtest results, argument are: trades. Example
|
|
||||||
--export=trades
|
|
||||||
--export-filename PATH
|
|
||||||
Save backtest results to this filename requires
|
|
||||||
--export to be set as well Example --export-
|
|
||||||
filename=user_data/backtest_data/backtest_today.json
|
|
||||||
(default: user_data/backtest_data/backtest-
|
|
||||||
result.json)
|
|
||||||
```
|
|
||||||
|
|
||||||
### How to use **--refresh-pairs-cached** parameter?
|
|
||||||
|
|
||||||
The first time your run Backtesting, it will take the pairs you have
|
|
||||||
set in your config file and download data from the Exchange.
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
To optimize your strategy, you can use hyperopt parameter hyperoptimization
|
|
||||||
to find optimal parameter values for your stategy.
|
|
||||||
|
|
||||||
```
|
|
||||||
usage: freqtrade hyperopt [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
|
||||||
[--max_open_trades INT]
|
|
||||||
[--stake_amount STAKE_AMOUNT] [-r]
|
|
||||||
[--customhyperopt NAME] [--hyperopt-path PATH]
|
|
||||||
[--eps] [-e INT]
|
|
||||||
[-s {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...]]
|
|
||||||
[--dmmp] [--print-all] [-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
|
||||||
@@ -222,20 +209,98 @@ optional arguments:
|
|||||||
Specify max_open_trades to use.
|
Specify max_open_trades to use.
|
||||||
--stake_amount STAKE_AMOUNT
|
--stake_amount STAKE_AMOUNT
|
||||||
Specify stake_amount.
|
Specify stake_amount.
|
||||||
-r, --refresh-pairs-cached
|
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
|
||||||
Refresh the pairs files in tests/testdata with the
|
entry and exit).
|
||||||
latest data from the exchange. Use it if you want to
|
--eps, --enable-position-stacking
|
||||||
run your optimization commands with up-to-date data.
|
Allow buying the same pair multiple times (position
|
||||||
--customhyperopt NAME
|
stacking).
|
||||||
Specify hyperopt class name (default:
|
--dmmp, --disable-max-market-positions
|
||||||
`DefaultHyperOpts`).
|
Disable applying `max_open_trades` during backtest
|
||||||
--hyperopt-path PATH Specify additional lookup path for Hyperopts and
|
(same as setting `max_open_trades` to a very high
|
||||||
|
number).
|
||||||
|
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
|
||||||
|
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`
|
||||||
|
--export EXPORT Export backtest results, argument are: trades.
|
||||||
|
Example: `--export=trades`
|
||||||
|
--export-filename PATH
|
||||||
|
Save backtest results to the file with this filename.
|
||||||
|
Requires `--export` to be set as well. Example:
|
||||||
|
`--export-filename=user_data/backtest_results/backtest
|
||||||
|
_today.json`
|
||||||
|
|
||||||
|
Common arguments:
|
||||||
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
|
--logfile FILE Log to the file specified.
|
||||||
|
-V, --version show program's version number and exit
|
||||||
|
-c PATH, --config PATH
|
||||||
|
Specify configuration file (default: `config.json`).
|
||||||
|
Multiple --config options may be used. Can be set to
|
||||||
|
`-` to read config from stdin.
|
||||||
|
-d PATH, --datadir PATH
|
||||||
|
Path to directory with historical backtesting data.
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
|
||||||
|
Strategy arguments:
|
||||||
|
-s NAME, --strategy NAME
|
||||||
|
Specify strategy class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
### Getting historic data for backtesting
|
||||||
|
|
||||||
|
The first time your run Backtesting, you will need to download some historic data first.
|
||||||
|
This can be accomplished by using `freqtrade download-data`.
|
||||||
|
Check the corresponding [Data Downloading](data-download.md) section for more details
|
||||||
|
|
||||||
|
## Hyperopt commands
|
||||||
|
|
||||||
|
To optimize your strategy, you can use hyperopt parameter hyperoptimization
|
||||||
|
to find optimal parameter values for your stategy.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||||
|
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||||
|
[-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
||||||
|
[--max_open_trades INT]
|
||||||
|
[--stake_amount STAKE_AMOUNT] [--fee FLOAT]
|
||||||
|
[--hyperopt NAME] [--hyperopt-path PATH] [--eps]
|
||||||
|
[-e INT]
|
||||||
|
[--spaces {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:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||||
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
|
`1d`).
|
||||||
|
--timerange TIMERANGE
|
||||||
|
Specify what timerange of data to use.
|
||||||
|
--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).
|
||||||
|
--hyperopt NAME Specify hyperopt class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--hyperopt-path PATH Specify additional lookup path for Hyperopt and
|
||||||
Hyperopt Loss functions.
|
Hyperopt Loss functions.
|
||||||
--eps, --enable-position-stacking
|
--eps, --enable-position-stacking
|
||||||
Allow buying the same pair multiple times (position
|
Allow buying the same pair multiple times (position
|
||||||
stacking).
|
stacking).
|
||||||
-e INT, --epochs INT Specify number of epochs (default: 100).
|
-e INT, --epochs INT Specify number of epochs (default: 100).
|
||||||
-s {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...], --spaces {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...]
|
--spaces {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...]
|
||||||
Specify which parameters to hyperopt. Space-separated
|
Specify which parameters to hyperopt. Space-separated
|
||||||
list. Default: `all`.
|
list. Default: `all`.
|
||||||
--dmmp, --disable-max-market-positions
|
--dmmp, --disable-max-market-positions
|
||||||
@@ -243,6 +308,9 @@ optional arguments:
|
|||||||
(same as setting `max_open_trades` to a very high
|
(same as setting `max_open_trades` to a very high
|
||||||
number).
|
number).
|
||||||
--print-all Print all results, not only the best ones.
|
--print-all Print all results, not only the best ones.
|
||||||
|
--no-color Disable colorization of hyperopt results. May be
|
||||||
|
useful if you are redirecting output to a file.
|
||||||
|
--print-json Print best result detailization in JSON format.
|
||||||
-j JOBS, --job-workers JOBS
|
-j JOBS, --job-workers JOBS
|
||||||
The number of concurrently running jobs for
|
The number of concurrently running jobs for
|
||||||
hyperoptimization (hyperopt worker processes). If -1
|
hyperoptimization (hyperopt worker processes). If -1
|
||||||
@@ -256,43 +324,82 @@ optional arguments:
|
|||||||
--continue Continue hyperopt from previous runs. By default,
|
--continue Continue hyperopt from previous runs. By default,
|
||||||
temporary files will be removed and hyperopt will
|
temporary files will be removed and hyperopt will
|
||||||
start from scratch.
|
start from scratch.
|
||||||
--hyperopt-loss NAME
|
--hyperopt-loss NAME Specify the class name of the hyperopt loss function
|
||||||
Specify the class name of the hyperopt loss function
|
|
||||||
class (IHyperOptLoss). Different functions can
|
class (IHyperOptLoss). Different functions can
|
||||||
generate completely different results, since the
|
generate completely different results, since the
|
||||||
target for optimization is different. (default:
|
target for optimization is different. Built-in
|
||||||
|
Hyperopt-loss-functions are: DefaultHyperOptLoss,
|
||||||
|
OnlyProfitHyperOptLoss, SharpeHyperOptLoss (default:
|
||||||
`DefaultHyperOptLoss`).
|
`DefaultHyperOptLoss`).
|
||||||
|
|
||||||
|
Common arguments:
|
||||||
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
|
--logfile FILE Log to the file specified.
|
||||||
|
-V, --version show program's version number and exit
|
||||||
|
-c PATH, --config PATH
|
||||||
|
Specify configuration file (default: `config.json`).
|
||||||
|
Multiple --config options may be used. Can be set to
|
||||||
|
`-` to read config from stdin.
|
||||||
|
-d PATH, --datadir PATH
|
||||||
|
Path to directory with historical backtesting data.
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
|
||||||
|
Strategy arguments:
|
||||||
|
-s NAME, --strategy NAME
|
||||||
|
Specify strategy class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Edge commands
|
## Edge commands
|
||||||
|
|
||||||
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: freqtrade edge [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
usage: freqtrade edge [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||||
[--max_open_trades MAX_OPEN_TRADES]
|
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||||
[--stake_amount STAKE_AMOUNT] [-r]
|
[-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
||||||
[--stoplosses STOPLOSS_RANGE]
|
[--max_open_trades INT] [--stake_amount STAKE_AMOUNT]
|
||||||
|
[--fee FLOAT] [--stoplosses STOPLOSS_RANGE]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||||
Specify ticker interval (1m, 5m, 30m, 1h, 1d).
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
|
`1d`).
|
||||||
--timerange TIMERANGE
|
--timerange TIMERANGE
|
||||||
Specify what timerange of data to use.
|
Specify what timerange of data to use.
|
||||||
--max_open_trades MAX_OPEN_TRADES
|
--max_open_trades INT
|
||||||
Specify max_open_trades to use.
|
Specify max_open_trades to use.
|
||||||
--stake_amount STAKE_AMOUNT
|
--stake_amount STAKE_AMOUNT
|
||||||
Specify stake_amount.
|
Specify stake_amount.
|
||||||
-r, --refresh-pairs-cached
|
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
|
||||||
Refresh the pairs files in tests/testdata with the
|
entry and exit).
|
||||||
latest data from the exchange. Use it if you want to
|
|
||||||
run your optimization commands with up-to-date data.
|
|
||||||
--stoplosses STOPLOSS_RANGE
|
--stoplosses STOPLOSS_RANGE
|
||||||
Defines a range of stoploss against which edge will
|
Defines a range of stoploss values against which edge
|
||||||
assess the strategy the format is "min,max,step"
|
will assess the strategy. The format is "min,max,step"
|
||||||
(without any space).example:
|
(without any space). Example:
|
||||||
--stoplosses=-0.01,-0.1,-0.001
|
`--stoplosses=-0.01,-0.1,-0.001`
|
||||||
|
|
||||||
|
Common arguments:
|
||||||
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
|
--logfile FILE Log to the file specified.
|
||||||
|
-V, --version show program's version number and exit
|
||||||
|
-c PATH, --config PATH
|
||||||
|
Specify configuration file (default: `config.json`).
|
||||||
|
Multiple --config options may be used. Can be set to
|
||||||
|
`-` to read config from stdin.
|
||||||
|
-d PATH, --datadir PATH
|
||||||
|
Path to directory with historical backtesting data.
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
|
||||||
|
Strategy arguments:
|
||||||
|
-s NAME, --strategy NAME
|
||||||
|
Specify strategy class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
```
|
```
|
||||||
|
|
||||||
To understand edge and how to read the results, please read the [edge documentation](edge.md).
|
To understand edge and how to read the results, please read the [edge documentation](edge.md).
|
||||||
|
|||||||
@@ -1,112 +1,152 @@
|
|||||||
# 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.
|
||||||
|
|
||||||
| Command | Default | Description |
|
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.
|
||||||
|----------|---------|-------------|
|
|
||||||
| `max_open_trades` | 3 | **Required.** Number of trades open your bot will have. If -1 then it is ignored (i.e. potentially unlimited open trades)
|
## Configuration parameters
|
||||||
| `stake_currency` | BTC | **Required.** Crypto-currency used for trading. [Strategy Override](#parameters-in-the-strategy).
|
|
||||||
| `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. [Strategy Override](#parameters-in-the-strategy).
|
The table below will list all configuration parameters available.
|
||||||
| `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, 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).
|
Freqtrade can also load many options via command line (CLI) arguments (check out the commands `--help` output for details).
|
||||||
| `fiat_display_currency` | USD | **Required.** Fiat currency used to show your profits. More information below.
|
The prevelance for all Options is as follows:
|
||||||
| `dry_run` | true | **Required.** Define if the bot must be in Dry-run or production mode.
|
|
||||||
| `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.
|
- CLI arguments override any other option
|
||||||
| `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).
|
- Configuration files are used in sequence (last file wins), and override Strategy configurations.
|
||||||
| `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).
|
- 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.
|
||||||
| `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` | 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).
|
Mandatory parameters are marked as **Required**, which means that they are required to be set in one of the possible ways.
|
||||||
| `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).
|
| Command | Description |
|
||||||
| `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.
|
| `max_open_trades` | **Required.** Number of trades open your bot will have. If -1 then it is ignored (i.e. potentially unlimited open trades).<br> ***Datatype:*** *Positive integer or -1.*
|
||||||
| `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.
|
| `stake_currency` | **Required.** Crypto-currency used for trading. [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *String*
|
||||||
| `bid_strategy.ask_last_balance` | 0.0 | **Required.** Set the bidding price. More information [below](#understand-ask_last_balance).
|
| `stake_amount` | **Required.** Amount of crypto-currency your bot will use for each trade. Set it to `"unlimited"` to allow the bot to use all available balance. [More information below](#understand-stake_amount). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *Positive float or `"unlimited"`.*
|
||||||
| `bid_strategy.use_order_book` | false | Allows buying of pair using the rates in Order Book Bids.
|
| `amount_reserve_percent` | Reserve some amount in min pair stake amount. The bot will reserve `amount_reserve_percent` + stoploss value when calculating min pair stake amount in order to avoid possible trade refusals. <br>*Defaults to `0.05` (5%).* <br> ***Datatype:*** *Positive Float as ratio.*
|
||||||
| `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.
|
| `ticker_interval` | The ticker interval to use (e.g `1m`, `5m`, `15m`, `30m`, `1h` ...). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *String*
|
||||||
| `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.
|
| `fiat_display_currency` | Fiat currency used to show your profits. [More information below](#what-values-can-be-used-for-fiat_display_currency). <br> ***Datatype:*** *String*
|
||||||
| `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.
|
| `dry_run` | **Required.** Define if the bot must be in Dry Run or production mode. <br>*Defaults to `true`.* <br> ***Datatype:*** *Boolean*
|
||||||
| `ask_strategy.use_order_book` | false | Allows selling of open traded pair using the rates in Order Book Asks.
|
| `dry_run_wallet` | Overrides the default amount of 999.9 stake currency units in the wallet used by the bot running in the Dry Run mode if you need it for any reason. <br> ***Datatype:*** *Float*
|
||||||
| `ask_strategy.order_book_min` | 0 | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
| `process_only_new_candles` | Enable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> ***Datatype:*** *Boolean*
|
||||||
| `ask_strategy.order_book_max` | 0 | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
| `minimal_roi` | **Required.** Set the threshold in percent the bot will use to sell a trade. [More information below](#understand-minimal_roi). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *Dict*
|
||||||
| `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).
|
| `stoploss` | **Required.** Value of the stoploss in percent used by the bot. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *Float (as ratio)*
|
||||||
| `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).
|
| `trailing_stop` | Enables trailing stoploss (based on `stoploss` in either configuration or strategy file). More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *Boolean*
|
||||||
| `exchange.name` | | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename).
|
| `trailing_stop_positive` | Changes stoploss once profit has been reached. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *Float*
|
||||||
| `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.
|
| `trailing_stop_positive_offset` | Offset on when to apply `trailing_stop_positive`. Percentage value which should be positive. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0` (no offset).* <br> ***Datatype:*** *Float*
|
||||||
| `exchange.key` | '' | API key to use for the exchange. Only required when you are in production mode.
|
| `trailing_only_offset_is_reached` | Only apply trailing stoploss when the offset is reached. [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> ***Datatype:*** *Boolean*
|
||||||
| `exchange.secret` | '' | API secret to use for the exchange. Only required when you are in production mode.
|
| `unfilledtimeout.buy` | **Required.** How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled. <br> ***Datatype:*** *Integer*
|
||||||
| `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)).
|
| `unfilledtimeout.sell` | **Required.** How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled. <br> ***Datatype:*** *Integer*
|
||||||
| `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)).
|
| `bid_strategy.ask_last_balance` | **Required.** Set the bidding price. More information [below](#understand-ask_last_balance).
|
||||||
| `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)
|
| `bid_strategy.use_order_book` | Enable buying using the rates in Order Book Bids. <br> ***Datatype:*** *Boolean*
|
||||||
| `exchange.ccxt_async_config` | None | Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation)
|
| `bid_strategy.order_book_top` | Bot will use the top N rate in Order Book Bids. I.e. a value of 2 will allow the bot to pick the 2nd bid rate in Order Book Bids. *Defaults to `1`.* <br> ***Datatype:*** *Positive Integer*
|
||||||
| `exchange.markets_refresh_interval` | 60 | The interval in minutes in which markets are reloaded.
|
| `bid_strategy. check_depth_of_market.enabled` | Do not buy if the difference of buy orders and sell orders is met in Order Book. <br>*Defaults to `false`.* <br> ***Datatype:*** *Boolean*
|
||||||
| `edge` | false | Please refer to [edge configuration document](edge.md) for detailed explanation.
|
| `bid_strategy. check_depth_of_market.bids_to_ask_delta` | The % difference of buy orders and sell orders found in Order Book. A value lesser than 1 means sell orders is greater, while value greater than 1 means buy orders is higher. *Defaults to `0`.* <br> ***Datatype:*** *Float (as ratio)*
|
||||||
| `experimental.use_sell_signal` | false | Use your sell strategy in addition of the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy).
|
| `ask_strategy.use_order_book` | Enable selling of open trades using Order Book Asks. <br> ***Datatype:*** *Boolean*
|
||||||
| `experimental.sell_profit_only` | false | Waits until you have made a positive profit before taking a sell decision. [Strategy Override](#parameters-in-the-strategy).
|
| `ask_strategy.order_book_min` | Bot will scan from the top min to max Order Book Asks searching for a profitable rate. <br>*Defaults to `1`.* <br> ***Datatype:*** *Positive Integer*
|
||||||
| `experimental.ignore_roi_if_buy_signal` | false | Does not sell if the buy-signal is still active. Takes preference over `minimal_roi` and `use_sell_signal`. [Strategy Override](#parameters-in-the-strategy).
|
| `ask_strategy.order_book_max` | Bot will scan from the top min to max Order Book Asks searching for a profitable rate. <br>*Defaults to `1`.* <br> ***Datatype:*** *Positive Integer*
|
||||||
| `pairlist.method` | StaticPairList | Use static or dynamic volume-based pairlist. [More information below](#dynamic-pairlists).
|
| `ask_strategy.use_sell_signal` | Use sell signals produced by the strategy in addition to the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `true`.* <br> ***Datatype:*** *Boolean*
|
||||||
| `pairlist.config` | None | Additional configuration for dynamic pairlists. [More information below](#dynamic-pairlists).
|
| `ask_strategy.sell_profit_only` | Wait until the bot makes a positive profit before taking a sell decision. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> ***Datatype:*** *Boolean*
|
||||||
| `telegram.enabled` | true | **Required.** Enable or not the usage of Telegram.
|
| `ask_strategy.ignore_roi_if_buy_signal` | Do not sell if the buy signal is still active. This setting takes preference over `minimal_roi` and `use_sell_signal`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> ***Datatype:*** *Boolean*
|
||||||
| `telegram.token` | token | Your Telegram bot token. Only required if `telegram.enabled` is `true`.
|
| `order_types` | Configure order-types depending on the action (`"buy"`, `"sell"`, `"stoploss"`, `"stoploss_on_exchange"`). [More information below](#understand-order_types). [Strategy Override](#parameters-in-the-strategy).<br> ***Datatype:*** *Dict*
|
||||||
| `telegram.chat_id` | chat_id | Your personal Telegram account id. Only required if `telegram.enabled` is `true`.
|
| `order_time_in_force` | Configure time in force for buy and sell orders. [More information below](#understand-order_time_in_force). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *Dict*
|
||||||
| `webhook.enabled` | false | Enable usage of Webhook notifications
|
| `exchange.name` | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename). <br> ***Datatype:*** *String*
|
||||||
| `webhook.url` | false | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details.
|
| `exchange.sandbox` | Use the 'sandbox' version of the exchange, where the exchange provides a sandbox for risk-free integration. See [here](sandbox-testing.md) in more details.<br> ***Datatype:*** *Boolean*
|
||||||
| `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.
|
| `exchange.key` | API key to use for the exchange. Only required when you are in production mode. **Keep it in secret, do not disclose publicly.** <br> ***Datatype:*** *String*
|
||||||
| `webhook.webhooksell` | false | Payload to send on sell. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details.
|
| `exchange.secret` | API secret to use for the exchange. Only required when you are in production mode. **Keep it in secret, do not disclose publicly.** <br> ***Datatype:*** *String*
|
||||||
| `webhook.webhookstatus` | false | Payload to send on status calls. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details.
|
| `exchange.password` | API password to use for the exchange. Only required when you are in production mode and for exchanges that use password for API requests. **Keep it in secret, do not disclose publicly.** <br> ***Datatype:*** *String*
|
||||||
| `db_url` | `sqlite:///tradesv3.sqlite`| Declares database URL to use. NOTE: This defaults to `sqlite://` if `dry_run` is `True`.
|
| `exchange.pair_whitelist` | List of pairs to use by the bot for trading and to check for potential trades during backtesting. Not used by VolumePairList (see [below](#dynamic-pairlists)). <br> ***Datatype:*** *List*
|
||||||
| `initial_state` | running | Defines the initial application state. More information below.
|
| `exchange.pair_blacklist` | List of pairs the bot must absolutely avoid for trading and backtesting (see [below](#dynamic-pairlists)). <br> ***Datatype:*** *List*
|
||||||
| `forcebuy_enable` | false | Enables the RPC Commands to force a buy. More information below.
|
| `exchange.ccxt_config` | Additional CCXT parameters passed to the regular ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> ***Datatype:*** *Dict*
|
||||||
| `strategy` | DefaultStrategy | Defines Strategy class to use.
|
| `exchange.ccxt_async_config` | Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> ***Datatype:*** *Dict*
|
||||||
| `strategy_path` | null | Adds an additional strategy lookup path (must be a directory).
|
| `exchange.markets_refresh_interval` | The interval in minutes in which markets are reloaded. <br>*Defaults to `60` minutes.* <br> ***Datatype:*** *Positive Integer*
|
||||||
| `internals.process_throttle_secs` | 5 | **Required.** Set the process throttle. Value in second.
|
| `edge.*` | Please refer to [edge configuration document](edge.md) for detailed explanation.
|
||||||
| `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.
|
| `experimental.block_bad_exchanges` | Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now. <br>*Defaults to `true`.* <br> ***Datatype:*** *Boolean*
|
||||||
| `logfile` | | Specify Logfile. Uses a rolling strategy of 10 files, with 1Mb per file.
|
| `pairlists` | Define one or more pairlists to be used. [More information below](#dynamic-pairlists). <br>*Defaults to `StaticPairList`.* <br> ***Datatype:*** *List of Dicts*
|
||||||
|
| `telegram.enabled` | Enable the usage of Telegram. <br> ***Datatype:*** *Boolean*
|
||||||
|
| `telegram.token` | Your Telegram bot token. Only required if `telegram.enabled` is `true`. **Keep it in secret, do not disclose publicly.** <br> ***Datatype:*** *String*
|
||||||
|
| `telegram.chat_id` | Your personal Telegram account id. Only required if `telegram.enabled` is `true`. **Keep it in secret, do not disclose publicly.** <br> ***Datatype:*** *String*
|
||||||
|
| `webhook.enabled` | Enable usage of Webhook notifications <br> ***Datatype:*** *Boolean*
|
||||||
|
| `webhook.url` | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> ***Datatype:*** *String*
|
||||||
|
| `webhook.webhookbuy` | Payload to send on buy. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details. <br> ***Datatype:*** *String*
|
||||||
|
| `webhook.webhooksell` | Payload to send on sell. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details. <br> ***Datatype:*** *String*
|
||||||
|
| `webhook.webhookstatus` | Payload to send on status calls. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details. <br> ***Datatype:*** *String*
|
||||||
|
| `api_server.enabled` | Enable usage of API Server. See the [API Server documentation](rest-api.md) for more details. <br> ***Datatype:*** *Boolean*
|
||||||
|
| `api_server.listen_ip_address` | Bind IP address. See the [API Server documentation](rest-api.md) for more details. <br> ***Datatype:*** *IPv4*
|
||||||
|
| `api_server.listen_port` | Bind Port. See the [API Server documentation](rest-api.md) for more details. <br> ***Datatype:*** *Integer between 1024 and 65535*
|
||||||
|
| `api_server.username` | Username for API server. See the [API Server documentation](rest-api.md) for more details. **Keep it in secret, do not disclose publicly.**<br> ***Datatype:*** *String*
|
||||||
|
| `api_server.password` | Password for API server. See the [API Server documentation](rest-api.md) for more details. **Keep it in secret, do not disclose publicly.**<br> ***Datatype:*** *String*
|
||||||
|
| `db_url` | Declares database URL to use. NOTE: This defaults to `sqlite://` if `dry_run` is `true`, and to `sqlite:///tradesv3.sqlite` for production instances. <br> ***Datatype:*** *String, SQLAlchemy connect string*
|
||||||
|
| `initial_state` | Defines the initial application state. More information below. <br>*Defaults to `stopped`.* <br> ***Datatype:*** *Enum, either `stopped` or `running`*
|
||||||
|
| `forcebuy_enable` | Enables the RPC Commands to force a buy. More information below. <br> ***Datatype:*** *Boolean*
|
||||||
|
| `strategy` | **Required** Defines Strategy class to use. Recommended to be set via `--strategy NAME`. <br> ***Datatype:*** *ClassName*
|
||||||
|
| `strategy_path` | Adds an additional strategy lookup path (must be a directory). <br> ***Datatype:*** *String*
|
||||||
|
| `internals.process_throttle_secs` | Set the process throttle. Value in second. <br>*Defaults to `5` seconds.* <br> ***Datatype:*** *Positive Integer*
|
||||||
|
| `internals.heartbeat_interval` | Print heartbeat message every N seconds. Set to 0 to disable heartbeat messages. <br>*Defaults to `60` seconds.* <br> ***Datatype:*** *Positive Integer or 0*
|
||||||
|
| `internals.sd_notify` | Enables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See [here](installation.md#7-optional-configure-freqtrade-as-a-systemd-service) for more details. <br> ***Datatype:*** *Boolean*
|
||||||
|
| `logfile` | Specifies logfile name. Uses a rolling strategy for log file rotation for 10 files with the 1MB limit per file. <br> ***Datatype:*** *String*
|
||||||
|
| `user_data_dir` | Directory containing user data. <br> *Defaults to `./user_data/`*. <br> ***Datatype:*** *String*
|
||||||
|
|
||||||
### Parameters in the strategy
|
### Parameters in the strategy
|
||||||
|
|
||||||
The following parameters can be set in either configuration file or strategy.
|
The following parameters can be set in either configuration file or strategy.
|
||||||
Values set in the configuration file always overwrite values set in the strategy.
|
Values set in the configuration file always overwrite values set in the strategy.
|
||||||
|
|
||||||
* `stake_currency`
|
|
||||||
* `stake_amount`
|
|
||||||
* `ticker_interval`
|
|
||||||
* `minimal_roi`
|
* `minimal_roi`
|
||||||
|
* `ticker_interval`
|
||||||
* `stoploss`
|
* `stoploss`
|
||||||
* `trailing_stop`
|
* `trailing_stop`
|
||||||
* `trailing_stop_positive`
|
* `trailing_stop_positive`
|
||||||
* `trailing_stop_positive_offset`
|
* `trailing_stop_positive_offset`
|
||||||
|
* `trailing_only_offset_is_reached`
|
||||||
* `process_only_new_candles`
|
* `process_only_new_candles`
|
||||||
* `order_types`
|
* `order_types`
|
||||||
* `order_time_in_force`
|
* `order_time_in_force`
|
||||||
* `use_sell_signal` (experimental)
|
* `stake_currency`
|
||||||
* `sell_profit_only` (experimental)
|
* `stake_amount`
|
||||||
* `ignore_roi_if_buy_signal` (experimental)
|
* `use_sell_signal` (ask_strategy)
|
||||||
|
* `sell_profit_only` (ask_strategy)
|
||||||
|
* `ignore_roi_if_buy_signal` (ask_strategy)
|
||||||
|
|
||||||
### Understand stake_amount
|
### Understand stake_amount
|
||||||
|
|
||||||
The `stake_amount` configuration parameter 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 account an exception is generated.
|
The minimal configuration value is 0.0001. Please check your exchange's trading minimums to avoid problems.
|
||||||
|
|
||||||
|
This setting works in combination with `max_open_trades`. The maximum capital engaged in trades is `stake_amount * max_open_trades`.
|
||||||
|
For example, the bot will at most use (0.05 BTC x 3) = 0.15 BTC, assuming a configuration of `max_open_trades=3` and `stake_amount=0.05`.
|
||||||
|
|
||||||
To allow the bot to trade all the available `stake_currency` in your account set
|
To allow the bot to trade all the available `stake_currency` in your account set
|
||||||
|
|
||||||
```json
|
```json
|
||||||
"stake_amount" : "unlimited",
|
"stake_amount" : "unlimited",
|
||||||
```
|
```
|
||||||
|
|
||||||
In this case a trade amount is calclulated as:
|
In this case a trade amount is calculated as:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
currency_balanse / (max_open_trades - current_open_trades)
|
currency_balance / (max_open_trades - current_open_trades)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Understand minimal_roi
|
### Understand minimal_roi
|
||||||
@@ -170,30 +210,38 @@ end up paying more then would probably have been necessary.
|
|||||||
|
|
||||||
### Understand order_types
|
### Understand order_types
|
||||||
|
|
||||||
The `order_types` configuration parameter contains a dict mapping order-types to
|
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.
|
||||||
market-types as well as stoploss on or off exchange type and stoploss on exchange
|
|
||||||
update interval in seconds. This allows to buy using limit orders, sell using
|
|
||||||
limit-orders, and create stoploss orders using market. It also allows to set the
|
|
||||||
stoploss "on exchange" which means stoploss order would be placed immediately once
|
|
||||||
the buy order is fulfilled. In case stoploss on exchange and `trailing_stop` are
|
|
||||||
both set, then the bot will use `stoploss_on_exchange_interval` to check it periodically
|
|
||||||
and update it if necessary (e.x. in case of trailing stoploss).
|
|
||||||
This can be set in the configuration file or in the strategy.
|
|
||||||
Values set in the configuration file overwrites values set in the strategy.
|
|
||||||
|
|
||||||
If this is configured, all 4 values (`buy`, `sell`, `stoploss` and
|
This allows to buy using limit orders, sell using
|
||||||
`stoploss_on_exchange`) need to be present, otherwise the bot will warn about it and fail to start.
|
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.
|
The below is the default which is used if this is not configured in either strategy or configuration file.
|
||||||
|
|
||||||
|
Since `stoploss_on_exchange` uses limit orders, the exchange needs 2 prices, the stoploss_price and the Limit price.
|
||||||
|
`stoploss` defines the stop-price - and limit should be slightly below this. This defaults to 0.99 / 1%.
|
||||||
|
Calculation example: we bought the asset at 100$.
|
||||||
|
Stop-price is 95$, then limit would be `95 * 0.99 = 94.05$` - so the stoploss will happen between 95$ and 94.05$.
|
||||||
|
|
||||||
Syntax for Strategy:
|
Syntax for Strategy:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
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,
|
||||||
|
"stoploss_on_exchange_limit_ratio": 0.99,
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -203,6 +251,7 @@ Configuration:
|
|||||||
"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
|
||||||
@@ -217,11 +266,13 @@ Configuration:
|
|||||||
!!! Note
|
!!! Note
|
||||||
Stoploss on exchange interval is not mandatory. Do not change its value if you are
|
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
|
unsure of what you are doing. For more information about how stoploss works please
|
||||||
read [the stoploss documentation](stoploss.md).
|
refer to [the stoploss documentation](stoploss.md).
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
In case of stoploss on exchange if the stoploss is cancelled manually then
|
If `stoploss_on_exchange` is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new order.
|
||||||
the bot would recreate one.
|
|
||||||
|
!!! Warning "Warning: stoploss_on_exchange failures"
|
||||||
|
If stoploss on exchange creation fails for some reason, then an "emergency sell" is initiated. By default, this will sell the asset using a market order. The order-type for the emergency-sell can be changed by setting the `emergencysell` value in the `order_types` dictionary - however this is not advised.
|
||||||
|
|
||||||
### Understand order_time_in_force
|
### Understand order_time_in_force
|
||||||
|
|
||||||
@@ -297,7 +348,7 @@ This configuration enables binance, as well as rate limiting to avoid bans from
|
|||||||
Optimal settings for rate limiting depend on the exchange and the size of the whitelist, so an ideal parameter will vary on many other settings.
|
Optimal settings for rate limiting depend on the exchange and the size of the whitelist, so an ideal parameter will vary on many other settings.
|
||||||
We try to provide sensible defaults per exchange where possible, if you encounter bans please make sure that `"enableRateLimit"` is enabled and increase the `"rateLimit"` parameter step by step.
|
We try to provide sensible defaults per exchange where possible, if you encounter bans please make sure that `"enableRateLimit"` is enabled and increase the `"rateLimit"` parameter step by step.
|
||||||
|
|
||||||
#### Advanced FreqTrade Exchange configuration
|
#### Advanced Freqtrade Exchange configuration
|
||||||
|
|
||||||
Advanced options can be configured using the `_ft_has_params` setting, which will override Defaults and exchange-specific behaviours.
|
Advanced options can be configured using the `_ft_has_params` setting, which will override Defaults and exchange-specific behaviours.
|
||||||
|
|
||||||
@@ -336,6 +387,91 @@ The valid values are:
|
|||||||
"BTC", "ETH", "XRP", "LTC", "BCH", "USDT"
|
"BTC", "ETH", "XRP", "LTC", "BCH", "USDT"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Pairlists
|
||||||
|
|
||||||
|
Pairlists define the list of pairs that the bot should trade.
|
||||||
|
There are [`StaticPairList`](#static-pair-list) and dynamic Whitelists available.
|
||||||
|
|
||||||
|
[`PrecisionFilter`](#precision-filter) and [`PriceFilter`](#price-pair-filter) act as filters, removing low-value pairs.
|
||||||
|
|
||||||
|
All pairlists can be chained, and a combination of all pairlists will become your new whitelist. Pairlists are executed in the sequence they are configured. You should always configure either `StaticPairList` or `DynamicPairList` as starting pairlists.
|
||||||
|
|
||||||
|
Inactive markets and blacklisted pairs are always removed from the resulting `pair_whitelist`.
|
||||||
|
|
||||||
|
### Available Pairlists
|
||||||
|
|
||||||
|
* [`StaticPairList`](#static-pair-list) (default, if not configured differently)
|
||||||
|
* [`VolumePairList`](#volume-pair-list)
|
||||||
|
* [`PrecisionFilter`](#precision-filter)
|
||||||
|
* [`PriceFilter`](#price-pair-filter)
|
||||||
|
|
||||||
|
!!! Tip "Testing pairlists"
|
||||||
|
Pairlist configurations can be quite tricky to get right. Best use the [`test-pairlist`](utils.md#test-pairlist) subcommand to test your configuration quickly.
|
||||||
|
|
||||||
|
#### Static Pair List
|
||||||
|
|
||||||
|
By default, the `StaticPairList` method is used, which uses a statically defined pair whitelist from the configuration.
|
||||||
|
|
||||||
|
It uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"pairlists": [
|
||||||
|
{"method": "StaticPairList"}
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Volume Pair List
|
||||||
|
|
||||||
|
`VolumePairList` selects `number_assets` top pairs based on `sort_key`, which can be one of `askVolume`, `bidVolume` and `quoteVolume` and defaults to `quoteVolume`.
|
||||||
|
|
||||||
|
`VolumePairList` considers outputs of previous pairlists unless it's the first configured pairlist, it does not consider `pair_whitelist`, but selects the top assets from all available markets (with matching stake-currency) on the exchange.
|
||||||
|
|
||||||
|
`refresh_period` allows setting the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes).
|
||||||
|
|
||||||
|
```json
|
||||||
|
"pairlists": [{
|
||||||
|
"method": "VolumePairList",
|
||||||
|
"number_assets": 20,
|
||||||
|
"sort_key": "quoteVolume",
|
||||||
|
"refresh_period": 1800,
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Precision Filter
|
||||||
|
|
||||||
|
Filters low-value coins which would not allow setting a stoploss.
|
||||||
|
|
||||||
|
#### Price Pair Filter
|
||||||
|
|
||||||
|
The `PriceFilter` allows filtering of pairs by price.
|
||||||
|
Currently, only `low_price_ratio` is implemented, where a raise of 1 price unit (pip) is below the `low_price_ratio` ratio.
|
||||||
|
This option is disabled by default, and will only apply if set to <> 0.
|
||||||
|
|
||||||
|
Calculation example:
|
||||||
|
Min price precision is 8 decimals. If price is 0.00000011 - one step would be 0.00000012 - which is almost 10% higher than the previous value.
|
||||||
|
|
||||||
|
These pairs are dangerous since it may be impossible to place the desired stoploss - and often result in high losses.
|
||||||
|
|
||||||
|
### Full Pairlist example
|
||||||
|
|
||||||
|
The below example blacklists `BNB/BTC`, uses `VolumePairList` with `20` assets, sorting by `quoteVolume` and applies both [`PrecisionFilter`](#precision-filter) and [`PriceFilter`](#price-pair-filter), filtering all assets where 1 priceunit is > 1%.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"exchange": {
|
||||||
|
"pair_whitelist": [],
|
||||||
|
"pair_blacklist": ["BNB/BTC"]
|
||||||
|
},
|
||||||
|
"pairlists": [
|
||||||
|
{
|
||||||
|
"method": "VolumePairList",
|
||||||
|
"number_assets": 20,
|
||||||
|
"sort_key": "quoteVolume",
|
||||||
|
},
|
||||||
|
{"method": "PrecisionFilter"},
|
||||||
|
{"method": "PriceFilter", "low_price_ratio": 0.01}
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
## Switch to Dry-run mode
|
## Switch to Dry-run mode
|
||||||
|
|
||||||
We recommend starting the bot in the Dry-run mode to see how your bot will
|
We recommend starting the bot in the Dry-run mode to see how your bot will
|
||||||
@@ -351,7 +487,7 @@ creating trades on the exchange.
|
|||||||
"db_url": "sqlite:///tradesv3.dryrun.sqlite",
|
"db_url": "sqlite:///tradesv3.dryrun.sqlite",
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Remove your Exchange API key and secrete (change them by empty values or fake credentials):
|
3. Remove your Exchange API key and secret (change them by empty values or fake credentials):
|
||||||
|
|
||||||
```json
|
```json
|
||||||
"exchange": {
|
"exchange": {
|
||||||
@@ -365,39 +501,6 @@ creating trades on the exchange.
|
|||||||
Once you will be happy with your bot performance running in the Dry-run mode,
|
Once you will be happy with your bot performance running in the Dry-run mode,
|
||||||
you can switch it to production mode.
|
you can switch it to production mode.
|
||||||
|
|
||||||
### Dynamic Pairlists
|
|
||||||
|
|
||||||
Dynamic pairlists select pairs for you based on the logic configured.
|
|
||||||
The bot runs against all pairs (with that stake) on the exchange, and a number of assets
|
|
||||||
(`number_assets`) is selected based on the selected criteria.
|
|
||||||
|
|
||||||
By default, the `StaticPairList` method is used.
|
|
||||||
The Pairlist method is configured as `pair_whitelist` parameter under the `exchange`
|
|
||||||
section of the configuration.
|
|
||||||
|
|
||||||
**Available Pairlist methods:**
|
|
||||||
|
|
||||||
* `StaticPairList`
|
|
||||||
* It uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`.
|
|
||||||
* `VolumePairList`
|
|
||||||
* It selects `number_assets` top pairs based on `sort_key`, which can be one of
|
|
||||||
`askVolume`, `bidVolume` and `quoteVolume`, defaults to `quoteVolume`.
|
|
||||||
* There is a possibility to filter low-value coins that would not allow setting a stop loss
|
|
||||||
(set `precision_filter` parameter to `true` for this).
|
|
||||||
|
|
||||||
Example:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"pairlist": {
|
|
||||||
"method": "VolumePairList",
|
|
||||||
"config": {
|
|
||||||
"number_assets": 20,
|
|
||||||
"sort_key": "quoteVolume",
|
|
||||||
"precision_filter": false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
```
|
|
||||||
|
|
||||||
## Switch to production mode
|
## Switch to production mode
|
||||||
|
|
||||||
In production mode, the bot will engage your money. Be careful, since a wrong
|
In production mode, the bot will engage your money. Be careful, since a wrong
|
||||||
@@ -423,12 +526,14 @@ you run it in production mode.
|
|||||||
"secret": "08a9dc6db3d7b53e1acebd9275677f4b0a04f1a5",
|
"secret": "08a9dc6db3d7b53e1acebd9275677f4b0a04f1a5",
|
||||||
...
|
...
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
If you have an exchange API key yet, [see our tutorial](/pre-requisite).
|
If you have an exchange API key yet, [see our tutorial](/pre-requisite).
|
||||||
|
|
||||||
### Using proxy with FreqTrade
|
You should also make sure to read the [Exchanges](exchanges.md) section of the documentation to be aware of potential configuration details specific to your exchange.
|
||||||
|
|
||||||
|
### Using proxy with Freqtrade
|
||||||
|
|
||||||
To use a proxy with freqtrade, add the kwarg `"aiohttp_trust_env"=true` to the `"ccxt_async_kwargs"` dict in the exchange section of the configuration.
|
To use a proxy with freqtrade, add the kwarg `"aiohttp_trust_env"=true` to the `"ccxt_async_kwargs"` dict in the exchange section of the configuration.
|
||||||
|
|
||||||
@@ -448,14 +553,13 @@ export HTTPS_PROXY="http://addr:port"
|
|||||||
freqtrade
|
freqtrade
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Embedding Strategies
|
||||||
### Embedding Strategies
|
|
||||||
|
|
||||||
FreqTrade provides you with with an easy way to embed the strategy into your configuration file.
|
FreqTrade provides you with with an easy way to embed the strategy into your configuration file.
|
||||||
This is done by utilizing BASE64 encoding and providing this string at the strategy configuration field,
|
This is done by utilizing BASE64 encoding and providing this string at the strategy configuration field,
|
||||||
in your chosen config file.
|
in your chosen config file.
|
||||||
|
|
||||||
#### Encoding a string as BASE64
|
### Encoding a string as BASE64
|
||||||
|
|
||||||
This is a quick example, how to generate the BASE64 string in python
|
This is a quick example, how to generate the BASE64 string in python
|
||||||
|
|
||||||
|
|||||||
@@ -1,42 +1,94 @@
|
|||||||
# Analyzing bot data
|
# Analyzing bot data with Jupyter notebooks
|
||||||
|
|
||||||
After performing backtests, or after running the bot for some time, it will be interesting to analyze the results your bot generated.
|
You can analyze the results of backtests and trading history easily using Jupyter notebooks. Sample notebooks are located at `user_data/notebooks/`.
|
||||||
|
|
||||||
A good way for this is using Jupyter (notebook or lab) - which provides an interactive environment to analyze the data.
|
## Pro tips
|
||||||
|
|
||||||
The following helpers will help you loading the data into Pandas DataFrames, and may also give you some starting points in analyzing the results.
|
* 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.
|
||||||
|
|
||||||
## Backtesting
|
## Fine print
|
||||||
|
|
||||||
To analyze your backtest results, you can [export the trades](#exporting-trades-to-file).
|
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.
|
||||||
You can then load the trades to perform further analysis.
|
|
||||||
|
|
||||||
Freqtrade provides the `load_backtest_data()` helper function to easily load the backtest results, which takes the path to the the backtest-results file as parameter.
|
## 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
|
```python
|
||||||
from freqtrade.data.btanalysis import load_backtest_data
|
import os
|
||||||
df = load_backtest_data("user_data/backtest-result.json")
|
from pathlib import Path
|
||||||
|
|
||||||
# Show value-counts per pair
|
|
||||||
df.groupby("pair")["sell_reason"].value_counts()
|
|
||||||
|
|
||||||
|
# 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())
|
||||||
```
|
```
|
||||||
|
|
||||||
This will allow you to drill deeper into your backtest results, and perform analysis which otherwise would make the regular backtest-output very difficult to digest due to information overload.
|
### Load multiple configuration files
|
||||||
|
|
||||||
If you have some ideas for interesting / helpful backtest data analysis ideas, please submit a Pull Request so the community can benefit from it.
|
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.
|
||||||
## Live data
|
|
||||||
|
|
||||||
To analyze the trades your bot generated, you can load them to a DataFrame as follows:
|
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
from freqtrade.data.btanalysis import load_trades_from_db
|
import json
|
||||||
|
from freqtrade.configuration import Configuration
|
||||||
|
|
||||||
df = load_trades_from_db("sqlite:///tradesv3.sqlite")
|
# Load config from multiple files
|
||||||
|
config = Configuration.from_files(["config1.json", "config2.json"])
|
||||||
df.groupby("pair")["sell_reason"].value_counts()
|
|
||||||
|
|
||||||
|
# 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.
|
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.
|
||||||
|
|||||||
86
docs/data-download.md
Normal file
86
docs/data-download.md
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
# 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 "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.
|
||||||
|
|
||||||
|
!!! Note "Kraken user"
|
||||||
|
Kraken users should read [this](exchanges.md#historic-kraken-data) before starting to download data.
|
||||||
|
|
||||||
|
## Next step
|
||||||
|
|
||||||
|
Great, you now have backtest data downloaded, so you can now start [backtesting](backtesting.md) your strategy.
|
||||||
@@ -4,16 +4,23 @@ This page contains description of the command line arguments, configuration para
|
|||||||
and the bot features that were declared as DEPRECATED by the bot development team
|
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.
|
and are no longer supported. Please avoid their usage in your configuration.
|
||||||
|
|
||||||
### the `--live` command line option
|
|
||||||
|
|
||||||
`--live` in the context of backtesting allows to download the latest tick data for backtesting.
|
|
||||||
Since this only downloads one set of data (by default 500 candles) - this is not really suitable for extendet backtesting, and has therefore been deprecated.
|
|
||||||
|
|
||||||
This command was deprecated in `2019.6-dev` and will be removed after the next release.
|
|
||||||
|
|
||||||
## Removed features
|
## 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
|
### The **--dynamic-whitelist** command line option
|
||||||
|
|
||||||
This command line option was deprecated in 2018 and removed freqtrade 2019.6-dev (develop branch)
|
This command line option was deprecated in 2018 and removed freqtrade 2019.6-dev (develop branch)
|
||||||
and in freqtrade 2019.7 (master 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/enQtNjU5ODcwNjI1MDU3LWEyODBiNzkzNzcyNzU0MWYyYzE5NjIyOTQxMzBmMGUxOTIzM2YyN2Y4NWY1YTEwZDgwYTRmMzE2NmM5ZmY2MTg) 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,79 @@ 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
|
||||||
@@ -32,22 +100,22 @@ This is a simple provider, which however serves as a good example on how to star
|
|||||||
|
|
||||||
Next, modify the classname of the provider (ideally align this with the Filename).
|
Next, modify the classname of the provider (ideally align this with the Filename).
|
||||||
|
|
||||||
The base-class provides the an instance of the bot (`self._freqtrade`), as well as the configuration (`self._config`), and initiates both `_blacklist` and `_whitelist`.
|
The base-class provides an instance of the exchange (`self._exchange`) the pairlist manager (`self._pairlistmanager`), as well as the main configuration (`self._config`), the pairlist dedicated configuration (`self._pairlistconfig`) and the absolute position within the list of pairlists.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
self._freqtrade = freqtrade
|
self._exchange = exchange
|
||||||
|
self._pairlistmanager = pairlistmanager
|
||||||
self._config = config
|
self._config = config
|
||||||
self._whitelist = self._config['exchange']['pair_whitelist']
|
self._pairlistconfig = pairlistconfig
|
||||||
self._blacklist = self._config['exchange'].get('pair_blacklist', [])
|
self._pairlist_pos = pairlist_pos
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
Now, let's step through the methods which require actions:
|
Now, let's step through the methods which require actions:
|
||||||
|
|
||||||
#### configuration
|
#### Pairlist configuration
|
||||||
|
|
||||||
Configuration for PairListProvider is done in the bot configuration file in the element `"pairlist"`.
|
Configuration for PairListProvider is done in the bot configuration file in the element `"pairlist"`.
|
||||||
This Pairlist-object may contain a `"config"` dict with additional configurations for the configured pairlist.
|
This Pairlist-object may contain configurations with additional configurations for the configured pairlist.
|
||||||
By convention, `"number_assets"` is used to specify the maximum number of pairs to keep in the whitelist. Please follow this to ensure a consistent user experience.
|
By convention, `"number_assets"` is used to specify the maximum number of pairs to keep in the whitelist. Please follow this to ensure a consistent user experience.
|
||||||
|
|
||||||
Additional elements can be configured as needed. `VolumePairList` uses `"sort_key"` to specify the sorting value - however feel free to specify whatever is necessary for your great algorithm to be successfull and dynamic.
|
Additional elements can be configured as needed. `VolumePairList` uses `"sort_key"` to specify the sorting value - however feel free to specify whatever is necessary for your great algorithm to be successfull and dynamic.
|
||||||
@@ -57,29 +125,30 @@ Additional elements can be configured as needed. `VolumePairList` uses `"sort_ke
|
|||||||
Returns a description used for Telegram messages.
|
Returns a description used for Telegram messages.
|
||||||
This should contain the name of the Provider, as well as a short description containing the number of assets. Please follow the format `"PairlistName - top/bottom X pairs"`.
|
This should contain the name of the Provider, as well as a short description containing the number of assets. Please follow the format `"PairlistName - top/bottom X pairs"`.
|
||||||
|
|
||||||
#### refresh_pairlist
|
#### filter_pairlist
|
||||||
|
|
||||||
Override this method and run all calculations needed in this method.
|
Override this method and run all calculations needed in this method.
|
||||||
This is called with each iteration of the bot - so consider implementing caching for compute/network heavy calculations.
|
This is called with each iteration of the bot - so consider implementing caching for compute/network heavy calculations.
|
||||||
|
|
||||||
Assign the resulting whiteslist to `self._whitelist` and `self._blacklist` respectively. These will then be used to run the bot in this iteration. Pairs with open trades will be added to the whitelist to have the sell-methods run correctly.
|
It get's passed a pairlist (which can be the result of previous pairlists) as well as `tickers`, a pre-fetched version of `get_tickers()`.
|
||||||
|
|
||||||
Please also run `self._validate_whitelist(pairs)` and to check and remove pairs with inactive markets. This function is available in the Parent class (`StaticPairList`) and should ideally not be overwritten.
|
It must return the resulting pairlist (which may then be passed into the next pairlist filter).
|
||||||
|
|
||||||
|
Validations are optional, the parent class exposes a `_verify_blacklist(pairlist)` and `_whitelist_for_active_markets(pairlist)` to do default filters. Use this if you limit your result to a certain number of pairs - so the endresult is not shorter than expected.
|
||||||
|
|
||||||
##### sample
|
##### sample
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
def refresh_pairlist(self) -> None:
|
def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
|
||||||
# Generate dynamic whitelist
|
# Generate dynamic whitelist
|
||||||
pairs = self._gen_pair_whitelist(self._config['stake_currency'], self._sort_key)
|
pairs = self._calculate_pairlist(pairlist, tickers)
|
||||||
# Validate whitelist to only have active market pairs
|
return pairs
|
||||||
self._whitelist = self._validate_whitelist(pairs)[:self._number_pairs]
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### _gen_pair_whitelist
|
#### _gen_pair_whitelist
|
||||||
|
|
||||||
This is a simple method used by `VolumePairList` - however serves as a good example.
|
This is a simple method used by `VolumePairList` - however serves as a good example.
|
||||||
It implements caching (`@cached(TTLCache(maxsize=1, ttl=1800))`) as well as a configuration option to allow different (but similar) strategies to work with the same PairListProvider.
|
In VolumePairList, this implements different methods of sorting, does early validation so only the expected number of pairs is returned.
|
||||||
|
|
||||||
## Implement a new Exchange (WIP)
|
## Implement a new Exchange (WIP)
|
||||||
|
|
||||||
@@ -126,20 +195,43 @@ print(datetime.utcnow())
|
|||||||
The output will show the last entry from the Exchange as well as the current UTC date.
|
The output will show the last entry from the Exchange as well as the current UTC date.
|
||||||
If the day shows the same day, then the last candle can be assumed as incomplete and should be dropped (leave the setting `"ohlcv_partial_candle"` from the exchange-class untouched / True). Otherwise, set `"ohlcv_partial_candle"` to `False` to not drop Candles (shown in the example above).
|
If the day shows the same day, then the last candle can be assumed as incomplete and should be dropped (leave the setting `"ohlcv_partial_candle"` from the exchange-class untouched / True). Otherwise, set `"ohlcv_partial_candle"` to `False` to not drop Candles (shown in the example above).
|
||||||
|
|
||||||
|
## Updating example notebooks
|
||||||
|
|
||||||
|
To keep the jupyter notebooks aligned with the documentation, the following should be ran after updating a example notebook.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace freqtrade/templates/strategy_analysis_example.ipynb
|
||||||
|
jupyter nbconvert --ClearOutputPreprocessor.enabled=True --to markdown freqtrade/templates/strategy_analysis_example.ipynb --stdout > docs/strategy_analysis_example.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## Continuous integration
|
||||||
|
|
||||||
|
This documents some decisions taken for the CI Pipeline.
|
||||||
|
|
||||||
|
* CI runs on all OS variants, Linux (ubuntu), macOS and Windows.
|
||||||
|
* Docker images are build for the branches `master` and `develop`.
|
||||||
|
* Raspberry PI Docker images are postfixed with `_pi` - so tags will be `:master_pi` and `develop_pi`.
|
||||||
|
* Docker images contain a file, `/freqtrade/freqtrade_commit` containing the commit this image is based of.
|
||||||
|
* Full docker image rebuilds are run once a week via schedule.
|
||||||
|
* Deployments run on ubuntu.
|
||||||
|
* ta-lib binaries are contained in the build_helpers directory to avoid fails related to external unavailability.
|
||||||
|
* All tests must pass for a PR to be merged to `master` or `develop`.
|
||||||
|
|
||||||
## Creating a release
|
## Creating a release
|
||||||
|
|
||||||
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
|
First, pick a commit that's about one week old (to not include latest additions to releases).
|
||||||
# make sure you're in develop branch
|
|
||||||
git checkout develop
|
|
||||||
|
|
||||||
|
``` bash
|
||||||
# create new branch
|
# create new branch
|
||||||
git checkout -b new_release
|
git checkout -b new_release <commitid>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Determine if crucial bugfixes have been made between this commit and the current state, and eventually cherry-pick these.
|
||||||
|
|
||||||
* Edit `freqtrade/__init__.py` and add the version matching the current date (for example `2019.7` for July 2019). Minor versions can be `2019.7-1` should we need to do a second release that month.
|
* Edit `freqtrade/__init__.py` and add the version matching the current date (for example `2019.7` for July 2019). Minor versions can be `2019.7-1` should we need to do a second release that month.
|
||||||
* Commit this part
|
* Commit this part
|
||||||
* push that branch to the remote and create a PR against the master branch
|
* push that branch to the remote and create a PR against the master branch
|
||||||
@@ -147,21 +239,18 @@ git checkout -b new_release
|
|||||||
### Create changelog from git commits
|
### Create changelog from git commits
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Make sure that both master and develop are up-todate!.
|
Make sure that the master branch is uptodate!
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
# Needs to be done before merging / pulling that branch.
|
# Needs to be done before merging / pulling that branch.
|
||||||
git log --oneline --no-decorate --no-merges master..develop
|
git log --oneline --no-decorate --no-merges master..new_release
|
||||||
```
|
```
|
||||||
|
|
||||||
### Create github release / tag
|
### Create github release / tag
|
||||||
|
|
||||||
* Use the button "Draft a new release" in the Github UI (subsection releases)
|
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 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
|
|
||||||
|
|
||||||
* Update version in develop by postfixing that with `-dev` (`2019.6 -> 2019.6-dev`).
|
|
||||||
* Create a PR against develop to update that branch.
|
|
||||||
|
|||||||
@@ -26,6 +26,10 @@ To update the image, simply run the above commands again and restart your runnin
|
|||||||
|
|
||||||
Should you require additional libraries, please [build the image yourself](#build-your-own-docker-image).
|
Should you require additional libraries, please [build the image yourself](#build-your-own-docker-image).
|
||||||
|
|
||||||
|
!!! Note "Docker image update frequency"
|
||||||
|
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
|
### Prepare the configuration files
|
||||||
|
|
||||||
Even though you will use docker, you'll still need some files from the github repository.
|
Even though you will use docker, you'll still need some files from the github repository.
|
||||||
@@ -156,7 +160,7 @@ docker run -d \
|
|||||||
-v ~/.freqtrade/config.json:/freqtrade/config.json \
|
-v ~/.freqtrade/config.json:/freqtrade/config.json \
|
||||||
-v ~/.freqtrade/user_data/:/freqtrade/user_data \
|
-v ~/.freqtrade/user_data/:/freqtrade/user_data \
|
||||||
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
||||||
freqtrade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy
|
freqtrade trade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
@@ -166,6 +170,9 @@ docker run -d \
|
|||||||
!!! Note
|
!!! Note
|
||||||
All available bot command line parameters can be added to the end of the `docker run` command.
|
All available bot command line parameters can be added to the end of the `docker run` command.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
You can define a [restart policy](https://docs.docker.com/config/containers/start-containers-automatically/) in docker. It can be useful in some cases to use the `--restart unless-stopped` flag (crash of freqtrade or reboot of your system).
|
||||||
|
|
||||||
### Monitor your Docker instance
|
### Monitor your Docker instance
|
||||||
|
|
||||||
You can use the following commands to monitor and manage your container:
|
You can use the following commands to monitor and manage your container:
|
||||||
@@ -195,7 +202,7 @@ docker run -d \
|
|||||||
-v ~/.freqtrade/config.json:/freqtrade/config.json \
|
-v ~/.freqtrade/config.json:/freqtrade/config.json \
|
||||||
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
||||||
-v ~/.freqtrade/user_data/:/freqtrade/user_data/ \
|
-v ~/.freqtrade/user_data/:/freqtrade/user_data/ \
|
||||||
freqtrade --strategy AwsomelyProfitableStrategy backtesting
|
freqtrade backtesting --strategy AwsomelyProfitableStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
Head over to the [Backtesting Documentation](backtesting.md) for more details.
|
Head over to the [Backtesting Documentation](backtesting.md) for more details.
|
||||||
|
|||||||
10
docs/edge.md
10
docs/edge.md
@@ -234,9 +234,8 @@ An example of its output:
|
|||||||
|
|
||||||
### Update cached pairs with the latest data
|
### Update cached pairs with the latest data
|
||||||
|
|
||||||
```bash
|
Edge requires historic data the same way as backtesting does.
|
||||||
freqtrade edge --refresh-pairs-cached
|
Please refer to the [Data Downloading](data-download.md) section of the documentation for details.
|
||||||
```
|
|
||||||
|
|
||||||
### Precising stoploss range
|
### Precising stoploss range
|
||||||
|
|
||||||
@@ -250,13 +249,10 @@ freqtrade edge --stoplosses=-0.01,-0.1,-0.001 #min,max,step
|
|||||||
freqtrade edge --timerange=20181110-20181113
|
freqtrade edge --timerange=20181110-20181113
|
||||||
```
|
```
|
||||||
|
|
||||||
Doing `--timerange=-200` will get the last 200 timeframes from your inputdata. You can also specify specific dates, or a range span indexed by start and stop.
|
Doing `--timerange=-20190901` will get all available data until September 1st (excluding September 1st 2019).
|
||||||
|
|
||||||
The full timerange specification:
|
The full timerange specification:
|
||||||
|
|
||||||
* Use last 123 tickframes of data: `--timerange=-123`
|
|
||||||
* Use first 123 tickframes of data: `--timerange=123-`
|
|
||||||
* Use tickframes from line 123 through 456: `--timerange=123-456`
|
|
||||||
* Use tickframes till 2018/01/31: `--timerange=-20180131`
|
* Use tickframes till 2018/01/31: `--timerange=-20180131`
|
||||||
* Use tickframes since 2018/01/31: `--timerange=20180131-`
|
* Use tickframes since 2018/01/31: `--timerange=20180131-`
|
||||||
* Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
|
* Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
|
||||||
|
|||||||
63
docs/exchanges.md
Normal file
63
docs/exchanges.md
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
# Exchange-specific Notes
|
||||||
|
|
||||||
|
This page combines common gotchas and informations which are exchange-specific and most likely don't apply to other exchanges.
|
||||||
|
|
||||||
|
## Binance
|
||||||
|
|
||||||
|
!!! Tip "Stoploss on Exchange"
|
||||||
|
Binance is currently the only exchange supporting `stoploss_on_exchange`. It provides great advantages, so we recommend to benefit from it.
|
||||||
|
|
||||||
|
### Blacklists
|
||||||
|
|
||||||
|
For Binance, please add `"BNB/<STAKE>"` to your blacklist to avoid issues.
|
||||||
|
Accounts having BNB accounts use this to pay for fees - if your first trade happens to be on `BNB`, further trades will consume this position and make the initial BNB order unsellable as the expected amount is not there anymore.
|
||||||
|
|
||||||
|
### Binance sites
|
||||||
|
|
||||||
|
Binance has been split into 3, and users must use the correct ccxt exchange ID for their exchange, otherwise API keys are not recognized.
|
||||||
|
|
||||||
|
* [binance.com](https://www.binance.com/) - International users. Use exchange id: `binance`.
|
||||||
|
* [binance.us](https://www.binance.us/) - US based users. Use exchange id: `binanceus`.
|
||||||
|
* [binance.je](https://www.binance.je/) - Binance Jersey, trading fiat currencies. Use exchange id: `binanceje`.
|
||||||
|
|
||||||
|
## Kraken
|
||||||
|
|
||||||
|
### Historic Kraken data
|
||||||
|
|
||||||
|
The Kraken API does only provide 720 historic candles, which is sufficient for Freqtrade dry-run and live trade modes, but is a problem for backtesting.
|
||||||
|
To download data for the Kraken exchange, using `--dl-trades` is mandatory, otherwise the bot will download the same 720 candles over and over, and you'll not have enough backtest data.
|
||||||
|
|
||||||
|
## Bittrex
|
||||||
|
|
||||||
|
### Restricted markets
|
||||||
|
|
||||||
|
Bittrex split its exchange into US and International versions.
|
||||||
|
The International version has more pairs available, however the API always returns all pairs, so there is currently no automated way to detect if you're affected by the restriction.
|
||||||
|
|
||||||
|
If you have restricted pairs in your whitelist, you'll get a warning message in the log on Freqtrade startup for each restricted pair.
|
||||||
|
|
||||||
|
The warning message will look similar to the following:
|
||||||
|
|
||||||
|
``` output
|
||||||
|
[...] Message: bittrex {"success":false,"message":"RESTRICTED_MARKET","result":null,"explanation":null}"
|
||||||
|
```
|
||||||
|
|
||||||
|
If you're an "International" customer on the Bittrex exchange, then this warning will probably not impact you.
|
||||||
|
If you're a US customer, the bot will fail to create orders for these pairs, and you should remove them from your whitelist.
|
||||||
|
|
||||||
|
You can get a list of restricted markets by using the following snippet:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
import ccxt
|
||||||
|
ct = ccxt.bittrex()
|
||||||
|
_ = ct.load_markets()
|
||||||
|
res = [ f"{x['MarketCurrency']}/{x['BaseCurrency']}" for x in ct.publicGetMarkets()['result'] if x['IsRestricted']]
|
||||||
|
print(res)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Random notes for other exchanges
|
||||||
|
|
||||||
|
* The Ocean (exchange id: `theocean`) exchange uses Web3 functionality and requires `web3` python package to be installed:
|
||||||
|
```shell
|
||||||
|
$ pip3 install web3
|
||||||
|
```
|
||||||
50
docs/faq.md
50
docs/faq.md
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
### The bot does not start
|
### The bot does not start
|
||||||
|
|
||||||
Running the bot with `freqtrade --config config.json` does show the output `freqtrade: command not found`.
|
Running the bot with `freqtrade trade --config config.json` does show the output `freqtrade: command not found`.
|
||||||
|
|
||||||
This could have the following reasons:
|
This could have the following reasons:
|
||||||
|
|
||||||
@@ -38,18 +38,62 @@ like pauses. You can stop your bot, adjust settings and start it again.
|
|||||||
|
|
||||||
### I want to improve the bot with a new strategy
|
### I want to improve the bot with a new strategy
|
||||||
|
|
||||||
That's great. We have a nice backtesting and hyperoptimizing setup. See
|
That's great. We have a nice backtesting and hyperoptimization setup. See
|
||||||
the tutorial [here|Testing-new-strategies-with-Hyperopt](bot-usage.md#hyperopt-commands).
|
the tutorial [here|Testing-new-strategies-with-Hyperopt](bot-usage.md#hyperopt-commands).
|
||||||
|
|
||||||
### Is there a setting to only SELL the coins being held and not perform anymore BUYS?
|
### Is there a setting to only SELL the coins being held and not perform anymore BUYS?
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
|
Read [the Bittrex section about restricted markets](exchanges.md#restricted-markets) for more information.
|
||||||
|
|
||||||
|
### How do I search the bot logs for something?
|
||||||
|
|
||||||
|
By default, the bot writes its log into stderr stream. This is implemented this way so that you can easily separate the bot's diagnostics messages from Backtesting, Edge and Hyperopt results, output from other various Freqtrade utility subcommands, as well as from the output of your custom `print()`'s you may have inserted into your strategy. So if you need to search the log messages with the grep utility, you need to redirect stderr to stdout and disregard stdout.
|
||||||
|
|
||||||
|
* In unix shells, this normally can be done as simple as:
|
||||||
|
```shell
|
||||||
|
$ freqtrade --some-options 2>&1 >/dev/null | grep 'something'
|
||||||
|
```
|
||||||
|
(note, `2>&1` and `>/dev/null` should be written in this order)
|
||||||
|
|
||||||
|
* Bash interpreter also supports so called process substitution syntax, you can grep the log for a string with it as:
|
||||||
|
```shell
|
||||||
|
$ freqtrade --some-options 2> >(grep 'something') >/dev/null
|
||||||
|
```
|
||||||
|
or
|
||||||
|
```shell
|
||||||
|
$ freqtrade --some-options 2> >(grep -v 'something' 1>&2)
|
||||||
|
```
|
||||||
|
|
||||||
|
* You can also write the copy of Freqtrade log messages to a file with the `--logfile` option:
|
||||||
|
```shell
|
||||||
|
$ freqtrade --logfile /path/to/mylogfile.log --some-options
|
||||||
|
```
|
||||||
|
and then grep it as:
|
||||||
|
```shell
|
||||||
|
$ cat /path/to/mylogfile.log | grep 'something'
|
||||||
|
```
|
||||||
|
or even on the fly, as the bot works and the logfile grows:
|
||||||
|
```shell
|
||||||
|
$ tail -f /path/to/mylogfile.log | grep 'something'
|
||||||
|
```
|
||||||
|
from a separate terminal window.
|
||||||
|
|
||||||
|
On Windows, the `--logfilename` option is also supported by Freqtrade and you can use the `findstr` command to search the log for the string of interest:
|
||||||
|
```
|
||||||
|
> type \path\to\mylogfile.log | findstr "something"
|
||||||
|
```
|
||||||
|
|
||||||
## Hyperopt module
|
## Hyperopt module
|
||||||
|
|
||||||
### How many epoch do I need to get a good Hyperopt result?
|
### How many epoch do I need to get a good Hyperopt result?
|
||||||
|
|
||||||
Per default Hyperopts without `-e` or `--epochs` parameter will only
|
Per default Hyperopt called without the `-e`/`--epochs` command line option will only
|
||||||
run 100 epochs, means 100 evals of your triggers, guards, ... Too few
|
run 100 epochs, means 100 evals of your triggers, guards, ... Too few
|
||||||
to find a great result (unless if you are very lucky), so you probably
|
to find a great result (unless if you are very lucky), so you probably
|
||||||
have to run it for 10.000 or more. But it will take an eternity to
|
have to run it for 10.000 or more. But it will take an eternity to
|
||||||
|
|||||||
282
docs/hyperopt.md
282
docs/hyperopt.md
@@ -6,32 +6,60 @@ 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/sample_hyperopt.py)
|
the sample hyperopt file located in [user_data/hyperopts/](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt.py).
|
||||||
|
|
||||||
Configuring hyperopt is similar to writing your own strategy, and many tasks will be similar and a lot of code can be copied across from the strategy.
|
Configuring hyperopt is similar to writing your own strategy, and many tasks will be similar and a lot of code can be copied across from the strategy.
|
||||||
|
|
||||||
|
The simplest way to get started is to use `freqtrade new-hyperopt --hyperopt AwesomeHyperopt`.
|
||||||
|
This will create a new hyperopt file from a template, which will be located under `user_data/hyperopts/AwesomeHyperopt.py`.
|
||||||
|
|
||||||
### Checklist on all tasks / possibilities in hyperopt
|
### Checklist on all tasks / possibilities in hyperopt
|
||||||
|
|
||||||
Depending on the space you want to optimize, only some of the below are required.
|
Depending on the space you want to optimize, only some of the below are required:
|
||||||
|
|
||||||
* fill `populate_indicators` - probably a copy from your strategy
|
|
||||||
* fill `buy_strategy_generator` - for buy signal optimization
|
* fill `buy_strategy_generator` - for buy signal optimization
|
||||||
* fill `indicator_space` - for buy signal optimzation
|
* fill `indicator_space` - for buy signal optimzation
|
||||||
* fill `sell_strategy_generator` - for sell signal optimization
|
* fill `sell_strategy_generator` - for sell signal optimization
|
||||||
* fill `sell_indicator_space` - for sell signal optimzation
|
* fill `sell_indicator_space` - for sell signal optimzation
|
||||||
* fill `roi_space` - for ROI optimization
|
|
||||||
* fill `generate_roi_table` - for ROI optimization (if you need more than 3 entries)
|
!!! Note
|
||||||
* fill `stoploss_space` - stoploss optimization
|
`populate_indicators` needs to create all indicators any of thee spaces may use, otherwise hyperopt will not work.
|
||||||
* Optional but recommended
|
|
||||||
|
Optional - can also be loaded from a strategy:
|
||||||
|
|
||||||
|
* copy `populate_indicators` from your strategy - otherwise default-strategy will be used
|
||||||
* copy `populate_buy_trend` from your strategy - otherwise default-strategy will be used
|
* copy `populate_buy_trend` from your strategy - otherwise default-strategy will be used
|
||||||
* copy `populate_sell_trend` from your strategy - otherwise default-strategy will be used
|
* copy `populate_sell_trend` from your strategy - otherwise default-strategy will be used
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Assuming the optional methods are not in your hyperopt file, please use `--strategy AweSomeStrategy` which contains these methods so hyperopt can use these methods instead.
|
||||||
|
|
||||||
|
Rarely you may also need to override:
|
||||||
|
|
||||||
|
* `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 the ranges for the values in the ROI table that differ from default or the number of entries (steps) in the ROI table which differs from the default 4 steps)
|
||||||
|
* `stoploss_space` - for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default)
|
||||||
|
* `trailing_space` - for custom trailing stop optimization (if you need the ranges for the trailing stop parameters in the optimization hyperspace that differ from default)
|
||||||
|
|
||||||
|
!!! Tip "Quickly optimize ROI, stoploss and trailing stoploss"
|
||||||
|
You can quickly optimize the spaces `roi`, `stoploss` and `trailing` without changing anything (i.e. without creation of a "complete" Hyperopt class with dimensions, parameters, triggers and guards, as described in this document) from the default hyperopt template by relying on your strategy to do most of the calculations.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
# Have a working strategy at hand.
|
||||||
|
freqtrade new-hyperopt --hyperopt EmptyHyperopt
|
||||||
|
|
||||||
|
freqtrade hyperopt --hyperopt EmptyHyperopt --spaces roi stoploss trailing --strategy MyWorkingStrategy --config config.json -e 100
|
||||||
|
```
|
||||||
|
|
||||||
### 1. Install a Custom Hyperopt File
|
### 1. Install a Custom Hyperopt File
|
||||||
|
|
||||||
Put your hyperopt file into the directory `user_data/hyperopts`.
|
Put your hyperopt file into the directory `user_data/hyperopts`.
|
||||||
@@ -56,9 +84,9 @@ multiple guards. The constructed strategy will be something like
|
|||||||
"*buy exactly when close price touches lower bollinger band, BUT only if
|
"*buy exactly when close price touches lower bollinger band, BUT only if
|
||||||
ADX > 10*".
|
ADX > 10*".
|
||||||
|
|
||||||
If you have updated the buy strategy, ie. changed the contents of
|
If you have updated the buy strategy, i.e. changed the contents of
|
||||||
`populate_buy_trend()` method you have to update the `guards` and
|
`populate_buy_trend()` method, you have to update the `guards` and
|
||||||
`triggers` hyperopts must use.
|
`triggers` your hyperopt must use correspondingly.
|
||||||
|
|
||||||
#### Sell optimization
|
#### Sell optimization
|
||||||
|
|
||||||
@@ -74,7 +102,7 @@ To avoid naming collisions in the search-space, please prefix all sell-spaces wi
|
|||||||
#### Using ticker-interval as part of the Strategy
|
#### Using ticker-interval as part of the Strategy
|
||||||
|
|
||||||
The Strategy exposes the ticker-interval as `self.ticker_interval`. The same value is available as class-attribute `HyperoptName.ticker_interval`.
|
The Strategy exposes the ticker-interval as `self.ticker_interval`. The same value is available as class-attribute `HyperoptName.ticker_interval`.
|
||||||
In the case of the linked sample-value this would be `SampleHyperOpts.ticker_interval`.
|
In the case of the linked sample-value this would be `SampleHyperOpt.ticker_interval`.
|
||||||
|
|
||||||
## Solving a Mystery
|
## Solving a Mystery
|
||||||
|
|
||||||
@@ -148,7 +176,7 @@ that minimizes the value of the [loss function](#loss-functions).
|
|||||||
|
|
||||||
The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators.
|
The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators.
|
||||||
When you want to test an indicator that isn't used by the bot currently, remember to
|
When you want to test an indicator that isn't used by the bot currently, remember to
|
||||||
add it to the `populate_indicators()` method in `hyperopt.py`.
|
add it to the `populate_indicators()` method in your custom hyperopt file.
|
||||||
|
|
||||||
## Loss-functions
|
## Loss-functions
|
||||||
|
|
||||||
@@ -159,65 +187,13 @@ By default, FreqTrade uses a loss function, which has been with freqtrade since
|
|||||||
A different loss function can be specified by using the `--hyperopt-loss <Class-name>` argument.
|
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.
|
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), `SharpeHyperOptLoss` (optimizes Sharpe Ratio calculated on the trade returns) and `OnlyProfitHyperOptLoss` (which takes only amount of profit into consideration).
|
Currently, the following loss functions are builtin:
|
||||||
|
|
||||||
### Creating and using a custom loss function
|
* `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)
|
||||||
|
|
||||||
To use a custom loss function class, make sure that the function `hyperopt_loss_function` is defined in your custom hyperopt loss class.
|
Creation of a custom loss function is covered in the [Advanced Hyperopt](advanced-hyperopt.md) part of the documentation.
|
||||||
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
|
||||||
|
|
||||||
@@ -227,15 +203,15 @@ Because hyperopt tries a lot of combinations to find the best parameters it will
|
|||||||
We strongly recommend to use `screen` or `tmux` to prevent any connection loss.
|
We strongly recommend to use `screen` or `tmux` to prevent any connection loss.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade -c config.json hyperopt --customhyperopt <hyperoptname> -e 5000 --spaces all
|
freqtrade hyperopt --config config.json --hyperopt <hyperoptname> -e 5000 --spaces all
|
||||||
```
|
```
|
||||||
|
|
||||||
Use `<hyperoptname>` as the name of the custom hyperopt used.
|
Use `<hyperoptname>` as the name of the custom hyperopt used.
|
||||||
|
|
||||||
The `-e` flag will set how many evaluations hyperopt will do. We recommend
|
The `-e` option will set how many evaluations hyperopt will do. We recommend
|
||||||
running at least several thousand evaluations.
|
running at least several thousand evaluations.
|
||||||
|
|
||||||
The `--spaces all` flag determines that all possible parameters should be optimized. Possibilities are listed below.
|
The `--spaces all` option determines that all possible parameters should be optimized. Possibilities are listed below.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
By default, hyperopt will erase previous results and start from scratch. Continuation can be archived by using `--continue`.
|
By default, hyperopt will erase previous results and start from scratch. Continuation can be archived by using `--continue`.
|
||||||
@@ -258,9 +234,17 @@ For example, to use one month of data, pass the following parameter to the hyper
|
|||||||
freqtrade hyperopt --timerange 20180401-20180501
|
freqtrade hyperopt --timerange 20180401-20180501
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Running Hyperopt using methods from a strategy
|
||||||
|
|
||||||
|
Hyperopt can reuse `populate_indicators`, `populate_buy_trend`, `populate_sell_trend` from your strategy, assuming these methods are **not** in your custom hyperopt file, and a strategy is provided.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade hyperopt --strategy SampleStrategy --customhyperopt SampleHyperopt
|
||||||
|
```
|
||||||
|
|
||||||
### Running Hyperopt with Smaller Search Space
|
### Running Hyperopt with Smaller Search Space
|
||||||
|
|
||||||
Use the `--spaces` argument to limit the search space used by hyperopt.
|
Use the `--spaces` option to limit the search space used by hyperopt.
|
||||||
Letting Hyperopt optimize everything is a huuuuge search space. Often it
|
Letting Hyperopt optimize everything is a huuuuge search space. Often it
|
||||||
might make more sense to start by just searching for initial buy algorithm.
|
might make more sense to start by just searching for initial buy algorithm.
|
||||||
Or maybe you just want to optimize your stoploss or roi table for that awesome
|
Or maybe you just want to optimize your stoploss or roi table for that awesome
|
||||||
@@ -273,8 +257,12 @@ Legal values are:
|
|||||||
* `sell`: just search for a new sell strategy
|
* `sell`: just search for a new sell strategy
|
||||||
* `roi`: just optimize the minimal profit table for your strategy
|
* `roi`: just optimize the minimal profit table for your strategy
|
||||||
* `stoploss`: search for the best stoploss value
|
* `stoploss`: search for the best stoploss value
|
||||||
|
* `trailing`: search for the best trailing stop values
|
||||||
|
* `default`: `all` except `trailing`
|
||||||
* space-separated list of any of the above values for example `--spaces roi stoploss`
|
* space-separated list of any of the above values for example `--spaces roi stoploss`
|
||||||
|
|
||||||
|
The default Hyperopt Search Space, used when no `--space` command line option is specified, does not include the `trailing` hyperspace. We recommend you to run optimization for the `trailing` hyperspace separately, when the best parameters for other hyperspaces were found, validated and pasted into your custom strategy.
|
||||||
|
|
||||||
### Position stacking and disabling max market positions
|
### Position stacking and disabling max market positions
|
||||||
|
|
||||||
In some situations, you may need to run Hyperopt (and Backtesting) with the
|
In some situations, you may need to run Hyperopt (and Backtesting) with the
|
||||||
@@ -303,8 +291,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,
|
||||||
@@ -327,8 +317,7 @@ So for example you had `rsi-value: 29.0` so we would look at `rsi`-block, that t
|
|||||||
(dataframe['rsi'] < 29.0)
|
(dataframe['rsi'] < 29.0)
|
||||||
```
|
```
|
||||||
|
|
||||||
Translating your whole hyperopt result as the new buy-signal
|
Translating your whole hyperopt result as the new buy-signal would then look like:
|
||||||
would then look like:
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:
|
def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:
|
||||||
@@ -341,46 +330,131 @@ 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', 'default' 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
|
||||||
{ 'adx-value': 44,
|
|
||||||
'rsi-value': 29,
|
|
||||||
'adx-enabled': false,
|
|
||||||
'rsi-enabled': True,
|
|
||||||
'trigger': 'bb_lower',
|
|
||||||
'roi_t1': 40,
|
|
||||||
'roi_t2': 57,
|
|
||||||
'roi_t3': 21,
|
|
||||||
'roi_p1': 0.03634636907306948,
|
|
||||||
'roi_p2': 0.055237357937802885,
|
|
||||||
'roi_p3': 0.015163796015548354,
|
|
||||||
'stoploss': -0.37996664668703606
|
|
||||||
}
|
|
||||||
ROI table:
|
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 designed for the strategy.
|
||||||
|
# This attribute will be overridden if the config file contains "minimal_roi"
|
||||||
minimal_roi = {
|
minimal_roi = {
|
||||||
"118": 0,
|
0: 0.10674,
|
||||||
"78": 0.0363463,
|
21: 0.09158,
|
||||||
"21": 0.0915,
|
78: 0.03634,
|
||||||
"0": 0.106
|
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 backtesting results
|
#### 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 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/freqtrade/templates/sample_hyperopt_advanced.py).
|
||||||
|
|
||||||
|
### Understand Hyperopt Stoploss results
|
||||||
|
|
||||||
|
If you are optimizing stoploss values (i.e. if optimization search-space contains 'all', 'default' or 'stoploss'), your result will look as follows and include stoploss:
|
||||||
|
|
||||||
|
```
|
||||||
|
Best result:
|
||||||
|
|
||||||
|
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 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/freqtrade/templates/sample_hyperopt_advanced.py).
|
||||||
|
|
||||||
|
### Understand Hyperopt Trailing Stop results
|
||||||
|
|
||||||
|
If you are optimizing trailing stop values (i.e. if optimization search-space contains 'all' or 'trailing'), your result will look as follows and include trailing stop parameters:
|
||||||
|
|
||||||
|
```
|
||||||
|
Best result:
|
||||||
|
|
||||||
|
45/100: 606 trades. Avg profit 1.04%. Total profit 0.31555614 BTC ( 630.48Σ%). Avg duration 150.3 mins. Objective: -1.10161
|
||||||
|
|
||||||
|
Trailing stop:
|
||||||
|
{ 'trailing_only_offset_is_reached': True,
|
||||||
|
'trailing_stop': True,
|
||||||
|
'trailing_stop_positive': 0.02001,
|
||||||
|
'trailing_stop_positive_offset': 0.06038}
|
||||||
|
```
|
||||||
|
|
||||||
|
In order to use these best trailing stop parameters found by Hyperopt in backtesting and for live trades/dry-run, copy-paste them as the values of the corresponding attributes of your custom strategy:
|
||||||
|
|
||||||
|
```
|
||||||
|
# Trailing stop
|
||||||
|
# These attributes will be overridden if the config file contains corresponding values.
|
||||||
|
trailing_stop = True
|
||||||
|
trailing_stop_positive = 0.02001
|
||||||
|
trailing_stop_positive_offset = 0.06038
|
||||||
|
trailing_only_offset_is_reached = True
|
||||||
|
```
|
||||||
|
As stated in the comment, you can also use it as the values of the corresponding settings in the configuration file.
|
||||||
|
|
||||||
|
#### Default Trailing Stop Search Space
|
||||||
|
|
||||||
|
If you are optimizing trailing stop values, Freqtrade creates the 'trailing' optimization hyperspace for you. By default, the `trailing_stop` parameter is always set to True in that hyperspace, the value of the `trailing_only_offset_is_reached` vary between True and False, the values of the `trailing_stop_positive` and `trailing_stop_positive_offset` parameters vary in the ranges 0.02...0.35 and 0.01...0.1 correspondingly, which is sufficient in most cases.
|
||||||
|
|
||||||
|
Override the `trailing_space()` method and define the desired range in it if you need values of the trailing stop parameters to vary in other ranges during hyperoptimization. A sample for this method can be found in [user_data/hyperopts/sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/sample_hyperopt_advanced.py).
|
||||||
|
|
||||||
|
## Show details of Hyperopt results
|
||||||
|
|
||||||
|
After you run Hyperopt for the desired amount of epochs, you can later list all results for analysis, select only best or profitable once, and show the details for any of the epochs previously evaluated. This can be done with the `hyperopt-list` and `hyperopt-show` subcommands. The usage of these subcommands is described in the [Utils](utils.md#list-hyperopt-results) chapter.
|
||||||
|
|
||||||
|
## Validate backtesting results
|
||||||
|
|
||||||
Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.
|
Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.
|
||||||
|
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ To run this bot we recommend you a cloud instance with a minimum of:
|
|||||||
Help / Slack
|
Help / Slack
|
||||||
For any questions not covered by the documentation or for further information about the bot, we encourage you to join our Slack channel.
|
For any questions not covered by the documentation or for further information about the bot, we encourage you to join our Slack channel.
|
||||||
|
|
||||||
Click [here](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LWEyODBiNzkzNzcyNzU0MWYyYzE5NjIyOTQxMzBmMGUxOTIzM2YyN2Y4NWY1YTEwZDgwYTRmMzE2NmM5ZmY2MTg) to join Slack channel.
|
Click [here](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE) to join Slack channel.
|
||||||
|
|
||||||
## Ready to try?
|
## Ready to try?
|
||||||
|
|
||||||
|
|||||||
@@ -26,24 +26,32 @@ You will need to create API Keys (Usually you get `key` and `secret`) from the E
|
|||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
Freqtrade provides a Linux/MacOS script to install all dependencies and help you to configure the bot.
|
Freqtrade provides the Linux/MacOS Easy Installation script to install all dependencies and help you configure the bot.
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Python3.6 or higher and the corresponding pip are assumed to be available. The install-script will warn and stop if that's not the case.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git clone git@github.com:freqtrade/freqtrade.git
|
|
||||||
cd freqtrade
|
|
||||||
git checkout develop
|
|
||||||
./setup.sh --install
|
|
||||||
```
|
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Windows installation is explained [here](#windows).
|
Windows installation is explained [here](#windows).
|
||||||
|
|
||||||
## Easy Installation - Linux Script
|
The easiest way to install and run Freqtrade is to clone the bot GitHub repository and then run the Easy Installation script, if it's available for your platform.
|
||||||
|
|
||||||
If you are on Debian, Ubuntu or MacOS freqtrade provides a script to Install, Update, Configure, and Reset your bot.
|
!!! Note "Version considerations"
|
||||||
|
When cloning the repository the default working branch has the name `develop`. This branch contains all last features (can be considered as relatively stable, thanks to automated tests). The `master` branch contains the code of the last release (done usually once per month on an approximately one week old snapshot of the `develop` branch to prevent packaging bugs, so potentially it's more stable).
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Python3.6 or higher and the corresponding `pip` are assumed to be available. The install-script will warn you and stop if that's not the case. `git` is also needed to clone the Freqtrade repository.
|
||||||
|
|
||||||
|
This can be achieved with the following commands:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone git@github.com:freqtrade/freqtrade.git
|
||||||
|
cd freqtrade
|
||||||
|
git checkout master # Optional, see (1)
|
||||||
|
./setup.sh --install
|
||||||
|
```
|
||||||
|
(1) This command switches the cloned repository to the use of the `master` branch. It's not needed if you wish to stay on the `develop` branch. You may later switch between branches at any time with the `git checkout master`/`git checkout develop` commands.
|
||||||
|
|
||||||
|
## Easy Installation Script (Linux/MacOS)
|
||||||
|
|
||||||
|
If you are on Debian, Ubuntu or MacOS Freqtrade provides the script to install, update, configure and reset the codebase of your bot.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ ./setup.sh
|
$ ./setup.sh
|
||||||
@@ -56,25 +64,25 @@ usage:
|
|||||||
|
|
||||||
** --install **
|
** --install **
|
||||||
|
|
||||||
This script will install everything you need to run the bot:
|
With this option, the script will install everything you need to run the bot:
|
||||||
|
|
||||||
* Mandatory software as: `ta-lib`
|
* Mandatory software as: `ta-lib`
|
||||||
* Setup your virtualenv
|
* Setup your virtualenv
|
||||||
* Configure your `config.json` file
|
* Configure your `config.json` file
|
||||||
|
|
||||||
This script is a combination of `install script` `--reset`, `--config`
|
This option is a combination of installation tasks, `--reset` and `--config`.
|
||||||
|
|
||||||
** --update **
|
** --update **
|
||||||
|
|
||||||
Update parameter will pull the last version of your current branch and update your virtualenv.
|
This option will pull the last version of your current branch and update your virtualenv. Run the script with this option periodically to update your bot.
|
||||||
|
|
||||||
** --reset **
|
** --reset **
|
||||||
|
|
||||||
Reset parameter will hard reset your branch (only if you are on `master` or `develop`) and recreate your virtualenv.
|
This option will hard reset your branch (only if you are on either `master` or `develop`) and recreate your virtualenv.
|
||||||
|
|
||||||
** --config **
|
** --config **
|
||||||
|
|
||||||
Config parameter is a `config.json` configurator. This script will ask you questions to setup your bot and create your `config.json`.
|
Use this option to configure the `config.json` configuration file. The script will interactively ask you questions to setup your bot and create your `config.json`.
|
||||||
|
|
||||||
------
|
------
|
||||||
|
|
||||||
@@ -95,27 +103,28 @@ sudo apt-get update
|
|||||||
sudo apt-get install build-essential git
|
sudo apt-get install build-essential git
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Raspberry Pi / Raspbian
|
### Raspberry Pi / Raspbian
|
||||||
|
|
||||||
Before installing FreqTrade on a Raspberry Pi running the official Raspbian Image, make sure you have at least Python 3.6 installed. The default image only provides Python 3.5. Probably the easiest way to get a recent version of python is [miniconda](https://repo.continuum.io/miniconda/).
|
The following assumes the latest [Raspbian Buster lite image](https://www.raspberrypi.org/downloads/raspbian/) from at least September 2019.
|
||||||
|
This image comes with python3.7 preinstalled, making it easy to get freqtrade up and running.
|
||||||
|
|
||||||
The following assumes that miniconda3 is installed and available in your environment. Last miniconda3 installation file use python 3.4, we will update to python 3.6 on this installation.
|
Tested using a Raspberry Pi 3 with the Raspbian Buster lite image, all updates applied.
|
||||||
It's recommended to use (mini)conda for this as installation/compilation of `numpy`, `scipy` and `pandas` takes a long time.
|
|
||||||
|
|
||||||
Additional package to install on your Raspbian, `libffi-dev` required by cryptography (from python-telegram-bot).
|
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
conda config --add channels rpi
|
sudo apt-get install python3-venv libatlas-base-dev
|
||||||
conda install python=3.6
|
git clone https://github.com/freqtrade/freqtrade.git
|
||||||
conda create -n freqtrade python=3.6
|
cd freqtrade
|
||||||
conda activate freqtrade
|
|
||||||
conda install scipy pandas numpy
|
|
||||||
|
|
||||||
sudo apt install libffi-dev
|
bash setup.sh -i
|
||||||
python3 -m pip install -r requirements-common.txt
|
|
||||||
python3 -m pip install -e .
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
!!! Note "Installation duration"
|
||||||
|
Depending on your internet speed and the Raspberry Pi version, installation can take multiple hours to complete.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
The above does not install hyperopt dependencies. To install these, please use `python3 -m pip install -e .[hyperopt]`.
|
||||||
|
We do not advise to run hyperopt on a Raspberry Pi, since this is a very resource-heavy operation, which should be done on powerful machine.
|
||||||
|
|
||||||
### Common
|
### Common
|
||||||
|
|
||||||
#### 1. Install TA-Lib
|
#### 1. Install TA-Lib
|
||||||
@@ -147,13 +156,13 @@ python3 -m venv .env
|
|||||||
source .env/bin/activate
|
source .env/bin/activate
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 3. Install FreqTrade
|
#### 3. Install Freqtrade
|
||||||
|
|
||||||
Clone the git repository:
|
Clone the git repository:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/freqtrade/freqtrade.git
|
git clone https://github.com/freqtrade/freqtrade.git
|
||||||
|
cd freqtrade
|
||||||
```
|
```
|
||||||
|
|
||||||
Optionally checkout the master branch to get the latest stable release:
|
Optionally checkout the master branch to get the latest stable release:
|
||||||
@@ -162,63 +171,51 @@ Optionally checkout the master branch to get the latest stable release:
|
|||||||
git checkout master
|
git checkout master
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 4. Initialize the configuration
|
#### 4. Install python dependencies
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
cd freqtrade
|
python3 -m pip install --upgrade pip
|
||||||
|
python3 -m pip install -e .
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 5. Initialize the configuration
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Initialize the user_directory
|
||||||
|
freqtrade create-userdir --userdir user_data/
|
||||||
|
|
||||||
cp config.json.example config.json
|
cp config.json.example config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
> *To edit the config please refer to [Bot Configuration](configuration.md).*
|
> *To edit the config please refer to [Bot Configuration](configuration.md).*
|
||||||
|
|
||||||
#### 5. Install python dependencies
|
|
||||||
|
|
||||||
``` bash
|
|
||||||
python3 -m pip install --upgrade pip
|
|
||||||
python3 -m pip install -r requirements.txt
|
|
||||||
python3 -m pip install -e .
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 6. Run the Bot
|
#### 6. Run the Bot
|
||||||
|
|
||||||
If this is the first time you run the bot, ensure you are running it in Dry-run `"dry_run": true,` otherwise it will start to buy and sell coins.
|
If this is the first time you run the bot, ensure you are running it in Dry-run `"dry_run": true,` otherwise it will start to buy and sell coins.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade -c config.json
|
freqtrade trade -c config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
*Note*: If you run the bot on a server, you should consider using [Docker](docker.md) or a terminal multiplexer like `screen` or [`tmux`](https://en.wikipedia.org/wiki/Tmux) to avoid that the bot is stopped on logout.
|
*Note*: If you run the bot on a server, you should consider using [Docker](docker.md) or a terminal multiplexer like `screen` or [`tmux`](https://en.wikipedia.org/wiki/Tmux) to avoid that the bot is stopped on logout.
|
||||||
|
|
||||||
#### 7. [Optional] Configure `freqtrade` as a `systemd` service
|
#### 7. (Optional) Post-installation Tasks
|
||||||
|
|
||||||
From the freqtrade repo... copy `freqtrade.service` to your systemd user directory (usually `~/.config/systemd/user`) and update `WorkingDirectory` and `ExecStart` to match your setup.
|
On Linux, as an optional post-installation task, you may wish to setup the bot to run as a `systemd` service or configure it to send the log messages to the `syslog`/`rsyslog` or `journald` daemons. See [Advanced Logging](advanced-setup.md#advanced-logging) for details.
|
||||||
|
|
||||||
After that you can start the daemon with:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
systemctl --user start freqtrade
|
|
||||||
```
|
|
||||||
|
|
||||||
For this to be persistent (run when user is logged out) you'll need to enable `linger` for your freqtrade user.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo loginctl enable-linger "$USER"
|
|
||||||
```
|
|
||||||
|
|
||||||
If you run the bot as a service, you can use systemd service manager as a software watchdog monitoring freqtrade bot
|
|
||||||
state and restarting it in the case of failures. If the `internals.sd_notify` parameter is set to true in the
|
|
||||||
configuration or the `--sd-notify` command line option is used, the bot will send keep-alive ping messages to systemd
|
|
||||||
using the sd_notify (systemd notifications) protocol and will also tell systemd its current state (Running or Stopped)
|
|
||||||
when it changes.
|
|
||||||
|
|
||||||
The `freqtrade.service.watchdog` file contains an example of the service unit configuration file which uses systemd
|
|
||||||
as the watchdog.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
The sd_notify communication between the bot and the systemd service manager will not work if the bot runs in a Docker container.
|
|
||||||
|
|
||||||
------
|
------
|
||||||
|
|
||||||
|
## 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.md) 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).
|
||||||
@@ -228,6 +225,12 @@ If that is not available on your system, feel free to try the instructions below
|
|||||||
|
|
||||||
### Install freqtrade manually
|
### Install freqtrade manually
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Make sure to use 64bit Windows and 64bit Python to avoid problems with backtesting or hyperopt due to the memory constraints 32bit applications have under Windows.
|
||||||
|
|
||||||
|
!!! Hint
|
||||||
|
Using the [Anaconda Distribution](https://www.anaconda.com/distribution/) under Windows can greatly help with installation problems. Check out the [Conda section](#using-conda) in this document for more information.
|
||||||
|
|
||||||
#### Clone the git repository
|
#### Clone the git repository
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -243,14 +246,12 @@ As compiling from source on windows has heavy dependencies (requires a partial v
|
|||||||
```cmd
|
```cmd
|
||||||
>cd \path\freqtrade-develop
|
>cd \path\freqtrade-develop
|
||||||
>python -m venv .env
|
>python -m venv .env
|
||||||
>cd .env\Scripts
|
>.env\Scripts\activate.bat
|
||||||
>activate.bat
|
|
||||||
>cd \path\freqtrade-develop
|
|
||||||
REM optionally install ta-lib from wheel
|
REM optionally install ta-lib from wheel
|
||||||
REM >pip install TA_Lib‑0.4.17‑cp36‑cp36m‑win32.whl
|
REM >pip install TA_Lib‑0.4.17‑cp36‑cp36m‑win32.whl
|
||||||
>pip install -r requirements.txt
|
>pip install -r requirements.txt
|
||||||
>pip install -e .
|
>pip install -e .
|
||||||
>python freqtrade\main.py
|
>freqtrade
|
||||||
```
|
```
|
||||||
|
|
||||||
> Thanks [Owdr](https://github.com/Owdr) for the commands. Source: [Issue #222](https://github.com/freqtrade/freqtrade/issues/222)
|
> Thanks [Owdr](https://github.com/Owdr) for the commands. Source: [Issue #222](https://github.com/freqtrade/freqtrade/issues/222)
|
||||||
|
|||||||
@@ -49,4 +49,6 @@
|
|||||||
</nav>
|
</nav>
|
||||||
<!-- Place this tag in your head or just before your close body tag. -->
|
<!-- Place this tag in your head or just before your close body tag. -->
|
||||||
<script async defer src="https://buttons.github.io/buttons.js"></script>
|
<script async defer src="https://buttons.github.io/buttons.js"></script>
|
||||||
|
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
|
||||||
|
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
|
||||||
</header>
|
</header>
|
||||||
213
docs/plotting.md
213
docs/plotting.md
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
This page explains how to plot prices, indicators and profits.
|
This page explains how to plot prices, indicators and profits.
|
||||||
|
|
||||||
## Installation
|
## Installation / Setup
|
||||||
|
|
||||||
Plotting scripts use Plotly library. Install/upgrade it with:
|
Plotting modules use the Plotly library. You can install / upgrade this by running the following command:
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
pip install -U -r requirements-plot.txt
|
pip install -U -r requirements-plot.txt
|
||||||
@@ -12,98 +12,213 @@ pip install -U -r requirements-plot.txt
|
|||||||
|
|
||||||
## 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:
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade plot-dataframe [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
|
[-d PATH] [--userdir PATH] [-s NAME]
|
||||||
|
[--strategy-path PATH] [-p PAIRS [PAIRS ...]]
|
||||||
|
[--indicators1 INDICATORS1 [INDICATORS1 ...]]
|
||||||
|
[--indicators2 INDICATORS2 [INDICATORS2 ...]]
|
||||||
|
[--plot-limit INT] [--db-url PATH]
|
||||||
|
[--trade-source {DB,file}] [--export EXPORT]
|
||||||
|
[--export-filename PATH]
|
||||||
|
[--timerange TIMERANGE] [-i TICKER_INTERVAL]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||||
|
Show profits for only these pairs. Pairs are space-
|
||||||
|
separated.
|
||||||
|
--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.
|
||||||
|
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||||
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
|
`1d`).
|
||||||
|
|
||||||
|
Common arguments:
|
||||||
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
|
--logfile FILE Log to the file specified.
|
||||||
|
-V, --version show program's version number and exit
|
||||||
|
-c PATH, --config PATH
|
||||||
|
Specify configuration file (default: `config.json`).
|
||||||
|
Multiple --config options may be used. Can be set to
|
||||||
|
`-` to read config from stdin.
|
||||||
|
-d PATH, --datadir PATH
|
||||||
|
Path to directory with historical backtesting data.
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
|
||||||
|
Strategy arguments:
|
||||||
|
-s NAME, --strategy NAME
|
||||||
|
Specify strategy class name (default:
|
||||||
|
`DefaultStrategy`).
|
||||||
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
|
|
||||||
``` bash
|
|
||||||
python3 script/plot_dataframe.py [-h] [-p pairs] [--live]
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Example
|
Example:
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
python3 scripts/plot_dataframe.py -p BTC/ETH
|
freqtrade plot-dataframe -p BTC/ETH
|
||||||
```
|
```
|
||||||
|
|
||||||
The `-p` pairs argument can be used to specify pairs you would like to plot.
|
The `-p/--pairs` argument can be used to specify pairs you would like to plot.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
The `freqtrade plot-dataframe` subcommand generates one plot-file per pair.
|
||||||
|
|
||||||
Specify custom indicators.
|
Specify custom indicators.
|
||||||
Use `--indicators1` for the main plot and `--indicators2` for the subplot below (if values are in a different range than prices).
|
Use `--indicators1` for the main plot and `--indicators2` for the subplot below (if values are in a different range than prices).
|
||||||
|
|
||||||
|
!!! Tip
|
||||||
|
You will almost certainly want to specify a custom strategy! This can be done by adding `-s Classname` / `--strategy ClassName` to the command.
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
python3 scripts/plot_dataframe.py -p BTC/ETH --indicators1 sma,ema --indicators2 macd
|
freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --indicators1 sma ema --indicators2 macd
|
||||||
```
|
```
|
||||||
|
|
||||||
### Advanced use
|
### Further usage examples
|
||||||
|
|
||||||
To plot multiple pairs, separate them with a comma:
|
To plot multiple pairs, separate them with a space:
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
python3 scripts/plot_dataframe.py -p BTC/ETH,XRP/ETH
|
freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH XRP/ETH
|
||||||
```
|
```
|
||||||
|
|
||||||
To plot the current live price use the `--live` flag:
|
To plot a timerange (to zoom in)
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
python3 scripts/plot_dataframe.py -p BTC/ETH --live
|
freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --timerange=20180801-20180805
|
||||||
```
|
```
|
||||||
|
|
||||||
To plot a timerange (to zoom in):
|
To plot trades stored in a database use `--db-url` in combination with `--trade-source DB`:
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
python3 scripts/plot_dataframe.py -p BTC/ETH --timerange=100-200
|
freqtrade plot-dataframe --strategy AwesomeStrategy --db-url sqlite:///tradesv3.dry_run.sqlite -p BTC/ETH --trade-source DB
|
||||||
```
|
|
||||||
|
|
||||||
Timerange doesn't work with live data.
|
|
||||||
|
|
||||||
To plot trades stored in a database use `--db-url` argument:
|
|
||||||
|
|
||||||
``` bash
|
|
||||||
python3 scripts/plot_dataframe.py --db-url sqlite:///tradesv3.dry_run.sqlite -p BTC/ETH --trade-source DB
|
|
||||||
```
|
```
|
||||||
|
|
||||||
To plot trades from a backtesting result, use `--export-filename <filename>`
|
To plot trades from a backtesting result, use `--export-filename <filename>`
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
python3 scripts/plot_dataframe.py --export-filename user_data/backtest_data/backtest-result.json -p BTC/ETH
|
freqtrade plot-dataframe --strategy AwesomeStrategy --export-filename user_data/backtest_results/backtest-result.json -p BTC/ETH
|
||||||
```
|
|
||||||
|
|
||||||
To plot a custom strategy the strategy should have first be backtested.
|
|
||||||
The results may then be plotted with the -s argument:
|
|
||||||
|
|
||||||
``` bash
|
|
||||||
python3 scripts/plot_dataframe.py -s Strategy_Name -p BTC/ETH --datadir user_data/data/<exchange_name>/
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Plot profit
|
## Plot profit
|
||||||
|
|
||||||
The profit plotter shows 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 your algorithm works or doesn't.
|
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:
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade plot-profit [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
|
[-d PATH] [--userdir PATH] [-p PAIRS [PAIRS ...]]
|
||||||
|
[--timerange TIMERANGE] [--export EXPORT]
|
||||||
|
[--export-filename PATH] [--db-url PATH]
|
||||||
|
[--trade-source {DB,file}] [-i TICKER_INTERVAL]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||||
|
Show profits for only these pairs. Pairs are space-
|
||||||
|
separated.
|
||||||
|
--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
|
||||||
|
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||||
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
|
`1d`).
|
||||||
|
|
||||||
|
Common arguments:
|
||||||
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
|
--logfile FILE Log to the file specified.
|
||||||
|
-V, --version show program's version number and exit
|
||||||
|
-c PATH, --config PATH
|
||||||
|
Specify configuration file (default: `config.json`).
|
||||||
|
Multiple --config options may be used. Can be set to
|
||||||
|
`-` to read config from stdin.
|
||||||
|
-d PATH, --datadir PATH
|
||||||
|
Path to directory with historical backtesting data.
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
|
||||||
``` bash
|
|
||||||
python3 script/plot_profit.py [-h] [-p pair] [--datadir directory] [--ticker_interval num]
|
|
||||||
```
|
```
|
||||||
|
|
||||||
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
|
``` bash
|
||||||
python3 scripts/plot_profit.py --datadir ../freqtrade/freqtrade/tests/testdata-20171221/ -p LTC/BTC
|
freqtrade plot-profit -p LTC/BTC --export-filename user_data/backtest_results/backtest-result-Strategy005.json
|
||||||
|
```
|
||||||
|
|
||||||
|
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.5.1
|
||||||
|
mdx_truly_sane_lists==1.2
|
||||||
|
|||||||
@@ -16,13 +16,20 @@ Sample configuration:
|
|||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Danger Security warning
|
!!! Danger "Security warning"
|
||||||
By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet and choose a strong, unique password, since others will potentially be able to control your bot.
|
By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet and choose a strong, unique password, since others will potentially be able to control your bot.
|
||||||
|
|
||||||
!!! Danger Password selection
|
!!! Danger "Password selection"
|
||||||
Please make sure to select a very strong, unique password to protect your bot from unauthorized access.
|
Please make sure to select a very strong, unique password to protect your bot from unauthorized access.
|
||||||
|
|
||||||
You can then access the API by going to `http://127.0.0.1:8080/api/v1/version` to check if the API is running correctly.
|
You can then access the API by going to `http://127.0.0.1:8080/api/v1/ping` in a browser to check if the API is running correctly.
|
||||||
|
This should return the response:
|
||||||
|
|
||||||
|
``` output
|
||||||
|
{"status":"pong"}
|
||||||
|
```
|
||||||
|
|
||||||
|
All other endpoints return sensitive info and require authentication, so are not available through a web browser.
|
||||||
|
|
||||||
To generate a secure password, either use a password manager, or use the below code snipped.
|
To generate a secure password, either use a password manager, or use the below code snipped.
|
||||||
|
|
||||||
@@ -58,7 +65,7 @@ docker run -d \
|
|||||||
-v ~/.freqtrade/user_data/:/freqtrade/user_data \
|
-v ~/.freqtrade/user_data/:/freqtrade/user_data \
|
||||||
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
|
||||||
-p 127.0.0.1:8080:8080 \
|
-p 127.0.0.1:8080:8080 \
|
||||||
freqtrade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy
|
freqtrade trade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Danger "Security warning"
|
!!! Danger "Security warning"
|
||||||
@@ -99,8 +106,8 @@ python3 scripts/rest_client.py --config rest_config.json <command> [optional par
|
|||||||
| `stop` | | Stops the trader
|
| `stop` | | Stops the trader
|
||||||
| `stopbuy` | | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
| `stopbuy` | | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
||||||
| `reload_conf` | | Reloads the configuration file
|
| `reload_conf` | | Reloads the configuration file
|
||||||
|
| `show_config` | | Shows part of the current configuration with relevant settings to operation
|
||||||
| `status` | | Lists all open trades
|
| `status` | | Lists all open trades
|
||||||
| `status table` | | List all open trades in a table format
|
|
||||||
| `count` | | Displays number of trades used and available
|
| `count` | | Displays number of trades used and available
|
||||||
| `profit` | | Display a summary of your profit/loss from close trades and some stats about your performance
|
| `profit` | | Display a summary of your profit/loss from close trades and some stats about your performance
|
||||||
| `forcesell <trade_id>` | | Instantly sells the given trade (Ignoring `minimum_roi`).
|
| `forcesell <trade_id>` | | Instantly sells the given trade (Ignoring `minimum_roi`).
|
||||||
@@ -166,6 +173,10 @@ reload_conf
|
|||||||
Reload configuration
|
Reload configuration
|
||||||
:returns: json object
|
:returns: json object
|
||||||
|
|
||||||
|
show_config
|
||||||
|
Returns part of the configuration, relevant for trading operations.
|
||||||
|
:return: json object containing the version
|
||||||
|
|
||||||
start
|
start
|
||||||
Start the bot if it's in stopped state.
|
Start the bot if it's in stopped state.
|
||||||
:returns: json object
|
:returns: json object
|
||||||
|
|||||||
@@ -3,74 +3,101 @@
|
|||||||
The `stoploss` configuration parameter is loss in percentage that should trigger a sale.
|
The `stoploss` configuration parameter is loss in percentage that should trigger a sale.
|
||||||
For example, value `-0.10` will cause immediate sell if the profit dips below -10% for a given trade. This parameter is optional.
|
For example, value `-0.10` will cause immediate sell if the profit dips below -10% for a given trade. This parameter is optional.
|
||||||
|
|
||||||
Most of the strategy files already include the optimal `stoploss`
|
Most of the strategy files already include the optimal `stoploss` value.
|
||||||
value. This parameter is optional. If you use it in the configuration file, it will take over the
|
|
||||||
`stoploss` value from the strategy file.
|
|
||||||
|
|
||||||
## Stop Loss support
|
!!! Info
|
||||||
|
All stoploss properties mentioned in this file can be set in the Strategy, or in the configuration. Configuration values will override the strategy values.
|
||||||
|
|
||||||
|
## Stop Loss Types
|
||||||
|
|
||||||
At this stage the bot contains the following stoploss support modes:
|
At this stage the bot contains the following stoploss support modes:
|
||||||
|
|
||||||
1. static stop loss, defined in either the strategy or configuration.
|
1. Static stop loss.
|
||||||
2. trailing stop loss, defined in the configuration.
|
2. Trailing stop loss.
|
||||||
3. trailing stop loss, custom positive loss, defined in configuration.
|
3. Trailing stop loss, custom positive loss.
|
||||||
|
4. Trailing stop loss only once the trade has reached a certain offset.
|
||||||
|
|
||||||
!!! Note
|
Those stoploss modes can be *on exchange* or *off exchange*. If the stoploss is *on exchange* it means a stoploss limit order is placed on the exchange immediately after buy order happens successfully. This will protect you against sudden crashes in market as the order will be in the queue immediately and if market goes down then the order has more chance of being fulfilled.
|
||||||
All stoploss properties can be configured in either Strategy or configuration. Configuration values override strategy values.
|
|
||||||
|
|
||||||
Those stoploss modes can be *on exchange* or *off exchange*. If the stoploss is *on exchange* it means a stoploss limit order is placed on the exchange immediately after buy order happens successfuly. This will protect you against sudden crashes in market as the order will be in the queue immediately and if market goes down then the order has more chance of being fulfilled.
|
In case of stoploss on exchange there is another parameter called `stoploss_on_exchange_interval`. This configures the interval in seconds at which the bot will check the stoploss and update it if necessary.
|
||||||
|
|
||||||
In case of stoploss on exchange there is another parameter called `stoploss_on_exchange_interval`. This configures the interval in seconds at which the bot will check the stoploss and update it if necessary. As an example in case of trailing stoploss if the order is on the exchange and the market is going up then the bot automatically cancels the previous stoploss order and put a new one with a stop value higher than previous one. It is clear that the bot cannot do it every 5 seconds otherwise it gets banned. So this parameter will tell the bot how often it should update the stoploss order. The default value is 60 (1 minute).
|
For example, assuming the stoploss is on exchange, and trailing stoploss is enabled, and the market is going up, then the bot automatically cancels the previous stoploss order and puts a new one with a stop value higher than the previous stoploss order.
|
||||||
|
The bot cannot do this every 5 seconds (at each iteration), otherwise it would get banned by the exchange.
|
||||||
|
So this parameter will tell the bot how often it should update the stoploss order. The default value is 60 (1 minute).
|
||||||
|
This same logic will reapply a stoploss order on the exchange should you cancel it accidentally.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Stoploss on exchange is only supported for Binance as of now.
|
Stoploss on exchange is only supported for Binance as of now.
|
||||||
|
|
||||||
## Static Stop Loss
|
## Static Stop Loss
|
||||||
|
|
||||||
This is very simple, basically you define a stop loss of x in your strategy file or alternative in the configuration, which
|
This is very simple, you define a stop loss of x (as a ratio of price, i.e. x * 100% of price). This will try to sell the asset once the loss exceeds the defined loss.
|
||||||
will overwrite the strategy definition. This will basically try to sell your asset, the second the loss exceeds the defined loss.
|
|
||||||
|
|
||||||
## Trailing Stop Loss
|
## Trailing Stop Loss
|
||||||
|
|
||||||
The initial value for this stop loss, is defined in your strategy or configuration. Just as you would define your Stop Loss normally.
|
The initial value for this is `stoploss`, just as you would define your static Stop loss.
|
||||||
To enable this Feauture all you have to do is to define the configuration element:
|
To enable trailing stoploss:
|
||||||
|
|
||||||
``` json
|
``` python
|
||||||
"trailing_stop" : True
|
trailing_stop = True
|
||||||
```
|
```
|
||||||
|
|
||||||
This will now activate an algorithm, which automatically moves your stop loss up every time the price of your asset increases.
|
This will now activate an algorithm, which automatically moves the stop loss up every time the price of your asset increases.
|
||||||
|
|
||||||
For example, simplified math,
|
For example, simplified math:
|
||||||
|
|
||||||
* you buy an asset at a price of 100$
|
* the bot buys an asset at a price of 100$
|
||||||
* your stop loss is defined at 2%
|
* the stop loss is defined at 2%
|
||||||
* which means your stop loss, gets triggered once your asset dropped below 98$
|
* the stop loss would get triggered once the asset dropps below 98$
|
||||||
* assuming your asset now increases to 102$
|
* assuming the asset now increases to 102$
|
||||||
* your stop loss, will now be 2% of 102$ or 99.96$
|
* the stop loss will now be 2% of 102$ or 99.96$
|
||||||
* now your asset drops in value to 101$, your stop loss, will still be 99.96$
|
* now the asset drops in value to 101$, the stop loss will still be 99.96$ and would trigger at 99.96$.
|
||||||
|
|
||||||
basically what this means is that your stop loss will be adjusted to be always be 2% of the highest observed price
|
In summary: The stoploss will be adjusted to be always be 2% of the highest observed price.
|
||||||
|
|
||||||
### Custom positive loss
|
### Custom positive stoploss
|
||||||
|
|
||||||
Due to demand, it is possible to have a default stop loss, when you are in the red with your buy, but once your profit surpasses a certain percentage,
|
It is also possible to have a default stop loss, when you are in the red with your buy, but once your profit surpasses a certain percentage, the system will utilize a new stop loss, which can have a different value.
|
||||||
the system will utilize a new stop loss, which can be a different value. For example your default stop loss is 5%, but once you have 1.1% profit,
|
For example your default stop loss is 5%, but once you have 1.1% profit, it will be changed to be only a 1% stop loss, which trails the green candles until it goes below them.
|
||||||
it will be changed to be only a 1% stop loss, which trails the green candles until it goes below them.
|
|
||||||
|
|
||||||
Both values can be configured in the main configuration file and requires `"trailing_stop": true` to be set to true.
|
Both values require `trailing_stop` to be set to true.
|
||||||
|
|
||||||
``` json
|
``` python
|
||||||
"trailing_stop_positive": 0.01,
|
trailing_stop_positive = 0.01
|
||||||
"trailing_stop_positive_offset": 0.011,
|
trailing_stop_positive_offset = 0.011
|
||||||
"trailing_only_offset_is_reached": false
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The 0.01 would translate to a 1% stop loss, once you hit 1.1% profit.
|
The 0.01 would translate to a 1% stop loss, once you hit 1.1% profit.
|
||||||
|
Before this, `stoploss` is used for the trailing stoploss.
|
||||||
|
|
||||||
You should also make sure to have this value (`trailing_stop_positive_offset`) lower than your minimal ROI, otherwise minimal ROI will apply first and sell your trade.
|
Read the [next section](#trailing-only-once-offset-is-reached) to keep stoploss at 5% of the entry point.
|
||||||
|
|
||||||
|
!!! Tip
|
||||||
|
Make sure to have this value (`trailing_stop_positive_offset`) lower than minimal ROI, otherwise minimal ROI will apply first and sell the trade.
|
||||||
|
|
||||||
|
### Trailing only once offset is reached
|
||||||
|
|
||||||
|
It is also possible to use a static stoploss until the offset is reached, and then trail the trade to take profits once the market turns.
|
||||||
|
|
||||||
If `"trailing_only_offset_is_reached": true` then the trailing stoploss is only activated once the offset is reached. Until then, the stoploss remains at the configured `stoploss`.
|
If `"trailing_only_offset_is_reached": true` then the trailing stoploss is only activated once the offset is reached. Until then, the stoploss remains at the configured `stoploss`.
|
||||||
|
This option can be used with or without `trailing_stop_positive`, but uses `trailing_stop_positive_offset` as offset.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
trailing_stop_positive_offset = 0.011
|
||||||
|
trailing_only_offset_is_reached = true
|
||||||
|
```
|
||||||
|
|
||||||
|
Simplified example:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
stoploss = 0.05
|
||||||
|
trailing_stop_positive_offset = 0.03
|
||||||
|
trailing_only_offset_is_reached = True
|
||||||
|
```
|
||||||
|
|
||||||
|
* the bot buys an asset at a price of 100$
|
||||||
|
* the stop loss is defined at 5%
|
||||||
|
* the stop loss will remain at 95% until profit reaches +3%
|
||||||
|
|
||||||
## Changing stoploss on open trades
|
## Changing stoploss on open trades
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Optimization
|
# Strategy Customization
|
||||||
|
|
||||||
This page explains where to customize your strategies, and add new
|
This page explains where to customize your strategies, and add new
|
||||||
indicators.
|
indicators.
|
||||||
@@ -7,24 +7,28 @@ indicators.
|
|||||||
|
|
||||||
This is very simple. Copy paste your strategy file into the directory `user_data/strategies`.
|
This is very simple. Copy paste your strategy file into the directory `user_data/strategies`.
|
||||||
|
|
||||||
Let assume you have a class called `AwesomeStrategy` in the file `awesome-strategy.py`:
|
Let assume you have a class called `AwesomeStrategy` in the file `AwesomeStrategy.py`:
|
||||||
|
|
||||||
1. Move your file into `user_data/strategies` (you should have `user_data/strategies/awesome-strategy.py`
|
1. Move your file into `user_data/strategies` (you should have `user_data/strategies/AwesomeStrategy.py`
|
||||||
2. Start the bot with the param `--strategy AwesomeStrategy` (the parameter is the class name)
|
2. Start the bot with the param `--strategy AwesomeStrategy` (the parameter is the class name)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade --strategy AwesomeStrategy
|
freqtrade trade --strategy AwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
## Change your strategy
|
## Develop your own strategy
|
||||||
|
|
||||||
The bot includes a default strategy file. However, we recommend you to
|
The bot includes a default strategy file.
|
||||||
use your own file to not have to lose your parameters every time the default
|
Also, several other strategies are available in the [strategy repository](https://github.com/freqtrade/freqtrade-strategies).
|
||||||
strategy file will be updated on Github. Put your custom strategy file
|
|
||||||
into the directory `user_data/strategies`.
|
|
||||||
|
|
||||||
Best copy the test-strategy and modify this copy to avoid having bot-updates override your changes.
|
You will however most likely have your own idea for a strategy.
|
||||||
`cp user_data/strategies/test_strategy.py user_data/strategies/awesome-strategy.py`
|
This document intends to help you develop one for yourself.
|
||||||
|
|
||||||
|
To get started, use `freqtrade new-strategy --strategy AwesomeStrategy`.
|
||||||
|
This will create a new strategy file from a template, which will be located under `user_data/strategies/AwesomeStrategy.py`.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
This is just a template file, which will most likely not be profitable out of the box.
|
||||||
|
|
||||||
### Anatomy of a strategy
|
### Anatomy of a strategy
|
||||||
|
|
||||||
@@ -36,27 +40,31 @@ 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
|
||||||
freqtrade --strategy AwesomeStrategy
|
freqtrade trade --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/freqtrade/templates/sample_strategy.py)
|
||||||
file as reference.**
|
file as reference.**
|
||||||
|
|
||||||
!!! Note Strategies and Backtesting
|
!!! Note "Strategies and Backtesting"
|
||||||
To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware
|
To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware
|
||||||
that during backtesting the full time-interval is passed to the `populate_*()` methods at once.
|
that during backtesting the full time-interval is passed to the `populate_*()` methods at once.
|
||||||
It is therefore best to use vectorized operations (across the whole dataframe, not loops) and
|
It is therefore best to use vectorized operations (across the whole dataframe, not loops) and
|
||||||
avoid index referencing (`df.iloc[-1]`), but instead use `df.shift()` to get to the previous candle.
|
avoid index referencing (`df.iloc[-1]`), but instead use `df.shift()` to get to the previous candle.
|
||||||
|
|
||||||
!!! Warning Using future data
|
!!! Warning "Warning: Using future data"
|
||||||
Since backtesting passes the full time interval to the `populate_*()` methods, the strategy author
|
Since backtesting passes the full time interval to the `populate_*()` methods, the strategy author
|
||||||
needs to take care to avoid having the strategy utilize data from the future.
|
needs to take care to avoid having the strategy utilize data from the future.
|
||||||
Samples for usage of future data are `dataframe.shift(-1)`, `dataframe.resample("1h")` (this uses the left border of the interval, so moves data from an hour to the start of the hour).
|
Some common patterns for this are listed in the [Common Mistakes](#common-mistakes-when-developing-strategies) section of this document.
|
||||||
They all use data which is not available during regular operations, so these strategies will perform well during backtesting, but will fail / perform badly in dry-runs.
|
|
||||||
|
|
||||||
### Customize Indicators
|
### Customize Indicators
|
||||||
|
|
||||||
@@ -109,11 +117,41 @@ 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/freqtrade/templates/sample_strategy.py).
|
||||||
Then uncomment indicators you need.
|
Then uncomment indicators you need.
|
||||||
|
|
||||||
|
### Strategy startup period
|
||||||
|
|
||||||
|
Most indicators have an instable startup period, in which they are either not available, or the calculation is incorrect. This can lead to inconsistencies, since Freqtrade does not know how long this instable period should be.
|
||||||
|
To account for this, the strategy can be assigned the `startup_candle_count` attribute.
|
||||||
|
This should be set to the maximum number of candles that the strategy requires to calculate stable indicators.
|
||||||
|
|
||||||
|
In this example strategy, this should be set to 100 (`startup_candle_count = 100`), since the longest needed history is 100 candles.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)
|
||||||
|
```
|
||||||
|
|
||||||
|
By letting the bot know how much history is needed, backtest trades can start at the specified timerange during backtesting and hyperopt.
|
||||||
|
|
||||||
|
!!! Warning
|
||||||
|
`startup_candle_count` should be below `ohlcv_candle_limit` (which is 500 for most exchanges) - since only this amount of candles will be available during Dry-Run/Live Trade operations.
|
||||||
|
|
||||||
|
#### Example
|
||||||
|
|
||||||
|
Let's try to backtest 1 month (January 2019) of 5m candles using the an example strategy with EMA100, as above.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade backtesting --timerange 20190101-20190201 --ticker-interval 5m
|
||||||
|
```
|
||||||
|
|
||||||
|
Assuming `startup_candle_count` is set to 100, backtesting knows it needs 100 candles to generate valid buy signals. It will load data from `20190101 - (100 * 5m)` - which is ~2019-12-31 15:30:00.
|
||||||
|
If this data is available, indicators will be calculated with this extended timerange. The instable startup period (up to 2019-01-01 00:00:00) will then be removed before starting backtesting.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
If data for the startup period is not available, then the timerange will be adjusted to account for this startup period - so Backtesting would start at 2019-01-01 08:30:00.
|
||||||
|
|
||||||
### Buy signal rules
|
### Buy signal rules
|
||||||
|
|
||||||
Edit the method `populate_buy_trend()` in your strategy file to update your buy strategy.
|
Edit the method `populate_buy_trend()` in your strategy file to update your buy strategy.
|
||||||
@@ -122,7 +160,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:
|
||||||
@@ -134,15 +172,19 @@ def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|||||||
"""
|
"""
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(
|
(
|
||||||
(dataframe['adx'] > 30) &
|
(qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30
|
||||||
(dataframe['tema'] <= dataframe['bb_middleband']) &
|
(dataframe['tema'] <= dataframe['bb_middleband']) & # Guard
|
||||||
(dataframe['tema'] > dataframe['tema'].shift(1))
|
(dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
),
|
),
|
||||||
'buy'] = 1
|
'buy'] = 1
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
```
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Buying requires sellers to buy from - therefore volume needs to be > 0 (`dataframe['volume'] > 0`) to make sure that the bot does not buy/sell in no-activity periods.
|
||||||
|
|
||||||
### Sell signal rules
|
### Sell signal rules
|
||||||
|
|
||||||
Edit the method `populate_sell_trend()` into your strategy file to update your sell strategy.
|
Edit the method `populate_sell_trend()` into your strategy file to update your sell strategy.
|
||||||
@@ -152,7 +194,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:
|
||||||
@@ -164,9 +206,10 @@ def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame
|
|||||||
"""
|
"""
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(
|
(
|
||||||
(dataframe['adx'] > 70) &
|
(qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70
|
||||||
(dataframe['tema'] > dataframe['bb_middleband']) &
|
(dataframe['tema'] > dataframe['bb_middleband']) & # Guard
|
||||||
(dataframe['tema'] < dataframe['tema'].shift(1))
|
(dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
),
|
),
|
||||||
'sell'] = 1
|
'sell'] = 1
|
||||||
return dataframe
|
return dataframe
|
||||||
@@ -220,7 +263,7 @@ This would signify a stoploss of -10%.
|
|||||||
|
|
||||||
For the full documentation on stoploss features, look at the dedicated [stoploss page](stoploss.md).
|
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 dict, so your stoploss is on the exchange and cannot be missed for network-problems (or other problems).
|
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).
|
For more information on order_types please look [here](configuration.md#understand-order_types).
|
||||||
|
|
||||||
@@ -242,9 +285,9 @@ Instead, have a look at the section [Storing information](#Storing-information)
|
|||||||
|
|
||||||
### Storing information
|
### Storing information
|
||||||
|
|
||||||
Storing information can be accomplished by crating a new dictionary within the strategy class.
|
Storing information can be accomplished by creating a new dictionary within the strategy class.
|
||||||
|
|
||||||
The name of the variable can be choosen at will, but should be prefixed with `cust_` to avoid naming collisions with predefined strategy variables.
|
The name of the variable can be chosen at will, but should be prefixed with `cust_` to avoid naming collisions with predefined strategy variables.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
class Awesomestrategy(IStrategy):
|
class Awesomestrategy(IStrategy):
|
||||||
@@ -274,30 +317,29 @@ Please always check the mode of operation to select the correct method to get da
|
|||||||
|
|
||||||
#### Possible options for DataProvider
|
#### Possible options for DataProvider
|
||||||
|
|
||||||
- `available_pairs` - Property with tuples listing cached pairs with their intervals. (pair, interval)
|
- `available_pairs` - Property with tuples listing cached pairs with their intervals (pair, interval).
|
||||||
- `ohlcv(pair, ticker_interval)` - Currently cached ticker data for all pairs in the whitelist, returns DataFrame or empty DataFrame
|
- `ohlcv(pair, timeframe)` - Currently cached ticker data for the pair, returns DataFrame or empty DataFrame.
|
||||||
- `historic_ohlcv(pair, ticker_interval)` - Data stored on disk
|
- `historic_ohlcv(pair, timeframe)` - Returns historical data stored on disk.
|
||||||
|
- `get_pair_dataframe(pair, timeframe)` - This is a universal method, which returns either historical data (for backtesting) or cached live data (for the Dry-Run and Live-Run modes).
|
||||||
|
- `orderbook(pair, maximum)` - Returns latest orderbook data for the pair, a dict with bids/asks with a total of `maximum` entries.
|
||||||
|
- `market(pair)` - Returns market data for the pair: fees, limits, precisions, activity flag, etc. See [ccxt documentation](https://github.com/ccxt/ccxt/wiki/Manual#markets) for more details on Market data structure.
|
||||||
- `runmode` - Property containing the current runmode.
|
- `runmode` - Property containing the current runmode.
|
||||||
|
|
||||||
#### ohlcv / historic_ohlcv
|
#### Example: fetch live ohlcv / historic data for the first informative pair
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
if self.dp:
|
if self.dp:
|
||||||
if self.dp.runmode in ('live', 'dry_run'):
|
inf_pair, inf_timeframe = self.informative_pairs()[0]
|
||||||
if (f'{self.stake_currency}/BTC', self.ticker_interval) in self.dp.available_pairs:
|
informative = self.dp.get_pair_dataframe(pair=inf_pair,
|
||||||
data_eth = self.dp.ohlcv(pair='{self.stake_currency}/BTC',
|
timeframe=inf_timeframe)
|
||||||
ticker_interval=self.ticker_interval)
|
|
||||||
else:
|
|
||||||
# Get historic ohlcv data (cached on disk).
|
|
||||||
history_eth = self.dp.historic_ohlcv(pair='{self.stake_currency}/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
|
!!! Warning "Warning in hyperopt"
|
||||||
This option cannot currently be used during hyperopt.
|
This option cannot currently be used during hyperopt.
|
||||||
|
|
||||||
#### Orderbook
|
#### Orderbook
|
||||||
@@ -309,7 +351,9 @@ if self.dp:
|
|||||||
dataframe['best_bid'] = ob['bids'][0][0]
|
dataframe['best_bid'] = ob['bids'][0][0]
|
||||||
dataframe['best_ask'] = ob['asks'][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
|
|
||||||
|
!!! Warning
|
||||||
|
The order book is not part of the historic data which means backtesting and hyperopt will not work if this
|
||||||
method is used.
|
method is used.
|
||||||
|
|
||||||
#### Available Pairs
|
#### Available Pairs
|
||||||
@@ -320,7 +364,6 @@ if self.dp:
|
|||||||
print(f"available {pair}, {ticker}")
|
print(f"available {pair}, {ticker}")
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
#### Get data for non-tradeable pairs
|
#### Get data for non-tradeable pairs
|
||||||
|
|
||||||
Data for additional, informative pairs (reference pairs) can be beneficial for some strategies.
|
Data for additional, informative pairs (reference pairs) can be beneficial for some strategies.
|
||||||
@@ -342,9 +385,9 @@ def informative_pairs(self):
|
|||||||
As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short.
|
As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short.
|
||||||
All intervals and all pairs can be specified as long as they are available (and active) on the used exchange.
|
All intervals and all pairs can be specified as long as they are available (and active) on the used exchange.
|
||||||
It is however better to use resampling to longer time-intervals when possible
|
It is however better to use resampling to longer time-intervals when possible
|
||||||
to avoid hammering the exchange with too many requests and risk beeing blocked.
|
to avoid hammering the exchange with too many requests and risk being blocked.
|
||||||
|
|
||||||
### Additional data - Wallets
|
### Additional data (Wallets)
|
||||||
|
|
||||||
The strategy provides access to the `Wallets` object. This contains the current balances on the exchange.
|
The strategy provides access to the `Wallets` object. This contains the current balances on the exchange.
|
||||||
|
|
||||||
@@ -366,6 +409,52 @@ if self.wallets:
|
|||||||
- `get_used(asset)` - currently tied up balance (open orders)
|
- `get_used(asset)` - currently tied up balance (open orders)
|
||||||
- `get_total(asset)` - total available balance - sum of the 2 above
|
- `get_total(asset)` - total available balance - sum of the 2 above
|
||||||
|
|
||||||
|
### Additional data (Trades)
|
||||||
|
|
||||||
|
A history of Trades can be retrieved in the strategy by querying the database.
|
||||||
|
|
||||||
|
At the top of the file, import Trade.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from freqtrade.persistence import Trade
|
||||||
|
```
|
||||||
|
|
||||||
|
The following example queries for the current pair and trades from today, however other filters can easily be added.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
if self.config['runmode'] in ('live', 'dry_run'):
|
||||||
|
trades = Trade.get_trades([Trade.pair == metadata['pair'],
|
||||||
|
Trade.open_date > datetime.utcnow() - timedelta(days=1),
|
||||||
|
Trade.is_open == False,
|
||||||
|
]).order_by(Trade.close_date).all()
|
||||||
|
# Summarize profit for this pair.
|
||||||
|
curdayprofit = sum(trade.close_profit for trade in trades)
|
||||||
|
```
|
||||||
|
|
||||||
|
Get amount of stake_currency currently invested in Trades:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
if self.config['runmode'] in ('live', 'dry_run'):
|
||||||
|
total_stakes = Trade.total_open_trades_stakes()
|
||||||
|
```
|
||||||
|
|
||||||
|
Retrieve performance per pair.
|
||||||
|
Returns a List of dicts per pair.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
if self.config['runmode'] in ('live', 'dry_run'):
|
||||||
|
performance = Trade.get_overall_performance()
|
||||||
|
```
|
||||||
|
|
||||||
|
Sample return value: ETH/BTC had 5 trades, with a total profit of 1.5% (ratio of 0.015).
|
||||||
|
|
||||||
|
``` json
|
||||||
|
{'pair': "ETH/BTC", 'profit': 0.015, 'count': 5}
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Warning
|
||||||
|
Trade history is not available during backtesting or hyperopt.
|
||||||
|
|
||||||
### Print created dataframe
|
### Print created dataframe
|
||||||
|
|
||||||
To inspect the created dataframe, you can issue a print-statement in either `populate_buy_trend()` or `populate_sell_trend()`.
|
To inspect the created dataframe, you can issue a print-statement in either `populate_buy_trend()` or `populate_sell_trend()`.
|
||||||
@@ -390,26 +479,38 @@ def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|||||||
|
|
||||||
Printing more than a few rows is also possible (simply use `print(dataframe)` instead of `print(dataframe.tail())`), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds).
|
Printing more than a few rows is also possible (simply use `print(dataframe)` instead of `print(dataframe.tail())`), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds).
|
||||||
|
|
||||||
### Where is the default strategy?
|
### Where can i find a strategy template?
|
||||||
|
|
||||||
The default buy strategy is located in the file
|
The strategy template is located in the file
|
||||||
[freqtrade/default_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/strategy/default_strategy.py).
|
[user_data/strategies/sample_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_strategy.py).
|
||||||
|
|
||||||
### Specify custom strategy location
|
### Specify custom strategy location
|
||||||
|
|
||||||
If you want to use a strategy from a different directory you can pass `--strategy-path`
|
If you want to use a strategy from a different directory you can pass `--strategy-path`
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade --strategy AwesomeStrategy --strategy-path /some/directory
|
freqtrade trade --strategy AwesomeStrategy --strategy-path /some/directory
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Common mistakes when developing strategies
|
||||||
|
|
||||||
|
Backtesting analyzes the whole time-range at once for performance reasons. Because of this, strategy authors need to make sure that strategies do not look-ahead into the future.
|
||||||
|
This is a common pain-point, which can cause huge differences between backtesting and dry/live run methods, since they all use data which is not available during dry/live runs, so these strategies will perform well during backtesting, but will fail / perform badly in real conditions.
|
||||||
|
|
||||||
|
The following lists some common patterns which should be avoided to prevent frustration:
|
||||||
|
|
||||||
|
- don't use `shift(-1)`. This uses data from the future, which is not available.
|
||||||
|
- don't use `.iloc[-1]` or any other absolute position in the dataframe, this will be different between dry-run and backtesting.
|
||||||
|
- don't use `dataframe['volume'].mean()`. This uses the full DataFrame for backtesting, including data from the future. Use `dataframe['volume'].rolling(<window>).mean()` instead
|
||||||
|
- don't use `.resample('1h')`. This uses the left border of the interval, so moves data from an hour to the start of the hour. Use `.resample('1h', label='right')` instead.
|
||||||
|
|
||||||
### Further strategy ideas
|
### Further strategy ideas
|
||||||
|
|
||||||
To get additional Ideas for strategies, head over to our [strategy repository](https://github.com/freqtrade/freqtrade-strategies). Feel free to use them as they are - but results will depend on the current market situation, pairs used etc. - therefore please backtest the strategy for your exchange/desired pairs first, evaluate carefully, use at your own risk.
|
To get additional Ideas for strategies, head over to our [strategy repository](https://github.com/freqtrade/freqtrade-strategies). Feel free to use them as they are - but results will depend on the current market situation, pairs used etc. - therefore please backtest the strategy for your exchange/desired pairs first, evaluate carefully, use at your own risk.
|
||||||
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/enQtNjU5ODcwNjI1MDU3LWEyODBiNzkzNzcyNzU0MWYyYzE5NjIyOTQxMzBmMGUxOTIzM2YyN2Y4NWY1YTEwZDgwYTRmMzE2NmM5ZmY2MTg) 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
|
||||||
|
|
||||||
|
|||||||
158
docs/strategy_analysis_example.md
Normal file
158
docs/strategy_analysis_example.md
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
# Strategy analysis example
|
||||||
|
|
||||||
|
Debugging a strategy can be time-consuming. FreqTrade offers helper functions to visualize raw data.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from pathlib import Path
|
||||||
|
# Customize these according to your needs.
|
||||||
|
|
||||||
|
# Define some constants
|
||||||
|
timeframe = "5m"
|
||||||
|
# Name of the strategy class
|
||||||
|
strategy_name = 'SampleStrategy'
|
||||||
|
# Path to user data
|
||||||
|
user_data_dir = Path('user_data')
|
||||||
|
# Location of the strategy
|
||||||
|
strategy_location = user_data_dir / 'strategies'
|
||||||
|
# Location of the data
|
||||||
|
data_location = Path(user_data_dir, 'data', 'binance')
|
||||||
|
# Pair to analyze - Only use one pair here
|
||||||
|
pair = "BTC_USDT"
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Load data using values set above
|
||||||
|
from freqtrade.data.history import load_pair_history
|
||||||
|
|
||||||
|
candles = load_pair_history(datadir=data_location,
|
||||||
|
timeframe=timeframe,
|
||||||
|
pair=pair)
|
||||||
|
|
||||||
|
# Confirm success
|
||||||
|
print("Loaded " + str(len(candles)) + f" rows of data for {pair} from {data_location}")
|
||||||
|
candles.head()
|
||||||
|
```
|
||||||
|
|
||||||
|
## Load and run strategy
|
||||||
|
* Rerun each time the strategy file is changed
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Load strategy using values set above
|
||||||
|
from freqtrade.resolvers import StrategyResolver
|
||||||
|
strategy = StrategyResolver({'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()
|
||||||
|
```
|
||||||
|
|
||||||
|
## Analyze the loaded trades for trade parallelism
|
||||||
|
This can be useful to find the best `max_open_trades` parameter, when used with backtesting in conjunction with `--disable-max-market-positions`.
|
||||||
|
|
||||||
|
`analyze_trade_parallelism()` returns a timeseries dataframe with an "open_trades" column, specifying the number of open trades for each candle.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from freqtrade.data.btanalysis import analyze_trade_parallelism
|
||||||
|
|
||||||
|
# Analyze the above
|
||||||
|
parallel_trades = analyze_trade_parallelism(trades, '5m')
|
||||||
|
|
||||||
|
|
||||||
|
parallel_trades.plot()
|
||||||
|
```
|
||||||
|
|
||||||
|
## Plot results
|
||||||
|
|
||||||
|
Freqtrade offers interactive plotting capabilities based on plotly.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from freqtrade.plot.plotting import generate_candlestick_graph
|
||||||
|
# Limit graph period to keep plotly quick and reactive
|
||||||
|
|
||||||
|
data_red = data['2019-06-01':'2019-06-10']
|
||||||
|
# Generate candlestick graph
|
||||||
|
graph = generate_candlestick_graph(pair=pair,
|
||||||
|
data=data_red,
|
||||||
|
trades=trades,
|
||||||
|
indicators1=['sma20', 'ema50', 'ema55'],
|
||||||
|
indicators2=['rsi', 'macd', 'macdsignal', 'macdhist']
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Show graph inline
|
||||||
|
# graph.show()
|
||||||
|
|
||||||
|
# Render graph in a seperate window
|
||||||
|
graph.show(renderer="browser")
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.
|
||||||
13
docs/stylesheets/ft.extra.css
Normal file
13
docs/stylesheets/ft.extra.css
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
.rst-versions {
|
||||||
|
font-size: .7rem;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rst-versions.rst-badge .rst-current-version {
|
||||||
|
font-size: .7rem;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rst-versions .rst-other-versions {
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
@@ -53,6 +53,7 @@ official commands. You can ask at any moment for help with `/help`.
|
|||||||
| `/stop` | | Stops the trader
|
| `/stop` | | Stops the trader
|
||||||
| `/stopbuy` | | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
| `/stopbuy` | | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
||||||
| `/reload_conf` | | Reloads the configuration file
|
| `/reload_conf` | | Reloads the configuration file
|
||||||
|
| `/show_config` | | Shows part of the current configuration with relevant settings to operation
|
||||||
| `/status` | | Lists all open trades
|
| `/status` | | Lists all open trades
|
||||||
| `/status table` | | List all open trades in a table format
|
| `/status table` | | List all open trades in a table format
|
||||||
| `/count` | | Displays number of trades used and available
|
| `/count` | | Displays number of trades used and available
|
||||||
@@ -93,7 +94,7 @@ Once all positions are sold, run `/stop` to completely stop the bot.
|
|||||||
|
|
||||||
`/reload_conf` resets "max_open_trades" to the value set in the configuration and resets this command.
|
`/reload_conf` resets "max_open_trades" to the value set in the configuration and resets this command.
|
||||||
|
|
||||||
!!! warning
|
!!! Warning
|
||||||
The stop-buy signal is ONLY active while the bot is running, and is not persisted anyway, so restarting the bot will cause this to reset.
|
The stop-buy signal is ONLY active while the bot is running, and is not persisted anyway, so restarting the bot will cause this to reset.
|
||||||
|
|
||||||
### /status
|
### /status
|
||||||
|
|||||||
329
docs/utils.md
Normal file
329
docs/utils.md
Normal file
@@ -0,0 +1,329 @@
|
|||||||
|
# Utility Subcommands
|
||||||
|
|
||||||
|
Besides the Live-Trade and Dry-Run run modes, the `backtesting`, `edge` and `hyperopt` optimization subcommands, and the `download-data` subcommand which prepares historical data, the bot contains a number of utility subcommands. They are described in this section.
|
||||||
|
|
||||||
|
## Create userdir
|
||||||
|
|
||||||
|
Creates the directory structure to hold your files for freqtrade.
|
||||||
|
Will also create strategy and hyperopt examples for you to get started.
|
||||||
|
Can be used multiple times - using `--reset` will reset the sample strategy and hyperopt files to their default state.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade create-userdir [-h] [--userdir PATH] [--reset]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
--reset Reset sample files to their original state.
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Warning
|
||||||
|
Using `--reset` may result in loss of data, since this will overwrite all sample files without asking again.
|
||||||
|
|
||||||
|
```
|
||||||
|
├── backtest_results
|
||||||
|
├── data
|
||||||
|
├── hyperopt_results
|
||||||
|
├── hyperopts
|
||||||
|
│ ├── sample_hyperopt_advanced.py
|
||||||
|
│ ├── sample_hyperopt_loss.py
|
||||||
|
│ └── sample_hyperopt.py
|
||||||
|
├── notebooks
|
||||||
|
│ └── strategy_analysis_example.ipynb
|
||||||
|
├── plot
|
||||||
|
└── strategies
|
||||||
|
└── sample_strategy.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## Create new strategy
|
||||||
|
|
||||||
|
Creates a new strategy from a template similar to SampleStrategy.
|
||||||
|
The file will be named inline with your class name, and will not overwrite existing files.
|
||||||
|
|
||||||
|
Results will be located in `user_data/strategies/<strategyclassname>.py`.
|
||||||
|
|
||||||
|
``` output
|
||||||
|
usage: freqtrade new-strategy [-h] [--userdir PATH] [-s NAME]
|
||||||
|
[--template {full,minimal}]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
-s NAME, --strategy NAME
|
||||||
|
Specify strategy class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--template {full,minimal}
|
||||||
|
Use a template which is either `minimal` or `full`
|
||||||
|
(containing multiple sample indicators). Default:
|
||||||
|
`full`.
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
### Sample usage of new-strategy
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade new-strategy --strategy AwesomeStrategy
|
||||||
|
```
|
||||||
|
|
||||||
|
With custom user directory
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade new-strategy --userdir ~/.freqtrade/ --strategy AwesomeStrategy
|
||||||
|
```
|
||||||
|
|
||||||
|
## Create new hyperopt
|
||||||
|
|
||||||
|
Creates a new hyperopt from a template similar to SampleHyperopt.
|
||||||
|
The file will be named inline with your class name, and will not overwrite existing files.
|
||||||
|
|
||||||
|
Results will be located in `user_data/hyperopts/<classname>.py`.
|
||||||
|
|
||||||
|
``` output
|
||||||
|
usage: freqtrade new-hyperopt [-h] [--userdir PATH] [--hyperopt NAME]
|
||||||
|
[--template {full,minimal}]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
--hyperopt NAME Specify hyperopt class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--template {full,minimal}
|
||||||
|
Use a template which is either `minimal` or `full`
|
||||||
|
(containing multiple sample indicators). Default:
|
||||||
|
`full`.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Sample usage of new-hyperopt
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade new-hyperopt --hyperopt AwesomeHyperopt
|
||||||
|
```
|
||||||
|
|
||||||
|
With custom user directory
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade new-hyperopt --userdir ~/.freqtrade/ --hyperopt AwesomeHyperopt
|
||||||
|
```
|
||||||
|
|
||||||
|
## List Exchanges
|
||||||
|
|
||||||
|
Use the `list-exchanges` subcommand to see the exchanges available for the bot.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade list-exchanges [-h] [-1] [-a]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
-1, --one-column Print output in one column.
|
||||||
|
-a, --all Print all exchanges known to the ccxt library.
|
||||||
|
```
|
||||||
|
|
||||||
|
* Example: see exchanges available for the bot:
|
||||||
|
```
|
||||||
|
$ freqtrade list-exchanges
|
||||||
|
Exchanges available for Freqtrade: _1btcxe, acx, allcoin, bequant, bibox, binance, binanceje, binanceus, bitbank, bitfinex, bitfinex2, bitkk, bitlish, bitmart, bittrex, bitz, bleutrade, btcalpha, btcmarkets, btcturk, buda, cex, cobinhood, coinbaseprime, coinbasepro, coinex, cointiger, coss, crex24, digifinex, dsx, dx, ethfinex, fcoin, fcoinjp, gateio, gdax, gemini, hitbtc2, huobipro, huobiru, idex, kkex, kraken, kucoin, kucoin2, kuna, lbank, mandala, mercado, oceanex, okcoincny, okcoinusd, okex, okex3, poloniex, rightbtc, theocean, tidebit, upbit, zb
|
||||||
|
```
|
||||||
|
|
||||||
|
* Example: see all exchanges supported by the ccxt library (including 'bad' ones, i.e. those that are known to not work with Freqtrade):
|
||||||
|
```
|
||||||
|
$ freqtrade list-exchanges -a
|
||||||
|
All exchanges supported by the ccxt library: _1btcxe, acx, adara, allcoin, anxpro, bcex, bequant, bibox, bigone, binance, binanceje, binanceus, bit2c, bitbank, bitbay, bitfinex, bitfinex2, bitflyer, bitforex, bithumb, bitkk, bitlish, bitmart, bitmex, bitso, bitstamp, bitstamp1, bittrex, bitz, bl3p, bleutrade, braziliex, btcalpha, btcbox, btcchina, btcmarkets, btctradeim, btctradeua, btcturk, buda, bxinth, cex, chilebit, cobinhood, coinbase, coinbaseprime, coinbasepro, coincheck, coinegg, coinex, coinexchange, coinfalcon, coinfloor, coingi, coinmarketcap, coinmate, coinone, coinspot, cointiger, coolcoin, coss, crex24, crypton, deribit, digifinex, dsx, dx, ethfinex, exmo, exx, fcoin, fcoinjp, flowbtc, foxbit, fybse, gateio, gdax, gemini, hitbtc, hitbtc2, huobipro, huobiru, ice3x, idex, independentreserve, indodax, itbit, kkex, kraken, kucoin, kucoin2, kuna, lakebtc, latoken, lbank, liquid, livecoin, luno, lykke, mandala, mercado, mixcoins, negociecoins, nova, oceanex, okcoincny, okcoinusd, okex, okex3, paymium, poloniex, rightbtc, southxchange, stronghold, surbitcoin, theocean, therock, tidebit, tidex, upbit, vaultoro, vbtc, virwox, xbtce, yobit, zaif, zb
|
||||||
|
```
|
||||||
|
|
||||||
|
## List Timeframes
|
||||||
|
|
||||||
|
Use the `list-timeframes` subcommand to see the list of ticker intervals (timeframes) available for the exchange.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade list-timeframes [-h] [--exchange EXCHANGE] [-1]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||||
|
config is provided.
|
||||||
|
-1, --one-column Print output in one column.
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
* Example: see the timeframes for the 'binance' exchange, set in the configuration file:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ freqtrade -c config_binance.json list-timeframes
|
||||||
|
...
|
||||||
|
Timeframes available for the exchange `binance`: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M
|
||||||
|
```
|
||||||
|
|
||||||
|
* Example: enumerate exchanges available for Freqtrade and print timeframes supported by each of them:
|
||||||
|
```
|
||||||
|
$ for i in `freqtrade list-exchanges -1`; do freqtrade list-timeframes --exchange $i; done
|
||||||
|
```
|
||||||
|
|
||||||
|
## List pairs/list markets
|
||||||
|
|
||||||
|
The `list-pairs` and `list-markets` subcommands allow to see the pairs/markets available on exchange.
|
||||||
|
|
||||||
|
Pairs are markets with the '/' character between the base currency part and the quote currency part in the market symbol.
|
||||||
|
For example, in the 'ETH/BTC' pair 'ETH' is the base currency, while 'BTC' is the quote currency.
|
||||||
|
|
||||||
|
For pairs traded by Freqtrade the pair quote currency is defined by the value of the `stake_currency` configuration setting.
|
||||||
|
|
||||||
|
You can print info about any pair/market with these subcommands - and you can filter output by quote-currency using `--quote BTC`, or by base-currency using `--base ETH` options correspondingly.
|
||||||
|
|
||||||
|
These subcommands have same usage and same set of available options:
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade list-markets [-h] [--exchange EXCHANGE] [--print-list]
|
||||||
|
[--print-json] [-1] [--print-csv]
|
||||||
|
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
||||||
|
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]
|
||||||
|
[-a]
|
||||||
|
|
||||||
|
usage: freqtrade list-pairs [-h] [--exchange EXCHANGE] [--print-list]
|
||||||
|
[--print-json] [-1] [--print-csv]
|
||||||
|
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
||||||
|
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||||
|
config is provided.
|
||||||
|
--print-list Print list of pairs or market symbols. By default data
|
||||||
|
is printed in the tabular format.
|
||||||
|
--print-json Print list of pairs or market symbols in JSON format.
|
||||||
|
-1, --one-column Print output in one column.
|
||||||
|
--print-csv Print exchange pair or market data in the csv format.
|
||||||
|
--base BASE_CURRENCY [BASE_CURRENCY ...]
|
||||||
|
Specify base currency(-ies). Space-separated list.
|
||||||
|
--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]
|
||||||
|
Specify quote currency(-ies). Space-separated list.
|
||||||
|
-a, --all Print all pairs or market symbols. By default only
|
||||||
|
active ones are shown.
|
||||||
|
```
|
||||||
|
|
||||||
|
By default, only active pairs/markets are shown. Active pairs/markets are those that can currently be traded
|
||||||
|
on the exchange. The see the list of all pairs/markets (not only the active ones), use the `-a`/`-all` option.
|
||||||
|
|
||||||
|
Pairs/markets are sorted by its symbol string in the printed output.
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
* Print the list of active pairs with quote currency USD on exchange, specified in the default
|
||||||
|
configuration file (i.e. pairs on the "Bittrex" exchange) in JSON format:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ freqtrade list-pairs --quote USD --print-json
|
||||||
|
```
|
||||||
|
|
||||||
|
* Print the list of all pairs on the exchange, specified in the `config_binance.json` configuration file
|
||||||
|
(i.e. on the "Binance" exchange) with base currencies BTC or ETH and quote currencies USDT or USD, as the
|
||||||
|
human-readable list with summary:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ freqtrade -c config_binance.json list-pairs --all --base BTC ETH --quote USDT USD --print-list
|
||||||
|
```
|
||||||
|
|
||||||
|
* Print all markets on exchange "Kraken", in the tabular format:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ freqtrade list-markets --exchange kraken --all
|
||||||
|
```
|
||||||
|
|
||||||
|
## Test pairlist
|
||||||
|
|
||||||
|
Use the `test-pairlist` subcommand to test the configuration of [dynamic pairlists](configuration.md#pairlists).
|
||||||
|
|
||||||
|
Requires a configuration with specified `pairlists` attribute.
|
||||||
|
Can be used to generate static pairlists to be used during backtesting / hyperopt.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade test-pairlist [-h] [-c PATH]
|
||||||
|
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]
|
||||||
|
[-1] [--print-json]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
-c PATH, --config PATH
|
||||||
|
Specify configuration file (default: `config.json`).
|
||||||
|
Multiple --config options may be used. Can be set to
|
||||||
|
`-` to read config from stdin.
|
||||||
|
--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]
|
||||||
|
Specify quote currency(-ies). Space-separated list.
|
||||||
|
-1, --one-column Print output in one column.
|
||||||
|
--print-json Print list of pairs or market symbols in JSON format.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
Show whitelist when using a [dynamic pairlist](configuration.md#pairlists).
|
||||||
|
|
||||||
|
```
|
||||||
|
freqtrade test-pairlist --config config.json --quote USDT BTC
|
||||||
|
```
|
||||||
|
|
||||||
|
## List Hyperopt results
|
||||||
|
|
||||||
|
You can list the hyperoptimization epochs the Hyperopt module evaluated previously with the `hyperopt-list` subcommand.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade hyperopt-list [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
|
[-d PATH] [--userdir PATH] [--best]
|
||||||
|
[--profitable] [--no-color] [--print-json]
|
||||||
|
[--no-details]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--best Select only best epochs.
|
||||||
|
--profitable Select only profitable epochs.
|
||||||
|
--no-color Disable colorization of hyperopt results. May be
|
||||||
|
useful if you are redirecting output to a file.
|
||||||
|
--print-json Print best result detailization in JSON format.
|
||||||
|
--no-details Do not print best epoch details.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
List all results, print details of the best result at the end:
|
||||||
|
```
|
||||||
|
freqtrade hyperopt-list
|
||||||
|
```
|
||||||
|
|
||||||
|
List only epochs with positive profit. Do not print the details of the best epoch, so that the list can be iterated in a script:
|
||||||
|
```
|
||||||
|
freqtrade hyperopt-list --profitable --no-details
|
||||||
|
```
|
||||||
|
|
||||||
|
## Show details of Hyperopt results
|
||||||
|
|
||||||
|
You can show the details of any hyperoptimization epoch previously evaluated by the Hyperopt module with the `hyperopt-show` subcommand.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade hyperopt-show [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
|
[-d PATH] [--userdir PATH] [--best]
|
||||||
|
[--profitable] [-n INT] [--print-json]
|
||||||
|
[--no-header]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--best Select only best epochs.
|
||||||
|
--profitable Select only profitable epochs.
|
||||||
|
-n INT, --index INT Specify the index of the epoch to print details for.
|
||||||
|
--print-json Print best result detailization in JSON format.
|
||||||
|
--no-header Do not print epoch details header.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
Print details for the epoch 168 (the number of the epoch is shown by the `hyperopt-list` subcommand or by Hyperopt itself during hyperoptimization run):
|
||||||
|
|
||||||
|
```
|
||||||
|
freqtrade hyperopt-show -n 168
|
||||||
|
```
|
||||||
|
|
||||||
|
Prints JSON data with details for the last best epoch (i.e., the best of all epochs):
|
||||||
|
|
||||||
|
```
|
||||||
|
freqtrade hyperopt-show --best -n -1 --print-json --no-header
|
||||||
|
```
|
||||||
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
|
ExecStart=/usr/bin/freqtrade trade
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ After=network.target
|
|||||||
# Set WorkingDirectory and ExecStart to your file paths accordingly
|
# Set WorkingDirectory and ExecStart to your file paths accordingly
|
||||||
# NOTE: %h will be resolved to /home/<username>
|
# NOTE: %h will be resolved to /home/<username>
|
||||||
WorkingDirectory=%h/freqtrade
|
WorkingDirectory=%h/freqtrade
|
||||||
ExecStart=/usr/bin/freqtrade --sd-notify
|
ExecStart=/usr/bin/freqtrade trade --sd-notify
|
||||||
|
|
||||||
Restart=always
|
Restart=always
|
||||||
#Restart=on-failure
|
#Restart=on-failure
|
||||||
|
|||||||
@@ -1,5 +1,16 @@
|
|||||||
""" FreqTrade bot """
|
""" FreqTrade bot """
|
||||||
__version__ = '2019.7'
|
__version__ = '2019.11'
|
||||||
|
|
||||||
|
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(Exception):
|
class DependencyException(Exception):
|
||||||
@@ -11,7 +22,7 @@ class DependencyException(Exception):
|
|||||||
|
|
||||||
class OperationalException(Exception):
|
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.
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -1,2 +1,5 @@
|
|||||||
from freqtrade.configuration.arguments import Arguments, TimeRange # noqa: F401
|
from freqtrade.configuration.arguments import Arguments # noqa: F401
|
||||||
|
from freqtrade.configuration.check_exchange import check_exchange, remove_credentials # noqa: F401
|
||||||
|
from freqtrade.configuration.timerange import TimeRange # noqa: F401
|
||||||
from freqtrade.configuration.configuration import Configuration # noqa: F401
|
from freqtrade.configuration.configuration import Configuration # noqa: F401
|
||||||
|
from freqtrade.configuration.config_validation import validate_config_consistency # noqa: F401
|
||||||
|
|||||||
@@ -2,83 +2,90 @@
|
|||||||
This module contains the argument manager class
|
This module contains the argument manager class
|
||||||
"""
|
"""
|
||||||
import argparse
|
import argparse
|
||||||
import re
|
from functools import partial
|
||||||
from typing import List, NamedTuple, Optional
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
import arrow
|
|
||||||
from freqtrade.configuration.cli_options import AVAILABLE_CLI_OPTIONS
|
|
||||||
from freqtrade import constants
|
from freqtrade import constants
|
||||||
|
from freqtrade.configuration.cli_options import AVAILABLE_CLI_OPTIONS
|
||||||
|
|
||||||
ARGS_COMMON = ["verbosity", "logfile", "version", "config", "datadir"]
|
ARGS_COMMON = ["verbosity", "logfile", "version", "config", "datadir", "user_data_dir"]
|
||||||
|
|
||||||
ARGS_STRATEGY = ["strategy", "strategy_path"]
|
ARGS_STRATEGY = ["strategy", "strategy_path"]
|
||||||
|
|
||||||
ARGS_MAIN = ARGS_COMMON + ARGS_STRATEGY + ["db_url", "sd_notify"]
|
ARGS_TRADE = ["db_url", "sd_notify", "dry_run"]
|
||||||
|
|
||||||
ARGS_COMMON_OPTIMIZE = ["ticker_interval", "timerange",
|
ARGS_COMMON_OPTIMIZE = ["ticker_interval", "timerange",
|
||||||
"max_open_trades", "stake_amount", "refresh_pairs"]
|
"max_open_trades", "stake_amount", "fee"]
|
||||||
|
|
||||||
ARGS_BACKTEST = ARGS_COMMON_OPTIMIZE + ["position_stacking", "use_max_market_positions",
|
ARGS_BACKTEST = ARGS_COMMON_OPTIMIZE + ["position_stacking", "use_max_market_positions",
|
||||||
"live", "strategy_list", "export", "exportfilename"]
|
"strategy_list", "export", "exportfilename"]
|
||||||
|
|
||||||
ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
|
ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
|
||||||
"position_stacking", "epochs", "spaces",
|
"position_stacking", "epochs", "spaces",
|
||||||
"use_max_market_positions", "print_all", "hyperopt_jobs",
|
"use_max_market_positions", "print_all",
|
||||||
|
"print_colorized", "print_json", "hyperopt_jobs",
|
||||||
"hyperopt_random_state", "hyperopt_min_trades",
|
"hyperopt_random_state", "hyperopt_min_trades",
|
||||||
"hyperopt_continue", "hyperopt_loss"]
|
"hyperopt_continue", "hyperopt_loss"]
|
||||||
|
|
||||||
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
|
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
|
||||||
|
|
||||||
ARGS_LIST_EXCHANGES = ["print_one_column"]
|
ARGS_LIST_EXCHANGES = ["print_one_column", "list_exchanges_all"]
|
||||||
|
|
||||||
ARGS_DOWNLOADER = ARGS_COMMON + ["pairs", "pairs_file", "days", "exchange", "timeframes", "erase"]
|
ARGS_LIST_TIMEFRAMES = ["exchange", "print_one_column"]
|
||||||
|
|
||||||
ARGS_PLOT_DATAFRAME = (ARGS_COMMON + ARGS_STRATEGY +
|
ARGS_LIST_PAIRS = ["exchange", "print_list", "list_pairs_print_json", "print_one_column",
|
||||||
["pairs", "indicators1", "indicators2", "plot_limit", "db_url",
|
"print_csv", "base_currencies", "quote_currencies", "list_pairs_all"]
|
||||||
"trade_source", "export", "exportfilename", "timerange",
|
|
||||||
"refresh_pairs", "live"])
|
|
||||||
|
|
||||||
ARGS_PLOT_PROFIT = (ARGS_COMMON + ARGS_STRATEGY +
|
ARGS_TEST_PAIRLIST = ["config", "quote_currencies", "print_one_column", "list_pairs_print_json"]
|
||||||
["pairs", "timerange", "export", "exportfilename", "db_url", "trade_source"])
|
|
||||||
|
ARGS_CREATE_USERDIR = ["user_data_dir", "reset"]
|
||||||
|
|
||||||
|
ARGS_BUILD_STRATEGY = ["user_data_dir", "strategy", "template"]
|
||||||
|
|
||||||
|
ARGS_BUILD_HYPEROPT = ["user_data_dir", "hyperopt", "template"]
|
||||||
|
|
||||||
|
ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "download_trades", "exchange",
|
||||||
|
"timeframes", "erase"]
|
||||||
|
|
||||||
|
ARGS_PLOT_DATAFRAME = ["pairs", "indicators1", "indicators2", "plot_limit",
|
||||||
|
"db_url", "trade_source", "export", "exportfilename",
|
||||||
|
"timerange", "ticker_interval"]
|
||||||
|
|
||||||
|
ARGS_PLOT_PROFIT = ["pairs", "timerange", "export", "exportfilename", "db_url",
|
||||||
|
"trade_source", "ticker_interval"]
|
||||||
|
|
||||||
|
ARGS_HYPEROPT_LIST = ["hyperopt_list_best", "hyperopt_list_profitable", "print_colorized",
|
||||||
|
"print_json", "hyperopt_list_no_details"]
|
||||||
|
|
||||||
|
ARGS_HYPEROPT_SHOW = ["hyperopt_list_best", "hyperopt_list_profitable", "hyperopt_show_index",
|
||||||
|
"print_json", "hyperopt_show_no_header"]
|
||||||
|
|
||||||
|
NO_CONF_REQURIED = ["download-data", "list-timeframes", "list-markets", "list-pairs",
|
||||||
|
"hyperopt-list", "hyperopt-show", "plot-dataframe", "plot-profit"]
|
||||||
|
|
||||||
|
NO_CONF_ALLOWED = ["create-userdir", "list-exchanges", "new-hyperopt", "new-strategy"]
|
||||||
|
|
||||||
|
|
||||||
class TimeRange(NamedTuple):
|
class Arguments:
|
||||||
"""
|
|
||||||
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
|
Arguments Class. Manage the arguments received by the cli
|
||||||
"""
|
"""
|
||||||
def __init__(self, args: Optional[List[str]], description: str,
|
|
||||||
no_default_config: bool = False) -> None:
|
def __init__(self, args: Optional[List[str]]) -> None:
|
||||||
self.args = args
|
self.args = args
|
||||||
self._parsed_arg: Optional[argparse.Namespace] = None
|
self._parsed_arg: Optional[argparse.Namespace] = None
|
||||||
self.parser = argparse.ArgumentParser(description=description)
|
|
||||||
self._no_default_config = no_default_config
|
|
||||||
|
|
||||||
def _load_args(self) -> None:
|
def get_parsed_arg(self) -> Dict[str, Any]:
|
||||||
self._build_args(optionlist=ARGS_MAIN)
|
|
||||||
self._build_subcommands()
|
|
||||||
|
|
||||||
def get_parsed_arg(self) -> argparse.Namespace:
|
|
||||||
"""
|
"""
|
||||||
Return the list of arguments
|
Return the list of arguments
|
||||||
:return: List[str] List of arguments
|
:return: List[str] List of arguments
|
||||||
"""
|
"""
|
||||||
if self._parsed_arg is None:
|
if self._parsed_arg is None:
|
||||||
self._load_args()
|
self._build_subcommands()
|
||||||
self._parsed_arg = self._parse_args()
|
self._parsed_arg = self._parse_args()
|
||||||
|
|
||||||
return self._parsed_arg
|
return vars(self._parsed_arg)
|
||||||
|
|
||||||
def _parse_args(self) -> argparse.Namespace:
|
def _parse_args(self) -> argparse.Namespace:
|
||||||
"""
|
"""
|
||||||
@@ -88,13 +95,15 @@ class Arguments(object):
|
|||||||
|
|
||||||
# Workaround issue in argparse with action='append' and default value
|
# Workaround issue in argparse with action='append' and default value
|
||||||
# (see https://bugs.python.org/issue16399)
|
# (see https://bugs.python.org/issue16399)
|
||||||
if not self._no_default_config and parsed_arg.config is None:
|
# Allow no-config for certain commands (like downloading / plotting)
|
||||||
|
if ('config' in parsed_arg and parsed_arg.config is None and
|
||||||
|
((Path.cwd() / constants.DEFAULT_CONFIG).is_file() or
|
||||||
|
not ('command' in parsed_arg and parsed_arg.command in NO_CONF_REQURIED))):
|
||||||
parsed_arg.config = [constants.DEFAULT_CONFIG]
|
parsed_arg.config = [constants.DEFAULT_CONFIG]
|
||||||
|
|
||||||
return parsed_arg
|
return parsed_arg
|
||||||
|
|
||||||
def _build_args(self, optionlist, parser=None):
|
def _build_args(self, optionlist, parser):
|
||||||
parser = parser or self.parser
|
|
||||||
|
|
||||||
for val in optionlist:
|
for val in optionlist:
|
||||||
opt = AVAILABLE_CLI_OPTIONS[val]
|
opt = AVAILABLE_CLI_OPTIONS[val]
|
||||||
@@ -105,72 +114,162 @@ class Arguments(object):
|
|||||||
Builds and attaches all subcommands.
|
Builds and attaches all subcommands.
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
from freqtrade.optimize import start_backtesting, start_hyperopt, start_edge
|
# Build shared arguments (as group Common Options)
|
||||||
from freqtrade.utils import start_list_exchanges
|
_common_parser = argparse.ArgumentParser(add_help=False)
|
||||||
|
group = _common_parser.add_argument_group("Common arguments")
|
||||||
|
self._build_args(optionlist=ARGS_COMMON, parser=group)
|
||||||
|
|
||||||
subparsers = self.parser.add_subparsers(dest='subparser')
|
_strategy_parser = argparse.ArgumentParser(add_help=False)
|
||||||
|
strategy_group = _strategy_parser.add_argument_group("Strategy arguments")
|
||||||
|
self._build_args(optionlist=ARGS_STRATEGY, parser=strategy_group)
|
||||||
|
|
||||||
|
# Build main command
|
||||||
|
self.parser = argparse.ArgumentParser(description='Free, open source crypto trading bot')
|
||||||
|
self._build_args(optionlist=['version'], parser=self.parser)
|
||||||
|
|
||||||
|
from freqtrade.optimize import start_backtesting, start_hyperopt, start_edge
|
||||||
|
from freqtrade.utils import (start_create_userdir, start_download_data,
|
||||||
|
start_hyperopt_list, start_hyperopt_show,
|
||||||
|
start_list_exchanges, start_list_markets,
|
||||||
|
start_new_hyperopt, start_new_strategy,
|
||||||
|
start_list_timeframes, start_test_pairlist, start_trading)
|
||||||
|
from freqtrade.plot.plot_utils import start_plot_dataframe, start_plot_profit
|
||||||
|
|
||||||
|
subparsers = self.parser.add_subparsers(dest='command',
|
||||||
|
# Use custom message when no subhandler is added
|
||||||
|
# shown from `main.py`
|
||||||
|
# required=True
|
||||||
|
)
|
||||||
|
|
||||||
|
# Add trade subcommand
|
||||||
|
trade_cmd = subparsers.add_parser('trade', help='Trade module.',
|
||||||
|
parents=[_common_parser, _strategy_parser])
|
||||||
|
trade_cmd.set_defaults(func=start_trading)
|
||||||
|
self._build_args(optionlist=ARGS_TRADE, parser=trade_cmd)
|
||||||
|
|
||||||
# Add backtesting subcommand
|
# Add backtesting subcommand
|
||||||
backtesting_cmd = subparsers.add_parser('backtesting', help='Backtesting module.')
|
backtesting_cmd = subparsers.add_parser('backtesting', help='Backtesting module.',
|
||||||
|
parents=[_common_parser, _strategy_parser])
|
||||||
backtesting_cmd.set_defaults(func=start_backtesting)
|
backtesting_cmd.set_defaults(func=start_backtesting)
|
||||||
self._build_args(optionlist=ARGS_BACKTEST, parser=backtesting_cmd)
|
self._build_args(optionlist=ARGS_BACKTEST, parser=backtesting_cmd)
|
||||||
|
|
||||||
# Add edge subcommand
|
# Add edge subcommand
|
||||||
edge_cmd = subparsers.add_parser('edge', help='Edge module.')
|
edge_cmd = subparsers.add_parser('edge', help='Edge module.',
|
||||||
|
parents=[_common_parser, _strategy_parser])
|
||||||
edge_cmd.set_defaults(func=start_edge)
|
edge_cmd.set_defaults(func=start_edge)
|
||||||
self._build_args(optionlist=ARGS_EDGE, parser=edge_cmd)
|
self._build_args(optionlist=ARGS_EDGE, parser=edge_cmd)
|
||||||
|
|
||||||
# Add hyperopt subcommand
|
# Add hyperopt subcommand
|
||||||
hyperopt_cmd = subparsers.add_parser('hyperopt', help='Hyperopt module.')
|
hyperopt_cmd = subparsers.add_parser('hyperopt', help='Hyperopt module.',
|
||||||
|
parents=[_common_parser, _strategy_parser],
|
||||||
|
)
|
||||||
hyperopt_cmd.set_defaults(func=start_hyperopt)
|
hyperopt_cmd.set_defaults(func=start_hyperopt)
|
||||||
self._build_args(optionlist=ARGS_HYPEROPT, parser=hyperopt_cmd)
|
self._build_args(optionlist=ARGS_HYPEROPT, parser=hyperopt_cmd)
|
||||||
|
|
||||||
|
# add create-userdir subcommand
|
||||||
|
create_userdir_cmd = subparsers.add_parser('create-userdir',
|
||||||
|
help="Create user-data directory.",
|
||||||
|
)
|
||||||
|
create_userdir_cmd.set_defaults(func=start_create_userdir)
|
||||||
|
self._build_args(optionlist=ARGS_CREATE_USERDIR, parser=create_userdir_cmd)
|
||||||
|
|
||||||
|
# add new-strategy subcommand
|
||||||
|
build_strategy_cmd = subparsers.add_parser('new-strategy',
|
||||||
|
help="Create new strategy")
|
||||||
|
build_strategy_cmd.set_defaults(func=start_new_strategy)
|
||||||
|
self._build_args(optionlist=ARGS_BUILD_STRATEGY, parser=build_strategy_cmd)
|
||||||
|
|
||||||
|
# add new-hyperopt subcommand
|
||||||
|
build_hyperopt_cmd = subparsers.add_parser('new-hyperopt',
|
||||||
|
help="Create new hyperopt")
|
||||||
|
build_hyperopt_cmd.set_defaults(func=start_new_hyperopt)
|
||||||
|
self._build_args(optionlist=ARGS_BUILD_HYPEROPT, parser=build_hyperopt_cmd)
|
||||||
|
|
||||||
# Add list-exchanges subcommand
|
# Add list-exchanges subcommand
|
||||||
list_exchanges_cmd = subparsers.add_parser(
|
list_exchanges_cmd = subparsers.add_parser(
|
||||||
'list-exchanges',
|
'list-exchanges',
|
||||||
help='Print available exchanges.'
|
help='Print available exchanges.',
|
||||||
|
parents=[_common_parser],
|
||||||
)
|
)
|
||||||
list_exchanges_cmd.set_defaults(func=start_list_exchanges)
|
list_exchanges_cmd.set_defaults(func=start_list_exchanges)
|
||||||
self._build_args(optionlist=ARGS_LIST_EXCHANGES, parser=list_exchanges_cmd)
|
self._build_args(optionlist=ARGS_LIST_EXCHANGES, parser=list_exchanges_cmd)
|
||||||
|
|
||||||
@staticmethod
|
# Add list-timeframes subcommand
|
||||||
def parse_timerange(text: Optional[str]) -> TimeRange:
|
list_timeframes_cmd = subparsers.add_parser(
|
||||||
"""
|
'list-timeframes',
|
||||||
Parse the value of the argument --timerange to determine what is the range desired
|
help='Print available ticker intervals (timeframes) for the exchange.',
|
||||||
:param text: value from --timerange
|
parents=[_common_parser],
|
||||||
:return: Start and End range period
|
)
|
||||||
"""
|
list_timeframes_cmd.set_defaults(func=start_list_timeframes)
|
||||||
if text is None:
|
self._build_args(optionlist=ARGS_LIST_TIMEFRAMES, parser=list_timeframes_cmd)
|
||||||
return TimeRange(None, None, 0, 0)
|
|
||||||
syntax = [(r'^-(\d{8})$', (None, 'date')),
|
# Add list-markets subcommand
|
||||||
(r'^(\d{8})-$', ('date', None)),
|
list_markets_cmd = subparsers.add_parser(
|
||||||
(r'^(\d{8})-(\d{8})$', ('date', 'date')),
|
'list-markets',
|
||||||
(r'^-(\d{10})$', (None, 'date')),
|
help='Print markets on exchange.',
|
||||||
(r'^(\d{10})-$', ('date', None)),
|
parents=[_common_parser],
|
||||||
(r'^(\d{10})-(\d{10})$', ('date', 'date')),
|
)
|
||||||
(r'^(-\d+)$', (None, 'line')),
|
list_markets_cmd.set_defaults(func=partial(start_list_markets, pairs_only=False))
|
||||||
(r'^(\d+)-$', ('line', None)),
|
self._build_args(optionlist=ARGS_LIST_PAIRS, parser=list_markets_cmd)
|
||||||
(r'^(\d+)-(\d+)$', ('index', 'index'))]
|
|
||||||
for rex, stype in syntax:
|
# Add list-pairs subcommand
|
||||||
# Apply the regular expression to text
|
list_pairs_cmd = subparsers.add_parser(
|
||||||
match = re.match(rex, text)
|
'list-pairs',
|
||||||
if match: # Regex has matched
|
help='Print pairs on exchange.',
|
||||||
rvals = match.groups()
|
parents=[_common_parser],
|
||||||
index = 0
|
)
|
||||||
start: int = 0
|
list_pairs_cmd.set_defaults(func=partial(start_list_markets, pairs_only=True))
|
||||||
stop: int = 0
|
self._build_args(optionlist=ARGS_LIST_PAIRS, parser=list_pairs_cmd)
|
||||||
if stype[0]:
|
|
||||||
starts = rvals[index]
|
# Add test-pairlist subcommand
|
||||||
if stype[0] == 'date' and len(starts) == 8:
|
test_pairlist_cmd = subparsers.add_parser(
|
||||||
start = arrow.get(starts, 'YYYYMMDD').timestamp
|
'test-pairlist',
|
||||||
else:
|
help='Test your pairlist configuration.',
|
||||||
start = int(starts)
|
)
|
||||||
index += 1
|
test_pairlist_cmd.set_defaults(func=start_test_pairlist)
|
||||||
if stype[1]:
|
self._build_args(optionlist=ARGS_TEST_PAIRLIST, parser=test_pairlist_cmd)
|
||||||
stops = rvals[index]
|
|
||||||
if stype[1] == 'date' and len(stops) == 8:
|
# Add download-data subcommand
|
||||||
stop = arrow.get(stops, 'YYYYMMDD').timestamp
|
download_data_cmd = subparsers.add_parser(
|
||||||
else:
|
'download-data',
|
||||||
stop = int(stops)
|
help='Download backtesting data.',
|
||||||
return TimeRange(stype[0], stype[1], start, stop)
|
parents=[_common_parser],
|
||||||
raise Exception('Incorrect syntax for timerange "%s"' % text)
|
)
|
||||||
|
download_data_cmd.set_defaults(func=start_download_data)
|
||||||
|
self._build_args(optionlist=ARGS_DOWNLOAD_DATA, parser=download_data_cmd)
|
||||||
|
|
||||||
|
# Add Plotting subcommand
|
||||||
|
plot_dataframe_cmd = subparsers.add_parser(
|
||||||
|
'plot-dataframe',
|
||||||
|
help='Plot candles with indicators.',
|
||||||
|
parents=[_common_parser, _strategy_parser],
|
||||||
|
)
|
||||||
|
plot_dataframe_cmd.set_defaults(func=start_plot_dataframe)
|
||||||
|
self._build_args(optionlist=ARGS_PLOT_DATAFRAME, parser=plot_dataframe_cmd)
|
||||||
|
|
||||||
|
# Plot profit
|
||||||
|
plot_profit_cmd = subparsers.add_parser(
|
||||||
|
'plot-profit',
|
||||||
|
help='Generate plot showing profits.',
|
||||||
|
parents=[_common_parser],
|
||||||
|
)
|
||||||
|
plot_profit_cmd.set_defaults(func=start_plot_profit)
|
||||||
|
self._build_args(optionlist=ARGS_PLOT_PROFIT, parser=plot_profit_cmd)
|
||||||
|
|
||||||
|
# Add hyperopt-list subcommand
|
||||||
|
hyperopt_list_cmd = subparsers.add_parser(
|
||||||
|
'hyperopt-list',
|
||||||
|
help='List Hyperopt results',
|
||||||
|
parents=[_common_parser],
|
||||||
|
)
|
||||||
|
hyperopt_list_cmd.set_defaults(func=start_hyperopt_list)
|
||||||
|
self._build_args(optionlist=ARGS_HYPEROPT_LIST, parser=hyperopt_list_cmd)
|
||||||
|
|
||||||
|
# Add hyperopt-show subcommand
|
||||||
|
hyperopt_show_cmd = subparsers.add_parser(
|
||||||
|
'hyperopt-show',
|
||||||
|
help='Show details of Hyperopt results',
|
||||||
|
parents=[_common_parser],
|
||||||
|
)
|
||||||
|
hyperopt_show_cmd.set_defaults(func=start_hyperopt_show)
|
||||||
|
self._build_args(optionlist=ARGS_HYPEROPT_SHOW, parser=hyperopt_show_cmd)
|
||||||
|
|||||||
@@ -2,13 +2,27 @@ import logging
|
|||||||
from typing import Any, Dict
|
from typing import Any, Dict
|
||||||
|
|
||||||
from freqtrade import OperationalException
|
from freqtrade import OperationalException
|
||||||
from freqtrade.exchange import (is_exchange_bad, is_exchange_available,
|
from freqtrade.exchange import (available_exchanges, get_exchange_bad_reason,
|
||||||
is_exchange_officially_supported, available_exchanges)
|
is_exchange_known_ccxt, is_exchange_bad,
|
||||||
|
is_exchange_officially_supported)
|
||||||
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def remove_credentials(config: Dict[str, Any]):
|
||||||
|
"""
|
||||||
|
Removes exchange keys from the configuration and specifies dry-run
|
||||||
|
Used for backtesting / hyperopt / edge and utils.
|
||||||
|
Modifies the input dict!
|
||||||
|
"""
|
||||||
|
config['exchange']['key'] = ''
|
||||||
|
config['exchange']['secret'] = ''
|
||||||
|
config['exchange']['password'] = ''
|
||||||
|
config['exchange']['uid'] = ''
|
||||||
|
config['dry_run'] = True
|
||||||
|
|
||||||
|
|
||||||
def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
||||||
"""
|
"""
|
||||||
Check if the exchange name in the config file is supported by Freqtrade
|
Check if the exchange name in the config file is supported by Freqtrade
|
||||||
@@ -19,28 +33,40 @@ def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
|||||||
raises an exception if the exchange if not supported by ccxt
|
raises an exception if the exchange if not supported by ccxt
|
||||||
and thus is not known for the Freqtrade at all.
|
and thus is not known for the Freqtrade at all.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
if (config['runmode'] in [RunMode.PLOT, RunMode.UTIL_NO_EXCHANGE, RunMode.OTHER]
|
||||||
|
and not config.get('exchange', {}).get('name')):
|
||||||
|
# Skip checking exchange in plot mode, since it requires no exchange
|
||||||
|
return True
|
||||||
logger.info("Checking exchange...")
|
logger.info("Checking exchange...")
|
||||||
|
|
||||||
exchange = config.get('exchange', {}).get('name').lower()
|
exchange = config.get('exchange', {}).get('name').lower()
|
||||||
if not is_exchange_available(exchange):
|
if not exchange:
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f'Exchange "{exchange}" is not supported by ccxt '
|
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'and therefore not available for the bot.\n'
|
||||||
f'The following exchanges are supported by ccxt: '
|
f'The following exchanges are available for Freqtrade: '
|
||||||
f'{", ".join(available_exchanges())}'
|
f'{", ".join(available_exchanges())}'
|
||||||
)
|
)
|
||||||
|
|
||||||
if check_for_bad and is_exchange_bad(exchange):
|
if check_for_bad and is_exchange_bad(exchange):
|
||||||
logger.warning(f'Exchange "{exchange}" is known to not work with the bot yet. '
|
raise OperationalException(f'Exchange "{exchange}" is known to not work with the bot yet. '
|
||||||
f'Use it only for development and testing purposes.')
|
f'Reason: {get_exchange_bad_reason(exchange)}')
|
||||||
return False
|
|
||||||
|
|
||||||
if is_exchange_officially_supported(exchange):
|
if is_exchange_officially_supported(exchange):
|
||||||
logger.info(f'Exchange "{exchange}" is officially supported '
|
logger.info(f'Exchange "{exchange}" is officially supported '
|
||||||
f'by the Freqtrade development team.')
|
f'by the Freqtrade development team.')
|
||||||
else:
|
else:
|
||||||
logger.warning(f'Exchange "{exchange}" is supported by ccxt '
|
logger.warning(f'Exchange "{exchange}" is known to the the ccxt library, '
|
||||||
f'and therefore available for the bot but not officially supported '
|
f'available for the bot, but not officially supported '
|
||||||
f'by the Freqtrade development team. '
|
f'by the Freqtrade development team. '
|
||||||
f'It may work flawlessly (please report back) or have serious issues. '
|
f'It may work flawlessly (please report back) or have serious issues. '
|
||||||
f'Use it at your own discretion.')
|
f'Use it at your own discretion.')
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
Definition of cli arguments used in arguments.py
|
Definition of cli arguments used in arguments.py
|
||||||
"""
|
"""
|
||||||
import argparse
|
import argparse
|
||||||
import os
|
|
||||||
|
|
||||||
from freqtrade import __version__, constants
|
from freqtrade import __version__, constants
|
||||||
|
|
||||||
@@ -19,6 +18,18 @@ def check_int_positive(value: str) -> int:
|
|||||||
return uint
|
return uint
|
||||||
|
|
||||||
|
|
||||||
|
def check_int_nonzero(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 non-zero integer value"
|
||||||
|
)
|
||||||
|
return uint
|
||||||
|
|
||||||
|
|
||||||
class Arg:
|
class Arg:
|
||||||
# Optional CLI arguments
|
# Optional CLI arguments
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
@@ -37,7 +48,8 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
),
|
),
|
||||||
"logfile": Arg(
|
"logfile": Arg(
|
||||||
'--logfile',
|
'--logfile',
|
||||||
help='Log to the file specified.',
|
help="Log to the file specified. Special values are: 'syslog', 'journald'. "
|
||||||
|
"See the documentation for more details.",
|
||||||
metavar='FILE',
|
metavar='FILE',
|
||||||
),
|
),
|
||||||
"version": Arg(
|
"version": Arg(
|
||||||
@@ -55,15 +67,24 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
),
|
),
|
||||||
"datadir": Arg(
|
"datadir": Arg(
|
||||||
'-d', '--datadir',
|
'-d', '--datadir',
|
||||||
help='Path to backtest data.',
|
help='Path to directory with historical backtesting data.',
|
||||||
metavar='PATH',
|
metavar='PATH',
|
||||||
),
|
),
|
||||||
|
"user_data_dir": Arg(
|
||||||
|
'--userdir', '--user-data-dir',
|
||||||
|
help='Path to userdata directory.',
|
||||||
|
metavar='PATH',
|
||||||
|
),
|
||||||
|
"reset": Arg(
|
||||||
|
'--reset',
|
||||||
|
help='Reset sample files to their original state.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
# Main options
|
# Main options
|
||||||
"strategy": Arg(
|
"strategy": Arg(
|
||||||
'-s', '--strategy',
|
'-s', '--strategy',
|
||||||
help='Specify strategy class name (default: `%(default)s`).',
|
help='Specify strategy class name which will be used by the bot.',
|
||||||
metavar='NAME',
|
metavar='NAME',
|
||||||
default='DefaultStrategy',
|
|
||||||
),
|
),
|
||||||
"strategy_path": Arg(
|
"strategy_path": Arg(
|
||||||
'--strategy-path',
|
'--strategy-path',
|
||||||
@@ -82,6 +103,11 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
help='Notify systemd service manager.',
|
help='Notify systemd service manager.',
|
||||||
action='store_true',
|
action='store_true',
|
||||||
),
|
),
|
||||||
|
"dry_run": Arg(
|
||||||
|
'--dry-run',
|
||||||
|
help='Enforce dry-run for trading (removes Exchange secrets and simulates trades).',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
# Optimize common
|
# Optimize common
|
||||||
"ticker_interval": Arg(
|
"ticker_interval": Arg(
|
||||||
'-i', '--ticker-interval',
|
'-i', '--ticker-interval',
|
||||||
@@ -102,13 +128,6 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
help='Specify stake_amount.',
|
help='Specify stake_amount.',
|
||||||
type=float,
|
type=float,
|
||||||
),
|
),
|
||||||
"refresh_pairs": Arg(
|
|
||||||
'-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 optimization commands with '
|
|
||||||
'up-to-date data.',
|
|
||||||
action='store_true',
|
|
||||||
),
|
|
||||||
# Backtesting
|
# Backtesting
|
||||||
"position_stacking": Arg(
|
"position_stacking": Arg(
|
||||||
'--eps', '--enable-position-stacking',
|
'--eps', '--enable-position-stacking',
|
||||||
@@ -123,14 +142,9 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
action='store_false',
|
action='store_false',
|
||||||
default=True,
|
default=True,
|
||||||
),
|
),
|
||||||
"live": Arg(
|
|
||||||
'-l', '--live',
|
|
||||||
help='Use live data.',
|
|
||||||
action='store_true',
|
|
||||||
),
|
|
||||||
"strategy_list": Arg(
|
"strategy_list": Arg(
|
||||||
'--strategy-list',
|
'--strategy-list',
|
||||||
help='Provide a comma-separated list of strategies to backtest. '
|
help='Provide a space-separated list of strategies to backtest. '
|
||||||
'Please note that ticker-interval needs to be set either in config '
|
'Please note that ticker-interval needs to be set either in config '
|
||||||
'or via command line. When using this together with `--export trades`, '
|
'or via command line. When using this together with `--export trades`, '
|
||||||
'the strategy-name is injected into the filename '
|
'the strategy-name is injected into the filename '
|
||||||
@@ -144,12 +158,16 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
),
|
),
|
||||||
"exportfilename": Arg(
|
"exportfilename": Arg(
|
||||||
'--export-filename',
|
'--export-filename',
|
||||||
help='Save backtest results to the file with this filename (default: `%(default)s`). '
|
help='Save backtest results to the file with this filename. '
|
||||||
'Requires `--export` to be set as well. '
|
'Requires `--export` to be set as well. '
|
||||||
'Example: `--export-filename=user_data/backtest_data/backtest_today.json`',
|
'Example: `--export-filename=user_data/backtest_results/backtest_today.json`',
|
||||||
metavar='PATH',
|
metavar='PATH',
|
||||||
default=os.path.join('user_data', 'backtest_data',
|
),
|
||||||
'backtest-result.json'),
|
"fee": Arg(
|
||||||
|
'--fee',
|
||||||
|
help='Specify fee ratio. Will be applied twice (on trade entry and exit).',
|
||||||
|
type=float,
|
||||||
|
metavar='FLOAT',
|
||||||
),
|
),
|
||||||
# Edge
|
# Edge
|
||||||
"stoploss_range": Arg(
|
"stoploss_range": Arg(
|
||||||
@@ -160,14 +178,13 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
),
|
),
|
||||||
# Hyperopt
|
# Hyperopt
|
||||||
"hyperopt": Arg(
|
"hyperopt": Arg(
|
||||||
'--customhyperopt',
|
'--hyperopt',
|
||||||
help='Specify hyperopt class name (default: `%(default)s`).',
|
help='Specify hyperopt class name which will be used by the bot.',
|
||||||
metavar='NAME',
|
metavar='NAME',
|
||||||
default=constants.DEFAULT_HYPEROPT,
|
|
||||||
),
|
),
|
||||||
"hyperopt_path": Arg(
|
"hyperopt_path": Arg(
|
||||||
'--hyperopt-path',
|
'--hyperopt-path',
|
||||||
help='Specify additional lookup path for Hyperopts and Hyperopt Loss functions.',
|
help='Specify additional lookup path for Hyperopt and Hyperopt Loss functions.',
|
||||||
metavar='PATH',
|
metavar='PATH',
|
||||||
),
|
),
|
||||||
"epochs": Arg(
|
"epochs": Arg(
|
||||||
@@ -178,12 +195,11 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
default=constants.HYPEROPT_EPOCH,
|
default=constants.HYPEROPT_EPOCH,
|
||||||
),
|
),
|
||||||
"spaces": Arg(
|
"spaces": Arg(
|
||||||
'-s', '--spaces',
|
'--spaces',
|
||||||
help='Specify which parameters to hyperopt. Space-separated list. '
|
help='Specify which parameters to hyperopt. Space-separated list.',
|
||||||
'Default: `%(default)s`.',
|
choices=['all', 'buy', 'sell', 'roi', 'stoploss', 'trailing', 'default'],
|
||||||
choices=['all', 'buy', 'sell', 'roi', 'stoploss'],
|
|
||||||
nargs='+',
|
nargs='+',
|
||||||
default='all',
|
default='default',
|
||||||
),
|
),
|
||||||
"print_all": Arg(
|
"print_all": Arg(
|
||||||
'--print-all',
|
'--print-all',
|
||||||
@@ -191,6 +207,19 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
action='store_true',
|
action='store_true',
|
||||||
default=False,
|
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(
|
"hyperopt_jobs": Arg(
|
||||||
'-j', '--job-workers',
|
'-j', '--job-workers',
|
||||||
help='The number of concurrently running jobs for hyperoptimization '
|
help='The number of concurrently running jobs for hyperoptimization '
|
||||||
@@ -226,20 +255,64 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
'--hyperopt-loss',
|
'--hyperopt-loss',
|
||||||
help='Specify the class name of the hyperopt loss function class (IHyperOptLoss). '
|
help='Specify the class name of the hyperopt loss function class (IHyperOptLoss). '
|
||||||
'Different functions can generate completely different results, '
|
'Different functions can generate completely different results, '
|
||||||
'since the target for optimization is different. (default: `%(default)s`).',
|
'since the target for optimization is different. Built-in Hyperopt-loss-functions are: '
|
||||||
|
'DefaultHyperOptLoss, OnlyProfitHyperOptLoss, SharpeHyperOptLoss.'
|
||||||
|
'(default: `%(default)s`).',
|
||||||
metavar='NAME',
|
metavar='NAME',
|
||||||
default=constants.DEFAULT_HYPEROPT_LOSS,
|
default=constants.DEFAULT_HYPEROPT_LOSS,
|
||||||
),
|
),
|
||||||
# List exchanges
|
# List exchanges
|
||||||
"print_one_column": Arg(
|
"print_one_column": Arg(
|
||||||
'-1', '--one-column',
|
'-1', '--one-column',
|
||||||
help='Print exchanges in one column.',
|
help='Print output in one column.',
|
||||||
action='store_true',
|
action='store_true',
|
||||||
),
|
),
|
||||||
|
"list_exchanges_all": Arg(
|
||||||
|
'-a', '--all',
|
||||||
|
help='Print all exchanges known to the ccxt library.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
# List pairs / markets
|
||||||
|
"list_pairs_all": Arg(
|
||||||
|
'-a', '--all',
|
||||||
|
help='Print all pairs or market symbols. By default only active '
|
||||||
|
'ones are shown.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"print_list": Arg(
|
||||||
|
'--print-list',
|
||||||
|
help='Print list of pairs or market symbols. By default data is '
|
||||||
|
'printed in the tabular format.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"list_pairs_print_json": Arg(
|
||||||
|
'--print-json',
|
||||||
|
help='Print list of pairs or market symbols in JSON format.',
|
||||||
|
action='store_true',
|
||||||
|
default=False,
|
||||||
|
),
|
||||||
|
"print_csv": Arg(
|
||||||
|
'--print-csv',
|
||||||
|
help='Print exchange pair or market data in the csv format.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"quote_currencies": Arg(
|
||||||
|
'--quote',
|
||||||
|
help='Specify quote currency(-ies). Space-separated list.',
|
||||||
|
nargs='+',
|
||||||
|
metavar='QUOTE_CURRENCY',
|
||||||
|
),
|
||||||
|
"base_currencies": Arg(
|
||||||
|
'--base',
|
||||||
|
help='Specify base currency(-ies). Space-separated list.',
|
||||||
|
nargs='+',
|
||||||
|
metavar='BASE_CURRENCY',
|
||||||
|
),
|
||||||
# Script options
|
# Script options
|
||||||
"pairs": Arg(
|
"pairs": Arg(
|
||||||
'-p', '--pairs',
|
'-p', '--pairs',
|
||||||
help='Show profits for only these pairs. Pairs are comma-separated.',
|
help='Show profits for only these pairs. Pairs are space-separated.',
|
||||||
|
nargs='+',
|
||||||
),
|
),
|
||||||
# Download data
|
# Download data
|
||||||
"pairs_file": Arg(
|
"pairs_file": Arg(
|
||||||
@@ -253,6 +326,12 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
type=check_int_positive,
|
type=check_int_positive,
|
||||||
metavar='INT',
|
metavar='INT',
|
||||||
),
|
),
|
||||||
|
"download_trades": Arg(
|
||||||
|
'--dl-trades',
|
||||||
|
help='Download trades instead of OHLCV data. The bot will resample trades to the '
|
||||||
|
'desired timeframe as specified as --timeframes/-t.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
"exchange": Arg(
|
"exchange": Arg(
|
||||||
'--exchange',
|
'--exchange',
|
||||||
help=f'Exchange name (default: `{constants.DEFAULT_EXCHANGE}`). '
|
help=f'Exchange name (default: `{constants.DEFAULT_EXCHANGE}`). '
|
||||||
@@ -261,9 +340,10 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
"timeframes": Arg(
|
"timeframes": Arg(
|
||||||
'-t', '--timeframes',
|
'-t', '--timeframes',
|
||||||
help=f'Specify which tickers to download. Space-separated list. '
|
help=f'Specify which tickers to download. Space-separated list. '
|
||||||
f'Default: `{constants.DEFAULT_DOWNLOAD_TICKER_INTERVALS}`.',
|
f'Default: `1m 5m`.',
|
||||||
choices=['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h',
|
choices=['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h',
|
||||||
'6h', '8h', '12h', '1d', '3d', '1w'],
|
'6h', '8h', '12h', '1d', '3d', '1w'],
|
||||||
|
default=['1m', '5m'],
|
||||||
nargs='+',
|
nargs='+',
|
||||||
),
|
),
|
||||||
"erase": Arg(
|
"erase": Arg(
|
||||||
@@ -271,18 +351,28 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
help='Clean all existing data for the selected exchange/pairs/timeframes.',
|
help='Clean all existing data for the selected exchange/pairs/timeframes.',
|
||||||
action='store_true',
|
action='store_true',
|
||||||
),
|
),
|
||||||
|
# Templating options
|
||||||
|
"template": Arg(
|
||||||
|
'--template',
|
||||||
|
help='Use a template which is either `minimal` or '
|
||||||
|
'`full` (containing multiple sample indicators). Default: `%(default)s`.',
|
||||||
|
choices=['full', 'minimal'],
|
||||||
|
default='full',
|
||||||
|
),
|
||||||
# Plot dataframe
|
# Plot dataframe
|
||||||
"indicators1": Arg(
|
"indicators1": Arg(
|
||||||
'--indicators1',
|
'--indicators1',
|
||||||
help='Set indicators from your strategy you want in the first row of the graph. '
|
help='Set indicators from your strategy you want in the first row of the graph. '
|
||||||
'Comma-separated list. Example: `ema3,ema5`. Default: `%(default)s`.',
|
'Space-separated list. Example: `ema3 ema5`. Default: `%(default)s`.',
|
||||||
default='sma,ema3,ema5',
|
default=['sma', 'ema3', 'ema5'],
|
||||||
|
nargs='+',
|
||||||
),
|
),
|
||||||
"indicators2": Arg(
|
"indicators2": Arg(
|
||||||
'--indicators2',
|
'--indicators2',
|
||||||
help='Set indicators from your strategy you want in the third row of the graph. '
|
help='Set indicators from your strategy you want in the third row of the graph. '
|
||||||
'Comma-separated list. Example: `fastd,fastk`. Default: `%(default)s`.',
|
'Space-separated list. Example: `fastd fastk`. Default: `%(default)s`.',
|
||||||
default='macd,macdsignal',
|
default=['macd', 'macdsignal'],
|
||||||
|
nargs='+',
|
||||||
),
|
),
|
||||||
"plot_limit": Arg(
|
"plot_limit": Arg(
|
||||||
'--plot-limit',
|
'--plot-limit',
|
||||||
@@ -299,4 +389,31 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
choices=["DB", "file"],
|
choices=["DB", "file"],
|
||||||
default="file",
|
default="file",
|
||||||
),
|
),
|
||||||
|
# hyperopt-list, hyperopt-show
|
||||||
|
"hyperopt_list_profitable": Arg(
|
||||||
|
'--profitable',
|
||||||
|
help='Select only profitable epochs.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"hyperopt_list_best": Arg(
|
||||||
|
'--best',
|
||||||
|
help='Select only best epochs.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"hyperopt_list_no_details": Arg(
|
||||||
|
'--no-details',
|
||||||
|
help='Do not print best epoch details.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
|
"hyperopt_show_index": Arg(
|
||||||
|
'-n', '--index',
|
||||||
|
help='Specify the index of the epoch to print details for.',
|
||||||
|
type=check_int_nonzero,
|
||||||
|
metavar='INT',
|
||||||
|
),
|
||||||
|
"hyperopt_show_no_header": Arg(
|
||||||
|
'--no-header',
|
||||||
|
help='Do not print epoch details header.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
}
|
}
|
||||||
|
|||||||
145
freqtrade/configuration/config_validation.py
Normal file
145
freqtrade/configuration/config_validation.py
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
import logging
|
||||||
|
from typing import Any, Dict
|
||||||
|
|
||||||
|
from jsonschema import Draft4Validator, validators
|
||||||
|
from jsonschema.exceptions import ValidationError, best_match
|
||||||
|
|
||||||
|
from freqtrade import constants, OperationalException
|
||||||
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
|
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)
|
||||||
|
_validate_whitelist(conf)
|
||||||
|
|
||||||
|
# validate configuration before returning
|
||||||
|
logger.info('Validating configuration ...')
|
||||||
|
validate_config_schema(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."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_whitelist(conf: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Dynamic whitelist does not require pair_whitelist to be set - however StaticWhitelist does.
|
||||||
|
"""
|
||||||
|
if conf.get('runmode', RunMode.OTHER) in [RunMode.OTHER, RunMode.PLOT,
|
||||||
|
RunMode.UTIL_NO_EXCHANGE, RunMode.UTIL_EXCHANGE]:
|
||||||
|
return
|
||||||
|
|
||||||
|
for pl in conf.get('pairlists', [{'method': 'StaticPairList'}]):
|
||||||
|
if (pl.get('method') == 'StaticPairList'
|
||||||
|
and not conf.get('exchange', {}).get('pair_whitelist')):
|
||||||
|
raise OperationalException("StaticPairList requires pair_whitelist to be set.")
|
||||||
|
|
||||||
|
if pl.get('method') == 'StaticPairList':
|
||||||
|
stake = conf['stake_currency']
|
||||||
|
invalid_pairs = []
|
||||||
|
for pair in conf['exchange'].get('pair_whitelist'):
|
||||||
|
if not pair.endswith(f'/{stake}'):
|
||||||
|
invalid_pairs.append(pair)
|
||||||
|
|
||||||
|
if invalid_pairs:
|
||||||
|
raise OperationalException(
|
||||||
|
f"Stake-currency '{stake}' not compatible with pair-whitelist. "
|
||||||
|
f"Please remove the following pairs: {invalid_pairs}")
|
||||||
@@ -1,31 +1,32 @@
|
|||||||
"""
|
"""
|
||||||
This module contains the configuration class
|
This module contains the configuration class
|
||||||
"""
|
"""
|
||||||
import json
|
|
||||||
import logging
|
import logging
|
||||||
import sys
|
|
||||||
import warnings
|
import warnings
|
||||||
from argparse import Namespace
|
from copy import deepcopy
|
||||||
from typing import Any, Callable, Dict, Optional
|
from pathlib import Path
|
||||||
|
from typing import Any, Callable, Dict, List, Optional
|
||||||
|
|
||||||
from freqtrade import OperationalException, constants
|
from freqtrade import OperationalException, constants
|
||||||
from freqtrade.configuration.check_exchange import check_exchange
|
from freqtrade.configuration.check_exchange import check_exchange
|
||||||
from freqtrade.configuration.create_datadir import create_datadir
|
from freqtrade.configuration.deprecated_settings import process_temporary_deprecated_settings
|
||||||
from freqtrade.configuration.json_schema import validate_config_schema
|
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.loggers import setup_logging
|
||||||
from freqtrade.misc import deep_merge_dicts
|
from freqtrade.misc import deep_merge_dicts, json_load
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode, TRADING_MODES, NON_UTIL_MODES
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class Configuration(object):
|
class Configuration:
|
||||||
"""
|
"""
|
||||||
Class to read and init the bot configuration
|
Class to read and init the bot configuration
|
||||||
Reuse this class for the bot, backtesting, hyperopt and every script that required configuration
|
Reuse this class for the bot, backtesting, hyperopt and every script that required configuration
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, args: Namespace, runmode: RunMode = None) -> None:
|
def __init__(self, args: Dict[str, Any], runmode: RunMode = None) -> None:
|
||||||
self.args = args
|
self.args = args
|
||||||
self.config: Optional[Dict[str, Any]] = None
|
self.config: Optional[Dict[str, Any]] = None
|
||||||
self.runmode = runmode
|
self.runmode = runmode
|
||||||
@@ -40,46 +41,48 @@ class Configuration(object):
|
|||||||
|
|
||||||
return self.config
|
return self.config
|
||||||
|
|
||||||
def _load_config_files(self) -> Dict[str, Any]:
|
@staticmethod
|
||||||
|
def from_files(files: List[str]) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Iterate through the config files passed in the args,
|
Iterate through the config files passed in, loading all of them
|
||||||
loading all of them and merging their contents.
|
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] = {}
|
config: Dict[str, Any] = {}
|
||||||
|
|
||||||
|
if not files:
|
||||||
|
return deepcopy(constants.MINIMAL_CONFIG)
|
||||||
|
|
||||||
# We expect here a list of config filenames
|
# We expect here a list of config filenames
|
||||||
for path in self.args.config:
|
for path in files:
|
||||||
logger.info('Using config: %s ...', path)
|
logger.info(f'Using config: {path} ...')
|
||||||
|
|
||||||
# Merge config options, overwriting old values
|
# Merge config options, overwriting old values
|
||||||
config = deep_merge_dicts(self._load_config_file(path), config)
|
config = deep_merge_dicts(load_config_file(path), config)
|
||||||
|
|
||||||
return config
|
# Normalize 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:
|
|
||||||
# Read config from stdin if requested in the options
|
|
||||||
with open(path) if path != '-' else sys.stdin as file:
|
|
||||||
config = json.load(file)
|
|
||||||
except FileNotFoundError:
|
|
||||||
raise OperationalException(
|
|
||||||
f'Config file "{path}" not found!'
|
|
||||||
' Please create a config file or check whether it exists.')
|
|
||||||
|
|
||||||
return config
|
|
||||||
|
|
||||||
def _normalize_config(self, config: Dict[str, Any]) -> None:
|
|
||||||
"""
|
|
||||||
Make config more canonical -- i.e. for example add missing parts that we expect
|
|
||||||
to be normally in it...
|
|
||||||
"""
|
|
||||||
if 'internals' not in config:
|
if 'internals' not in config:
|
||||||
config['internals'] = {}
|
config['internals'] = {}
|
||||||
|
# TODO: This can be deleted along with removal of deprecated
|
||||||
|
# experimental settings
|
||||||
|
if 'ask_strategy' not in config:
|
||||||
|
config['ask_strategy'] = {}
|
||||||
|
|
||||||
|
if 'pairlists' not in config:
|
||||||
|
config['pairlists'] = []
|
||||||
|
|
||||||
|
return config
|
||||||
|
|
||||||
def load_config(self) -> Dict[str, Any]:
|
def load_config(self) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
@@ -87,23 +90,27 @@ class Configuration(object):
|
|||||||
:return: Configuration dictionary
|
:return: Configuration dictionary
|
||||||
"""
|
"""
|
||||||
# Load all configs
|
# Load all configs
|
||||||
config: Dict[str, Any] = self._load_config_files()
|
config: Dict[str, Any] = self.load_from_files(self.args.get("config", []))
|
||||||
|
|
||||||
# Make resulting config more canonical
|
# Keep a copy of the original configuration file
|
||||||
self._normalize_config(config)
|
config['original_config'] = deepcopy(config)
|
||||||
|
|
||||||
logger.info('Validating configuration ...')
|
self._process_runmode(config)
|
||||||
validate_config_schema(config)
|
|
||||||
|
|
||||||
self._validate_config_consistency(config)
|
|
||||||
|
|
||||||
self._process_common_options(config)
|
self._process_common_options(config)
|
||||||
|
|
||||||
|
self._process_trading_options(config)
|
||||||
|
|
||||||
self._process_optimize_options(config)
|
self._process_optimize_options(config)
|
||||||
|
|
||||||
self._process_plot_options(config)
|
self._process_plot_options(config)
|
||||||
|
|
||||||
self._process_runmode(config)
|
# Check if the exchange set by the user is supported
|
||||||
|
check_exchange(config, config.get('experimental', {}).get('block_bad_exchanges', True))
|
||||||
|
|
||||||
|
self._resolve_pairs_list(config)
|
||||||
|
|
||||||
|
process_temporary_deprecated_settings(config)
|
||||||
|
|
||||||
return config
|
return config
|
||||||
|
|
||||||
@@ -113,34 +120,16 @@ class Configuration(object):
|
|||||||
the -v/--verbose, --logfile options
|
the -v/--verbose, --logfile options
|
||||||
"""
|
"""
|
||||||
# Log level
|
# Log level
|
||||||
if 'verbosity' in self.args and self.args.verbosity:
|
config.update({'verbosity': self.args.get("verbosity", 0)})
|
||||||
config.update({'verbosity': self.args.verbosity})
|
|
||||||
else:
|
|
||||||
config.update({'verbosity': 0})
|
|
||||||
|
|
||||||
if 'logfile' in self.args and self.args.logfile:
|
if 'logfile' in self.args and self.args["logfile"]:
|
||||||
config.update({'logfile': self.args.logfile})
|
config.update({'logfile': self.args["logfile"]})
|
||||||
|
|
||||||
setup_logging(config)
|
setup_logging(config)
|
||||||
|
|
||||||
def _process_strategy_options(self, config: Dict[str, Any]) -> None:
|
def _process_trading_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
if config['runmode'] not in TRADING_MODES:
|
||||||
# Set strategy if not specified in config and or if it's non default
|
return
|
||||||
if self.args.strategy != constants.DEFAULT_STRATEGY or not config.get('strategy'):
|
|
||||||
config.update({'strategy': self.args.strategy})
|
|
||||||
|
|
||||||
self._args_to_config(config, argname='strategy_path',
|
|
||||||
logstring='Using additional Strategy lookup path: {}')
|
|
||||||
|
|
||||||
def _process_common_options(self, config: Dict[str, Any]) -> None:
|
|
||||||
|
|
||||||
self._process_logging_options(config)
|
|
||||||
self._process_strategy_options(config)
|
|
||||||
|
|
||||||
if ('db_url' in self.args and self.args.db_url and
|
|
||||||
self.args.db_url != constants.DEFAULT_DB_PROD_URL):
|
|
||||||
config.update({'db_url': self.args.db_url})
|
|
||||||
logger.info('Parameter --db-url detected ...')
|
|
||||||
|
|
||||||
if config.get('dry_run', False):
|
if config.get('dry_run', False):
|
||||||
logger.info('Dry run is enabled')
|
logger.info('Dry run is enabled')
|
||||||
@@ -154,31 +143,66 @@ class Configuration(object):
|
|||||||
|
|
||||||
logger.info(f'Using DB: "{config["db_url"]}"')
|
logger.info(f'Using DB: "{config["db_url"]}"')
|
||||||
|
|
||||||
|
def _process_common_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
self._process_logging_options(config)
|
||||||
|
|
||||||
|
# Set strategy if not specified in config and or if it's non default
|
||||||
|
if self.args.get("strategy") or not config.get('strategy'):
|
||||||
|
config.update({'strategy': self.args.get("strategy")})
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='strategy_path',
|
||||||
|
logstring='Using additional Strategy lookup path: {}')
|
||||||
|
|
||||||
|
if ('db_url' in self.args and self.args["db_url"] and
|
||||||
|
self.args["db_url"] != constants.DEFAULT_DB_PROD_URL):
|
||||||
|
config.update({'db_url': self.args["db_url"]})
|
||||||
|
logger.info('Parameter --db-url detected ...')
|
||||||
|
|
||||||
if config.get('forcebuy_enable', False):
|
if config.get('forcebuy_enable', False):
|
||||||
logger.warning('`forcebuy` RPC message enabled.')
|
logger.warning('`forcebuy` RPC message enabled.')
|
||||||
|
|
||||||
# Setting max_open_trades to infinite if -1
|
|
||||||
if config.get('max_open_trades') == -1:
|
|
||||||
config['max_open_trades'] = float('inf')
|
|
||||||
|
|
||||||
# Support for sd_notify
|
# Support for sd_notify
|
||||||
if 'sd_notify' in self.args and self.args.sd_notify:
|
if 'sd_notify' in self.args and self.args["sd_notify"]:
|
||||||
config['internals'].update({'sd_notify': True})
|
config['internals'].update({'sd_notify': True})
|
||||||
|
|
||||||
# Check if the exchange set by the user is supported
|
self._args_to_config(config, argname='dry_run',
|
||||||
check_exchange(config)
|
logstring='Parameter --dry-run detected, '
|
||||||
|
'overriding dry_run to: {} ...')
|
||||||
|
|
||||||
def _process_datadir_options(self, config: Dict[str, Any]) -> None:
|
def _process_datadir_options(self, config: Dict[str, Any]) -> None:
|
||||||
"""
|
"""
|
||||||
Extract information for sys.argv and load datadir configuration:
|
Extract information for sys.argv and load directory configurations
|
||||||
the --datadir option
|
--user-data, --datadir
|
||||||
"""
|
"""
|
||||||
if 'datadir' in self.args and self.args.datadir:
|
# Check exchange parameter here - otherwise `datadir` might be wrong.
|
||||||
config.update({'datadir': create_datadir(config, self.args.datadir)})
|
if "exchange" in self.args and self.args["exchange"]:
|
||||||
else:
|
config['exchange']['name'] = self.args["exchange"]
|
||||||
config.update({'datadir': create_datadir(config, None)})
|
logger.info(f"Using exchange {config['exchange']['name']}")
|
||||||
|
|
||||||
|
if 'pair_whitelist' not in config['exchange']:
|
||||||
|
config['exchange']['pair_whitelist'] = []
|
||||||
|
|
||||||
|
if 'user_data_dir' in self.args and self.args["user_data_dir"]:
|
||||||
|
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'))
|
logger.info('Using data directory: %s ...', config.get('datadir'))
|
||||||
|
|
||||||
|
if self.args.get('exportfilename'):
|
||||||
|
self._args_to_config(config, argname='exportfilename',
|
||||||
|
logstring='Storing backtest results to {} ...')
|
||||||
|
else:
|
||||||
|
config['exportfilename'] = (config['user_data_dir']
|
||||||
|
/ 'backtest_results/backtest-result.json')
|
||||||
|
|
||||||
def _process_optimize_options(self, config: Dict[str, Any]) -> None:
|
def _process_optimize_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
# This will override the strategy configuration
|
# This will override the strategy configuration
|
||||||
@@ -186,38 +210,39 @@ class Configuration(object):
|
|||||||
logstring='Parameter -i/--ticker-interval detected ... '
|
logstring='Parameter -i/--ticker-interval detected ... '
|
||||||
'Using ticker_interval: {} ...')
|
'Using ticker_interval: {} ...')
|
||||||
|
|
||||||
self._args_to_config(config, argname='live',
|
|
||||||
logstring='Parameter -l/--live detected ...',
|
|
||||||
deprecated_msg='--live will be removed soon.')
|
|
||||||
|
|
||||||
self._args_to_config(config, argname='position_stacking',
|
self._args_to_config(config, argname='position_stacking',
|
||||||
logstring='Parameter --enable-position-stacking detected ...')
|
logstring='Parameter --enable-position-stacking detected ...')
|
||||||
|
|
||||||
if 'use_max_market_positions' in self.args and not self.args.use_max_market_positions:
|
# Setting max_open_trades to infinite if -1
|
||||||
|
if config.get('max_open_trades') == -1:
|
||||||
|
config['max_open_trades'] = float('inf')
|
||||||
|
|
||||||
|
if 'use_max_market_positions' in self.args and not self.args["use_max_market_positions"]:
|
||||||
config.update({'use_max_market_positions': False})
|
config.update({'use_max_market_positions': False})
|
||||||
logger.info('Parameter --disable-max-market-positions detected ...')
|
logger.info('Parameter --disable-max-market-positions detected ...')
|
||||||
logger.info('max_open_trades set to unlimited ...')
|
logger.info('max_open_trades set to unlimited ...')
|
||||||
elif 'max_open_trades' in self.args and self.args.max_open_trades:
|
elif 'max_open_trades' in self.args and self.args["max_open_trades"]:
|
||||||
config.update({'max_open_trades': self.args.max_open_trades})
|
config.update({'max_open_trades': self.args["max_open_trades"]})
|
||||||
logger.info('Parameter --max_open_trades detected, '
|
logger.info('Parameter --max_open_trades detected, '
|
||||||
'overriding max_open_trades to: %s ...', config.get('max_open_trades'))
|
'overriding max_open_trades to: %s ...', config.get('max_open_trades'))
|
||||||
else:
|
elif config['runmode'] in NON_UTIL_MODES:
|
||||||
logger.info('Using max_open_trades: %s ...', config.get('max_open_trades'))
|
logger.info('Using max_open_trades: %s ...', config.get('max_open_trades'))
|
||||||
|
|
||||||
self._args_to_config(config, argname='stake_amount',
|
self._args_to_config(config, argname='stake_amount',
|
||||||
logstring='Parameter --stake_amount detected, '
|
logstring='Parameter --stake_amount detected, '
|
||||||
'overriding stake_amount to: {} ...')
|
'overriding stake_amount to: {} ...')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='fee',
|
||||||
|
logstring='Parameter --fee detected, '
|
||||||
|
'setting fee to: {} ...')
|
||||||
|
|
||||||
self._args_to_config(config, argname='timerange',
|
self._args_to_config(config, argname='timerange',
|
||||||
logstring='Parameter --timerange detected: {} ...')
|
logstring='Parameter --timerange detected: {} ...')
|
||||||
|
|
||||||
self._process_datadir_options(config)
|
self._process_datadir_options(config)
|
||||||
|
|
||||||
self._args_to_config(config, argname='refresh_pairs',
|
|
||||||
logstring='Parameter -r/--refresh-pairs-cached detected ...')
|
|
||||||
|
|
||||||
self._args_to_config(config, argname='strategy_list',
|
self._args_to_config(config, argname='strategy_list',
|
||||||
logstring='Using strategy list of {} Strategies', logfun=len)
|
logstring='Using strategy list of {} strategies', logfun=len)
|
||||||
|
|
||||||
self._args_to_config(config, argname='ticker_interval',
|
self._args_to_config(config, argname='ticker_interval',
|
||||||
logstring='Overriding ticker interval with Command line argument')
|
logstring='Overriding ticker interval with Command line argument')
|
||||||
@@ -225,20 +250,17 @@ class Configuration(object):
|
|||||||
self._args_to_config(config, argname='export',
|
self._args_to_config(config, argname='export',
|
||||||
logstring='Parameter --export detected: {} ...')
|
logstring='Parameter --export detected: {} ...')
|
||||||
|
|
||||||
self._args_to_config(config, argname='exportfilename',
|
|
||||||
logstring='Storing backtest results to {} ...')
|
|
||||||
|
|
||||||
# Edge section:
|
# Edge section:
|
||||||
if 'stoploss_range' in self.args and self.args.stoploss_range:
|
if 'stoploss_range' in self.args and self.args["stoploss_range"]:
|
||||||
txt_range = eval(self.args.stoploss_range)
|
txt_range = eval(self.args["stoploss_range"])
|
||||||
config['edge'].update({'stoploss_range_min': txt_range[0]})
|
config['edge'].update({'stoploss_range_min': txt_range[0]})
|
||||||
config['edge'].update({'stoploss_range_max': txt_range[1]})
|
config['edge'].update({'stoploss_range_max': txt_range[1]})
|
||||||
config['edge'].update({'stoploss_range_step': txt_range[2]})
|
config['edge'].update({'stoploss_range_step': txt_range[2]})
|
||||||
logger.info('Parameter --stoplosses detected: %s ...', self.args.stoploss_range)
|
logger.info('Parameter --stoplosses detected: %s ...', self.args["stoploss_range"])
|
||||||
|
|
||||||
# Hyperopt section
|
# Hyperopt section
|
||||||
self._args_to_config(config, argname='hyperopt',
|
self._args_to_config(config, argname='hyperopt',
|
||||||
logstring='Using Hyperopt file {}')
|
logstring='Using Hyperopt class name: {}')
|
||||||
|
|
||||||
self._args_to_config(config, argname='hyperopt_path',
|
self._args_to_config(config, argname='hyperopt_path',
|
||||||
logstring='Using additional Hyperopt lookup path: {}')
|
logstring='Using additional Hyperopt lookup path: {}')
|
||||||
@@ -254,6 +276,15 @@ class Configuration(object):
|
|||||||
self._args_to_config(config, argname='print_all',
|
self._args_to_config(config, argname='print_all',
|
||||||
logstring='Parameter --print-all detected ...')
|
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',
|
self._args_to_config(config, argname='hyperopt_jobs',
|
||||||
logstring='Parameter -j/--job-workers detected: {}')
|
logstring='Parameter -j/--job-workers detected: {}')
|
||||||
|
|
||||||
@@ -267,7 +298,22 @@ class Configuration(object):
|
|||||||
logstring='Hyperopt continue: {}')
|
logstring='Hyperopt continue: {}')
|
||||||
|
|
||||||
self._args_to_config(config, argname='hyperopt_loss',
|
self._args_to_config(config, argname='hyperopt_loss',
|
||||||
logstring='Using loss function: {}')
|
logstring='Using Hyperopt loss class name: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_show_index',
|
||||||
|
logstring='Parameter -n/--index detected: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_list_best',
|
||||||
|
logstring='Parameter --best detected: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_list_profitable',
|
||||||
|
logstring='Parameter --profitable detected: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_list_no_details',
|
||||||
|
logstring='Parameter --no-details detected: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_show_no_header',
|
||||||
|
logstring='Parameter --no-header detected: {}')
|
||||||
|
|
||||||
def _process_plot_options(self, config: Dict[str, Any]) -> None:
|
def _process_plot_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
@@ -285,44 +331,26 @@ class Configuration(object):
|
|||||||
self._args_to_config(config, argname='trade_source',
|
self._args_to_config(config, argname='trade_source',
|
||||||
logstring='Using trades from: {}')
|
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:
|
def _process_runmode(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
if not self.runmode:
|
if not self.runmode:
|
||||||
# Handle real mode, infer dry/live from config
|
# Handle real mode, infer dry/live from config
|
||||||
self.runmode = RunMode.DRY_RUN if config.get('dry_run', True) else RunMode.LIVE
|
self.runmode = RunMode.DRY_RUN if config.get('dry_run', True) else RunMode.LIVE
|
||||||
logger.info("Runmode set to {self.runmode}.")
|
logger.info(f"Runmode set to {self.runmode}.")
|
||||||
|
|
||||||
config.update({'runmode': self.runmode})
|
config.update({'runmode': self.runmode})
|
||||||
|
|
||||||
def _validate_config_consistency(self, conf: Dict[str, Any]) -> None:
|
|
||||||
"""
|
|
||||||
Validate the configuration consistency
|
|
||||||
:param conf: Config in JSON format
|
|
||||||
:return: Returns None if everything is ok, otherwise throw an OperationalException
|
|
||||||
"""
|
|
||||||
# validating trailing stoploss
|
|
||||||
self._validate_trailing_stoploss(conf)
|
|
||||||
|
|
||||||
def _validate_trailing_stoploss(self, conf: Dict[str, Any]) -> None:
|
|
||||||
|
|
||||||
# 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(
|
|
||||||
f'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(
|
|
||||||
f'The config trailing_stop_positive_offset needs '
|
|
||||||
'to be greater than trailing_stop_positive_offset in your config.')
|
|
||||||
|
|
||||||
def _args_to_config(self, config: Dict[str, Any], argname: str,
|
def _args_to_config(self, config: Dict[str, Any], argname: str,
|
||||||
logstring: str, logfun: Optional[Callable] = None,
|
logstring: str, logfun: Optional[Callable] = None,
|
||||||
deprecated_msg: Optional[str] = None) -> None:
|
deprecated_msg: Optional[str] = None) -> None:
|
||||||
@@ -335,12 +363,49 @@ class Configuration(object):
|
|||||||
sample: logfun=len (prints the length of the found
|
sample: logfun=len (prints the length of the found
|
||||||
configuration instead of the content)
|
configuration instead of the content)
|
||||||
"""
|
"""
|
||||||
if argname in self.args and getattr(self.args, argname):
|
if (argname in self.args and self.args[argname] is not None
|
||||||
|
and self.args[argname] is not False):
|
||||||
|
|
||||||
config.update({argname: getattr(self.args, argname)})
|
config.update({argname: self.args[argname]})
|
||||||
if logfun:
|
if logfun:
|
||||||
logger.info(logstring.format(logfun(config[argname])))
|
logger.info(logstring.format(logfun(config[argname])))
|
||||||
else:
|
else:
|
||||||
logger.info(logstring.format(config[argname]))
|
logger.info(logstring.format(config[argname]))
|
||||||
if deprecated_msg:
|
if deprecated_msg:
|
||||||
warnings.warn(f"DEPRECATED: {deprecated_msg}", DeprecationWarning)
|
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()
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
import logging
|
|
||||||
from typing import Any, Dict, Optional
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def create_datadir(config: Dict[str, Any], datadir: Optional[str] = None) -> str:
|
|
||||||
|
|
||||||
folder = Path(datadir) if datadir else Path('user_data/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)
|
|
||||||
82
freqtrade/configuration/deprecated_settings.py
Normal file
82
freqtrade/configuration/deprecated_settings.py
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
"""
|
||||||
|
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')
|
||||||
|
|
||||||
|
if not config.get('pairlists') and not config.get('pairlists'):
|
||||||
|
config['pairlists'] = [{'method': 'StaticPairList'}]
|
||||||
|
logger.warning(
|
||||||
|
"DEPRECATED: "
|
||||||
|
"Pairlists must be defined explicitly in the future."
|
||||||
|
"Defaulting to StaticPairList for now.")
|
||||||
|
|
||||||
|
if config.get('pairlist', {}).get("method") == 'VolumePairList':
|
||||||
|
logger.warning(
|
||||||
|
"DEPRECATED: "
|
||||||
|
f"Using VolumePairList in pairlist is deprecated and must be moved to pairlists. "
|
||||||
|
"Please refer to the docs on configuration details")
|
||||||
|
pl = {'method': 'VolumePairList'}
|
||||||
|
pl.update(config.get('pairlist', {}).get('config'))
|
||||||
|
config['pairlists'].append(pl)
|
||||||
|
|
||||||
|
if config.get('pairlist', {}).get('config', {}).get('precision_filter'):
|
||||||
|
logger.warning(
|
||||||
|
"DEPRECATED: "
|
||||||
|
f"Using precision_filter setting is deprecated and has been replaced by"
|
||||||
|
"PrecisionFilter. Please refer to the docs on configuration details")
|
||||||
|
config['pairlists'].append({'method': 'PrecisionFilter'})
|
||||||
76
freqtrade/configuration/directory_operations.py
Normal file
76
freqtrade/configuration/directory_operations.py
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
import logging
|
||||||
|
import shutil
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
|
from freqtrade import OperationalException
|
||||||
|
from freqtrade.constants import USER_DATA_FILES
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def create_datadir(config: Dict[str, Any], datadir: Optional[str] = None) -> str:
|
||||||
|
|
||||||
|
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", "notebooks",
|
||||||
|
"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
|
||||||
|
|
||||||
|
|
||||||
|
def copy_sample_files(directory: Path, overwrite: bool = False) -> None:
|
||||||
|
"""
|
||||||
|
Copy files from templates to User data directory.
|
||||||
|
:param directory: Directory to copy data to
|
||||||
|
:param overwrite: Overwrite existing sample files
|
||||||
|
"""
|
||||||
|
if not directory.is_dir():
|
||||||
|
raise OperationalException(f"Directory `{directory}` does not exist.")
|
||||||
|
sourcedir = Path(__file__).parents[1] / "templates"
|
||||||
|
for source, target in USER_DATA_FILES.items():
|
||||||
|
targetdir = directory / target
|
||||||
|
if not targetdir.is_dir():
|
||||||
|
raise OperationalException(f"Directory `{targetdir}` does not exist.")
|
||||||
|
targetfile = targetdir / source
|
||||||
|
if targetfile.exists():
|
||||||
|
if not overwrite:
|
||||||
|
logger.warning(f"File `{targetfile}` exists already, not deploying sample file.")
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
logger.warning(f"File `{targetfile}` exists already, overwriting.")
|
||||||
|
shutil.copy(str(sourcedir / source), str(targetfile))
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
import logging
|
|
||||||
from typing import Any, Dict
|
|
||||||
|
|
||||||
from jsonschema import Draft4Validator, validators
|
|
||||||
from jsonschema.exceptions import ValidationError, best_match
|
|
||||||
|
|
||||||
from freqtrade import constants
|
|
||||||
|
|
||||||
|
|
||||||
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
|
|
||||||
)
|
|
||||||
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
|
||||||
106
freqtrade/configuration/timerange.py
Normal file
106
freqtrade/configuration/timerange.py
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
"""
|
||||||
|
This module contains the argument manager class
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import arrow
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
def subtract_start(self, seconds) -> None:
|
||||||
|
"""
|
||||||
|
Subtracts <seconds> from startts if startts is set.
|
||||||
|
:param seconds: Seconds to subtract from starttime
|
||||||
|
:return: None (Modifies the object in place)
|
||||||
|
"""
|
||||||
|
if self.startts:
|
||||||
|
self.startts = self.startts - seconds
|
||||||
|
|
||||||
|
def adjust_start_if_necessary(self, timeframe_secs: int, startup_candles: int,
|
||||||
|
min_date: arrow.Arrow) -> None:
|
||||||
|
"""
|
||||||
|
Adjust startts by <startup_candles> candles.
|
||||||
|
Applies only if no startup-candles have been available.
|
||||||
|
:param timeframe_secs: Ticker timeframe in seconds e.g. `timeframe_to_seconds('5m')`
|
||||||
|
:param startup_candles: Number of candles to move start-date forward
|
||||||
|
:param min_date: Minimum data date loaded. Key kriterium to decide if start-time
|
||||||
|
has to be moved
|
||||||
|
:return: None (Modifies the object in place)
|
||||||
|
"""
|
||||||
|
if (not self.starttype or (startup_candles
|
||||||
|
and min_date.timestamp >= self.startts)):
|
||||||
|
# If no startts was defined, or backtest-data starts at the defined backtest-date
|
||||||
|
logger.warning("Moving start-date by %s candles to account for startup time.",
|
||||||
|
startup_candles)
|
||||||
|
self.startts = (min_date.timestamp + timeframe_secs * startup_candles)
|
||||||
|
self.starttype = 'date'
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
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)
|
||||||
@@ -5,13 +5,9 @@ bot constants
|
|||||||
"""
|
"""
|
||||||
DEFAULT_CONFIG = 'config.json'
|
DEFAULT_CONFIG = 'config.json'
|
||||||
DEFAULT_EXCHANGE = 'bittrex'
|
DEFAULT_EXCHANGE = 'bittrex'
|
||||||
DYNAMIC_WHITELIST = 20 # pairs
|
|
||||||
PROCESS_THROTTLE_SECS = 5 # sec
|
PROCESS_THROTTLE_SECS = 5 # sec
|
||||||
DEFAULT_TICKER_INTERVAL = 5 # min
|
|
||||||
HYPEROPT_EPOCH = 100 # epochs
|
HYPEROPT_EPOCH = 100 # epochs
|
||||||
RETRY_TIMEOUT = 30 # sec
|
RETRY_TIMEOUT = 30 # sec
|
||||||
DEFAULT_STRATEGY = 'DefaultStrategy'
|
|
||||||
DEFAULT_HYPEROPT = 'DefaultHyperOpts'
|
|
||||||
DEFAULT_HYPEROPT_LOSS = 'DefaultHyperOptLoss'
|
DEFAULT_HYPEROPT_LOSS = 'DefaultHyperOptLoss'
|
||||||
DEFAULT_DB_PROD_URL = 'sqlite:///tradesv3.sqlite'
|
DEFAULT_DB_PROD_URL = 'sqlite:///tradesv3.sqlite'
|
||||||
DEFAULT_DB_DRYRUN_URL = 'sqlite://'
|
DEFAULT_DB_DRYRUN_URL = 'sqlite://'
|
||||||
@@ -21,11 +17,23 @@ REQUIRED_ORDERTIF = ['buy', 'sell']
|
|||||||
REQUIRED_ORDERTYPES = ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
REQUIRED_ORDERTYPES = ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
||||||
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
||||||
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
||||||
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList']
|
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList', 'PrecisionFilter', 'PriceFilter']
|
||||||
DRY_RUN_WALLET = 999.9
|
DRY_RUN_WALLET = 999.9
|
||||||
DEFAULT_DOWNLOAD_TICKER_INTERVALS = '1m 5m'
|
MATH_CLOSE_PREC = 1e-14 # Precision used for float comparisons
|
||||||
|
|
||||||
TICKER_INTERVALS = [
|
USERPATH_HYPEROPTS = 'hyperopts'
|
||||||
|
USERPATH_STRATEGY = 'strategies'
|
||||||
|
|
||||||
|
# Soure files with destination directories within user-directory
|
||||||
|
USER_DATA_FILES = {
|
||||||
|
'sample_strategy.py': USERPATH_STRATEGY,
|
||||||
|
'sample_hyperopt_advanced.py': USERPATH_HYPEROPTS,
|
||||||
|
'sample_hyperopt_loss.py': USERPATH_HYPEROPTS,
|
||||||
|
'sample_hyperopt.py': USERPATH_HYPEROPTS,
|
||||||
|
'strategy_analysis_example.ipynb': 'notebooks',
|
||||||
|
}
|
||||||
|
|
||||||
|
TIMEFRAMES = [
|
||||||
'1m', '3m', '5m', '15m', '30m',
|
'1m', '3m', '5m', '15m', '30m',
|
||||||
'1h', '2h', '4h', '6h', '8h', '12h',
|
'1h', '2h', '4h', '6h', '8h', '12h',
|
||||||
'1d', '3d', '1w',
|
'1d', '3d', '1w',
|
||||||
@@ -39,17 +47,31 @@ 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', 'number'], 'minimum': -1},
|
||||||
'ticker_interval': {'type': 'string', 'enum': TICKER_INTERVALS},
|
'ticker_interval': {'type': 'string', 'enum': TIMEFRAMES},
|
||||||
'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'],
|
||||||
"minimum": 0.0005,
|
'minimum': 0.0001,
|
||||||
"pattern": UNLIMITED_STAKE_AMOUNT
|
'pattern': UNLIMITED_STAKE_AMOUNT
|
||||||
},
|
},
|
||||||
'fiat_display_currency': {'type': 'string', 'enum': SUPPORTED_FIAT},
|
'fiat_display_currency': {'type': 'string', 'enum': SUPPORTED_FIAT},
|
||||||
'dry_run': {'type': 'boolean'},
|
'dry_run': {'type': 'boolean'},
|
||||||
@@ -71,8 +93,8 @@ CONF_SCHEMA = {
|
|||||||
'unfilledtimeout': {
|
'unfilledtimeout': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'buy': {'type': 'number', 'minimum': 3},
|
'buy': {'type': 'number', 'minimum': 1},
|
||||||
'sell': {'type': 'number', 'minimum': 10}
|
'sell': {'type': 'number', 'minimum': 1}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
'bid_strategy': {
|
'bid_strategy': {
|
||||||
@@ -84,7 +106,7 @@ CONF_SCHEMA = {
|
|||||||
'maximum': 1,
|
'maximum': 1,
|
||||||
'exclusiveMaximum': False,
|
'exclusiveMaximum': False,
|
||||||
'use_order_book': {'type': 'boolean'},
|
'use_order_book': {'type': 'boolean'},
|
||||||
'order_book_top': {'type': 'number', 'maximum': 20, 'minimum': 1},
|
'order_book_top': {'type': 'integer', 'maximum': 20, 'minimum': 1},
|
||||||
'check_depth_of_market': {
|
'check_depth_of_market': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
@@ -100,8 +122,11 @@ CONF_SCHEMA = {
|
|||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'use_order_book': {'type': 'boolean'},
|
'use_order_book': {'type': 'boolean'},
|
||||||
'order_book_min': {'type': 'number', 'minimum': 1},
|
'order_book_min': {'type': 'integer', 'minimum': 1},
|
||||||
'order_book_max': {'type': 'number', 'minimum': 1, 'maximum': 50}
|
'order_book_max': {'type': 'integer', 'minimum': 1, 'maximum': 50},
|
||||||
|
'use_sell_signal': {'type': 'boolean'},
|
||||||
|
'sell_profit_only': {'type': 'boolean'},
|
||||||
|
'ignore_roi_if_buy_signal': {'type': 'boolean'}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
'order_types': {
|
'order_types': {
|
||||||
@@ -109,6 +134,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'}
|
||||||
@@ -130,16 +156,20 @@ CONF_SCHEMA = {
|
|||||||
'properties': {
|
'properties': {
|
||||||
'use_sell_signal': {'type': 'boolean'},
|
'use_sell_signal': {'type': 'boolean'},
|
||||||
'sell_profit_only': {'type': 'boolean'},
|
'sell_profit_only': {'type': 'boolean'},
|
||||||
'ignore_roi_if_buy_signal_true': {'type': 'boolean'}
|
'ignore_roi_if_buy_signal': {'type': 'boolean'},
|
||||||
|
'block_bad_exchanges': {'type': 'boolean'}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
'pairlist': {
|
'pairlists': {
|
||||||
|
'type': 'array',
|
||||||
|
'items': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'method': {'type': 'string', 'enum': AVAILABLE_PAIRLISTS},
|
'method': {'type': 'string', 'enum': AVAILABLE_PAIRLISTS},
|
||||||
'config': {'type': 'object'}
|
'config': {'type': 'object'}
|
||||||
},
|
},
|
||||||
'required': ['method']
|
'required': ['method'],
|
||||||
|
}
|
||||||
},
|
},
|
||||||
'telegram': {
|
'telegram': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
@@ -166,8 +196,8 @@ CONF_SCHEMA = {
|
|||||||
'listen_ip_address': {'format': 'ipv4'},
|
'listen_ip_address': {'format': 'ipv4'},
|
||||||
'listen_port': {
|
'listen_port': {
|
||||||
'type': 'integer',
|
'type': 'integer',
|
||||||
"minimum": 1024,
|
'minimum': 1024,
|
||||||
"maximum": 65535
|
'maximum': 65535
|
||||||
},
|
},
|
||||||
'username': {'type': 'string'},
|
'username': {'type': 'string'},
|
||||||
'password': {'type': 'string'},
|
'password': {'type': 'string'},
|
||||||
@@ -180,7 +210,7 @@ CONF_SCHEMA = {
|
|||||||
'internals': {
|
'internals': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'process_throttle_secs': {'type': 'number'},
|
'process_throttle_secs': {'type': 'integer'},
|
||||||
'interval': {'type': 'integer'},
|
'interval': {'type': 'integer'},
|
||||||
'sd_notify': {'type': 'boolean'},
|
'sd_notify': {'type': 'boolean'},
|
||||||
}
|
}
|
||||||
@@ -217,37 +247,37 @@ CONF_SCHEMA = {
|
|||||||
'ccxt_config': {'type': 'object'},
|
'ccxt_config': {'type': 'object'},
|
||||||
'ccxt_async_config': {'type': 'object'}
|
'ccxt_async_config': {'type': 'object'}
|
||||||
},
|
},
|
||||||
'required': ['name', 'pair_whitelist']
|
'required': ['name']
|
||||||
},
|
},
|
||||||
'edge': {
|
'edge': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
"enabled": {'type': 'boolean'},
|
'enabled': {'type': 'boolean'},
|
||||||
"process_throttle_secs": {'type': 'integer', 'minimum': 600},
|
'process_throttle_secs': {'type': 'integer', 'minimum': 600},
|
||||||
"calculate_since_number_of_days": {'type': 'integer'},
|
'calculate_since_number_of_days': {'type': 'integer'},
|
||||||
"allowed_risk": {'type': 'number'},
|
'allowed_risk': {'type': 'number'},
|
||||||
"capital_available_percentage": {'type': 'number'},
|
'capital_available_percentage': {'type': 'number'},
|
||||||
"stoploss_range_min": {'type': 'number'},
|
'stoploss_range_min': {'type': 'number'},
|
||||||
"stoploss_range_max": {'type': 'number'},
|
'stoploss_range_max': {'type': 'number'},
|
||||||
"stoploss_range_step": {'type': 'number'},
|
'stoploss_range_step': {'type': 'number'},
|
||||||
"minimum_winrate": {'type': 'number'},
|
'minimum_winrate': {'type': 'number'},
|
||||||
"minimum_expectancy": {'type': 'number'},
|
'minimum_expectancy': {'type': 'number'},
|
||||||
"min_trade_number": {'type': 'number'},
|
'min_trade_number': {'type': 'number'},
|
||||||
"max_trade_duration_minute": {'type': 'integer'},
|
'max_trade_duration_minute': {'type': 'integer'},
|
||||||
"remove_pumps": {'type': 'boolean'}
|
'remove_pumps': {'type': 'boolean'}
|
||||||
},
|
},
|
||||||
'required': ['process_throttle_secs', 'allowed_risk', 'capital_available_percentage']
|
'required': ['process_throttle_secs', 'allowed_risk', 'capital_available_percentage']
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
'anyOf': [
|
|
||||||
{'required': ['exchange']}
|
|
||||||
],
|
|
||||||
'required': [
|
'required': [
|
||||||
|
'exchange',
|
||||||
'max_open_trades',
|
'max_open_trades',
|
||||||
'stake_currency',
|
'stake_currency',
|
||||||
'stake_amount',
|
'stake_amount',
|
||||||
'dry_run',
|
'dry_run',
|
||||||
'bid_strategy',
|
'bid_strategy',
|
||||||
'telegram'
|
'unfilledtimeout',
|
||||||
|
'stoploss',
|
||||||
|
'minimal_roi',
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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'
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from typing import Dict
|
|||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pytz
|
from datetime import timezone
|
||||||
|
|
||||||
from freqtrade import persistence
|
from freqtrade import persistence
|
||||||
from freqtrade.misc import json_load
|
from freqtrade.misc import json_load
|
||||||
@@ -30,7 +30,7 @@ def load_backtest_data(filename) -> pd.DataFrame:
|
|||||||
filename = Path(filename)
|
filename = Path(filename)
|
||||||
|
|
||||||
if not filename.is_file():
|
if not filename.is_file():
|
||||||
raise ValueError("File {filename} does not exist.")
|
raise ValueError(f"File {filename} does not exist.")
|
||||||
|
|
||||||
with filename.open() as file:
|
with filename.open() as file:
|
||||||
data = json_load(file)
|
data = json_load(file)
|
||||||
@@ -52,16 +52,18 @@ def load_backtest_data(filename) -> pd.DataFrame:
|
|||||||
return df
|
return df
|
||||||
|
|
||||||
|
|
||||||
def evaluate_result_multi(results: pd.DataFrame, freq: str, max_open_trades: int) -> pd.DataFrame:
|
def analyze_trade_parallelism(results: pd.DataFrame, timeframe: str) -> pd.DataFrame:
|
||||||
"""
|
"""
|
||||||
Find overlapping trades by expanding each trade once per period it was open
|
Find overlapping trades by expanding each trade once per period it was open
|
||||||
and then counting overlaps
|
and then counting overlaps.
|
||||||
:param results: Results Dataframe - can be loaded
|
:param results: Results Dataframe - can be loaded
|
||||||
:param freq: Frequency used for the backtest
|
:param timeframe: Timeframe used for backtest
|
||||||
:param max_open_trades: parameter max_open_trades used during backtest run
|
:return: dataframe with open-counts per time-period in timeframe
|
||||||
:return: dataframe with open-counts per time-period in freq
|
|
||||||
"""
|
"""
|
||||||
dates = [pd.Series(pd.date_range(row[1].open_time, row[1].close_time, freq=freq))
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
timeframe_min = timeframe_to_minutes(timeframe)
|
||||||
|
dates = [pd.Series(pd.date_range(row[1].open_time, row[1].close_time,
|
||||||
|
freq=f"{timeframe_min}min"))
|
||||||
for row in results[['open_time', 'close_time']].iterrows()]
|
for row in results[['open_time', 'close_time']].iterrows()]
|
||||||
deltas = [len(x) for x in dates]
|
deltas = [len(x) for x in dates]
|
||||||
dates = pd.Series(pd.concat(dates).values, name='date')
|
dates = pd.Series(pd.concat(dates).values, name='date')
|
||||||
@@ -69,8 +71,23 @@ def evaluate_result_multi(results: pd.DataFrame, freq: str, max_open_trades: int
|
|||||||
|
|
||||||
df2 = pd.concat([dates, df2], axis=1)
|
df2 = pd.concat([dates, df2], axis=1)
|
||||||
df2 = df2.set_index('date')
|
df2 = df2.set_index('date')
|
||||||
df_final = df2.resample(freq)[['pair']].count()
|
df_final = df2.resample(f"{timeframe_min}min")[['pair']].count()
|
||||||
return df_final[df_final['pair'] > max_open_trades]
|
df_final = df_final.rename({'pair': 'open_trades'}, axis=1)
|
||||||
|
return df_final
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_result_multi(results: pd.DataFrame, timeframe: str,
|
||||||
|
max_open_trades: int) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Find overlapping trades by expanding each trade once per period it was open
|
||||||
|
and then counting overlaps
|
||||||
|
:param results: Results Dataframe - can be loaded
|
||||||
|
:param timeframe: Frequency used for the backtest
|
||||||
|
:param max_open_trades: parameter max_open_trades used during backtest run
|
||||||
|
:return: dataframe with open-counts per time-period in freq
|
||||||
|
"""
|
||||||
|
df_final = analyze_trade_parallelism(results, timeframe)
|
||||||
|
return df_final[df_final['open_trades'] > max_open_trades]
|
||||||
|
|
||||||
|
|
||||||
def load_trades_from_db(db_url: str) -> pd.DataFrame:
|
def load_trades_from_db(db_url: str) -> pd.DataFrame:
|
||||||
@@ -81,36 +98,47 @@ def load_trades_from_db(db_url: str) -> pd.DataFrame:
|
|||||||
"""
|
"""
|
||||||
trades: pd.DataFrame = pd.DataFrame([], columns=BT_DATA_COLUMNS)
|
trades: pd.DataFrame = pd.DataFrame([], columns=BT_DATA_COLUMNS)
|
||||||
persistence.init(db_url, clean_open_orders=False)
|
persistence.init(db_url, clean_open_orders=False)
|
||||||
columns = ["pair", "profit", "open_time", "close_time",
|
|
||||||
"open_rate", "close_rate", "duration", "sell_reason",
|
|
||||||
"max_rate", "min_rate"]
|
|
||||||
|
|
||||||
trades = pd.DataFrame([(t.pair, t.calc_profit(),
|
columns = ["pair", "open_time", "close_time", "profit", "profitperc",
|
||||||
t.open_date.replace(tzinfo=pytz.UTC),
|
"open_rate", "close_rate", "amount", "duration", "sell_reason",
|
||||||
t.close_date.replace(tzinfo=pytz.UTC) if t.close_date else None,
|
"fee_open", "fee_close", "open_rate_requested", "close_rate_requested",
|
||||||
t.open_rate, t.close_rate,
|
"stake_amount", "max_rate", "min_rate", "id", "exchange",
|
||||||
t.close_date.timestamp() - t.open_date.timestamp()
|
"stop_loss", "initial_stop_loss", "strategy", "ticker_interval"]
|
||||||
if t.close_date else None,
|
|
||||||
|
trades = pd.DataFrame([(t.pair,
|
||||||
|
t.open_date.replace(tzinfo=timezone.utc),
|
||||||
|
t.close_date.replace(tzinfo=timezone.utc) if t.close_date else None,
|
||||||
|
t.calc_profit(), t.calc_profit_percent(),
|
||||||
|
t.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.sell_reason,
|
||||||
|
t.fee_open, t.fee_close,
|
||||||
|
t.open_rate_requested,
|
||||||
|
t.close_rate_requested,
|
||||||
|
t.stake_amount,
|
||||||
t.max_rate,
|
t.max_rate,
|
||||||
t.min_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()],
|
for t in Trade.get_trades().all()],
|
||||||
columns=columns)
|
columns=columns)
|
||||||
|
|
||||||
return trades
|
return trades
|
||||||
|
|
||||||
|
|
||||||
def load_trades(config) -> pd.DataFrame:
|
def load_trades(source: str, db_url: str, exportfilename: str) -> pd.DataFrame:
|
||||||
"""
|
"""
|
||||||
Based on configuration option "trade_source":
|
Based on configuration option "trade_source":
|
||||||
* loads data from DB (using `db_url`)
|
* loads data from DB (using `db_url`)
|
||||||
* loads data from backtestfile (using `exportfilename`)
|
* loads data from backtestfile (using `exportfilename`)
|
||||||
"""
|
"""
|
||||||
if config["trade_source"] == "DB":
|
if source == "DB":
|
||||||
return load_trades_from_db(config["db_url"])
|
return load_trades_from_db(db_url)
|
||||||
elif config["trade_source"] == "file":
|
elif source == "file":
|
||||||
return load_backtest_data(Path(config["exportfilename"]))
|
return load_backtest_data(Path(exportfilename))
|
||||||
|
|
||||||
|
|
||||||
def extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame) -> pd.DataFrame:
|
def extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame) -> pd.DataFrame:
|
||||||
@@ -139,14 +167,21 @@ def combine_tickers_with_mean(tickers: Dict[str, pd.DataFrame], column: str = "c
|
|||||||
return df_comb
|
return df_comb
|
||||||
|
|
||||||
|
|
||||||
def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str) -> pd.DataFrame:
|
def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str,
|
||||||
|
timeframe: str) -> pd.DataFrame:
|
||||||
"""
|
"""
|
||||||
Adds a column `col_name` with the cumulative profit for the given trades array.
|
Adds a column `col_name` with the cumulative profit for the given trades array.
|
||||||
:param df: DataFrame with date index
|
:param df: DataFrame with date index
|
||||||
:param trades: DataFrame containing trades (requires columns close_time and profitperc)
|
:param trades: DataFrame containing trades (requires columns close_time and profitperc)
|
||||||
|
:param col_name: Column name that will be assigned the results
|
||||||
|
:param timeframe: Timeframe used during the operations
|
||||||
:return: Returns df with one additional column, col_name, containing the cumulative profit.
|
:return: Returns df with one additional column, col_name, containing the cumulative profit.
|
||||||
"""
|
"""
|
||||||
df[col_name] = trades.set_index('close_time')['profitperc'].cumsum()
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
timeframe_minutes = timeframe_to_minutes(timeframe)
|
||||||
|
# Resample to timeframe to make sure trades match candles
|
||||||
|
_trades_sum = trades.resample(f'{timeframe_minutes}min', on='close_time')[['profitperc']].sum()
|
||||||
|
df.loc[:, col_name] = _trades_sum.cumsum()
|
||||||
# Set first value to 0
|
# Set first value to 0
|
||||||
df.loc[df.iloc[0].name, col_name] = 0
|
df.loc[df.iloc[0].name, col_name] = 0
|
||||||
# FFill to get continuous
|
# FFill to get continuous
|
||||||
|
|||||||
@@ -10,13 +10,13 @@ from pandas import DataFrame, to_datetime
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def parse_ticker_dataframe(ticker: list, ticker_interval: str, pair: str, *,
|
def parse_ticker_dataframe(ticker: list, timeframe: str, pair: str, *,
|
||||||
fill_missing: bool = True,
|
fill_missing: bool = True,
|
||||||
drop_incomplete: bool = True) -> DataFrame:
|
drop_incomplete: bool = True) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Converts a ticker-list (format ccxt.fetch_ohlcv) to a Dataframe
|
Converts a ticker-list (format ccxt.fetch_ohlcv) to a Dataframe
|
||||||
:param ticker: ticker list, as returned by exchange.async_get_candle_history
|
:param ticker: ticker list, as returned by exchange.async_get_candle_history
|
||||||
:param ticker_interval: ticker_interval (e.g. 5m). Used to fill up eventual missing data
|
:param timeframe: timeframe (e.g. 5m). Used to fill up eventual missing data
|
||||||
:param pair: Pair this data is for (used to warn if fillup was necessary)
|
:param pair: Pair this data is for (used to warn if fillup was necessary)
|
||||||
:param fill_missing: fill up missing candles with 0 candles
|
:param fill_missing: fill up missing candles with 0 candles
|
||||||
(see ohlcv_fill_up_missing_data for details)
|
(see ohlcv_fill_up_missing_data for details)
|
||||||
@@ -52,12 +52,12 @@ def parse_ticker_dataframe(ticker: list, ticker_interval: str, pair: str, *,
|
|||||||
logger.debug('Dropping last candle')
|
logger.debug('Dropping last candle')
|
||||||
|
|
||||||
if fill_missing:
|
if fill_missing:
|
||||||
return ohlcv_fill_up_missing_data(frame, ticker_interval, pair)
|
return ohlcv_fill_up_missing_data(frame, timeframe, pair)
|
||||||
else:
|
else:
|
||||||
return frame
|
return frame
|
||||||
|
|
||||||
|
|
||||||
def ohlcv_fill_up_missing_data(dataframe: DataFrame, ticker_interval: str, pair: str) -> DataFrame:
|
def ohlcv_fill_up_missing_data(dataframe: DataFrame, timeframe: str, pair: str) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Fills up missing data with 0 volume rows,
|
Fills up missing data with 0 volume rows,
|
||||||
using the previous close as price for "open", "high" "low" and "close", volume is set to 0
|
using the previous close as price for "open", "high" "low" and "close", volume is set to 0
|
||||||
@@ -72,7 +72,7 @@ def ohlcv_fill_up_missing_data(dataframe: DataFrame, ticker_interval: str, pair:
|
|||||||
'close': 'last',
|
'close': 'last',
|
||||||
'volume': 'sum'
|
'volume': 'sum'
|
||||||
}
|
}
|
||||||
ticker_minutes = timeframe_to_minutes(ticker_interval)
|
ticker_minutes = timeframe_to_minutes(timeframe)
|
||||||
# Resample to create "NAN" values
|
# Resample to create "NAN" values
|
||||||
df = dataframe.resample(f'{ticker_minutes}min', on='date').agg(ohlc_dict)
|
df = dataframe.resample(f'{ticker_minutes}min', on='date').agg(ohlc_dict)
|
||||||
|
|
||||||
@@ -114,3 +114,25 @@ def order_book_to_dataframe(bids: list, asks: list) -> DataFrame:
|
|||||||
keys=['b_sum', 'b_size', 'bids', 'asks', 'a_size', 'a_sum'])
|
keys=['b_sum', 'b_size', 'bids', 'asks', 'a_size', 'a_sum'])
|
||||||
# logger.info('order book %s', frame )
|
# logger.info('order book %s', frame )
|
||||||
return frame
|
return frame
|
||||||
|
|
||||||
|
|
||||||
|
def trades_to_ohlcv(trades: list, timeframe: str) -> list:
|
||||||
|
"""
|
||||||
|
Converts trades list to ohlcv list
|
||||||
|
:param trades: List of trades, as returned by ccxt.fetch_trades.
|
||||||
|
:param timeframe: Ticker timeframe to resample data to
|
||||||
|
:return: ohlcv timeframe as list (as returned by ccxt.fetch_ohlcv)
|
||||||
|
"""
|
||||||
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
ticker_minutes = timeframe_to_minutes(timeframe)
|
||||||
|
df = pd.DataFrame(trades)
|
||||||
|
df['datetime'] = pd.to_datetime(df['datetime'])
|
||||||
|
df = df.set_index('datetime')
|
||||||
|
|
||||||
|
df_new = df['price'].resample(f'{ticker_minutes}min').ohlc()
|
||||||
|
df_new['volume'] = df['amount'].resample(f'{ticker_minutes}min').sum()
|
||||||
|
df_new['date'] = df_new.index.astype("int64") // 10 ** 6
|
||||||
|
# Drop 0 volume rows
|
||||||
|
df_new = df_new.dropna()
|
||||||
|
columns = ["date", "open", "high", "low", "close", "volume"]
|
||||||
|
return list(zip(*[df_new[x].values.tolist() for x in columns]))
|
||||||
|
|||||||
@@ -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():
|
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,63 @@ class DataProvider():
|
|||||||
@property
|
@property
|
||||||
def available_pairs(self) -> List[Tuple[str, str]]:
|
def available_pairs(self) -> List[Tuple[str, str]]:
|
||||||
"""
|
"""
|
||||||
Return a list of tuples containing pair, ticker_interval for which data is currently cached.
|
Return a list of tuples containing (pair, timeframe) for which data is currently cached.
|
||||||
Should be whitelist + open trades.
|
Should be whitelist + open trades.
|
||||||
"""
|
"""
|
||||||
return list(self._exchange._klines.keys())
|
return list(self._exchange._klines.keys())
|
||||||
|
|
||||||
def ohlcv(self, pair: str, ticker_interval: str = None, copy: bool = True) -> DataFrame:
|
def ohlcv(self, pair: str, timeframe: str = None, copy: bool = True) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
get ohlcv data for the given pair as DataFrame
|
Get ohlcv data for the given pair as DataFrame
|
||||||
Please 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 ticker_interval: ticker_interval to get pair for
|
:param timeframe: Ticker timeframe 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 ticker_interval:
|
return self._exchange.klines((pair, timeframe or self._config['ticker_interval']),
|
||||||
pairtick = (pair, ticker_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, timeframe: str = None) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
get stored historic ohlcv data
|
Get stored historic ohlcv data
|
||||||
:param pair: pair to get the data for
|
:param pair: pair to get the data for
|
||||||
:param ticker_interval: ticker_interval to get pair for
|
:param timeframe: timeframe to get data for
|
||||||
"""
|
"""
|
||||||
return load_pair_history(pair=pair,
|
return load_pair_history(pair=pair,
|
||||||
ticker_interval=ticker_interval,
|
timeframe=timeframe 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, timeframe: 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 timeframe: timeframe to get data for
|
||||||
|
:return: Dataframe for this pair
|
||||||
|
"""
|
||||||
|
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
||||||
|
# Get live ohlcv data.
|
||||||
|
data = self.ohlcv(pair=pair, timeframe=timeframe)
|
||||||
|
else:
|
||||||
|
# Get historic ohlcv data (cached on disk).
|
||||||
|
data = self.historic_ohlcv(pair=pair, timeframe=timeframe)
|
||||||
|
if len(data) == 0:
|
||||||
|
logger.warning(f"No data found for ({pair}, {timeframe}).")
|
||||||
|
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,9 +101,9 @@ class DataProvider():
|
|||||||
# TODO: Implement me
|
# TODO: Implement me
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def orderbook(self, pair: str, maximum: int):
|
def orderbook(self, pair: str, maximum: int) -> Dict[str, List]:
|
||||||
"""
|
"""
|
||||||
return latest orderbook data
|
fetch latest orderbook data
|
||||||
:param pair: pair to get the data for
|
:param pair: pair to get the data for
|
||||||
:param maximum: Maximum number of orderbook entries to query
|
:param maximum: Maximum number of orderbook entries to query
|
||||||
:return: dict including bids/asks with a total of `maximum` entries.
|
:return: dict including bids/asks with a total of `maximum` entries.
|
||||||
|
|||||||
@@ -8,7 +8,8 @@ Includes:
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
import operator
|
import operator
|
||||||
from datetime import datetime
|
from copy import deepcopy
|
||||||
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, List, Optional, Tuple
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
@@ -17,8 +18,8 @@ from pandas import DataFrame
|
|||||||
|
|
||||||
from freqtrade import OperationalException, misc
|
from freqtrade import OperationalException, misc
|
||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.data.converter import parse_ticker_dataframe
|
from freqtrade.data.converter import parse_ticker_dataframe, trades_to_ohlcv
|
||||||
from freqtrade.exchange import Exchange, timeframe_to_minutes
|
from freqtrade.exchange import Exchange, timeframe_to_minutes, timeframe_to_seconds
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -33,20 +34,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
|
||||||
@@ -57,37 +50,94 @@ 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 trim_dataframe(df: DataFrame, timerange: TimeRange, df_date_col: str = 'date') -> DataFrame:
|
||||||
datadir: Optional[Path], pair: str,
|
"""
|
||||||
ticker_interval: str,
|
Trim dataframe based on given timerange
|
||||||
|
:param df: Dataframe to trim
|
||||||
|
:param timerange: timerange (use start and end date if available)
|
||||||
|
:param: df_date_col: Column in the dataframe to use as Date column
|
||||||
|
:return: trimmed dataframe
|
||||||
|
"""
|
||||||
|
if timerange.starttype == 'date':
|
||||||
|
start = datetime.fromtimestamp(timerange.startts, tz=timezone.utc)
|
||||||
|
df = df.loc[df[df_date_col] >= start, :]
|
||||||
|
if timerange.stoptype == 'date':
|
||||||
|
stop = datetime.fromtimestamp(timerange.stopts, tz=timezone.utc)
|
||||||
|
df = df.loc[df[df_date_col] <= stop, :]
|
||||||
|
return df
|
||||||
|
|
||||||
|
|
||||||
|
def load_tickerdata_file(datadir: Path, pair: str, timeframe: str,
|
||||||
timerange: Optional[TimeRange] = None) -> Optional[list]:
|
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
|
||||||
"""
|
"""
|
||||||
filename = pair_data_filename(datadir, pair, ticker_interval)
|
filename = pair_data_filename(datadir, pair, timeframe)
|
||||||
pairdata = misc.file_load_json(filename)
|
pairdata = misc.file_load_json(filename)
|
||||||
if not pairdata:
|
if not pairdata:
|
||||||
return 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,
|
||||||
|
timeframe: str, data: list, is_zip: bool = False):
|
||||||
|
"""
|
||||||
|
Stores tickerdata to file
|
||||||
|
"""
|
||||||
|
filename = pair_data_filename(datadir, pair, timeframe)
|
||||||
|
misc.file_dump_json(filename, data, is_zip=is_zip)
|
||||||
|
|
||||||
|
|
||||||
|
def load_trades_file(datadir: Path, pair: str,
|
||||||
|
timerange: Optional[TimeRange] = None) -> List[Dict]:
|
||||||
|
"""
|
||||||
|
Load a pair from file, either .json.gz or .json
|
||||||
|
:return: tradelist or empty list if unsuccesful
|
||||||
|
"""
|
||||||
|
filename = pair_trades_filename(datadir, pair)
|
||||||
|
tradesdata = misc.file_load_json(filename)
|
||||||
|
if not tradesdata:
|
||||||
|
return []
|
||||||
|
|
||||||
|
return tradesdata
|
||||||
|
|
||||||
|
|
||||||
|
def store_trades_file(datadir: Path, pair: str,
|
||||||
|
data: list, is_zip: bool = True):
|
||||||
|
"""
|
||||||
|
Stores tickerdata to file
|
||||||
|
"""
|
||||||
|
filename = pair_trades_filename(datadir, pair)
|
||||||
|
misc.file_dump_json(filename, data, is_zip=is_zip)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_pairdata(pair, pairdata, timerange: TimeRange):
|
||||||
|
if timerange.starttype == 'date' and pairdata[0][0] > timerange.startts * 1000:
|
||||||
|
logger.warning('Missing data at start for pair %s, data starts at %s',
|
||||||
|
pair, arrow.get(pairdata[0][0] // 1000).strftime('%Y-%m-%d %H:%M:%S'))
|
||||||
|
if timerange.stoptype == 'date' and pairdata[-1][0] < timerange.stopts * 1000:
|
||||||
|
logger.warning('Missing data at end for pair %s, data ends at %s',
|
||||||
|
pair, arrow.get(pairdata[-1][0] // 1000).strftime('%Y-%m-%d %H:%M:%S'))
|
||||||
|
|
||||||
|
|
||||||
def load_pair_history(pair: str,
|
def load_pair_history(pair: str,
|
||||||
ticker_interval: str,
|
timeframe: 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
|
drop_incomplete: bool = True,
|
||||||
|
startup_candles: int = 0,
|
||||||
) -> 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 pair: Pair to load data for
|
||||||
:param ticker_interval: Ticker-interval (e.g. "5m")
|
:param timeframe: Ticker timeframe (e.g. "5m")
|
||||||
:param datadir: Path to the data storage location.
|
:param datadir: Path to the data storage location.
|
||||||
:param timerange: Limit data to be loaded to this timerange
|
:param timerange: Limit data to be loaded to this timerange
|
||||||
:param refresh_pairs: Refresh pairs from exchange.
|
:param refresh_pairs: Refresh pairs from exchange.
|
||||||
@@ -95,93 +145,106 @@ def load_pair_history(pair: str,
|
|||||||
:param exchange: Exchange object (needed when using "refresh_pairs")
|
:param exchange: Exchange object (needed when using "refresh_pairs")
|
||||||
:param fill_up_missing: Fill missing values with "No action"-candles
|
:param fill_up_missing: Fill missing values with "No action"-candles
|
||||||
:param drop_incomplete: Drop last candle assuming it may be incomplete.
|
:param drop_incomplete: Drop last candle assuming it may be incomplete.
|
||||||
:return: DataFrame with ohlcv data
|
:param startup_candles: Additional candles to load at the start of the period
|
||||||
|
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
timerange_startup = deepcopy(timerange)
|
||||||
|
if startup_candles > 0 and timerange_startup:
|
||||||
|
timerange_startup.subtract_start(timeframe_to_seconds(timeframe) * startup_candles)
|
||||||
|
|
||||||
# The user forced the refresh of pairs
|
# The user forced the refresh of pairs
|
||||||
if refresh_pairs:
|
if refresh_pairs:
|
||||||
download_pair_history(datadir=datadir,
|
download_pair_history(datadir=datadir,
|
||||||
exchange=exchange,
|
exchange=exchange,
|
||||||
pair=pair,
|
pair=pair,
|
||||||
ticker_interval=ticker_interval,
|
timeframe=timeframe,
|
||||||
timerange=timerange)
|
timerange=timerange)
|
||||||
|
|
||||||
pairdata = load_tickerdata_file(datadir, pair, ticker_interval, timerange=timerange)
|
pairdata = load_tickerdata_file(datadir, pair, timeframe, timerange=timerange_startup)
|
||||||
|
|
||||||
if pairdata:
|
if pairdata:
|
||||||
if timerange.starttype == 'date' and pairdata[0][0] > timerange.startts * 1000:
|
if timerange_startup:
|
||||||
logger.warning('Missing data at start for pair %s, data starts at %s',
|
_validate_pairdata(pair, pairdata, timerange_startup)
|
||||||
pair, arrow.get(pairdata[0][0] // 1000).strftime('%Y-%m-%d %H:%M:%S'))
|
return parse_ticker_dataframe(pairdata, timeframe, pair=pair,
|
||||||
if timerange.stoptype == 'date' and pairdata[-1][0] < timerange.stopts * 1000:
|
|
||||||
logger.warning('Missing data at end for pair %s, data ends at %s',
|
|
||||||
pair,
|
|
||||||
arrow.get(pairdata[-1][0] // 1000).strftime('%Y-%m-%d %H:%M:%S'))
|
|
||||||
return parse_ticker_dataframe(pairdata, ticker_interval, pair=pair,
|
|
||||||
fill_missing=fill_up_missing,
|
fill_missing=fill_up_missing,
|
||||||
drop_incomplete=drop_incomplete)
|
drop_incomplete=drop_incomplete)
|
||||||
else:
|
else:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f'No history data for pair: "{pair}", interval: {ticker_interval}. '
|
f'No history data for pair: "{pair}", timeframe: {timeframe}. '
|
||||||
'Use --refresh-pairs-cached option or download_backtest_data.py '
|
'Use `freqtrade download-data` to download the data'
|
||||||
'script to download the data'
|
|
||||||
)
|
)
|
||||||
return None
|
return DataFrame()
|
||||||
|
|
||||||
|
|
||||||
def load_data(datadir: Optional[Path],
|
def load_data(datadir: Path,
|
||||||
ticker_interval: str,
|
timeframe: 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,
|
fill_up_missing: bool = True,
|
||||||
live: bool = False
|
startup_candles: int = 0,
|
||||||
|
fail_without_data: bool = False
|
||||||
) -> Dict[str, DataFrame]:
|
) -> 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>)
|
:param datadir: Path to the data storage location.
|
||||||
|
:param timeframe: Ticker Timeframe (e.g. "5m")
|
||||||
|
:param pairs: List of pairs to load
|
||||||
|
:param refresh_pairs: Refresh pairs from exchange.
|
||||||
|
(Note: Requires exchange to be passed as well.)
|
||||||
|
:param exchange: Exchange object (needed when using "refresh_pairs")
|
||||||
|
:param timerange: Limit data to be loaded to this timerange
|
||||||
|
:param fill_up_missing: Fill missing values with "No action"-candles
|
||||||
|
:param startup_candles: Additional candles to load at the start of the period
|
||||||
|
:param fail_without_data: Raise OperationalException if no data is found.
|
||||||
|
:return: dict(<pair>:<Dataframe>)
|
||||||
|
TODO: refresh_pairs is still used by edge to keep the data uptodate.
|
||||||
|
This should be replaced in the future. Instead, writing the current candles to disk
|
||||||
|
from dataprovider should be implemented, as this would avoid loading ohlcv data twice.
|
||||||
|
exchange and refresh_pairs are then not needed here nor in load_pair_history.
|
||||||
"""
|
"""
|
||||||
result: Dict[str, DataFrame] = {}
|
result: Dict[str, DataFrame] = {}
|
||||||
if live:
|
if startup_candles > 0 and timerange:
|
||||||
if exchange:
|
logger.info(f'Using indicator startup period: {startup_candles} ...')
|
||||||
logger.info('Live: Downloading data for all defined pairs ...')
|
|
||||||
exchange.refresh_latest_ohlcv([(pair, ticker_interval) for pair in pairs])
|
|
||||||
result = {key[0]: value for key, value in exchange._klines.items() if value is not None}
|
|
||||||
else:
|
|
||||||
raise OperationalException(
|
|
||||||
"Exchange needs to be initialized when using live data."
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
logger.info('Using local backtesting data ...')
|
|
||||||
|
|
||||||
for pair in pairs:
|
for pair in pairs:
|
||||||
hist = load_pair_history(pair=pair, ticker_interval=ticker_interval,
|
hist = load_pair_history(pair=pair, timeframe=timeframe,
|
||||||
datadir=datadir, timerange=timerange,
|
datadir=datadir, timerange=timerange,
|
||||||
refresh_pairs=refresh_pairs,
|
refresh_pairs=refresh_pairs,
|
||||||
exchange=exchange,
|
exchange=exchange,
|
||||||
fill_up_missing=fill_up_missing)
|
fill_up_missing=fill_up_missing,
|
||||||
if hist is not None:
|
startup_candles=startup_candles)
|
||||||
|
if not hist.empty:
|
||||||
result[pair] = hist
|
result[pair] = hist
|
||||||
|
|
||||||
|
if fail_without_data and not result:
|
||||||
|
raise OperationalException("No data found. Terminating.")
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def make_testdata_path(datadir: Optional[Path]) -> Path:
|
def pair_data_filename(datadir: Path, pair: str, timeframe: str) -> Path:
|
||||||
"""Return the path where testdata files are stored"""
|
|
||||||
return datadir or (Path(__file__).parent.parent / "tests" / "testdata").resolve()
|
|
||||||
|
|
||||||
|
|
||||||
def pair_data_filename(datadir: Optional[Path], pair: str, ticker_interval: str) -> Path:
|
|
||||||
path = make_testdata_path(datadir)
|
|
||||||
pair_s = pair.replace("/", "_")
|
pair_s = pair.replace("/", "_")
|
||||||
filename = path.joinpath(f'{pair_s}-{ticker_interval}.json')
|
filename = datadir.joinpath(f'{pair_s}-{timeframe}.json')
|
||||||
return filename
|
return filename
|
||||||
|
|
||||||
|
|
||||||
def load_cached_data_for_updating(filename: Path, ticker_interval: str,
|
def pair_trades_filename(datadir: Path, pair: str) -> Path:
|
||||||
|
pair_s = pair.replace("/", "_")
|
||||||
|
filename = datadir.joinpath(f'{pair_s}-trades.json.gz')
|
||||||
|
return filename
|
||||||
|
|
||||||
|
|
||||||
|
def _load_cached_data_for_updating(datadir: Path, pair: str, timeframe: str,
|
||||||
timerange: Optional[TimeRange]) -> Tuple[List[Any],
|
timerange: Optional[TimeRange]) -> Tuple[List[Any],
|
||||||
Optional[int]]:
|
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
|
||||||
@@ -191,13 +254,12 @@ def load_cached_data_for_updating(filename: Path, ticker_interval: str,
|
|||||||
if timerange.starttype == 'date':
|
if timerange.starttype == 'date':
|
||||||
since_ms = timerange.startts * 1000
|
since_ms = timerange.startts * 1000
|
||||||
elif timerange.stoptype == 'line':
|
elif timerange.stoptype == 'line':
|
||||||
num_minutes = timerange.stopts * timeframe_to_minutes(ticker_interval)
|
num_minutes = timerange.stopts * timeframe_to_minutes(timeframe)
|
||||||
since_ms = arrow.utcnow().shift(minutes=num_minutes).timestamp * 1000
|
since_ms = arrow.utcnow().shift(minutes=num_minutes).timestamp * 1000
|
||||||
|
|
||||||
# read the cached file
|
# read the cached file
|
||||||
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, timeframe)
|
||||||
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()
|
||||||
@@ -215,21 +277,21 @@ def load_cached_data_for_updating(filename: Path, ticker_interval: str,
|
|||||||
return (data, since_ms)
|
return (data, since_ms)
|
||||||
|
|
||||||
|
|
||||||
def download_pair_history(datadir: Optional[Path],
|
def download_pair_history(datadir: Path,
|
||||||
exchange: Optional[Exchange],
|
exchange: Optional[Exchange],
|
||||||
pair: str,
|
pair: str,
|
||||||
ticker_interval: str = '5m',
|
timeframe: str = '5m',
|
||||||
timerange: Optional[TimeRange] = None) -> bool:
|
timerange: Optional[TimeRange] = None) -> bool:
|
||||||
"""
|
"""
|
||||||
Download the latest ticker intervals from the exchange for the pair passed in parameters
|
Download latest candles from the exchange for the pair and timeframe passed in parameters
|
||||||
The data is downloaded starting from the last correct ticker interval data that
|
The data is downloaded starting from the last correct data that
|
||||||
exists in a cache. If timerange starts earlier than the data in the cache,
|
exists in a cache. If timerange starts earlier than the data in the cache,
|
||||||
the full data will be redownloaded
|
the full data will be redownloaded
|
||||||
|
|
||||||
Based on @Rybolov work: https://github.com/rybolov/freqtrade-data
|
Based on @Rybolov work: https://github.com/rybolov/freqtrade-data
|
||||||
|
|
||||||
:param pair: pair to download
|
:param pair: pair to download
|
||||||
:param ticker_interval: ticker interval
|
:param timeframe: Ticker Timeframe (e.g 5m)
|
||||||
:param timerange: range of time to download
|
:param timerange: range of time to download
|
||||||
:return: bool with success state
|
:return: bool with success state
|
||||||
"""
|
"""
|
||||||
@@ -239,39 +301,153 @@ def download_pair_history(datadir: Optional[Path],
|
|||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
filename = pair_data_filename(datadir, pair, ticker_interval)
|
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
f'Download history data for pair: "{pair}", interval: {ticker_interval} '
|
f'Download history data for pair: "{pair}", timeframe: {timeframe} '
|
||||||
f'and store in {datadir}.'
|
f'and store in {datadir}.'
|
||||||
)
|
)
|
||||||
|
|
||||||
data, since_ms = load_cached_data_for_updating(filename, ticker_interval, timerange)
|
data, since_ms = _load_cached_data_for_updating(datadir, pair, timeframe, timerange)
|
||||||
|
|
||||||
logger.debug("Current Start: %s", misc.format_ms_time(data[1][0]) if data else 'None')
|
logger.debug("Current Start: %s", misc.format_ms_time(data[1][0]) if data else 'None')
|
||||||
logger.debug("Current End: %s", misc.format_ms_time(data[-1][0]) if data else 'None')
|
logger.debug("Current End: %s", misc.format_ms_time(data[-1][0]) if data else 'None')
|
||||||
|
|
||||||
# Default since_ms to 30 days if nothing is given
|
# Default since_ms to 30 days if nothing is given
|
||||||
new_data = exchange.get_history(pair=pair, ticker_interval=ticker_interval,
|
new_data = exchange.get_historic_ohlcv(pair=pair, timeframe=timeframe,
|
||||||
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, timeframe, data=data)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(
|
logger.error(
|
||||||
f'Failed to download history data for pair: "{pair}", interval: {ticker_interval}. '
|
f'Failed to download history data for pair: "{pair}", timeframe: {timeframe}. '
|
||||||
f'Error: {e}'
|
f'Error: {e}'
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes: List[str],
|
||||||
|
dl_path: Path, timerange: Optional[TimeRange] = None,
|
||||||
|
erase=False) -> List[str]:
|
||||||
|
"""
|
||||||
|
Refresh stored ohlcv data for backtesting and hyperopt operations.
|
||||||
|
Used by freqtrade download-data
|
||||||
|
:return: Pairs not available
|
||||||
|
"""
|
||||||
|
pairs_not_available = []
|
||||||
|
for pair in pairs:
|
||||||
|
if pair not in exchange.markets:
|
||||||
|
pairs_not_available.append(pair)
|
||||||
|
logger.info(f"Skipping pair {pair}...")
|
||||||
|
continue
|
||||||
|
for timeframe in timeframes:
|
||||||
|
|
||||||
|
dl_file = pair_data_filename(dl_path, pair, timeframe)
|
||||||
|
if erase and dl_file.exists():
|
||||||
|
logger.info(
|
||||||
|
f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
||||||
|
dl_file.unlink()
|
||||||
|
|
||||||
|
logger.info(f'Downloading pair {pair}, interval {timeframe}.')
|
||||||
|
download_pair_history(datadir=dl_path, exchange=exchange,
|
||||||
|
pair=pair, timeframe=str(timeframe),
|
||||||
|
timerange=timerange)
|
||||||
|
return pairs_not_available
|
||||||
|
|
||||||
|
|
||||||
|
def download_trades_history(datadir: Path,
|
||||||
|
exchange: Exchange,
|
||||||
|
pair: str,
|
||||||
|
timerange: Optional[TimeRange] = None) -> bool:
|
||||||
|
"""
|
||||||
|
Download trade history from the exchange.
|
||||||
|
Appends to previously downloaded trades data.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
|
||||||
|
since = timerange.startts * 1000 if timerange and timerange.starttype == 'date' else None
|
||||||
|
|
||||||
|
trades = load_trades_file(datadir, pair)
|
||||||
|
|
||||||
|
from_id = trades[-1]['id'] if trades else None
|
||||||
|
|
||||||
|
logger.debug("Current Start: %s", trades[0]['datetime'] if trades else 'None')
|
||||||
|
logger.debug("Current End: %s", trades[-1]['datetime'] if trades else 'None')
|
||||||
|
|
||||||
|
new_trades = exchange.get_historic_trades(pair=pair,
|
||||||
|
since=since if since else
|
||||||
|
int(arrow.utcnow().shift(
|
||||||
|
days=-30).float_timestamp) * 1000,
|
||||||
|
# until=xxx,
|
||||||
|
from_id=from_id,
|
||||||
|
)
|
||||||
|
trades.extend(new_trades[1])
|
||||||
|
store_trades_file(datadir, pair, trades)
|
||||||
|
|
||||||
|
logger.debug("New Start: %s", trades[0]['datetime'])
|
||||||
|
logger.debug("New End: %s", trades[-1]['datetime'])
|
||||||
|
logger.info(f"New Amount of trades: {len(trades)}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(
|
||||||
|
f'Failed to download historic trades for pair: "{pair}". '
|
||||||
|
f'Error: {e}'
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def refresh_backtest_trades_data(exchange: Exchange, pairs: List[str], datadir: Path,
|
||||||
|
timerange: TimeRange, erase=False) -> List[str]:
|
||||||
|
"""
|
||||||
|
Refresh stored trades data.
|
||||||
|
Used by freqtrade download-data
|
||||||
|
:return: Pairs not available
|
||||||
|
"""
|
||||||
|
pairs_not_available = []
|
||||||
|
for pair in pairs:
|
||||||
|
if pair not in exchange.markets:
|
||||||
|
pairs_not_available.append(pair)
|
||||||
|
logger.info(f"Skipping pair {pair}...")
|
||||||
|
continue
|
||||||
|
|
||||||
|
dl_file = pair_trades_filename(datadir, pair)
|
||||||
|
if erase and dl_file.exists():
|
||||||
|
logger.info(
|
||||||
|
f'Deleting existing data for pair {pair}.')
|
||||||
|
dl_file.unlink()
|
||||||
|
|
||||||
|
logger.info(f'Downloading trades for pair {pair}.')
|
||||||
|
download_trades_history(datadir=datadir, exchange=exchange,
|
||||||
|
pair=pair,
|
||||||
|
timerange=timerange)
|
||||||
|
return pairs_not_available
|
||||||
|
|
||||||
|
|
||||||
|
def convert_trades_to_ohlcv(pairs: List[str], timeframes: List[str],
|
||||||
|
datadir: Path, timerange: TimeRange, erase=False) -> None:
|
||||||
|
"""
|
||||||
|
Convert stored trades data to ohlcv data
|
||||||
|
"""
|
||||||
|
for pair in pairs:
|
||||||
|
trades = load_trades_file(datadir, pair)
|
||||||
|
for timeframe in timeframes:
|
||||||
|
ohlcv_file = pair_data_filename(datadir, pair, timeframe)
|
||||||
|
if erase and ohlcv_file.exists():
|
||||||
|
logger.info(f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
||||||
|
ohlcv_file.unlink()
|
||||||
|
ohlcv = trades_to_ohlcv(trades, timeframe)
|
||||||
|
# Store ohlcv
|
||||||
|
store_tickerdata_file(datadir, pair, timeframe, data=ohlcv)
|
||||||
|
|
||||||
|
|
||||||
def get_timeframe(data: Dict[str, DataFrame]) -> Tuple[arrow.Arrow, arrow.Arrow]:
|
def get_timeframe(data: Dict[str, DataFrame]) -> Tuple[arrow.Arrow, arrow.Arrow]:
|
||||||
"""
|
"""
|
||||||
Get the maximum timeframe for the given backtest data
|
Get the maximum timeframe for the given backtest data
|
||||||
@@ -287,7 +463,7 @@ def get_timeframe(data: Dict[str, DataFrame]) -> Tuple[arrow.Arrow, arrow.Arrow]
|
|||||||
|
|
||||||
|
|
||||||
def validate_backtest_data(data: DataFrame, pair: str, min_date: datetime,
|
def validate_backtest_data(data: DataFrame, pair: str, min_date: datetime,
|
||||||
max_date: datetime, ticker_interval_mins: int) -> bool:
|
max_date: datetime, timeframe_mins: int) -> bool:
|
||||||
"""
|
"""
|
||||||
Validates preprocessed backtesting data for missing values and shows warnings about it that.
|
Validates preprocessed backtesting data for missing values and shows warnings about it that.
|
||||||
|
|
||||||
@@ -295,10 +471,10 @@ def validate_backtest_data(data: DataFrame, pair: str, min_date: datetime,
|
|||||||
:param pair: pair used for log output.
|
:param pair: pair used for log output.
|
||||||
:param min_date: start-date of the data
|
:param min_date: start-date of the data
|
||||||
:param max_date: end-date of the data
|
:param max_date: end-date of the data
|
||||||
:param ticker_interval_mins: ticker interval in minutes
|
:param timeframe_mins: ticker Timeframe in minutes
|
||||||
"""
|
"""
|
||||||
# total difference in minutes / interval-minutes
|
# total difference in minutes / timeframe-minutes
|
||||||
expected_frames = int((max_date - min_date).total_seconds() // 60 // ticker_interval_mins)
|
expected_frames = int((max_date - min_date).total_seconds() // 60 // timeframe_mins)
|
||||||
found_missing = False
|
found_missing = False
|
||||||
dflen = len(data)
|
dflen = len(data)
|
||||||
if dflen < expected_frames:
|
if dflen < expected_frames:
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ 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.configuration import Arguments, TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.data import history
|
from freqtrade.data import history
|
||||||
from freqtrade.strategy.interface import SellType
|
from freqtrade.strategy.interface import SellType
|
||||||
|
|
||||||
@@ -28,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
|
||||||
@@ -75,9 +75,11 @@ 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 = config['fee']
|
||||||
|
else:
|
||||||
self.fee = self.exchange.get_fee()
|
self.fee = self.exchange.get_fee()
|
||||||
|
|
||||||
def calculate(self) -> bool:
|
def calculate(self) -> bool:
|
||||||
@@ -93,12 +95,13 @@ 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.strategy.ticker_interval,
|
timeframe=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,
|
||||||
|
startup_candles=self.strategy.startup_candle_count,
|
||||||
)
|
)
|
||||||
|
|
||||||
if not data:
|
if not data:
|
||||||
|
|||||||
@@ -1,10 +1,18 @@
|
|||||||
|
from freqtrade.exchange.common import MAP_EXCHANGE_CHILDCLASS # noqa: F401
|
||||||
from freqtrade.exchange.exchange import Exchange # noqa: F401
|
from freqtrade.exchange.exchange import Exchange # noqa: F401
|
||||||
from freqtrade.exchange.exchange import (is_exchange_bad, # noqa: F401
|
from freqtrade.exchange.exchange import (get_exchange_bad_reason, # noqa: F401
|
||||||
is_exchange_available,
|
is_exchange_bad,
|
||||||
|
is_exchange_known_ccxt,
|
||||||
is_exchange_officially_supported,
|
is_exchange_officially_supported,
|
||||||
|
ccxt_exchanges,
|
||||||
available_exchanges)
|
available_exchanges)
|
||||||
from freqtrade.exchange.exchange import (timeframe_to_seconds, # noqa: F401
|
from freqtrade.exchange.exchange import (timeframe_to_seconds, # noqa: F401
|
||||||
timeframe_to_minutes,
|
timeframe_to_minutes,
|
||||||
timeframe_to_msecs)
|
timeframe_to_msecs,
|
||||||
|
timeframe_to_next_date,
|
||||||
|
timeframe_to_prev_date)
|
||||||
|
from freqtrade.exchange.exchange import (market_is_active, # noqa: F401
|
||||||
|
symbol_is_pair)
|
||||||
from freqtrade.exchange.kraken import Kraken # noqa: F401
|
from freqtrade.exchange.kraken import Kraken # noqa: F401
|
||||||
from freqtrade.exchange.binance import Binance # noqa: F401
|
from freqtrade.exchange.binance import Binance # noqa: F401
|
||||||
|
from freqtrade.exchange.bibox import Bibox # noqa: F401
|
||||||
|
|||||||
22
freqtrade/exchange/bibox.py
Normal file
22
freqtrade/exchange/bibox.py
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
""" Bibox exchange subclass """
|
||||||
|
import logging
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
from freqtrade.exchange import Exchange
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class Bibox(Exchange):
|
||||||
|
"""
|
||||||
|
Bibox exchange class. Contains adjustments needed for Freqtrade to work
|
||||||
|
with this exchange.
|
||||||
|
|
||||||
|
Please note that this exchange is not included in the list of exchanges
|
||||||
|
officially supported by the Freqtrade development team. So some features
|
||||||
|
may still not work as expected.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# fetchCurrencies API point requires authentication for Bibox,
|
||||||
|
# so switch it off for Freqtrade load_markets()
|
||||||
|
_ccxt_config: Dict = {"has": {"fetchCurrencies": False}}
|
||||||
@@ -2,6 +2,10 @@
|
|||||||
import logging
|
import logging
|
||||||
from typing import Dict
|
from typing import Dict
|
||||||
|
|
||||||
|
import ccxt
|
||||||
|
|
||||||
|
from freqtrade import (DependencyException, InvalidOrderException,
|
||||||
|
OperationalException, TemporaryError)
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -12,6 +16,8 @@ class Binance(Exchange):
|
|||||||
_ft_has: Dict = {
|
_ft_has: Dict = {
|
||||||
"stoploss_on_exchange": True,
|
"stoploss_on_exchange": True,
|
||||||
"order_time_in_force": ['gtc', 'fok', 'ioc'],
|
"order_time_in_force": ['gtc', 'fok', 'ioc'],
|
||||||
|
"trades_pagination": "id",
|
||||||
|
"trades_pagination_arg": "fromId",
|
||||||
}
|
}
|
||||||
|
|
||||||
def get_order_book(self, pair: str, limit: int = 100) -> dict:
|
def get_order_book(self, pair: str, limit: int = 100) -> dict:
|
||||||
@@ -25,3 +31,55 @@ class Binance(Exchange):
|
|||||||
limit = min(list(filter(lambda x: limit <= x, limit_range)))
|
limit = min(list(filter(lambda x: limit <= x, limit_range)))
|
||||||
|
|
||||||
return super().get_order_book(pair, limit)
|
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
|
||||||
|
|||||||
124
freqtrade/exchange/common.py
Normal file
124
freqtrade/exchange/common.py
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
import logging
|
||||||
|
|
||||||
|
from freqtrade import DependencyException, TemporaryError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
API_RETRY_COUNT = 4
|
||||||
|
BAD_EXCHANGES = {
|
||||||
|
"bitmex": "Various reasons.",
|
||||||
|
"bitstamp": "Does not provide history. "
|
||||||
|
"Details in https://github.com/freqtrade/freqtrade/issues/1983",
|
||||||
|
"hitbtc": "This API cannot be used with Freqtrade. "
|
||||||
|
"Use `hitbtc2` exchange id to access this exchange.",
|
||||||
|
**dict.fromkeys([
|
||||||
|
'adara',
|
||||||
|
'anxpro',
|
||||||
|
'bigone',
|
||||||
|
'coinbase',
|
||||||
|
'coinexchange',
|
||||||
|
'coinmarketcap',
|
||||||
|
'lykke',
|
||||||
|
'xbtce',
|
||||||
|
], "Does not provide timeframes. ccxt fetchOHLCV: False"),
|
||||||
|
**dict.fromkeys([
|
||||||
|
'bcex',
|
||||||
|
'bit2c',
|
||||||
|
'bitbay',
|
||||||
|
'bitflyer',
|
||||||
|
'bitforex',
|
||||||
|
'bithumb',
|
||||||
|
'bitso',
|
||||||
|
'bitstamp1',
|
||||||
|
'bl3p',
|
||||||
|
'braziliex',
|
||||||
|
'btcbox',
|
||||||
|
'btcchina',
|
||||||
|
'btctradeim',
|
||||||
|
'btctradeua',
|
||||||
|
'bxinth',
|
||||||
|
'chilebit',
|
||||||
|
'coincheck',
|
||||||
|
'coinegg',
|
||||||
|
'coinfalcon',
|
||||||
|
'coinfloor',
|
||||||
|
'coingi',
|
||||||
|
'coinmate',
|
||||||
|
'coinone',
|
||||||
|
'coinspot',
|
||||||
|
'coolcoin',
|
||||||
|
'crypton',
|
||||||
|
'deribit',
|
||||||
|
'exmo',
|
||||||
|
'exx',
|
||||||
|
'flowbtc',
|
||||||
|
'foxbit',
|
||||||
|
'fybse',
|
||||||
|
# 'hitbtc',
|
||||||
|
'ice3x',
|
||||||
|
'independentreserve',
|
||||||
|
'indodax',
|
||||||
|
'itbit',
|
||||||
|
'lakebtc',
|
||||||
|
'latoken',
|
||||||
|
'liquid',
|
||||||
|
'livecoin',
|
||||||
|
'luno',
|
||||||
|
'mixcoins',
|
||||||
|
'negociecoins',
|
||||||
|
'nova',
|
||||||
|
'paymium',
|
||||||
|
'southxchange',
|
||||||
|
'stronghold',
|
||||||
|
'surbitcoin',
|
||||||
|
'therock',
|
||||||
|
'tidex',
|
||||||
|
'vaultoro',
|
||||||
|
'vbtc',
|
||||||
|
'virwox',
|
||||||
|
'yobit',
|
||||||
|
'zaif',
|
||||||
|
], "Does not provide timeframes. ccxt fetchOHLCV: emulated"),
|
||||||
|
}
|
||||||
|
|
||||||
|
MAP_EXCHANGE_CHILDCLASS = {
|
||||||
|
'binanceus': 'binance',
|
||||||
|
'binanceje': 'binance',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def retrier_async(f):
|
||||||
|
async def wrapper(*args, **kwargs):
|
||||||
|
count = kwargs.pop('count', API_RETRY_COUNT)
|
||||||
|
try:
|
||||||
|
return await f(*args, **kwargs)
|
||||||
|
except (TemporaryError, DependencyException) as ex:
|
||||||
|
logger.warning('%s() returned exception: "%s"', f.__name__, ex)
|
||||||
|
if count > 0:
|
||||||
|
count -= 1
|
||||||
|
kwargs.update({'count': count})
|
||||||
|
logger.warning('retrying %s() still for %s times', f.__name__, count)
|
||||||
|
return await wrapper(*args, **kwargs)
|
||||||
|
else:
|
||||||
|
logger.warning('Giving up retrying: %s()', f.__name__)
|
||||||
|
raise ex
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
def retrier(f):
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
count = kwargs.pop('count', API_RETRY_COUNT)
|
||||||
|
try:
|
||||||
|
return f(*args, **kwargs)
|
||||||
|
except (TemporaryError, DependencyException) as ex:
|
||||||
|
logger.warning('%s() returned exception: "%s"', f.__name__, ex)
|
||||||
|
if count > 0:
|
||||||
|
count -= 1
|
||||||
|
kwargs.update({'count': count})
|
||||||
|
logger.warning('retrying %s() still for %s times', f.__name__, count)
|
||||||
|
return wrapper(*args, **kwargs)
|
||||||
|
else:
|
||||||
|
logger.warning('Giving up retrying: %s()', f.__name__)
|
||||||
|
raise ex
|
||||||
|
return wrapper
|
||||||
@@ -6,7 +6,7 @@ import asyncio
|
|||||||
import inspect
|
import inspect
|
||||||
import logging
|
import logging
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
from math import ceil, floor
|
from math import ceil, floor
|
||||||
from random import randint
|
from random import randint
|
||||||
from typing import Any, Dict, List, Optional, Tuple
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
@@ -14,58 +14,26 @@ from typing import Any, Dict, List, Optional, Tuple
|
|||||||
import arrow
|
import arrow
|
||||||
import ccxt
|
import ccxt
|
||||||
import ccxt.async_support as ccxt_async
|
import ccxt.async_support as ccxt_async
|
||||||
|
from ccxt.base.decimal_to_precision import ROUND_DOWN, ROUND_UP
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
from freqtrade import (DependencyException, InvalidOrderException,
|
from freqtrade import (DependencyException, InvalidOrderException,
|
||||||
OperationalException, TemporaryError, constants)
|
OperationalException, TemporaryError, constants)
|
||||||
from freqtrade.data.converter import parse_ticker_dataframe
|
from freqtrade.data.converter import parse_ticker_dataframe
|
||||||
|
from freqtrade.exchange.common import BAD_EXCHANGES, retrier, retrier_async
|
||||||
from freqtrade.misc import deep_merge_dicts
|
from freqtrade.misc import deep_merge_dicts
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
API_RETRY_COUNT = 4
|
class Exchange:
|
||||||
|
|
||||||
|
|
||||||
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):
|
|
||||||
|
|
||||||
_config: Dict = {}
|
_config: Dict = {}
|
||||||
|
|
||||||
|
# Parameters to add directly to ccxt sync/async initialization.
|
||||||
|
_ccxt_config: Dict = {}
|
||||||
|
|
||||||
|
# Parameters to add directly to buy/sell calls (like agreeing to trading agreement)
|
||||||
_params: Dict = {}
|
_params: Dict = {}
|
||||||
|
|
||||||
# Dict to specify which options each exchange implements
|
# Dict to specify which options each exchange implements
|
||||||
@@ -76,10 +44,13 @@ class Exchange(object):
|
|||||||
"order_time_in_force": ["gtc"],
|
"order_time_in_force": ["gtc"],
|
||||||
"ohlcv_candle_limit": 500,
|
"ohlcv_candle_limit": 500,
|
||||||
"ohlcv_partial_candle": True,
|
"ohlcv_partial_candle": True,
|
||||||
|
"trades_pagination": "time", # Possible are "time" or "id"
|
||||||
|
"trades_pagination_arg": "since",
|
||||||
|
|
||||||
}
|
}
|
||||||
_ft_has: Dict = {}
|
_ft_has: Dict = {}
|
||||||
|
|
||||||
def __init__(self, config: dict) -> None:
|
def __init__(self, config: dict, validate: bool = True) -> None:
|
||||||
"""
|
"""
|
||||||
Initializes this module with the given config,
|
Initializes this module with the given config,
|
||||||
it does basic validation whether the specified exchange and pairs are valid.
|
it does basic validation whether the specified exchange and pairs are valid.
|
||||||
@@ -119,17 +90,28 @@ class Exchange(object):
|
|||||||
self._ohlcv_candle_limit = self._ft_has['ohlcv_candle_limit']
|
self._ohlcv_candle_limit = self._ft_has['ohlcv_candle_limit']
|
||||||
self._ohlcv_partial_candle = self._ft_has['ohlcv_partial_candle']
|
self._ohlcv_partial_candle = self._ft_has['ohlcv_partial_candle']
|
||||||
|
|
||||||
|
self._trades_pagination = self._ft_has['trades_pagination']
|
||||||
|
self._trades_pagination_arg = self._ft_has['trades_pagination_arg']
|
||||||
|
|
||||||
# Initialize ccxt objects
|
# Initialize ccxt objects
|
||||||
|
ccxt_config = self._ccxt_config.copy()
|
||||||
|
ccxt_config = deep_merge_dicts(exchange_config.get('ccxt_config', {}),
|
||||||
|
ccxt_config)
|
||||||
self._api = self._init_ccxt(
|
self._api = self._init_ccxt(
|
||||||
exchange_config, ccxt_kwargs=exchange_config.get('ccxt_config'))
|
exchange_config, ccxt_kwargs=ccxt_config)
|
||||||
|
|
||||||
|
ccxt_async_config = self._ccxt_config.copy()
|
||||||
|
ccxt_async_config = deep_merge_dicts(exchange_config.get('ccxt_async_config', {}),
|
||||||
|
ccxt_async_config)
|
||||||
self._api_async = self._init_ccxt(
|
self._api_async = self._init_ccxt(
|
||||||
exchange_config, ccxt_async, ccxt_kwargs=exchange_config.get('ccxt_async_config'))
|
exchange_config, ccxt_async, ccxt_kwargs=ccxt_async_config)
|
||||||
|
|
||||||
logger.info('Using Exchange "%s"', self.name)
|
logger.info('Using Exchange "%s"', self.name)
|
||||||
|
|
||||||
# Converts the interval provided in minutes in config to seconds
|
if validate:
|
||||||
self.markets_refresh_interval: int = exchange_config.get(
|
# Check if timeframe is available
|
||||||
"markets_refresh_interval", 60) * 60
|
self.validate_timeframes(config.get('ticker_interval'))
|
||||||
|
|
||||||
# Initial markets load
|
# Initial markets load
|
||||||
self._load_markets()
|
self._load_markets()
|
||||||
|
|
||||||
@@ -137,10 +119,11 @@ class Exchange(object):
|
|||||||
self.validate_pairs(config['exchange']['pair_whitelist'])
|
self.validate_pairs(config['exchange']['pair_whitelist'])
|
||||||
self.validate_ordertypes(config.get('order_types', {}))
|
self.validate_ordertypes(config.get('order_types', {}))
|
||||||
self.validate_order_time_in_force(config.get('order_time_in_force', {}))
|
self.validate_order_time_in_force(config.get('order_time_in_force', {}))
|
||||||
|
self.validate_required_startup_candles(config.get('startup_candle_count', 0))
|
||||||
|
|
||||||
if config.get('ticker_interval'):
|
# Converts the interval provided in minutes in config to seconds
|
||||||
# Check if timeframe is available
|
self.markets_refresh_interval: int = exchange_config.get(
|
||||||
self.validate_timeframes(config['ticker_interval'])
|
"markets_refresh_interval", 60) * 60
|
||||||
|
|
||||||
def __del__(self):
|
def __del__(self):
|
||||||
"""
|
"""
|
||||||
@@ -159,7 +142,7 @@ class Exchange(object):
|
|||||||
# Find matching class for the given exchange name
|
# Find matching class for the given exchange name
|
||||||
name = exchange_config['name']
|
name = exchange_config['name']
|
||||||
|
|
||||||
if not is_exchange_available(name, ccxt_module):
|
if not is_exchange_known_ccxt(name, ccxt_module):
|
||||||
raise OperationalException(f'Exchange {name} is not supported by ccxt')
|
raise OperationalException(f'Exchange {name} is not supported by ccxt')
|
||||||
|
|
||||||
ex_config = {
|
ex_config = {
|
||||||
@@ -193,6 +176,10 @@ class Exchange(object):
|
|||||||
"""exchange ccxt id"""
|
"""exchange ccxt id"""
|
||||||
return self._api.id
|
return self._api.id
|
||||||
|
|
||||||
|
@property
|
||||||
|
def timeframes(self) -> List[str]:
|
||||||
|
return list((self._api.timeframes or {}).keys())
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def markets(self) -> Dict:
|
def markets(self) -> Dict:
|
||||||
"""exchange ccxt markets"""
|
"""exchange ccxt markets"""
|
||||||
@@ -201,6 +188,28 @@ class Exchange(object):
|
|||||||
self._load_markets()
|
self._load_markets()
|
||||||
return self._api.markets
|
return self._api.markets
|
||||||
|
|
||||||
|
def get_markets(self, base_currencies: List[str] = None, quote_currencies: List[str] = None,
|
||||||
|
pairs_only: bool = False, active_only: bool = False) -> Dict:
|
||||||
|
"""
|
||||||
|
Return exchange ccxt markets, filtered out by base currency and quote currency
|
||||||
|
if this was requested in parameters.
|
||||||
|
|
||||||
|
TODO: consider moving it to the Dataprovider
|
||||||
|
"""
|
||||||
|
markets = self.markets
|
||||||
|
if not markets:
|
||||||
|
raise OperationalException("Markets were not loaded.")
|
||||||
|
|
||||||
|
if base_currencies:
|
||||||
|
markets = {k: v for k, v in markets.items() if v['base'] in base_currencies}
|
||||||
|
if quote_currencies:
|
||||||
|
markets = {k: v for k, v in markets.items() if v['quote'] in quote_currencies}
|
||||||
|
if pairs_only:
|
||||||
|
markets = {k: v for k, v in markets.items() if symbol_is_pair(v['symbol'])}
|
||||||
|
if active_only:
|
||||||
|
markets = {k: v for k, v in markets.items() if market_is_active(v)}
|
||||||
|
return markets
|
||||||
|
|
||||||
def klines(self, pair_interval: Tuple[str, str], copy=True) -> DataFrame:
|
def klines(self, pair_interval: Tuple[str, str], copy=True) -> DataFrame:
|
||||||
if pair_interval in self._klines:
|
if pair_interval in self._klines:
|
||||||
return self._klines[pair_interval].copy() if copy else self._klines[pair_interval]
|
return self._klines[pair_interval].copy() if copy else self._klines[pair_interval]
|
||||||
@@ -260,7 +269,7 @@ class Exchange(object):
|
|||||||
|
|
||||||
if not self.markets:
|
if not self.markets:
|
||||||
logger.warning('Unable to validate pairs (assuming they are correct).')
|
logger.warning('Unable to validate pairs (assuming they are correct).')
|
||||||
# return
|
return
|
||||||
|
|
||||||
for pair in pairs:
|
for pair in pairs:
|
||||||
# Note: ccxt has BaseCurrency/QuoteCurrency format for pairs
|
# Note: ccxt has BaseCurrency/QuoteCurrency format for pairs
|
||||||
@@ -269,6 +278,12 @@ class Exchange(object):
|
|||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f'Pair {pair} is not available on {self.name}. '
|
f'Pair {pair} is not available on {self.name}. '
|
||||||
f'Please remove {pair} from your whitelist.')
|
f'Please remove {pair} from your whitelist.')
|
||||||
|
elif self.markets[pair].get('info', {}).get('IsRestricted', False):
|
||||||
|
# Warn users about restricted pairs in whitelist.
|
||||||
|
# We cannot determine reliably if Users are affected.
|
||||||
|
logger.warning(f"Pair {pair} is restricted for some users on this exchange."
|
||||||
|
f"Please check if you are impacted by this restriction "
|
||||||
|
f"on the exchange and eventually remove {pair} from your whitelist.")
|
||||||
|
|
||||||
def get_valid_pair_combination(self, curr_1, curr_2) -> str:
|
def get_valid_pair_combination(self, curr_1, curr_2) -> str:
|
||||||
"""
|
"""
|
||||||
@@ -279,7 +294,7 @@ class Exchange(object):
|
|||||||
return pair
|
return pair
|
||||||
raise DependencyException(f"Could not combine {curr_1} and {curr_2} to get a valid pair.")
|
raise DependencyException(f"Could not combine {curr_1} and {curr_2} to get a valid pair.")
|
||||||
|
|
||||||
def validate_timeframes(self, timeframe: List[str]) -> None:
|
def validate_timeframes(self, timeframe: Optional[str]) -> None:
|
||||||
"""
|
"""
|
||||||
Checks if ticker interval from config is a supported timeframe on the exchange
|
Checks if ticker interval from config is a supported timeframe on the exchange
|
||||||
"""
|
"""
|
||||||
@@ -292,10 +307,9 @@ class Exchange(object):
|
|||||||
f"for the exchange \"{self.name}\" and this exchange "
|
f"for the exchange \"{self.name}\" and this exchange "
|
||||||
f"is therefore not supported. ccxt fetchOHLCV: {self.exchange_has('fetchOHLCV')}")
|
f"is therefore not supported. ccxt fetchOHLCV: {self.exchange_has('fetchOHLCV')}")
|
||||||
|
|
||||||
timeframes = self._api.timeframes
|
if timeframe and (timeframe not in self.timeframes):
|
||||||
if timeframe not in timeframes:
|
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f'Invalid ticker {timeframe}, this Exchange supports {timeframes}')
|
f"Invalid ticker interval '{timeframe}'. This exchange supports: {self.timeframes}")
|
||||||
|
|
||||||
def validate_ordertypes(self, order_types: Dict) -> None:
|
def validate_ordertypes(self, order_types: Dict) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -309,7 +323,7 @@ class Exchange(object):
|
|||||||
if (order_types.get("stoploss_on_exchange")
|
if (order_types.get("stoploss_on_exchange")
|
||||||
and not self._ft_has.get("stoploss_on_exchange", False)):
|
and not self._ft_has.get("stoploss_on_exchange", False)):
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
'On exchange stoploss is not supported for %s.' % self.name
|
f'On exchange stoploss is not supported for {self.name}.'
|
||||||
)
|
)
|
||||||
|
|
||||||
def validate_order_time_in_force(self, order_time_in_force: Dict) -> None:
|
def validate_order_time_in_force(self, order_time_in_force: Dict) -> None:
|
||||||
@@ -321,6 +335,16 @@ class Exchange(object):
|
|||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f'Time in force policies are not supported for {self.name} yet.')
|
f'Time in force policies are not supported for {self.name} yet.')
|
||||||
|
|
||||||
|
def validate_required_startup_candles(self, startup_candles) -> None:
|
||||||
|
"""
|
||||||
|
Checks if required startup_candles is more than ohlcv_candle_limit.
|
||||||
|
Requires a grace-period of 5 candles - so a startup-period up to 494 is allowed by default.
|
||||||
|
"""
|
||||||
|
if startup_candles + 5 > self._ft_has['ohlcv_candle_limit']:
|
||||||
|
raise OperationalException(
|
||||||
|
f"This strategy requires {startup_candles} candles to start. "
|
||||||
|
f"{self.name} only provides {self._ft_has['ohlcv_candle_limit']}.")
|
||||||
|
|
||||||
def exchange_has(self, endpoint: str) -> bool:
|
def exchange_has(self, endpoint: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Checks if exchange implements a specific API endpoint.
|
Checks if exchange implements a specific API endpoint.
|
||||||
@@ -355,7 +379,7 @@ class Exchange(object):
|
|||||||
def dry_run_order(self, pair: str, ordertype: str, side: str, amount: float,
|
def dry_run_order(self, pair: str, ordertype: str, side: str, amount: float,
|
||||||
rate: float, params: Dict = {}) -> Dict[str, Any]:
|
rate: float, params: Dict = {}) -> Dict[str, Any]:
|
||||||
order_id = f'dry_run_{side}_{randint(0, 10**6)}'
|
order_id = f'dry_run_{side}_{randint(0, 10**6)}'
|
||||||
dry_order = { # TODO: additional entry should be added for stoploss limit
|
dry_order = {
|
||||||
"id": order_id,
|
"id": order_id,
|
||||||
'pair': pair,
|
'pair': pair,
|
||||||
'price': rate,
|
'price': rate,
|
||||||
@@ -365,11 +389,12 @@ class Exchange(object):
|
|||||||
'side': side,
|
'side': side,
|
||||||
'remaining': amount,
|
'remaining': amount,
|
||||||
'datetime': arrow.utcnow().isoformat(),
|
'datetime': arrow.utcnow().isoformat(),
|
||||||
'status': "open",
|
'status': "closed" if ordertype == "market" else "open",
|
||||||
'fee': None,
|
'fee': None,
|
||||||
"info": {}
|
"info": {}
|
||||||
}
|
}
|
||||||
self._store_dry_order(dry_order)
|
self._store_dry_order(dry_order)
|
||||||
|
# Copy order and close it - so the returned order is open unless it's a market order
|
||||||
return dry_order
|
return dry_order
|
||||||
|
|
||||||
def _store_dry_order(self, dry_order: Dict) -> None:
|
def _store_dry_order(self, dry_order: Dict) -> None:
|
||||||
@@ -380,6 +405,8 @@ class Exchange(object):
|
|||||||
"filled": closed_order["amount"],
|
"filled": closed_order["amount"],
|
||||||
"remaining": 0
|
"remaining": 0
|
||||||
})
|
})
|
||||||
|
if closed_order["type"] in ["stop_loss_limit"]:
|
||||||
|
closed_order["info"].update({"stopPrice": closed_order["price"]})
|
||||||
self._dry_run_open_orders[closed_order["id"]] = closed_order
|
self._dry_run_open_orders[closed_order["id"]] = closed_order
|
||||||
|
|
||||||
def create_order(self, pair: str, ordertype: str, side: str, amount: float,
|
def create_order(self, pair: str, ordertype: str, side: str, amount: float,
|
||||||
@@ -397,12 +424,12 @@ class Exchange(object):
|
|||||||
except ccxt.InsufficientFunds as e:
|
except ccxt.InsufficientFunds as e:
|
||||||
raise DependencyException(
|
raise DependencyException(
|
||||||
f'Insufficient funds to create {ordertype} {side} order on market {pair}.'
|
f'Insufficient funds to create {ordertype} {side} order on market {pair}.'
|
||||||
f'Tried to {side} amount {amount} at rate {rate} (total {rate * amount}).'
|
f'Tried to {side} amount {amount} at rate {rate}.'
|
||||||
f'Message: {e}') from e
|
f'Message: {e}') from e
|
||||||
except ccxt.InvalidOrder as e:
|
except ccxt.InvalidOrder as e:
|
||||||
raise DependencyException(
|
raise DependencyException(
|
||||||
f'Could not create {ordertype} {side} order on market {pair}.'
|
f'Could not create {ordertype} {side} order on market {pair}.'
|
||||||
f'Tried to {side} amount {amount} at rate {rate} (total {rate * amount}).'
|
f'Tried to {side} amount {amount} at rate {rate}.'
|
||||||
f'Message: {e}') from e
|
f'Message: {e}') from e
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||||
raise TemporaryError(
|
raise TemporaryError(
|
||||||
@@ -439,30 +466,14 @@ class Exchange(object):
|
|||||||
def stoploss_limit(self, pair: str, amount: float, stop_price: float, rate: float) -> Dict:
|
def stoploss_limit(self, pair: str, amount: float, stop_price: float, rate: float) -> Dict:
|
||||||
"""
|
"""
|
||||||
creates a stoploss limit order.
|
creates a stoploss limit order.
|
||||||
NOTICE: it is not supported by all exchanges. only binance is tested for now.
|
Since ccxt does not unify stoploss-limit orders yet, this needs to be implemented in each
|
||||||
TODO: implementation maybe needs to be moved to the binance subclass
|
exchange's subclass.
|
||||||
|
The exception below should never raise, since we disallow
|
||||||
|
starting the bot in validate_ordertypes()
|
||||||
|
Note: Changes to this interface need to be applied to all sub-classes too.
|
||||||
"""
|
"""
|
||||||
ordertype = "stop_loss_limit"
|
|
||||||
|
|
||||||
stop_price = self.symbol_price_prec(pair, stop_price)
|
raise OperationalException(f"stoploss_limit is not implemented for {self.name}.")
|
||||||
|
|
||||||
# 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
|
|
||||||
|
|
||||||
params = self._params.copy()
|
|
||||||
params.update({'stopPrice': stop_price})
|
|
||||||
|
|
||||||
order = self.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
|
|
||||||
|
|
||||||
@retrier
|
@retrier
|
||||||
def get_balance(self, currency: str) -> float:
|
def get_balance(self, currency: str) -> float:
|
||||||
@@ -535,35 +546,40 @@ class Exchange(object):
|
|||||||
logger.info("returning cached ticker-data for %s", pair)
|
logger.info("returning cached ticker-data for %s", pair)
|
||||||
return self._cached_ticker[pair]
|
return self._cached_ticker[pair]
|
||||||
|
|
||||||
def get_history(self, pair: str, ticker_interval: str,
|
def get_historic_ohlcv(self, pair: str, timeframe: str,
|
||||||
since_ms: int) -> List:
|
since_ms: int) -> List:
|
||||||
"""
|
"""
|
||||||
Gets candle history using asyncio and returns the list of candles.
|
Gets candle history using asyncio and returns the list of candles.
|
||||||
Handles all async doing.
|
Handles all async doing.
|
||||||
|
Async over one pair, assuming we get `_ohlcv_candle_limit` candles per call.
|
||||||
|
:param pair: Pair to download
|
||||||
|
:param timeframe: Ticker Timeframe to get
|
||||||
|
:param since_ms: Timestamp in milliseconds to get history from
|
||||||
|
:returns List of tickers
|
||||||
"""
|
"""
|
||||||
return asyncio.get_event_loop().run_until_complete(
|
return asyncio.get_event_loop().run_until_complete(
|
||||||
self._async_get_history(pair=pair, ticker_interval=ticker_interval,
|
self._async_get_historic_ohlcv(pair=pair, timeframe=timeframe,
|
||||||
since_ms=since_ms))
|
since_ms=since_ms))
|
||||||
|
|
||||||
async def _async_get_history(self, pair: str,
|
async def _async_get_historic_ohlcv(self, pair: str,
|
||||||
ticker_interval: str,
|
timeframe: str,
|
||||||
since_ms: int) -> List:
|
since_ms: int) -> List:
|
||||||
|
|
||||||
one_call = timeframe_to_msecs(ticker_interval) * self._ohlcv_candle_limit
|
one_call = timeframe_to_msecs(timeframe) * self._ohlcv_candle_limit
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"one_call: %s msecs (%s)",
|
"one_call: %s msecs (%s)",
|
||||||
one_call,
|
one_call,
|
||||||
arrow.utcnow().shift(seconds=one_call // 1000).humanize(only_distance=True)
|
arrow.utcnow().shift(seconds=one_call // 1000).humanize(only_distance=True)
|
||||||
)
|
)
|
||||||
input_coroutines = [self._async_get_candle_history(
|
input_coroutines = [self._async_get_candle_history(
|
||||||
pair, ticker_interval, since) for since in
|
pair, timeframe, since) for since in
|
||||||
range(since_ms, arrow.utcnow().timestamp * 1000, one_call)]
|
range(since_ms, arrow.utcnow().timestamp * 1000, one_call)]
|
||||||
|
|
||||||
tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
|
tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
|
||||||
|
|
||||||
# Combine tickers
|
# Combine tickers
|
||||||
data: List = []
|
data: List = []
|
||||||
for p, ticker_interval, ticker in tickers:
|
for p, timeframe, ticker in tickers:
|
||||||
if p == pair:
|
if p == pair:
|
||||||
data.extend(ticker)
|
data.extend(ticker)
|
||||||
# Sort data again after extending the result - above calls return in "async order"
|
# Sort data again after extending the result - above calls return in "async order"
|
||||||
@@ -573,21 +589,24 @@ class Exchange(object):
|
|||||||
|
|
||||||
def refresh_latest_ohlcv(self, pair_list: List[Tuple[str, str]]) -> List[Tuple[str, List]]:
|
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
|
Refresh in-memory ohlcv asynchronously and set `_klines` with the result
|
||||||
|
Loops asynchronously over pair_list and downloads all pairs async (semi-parallel).
|
||||||
|
:param pair_list: List of 2 element tuples containing pair, interval to refresh
|
||||||
|
:return: Returns a List of ticker-dataframes.
|
||||||
"""
|
"""
|
||||||
logger.debug("Refreshing ohlcv data for %d pairs", len(pair_list))
|
logger.debug("Refreshing ohlcv data for %d pairs", len(pair_list))
|
||||||
|
|
||||||
input_coroutines = []
|
input_coroutines = []
|
||||||
|
|
||||||
# Gather coroutines to run
|
# Gather coroutines to run
|
||||||
for pair, ticker_interval in set(pair_list):
|
for pair, timeframe in set(pair_list):
|
||||||
if (not ((pair, ticker_interval) in self._klines)
|
if (not ((pair, timeframe) in self._klines)
|
||||||
or self._now_is_time_to_refresh(pair, ticker_interval)):
|
or self._now_is_time_to_refresh(pair, timeframe)):
|
||||||
input_coroutines.append(self._async_get_candle_history(pair, ticker_interval))
|
input_coroutines.append(self._async_get_candle_history(pair, timeframe))
|
||||||
else:
|
else:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Using cached ohlcv data for pair %s, interval %s ...",
|
"Using cached ohlcv data for pair %s, timeframe %s ...",
|
||||||
pair, ticker_interval
|
pair, timeframe
|
||||||
)
|
)
|
||||||
|
|
||||||
tickers = asyncio.get_event_loop().run_until_complete(
|
tickers = asyncio.get_event_loop().run_until_complete(
|
||||||
@@ -599,40 +618,40 @@ class Exchange(object):
|
|||||||
logger.warning("Async code raised an exception: %s", res.__class__.__name__)
|
logger.warning("Async code raised an exception: %s", res.__class__.__name__)
|
||||||
continue
|
continue
|
||||||
pair = res[0]
|
pair = res[0]
|
||||||
ticker_interval = res[1]
|
timeframe = res[1]
|
||||||
ticks = res[2]
|
ticks = res[2]
|
||||||
# keeping last candle time as last refreshed time of the pair
|
# keeping last candle time as last refreshed time of the pair
|
||||||
if ticks:
|
if ticks:
|
||||||
self._pairs_last_refresh_time[(pair, ticker_interval)] = ticks[-1][0] // 1000
|
self._pairs_last_refresh_time[(pair, timeframe)] = ticks[-1][0] // 1000
|
||||||
# keeping parsed dataframe in cache
|
# keeping parsed dataframe in cache
|
||||||
self._klines[(pair, ticker_interval)] = parse_ticker_dataframe(
|
self._klines[(pair, timeframe)] = parse_ticker_dataframe(
|
||||||
ticks, ticker_interval, pair=pair, fill_missing=True,
|
ticks, timeframe, pair=pair, fill_missing=True,
|
||||||
drop_incomplete=self._ohlcv_partial_candle)
|
drop_incomplete=self._ohlcv_partial_candle)
|
||||||
return tickers
|
return tickers
|
||||||
|
|
||||||
def _now_is_time_to_refresh(self, pair: str, ticker_interval: str) -> bool:
|
def _now_is_time_to_refresh(self, pair: str, timeframe: str) -> bool:
|
||||||
# Calculating ticker interval in seconds
|
# Calculating ticker interval in seconds
|
||||||
interval_in_sec = timeframe_to_seconds(ticker_interval)
|
interval_in_sec = timeframe_to_seconds(timeframe)
|
||||||
|
|
||||||
return not ((self._pairs_last_refresh_time.get((pair, ticker_interval), 0)
|
return not ((self._pairs_last_refresh_time.get((pair, timeframe), 0)
|
||||||
+ interval_in_sec) >= arrow.utcnow().timestamp)
|
+ interval_in_sec) >= arrow.utcnow().timestamp)
|
||||||
|
|
||||||
@retrier_async
|
@retrier_async
|
||||||
async def _async_get_candle_history(self, pair: str, ticker_interval: str,
|
async def _async_get_candle_history(self, pair: str, timeframe: str,
|
||||||
since_ms: Optional[int] = None) -> Tuple[str, str, List]:
|
since_ms: Optional[int] = None) -> Tuple[str, str, List]:
|
||||||
"""
|
"""
|
||||||
Asyncronously gets candle histories using fetch_ohlcv
|
Asynchronously gets candle histories using fetch_ohlcv
|
||||||
returns tuple: (pair, ticker_interval, ohlcv_list)
|
returns tuple: (pair, timeframe, ohlcv_list)
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# fetch ohlcv asynchronously
|
# fetch ohlcv asynchronously
|
||||||
s = '(' + arrow.get(since_ms // 1000).isoformat() + ') ' if since_ms is not None else ''
|
s = '(' + arrow.get(since_ms // 1000).isoformat() + ') ' if since_ms is not None else ''
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Fetching pair %s, interval %s, since %s %s...",
|
"Fetching pair %s, interval %s, since %s %s...",
|
||||||
pair, ticker_interval, since_ms, s
|
pair, timeframe, since_ms, s
|
||||||
)
|
)
|
||||||
|
|
||||||
data = await self._api_async.fetch_ohlcv(pair, timeframe=ticker_interval,
|
data = await self._api_async.fetch_ohlcv(pair, timeframe=timeframe,
|
||||||
since=since_ms)
|
since=since_ms)
|
||||||
|
|
||||||
# Because some exchange sort Tickers ASC and other DESC.
|
# Because some exchange sort Tickers ASC and other DESC.
|
||||||
@@ -644,9 +663,9 @@ class Exchange(object):
|
|||||||
data = sorted(data, key=lambda x: x[0])
|
data = sorted(data, key=lambda x: x[0])
|
||||||
except IndexError:
|
except IndexError:
|
||||||
logger.exception("Error loading %s. Result was %s.", pair, data)
|
logger.exception("Error loading %s. Result was %s.", pair, data)
|
||||||
return pair, ticker_interval, []
|
return pair, timeframe, []
|
||||||
logger.debug("Done fetching pair %s, interval %s ...", pair, ticker_interval)
|
logger.debug("Done fetching pair %s, interval %s ...", pair, timeframe)
|
||||||
return pair, ticker_interval, data
|
return pair, timeframe, data
|
||||||
|
|
||||||
except ccxt.NotSupported as e:
|
except ccxt.NotSupported as e:
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
@@ -658,6 +677,153 @@ class Exchange(object):
|
|||||||
except ccxt.BaseError as e:
|
except ccxt.BaseError as e:
|
||||||
raise OperationalException(f'Could not fetch ticker data. Msg: {e}') from e
|
raise OperationalException(f'Could not fetch ticker data. Msg: {e}') from e
|
||||||
|
|
||||||
|
@retrier_async
|
||||||
|
async def _async_fetch_trades(self, pair: str,
|
||||||
|
since: Optional[int] = None,
|
||||||
|
params: Optional[dict] = None) -> List[Dict]:
|
||||||
|
"""
|
||||||
|
Asyncronously gets trade history using fetch_trades.
|
||||||
|
Handles exchange errors, does one call to the exchange.
|
||||||
|
:param pair: Pair to fetch trade data for
|
||||||
|
:param since: Since as integer timestamp in milliseconds
|
||||||
|
returns: List of dicts containing trades
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# fetch trades asynchronously
|
||||||
|
if params:
|
||||||
|
logger.debug("Fetching trades for pair %s, params: %s ", pair, params)
|
||||||
|
trades = await self._api_async.fetch_trades(pair, params=params, limit=1000)
|
||||||
|
else:
|
||||||
|
logger.debug(
|
||||||
|
"Fetching trades for pair %s, since %s %s...",
|
||||||
|
pair, since,
|
||||||
|
'(' + arrow.get(since // 1000).isoformat() + ') ' if since is not None else ''
|
||||||
|
)
|
||||||
|
trades = await self._api_async.fetch_trades(pair, since=since, limit=1000)
|
||||||
|
return trades
|
||||||
|
except ccxt.NotSupported as e:
|
||||||
|
raise OperationalException(
|
||||||
|
f'Exchange {self._api.name} does not support fetching historical trade data.'
|
||||||
|
f'Message: {e}') from e
|
||||||
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||||
|
raise TemporaryError(f'Could not load trade history due to {e.__class__.__name__}. '
|
||||||
|
f'Message: {e}') from e
|
||||||
|
except ccxt.BaseError as e:
|
||||||
|
raise OperationalException(f'Could not fetch trade data. Msg: {e}') from e
|
||||||
|
|
||||||
|
async def _async_get_trade_history_id(self, pair: str,
|
||||||
|
until: int,
|
||||||
|
since: Optional[int] = None,
|
||||||
|
from_id: Optional[str] = None) -> Tuple[str, List[Dict]]:
|
||||||
|
"""
|
||||||
|
Asyncronously gets trade history using fetch_trades
|
||||||
|
use this when exchange uses id-based iteration (check `self._trades_pagination`)
|
||||||
|
:param pair: Pair to fetch trade data for
|
||||||
|
:param since: Since as integer timestamp in milliseconds
|
||||||
|
:param until: Until as integer timestamp in milliseconds
|
||||||
|
:param from_id: Download data starting with ID (if id is known). Ignores "since" if set.
|
||||||
|
returns tuple: (pair, trades-list)
|
||||||
|
"""
|
||||||
|
|
||||||
|
trades: List[Dict] = []
|
||||||
|
|
||||||
|
if not from_id:
|
||||||
|
# Fetch first elements using timebased method to get an ID to paginate on
|
||||||
|
# Depending on the Exchange, this can introduce a drift at the start of the interval
|
||||||
|
# of up to an hour.
|
||||||
|
# e.g. Binance returns the "last 1000" candles within a 1h time interval
|
||||||
|
# - so we will miss the first trades.
|
||||||
|
t = await self._async_fetch_trades(pair, since=since)
|
||||||
|
from_id = t[-1]['id']
|
||||||
|
trades.extend(t[:-1])
|
||||||
|
while True:
|
||||||
|
t = await self._async_fetch_trades(pair,
|
||||||
|
params={self._trades_pagination_arg: from_id})
|
||||||
|
if len(t):
|
||||||
|
# Skip last id since its the key for the next call
|
||||||
|
trades.extend(t[:-1])
|
||||||
|
if from_id == t[-1]['id'] or t[-1]['timestamp'] > until:
|
||||||
|
logger.debug(f"Stopping because from_id did not change. "
|
||||||
|
f"Reached {t[-1]['timestamp']} > {until}")
|
||||||
|
# Reached the end of the defined-download period - add last trade as well.
|
||||||
|
trades.extend(t[-1:])
|
||||||
|
break
|
||||||
|
|
||||||
|
from_id = t[-1]['id']
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
return (pair, trades)
|
||||||
|
|
||||||
|
async def _async_get_trade_history_time(self, pair: str, until: int,
|
||||||
|
since: Optional[int] = None) -> Tuple[str, List]:
|
||||||
|
"""
|
||||||
|
Asyncronously gets trade history using fetch_trades,
|
||||||
|
when the exchange uses time-based iteration (check `self._trades_pagination`)
|
||||||
|
:param pair: Pair to fetch trade data for
|
||||||
|
:param since: Since as integer timestamp in milliseconds
|
||||||
|
:param until: Until as integer timestamp in milliseconds
|
||||||
|
returns tuple: (pair, trades-list)
|
||||||
|
"""
|
||||||
|
|
||||||
|
trades: List[Dict] = []
|
||||||
|
while True:
|
||||||
|
t = await self._async_fetch_trades(pair, since=since)
|
||||||
|
if len(t):
|
||||||
|
since = t[-1]['timestamp']
|
||||||
|
trades.extend(t)
|
||||||
|
# Reached the end of the defined-download period
|
||||||
|
if until and t[-1]['timestamp'] > until:
|
||||||
|
logger.debug(
|
||||||
|
f"Stopping because until was reached. {t[-1]['timestamp']} > {until}")
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
return (pair, trades)
|
||||||
|
|
||||||
|
async def _async_get_trade_history(self, pair: str,
|
||||||
|
since: Optional[int] = None,
|
||||||
|
until: Optional[int] = None,
|
||||||
|
from_id: Optional[str] = None) -> Tuple[str, List[Dict]]:
|
||||||
|
"""
|
||||||
|
Async wrapper handling downloading trades using either time or id based methods.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if self._trades_pagination == 'time':
|
||||||
|
return await self._async_get_trade_history_time(
|
||||||
|
pair=pair, since=since,
|
||||||
|
until=until or ccxt.Exchange.milliseconds())
|
||||||
|
elif self._trades_pagination == 'id':
|
||||||
|
return await self._async_get_trade_history_id(
|
||||||
|
pair=pair, since=since,
|
||||||
|
until=until or ccxt.Exchange.milliseconds(), from_id=from_id
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise OperationalException(f"Exchange {self.name} does use neither time, "
|
||||||
|
f"nor id based pagination")
|
||||||
|
|
||||||
|
def get_historic_trades(self, pair: str,
|
||||||
|
since: Optional[int] = None,
|
||||||
|
until: Optional[int] = None,
|
||||||
|
from_id: Optional[str] = None) -> Tuple[str, List]:
|
||||||
|
"""
|
||||||
|
Gets candle history using asyncio and returns the list of candles.
|
||||||
|
Handles all async doing.
|
||||||
|
Async over one pair, assuming we get `_ohlcv_candle_limit` candles per call.
|
||||||
|
:param pair: Pair to download
|
||||||
|
:param since: Timestamp in milliseconds to get history from
|
||||||
|
:param until: Timestamp in milliseconds. Defaults to current timestamp if not defined.
|
||||||
|
:param from_id: Download data starting with ID (if id is known)
|
||||||
|
:returns List of tickers
|
||||||
|
"""
|
||||||
|
if not self.exchange_has("fetchTrades"):
|
||||||
|
raise OperationalException("This exchange does not suport downloading Trades.")
|
||||||
|
|
||||||
|
return asyncio.get_event_loop().run_until_complete(
|
||||||
|
self._async_get_trade_history(pair=pair, since=since,
|
||||||
|
until=until, from_id=from_id))
|
||||||
|
|
||||||
@retrier
|
@retrier
|
||||||
def cancel_order(self, order_id: str, pair: str) -> None:
|
def cancel_order(self, order_id: str, pair: str) -> None:
|
||||||
if self._config['dry_run']:
|
if self._config['dry_run']:
|
||||||
@@ -677,8 +843,13 @@ class Exchange(object):
|
|||||||
@retrier
|
@retrier
|
||||||
def get_order(self, order_id: str, pair: str) -> Dict:
|
def get_order(self, order_id: str, pair: str) -> Dict:
|
||||||
if self._config['dry_run']:
|
if self._config['dry_run']:
|
||||||
|
try:
|
||||||
order = self._dry_run_open_orders[order_id]
|
order = self._dry_run_open_orders[order_id]
|
||||||
return order
|
return order
|
||||||
|
except KeyError as e:
|
||||||
|
# Gracefully handle errors with dry-run orders.
|
||||||
|
raise InvalidOrderException(
|
||||||
|
f'Tried to get an invalid dry-run-order (id: {order_id}). Message: {e}') from e
|
||||||
try:
|
try:
|
||||||
return self._api.fetch_order(order_id, pair)
|
return self._api.fetch_order(order_id, pair)
|
||||||
except ccxt.InvalidOrder as e:
|
except ccxt.InvalidOrder as e:
|
||||||
@@ -713,13 +884,31 @@ class Exchange(object):
|
|||||||
|
|
||||||
@retrier
|
@retrier
|
||||||
def get_trades_for_order(self, order_id: str, pair: str, since: datetime) -> List:
|
def get_trades_for_order(self, order_id: str, pair: str, since: datetime) -> List:
|
||||||
|
"""
|
||||||
|
Fetch Orders using the "fetch_my_trades" endpoint and filter them by order-id.
|
||||||
|
The "since" argument passed in is coming from the database and is in UTC,
|
||||||
|
as timezone-native datetime object.
|
||||||
|
From the python documentation:
|
||||||
|
> Naive datetime instances are assumed to represent local time
|
||||||
|
Therefore, calling "since.timestamp()" will get the UTC timestamp, after applying the
|
||||||
|
transformation from local timezone to UTC.
|
||||||
|
This works for timezones UTC+ since then the result will contain trades from a few hours
|
||||||
|
instead of from the last 5 seconds, however fails for UTC- timezones,
|
||||||
|
since we're then asking for trades with a "since" argument in the future.
|
||||||
|
|
||||||
|
:param order_id order_id: Order-id as given when creating the order
|
||||||
|
:param pair: Pair the order is for
|
||||||
|
:param since: datetime object of the order creation time. Assumes object is in UTC.
|
||||||
|
"""
|
||||||
if self._config['dry_run']:
|
if self._config['dry_run']:
|
||||||
return []
|
return []
|
||||||
if not self.exchange_has('fetchMyTrades'):
|
if not self.exchange_has('fetchMyTrades'):
|
||||||
return []
|
return []
|
||||||
try:
|
try:
|
||||||
# Allow 5s offset to catch slight time offsets (discovered in #1185)
|
# Allow 5s offset to catch slight time offsets (discovered in #1185)
|
||||||
my_trades = self._api.fetch_my_trades(pair, since.timestamp() - 5)
|
# since needs to be int in milliseconds
|
||||||
|
my_trades = self._api.fetch_my_trades(
|
||||||
|
pair, int((since.replace(tzinfo=timezone.utc).timestamp() - 5) * 1000))
|
||||||
matched_trades = [trade for trade in my_trades if trade['order'] == order_id]
|
matched_trades = [trade for trade in my_trades if trade['order'] == order_id]
|
||||||
|
|
||||||
return matched_trades
|
return matched_trades
|
||||||
@@ -747,40 +936,108 @@ class Exchange(object):
|
|||||||
raise OperationalException(e) from e
|
raise OperationalException(e) from e
|
||||||
|
|
||||||
|
|
||||||
def is_exchange_bad(exchange: str) -> bool:
|
def is_exchange_bad(exchange_name: str) -> bool:
|
||||||
return exchange in ['bitmex', 'bitstamp']
|
return exchange_name in BAD_EXCHANGES
|
||||||
|
|
||||||
|
|
||||||
def is_exchange_available(exchange: str, ccxt_module=None) -> bool:
|
def get_exchange_bad_reason(exchange_name: str) -> str:
|
||||||
return exchange in available_exchanges(ccxt_module)
|
return BAD_EXCHANGES.get(exchange_name, "")
|
||||||
|
|
||||||
|
|
||||||
def is_exchange_officially_supported(exchange: str) -> bool:
|
def is_exchange_known_ccxt(exchange_name: str, ccxt_module=None) -> bool:
|
||||||
return exchange in ['bittrex', 'binance']
|
return exchange_name in ccxt_exchanges(ccxt_module)
|
||||||
|
|
||||||
|
|
||||||
def available_exchanges(ccxt_module=None) -> List[str]:
|
def is_exchange_officially_supported(exchange_name: str) -> bool:
|
||||||
|
return exchange_name in ['bittrex', 'binance']
|
||||||
|
|
||||||
|
|
||||||
|
def ccxt_exchanges(ccxt_module=None) -> List[str]:
|
||||||
|
"""
|
||||||
|
Return the list of all exchanges known to ccxt
|
||||||
|
"""
|
||||||
return ccxt_module.exchanges if ccxt_module is not None else ccxt.exchanges
|
return ccxt_module.exchanges if ccxt_module is not None else ccxt.exchanges
|
||||||
|
|
||||||
|
|
||||||
def timeframe_to_seconds(ticker_interval: str) -> int:
|
def available_exchanges(ccxt_module=None) -> List[str]:
|
||||||
|
"""
|
||||||
|
Return exchanges available to the bot, i.e. non-bad exchanges in the ccxt list
|
||||||
|
"""
|
||||||
|
exchanges = ccxt_exchanges(ccxt_module)
|
||||||
|
return [x for x in exchanges if not is_exchange_bad(x)]
|
||||||
|
|
||||||
|
|
||||||
|
def timeframe_to_seconds(timeframe: str) -> int:
|
||||||
"""
|
"""
|
||||||
Translates the timeframe interval value written in the human readable
|
Translates the timeframe interval value written in the human readable
|
||||||
form ('1m', '5m', '1h', '1d', '1w', etc.) to the number
|
form ('1m', '5m', '1h', '1d', '1w', etc.) to the number
|
||||||
of seconds for one timeframe interval.
|
of seconds for one timeframe interval.
|
||||||
"""
|
"""
|
||||||
return ccxt.Exchange.parse_timeframe(ticker_interval)
|
return ccxt.Exchange.parse_timeframe(timeframe)
|
||||||
|
|
||||||
|
|
||||||
def timeframe_to_minutes(ticker_interval: str) -> int:
|
def timeframe_to_minutes(timeframe: str) -> int:
|
||||||
"""
|
"""
|
||||||
Same as above, but returns minutes.
|
Same as timeframe_to_seconds, but returns minutes.
|
||||||
"""
|
"""
|
||||||
return ccxt.Exchange.parse_timeframe(ticker_interval) // 60
|
return ccxt.Exchange.parse_timeframe(timeframe) // 60
|
||||||
|
|
||||||
|
|
||||||
def timeframe_to_msecs(ticker_interval: str) -> int:
|
def timeframe_to_msecs(timeframe: str) -> int:
|
||||||
"""
|
"""
|
||||||
Same as above, but returns milliseconds.
|
Same as timeframe_to_seconds, but returns milliseconds.
|
||||||
"""
|
"""
|
||||||
return ccxt.Exchange.parse_timeframe(ticker_interval) * 1000
|
return ccxt.Exchange.parse_timeframe(timeframe) * 1000
|
||||||
|
|
||||||
|
|
||||||
|
def timeframe_to_prev_date(timeframe: str, date: datetime = None) -> datetime:
|
||||||
|
"""
|
||||||
|
Use Timeframe and determine last possible candle.
|
||||||
|
:param timeframe: timeframe in string format (e.g. "5m")
|
||||||
|
:param date: date to use. Defaults to utcnow()
|
||||||
|
:returns: date of previous candle (with utc timezone)
|
||||||
|
"""
|
||||||
|
if not date:
|
||||||
|
date = datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
new_timestamp = ccxt.Exchange.round_timeframe(timeframe, date.timestamp() * 1000,
|
||||||
|
ROUND_DOWN) // 1000
|
||||||
|
return datetime.fromtimestamp(new_timestamp, tz=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def timeframe_to_next_date(timeframe: str, date: datetime = None) -> datetime:
|
||||||
|
"""
|
||||||
|
Use Timeframe and determine next candle.
|
||||||
|
:param timeframe: timeframe in string format (e.g. "5m")
|
||||||
|
:param date: date to use. Defaults to utcnow()
|
||||||
|
:returns: date of next candle (with utc timezone)
|
||||||
|
"""
|
||||||
|
if not date:
|
||||||
|
date = datetime.now(timezone.utc)
|
||||||
|
new_timestamp = ccxt.Exchange.round_timeframe(timeframe, date.timestamp() * 1000,
|
||||||
|
ROUND_UP) // 1000
|
||||||
|
return datetime.fromtimestamp(new_timestamp, tz=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def symbol_is_pair(market_symbol: str, base_currency: str = None, quote_currency: str = None):
|
||||||
|
"""
|
||||||
|
Check if the market symbol is a pair, i.e. that its symbol consists of the base currency and the
|
||||||
|
quote currency separated by '/' character. If base_currency and/or quote_currency is passed,
|
||||||
|
it also checks that the symbol contains appropriate base and/or quote currency part before
|
||||||
|
and after the separating character correspondingly.
|
||||||
|
"""
|
||||||
|
symbol_parts = market_symbol.split('/')
|
||||||
|
return (len(symbol_parts) == 2 and
|
||||||
|
(symbol_parts[0] == base_currency if base_currency else len(symbol_parts[0]) > 0) and
|
||||||
|
(symbol_parts[1] == quote_currency if quote_currency else len(symbol_parts[1]) > 0))
|
||||||
|
|
||||||
|
|
||||||
|
def market_is_active(market):
|
||||||
|
"""
|
||||||
|
Return True if the market is active.
|
||||||
|
"""
|
||||||
|
# "It's active, if the active flag isn't explicitly set to false. If it's missing or
|
||||||
|
# true then it's true. If it's undefined, then it's most likely true, but not 100% )"
|
||||||
|
# See https://github.com/ccxt/ccxt/issues/4874,
|
||||||
|
# https://github.com/ccxt/ccxt/issues/4075#issuecomment-434760520
|
||||||
|
return market.get('active', True) is not False
|
||||||
|
|||||||
@@ -2,7 +2,11 @@
|
|||||||
import logging
|
import logging
|
||||||
from typing import Dict
|
from typing import Dict
|
||||||
|
|
||||||
|
import ccxt
|
||||||
|
|
||||||
|
from freqtrade import OperationalException, TemporaryError
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
|
from freqtrade.exchange.exchange import retrier
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -10,3 +14,37 @@ logger = logging.getLogger(__name__)
|
|||||||
class Kraken(Exchange):
|
class Kraken(Exchange):
|
||||||
|
|
||||||
_params: Dict = {"trading_agreement": "agree"}
|
_params: Dict = {"trading_agreement": "agree"}
|
||||||
|
_ft_has: Dict = {
|
||||||
|
"trades_pagination": "id",
|
||||||
|
"trades_pagination_arg": "since",
|
||||||
|
}
|
||||||
|
|
||||||
|
@retrier
|
||||||
|
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
|
||||||
|
|||||||
@@ -1,34 +1,36 @@
|
|||||||
"""
|
"""
|
||||||
Freqtrade is the main module of this bot. It contains the class Freqtrade()
|
Freqtrade is the main module of this bot. It contains the class Freqtrade()
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import copy
|
import copy
|
||||||
import logging
|
import logging
|
||||||
import traceback
|
import traceback
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from math import isclose
|
||||||
|
from os import getpid
|
||||||
from typing import Any, Dict, List, Optional, Tuple
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
import arrow
|
import arrow
|
||||||
from requests.exceptions import RequestException
|
from requests.exceptions import RequestException
|
||||||
|
|
||||||
from freqtrade import (DependencyException, OperationalException, InvalidOrderException,
|
from freqtrade import (DependencyException, InvalidOrderException, __version__,
|
||||||
__version__, constants, persistence)
|
constants, persistence)
|
||||||
|
from freqtrade.configuration import validate_config_consistency
|
||||||
from freqtrade.data.converter import order_book_to_dataframe
|
from freqtrade.data.converter import order_book_to_dataframe
|
||||||
from freqtrade.data.dataprovider import DataProvider
|
from freqtrade.data.dataprovider import DataProvider
|
||||||
from freqtrade.edge import Edge
|
from freqtrade.edge import Edge
|
||||||
from freqtrade.exchange import timeframe_to_minutes
|
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_next_date
|
||||||
from freqtrade.persistence import Trade
|
from freqtrade.persistence import Trade
|
||||||
|
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||||
from freqtrade.rpc import RPCManager, RPCMessageType
|
from freqtrade.rpc import RPCManager, RPCMessageType
|
||||||
from freqtrade.resolvers import ExchangeResolver, StrategyResolver, PairListResolver
|
from freqtrade.pairlist.pairlistmanager import PairListManager
|
||||||
from freqtrade.state import State
|
from freqtrade.state import State
|
||||||
from freqtrade.strategy.interface import SellType, IStrategy
|
from freqtrade.strategy.interface import IStrategy, SellType
|
||||||
from freqtrade.wallets import Wallets
|
from freqtrade.wallets import Wallets
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class FreqtradeBot(object):
|
class FreqtradeBot:
|
||||||
"""
|
"""
|
||||||
Freqtrade is the main class of the bot.
|
Freqtrade is the main class of the bot.
|
||||||
This is from here the bot start its logic.
|
This is from here the bot start its logic.
|
||||||
@@ -49,9 +51,14 @@ class FreqtradeBot(object):
|
|||||||
# Init objects
|
# Init objects
|
||||||
self.config = config
|
self.config = config
|
||||||
|
|
||||||
|
self._heartbeat_msg = 0
|
||||||
|
|
||||||
|
self.heartbeat_interval = self.config.get('internals', {}).get('heartbeat_interval', 60)
|
||||||
|
|
||||||
self.strategy: IStrategy = StrategyResolver(self.config).strategy
|
self.strategy: IStrategy = StrategyResolver(self.config).strategy
|
||||||
|
|
||||||
self.rpc: RPCManager = RPCManager(self)
|
# Check config consistency here since strategies can set certain options
|
||||||
|
validate_config_consistency(config)
|
||||||
|
|
||||||
self.exchange = ExchangeResolver(self.config['exchange']['name'], self.config).exchange
|
self.exchange = ExchangeResolver(self.config['exchange']['name'], self.config).exchange
|
||||||
|
|
||||||
@@ -63,14 +70,13 @@ class FreqtradeBot(object):
|
|||||||
# Attach Wallets to Strategy baseclass
|
# Attach Wallets to Strategy baseclass
|
||||||
IStrategy.wallets = self.wallets
|
IStrategy.wallets = self.wallets
|
||||||
|
|
||||||
pairlistname = self.config.get('pairlist', {}).get('method', 'StaticPairList')
|
self.pairlists = PairListManager(self.exchange, self.config)
|
||||||
self.pairlists = PairListResolver(pairlistname, self, self.config).pairlist
|
|
||||||
|
|
||||||
# Initializing Edge only if enabled
|
# Initializing Edge only if enabled
|
||||||
self.edge = Edge(self.config, self.exchange, self.strategy) if \
|
self.edge = Edge(self.config, self.exchange, self.strategy) if \
|
||||||
self.config.get('edge', {}).get('enabled', False) else None
|
self.config.get('edge', {}).get('enabled', False) else None
|
||||||
|
|
||||||
self.active_pair_whitelist: List[str] = self.config['exchange']['pair_whitelist']
|
self.active_pair_whitelist = self._refresh_whitelist()
|
||||||
|
|
||||||
persistence.init(self.config.get('db_url', None),
|
persistence.init(self.config.get('db_url', None),
|
||||||
clean_open_orders=self.config.get('dry_run', False))
|
clean_open_orders=self.config.get('dry_run', False))
|
||||||
@@ -79,6 +85,13 @@ class FreqtradeBot(object):
|
|||||||
initial_state = self.config.get('initial_state')
|
initial_state = self.config.get('initial_state')
|
||||||
self.state = State[initial_state.upper()] if initial_state else State.STOPPED
|
self.state = State[initial_state.upper()] if initial_state else State.STOPPED
|
||||||
|
|
||||||
|
# RPC runs in separate threads, can start handling external commands just after
|
||||||
|
# initialization, even before Freqtradebot has a chance to start its throttling,
|
||||||
|
# so anything in the Freqtradebot instance should be ready (initialized), including
|
||||||
|
# the initial state of the bot.
|
||||||
|
# Keep this at the end of this initialization method.
|
||||||
|
self.rpc: RPCManager = RPCManager(self)
|
||||||
|
|
||||||
def cleanup(self) -> None:
|
def cleanup(self) -> None:
|
||||||
"""
|
"""
|
||||||
Cleanup pending resources on an already stopped bot
|
Cleanup pending resources on an already stopped bot
|
||||||
@@ -99,57 +112,59 @@ class FreqtradeBot(object):
|
|||||||
# Adjust stoploss if it was changed
|
# Adjust stoploss if it was changed
|
||||||
Trade.stoploss_reinitialization(self.strategy.stoploss)
|
Trade.stoploss_reinitialization(self.strategy.stoploss)
|
||||||
|
|
||||||
def process(self) -> bool:
|
def process(self) -> None:
|
||||||
"""
|
"""
|
||||||
Queries the persistence layer for open trades and handles them,
|
Queries the persistence layer for open trades and handles them,
|
||||||
otherwise a new trade is created.
|
otherwise a new trade is created.
|
||||||
:return: True if one or more trades has been created or closed, False otherwise
|
:return: True if one or more trades has been created or closed, False otherwise
|
||||||
"""
|
"""
|
||||||
state_changed = False
|
|
||||||
|
|
||||||
# Check whether markets have to be reloaded
|
# Check whether markets have to be reloaded
|
||||||
self.exchange._reload_markets()
|
self.exchange._reload_markets()
|
||||||
|
|
||||||
# Refresh whitelist
|
|
||||||
self.pairlists.refresh_pairlist()
|
|
||||||
self.active_pair_whitelist = self.pairlists.whitelist
|
|
||||||
|
|
||||||
# Calculating Edge positioning
|
|
||||||
if self.edge:
|
|
||||||
self.edge.calculate()
|
|
||||||
self.active_pair_whitelist = self.edge.adjust(self.active_pair_whitelist)
|
|
||||||
|
|
||||||
# Query trades from persistence layer
|
# Query trades from persistence layer
|
||||||
trades = Trade.get_open_trades()
|
trades = Trade.get_open_trades()
|
||||||
|
|
||||||
# Extend active-pair whitelist with pairs from open trades
|
self.active_pair_whitelist = self._refresh_whitelist(trades)
|
||||||
# It ensures that tickers are downloaded for open trades
|
|
||||||
self._extend_whitelist_with_trades(self.active_pair_whitelist, trades)
|
|
||||||
|
|
||||||
# Refreshing candles
|
# Refreshing candles
|
||||||
self.dataprovider.refresh(self._create_pair_whitelist(self.active_pair_whitelist),
|
self.dataprovider.refresh(self._create_pair_whitelist(self.active_pair_whitelist),
|
||||||
self.strategy.informative_pairs())
|
self.strategy.informative_pairs())
|
||||||
|
|
||||||
# First process current opened trades
|
# First process current opened trades
|
||||||
for trade in trades:
|
self.process_maybe_execute_sells(trades)
|
||||||
state_changed |= self.process_maybe_execute_sell(trade)
|
|
||||||
|
|
||||||
# Then looking for buy opportunities
|
# Then looking for buy opportunities
|
||||||
if len(trades) < self.config['max_open_trades']:
|
if len(trades) < self.config['max_open_trades']:
|
||||||
state_changed = self.process_maybe_execute_buy()
|
self.process_maybe_execute_buys()
|
||||||
|
|
||||||
if 'unfilledtimeout' in self.config:
|
|
||||||
# Check and handle any timed out open orders
|
# Check and handle any timed out open orders
|
||||||
self.check_handle_timedout()
|
self.check_handle_timedout()
|
||||||
Trade.session.flush()
|
Trade.session.flush()
|
||||||
|
|
||||||
return state_changed
|
if (self.heartbeat_interval
|
||||||
|
and (arrow.utcnow().timestamp - self._heartbeat_msg > self.heartbeat_interval)):
|
||||||
|
logger.info(f"Bot heartbeat. PID={getpid()}")
|
||||||
|
self._heartbeat_msg = arrow.utcnow().timestamp
|
||||||
|
|
||||||
def _extend_whitelist_with_trades(self, whitelist: List[str], trades: List[Any]):
|
def _refresh_whitelist(self, trades: List[Trade] = []) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Extend whitelist with pairs from open trades
|
Refresh whitelist from pairlist or edge and extend it with trades.
|
||||||
"""
|
"""
|
||||||
whitelist.extend([trade.pair for trade in trades if trade.pair not in whitelist])
|
# Refresh whitelist
|
||||||
|
self.pairlists.refresh_pairlist()
|
||||||
|
_whitelist = self.pairlists.whitelist
|
||||||
|
|
||||||
|
# Calculating Edge positioning
|
||||||
|
if self.edge:
|
||||||
|
self.edge.calculate()
|
||||||
|
_whitelist = self.edge.adjust(_whitelist)
|
||||||
|
|
||||||
|
if trades:
|
||||||
|
# Extend active-pair whitelist with pairs from open trades
|
||||||
|
# It ensures that tickers are downloaded for open trades
|
||||||
|
_whitelist.extend([trade.pair for trade in trades if trade.pair not in _whitelist])
|
||||||
|
return _whitelist
|
||||||
|
|
||||||
def _create_pair_whitelist(self, pairs: List[str]) -> List[Tuple[str, str]]:
|
def _create_pair_whitelist(self, pairs: List[str]) -> List[Tuple[str, str]]:
|
||||||
"""
|
"""
|
||||||
@@ -209,7 +224,7 @@ class FreqtradeBot(object):
|
|||||||
if stake_amount == constants.UNLIMITED_STAKE_AMOUNT:
|
if stake_amount == constants.UNLIMITED_STAKE_AMOUNT:
|
||||||
open_trades = len(Trade.get_open_trades())
|
open_trades = len(Trade.get_open_trades())
|
||||||
if open_trades >= self.config['max_open_trades']:
|
if open_trades >= self.config['max_open_trades']:
|
||||||
logger.warning('Can\'t open a new trade: max number of trades is reached')
|
logger.warning("Can't open a new trade: max number of trades is reached")
|
||||||
return None
|
return None
|
||||||
return available_amount / (self.config['max_open_trades'] - open_trades)
|
return available_amount / (self.config['max_open_trades'] - open_trades)
|
||||||
|
|
||||||
@@ -251,19 +266,23 @@ class FreqtradeBot(object):
|
|||||||
amount_reserve_percent += self.strategy.stoploss
|
amount_reserve_percent += self.strategy.stoploss
|
||||||
# it should not be more than 50%
|
# it should not be more than 50%
|
||||||
amount_reserve_percent = max(amount_reserve_percent, 0.5)
|
amount_reserve_percent = max(amount_reserve_percent, 0.5)
|
||||||
return min(min_stake_amounts) / amount_reserve_percent
|
|
||||||
|
|
||||||
def create_trade(self) -> bool:
|
# The value returned should satisfy both limits: for amount (base currency) and
|
||||||
|
# for cost (quote, stake currency), so max() is used here.
|
||||||
|
# See also #2575 at github.
|
||||||
|
return max(min_stake_amounts) / amount_reserve_percent
|
||||||
|
|
||||||
|
def create_trades(self) -> bool:
|
||||||
"""
|
"""
|
||||||
Checks the implemented trading indicator(s) for a randomly picked pair,
|
Checks the implemented trading strategy for buy-signals, using the active pair whitelist.
|
||||||
if one pair triggers the buy_signal a new trade record gets created
|
If a pair triggers the buy_signal a new trade record gets created.
|
||||||
:return: True if a trade object has been created and persisted, False otherwise
|
Checks pairs as long as the open trade count is below `max_open_trades`.
|
||||||
|
:return: True if at least one trade has been created.
|
||||||
"""
|
"""
|
||||||
interval = self.strategy.ticker_interval
|
|
||||||
whitelist = copy.deepcopy(self.active_pair_whitelist)
|
whitelist = copy.deepcopy(self.active_pair_whitelist)
|
||||||
|
|
||||||
if not whitelist:
|
if not whitelist:
|
||||||
logger.warning("Whitelist is empty.")
|
logger.info("Active pair whitelist is empty.")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Remove currently opened and latest pairs from whitelist
|
# Remove currently opened and latest pairs from whitelist
|
||||||
@@ -273,18 +292,25 @@ class FreqtradeBot(object):
|
|||||||
logger.debug('Ignoring %s in pair whitelist', trade.pair)
|
logger.debug('Ignoring %s in pair whitelist', trade.pair)
|
||||||
|
|
||||||
if not whitelist:
|
if not whitelist:
|
||||||
logger.info("No currency pair in whitelist, but checking to sell open trades.")
|
logger.info("No currency pair in active pair whitelist, "
|
||||||
|
"but checking to sell open trades.")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
buycount = 0
|
||||||
# running get_signal on historical data fetched
|
# running get_signal on historical data fetched
|
||||||
for _pair in whitelist:
|
for _pair in whitelist:
|
||||||
(buy, sell) = self.strategy.get_signal(
|
if self.strategy.is_pair_locked(_pair):
|
||||||
_pair, interval, self.dataprovider.ohlcv(_pair, self.strategy.ticker_interval))
|
logger.info(f"Pair {_pair} is currently locked.")
|
||||||
|
continue
|
||||||
|
|
||||||
if buy and not sell:
|
(buy, sell) = self.strategy.get_signal(
|
||||||
|
_pair, self.strategy.ticker_interval,
|
||||||
|
self.dataprovider.ohlcv(_pair, self.strategy.ticker_interval))
|
||||||
|
|
||||||
|
if buy and not sell and len(Trade.get_open_trades()) < self.config['max_open_trades']:
|
||||||
stake_amount = self._get_trade_stake_amount(_pair)
|
stake_amount = self._get_trade_stake_amount(_pair)
|
||||||
if not stake_amount:
|
if not stake_amount:
|
||||||
return False
|
continue
|
||||||
|
|
||||||
logger.info(f"Buy signal found: about create a new trade with stake_amount: "
|
logger.info(f"Buy signal found: about create a new trade with stake_amount: "
|
||||||
f"{stake_amount} ...")
|
f"{stake_amount} ...")
|
||||||
@@ -294,12 +320,12 @@ class FreqtradeBot(object):
|
|||||||
if (bidstrat_check_depth_of_market.get('enabled', False)) and\
|
if (bidstrat_check_depth_of_market.get('enabled', False)) and\
|
||||||
(bidstrat_check_depth_of_market.get('bids_to_ask_delta', 0) > 0):
|
(bidstrat_check_depth_of_market.get('bids_to_ask_delta', 0) > 0):
|
||||||
if self._check_depth_of_market_buy(_pair, bidstrat_check_depth_of_market):
|
if self._check_depth_of_market_buy(_pair, bidstrat_check_depth_of_market):
|
||||||
return self.execute_buy(_pair, stake_amount)
|
buycount += self.execute_buy(_pair, stake_amount)
|
||||||
else:
|
continue
|
||||||
return False
|
|
||||||
return self.execute_buy(_pair, stake_amount)
|
|
||||||
|
|
||||||
return False
|
buycount += self.execute_buy(_pair, stake_amount)
|
||||||
|
|
||||||
|
return buycount > 0
|
||||||
|
|
||||||
def _check_depth_of_market_buy(self, pair: str, conf: Dict) -> bool:
|
def _check_depth_of_market_buy(self, pair: str, conf: Dict) -> bool:
|
||||||
"""
|
"""
|
||||||
@@ -338,8 +364,8 @@ class FreqtradeBot(object):
|
|||||||
min_stake_amount = self._get_min_pair_stake_amount(pair_s, buy_limit_requested)
|
min_stake_amount = self._get_min_pair_stake_amount(pair_s, buy_limit_requested)
|
||||||
if min_stake_amount is not None and min_stake_amount > stake_amount:
|
if min_stake_amount is not None and min_stake_amount > stake_amount:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f'Can\'t open a new trade for {pair_s}: stake amount '
|
f"Can't open a new trade for {pair_s}: stake amount "
|
||||||
f'is too small ({stake_amount} < {min_stake_amount})'
|
f"is too small ({stake_amount} < {min_stake_amount})"
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -423,55 +449,47 @@ class FreqtradeBot(object):
|
|||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def process_maybe_execute_buy(self) -> bool:
|
def process_maybe_execute_buys(self) -> None:
|
||||||
"""
|
"""
|
||||||
Tries to execute a buy trade in a safe way
|
Tries to execute buy orders for trades in a safe way
|
||||||
:return: True if executed
|
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Create entity and execute trade
|
# Create entity and execute trade
|
||||||
if self.create_trade():
|
if not self.create_trades():
|
||||||
return True
|
logger.debug('Found no buy signals for whitelisted currencies. Trying again...')
|
||||||
|
|
||||||
logger.info('Found no buy signals for whitelisted currencies. Trying again..')
|
|
||||||
return False
|
|
||||||
except DependencyException as exception:
|
except DependencyException as exception:
|
||||||
logger.warning('Unable to create trade: %s', exception)
|
logger.warning('Unable to create trade: %s', exception)
|
||||||
return False
|
|
||||||
|
|
||||||
def process_maybe_execute_sell(self, trade: Trade) -> bool:
|
def process_maybe_execute_sells(self, trades: List[Any]) -> None:
|
||||||
"""
|
"""
|
||||||
Tries to execute a sell trade
|
Tries to execute sell orders for trades in a safe way
|
||||||
:return: True if executed
|
|
||||||
"""
|
"""
|
||||||
|
result = False
|
||||||
|
for trade in trades:
|
||||||
try:
|
try:
|
||||||
self.update_trade_state(trade)
|
self.update_trade_state(trade)
|
||||||
|
|
||||||
if self.strategy.order_types.get('stoploss_on_exchange') and trade.is_open:
|
if (self.strategy.order_types.get('stoploss_on_exchange') and
|
||||||
result = self.handle_stoploss_on_exchange(trade)
|
self.handle_stoploss_on_exchange(trade)):
|
||||||
if result:
|
result = True
|
||||||
self.wallets.update()
|
continue
|
||||||
return result
|
|
||||||
|
|
||||||
if trade.is_open and trade.open_order_id is None:
|
|
||||||
# Check if we can sell our current pair
|
# Check if we can sell our current pair
|
||||||
result = self.handle_trade(trade)
|
if trade.open_order_id is None and self.handle_trade(trade):
|
||||||
|
result = True
|
||||||
|
|
||||||
|
except DependencyException as exception:
|
||||||
|
logger.warning('Unable to sell trade: %s', exception)
|
||||||
|
|
||||||
# Updating wallets if any trade occured
|
# Updating wallets if any trade occured
|
||||||
if result:
|
if result:
|
||||||
self.wallets.update()
|
self.wallets.update()
|
||||||
|
|
||||||
return result
|
def get_real_amount(self, trade: Trade, order: Dict, order_amount: float = None) -> float:
|
||||||
|
|
||||||
except DependencyException as exception:
|
|
||||||
logger.warning('Unable to sell trade: %s', exception)
|
|
||||||
return False
|
|
||||||
|
|
||||||
def get_real_amount(self, trade: Trade, order: Dict) -> float:
|
|
||||||
"""
|
"""
|
||||||
Get real amount for the trade
|
Get real amount for the trade
|
||||||
Necessary for exchanges which charge fees in base currency (e.g. binance)
|
Necessary for exchanges which charge fees in base currency (e.g. binance)
|
||||||
"""
|
"""
|
||||||
|
if order_amount is None:
|
||||||
order_amount = order['amount']
|
order_amount = order['amount']
|
||||||
# Only run for closed orders
|
# Only run for closed orders
|
||||||
if trade.fee_open == 0 or order['status'] == 'open':
|
if trade.fee_open == 0 or order['status'] == 'open':
|
||||||
@@ -507,9 +525,9 @@ class FreqtradeBot(object):
|
|||||||
trade.pair.startswith(exectrade['fee']['currency'])):
|
trade.pair.startswith(exectrade['fee']['currency'])):
|
||||||
fee_abs += exectrade['fee']['cost']
|
fee_abs += exectrade['fee']['cost']
|
||||||
|
|
||||||
if amount != order_amount:
|
if not isclose(amount, order_amount, abs_tol=constants.MATH_CLOSE_PREC):
|
||||||
logger.warning(f"Amount {amount} does not match amount {trade.amount}")
|
logger.warning(f"Amount {amount} does not match amount {trade.amount}")
|
||||||
raise OperationalException("Half bought? Amounts don't match")
|
raise DependencyException("Half bought? Amounts don't match")
|
||||||
real_amount = amount - fee_abs
|
real_amount = amount - fee_abs
|
||||||
if fee_abs != 0:
|
if fee_abs != 0:
|
||||||
logger.info(f"Applying fee on amount for {trade} "
|
logger.info(f"Applying fee on amount for {trade} "
|
||||||
@@ -532,12 +550,12 @@ class FreqtradeBot(object):
|
|||||||
# Try update amount (binance-fix)
|
# Try update amount (binance-fix)
|
||||||
try:
|
try:
|
||||||
new_amount = self.get_real_amount(trade, order)
|
new_amount = self.get_real_amount(trade, order)
|
||||||
if order['amount'] != new_amount:
|
if not isclose(order['amount'], new_amount, abs_tol=constants.MATH_CLOSE_PREC):
|
||||||
order['amount'] = new_amount
|
order['amount'] = new_amount
|
||||||
# Fee was applied, so set to 0
|
# Fee was applied, so set to 0
|
||||||
trade.fee_open = 0
|
trade.fee_open = 0
|
||||||
|
|
||||||
except OperationalException as exception:
|
except DependencyException as exception:
|
||||||
logger.warning("Could not update trade amount: %s", exception)
|
logger.warning("Could not update trade amount: %s", exception)
|
||||||
|
|
||||||
trade.update(order)
|
trade.update(order)
|
||||||
@@ -571,18 +589,20 @@ class FreqtradeBot(object):
|
|||||||
:return: True if trade has been sold, False otherwise
|
:return: True if trade has been sold, False otherwise
|
||||||
"""
|
"""
|
||||||
if not trade.is_open:
|
if not trade.is_open:
|
||||||
raise ValueError(f'Attempt to handle closed trade: {trade}')
|
raise DependencyException(f'Attempt to handle closed trade: {trade}')
|
||||||
|
|
||||||
logger.debug('Handling %s ...', trade)
|
logger.debug('Handling %s ...', trade)
|
||||||
|
|
||||||
(buy, sell) = (False, False)
|
(buy, sell) = (False, False)
|
||||||
experimental = self.config.get('experimental', {})
|
|
||||||
if experimental.get('use_sell_signal') or experimental.get('ignore_roi_if_buy_signal'):
|
config_ask_strategy = self.config.get('ask_strategy', {})
|
||||||
|
|
||||||
|
if (config_ask_strategy.get('use_sell_signal', True) or
|
||||||
|
config_ask_strategy.get('ignore_roi_if_buy_signal')):
|
||||||
(buy, sell) = self.strategy.get_signal(
|
(buy, sell) = self.strategy.get_signal(
|
||||||
trade.pair, self.strategy.ticker_interval,
|
trade.pair, self.strategy.ticker_interval,
|
||||||
self.dataprovider.ohlcv(trade.pair, self.strategy.ticker_interval))
|
self.dataprovider.ohlcv(trade.pair, self.strategy.ticker_interval))
|
||||||
|
|
||||||
config_ask_strategy = self.config.get('ask_strategy', {})
|
|
||||||
if config_ask_strategy.get('use_order_book', False):
|
if config_ask_strategy.get('use_order_book', False):
|
||||||
logger.info('Using order book for selling...')
|
logger.info('Using order book for selling...')
|
||||||
# logger.debug('Order book %s',orderBook)
|
# logger.debug('Order book %s',orderBook)
|
||||||
@@ -608,6 +628,33 @@ class FreqtradeBot(object):
|
|||||||
logger.debug('Found no sell signal for %s.', trade)
|
logger.debug('Found no sell signal for %s.', trade)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def create_stoploss_order(self, trade: Trade, stop_price: float, rate: float) -> bool:
|
||||||
|
"""
|
||||||
|
Abstracts creating stoploss orders from the logic.
|
||||||
|
Handles errors and updates the trade database object.
|
||||||
|
Force-sells the pair (using EmergencySell reason) in case of Problems creating the order.
|
||||||
|
:return: True if the order succeeded, and False in case of problems.
|
||||||
|
"""
|
||||||
|
# Limit price threshold: As limit price should always be below stop-price
|
||||||
|
LIMIT_PRICE_PCT = self.strategy.order_types.get('stoploss_on_exchange_limit_ratio', 0.99)
|
||||||
|
|
||||||
|
try:
|
||||||
|
stoploss_order = self.exchange.stoploss_limit(pair=trade.pair, amount=trade.amount,
|
||||||
|
stop_price=stop_price,
|
||||||
|
rate=rate * LIMIT_PRICE_PCT)
|
||||||
|
trade.stoploss_order_id = str(stoploss_order['id'])
|
||||||
|
return True
|
||||||
|
except InvalidOrderException as e:
|
||||||
|
trade.stoploss_order_id = None
|
||||||
|
logger.error(f'Unable to place a stoploss order on exchange. {e}')
|
||||||
|
logger.warning('Selling the trade forcefully')
|
||||||
|
self.execute_sell(trade, trade.stop_loss, sell_reason=SellType.EMERGENCY_SELL)
|
||||||
|
|
||||||
|
except DependencyException:
|
||||||
|
trade.stoploss_order_id = None
|
||||||
|
logger.exception('Unable to place a stoploss order on exchange.')
|
||||||
|
return False
|
||||||
|
|
||||||
def handle_stoploss_on_exchange(self, trade: Trade) -> bool:
|
def handle_stoploss_on_exchange(self, trade: Trade) -> bool:
|
||||||
"""
|
"""
|
||||||
Check if trade is fulfilled in which case the stoploss
|
Check if trade is fulfilled in which case the stoploss
|
||||||
@@ -626,53 +673,34 @@ class FreqtradeBot(object):
|
|||||||
except InvalidOrderException as exception:
|
except InvalidOrderException as exception:
|
||||||
logger.warning('Unable to fetch stoploss order: %s', exception)
|
logger.warning('Unable to fetch stoploss order: %s', exception)
|
||||||
|
|
||||||
# If trade open order id does not exist: buy order is fulfilled
|
|
||||||
buy_order_fulfilled = not trade.open_order_id
|
|
||||||
|
|
||||||
# Limit price threshold: As limit price should always be below price
|
|
||||||
limit_price_pct = 0.99
|
|
||||||
|
|
||||||
# If buy order is fulfilled but there is no stoploss, we add a stoploss on exchange
|
# If buy order is fulfilled but there is no stoploss, we add a stoploss on exchange
|
||||||
if (buy_order_fulfilled and not stoploss_order):
|
if (not trade.open_order_id and not stoploss_order):
|
||||||
if self.edge:
|
|
||||||
stoploss = self.edge.stoploss(pair=trade.pair)
|
stoploss = self.edge.stoploss(pair=trade.pair) if self.edge else self.strategy.stoploss
|
||||||
else:
|
|
||||||
stoploss = self.strategy.stoploss
|
|
||||||
|
|
||||||
stop_price = trade.open_rate * (1 + stoploss)
|
stop_price = trade.open_rate * (1 + stoploss)
|
||||||
|
|
||||||
# limit price should be less than stop price.
|
if self.create_stoploss_order(trade=trade, stop_price=stop_price, rate=stop_price):
|
||||||
limit_price = stop_price * limit_price_pct
|
|
||||||
|
|
||||||
try:
|
|
||||||
stoploss_order_id = self.exchange.stoploss_limit(
|
|
||||||
pair=trade.pair, amount=trade.amount, stop_price=stop_price, rate=limit_price
|
|
||||||
)['id']
|
|
||||||
trade.stoploss_order_id = str(stoploss_order_id)
|
|
||||||
trade.stoploss_last_update = datetime.now()
|
trade.stoploss_last_update = datetime.now()
|
||||||
return False
|
return False
|
||||||
|
|
||||||
except DependencyException as exception:
|
|
||||||
logger.warning('Unable to place a stoploss order on exchange: %s', exception)
|
|
||||||
|
|
||||||
# If stoploss order is canceled for some reason we add it
|
# If stoploss order is canceled for some reason we add it
|
||||||
if stoploss_order and stoploss_order['status'] == 'canceled':
|
if stoploss_order and stoploss_order['status'] == 'canceled':
|
||||||
try:
|
if self.create_stoploss_order(trade=trade, stop_price=trade.stop_loss,
|
||||||
stoploss_order_id = self.exchange.stoploss_limit(
|
rate=trade.stop_loss):
|
||||||
pair=trade.pair, amount=trade.amount,
|
|
||||||
stop_price=trade.stop_loss, rate=trade.stop_loss * limit_price_pct
|
|
||||||
)['id']
|
|
||||||
trade.stoploss_order_id = str(stoploss_order_id)
|
|
||||||
return False
|
return False
|
||||||
except DependencyException as exception:
|
else:
|
||||||
logger.warning('Stoploss order was cancelled, '
|
trade.stoploss_order_id = None
|
||||||
'but unable to recreate one: %s', exception)
|
logger.warning('Stoploss order was cancelled, but unable to recreate one.')
|
||||||
|
|
||||||
# We check if stoploss order is fulfilled
|
# We check if stoploss order is fulfilled
|
||||||
if stoploss_order and stoploss_order['status'] == 'closed':
|
if stoploss_order and stoploss_order['status'] == 'closed':
|
||||||
trade.sell_reason = SellType.STOPLOSS_ON_EXCHANGE.value
|
trade.sell_reason = SellType.STOPLOSS_ON_EXCHANGE.value
|
||||||
trade.update(stoploss_order)
|
trade.update(stoploss_order)
|
||||||
self._notify_sell(trade)
|
# Lock pair for one candle to prevent immediate rebuys
|
||||||
|
self.strategy.lock_pair(trade.pair,
|
||||||
|
timeframe_to_next_date(self.config['ticker_interval']))
|
||||||
|
self._notify_sell(trade, "stoploss")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# Finally we check if stoploss on exchange should be moved up because of trailing.
|
# Finally we check if stoploss on exchange should be moved up because of trailing.
|
||||||
@@ -696,7 +724,7 @@ class FreqtradeBot(object):
|
|||||||
if trade.stop_loss > float(order['info']['stopPrice']):
|
if trade.stop_loss > float(order['info']['stopPrice']):
|
||||||
# we check if the update is neccesary
|
# we check if the update is neccesary
|
||||||
update_beat = self.strategy.order_types.get('stoploss_on_exchange_interval', 60)
|
update_beat = self.strategy.order_types.get('stoploss_on_exchange_interval', 60)
|
||||||
if (datetime.utcnow() - trade.stoploss_last_update).total_seconds() > update_beat:
|
if (datetime.utcnow() - trade.stoploss_last_update).total_seconds() >= update_beat:
|
||||||
# cancelling the current stoploss on exchange first
|
# cancelling the current stoploss on exchange first
|
||||||
logger.info('Trailing stoploss: cancelling current stoploss on exchange (id:{%s})'
|
logger.info('Trailing stoploss: cancelling current stoploss on exchange (id:{%s})'
|
||||||
'in order to add another one ...', order['id'])
|
'in order to add another one ...', order['id'])
|
||||||
@@ -706,15 +734,12 @@ class FreqtradeBot(object):
|
|||||||
logger.exception(f"Could not cancel stoploss order {order['id']} "
|
logger.exception(f"Could not cancel stoploss order {order['id']} "
|
||||||
f"for pair {trade.pair}")
|
f"for pair {trade.pair}")
|
||||||
|
|
||||||
try:
|
# Create new stoploss order
|
||||||
# creating the new one
|
if self.create_stoploss_order(trade=trade, stop_price=trade.stop_loss,
|
||||||
stoploss_order_id = self.exchange.stoploss_limit(
|
rate=trade.stop_loss):
|
||||||
pair=trade.pair, amount=trade.amount,
|
return False
|
||||||
stop_price=trade.stop_loss, rate=trade.stop_loss * 0.99
|
else:
|
||||||
)['id']
|
logger.warning(f"Could not create trailing stoploss order "
|
||||||
trade.stoploss_order_id = str(stoploss_order_id)
|
|
||||||
except DependencyException:
|
|
||||||
logger.exception(f"Could create trailing stoploss order "
|
|
||||||
f"for pair {trade.pair}.")
|
f"for pair {trade.pair}.")
|
||||||
|
|
||||||
def _check_and_execute_sell(self, trade: Trade, sell_rate: float,
|
def _check_and_execute_sell(self, trade: Trade, sell_rate: float,
|
||||||
@@ -733,23 +758,28 @@ class FreqtradeBot(object):
|
|||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def _check_timed_out(self, side: str, order: dict) -> bool:
|
||||||
|
"""
|
||||||
|
Check if timeout is active, and if the order is still open and timed out
|
||||||
|
"""
|
||||||
|
timeout = self.config.get('unfilledtimeout', {}).get(side)
|
||||||
|
ordertime = arrow.get(order['datetime']).datetime
|
||||||
|
if timeout is not None:
|
||||||
|
timeout_threshold = arrow.utcnow().shift(minutes=-timeout).datetime
|
||||||
|
|
||||||
|
return (order['status'] == 'open' and order['side'] == side
|
||||||
|
and ordertime < timeout_threshold)
|
||||||
|
return False
|
||||||
|
|
||||||
def check_handle_timedout(self) -> None:
|
def check_handle_timedout(self) -> None:
|
||||||
"""
|
"""
|
||||||
Check if any orders are timed out and cancel if neccessary
|
Check if any orders are timed out and cancel if neccessary
|
||||||
:param timeoutvalue: Number of minutes until order is considered timed out
|
:param timeoutvalue: Number of minutes until order is considered timed out
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
buy_timeout = self.config['unfilledtimeout']['buy']
|
|
||||||
sell_timeout = self.config['unfilledtimeout']['sell']
|
|
||||||
buy_timeoutthreashold = arrow.utcnow().shift(minutes=-buy_timeout).datetime
|
|
||||||
sell_timeoutthreashold = arrow.utcnow().shift(minutes=-sell_timeout).datetime
|
|
||||||
|
|
||||||
for trade in Trade.query.filter(Trade.open_order_id.isnot(None)).all():
|
for trade in Trade.get_open_order_trades():
|
||||||
try:
|
try:
|
||||||
# FIXME: Somehow the query above returns results
|
|
||||||
# where the open_order_id is in fact None.
|
|
||||||
# This is probably because the record got
|
|
||||||
# updated via /forcesell in a different thread.
|
|
||||||
if not trade.open_order_id:
|
if not trade.open_order_id:
|
||||||
continue
|
continue
|
||||||
order = self.exchange.get_order(trade.open_order_id, trade.pair)
|
order = self.exchange.get_order(trade.open_order_id, trade.pair)
|
||||||
@@ -759,26 +789,20 @@ class FreqtradeBot(object):
|
|||||||
trade,
|
trade,
|
||||||
traceback.format_exc())
|
traceback.format_exc())
|
||||||
continue
|
continue
|
||||||
ordertime = arrow.get(order['datetime']).datetime
|
|
||||||
|
|
||||||
# Check if trade is still actually open
|
# Check if trade is still actually open
|
||||||
if float(order['remaining']) == 0.0:
|
if float(order.get('remaining', 0.0)) == 0.0:
|
||||||
self.wallets.update()
|
self.wallets.update()
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Handle cancelled on exchange
|
if ((order['side'] == 'buy' and order['status'] == 'canceled')
|
||||||
if order['status'] == 'canceled':
|
or (self._check_timed_out('buy', order))):
|
||||||
if order['side'] == 'buy':
|
|
||||||
self.handle_buy_order_full_cancel(trade, "canceled on Exchange")
|
|
||||||
elif order['side'] == 'sell':
|
|
||||||
self.handle_timedout_limit_sell(trade, order)
|
|
||||||
self.wallets.update()
|
|
||||||
# Check if order is still actually open
|
|
||||||
elif order['status'] == 'open':
|
|
||||||
if order['side'] == 'buy' and ordertime < buy_timeoutthreashold:
|
|
||||||
self.handle_timedout_limit_buy(trade, order)
|
self.handle_timedout_limit_buy(trade, order)
|
||||||
self.wallets.update()
|
self.wallets.update()
|
||||||
elif order['side'] == 'sell' and ordertime < sell_timeoutthreashold:
|
|
||||||
|
elif ((order['side'] == 'sell' and order['status'] == 'canceled')
|
||||||
|
or (self._check_timed_out('sell', order))):
|
||||||
self.handle_timedout_limit_sell(trade, order)
|
self.handle_timedout_limit_sell(trade, order)
|
||||||
self.wallets.update()
|
self.wallets.update()
|
||||||
|
|
||||||
@@ -793,19 +817,41 @@ class FreqtradeBot(object):
|
|||||||
})
|
})
|
||||||
|
|
||||||
def handle_timedout_limit_buy(self, trade: Trade, order: Dict) -> bool:
|
def handle_timedout_limit_buy(self, trade: Trade, order: Dict) -> bool:
|
||||||
"""Buy timeout - cancel order
|
"""
|
||||||
|
Buy timeout - cancel order
|
||||||
:return: True if order was fully cancelled
|
:return: True if order was fully cancelled
|
||||||
"""
|
"""
|
||||||
self.exchange.cancel_order(trade.open_order_id, trade.pair)
|
reason = "cancelled due to timeout"
|
||||||
if order['remaining'] == order['amount']:
|
if order['status'] != 'canceled':
|
||||||
|
corder = self.exchange.cancel_order(trade.open_order_id, trade.pair)
|
||||||
|
else:
|
||||||
|
# Order was cancelled already, so we can reuse the existing dict
|
||||||
|
corder = order
|
||||||
|
reason = "canceled on Exchange"
|
||||||
|
|
||||||
|
if corder.get('remaining', order['remaining']) == order['amount']:
|
||||||
# if trade is not partially completed, just delete the trade
|
# if trade is not partially completed, just delete the trade
|
||||||
self.handle_buy_order_full_cancel(trade, "cancelled due to timeout")
|
self.handle_buy_order_full_cancel(trade, reason)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# if trade is partially complete, edit the stake details for the trade
|
# if trade is partially complete, edit the stake details for the trade
|
||||||
# and close the order
|
# and close the order
|
||||||
trade.amount = order['amount'] - order['remaining']
|
# cancel_order may not contain the full order dict, so we need to fallback
|
||||||
|
# to the order dict aquired before cancelling.
|
||||||
|
# we need to fall back to the values from order if corder does not contain these keys.
|
||||||
|
trade.amount = order['amount'] - corder.get('remaining', order['remaining'])
|
||||||
trade.stake_amount = trade.amount * trade.open_rate
|
trade.stake_amount = trade.amount * trade.open_rate
|
||||||
|
# verify if fees were taken from amount to avoid problems during selling
|
||||||
|
try:
|
||||||
|
new_amount = self.get_real_amount(trade, corder if 'fee' in corder else order,
|
||||||
|
trade.amount)
|
||||||
|
if not isclose(order['amount'], new_amount, abs_tol=constants.MATH_CLOSE_PREC):
|
||||||
|
trade.amount = new_amount
|
||||||
|
# Fee was applied, so set to 0
|
||||||
|
trade.fee_open = 0
|
||||||
|
except DependencyException as e:
|
||||||
|
logger.warning("Could not update trade amount: %s", e)
|
||||||
|
|
||||||
trade.open_order_id = None
|
trade.open_order_id = None
|
||||||
logger.info('Partial buy order timeout for %s.', trade)
|
logger.info('Partial buy order timeout for %s.', trade)
|
||||||
self.rpc.send_msg({
|
self.rpc.send_msg({
|
||||||
@@ -868,20 +914,32 @@ class FreqtradeBot(object):
|
|||||||
except InvalidOrderException:
|
except InvalidOrderException:
|
||||||
logger.exception(f"Could not cancel stoploss order {trade.stoploss_order_id}")
|
logger.exception(f"Could not cancel stoploss order {trade.stoploss_order_id}")
|
||||||
|
|
||||||
|
ordertype = self.strategy.order_types[sell_type]
|
||||||
|
if sell_reason == SellType.EMERGENCY_SELL:
|
||||||
|
# Emergencysells (default to market!)
|
||||||
|
ordertype = self.strategy.order_types.get("emergencysell", "market")
|
||||||
|
|
||||||
# Execute sell and update trade record
|
# Execute sell and update trade record
|
||||||
order_id = self.exchange.sell(pair=str(trade.pair),
|
order = self.exchange.sell(pair=str(trade.pair),
|
||||||
ordertype=self.strategy.order_types[sell_type],
|
ordertype=ordertype,
|
||||||
amount=trade.amount, rate=limit,
|
amount=trade.amount, rate=limit,
|
||||||
time_in_force=self.strategy.order_time_in_force['sell']
|
time_in_force=self.strategy.order_time_in_force['sell']
|
||||||
)['id']
|
)
|
||||||
|
|
||||||
trade.open_order_id = order_id
|
trade.open_order_id = order['id']
|
||||||
trade.close_rate_requested = limit
|
trade.close_rate_requested = limit
|
||||||
trade.sell_reason = sell_reason.value
|
trade.sell_reason = sell_reason.value
|
||||||
|
# In case of market sell orders the order can be closed immediately
|
||||||
|
if order.get('status', 'unknown') == 'closed':
|
||||||
|
trade.update(order)
|
||||||
Trade.session.flush()
|
Trade.session.flush()
|
||||||
self._notify_sell(trade)
|
|
||||||
|
|
||||||
def _notify_sell(self, trade: Trade):
|
# Lock pair for one candle to prevent immediate rebuys
|
||||||
|
self.strategy.lock_pair(trade.pair, timeframe_to_next_date(self.config['ticker_interval']))
|
||||||
|
|
||||||
|
self._notify_sell(trade, ordertype)
|
||||||
|
|
||||||
|
def _notify_sell(self, trade: Trade, order_type: str):
|
||||||
"""
|
"""
|
||||||
Sends rpc notification when a sell occured.
|
Sends rpc notification when a sell occured.
|
||||||
"""
|
"""
|
||||||
@@ -898,7 +956,7 @@ class FreqtradeBot(object):
|
|||||||
'pair': trade.pair,
|
'pair': trade.pair,
|
||||||
'gain': gain,
|
'gain': gain,
|
||||||
'limit': trade.close_rate_requested,
|
'limit': trade.close_rate_requested,
|
||||||
'order_type': self.strategy.order_types['sell'],
|
'order_type': order_type,
|
||||||
'amount': trade.amount,
|
'amount': trade.amount,
|
||||||
'open_rate': trade.open_rate,
|
'open_rate': trade.open_rate,
|
||||||
'current_rate': current_rate,
|
'current_rate': current_rate,
|
||||||
|
|||||||
@@ -1,40 +0,0 @@
|
|||||||
from math import cos, exp, pi, sqrt
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import talib as ta
|
|
||||||
from pandas import Series
|
|
||||||
|
|
||||||
|
|
||||||
def went_up(series: Series) -> bool:
|
|
||||||
return series > series.shift(1)
|
|
||||||
|
|
||||||
|
|
||||||
def went_down(series: Series) -> bool:
|
|
||||||
return series < series.shift(1)
|
|
||||||
|
|
||||||
|
|
||||||
def ehlers_super_smoother(series: Series, smoothing: float = 6) -> Series:
|
|
||||||
magic = pi * sqrt(2) / smoothing
|
|
||||||
a1 = exp(-magic)
|
|
||||||
coeff2 = 2 * a1 * cos(magic)
|
|
||||||
coeff3 = -a1 * a1
|
|
||||||
coeff1 = (1 - coeff2 - coeff3) / 2
|
|
||||||
|
|
||||||
filtered = series.copy()
|
|
||||||
|
|
||||||
for i in range(2, len(series)):
|
|
||||||
filtered.iloc[i] = coeff1 * (series.iloc[i] + series.iloc[i-1]) + \
|
|
||||||
coeff2 * filtered.iloc[i-1] + coeff3 * filtered.iloc[i-2]
|
|
||||||
|
|
||||||
return filtered
|
|
||||||
|
|
||||||
|
|
||||||
def fishers_inverse(series: Series, smoothing: float = 0) -> np.ndarray:
|
|
||||||
""" Does a smoothed fishers inverse transformation.
|
|
||||||
Can be used with any oscillator that goes from 0 to 100 like RSI or MFI """
|
|
||||||
v1 = 0.1 * (series - 50)
|
|
||||||
if smoothing > 0:
|
|
||||||
v2 = ta.WMA(v1.values, timeperiod=smoothing)
|
|
||||||
else:
|
|
||||||
v2 = v1
|
|
||||||
return (np.exp(2 * v2)-1) / (np.exp(2 * v2) + 1)
|
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
from logging.handlers import RotatingFileHandler
|
from logging import Formatter
|
||||||
|
from logging.handlers import RotatingFileHandler, SysLogHandler
|
||||||
from typing import Any, Dict, List
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
from freqtrade import OperationalException
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -33,11 +36,39 @@ def setup_logging(config: Dict[str, Any]) -> None:
|
|||||||
# Log level
|
# Log level
|
||||||
verbosity = config['verbosity']
|
verbosity = config['verbosity']
|
||||||
|
|
||||||
# Log to stdout, not stderr
|
# Log to stderr
|
||||||
log_handlers: List[logging.Handler] = [logging.StreamHandler(sys.stdout)]
|
log_handlers: List[logging.Handler] = [logging.StreamHandler(sys.stderr)]
|
||||||
|
|
||||||
if config.get('logfile'):
|
logfile = config.get('logfile')
|
||||||
log_handlers.append(RotatingFileHandler(config['logfile'],
|
if logfile:
|
||||||
|
s = logfile.split(':')
|
||||||
|
if s[0] == 'syslog':
|
||||||
|
# Address can be either a string (socket filename) for Unix domain socket or
|
||||||
|
# a tuple (hostname, port) for UDP socket.
|
||||||
|
# Address can be omitted (i.e. simple 'syslog' used as the value of
|
||||||
|
# config['logfilename']), which defaults to '/dev/log', applicable for most
|
||||||
|
# of the systems.
|
||||||
|
address = (s[1], int(s[2])) if len(s) > 2 else s[1] if len(s) > 1 else '/dev/log'
|
||||||
|
handler = SysLogHandler(address=address)
|
||||||
|
# No datetime field for logging into syslog, to allow syslog
|
||||||
|
# to perform reduction of repeating messages if this is set in the
|
||||||
|
# syslog config. The messages should be equal for this.
|
||||||
|
handler.setFormatter(Formatter('%(name)s - %(levelname)s - %(message)s'))
|
||||||
|
log_handlers.append(handler)
|
||||||
|
elif s[0] == 'journald':
|
||||||
|
try:
|
||||||
|
from systemd.journal import JournaldLogHandler
|
||||||
|
except ImportError:
|
||||||
|
raise OperationalException("You need the systemd python package be installed in "
|
||||||
|
"order to use logging to journald.")
|
||||||
|
handler = JournaldLogHandler()
|
||||||
|
# No datetime field for logging into journald, to allow syslog
|
||||||
|
# to perform reduction of repeating messages if this is set in the
|
||||||
|
# syslog config. The messages should be equal for this.
|
||||||
|
handler.setFormatter(Formatter('%(name)s - %(levelname)s - %(message)s'))
|
||||||
|
log_handlers.append(handler)
|
||||||
|
else:
|
||||||
|
log_handlers.append(RotatingFileHandler(logfile,
|
||||||
maxBytes=1024 * 1024, # 1Mb
|
maxBytes=1024 * 1024, # 1Mb
|
||||||
backupCount=10))
|
backupCount=10))
|
||||||
|
|
||||||
|
|||||||
@@ -11,12 +11,10 @@ if sys.version_info < (3, 6):
|
|||||||
|
|
||||||
# flake8: noqa E402
|
# flake8: noqa E402
|
||||||
import logging
|
import logging
|
||||||
from argparse import Namespace
|
|
||||||
from typing import Any, List
|
from typing import Any, List
|
||||||
|
|
||||||
from freqtrade import OperationalException
|
from freqtrade import OperationalException
|
||||||
from freqtrade.configuration import Arguments
|
from freqtrade.configuration import Arguments
|
||||||
from freqtrade.worker import Worker
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger('freqtrade')
|
logger = logging.getLogger('freqtrade')
|
||||||
@@ -29,24 +27,23 @@ def main(sysargv: List[str] = None) -> None:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
return_code: Any = 1
|
return_code: Any = 1
|
||||||
worker = None
|
|
||||||
try:
|
try:
|
||||||
arguments = Arguments(
|
arguments = Arguments(sysargv)
|
||||||
sysargv,
|
args = arguments.get_parsed_arg()
|
||||||
'Free, open source crypto trading bot'
|
|
||||||
)
|
|
||||||
args: Namespace = arguments.get_parsed_arg()
|
|
||||||
|
|
||||||
# A subcommand has been issued.
|
# Call subcommand.
|
||||||
# Means if Backtesting or Hyperopt have been called we exit the bot
|
if 'func' in args:
|
||||||
if hasattr(args, 'func'):
|
return_code = args['func'](args)
|
||||||
args.func(args)
|
|
||||||
# TODO: fetch return_code as returned by the command function here
|
|
||||||
return_code = 0
|
|
||||||
else:
|
else:
|
||||||
# Load and run worker
|
# No subcommand was issued.
|
||||||
worker = Worker(args)
|
raise OperationalException(
|
||||||
worker.run()
|
"Usage of Freqtrade requires a subcommand to be specified.\n"
|
||||||
|
"To have the previous behavior (bot executing trades in live/dry-run modes, "
|
||||||
|
"depending on the value of the `dry_run` setting in the config), run freqtrade "
|
||||||
|
"as `freqtrade trade [options...]`.\n"
|
||||||
|
"To see the full list of options available, please use "
|
||||||
|
"`freqtrade --help` or `freqtrade <command> --help`."
|
||||||
|
)
|
||||||
|
|
||||||
except SystemExit as e:
|
except SystemExit as e:
|
||||||
return_code = e
|
return_code = e
|
||||||
@@ -59,8 +56,6 @@ def main(sysargv: List[str] = None) -> None:
|
|||||||
except Exception:
|
except Exception:
|
||||||
logger.exception('Fatal exception!')
|
logger.exception('Fatal exception!')
|
||||||
finally:
|
finally:
|
||||||
if worker:
|
|
||||||
worker.exit()
|
|
||||||
sys.exit(return_code)
|
sys.exit(return_code)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,11 +5,12 @@ import gzip
|
|||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing.io import IO
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import rapidjson
|
import rapidjson
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@@ -39,7 +40,7 @@ def datesarray_to_datetimearray(dates: np.ndarray) -> np.ndarray:
|
|||||||
return dates.dt.to_pydatetime()
|
return dates.dt.to_pydatetime()
|
||||||
|
|
||||||
|
|
||||||
def file_dump_json(filename, data, is_zip=False) -> None:
|
def file_dump_json(filename: Path, 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
|
||||||
@@ -49,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:
|
||||||
@@ -60,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,
|
||||||
@@ -71,8 +72,10 @@ def json_load(datafile):
|
|||||||
|
|
||||||
def file_load_json(file):
|
def file_load_json(file):
|
||||||
|
|
||||||
|
if file.suffix != ".gz":
|
||||||
gzipfile = file.with_suffix(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 +116,27 @@ def deep_merge_dicts(source, destination):
|
|||||||
destination[key] = value
|
destination[key] = value
|
||||||
|
|
||||||
return destination
|
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'
|
||||||
|
|
||||||
|
|
||||||
|
def render_template(templatefile: str, arguments: dict = {}):
|
||||||
|
|
||||||
|
from jinja2 import Environment, PackageLoader, select_autoescape
|
||||||
|
|
||||||
|
env = Environment(
|
||||||
|
loader=PackageLoader('freqtrade', 'templates'),
|
||||||
|
autoescape=select_autoescape(['html', 'xml'])
|
||||||
|
)
|
||||||
|
template = env.get_template(templatefile)
|
||||||
|
|
||||||
|
return template.render(**arguments)
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
import logging
|
import logging
|
||||||
from argparse import Namespace
|
|
||||||
from typing import Any, Dict
|
from typing import Any, Dict
|
||||||
|
|
||||||
from filelock import FileLock, Timeout
|
from freqtrade import DependencyException, constants, OperationalException
|
||||||
|
|
||||||
from freqtrade import DependencyException, constants
|
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode
|
||||||
from freqtrade.utils import setup_utils_configuration
|
from freqtrade.utils import setup_utils_configuration
|
||||||
|
|
||||||
@@ -12,7 +9,7 @@ from freqtrade.utils import setup_utils_configuration
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def setup_configuration(args: Namespace, method: RunMode) -> Dict[str, Any]:
|
def setup_configuration(args: Dict[str, Any], method: RunMode) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Prepare the configuration for the Hyperopt module
|
Prepare the configuration for the Hyperopt module
|
||||||
:param args: Cli args from Arguments()
|
:param args: Cli args from Arguments()
|
||||||
@@ -25,20 +22,10 @@ def setup_configuration(args: Namespace, method: RunMode) -> Dict[str, Any]:
|
|||||||
raise DependencyException('stake amount could not be "%s" for backtesting' %
|
raise DependencyException('stake amount could not be "%s" for backtesting' %
|
||||||
constants.UNLIMITED_STAKE_AMOUNT)
|
constants.UNLIMITED_STAKE_AMOUNT)
|
||||||
|
|
||||||
if method == RunMode.HYPEROPT:
|
|
||||||
# Special cases for Hyperopt
|
|
||||||
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 DependencyException("--strategy configured but not supported for hyperopt")
|
|
||||||
|
|
||||||
return config
|
return config
|
||||||
|
|
||||||
|
|
||||||
def start_backtesting(args: Namespace) -> None:
|
def start_backtesting(args: Dict[str, Any]) -> None:
|
||||||
"""
|
"""
|
||||||
Start Backtesting script
|
Start Backtesting script
|
||||||
:param args: Cli args from Arguments()
|
:param args: Cli args from Arguments()
|
||||||
@@ -57,21 +44,25 @@ def start_backtesting(args: Namespace) -> None:
|
|||||||
backtesting.start()
|
backtesting.start()
|
||||||
|
|
||||||
|
|
||||||
def start_hyperopt(args: Namespace) -> None:
|
def start_hyperopt(args: Dict[str, Any]) -> None:
|
||||||
"""
|
"""
|
||||||
Start hyperopt script
|
Start hyperopt script
|
||||||
:param args: Cli args from Arguments()
|
:param args: Cli args from Arguments()
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
# Import here to avoid loading hyperopt module when it's not used
|
# Import here to avoid loading hyperopt module when it's not used
|
||||||
from freqtrade.optimize.hyperopt import Hyperopt, HYPEROPT_LOCKFILE
|
try:
|
||||||
|
from filelock import FileLock, Timeout
|
||||||
|
from freqtrade.optimize.hyperopt import Hyperopt
|
||||||
|
except ImportError as e:
|
||||||
|
raise OperationalException(
|
||||||
|
f"{e}. Please ensure that the hyperopt dependencies are installed.") from e
|
||||||
# Initialize configuration
|
# Initialize configuration
|
||||||
config = setup_configuration(args, RunMode.HYPEROPT)
|
config = setup_configuration(args, RunMode.HYPEROPT)
|
||||||
|
|
||||||
logger.info('Starting freqtrade in Hyperopt mode')
|
logger.info('Starting freqtrade in Hyperopt mode')
|
||||||
|
|
||||||
lock = FileLock(HYPEROPT_LOCKFILE)
|
lock = FileLock(Hyperopt.get_lock_filename(config))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with lock.acquire(timeout=1):
|
with lock.acquire(timeout=1):
|
||||||
@@ -87,7 +78,7 @@ def start_hyperopt(args: Namespace) -> None:
|
|||||||
except Timeout:
|
except Timeout:
|
||||||
logger.info("Another running instance of freqtrade Hyperopt detected.")
|
logger.info("Another running instance of freqtrade Hyperopt detected.")
|
||||||
logger.info("Simultaneous execution of multiple Hyperopt commands is not supported. "
|
logger.info("Simultaneous execution of multiple Hyperopt commands is not supported. "
|
||||||
"Hyperopt module is resource hungry. Please run your Hyperopts sequentially "
|
"Hyperopt module is resource hungry. Please run your Hyperopt sequentially "
|
||||||
"or on separate machines.")
|
"or on separate machines.")
|
||||||
logger.info("Quitting now.")
|
logger.info("Quitting now.")
|
||||||
# TODO: return False here in order to help freqtrade to exit
|
# TODO: return False here in order to help freqtrade to exit
|
||||||
@@ -95,7 +86,7 @@ def start_hyperopt(args: Namespace) -> None:
|
|||||||
# Same in Edge and Backtesting start() functions.
|
# Same in Edge and Backtesting start() functions.
|
||||||
|
|
||||||
|
|
||||||
def start_edge(args: Namespace) -> None:
|
def start_edge(args: Dict[str, Any]) -> None:
|
||||||
"""
|
"""
|
||||||
Start Edge script
|
Start Edge script
|
||||||
:param args: Cli args from Arguments()
|
:param args: Cli args from Arguments()
|
||||||
|
|||||||
@@ -12,10 +12,12 @@ from typing import Any, Dict, List, NamedTuple, Optional
|
|||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
from tabulate import tabulate
|
from tabulate import tabulate
|
||||||
|
|
||||||
from freqtrade.configuration import Arguments
|
from freqtrade import OperationalException
|
||||||
|
from freqtrade.configuration import (TimeRange, remove_credentials,
|
||||||
|
validate_config_consistency)
|
||||||
from freqtrade.data import history
|
from freqtrade.data import history
|
||||||
from freqtrade.data.dataprovider import DataProvider
|
from freqtrade.data.dataprovider import DataProvider
|
||||||
from freqtrade.exchange import timeframe_to_minutes
|
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds
|
||||||
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 ExchangeResolver, StrategyResolver
|
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||||
@@ -43,7 +45,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
|
||||||
|
|
||||||
@@ -56,14 +58,13 @@ class Backtesting(object):
|
|||||||
self.config = config
|
self.config = config
|
||||||
|
|
||||||
# Reset keys for backtesting
|
# Reset keys for backtesting
|
||||||
self.config['exchange']['key'] = ''
|
remove_credentials(self.config)
|
||||||
self.config['exchange']['secret'] = ''
|
|
||||||
self.config['exchange']['password'] = ''
|
|
||||||
self.config['exchange']['uid'] = ''
|
|
||||||
self.config['dry_run'] = True
|
|
||||||
self.strategylist: List[IStrategy] = []
|
self.strategylist: List[IStrategy] = []
|
||||||
|
|
||||||
self.exchange = ExchangeResolver(self.config['exchange']['name'], self.config).exchange
|
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()
|
self.fee = self.exchange.get_fee()
|
||||||
|
|
||||||
if self.config.get('runmode') != RunMode.HYPEROPT:
|
if self.config.get('runmode') != RunMode.HYPEROPT:
|
||||||
@@ -75,11 +76,21 @@ class Backtesting(object):
|
|||||||
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)
|
||||||
|
validate_config_consistency(stratconf)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# No strategy list specified, only one strategy
|
# No strategy list specified, only one strategy
|
||||||
self.strategylist.append(StrategyResolver(self.config).strategy)
|
self.strategylist.append(StrategyResolver(self.config).strategy)
|
||||||
|
validate_config_consistency(self.config)
|
||||||
|
|
||||||
|
if "ticker_interval" not in self.config:
|
||||||
|
raise OperationalException("Ticker-interval needs to be set in either configuration "
|
||||||
|
"or as cli argument `--ticker-interval 5m`")
|
||||||
|
self.timeframe = str(self.config.get('ticker_interval'))
|
||||||
|
self.timeframe_mins = timeframe_to_minutes(self.timeframe)
|
||||||
|
|
||||||
|
# Get maximum required startup period
|
||||||
|
self.required_startup = max([strat.startup_candle_count for strat in self.strategylist])
|
||||||
# Load one (first) strategy
|
# Load one (first) strategy
|
||||||
self._set_strategy(self.strategylist[0])
|
self._set_strategy(self.strategylist[0])
|
||||||
|
|
||||||
@@ -88,16 +99,36 @@ class Backtesting(object):
|
|||||||
Load strategy into backtesting
|
Load strategy into backtesting
|
||||||
"""
|
"""
|
||||||
self.strategy = strategy
|
self.strategy = strategy
|
||||||
|
|
||||||
self.ticker_interval = self.config.get('ticker_interval')
|
|
||||||
self.ticker_interval_mins = timeframe_to_minutes(self.ticker_interval)
|
|
||||||
self.advise_buy = strategy.advise_buy
|
|
||||||
self.advise_sell = strategy.advise_sell
|
|
||||||
# Set stoploss_on_exchange to false for backtesting,
|
# Set stoploss_on_exchange to false for backtesting,
|
||||||
# since a "perfect" stoploss-sell is assumed anyway
|
# since a "perfect" stoploss-sell is assumed anyway
|
||||||
# And the regular "stoploss" function would not apply to that case
|
# And the regular "stoploss" function would not apply to that case
|
||||||
self.strategy.order_types['stoploss_on_exchange'] = False
|
self.strategy.order_types['stoploss_on_exchange'] = False
|
||||||
|
|
||||||
|
def load_bt_data(self):
|
||||||
|
timerange = TimeRange.parse_timerange(None if self.config.get(
|
||||||
|
'timerange') is None else str(self.config.get('timerange')))
|
||||||
|
|
||||||
|
data = history.load_data(
|
||||||
|
datadir=Path(self.config['datadir']),
|
||||||
|
pairs=self.config['exchange']['pair_whitelist'],
|
||||||
|
timeframe=self.timeframe,
|
||||||
|
timerange=timerange,
|
||||||
|
startup_candles=self.required_startup,
|
||||||
|
fail_without_data=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
min_date, max_date = history.get_timeframe(data)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
'Loading data from %s up to %s (%s days)..',
|
||||||
|
min_date.isoformat(), max_date.isoformat(), (max_date - min_date).days
|
||||||
|
)
|
||||||
|
# Adjust startts forward if not enough data is available
|
||||||
|
timerange.adjust_start_if_necessary(timeframe_to_seconds(self.timeframe),
|
||||||
|
self.required_startup, min_date)
|
||||||
|
|
||||||
|
return data, timerange
|
||||||
|
|
||||||
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:
|
||||||
"""
|
"""
|
||||||
@@ -144,8 +175,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:
|
||||||
"""
|
"""
|
||||||
@@ -183,10 +214,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(),
|
||||||
@@ -197,10 +228,10 @@ 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]:
|
def _get_ticker_list(self, processed) -> Dict[str, DataFrame]:
|
||||||
@@ -213,10 +244,11 @@ class Backtesting(object):
|
|||||||
ticker: Dict = {}
|
ticker: Dict = {}
|
||||||
# Create ticker dict
|
# Create ticker dict
|
||||||
for pair, pair_data in processed.items():
|
for pair, pair_data in processed.items():
|
||||||
pair_data['buy'], pair_data['sell'] = 0, 0 # cleanup from previous run
|
pair_data.loc[:, 'buy'] = 0 # cleanup from previous run
|
||||||
|
pair_data.loc[:, 'sell'] = 0 # cleanup from previous run
|
||||||
|
|
||||||
ticker_data = self.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()
|
||||||
|
|
||||||
# to avoid using data from future, we buy/sell with signal from previous candle
|
# 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[:, 'buy'] = ticker_data['buy'].shift(1)
|
||||||
@@ -235,14 +267,16 @@ class Backtesting(object):
|
|||||||
stake_amount: float, max_open_trades: int) -> Optional[BacktestResult]:
|
stake_amount: float, max_open_trades: int) -> Optional[BacktestResult]:
|
||||||
|
|
||||||
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:
|
||||||
@@ -263,6 +297,11 @@ class Backtesting(object):
|
|||||||
# - (Expected abs profit + open_rate + open_fee) / (fee_close -1)
|
# - (Expected abs profit + open_rate + open_fee) / (fee_close -1)
|
||||||
closerate = - (trade.open_rate * roi + trade.open_rate *
|
closerate = - (trade.open_rate * roi + trade.open_rate *
|
||||||
(1 + trade.fee_open)) / (trade.fee_close - 1)
|
(1 + trade.fee_open)) / (trade.fee_close - 1)
|
||||||
|
|
||||||
|
# Use the maximum between closerate and low as we
|
||||||
|
# cannot sell outside of a candle.
|
||||||
|
# Applies when using {"xx": -1} as roi to force sells after xx minutes
|
||||||
|
closerate = max(closerate, sell_row.low)
|
||||||
else:
|
else:
|
||||||
# This should not be reached...
|
# This should not be reached...
|
||||||
closerate = sell_row.open
|
closerate = sell_row.open
|
||||||
@@ -285,7 +324,7 @@ 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,
|
||||||
@@ -299,9 +338,11 @@ class Backtesting(object):
|
|||||||
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:
|
||||||
@@ -337,7 +378,7 @@ class Backtesting(object):
|
|||||||
lock_pair_until: Dict = {}
|
lock_pair_until: Dict = {}
|
||||||
# Indexes per pair, so some pairs are allowed to have a missing start.
|
# Indexes per pair, so some pairs are allowed to have a missing start.
|
||||||
indexes: Dict = {}
|
indexes: Dict = {}
|
||||||
tmp = start_date + timedelta(minutes=self.ticker_interval_mins)
|
tmp = start_date + timedelta(minutes=self.timeframe_mins)
|
||||||
|
|
||||||
# Loop timerange and get candle for each pair at that point in time
|
# Loop timerange and get candle for each pair at that point in time
|
||||||
while tmp < end_date:
|
while tmp < end_date:
|
||||||
@@ -373,11 +414,15 @@ class Backtesting(object):
|
|||||||
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][indexes[pair]:],
|
# since indexes has been incremented before, we need to go one step back to
|
||||||
|
# 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,
|
trade_count_lock, stake_amount,
|
||||||
max_open_trades)
|
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:
|
||||||
@@ -385,7 +430,7 @@ class Backtesting(object):
|
|||||||
lock_pair_until[pair] = end_date.datetime
|
lock_pair_until[pair] = end_date.datetime
|
||||||
|
|
||||||
# Move time one configured time_interval ahead.
|
# Move time one configured time_interval ahead.
|
||||||
tmp += timedelta(minutes=self.ticker_interval_mins)
|
tmp += timedelta(minutes=self.timeframe_mins)
|
||||||
return DataFrame.from_records(trades, columns=BacktestResult._fields)
|
return DataFrame.from_records(trades, columns=BacktestResult._fields)
|
||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
@@ -394,42 +439,18 @@ class Backtesting(object):
|
|||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
data: Dict[str, Any] = {}
|
data: Dict[str, Any] = {}
|
||||||
pairs = self.config['exchange']['pair_whitelist']
|
|
||||||
logger.info('Using stake_currency: %s ...', self.config['stake_currency'])
|
logger.info('Using stake_currency: %s ...', self.config['stake_currency'])
|
||||||
logger.info('Using stake_amount: %s ...', self.config['stake_amount'])
|
logger.info('Using stake_amount: %s ...', self.config['stake_amount'])
|
||||||
|
|
||||||
timerange = 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,
|
|
||||||
live=self.config.get('live', False)
|
|
||||||
)
|
|
||||||
|
|
||||||
if not data:
|
|
||||||
logger.critical("No data found. Terminating.")
|
|
||||||
return
|
|
||||||
# Use max_open_trades in backtesting, except --disable-max-market-positions is set
|
# Use max_open_trades in backtesting, except --disable-max-market-positions is set
|
||||||
if self.config.get('use_max_market_positions', True):
|
if self.config.get('use_max_market_positions', True):
|
||||||
max_open_trades = self.config['max_open_trades']
|
max_open_trades = self.config['max_open_trades']
|
||||||
else:
|
else:
|
||||||
logger.info('Ignoring max_open_trades (--disable-max-market-positions was used) ...')
|
logger.info('Ignoring max_open_trades (--disable-max-market-positions was used) ...')
|
||||||
max_open_trades = 0
|
max_open_trades = 0
|
||||||
|
|
||||||
|
data, timerange = self.load_bt_data()
|
||||||
|
|
||||||
all_results = {}
|
all_results = {}
|
||||||
|
|
||||||
min_date, max_date = history.get_timeframe(data)
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
'Backtesting with data from %s up to %s (%s days)..',
|
|
||||||
min_date.isoformat(),
|
|
||||||
max_date.isoformat(),
|
|
||||||
(max_date - min_date).days
|
|
||||||
)
|
|
||||||
|
|
||||||
for strat in self.strategylist:
|
for strat in self.strategylist:
|
||||||
logger.info("Running backtesting for Strategy %s", strat.get_strategy_name())
|
logger.info("Running backtesting for Strategy %s", strat.get_strategy_name())
|
||||||
self._set_strategy(strat)
|
self._set_strategy(strat)
|
||||||
@@ -437,6 +458,15 @@ class Backtesting(object):
|
|||||||
# need to reprocess data every time to populate signals
|
# need to reprocess data every time to populate signals
|
||||||
preprocessed = self.strategy.tickerdata_to_dataframe(data)
|
preprocessed = self.strategy.tickerdata_to_dataframe(data)
|
||||||
|
|
||||||
|
# Trim startup period from analyzed dataframe
|
||||||
|
for pair, df in preprocessed.items():
|
||||||
|
preprocessed[pair] = history.trim_dataframe(df, timerange)
|
||||||
|
min_date, max_date = history.get_timeframe(preprocessed)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
'Backtesting with data from %s up to %s (%s days)..',
|
||||||
|
min_date.isoformat(), max_date.isoformat(), (max_date - min_date).days
|
||||||
|
)
|
||||||
# Execute backtest and print results
|
# Execute backtest and print results
|
||||||
all_results[self.strategy.get_strategy_name()] = self.backtest(
|
all_results[self.strategy.get_strategy_name()] = self.backtest(
|
||||||
{
|
{
|
||||||
@@ -452,7 +482,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}")
|
||||||
|
|||||||
@@ -5,46 +5,57 @@ 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 skopt.space import Categorical, Dimension, Integer, Real
|
from skopt.space import Categorical, Dimension, Integer
|
||||||
|
|
||||||
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 DefaultHyperOpts(IHyperOpt):
|
class DefaultHyperOpt(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'])
|
||||||
@@ -80,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'),
|
||||||
@@ -97,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'])
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -4,19 +4,21 @@
|
|||||||
This module contains the edge backtesting interface
|
This module contains the edge backtesting interface
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
from typing import Dict, Any
|
from typing import Any, Dict
|
||||||
from tabulate import tabulate
|
|
||||||
from freqtrade import constants
|
|
||||||
from freqtrade.edge import Edge
|
|
||||||
|
|
||||||
from freqtrade.configuration import Arguments
|
from tabulate import tabulate
|
||||||
|
|
||||||
|
from freqtrade import constants
|
||||||
|
from freqtrade.configuration import (TimeRange, remove_credentials,
|
||||||
|
validate_config_consistency)
|
||||||
|
from freqtrade.edge import Edge
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
from freqtrade.resolvers import StrategyResolver
|
from freqtrade.resolvers import StrategyResolver
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
@@ -29,19 +31,18 @@ class EdgeCli(object):
|
|||||||
self.config = config
|
self.config = config
|
||||||
|
|
||||||
# Reset keys for edge
|
# Reset keys for edge
|
||||||
self.config['exchange']['key'] = ''
|
remove_credentials(self.config)
|
||||||
self.config['exchange']['secret'] = ''
|
|
||||||
self.config['exchange']['password'] = ''
|
|
||||||
self.config['exchange']['uid'] = ''
|
|
||||||
self.config['stake_amount'] = constants.UNLIMITED_STAKE_AMOUNT
|
self.config['stake_amount'] = constants.UNLIMITED_STAKE_AMOUNT
|
||||||
self.config['dry_run'] = True
|
|
||||||
self.exchange = 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)
|
validate_config_consistency(self.config)
|
||||||
self.edge._refresh_pairs = self.config.get('refresh_pairs', False)
|
|
||||||
|
|
||||||
self.timerange = Arguments.parse_timerange(None if self.config.get(
|
self.edge = Edge(config, self.exchange, self.strategy)
|
||||||
|
# Set refresh_pairs to false for edge-cli (it must be true for edge)
|
||||||
|
self.edge._refresh_pairs = False
|
||||||
|
|
||||||
|
self.timerange = TimeRange.parse_timerange(None if self.config.get(
|
||||||
'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
|
||||||
@@ -68,8 +69,8 @@ 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:
|
||||||
result = self.edge.calculate()
|
result = self.edge.calculate()
|
||||||
|
|||||||
@@ -4,39 +4,47 @@
|
|||||||
This module contains the hyperopt logic
|
This module contains the hyperopt logic
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import locale
|
||||||
import logging
|
import logging
|
||||||
import os
|
|
||||||
import sys
|
import sys
|
||||||
|
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, cpu_count
|
import rapidjson
|
||||||
|
from colorama import Fore, Style
|
||||||
|
from colorama import init as colorama_init
|
||||||
|
from joblib import (Parallel, cpu_count, delayed, dump, load,
|
||||||
|
wrap_non_picklable_objects)
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
from skopt import Optimizer
|
from skopt import Optimizer
|
||||||
from skopt.space import Dimension
|
from skopt.space import Dimension
|
||||||
|
|
||||||
from freqtrade.configuration import Arguments
|
from freqtrade import OperationalException
|
||||||
from freqtrade.data.history import load_data, get_timeframe
|
from freqtrade.data.history import get_timeframe, trim_dataframe
|
||||||
|
from freqtrade.misc import plural, round_dict
|
||||||
from freqtrade.optimize.backtesting import Backtesting
|
from freqtrade.optimize.backtesting import Backtesting
|
||||||
# Import IHyperOptLoss to allow users import from this file
|
# Import IHyperOpt and IHyperOptLoss to allow unpickling classes from these modules
|
||||||
|
from freqtrade.optimize.hyperopt_interface import IHyperOpt # noqa: F4
|
||||||
from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss # noqa: F4
|
from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss # noqa: F4
|
||||||
from freqtrade.resolvers.hyperopt_resolver import HyperOptResolver, HyperOptLossResolver
|
from freqtrade.resolvers.hyperopt_resolver import (HyperOptLossResolver,
|
||||||
|
HyperOptResolver)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
INITIAL_POINTS = 30
|
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')
|
|
||||||
TRIALSDATA_PICKLE = os.path.join('user_data', 'hyperopt_results.pickle')
|
|
||||||
HYPEROPT_LOCKFILE = os.path.join('user_data', 'hyperopt.lock')
|
|
||||||
|
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
@@ -45,13 +53,21 @@ 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.backtesting = Backtesting(self.config)
|
||||||
|
|
||||||
self.custom_hyperopt = HyperOptResolver(self.config).hyperopt
|
self.custom_hyperopt = HyperOptResolver(self.config).hyperopt
|
||||||
|
|
||||||
self.custom_hyperoptloss = HyperOptLossResolver(self.config).hyperoptloss
|
self.custom_hyperoptloss = HyperOptLossResolver(self.config).hyperoptloss
|
||||||
self.calculate_loss = self.custom_hyperoptloss.hyperopt_loss_function
|
self.calculate_loss = self.custom_hyperoptloss.hyperopt_loss_function
|
||||||
|
|
||||||
self.total_tries = config.get('epochs', 0)
|
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
|
||||||
|
|
||||||
if not self.config.get('hyperopt_continue'):
|
if not self.config.get('hyperopt_continue'):
|
||||||
@@ -59,16 +75,21 @@ class Hyperopt(Backtesting):
|
|||||||
else:
|
else:
|
||||||
logger.info("Continuing on previous hyperopt results.")
|
logger.info("Continuing on previous hyperopt results.")
|
||||||
|
|
||||||
|
self.num_trials_saved = 0
|
||||||
|
|
||||||
# Previous evaluations
|
# Previous evaluations
|
||||||
self.trials_file = TRIALSDATA_PICKLE
|
|
||||||
self.trials: List = []
|
self.trials: List = []
|
||||||
|
|
||||||
# Populate functions here (hasattr is slow so should not be run during "regular" operations)
|
# 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'):
|
if hasattr(self.custom_hyperopt, 'populate_buy_trend'):
|
||||||
self.advise_buy = self.custom_hyperopt.populate_buy_trend # type: ignore
|
self.backtesting.strategy.advise_buy = \
|
||||||
|
self.custom_hyperopt.populate_buy_trend # type: ignore
|
||||||
if hasattr(self.custom_hyperopt, 'populate_sell_trend'):
|
if hasattr(self.custom_hyperopt, 'populate_sell_trend'):
|
||||||
self.advise_sell = self.custom_hyperopt.populate_sell_trend # type: ignore
|
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
|
# Use max_open_trades for hyperopt as well, except --disable-max-market-positions is set
|
||||||
if self.config.get('use_max_market_positions', True):
|
if self.config.get('use_max_market_positions', True):
|
||||||
@@ -76,135 +97,275 @@ class Hyperopt(Backtesting):
|
|||||||
else:
|
else:
|
||||||
logger.debug('Ignoring max_open_trades (--disable-max-market-positions was used) ...')
|
logger.debug('Ignoring max_open_trades (--disable-max-market-positions was used) ...')
|
||||||
self.max_open_trades = 0
|
self.max_open_trades = 0
|
||||||
self.position_stacking = self.config.get('position_stacking', False),
|
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
|
||||||
|
|
||||||
|
self.print_all = self.config.get('print_all', False)
|
||||||
|
self.print_colorized = self.config.get('print_colorized', False)
|
||||||
|
self.print_json = self.config.get('print_json', False)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_lock_filename(config) -> str:
|
||||||
|
|
||||||
|
return str(config['user_data_dir'] / 'hyperopt.lock')
|
||||||
|
|
||||||
def clean_hyperopt(self):
|
def clean_hyperopt(self):
|
||||||
"""
|
"""
|
||||||
Remove hyperopt pickle files to restart hyperopt.
|
Remove hyperopt pickle files to restart hyperopt.
|
||||||
"""
|
"""
|
||||||
for f in [TICKERDATA_PICKLE, TRIALSDATA_PICKLE]:
|
for f in [self.tickerdata_pickle, self.trials_file]:
|
||||||
p = Path(f)
|
p = Path(f)
|
||||||
if p.is_file():
|
if p.is_file():
|
||||||
logger.info(f"Removing `{p}`.")
|
logger.info(f"Removing `{p}`.")
|
||||||
p.unlink()
|
p.unlink()
|
||||||
|
|
||||||
def get_args(self, params):
|
def _get_params_dict(self, raw_params: List[Any]) -> Dict:
|
||||||
dimensions = self.hyperopt_space()
|
|
||||||
|
dimensions: List[Dimension] = self.dimensions
|
||||||
|
|
||||||
# Ensure the number of dimensions match
|
# Ensure the number of dimensions match
|
||||||
# the number of parameters in the list x.
|
# the number of parameters in the list.
|
||||||
if len(params) != len(dimensions):
|
if len(raw_params) != len(dimensions):
|
||||||
raise ValueError('Mismatch in number of search-space dimensions. '
|
raise ValueError('Mismatch in number of search-space dimensions.')
|
||||||
f'len(dimensions)=={len(dimensions)} and len(x)=={len(params)}')
|
|
||||||
|
|
||||||
# Create a dict where the keys are the names of the dimensions
|
# Return a dict where the keys are the names of the dimensions
|
||||||
# and the values are taken from the list of parameters x.
|
# and the values are taken from the list of parameters.
|
||||||
arg_dict = {dim.name: value for dim, value in zip(dimensions, params)}
|
return {d.name: v for d, v in zip(dimensions, raw_params)}
|
||||||
return arg_dict
|
|
||||||
|
|
||||||
def save_trials(self) -> None:
|
def save_trials(self, final: bool = False) -> None:
|
||||||
"""
|
"""
|
||||||
Save hyperopt trials to file
|
Save hyperopt trials to file
|
||||||
"""
|
"""
|
||||||
if self.trials:
|
num_trials = len(self.trials)
|
||||||
logger.info('Saving %d evaluations to \'%s\'', len(self.trials), self.trials_file)
|
if num_trials > self.num_trials_saved:
|
||||||
|
logger.info(f"Saving {num_trials} {plural(num_trials, 'epoch')}.")
|
||||||
dump(self.trials, self.trials_file)
|
dump(self.trials, self.trials_file)
|
||||||
|
self.num_trials_saved = num_trials
|
||||||
|
if final:
|
||||||
|
logger.info(f"{num_trials} {plural(num_trials, 'epoch')} "
|
||||||
|
f"saved to '{self.trials_file}'.")
|
||||||
|
|
||||||
def read_trials(self) -> List:
|
@staticmethod
|
||||||
|
def _read_trials(trials_file) -> List:
|
||||||
"""
|
"""
|
||||||
Read hyperopt trials file
|
Read hyperopt trials file
|
||||||
"""
|
"""
|
||||||
logger.info('Reading Trials from \'%s\'', self.trials_file)
|
logger.info("Reading Trials from '%s'", trials_file)
|
||||||
trials = load(self.trials_file)
|
trials = load(trials_file)
|
||||||
os.remove(self.trials_file)
|
|
||||||
return trials
|
return trials
|
||||||
|
|
||||||
def log_trials_result(self) -> None:
|
def _get_params_details(self, params: Dict) -> Dict:
|
||||||
"""
|
"""
|
||||||
Display Best hyperopt result
|
Return the params for each space
|
||||||
"""
|
"""
|
||||||
results = sorted(self.trials, key=itemgetter('loss'))
|
result: Dict = {}
|
||||||
best_result = results[0]
|
|
||||||
logger.info(
|
|
||||||
'Best result:\n%s\nwith values:\n',
|
|
||||||
best_result['result']
|
|
||||||
)
|
|
||||||
pprint(best_result['params'], indent=4)
|
|
||||||
if 'roi_t1' in best_result['params']:
|
|
||||||
logger.info('ROI table:')
|
|
||||||
pprint(self.custom_hyperopt.generate_roi_table(best_result['params']), indent=4)
|
|
||||||
|
|
||||||
def log_results(self, results) -> None:
|
if self.has_space('buy'):
|
||||||
|
result['buy'] = {p.name: params.get(p.name)
|
||||||
|
for p in self.hyperopt_space('buy')}
|
||||||
|
if self.has_space('sell'):
|
||||||
|
result['sell'] = {p.name: params.get(p.name)
|
||||||
|
for p in self.hyperopt_space('sell')}
|
||||||
|
if self.has_space('roi'):
|
||||||
|
result['roi'] = self.custom_hyperopt.generate_roi_table(params)
|
||||||
|
if self.has_space('stoploss'):
|
||||||
|
result['stoploss'] = {p.name: params.get(p.name)
|
||||||
|
for p in self.hyperopt_space('stoploss')}
|
||||||
|
if self.has_space('trailing'):
|
||||||
|
result['trailing'] = {p.name: params.get(p.name)
|
||||||
|
for p in self.hyperopt_space('trailing')}
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def print_epoch_details(results, total_epochs, print_json: bool,
|
||||||
|
no_header: bool = False, header_str: str = None) -> None:
|
||||||
|
"""
|
||||||
|
Display details of the hyperopt result
|
||||||
|
"""
|
||||||
|
params = results.get('params_details', {})
|
||||||
|
|
||||||
|
# Default header string
|
||||||
|
if header_str is None:
|
||||||
|
header_str = "Best result"
|
||||||
|
|
||||||
|
if not no_header:
|
||||||
|
explanation_str = Hyperopt._format_explanation_string(results, total_epochs)
|
||||||
|
print(f"\n{header_str}:\n\n{explanation_str}\n")
|
||||||
|
|
||||||
|
if print_json:
|
||||||
|
result_dict: Dict = {}
|
||||||
|
for s in ['buy', 'sell', 'roi', 'stoploss', 'trailing']:
|
||||||
|
Hyperopt._params_update_for_json(result_dict, params, s)
|
||||||
|
print(rapidjson.dumps(result_dict, default=str, number_mode=rapidjson.NM_NATIVE))
|
||||||
|
|
||||||
|
else:
|
||||||
|
Hyperopt._params_pretty_print(params, 'buy', "Buy hyperspace params:")
|
||||||
|
Hyperopt._params_pretty_print(params, 'sell', "Sell hyperspace params:")
|
||||||
|
Hyperopt._params_pretty_print(params, 'roi', "ROI table:")
|
||||||
|
Hyperopt._params_pretty_print(params, 'stoploss', "Stoploss:")
|
||||||
|
Hyperopt._params_pretty_print(params, 'trailing', "Trailing stop:")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _params_update_for_json(result_dict, params, space: str):
|
||||||
|
if space in params:
|
||||||
|
space_params = Hyperopt._space_params(params, space)
|
||||||
|
if space in ['buy', 'sell']:
|
||||||
|
result_dict.setdefault('params', {}).update(space_params)
|
||||||
|
elif space == 'roi':
|
||||||
|
# Convert keys in min_roi dict to strings because
|
||||||
|
# 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 space_params.items()
|
||||||
|
)
|
||||||
|
else: # 'stoploss', 'trailing'
|
||||||
|
result_dict.update(space_params)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _params_pretty_print(params, space: str, header: str):
|
||||||
|
if space in params:
|
||||||
|
space_params = Hyperopt._space_params(params, space, 5)
|
||||||
|
if space == 'stoploss':
|
||||||
|
print(header, space_params.get('stoploss'))
|
||||||
|
else:
|
||||||
|
print(header)
|
||||||
|
pprint(space_params, indent=4)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _space_params(params, space: str, r: int = None) -> Dict:
|
||||||
|
d = params[space]
|
||||||
|
# Round floats to `r` digits after the decimal point if requested
|
||||||
|
return round_dict(d, r) if r else d
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def is_best_loss(results, current_best_loss) -> bool:
|
||||||
|
return results['loss'] < current_best_loss
|
||||||
|
|
||||||
|
def print_results(self, results) -> None:
|
||||||
"""
|
"""
|
||||||
Log results if it is better than any previous evaluation
|
Log results if it is better than any previous evaluation
|
||||||
"""
|
"""
|
||||||
print_all = self.config.get('print_all', False)
|
is_best = results['is_best']
|
||||||
if print_all or results['loss'] < self.current_best_loss:
|
if not self.print_all:
|
||||||
# Output human-friendly index here (starting from 1)
|
# Print '\n' after each 100th epoch to separate dots from the log messages.
|
||||||
current = results['current_tries'] + 1
|
# Otherwise output is messy on a terminal.
|
||||||
total = results['total_tries']
|
print('.', end='' if results['current_epoch'] % 100 != 0 else None) # type: ignore
|
||||||
res = results['result']
|
|
||||||
loss = results['loss']
|
|
||||||
self.current_best_loss = results['loss']
|
|
||||||
log_msg = f'{current:5d}/{total}: {res} Objective: {loss:.5f}'
|
|
||||||
log_msg = f'*{log_msg}' if results['initial_point'] else f' {log_msg}'
|
|
||||||
if print_all:
|
|
||||||
print(log_msg)
|
|
||||||
else:
|
|
||||||
print('\n' + log_msg)
|
|
||||||
else:
|
|
||||||
print('.', end='')
|
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
|
|
||||||
|
if self.print_all or is_best:
|
||||||
|
if not self.print_all:
|
||||||
|
# Separate the results explanation string from dots
|
||||||
|
print("\n")
|
||||||
|
self.print_results_explanation(results, self.total_epochs, self.print_all,
|
||||||
|
self.print_colorized)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def print_results_explanation(results, total_epochs, highlight_best: bool,
|
||||||
|
print_colorized: bool) -> None:
|
||||||
|
"""
|
||||||
|
Log results explanation string
|
||||||
|
"""
|
||||||
|
explanation_str = Hyperopt._format_explanation_string(results, total_epochs)
|
||||||
|
# Colorize output
|
||||||
|
if print_colorized:
|
||||||
|
if results['total_profit'] > 0:
|
||||||
|
explanation_str = Fore.GREEN + explanation_str
|
||||||
|
if highlight_best and results['is_best']:
|
||||||
|
explanation_str = Style.BRIGHT + explanation_str
|
||||||
|
print(explanation_str)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _format_explanation_string(results, total_epochs) -> str:
|
||||||
|
return (("*" if results['is_initial_point'] else " ") +
|
||||||
|
f"{results['current_epoch']:5d}/{total_epochs}: " +
|
||||||
|
f"{results['results_explanation']} " +
|
||||||
|
f"Objective: {results['loss']:.5f}")
|
||||||
|
|
||||||
def has_space(self, space: str) -> bool:
|
def has_space(self, space: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Tell if a space value is contained in the configuration
|
Tell if the space value is contained in the configuration
|
||||||
"""
|
"""
|
||||||
if space in self.config['spaces'] or 'all' in self.config['spaces']:
|
# The 'trailing' space is not included in the 'default' set of spaces
|
||||||
return True
|
if space == 'trailing':
|
||||||
return False
|
return any(s in self.config['spaces'] for s in [space, 'all'])
|
||||||
|
else:
|
||||||
|
return any(s in self.config['spaces'] for s in [space, 'all', 'default'])
|
||||||
|
|
||||||
def hyperopt_space(self) -> 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 'experimental' not in self.config:
|
if space == 'roi' or (space is None and self.has_space('roi')):
|
||||||
self.config['experimental'] = {}
|
logger.debug("Hyperopt has 'roi' space")
|
||||||
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()
|
||||||
|
|
||||||
|
if space == 'trailing' or (space is None and self.has_space('trailing')):
|
||||||
|
logger.debug("Hyperopt has 'trailing' space")
|
||||||
|
spaces += self.custom_hyperopt.trailing_space()
|
||||||
|
|
||||||
return spaces
|
return spaces
|
||||||
|
|
||||||
def generate_optimizer(self, _params: Dict) -> Dict:
|
def generate_optimizer(self, raw_params: List[Any], iteration=None) -> Dict:
|
||||||
"""
|
"""
|
||||||
Used Optimize function. Called once per epoch to optimize whatever is configured.
|
Used Optimize function. Called once per epoch to optimize whatever is configured.
|
||||||
Keep this function as optimized as possible!
|
Keep this function as optimized as possible!
|
||||||
"""
|
"""
|
||||||
params = self.get_args(_params)
|
params_dict = self._get_params_dict(raw_params)
|
||||||
|
params_details = self._get_params_details(params_dict)
|
||||||
|
|
||||||
if self.has_space('roi'):
|
if self.has_space('roi'):
|
||||||
self.strategy.minimal_roi = self.custom_hyperopt.generate_roi_table(params)
|
self.backtesting.strategy.minimal_roi = \
|
||||||
|
self.custom_hyperopt.generate_roi_table(params_dict)
|
||||||
|
|
||||||
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 = \
|
||||||
|
self.custom_hyperopt.buy_strategy_generator(params_dict)
|
||||||
|
|
||||||
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 = \
|
||||||
|
self.custom_hyperopt.sell_strategy_generator(params_dict)
|
||||||
|
|
||||||
if self.has_space('stoploss'):
|
if self.has_space('stoploss'):
|
||||||
self.strategy.stoploss = params['stoploss']
|
self.backtesting.strategy.stoploss = params_dict['stoploss']
|
||||||
|
|
||||||
processed = load(TICKERDATA_PICKLE)
|
if self.has_space('trailing'):
|
||||||
|
self.backtesting.strategy.trailing_stop = params_dict['trailing_stop']
|
||||||
|
self.backtesting.strategy.trailing_stop_positive = \
|
||||||
|
params_dict['trailing_stop_positive']
|
||||||
|
self.backtesting.strategy.trailing_stop_positive_offset = \
|
||||||
|
params_dict['trailing_stop_positive_offset']
|
||||||
|
self.backtesting.strategy.trailing_only_offset_is_reached = \
|
||||||
|
params_dict['trailing_only_offset_is_reached']
|
||||||
|
|
||||||
|
processed = load(self.tickerdata_pickle)
|
||||||
|
|
||||||
min_date, max_date = get_timeframe(processed)
|
min_date, max_date = get_timeframe(processed)
|
||||||
|
|
||||||
results = self.backtest(
|
backtesting_results = self.backtesting.backtest(
|
||||||
{
|
{
|
||||||
'stake_amount': self.config['stake_amount'],
|
'stake_amount': self.config['stake_amount'],
|
||||||
'processed': processed,
|
'processed': processed,
|
||||||
@@ -214,136 +375,176 @@ class Hyperopt(Backtesting):
|
|||||||
'end_date': max_date,
|
'end_date': max_date,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
result_explanation = self.format_results(results)
|
return self._get_results_dict(backtesting_results, min_date, max_date,
|
||||||
|
params_dict, params_details)
|
||||||
|
|
||||||
trade_count = len(results.index)
|
def _get_results_dict(self, backtesting_results, min_date, max_date,
|
||||||
|
params_dict, params_details):
|
||||||
|
results_metrics = self._calculate_results_metrics(backtesting_results)
|
||||||
|
results_explanation = self._format_results_explanation_string(results_metrics)
|
||||||
|
|
||||||
|
trade_count = results_metrics['trade_count']
|
||||||
|
total_profit = results_metrics['total_profit']
|
||||||
|
|
||||||
# If this evaluation contains too short amount of trades to be
|
# If this evaluation contains too short amount of trades to be
|
||||||
# interesting -- consider it as 'bad' (assigned max. loss value)
|
# interesting -- consider it as 'bad' (assigned max. loss value)
|
||||||
# in order to cast this hyperspace point away from optimization
|
# in order to cast this hyperspace point away from optimization
|
||||||
# path. We do not want to optimize 'hodl' strategies.
|
# path. We do not want to optimize 'hodl' strategies.
|
||||||
if trade_count < self.config['hyperopt_min_trades']:
|
loss: float = MAX_LOSS
|
||||||
return {
|
if trade_count >= self.config['hyperopt_min_trades']:
|
||||||
'loss': MAX_LOSS,
|
loss = self.calculate_loss(results=backtesting_results, trade_count=trade_count,
|
||||||
'params': params,
|
|
||||||
'result': result_explanation,
|
|
||||||
}
|
|
||||||
|
|
||||||
loss = self.calculate_loss(results=results, trade_count=trade_count,
|
|
||||||
min_date=min_date.datetime, max_date=max_date.datetime)
|
min_date=min_date.datetime, max_date=max_date.datetime)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'loss': loss,
|
'loss': loss,
|
||||||
'params': params,
|
'params_dict': params_dict,
|
||||||
'result': result_explanation,
|
'params_details': params_details,
|
||||||
|
'results_metrics': results_metrics,
|
||||||
|
'results_explanation': results_explanation,
|
||||||
|
'total_profit': total_profit,
|
||||||
}
|
}
|
||||||
|
|
||||||
def format_results(self, results: DataFrame) -> str:
|
def _calculate_results_metrics(self, backtesting_results: DataFrame) -> Dict:
|
||||||
|
return {
|
||||||
|
'trade_count': len(backtesting_results.index),
|
||||||
|
'avg_profit': backtesting_results.profit_percent.mean() * 100.0,
|
||||||
|
'total_profit': backtesting_results.profit_abs.sum(),
|
||||||
|
'profit': backtesting_results.profit_percent.sum() * 100.0,
|
||||||
|
'duration': backtesting_results.trade_duration.mean(),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _format_results_explanation_string(self, results_metrics: Dict) -> str:
|
||||||
"""
|
"""
|
||||||
Return the format result in a string
|
Return the formatted results explanation in a string
|
||||||
"""
|
"""
|
||||||
trades = len(results.index)
|
|
||||||
avg_profit = results.profit_percent.mean() * 100.0
|
|
||||||
total_profit = results.profit_abs.sum()
|
|
||||||
stake_cur = self.config['stake_currency']
|
stake_cur = self.config['stake_currency']
|
||||||
profit = results.profit_percent.sum() * 100.0
|
return (f"{results_metrics['trade_count']:6d} trades. "
|
||||||
duration = results.trade_duration.mean()
|
f"Avg profit {results_metrics['avg_profit']: 6.2f}%. "
|
||||||
|
f"Total profit {results_metrics['total_profit']: 11.8f} {stake_cur} "
|
||||||
|
f"({results_metrics['profit']: 7.2f}\N{GREEK CAPITAL LETTER SIGMA}%). "
|
||||||
|
f"Avg duration {results_metrics['duration']:5.1f} mins."
|
||||||
|
).encode(locale.getpreferredencoding(), 'replace').decode('utf-8')
|
||||||
|
|
||||||
return (f'{trades:6d} trades. Avg profit {avg_profit: 5.2f}%. '
|
def get_optimizer(self, dimensions: List[Dimension], cpu_count) -> Optimizer:
|
||||||
f'Total profit {total_profit: 11.8f} {stake_cur} '
|
|
||||||
f'({profit: 7.2f}Σ%). Avg duration {duration:5.1f} mins.')
|
|
||||||
|
|
||||||
def get_optimizer(self, 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=INITIAL_POINTS,
|
n_initial_points=INITIAL_POINTS,
|
||||||
acq_optimizer_kwargs={'n_jobs': cpu_count},
|
acq_optimizer_kwargs={'n_jobs': cpu_count},
|
||||||
random_state=self.config.get('hyperopt_random_state', None)
|
random_state=self.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):
|
@staticmethod
|
||||||
""" read trials file if we have one """
|
def load_previous_results(trials_file) -> List:
|
||||||
if os.path.exists(self.trials_file) and os.path.getsize(self.trials_file) > 0:
|
"""
|
||||||
self.trials = self.read_trials()
|
Load data for epochs from the file if we have one
|
||||||
logger.info(
|
"""
|
||||||
'Loaded %d previous evaluations from disk.',
|
trials: List = []
|
||||||
len(self.trials)
|
if trials_file.is_file() and trials_file.stat().st_size > 0:
|
||||||
)
|
trials = Hyperopt._read_trials(trials_file)
|
||||||
|
if trials[0].get('is_best') is None:
|
||||||
|
raise OperationalException(
|
||||||
|
"The file with Hyperopt results is incompatible with this version "
|
||||||
|
"of Freqtrade and cannot be loaded.")
|
||||||
|
logger.info(f"Loaded {len(trials)} previous evaluations from disk.")
|
||||||
|
return trials
|
||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
timerange = Arguments.parse_timerange(None if self.config.get(
|
data, timerange = self.backtesting.load_bt_data()
|
||||||
'timerange') is None else str(self.config.get('timerange')))
|
|
||||||
data = load_data(
|
|
||||||
datadir=Path(self.config['datadir']) if self.config.get('datadir') else None,
|
|
||||||
pairs=self.config['exchange']['pair_whitelist'],
|
|
||||||
ticker_interval=self.ticker_interval,
|
|
||||||
refresh_pairs=self.config.get('refresh_pairs', False),
|
|
||||||
exchange=self.exchange,
|
|
||||||
timerange=timerange
|
|
||||||
)
|
|
||||||
|
|
||||||
if not data:
|
preprocessed = self.backtesting.strategy.tickerdata_to_dataframe(data)
|
||||||
logger.critical("No data found. Terminating.")
|
|
||||||
return
|
|
||||||
|
|
||||||
|
# Trim startup period from analyzed dataframe
|
||||||
|
for pair, df in preprocessed.items():
|
||||||
|
preprocessed[pair] = trim_dataframe(df, timerange)
|
||||||
min_date, max_date = get_timeframe(data)
|
min_date, max_date = get_timeframe(data)
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
'Hyperopting with data from %s up to %s (%s days)..',
|
'Hyperopting with data from %s up to %s (%s days)..',
|
||||||
min_date.isoformat(),
|
min_date.isoformat(), max_date.isoformat(), (max_date - min_date).days
|
||||||
max_date.isoformat(),
|
|
||||||
(max_date - min_date).days
|
|
||||||
)
|
)
|
||||||
|
dump(preprocessed, self.tickerdata_pickle)
|
||||||
self.strategy.advise_indicators = \
|
|
||||||
self.custom_hyperopt.populate_indicators # type: ignore
|
|
||||||
|
|
||||||
preprocessed = self.strategy.tickerdata_to_dataframe(data)
|
|
||||||
|
|
||||||
dump(preprocessed, TICKERDATA_PICKLE)
|
|
||||||
|
|
||||||
# We don't need exchange instance anymore while running hyperopt
|
# We don't need exchange instance anymore while running hyperopt
|
||||||
self.exchange = None # type: ignore
|
self.backtesting.exchange = None # type: ignore
|
||||||
|
|
||||||
self.load_previous_results()
|
self.trials = self.load_previous_results(self.trials_file)
|
||||||
|
|
||||||
cpus = cpu_count()
|
cpus = cpu_count()
|
||||||
logger.info(f'Found {cpus} CPU cores. Let\'s make them scream!')
|
logger.info(f"Found {cpus} CPU cores. Let's make them scream!")
|
||||||
config_jobs = self.config.get('hyperopt_jobs', -1)
|
config_jobs = self.config.get('hyperopt_jobs', -1)
|
||||||
logger.info(f'Number of parallel jobs set as: {config_jobs}')
|
logger.info(f'Number of parallel jobs set as: {config_jobs}')
|
||||||
|
|
||||||
opt = self.get_optimizer(config_jobs)
|
self.dimensions: List[Dimension] = self.hyperopt_space()
|
||||||
|
self.opt = self.get_optimizer(self.dimensions, config_jobs)
|
||||||
|
|
||||||
|
if self.print_colorized:
|
||||||
|
colorama_init(autoreset=True)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with Parallel(n_jobs=config_jobs) as parallel:
|
with Parallel(n_jobs=config_jobs) as parallel:
|
||||||
jobs = parallel._effective_n_jobs()
|
jobs = parallel._effective_n_jobs()
|
||||||
logger.info(f'Effective number of parallel workers used: {jobs}')
|
logger.info(f'Effective number of parallel workers used: {jobs}')
|
||||||
EVALS = max(self.total_tries // jobs, 1)
|
EVALS = max(self.total_epochs // jobs, 1)
|
||||||
for i in range(EVALS):
|
for i in range(EVALS):
|
||||||
asked = opt.ask(n_points=jobs)
|
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()
|
||||||
|
for j in range(jobs):
|
||||||
|
# Use human-friendly indexes here (starting from 1)
|
||||||
|
current = i * jobs + j + 1
|
||||||
|
val = f_val[j]
|
||||||
|
val['current_epoch'] = current
|
||||||
|
val['is_initial_point'] = current <= INITIAL_POINTS
|
||||||
|
logger.debug(f"Optimizer epoch evaluated: {val}")
|
||||||
|
|
||||||
self.trials += f_val
|
is_best = self.is_best_loss(val, self.current_best_loss)
|
||||||
for j in range(jobs):
|
# This value is assigned here and not in the optimization method
|
||||||
current = i * jobs + j
|
# to keep proper order in the list of results. That's because
|
||||||
self.log_results({
|
# evaluations can take different time. Here they are aligned in the
|
||||||
'loss': f_val[j]['loss'],
|
# order they will be shown to the user.
|
||||||
'current_tries': current,
|
val['is_best'] = is_best
|
||||||
'initial_point': current < INITIAL_POINTS,
|
|
||||||
'total_tries': self.total_tries,
|
self.print_results(val)
|
||||||
'result': f_val[j]['result'],
|
|
||||||
})
|
if is_best:
|
||||||
logger.debug(f"Optimizer params: {f_val[j]['params']}")
|
self.current_best_loss = val['loss']
|
||||||
for j in range(jobs):
|
self.trials.append(val)
|
||||||
logger.debug(f"Optimizer state: Xi: {opt.Xi[-j-1]}, yi: {opt.yi[-j-1]}")
|
# Save results after each best epoch and every 100 epochs
|
||||||
|
if is_best or current % 100 == 0:
|
||||||
|
self.save_trials()
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print('User interrupted..')
|
print('User interrupted..')
|
||||||
|
|
||||||
self.save_trials()
|
self.save_trials(final=True)
|
||||||
self.log_trials_result()
|
|
||||||
|
if self.trials:
|
||||||
|
sorted_trials = sorted(self.trials, key=itemgetter('loss'))
|
||||||
|
results = sorted_trials[0]
|
||||||
|
self.print_epoch_details(results, self.total_epochs, self.print_json)
|
||||||
|
else:
|
||||||
|
# This is printed when Ctrl+C is pressed quickly, before first epochs have
|
||||||
|
# a chance to be evaluated.
|
||||||
|
print("No epochs evaluated yet, no best result.")
|
||||||
|
|||||||
@@ -1,81 +1,208 @@
|
|||||||
"""
|
"""
|
||||||
IHyperOpt interface
|
IHyperOpt interface
|
||||||
This module defines the interface to apply for hyperopts
|
This module defines the interface to apply for hyperopt
|
||||||
"""
|
"""
|
||||||
|
import logging
|
||||||
|
import math
|
||||||
|
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC
|
||||||
from typing import Dict, Any, Callable, List
|
from typing import Dict, Any, Callable, List
|
||||||
|
|
||||||
from pandas import DataFrame
|
from skopt.space import Categorical, Dimension, Integer, Real
|
||||||
from skopt.space import Dimension
|
|
||||||
|
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 hyperopt
|
||||||
Defines the mandatory structure must follow any custom strategies
|
Defines the mandatory structure must follow any custom hyperopt
|
||||||
|
|
||||||
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
|
ticker_interval: str
|
||||||
|
|
||||||
@staticmethod
|
def __init__(self, config: dict) -> None:
|
||||||
@abstractmethod
|
self.config = config
|
||||||
def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
||||||
"""
|
# Assign ticker_interval to be used in hyperopt
|
||||||
Populate indicators that will be used in the Buy and Sell strategy
|
IHyperOpt.ticker_interval = str(config['ticker_interval'])
|
||||||
:param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe()
|
|
||||||
:return: a Dataframe with all mandatory indicators for the strategies
|
|
||||||
"""
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@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
|
||||||
|
|
||||||
|
timeframe_mins = timeframe_to_minutes(IHyperOpt.ticker_interval)
|
||||||
|
|
||||||
|
# We define here limits for the ROI space parameters automagically adapted to the
|
||||||
|
# timeframe 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 = timeframe_mins / 5
|
||||||
|
roi_p_scale = math.log1p(timeframe_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'),
|
||||||
|
]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def trailing_space() -> List[Dimension]:
|
||||||
|
"""
|
||||||
|
Create a trailing stoploss space.
|
||||||
|
|
||||||
|
You may override it in your custom Hyperopt class.
|
||||||
|
"""
|
||||||
|
return [
|
||||||
|
# It was decided to always set trailing_stop is to True if the 'trailing' hyperspace
|
||||||
|
# is used. Otherwise hyperopt will vary other parameters that won't have effect if
|
||||||
|
# trailing_stop is set False.
|
||||||
|
# This parameter is included into the hyperspace dimensions rather than assigning
|
||||||
|
# it explicitly in the code in order to have it printed in the results along with
|
||||||
|
# other 'trailing' hyperspace parameters.
|
||||||
|
Categorical([True], name='trailing_stop'),
|
||||||
|
|
||||||
|
Real(0.02, 0.35, name='trailing_stop_positive'),
|
||||||
|
Real(0.01, 0.1, name='trailing_stop_positive_offset'),
|
||||||
|
Categorical([True, False], name='trailing_only_offset_is_reached'),
|
||||||
|
]
|
||||||
|
|
||||||
|
# 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']
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"""
|
"""
|
||||||
IHyperOptLoss interface
|
IHyperOptLoss interface
|
||||||
This module defines the interface for the loss-function for hyperopts
|
This module defines the interface for the loss-function for hyperopt
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
@@ -11,7 +11,7 @@ from pandas import DataFrame
|
|||||||
|
|
||||||
class IHyperOptLoss(ABC):
|
class IHyperOptLoss(ABC):
|
||||||
"""
|
"""
|
||||||
Interface for freqtrade hyperopts Loss functions.
|
Interface for freqtrade hyperopt Loss functions.
|
||||||
Defines the custom loss function (`hyperopt_loss_function()` which is evaluated every epoch.)
|
Defines the custom loss function (`hyperopt_loss_function()` which is evaluated every epoch.)
|
||||||
"""
|
"""
|
||||||
ticker_interval: str
|
ticker_interval: str
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ class SharpeHyperOptLoss(IHyperOptLoss):
|
|||||||
sharp_ratio = expected_yearly_return / np.std(total_profit) * np.sqrt(365)
|
sharp_ratio = expected_yearly_return / np.std(total_profit) * np.sqrt(365)
|
||||||
else:
|
else:
|
||||||
# Define high (negative) sharpe ratio to be clear that this is NOT optimal.
|
# Define high (negative) sharpe ratio to be clear that this is NOT optimal.
|
||||||
sharp_ratio = 20.
|
sharp_ratio = -20.
|
||||||
|
|
||||||
# print(expected_yearly_return, np.std(total_profit), sharp_ratio)
|
# print(expected_yearly_return, np.std(total_profit), sharp_ratio)
|
||||||
return -sharp_ratio
|
return -sharp_ratio
|
||||||
|
|||||||
@@ -5,19 +5,31 @@ Provides lists as configured in config.json
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod, abstractproperty
|
||||||
from typing import List
|
from copy import deepcopy
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
from freqtrade.exchange import market_is_active
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class IPairList(ABC):
|
class IPairList(ABC):
|
||||||
|
|
||||||
def __init__(self, freqtrade, config: dict) -> None:
|
def __init__(self, exchange, pairlistmanager, config, pairlistconfig: dict,
|
||||||
self._freqtrade = freqtrade
|
pairlist_pos: int) -> None:
|
||||||
|
"""
|
||||||
|
:param exchange: Exchange instance
|
||||||
|
:param pairlistmanager: Instanciating Pairlist manager
|
||||||
|
:param config: Global bot configuration
|
||||||
|
:param pairlistconfig: Configuration for this pairlist - can be empty.
|
||||||
|
:param pairlist_pos: Position of the filter in the pairlist-filter-list
|
||||||
|
"""
|
||||||
|
self._exchange = exchange
|
||||||
|
self._pairlistmanager = pairlistmanager
|
||||||
self._config = config
|
self._config = config
|
||||||
self._whitelist = self._config['exchange']['pair_whitelist']
|
self._pairlistconfig = pairlistconfig
|
||||||
self._blacklist = self._config['exchange'].get('pair_blacklist', [])
|
self._pairlist_pos = pairlist_pos
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def name(self) -> str:
|
def name(self) -> str:
|
||||||
@@ -27,21 +39,13 @@ class IPairList(ABC):
|
|||||||
"""
|
"""
|
||||||
return self.__class__.__name__
|
return self.__class__.__name__
|
||||||
|
|
||||||
@property
|
@abstractproperty
|
||||||
def whitelist(self) -> List[str]:
|
def needstickers(self) -> bool:
|
||||||
"""
|
"""
|
||||||
Has the current whitelist
|
Boolean property defining if tickers are necessary.
|
||||||
-> no need to overwrite in subclasses
|
If no Pairlist requries tickers, an empty List is passed
|
||||||
|
as tickers argument to filter_pairlist
|
||||||
"""
|
"""
|
||||||
return self._whitelist
|
|
||||||
|
|
||||||
@property
|
|
||||||
def blacklist(self) -> List[str]:
|
|
||||||
"""
|
|
||||||
Has the current blacklist
|
|
||||||
-> no need to overwrite in subclasses
|
|
||||||
"""
|
|
||||||
return self._blacklist
|
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def short_desc(self) -> str:
|
def short_desc(self) -> str:
|
||||||
@@ -51,36 +55,62 @@ class IPairList(ABC):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def refresh_pairlist(self) -> None:
|
def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Refreshes pairlists and assigns them to self._whitelist and self._blacklist respectively
|
Filters and sorts pairlist and returns the whitelist again.
|
||||||
|
Called on each bot iteration - please use internal caching if necessary
|
||||||
-> Please overwrite in subclasses
|
-> Please overwrite in subclasses
|
||||||
|
:param pairlist: pairlist to filter or sort
|
||||||
|
:param tickers: Tickers (from exchange.get_tickers()). May be cached.
|
||||||
|
:return: new whitelist
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def _validate_whitelist(self, whitelist: List[str]) -> List[str]:
|
@staticmethod
|
||||||
|
def verify_blacklist(pairlist: List[str], blacklist: List[str]) -> List[str]:
|
||||||
|
"""
|
||||||
|
Verify and remove items from pairlist - returning a filtered pairlist.
|
||||||
|
"""
|
||||||
|
for pair in deepcopy(pairlist):
|
||||||
|
if pair in blacklist:
|
||||||
|
logger.warning(f"Pair {pair} in your blacklist. Removing it from whitelist...")
|
||||||
|
pairlist.remove(pair)
|
||||||
|
return pairlist
|
||||||
|
|
||||||
|
def _verify_blacklist(self, pairlist: List[str]) -> List[str]:
|
||||||
|
"""
|
||||||
|
Proxy method to verify_blacklist for easy access for child classes.
|
||||||
|
"""
|
||||||
|
return IPairList.verify_blacklist(pairlist, self._pairlistmanager.blacklist)
|
||||||
|
|
||||||
|
def _whitelist_for_active_markets(self, pairlist: List[str]) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Check available markets and remove pair from whitelist if necessary
|
Check available markets and remove pair from whitelist if necessary
|
||||||
:param whitelist: the sorted list of pairs the user might want to trade
|
:param whitelist: the sorted list of pairs the user might want to trade
|
||||||
:return: the list of pairs the user wants to trade without those unavailable or
|
:return: the list of pairs the user wants to trade without those unavailable or
|
||||||
black_listed
|
black_listed
|
||||||
"""
|
"""
|
||||||
markets = self._freqtrade.exchange.markets
|
markets = self._exchange.markets
|
||||||
|
|
||||||
sanitized_whitelist = set()
|
sanitized_whitelist: List[str] = []
|
||||||
for pair in whitelist:
|
for pair in pairlist:
|
||||||
# pair is not in the generated dynamic market, or in the blacklist ... ignore it
|
# pair is not in the generated dynamic market or has the wrong stake currency
|
||||||
if (pair in self.blacklist or pair not in markets
|
if pair not in markets:
|
||||||
or not pair.endswith(self._config['stake_currency'])):
|
|
||||||
logger.warning(f"Pair {pair} is not compatible with exchange "
|
logger.warning(f"Pair {pair} is not compatible with exchange "
|
||||||
f"{self._freqtrade.exchange.name} or contained in "
|
f"{self._exchange.name}. Removing it from whitelist..")
|
||||||
f"your blacklist. Removing it from whitelist..")
|
|
||||||
continue
|
continue
|
||||||
|
if not pair.endswith(self._config['stake_currency']):
|
||||||
|
logger.warning(f"Pair {pair} is not compatible with your stake currency "
|
||||||
|
f"{self._config['stake_currency']}. Removing it from whitelist..")
|
||||||
|
continue
|
||||||
|
|
||||||
# Check if market is active
|
# Check if market is active
|
||||||
market = markets[pair]
|
market = markets[pair]
|
||||||
if not market['active']:
|
if not market_is_active(market):
|
||||||
logger.info(f"Ignoring {pair} from whitelist. Market is not active.")
|
logger.info(f"Ignoring {pair} from whitelist. Market is not active.")
|
||||||
continue
|
continue
|
||||||
sanitized_whitelist.add(pair)
|
if pair not in sanitized_whitelist:
|
||||||
|
sanitized_whitelist.append(pair)
|
||||||
|
|
||||||
|
sanitized_whitelist = self._verify_blacklist(sanitized_whitelist)
|
||||||
# We need to remove pairs that are unknown
|
# We need to remove pairs that are unknown
|
||||||
return list(sanitized_whitelist)
|
return sanitized_whitelist
|
||||||
|
|||||||
63
freqtrade/pairlist/PrecisionFilter.py
Normal file
63
freqtrade/pairlist/PrecisionFilter.py
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import logging
|
||||||
|
from copy import deepcopy
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
from freqtrade.pairlist.IPairList import IPairList
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class PrecisionFilter(IPairList):
|
||||||
|
|
||||||
|
@property
|
||||||
|
def needstickers(self) -> bool:
|
||||||
|
"""
|
||||||
|
Boolean property defining if tickers are necessary.
|
||||||
|
If no Pairlist requries tickers, an empty List is passed
|
||||||
|
as tickers argument to filter_pairlist
|
||||||
|
"""
|
||||||
|
return True
|
||||||
|
|
||||||
|
def short_desc(self) -> str:
|
||||||
|
"""
|
||||||
|
Short whitelist method description - used for startup-messages
|
||||||
|
"""
|
||||||
|
return f"{self.name} - Filtering untradable pairs."
|
||||||
|
|
||||||
|
def _validate_precision_filter(self, ticker: dict, stoploss: float) -> bool:
|
||||||
|
"""
|
||||||
|
Check if pair has enough room to add a stoploss to avoid "unsellable" buys of very
|
||||||
|
low value pairs.
|
||||||
|
:param ticker: ticker dict as returned from ccxt.load_markets()
|
||||||
|
:param stoploss: stoploss value as set in the configuration
|
||||||
|
(already cleaned to be 1 - stoploss)
|
||||||
|
:return: True if the pair can stay, false if it should be removed
|
||||||
|
"""
|
||||||
|
stop_price = ticker['ask'] * stoploss
|
||||||
|
# Adjust stop-prices to precision
|
||||||
|
sp = self._exchange.symbol_price_prec(ticker["symbol"], stop_price)
|
||||||
|
stop_gap_price = self._exchange.symbol_price_prec(ticker["symbol"], stop_price * 0.99)
|
||||||
|
logger.debug(f"{ticker['symbol']} - {sp} : {stop_gap_price}")
|
||||||
|
if sp <= stop_gap_price:
|
||||||
|
logger.info(f"Removed {ticker['symbol']} from whitelist, "
|
||||||
|
f"because stop price {sp} would be <= stop limit {stop_gap_price}")
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
|
||||||
|
"""
|
||||||
|
Filters and sorts pairlists and assigns and returns them again.
|
||||||
|
"""
|
||||||
|
stoploss = None
|
||||||
|
if self._config.get('stoploss') is not None:
|
||||||
|
# Precalculate sanitized stoploss value to avoid recalculation for every pair
|
||||||
|
stoploss = 1 - abs(self._config.get('stoploss'))
|
||||||
|
# Copy list since we're modifying this list
|
||||||
|
for p in deepcopy(pairlist):
|
||||||
|
ticker = tickers.get(p)
|
||||||
|
# Filter out assets which would not allow setting a stoploss
|
||||||
|
if not ticker or (stoploss and not self._validate_precision_filter(ticker, stoploss)):
|
||||||
|
pairlist.remove(p)
|
||||||
|
continue
|
||||||
|
|
||||||
|
return pairlist
|
||||||
69
freqtrade/pairlist/PriceFilter.py
Normal file
69
freqtrade/pairlist/PriceFilter.py
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
import logging
|
||||||
|
from copy import deepcopy
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
from freqtrade.pairlist.IPairList import IPairList
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class PriceFilter(IPairList):
|
||||||
|
|
||||||
|
def __init__(self, exchange, pairlistmanager, config, pairlistconfig: dict,
|
||||||
|
pairlist_pos: int) -> None:
|
||||||
|
super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos)
|
||||||
|
|
||||||
|
self._low_price_ratio = pairlistconfig.get('low_price_ratio', 0)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def needstickers(self) -> bool:
|
||||||
|
"""
|
||||||
|
Boolean property defining if tickers are necessary.
|
||||||
|
If no Pairlist requries tickers, an empty List is passed
|
||||||
|
as tickers argument to filter_pairlist
|
||||||
|
"""
|
||||||
|
return True
|
||||||
|
|
||||||
|
def short_desc(self) -> str:
|
||||||
|
"""
|
||||||
|
Short whitelist method description - used for startup-messages
|
||||||
|
"""
|
||||||
|
return f"{self.name} - Filtering pairs priced below {self._low_price_ratio * 100}%."
|
||||||
|
|
||||||
|
def _validate_ticker_lowprice(self, ticker) -> bool:
|
||||||
|
"""
|
||||||
|
Check if if one price-step (pip) is > than a certain barrier.
|
||||||
|
:param ticker: ticker dict as returned from ccxt.load_markets()
|
||||||
|
:param precision: Precision
|
||||||
|
:return: True if the pair can stay, false if it should be removed
|
||||||
|
"""
|
||||||
|
precision = self._exchange.markets[ticker['symbol']]['precision']['price']
|
||||||
|
|
||||||
|
compare = ticker['last'] + 1 / pow(10, precision)
|
||||||
|
changeperc = (compare - ticker['last']) / ticker['last']
|
||||||
|
if changeperc > self._low_price_ratio:
|
||||||
|
logger.info(f"Removed {ticker['symbol']} from whitelist, "
|
||||||
|
f"because 1 unit is {changeperc * 100:.3f}%")
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
|
||||||
|
|
||||||
|
"""
|
||||||
|
Filters and sorts pairlist and returns the whitelist again.
|
||||||
|
Called on each bot iteration - please use internal caching if necessary
|
||||||
|
:param pairlist: pairlist to filter or sort
|
||||||
|
:param tickers: Tickers (from exchange.get_tickers()). May be cached.
|
||||||
|
:return: new whitelist
|
||||||
|
"""
|
||||||
|
# Copy list since we're modifying this list
|
||||||
|
for p in deepcopy(pairlist):
|
||||||
|
ticker = tickers.get(p)
|
||||||
|
if not ticker:
|
||||||
|
pairlist.remove(p)
|
||||||
|
|
||||||
|
# Filter out assets which would not allow setting a stoploss
|
||||||
|
if self._low_price_ratio and not self._validate_ticker_lowprice(ticker):
|
||||||
|
pairlist.remove(p)
|
||||||
|
|
||||||
|
return pairlist
|
||||||
@@ -5,6 +5,7 @@ Provides lists as configured in config.json
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
from freqtrade.pairlist.IPairList import IPairList
|
from freqtrade.pairlist.IPairList import IPairList
|
||||||
|
|
||||||
@@ -13,18 +14,28 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
class StaticPairList(IPairList):
|
class StaticPairList(IPairList):
|
||||||
|
|
||||||
def __init__(self, freqtrade, config: dict) -> None:
|
@property
|
||||||
super().__init__(freqtrade, config)
|
def needstickers(self) -> bool:
|
||||||
|
"""
|
||||||
|
Boolean property defining if tickers are necessary.
|
||||||
|
If no Pairlist requries tickers, an empty List is passed
|
||||||
|
as tickers argument to filter_pairlist
|
||||||
|
"""
|
||||||
|
return False
|
||||||
|
|
||||||
def short_desc(self) -> str:
|
def short_desc(self) -> str:
|
||||||
"""
|
"""
|
||||||
Short whitelist method description - used for startup-messages
|
Short whitelist method description - used for startup-messages
|
||||||
-> Please overwrite in subclasses
|
-> Please overwrite in subclasses
|
||||||
"""
|
"""
|
||||||
return f"{self.name}: {self.whitelist}"
|
return f"{self.name}"
|
||||||
|
|
||||||
def refresh_pairlist(self) -> None:
|
def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Refreshes pairlists and assigns them to self._whitelist and self._blacklist respectively
|
Filters and sorts pairlist and returns the whitelist again.
|
||||||
|
Called on each bot iteration - please use internal caching if necessary
|
||||||
|
:param pairlist: pairlist to filter or sort
|
||||||
|
:param tickers: Tickers (from exchange.get_tickers()). May be cached.
|
||||||
|
:return: new whitelist
|
||||||
"""
|
"""
|
||||||
self._whitelist = self._validate_whitelist(self._config['exchange']['pair_whitelist'])
|
return self._whitelist_for_active_markets(self._config['exchange']['pair_whitelist'])
|
||||||
|
|||||||
@@ -5,11 +5,12 @@ Provides lists as configured in config.json
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
from typing import List
|
from datetime import datetime
|
||||||
from cachetools import TTLCache, cached
|
from typing import Dict, List
|
||||||
|
|
||||||
from freqtrade.pairlist.IPairList import IPairList
|
|
||||||
from freqtrade import OperationalException
|
from freqtrade import OperationalException
|
||||||
|
from freqtrade.pairlist.IPairList import IPairList
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
SORT_VALUES = ['askVolume', 'bidVolume', 'quoteVolume']
|
SORT_VALUES = ['askVolume', 'bidVolume', 'quoteVolume']
|
||||||
@@ -17,18 +18,19 @@ SORT_VALUES = ['askVolume', 'bidVolume', 'quoteVolume']
|
|||||||
|
|
||||||
class VolumePairList(IPairList):
|
class VolumePairList(IPairList):
|
||||||
|
|
||||||
def __init__(self, freqtrade, config: dict) -> None:
|
def __init__(self, exchange, pairlistmanager, config, pairlistconfig: dict,
|
||||||
super().__init__(freqtrade, config)
|
pairlist_pos: int) -> None:
|
||||||
self._whitelistconf = self._config.get('pairlist', {}).get('config')
|
super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos)
|
||||||
if 'number_assets' not in self._whitelistconf:
|
|
||||||
|
if 'number_assets' not in self._pairlistconfig:
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f'`number_assets` not specified. Please check your configuration '
|
f'`number_assets` not specified. Please check your configuration '
|
||||||
'for "pairlist.config.number_assets"')
|
'for "pairlist.config.number_assets"')
|
||||||
self._number_pairs = self._whitelistconf['number_assets']
|
self._number_pairs = self._pairlistconfig['number_assets']
|
||||||
self._sort_key = self._whitelistconf.get('sort_key', 'quoteVolume')
|
self._sort_key = self._pairlistconfig.get('sort_key', 'quoteVolume')
|
||||||
self._precision_filter = self._whitelistconf.get('precision_filter', False)
|
self.refresh_period = self._pairlistconfig.get('refresh_period', 1800)
|
||||||
|
|
||||||
if not self._freqtrade.exchange.exchange_has('fetchTickers'):
|
if not self._exchange.exchange_has('fetchTickers'):
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
'Exchange does not support dynamic whitelist.'
|
'Exchange does not support dynamic whitelist.'
|
||||||
'Please edit your config and restart the bot'
|
'Please edit your config and restart the bot'
|
||||||
@@ -36,6 +38,16 @@ class VolumePairList(IPairList):
|
|||||||
if not self._validate_keys(self._sort_key):
|
if not self._validate_keys(self._sort_key):
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f'key {self._sort_key} not in {SORT_VALUES}')
|
f'key {self._sort_key} not in {SORT_VALUES}')
|
||||||
|
self._last_refresh = 0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def needstickers(self) -> bool:
|
||||||
|
"""
|
||||||
|
Boolean property defining if tickers are necessary.
|
||||||
|
If no Pairlist requries tickers, an empty List is passed
|
||||||
|
as tickers argument to filter_pairlist
|
||||||
|
"""
|
||||||
|
return True
|
||||||
|
|
||||||
def _validate_keys(self, key):
|
def _validate_keys(self, key):
|
||||||
return key in SORT_VALUES
|
return key in SORT_VALUES
|
||||||
@@ -43,53 +55,54 @@ class VolumePairList(IPairList):
|
|||||||
def short_desc(self) -> str:
|
def short_desc(self) -> str:
|
||||||
"""
|
"""
|
||||||
Short whitelist method description - used for startup-messages
|
Short whitelist method description - used for startup-messages
|
||||||
-> Please overwrite in subclasses
|
|
||||||
"""
|
"""
|
||||||
return f"{self.name} - top {self._whitelistconf['number_assets']} volume pairs."
|
return f"{self.name} - top {self._pairlistconfig['number_assets']} volume pairs."
|
||||||
|
|
||||||
def refresh_pairlist(self) -> None:
|
def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Refreshes pairlists and assigns them to self._whitelist and self._blacklist respectively
|
Filters and sorts pairlist and returns the whitelist again.
|
||||||
-> Please overwrite in subclasses
|
Called on each bot iteration - please use internal caching if necessary
|
||||||
|
:param pairlist: pairlist to filter or sort
|
||||||
|
:param tickers: Tickers (from exchange.get_tickers()). May be cached.
|
||||||
|
:return: new whitelist
|
||||||
"""
|
"""
|
||||||
# Generate dynamic whitelist
|
# Generate dynamic whitelist
|
||||||
self._whitelist = self._gen_pair_whitelist(
|
if self._last_refresh + self.refresh_period < datetime.now().timestamp():
|
||||||
self._config['stake_currency'], self._sort_key)[:self._number_pairs]
|
self._last_refresh = int(datetime.now().timestamp())
|
||||||
logger.info(f"Searching pairs: {self._whitelist}")
|
return self._gen_pair_whitelist(pairlist,
|
||||||
|
tickers,
|
||||||
|
self._config['stake_currency'],
|
||||||
|
self._sort_key,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
return pairlist
|
||||||
|
|
||||||
@cached(TTLCache(maxsize=1, ttl=1800))
|
def _gen_pair_whitelist(self, pairlist, tickers, base_currency: str, key: str) -> List[str]:
|
||||||
def _gen_pair_whitelist(self, base_currency: str, key: str) -> List[str]:
|
|
||||||
"""
|
"""
|
||||||
Updates the whitelist with with a dynamically generated list
|
Updates the whitelist with with a dynamically generated list
|
||||||
:param base_currency: base currency as str
|
:param base_currency: base currency as str
|
||||||
:param key: sort key (defaults to 'quoteVolume')
|
:param key: sort key (defaults to 'quoteVolume')
|
||||||
|
:param tickers: Tickers (from exchange.get_tickers()).
|
||||||
:return: List of pairs
|
:return: List of pairs
|
||||||
"""
|
"""
|
||||||
|
|
||||||
tickers = self._freqtrade.exchange.get_tickers()
|
if self._pairlist_pos == 0:
|
||||||
|
# If VolumePairList is the first in the list, use fresh pairlist
|
||||||
# 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()
|
filtered_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)]
|
and v[key] is not None)]
|
||||||
sorted_tickers = sorted(tickers, reverse=True, key=lambda t: t[key])
|
else:
|
||||||
|
# If other pairlist is in front, use the incomming pairlist.
|
||||||
|
filtered_tickers = [v for k, v in tickers.items() if k in pairlist]
|
||||||
|
|
||||||
|
sorted_tickers = sorted(filtered_tickers, reverse=True, key=lambda t: t[key])
|
||||||
|
|
||||||
# Validate whitelist to only have active market pairs
|
# Validate whitelist to only have active market pairs
|
||||||
valid_pairs = self._validate_whitelist([s['symbol'] for s in sorted_tickers])
|
pairs = self._whitelist_for_active_markets([s['symbol'] for s in sorted_tickers])
|
||||||
valid_tickers = [t for t in sorted_tickers if t["symbol"] in valid_pairs]
|
pairs = self._verify_blacklist(pairs)
|
||||||
|
# Limit to X number of pairs
|
||||||
|
pairs = pairs[:self._number_pairs]
|
||||||
|
logger.info(f"Searching {self._number_pairs} pairs: {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]
|
|
||||||
return pairs
|
return pairs
|
||||||
|
|||||||
95
freqtrade/pairlist/pairlistmanager.py
Normal file
95
freqtrade/pairlist/pairlistmanager.py
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
"""
|
||||||
|
Static List provider
|
||||||
|
|
||||||
|
Provides lists as configured in config.json
|
||||||
|
|
||||||
|
"""
|
||||||
|
from cachetools import TTLCache, cached
|
||||||
|
import logging
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
from freqtrade import OperationalException
|
||||||
|
from freqtrade.pairlist.IPairList import IPairList
|
||||||
|
from freqtrade.resolvers import PairListResolver
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class PairListManager():
|
||||||
|
|
||||||
|
def __init__(self, exchange, config: dict) -> None:
|
||||||
|
self._exchange = exchange
|
||||||
|
self._config = config
|
||||||
|
self._whitelist = self._config['exchange'].get('pair_whitelist')
|
||||||
|
self._blacklist = self._config['exchange'].get('pair_blacklist', [])
|
||||||
|
self._pairlists: List[IPairList] = []
|
||||||
|
self._tickers_needed = False
|
||||||
|
for pl in self._config.get('pairlists', None):
|
||||||
|
if 'method' not in pl:
|
||||||
|
logger.warning(f"No method in {pl}")
|
||||||
|
continue
|
||||||
|
pairl = PairListResolver(pl.get('method'),
|
||||||
|
exchange=exchange,
|
||||||
|
pairlistmanager=self,
|
||||||
|
config=config,
|
||||||
|
pairlistconfig=pl,
|
||||||
|
pairlist_pos=len(self._pairlists)
|
||||||
|
).pairlist
|
||||||
|
self._tickers_needed = pairl.needstickers or self._tickers_needed
|
||||||
|
self._pairlists.append(pairl)
|
||||||
|
|
||||||
|
if not self._pairlists:
|
||||||
|
raise OperationalException("No Pairlist defined!")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def whitelist(self) -> List[str]:
|
||||||
|
"""
|
||||||
|
Has the current whitelist
|
||||||
|
"""
|
||||||
|
return self._whitelist
|
||||||
|
|
||||||
|
@property
|
||||||
|
def blacklist(self) -> List[str]:
|
||||||
|
"""
|
||||||
|
Has the current blacklist
|
||||||
|
-> no need to overwrite in subclasses
|
||||||
|
"""
|
||||||
|
return self._blacklist
|
||||||
|
|
||||||
|
@property
|
||||||
|
def name_list(self) -> List[str]:
|
||||||
|
"""
|
||||||
|
Get list of loaded pairlists names
|
||||||
|
"""
|
||||||
|
return [p.name for p in self._pairlists]
|
||||||
|
|
||||||
|
def short_desc(self) -> List[Dict]:
|
||||||
|
"""
|
||||||
|
List of short_desc for each pairlist
|
||||||
|
"""
|
||||||
|
return [{p.name: p.short_desc()} for p in self._pairlists]
|
||||||
|
|
||||||
|
@cached(TTLCache(maxsize=1, ttl=1800))
|
||||||
|
def _get_cached_tickers(self):
|
||||||
|
return self._exchange.get_tickers()
|
||||||
|
|
||||||
|
def refresh_pairlist(self) -> None:
|
||||||
|
"""
|
||||||
|
Run pairlist through all configured pairlists.
|
||||||
|
"""
|
||||||
|
|
||||||
|
pairlist = self._whitelist.copy()
|
||||||
|
|
||||||
|
# tickers should be cached to avoid calling the exchange on each call.
|
||||||
|
tickers: Dict = {}
|
||||||
|
if self._tickers_needed:
|
||||||
|
tickers = self._get_cached_tickers()
|
||||||
|
|
||||||
|
# Process all pairlists in chain
|
||||||
|
for pl in self._pairlists:
|
||||||
|
pairlist = pl.filter_pairlist(pairlist, tickers)
|
||||||
|
|
||||||
|
# Validation against blacklist happens after the pairlists to ensure blacklist is respected.
|
||||||
|
pairlist = IPairList.verify_blacklist(pairlist, self.blacklist)
|
||||||
|
|
||||||
|
self._whitelist = pairlist
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
"""
|
"""
|
||||||
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
|
||||||
@@ -9,18 +8,19 @@ 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,
|
||||||
create_engine, inspect)
|
create_engine, desc, func, inspect)
|
||||||
from sqlalchemy.exc import NoSuchModuleError
|
from sqlalchemy.exc import NoSuchModuleError
|
||||||
from sqlalchemy.ext.declarative import declarative_base
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
|
from sqlalchemy.orm import Query
|
||||||
from sqlalchemy.orm.scoping import scoped_session
|
from sqlalchemy.orm.scoping import scoped_session
|
||||||
from sqlalchemy.orm.session import sessionmaker
|
from sqlalchemy.orm.session import sessionmaker
|
||||||
from sqlalchemy import func
|
|
||||||
from sqlalchemy.pool import StaticPool
|
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'
|
||||||
|
|
||||||
@@ -48,12 +48,14 @@ def init(db_url: str, clean_open_orders: bool = False) -> 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))
|
# https://docs.sqlalchemy.org/en/13/orm/contextual.html#thread-local-scope
|
||||||
Trade.session = session()
|
# Scoped sessions proxy requests to the appropriate thread-local session.
|
||||||
Trade.query = session.query_property()
|
# We should use the scoped_session object - not a seperately initialized version
|
||||||
|
Trade.session = scoped_session(sessionmaker(bind=engine, autoflush=True, autocommit=True))
|
||||||
|
Trade.query = Trade.session.query_property()
|
||||||
_DECL_BASE.metadata.create_all(engine)
|
_DECL_BASE.metadata.create_all(engine)
|
||||||
check_migrate(engine)
|
check_migrate(engine)
|
||||||
|
|
||||||
@@ -209,7 +211,7 @@ class Trade(_DECL_BASE):
|
|||||||
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})')
|
||||||
@@ -250,7 +252,6 @@ class Trade(_DECL_BASE):
|
|||||||
:param initial: Called to initiate stop_loss.
|
:param initial: Called to initiate stop_loss.
|
||||||
Skips everything if self.stop_loss is already set.
|
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
|
||||||
@@ -259,7 +260,7 @@ class Trade(_DECL_BASE):
|
|||||||
|
|
||||||
# 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.stop_loss_pct = -1 * abs(stoploss)
|
||||||
self.initial_stop_loss = new_loss
|
self.initial_stop_loss = new_loss
|
||||||
@@ -269,21 +270,20 @@ class Trade(_DECL_BASE):
|
|||||||
# 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.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:
|
||||||
"""
|
"""
|
||||||
@@ -331,23 +331,18 @@ 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,
|
|
||||||
rate: Optional[float] = None,
|
|
||||||
fee: Optional[float] = None) -> float:
|
fee: Optional[float] = None) -> float:
|
||||||
"""
|
"""
|
||||||
Calculate the close_rate including fee
|
Calculate the close_rate including fee
|
||||||
@@ -357,7 +352,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
|
||||||
|
|
||||||
@@ -365,9 +359,7 @@ 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,
|
|
||||||
rate: Optional[float] = None,
|
|
||||||
fee: Optional[float] = None) -> float:
|
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
|
||||||
@@ -385,9 +377,7 @@ 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,
|
|
||||||
rate: Optional[float] = None,
|
|
||||||
fee: Optional[float] = None) -> float:
|
fee: Optional[float] = None) -> float:
|
||||||
"""
|
"""
|
||||||
Calculates the profit in percentage (including fee).
|
Calculates the profit in percentage (including fee).
|
||||||
@@ -396,7 +386,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),
|
||||||
@@ -405,6 +394,37 @@ class Trade(_DECL_BASE):
|
|||||||
profit_percent = (close_trade_price / open_trade_price) - 1
|
profit_percent = (close_trade_price / open_trade_price) - 1
|
||||||
return float(f"{profit_percent:.8f}")
|
return float(f"{profit_percent:.8f}")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_trades(trade_filter=None) -> Query:
|
||||||
|
"""
|
||||||
|
Helper function to query Trades using filters.
|
||||||
|
:param trade_filter: Optional filter to apply to trades
|
||||||
|
Can be either a Filter object, or a List of filters
|
||||||
|
e.g. `(trade_filter=[Trade.id == trade_id, Trade.is_open.is_(True),])`
|
||||||
|
e.g. `(trade_filter=Trade.id == trade_id)`
|
||||||
|
:return: unsorted query object
|
||||||
|
"""
|
||||||
|
if trade_filter is not None:
|
||||||
|
if not isinstance(trade_filter, list):
|
||||||
|
trade_filter = [trade_filter]
|
||||||
|
return Trade.query.filter(*trade_filter)
|
||||||
|
else:
|
||||||
|
return Trade.query
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_open_trades() -> List[Any]:
|
||||||
|
"""
|
||||||
|
Query trades from persistence layer
|
||||||
|
"""
|
||||||
|
return Trade.get_trades(Trade.is_open.is_(True)).all()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_open_order_trades():
|
||||||
|
"""
|
||||||
|
Returns all open trades
|
||||||
|
"""
|
||||||
|
return Trade.get_trades(Trade.open_order_id.isnot(None)).all()
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def total_open_trades_stakes() -> float:
|
def total_open_trades_stakes() -> float:
|
||||||
"""
|
"""
|
||||||
@@ -417,11 +437,38 @@ class Trade(_DECL_BASE):
|
|||||||
return total_open_stake_amount or 0
|
return total_open_stake_amount or 0
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_open_trades() -> List[Any]:
|
def get_overall_performance() -> List[Dict[str, Any]]:
|
||||||
"""
|
"""
|
||||||
Query trades from persistence layer
|
Returns List of dicts containing all Trades, including profit and trade count
|
||||||
"""
|
"""
|
||||||
return Trade.query.filter(Trade.is_open.is_(True)).all()
|
pair_rates = Trade.session.query(
|
||||||
|
Trade.pair,
|
||||||
|
func.sum(Trade.close_profit).label('profit_sum'),
|
||||||
|
func.count(Trade.pair).label('count')
|
||||||
|
).filter(Trade.is_open.is_(False))\
|
||||||
|
.group_by(Trade.pair) \
|
||||||
|
.order_by(desc('profit_sum')) \
|
||||||
|
.all()
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
'pair': pair,
|
||||||
|
'profit': rate,
|
||||||
|
'count': count
|
||||||
|
}
|
||||||
|
for pair, rate, count in pair_rates
|
||||||
|
]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_best_pair():
|
||||||
|
"""
|
||||||
|
Get best pair with closed trade.
|
||||||
|
"""
|
||||||
|
best_pair = Trade.session.query(
|
||||||
|
Trade.pair, func.sum(Trade.close_profit).label('profit_sum')
|
||||||
|
).filter(Trade.is_open.is_(False)) \
|
||||||
|
.group_by(Trade.pair) \
|
||||||
|
.order_by(desc('profit_sum')).first()
|
||||||
|
return best_pair
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def stoploss_reinitialization(desired_stoploss):
|
def stoploss_reinitialization(desired_stoploss):
|
||||||
@@ -436,8 +483,8 @@ class Trade(_DECL_BASE):
|
|||||||
and trade.initial_stop_loss_pct != desired_stoploss):
|
and trade.initial_stop_loss_pct != desired_stoploss):
|
||||||
# Stoploss value got changed
|
# Stoploss value got changed
|
||||||
|
|
||||||
logger.info(f"Stoploss for {trade} needs adjustment.")
|
logger.info(f"Stoploss for {trade} needs adjustment...")
|
||||||
# Force reset of stoploss
|
# Force reset of stoploss
|
||||||
trade.stop_loss = None
|
trade.stop_loss = None
|
||||||
trade.adjust_stop_loss(trade.open_rate, desired_stoploss)
|
trade.adjust_stop_loss(trade.open_rate, desired_stoploss)
|
||||||
logger.info(f"new stoploss: {trade.stop_loss}, ")
|
logger.info(f"New stoploss: {trade.stop_loss}.")
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user