Compare commits
1260 Commits
2022.7
...
add-spice-
Author | SHA1 | Date | |
---|---|---|---|
|
ecdb466887 | ||
|
011759d1b7 | ||
|
7cdd510cf9 | ||
|
1e5df9611b | ||
|
f3dcbb9736 | ||
|
06f4f2db0a | ||
|
d362332527 | ||
|
e337d4b78a | ||
|
bc09c812a8 | ||
|
0460f362fb | ||
|
d42fb15608 | ||
|
a5bf34587a | ||
|
fab6b2f105 | ||
|
1cabfe8d0a | ||
|
1595e5fd8a | ||
|
b92b98af29 | ||
|
3e08c6e540 | ||
|
6e179c7699 | ||
|
7c702dd106 | ||
|
92a1d58df8 | ||
|
f475c6c305 | ||
|
638515bce5 | ||
|
678272e2ef | ||
|
cea017e79f | ||
|
b7f26e4f96 | ||
|
02e238a944 | ||
|
edb942f662 | ||
|
9b1fb02df8 | ||
|
b0eff4160f | ||
|
7dbb78da95 | ||
|
0d67afe15b | ||
|
4edb30bfa8 | ||
|
0e0bda8f13 | ||
|
22043deffa | ||
|
ca913fb29d | ||
|
4df533feb0 | ||
|
a1a598dcab | ||
|
5019300d5c | ||
|
3264d7b890 | ||
|
c1d8ade2fa | ||
|
68db0bc647 | ||
|
a6296be2f5 | ||
|
eb8eebe492 | ||
|
016e438468 | ||
|
bc6729f724 | ||
|
7f308c5186 | ||
|
7f475e37d7 | ||
|
dc5c3a0ed2 | ||
|
4c83552f3b | ||
|
f0c04212f2 | ||
|
ca22d857b7 | ||
|
3585742b43 | ||
|
74277c7eff | ||
|
265795824b | ||
|
c2d0eca9d8 | ||
|
6ecd92de4a | ||
|
3921615023 | ||
|
ac7df58447 | ||
|
a78d6a05a6 | ||
|
616d69e0bd | ||
|
ae0a39521b | ||
|
3c789bca63 | ||
|
0af124701b | ||
|
4cf4642a6c | ||
|
f3d4c56b3b | ||
|
6defa62297 | ||
|
9691524ade | ||
|
a6bc00501f | ||
|
373132e135 | ||
|
70d6c27e3e | ||
|
0a7e4d6da5 | ||
|
f722104f7e | ||
|
6f7b75d4b0 | ||
|
b70f18f4c3 | ||
|
1727f99b58 | ||
|
21440eaec2 | ||
|
d0b8c8b1a0 | ||
|
a5bc75b48c | ||
|
e686faf1bc | ||
|
9bb061073d | ||
|
308fa43007 | ||
|
564318415e | ||
|
2c94ed2e59 | ||
|
3e34f10e3d | ||
|
84b822dbf1 | ||
|
f4c6b99d63 | ||
|
cd514cf15d | ||
|
f2b875483f | ||
|
51556e08c3 | ||
|
6702a1b219 | ||
|
8f8b5cc28e | ||
|
201bbbcee6 | ||
|
a96aa568bf | ||
|
545d652352 | ||
|
fad9026939 | ||
|
cdc01a0781 | ||
|
47ef99f588 | ||
|
819488c906 | ||
|
c946d30596 | ||
|
649879192b | ||
|
d462f40299 | ||
|
bd664580fb | ||
|
cc06c60fd8 | ||
|
0d8dfc1a92 | ||
|
f6a0d677d2 | ||
|
7dd984e25e | ||
|
561600e98b | ||
|
2d2ff2fff6 | ||
|
2ce265bed3 | ||
|
34951f59d2 | ||
|
be48131185 | ||
|
38aca8e908 | ||
|
578da343dc | ||
|
b4fb28e4ef | ||
|
00965d8c06 | ||
|
80d0e66b48 | ||
|
388a572cb3 | ||
|
ac229b7a42 | ||
|
4e920e9c53 | ||
|
772abfc6f0 | ||
|
683b084323 | ||
|
fb3d408338 | ||
|
e9abe3cb68 | ||
|
7e124618d4 | ||
|
7c84edbc23 | ||
|
a06372c7b2 | ||
|
42cecb83f2 | ||
|
e668bf7138 | ||
|
255c748ca2 | ||
|
30a5bb08dd | ||
|
8eda3a45a3 | ||
|
6c491ee02e | ||
|
895b15abbc | ||
|
24c1d84982 | ||
|
9d462af047 | ||
|
8c2e473ee5 | ||
|
43e847ff2f | ||
|
bc007ce038 | ||
|
ba8c714698 | ||
|
853a4d1014 | ||
|
eb36105de4 | ||
|
cf5267a4d3 | ||
|
9f32e02bba | ||
|
4faa6a0bd7 | ||
|
3d72168c01 | ||
|
d493b2b7e7 | ||
|
5477966cb6 | ||
|
32930a269e | ||
|
8e0811d9de | ||
|
cde1d1c2b3 | ||
|
ed2c960a93 | ||
|
a1a62681bf | ||
|
041258a549 | ||
|
ecb41ff9aa | ||
|
965f8ff39b | ||
|
8ef3a41a0e | ||
|
b90513d676 | ||
|
c4784c6695 | ||
|
5faaa25faf | ||
|
95a2d43e1a | ||
|
a38f47e1a5 | ||
|
e54ed5b10e | ||
|
760f3f157d | ||
|
c31f322349 | ||
|
f5535e780c | ||
|
117e510e61 | ||
|
8051235171 | ||
|
48e89e68b9 | ||
|
e53f0ce897 | ||
|
af59572cb9 | ||
|
adb5b98a3d | ||
|
0e7ec182a3 | ||
|
677c5719bf | ||
|
02dba5304b | ||
|
aca03e38f6 | ||
|
873d2a5069 | ||
|
bd106b4b8e | ||
|
1bb45a2650 | ||
|
30d51b6939 | ||
|
1c089dcd51 | ||
|
527fd36134 | ||
|
4940fa7be3 | ||
|
0c810868de | ||
|
f4fac53a13 | ||
|
96336cb552 | ||
|
873eb5f2ca | ||
|
1bd742f7e9 | ||
|
585342f193 | ||
|
e63f9e1c14 | ||
|
8d77ba118c | ||
|
50dfde7048 | ||
|
53c8e0923f | ||
|
166ae8e3a1 | ||
|
98ba57ffaa | ||
|
4efe2e9bc4 | ||
|
00b192b4df | ||
|
2cc00a1a2c | ||
|
e429aa16f3 | ||
|
6643d90e64 | ||
|
5d27d5689f | ||
|
d9c8e7157b | ||
|
af974443cd | ||
|
6b5d71049e | ||
|
4c7cef570f | ||
|
b8e1d29a1b | ||
|
cf05f374cf | ||
|
255ff000af | ||
|
2fffe7c5dd | ||
|
7c093388e7 | ||
|
4576d291a9 | ||
|
7e1e388b9c | ||
|
48352b8a37 | ||
|
0bbb6faeba | ||
|
a4eaff4da6 | ||
|
5fb56b09f2 | ||
|
983a16d937 | ||
|
044891f543 | ||
|
dc2b93228b | ||
|
3c0d2c446d | ||
|
7b4af85425 | ||
|
f62f2bb1ca | ||
|
2a5bc58df8 | ||
|
1db8421b9d | ||
|
b7c60e810a | ||
|
06a5cfa401 | ||
|
1626eb7f97 | ||
|
e6c5c22ea0 | ||
|
71e6c54ea4 | ||
|
b1dbc3a65f | ||
|
3e1e530aca | ||
|
6a6ae809f4 | ||
|
77ed713232 | ||
|
128b117af6 | ||
|
0811bca8b4 | ||
|
91dc5e7aa6 | ||
|
08e183fb55 | ||
|
366c6c24d8 | ||
|
923182680e | ||
|
f7b8c5a767 | ||
|
02f2096fc3 | ||
|
8f41f943b4 | ||
|
ff36431680 | ||
|
3b0874eb37 | ||
|
0c01b23cba | ||
|
0bd6ad55a1 | ||
|
8a91c8e220 | ||
|
6c18fa0847 | ||
|
914eccecec | ||
|
3274bb0751 | ||
|
b5fd11f91b | ||
|
32d46e8a6b | ||
|
703bcc099a | ||
|
eb9ac9cbda | ||
|
a023ac26f3 | ||
|
42c75b4a7b | ||
|
9b66297cc0 | ||
|
995396c775 | ||
|
ad652817ef | ||
|
f9460c80c2 | ||
|
ea58c29ded | ||
|
225f7cd5f8 | ||
|
2c4137e5ca | ||
|
ec7642febf | ||
|
4a0a0c307c | ||
|
d930931000 | ||
|
1d0e686cd4 | ||
|
cc89b4127a | ||
|
b5f51b5ec2 | ||
|
613ad8cb31 | ||
|
15c9b6bf41 | ||
|
cbdb0ce3e7 | ||
|
f512717943 | ||
|
4cdc89706e | ||
|
8b1e5daf22 | ||
|
8116ca847b | ||
|
a06eee300a | ||
|
584b2381d1 | ||
|
9e01ff5a72 | ||
|
7b390b8edb | ||
|
470d5d8405 | ||
|
eaa43337d2 | ||
|
edbe9137da | ||
|
95457d23ca | ||
|
994c1c5ea0 | ||
|
667853c504 | ||
|
91e2a05aff | ||
|
793c54db9d | ||
|
188f75d8ec | ||
|
27c46300a7 | ||
|
9f23588154 | ||
|
7a73adb955 | ||
|
faf84295a5 | ||
|
ab78fb373a | ||
|
4634936265 | ||
|
fa3d4b58ab | ||
|
bdeb2f9c6a | ||
|
1ef875901a | ||
|
68f7a31504 | ||
|
2c23effbf2 | ||
|
b1e92933f4 | ||
|
1c92734f39 | ||
|
c210d6614c | ||
|
12a9fda885 | ||
|
92a32ab31b | ||
|
063511826c | ||
|
9f266cbcb2 | ||
|
ca6dec3d4c | ||
|
8639c1f23d | ||
|
93237efc15 | ||
|
a7312dec03 | ||
|
ff300d5c85 | ||
|
38b28fc4da | ||
|
4182a7891a | ||
|
6682ae35b3 | ||
|
10ec681b30 | ||
|
d62cef01be | ||
|
0aada271ca | ||
|
4422ac7f45 | ||
|
86aa875bc9 | ||
|
b707a6da35 | ||
|
e5368f5a14 | ||
|
b0b575ead9 | ||
|
1ad25095c1 | ||
|
efaef68ad7 | ||
|
7d1645ac20 | ||
|
4d93a6b757 | ||
|
dac07c5609 | ||
|
fb2d190865 | ||
|
b209490009 | ||
|
8e75852ff3 | ||
|
6126925dbe | ||
|
711849abd6 | ||
|
8a236c3c4f | ||
|
91bc3d1161 | ||
|
49800e4cc3 | ||
|
aed19ff6ce | ||
|
37dd22c89e | ||
|
06350a13cb | ||
|
d75d5a7dad | ||
|
7a98775f01 | ||
|
46a425d1b6 | ||
|
7b6e465d57 | ||
|
877d24bcdd | ||
|
d2abc9417f | ||
|
79c70bd52d | ||
|
aeaca78940 | ||
|
07aa206f71 | ||
|
6d0dfd4dc8 | ||
|
75ce9067dc | ||
|
26441820a9 | ||
|
bf2e5dee75 | ||
|
12a3e90f78 | ||
|
0697041f14 | ||
|
c19a5fbe06 | ||
|
b6434040de | ||
|
867d59b930 | ||
|
0052e58917 | ||
|
a477b3c244 | ||
|
10852555e5 | ||
|
fac8f19554 | ||
|
457075b823 | ||
|
d6205e6cfb | ||
|
85b43a7c34 | ||
|
a93e355175 | ||
|
f45824acf5 | ||
|
2599e57fe6 | ||
|
e20ebc99c4 | ||
|
21ed992b78 | ||
|
7ee92db7a2 | ||
|
91b7e152c2 | ||
|
00db473f10 | ||
|
4ac804f795 | ||
|
d3f4d742bb | ||
|
09cdce864e | ||
|
1f11d6091c | ||
|
dae2ee446c | ||
|
715a71465d | ||
|
c149c47afb | ||
|
3c2e0b5ad6 | ||
|
6968fc333b | ||
|
a4b7e0a714 | ||
|
1ef334411e | ||
|
6bfe996061 | ||
|
6777d43aea | ||
|
5483cf21f6 | ||
|
982c0315fa | ||
|
816c1f7603 | ||
|
72d197a99d | ||
|
ede282392f | ||
|
818f7bfc40 | ||
|
68a900a9b7 | ||
|
78cd46ecd5 | ||
|
32e13d65c3 | ||
|
a48923c0e4 | ||
|
9c8c7a03a1 | ||
|
ccc70a21f2 | ||
|
4476b5a7f4 | ||
|
24b35bfb44 | ||
|
d598f4334e | ||
|
0a8b7686d6 | ||
|
ed4ba8801f | ||
|
9a1a4dfb5b | ||
|
0f8eaf98e7 | ||
|
0bc18ea33c | ||
|
330d7068ab | ||
|
075748b21a | ||
|
2afd5c202c | ||
|
5a0cfee27e | ||
|
73e122ad10 | ||
|
c5d031733b | ||
|
a7baccdb7d | ||
|
866a564958 | ||
|
b3fc1cfde9 | ||
|
88892ba663 | ||
|
f97f1dc5c3 | ||
|
e4caccc353 | ||
|
d8cdd92140 | ||
|
311ae8bf1f | ||
|
60eb02bb62 | ||
|
2077f84f9b | ||
|
4a47c63f71 | ||
|
10b6aebc5f | ||
|
daf352e6a5 | ||
|
a1f88cca80 | ||
|
79985fda01 | ||
|
4250174de9 | ||
|
b344f78d00 | ||
|
170bec0438 | ||
|
5705b8759b | ||
|
2f6a61521f | ||
|
05581db4e3 | ||
|
939fb7acb3 | ||
|
97be3318f4 | ||
|
37fcbeba58 | ||
|
826eb85254 | ||
|
c13bec26d1 | ||
|
6cbc03a96a | ||
|
a826c0eb83 | ||
|
acb410a0de | ||
|
df6e43d2c5 | ||
|
1b6410d7d1 | ||
|
09679cc798 | ||
|
d38cc06139 | ||
|
ad96597693 | ||
|
445ab1beee | ||
|
426f8f37e9 | ||
|
e256ebd727 | ||
|
afc17c5ec9 | ||
|
92d71ebdb7 | ||
|
46cd0ce994 | ||
|
1466d2d26f | ||
|
75cf8dbfe4 | ||
|
c5d9180758 | ||
|
bc7295579f | ||
|
c9d4f666c5 | ||
|
2b9c8550b0 | ||
|
b9e7af1ce2 | ||
|
fac6626459 | ||
|
b3b0c918d9 | ||
|
379b1cbc90 | ||
|
df3c126146 | ||
|
9b752475db | ||
|
4104d0f68a | ||
|
4fac125443 | ||
|
83770d20fa | ||
|
883abe5b4f | ||
|
08726a264b | ||
|
5e42defafc | ||
|
9ef0ffe277 | ||
|
791f61c089 | ||
|
b91ad609f2 | ||
|
39b6cadd14 | ||
|
4e15611b05 | ||
|
045c3f0f3a | ||
|
f3417a8690 | ||
|
20bf44a856 | ||
|
a50923f796 | ||
|
f4f2884a66 | ||
|
1ef1fc269e | ||
|
5934495dda | ||
|
bf3ee51167 | ||
|
f8e7ed5d7d | ||
|
a9fd12b816 | ||
|
e51d352777 | ||
|
4c9ac6b7c0 | ||
|
5d338e697c | ||
|
48cadbf933 | ||
|
ea7bdac9ed | ||
|
322f00e3e8 | ||
|
cdc72bf8ca | ||
|
047ded1baa | ||
|
2c9b765953 | ||
|
972b699105 | ||
|
6b7644029c | ||
|
c08c82bc40 | ||
|
3454a52b95 | ||
|
4d69df08dd | ||
|
83d9f3aeba | ||
|
95a33ab2e6 | ||
|
5aba5de20f | ||
|
8bfaf0a998 | ||
|
e0490b3efc | ||
|
8d16dd804d | ||
|
b1c0267449 | ||
|
d7585161b2 | ||
|
55195260e4 | ||
|
97077ba18a | ||
|
dc4a4bdf09 | ||
|
3535aa7724 | ||
|
d44296783e | ||
|
90ec336c70 | ||
|
e83c9b276d | ||
|
f2f811a2fe | ||
|
4b28d0495f | ||
|
98ec84fca6 | ||
|
8597b52e34 | ||
|
1820bc6832 | ||
|
3f3099cbfc | ||
|
38f14349e9 | ||
|
d526dfb171 | ||
|
4dec19de9f | ||
|
4e5153609e | ||
|
3b5c3a366e | ||
|
a0d774fdc4 | ||
|
b949ea301c | ||
|
cd8455ccb7 | ||
|
2c8e5b191b | ||
|
5b826150df | ||
|
1ea703d527 | ||
|
8f261d8edf | ||
|
9fb3517adc | ||
|
689b193240 | ||
|
36e5c18fa6 | ||
|
4628bfa580 | ||
|
545cfdf913 | ||
|
fda0e547f2 | ||
|
949f618d42 | ||
|
9f5642fd97 | ||
|
da183364f2 | ||
|
205ebfc801 | ||
|
8d61ee7dd7 | ||
|
7d48d5cfc6 | ||
|
523f9ebe84 | ||
|
d829dbb177 | ||
|
15383a03e6 | ||
|
48dc1f2d88 | ||
|
f5500350f9 | ||
|
6f6afca027 | ||
|
90fbb79471 | ||
|
3d03856845 | ||
|
af7e4d7bf0 | ||
|
7cc8ac0a34 | ||
|
a035a69a61 | ||
|
52b20fd4b7 | ||
|
c8a9ac900c | ||
|
78d01810ed | ||
|
d43ed186fc | ||
|
8a08f8ff8d | ||
|
07f806a314 | ||
|
1601868854 | ||
|
956ea43e55 | ||
|
ec76214d02 | ||
|
3b5e5fc57b | ||
|
8545d74378 | ||
|
dae3b3d86a | ||
|
16573b19e3 | ||
|
5cfb4154eb | ||
|
63514b0443 | ||
|
c21808ff98 | ||
|
fa8d5b9834 | ||
|
c9be66b5b6 | ||
|
ed4cc18cdd | ||
|
b95b3d8391 | ||
|
0f483ee31f | ||
|
0c6a02687a | ||
|
df50b1928d | ||
|
80b5f035ab | ||
|
599c1c79fb | ||
|
be192fae91 | ||
|
966de19611 | ||
|
af5460cebf | ||
|
05cbcf834c | ||
|
cf917ad2f5 | ||
|
b26126cb57 | ||
|
6a5774b476 | ||
|
a948e51389 | ||
|
5b0b802f31 | ||
|
eb4cd6ba82 | ||
|
dccde88c83 | ||
|
b53791fef2 | ||
|
00f35f4870 | ||
|
11b2bc269e | ||
|
3f8400df10 | ||
|
11fbfd3402 | ||
|
61d5fc0e08 | ||
|
d6e115178a | ||
|
f3c73189d5 | ||
|
ba2eb7cf0f | ||
|
57e9078727 | ||
|
44d3a9140d | ||
|
7bed0450d2 | ||
|
c72a2c26c7 | ||
|
6e8abf8674 | ||
|
3d4497467c | ||
|
3d4ad1de4c | ||
|
865b34cd6f | ||
|
510cf4f305 | ||
|
df51da22ee | ||
|
57ff6f8ac5 | ||
|
13ccd940d5 | ||
|
7ba4fda5d7 | ||
|
a88ffd2c9d | ||
|
4aec2db14d | ||
|
115a901773 | ||
|
ddc45ce2eb | ||
|
346e73dd75 | ||
|
10e0d53860 | ||
|
c9aa09ec89 | ||
|
7e8e29e42d | ||
|
0b8482360f | ||
|
418bd26a80 | ||
|
7f52908e87 | ||
|
a58dd0bbf9 | ||
|
b11742a4c5 | ||
|
d3cb211283 | ||
|
50e2808667 | ||
|
47f7c384fb | ||
|
71846ecbf2 | ||
|
7952e0df25 | ||
|
eee2071e32 | ||
|
efc3b39fb8 | ||
|
93cbfc5f29 | ||
|
62c0a174c8 | ||
|
c54484dad5 | ||
|
db3d972d47 | ||
|
25a7f44856 | ||
|
b7b87c398b | ||
|
27a9f98d5f | ||
|
226fa5d93c | ||
|
56cd80926a | ||
|
f664ebd262 | ||
|
9b5f85b970 | ||
|
ebbb2cc552 | ||
|
a0db6652a7 | ||
|
4def3678b7 | ||
|
8be8a12cc4 | ||
|
40c00d2d8f | ||
|
a01402fa46 | ||
|
d7189847a7 | ||
|
d734f7612f | ||
|
3a7441a27d | ||
|
49dd1c1d49 | ||
|
e9f46f4768 | ||
|
0af4bd2944 | ||
|
e9e872ca20 | ||
|
8b0cfe1236 | ||
|
8c4e68b8eb | ||
|
39a739eadb | ||
|
a44a235b56 | ||
|
6634229cc1 | ||
|
fcb5d1cb5a | ||
|
dd628eb525 | ||
|
1e41c773a0 | ||
|
22b42e91f3 | ||
|
ff3a4995c1 | ||
|
b9f35cadb3 | ||
|
005594c29c | ||
|
59a723aec8 | ||
|
71f7d68783 | ||
|
c61b986c3d | ||
|
104a73025d | ||
|
6686489c06 | ||
|
c3e74e6e8d | ||
|
2b70c3d0c0 | ||
|
05ca673883 | ||
|
fcceb744c5 | ||
|
2b5f067877 | ||
|
9204f01312 | ||
|
86c5ac44e4 | ||
|
a998d6d773 | ||
|
2ef4534fee | ||
|
efe4fd3e24 | ||
|
01126c43f7 | ||
|
753d1b2aad | ||
|
b2d664c63c | ||
|
bb3523f383 | ||
|
e7261cf515 | ||
|
65b552e310 | ||
|
4b7e640f31 | ||
|
53d46a0385 | ||
|
1fd223c815 | ||
|
f2a356a80c | ||
|
6636f17e0f | ||
|
9e48e6a40b | ||
|
205ab26e92 | ||
|
70df037690 | ||
|
3e786a9b8b | ||
|
d474111a65 | ||
|
592373f096 | ||
|
32faad9333 | ||
|
a6d78a8615 | ||
|
fe7108ae75 | ||
|
78b161e14c | ||
|
6036018f35 | ||
|
1b0f37a93c | ||
|
5f38a574ce | ||
|
5ce1c69803 | ||
|
60ba921f56 | ||
|
ac42c0153d | ||
|
96d8882f1e | ||
|
f55d5ffd8c | ||
|
914b6247e4 | ||
|
da87e9cbb3 | ||
|
484b147a89 | ||
|
4fa01548f6 | ||
|
6f5478cc02 | ||
|
015be770c3 | ||
|
93d2f7fc85 | ||
|
7844157a90 | ||
|
6e046884af | ||
|
a784f63e9a | ||
|
ff9ed1abad | ||
|
354d3c0cda | ||
|
eeb177110e | ||
|
70848a258d | ||
|
3958e53aaa | ||
|
dfa7d1fc27 | ||
|
2dc34779d5 | ||
|
f6d832c6d9 | ||
|
87a3115073 | ||
|
085f81ec9e | ||
|
0ec38e0cfd | ||
|
6189aa817c | ||
|
64b0834437 | ||
|
90c03178b1 | ||
|
cdd4745693 | ||
|
1fb2e9558f | ||
|
5b3f031590 | ||
|
4511634f3a | ||
|
738e95b875 | ||
|
b6e8b9df35 | ||
|
52ec0d1046 | ||
|
7563050f17 | ||
|
0da0600836 | ||
|
54ddc1a4c2 | ||
|
aa3da092a0 | ||
|
63efb3ff3e | ||
|
665cf4431d | ||
|
01d45ed12e | ||
|
7b8b73e651 | ||
|
739b68f8fd | ||
|
692c6bf1fd | ||
|
88d6a7fbff | ||
|
9c6b745f06 | ||
|
b44bd0171c | ||
|
b9d48c3278 | ||
|
1389c8f5b6 | ||
|
733f716819 | ||
|
bc359675a2 | ||
|
09f8904545 | ||
|
08ef5ad2d8 | ||
|
1c6f966579 | ||
|
16af10a5bc | ||
|
b7553d20d4 | ||
|
7d84ef2e2c | ||
|
521381ebf0 | ||
|
790534e0f8 | ||
|
cfa5b3f12c | ||
|
277245c69d | ||
|
b420614d65 | ||
|
975bf8fe88 | ||
|
47b3143534 | ||
|
6834db11f3 | ||
|
42eb508515 | ||
|
76a3e97e05 | ||
|
9f6bba40af | ||
|
70a77ba3d9 | ||
|
1fada53ddd | ||
|
85b43ec1a1 | ||
|
fde469a253 | ||
|
075e9b8526 | ||
|
46e8d9a5e4 | ||
|
18fab86431 | ||
|
0461a89348 | ||
|
f70b0bab80 | ||
|
66910bfe63 | ||
|
88dd9920ea | ||
|
5155afb4e7 | ||
|
0c34104e45 | ||
|
9c38c27eed | ||
|
72c34291e3 | ||
|
3983368228 | ||
|
83ca168bb8 | ||
|
c615e1bc62 | ||
|
b9667f50cf | ||
|
e7902bffa0 | ||
|
e0883a4ea0 | ||
|
819bc71941 | ||
|
463cf66881 | ||
|
c8d7c2caac | ||
|
8d182768f9 | ||
|
0b0e7eaf96 | ||
|
24690c1918 | ||
|
3b44dc52e1 | ||
|
ea6bc47d7a | ||
|
5dde011b31 | ||
|
a1e4fbf313 | ||
|
1ac81aa316 | ||
|
c865814a8e | ||
|
4c0fda400f | ||
|
fa89368c02 | ||
|
96d2f61812 | ||
|
b8c1cf0107 | ||
|
15a1c59a91 | ||
|
a73e4f8e41 | ||
|
2fb7a3091d | ||
|
711b6b1a1a | ||
|
a5b438e41e | ||
|
1dd56e35d5 | ||
|
e4b7bcaeab | ||
|
e818797427 | ||
|
c0bdb71810 | ||
|
f2b6ff910f | ||
|
09ee9089fb | ||
|
e6af9a6903 | ||
|
c3f159bd57 | ||
|
22241c55d5 | ||
|
15e85797c2 | ||
|
6c32331740 | ||
|
053ab12ba6 | ||
|
c7e1719215 | ||
|
686b72a82d | ||
|
398b2946b5 | ||
|
490c3a30ed | ||
|
3caf0f9df3 | ||
|
b7b74a430c | ||
|
4ae9b48d89 | ||
|
dba7d7fd65 | ||
|
a0c348cf97 | ||
|
ce892d4cde | ||
|
6fb5fbdd30 | ||
|
bc79027cf4 | ||
|
2581acd75e | ||
|
baa0af68b2 | ||
|
025ff27dd2 | ||
|
96c279f86c | ||
|
4b708caa6a | ||
|
3f6d427084 | ||
|
006b11e5d5 | ||
|
8961b8d560 | ||
|
ad846cdb76 | ||
|
464d99808f | ||
|
d442383a15 | ||
|
a29402ddde | ||
|
3a9ec76c91 | ||
|
a5e96881f4 | ||
|
c08a89378d | ||
|
e7513c96b3 | ||
|
24f1dc4ecc | ||
|
044cf8bb2e | ||
|
22ac291c3a | ||
|
c9c128f781 | ||
|
8d9284a524 | ||
|
7a2b4dbb99 | ||
|
58de20af0f | ||
|
31be707cc8 | ||
|
3e38c1b0bd | ||
|
7d448fd4ac | ||
|
1f192be43b | ||
|
b1b76a2dbe | ||
|
23cc21ce59 | ||
|
61acbf21d0 | ||
|
7075b00e20 | ||
|
7c18ec4053 | ||
|
e09fbe9e53 | ||
|
d36da95941 | ||
|
82ac8cb41f | ||
|
0b92c30abd | ||
|
5aaab75d1c | ||
|
1ac6ec1446 | ||
|
b682fc446e | ||
|
c190d57f1a | ||
|
3918f4abbd | ||
|
3b827ee60a | ||
|
49989012ab | ||
|
f6545ebdb8 | ||
|
e3a5b97b45 | ||
|
9513c39a17 | ||
|
3bcb47d75d | ||
|
902afc2f02 | ||
|
da253f12fe | ||
|
0e61c2d057 | ||
|
df701b5862 | ||
|
2312b86a66 | ||
|
ccc0ad6f64 | ||
|
923f73a516 | ||
|
fb4b73ce89 | ||
|
b427c7ff13 | ||
|
d93bb82193 | ||
|
aa1bf2adbd | ||
|
cc885e25ac | ||
|
de690b0a69 | ||
|
dd4e44931e | ||
|
f7502bcc92 | ||
|
2cae3c42e6 | ||
|
ace9626483 | ||
|
c0d60c63ab | ||
|
ed004236ce | ||
|
e7cb1b7375 | ||
|
91d0c91287 | ||
|
adc8ee88e2 | ||
|
573964b19f | ||
|
53251e7140 | ||
|
ce2c9bf26d | ||
|
736884c5a9 | ||
|
b5c5a95b64 | ||
|
4289c5c684 | ||
|
5a16d5a512 | ||
|
e7de812948 | ||
|
aef086b02e | ||
|
02646a4a08 | ||
|
9a82898d6b | ||
|
77b3b8a134 | ||
|
20b4134787 | ||
|
8a18609be4 | ||
|
0c7d862aae | ||
|
05fb4de68b | ||
|
21649712a9 | ||
|
001b6c087a | ||
|
77b6025f12 | ||
|
71c88244fe | ||
|
97c077171a | ||
|
a45a35f38c | ||
|
7fd3f98ae8 | ||
|
11a2eb6cc5 | ||
|
ea64f43e52 | ||
|
67c722c9c8 | ||
|
e48e82232d | ||
|
0b2104fc7a | ||
|
5182f755f1 | ||
|
6ded2d5b7c | ||
|
d3780b931c | ||
|
d1998f7ed0 | ||
|
eff8cd7ecb | ||
|
daf015d007 | ||
|
82aecc81f3 | ||
|
aaa5349003 | ||
|
78e129034e | ||
|
eb8bde37c1 | ||
|
bfa859e618 | ||
|
5250189f77 | ||
|
47a30047eb | ||
|
b16f57cb0d | ||
|
c172ce1011 | ||
|
45d68222a1 | ||
|
fdc82f8302 | ||
|
f8f1ade163 | ||
|
2687633941 | ||
|
b12dd15f4f | ||
|
07763d0d4f | ||
|
ce8fbbf743 | ||
|
60d782e5c5 | ||
|
a42a060ab5 | ||
|
a3799c4d5d | ||
|
29b7b014e5 | ||
|
db1d367941 | ||
|
26de992d20 | ||
|
05ec5c5e54 | ||
|
9545402452 | ||
|
29e41cc817 | ||
|
7675187c37 | ||
|
cffc769549 | ||
|
c6e121ffb4 | ||
|
a8541d86fb | ||
|
debc73b654 | ||
|
c2a3e2776e | ||
|
987bbb8e12 | ||
|
df4a5a7573 | ||
|
c3d06257be | ||
|
8bf056ca39 | ||
|
51a6b4289f | ||
|
fe1b8515a8 | ||
|
55360b4c08 | ||
|
febd809119 | ||
|
29225e4baf | ||
|
778833f90e | ||
|
95327750dc | ||
|
eae82d0222 | ||
|
95d3009a95 | ||
|
9df10c6b5b | ||
|
ae0d6f63fa | ||
|
87e5460aed | ||
|
895ebbfd18 | ||
|
694bea133b | ||
|
3b90bdf980 | ||
|
d75e0a9820 | ||
|
707a4e7c9e | ||
|
f3154a4313 | ||
|
e9b7e1e600 | ||
|
70dcff3b23 | ||
|
dce16909b4 | ||
|
f82724bbc1 | ||
|
3013282dbf | ||
|
97064a9ce3 | ||
|
79b650258e | ||
|
ed230dd750 | ||
|
372be54252 | ||
|
b4ded59c63 | ||
|
a75fa26caf | ||
|
7a696f58f9 | ||
|
946d4c7cfc | ||
|
4e68626bcb | ||
|
d830105605 | ||
|
153336d424 | ||
|
659870312d | ||
|
cbb05354a8 | ||
|
a4bada3ebe | ||
|
61693f6c8b | ||
|
e6ebc0443e | ||
|
369c6da5d8 | ||
|
15424169ad | ||
|
09e5fb2f55 | ||
|
c2eaa3d2cd | ||
|
bad15f077c | ||
|
dc82675f00 | ||
|
fc31c890e3 | ||
|
d046f0cc5e | ||
|
dba7a7257d | ||
|
845cecd38f | ||
|
4da96bc511 | ||
|
15752ce3c2 | ||
|
ff4cc5d316 | ||
|
9852733ef7 | ||
|
f57ecb1861 | ||
|
8711b7d99f | ||
|
995be90f91 | ||
|
dd8288c090 | ||
|
f22b140782 | ||
|
08d3ac7ef8 | ||
|
59624181bd | ||
|
c84d54b35e | ||
|
efbd83c56d | ||
|
a2a0d35a24 | ||
|
3273881282 | ||
|
f31106dc61 | ||
|
31ddec8348 | ||
|
0adfa4d9ef | ||
|
7bac054668 | ||
|
229e8864bb | ||
|
bc760b7eb2 | ||
|
324e54c015 | ||
|
3f149c4067 | ||
|
ad25a4cb56 | ||
|
fb4e8430cd | ||
|
e213d0ad55 | ||
|
56b17e6f3c | ||
|
55cf378ec2 | ||
|
897f18a8c8 | ||
|
7b105532d1 | ||
|
4abc26b582 | ||
|
c9d46a5237 | ||
|
ab587747fb | ||
|
520ee3f7a1 | ||
|
1885deb632 | ||
|
70b7a254af | ||
|
61c41fd919 | ||
|
88e10f7306 | ||
|
fff39eff9e | ||
|
95f5218ceb | ||
|
f3d46613ee | ||
|
81c1aa3c13 | ||
|
8a3cffcd1b | ||
|
62f7606d2c | ||
|
8fa6e8b4ba | ||
|
c91e23dc50 | ||
|
50d630a155 | ||
|
a1cff377ec | ||
|
c2d6a0e891 | ||
|
3acc869570 | ||
|
36dc9be7aa | ||
|
5559e605b8 | ||
|
40f00196eb | ||
|
accc629e32 | ||
|
98c8a447b2 | ||
|
afcb0bec00 | ||
|
0b21750e76 | ||
|
ac0f484918 | ||
|
3205788bce | ||
|
8033e0bf23 | ||
|
183dec866a | ||
|
e694ea1cfd | ||
|
ca4dd58642 | ||
|
8f86b0deaa | ||
|
e7337728bf | ||
|
c9a6dc88a1 | ||
|
6c5e48dd4f | ||
|
a99c126266 | ||
|
4e5d60fdc9 | ||
|
921a7ef216 | ||
|
286bd0c40b | ||
|
c43935e82a | ||
|
88d769d801 | ||
|
d43c146676 | ||
|
ac2e8d760e | ||
|
9c051958a6 | ||
|
714d9534b6 | ||
|
ed0f8b1189 | ||
|
921f3899f0 | ||
|
41eeb99177 | ||
|
9d184586f1 | ||
|
f6bfd89cef | ||
|
4ef2ed2f1b | ||
|
ca2029a46b | ||
|
4141d165ff | ||
|
ef409dd345 | ||
|
fea63fba12 | ||
|
8ce6b18318 | ||
|
3fc92b1b21 | ||
|
607455919e | ||
|
819cc9c0e4 | ||
|
58b18770e3 | ||
|
2e1061af64 | ||
|
d9acdc9767 | ||
|
4cac67fd66 | ||
|
eda9464d30 | ||
|
bd3a6ba2fe | ||
|
8ac8d53c32 | ||
|
a6077ac7f4 | ||
|
4ff0ef7359 | ||
|
ffb39a5029 | ||
|
106131ff0f | ||
|
93e1410ed9 | ||
|
6c7d02cb18 | ||
|
7dfbd432d1 | ||
|
68bafa9517 | ||
|
051b99791d | ||
|
852706cd6b | ||
|
b35c64b6c0 | ||
|
3599d18ff6 | ||
|
6da7a98857 | ||
|
5e914d5756 | ||
|
f631ae911b | ||
|
61040c9f8e | ||
|
0b0688a91e | ||
|
121edc3e42 | ||
|
c5de0c49e4 | ||
|
4d472a0ea1 | ||
|
c981ad4608 | ||
|
75a248cf42 | ||
|
eb47c74096 | ||
|
d9b79d94e4 | ||
|
66800c7a45 | ||
|
f8f25e36ef | ||
|
15d049cffe | ||
|
cab8f517b4 | ||
|
4b26b6aaec | ||
|
3c2e314ee5 | ||
|
e6c5e737a2 | ||
|
bf19055e53 | ||
|
2451ed8c88 | ||
|
d6b8801f41 | ||
|
e8c0dcf9f3 | ||
|
f2762e3b4b | ||
|
16b4a5b71f | ||
|
15a971346d | ||
|
7d41542f93 | ||
|
fea39254d9 | ||
|
b37c31cc21 | ||
|
4ac6ef2972 | ||
|
ace951bf7e | ||
|
833d25bda0 | ||
|
0b0dd8dd80 | ||
|
7523ed825e | ||
|
9b3b08a2bb | ||
|
bac4ced382 | ||
|
70adf55643 | ||
|
0306f5ca13 | ||
|
45f4f0f603 | ||
|
29d2f59f12 | ||
|
606f18e5c1 | ||
|
5b4c649d43 | ||
|
e229902381 | ||
|
a20651efd8 | ||
|
2f1a2c1cd7 | ||
|
d59eac3321 | ||
|
a79032bf75 | ||
|
3f72263278 | ||
|
cc6cae47ec | ||
|
4eb4753e20 | ||
|
0aa7162055 | ||
|
fe36b08fce | ||
|
ce365eb9e3 | ||
|
4eb29c8810 | ||
|
83dd453723 | ||
|
e54614fa2f | ||
|
2a4d1e2d64 | ||
|
7870a86e9a | ||
|
0bf915054d | ||
|
c5a16e91fb | ||
|
b8f9c3557b | ||
|
891fb87712 | ||
|
65fdebab75 | ||
|
c080571b7a | ||
|
8a501831d6 | ||
|
23c30dbc10 | ||
|
6193205012 | ||
|
ff531c416f | ||
|
d79983c791 | ||
|
7593339c14 | ||
|
b79d4e8876 | ||
|
7486d9d9e2 | ||
|
7ff3258607 | ||
|
35bed842cb | ||
|
58b5abbaa6 | ||
|
31ae2b3060 | ||
|
255d35976e | ||
|
059c285425 | ||
|
b0d2d13eb1 | ||
|
e1c068ca66 | ||
|
dede128648 | ||
|
ee3cdd0ffe | ||
|
3587bd82e1 | ||
|
af0cc21af9 | ||
|
42d95af829 | ||
|
c5ecf94177 | ||
|
1fae6c9ef7 | ||
|
67eb94c69d | ||
|
89eacf2f47 | ||
|
c708dd3186 | ||
|
c81b960791 | ||
|
db66b82f6f | ||
|
d1d451c27e | ||
|
8664e8f9a3 | ||
|
80dcd88abf | ||
|
9e94d28860 | ||
|
e5759d950b | ||
|
f4296173e9 | ||
|
717df891b1 | ||
|
a8022c104a | ||
|
a7029e35b5 | ||
|
9b3e5faebe | ||
|
22bd5556ed | ||
|
178c2014b0 | ||
|
a4f5811a5b | ||
|
aae233bd6c | ||
|
f653ace24b | ||
|
b08c0888bb | ||
|
b03c7b514d | ||
|
e9a7b68bc1 | ||
|
3020218096 | ||
|
00ff0c9b91 | ||
|
66715c5ba4 | ||
|
def71a0afe | ||
|
764f9449b4 | ||
|
29c2d1d189 | ||
|
99f7e44c30 | ||
|
2600ba4e74 | ||
|
630d201546 | ||
|
b40f8f88ac | ||
|
fc837c4daa |
41
.github/workflows/ci.yml
vendored
@@ -24,7 +24,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ ubuntu-18.04, ubuntu-20.04, ubuntu-22.04 ]
|
||||
python-version: ["3.8", "3.9", "3.10"]
|
||||
python-version: ["3.8", "3.9", "3.10.6"]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
@@ -121,7 +121,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ macos-latest ]
|
||||
python-version: ["3.8", "3.9", "3.10"]
|
||||
python-version: ["3.8", "3.9", "3.10.6"]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
@@ -205,7 +205,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ windows-latest ]
|
||||
python-version: ["3.8", "3.9", "3.10"]
|
||||
python-version: ["3.8", "3.9", "3.10.6"]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
@@ -272,6 +272,16 @@ jobs:
|
||||
pip install pyaml
|
||||
python build_helpers/pre_commit_update.py
|
||||
|
||||
pre-commit:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: "3.10"
|
||||
- uses: pre-commit/action@v3.0.0
|
||||
|
||||
docs_check:
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
@@ -302,7 +312,7 @@ jobs:
|
||||
|
||||
# Notify only once - when CI completes (and after deploy) in case it's successfull
|
||||
notify-complete:
|
||||
needs: [ build_linux, build_macos, build_windows, docs_check, mypy_version_check ]
|
||||
needs: [ build_linux, build_macos, build_windows, docs_check, mypy_version_check, pre-commit ]
|
||||
runs-on: ubuntu-20.04
|
||||
# Discord notification can't handle schedule events
|
||||
if: (github.event_name != 'schedule')
|
||||
@@ -327,7 +337,7 @@ jobs:
|
||||
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
||||
|
||||
deploy:
|
||||
needs: [ build_linux, build_macos, build_windows, docs_check, mypy_version_check ]
|
||||
needs: [ build_linux, build_macos, build_windows, docs_check, mypy_version_check, pre-commit ]
|
||||
runs-on: ubuntu-20.04
|
||||
|
||||
if: (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'release') && github.repository == 'freqtrade/freqtrade'
|
||||
@@ -351,7 +361,7 @@ jobs:
|
||||
python setup.py sdist bdist_wheel
|
||||
|
||||
- name: Publish to PyPI (Test)
|
||||
uses: pypa/gh-action-pypi-publish@v1.5.0
|
||||
uses: pypa/gh-action-pypi-publish@v1.5.1
|
||||
if: (github.event_name == 'release')
|
||||
with:
|
||||
user: __token__
|
||||
@@ -359,7 +369,7 @@ jobs:
|
||||
repository_url: https://test.pypi.org/legacy/
|
||||
|
||||
- name: Publish to PyPI
|
||||
uses: pypa/gh-action-pypi-publish@v1.5.0
|
||||
uses: pypa/gh-action-pypi-publish@v1.5.1
|
||||
if: (github.event_name == 'release')
|
||||
with:
|
||||
user: __token__
|
||||
@@ -397,15 +407,6 @@ jobs:
|
||||
run: |
|
||||
build_helpers/publish_docker_multi.sh
|
||||
|
||||
- name: Discord notification
|
||||
uses: rjstone/discord-webhook-notify@v1
|
||||
if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) && (github.event_name != 'schedule')
|
||||
with:
|
||||
severity: info
|
||||
details: Deploy Succeeded!
|
||||
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
||||
|
||||
|
||||
deploy_arm:
|
||||
needs: [ deploy ]
|
||||
# Only run on 64bit machines
|
||||
@@ -433,3 +434,11 @@ jobs:
|
||||
BRANCH_NAME: ${{ steps.extract_branch.outputs.branch }}
|
||||
run: |
|
||||
build_helpers/publish_docker_arm64.sh
|
||||
|
||||
- name: Discord notification
|
||||
uses: rjstone/discord-webhook-notify@v1
|
||||
if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) && (github.event_name != 'schedule')
|
||||
with:
|
||||
severity: info
|
||||
details: Deploy Succeeded!
|
||||
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
6
.gitignore
vendored
@@ -7,10 +7,15 @@ logfile.txt
|
||||
user_data/*
|
||||
!user_data/strategy/sample_strategy.py
|
||||
!user_data/notebooks
|
||||
!user_data/models
|
||||
!user_data/freqaimodels
|
||||
user_data/freqaimodels/*
|
||||
user_data/models/*
|
||||
user_data/notebooks/*
|
||||
freqtrade-plot.html
|
||||
freqtrade-profit-plot.html
|
||||
freqtrade/rpc/api_server/ui/*
|
||||
build_helpers/ta-lib/*
|
||||
|
||||
# Macos related
|
||||
.DS_Store
|
||||
@@ -107,3 +112,4 @@ target/
|
||||
!config_examples/config_ftx.example.json
|
||||
!config_examples/config_full.example.json
|
||||
!config_examples/config_kraken.example.json
|
||||
!config_examples/config_freqai.example.json
|
||||
|
@@ -15,7 +15,7 @@ repos:
|
||||
additional_dependencies:
|
||||
- types-cachetools==5.2.1
|
||||
- types-filelock==3.2.7
|
||||
- types-requests==2.28.3
|
||||
- types-requests==2.28.11
|
||||
- types-tabulate==0.8.11
|
||||
- types-python-dateutil==2.8.19
|
||||
# stages: [push]
|
||||
@@ -34,7 +34,9 @@ repos:
|
||||
exclude: |
|
||||
(?x)^(
|
||||
tests/.*|
|
||||
.*\.svg
|
||||
.*\.svg|
|
||||
.*\.yml|
|
||||
.*\.json
|
||||
)$
|
||||
- id: mixed-line-ending
|
||||
- id: debug-statements
|
||||
|
@@ -1,4 +1,4 @@
|
||||
FROM python:3.10.5-slim-bullseye as base
|
||||
FROM python:3.10.7-slim-bullseye as base
|
||||
|
||||
# Setup env
|
||||
ENV LANG C.UTF-8
|
||||
@@ -11,7 +11,7 @@ ENV FT_APP_ENV="docker"
|
||||
# Prepare environment
|
||||
RUN mkdir /freqtrade \
|
||||
&& apt-get update \
|
||||
&& apt-get -y install sudo libatlas3-base curl sqlite3 libhdf5-serial-dev \
|
||||
&& apt-get -y install sudo libatlas3-base curl sqlite3 libhdf5-serial-dev libgomp1 \
|
||||
&& apt-get clean \
|
||||
&& useradd -u 1000 -G sudo -U -m -s /bin/bash ftuser \
|
||||
&& chown ftuser:ftuser /freqtrade \
|
||||
|
@@ -63,6 +63,7 @@ Please find the complete documentation on the [freqtrade website](https://www.fr
|
||||
- [x] **Dry-run**: Run the bot without paying money.
|
||||
- [x] **Backtesting**: Run a simulation of your buy/sell strategy.
|
||||
- [x] **Strategy Optimization by machine learning**: Use machine learning to optimize your buy/sell strategy parameters with real exchange data.
|
||||
- [X] **Adaptive prediction modeling**: Build a smart strategy with FreqAI that self-trains to the market via adaptive machine learning methods. [Learn more](https://www.freqtrade.io/en/stable/freqai/)
|
||||
- [x] **Edge position sizing** Calculate your win rate, risk reward ratio, the best stoploss and adjust your position size before taking a position for each specific market. [Learn more](https://www.freqtrade.io/en/stable/edge/).
|
||||
- [x] **Whitelist crypto-currencies**: Select which crypto-currency you want to trade or use dynamic whitelists.
|
||||
- [x] **Blacklist crypto-currencies**: Select which crypto-currency you want to avoid.
|
||||
@@ -129,7 +130,7 @@ Telegram is not mandatory. However, this is a great way to control your bot. Mor
|
||||
|
||||
- `/start`: Starts the trader.
|
||||
- `/stop`: Stops the trader.
|
||||
- `/stopbuy`: Stop entering new trades.
|
||||
- `/stopentry`: Stop entering new trades.
|
||||
- `/status <trade_id>|[table]`: Lists all or specific open trades.
|
||||
- `/profit [<n>]`: Lists cumulative profit from all finished trades, over the last n days.
|
||||
- `/forceexit <trade_id>|all`: Instantly exits the given trade (Ignoring `minimum_roi`).
|
||||
@@ -193,7 +194,7 @@ Issues labeled [good first issue](https://github.com/freqtrade/freqtrade/labels/
|
||||
|
||||
The clock must be accurate, synchronized to a NTP server very frequently to avoid problems with communication to the exchanges.
|
||||
|
||||
### Min hardware required
|
||||
### Minimum hardware required
|
||||
|
||||
To run this bot we recommend you a cloud instance with a minimum of:
|
||||
|
||||
|
BIN
build_helpers/TA_Lib-0.4.25-cp310-cp310-win_amd64.whl
Normal file
BIN
build_helpers/TA_Lib-0.4.25-cp38-cp38-win_amd64.whl
Normal file
BIN
build_helpers/TA_Lib-0.4.25-cp39-cp39-win_amd64.whl
Normal file
@@ -4,7 +4,7 @@ else
|
||||
INSTALL_LOC=${1}
|
||||
fi
|
||||
echo "Installing to ${INSTALL_LOC}"
|
||||
if [ ! -f "${INSTALL_LOC}/lib/libta_lib.a" ]; then
|
||||
if [ -n "$2" ] || [ ! -f "${INSTALL_LOC}/lib/libta_lib.a" ]; then
|
||||
tar zxvf ta-lib-0.4.0-src.tar.gz
|
||||
cd ta-lib \
|
||||
&& sed -i.bak "s|0.00000001|0.000000000000000001 |g" src/ta_func/ta_utility.h \
|
||||
@@ -17,11 +17,17 @@ if [ ! -f "${INSTALL_LOC}/lib/libta_lib.a" ]; then
|
||||
cd .. && rm -rf ./ta-lib/
|
||||
exit 1
|
||||
fi
|
||||
which sudo && sudo make install || make install
|
||||
if [ -x "$(command -v apt-get)" ]; then
|
||||
echo "Updating library path using ldconfig"
|
||||
sudo ldconfig
|
||||
if [ -z "$2" ]; then
|
||||
which sudo && sudo make install || make install
|
||||
if [ -x "$(command -v apt-get)" ]; then
|
||||
echo "Updating library path using ldconfig"
|
||||
sudo ldconfig
|
||||
fi
|
||||
else
|
||||
# Don't install with sudo
|
||||
make install
|
||||
fi
|
||||
|
||||
cd .. && rm -rf ./ta-lib/
|
||||
else
|
||||
echo "TA-lib already installed, skipping installation"
|
||||
|
@@ -6,13 +6,13 @@ python -m pip install --upgrade pip wheel
|
||||
$pyv = python -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"
|
||||
|
||||
if ($pyv -eq '3.8') {
|
||||
pip install build_helpers\TA_Lib-0.4.24-cp38-cp38-win_amd64.whl
|
||||
pip install build_helpers\TA_Lib-0.4.25-cp38-cp38-win_amd64.whl
|
||||
}
|
||||
if ($pyv -eq '3.9') {
|
||||
pip install build_helpers\TA_Lib-0.4.24-cp39-cp39-win_amd64.whl
|
||||
pip install build_helpers\TA_Lib-0.4.25-cp39-cp39-win_amd64.whl
|
||||
}
|
||||
if ($pyv -eq '3.10') {
|
||||
pip install build_helpers\TA_Lib-0.4.24-cp310-cp310-win_amd64.whl
|
||||
pip install build_helpers\TA_Lib-0.4.25-cp310-cp310-win_amd64.whl
|
||||
}
|
||||
pip install -r requirements-dev.txt
|
||||
pip install -e .
|
||||
|
@@ -6,10 +6,12 @@ export DOCKER_BUILDKIT=1
|
||||
# Replace / with _ to create a valid tag
|
||||
TAG=$(echo "${BRANCH_NAME}" | sed -e "s/\//_/g")
|
||||
TAG_PLOT=${TAG}_plot
|
||||
TAG_FREQAI=${TAG}_freqai
|
||||
TAG_PI="${TAG}_pi"
|
||||
|
||||
TAG_ARM=${TAG}_arm
|
||||
TAG_PLOT_ARM=${TAG_PLOT}_arm
|
||||
TAG_FREQAI_ARM=${TAG_FREQAI}_arm
|
||||
CACHE_IMAGE=freqtradeorg/freqtrade_cache
|
||||
|
||||
echo "Running for ${TAG}"
|
||||
@@ -38,8 +40,10 @@ fi
|
||||
docker tag freqtrade:$TAG_ARM ${CACHE_IMAGE}:$TAG_ARM
|
||||
|
||||
docker build --cache-from freqtrade:${TAG_ARM} --build-arg sourceimage=${CACHE_IMAGE} --build-arg sourcetag=${TAG_ARM} -t freqtrade:${TAG_PLOT_ARM} -f docker/Dockerfile.plot .
|
||||
docker build --cache-from freqtrade:${TAG_ARM} --build-arg sourceimage=${CACHE_IMAGE} --build-arg sourcetag=${TAG_ARM} -t freqtrade:${TAG_FREQAI_ARM} -f docker/Dockerfile.freqai .
|
||||
|
||||
docker tag freqtrade:$TAG_PLOT_ARM ${CACHE_IMAGE}:$TAG_PLOT_ARM
|
||||
docker tag freqtrade:$TAG_FREQAI_ARM ${CACHE_IMAGE}:$TAG_FREQAI_ARM
|
||||
|
||||
# Run backtest
|
||||
docker run --rm -v $(pwd)/config_examples/config_bittrex.example.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG_ARM} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV3
|
||||
@@ -53,6 +57,7 @@ docker images
|
||||
|
||||
# docker push ${IMAGE_NAME}
|
||||
docker push ${CACHE_IMAGE}:$TAG_PLOT_ARM
|
||||
docker push ${CACHE_IMAGE}:$TAG_FREQAI_ARM
|
||||
docker push ${CACHE_IMAGE}:$TAG_ARM
|
||||
|
||||
# Create multi-arch image
|
||||
@@ -66,6 +71,9 @@ docker manifest push -p ${IMAGE_NAME}:${TAG}
|
||||
docker manifest create ${IMAGE_NAME}:${TAG_PLOT} ${CACHE_IMAGE}:${TAG_PLOT_ARM} ${CACHE_IMAGE}:${TAG_PLOT}
|
||||
docker manifest push -p ${IMAGE_NAME}:${TAG_PLOT}
|
||||
|
||||
docker manifest create ${IMAGE_NAME}:${TAG_FREQAI} ${CACHE_IMAGE}:${TAG_FREQAI_ARM} ${CACHE_IMAGE}:${TAG_FREQAI}
|
||||
docker manifest push -p ${IMAGE_NAME}:${TAG_FREQAI}
|
||||
|
||||
# Tag as latest for develop builds
|
||||
if [ "${TAG}" = "develop" ]; then
|
||||
docker manifest create ${IMAGE_NAME}:latest ${CACHE_IMAGE}:${TAG_ARM} ${IMAGE_NAME}:${TAG_PI} ${CACHE_IMAGE}:${TAG}
|
||||
|
@@ -5,6 +5,7 @@
|
||||
# Replace / with _ to create a valid tag
|
||||
TAG=$(echo "${BRANCH_NAME}" | sed -e "s/\//_/g")
|
||||
TAG_PLOT=${TAG}_plot
|
||||
TAG_FREQAI=${TAG}_freqai
|
||||
TAG_PI="${TAG}_pi"
|
||||
|
||||
PI_PLATFORM="linux/arm/v7"
|
||||
@@ -49,8 +50,10 @@ fi
|
||||
docker tag freqtrade:$TAG ${CACHE_IMAGE}:$TAG
|
||||
|
||||
docker build --cache-from freqtrade:${TAG} --build-arg sourceimage=${CACHE_IMAGE} --build-arg sourcetag=${TAG} -t freqtrade:${TAG_PLOT} -f docker/Dockerfile.plot .
|
||||
docker build --cache-from freqtrade:${TAG} --build-arg sourceimage=${CACHE_IMAGE} --build-arg sourcetag=${TAG} -t freqtrade:${TAG_FREQAI} -f docker/Dockerfile.freqai .
|
||||
|
||||
docker tag freqtrade:$TAG_PLOT ${CACHE_IMAGE}:$TAG_PLOT
|
||||
docker tag freqtrade:$TAG_FREQAI ${CACHE_IMAGE}:$TAG_FREQAI
|
||||
|
||||
# Run backtest
|
||||
docker run --rm -v $(pwd)/config_examples/config_bittrex.example.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV3
|
||||
@@ -64,6 +67,7 @@ docker images
|
||||
|
||||
docker push ${CACHE_IMAGE}
|
||||
docker push ${CACHE_IMAGE}:$TAG_PLOT
|
||||
docker push ${CACHE_IMAGE}:$TAG_FREQAI
|
||||
docker push ${CACHE_IMAGE}:$TAG
|
||||
|
||||
|
||||
|
97
config_examples/config_freqai.example.json
Normal file
@@ -0,0 +1,97 @@
|
||||
{
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"max_open_trades": 5,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": 200,
|
||||
"tradable_balance_ratio": 1,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"timeframe": "3m",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"unfilledtimeout": {
|
||||
"entry": 10,
|
||||
"exit": 30
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "",
|
||||
"secret": "",
|
||||
"ccxt_config": {
|
||||
"enableRateLimit": true
|
||||
},
|
||||
"ccxt_async_config": {
|
||||
"enableRateLimit": true,
|
||||
"rateLimit": 200
|
||||
},
|
||||
"pair_whitelist": [
|
||||
"1INCH/USDT",
|
||||
"ALGO/USDT"
|
||||
],
|
||||
"pair_blacklist": []
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing": {
|
||||
"price_side": "other",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList"
|
||||
}
|
||||
],
|
||||
"freqai": {
|
||||
"enabled": true,
|
||||
"purge_old_models": true,
|
||||
"train_period_days": 15,
|
||||
"backtest_period_days": 7,
|
||||
"live_retrain_hours": 0,
|
||||
"identifier": "uniqe-id",
|
||||
"feature_parameters": {
|
||||
"include_timeframes": [
|
||||
"3m",
|
||||
"15m",
|
||||
"1h"
|
||||
],
|
||||
"include_corr_pairlist": [
|
||||
"BTC/USDT",
|
||||
"ETH/USDT"
|
||||
],
|
||||
"label_period_candles": 20,
|
||||
"include_shifted_candles": 2,
|
||||
"DI_threshold": 0.9,
|
||||
"weight_factor": 0.9,
|
||||
"principal_component_analysis": false,
|
||||
"use_SVM_to_remove_outliers": true,
|
||||
"indicator_periods_candles": [
|
||||
10,
|
||||
20
|
||||
],
|
||||
"plot_feature_importances": 0
|
||||
},
|
||||
"data_split_parameters": {
|
||||
"test_size": 0.33,
|
||||
"random_state": 1
|
||||
},
|
||||
"model_training_parameters": {
|
||||
"n_estimators": 1000
|
||||
}
|
||||
},
|
||||
"bot_name": "",
|
||||
"force_entry_enable": true,
|
||||
"initial_state": "running",
|
||||
"internals": {
|
||||
"process_throttle_secs": 5
|
||||
}
|
||||
}
|
@@ -5,6 +5,7 @@
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"amount_reserve_percent": 0.05,
|
||||
"available_capital": 1000,
|
||||
"amend_last_stake_amount": false,
|
||||
"last_stake_amount_min_ratio": 0.5,
|
||||
"dry_run": true,
|
||||
@@ -63,8 +64,8 @@
|
||||
"stoploss_on_exchange_limit_ratio": 0.99
|
||||
},
|
||||
"order_time_in_force": {
|
||||
"entry": "gtc",
|
||||
"exit": "gtc"
|
||||
"entry": "GTC",
|
||||
"exit": "GTC"
|
||||
},
|
||||
"pairlists": [
|
||||
{"method": "StaticPairList"},
|
||||
@@ -92,6 +93,7 @@
|
||||
"secret": "your_exchange_secret",
|
||||
"password": "",
|
||||
"log_responses": false,
|
||||
// "unknown_fee_rate": 1,
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
@@ -170,7 +172,24 @@
|
||||
"jwt_secret_key": "somethingrandom",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "SuperSecurePassword"
|
||||
"password": "SuperSecurePassword",
|
||||
"ws_token": "secret_ws_t0ken."
|
||||
},
|
||||
"external_message_consumer": {
|
||||
"enabled": false,
|
||||
"producers": [
|
||||
{
|
||||
"name": "default",
|
||||
"host": "127.0.0.2",
|
||||
"port": 8080,
|
||||
"ws_token": "secret_ws_t0ken."
|
||||
}
|
||||
],
|
||||
"wait_timeout": 300,
|
||||
"ping_timeout": 10,
|
||||
"sleep_time": 10,
|
||||
"remove_entry_exit_signals": false,
|
||||
"message_size_limit": 8
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"db_url": "sqlite:///tradesv3.sqlite",
|
||||
|
8
docker/Dockerfile.freqai
Normal file
@@ -0,0 +1,8 @@
|
||||
ARG sourceimage=freqtradeorg/freqtrade
|
||||
ARG sourcetag=develop
|
||||
FROM ${sourceimage}:${sourcetag}
|
||||
|
||||
# Install dependencies
|
||||
COPY requirements-freqai.txt /freqtrade/
|
||||
|
||||
RUN pip install -r requirements-freqai.txt --user --no-cache-dir
|
@@ -1,7 +1,8 @@
|
||||
FROM freqtradeorg/freqtrade:develop_plot
|
||||
|
||||
|
||||
RUN pip install jupyterlab --user --no-cache-dir
|
||||
# Pin jupyter-client to avoid tornado version conflict
|
||||
RUN pip install jupyterlab jupyter-client==7.3.4 --user --no-cache-dir
|
||||
|
||||
# Empty the ENTRYPOINT to allow all commands
|
||||
ENTRYPOINT []
|
||||
|
@@ -10,7 +10,7 @@ services:
|
||||
ports:
|
||||
- "127.0.0.1:8888:8888"
|
||||
volumes:
|
||||
- "./user_data:/freqtrade/user_data"
|
||||
- "../user_data:/freqtrade/user_data"
|
||||
# Default command used when running `docker compose up`
|
||||
command: >
|
||||
jupyter lab --port=8888 --ip 0.0.0.0 --allow-root
|
||||
|
@@ -17,6 +17,7 @@ from typing import Any, Dict
|
||||
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.constants import Config
|
||||
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
||||
|
||||
TARGET_TRADES = 600
|
||||
@@ -31,7 +32,7 @@ class SuperDuperHyperOptLoss(IHyperOptLoss):
|
||||
@staticmethod
|
||||
def hyperopt_loss_function(results: DataFrame, trade_count: int,
|
||||
min_date: datetime, max_date: datetime,
|
||||
config: Dict, processed: Dict[str, DataFrame],
|
||||
config: Config, processed: Dict[str, DataFrame],
|
||||
backtest_stats: Dict[str, Any],
|
||||
*args, **kwargs) -> float:
|
||||
"""
|
||||
|
BIN
docs/assets/binance_futures_settings.png
Normal file
After Width: | Height: | Size: 80 KiB |
BIN
docs/assets/freqai_DI.jpg
Normal file
After Width: | Height: | Size: 307 KiB |
BIN
docs/assets/freqai_algo.jpg
Normal file
After Width: | Height: | Size: 345 KiB |
BIN
docs/assets/freqai_algorithm-diagram.jpg
Normal file
After Width: | Height: | Size: 490 KiB |
BIN
docs/assets/freqai_dbscan.jpg
Normal file
After Width: | Height: | Size: 66 KiB |
304
docs/assets/freqai_doc_logo.svg
Normal file
After Width: | Height: | Size: 2.0 MiB |
BIN
docs/assets/freqai_inlier-metric.jpg
Normal file
After Width: | Height: | Size: 458 KiB |
BIN
docs/assets/freqai_moving-window.jpg
Normal file
After Width: | Height: | Size: 270 KiB |
BIN
docs/assets/freqai_weight-factor.jpg
Normal file
After Width: | Height: | Size: 185 KiB |
@@ -107,7 +107,7 @@ Strategy arguments:
|
||||
|
||||
## Test your strategy with Backtesting
|
||||
|
||||
Now you have good Buy and Sell strategies and some historic data, you want to test it against
|
||||
Now you have good Entry and exit strategies and some historic data, you want to test it against
|
||||
real data. This is what we call [backtesting](https://en.wikipedia.org/wiki/Backtesting).
|
||||
|
||||
Backtesting will use the crypto-currencies (pairs) from your config file and load historical candle (OHLCV) data from `user_data/data/<exchange>` by default.
|
||||
@@ -215,7 +215,7 @@ Sometimes your account has certain fee rebates (fee reductions starting with a c
|
||||
To account for this in backtesting, you can use the `--fee` command line option to supply this value to backtesting.
|
||||
This fee must be a ratio, and will be applied twice (once for trade entry, and once for trade exit).
|
||||
|
||||
For example, if the buying and selling commission fee is 0.1% (i.e., 0.001 written as ratio), then you would run backtesting as the following:
|
||||
For example, if the commission fee per order is 0.1% (i.e., 0.001 written as ratio), then you would run backtesting as the following:
|
||||
|
||||
```bash
|
||||
freqtrade backtesting --fee 0.001
|
||||
@@ -252,41 +252,41 @@ The most important in the backtesting is to understand the result.
|
||||
A backtesting result will look like that:
|
||||
|
||||
```
|
||||
========================================================= BACKTESTING REPORT ==========================================================
|
||||
| Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins Draws Loss Win% |
|
||||
|:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:-------------|-------------------------:|
|
||||
| ADA/BTC | 35 | -0.11 | -3.88 | -0.00019428 | -1.94 | 4:35:00 | 14 0 21 40.0 |
|
||||
| ARK/BTC | 11 | -0.41 | -4.52 | -0.00022647 | -2.26 | 2:03:00 | 3 0 8 27.3 |
|
||||
| BTS/BTC | 32 | 0.31 | 9.78 | 0.00048938 | 4.89 | 5:05:00 | 18 0 14 56.2 |
|
||||
| DASH/BTC | 13 | -0.08 | -1.07 | -0.00005343 | -0.53 | 4:39:00 | 6 0 7 46.2 |
|
||||
| ENG/BTC | 18 | 1.36 | 24.54 | 0.00122807 | 12.27 | 2:50:00 | 8 0 10 44.4 |
|
||||
| EOS/BTC | 36 | 0.08 | 3.06 | 0.00015304 | 1.53 | 3:34:00 | 16 0 20 44.4 |
|
||||
| ETC/BTC | 26 | 0.37 | 9.51 | 0.00047576 | 4.75 | 6:14:00 | 11 0 15 42.3 |
|
||||
| ETH/BTC | 33 | 0.30 | 9.96 | 0.00049856 | 4.98 | 7:31:00 | 16 0 17 48.5 |
|
||||
| IOTA/BTC | 32 | 0.03 | 1.09 | 0.00005444 | 0.54 | 3:12:00 | 14 0 18 43.8 |
|
||||
| LSK/BTC | 15 | 1.75 | 26.26 | 0.00131413 | 13.13 | 2:58:00 | 6 0 9 40.0 |
|
||||
| LTC/BTC | 32 | -0.04 | -1.38 | -0.00006886 | -0.69 | 4:49:00 | 11 0 21 34.4 |
|
||||
| NANO/BTC | 17 | 1.26 | 21.39 | 0.00107058 | 10.70 | 1:55:00 | 10 0 7 58.5 |
|
||||
| NEO/BTC | 23 | 0.82 | 18.97 | 0.00094936 | 9.48 | 2:59:00 | 10 0 13 43.5 |
|
||||
| REQ/BTC | 9 | 1.17 | 10.54 | 0.00052734 | 5.27 | 3:47:00 | 4 0 5 44.4 |
|
||||
| XLM/BTC | 16 | 1.22 | 19.54 | 0.00097800 | 9.77 | 3:15:00 | 7 0 9 43.8 |
|
||||
| XMR/BTC | 23 | -0.18 | -4.13 | -0.00020696 | -2.07 | 5:30:00 | 12 0 11 52.2 |
|
||||
| XRP/BTC | 35 | 0.66 | 22.96 | 0.00114897 | 11.48 | 3:49:00 | 12 0 23 34.3 |
|
||||
| ZEC/BTC | 22 | -0.46 | -10.18 | -0.00050971 | -5.09 | 2:22:00 | 7 0 15 31.8 |
|
||||
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 0 243 43.4 |
|
||||
========================================================= BACKTESTING REPORT =========================================================
|
||||
| Pair | Entries | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins Draws Loss Win% |
|
||||
|:---------|--------:|---------------:|---------------:|-----------------:|---------------:|:-------------|-------------------------:|
|
||||
| ADA/BTC | 35 | -0.11 | -3.88 | -0.00019428 | -1.94 | 4:35:00 | 14 0 21 40.0 |
|
||||
| ARK/BTC | 11 | -0.41 | -4.52 | -0.00022647 | -2.26 | 2:03:00 | 3 0 8 27.3 |
|
||||
| BTS/BTC | 32 | 0.31 | 9.78 | 0.00048938 | 4.89 | 5:05:00 | 18 0 14 56.2 |
|
||||
| DASH/BTC | 13 | -0.08 | -1.07 | -0.00005343 | -0.53 | 4:39:00 | 6 0 7 46.2 |
|
||||
| ENG/BTC | 18 | 1.36 | 24.54 | 0.00122807 | 12.27 | 2:50:00 | 8 0 10 44.4 |
|
||||
| EOS/BTC | 36 | 0.08 | 3.06 | 0.00015304 | 1.53 | 3:34:00 | 16 0 20 44.4 |
|
||||
| ETC/BTC | 26 | 0.37 | 9.51 | 0.00047576 | 4.75 | 6:14:00 | 11 0 15 42.3 |
|
||||
| ETH/BTC | 33 | 0.30 | 9.96 | 0.00049856 | 4.98 | 7:31:00 | 16 0 17 48.5 |
|
||||
| IOTA/BTC | 32 | 0.03 | 1.09 | 0.00005444 | 0.54 | 3:12:00 | 14 0 18 43.8 |
|
||||
| LSK/BTC | 15 | 1.75 | 26.26 | 0.00131413 | 13.13 | 2:58:00 | 6 0 9 40.0 |
|
||||
| LTC/BTC | 32 | -0.04 | -1.38 | -0.00006886 | -0.69 | 4:49:00 | 11 0 21 34.4 |
|
||||
| NANO/BTC | 17 | 1.26 | 21.39 | 0.00107058 | 10.70 | 1:55:00 | 10 0 7 58.5 |
|
||||
| NEO/BTC | 23 | 0.82 | 18.97 | 0.00094936 | 9.48 | 2:59:00 | 10 0 13 43.5 |
|
||||
| REQ/BTC | 9 | 1.17 | 10.54 | 0.00052734 | 5.27 | 3:47:00 | 4 0 5 44.4 |
|
||||
| XLM/BTC | 16 | 1.22 | 19.54 | 0.00097800 | 9.77 | 3:15:00 | 7 0 9 43.8 |
|
||||
| XMR/BTC | 23 | -0.18 | -4.13 | -0.00020696 | -2.07 | 5:30:00 | 12 0 11 52.2 |
|
||||
| XRP/BTC | 35 | 0.66 | 22.96 | 0.00114897 | 11.48 | 3:49:00 | 12 0 23 34.3 |
|
||||
| ZEC/BTC | 22 | -0.46 | -10.18 | -0.00050971 | -5.09 | 2:22:00 | 7 0 15 31.8 |
|
||||
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 0 243 43.4 |
|
||||
========================================================= EXIT REASON STATS ==========================================================
|
||||
| Exit Reason | Sells | Wins | Draws | Losses |
|
||||
| Exit Reason | Exits | Wins | Draws | Losses |
|
||||
|:-------------------|--------:|------:|-------:|--------:|
|
||||
| trailing_stop_loss | 205 | 150 | 0 | 55 |
|
||||
| stop_loss | 166 | 0 | 0 | 166 |
|
||||
| exit_signal | 56 | 36 | 0 | 20 |
|
||||
| force_exit | 2 | 0 | 0 | 2 |
|
||||
====================================================== LEFT OPEN TRADES REPORT ======================================================
|
||||
| Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Win Draw Loss Win% |
|
||||
|:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|--------------------:|
|
||||
| ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 0 0 100 |
|
||||
| LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 0 0 100 |
|
||||
| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 0 0 100 |
|
||||
| Pair | Entries | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Win Draw Loss Win% |
|
||||
|:---------|---------:|---------------:|---------------:|-----------------:|---------------:|:---------------|--------------------:|
|
||||
| ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 0 0 100 |
|
||||
| LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 0 0 100 |
|
||||
| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 0 0 100 |
|
||||
================== SUMMARY METRICS ==================
|
||||
| Metric | Value |
|
||||
|-----------------------------+---------------------|
|
||||
@@ -356,7 +356,7 @@ The column `Avg Profit %` shows the average profit for all trades made while the
|
||||
The column `Tot Profit %` shows instead the total profit % in relation to the starting balance.
|
||||
In the above results, we have a starting balance of 0.01 BTC and an absolute profit of 0.00762792 BTC - so the `Tot Profit %` will be `(0.00762792 / 0.01) * 100 ~= 76.2%`.
|
||||
|
||||
Your strategy performance is influenced by your buy strategy, your exit strategy, and also by the `minimal_roi` and `stop_loss` you have set.
|
||||
Your strategy performance is influenced by your entry strategy, your exit strategy, and also by the `minimal_roi` and `stop_loss` you have set.
|
||||
|
||||
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 exit every time a trade reaches 1%).
|
||||
|
||||
@@ -514,7 +514,8 @@ You can then load the trades to perform further analysis as shown in the [data a
|
||||
|
||||
Since backtesting lacks some detailed information about what happens within a candle, it needs to take a few assumptions:
|
||||
|
||||
- Buys happen at open-price
|
||||
- Exchange [trading limits](#trading-limits-in-backtesting) are respected
|
||||
- Entries happen at open-price
|
||||
- All orders are filled at the requested price (no slippage, no unfilled orders)
|
||||
- Exit-signal exits happen at open-price of the consecutive candle
|
||||
- Exit-signal is favored over Stoploss, because exit-signals are assumed to trigger on candle's open
|
||||
@@ -543,7 +544,32 @@ 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.
|
||||
|
||||
### Improved backtest accuracy
|
||||
### Trading limits in backtesting
|
||||
|
||||
Exchanges have certain trading limits, like minimum base currency, or minimum stake (quote) currency.
|
||||
These limits are usually listed in the exchange documentation as "trading rules" or similar.
|
||||
|
||||
Backtesting (as well as live and dry-run) does honor these limits, and will ensure that a stoploss can be placed below this value - so the value will be slightly higher than what the exchange specifies.
|
||||
Freqtrade has however no information about historic limits.
|
||||
|
||||
This can lead to situations where trading-limits are inflated by using a historic price, resulting in minimum amounts > 50$.
|
||||
|
||||
For example:
|
||||
|
||||
BTC minimum tradable amount is 0.001.
|
||||
BTC trades at 22.000\$ today (0.001 BTC is related to this) - but the backtesting period includes prices as high as 50.000\$.
|
||||
Today's minimum would be `0.001 * 22_000` - or 22\$.
|
||||
However the limit could also be 50$ - based on `0.001 * 50_000` in some historic setting.
|
||||
|
||||
#### Trading precision limits
|
||||
|
||||
Most exchanges pose precision limits on both price and amounts, so you cannot buy 1.0020401 of a pair, or at a price of 1.24567123123.
|
||||
Instead, these prices and amounts will be rounded or truncated (based on the exchange definition) to the defined trading precision.
|
||||
The above values may for example be rounded to an amount of 1.002, and a price of 1.24567.
|
||||
|
||||
These precision values are based on current exchange limits (as described in the [above section](#trading-limits-in-backtesting)), as historic precision limits are not available.
|
||||
|
||||
## Improved backtest accuracy
|
||||
|
||||
One big limitation of backtesting is it's inability to know how prices moved intra-candle (was high before close, or viceversa?).
|
||||
So assuming you run backtesting with a 1h timeframe, there will be 4 prices for that candle (Open, High, Low, Close).
|
||||
@@ -586,11 +612,11 @@ There will be an additional table comparing win/losses of the different strategi
|
||||
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 | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins | Draws | Losses | Drawdown % |
|
||||
|:------------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|------:|-------:|-------:|-----------:|
|
||||
| Strategy1 | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 0 | 243 | 45.2 |
|
||||
| Strategy2 | 1487 | -0.13 | -197.58 | -0.00988917 | -98.79 | 4:43:00 | 662 | 0 | 825 | 241.68 |
|
||||
=========================================================== STRATEGY SUMMARY ===========================================================================
|
||||
| Strategy | Entries | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins | Draws | Losses | Drawdown % |
|
||||
|:------------|---------:|---------------:|---------------:|-----------------:|---------------:|:---------------|------:|-------:|-------:|-----------:|
|
||||
| Strategy1 | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 0 | 243 | 45.2 |
|
||||
| Strategy2 | 1487 | -0.13 | -197.58 | -0.00988917 | -98.79 | 4:43:00 | 662 | 0 | 825 | 241.68 |
|
||||
```
|
||||
|
||||
## Next step
|
||||
|
@@ -70,7 +70,7 @@ This loop will be repeated again and again until the bot is stopped.
|
||||
* Determine stake size by calling the `custom_stake_amount()` callback.
|
||||
* Check position adjustments for open trades if enabled and call `adjust_trade_position()` to determine if an additional order is requested.
|
||||
* Call `custom_stoploss()` and `custom_exit()` to find custom exit points.
|
||||
* For exits based on exit-signal and custom-exit: Call `custom_exit_price()` to determine exit price (Prices are moved to be within the closing candle).
|
||||
* For exits based on exit-signal, custom-exit and partial exits: Call `custom_exit_price()` to determine exit price (Prices are moved to be within the closing candle).
|
||||
* Generate backtest report output
|
||||
|
||||
!!! Note
|
||||
|
@@ -58,9 +58,20 @@ This is similar to using multiple `--config` parameters, but simpler in usage as
|
||||
|
||||
!!! Tip "Use multiple configuration files to keep secrets secret"
|
||||
You can use a 2nd configuration file containing your secrets. That way you can share your "primary" configuration file, while still keeping your API keys for yourself.
|
||||
The 2nd file should only specify what you intend to override.
|
||||
If a key is in more than one of the configurations, then the "last specified configuration" wins (in the above example, `config-private.json`).
|
||||
|
||||
For one-off commands, you can also use the below syntax by specifying multiple "--config" parameters.
|
||||
|
||||
``` bash
|
||||
freqtrade trade --config user_data/config1.json --config user_data/config-private.json <...>
|
||||
```
|
||||
|
||||
The below is equivalent to the example above - but having 2 configuration files in the configuration, for easier reuse.
|
||||
|
||||
``` json title="user_data/config.json"
|
||||
"add_config_files": [
|
||||
"config1.json",
|
||||
"config-private.json"
|
||||
]
|
||||
```
|
||||
@@ -69,17 +80,6 @@ This is similar to using multiple `--config` parameters, but simpler in usage as
|
||||
freqtrade trade --config user_data/config.json <...>
|
||||
```
|
||||
|
||||
The 2nd file should only specify what you intend to override.
|
||||
If a key is in more than one of the configurations, then the "last specified configuration" wins (in the above example, `config-private.json`).
|
||||
|
||||
For one-off commands, you can also use the below syntax by specifying multiple "--config" parameters.
|
||||
|
||||
``` bash
|
||||
freqtrade trade --config user_data/config.json --config user_data/config-private.json <...>
|
||||
```
|
||||
|
||||
This is equivalent to the example above - but `config-private.json` is specified as cli argument.
|
||||
|
||||
??? Note "config collision handling"
|
||||
If the same configuration setting takes place in both `config.json` and `config-import.json`, then the parent configuration wins.
|
||||
In the below case, `max_open_trades` would be 3 after the merging - as the reusable "import" configuration has this key overwritten.
|
||||
@@ -105,12 +105,14 @@ This is similar to using multiple `--config` parameters, but simpler in usage as
|
||||
|
||||
``` json title="Result"
|
||||
{
|
||||
"max_open_trades": 10,
|
||||
"max_open_trades": 3,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited"
|
||||
}
|
||||
```
|
||||
|
||||
If multiple files are in the `add_config_files` section, then they will be assumed to be at identical levels, having the last occurrence override the earlier config (unless a parent already defined such a key).
|
||||
|
||||
## Configuration parameters
|
||||
|
||||
The table below will list all configuration parameters available.
|
||||
@@ -223,14 +225,16 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
||||
| `webhook.webhookexitcancel` | Payload to send on exit order cancel. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||
| `webhook.webhookexitfill` | Payload to send on exit order filled. Only required if `webhook.enabled` is `true`. See the [webhook documentation](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 documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||
| | **Rest API / FreqUI**
|
||||
| | **Rest API / FreqUI / Producer-Consumer**
|
||||
| `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.verbosity` | Logging verbosity. `info` will print all RPC Calls, while "error" will only display errors. <br>**Datatype:** Enum, either `info` or `error`. Defaults to `info`.
|
||||
| `api_server.username` | Username for API server. See the [API Server documentation](rest-api.md) for more details. <br>**Keep it in secret, do not disclose publicly.**<br> **Datatype:** String
|
||||
| `api_server.password` | Password for API server. See the [API Server documentation](rest-api.md) for more details. <br>**Keep it in secret, do not disclose publicly.**<br> **Datatype:** String
|
||||
| `api_server.ws_token` | API token for the Message WebSocket. See the [API Server documentation](rest-api.md) for more details. <br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||
| `bot_name` | Name of the bot. Passed via API to a client - can be shown to distinguish / name bots.<br> *Defaults to `freqtrade`*<br> **Datatype:** String
|
||||
| `external_message_consumer` | Enable [Producer/Consumer mode](producer-consumer.md) for more details. <br> **Datatype:** Dict
|
||||
| | **Other**
|
||||
| `initial_state` | Defines the initial application state. If set to stopped, then the bot has to be explicitly started via `/start` RPC command. <br>*Defaults to `stopped`.* <br> **Datatype:** Enum, either `stopped` or `running`
|
||||
| `force_entry_enable` | Enables the RPC Commands to force a Trade entry. More information below. <br> **Datatype:** Boolean
|
||||
@@ -525,21 +529,28 @@ It means if the order is not executed immediately AND fully then it is cancelled
|
||||
It is the same as FOK (above) except it can be partially fulfilled. The remaining part
|
||||
is automatically cancelled by the exchange.
|
||||
|
||||
The `order_time_in_force` parameter contains a dict with buy and sell time in force policy values.
|
||||
**PO (Post only):**
|
||||
|
||||
Post only order. The order is either placed as a maker order, or it is canceled.
|
||||
This means the order must be placed on orderbook for at at least time in an unfilled state.
|
||||
|
||||
#### time_in_force config
|
||||
|
||||
The `order_time_in_force` parameter contains a dict with entry and exit time in force policy values.
|
||||
This can be set in the configuration file or in the strategy.
|
||||
Values set in the configuration file overwrites values set in the strategy.
|
||||
|
||||
The possible values are: `gtc` (default), `fok` or `ioc`.
|
||||
The possible values are: `GTC` (default), `FOK` or `IOC`.
|
||||
|
||||
``` python
|
||||
"order_time_in_force": {
|
||||
"entry": "gtc",
|
||||
"exit": "gtc"
|
||||
"entry": "GTC",
|
||||
"exit": "GTC"
|
||||
},
|
||||
```
|
||||
|
||||
!!! Warning
|
||||
This is ongoing work. For now, it is supported only for binance and kucoin.
|
||||
This is ongoing work. For now, it is supported only for binance, gate, ftx and kucoin.
|
||||
Please don't change the default value unless you know what you are doing and have researched the impact of using different values for your particular exchange.
|
||||
|
||||
### What values can be used for fiat_display_currency?
|
||||
@@ -650,17 +661,7 @@ You should also make sure to read the [Exchanges](exchanges.md) section of the d
|
||||
|
||||
### Using proxy with Freqtrade
|
||||
|
||||
To use a proxy with freqtrade, add the kwarg `"aiohttp_trust_env"=true` to the `"ccxt_async_kwargs"` dict in the exchange section of the configuration.
|
||||
|
||||
An example for this can be found in `config_examples/config_full.example.json`
|
||||
|
||||
``` json
|
||||
"ccxt_async_config": {
|
||||
"aiohttp_trust_env": true
|
||||
}
|
||||
```
|
||||
|
||||
Then, export your proxy settings using the variables `"HTTP_PROXY"` and `"HTTPS_PROXY"` set to the appropriate values
|
||||
To use a proxy with freqtrade, export your proxy settings using the variables `"HTTP_PROXY"` and `"HTTPS_PROXY"` set to the appropriate values.
|
||||
|
||||
``` bash
|
||||
export HTTP_PROXY="http://addr:port"
|
||||
@@ -668,6 +669,20 @@ export HTTPS_PROXY="http://addr:port"
|
||||
freqtrade
|
||||
```
|
||||
|
||||
#### Proxy just exchange requests
|
||||
|
||||
To use a proxy just for exchange connections (skips/ignores telegram and coingecko) - you can also define the proxies as part of the ccxt configuration.
|
||||
|
||||
``` json
|
||||
"ccxt_config": {
|
||||
"aiohttp_proxy": "http://addr:port",
|
||||
"proxies": {
|
||||
"http": "http://addr:port",
|
||||
"https": "http://addr:port"
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Next step
|
||||
|
||||
Now you have configured your config.json, the next step is to [start your bot](bot-usage.md).
|
||||
|
@@ -25,9 +25,8 @@ usage: freqtrade download-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[--include-inactive-pairs]
|
||||
[--timerange TIMERANGE] [--dl-trades]
|
||||
[--exchange EXCHANGE]
|
||||
[-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]]
|
||||
[--erase]
|
||||
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||
[-t TIMEFRAMES [TIMEFRAMES ...]] [--erase]
|
||||
[--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}]
|
||||
[--data-format-trades {json,jsongz,hdf5}]
|
||||
[--trading-mode {spot,margin,futures}]
|
||||
[--prepend]
|
||||
@@ -37,7 +36,8 @@ optional arguments:
|
||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||
Limit command to these pairs. Pairs are space-
|
||||
separated.
|
||||
--pairs-file FILE File containing a list of pairs to download.
|
||||
--pairs-file FILE File containing a list of pairs. Takes precedence over
|
||||
--pairs or pairs configured in the configuration.
|
||||
--days INT Download data for given number of days.
|
||||
--new-pairs-days INT Download data of new pairs for given number of days.
|
||||
Default: `None`.
|
||||
@@ -50,20 +50,20 @@ optional arguments:
|
||||
as --timeframes/-t.
|
||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||
config is provided.
|
||||
-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]
|
||||
-t TIMEFRAMES [TIMEFRAMES ...], --timeframes TIMEFRAMES [TIMEFRAMES ...]
|
||||
Specify which tickers to download. Space-separated
|
||||
list. Default: `1m 5m`.
|
||||
--erase Clean all existing data for the selected
|
||||
exchange/pairs/timeframes.
|
||||
--data-format-ohlcv {json,jsongz,hdf5}
|
||||
--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}
|
||||
Storage format for downloaded candle (OHLCV) data.
|
||||
(default: `json`).
|
||||
--data-format-trades {json,jsongz,hdf5}
|
||||
Storage format for downloaded trades data. (default:
|
||||
`jsongz`).
|
||||
--trading-mode {spot,margin,futures}
|
||||
--trading-mode {spot,margin,futures}, --tradingmode {spot,margin,futures}
|
||||
Select Trading mode
|
||||
--prepend Allow data prepending.
|
||||
--prepend Allow data prepending. (Data-appending is disabled)
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
@@ -76,7 +76,7 @@ Common arguments:
|
||||
`userdir/config.json` or `config.json` whichever
|
||||
exists). Multiple --config options may be used. Can be
|
||||
set to `-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
-d PATH, --datadir PATH, --data-dir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
@@ -179,14 +179,16 @@ freqtrade download-data --exchange binance --pairs ETH/USDT XRP/USDT BTC/USDT --
|
||||
|
||||
Freqtrade currently supports 3 data-formats for both OHLCV and trades data:
|
||||
|
||||
* `json` (plain "text" json files)
|
||||
* `jsongz` (a gzip-zipped version of json files)
|
||||
* `hdf5` (a high performance datastore)
|
||||
* `json` - plain "text" json files
|
||||
* `jsongz` - a gzip-zipped version of json files
|
||||
* `hdf5` - a high performance datastore
|
||||
* `feather` - a dataformat based on Apache Arrow
|
||||
* `parquet` - columnar datastore
|
||||
|
||||
By default, OHLCV data is stored as `json` data, while trades data is stored as `jsongz` data.
|
||||
|
||||
This can be changed via the `--data-format-ohlcv` and `--data-format-trades` command line arguments respectively.
|
||||
To persist this change, you can should also add the following snippet to your configuration, so you don't have to insert the above arguments each time:
|
||||
To persist this change, you should also add the following snippet to your configuration, so you don't have to insert the above arguments each time:
|
||||
|
||||
``` jsonc
|
||||
// ...
|
||||
@@ -200,38 +202,74 @@ If the default data-format has been changed during download, then the keys `data
|
||||
!!! Note
|
||||
You can convert between data-formats using the [convert-data](#sub-command-convert-data) and [convert-trade-data](#sub-command-convert-trade-data) methods.
|
||||
|
||||
#### Dataformat comparison
|
||||
|
||||
The following comparisons have been made with the following data, and by using the linux `time` command.
|
||||
|
||||
```
|
||||
Found 6 pair / timeframe combinations.
|
||||
+----------+-------------+--------+---------------------+---------------------+
|
||||
| Pair | Timeframe | Type | From | To |
|
||||
|----------+-------------+--------+---------------------+---------------------|
|
||||
| BTC/USDT | 5m | spot | 2017-08-17 04:00:00 | 2022-09-13 19:25:00 |
|
||||
| ETH/USDT | 1m | spot | 2017-08-17 04:00:00 | 2022-09-13 19:26:00 |
|
||||
| BTC/USDT | 1m | spot | 2017-08-17 04:00:00 | 2022-09-13 19:30:00 |
|
||||
| XRP/USDT | 5m | spot | 2018-05-04 08:10:00 | 2022-09-13 19:15:00 |
|
||||
| XRP/USDT | 1m | spot | 2018-05-04 08:11:00 | 2022-09-13 19:22:00 |
|
||||
| ETH/USDT | 5m | spot | 2017-08-17 04:00:00 | 2022-09-13 19:20:00 |
|
||||
+----------+-------------+--------+---------------------+---------------------+
|
||||
```
|
||||
|
||||
Timings have been taken in a not very scientific way with the following command, which forces reading the data into memory.
|
||||
|
||||
``` bash
|
||||
time freqtrade list-data --show-timerange --data-format-ohlcv <dataformat>
|
||||
```
|
||||
|
||||
| Format | Size | timing |
|
||||
|------------|-------------|-------------|
|
||||
| `json` | 149Mb | 25.6s |
|
||||
| `jsongz` | 39Mb | 27s |
|
||||
| `hdf5` | 145Mb | 3.9s |
|
||||
| `feather` | 72Mb | 3.5s |
|
||||
| `parquet` | 83Mb | 3.8s |
|
||||
|
||||
Size has been taken from the BTC/USDT 1m spot combination for the timerange specified above.
|
||||
|
||||
To have a best performance/size mix, we recommend the use of either feather or parquet.
|
||||
|
||||
#### Sub-command convert data
|
||||
|
||||
```
|
||||
usage: freqtrade convert-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH]
|
||||
[-p PAIRS [PAIRS ...]] --format-from
|
||||
{json,jsongz,hdf5} --format-to
|
||||
{json,jsongz,hdf5} [--erase]
|
||||
[-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]]
|
||||
{json,jsongz,hdf5,feather,parquet} --format-to
|
||||
{json,jsongz,hdf5,feather,parquet} [--erase]
|
||||
[--exchange EXCHANGE]
|
||||
[-t TIMEFRAMES [TIMEFRAMES ...]]
|
||||
[--trading-mode {spot,margin,futures}]
|
||||
[--candle-types {spot,,futures,mark,index,premiumIndex,funding_rate} [{spot,,futures,mark,index,premiumIndex,funding_rate} ...]]
|
||||
[--candle-types {spot,futures,mark,index,premiumIndex,funding_rate} [{spot,futures,mark,index,premiumIndex,funding_rate} ...]]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||
Limit command to these pairs. Pairs are space-
|
||||
separated.
|
||||
--format-from {json,jsongz,hdf5}
|
||||
--format-from {json,jsongz,hdf5,feather,parquet}
|
||||
Source format for data conversion.
|
||||
--format-to {json,jsongz,hdf5}
|
||||
--format-to {json,jsongz,hdf5,feather,parquet}
|
||||
Destination format for data conversion.
|
||||
--erase Clean all existing data for the selected
|
||||
exchange/pairs/timeframes.
|
||||
-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]
|
||||
Specify which tickers to download. Space-separated
|
||||
list. Default: `1m 5m`.
|
||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||
config is provided.
|
||||
--trading-mode {spot,margin,futures}
|
||||
-t TIMEFRAMES [TIMEFRAMES ...], --timeframes TIMEFRAMES [TIMEFRAMES ...]
|
||||
Specify which tickers to download. Space-separated
|
||||
list. Default: `1m 5m`.
|
||||
--trading-mode {spot,margin,futures}, --tradingmode {spot,margin,futures}
|
||||
Select Trading mode
|
||||
--candle-types {spot,,futures,mark,index,premiumIndex,funding_rate} [{spot,,futures,mark,index,premiumIndex,funding_rate} ...]
|
||||
--candle-types {spot,futures,mark,index,premiumIndex,funding_rate} [{spot,futures,mark,index,premiumIndex,funding_rate} ...]
|
||||
Select candle type to use
|
||||
|
||||
Common arguments:
|
||||
@@ -245,7 +283,7 @@ Common arguments:
|
||||
`userdir/config.json` or `config.json` whichever
|
||||
exists). Multiple --config options may be used. Can be
|
||||
set to `-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
-d PATH, --datadir PATH, --data-dir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
@@ -267,20 +305,24 @@ freqtrade convert-data --format-from json --format-to jsongz --datadir ~/.freqtr
|
||||
usage: freqtrade convert-trade-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH]
|
||||
[-p PAIRS [PAIRS ...]] --format-from
|
||||
{json,jsongz,hdf5} --format-to
|
||||
{json,jsongz,hdf5} [--erase]
|
||||
{json,jsongz,hdf5,feather,parquet}
|
||||
--format-to
|
||||
{json,jsongz,hdf5,feather,parquet}
|
||||
[--erase] [--exchange EXCHANGE]
|
||||
|
||||
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-
|
||||
Limit command to these pairs. Pairs are space-
|
||||
separated.
|
||||
--format-from {json,jsongz,hdf5}
|
||||
--format-from {json,jsongz,hdf5,feather,parquet}
|
||||
Source format for data conversion.
|
||||
--format-to {json,jsongz,hdf5}
|
||||
--format-to {json,jsongz,hdf5,feather,parquet}
|
||||
Destination format for data conversion.
|
||||
--erase Clean all existing data for the selected
|
||||
exchange/pairs/timeframes.
|
||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||
config is provided.
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
@@ -293,7 +335,7 @@ Common arguments:
|
||||
`userdir/config.json` or `config.json` whichever
|
||||
exists). Multiple --config options may be used. Can be
|
||||
set to `-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
-d PATH, --datadir PATH, --data-dir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
@@ -318,9 +360,9 @@ This command will allow you to repeat this last step for additional timeframes w
|
||||
usage: freqtrade trades-to-ohlcv [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH]
|
||||
[-p PAIRS [PAIRS ...]]
|
||||
[-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]]
|
||||
[-t TIMEFRAMES [TIMEFRAMES ...]]
|
||||
[--exchange EXCHANGE]
|
||||
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||
[--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}]
|
||||
[--data-format-trades {json,jsongz,hdf5}]
|
||||
|
||||
optional arguments:
|
||||
@@ -328,12 +370,12 @@ optional arguments:
|
||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||
Limit command to these pairs. Pairs are space-
|
||||
separated.
|
||||
-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]
|
||||
-t TIMEFRAMES [TIMEFRAMES ...], --timeframes TIMEFRAMES [TIMEFRAMES ...]
|
||||
Specify which tickers to download. Space-separated
|
||||
list. Default: `1m 5m`.
|
||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||
config is provided.
|
||||
--data-format-ohlcv {json,jsongz,hdf5}
|
||||
--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}
|
||||
Storage format for downloaded candle (OHLCV) data.
|
||||
(default: `json`).
|
||||
--data-format-trades {json,jsongz,hdf5}
|
||||
@@ -351,7 +393,7 @@ Common arguments:
|
||||
`userdir/config.json` or `config.json` whichever
|
||||
exists). Multiple --config options may be used. Can be
|
||||
set to `-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
-d PATH, --datadir PATH, --data-dir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
@@ -371,22 +413,25 @@ You can get a list of downloaded data using the `list-data` sub-command.
|
||||
```
|
||||
usage: freqtrade list-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||
[--userdir PATH] [--exchange EXCHANGE]
|
||||
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||
[--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}]
|
||||
[-p PAIRS [PAIRS ...]]
|
||||
[--trading-mode {spot,margin,futures}]
|
||||
[--show-timerange]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||
config is provided.
|
||||
--data-format-ohlcv {json,jsongz,hdf5}
|
||||
--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}
|
||||
Storage format for downloaded candle (OHLCV) data.
|
||||
(default: `json`).
|
||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||
Limit command to these pairs. Pairs are space-
|
||||
separated.
|
||||
--trading-mode {spot,margin,futures}
|
||||
--trading-mode {spot,margin,futures}, --tradingmode {spot,margin,futures}
|
||||
Select Trading mode
|
||||
--show-timerange Show timerange available for available data. (May take
|
||||
a while to calculate).
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
@@ -399,7 +444,7 @@ Common arguments:
|
||||
`userdir/config.json` or `config.json` whichever
|
||||
exists). Multiple --config options may be used. Can be
|
||||
set to `-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
-d PATH, --datadir PATH, --data-dir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
|
@@ -68,6 +68,36 @@ def test_method_to_test(caplog):
|
||||
|
||||
```
|
||||
|
||||
### Debug configuration
|
||||
|
||||
To debug freqtrade, we recommend VSCode with the following launch configuration (located in `.vscode/launch.json`).
|
||||
Details will obviously vary between setups - but this should work to get you started.
|
||||
|
||||
``` json
|
||||
{
|
||||
"name": "freqtrade trade",
|
||||
"type": "python",
|
||||
"request": "launch",
|
||||
"module": "freqtrade",
|
||||
"console": "integratedTerminal",
|
||||
"args": [
|
||||
"trade",
|
||||
// Optional:
|
||||
// "--userdir", "user_data",
|
||||
"--strategy",
|
||||
"MyAwesomeStrategy",
|
||||
]
|
||||
},
|
||||
```
|
||||
|
||||
Command line arguments can be added in the `"args"` array.
|
||||
This method can also be used to debug a strategy, by setting the breakpoints within the strategy.
|
||||
|
||||
A similar setup can also be taken for Pycharm - using `freqtrade` as module name, and setting the command line arguments as "parameters".
|
||||
|
||||
!!! Note "Startup directory"
|
||||
This assumes that you have the repository checked out, and the editor is started at the repository root level (so setup.py is at the top level of your repository).
|
||||
|
||||
## ErrorHandling
|
||||
|
||||
Freqtrade Exceptions all inherit from `FreqtradeException`.
|
||||
@@ -379,8 +409,9 @@ Determine if crucial bugfixes have been made between this commit and the current
|
||||
|
||||
* Merge the release branch (stable) into this branch.
|
||||
* 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. Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi.
|
||||
* Commit this part
|
||||
* push that branch to the remote and create a PR against the stable branch
|
||||
* Commit this part.
|
||||
* push that branch to the remote and create a PR against the stable branch.
|
||||
* Update develop version to next version following the pattern `2019.8-dev`.
|
||||
|
||||
### Create changelog from git commits
|
||||
|
||||
|
@@ -57,12 +57,20 @@ This configuration enables kraken, as well as rate-limiting to avoid bans from t
|
||||
Binance supports [time_in_force](configuration.md#understand-order_time_in_force).
|
||||
|
||||
!!! Tip "Stoploss on Exchange"
|
||||
Binance supports `stoploss_on_exchange` and uses `stop-loss-limit` orders. It provides great advantages, so we recommend to benefit from it by enabling stoploss on exchange..
|
||||
Binance supports `stoploss_on_exchange` and uses `stop-loss-limit` orders. It provides great advantages, so we recommend to benefit from it by enabling stoploss on exchange.
|
||||
On futures, Binance supports both `stop-limit` as well as `stop-market` orders. You can use either `"limit"` or `"market"` in the `order_types.stoploss` configuration setting to decide which type to use.
|
||||
|
||||
### Binance Blacklist
|
||||
### Binance Blacklist recommendation
|
||||
|
||||
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 trade unsellable as the expected amount is not there anymore.
|
||||
For Binance, it is suggested to add `"BNB/<STAKE>"` to your blacklist to avoid issues, unless you are willing to maintain enough extra `BNB` on the account or unless you're willing to disable using `BNB` for fees.
|
||||
Binance accounts may use `BNB` for fees, and if a trade happens to be on `BNB`, further trades may consume this position and make the initial BNB trade unsellable as the expected amount is not there anymore.
|
||||
|
||||
### Binance sites
|
||||
|
||||
Binance has been split into 2, 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 Futures
|
||||
|
||||
@@ -86,12 +94,14 @@ When trading on Binance Futures market, orderbook must be used because there is
|
||||
},
|
||||
```
|
||||
|
||||
### Binance sites
|
||||
#### Binance futures settings
|
||||
|
||||
Binance has been split into 2, and users must use the correct ccxt exchange ID for their exchange, otherwise API keys are not recognized.
|
||||
Users will also have to have the futures-setting "Position Mode" set to "One-way Mode", and "Asset Mode" set to "Single-Asset Mode".
|
||||
These settings will be checked on startup, and freqtrade will show an error if this setting is wrong.
|
||||
|
||||
* [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`.
|
||||

|
||||
|
||||
Freqtrade will not attempt to change these settings.
|
||||
|
||||
## Kraken
|
||||
|
||||
@@ -205,8 +215,8 @@ Kucoin supports [time_in_force](configuration.md#understand-order_time_in_force)
|
||||
|
||||
### Kucoin Blacklists
|
||||
|
||||
For Kucoin, please add `"KCS/<STAKE>"` to your blacklist to avoid issues.
|
||||
Accounts having KCS accounts use this to pay for fees - if your first trade happens to be on `KCS`, further trades will consume this position and make the initial KCS trade unsellable as the expected amount is not there anymore.
|
||||
For Kucoin, it is suggested to add `"KCS/<STAKE>"` to your blacklist to avoid issues, unless you are willing to maintain enough extra `KCS` on the account or unless you're willing to disable using `KCS` for fees.
|
||||
Kucoin accounts may use `KCS` for fees, and if a trade happens to be on `KCS`, further trades may consume this position and make the initial `KCS` trade unsellable as the expected amount is not there anymore.
|
||||
|
||||
## Huobi
|
||||
|
||||
@@ -232,7 +242,7 @@ OKX requires a passphrase for each api key, you will therefore need to add this
|
||||
|
||||
!!! Warning "Futures"
|
||||
OKX Futures has the concept of "position mode" - which can be Net or long/short (hedge mode).
|
||||
Freqtrade supports both modes - but changing the mode mid-trading is not supported and will lead to exceptions and failures to place trades.
|
||||
Freqtrade supports both modes (we recommend to use net mode) - but changing the mode mid-trading is not supported and will lead to exceptions and failures to place trades.
|
||||
OKX also only provides MARK candles for the past ~3 months. Backtesting futures prior to that date will therefore lead to slight deviations, as funding-fees cannot be calculated correctly without this data.
|
||||
|
||||
## Gate.io
|
||||
@@ -278,7 +288,7 @@ For example, to test the order type `FOK` with Kraken, and modify candle limit t
|
||||
"exchange": {
|
||||
"name": "kraken",
|
||||
"_ft_has_params": {
|
||||
"order_time_in_force": ["gtc", "fok"],
|
||||
"order_time_in_force": ["GTC", "FOK"],
|
||||
"ohlcv_candle_limit": 200
|
||||
}
|
||||
//...
|
||||
|
31
docs/faq.md
@@ -4,7 +4,7 @@
|
||||
|
||||
Freqtrade supports spot trading only.
|
||||
|
||||
### Can I open short positions?
|
||||
### Can my bot open short positions?
|
||||
|
||||
Freqtrade can open short positions in futures markets.
|
||||
This requires the strategy to be made for this - and `"trading_mode": "futures"` in the configuration.
|
||||
@@ -12,9 +12,9 @@ Please make sure to read the [relevant documentation page](leverage.md) first.
|
||||
|
||||
In spot markets, you can in some cases use leveraged spot tokens, which reflect an inverted pair (eg. BTCUP/USD, BTCDOWN/USD, ETHBULL/USD, ETHBEAR/USD,...) which can be traded with Freqtrade.
|
||||
|
||||
### Can I trade options or futures?
|
||||
### Can my bot trade options or futures?
|
||||
|
||||
Futures trading is supported for selected exchanges.
|
||||
Futures trading is supported for selected exchanges. Please refer to the [documentation start page](index.md#supported-futures-exchanges-experimental) for an uptodate list of supported exchanges.
|
||||
|
||||
## Beginner Tips & Tricks
|
||||
|
||||
@@ -22,6 +22,13 @@ Futures trading is supported for selected exchanges.
|
||||
|
||||
## Freqtrade common issues
|
||||
|
||||
### Can freqtrade open multiple positions on the same pair in parallel?
|
||||
|
||||
No. Freqtrade will only open one position per pair at a time.
|
||||
You can however use the [`adjust_trade_position()` callback](strategy-callbacks.md#adjust-trade-position) to adjust an open position.
|
||||
|
||||
Backtesting provides an option for this in `--eps` - however this is only there to highlight "hidden" signals, and will not work in live.
|
||||
|
||||
### The bot does not start
|
||||
|
||||
Running the bot with `freqtrade trade --config config.json` shows the output `freqtrade: command not found`.
|
||||
@@ -30,7 +37,7 @@ This could be caused by the following reasons:
|
||||
|
||||
* The virtual environment is not active.
|
||||
* Run `source .env/bin/activate` to activate the virtual environment.
|
||||
* The installation did not work correctly.
|
||||
* The installation did not complete successfully.
|
||||
* Please check the [Installation documentation](installation.md).
|
||||
|
||||
### I have waited 5 minutes, why hasn't the bot made any trades yet?
|
||||
@@ -67,7 +74,7 @@ This is not a bot-problem, but will also happen while manual trading.
|
||||
While freqtrade can handle this (it'll sell 99 COIN), fees are often below the minimum tradable lot-size (you can only trade full COIN, not 0.9 COIN).
|
||||
Leaving the dust (0.9 COIN) on the exchange makes usually sense, as the next time freqtrade buys COIN, it'll eat into the remaining small balance, this time selling everything it bought, and therefore slowly declining the dust balance (although it most likely will never reach exactly 0).
|
||||
|
||||
Where possible (e.g. on binance), the use of the exchange's dedicated fee currency will fix this.
|
||||
Where possible (e.g. on binance), the use of the exchange's dedicated fee currency will fix this.
|
||||
On binance, it's sufficient to have BNB in your account, and have "Pay fees in BNB" enabled in your profile. Your BNB balance will slowly decline (as it's used to pay fees) - but you'll no longer encounter dust (Freqtrade will include the fees in the profit calculations).
|
||||
Other exchanges don't offer such possibilities, where it's simply something you'll have to accept or move to a different exchange.
|
||||
|
||||
@@ -77,9 +84,9 @@ Freqtrade will not provide incomplete candles to strategies. Using incomplete ca
|
||||
|
||||
You can use "current" market data by using the [dataprovider](strategy-customization.md#orderbookpair-maximum)'s orderbook or ticker methods - which however cannot be used during backtesting.
|
||||
|
||||
### Is there a setting to only SELL the coins being held and not perform anymore BUYS?
|
||||
### Is there a setting to only Exit the trades being held and not perform any new Entries?
|
||||
|
||||
You can use the `/stopbuy` command in Telegram to prevent future buys, followed by `/forceexit all` (sell all open trades).
|
||||
You can use the `/stopentry` command in Telegram to prevent future trade entry, followed by `/forceexit all` (sell all open trades).
|
||||
|
||||
### I want to run multiple bots on the same machine
|
||||
|
||||
@@ -109,7 +116,7 @@ This warning can point to one of the below problems:
|
||||
|
||||
### I'm getting the "RESTRICTED_MARKET" message in the log
|
||||
|
||||
Currently known to happen for US Bittrex users.
|
||||
Currently known to happen for US Bittrex users.
|
||||
|
||||
Read [the Bittrex section about restricted markets](exchanges.md#restricted-markets) for more information.
|
||||
|
||||
@@ -177,8 +184,8 @@ The GPU improvements would only apply to pandas-native calculations - or ones wr
|
||||
For hyperopt, freqtrade is using scikit-optimize, which is built on top of scikit-learn.
|
||||
Their statement about GPU support is [pretty clear](https://scikit-learn.org/stable/faq.html#will-you-add-gpu-support).
|
||||
|
||||
GPU's also are only good at crunching numbers (floating point operations).
|
||||
For hyperopt, we need both number-crunching (find next parameters) and running python code (running backtesting).
|
||||
GPU's also are only good at crunching numbers (floating point operations).
|
||||
For hyperopt, we need both number-crunching (find next parameters) and running python code (running backtesting).
|
||||
As such, GPU's are not too well suited for most parts of hyperopt.
|
||||
|
||||
The benefit of using GPU would therefore be pretty slim - and will not justify the complexity introduced by trying to add GPU support.
|
||||
@@ -219,9 +226,9 @@ already 8\*10^9\*10 evaluations. A roughly total of 80 billion evaluations.
|
||||
Did you run 100 000 evaluations? Congrats, you've done roughly 1 / 100 000 th
|
||||
of the search space, assuming that the bot never tests the same parameters more than once.
|
||||
|
||||
* The time it takes to run 1000 hyperopt epochs depends on things like: The available cpu, hard-disk, ram, timeframe, timerange, indicator settings, indicator count, amount of coins that hyperopt test strategies on and the resulting trade count - which can be 650 trades in a year or 100000 trades depending if the strategy aims for big profits by trading rarely or for many low profit trades.
|
||||
* The time it takes to run 1000 hyperopt epochs depends on things like: The available cpu, hard-disk, ram, timeframe, timerange, indicator settings, indicator count, amount of coins that hyperopt test strategies on and the resulting trade count - which can be 650 trades in a year or 100000 trades depending if the strategy aims for big profits by trading rarely or for many low profit trades.
|
||||
|
||||
Example: 4% profit 650 times vs 0,3% profit a trade 10000 times in a year. If we assume you set the --timerange to 365 days.
|
||||
Example: 4% profit 650 times vs 0,3% profit a trade 10000 times in a year. If we assume you set the --timerange to 365 days.
|
||||
|
||||
Example:
|
||||
`freqtrade --config config.json --strategy SampleStrategy --hyperopt SampleHyperopt -e 1000 --timerange 20190601-20200601`
|
||||
|
217
docs/freqai-configuration.md
Normal file
@@ -0,0 +1,217 @@
|
||||
# Configuration
|
||||
|
||||
FreqAI is configured through the typical [Freqtrade config file](configuration.md) and the standard [Freqtrade strategy](strategy-customization.md). Examples of FreqAI config and strategy files can be found in `config_examples/config_freqai.example.json` and `freqtrade/templates/FreqaiExampleStrategy.py`, respectively.
|
||||
|
||||
## Setting up the configuration file
|
||||
|
||||
Although there are plenty of additional parameters to choose from, as highlighted in the [parameter table](freqai-parameter-table.md#parameter-table), a FreqAI config must at minimum include the following parameters (the parameter values are only examples):
|
||||
|
||||
```json
|
||||
"freqai": {
|
||||
"enabled": true,
|
||||
"purge_old_models": true,
|
||||
"train_period_days": 30,
|
||||
"backtest_period_days": 7,
|
||||
"identifier" : "unique-id",
|
||||
"feature_parameters" : {
|
||||
"include_timeframes": ["5m","15m","4h"],
|
||||
"include_corr_pairlist": [
|
||||
"ETH/USD",
|
||||
"LINK/USD",
|
||||
"BNB/USD"
|
||||
],
|
||||
"label_period_candles": 24,
|
||||
"include_shifted_candles": 2,
|
||||
"indicator_periods_candles": [10, 20]
|
||||
},
|
||||
"data_split_parameters" : {
|
||||
"test_size": 0.25
|
||||
},
|
||||
"model_training_parameters" : {
|
||||
"n_estimators": 100
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
A full example config is available in `config_examples/config_freqai.example.json`.
|
||||
|
||||
## Building a FreqAI strategy
|
||||
|
||||
The FreqAI strategy requires including the following lines of code in the standard [Freqtrade strategy](strategy-customization.md):
|
||||
|
||||
```python
|
||||
# user should define the maximum startup candle count (the largest number of candles
|
||||
# passed to any single indicator)
|
||||
startup_candle_count: int = 20
|
||||
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
|
||||
# the model will return all labels created by user in `populate_any_indicators`
|
||||
# (& appended targets), an indication of whether or not the prediction should be accepted,
|
||||
# the target mean/std values for each of the labels created by user in
|
||||
# `populate_any_indicators()` for each training period.
|
||||
|
||||
dataframe = self.freqai.start(dataframe, metadata, self)
|
||||
|
||||
return dataframe
|
||||
|
||||
def populate_any_indicators(
|
||||
self, pair, df, tf, informative=None, set_generalized_indicators=False
|
||||
):
|
||||
"""
|
||||
Function designed to automatically generate, name and merge features
|
||||
from user indicated timeframes in the configuration file. User controls the indicators
|
||||
passed to the training/prediction by prepending indicators with `'%-' + coin `
|
||||
(see convention below). I.e. user should not prepend any supporting metrics
|
||||
(e.g. bb_lowerband below) with % unless they explicitly want to pass that metric to the
|
||||
model.
|
||||
:param pair: pair to be used as informative
|
||||
:param df: strategy dataframe which will receive merges from informatives
|
||||
:param tf: timeframe of the dataframe which will modify the feature names
|
||||
:param informative: the dataframe associated with the informative pair
|
||||
:param coin: the name of the coin which will modify the feature names.
|
||||
"""
|
||||
|
||||
coin = pair.split('/')[0]
|
||||
|
||||
if informative is None:
|
||||
informative = self.dp.get_pair_dataframe(pair, tf)
|
||||
|
||||
# first loop is automatically duplicating indicators for time periods
|
||||
for t in self.freqai_info["feature_parameters"]["indicator_periods_candles"]:
|
||||
t = int(t)
|
||||
informative[f"%-{coin}rsi-period_{t}"] = ta.RSI(informative, timeperiod=t)
|
||||
informative[f"%-{coin}mfi-period_{t}"] = ta.MFI(informative, timeperiod=t)
|
||||
informative[f"%-{coin}adx-period_{t}"] = ta.ADX(informative, window=t)
|
||||
|
||||
indicators = [col for col in informative if col.startswith("%")]
|
||||
# This loop duplicates and shifts all indicators to add a sense of recency to data
|
||||
for n in range(self.freqai_info["feature_parameters"]["include_shifted_candles"] + 1):
|
||||
if n == 0:
|
||||
continue
|
||||
informative_shift = informative[indicators].shift(n)
|
||||
informative_shift = informative_shift.add_suffix("_shift-" + str(n))
|
||||
informative = pd.concat((informative, informative_shift), axis=1)
|
||||
|
||||
df = merge_informative_pair(df, informative, self.config["timeframe"], tf, ffill=True)
|
||||
skip_columns = [
|
||||
(s + "_" + tf) for s in ["date", "open", "high", "low", "close", "volume"]
|
||||
]
|
||||
df = df.drop(columns=skip_columns)
|
||||
|
||||
# Add generalized indicators here (because in live, it will call this
|
||||
# function to populate indicators during training). Notice how we ensure not to
|
||||
# add them multiple times
|
||||
if set_generalized_indicators:
|
||||
|
||||
# user adds targets here by prepending them with &- (see convention below)
|
||||
# If user wishes to use multiple targets, a multioutput prediction model
|
||||
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
||||
df["&-s_close"] = (
|
||||
df["close"]
|
||||
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||
.mean()
|
||||
/ df["close"]
|
||||
- 1
|
||||
)
|
||||
|
||||
return df
|
||||
|
||||
|
||||
```
|
||||
|
||||
Notice how the `populate_any_indicators()` is where [features](freqai-feature-engineering.md#feature-engineering) and labels/targets are added. A full example strategy is available in `templates/FreqaiExampleStrategy.py`.
|
||||
|
||||
Notice also the location of the labels under `if set_generalized_indicators:` at the bottom of the example. This is where single features and labels/targets should be added to the feature set to avoid duplication of them from various configuration parameters that multiply the feature set, such as `include_timeframes`.
|
||||
|
||||
!!! Note
|
||||
The `self.freqai.start()` function cannot be called outside the `populate_indicators()`.
|
||||
|
||||
!!! Note
|
||||
Features **must** be defined in `populate_any_indicators()`. Defining FreqAI features in `populate_indicators()`
|
||||
will cause the algorithm to fail in live/dry mode. In order to add generalized features that are not associated with a specific pair or timeframe, the following structure inside `populate_any_indicators()` should be used
|
||||
(as exemplified in `freqtrade/templates/FreqaiExampleStrategy.py`):
|
||||
|
||||
```python
|
||||
def populate_any_indicators(self, metadata, pair, df, tf, informative=None, coin="", set_generalized_indicators=False):
|
||||
|
||||
...
|
||||
|
||||
# Add generalized indicators here (because in live, it will call only this function to populate
|
||||
# indicators for retraining). Notice how we ensure not to add them multiple times by associating
|
||||
# these generalized indicators to the basepair/timeframe
|
||||
if set_generalized_indicators:
|
||||
df['%-day_of_week'] = (df["date"].dt.dayofweek + 1) / 7
|
||||
df['%-hour_of_day'] = (df['date'].dt.hour + 1) / 25
|
||||
|
||||
# user adds targets here by prepending them with &- (see convention below)
|
||||
# If user wishes to use multiple targets, a multioutput prediction model
|
||||
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
||||
df["&-s_close"] = (
|
||||
df["close"]
|
||||
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||
.mean()
|
||||
/ df["close"]
|
||||
- 1
|
||||
)
|
||||
```
|
||||
|
||||
Please see the example script located in `freqtrade/templates/FreqaiExampleStrategy.py` for a full example of `populate_any_indicators()`.
|
||||
|
||||
## Important dataframe key patterns
|
||||
|
||||
Below are the values you can expect to include/use inside a typical strategy dataframe (`df[]`):
|
||||
|
||||
| DataFrame Key | Description |
|
||||
|------------|-------------|
|
||||
| `df['&*']` | Any dataframe column prepended with `&` in `populate_any_indicators()` is treated as a training target (label) inside FreqAI (typically following the naming convention `&-s*`). For example, to predict the close price 40 candles into the future, you would set `df['&-s_close'] = df['close'].shift(-self.freqai_info["feature_parameters"]["label_period_candles"])` with `"label_period_candles": 40` in the config. FreqAI makes the predictions and gives them back under the same key (`df['&-s_close']`) to be used in `populate_entry/exit_trend()`. <br> **Datatype:** Depends on the output of the model.
|
||||
| `df['&*_std/mean']` | Standard deviation and mean values of the defined labels during training (or live tracking with `fit_live_predictions_candles`). Commonly used to understand the rarity of a prediction (use the z-score as shown in `templates/FreqaiExampleStrategy.py` and explained [here](#creating-a-dynamic-target-threshold) to evaluate how often a particular prediction was observed during training or historically with `fit_live_predictions_candles`). <br> **Datatype:** Float.
|
||||
| `df['do_predict']` | Indication of an outlier data point. The return value is integer between -2 and 2, which lets you know if the prediction is trustworthy or not. `do_predict==1` means that the prediction is trustworthy. If the Dissimilarity Index (DI, see details [here](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di)) of the input data point is above the threshold defined in the config, FreqAI will subtract 1 from `do_predict`, resulting in `do_predict==0`. If `use_SVM_to_remove_outliers()` is active, the Support Vector Machine (SVM, see details [here](freqai-feature-engineering.md#identifying-outliers-using-a-support-vector-machine-svm)) may also detect outliers in training and prediction data. In this case, the SVM will also subtract 1 from `do_predict`. If the input data point was considered an outlier by the SVM but not by the DI, or vice versa, the result will be `do_predict==0`. If both the DI and the SVM considers the input data point to be an outlier, the result will be `do_predict==-1`. As with the SVM, if `use_DBSCAN_to_remove_outliers` is active, DBSCAN (see details [here](freqai-feature-engineering.md#identifying-outliers-with-dbscan)) may also detect outliers and subtract 1 from `do_predict`. Hence, if both the SVM and DBSCAN are active and identify a datapoint that was above the DI threshold as an outlier, the result will be `do_predict==-2`. A particular case is when `do_predict == 2`, which means that the model has expired due to exceeding `expired_hours`. <br> **Datatype:** Integer between -2 and 2.
|
||||
| `df['DI_values']` | Dissimilarity Index (DI) values are proxies for the level of confidence FreqAI has in the prediction. A lower DI means the prediction is close to the training data, i.e., higher prediction confidence. See details about the DI [here](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di). <br> **Datatype:** Float.
|
||||
| `df['%*']` | Any dataframe column prepended with `%` in `populate_any_indicators()` is treated as a training feature. For example, you can include the RSI in the training feature set (similar to in `templates/FreqaiExampleStrategy.py`) by setting `df['%-rsi']`. See more details on how this is done [here](freqai-feature-engineering.md). <br> **Note:** Since the number of features prepended with `%` can multiply very quickly (10s of thousands of features are easily engineered using the multiplictative functionality of, e.g., `include_shifted_candles` and `include_timeframes` as described in the [parameter table](freqai-parameter-table.md)), these features are removed from the dataframe that is returned from FreqAI to the strategy. To keep a particular type of feature for plotting purposes, you would prepend it with `%%`. <br> **Datatype:** Depends on the output of the model.
|
||||
|
||||
## Setting the `startup_candle_count`
|
||||
|
||||
The `startup_candle_count` in the FreqAI strategy needs to be set up in the same way as in the standard Freqtrade strategy (see details [here](strategy-customization.md#strategy-startup-period)). This value is used by Freqtrade to ensure that a sufficient amount of data is provided when calling the `dataprovider`, to avoid any NaNs at the beginning of the first training. You can easily set this value by identifying the longest period (in candle units) which is passed to the indicator creation functions (e.g., Ta-Lib functions). In the presented example, `startup_candle_count` is 20 since this is the maximum value in `indicators_periods_candles`.
|
||||
|
||||
!!! Note
|
||||
There are instances where the Ta-Lib functions actually require more data than just the passed `period` or else the feature dataset gets populated with NaNs. Anecdotally, multiplying the `startup_candle_count` by 2 always leads to a fully NaN free training dataset. Hence, it is typically safest to multiply the expected `startup_candle_count` by 2. Look out for this log message to confirm that the data is clean:
|
||||
|
||||
```
|
||||
2022-08-31 15:14:04 - freqtrade.freqai.data_kitchen - INFO - dropped 0 training points due to NaNs in populated dataset 4319.
|
||||
```
|
||||
|
||||
## Creating a dynamic target threshold
|
||||
|
||||
Deciding when to enter or exit a trade can be done in a dynamic way to reflect current market conditions. FreqAI allows you to return additional information from the training of a model (more info [here](freqai-feature-engineering.md#returning-additional-info-from-training)). For example, the `&*_std/mean` return values describe the statistical distribution of the target/label *during the most recent training*. Comparing a given prediction to these values allows you to know the rarity of the prediction. In `templates/FreqaiExampleStrategy.py`, the `target_roi` and `sell_roi` are defined to be 1.25 z-scores away from the mean which causes predictions that are closer to the mean to be filtered out.
|
||||
|
||||
```python
|
||||
dataframe["target_roi"] = dataframe["&-s_close_mean"] + dataframe["&-s_close_std"] * 1.25
|
||||
dataframe["sell_roi"] = dataframe["&-s_close_mean"] - dataframe["&-s_close_std"] * 1.25
|
||||
```
|
||||
|
||||
To consider the population of *historical predictions* for creating the dynamic target instead of information from the training as discussed above, you would set `fit_live_prediction_candles` in the config to the number of historical prediction candles you wish to use to generate target statistics.
|
||||
|
||||
```json
|
||||
"freqai": {
|
||||
"fit_live_prediction_candles": 300,
|
||||
}
|
||||
```
|
||||
|
||||
If this value is set, FreqAI will initially use the predictions from the training data and subsequently begin introducing real prediction data as it is generated. FreqAI will save this historical data to be reloaded if you stop and restart a model with the same `identifier`.
|
||||
|
||||
## Using different prediction models
|
||||
|
||||
FreqAI has multiple example prediction model libraries that are ready to be used as is via the flag `--freqaimodel`. These libraries include `Catboost`, `LightGBM`, and `XGBoost` regression, classification, and multi-target models, and can be found in `freqai/prediction_models/`. However, it is possible to customize and create your own prediction models using the `IFreqaiModel` class. You are encouraged to inherit `fit()`, `train()`, and `predict()` to let these customize various aspects of the training procedures.
|
||||
|
||||
### Setting classifier targets
|
||||
|
||||
FreqAI includes a variety of classifiers, such as the `CatboostClassifier` via the flag `--freqaimodel CatboostClassifier`. If you elects to use a classifier, the classes need to be set using strings. For example:
|
||||
|
||||
```python
|
||||
df['&s-up_or_down'] = np.where( df["close"].shift(-100) > df["close"], 'up', 'down')
|
||||
```
|
||||
|
||||
Additionally, the example classifier models do not accommodate multiple labels, but they do allow multi-class classification within a single label column.
|
78
docs/freqai-developers.md
Normal file
@@ -0,0 +1,78 @@
|
||||
# Development
|
||||
|
||||
## Project architecture
|
||||
|
||||
The architecture and functions of FreqAI are generalized to encourages development of unique features, functions, models, etc.
|
||||
|
||||
The class structure and a detailed algorithmic overview is depicted in the following diagram:
|
||||
|
||||

|
||||
|
||||
As shown, there are three distinct objects comprising FreqAI:
|
||||
|
||||
* **IFreqaiModel** - A singular persistent object containing all the necessary logic to collect, store, and process data, engineer features, run training, and inference models.
|
||||
* **FreqaiDataKitchen** - A non-persistent object which is created uniquely for each unique asset/model. Beyond metadata, it also contains a variety of data processing tools.
|
||||
* **FreqaiDataDrawer** - A singular persistent object containing all the historical predictions, models, and save/load methods.
|
||||
|
||||
There are a variety of built-in [prediction models](freqai-configuration.md#using-different-prediction-models) which inherit directly from `IFreqaiModel`. Each of these models have full access to all methods in `IFreqaiModel` and can therefore override any of those functions at will. However, advanced users will likely stick to overriding `fit()`, `train()`, `predict()`, and `data_cleaning_train/predict()`.
|
||||
|
||||
## Data handling
|
||||
|
||||
FreqAI aims to organize model files, prediction data, and meta data in a way that simplifies post-processing and enhances crash resilience by automatic data reloading. The data is saved in a file structure,`user_data_dir/models/`, which contains all the data associated with the trainings and backtests. The `FreqaiDataKitchen()` relies heavily on the file structure for proper training and inferencing and should therefore not be manually modified.
|
||||
|
||||
### File structure
|
||||
|
||||
The file structure is automatically generated based on the model `identifier` set in the [config](freqai-configuration.md#setting-up-the-configuration-file). The following structure shows where the data is stored for post processing:
|
||||
|
||||
| Structure | Description |
|
||||
|-----------|-------------|
|
||||
| `config_*.json` | A copy of the model specific configuration file. |
|
||||
| `historic_predictions.pkl` | A file containing all historic predictions generated during the lifetime of the `identifier` model during live deployment. `historic_predictions.pkl` is used to reload the model after a crash or a config change. A backup file is always held in case of corruption on the main file. FreqAI **automatically** detects corruption and replaces the corrupted file with the backup. |
|
||||
| `pair_dictionary.json` | A file containing the training queue as well as the on disk location of the most recently trained model. |
|
||||
| `sub-train-*_TIMESTAMP` | A folder containing all the files associated with a single model, such as: <br>
|
||||
|| `*_metadata.json` - Metadata for the model, such as normalization max/min, expected training feature list, etc. <br>
|
||||
|| `*_model.*` - The model file saved to disk for reloading from a crash. Can be `joblib` (typical boosting libs), `zip` (stable_baselines), `hd5` (keras type), etc. <br>
|
||||
|| `*_pca_object.pkl` - The [Principal component analysis (PCA)](freqai-feature-engineering.md#data-dimensionality-reduction-with-principal-component-analysis) transform (if `principal_component_analysis: True` is set in the config) which will be used to transform unseen prediction features. <br>
|
||||
|| `*_svm_model.pkl` - The [Support Vector Machine (SVM)](freqai-feature-engineering.md#identifying-outliers-using-a-support-vector-machine-svm) model (if `use_SVM_to_remove_outliers: True` is set in the config) which is used to detect outliers in unseen prediction features. <br>
|
||||
|| `*_trained_df.pkl` - The dataframe containing all the training features used to train the `identifier` model. This is used for computing the [Dissimilarity Index (DI)](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di) and can also be used for post-processing. <br>
|
||||
|| `*_trained_dates.df.pkl` - The dates associated with the `trained_df.pkl`, which is useful for post-processing. |
|
||||
|
||||
The example file structure would look like this:
|
||||
|
||||
```
|
||||
├── models
|
||||
│ └── unique-id
|
||||
│ ├── config_freqai.example.json
|
||||
│ ├── historic_predictions.backup.pkl
|
||||
│ ├── historic_predictions.pkl
|
||||
│ ├── pair_dictionary.json
|
||||
│ ├── sub-train-1INCH_1662821319
|
||||
│ │ ├── cb_1inch_1662821319_metadata.json
|
||||
│ │ ├── cb_1inch_1662821319_model.joblib
|
||||
│ │ ├── cb_1inch_1662821319_pca_object.pkl
|
||||
│ │ ├── cb_1inch_1662821319_svm_model.joblib
|
||||
│ │ ├── cb_1inch_1662821319_trained_dates_df.pkl
|
||||
│ │ └── cb_1inch_1662821319_trained_df.pkl
|
||||
│ ├── sub-train-1INCH_1662821371
|
||||
│ │ ├── cb_1inch_1662821371_metadata.json
|
||||
│ │ ├── cb_1inch_1662821371_model.joblib
|
||||
│ │ ├── cb_1inch_1662821371_pca_object.pkl
|
||||
│ │ ├── cb_1inch_1662821371_svm_model.joblib
|
||||
│ │ ├── cb_1inch_1662821371_trained_dates_df.pkl
|
||||
│ │ └── cb_1inch_1662821371_trained_df.pkl
|
||||
│ ├── sub-train-ADA_1662821344
|
||||
│ │ ├── cb_ada_1662821344_metadata.json
|
||||
│ │ ├── cb_ada_1662821344_model.joblib
|
||||
│ │ ├── cb_ada_1662821344_pca_object.pkl
|
||||
│ │ ├── cb_ada_1662821344_svm_model.joblib
|
||||
│ │ ├── cb_ada_1662821344_trained_dates_df.pkl
|
||||
│ │ └── cb_ada_1662821344_trained_df.pkl
|
||||
│ └── sub-train-ADA_1662821399
|
||||
│ ├── cb_ada_1662821399_metadata.json
|
||||
│ ├── cb_ada_1662821399_model.joblib
|
||||
│ ├── cb_ada_1662821399_pca_object.pkl
|
||||
│ ├── cb_ada_1662821399_svm_model.joblib
|
||||
│ ├── cb_ada_1662821399_trained_dates_df.pkl
|
||||
│ └── cb_ada_1662821399_trained_df.pkl
|
||||
|
||||
```
|
268
docs/freqai-feature-engineering.md
Normal file
@@ -0,0 +1,268 @@
|
||||
# Feature engineering
|
||||
|
||||
## Defining the features
|
||||
|
||||
Low level feature engineering is performed in the user strategy within a function called `populate_any_indicators()`. That function sets the `base features` such as, `RSI`, `MFI`, `EMA`, `SMA`, time of day, volume, etc. The `base features` can be custom indicators or they can be imported from any technical-analysis library that you can find. One important syntax rule is that all `base features` string names are prepended with `%`, while labels/targets are prepended with `&`.
|
||||
|
||||
Meanwhile, high level feature engineering is handled within `"feature_parameters":{}` in the FreqAI config. Within this file, it is possible to decide large scale feature expansions on top of the `base_features` such as "including correlated pairs" or "including informative timeframes" or even "including recent candles."
|
||||
|
||||
It is advisable to start from the template `populate_any_indicators()` in the source provided example strategy (found in `templates/FreqaiExampleStrategy.py`) to ensure that the feature definitions are following the correct conventions. Here is an example of how to set the indicators and labels in the strategy:
|
||||
|
||||
```python
|
||||
def populate_any_indicators(
|
||||
self, pair, df, tf, informative=None, set_generalized_indicators=False
|
||||
):
|
||||
"""
|
||||
Function designed to automatically generate, name, and merge features
|
||||
from user-indicated timeframes in the configuration file. The user controls the indicators
|
||||
passed to the training/prediction by prepending indicators with `'%-' + coin `
|
||||
(see convention below). I.e., the user should not prepend any supporting metrics
|
||||
(e.g., bb_lowerband below) with % unless they explicitly want to pass that metric to the
|
||||
model.
|
||||
:param pair: pair to be used as informative
|
||||
:param df: strategy dataframe which will receive merges from informatives
|
||||
:param tf: timeframe of the dataframe which will modify the feature names
|
||||
:param informative: the dataframe associated with the informative pair
|
||||
:param coin: the name of the coin which will modify the feature names.
|
||||
"""
|
||||
|
||||
coin = pair.split('/')[0]
|
||||
|
||||
if informative is None:
|
||||
informative = self.dp.get_pair_dataframe(pair, tf)
|
||||
|
||||
# first loop is automatically duplicating indicators for time periods
|
||||
for t in self.freqai_info["feature_parameters"]["indicator_periods_candles"]:
|
||||
t = int(t)
|
||||
informative[f"%-{coin}rsi-period_{t}"] = ta.RSI(informative, timeperiod=t)
|
||||
informative[f"%-{coin}mfi-period_{t}"] = ta.MFI(informative, timeperiod=t)
|
||||
informative[f"%-{coin}adx-period_{t}"] = ta.ADX(informative, window=t)
|
||||
|
||||
bollinger = qtpylib.bollinger_bands(
|
||||
qtpylib.typical_price(informative), window=t, stds=2.2
|
||||
)
|
||||
informative[f"{coin}bb_lowerband-period_{t}"] = bollinger["lower"]
|
||||
informative[f"{coin}bb_middleband-period_{t}"] = bollinger["mid"]
|
||||
informative[f"{coin}bb_upperband-period_{t}"] = bollinger["upper"]
|
||||
|
||||
informative[f"%-{coin}bb_width-period_{t}"] = (
|
||||
informative[f"{coin}bb_upperband-period_{t}"]
|
||||
- informative[f"{coin}bb_lowerband-period_{t}"]
|
||||
) / informative[f"{coin}bb_middleband-period_{t}"]
|
||||
informative[f"%-{coin}close-bb_lower-period_{t}"] = (
|
||||
informative["close"] / informative[f"{coin}bb_lowerband-period_{t}"]
|
||||
)
|
||||
|
||||
informative[f"%-{coin}relative_volume-period_{t}"] = (
|
||||
informative["volume"] / informative["volume"].rolling(t).mean()
|
||||
)
|
||||
|
||||
indicators = [col for col in informative if col.startswith("%")]
|
||||
# This loop duplicates and shifts all indicators to add a sense of recency to data
|
||||
for n in range(self.freqai_info["feature_parameters"]["include_shifted_candles"] + 1):
|
||||
if n == 0:
|
||||
continue
|
||||
informative_shift = informative[indicators].shift(n)
|
||||
informative_shift = informative_shift.add_suffix("_shift-" + str(n))
|
||||
informative = pd.concat((informative, informative_shift), axis=1)
|
||||
|
||||
df = merge_informative_pair(df, informative, self.config["timeframe"], tf, ffill=True)
|
||||
skip_columns = [
|
||||
(s + "_" + tf) for s in ["date", "open", "high", "low", "close", "volume"]
|
||||
]
|
||||
df = df.drop(columns=skip_columns)
|
||||
|
||||
# Add generalized indicators here (because in live, it will call this
|
||||
# function to populate indicators during training). Notice how we ensure not to
|
||||
# add them multiple times
|
||||
if set_generalized_indicators:
|
||||
df["%-day_of_week"] = (df["date"].dt.dayofweek + 1) / 7
|
||||
df["%-hour_of_day"] = (df["date"].dt.hour + 1) / 25
|
||||
|
||||
# user adds targets here by prepending them with &- (see convention below)
|
||||
# If user wishes to use multiple targets, a multioutput prediction model
|
||||
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
||||
df["&-s_close"] = (
|
||||
df["close"]
|
||||
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||
.mean()
|
||||
/ df["close"]
|
||||
- 1
|
||||
)
|
||||
|
||||
return df
|
||||
```
|
||||
|
||||
In the presented example, the user does not wish to pass the `bb_lowerband` as a feature to the model,
|
||||
and has therefore not prepended it with `%`. The user does, however, wish to pass `bb_width` to the
|
||||
model for training/prediction and has therefore prepended it with `%`.
|
||||
|
||||
After having defined the `base features`, the next step is to expand upon them using the powerful `feature_parameters` in the configuration file:
|
||||
|
||||
```json
|
||||
"freqai": {
|
||||
//...
|
||||
"feature_parameters" : {
|
||||
"include_timeframes": ["5m","15m","4h"],
|
||||
"include_corr_pairlist": [
|
||||
"ETH/USD",
|
||||
"LINK/USD",
|
||||
"BNB/USD"
|
||||
],
|
||||
"label_period_candles": 24,
|
||||
"include_shifted_candles": 2,
|
||||
"indicator_periods_candles": [10, 20]
|
||||
},
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
The `include_timeframes` in the config above are the timeframes (`tf`) of each call to `populate_any_indicators()` in the strategy. In the presented case, the user is asking for the `5m`, `15m`, and `4h` timeframes of the `rsi`, `mfi`, `roc`, and `bb_width` to be included in the feature set.
|
||||
|
||||
You can ask for each of the defined features to be included also for informative pairs using the `include_corr_pairlist`. This means that the feature set will include all the features from `populate_any_indicators` on all the `include_timeframes` for each of the correlated pairs defined in the config (`ETH/USD`, `LINK/USD`, and `BNB/USD` in the presented example).
|
||||
|
||||
`include_shifted_candles` indicates the number of previous candles to include in the feature set. For example, `include_shifted_candles: 2` tells FreqAI to include the past 2 candles for each of the features in the feature set.
|
||||
|
||||
In total, the number of features the user of the presented example strat has created is: length of `include_timeframes` * no. features in `populate_any_indicators()` * length of `include_corr_pairlist` * no. `include_shifted_candles` * length of `indicator_periods_candles`
|
||||
$= 3 * 3 * 3 * 2 * 2 = 108$.
|
||||
|
||||
### Returning additional info from training
|
||||
|
||||
Important metrics can be returned to the strategy at the end of each model training by assigning them to `dk.data['extra_returns_per_train']['my_new_value'] = XYZ` inside the custom prediction model class.
|
||||
|
||||
FreqAI takes the `my_new_value` assigned in this dictionary and expands it to fit the dataframe that is returned to the strategy. You can then use the returned metrics in your strategy through `dataframe['my_new_value']`. An example of how return values can be used in FreqAI are the `&*_mean` and `&*_std` values that are used to [created a dynamic target threshold](freqai-configuration.md#creating-a-dynamic-target-threshold).
|
||||
|
||||
Another example, where the user wants to use live metrics from the trade database, is shown below:
|
||||
|
||||
```json
|
||||
"freqai": {
|
||||
"extra_returns_per_train": {"total_profit": 4}
|
||||
}
|
||||
```
|
||||
|
||||
You need to set the standard dictionary in the config so that FreqAI can return proper dataframe shapes. These values will likely be overridden by the prediction model, but in the case where the model has yet to set them, or needs a default initial value, the pre-set values are what will be returned.
|
||||
|
||||
## Feature normalization
|
||||
|
||||
FreqAI is strict when it comes to data normalization. The train features, $X^{train}$, are always normalized to [-1, 1] using a shifted min-max normalization:
|
||||
|
||||
$$X^{train}_{norm} = 2 * \frac{X^{train} - X^{train}.min()}{X^{train}.max() - X^{train}.min()} - 1$$
|
||||
|
||||
All other data (test data and unseen prediction data in dry/live/backtest) is always automatically normalized to the training feature space according to industry standards. FreqAI stores all the metadata required to ensure that test and prediction features will be properly normalized and that predictions are properly denormalized. For this reason, it is not recommended to eschew industry standards and modify FreqAI internals - however - advanced users can do so by inheriting `train()` in their custom `IFreqaiModel` and using their own normalization functions.
|
||||
|
||||
## Data dimensionality reduction with Principal Component Analysis
|
||||
|
||||
You can reduce the dimensionality of your features by activating the `principal_component_analysis` in the config:
|
||||
|
||||
```json
|
||||
"freqai": {
|
||||
"feature_parameters" : {
|
||||
"principal_component_analysis": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This will perform PCA on the features and reduce their dimensionality so that the explained variance of the data set is >= 0.999. Reducing data dimensionality makes training the model faster and hence allows for more up-to-date models.
|
||||
|
||||
## Inlier metric
|
||||
|
||||
The `inlier_metric` is a metric aimed at quantifying how similar a the features of a data point are to the most recent historic data points.
|
||||
|
||||
You define the lookback window by setting `inlier_metric_window` and FreqAI computes the distance between the present time point and each of the previous `inlier_metric_window` lookback points. A Weibull function is fit to each of the lookback distributions and its cumulative distribution function (CDF) is used to produce a quantile for each lookback point. The `inlier_metric` is then computed for each time point as the average of the corresponding lookback quantiles. The figure below explains the concept for an `inlier_metric_window` of 5.
|
||||
|
||||

|
||||
|
||||
FreqAI adds the `inlier_metric` to the training features and hence gives the model access to a novel type of temporal information.
|
||||
|
||||
This function does **not** remove outliers from the data set.
|
||||
|
||||
## Weighting features for temporal importance
|
||||
|
||||
FreqAI allows you to set a `weight_factor` to weight recent data more strongly than past data via an exponential function:
|
||||
|
||||
$$ W_i = \exp(\frac{-i}{\alpha*n}) $$
|
||||
|
||||
where $W_i$ is the weight of data point $i$ in a total set of $n$ data points. Below is a figure showing the effect of different weight factors on the data points in a feature set.
|
||||
|
||||

|
||||
|
||||
## Outlier detection
|
||||
|
||||
Equity and crypto markets suffer from a high level of non-patterned noise in the form of outlier data points. FreqAI implements a variety of methods to identify such outliers and hence mitigate risk.
|
||||
|
||||
### Identifying outliers with the Dissimilarity Index (DI)
|
||||
|
||||
The Dissimilarity Index (DI) aims to quantify the uncertainty associated with each prediction made by the model.
|
||||
|
||||
You can tell FreqAI to remove outlier data points from the training/test data sets using the DI by including the following statement in the config:
|
||||
|
||||
```json
|
||||
"freqai": {
|
||||
"feature_parameters" : {
|
||||
"DI_threshold": 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The DI allows predictions which are outliers (not existent in the model feature space) to be thrown out due to low levels of certainty. To do so, FreqAI measures the distance between each training data point (feature vector), $X_{a}$, and all other training data points:
|
||||
|
||||
$$ d_{ab} = \sqrt{\sum_{j=1}^p(X_{a,j}-X_{b,j})^2} $$
|
||||
|
||||
where $d_{ab}$ is the distance between the normalized points $a$ and $b$, and $p$ is the number of features, i.e., the length of the vector $X$. The characteristic distance, $\overline{d}$, for a set of training data points is simply the mean of the average distances:
|
||||
|
||||
$$ \overline{d} = \sum_{a=1}^n(\sum_{b=1}^n(d_{ab}/n)/n) $$
|
||||
|
||||
$\overline{d}$ quantifies the spread of the training data, which is compared to the distance between a new prediction feature vectors, $X_k$ and all the training data:
|
||||
|
||||
$$ d_k = \arg \min d_{k,i} $$
|
||||
|
||||
This enables the estimation of the Dissimilarity Index as:
|
||||
|
||||
$$ DI_k = d_k/\overline{d} $$
|
||||
|
||||
You can tweak the DI through the `DI_threshold` to increase or decrease the extrapolation of the trained model. A higher `DI_threshold` means that the DI is more lenient and allows predictions further away from the training data to be used whilst a lower `DI_threshold` has the opposite effect and hence discards more predictions.
|
||||
|
||||
Below is a figure that describes the DI for a 3D data set.
|
||||
|
||||

|
||||
|
||||
### Identifying outliers using a Support Vector Machine (SVM)
|
||||
|
||||
You can tell FreqAI to remove outlier data points from the training/test data sets using a Support Vector Machine (SVM) by including the following statement in the config:
|
||||
|
||||
```json
|
||||
"freqai": {
|
||||
"feature_parameters" : {
|
||||
"use_SVM_to_remove_outliers": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The SVM will be trained on the training data and any data point that the SVM deems to be beyond the feature space will be removed.
|
||||
|
||||
FreqAI uses `sklearn.linear_model.SGDOneClassSVM` (details are available on scikit-learn's webpage [here](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDOneClassSVM.html) (external website)) and you can elect to provide additional parameters for the SVM, such as `shuffle`, and `nu`.
|
||||
|
||||
The parameter `shuffle` is by default set to `False` to ensure consistent results. If it is set to `True`, running the SVM multiple times on the same data set might result in different outcomes due to `max_iter` being to low for the algorithm to reach the demanded `tol`. Increasing `max_iter` solves this issue but causes the procedure to take longer time.
|
||||
|
||||
The parameter `nu`, *very* broadly, is the amount of data points that should be considered outliers and should be between 0 and 1.
|
||||
|
||||
### Identifying outliers with DBSCAN
|
||||
|
||||
You can configure FreqAI to use DBSCAN to cluster and remove outliers from the training/test data set or incoming outliers from predictions, by activating `use_DBSCAN_to_remove_outliers` in the config:
|
||||
|
||||
```json
|
||||
"freqai": {
|
||||
"feature_parameters" : {
|
||||
"use_DBSCAN_to_remove_outliers": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
DBSCAN is an unsupervised machine learning algorithm that clusters data without needing to know how many clusters there should be.
|
||||
|
||||
Given a number of data points $N$, and a distance $\varepsilon$, DBSCAN clusters the data set by setting all data points that have $N-1$ other data points within a distance of $\varepsilon$ as *core points*. A data point that is within a distance of $\varepsilon$ from a *core point* but that does not have $N-1$ other data points within a distance of $\varepsilon$ from itself is considered an *edge point*. A cluster is then the collection of *core points* and *edge points*. Data points that have no other data points at a distance $<\varepsilon$ are considered outliers. The figure below shows a cluster with $N = 3$.
|
||||
|
||||

|
||||
|
||||
FreqAI uses `sklearn.cluster.DBSCAN` (details are available on scikit-learn's webpage [here](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html) (external website)) with `min_samples` ($N$) taken as 1/4 of the no. of time points (candles) in the feature set. `eps` ($\varepsilon$) is computed automatically as the elbow point in the *k-distance graph* computed from the nearest neighbors in the pairwise distances of all data points in the feature set.
|
51
docs/freqai-parameter-table.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Parameter table
|
||||
|
||||
The table below will list all configuration parameters available for FreqAI. Some of the parameters are exemplified in `config_examples/config_freqai.example.json`.
|
||||
|
||||
Mandatory parameters are marked as **Required** and have to be set in one of the suggested ways.
|
||||
|
||||
| Parameter | Description |
|
||||
|------------|-------------|
|
||||
| | **General configuration parameters**
|
||||
| `freqai` | **Required.** <br> The parent dictionary containing all the parameters for controlling FreqAI. <br> **Datatype:** Dictionary.
|
||||
| `train_period_days` | **Required.** <br> Number of days to use for the training data (width of the sliding window). <br> **Datatype:** Positive integer.
|
||||
| `backtest_period_days` | **Required.** <br> Number of days to inference from the trained model before sliding the `train_period_days` window defined above, and retraining the model during backtesting (more info [here](freqai-running.md#backtesting)). This can be fractional days, but beware that the provided `timerange` will be divided by this number to yield the number of trainings necessary to complete the backtest. <br> **Datatype:** Float.
|
||||
| `identifier` | **Required.** <br> A unique ID for the current model. If models are saved to disk, the `identifier` allows for reloading specific pre-trained models/data. <br> **Datatype:** String.
|
||||
| `live_retrain_hours` | Frequency of retraining during dry/live runs. <br> **Datatype:** Float > 0. <br> Default: `0` (models retrain as often as possible).
|
||||
| `expiration_hours` | Avoid making predictions if a model is more than `expiration_hours` old. <br> **Datatype:** Positive integer. <br> Default: `0` (models never expire).
|
||||
| `purge_old_models` | Delete obsolete models. <br> **Datatype:** Boolean. <br> Default: `False` (all historic models remain on disk).
|
||||
| `save_backtest_models` | Save models to disk when running backtesting. Backtesting operates most efficiently by saving the prediction data and reusing them directly for subsequent runs (when you wish to tune entry/exit parameters). Saving backtesting models to disk also allows to use the same model files for starting a dry/live instance with the same model `identifier`. <br> **Datatype:** Boolean. <br> Default: `False` (no models are saved).
|
||||
| `fit_live_predictions_candles` | Number of historical candles to use for computing target (label) statistics from prediction data, instead of from the training dataset (more information can be found [here](freqai-configuration.md#creating-a-dynamic-target-threshold)). <br> **Datatype:** Positive integer.
|
||||
| `follow_mode` | Use a `follower` that will look for models associated with a specific `identifier` and load those for inferencing. A `follower` will **not** train new models. <br> **Datatype:** Boolean. <br> Default: `False`.
|
||||
| `continual_learning` | Use the final state of the most recently trained model as starting point for the new model, allowing for incremental learning (more information can be found [here](freqai-running.md#continual-learning)). <br> **Datatype:** Boolean. <br> Default: `False`.
|
||||
| | **Feature parameters**
|
||||
| `feature_parameters` | A dictionary containing the parameters used to engineer the feature set. Details and examples are shown [here](freqai-feature-engineering.md). <br> **Datatype:** Dictionary.
|
||||
| `include_timeframes` | A list of timeframes that all indicators in `populate_any_indicators` will be created for. The list is added as features to the base indicators dataset. <br> **Datatype:** List of timeframes (strings).
|
||||
| `include_corr_pairlist` | A list of correlated coins that FreqAI will add as additional features to all `pair_whitelist` coins. All indicators set in `populate_any_indicators` during feature engineering (see details [here](freqai-feature-engineering.md)) will be created for each correlated coin. The correlated coins features are added to the base indicators dataset. <br> **Datatype:** List of assets (strings).
|
||||
| `label_period_candles` | Number of candles into the future that the labels are created for. This is used in `populate_any_indicators` (see `templates/FreqaiExampleStrategy.py` for detailed usage). You can create custom labels and choose whether to make use of this parameter or not. <br> **Datatype:** Positive integer.
|
||||
| `include_shifted_candles` | Add features from previous candles to subsequent candles with the intent of adding historical information. If used, FreqAI will duplicate and shift all features from the `include_shifted_candles` previous candles so that the information is available for the subsequent candle. <br> **Datatype:** Positive integer.
|
||||
| `weight_factor` | Weight training data points according to their recency (see details [here](freqai-feature-engineering.md#weighting-features-for-temporal-importance)). <br> **Datatype:** Positive float (typically < 1).
|
||||
| `indicator_max_period_candles` | **No longer used (#7325)**. Replaced by `startup_candle_count` which is set in the [strategy](freqai-configuration.md#building-a-freqai-strategy). `startup_candle_count` is timeframe independent and defines the maximum *period* used in `populate_any_indicators()` for indicator creation. FreqAI uses this parameter together with the maximum timeframe in `include_time_frames` to calculate how many data points to download such that the first data point does not include a NaN. <br> **Datatype:** Positive integer.
|
||||
| `indicator_periods_candles` | Time periods to calculate indicators for. The indicators are added to the base indicator dataset. <br> **Datatype:** List of positive integers.
|
||||
| `principal_component_analysis` | Automatically reduce the dimensionality of the data set using Principal Component Analysis. See details about how it works [here](#reducing-data-dimensionality-with-principal-component-analysis) <br> **Datatype:** Boolean. <br> Default: `False`.
|
||||
| `plot_feature_importances` | Create a feature importance plot for each model for the top/bottom `plot_feature_importances` number of features. <br> **Datatype:** Integer. <br> Default: `0`.
|
||||
| `DI_threshold` | Activates the use of the Dissimilarity Index for outlier detection when set to > 0. See details about how it works [here](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di). <br> **Datatype:** Positive float (typically < 1).
|
||||
| `use_SVM_to_remove_outliers` | Train a support vector machine to detect and remove outliers from the training dataset, as well as from incoming data points. See details about how it works [here](freqai-feature-engineering.md#identifying-outliers-using-a-support-vector-machine-svm). <br> **Datatype:** Boolean.
|
||||
| `svm_params` | All parameters available in Sklearn's `SGDOneClassSVM()`. See details about some select parameters [here](freqai-feature-engineering.md#identifying-outliers-using-a-support-vector-machine-svm). <br> **Datatype:** Dictionary.
|
||||
| `use_DBSCAN_to_remove_outliers` | Cluster data using the DBSCAN algorithm to identify and remove outliers from training and prediction data. See details about how it works [here](freqai-feature-engineering.md#identifying-outliers-with-dbscan). <br> **Datatype:** Boolean.
|
||||
| `inlier_metric_window` | If set, FreqAI adds an `inlier_metric` to the training feature set and set the lookback to be the `inlier_metric_window`, i.e., the number of previous time points to compare the current candle to. Details of how the `inlier_metric` is computed can be found [here](freqai-feature-engineering.md#inlier-metric). <br> **Datatype:** Integer. <br> Default: `0`.
|
||||
| `noise_standard_deviation` | If set, FreqAI adds noise to the training features with the aim of preventing overfitting. FreqAI generates random deviates from a gaussian distribution with a standard deviation of `noise_standard_deviation` and adds them to all data points. `noise_standard_deviation` should be kept relative to the normalized space, i.e., between -1 and 1. In other words, since data in FreqAI is always normalized to be between -1 and 1, `noise_standard_deviation: 0.05` would result in 32% of the data being randomly increased/decreased by more than 2.5% (i.e., the percent of data falling within the first standard deviation). <br> **Datatype:** Integer. <br> Default: `0`.
|
||||
| `outlier_protection_percentage` | Enable to prevent outlier detection methods from discarding too much data. If more than `outlier_protection_percentage` % of points are detected as outliers by the SVM or DBSCAN, FreqAI will log a warning message and ignore outlier detection, i.e., the original dataset will be kept intact. If the outlier protection is triggered, no predictions will be made based on the training dataset. <br> **Datatype:** Float. <br> Default: `30`.
|
||||
| `reverse_train_test_order` | Split the feature dataset (see below) and use the latest data split for training and test on historical split of the data. This allows the model to be trained up to the most recent data point, while avoiding overfitting. However, you should be careful to understand the unorthodox nature of this parameter before employing it. <br> **Datatype:** Boolean. <br> Default: `False` (no reversal).
|
||||
| | **Data split parameters**
|
||||
| `data_split_parameters` | Include any additional parameters available from Scikit-learn `test_train_split()`, which are shown [here](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) (external website). <br> **Datatype:** Dictionary.
|
||||
| `test_size` | The fraction of data that should be used for testing instead of training. <br> **Datatype:** Positive float < 1.
|
||||
| `shuffle` | Shuffle the training data points during training. Typically, to not remove the chronological order of data in time-series forecasting, this is set to `False`. <br> **Datatype:** Boolean. <br> Defaut: `False`.
|
||||
| | **Model training parameters**
|
||||
| `model_training_parameters` | A flexible dictionary that includes all parameters available by the selected model library. For example, if you use `LightGBMRegressor`, this dictionary can contain any parameter available by the `LightGBMRegressor` [here](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMRegressor.html) (external website). If you select a different model, this dictionary can contain any parameter from that model. <br> **Datatype:** Dictionary.
|
||||
| `n_estimators` | The number of boosted trees to fit in the training of the model. <br> **Datatype:** Integer.
|
||||
| `learning_rate` | Boosting learning rate during training of the model. <br> **Datatype:** Float.
|
||||
| `n_jobs`, `thread_count`, `task_type` | Set the number of threads for parallel processing and the `task_type` (`gpu` or `cpu`). Different model libraries use different parameter names. <br> **Datatype:** Float.
|
||||
| | **Extraneous parameters**
|
||||
| `keras` | If the selected model makes use of Keras (typical for Tensorflow-based prediction models), this flag needs to be activated so that the model save/loading follows Keras standards. <br> **Datatype:** Boolean. <br> Default: `False`.
|
||||
| `conv_width` | The width of a convolutional neural network input tensor. This replaces the need for shifting candles (`include_shifted_candles`) by feeding in historical data points as the second dimension of the tensor. Technically, this parameter can also be used for regressors, but it only adds computational overhead and does not change the model training/prediction. <br> **Datatype:** Integer. <br> Default: `2`.
|
156
docs/freqai-running.md
Normal file
@@ -0,0 +1,156 @@
|
||||
# Running FreqAI
|
||||
|
||||
There are two ways to train and deploy an adaptive machine learning model - live deployment and historical backtesting. In both cases, FreqAI runs/simulates periodic retraining of models as shown in the following figure:
|
||||
|
||||

|
||||
|
||||
## Live deployments
|
||||
|
||||
FreqAI can be run dry/live using the following command:
|
||||
|
||||
```bash
|
||||
freqtrade trade --strategy FreqaiExampleStrategy --config config_freqai.example.json --freqaimodel LightGBMRegressor
|
||||
```
|
||||
|
||||
When launched, FreqAI will start training a new model, with a new `identifier`, based on the config settings. Following training, the model will be used to make predictions on incoming candles until a new model is available. New models are typically generated as often as possible, with FreqAI managing an internal queue of the coin pairs to try to keep all models equally up to date. FreqAI will always use the most recently trained model to make predictions on incoming live data. If you do not want FreqAI to retrain new models as often as possible, you can set `live_retrain_hours` to tell FreqAI to wait at least that number of hours before training a new model. Additionally, you can set `expired_hours` to tell FreqAI to avoid making predictions on models that are older than that number of hours.
|
||||
|
||||
Trained models are by default saved to disk to allow for reuse during backtesting or after a crash. You can opt to [purge old models](#purging-old-model-data) to save disk space by setting `"purge_old_models": true` in the config.
|
||||
|
||||
To start a dry/live run from a saved backtest model (or from a previously crashed dry/live session), you only need to specify the `identifier` of the specific model:
|
||||
|
||||
```json
|
||||
"freqai": {
|
||||
"identifier": "example",
|
||||
"live_retrain_hours": 0.5
|
||||
}
|
||||
```
|
||||
|
||||
In this case, although FreqAI will initiate with a pre-trained model, it will still check to see how much time has elapsed since the model was trained. If a full `live_retrain_hours` has elapsed since the end of the loaded model, FreqAI will start training a new model.
|
||||
|
||||
### Automatic data download
|
||||
|
||||
FreqAI automatically downloads the proper amount of data needed to ensure training of a model through the defined `train_period_days` and `startup_candle_count` (see the [parameter table](freqai-parameter-table.md) for detailed descriptions of these parameters).
|
||||
|
||||
### Saving prediction data
|
||||
|
||||
All predictions made during the lifetime of a specific `identifier` model are stored in `historic_predictions.pkl` to allow for reloading after a crash or changes made to the config.
|
||||
|
||||
### Purging old model data
|
||||
|
||||
FreqAI stores new model files after each successful training. These files become obsolete as new models are generated to adapt to new market conditions. If you are planning to leave FreqAI running for extended periods of time with high frequency retraining, you should enable `purge_old_models` in the config:
|
||||
|
||||
```json
|
||||
"freqai": {
|
||||
"purge_old_models": true,
|
||||
}
|
||||
```
|
||||
|
||||
This will automatically purge all models older than the two most recently trained ones to save disk space.
|
||||
|
||||
## Backtesting
|
||||
|
||||
The FreqAI backtesting module can be executed with the following command:
|
||||
|
||||
```bash
|
||||
freqtrade backtesting --strategy FreqaiExampleStrategy --strategy-path freqtrade/templates --config config_examples/config_freqai.example.json --freqaimodel LightGBMRegressor --timerange 20210501-20210701
|
||||
```
|
||||
|
||||
If this command has never been executed with the existing config file, FreqAI will train a new model
|
||||
for each pair, for each backtesting window within the expanded `--timerange`.
|
||||
|
||||
Backtesting mode requires [downloading the necessary data](#downloading-data-to-cover-the-full-backtest-period) before deployment (unlike in dry/live mode where FreqAI handles the data downloading automatically). You should be careful to consider that the time range of the downloaded data is more than the backtesting time range. This is because FreqAI needs data prior to the desired backtesting time range in order to train a model to be ready to make predictions on the first candle of the set backtesting time range. More details on how to calculate the data to download can be found [here](#deciding-the-size-of-the-sliding-training-window-and-backtesting-duration).
|
||||
|
||||
!!! Note "Model reuse"
|
||||
Once the training is completed, you can execute the backtesting again with the same config file and
|
||||
FreqAI will find the trained models and load them instead of spending time training. This is useful
|
||||
if you want to tweak (or even hyperopt) buy and sell criteria inside the strategy. If you
|
||||
*want* to retrain a new model with the same config file, you should simply change the `identifier`.
|
||||
This way, you can return to using any model you wish by simply specifying the `identifier`.
|
||||
|
||||
---
|
||||
|
||||
### Saving prediction data
|
||||
|
||||
To allow for tweaking your strategy (**not** the features!), FreqAI will automatically save the predictions during backtesting so that they can be reused for future backtests and live runs using the same `identifier` model. This provides a performance enhancement geared towards enabling **high-level hyperopting** of entry/exit criteria.
|
||||
|
||||
An additional directory called `predictions`, which contains all the predictions stored in `hdf` format, will be created in the `unique-id` folder.
|
||||
|
||||
To change your **features**, you **must** set a new `identifier` in the config to signal to FreqAI to train new models.
|
||||
|
||||
To save the models generated during a particular backtest so that you can start a live deployment from one of them instead of training a new model, you must set `save_backtest_models` to `True` in the config.
|
||||
|
||||
### Downloading data to cover the full backtest period
|
||||
|
||||
For live/dry deployments, FreqAI will download the necessary data automatically. However, to use backtesting functionality, you need to download the necessary data using `download-data` (details [here](data-download.md#data-downloading)). You need to pay careful attention to understanding how much *additional* data needs to be downloaded to ensure that there is a sufficient amount of training data *before* the start of the backtesting time range. The amount of additional data can be roughly estimated by moving the start date of the time range backwards by `train_period_days` and the `startup_candle_count` (see the [parameter table](freqai-parameter-table.md) for detailed descriptions of these parameters) from the beginning of the desired backtesting time range.
|
||||
|
||||
As an example, to backtest the `--timerange 20210501-20210701` using the [example config](freqai-configuration.md#setting-up-the-configuration-file) which sets `train_period_days` to 30, together with `startup_candle_count: 40` on a maximum `include_timeframes` of 1h, the start date for the downloaded data needs to be `20210501` - 30 days - 40 * 1h / 24 hours = 20210330 (31.7 days earlier than the start of the desired training time range).
|
||||
|
||||
### Deciding the size of the sliding training window and backtesting duration
|
||||
|
||||
The backtesting time range is defined with the typical `--timerange` parameter in the configuration file. The duration of the sliding training window is set by `train_period_days`, whilst `backtest_period_days` is the sliding backtesting window, both in number of days (`backtest_period_days` can be
|
||||
a float to indicate sub-daily retraining in live/dry mode). In the presented [example config](freqai-configuration.md#setting-up-the-configuration-file) (found in `config_examples/config_freqai.example.json`), the user is asking FreqAI to use a training period of 30 days and backtest on the subsequent 7 days. After the training of the model, FreqAI will backtest the subsequent 7 days. The "sliding window" then moves one week forward (emulating FreqAI retraining once per week in live mode) and the new model uses the previous 30 days (including the 7 days used for backtesting by the previous model) to train. This is repeated until the end of `--timerange`. This means that if you set `--timerange 20210501-20210701`, FreqAI will have trained 8 separate models at the end of `--timerange` (because the full range comprises 8 weeks).
|
||||
|
||||
!!! Note
|
||||
Although fractional `backtest_period_days` is allowed, you should be aware that the `--timerange` is divided by this value to determine the number of models that FreqAI will need to train in order to backtest the full range. For example, by setting a `--timerange` of 10 days, and a `backtest_period_days` of 0.1, FreqAI will need to train 100 models per pair to complete the full backtest. Because of this, a true backtest of FreqAI adaptive training would take a *very* long time. The best way to fully test a model is to run it dry and let it train constantly. In this case, backtesting would take the exact same amount of time as a dry run.
|
||||
|
||||
## Defining model expirations
|
||||
|
||||
During dry/live mode, FreqAI trains each coin pair sequentially (on separate threads/GPU from the main Freqtrade bot). This means that there is always an age discrepancy between models. If you are training on 50 pairs, and each pair requires 5 minutes to train, the oldest model will be over 4 hours old. This may be undesirable if the characteristic time scale (the trade duration target) for a strategy is less than 4 hours. You can decide to only make trade entries if the model is less than a certain number of hours old by setting the `expiration_hours` in the config file:
|
||||
|
||||
```json
|
||||
"freqai": {
|
||||
"expiration_hours": 0.5,
|
||||
}
|
||||
```
|
||||
|
||||
In the presented example config, the user will only allow predictions on models that are less than 1/2 hours old.
|
||||
|
||||
## Controlling the model learning process
|
||||
|
||||
Model training parameters are unique to the selected machine learning library. FreqAI allows you to set any parameter for any library using the `model_training_parameters` dictionary in the config. The example config (found in `config_examples/config_freqai.example.json`) shows some of the example parameters associated with `Catboost` and `LightGBM`, but you can add any parameters available in those libraries or any other machine learning library you choose to implement.
|
||||
|
||||
Data split parameters are defined in `data_split_parameters` which can be any parameters associated with Scikit-learn's `train_test_split()` function. `train_test_split()` has a parameters called `shuffle` which allows to shuffle the data or keep it unshuffled. This is particularly useful to avoid biasing training with temporally auto-correlated data. More details about these parameters can be found the [Scikit-learn website](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) (external website).
|
||||
|
||||
The FreqAI specific parameter `label_period_candles` defines the offset (number of candles into the future) used for the `labels`. In the presented [example config](freqai-configuration.md#setting-up-the-configuration-file), the user is asking for `labels` that are 24 candles in the future.
|
||||
|
||||
## Continual learning
|
||||
|
||||
You can choose to adopt a continual learning scheme by setting `"continual_learning": true` in the config. By enabling `continual_learning`, after training an initial model from scratch, subsequent trainings will start from the final model state of the preceding training. This gives the new model a "memory" of the previous state. By default, this is set to `False` which means that all new models are trained from scratch, without input from previous models.
|
||||
|
||||
## Hyperopt
|
||||
|
||||
You can hyperopt using the same command as for [typical Freqtrade hyperopt](hyperopt.md):
|
||||
|
||||
```bash
|
||||
freqtrade hyperopt --hyperopt-loss SharpeHyperOptLoss --strategy FreqaiExampleStrategy --freqaimodel LightGBMRegressor --strategy-path freqtrade/templates --config config_examples/config_freqai.example.json --timerange 20220428-20220507
|
||||
```
|
||||
|
||||
`hyperopt` requires you to have the data pre-downloaded in the same fashion as if you were doing [backtesting](#backtesting). In addition, you must consider some restrictions when trying to hyperopt FreqAI strategies:
|
||||
|
||||
- The `--analyze-per-epoch` hyperopt parameter is not compatible with FreqAI.
|
||||
- It's not possible to hyperopt indicators in the `populate_any_indicators()` function. This means that you cannot optimize model parameters using hyperopt. Apart from this exception, it is possible to optimize all other [spaces](hyperopt.md#running-hyperopt-with-smaller-search-space).
|
||||
- The backtesting instructions also apply to hyperopt.
|
||||
|
||||
The best method for combining hyperopt and FreqAI is to focus on hyperopting entry/exit thresholds/criteria. You need to focus on hyperopting parameters that are not used in your features. For example, you should not try to hyperopt rolling window lengths in the feature creation, or any part of the FreqAI config which changes predictions. In order to efficiently hyperopt the FreqAI strategy, FreqAI stores predictions as dataframes and reuses them. Hence the requirement to hyperopt entry/exit thresholds/criteria only.
|
||||
|
||||
A good example of a hyperoptable parameter in FreqAI is a threshold for the [Dissimilarity Index (DI)](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di) `DI_values` beyond which we consider data points as outliers:
|
||||
|
||||
```python
|
||||
di_max = IntParameter(low=1, high=20, default=10, space='buy', optimize=True, load=True)
|
||||
dataframe['outlier'] = np.where(dataframe['DI_values'] > self.di_max.value/10, 1, 0)
|
||||
```
|
||||
|
||||
This specific hyperopt would help you understand the appropriate `DI_values` for your particular parameter space.
|
||||
|
||||
## Setting up a follower
|
||||
|
||||
You can indicate to the bot that it should not train models, but instead should look for models trained by a leader with a specific `identifier` by defining:
|
||||
|
||||
```json
|
||||
"freqai": {
|
||||
"follow_mode": true,
|
||||
"identifier": "example"
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the user has a leader bot with the `"identifier": "example"`. The leader bot is already running or is launched simultaneously with the follower. The follower will load models created by the leader and inference them to obtain predictions instead of training its own models.
|
71
docs/freqai-spice-rack.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# Using the `spice_rack`
|
||||
|
||||
!!! Note:
|
||||
`spice_rack` indicators should not be used exclusively for entries and exits, the following example is just a demonstration of syntax. `spice_rack` indicators should **always** be used to support existing strategies.
|
||||
|
||||
The `spice_rack` is aimed at users who do not wish to deal with setting up `FreqAI` confgs, but instead prefer to interact with `FreqAI` similar to a `talib` indicator. In this case, the user can instead simply add two keys to their config:
|
||||
|
||||
```json
|
||||
"freqai_spice_rack": true,
|
||||
"freqai_identifier": "spicey-id",
|
||||
```
|
||||
|
||||
Which tells `FreqAI` to set up a pre-set `FreqAI` instance automatically under the hood with preset parameters. Now the user can access a suite of custom `FreqAI` supercharged indicators inside their strategy by placing the following code into `populate_indicators`:
|
||||
|
||||
```python
|
||||
dataframe['dissimilarity_index'] = self.freqai.spice_rack(
|
||||
'DI_values', dataframe, metadata, self)
|
||||
dataframe['extrema'] = self.freqai.spice_rack(
|
||||
'&s-extrema', dataframe, metadata, self)
|
||||
self.freqai.close_spice_rack() # user must close the spicerack
|
||||
```
|
||||
|
||||
Users can then use these columns in concert with all their own additional indicators added to `populate_indicators` in their entry/exit criteria and strategy callback methods the same way as any typical indicator. For example:
|
||||
|
||||
```python
|
||||
def populate_entry_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
|
||||
|
||||
df.loc[
|
||||
(
|
||||
(df['dissimilarity_index'] < 1) &
|
||||
(df['extrema'] < -0.1)
|
||||
),
|
||||
'enter_long'] = 1
|
||||
|
||||
df.loc[
|
||||
(
|
||||
(df['dissimilarity_index'] < 1) &
|
||||
(df['extrema'] > 0.1)
|
||||
),
|
||||
'enter_short'] = 1
|
||||
|
||||
return df
|
||||
|
||||
def populate_exit_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
|
||||
|
||||
df.loc[
|
||||
(
|
||||
(df['dissimilarity_index'] < 1) &
|
||||
(df['extrema'] > 0.1)
|
||||
),
|
||||
|
||||
'exit_long'] = 1
|
||||
|
||||
df.loc[
|
||||
(
|
||||
|
||||
(df['dissimilarity_index'] < 1) &
|
||||
(df['extrema'] < -0.1)
|
||||
),
|
||||
'exit_short'] = 1
|
||||
|
||||
return df
|
||||
```
|
||||
|
||||
|
||||
## Available indicators
|
||||
|
||||
| Parameter | Description |
|
||||
|------------|-------------|
|
||||
| `DI_values` | **Required.** <br> The dissimilarity index of the current candle to the recent candles. More information available [here](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di) <br> **Datatype:** Floats.
|
||||
| `extrema` | **Required.** <br> A continuous prediction from FreqAI which aims to help predict if the current candle is a maxima or a minma. FreqAI aims for 1 to be a maxima and -1 to be a minima - but the values should typically hover between -0.2 and 0.2. <br> **Datatype:** Floats.
|
99
docs/freqai.md
Normal file
@@ -0,0 +1,99 @@
|
||||

|
||||
|
||||
# FreqAI
|
||||
|
||||
## Introduction
|
||||
|
||||
FreqAI is a software designed to automate a variety of tasks associated with training a predictive machine learning model to generate market forecasts given a set of input features.
|
||||
|
||||
Features include:
|
||||
|
||||
* **Self-adaptive retraining** - Retrain models during [live deployments](freqai-running.md#live-deployments) to self-adapt to the market in a supervised manner
|
||||
* **Rapid feature engineering** - Create large rich [feature sets](freqai-feature-engineering.md#feature-engineering) (10k+ features) based on simple user-created strategies
|
||||
* **High performance** - Threading allows for adaptive model retraining on a separate thread (or on GPU if available) from model inferencing (prediction) and bot trade operations. Newest models and data are kept in RAM for rapid inferencing
|
||||
* **Realistic backtesting** - Emulate self-adaptive training on historic data with a [backtesting module](freqai-running.md#backtesting) that automates retraining
|
||||
* **Extensibility** - The generalized and robust architecture allows for incorporating any [machine learning library/method](freqai-configuration.md#using-different-prediction-models) available in Python. Eight examples are currently available, including classifiers, regressors, and a convolutional neural network
|
||||
* **Smart outlier removal** - Remove outliers from training and prediction data sets using a variety of [outlier detection techniques](freqai-feature-engineering.md#outlier-detection)
|
||||
* **Crash resilience** - Store trained models to disk to make reloading from a crash fast and easy, and [purge obsolete files](freqai-running.md#purging-old-model-data) for sustained dry/live runs
|
||||
* **Automatic data normalization** - [Normalize the data](freqai-feature-engineering.md#feature-normalization) in a smart and statistically safe way
|
||||
* **Automatic data download** - Compute timeranges for data downloads and update historic data (in live deployments)
|
||||
* **Cleaning of incoming data** - Handle NaNs safely before training and model inferencing
|
||||
* **Dimensionality reduction** - Reduce the size of the training data via [Principal Component Analysis](freqai-feature-engineering.md#data-dimensionality-reduction-with-principal-component-analysis)
|
||||
* **Deploying bot fleets** - Set one bot to train models while a fleet of [follower bots](freqai-running.md#setting-up-a-follower) inference the models and handle trades
|
||||
|
||||
## Quick start
|
||||
|
||||
The easiest way to quickly test FreqAI is to run it in dry mode with the following command:
|
||||
|
||||
```bash
|
||||
freqtrade trade --config config_examples/config_freqai.example.json --strategy FreqaiExampleStrategy --freqaimodel LightGBMRegressor --strategy-path freqtrade/templates
|
||||
```
|
||||
|
||||
You will see the boot-up process of automatic data downloading, followed by simultaneous training and trading.
|
||||
|
||||
An example strategy, prediction model, and config to use as a starting points can be found in
|
||||
`freqtrade/templates/FreqaiExampleStrategy.py`, `freqtrade/freqai/prediction_models/LightGBMRegressor.py`, and
|
||||
`config_examples/config_freqai.example.json`, respectively.
|
||||
|
||||
## General approach
|
||||
|
||||
You provide FreqAI with a set of custom *base indicators* (the same way as in a [typical Freqtrade strategy](strategy-customization.md)) as well as target values (*labels*). For each pair in the whitelist, FreqAI trains a model to predict the target values based on the input of custom indicators. The models are then consistently retrained, with a predetermined frequency, to adapt to market conditions. FreqAI offers the ability to both backtest strategies (emulating reality with periodic retraining on historic data) and deploy dry/live runs. In dry/live conditions, FreqAI can be set to constant retraining in a background thread to keep models as up to date as possible.
|
||||
|
||||
An overview of the algorithm, explaining the data processing pipeline and model usage, is shown below.
|
||||
|
||||

|
||||
|
||||
### Important machine learning vocabulary
|
||||
|
||||
**Features** - the parameters, based on historic data, on which a model is trained. All features for a single candle are stored as a vector. In FreqAI, you build a feature data set from anything you can construct in the strategy.
|
||||
|
||||
**Labels** - the target values that the model is trained toward. Each feature vector is associated with a single label that is defined by you within the strategy. These labels intentionally look into the future and are what you are training the model to be able to predict.
|
||||
|
||||
**Training** - the process of "teaching" the model to match the feature sets to the associated labels. Different types of models "learn" in different ways which means that one might be better than another for a specific application. More information about the different models that are already implemented in FreqAI can be found [here](freqai-configuration.md#using-different-prediction-models).
|
||||
|
||||
**Train data** - a subset of the feature data set that is fed to the model during training to "teach" the model how to predict the targets. This data directly influences weight connections in the model.
|
||||
|
||||
**Test data** - a subset of the feature data set that is used to evaluate the performance of the model after training. This data does not influence nodal weights within the model.
|
||||
|
||||
**Inferencing** - the process of feeding a trained model new unseen data on which it will make a prediction.
|
||||
|
||||
## Install prerequisites
|
||||
|
||||
The normal Freqtrade install process will ask if you wish to install FreqAI dependencies. You should reply "yes" to this question if you wish to use FreqAI. If you did not reply yes, you can manually install these dependencies after the install with:
|
||||
|
||||
``` bash
|
||||
pip install -r requirements-freqai.txt
|
||||
```
|
||||
|
||||
!!! Note
|
||||
Catboost will not be installed on arm devices (raspberry, Mac M1, ARM based VPS, ...), since it does not provide wheels for this platform.
|
||||
|
||||
### Usage with docker
|
||||
|
||||
If you are using docker, a dedicated tag with FreqAI dependencies is available as `:freqai`. As such - you can replace the image line in your docker-compose file with `image: freqtradeorg/freqtrade:develop_freqai`. This image contains the regular FreqAI dependencies. Similar to native installs, Catboost will not be available on ARM based devices.
|
||||
|
||||
## Common pitfalls
|
||||
|
||||
FreqAI cannot be combined with dynamic `VolumePairlists` (or any pairlist filter that adds and removes pairs dynamically).
|
||||
This is for performance reasons - FreqAI relies on making quick predictions/retrains. To do this effectively,
|
||||
it needs to download all the training data at the beginning of a dry/live instance. FreqAI stores and appends
|
||||
new candles automatically for future retrains. This means that if new pairs arrive later in the dry run due to a volume pairlist, it will not have the data ready. However, FreqAI does work with the `ShufflePairlist` or a `VolumePairlist` which keeps the total pairlist constant (but reorders the pairs according to volume).
|
||||
|
||||
## Credits
|
||||
|
||||
FreqAI is developed by a group of individuals who all contribute specific skillsets to the project.
|
||||
|
||||
Conception and software development:
|
||||
Robert Caulk @robcaulk
|
||||
|
||||
Theoretical brainstorming and data analysis:
|
||||
Elin Törnquist @th0rntwig
|
||||
|
||||
Code review and software architecture brainstorming:
|
||||
@xmatthias
|
||||
|
||||
Software development:
|
||||
Wagner Costa @wagnercosta
|
||||
|
||||
Beta testing and bug reporting:
|
||||
Stefan Gehring @bloodhunter4rc, @longyu, Andrew Lawless @paranoidandy, Pascal Schmidt @smidelis, Ryan McMullan @smarmau, Juha Nykänen @suikula, Johan van der Vlugt @jooopiert, Richárd Józsa @richardjosza, Timothy Pogue @wizrds
|
@@ -40,7 +40,8 @@ pip install -r requirements-hyperopt.txt
|
||||
```
|
||||
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||
[--recursive-strategy-search] [-i TIMEFRAME]
|
||||
[--recursive-strategy-search] [--freqaimodel NAME]
|
||||
[--freqaimodel-path PATH] [-i TIMEFRAME]
|
||||
[--timerange TIMERANGE]
|
||||
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||
[--max-open-trades INT]
|
||||
@@ -53,7 +54,7 @@ usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||
[--print-all] [--no-color] [--print-json] [-j JOBS]
|
||||
[--random-state INT] [--min-trades INT]
|
||||
[--hyperopt-loss NAME] [--disable-param-export]
|
||||
[--ignore-missing-spaces]
|
||||
[--ignore-missing-spaces] [--analyze-per-epoch]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
@@ -129,6 +130,7 @@ optional arguments:
|
||||
--ignore-missing-spaces, --ignore-unparameterized-spaces
|
||||
Suppress errors for any requested Hyperopt spaces that
|
||||
do not contain any parameters.
|
||||
--analyze-per-epoch Run populate_indicators once per epoch.
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
@@ -154,6 +156,10 @@ Strategy arguments:
|
||||
--recursive-strategy-search
|
||||
Recursively search for a strategy in the strategies
|
||||
folder.
|
||||
--freqaimodel NAME Specify a custom freqaimodels.
|
||||
--freqaimodel-path PATH
|
||||
Specify additional lookup path for freqaimodels.
|
||||
|
||||
```
|
||||
|
||||
### Hyperopt checklist
|
||||
@@ -185,7 +191,7 @@ Rarely you may also need to create a [nested class](advanced-hyperopt.md#overrid
|
||||
|
||||
### Hyperopt execution logic
|
||||
|
||||
Hyperopt will first load your data into memory and will then run `populate_indicators()` once per Pair to generate all indicators.
|
||||
Hyperopt will first load your data into memory and will then run `populate_indicators()` once per Pair to generate all indicators, unless `--analyze-per-epoch` is specified.
|
||||
|
||||
Hyperopt will then spawn into different processes (number of processors, or `-j <n>`), and run backtesting over and over again, changing the parameters that are part of the `--spaces` defined.
|
||||
|
||||
@@ -426,9 +432,10 @@ While this strategy is most likely too simple to provide consistent profit, it s
|
||||
`range` property may also be used with `DecimalParameter` and `CategoricalParameter`. `RealParameter` does not provide this property due to infinite search space.
|
||||
|
||||
??? Hint "Performance tip"
|
||||
By doing the calculation of all possible indicators in `populate_indicators()`, the calculation of the indicator happens only once for every parameter.
|
||||
While this may slow down the hyperopt startup speed, the overall performance will increase as the Hyperopt execution itself may pick the same value for multiple epochs (changing other values).
|
||||
You should however try to use space ranges as small as possible. Every new column will require more memory, and every possibility hyperopt can try will increase the search space.
|
||||
During normal hyperopting, indicators are calculated once and supplied to each epoch, linearly increasing RAM usage as a factor of increasing cores. As this also has performance implications, hyperopt provides `--analyze-per-epoch` which will move the execution of `populate_indicators()` to the epoch process, calculating a single value per parameter per epoch instead of using the `.range` functionality. In this case, `.range` functionality will only return the actually used value. This will reduce RAM usage, but increase CPU usage. However, your hyperopting run will be less likely to fail due to Out Of Memory (OOM) issues.
|
||||
|
||||
In either case, you should try to use space ranges as small as possible this will improve CPU/RAM usage in both scenarios.
|
||||
|
||||
|
||||
## Optimizing protections
|
||||
|
||||
@@ -879,6 +886,7 @@ To combat these, you have multiple options:
|
||||
* Avoid using `--timeframe-detail` (this loads a lot of additional data into memory).
|
||||
* Reduce the number of parallel processes (`-j <n>`).
|
||||
* Increase the memory of your machine.
|
||||
* Use `--analyze-per-epoch` if you're using a lot of parameters with `.range` functionality.
|
||||
|
||||
|
||||
## The objective has been evaluated at this point before.
|
||||
|
@@ -22,6 +22,7 @@ You may also use something like `.*DOWN/BTC` or `.*UP/BTC` to exclude leveraged
|
||||
|
||||
* [`StaticPairList`](#static-pair-list) (default, if not configured differently)
|
||||
* [`VolumePairList`](#volume-pair-list)
|
||||
* [`ProducerPairList`](#producerpairlist)
|
||||
* [`AgeFilter`](#agefilter)
|
||||
* [`OffsetFilter`](#offsetfilter)
|
||||
* [`PerformanceFilter`](#performancefilter)
|
||||
@@ -84,7 +85,7 @@ Filtering instances (not the first position in the list) will not apply any cach
|
||||
|
||||
You can define a minimum volume with `min_value` - which will filter out pairs with a volume lower than the specified value in the specified timerange.
|
||||
|
||||
### VolumePairList Advanced mode
|
||||
##### VolumePairList Advanced mode
|
||||
|
||||
`VolumePairList` can also operate in an advanced mode to build volume over a given timerange of specified candle size. It utilizes exchange historical candle data, builds a typical price (calculated by (open+high+low)/3) and multiplies the typical price with every candle's volume. The sum is the `quoteVolume` over the given range. This allows different scenarios, for a more smoothened volume, when using longer ranges with larger candle sizes, or the opposite when using a short range with small candles.
|
||||
|
||||
@@ -146,6 +147,32 @@ More sophisticated approach can be used, by using `lookback_timeframe` for candl
|
||||
!!! Note
|
||||
`VolumePairList` does not support backtesting mode.
|
||||
|
||||
#### ProducerPairList
|
||||
|
||||
With `ProducerPairList`, you can reuse the pairlist from a [Producer](producer-consumer.md) without explicitly defining the pairlist on each consumer.
|
||||
|
||||
[Consumer mode](producer-consumer.md) is required for this pairlist to work.
|
||||
|
||||
The pairlist will perform a check on active pairs against the current exchange configuration to avoid attempting to trade on invalid markets.
|
||||
|
||||
You can limit the length of the pairlist with the optional parameter `number_assets`. Using `"number_assets"=0` or omitting this key will result in the reuse of all producer pairs valid for the current setup.
|
||||
|
||||
```json
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "ProducerPairList",
|
||||
"number_assets": 5,
|
||||
"producer_name": "default",
|
||||
}
|
||||
],
|
||||
```
|
||||
|
||||
|
||||
!!! Tip "Combining pairlists"
|
||||
This pairlist can be combined with all other pairlists and filters for further pairlist reduction, and can also act as an "additional" pairlist, on top of already defined pairs.
|
||||
`ProducerPairList` can also be used multiple times in sequence, combining the pairs from multiple producers.
|
||||
Obviously in complex such configurations, the Producer may not provide data for all pairs, so the strategy must be fit for this.
|
||||
|
||||
#### AgeFilter
|
||||
|
||||
Removes pairs that have been listed on the exchange for less than `min_days_listed` days (defaults to `10`) or more than `max_days_listed` days (defaults `None` mean infinity).
|
||||
|
@@ -326,6 +326,16 @@ python3 -m pip install --upgrade pip
|
||||
python3 -m pip install -e .
|
||||
```
|
||||
|
||||
Patch conda libta-lib (Linux only)
|
||||
|
||||
```bash
|
||||
# Ensure that the environment is active!
|
||||
conda activate freqtrade-conda
|
||||
|
||||
cd build_helpers
|
||||
bash install_ta-lib.sh ${CONDA_PREFIX} nosudo
|
||||
```
|
||||
|
||||
### Congratulations
|
||||
|
||||
[You are ready](#you-are-ready), and run the bot
|
||||
|
@@ -13,7 +13,7 @@
|
||||
Please only use advanced trading modes when you know how freqtrade (and your strategy) works.
|
||||
Also, never risk more than what you can afford to lose.
|
||||
|
||||
Please read the [strategy migration guide](strategy_migration.md#strategy-migration-between-v2-and-v3) to migrate your strategy from a freqtrade v2 strategy, to v3 strategy that can short and trade futures.
|
||||
If you already have an existing strategy, please read the [strategy migration guide](strategy_migration.md#strategy-migration-between-v2-and-v3) to migrate your strategy from a freqtrade v2 strategy, to strategy of version 3 which can short and trade futures.
|
||||
|
||||
## Shorting
|
||||
|
||||
@@ -62,6 +62,13 @@ You will also have to pick a "margin mode" (explanation below) - with freqtrade
|
||||
"margin_mode": "isolated"
|
||||
```
|
||||
|
||||
##### Pair namings
|
||||
|
||||
Freqtrade follows the [ccxt naming conventions for futures](https://docs.ccxt.com/en/latest/manual.html?#perpetual-swap-perpetual-future).
|
||||
A futures pair will therefore have the naming of `base/quote:settle` (e.g. `ETH/USDT:USDT`).
|
||||
|
||||
Binance is currently still an exception to this naming scheme, where pairs are named `ETH/USDT` also for futures markets, but will be aligned as soon as CCXT is ready.
|
||||
|
||||
### Margin mode
|
||||
|
||||
On top of `trading_mode` - you will also have to configure your `margin_mode`.
|
||||
|
163
docs/producer-consumer.md
Normal file
@@ -0,0 +1,163 @@
|
||||
# Producer / Consumer mode
|
||||
|
||||
freqtrade provides a mechanism whereby an instance (also called `consumer`) may listen to messages from an upstream freqtrade instance (also called `producer`) using the message websocket. Mainly, `analyzed_df` and `whitelist` messages. This allows the reuse of computed indicators (and signals) for pairs in multiple bots without needing to compute them multiple times.
|
||||
|
||||
See [Message Websocket](rest-api.md#message-websocket) in the Rest API docs for setting up the `api_server` configuration for your message websocket (this will be your producer).
|
||||
|
||||
!!! Note
|
||||
We strongly recommend to set `ws_token` to something random and known only to yourself to avoid unauthorized access to your bot.
|
||||
|
||||
## Configuration
|
||||
|
||||
Enable subscribing to an instance by adding the `external_message_consumer` section to the consumer's config file.
|
||||
|
||||
```json
|
||||
{
|
||||
//...
|
||||
"external_message_consumer": {
|
||||
"enabled": true,
|
||||
"producers": [
|
||||
{
|
||||
"name": "default", // This can be any name you'd like, default is "default"
|
||||
"host": "127.0.0.1", // The host from your producer's api_server config
|
||||
"port": 8080, // The port from your producer's api_server config
|
||||
"ws_token": "sercet_Ws_t0ken" // The ws_token from your producer's api_server config
|
||||
}
|
||||
],
|
||||
// The following configurations are optional, and usually not required
|
||||
// "wait_timeout": 300,
|
||||
// "ping_timeout": 10,
|
||||
// "sleep_time": 10,
|
||||
// "remove_entry_exit_signals": false,
|
||||
// "message_size_limit": 8
|
||||
}
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
| Parameter | Description |
|
||||
|------------|-------------|
|
||||
| `enabled` | **Required.** Enable consumer mode. If set to false, all other settings in this section are ignored.<br>*Defaults to `false`.*<br> **Datatype:** boolean .
|
||||
| `producers` | **Required.** List of producers <br> **Datatype:** Array.
|
||||
| `producers.name` | **Required.** Name of this producer. This name must be used in calls to `get_producer_pairs()` and `get_producer_df()` if more than one producer is used.<br> **Datatype:** string
|
||||
| `producers.host` | **Required.** The hostname or IP address from your producer.<br> **Datatype:** string
|
||||
| `producers.port` | **Required.** The port matching the above host.<br> **Datatype:** string
|
||||
| `producers.ws_token` | **Required.** `ws_token` as configured on the producer.<br> **Datatype:** string
|
||||
| | **Optional settings**
|
||||
| `wait_timeout` | Timeout until we ping again if no message is received. <br>*Defaults to `300`.*<br> **Datatype:** Integer - in seconds.
|
||||
| `wait_timeout` | Ping timeout <br>*Defaults to `10`.*<br> **Datatype:** Integer - in seconds.
|
||||
| `sleep_time` | Sleep time before retrying to connect.<br>*Defaults to `10`.*<br> **Datatype:** Integer - in seconds.
|
||||
| `remove_entry_exit_signals` | Remove signal columns from the dataframe (set them to 0) on dataframe receipt.<br>*Defaults to `10`.*<br> **Datatype:** Integer - in seconds.
|
||||
| `message_size_limit` | Size limit per message<br>*Defaults to `8`.*<br> **Datatype:** Integer - Megabytes.
|
||||
|
||||
Instead of (or as well as) calculating indicators in `populate_indicators()` the follower instance listens on the connection to a producer instance's messages (or multiple producer instances in advanced configurations) and requests the producer's most recently analyzed dataframes for each pair in the active whitelist.
|
||||
|
||||
A consumer instance will then have a full copy of the analyzed dataframes without the need to calculate them itself.
|
||||
|
||||
## Examples
|
||||
|
||||
### Example - Producer Strategy
|
||||
|
||||
A simple strategy with multiple indicators. No special considerations are required in the strategy itself.
|
||||
|
||||
```py
|
||||
class ProducerStrategy(IStrategy):
|
||||
#...
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Calculate indicators in the standard freqtrade way which can then be broadcast to other instances
|
||||
"""
|
||||
dataframe['rsi'] = ta.RSI(dataframe)
|
||||
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
|
||||
dataframe['bb_lowerband'] = bollinger['lower']
|
||||
dataframe['bb_middleband'] = bollinger['mid']
|
||||
dataframe['bb_upperband'] = bollinger['upper']
|
||||
dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)
|
||||
|
||||
return dataframe
|
||||
|
||||
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Populates the entry signal for the given dataframe
|
||||
"""
|
||||
dataframe.loc[
|
||||
(
|
||||
(qtpylib.crossed_above(dataframe['rsi'], self.buy_rsi.value)) &
|
||||
(dataframe['tema'] <= dataframe['bb_middleband']) &
|
||||
(dataframe['tema'] > dataframe['tema'].shift(1)) &
|
||||
(dataframe['volume'] > 0)
|
||||
),
|
||||
'enter_long'] = 1
|
||||
|
||||
return dataframe
|
||||
```
|
||||
|
||||
!!! Tip "FreqAI"
|
||||
You can use this to setup [FreqAI](freqai.md) on a powerful machine, while you run consumers on simple machines like raspberries, which can interpret the signals generated from the producer in different ways.
|
||||
|
||||
|
||||
### Example - Consumer Strategy
|
||||
|
||||
A logically equivalent strategy which calculates no indicators itself, but will have the same analyzed dataframes available to make trading decisions based on the indicators calculated in the producer. In this example the consumer has the same entry criteria, however this is not necessary. The consumer may use different logic to enter/exit trades, and only use the indicators as specified.
|
||||
|
||||
```py
|
||||
class ConsumerStrategy(IStrategy):
|
||||
#...
|
||||
process_only_new_candles = False # required for consumers
|
||||
|
||||
_columns_to_expect = ['rsi_default', 'tema_default', 'bb_middleband_default']
|
||||
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Use the websocket api to get pre-populated indicators from another freqtrade instance.
|
||||
Use `self.dp.get_producer_df(pair)` to get the dataframe
|
||||
"""
|
||||
pair = metadata['pair']
|
||||
timeframe = self.timeframe
|
||||
|
||||
producer_pairs = self.dp.get_producer_pairs()
|
||||
# You can specify which producer to get pairs from via:
|
||||
# self.dp.get_producer_pairs("my_other_producer")
|
||||
|
||||
# This func returns the analyzed dataframe, and when it was analyzed
|
||||
producer_dataframe, _ = self.dp.get_producer_df(pair)
|
||||
# You can get other data if the producer makes it available:
|
||||
# self.dp.get_producer_df(
|
||||
# pair,
|
||||
# timeframe="1h",
|
||||
# candle_type=CandleType.SPOT,
|
||||
# producer_name="my_other_producer"
|
||||
# )
|
||||
|
||||
if not producer_dataframe.empty:
|
||||
# If you plan on passing the producer's entry/exit signal directly,
|
||||
# specify ffill=False or it will have unintended results
|
||||
merged_dataframe = merge_informative_pair(dataframe, producer_dataframe,
|
||||
timeframe, timeframe,
|
||||
append_timeframe=False,
|
||||
suffix="default")
|
||||
return merged_dataframe
|
||||
else:
|
||||
dataframe[self._columns_to_expect] = 0
|
||||
|
||||
return dataframe
|
||||
|
||||
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Populates the entry signal for the given dataframe
|
||||
"""
|
||||
# Use the dataframe columns as if we calculated them ourselves
|
||||
dataframe.loc[
|
||||
(
|
||||
(qtpylib.crossed_above(dataframe['rsi_default'], self.buy_rsi.value)) &
|
||||
(dataframe['tema_default'] <= dataframe['bb_middleband_default']) &
|
||||
(dataframe['tema_default'] > dataframe['tema_default'].shift(1)) &
|
||||
(dataframe['volume'] > 0)
|
||||
),
|
||||
'enter_long'] = 1
|
||||
|
||||
return dataframe
|
||||
```
|
||||
|
||||
!!! Tip "Using upstream signals"
|
||||
By setting `remove_entry_exit_signals=false`, you can also use the producer's signals directly. They should be available as `enter_long_default` (assuming `suffix="default"` was used) - and can be used as either signal directly, or as additional indicator.
|
@@ -1,6 +1,6 @@
|
||||
markdown==3.3.7
|
||||
mkdocs==1.3.1
|
||||
mkdocs-material==8.3.9
|
||||
mkdocs==1.4.0
|
||||
mkdocs-material==8.5.6
|
||||
mdx_truly_sane_lists==1.3
|
||||
pymdown-extensions==9.5
|
||||
pymdown-extensions==9.6
|
||||
jinja2==3.1.2
|
||||
|
@@ -31,7 +31,8 @@ Sample configuration:
|
||||
"jwt_secret_key": "somethingrandom",
|
||||
"CORS_origins": [],
|
||||
"username": "Freqtrader",
|
||||
"password": "SuperSecret1!"
|
||||
"password": "SuperSecret1!",
|
||||
"ws_token": "sercet_Ws_t0ken"
|
||||
},
|
||||
```
|
||||
|
||||
@@ -66,7 +67,7 @@ secrets.token_hex()
|
||||
|
||||
!!! Danger "Password selection"
|
||||
Please make sure to select a very strong, unique password to protect your bot from unauthorized access.
|
||||
Also change `jwt_secret_key` to something random (no need to remember this, but it'll be used to encrypt your session, so it better be something unique!).
|
||||
Also change `jwt_secret_key` to something random (no need to remember this, but it'll be used to encrypt your session, so it better be something unique!).
|
||||
|
||||
### Configuration with docker
|
||||
|
||||
@@ -93,7 +94,6 @@ Make sure that the following 2 lines are available in your docker-compose file:
|
||||
!!! Danger "Security warning"
|
||||
By using `8080:8080` in the docker port mapping, the API will be available to everyone connecting to the server under the correct port, so others may be able to control your bot.
|
||||
|
||||
|
||||
## Rest API
|
||||
|
||||
### Consuming the API
|
||||
@@ -163,6 +163,8 @@ python3 scripts/rest_client.py --config rest_config.json <command> [optional par
|
||||
| `strategy <strategy>` | Get specific Strategy content. **Alpha**
|
||||
| `available_pairs` | List available backtest data. **Alpha**
|
||||
| `version` | Show version.
|
||||
| `sysinfo` | Show informations about the system load.
|
||||
| `health` | Show bot health (last bot loop).
|
||||
|
||||
!!! Warning "Alpha status"
|
||||
Endpoints labeled with *Alpha status* above may change at any time without notice.
|
||||
@@ -227,6 +229,11 @@ forceexit
|
||||
Force-exit a trade.
|
||||
|
||||
:param tradeid: Id of the trade (can be received via status command)
|
||||
:param ordertype: Order type to use (must be market or limit)
|
||||
:param amount: Amount to sell. Full sell if not given
|
||||
|
||||
health
|
||||
Provides a quick health check of the running bot.
|
||||
|
||||
locks
|
||||
Return current locks
|
||||
@@ -267,7 +274,7 @@ reload_config
|
||||
Reload configuration.
|
||||
|
||||
show_config
|
||||
|
||||
|
||||
Returns part of the configuration, relevant for trading operations.
|
||||
|
||||
start
|
||||
@@ -312,12 +319,80 @@ version
|
||||
|
||||
whitelist
|
||||
Show the current whitelist.
|
||||
|
||||
```
|
||||
|
||||
### Message WebSocket
|
||||
|
||||
The API Server includes a websocket endpoint for subscribing to RPC messages from the freqtrade Bot.
|
||||
This can be used to consume real-time data from your bot, such as entry/exit fill messages, whitelist changes, populated indicators for pairs, and more.
|
||||
|
||||
This is also used to setup [Producer/Consumer mode](producer-consumer.md) in Freqtrade.
|
||||
|
||||
Assuming your rest API is set to `127.0.0.1` on port `8080`, the endpoint is available at `http://localhost:8080/api/v1/message/ws`.
|
||||
|
||||
To access the websocket endpoint, the `ws_token` is required as a query parameter in the endpoint URL.
|
||||
|
||||
To generate a safe `ws_token` you can run the following code:
|
||||
|
||||
``` python
|
||||
>>> import secrets
|
||||
>>> secrets.token_urlsafe(25)
|
||||
'hZ-y58LXyX_HZ8O1cJzVyN6ePWrLpNQv4Q'
|
||||
```
|
||||
|
||||
You would then add that token under `ws_token` in your `api_server` config. Like so:
|
||||
|
||||
``` json
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8080,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "somethingrandom",
|
||||
"CORS_origins": [],
|
||||
"username": "Freqtrader",
|
||||
"password": "SuperSecret1!",
|
||||
"ws_token": "hZ-y58LXyX_HZ8O1cJzVyN6ePWrLpNQv4Q" // <-----
|
||||
},
|
||||
```
|
||||
|
||||
You can now connect to the endpoint at `http://localhost:8080/api/v1/message/ws?token=hZ-y58LXyX_HZ8O1cJzVyN6ePWrLpNQv4Q`.
|
||||
|
||||
!!! Danger "Reuse of example tokens"
|
||||
Please do not use the above example token. To make sure you are secure, generate a completely new token.
|
||||
|
||||
#### Using the WebSocket
|
||||
|
||||
Once connected to the WebSocket, the bot will broadcast RPC messages to anyone who is subscribed to them. To subscribe to a list of messages, you must send a JSON request through the WebSocket like the one below. The `data` key must be a list of message type strings.
|
||||
|
||||
``` json
|
||||
{
|
||||
"type": "subscribe",
|
||||
"data": ["whitelist", "analyzed_df"] // A list of string message types
|
||||
}
|
||||
```
|
||||
|
||||
For a list of message types, please refer to the RPCMessageType enum in `freqtrade/enums/rpcmessagetype.py`
|
||||
|
||||
Now anytime those types of RPC messages are sent in the bot, you will receive them through the WebSocket as long as the connection is active. They typically take the same form as the request:
|
||||
|
||||
``` json
|
||||
{
|
||||
"type": "analyzed_df",
|
||||
"data": {
|
||||
"key": ["NEO/BTC", "5m", "spot"],
|
||||
"df": {}, // The dataframe
|
||||
"la": "2022-09-08 22:14:41.457786+00:00"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### OpenAPI interface
|
||||
|
||||
To enable the builtin openAPI interface (Swagger UI), specify `"enable_openapi": true` in the api_server configuration.
|
||||
This will enable the Swagger UI at the `/docs` endpoint. By default, that's running at http://localhost:8080/docs/ - but it'll depend on your settings.
|
||||
This will enable the Swagger UI at the `/docs` endpoint. By default, that's running at http://localhost:8080/docs - but it'll depend on your settings.
|
||||
|
||||
### Advanced API usage using JWT tokens
|
||||
|
||||
|
@@ -106,6 +106,12 @@ def custom_exit(self, pair: str, trade: Trade, current_time: datetime, current_r
|
||||
!!! Note
|
||||
`enter_tag` is limited to 100 characters, remaining data will be truncated.
|
||||
|
||||
!!! Warning
|
||||
There is only one `enter_tag` column, which is used for both long and short trades.
|
||||
As a consequence, this column must be treated as "last write wins" (it's just a dataframe column after all).
|
||||
In fancy situations, where multiple signals collide (or if signals are deactivated again based on different conditions), this can lead to odd results with the wrong tag applied to an entry signal.
|
||||
These results are a consequence of the strategy overwriting prior tags - where the last tag will "stick" and will be the one freqtrade will use.
|
||||
|
||||
## Exit tag
|
||||
|
||||
Similar to [Buy Tagging](#buy-tag), you can also specify a sell tag.
|
||||
|
@@ -75,7 +75,7 @@ class AwesomeStrategy(IStrategy):
|
||||
|
||||
```
|
||||
|
||||
### Stake size management
|
||||
## Stake size management
|
||||
|
||||
Called before entering a trade, makes it possible to manage your position size when placing a new trade.
|
||||
|
||||
@@ -423,7 +423,7 @@ class AwesomeStrategy(IStrategy):
|
||||
!!! Warning "Backtesting"
|
||||
Custom prices are supported in backtesting (starting with 2021.12), and orders will fill if the price falls within the candle's low/high range.
|
||||
Orders that don't fill immediately are subject to regular timeout handling, which happens once per (detail) candle.
|
||||
`custom_exit_price()` is only called for sells of type exit_signal and Custom exit. All other exit-types will use regular backtesting prices.
|
||||
`custom_exit_price()` is only called for sells of type exit_signal, Custom exit and partial exits. All other exit-types will use regular backtesting prices.
|
||||
|
||||
## Custom order timeout rules
|
||||
|
||||
@@ -623,12 +623,13 @@ class AwesomeStrategy(IStrategy):
|
||||
|
||||
!!! Warning
|
||||
`confirm_trade_exit()` can prevent stoploss exits, causing significant losses as this would ignore stoploss exits.
|
||||
`confirm_trade_exit()` will not be called for Liquidations - as liquidations are forced by the exchange, and therefore cannot be rejected.
|
||||
|
||||
## Adjust trade position
|
||||
|
||||
The `position_adjustment_enable` strategy property enables the usage of `adjust_trade_position()` callback in the strategy.
|
||||
For performance reasons, it's disabled by default and freqtrade will show a warning message on startup if enabled.
|
||||
`adjust_trade_position()` can be used to perform additional orders, for example to manage risk with DCA (Dollar Cost Averaging).
|
||||
`adjust_trade_position()` can be used to perform additional orders, for example to manage risk with DCA (Dollar Cost Averaging) or to increase or decrease positions.
|
||||
|
||||
`max_entry_position_adjustment` property is used to limit the number of additional buys per trade (on top of the first buy) that the bot can execute. By default, the value is -1 which means the bot have no limit on number of adjustment buys.
|
||||
|
||||
@@ -636,10 +637,13 @@ The strategy is expected to return a stake_amount (in stake currency) between `m
|
||||
If there are not enough funds in the wallet (the return value is above `max_stake`) then the signal will be ignored.
|
||||
Additional orders also result in additional fees and those orders don't count towards `max_open_trades`.
|
||||
|
||||
This callback is **not** called when there is an open order (either buy or sell) waiting for execution, or when you have reached the maximum amount of extra buys that you have set on `max_entry_position_adjustment`.
|
||||
This callback is **not** called when there is an open order (either buy or sell) waiting for execution.
|
||||
|
||||
`adjust_trade_position()` is called very frequently for the duration of a trade, so you must keep your implementation as performant as possible.
|
||||
|
||||
Position adjustments will always be applied in the direction of the trade, so a positive value will always increase your position, no matter if it's a long or short trade. Modifications to leverage are not possible.
|
||||
Additional Buys are ignored once you have reached the maximum amount of extra buys that you have set on `max_entry_position_adjustment`, but the callback is called anyway looking for partial exits.
|
||||
|
||||
Position adjustments will always be applied in the direction of the trade, so a positive value will always increase your position (negative values will decrease your position), no matter if it's a long or short trade. Modifications to leverage are not possible, and the stake-amount is assumed to be before applying leverage.
|
||||
|
||||
!!! Note "About stake size"
|
||||
Using fixed stake size means it will be the amount used for the first order, just like without position adjustment.
|
||||
@@ -648,12 +652,12 @@ Position adjustments will always be applied in the direction of the trade, so a
|
||||
|
||||
!!! Warning
|
||||
Stoploss is still calculated from the initial opening price, not averaged price.
|
||||
Regular stoploss rules still apply (cannot move down).
|
||||
|
||||
!!! Warning "/stopbuy"
|
||||
While `/stopbuy` command stops the bot from entering new trades, the position adjustment feature will continue buying new orders on existing trades.
|
||||
While `/stopentry` command stops the bot from entering new trades, the position adjustment feature will continue buying new orders on existing trades.
|
||||
|
||||
!!! Warning "Backtesting"
|
||||
During backtesting this callback is called for each candle in `timeframe` or `timeframe_detail`, so performance will be affected.
|
||||
During backtesting this callback is called for each candle in `timeframe` or `timeframe_detail`, so run-time performance will be affected.
|
||||
|
||||
``` python
|
||||
from freqtrade.persistence import Trade
|
||||
@@ -674,7 +678,7 @@ class DigDeeperStrategy(IStrategy):
|
||||
max_dca_multiplier = 5.5
|
||||
|
||||
# This is called when placing the initial order (opening trade)
|
||||
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
|
||||
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
|
||||
proposed_stake: float, min_stake: Optional[float], max_stake: float,
|
||||
leverage: float, entry_tag: Optional[str], side: str,
|
||||
**kwargs) -> float:
|
||||
@@ -684,22 +688,41 @@ def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: f
|
||||
return proposed_stake / self.max_dca_multiplier
|
||||
|
||||
def adjust_trade_position(self, trade: Trade, current_time: datetime,
|
||||
current_rate: float, current_profit: float, min_stake: Optional[float],
|
||||
max_stake: float, **kwargs):
|
||||
current_rate: float, current_profit: float,
|
||||
min_stake: Optional[float], max_stake: float,
|
||||
current_entry_rate: float, current_exit_rate: float,
|
||||
current_entry_profit: float, current_exit_profit: float,
|
||||
**kwargs) -> Optional[float]:
|
||||
"""
|
||||
Custom trade adjustment logic, returning the stake amount that a trade should be increased.
|
||||
This means extra buy orders with additional fees.
|
||||
Custom trade adjustment logic, returning the stake amount that a trade should be
|
||||
increased or decreased.
|
||||
This means extra buy or sell orders with additional fees.
|
||||
Only called when `position_adjustment_enable` is set to True.
|
||||
|
||||
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
||||
|
||||
When not implemented by a strategy, returns None
|
||||
|
||||
:param trade: trade object.
|
||||
:param current_time: datetime object, containing the current datetime
|
||||
:param current_rate: Current buy rate.
|
||||
:param current_profit: Current profit (as ratio), calculated based on current_rate.
|
||||
:param min_stake: Minimal stake size allowed by exchange.
|
||||
:param max_stake: Balance available for trading.
|
||||
:param min_stake: Minimal stake size allowed by exchange (for both entries and exits)
|
||||
:param max_stake: Maximum stake allowed (either through balance, or by exchange limits).
|
||||
:param current_entry_rate: Current rate using entry pricing.
|
||||
:param current_exit_rate: Current rate using exit pricing.
|
||||
:param current_entry_profit: Current profit using entry pricing.
|
||||
:param current_exit_profit: Current profit using exit pricing.
|
||||
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
||||
:return float: Stake amount to adjust your trade
|
||||
:return float: Stake amount to adjust your trade,
|
||||
Positive values to increase position, Negative values to decrease position.
|
||||
Return None for no action.
|
||||
"""
|
||||
|
||||
if current_profit > 0.05 and trade.nr_of_successful_exits == 0:
|
||||
# Take half of the profit at +5%
|
||||
return -(trade.stake_amount / 2)
|
||||
|
||||
if current_profit > -0.05:
|
||||
return None
|
||||
|
||||
@@ -734,6 +757,25 @@ def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: f
|
||||
|
||||
```
|
||||
|
||||
### Position adjust calculations
|
||||
|
||||
* Entry rates are calculated using weighted averages.
|
||||
* Exits will not influence the average entry rate.
|
||||
* Partial exit relative profit is relative to the average entry price at this point.
|
||||
* Final exit relative profit is calculated based on the total invested capital. (See example below)
|
||||
|
||||
??? example "Calculation example"
|
||||
*This example assumes 0 fees for simplicity, and a long position on an imaginary coin.*
|
||||
|
||||
* Buy 100@8\$
|
||||
* Buy 100@9\$ -> Avg price: 8.5\$
|
||||
* Sell 100@10\$ -> Avg price: 8.5\$, realized profit 150\$, 17.65%
|
||||
* Buy 150@11\$ -> Avg price: 10\$, realized profit 150\$, 17.65%
|
||||
* Sell 100@12\$ -> Avg price: 10\$, total realized profit 350\$, 20%
|
||||
* Sell 150@14\$ -> Avg price: 10\$, total realized profit 950\$, 40%
|
||||
|
||||
The total profit for this trade was 950$ on a 3350$ investment (`100@8$ + 100@9$ + 150@11$`). As such - the final relative profit is 28.35% (`950 / 3350`).
|
||||
|
||||
## Adjust Entry Price
|
||||
|
||||
The `adjust_entry_price()` callback may be used by strategy developer to refresh/replace limit orders upon arrival of new candles.
|
||||
|
@@ -166,7 +166,7 @@ Additional technical libraries can be installed as necessary, or custom indicato
|
||||
|
||||
Most indicators have an instable startup period, in which they are either not available (NaN), 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.
|
||||
This should be set to the maximum number of candles that the strategy requires to calculate stable indicators. In the case where a user includes higher timeframes with informative pairs, the `startup_candle_count` does not necessarily change. The value is the maximum period (in candles) that any of the informatives timeframes need to compute stable indicators.
|
||||
|
||||
In this example strategy, this should be set to 100 (`startup_candle_count = 100`), since the longest needed history is 100 candles.
|
||||
|
||||
@@ -264,7 +264,8 @@ def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFram
|
||||
### Exit signal rules
|
||||
|
||||
Edit the method `populate_exit_trend()` into your strategy file to update your exit strategy.
|
||||
Please note that the exit-signal is only used if `use_exit_signal` is set to true in the configuration.
|
||||
The exit-signal is only used for exits if `use_exit_signal` is set to true in the configuration.
|
||||
`use_exit_signal` will not influence [signal collision rules](#colliding-signals) - which will still apply and can prevent entries.
|
||||
|
||||
It's important to always return the dataframe without removing/modifying the columns `"open", "high", "low", "close", "volume"`, otherwise these fields would contain something unexpected.
|
||||
|
||||
@@ -617,9 +618,8 @@ Please always check the mode of operation to select the correct method to get da
|
||||
### *available_pairs*
|
||||
|
||||
``` python
|
||||
if self.dp:
|
||||
for pair, timeframe in self.dp.available_pairs:
|
||||
print(f"available {pair}, {timeframe}")
|
||||
for pair, timeframe in self.dp.available_pairs:
|
||||
print(f"available {pair}, {timeframe}")
|
||||
```
|
||||
|
||||
### *current_whitelist()*
|
||||
@@ -630,7 +630,7 @@ The strategy might look something like this:
|
||||
|
||||
*Scan through the top 10 pairs by volume using the `VolumePairList` every 5 minutes and use a 14 day RSI to buy and sell.*
|
||||
|
||||
Due to the limited available data, it's very difficult to resample `5m` candles into daily candles for use in a 14 day RSI. Most exchanges limit us to just 500 candles which effectively gives us around 1.74 daily candles. We need 14 days at least!
|
||||
Due to the limited available data, it's very difficult to resample `5m` candles into daily candles for use in a 14 day RSI. Most exchanges limit us to just 500-1000 candles which effectively gives us around 1.74 daily candles. We need 14 days at least!
|
||||
|
||||
Since we can't resample the data we will have to use an informative pair; and since the whitelist will be dynamic we don't know which pair(s) to use.
|
||||
|
||||
@@ -653,10 +653,9 @@ This is where calling `self.dp.current_whitelist()` comes in handy.
|
||||
|
||||
``` python
|
||||
# fetch live / historical candle (OHLCV) data for the first informative pair
|
||||
if self.dp:
|
||||
inf_pair, inf_timeframe = self.informative_pairs()[0]
|
||||
informative = self.dp.get_pair_dataframe(pair=inf_pair,
|
||||
timeframe=inf_timeframe)
|
||||
inf_pair, inf_timeframe = self.informative_pairs()[0]
|
||||
informative = self.dp.get_pair_dataframe(pair=inf_pair,
|
||||
timeframe=inf_timeframe)
|
||||
```
|
||||
|
||||
!!! Warning "Warning about backtesting"
|
||||
@@ -671,10 +670,9 @@ It can also be used in specific callbacks to get the signal that caused the acti
|
||||
|
||||
``` python
|
||||
# fetch current dataframe
|
||||
if self.dp:
|
||||
if self.dp.runmode.value in ('live', 'dry_run'):
|
||||
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=metadata['pair'],
|
||||
timeframe=self.timeframe)
|
||||
if self.dp.runmode.value in ('live', 'dry_run'):
|
||||
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=metadata['pair'],
|
||||
timeframe=self.timeframe)
|
||||
```
|
||||
|
||||
!!! Note "No data available"
|
||||
@@ -684,11 +682,10 @@ if self.dp:
|
||||
### *orderbook(pair, maximum)*
|
||||
|
||||
``` python
|
||||
if self.dp:
|
||||
if self.dp.runmode.value in ('live', 'dry_run'):
|
||||
ob = self.dp.orderbook(metadata['pair'], 1)
|
||||
dataframe['best_bid'] = ob['bids'][0][0]
|
||||
dataframe['best_ask'] = ob['asks'][0][0]
|
||||
if self.dp.runmode.value in ('live', 'dry_run'):
|
||||
ob = self.dp.orderbook(metadata['pair'], 1)
|
||||
dataframe['best_bid'] = ob['bids'][0][0]
|
||||
dataframe['best_ask'] = ob['asks'][0][0]
|
||||
```
|
||||
|
||||
The orderbook structure is aligned with the order structure from [ccxt](https://github.com/ccxt/ccxt/wiki/Manual#order-book-structure), so the result will look as follows:
|
||||
@@ -717,12 +714,11 @@ Therefore, using `ob['bids'][0][0]` as demonstrated above will result in using t
|
||||
### *ticker(pair)*
|
||||
|
||||
``` python
|
||||
if self.dp:
|
||||
if self.dp.runmode.value in ('live', 'dry_run'):
|
||||
ticker = self.dp.ticker(metadata['pair'])
|
||||
dataframe['last_price'] = ticker['last']
|
||||
dataframe['volume24h'] = ticker['quoteVolume']
|
||||
dataframe['vwap'] = ticker['vwap']
|
||||
if self.dp.runmode.value in ('live', 'dry_run'):
|
||||
ticker = self.dp.ticker(metadata['pair'])
|
||||
dataframe['last_price'] = ticker['last']
|
||||
dataframe['volume24h'] = ticker['quoteVolume']
|
||||
dataframe['vwap'] = ticker['vwap']
|
||||
```
|
||||
|
||||
!!! Warning
|
||||
@@ -732,7 +728,24 @@ if self.dp:
|
||||
data returned from the exchange and add appropriate error handling / defaults.
|
||||
|
||||
!!! Warning "Warning about backtesting"
|
||||
This method will always return up-to-date values - so usage during backtesting / hyperopt will lead to wrong results.
|
||||
This method will always return up-to-date values - so usage during backtesting / hyperopt without runmode checks will lead to wrong results.
|
||||
|
||||
### Send Notification
|
||||
|
||||
The dataprovider `.send_msg()` function allows you to send custom notifications from your strategy.
|
||||
Identical notifications will only be sent once per candle, unless the 2nd argument (`always_send`) is set to True.
|
||||
|
||||
``` python
|
||||
self.dp.send_msg(f"{metadata['pair']} just got hot!")
|
||||
|
||||
# Force send this notification, avoid caching (Please read warning below!)
|
||||
self.dp.send_msg(f"{metadata['pair']} just got hot!", always_send=True)
|
||||
```
|
||||
|
||||
Notifications will only be sent in trading modes (Live/Dry-run) - so this method can be called without conditions for backtesting.
|
||||
|
||||
!!! Warning "Spamming"
|
||||
You can spam yourself pretty good by setting `always_send=True` in this method. Use this with great care and only in conditions you know will not happen throughout a candle to avoid a message every 5 seconds.
|
||||
|
||||
### Complete Data-provider sample
|
||||
|
||||
@@ -812,6 +825,8 @@ Options:
|
||||
- Merge the dataframe without lookahead bias
|
||||
- Forward-fill (optional)
|
||||
|
||||
For a full sample, please refer to the [complete data provider example](#complete-data-provider-sample) below.
|
||||
|
||||
All columns of the informative dataframe will be available on the returning dataframe in a renamed fashion:
|
||||
|
||||
!!! Example "Column renaming"
|
||||
|
@@ -14,7 +14,7 @@ from freqtrade.configuration import Configuration
|
||||
|
||||
# Initialize empty configuration object
|
||||
config = Configuration.from_files([])
|
||||
# Optionally, use existing configuration file
|
||||
# Optionally (recommended), use existing configuration file
|
||||
# config = Configuration.from_files(["config.json"])
|
||||
|
||||
# Define some constants
|
||||
@@ -22,7 +22,7 @@ config["timeframe"] = "5m"
|
||||
# Name of the strategy class
|
||||
config["strategy"] = "SampleStrategy"
|
||||
# Location of the data
|
||||
data_location = Path(config['user_data_dir'], 'data', 'binance')
|
||||
data_location = config['datadir']
|
||||
# Pair to analyze - Only use one pair here
|
||||
pair = "BTC/USDT"
|
||||
```
|
||||
|
@@ -18,7 +18,7 @@ Note : `forcesell`, `forcebuy`, `emergencysell` are changed to `force_exit`, `fo
|
||||
* [`check_buy_timeout()` -> `check_entry_timeout()`](#custom_entry_timeout)
|
||||
* [`check_sell_timeout()` -> `check_exit_timeout()`](#custom_entry_timeout)
|
||||
* New `side` argument to callbacks without trade object
|
||||
* [`custom_stake_amount`](#custom-stake-amount)
|
||||
* [`custom_stake_amount`](#custom_stake_amount)
|
||||
* [`confirm_trade_entry`](#confirm_trade_entry)
|
||||
* [`custom_entry_price`](#custom_entry_price)
|
||||
* [Changed argument name in `confirm_trade_exit`](#confirm_trade_exit)
|
||||
@@ -192,7 +192,7 @@ class AwesomeStrategy(IStrategy):
|
||||
return False
|
||||
```
|
||||
|
||||
### Custom-stake-amount
|
||||
### `custom_stake_amount`
|
||||
|
||||
New string argument `side` - which can be either `"long"` or `"short"`.
|
||||
|
||||
@@ -332,8 +332,8 @@ After:
|
||||
|
||||
``` python hl_lines="2 3"
|
||||
order_time_in_force: Dict = {
|
||||
"entry": "gtc",
|
||||
"exit": "gtc",
|
||||
"entry": "GTC",
|
||||
"exit": "GTC",
|
||||
}
|
||||
```
|
||||
|
||||
|
@@ -82,6 +82,8 @@ Example configuration showing the different settings:
|
||||
"warning": "on",
|
||||
"startup": "off",
|
||||
"entry": "silent",
|
||||
"entry_fill": "on",
|
||||
"entry_cancel": "silent",
|
||||
"exit": {
|
||||
"roi": "silent",
|
||||
"emergency_exit": "on",
|
||||
@@ -90,14 +92,14 @@ Example configuration showing the different settings:
|
||||
"trailing_stop_loss": "on",
|
||||
"stop_loss": "on",
|
||||
"stoploss_on_exchange": "on",
|
||||
"custom_exit": "silent"
|
||||
"custom_exit": "silent",
|
||||
"partial_exit": "on"
|
||||
},
|
||||
"entry_cancel": "silent",
|
||||
"exit_cancel": "on",
|
||||
"entry_fill": "off",
|
||||
"exit_fill": "off",
|
||||
"protection_trigger": "off",
|
||||
"protection_trigger_global": "on",
|
||||
"strategy_msg": "off",
|
||||
"show_candle": "off"
|
||||
},
|
||||
"reload": true,
|
||||
@@ -109,7 +111,8 @@ Example configuration showing the different settings:
|
||||
`exit` notifications are sent when the order is placed, while `exit_fill` notifications are sent when the order is filled on the exchange.
|
||||
`*_fill` notifications are off by default and must be explicitly enabled.
|
||||
`protection_trigger` notifications are sent when a protection triggers and `protection_trigger_global` notifications trigger when global protections are triggered.
|
||||
`show_candle` - show candle values as part of entry/exit messages. Only possible value is "ohlc".
|
||||
`strategy_msg` - Receive notifications from the strategy, sent via `self.dp.send_msg()` from the strategy [more details](strategy-customization.md#send-notification).
|
||||
`show_candle` - show candle values as part of entry/exit messages. Only possible values are `"ohlc"` or `"off"`.
|
||||
|
||||
`balance_dust_level` will define what the `/balance` command takes as "dust" - Currencies with a balance below this will be shown.
|
||||
`reload` allows you to disable reload-buttons on selected messages.
|
||||
@@ -136,7 +139,7 @@ You can create your own keyboard in `config.json`:
|
||||
"enabled": true,
|
||||
"token": "your_telegram_token",
|
||||
"chat_id": "your_telegram_chat_id",
|
||||
"keyboard": [
|
||||
"keyboard": [
|
||||
["/daily", "/stats", "/balance", "/profit"],
|
||||
["/status table", "/performance"],
|
||||
["/reload_config", "/count", "/logs"]
|
||||
@@ -147,7 +150,7 @@ You can create your own keyboard in `config.json`:
|
||||
!!! Note "Supported Commands"
|
||||
Only the following commands are allowed. Command arguments are not supported!
|
||||
|
||||
`/start`, `/stop`, `/status`, `/status table`, `/trades`, `/profit`, `/performance`, `/daily`, `/stats`, `/count`, `/locks`, `/balance`, `/stopbuy`, `/reload_config`, `/show_config`, `/logs`, `/whitelist`, `/blacklist`, `/edge`, `/help`, `/version`
|
||||
`/start`, `/stop`, `/status`, `/status table`, `/trades`, `/profit`, `/performance`, `/daily`, `/stats`, `/count`, `/locks`, `/balance`, `/stopentry`, `/reload_config`, `/show_config`, `/logs`, `/whitelist`, `/blacklist`, `/edge`, `/help`, `/version`
|
||||
|
||||
## Telegram commands
|
||||
|
||||
@@ -159,7 +162,7 @@ official commands. You can ask at any moment for help with `/help`.
|
||||
|----------|-------------|
|
||||
| `/start` | Starts the trader
|
||||
| `/stop` | Stops the trader
|
||||
| `/stopbuy` | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
||||
| `/stopbuy | /stopentry` | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
||||
| `/reload_config` | Reloads the configuration file
|
||||
| `/show_config` | Shows part of the current configuration with relevant settings to operation
|
||||
| `/logs [limit]` | Show last log messages.
|
||||
@@ -185,7 +188,7 @@ official commands. You can ask at any moment for help with `/help`.
|
||||
| `/stats` | Shows Wins / losses by Exit reason as well as Avg. holding durations for buys and sells
|
||||
| `/exits` | Shows Wins / losses by Exit reason as well as Avg. holding durations for buys and sells
|
||||
| `/entries` | Shows Wins / losses by Exit reason as well as Avg. holding durations for buys and sells
|
||||
| `/whitelist` | Show the current whitelist
|
||||
| `/whitelist [sorted] [baseonly]` | Show the current whitelist. Optionally display in alphabetical order and/or with just the base currency of each pairing.
|
||||
| `/blacklist [pair]` | Show the current blacklist, or adds a pair to the blacklist.
|
||||
| `/edge` | Show validated pairs by Edge if it is enabled.
|
||||
| `/help` | Show help message
|
||||
@@ -223,16 +226,16 @@ Once all positions are sold, run `/stop` to completely stop the bot.
|
||||
For each open trade, the bot will send you the following message.
|
||||
Enter Tag is configurable via Strategy.
|
||||
|
||||
> **Trade ID:** `123` `(since 1 days ago)`
|
||||
> **Current Pair:** CVC/BTC
|
||||
> **Trade ID:** `123` `(since 1 days ago)`
|
||||
> **Current Pair:** CVC/BTC
|
||||
> **Direction:** Long
|
||||
> **Leverage:** 1.0
|
||||
> **Amount:** `26.64180098`
|
||||
> **Amount:** `26.64180098`
|
||||
> **Enter Tag:** Awesome Long Signal
|
||||
> **Open Rate:** `0.00007489`
|
||||
> **Current Rate:** `0.00007489`
|
||||
> **Current Profit:** `12.95%`
|
||||
> **Stoploss:** `0.00007389 (-0.02%)`
|
||||
> **Open Rate:** `0.00007489`
|
||||
> **Current Rate:** `0.00007489`
|
||||
> **Current Profit:** `12.95%`
|
||||
> **Stoploss:** `0.00007389 (-0.02%)`
|
||||
|
||||
### /status table
|
||||
|
||||
@@ -259,26 +262,26 @@ current max
|
||||
|
||||
Return a summary of your profit/loss and performance.
|
||||
|
||||
> **ROI:** Close trades
|
||||
> ∙ `0.00485701 BTC (2.2%) (15.2 Σ%)`
|
||||
> ∙ `62.968 USD`
|
||||
> **ROI:** All trades
|
||||
> ∙ `0.00255280 BTC (1.5%) (6.43 Σ%)`
|
||||
> ∙ `33.095 EUR`
|
||||
>
|
||||
> **Total Trade Count:** `138`
|
||||
> **First Trade opened:** `3 days ago`
|
||||
> **Latest Trade opened:** `2 minutes ago`
|
||||
> **Avg. Duration:** `2:33:45`
|
||||
> **Best Performing:** `PAY/BTC: 50.23%`
|
||||
> **Trading volume:** `0.5 BTC`
|
||||
> **Profit factor:** `1.04`
|
||||
> **Max Drawdown:** `9.23% (0.01255 BTC)`
|
||||
> **ROI:** Close trades
|
||||
> ∙ `0.00485701 BTC (2.2%) (15.2 Σ%)`
|
||||
> ∙ `62.968 USD`
|
||||
> **ROI:** All trades
|
||||
> ∙ `0.00255280 BTC (1.5%) (6.43 Σ%)`
|
||||
> ∙ `33.095 EUR`
|
||||
>
|
||||
> **Total Trade Count:** `138`
|
||||
> **First Trade opened:** `3 days ago`
|
||||
> **Latest Trade opened:** `2 minutes ago`
|
||||
> **Avg. Duration:** `2:33:45`
|
||||
> **Best Performing:** `PAY/BTC: 50.23%`
|
||||
> **Trading volume:** `0.5 BTC`
|
||||
> **Profit factor:** `1.04`
|
||||
> **Max Drawdown:** `9.23% (0.01255 BTC)`
|
||||
|
||||
The relative profit of `1.2%` is the average profit per trade.
|
||||
The relative profit of `15.2 Σ%` is be based on the starting capital - so in this case, the starting capital was `0.00485701 * 1.152 = 0.00738 BTC`.
|
||||
Starting capital is either taken from the `available_capital` setting, or calculated by using current wallet size - profits.
|
||||
Profit Factor is calculated as gross profits / gross losses - and should serve as an overall metric for the strategy.
|
||||
The relative profit of `1.2%` is the average profit per trade.
|
||||
The relative profit of `15.2 Σ%` is be based on the starting capital - so in this case, the starting capital was `0.00485701 * 1.152 = 0.00738 BTC`.
|
||||
Starting capital is either taken from the `available_capital` setting, or calculated by using current wallet size - profits.
|
||||
Profit Factor is calculated as gross profits / gross losses - and should serve as an overall metric for the strategy.
|
||||
Max drawdown corresponds to the backtesting metric `Absolute Drawdown (Account)` - calculated as `(Absolute Drawdown) / (DrawdownHigh + startingBalance)`.
|
||||
|
||||
### /forceexit <trade_id>
|
||||
@@ -307,27 +310,27 @@ Note that for this to work, `force_entry_enable` needs to be set to true.
|
||||
### /performance
|
||||
|
||||
Return the performance of each crypto-currency the bot has sold.
|
||||
> Performance:
|
||||
> 1. `RCN/BTC 0.003 BTC (57.77%) (1)`
|
||||
> 2. `PAY/BTC 0.0012 BTC (56.91%) (1)`
|
||||
> 3. `VIB/BTC 0.0011 BTC (47.07%) (1)`
|
||||
> 4. `SALT/BTC 0.0010 BTC (30.24%) (1)`
|
||||
> 5. `STORJ/BTC 0.0009 BTC (27.24%) (1)`
|
||||
> ...
|
||||
> Performance:
|
||||
> 1. `RCN/BTC 0.003 BTC (57.77%) (1)`
|
||||
> 2. `PAY/BTC 0.0012 BTC (56.91%) (1)`
|
||||
> 3. `VIB/BTC 0.0011 BTC (47.07%) (1)`
|
||||
> 4. `SALT/BTC 0.0010 BTC (30.24%) (1)`
|
||||
> 5. `STORJ/BTC 0.0009 BTC (27.24%) (1)`
|
||||
> ...
|
||||
|
||||
### /balance
|
||||
|
||||
Return the balance of all crypto-currency your have on the exchange.
|
||||
|
||||
> **Currency:** BTC
|
||||
> **Available:** 3.05890234
|
||||
> **Balance:** 3.05890234
|
||||
> **Pending:** 0.0
|
||||
> **Currency:** BTC
|
||||
> **Available:** 3.05890234
|
||||
> **Balance:** 3.05890234
|
||||
> **Pending:** 0.0
|
||||
|
||||
> **Currency:** CVC
|
||||
> **Available:** 86.64180098
|
||||
> **Balance:** 86.64180098
|
||||
> **Pending:** 0.0
|
||||
> **Currency:** CVC
|
||||
> **Available:** 86.64180098
|
||||
> **Balance:** 86.64180098
|
||||
> **Pending:** 0.0
|
||||
|
||||
### /daily <n>
|
||||
|
||||
@@ -374,7 +377,7 @@ Month (count) Profit BTC Profit USD Profit %
|
||||
|
||||
Shows the current whitelist
|
||||
|
||||
> Using whitelist `StaticPairList` with 22 pairs
|
||||
> Using whitelist `StaticPairList` with 22 pairs
|
||||
> `IOTA/BTC, NEO/BTC, TRX/BTC, VET/BTC, ADA/BTC, ETC/BTC, NCASH/BTC, DASH/BTC, XRP/BTC, XVG/BTC, EOS/BTC, LTC/BTC, OMG/BTC, BTG/BTC, LSK/BTC, ZEC/BTC, HOT/BTC, IOTX/BTC, XMR/BTC, AST/BTC, XLM/BTC, NANO/BTC`
|
||||
|
||||
### /blacklist [pair]
|
||||
@@ -384,7 +387,7 @@ If Pair is set, then this pair will be added to the pairlist.
|
||||
Also supports multiple pairs, separated by a space.
|
||||
Use `/reload_config` to reset the blacklist.
|
||||
|
||||
> Using blacklist `StaticPairList` with 2 pairs
|
||||
> Using blacklist `StaticPairList` with 2 pairs
|
||||
>`DODGE/BTC`, `HOT/BTC`.
|
||||
|
||||
### /edge
|
||||
|
@@ -37,3 +37,12 @@ pip install -e .
|
||||
# Ensure freqUI is at the latest version
|
||||
freqtrade install-ui
|
||||
```
|
||||
|
||||
### Problems updating
|
||||
|
||||
Update-problems usually come missing dependencies (you didn't follow the above instructions) - or from updated dependencies, which fail to install (for example TA-lib).
|
||||
Please refer to the corresponding installation sections (common problems linked below)
|
||||
|
||||
Common problems and their solutions:
|
||||
|
||||
* [ta-lib update on windows](windows_installation.md#2-install-ta-lib)
|
||||
|
@@ -525,12 +525,14 @@ 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] [-v] [-c PATH]
|
||||
usage: freqtrade test-pairlist [-h] [--userdir PATH] [-v] [-c PATH]
|
||||
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]
|
||||
[-1] [--print-json] [--exchange EXCHANGE]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default:
|
||||
@@ -611,6 +613,26 @@ Common arguments:
|
||||
|
||||
```
|
||||
|
||||
### Webserver mode - docker
|
||||
|
||||
You can also use webserver mode via docker.
|
||||
Starting a one-off container requires the configuration of the port explicitly, as ports are not exposed by default.
|
||||
You can use `docker-compose run --rm -p 127.0.0.1:8080:8080 freqtrade webserver` to start a one-off container that'll be removed once you stop it. This assumes that port 8080 is still available and no other bot is running on that port.
|
||||
|
||||
Alternatively, you can reconfigure the docker-compose file to have the command updated:
|
||||
|
||||
``` yml
|
||||
command: >
|
||||
webserver
|
||||
--config /freqtrade/user_data/config.json
|
||||
```
|
||||
|
||||
You can now use `docker-compose up` to start the webserver.
|
||||
This assumes that the configuration has a webserver enabled and configured for docker (listening port = `0.0.0.0`).
|
||||
|
||||
!!! Tip
|
||||
Don't forget to reset the command back to the trade command if you want to start a live or dry-run bot.
|
||||
|
||||
## Show previous Backtest results
|
||||
|
||||
Allows you to show previous backtest results.
|
||||
|
@@ -23,7 +23,7 @@ git clone https://github.com/freqtrade/freqtrade.git
|
||||
|
||||
Install ta-lib according to the [ta-lib documentation](https://github.com/mrjbq7/ta-lib#windows).
|
||||
|
||||
As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial pre-compiled windows Wheels [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib), which need to be downloaded and installed using `pip install TA_Lib-0.4.24-cp38-cp38-win_amd64.whl` (make sure to use the version matching your python version).
|
||||
As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial pre-compiled windows Wheels [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib), which need to be downloaded and installed using `pip install TA_Lib-0.4.25-cp38-cp38-win_amd64.whl` (make sure to use the version matching your python version).
|
||||
|
||||
Freqtrade provides these dependencies for the latest 3 Python versions (3.8, 3.9 and 3.10) and for 64bit Windows.
|
||||
Other versions must be downloaded from the above link.
|
||||
@@ -34,7 +34,7 @@ python -m venv .env
|
||||
.env\Scripts\activate.ps1
|
||||
# optionally install ta-lib from wheel
|
||||
# Eventually adjust the below filename to match the downloaded wheel
|
||||
pip install build_helpers/TA_Lib-0.4.19-cp38-cp38-win_amd64.whl
|
||||
pip install --find-links build_helpers\ TA-Lib -U
|
||||
pip install -r requirements.txt
|
||||
pip install -e .
|
||||
freqtrade
|
||||
|
@@ -9,6 +9,7 @@ dependencies:
|
||||
- pandas
|
||||
- pip
|
||||
|
||||
- py-find-1st
|
||||
- aiohttp
|
||||
- SQLAlchemy
|
||||
- python-telegram-bot
|
||||
@@ -33,6 +34,7 @@ dependencies:
|
||||
- schedule
|
||||
- python-dateutil
|
||||
- joblib
|
||||
- pyarrow
|
||||
|
||||
|
||||
# ============================
|
||||
@@ -64,7 +66,7 @@ dependencies:
|
||||
|
||||
- pip:
|
||||
- pycoingecko
|
||||
- py_find_1st
|
||||
# - py_find_1st
|
||||
- tables
|
||||
- pytest-random-order
|
||||
- ccxt
|
||||
|
@@ -1,5 +1,5 @@
|
||||
""" Freqtrade bot """
|
||||
__version__ = '2022.7'
|
||||
__version__ = '2022.10.dev'
|
||||
|
||||
if 'dev' in __version__:
|
||||
try:
|
||||
|
@@ -12,7 +12,8 @@ from freqtrade.constants import DEFAULT_CONFIG
|
||||
|
||||
ARGS_COMMON = ["verbosity", "logfile", "version", "config", "datadir", "user_data_dir"]
|
||||
|
||||
ARGS_STRATEGY = ["strategy", "strategy_path", "recursive_strategy_search"]
|
||||
ARGS_STRATEGY = ["strategy", "strategy_path", "recursive_strategy_search", "freqaimodel",
|
||||
"freqaimodel_path"]
|
||||
|
||||
ARGS_TRADE = ["db_url", "sd_notify", "dry_run", "dry_run_wallet", "fee"]
|
||||
|
||||
@@ -33,7 +34,7 @@ ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
|
||||
"print_colorized", "print_json", "hyperopt_jobs",
|
||||
"hyperopt_random_state", "hyperopt_min_trades",
|
||||
"hyperopt_loss", "disableparamexport",
|
||||
"hyperopt_ignore_missing_space"]
|
||||
"hyperopt_ignore_missing_space", "analyze_per_epoch"]
|
||||
|
||||
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
|
||||
|
||||
@@ -52,8 +53,8 @@ ARGS_LIST_PAIRS = ["exchange", "print_list", "list_pairs_print_json", "print_one
|
||||
"print_csv", "base_currencies", "quote_currencies", "list_pairs_all",
|
||||
"trading_mode"]
|
||||
|
||||
ARGS_TEST_PAIRLIST = ["verbosity", "config", "quote_currencies", "print_one_column",
|
||||
"list_pairs_print_json", "exchange"]
|
||||
ARGS_TEST_PAIRLIST = ["user_data_dir", "verbosity", "config", "quote_currencies",
|
||||
"print_one_column", "list_pairs_print_json", "exchange"]
|
||||
|
||||
ARGS_CREATE_USERDIR = ["user_data_dir", "reset"]
|
||||
|
||||
@@ -61,14 +62,14 @@ ARGS_BUILD_CONFIG = ["config"]
|
||||
|
||||
ARGS_BUILD_STRATEGY = ["user_data_dir", "strategy", "template"]
|
||||
|
||||
ARGS_CONVERT_DATA = ["pairs", "format_from", "format_to", "erase"]
|
||||
ARGS_CONVERT_DATA = ["pairs", "format_from", "format_to", "erase", "exchange"]
|
||||
|
||||
ARGS_CONVERT_DATA_OHLCV = ARGS_CONVERT_DATA + ["timeframes", "exchange", "trading_mode",
|
||||
ARGS_CONVERT_DATA_OHLCV = ARGS_CONVERT_DATA + ["timeframes", "trading_mode",
|
||||
"candle_types"]
|
||||
|
||||
ARGS_CONVERT_TRADES = ["pairs", "timeframes", "exchange", "dataformat_ohlcv", "dataformat_trades"]
|
||||
|
||||
ARGS_LIST_DATA = ["exchange", "dataformat_ohlcv", "pairs", "trading_mode"]
|
||||
ARGS_LIST_DATA = ["exchange", "dataformat_ohlcv", "pairs", "trading_mode", "show_timerange"]
|
||||
|
||||
ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "new_pairs_days", "include_inactive",
|
||||
"timerange", "download_trades", "exchange", "timeframes",
|
||||
|
@@ -67,7 +67,7 @@ def ask_user_config() -> Dict[str, Any]:
|
||||
"type": "text",
|
||||
"name": "stake_amount",
|
||||
"message": f"Please insert your stake amount (Number or '{UNLIMITED_STAKE_AMOUNT}'):",
|
||||
"default": "100",
|
||||
"default": "unlimited",
|
||||
"validate": lambda val: val == UNLIMITED_STAKE_AMOUNT or validate_is_float(val),
|
||||
"filter": lambda val: '"' + UNLIMITED_STAKE_AMOUNT + '"'
|
||||
if val == UNLIMITED_STAKE_AMOUNT
|
||||
@@ -164,7 +164,7 @@ def ask_user_config() -> Dict[str, Any]:
|
||||
"when": lambda x: x['telegram']
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"type": "password",
|
||||
"name": "telegram_chat_id",
|
||||
"message": "Insert Telegram chat id",
|
||||
"when": lambda x: x['telegram']
|
||||
@@ -191,7 +191,7 @@ def ask_user_config() -> Dict[str, Any]:
|
||||
"when": lambda x: x['api_server']
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"type": "password",
|
||||
"name": "api_server_password",
|
||||
"message": "Insert api-server password",
|
||||
"when": lambda x: x['api_server']
|
||||
@@ -211,6 +211,7 @@ def ask_user_config() -> Dict[str, Any]:
|
||||
)
|
||||
# Force JWT token to be a random string
|
||||
answers['api_server_jwt_key'] = secrets.token_hex()
|
||||
answers['api_server_ws_token'] = secrets.token_urlsafe(25)
|
||||
|
||||
return answers
|
||||
|
||||
|
@@ -69,7 +69,7 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
metavar='PATH',
|
||||
),
|
||||
"datadir": Arg(
|
||||
'-d', '--datadir',
|
||||
'-d', '--datadir', '--data-dir',
|
||||
help='Path to directory with historical backtesting data.',
|
||||
metavar='PATH',
|
||||
),
|
||||
@@ -255,6 +255,13 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
nargs='+',
|
||||
default='default',
|
||||
),
|
||||
"analyze_per_epoch": Arg(
|
||||
'--analyze-per-epoch',
|
||||
help='Run populate_indicators once per epoch.',
|
||||
action='store_true',
|
||||
default=False,
|
||||
),
|
||||
|
||||
"print_all": Arg(
|
||||
'--print-all',
|
||||
help='Print all results, not only the best ones.',
|
||||
@@ -367,7 +374,7 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
metavar='BASE_CURRENCY',
|
||||
),
|
||||
"trading_mode": Arg(
|
||||
'--trading-mode',
|
||||
'--trading-mode', '--tradingmode',
|
||||
help='Select Trading mode',
|
||||
choices=constants.TRADING_MODES,
|
||||
),
|
||||
@@ -386,7 +393,8 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
# Download data
|
||||
"pairs_file": Arg(
|
||||
'--pairs-file',
|
||||
help='File containing a list of pairs to download.',
|
||||
help='File containing a list of pairs. '
|
||||
'Takes precedence over --pairs or pairs configured in the configuration.',
|
||||
metavar='FILE',
|
||||
),
|
||||
"days": Arg(
|
||||
@@ -432,7 +440,12 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
"dataformat_trades": Arg(
|
||||
'--data-format-trades',
|
||||
help='Storage format for downloaded trades data. (default: `jsongz`).',
|
||||
choices=constants.AVAILABLE_DATAHANDLERS,
|
||||
choices=constants.AVAILABLE_DATAHANDLERS_TRADES,
|
||||
),
|
||||
"show_timerange": Arg(
|
||||
'--show-timerange',
|
||||
help='Show timerange available for available data. (May take a while to calculate).',
|
||||
action='store_true',
|
||||
),
|
||||
"exchange": Arg(
|
||||
'--exchange',
|
||||
@@ -443,14 +456,12 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
'-t', '--timeframes',
|
||||
help='Specify which tickers to download. Space-separated list. '
|
||||
'Default: `1m 5m`.',
|
||||
choices=['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h',
|
||||
'6h', '8h', '12h', '1d', '3d', '1w', '2w', '1M', '1y'],
|
||||
default=['1m', '5m'],
|
||||
nargs='+',
|
||||
),
|
||||
"prepend_data": Arg(
|
||||
'--prepend',
|
||||
help='Allow data prepending.',
|
||||
help='Allow data prepending. (Data-appending is disabled)',
|
||||
action='store_true',
|
||||
),
|
||||
"erase": Arg(
|
||||
@@ -647,4 +658,14 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
nargs='+',
|
||||
default=[],
|
||||
),
|
||||
"freqaimodel": Arg(
|
||||
'--freqaimodel',
|
||||
help='Specify a custom freqaimodels.',
|
||||
metavar='NAME',
|
||||
),
|
||||
"freqaimodel_path": Arg(
|
||||
'--freqaimodel-path',
|
||||
help='Specify additional lookup path for freqaimodels.',
|
||||
metavar='PATH',
|
||||
),
|
||||
}
|
||||
|
@@ -5,14 +5,15 @@ from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from freqtrade.configuration import TimeRange, setup_utils_configuration
|
||||
from freqtrade.constants import DATETIME_PRINT_FORMAT
|
||||
from freqtrade.data.converter import convert_ohlcv_format, convert_trades_format
|
||||
from freqtrade.data.history import (convert_trades_to_ohlcv, refresh_backtest_ohlcv_data,
|
||||
refresh_backtest_trades_data)
|
||||
from freqtrade.enums import CandleType, RunMode, TradingMode
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange import timeframe_to_minutes
|
||||
from freqtrade.exchange.exchange import market_is_active
|
||||
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
||||
from freqtrade.exchange import Exchange, market_is_active, timeframe_to_minutes
|
||||
from freqtrade.freqai.utils import setup_freqai_spice_rack
|
||||
from freqtrade.plugins.pairlist.pairlist_helpers import dynamic_expand_pairlist, expand_pairlist
|
||||
from freqtrade.resolvers import ExchangeResolver
|
||||
|
||||
|
||||
@@ -48,9 +49,14 @@ def start_download_data(args: Dict[str, Any]) -> None:
|
||||
|
||||
# Init exchange
|
||||
exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config, validate=False)
|
||||
|
||||
if config.get('freqai_spice_rack', False):
|
||||
config = setup_freqai_spice_rack(config, exchange)
|
||||
|
||||
markets = [p for p, m in exchange.markets.items() if market_is_active(m)
|
||||
or config.get('include_inactive')]
|
||||
expanded_pairs = expand_pairlist(config['pairs'], markets)
|
||||
|
||||
expanded_pairs = dynamic_expand_pairlist(config, markets)
|
||||
|
||||
# Manual validations of relevant settings
|
||||
if not config['exchange'].get('skip_pair_validation', False):
|
||||
@@ -62,37 +68,7 @@ def start_download_data(args: Dict[str, Any]) -> None:
|
||||
exchange.validate_timeframes(timeframe)
|
||||
|
||||
try:
|
||||
|
||||
if config.get('download_trades'):
|
||||
if config.get('trading_mode') == 'futures':
|
||||
raise OperationalException("Trade download not supported for futures.")
|
||||
pairs_not_available = refresh_backtest_trades_data(
|
||||
exchange, pairs=expanded_pairs, datadir=config['datadir'],
|
||||
timerange=timerange, new_pairs_days=config['new_pairs_days'],
|
||||
erase=bool(config.get('erase')), data_format=config['dataformat_trades'])
|
||||
|
||||
# Convert downloaded trade data to different timeframes
|
||||
convert_trades_to_ohlcv(
|
||||
pairs=expanded_pairs, timeframes=config['timeframes'],
|
||||
datadir=config['datadir'], timerange=timerange, erase=bool(config.get('erase')),
|
||||
data_format_ohlcv=config['dataformat_ohlcv'],
|
||||
data_format_trades=config['dataformat_trades'],
|
||||
)
|
||||
else:
|
||||
if not exchange._ft_has.get('ohlcv_has_history', True):
|
||||
raise OperationalException(
|
||||
f"Historic klines not available for {exchange.name}. "
|
||||
"Please use `--dl-trades` instead for this exchange "
|
||||
"(will unfortunately take a long time)."
|
||||
)
|
||||
pairs_not_available = refresh_backtest_ohlcv_data(
|
||||
exchange, pairs=expanded_pairs, timeframes=config['timeframes'],
|
||||
datadir=config['datadir'], timerange=timerange,
|
||||
new_pairs_days=config['new_pairs_days'],
|
||||
erase=bool(config.get('erase')), data_format=config['dataformat_ohlcv'],
|
||||
trading_mode=config.get('trading_mode', 'spot'),
|
||||
prepend=config.get('prepend_data', False)
|
||||
)
|
||||
pairs_not_available = download_trades(exchange, expanded_pairs, config, timerange)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
sys.exit("SIGINT received, aborting ...")
|
||||
@@ -103,6 +79,42 @@ def start_download_data(args: Dict[str, Any]) -> None:
|
||||
f"on exchange {exchange.name}.")
|
||||
|
||||
|
||||
def download_trades(exchange: Exchange, expanded_pairs: list,
|
||||
config: Dict[str, Any], timerange: TimeRange) -> list:
|
||||
if config.get('download_trades'):
|
||||
if config.get('trading_mode') == 'futures':
|
||||
raise OperationalException("Trade download not supported for futures.")
|
||||
pairs_not_available = refresh_backtest_trades_data(
|
||||
exchange, pairs=expanded_pairs, datadir=config['datadir'],
|
||||
timerange=timerange, new_pairs_days=config['new_pairs_days'],
|
||||
erase=bool(config.get('erase')), data_format=config['dataformat_trades'])
|
||||
|
||||
# Convert downloaded trade data to different timeframes
|
||||
convert_trades_to_ohlcv(
|
||||
pairs=expanded_pairs, timeframes=config['timeframes'],
|
||||
datadir=config['datadir'], timerange=timerange, erase=bool(config.get('erase')),
|
||||
data_format_ohlcv=config['dataformat_ohlcv'],
|
||||
data_format_trades=config['dataformat_trades'],
|
||||
)
|
||||
else:
|
||||
if not exchange.get_option('ohlcv_has_history', True):
|
||||
raise OperationalException(
|
||||
f"Historic klines not available for {exchange.name}. "
|
||||
"Please use `--dl-trades` instead for this exchange "
|
||||
"(will unfortunately take a long time)."
|
||||
)
|
||||
pairs_not_available = refresh_backtest_ohlcv_data(
|
||||
exchange, pairs=expanded_pairs, timeframes=config['timeframes'],
|
||||
datadir=config['datadir'], timerange=timerange,
|
||||
new_pairs_days=config['new_pairs_days'],
|
||||
erase=bool(config.get('erase')), data_format=config['dataformat_ohlcv'],
|
||||
trading_mode=config.get('trading_mode', 'spot'),
|
||||
prepend=config.get('prepend_data', False)
|
||||
)
|
||||
|
||||
return pairs_not_available
|
||||
|
||||
|
||||
def start_convert_trades(args: Dict[str, Any]) -> None:
|
||||
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_EXCHANGE)
|
||||
@@ -176,17 +188,31 @@ def start_list_data(args: Dict[str, Any]) -> None:
|
||||
paircombs = [comb for comb in paircombs if comb[0] in args['pairs']]
|
||||
|
||||
print(f"Found {len(paircombs)} pair / timeframe combinations.")
|
||||
groupedpair = defaultdict(list)
|
||||
for pair, timeframe, candle_type in sorted(
|
||||
paircombs,
|
||||
key=lambda x: (x[0], timeframe_to_minutes(x[1]), x[2])
|
||||
):
|
||||
groupedpair[(pair, candle_type)].append(timeframe)
|
||||
if not config.get('show_timerange'):
|
||||
groupedpair = defaultdict(list)
|
||||
for pair, timeframe, candle_type in sorted(
|
||||
paircombs,
|
||||
key=lambda x: (x[0], timeframe_to_minutes(x[1]), x[2])
|
||||
):
|
||||
groupedpair[(pair, candle_type)].append(timeframe)
|
||||
|
||||
if groupedpair:
|
||||
if groupedpair:
|
||||
print(tabulate([
|
||||
(pair, ', '.join(timeframes), candle_type)
|
||||
for (pair, candle_type), timeframes in groupedpair.items()
|
||||
],
|
||||
headers=("Pair", "Timeframe", "Type"),
|
||||
tablefmt='psql', stralign='right'))
|
||||
else:
|
||||
paircombs1 = [(
|
||||
pair, timeframe, candle_type,
|
||||
*dhc.ohlcv_data_min_max(pair, timeframe, candle_type)
|
||||
) for pair, timeframe, candle_type in paircombs]
|
||||
print(tabulate([
|
||||
(pair, ', '.join(timeframes), candle_type)
|
||||
for (pair, candle_type), timeframes in groupedpair.items()
|
||||
],
|
||||
headers=("Pair", "Timeframe", "Type"),
|
||||
(pair, timeframe, candle_type,
|
||||
start.strftime(DATETIME_PRINT_FORMAT),
|
||||
end.strftime(DATETIME_PRINT_FORMAT))
|
||||
for pair, timeframe, candle_type, start, end in paircombs1
|
||||
],
|
||||
headers=("Pair", "Timeframe", "Type", 'From', 'To'),
|
||||
tablefmt='psql', stralign='right'))
|
||||
|
@@ -4,7 +4,7 @@ from typing import Any, Dict
|
||||
from sqlalchemy import func
|
||||
|
||||
from freqtrade.configuration.config_setup import setup_utils_configuration
|
||||
from freqtrade.enums.runmode import RunMode
|
||||
from freqtrade.enums import RunMode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
@@ -36,24 +36,24 @@ def deploy_new_strategy(strategy_name: str, strategy_path: Path, subtemplate: st
|
||||
"""
|
||||
fallback = 'full'
|
||||
indicators = render_template_with_fallback(
|
||||
templatefile=f"subtemplates/indicators_{subtemplate}.j2",
|
||||
templatefallbackfile=f"subtemplates/indicators_{fallback}.j2",
|
||||
templatefile=f"strategy_subtemplates/indicators_{subtemplate}.j2",
|
||||
templatefallbackfile=f"strategy_subtemplates/indicators_{fallback}.j2",
|
||||
)
|
||||
buy_trend = render_template_with_fallback(
|
||||
templatefile=f"subtemplates/buy_trend_{subtemplate}.j2",
|
||||
templatefallbackfile=f"subtemplates/buy_trend_{fallback}.j2",
|
||||
templatefile=f"strategy_subtemplates/buy_trend_{subtemplate}.j2",
|
||||
templatefallbackfile=f"strategy_subtemplates/buy_trend_{fallback}.j2",
|
||||
)
|
||||
sell_trend = render_template_with_fallback(
|
||||
templatefile=f"subtemplates/sell_trend_{subtemplate}.j2",
|
||||
templatefallbackfile=f"subtemplates/sell_trend_{fallback}.j2",
|
||||
templatefile=f"strategy_subtemplates/sell_trend_{subtemplate}.j2",
|
||||
templatefallbackfile=f"strategy_subtemplates/sell_trend_{fallback}.j2",
|
||||
)
|
||||
plot_config = render_template_with_fallback(
|
||||
templatefile=f"subtemplates/plot_config_{subtemplate}.j2",
|
||||
templatefallbackfile=f"subtemplates/plot_config_{fallback}.j2",
|
||||
templatefile=f"strategy_subtemplates/plot_config_{subtemplate}.j2",
|
||||
templatefallbackfile=f"strategy_subtemplates/plot_config_{fallback}.j2",
|
||||
)
|
||||
additional_methods = render_template_with_fallback(
|
||||
templatefile=f"subtemplates/strategy_methods_{subtemplate}.j2",
|
||||
templatefallbackfile="subtemplates/strategy_methods_empty.j2",
|
||||
templatefile=f"strategy_subtemplates/strategy_methods_{subtemplate}.j2",
|
||||
templatefallbackfile="strategy_subtemplates/strategy_methods_empty.j2",
|
||||
)
|
||||
|
||||
strategy_text = render_template(templatefile='base_strategy.py.j2',
|
||||
|
@@ -1,8 +1,6 @@
|
||||
# flake8: noqa: F401
|
||||
|
||||
from freqtrade.configuration.check_exchange import check_exchange
|
||||
from freqtrade.configuration.config_setup import setup_utils_configuration
|
||||
from freqtrade.configuration.config_validation import validate_config_consistency
|
||||
from freqtrade.configuration.configuration import Configuration
|
||||
from freqtrade.configuration.PeriodicCache import PeriodicCache
|
||||
from freqtrade.configuration.timerange import TimeRange
|
||||
|
@@ -1,4 +1,5 @@
|
||||
import logging
|
||||
from collections import Counter
|
||||
from copy import deepcopy
|
||||
from typing import Any, Dict
|
||||
|
||||
@@ -84,6 +85,8 @@ def validate_config_consistency(conf: Dict[str, Any], preliminary: bool = False)
|
||||
_validate_protections(conf)
|
||||
_validate_unlimited_amount(conf)
|
||||
_validate_ask_orderbook(conf)
|
||||
_validate_freqai_hyperopt(conf)
|
||||
_validate_consumers(conf)
|
||||
validate_migrated_strategy_settings(conf)
|
||||
|
||||
# validate configuration before returning
|
||||
@@ -323,6 +326,31 @@ def _validate_pricing_rules(conf: Dict[str, Any]) -> None:
|
||||
del conf['ask_strategy']
|
||||
|
||||
|
||||
def _validate_freqai_hyperopt(conf: Dict[str, Any]) -> None:
|
||||
freqai_enabled = conf.get('freqai', {}).get('enabled', False)
|
||||
analyze_per_epoch = conf.get('analyze_per_epoch', False)
|
||||
if analyze_per_epoch and freqai_enabled:
|
||||
raise OperationalException(
|
||||
'Using analyze-per-epoch parameter is not supported with a FreqAI strategy.')
|
||||
|
||||
|
||||
def _validate_consumers(conf: Dict[str, Any]) -> None:
|
||||
emc_conf = conf.get('external_message_consumer', {})
|
||||
if emc_conf.get('enabled', False):
|
||||
if len(emc_conf.get('producers', [])) < 1:
|
||||
raise OperationalException("You must specify at least 1 Producer to connect to.")
|
||||
|
||||
producer_names = [p['name'] for p in emc_conf.get('producers', [])]
|
||||
duplicates = [item for item, count in Counter(producer_names).items() if count > 1]
|
||||
if duplicates:
|
||||
raise OperationalException(
|
||||
f"Producer names must be unique. Duplicate: {', '.join(duplicates)}")
|
||||
if conf.get('process_only_new_candles', True):
|
||||
# Warning here or require it?
|
||||
logger.warning("To receive best performance with external data, "
|
||||
"please set `process_only_new_candles` to False")
|
||||
|
||||
|
||||
def _strategy_settings(conf: Dict[str, Any]) -> None:
|
||||
|
||||
process_deprecated_setting(conf, None, 'use_sell_signal', None, 'use_exit_signal')
|
||||
|
@@ -8,11 +8,11 @@ from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from freqtrade import constants
|
||||
from freqtrade.configuration.check_exchange import check_exchange
|
||||
from freqtrade.configuration.deprecated_settings import process_temporary_deprecated_settings
|
||||
from freqtrade.configuration.directory_operations import create_datadir, create_userdata_dir
|
||||
from freqtrade.configuration.environment_vars import enironment_vars_to_dict
|
||||
from freqtrade.configuration.load_config import load_file, load_from_files
|
||||
from freqtrade.constants import Config
|
||||
from freqtrade.enums import NON_UTIL_MODES, TRADING_MODES, CandleType, RunMode, TradingMode
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.loggers import setup_logging
|
||||
@@ -30,10 +30,10 @@ class Configuration:
|
||||
|
||||
def __init__(self, args: Dict[str, Any], runmode: RunMode = None) -> None:
|
||||
self.args = args
|
||||
self.config: Optional[Dict[str, Any]] = None
|
||||
self.config: Optional[Config] = None
|
||||
self.runmode = runmode
|
||||
|
||||
def get_config(self) -> Dict[str, Any]:
|
||||
def get_config(self) -> Config:
|
||||
"""
|
||||
Return the config. Use this method to get the bot config
|
||||
:return: Dict: Bot config
|
||||
@@ -65,7 +65,7 @@ class Configuration:
|
||||
:return: Configuration dictionary
|
||||
"""
|
||||
# Load all configs
|
||||
config: Dict[str, Any] = load_from_files(self.args.get("config", []))
|
||||
config: Config = load_from_files(self.args.get("config", []))
|
||||
|
||||
# Load environment variables
|
||||
env_data = enironment_vars_to_dict()
|
||||
@@ -97,6 +97,11 @@ class Configuration:
|
||||
|
||||
self._process_analyze_options(config)
|
||||
|
||||
self._process_freqai_options(config)
|
||||
|
||||
# Import check_exchange here to avoid import cycle problems
|
||||
from freqtrade.exchange.check_exchange import check_exchange
|
||||
|
||||
# Check if the exchange set by the user is supported
|
||||
check_exchange(config, config.get('experimental', {}).get('block_bad_exchanges', True))
|
||||
|
||||
@@ -106,7 +111,7 @@ class Configuration:
|
||||
|
||||
return config
|
||||
|
||||
def _process_logging_options(self, config: Dict[str, Any]) -> None:
|
||||
def _process_logging_options(self, config: Config) -> None:
|
||||
"""
|
||||
Extract information for sys.argv and load logging configuration:
|
||||
the -v/--verbose, --logfile options
|
||||
@@ -119,7 +124,7 @@ class Configuration:
|
||||
|
||||
setup_logging(config)
|
||||
|
||||
def _process_trading_options(self, config: Dict[str, Any]) -> None:
|
||||
def _process_trading_options(self, config: Config) -> None:
|
||||
if config['runmode'] not in TRADING_MODES:
|
||||
return
|
||||
|
||||
@@ -135,7 +140,7 @@ class Configuration:
|
||||
|
||||
logger.info(f'Using DB: "{parse_db_uri_for_logging(config["db_url"])}"')
|
||||
|
||||
def _process_common_options(self, config: Dict[str, Any]) -> None:
|
||||
def _process_common_options(self, config: Config) -> None:
|
||||
|
||||
# Set strategy if not specified in config and or if it's non default
|
||||
if self.args.get('strategy') or not config.get('strategy'):
|
||||
@@ -159,7 +164,7 @@ class Configuration:
|
||||
if 'sd_notify' in self.args and self.args['sd_notify']:
|
||||
config['internals'].update({'sd_notify': True})
|
||||
|
||||
def _process_datadir_options(self, config: Dict[str, Any]) -> None:
|
||||
def _process_datadir_options(self, config: Config) -> None:
|
||||
"""
|
||||
Extract information for sys.argv and load directory configurations
|
||||
--user-data, --datadir
|
||||
@@ -193,7 +198,7 @@ class Configuration:
|
||||
config['exportfilename'] = (config['user_data_dir']
|
||||
/ 'backtest_results')
|
||||
|
||||
def _process_optimize_options(self, config: Dict[str, Any]) -> None:
|
||||
def _process_optimize_options(self, config: Config) -> None:
|
||||
|
||||
# This will override the strategy configuration
|
||||
self._args_to_config(config, argname='timeframe',
|
||||
@@ -300,6 +305,9 @@ class Configuration:
|
||||
self._args_to_config(config, argname='spaces',
|
||||
logstring='Parameter -s/--spaces detected: {}')
|
||||
|
||||
self._args_to_config(config, argname='analyze_per_epoch',
|
||||
logstring='Parameter --analyze-per-epoch detected.')
|
||||
|
||||
self._args_to_config(config, argname='print_all',
|
||||
logstring='Parameter --print-all detected ...')
|
||||
|
||||
@@ -375,7 +383,7 @@ class Configuration:
|
||||
self._args_to_config(config, argname="hyperopt_ignore_missing_space",
|
||||
logstring="Paramter --ignore-missing-space detected: {}")
|
||||
|
||||
def _process_plot_options(self, config: Dict[str, Any]) -> None:
|
||||
def _process_plot_options(self, config: Config) -> None:
|
||||
|
||||
self._args_to_config(config, argname='pairs',
|
||||
logstring='Using pairs {}')
|
||||
@@ -424,7 +432,10 @@ class Configuration:
|
||||
self._args_to_config(config, argname='dataformat_trades',
|
||||
logstring='Using "{}" to store trades data.')
|
||||
|
||||
def _process_data_options(self, config: Dict[str, Any]) -> None:
|
||||
self._args_to_config(config, argname='show_timerange',
|
||||
logstring='Detected --show-timerange')
|
||||
|
||||
def _process_data_options(self, config: Config) -> None:
|
||||
self._args_to_config(config, argname='new_pairs_days',
|
||||
logstring='Detected --new-pairs-days: {}')
|
||||
self._args_to_config(config, argname='trading_mode',
|
||||
@@ -435,7 +446,7 @@ class Configuration:
|
||||
self._args_to_config(config, argname='candle_types',
|
||||
logstring='Detected --candle-types: {}')
|
||||
|
||||
def _process_analyze_options(self, config: Dict[str, Any]) -> None:
|
||||
def _process_analyze_options(self, config: Config) -> None:
|
||||
self._args_to_config(config, argname='analysis_groups',
|
||||
logstring='Analysis reason groups: {}')
|
||||
|
||||
@@ -448,7 +459,7 @@ class Configuration:
|
||||
self._args_to_config(config, argname='indicator_list',
|
||||
logstring='Analysis indicator list: {}')
|
||||
|
||||
def _process_runmode(self, config: Dict[str, Any]) -> None:
|
||||
def _process_runmode(self, config: Config) -> None:
|
||||
|
||||
self._args_to_config(config, argname='dry_run',
|
||||
logstring='Parameter --dry-run detected, '
|
||||
@@ -461,7 +472,17 @@ class Configuration:
|
||||
|
||||
config.update({'runmode': self.runmode})
|
||||
|
||||
def _args_to_config(self, config: Dict[str, Any], argname: str,
|
||||
def _process_freqai_options(self, config: Config) -> None:
|
||||
|
||||
self._args_to_config(config, argname='freqaimodel',
|
||||
logstring='Using freqaimodel class name: {}')
|
||||
|
||||
self._args_to_config(config, argname='freqaimodel_path',
|
||||
logstring='Using freqaimodel path: {}')
|
||||
|
||||
return
|
||||
|
||||
def _args_to_config(self, config: Config, argname: str,
|
||||
logstring: str, logfun: Optional[Callable] = None,
|
||||
deprecated_msg: Optional[str] = None) -> None:
|
||||
"""
|
||||
@@ -484,7 +505,7 @@ class Configuration:
|
||||
if deprecated_msg:
|
||||
warnings.warn(f"DEPRECATED: {deprecated_msg}", DeprecationWarning)
|
||||
|
||||
def _resolve_pairs_list(self, config: Dict[str, Any]) -> None:
|
||||
def _resolve_pairs_list(self, config: Config) -> None:
|
||||
"""
|
||||
Helper for download script.
|
||||
Takes first found:
|
||||
|
@@ -3,15 +3,16 @@ Functions to handle deprecated settings
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Optional
|
||||
|
||||
from freqtrade.constants import Config
|
||||
from freqtrade.exceptions import OperationalException
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def check_conflicting_settings(config: Dict[str, Any],
|
||||
def check_conflicting_settings(config: Config,
|
||||
section_old: Optional[str], name_old: str,
|
||||
section_new: Optional[str], name_new: str) -> None:
|
||||
section_new_config = config.get(section_new, {}) if section_new else config
|
||||
@@ -28,7 +29,7 @@ def check_conflicting_settings(config: Dict[str, Any],
|
||||
)
|
||||
|
||||
|
||||
def process_removed_setting(config: Dict[str, Any],
|
||||
def process_removed_setting(config: Config,
|
||||
section1: str, name1: str,
|
||||
section2: Optional[str], name2: str) -> None:
|
||||
"""
|
||||
@@ -47,7 +48,7 @@ def process_removed_setting(config: Dict[str, Any],
|
||||
)
|
||||
|
||||
|
||||
def process_deprecated_setting(config: Dict[str, Any],
|
||||
def process_deprecated_setting(config: Config,
|
||||
section_old: Optional[str], name_old: str,
|
||||
section_new: Optional[str], name_new: str
|
||||
) -> None:
|
||||
@@ -69,7 +70,7 @@ def process_deprecated_setting(config: Dict[str, Any],
|
||||
del section_old_config[name_old]
|
||||
|
||||
|
||||
def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
|
||||
def process_temporary_deprecated_settings(config: Config) -> None:
|
||||
|
||||
# Kept for future deprecated / moved settings
|
||||
# check_conflicting_settings(config, 'ask_strategy', 'use_sell_signal',
|
||||
|
@@ -1,16 +1,16 @@
|
||||
import logging
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Optional
|
||||
|
||||
from freqtrade.constants import USER_DATA_FILES
|
||||
from freqtrade.constants import USER_DATA_FILES, Config
|
||||
from freqtrade.exceptions import OperationalException
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def create_datadir(config: Dict[str, Any], datadir: Optional[str] = None) -> Path:
|
||||
def create_datadir(config: Config, datadir: Optional[str] = None) -> Path:
|
||||
|
||||
folder = Path(datadir) if datadir else Path(f"{config['user_data_dir']}/data")
|
||||
if not datadir:
|
||||
|
@@ -10,7 +10,7 @@ from typing import Any, Dict, List
|
||||
|
||||
import rapidjson
|
||||
|
||||
from freqtrade.constants import MINIMAL_CONFIG
|
||||
from freqtrade.constants import MINIMAL_CONFIG, Config
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.misc import deep_merge_dicts
|
||||
|
||||
@@ -80,7 +80,7 @@ def load_from_files(files: List[str], base_path: Path = None, level: int = 0) ->
|
||||
Recursively load configuration files if specified.
|
||||
Sub-files are assumed to be relative to the initial config.
|
||||
"""
|
||||
config: Dict[str, Any] = {}
|
||||
config: Config = {}
|
||||
if level > 5:
|
||||
raise OperationalException("Config loop detected.")
|
||||
|
||||
|
@@ -3,7 +3,7 @@
|
||||
"""
|
||||
bot constants
|
||||
"""
|
||||
from typing import List, Literal, Tuple
|
||||
from typing import Any, Dict, List, Literal, Tuple
|
||||
|
||||
from freqtrade.enums import CandleType
|
||||
|
||||
@@ -23,19 +23,21 @@ REQUIRED_ORDERTIF = ['entry', 'exit']
|
||||
REQUIRED_ORDERTYPES = ['entry', 'exit', 'stoploss', 'stoploss_on_exchange']
|
||||
PRICING_SIDES = ['ask', 'bid', 'same', 'other']
|
||||
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
||||
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
||||
_ORDERTIF_POSSIBILITIES = ['GTC', 'FOK', 'IOC', 'PO']
|
||||
ORDERTIF_POSSIBILITIES = _ORDERTIF_POSSIBILITIES + [t.lower() for t in _ORDERTIF_POSSIBILITIES]
|
||||
HYPEROPT_LOSS_BUILTIN = ['ShortTradeDurHyperOptLoss', 'OnlyProfitHyperOptLoss',
|
||||
'SharpeHyperOptLoss', 'SharpeHyperOptLossDaily',
|
||||
'SortinoHyperOptLoss', 'SortinoHyperOptLossDaily',
|
||||
'CalmarHyperOptLoss',
|
||||
'MaxDrawDownHyperOptLoss', 'MaxDrawDownRelativeHyperOptLoss',
|
||||
'ProfitDrawDownHyperOptLoss']
|
||||
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList',
|
||||
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList', 'ProducerPairList',
|
||||
'AgeFilter', 'OffsetFilter', 'PerformanceFilter',
|
||||
'PrecisionFilter', 'PriceFilter', 'RangeStabilityFilter',
|
||||
'ShuffleFilter', 'SpreadFilter', 'VolatilityFilter']
|
||||
AVAILABLE_PROTECTIONS = ['CooldownPeriod', 'LowProfitPairs', 'MaxDrawdown', 'StoplossGuard']
|
||||
AVAILABLE_DATAHANDLERS = ['json', 'jsongz', 'hdf5']
|
||||
AVAILABLE_DATAHANDLERS_TRADES = ['json', 'jsongz', 'hdf5']
|
||||
AVAILABLE_DATAHANDLERS = AVAILABLE_DATAHANDLERS_TRADES + ['feather', 'parquet']
|
||||
BACKTEST_BREAKDOWNS = ['day', 'week', 'month']
|
||||
BACKTEST_CACHE_AGE = ['none', 'day', 'week', 'month']
|
||||
BACKTEST_CACHE_DEFAULT = 'day'
|
||||
@@ -55,6 +57,7 @@ FTHYPT_FILEVERSION = 'fthypt_fileversion'
|
||||
USERPATH_HYPEROPTS = 'hyperopts'
|
||||
USERPATH_STRATEGIES = 'strategies'
|
||||
USERPATH_NOTEBOOKS = 'notebooks'
|
||||
USERPATH_FREQAIMODELS = 'freqaimodels'
|
||||
|
||||
TELEGRAM_SETTING_OPTIONS = ['on', 'off', 'silent']
|
||||
WEBHOOK_FORMAT_OPTIONS = ['form', 'json', 'raw']
|
||||
@@ -240,6 +243,8 @@ CONF_SCHEMA = {
|
||||
},
|
||||
'exchange': {'$ref': '#/definitions/exchange'},
|
||||
'edge': {'$ref': '#/definitions/edge'},
|
||||
'freqai': {'$ref': '#/definitions/freqai'},
|
||||
'external_message_consumer': {'$ref': '#/definitions/external_message_consumer'},
|
||||
'experimental': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
@@ -286,11 +291,12 @@ CONF_SCHEMA = {
|
||||
'warning': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||
'startup': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||
'entry': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||
'entry_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||
'entry_fill': {'type': 'string',
|
||||
'enum': TELEGRAM_SETTING_OPTIONS,
|
||||
'default': 'off'
|
||||
},
|
||||
'entry_fill': {
|
||||
'type': 'string',
|
||||
'enum': TELEGRAM_SETTING_OPTIONS,
|
||||
'default': 'off'
|
||||
},
|
||||
'entry_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS, },
|
||||
'exit': {
|
||||
'type': ['string', 'object'],
|
||||
'additionalProperties': {
|
||||
@@ -298,12 +304,12 @@ CONF_SCHEMA = {
|
||||
'enum': TELEGRAM_SETTING_OPTIONS
|
||||
}
|
||||
},
|
||||
'exit_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||
'exit_fill': {
|
||||
'type': 'string',
|
||||
'enum': TELEGRAM_SETTING_OPTIONS,
|
||||
'default': 'on'
|
||||
},
|
||||
'exit_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||
'protection_trigger': {
|
||||
'type': 'string',
|
||||
'enum': TELEGRAM_SETTING_OPTIONS,
|
||||
@@ -312,10 +318,17 @@ CONF_SCHEMA = {
|
||||
'protection_trigger_global': {
|
||||
'type': 'string',
|
||||
'enum': TELEGRAM_SETTING_OPTIONS,
|
||||
'default': 'on'
|
||||
},
|
||||
'show_candle': {
|
||||
'type': 'string',
|
||||
'enum': ['off', 'ohlc'],
|
||||
'default': 'off'
|
||||
},
|
||||
'strategy_msg': {
|
||||
'type': 'string',
|
||||
'enum': TELEGRAM_SETTING_OPTIONS,
|
||||
'default': 'on'
|
||||
},
|
||||
}
|
||||
},
|
||||
@@ -393,6 +406,7 @@ CONF_SCHEMA = {
|
||||
},
|
||||
'username': {'type': 'string'},
|
||||
'password': {'type': 'string'},
|
||||
'ws_token': {'type': ['string', 'array'], 'items': {'type': 'string'}},
|
||||
'jwt_secret_key': {'type': 'string'},
|
||||
'CORS_origins': {'type': 'array', 'items': {'type': 'string'}},
|
||||
'verbosity': {'type': 'string', 'enum': ['error', 'info']},
|
||||
@@ -421,7 +435,7 @@ CONF_SCHEMA = {
|
||||
},
|
||||
'dataformat_trades': {
|
||||
'type': 'string',
|
||||
'enum': AVAILABLE_DATAHANDLERS,
|
||||
'enum': AVAILABLE_DATAHANDLERS_TRADES,
|
||||
'default': 'jsongz'
|
||||
},
|
||||
'position_adjustment_enable': {'type': 'boolean'},
|
||||
@@ -476,7 +490,103 @@ CONF_SCHEMA = {
|
||||
'remove_pumps': {'type': 'boolean'}
|
||||
},
|
||||
'required': ['process_throttle_secs', 'allowed_risk']
|
||||
}
|
||||
},
|
||||
'external_message_consumer': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'enabled': {'type': 'boolean', 'default': False},
|
||||
'producers': {
|
||||
'type': 'array',
|
||||
'items': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'name': {'type': 'string'},
|
||||
'host': {'type': 'string'},
|
||||
'port': {
|
||||
'type': 'integer',
|
||||
'default': 8080,
|
||||
'minimum': 0,
|
||||
'maximum': 65535
|
||||
},
|
||||
'ws_token': {'type': 'string'},
|
||||
},
|
||||
'required': ['name', 'host', 'ws_token']
|
||||
}
|
||||
},
|
||||
'wait_timeout': {'type': 'integer', 'minimum': 0},
|
||||
'sleep_time': {'type': 'integer', 'minimum': 0},
|
||||
'ping_timeout': {'type': 'integer', 'minimum': 0},
|
||||
'remove_entry_exit_signals': {'type': 'boolean', 'default': False},
|
||||
'initial_candle_limit': {
|
||||
'type': 'integer',
|
||||
'minimum': 0,
|
||||
'maximum': 1500,
|
||||
'default': 1500
|
||||
},
|
||||
'message_size_limit': { # In megabytes
|
||||
'type': 'integer',
|
||||
'minimum': 1,
|
||||
'maxmium': 20,
|
||||
'default': 8,
|
||||
}
|
||||
},
|
||||
'required': ['producers']
|
||||
},
|
||||
"freqai": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {"type": "boolean", "default": False},
|
||||
"keras": {"type": "boolean", "default": False},
|
||||
"conv_width": {"type": "integer", "default": 2},
|
||||
"train_period_days": {"type": "integer", "default": 0},
|
||||
"backtest_period_days": {"type": "number", "default": 7},
|
||||
"identifier": {"type": "string", "default": "example"},
|
||||
"feature_parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"include_corr_pairlist": {"type": "array"},
|
||||
"include_timeframes": {"type": "array"},
|
||||
"label_period_candles": {"type": "integer"},
|
||||
"include_shifted_candles": {"type": "integer", "default": 0},
|
||||
"DI_threshold": {"type": "number", "default": 0},
|
||||
"weight_factor": {"type": "number", "default": 0},
|
||||
"principal_component_analysis": {"type": "boolean", "default": False},
|
||||
"use_SVM_to_remove_outliers": {"type": "boolean", "default": False},
|
||||
"plot_feature_importances": {"type": "integer", "default": 0},
|
||||
"svm_params": {"type": "object",
|
||||
"properties": {
|
||||
"shuffle": {"type": "boolean", "default": False},
|
||||
"nu": {"type": "number", "default": 0.1}
|
||||
},
|
||||
}
|
||||
},
|
||||
"required": ["include_timeframes", "include_corr_pairlist", ]
|
||||
},
|
||||
"data_split_parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"test_size": {"type": "number"},
|
||||
"random_state": {"type": "integer"},
|
||||
"shuffle": {"type": "boolean", "default": False}
|
||||
},
|
||||
},
|
||||
"model_training_parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"n_estimators": {"type": "integer", "default": 1000}
|
||||
},
|
||||
},
|
||||
},
|
||||
"required": [
|
||||
"enabled",
|
||||
"train_period_days",
|
||||
"backtest_period_days",
|
||||
"identifier",
|
||||
"feature_parameters",
|
||||
"data_split_parameters",
|
||||
"model_training_parameters"
|
||||
]
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -543,3 +653,5 @@ LongShort = Literal['long', 'short']
|
||||
EntryExit = Literal['entry', 'exit']
|
||||
BuySell = Literal['buy', 'sell']
|
||||
MakerTaker = Literal['maker', 'taker']
|
||||
|
||||
Config = Dict[str, Any]
|
||||
|
@@ -284,7 +284,7 @@ def load_backtest_data(filename: Union[Path, str], strategy: Optional[str] = Non
|
||||
df['enter_tag'] = df['buy_tag']
|
||||
df = df.drop(['buy_tag'], axis=1)
|
||||
if 'orders' not in df.columns:
|
||||
df.loc[:, 'orders'] = None
|
||||
df['orders'] = None
|
||||
|
||||
else:
|
||||
# old format - only with lists.
|
||||
@@ -341,9 +341,9 @@ def trade_list_to_dataframe(trades: List[LocalTrade]) -> pd.DataFrame:
|
||||
"""
|
||||
df = pd.DataFrame.from_records([t.to_json(True) for t in trades], columns=BT_DATA_COLUMNS)
|
||||
if len(df) > 0:
|
||||
df.loc[:, 'close_date'] = pd.to_datetime(df['close_date'], utc=True)
|
||||
df.loc[:, 'open_date'] = pd.to_datetime(df['open_date'], utc=True)
|
||||
df.loc[:, 'close_rate'] = df['close_rate'].astype('float64')
|
||||
df['close_date'] = pd.to_datetime(df['close_date'], utc=True)
|
||||
df['open_date'] = pd.to_datetime(df['open_date'], utc=True)
|
||||
df['close_rate'] = df['close_rate'].astype('float64')
|
||||
return df
|
||||
|
||||
|
||||
|
@@ -5,12 +5,12 @@ import itertools
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from operator import itemgetter
|
||||
from typing import Any, Dict, List
|
||||
from typing import Dict, List
|
||||
|
||||
import pandas as pd
|
||||
from pandas import DataFrame, to_datetime
|
||||
|
||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, TradeList
|
||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, Config, TradeList
|
||||
from freqtrade.enums import CandleType
|
||||
|
||||
|
||||
@@ -47,8 +47,7 @@ def ohlcv_to_dataframe(ohlcv: list, timeframe: str, pair: str, *,
|
||||
|
||||
|
||||
def clean_ohlcv_dataframe(data: DataFrame, timeframe: str, pair: str, *,
|
||||
fill_missing: bool = True,
|
||||
drop_incomplete: bool = True) -> DataFrame:
|
||||
fill_missing: bool, drop_incomplete: bool) -> DataFrame:
|
||||
"""
|
||||
Cleanse a OHLCV dataframe by
|
||||
* Grouping it by date (removes duplicate tics)
|
||||
@@ -237,7 +236,7 @@ def trades_to_ohlcv(trades: TradeList, timeframe: str) -> DataFrame:
|
||||
return df_new.loc[:, DEFAULT_DATAFRAME_COLUMNS]
|
||||
|
||||
|
||||
def convert_trades_format(config: Dict[str, Any], convert_from: str, convert_to: str, erase: bool):
|
||||
def convert_trades_format(config: Config, convert_from: str, convert_to: str, erase: bool):
|
||||
"""
|
||||
Convert trades from one format to another format.
|
||||
:param config: Config dictionary
|
||||
@@ -263,7 +262,7 @@ def convert_trades_format(config: Dict[str, Any], convert_from: str, convert_to:
|
||||
|
||||
|
||||
def convert_ohlcv_format(
|
||||
config: Dict[str, Any],
|
||||
config: Config,
|
||||
convert_from: str,
|
||||
convert_to: str,
|
||||
erase: bool,
|
||||
@@ -292,6 +291,7 @@ def convert_ohlcv_format(
|
||||
timeframe,
|
||||
candle_type=candle_type
|
||||
))
|
||||
config['pairs'] = sorted(set(config['pairs']))
|
||||
logger.info(f"Converting candle (OHLCV) data for {config['pairs']}")
|
||||
|
||||
for timeframe in timeframes:
|
||||
@@ -302,7 +302,7 @@ def convert_ohlcv_format(
|
||||
drop_incomplete=False,
|
||||
startup_candles=0,
|
||||
candle_type=candle_type)
|
||||
logger.info(f"Converting {len(data)} {candle_type} candles for {pair}")
|
||||
logger.info(f"Converting {len(data)} {timeframe} {candle_type} candles for {pair}")
|
||||
if len(data) > 0:
|
||||
trg.ohlcv_store(
|
||||
pair=pair,
|
||||
|
@@ -5,17 +5,20 @@ including ticker and orderbook data, live and historical candle (OHLCV) data
|
||||
Common Interface for bot and strategy to access data.
|
||||
"""
|
||||
import logging
|
||||
from collections import deque
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.constants import ListPairsWithTimeframes, PairWithTimeframe
|
||||
from freqtrade.constants import Config, ListPairsWithTimeframes, PairWithTimeframe
|
||||
from freqtrade.data.history import load_pair_history
|
||||
from freqtrade.enums import CandleType, RunMode
|
||||
from freqtrade.enums import CandleType, RPCMessageType, RunMode
|
||||
from freqtrade.exceptions import ExchangeError, OperationalException
|
||||
from freqtrade.exchange import Exchange, timeframe_to_seconds
|
||||
from freqtrade.rpc import RPCManager
|
||||
from freqtrade.util import PeriodicCache
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -26,13 +29,33 @@ MAX_DATAFRAME_CANDLES = 1000
|
||||
|
||||
class DataProvider:
|
||||
|
||||
def __init__(self, config: dict, exchange: Optional[Exchange], pairlists=None) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
config: Config,
|
||||
exchange: Optional[Exchange],
|
||||
pairlists=None,
|
||||
rpc: Optional[RPCManager] = None
|
||||
) -> None:
|
||||
self._config = config
|
||||
self._exchange = exchange
|
||||
self._pairlists = pairlists
|
||||
self.__rpc = rpc
|
||||
self.__cached_pairs: Dict[PairWithTimeframe, Tuple[DataFrame, datetime]] = {}
|
||||
self.__slice_index: Optional[int] = None
|
||||
self.__cached_pairs_backtesting: Dict[PairWithTimeframe, DataFrame] = {}
|
||||
self.__producer_pairs_df: Dict[str,
|
||||
Dict[PairWithTimeframe, Tuple[DataFrame, datetime]]] = {}
|
||||
self.__producer_pairs: Dict[str, List[str]] = {}
|
||||
self._msg_queue: deque = deque()
|
||||
|
||||
self._default_candle_type = self._config.get('candle_type_def', CandleType.SPOT)
|
||||
self._default_timeframe = self._config.get('timeframe', '1h')
|
||||
|
||||
self.__msg_cache = PeriodicCache(
|
||||
maxsize=1000, ttl=timeframe_to_seconds(self._default_timeframe))
|
||||
|
||||
self.producers = self._config.get('external_message_consumer', {}).get('producers', [])
|
||||
self.external_data_enabled = len(self.producers) > 0
|
||||
|
||||
def _set_dataframe_max_index(self, limit_index: int):
|
||||
"""
|
||||
@@ -57,9 +80,110 @@ class DataProvider:
|
||||
:param dataframe: analyzed dataframe
|
||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||
"""
|
||||
self.__cached_pairs[(pair, timeframe, candle_type)] = (
|
||||
pair_key = (pair, timeframe, candle_type)
|
||||
self.__cached_pairs[pair_key] = (
|
||||
dataframe, datetime.now(timezone.utc))
|
||||
|
||||
# For multiple producers we will want to merge the pairlists instead of overwriting
|
||||
def _set_producer_pairs(self, pairlist: List[str], producer_name: str = "default"):
|
||||
"""
|
||||
Set the pairs received to later be used.
|
||||
|
||||
:param pairlist: List of pairs
|
||||
"""
|
||||
self.__producer_pairs[producer_name] = pairlist
|
||||
|
||||
def get_producer_pairs(self, producer_name: str = "default") -> List[str]:
|
||||
"""
|
||||
Get the pairs cached from the producer
|
||||
|
||||
:returns: List of pairs
|
||||
"""
|
||||
return self.__producer_pairs.get(producer_name, []).copy()
|
||||
|
||||
def _emit_df(
|
||||
self,
|
||||
pair_key: PairWithTimeframe,
|
||||
dataframe: DataFrame
|
||||
) -> None:
|
||||
"""
|
||||
Send this dataframe as an ANALYZED_DF message to RPC
|
||||
|
||||
:param pair_key: PairWithTimeframe tuple
|
||||
:param data: Tuple containing the DataFrame and the datetime it was cached
|
||||
"""
|
||||
if self.__rpc:
|
||||
self.__rpc.send_msg(
|
||||
{
|
||||
'type': RPCMessageType.ANALYZED_DF,
|
||||
'data': {
|
||||
'key': pair_key,
|
||||
'df': dataframe,
|
||||
'la': datetime.now(timezone.utc)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
def _add_external_df(
|
||||
self,
|
||||
pair: str,
|
||||
dataframe: DataFrame,
|
||||
last_analyzed: datetime,
|
||||
timeframe: str,
|
||||
candle_type: CandleType,
|
||||
producer_name: str = "default"
|
||||
) -> None:
|
||||
"""
|
||||
Add the pair data to this class from an external source.
|
||||
|
||||
:param pair: pair to get the data for
|
||||
:param timeframe: Timeframe to get data for
|
||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||
"""
|
||||
pair_key = (pair, timeframe, candle_type)
|
||||
|
||||
if producer_name not in self.__producer_pairs_df:
|
||||
self.__producer_pairs_df[producer_name] = {}
|
||||
|
||||
_last_analyzed = datetime.now(timezone.utc) if not last_analyzed else last_analyzed
|
||||
|
||||
self.__producer_pairs_df[producer_name][pair_key] = (dataframe, _last_analyzed)
|
||||
logger.debug(f"External DataFrame for {pair_key} from {producer_name} added.")
|
||||
|
||||
def get_producer_df(
|
||||
self,
|
||||
pair: str,
|
||||
timeframe: Optional[str] = None,
|
||||
candle_type: Optional[CandleType] = None,
|
||||
producer_name: str = "default"
|
||||
) -> Tuple[DataFrame, datetime]:
|
||||
"""
|
||||
Get the pair data from producers.
|
||||
|
||||
:param pair: pair to get the data for
|
||||
:param timeframe: Timeframe to get data for
|
||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||
:returns: Tuple of the DataFrame and last analyzed timestamp
|
||||
"""
|
||||
_timeframe = self._default_timeframe if not timeframe else timeframe
|
||||
_candle_type = self._default_candle_type if not candle_type else candle_type
|
||||
|
||||
pair_key = (pair, _timeframe, _candle_type)
|
||||
|
||||
# If we have no data from this Producer yet
|
||||
if producer_name not in self.__producer_pairs_df:
|
||||
# We don't have this data yet, return empty DataFrame and datetime (01-01-1970)
|
||||
return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc))
|
||||
|
||||
# If we do have data from that Producer, but no data on this pair_key
|
||||
if pair_key not in self.__producer_pairs_df[producer_name]:
|
||||
# We don't have this data yet, return empty DataFrame and datetime (01-01-1970)
|
||||
return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc))
|
||||
|
||||
# We have it, return this data
|
||||
df, la = self.__producer_pairs_df[producer_name][pair_key]
|
||||
return (df.copy(), la)
|
||||
|
||||
def add_pairlisthandler(self, pairlists) -> None:
|
||||
"""
|
||||
Allow adding pairlisthandler after initialization
|
||||
@@ -80,14 +204,16 @@ class DataProvider:
|
||||
"""
|
||||
_candle_type = CandleType.from_string(
|
||||
candle_type) if candle_type != '' else self._config['candle_type_def']
|
||||
saved_pair = (pair, str(timeframe), _candle_type)
|
||||
saved_pair: PairWithTimeframe = (pair, str(timeframe), _candle_type)
|
||||
if saved_pair not in self.__cached_pairs_backtesting:
|
||||
timerange = TimeRange.parse_timerange(None if self._config.get(
|
||||
'timerange') is None else str(self._config.get('timerange')))
|
||||
# Move informative start time respecting startup_candle_count
|
||||
timerange.subtract_start(
|
||||
timeframe_to_seconds(str(timeframe)) * self._config.get('startup_candle_count', 0)
|
||||
)
|
||||
|
||||
# It is not necessary to add the training candles, as they
|
||||
# were already added at the beginning of the backtest.
|
||||
startup_candles = self.get_required_startup(str(timeframe), False)
|
||||
tf_seconds = timeframe_to_seconds(str(timeframe))
|
||||
timerange.subtract_start(tf_seconds * startup_candles)
|
||||
self.__cached_pairs_backtesting[saved_pair] = load_pair_history(
|
||||
pair=pair,
|
||||
timeframe=timeframe or self._config['timeframe'],
|
||||
@@ -99,6 +225,23 @@ class DataProvider:
|
||||
)
|
||||
return self.__cached_pairs_backtesting[saved_pair].copy()
|
||||
|
||||
def get_required_startup(self, timeframe: str, add_train_candles: bool = True) -> int:
|
||||
freqai_config = self._config.get('freqai', {})
|
||||
if not freqai_config.get('enabled', False):
|
||||
return self._config.get('startup_candle_count', 0)
|
||||
else:
|
||||
startup_candles = self._config.get('startup_candle_count', 0)
|
||||
indicator_periods = freqai_config['feature_parameters']['indicator_periods_candles']
|
||||
# make sure the startupcandles is at least the set maximum indicator periods
|
||||
self._config['startup_candle_count'] = max(startup_candles, max(indicator_periods))
|
||||
tf_seconds = timeframe_to_seconds(timeframe)
|
||||
train_candles = 0
|
||||
if add_train_candles:
|
||||
train_candles = freqai_config['train_period_days'] * 86400 / tf_seconds
|
||||
total_candles = int(self._config['startup_candle_count'] + train_candles)
|
||||
logger.info(f'Increasing startup_candle_count for freqai to {total_candles}')
|
||||
return total_candles
|
||||
|
||||
def get_pair_dataframe(
|
||||
self,
|
||||
pair: str,
|
||||
@@ -175,7 +318,9 @@ class DataProvider:
|
||||
Clear pair dataframe cache.
|
||||
"""
|
||||
self.__cached_pairs = {}
|
||||
self.__cached_pairs_backtesting = {}
|
||||
# Don't reset backtesting pairs -
|
||||
# otherwise they're reloaded each time during hyperopt due to with analyze_per_epoch
|
||||
# self.__cached_pairs_backtesting = {}
|
||||
self.__slice_index = 0
|
||||
|
||||
# Exchange functions
|
||||
@@ -265,3 +410,20 @@ class DataProvider:
|
||||
if self._exchange is None:
|
||||
raise OperationalException(NO_EXCHANGE_EXCEPTION)
|
||||
return self._exchange.fetch_l2_order_book(pair, maximum)
|
||||
|
||||
def send_msg(self, message: str, *, always_send: bool = False) -> None:
|
||||
"""
|
||||
Send custom RPC Notifications from your bot.
|
||||
Will not send any bot in modes other than Dry-run or Live.
|
||||
:param message: Message to be sent. Must be below 4096.
|
||||
:param always_send: If False, will send the message only once per candle, and surpress
|
||||
identical messages.
|
||||
Careful as this can end up spaming your chat.
|
||||
Defaults to False
|
||||
"""
|
||||
if self.runmode not in (RunMode.DRY_RUN, RunMode.LIVE):
|
||||
return
|
||||
|
||||
if always_send or message not in self.__msg_cache:
|
||||
self._msg_queue.append(message)
|
||||
self.__msg_cache[message] = True
|
||||
|
130
freqtrade/data/history/featherdatahandler.py
Normal file
@@ -0,0 +1,130 @@
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from pandas import DataFrame, read_feather, to_datetime
|
||||
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, TradeList
|
||||
from freqtrade.enums import CandleType
|
||||
|
||||
from .idatahandler import IDataHandler
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class FeatherDataHandler(IDataHandler):
|
||||
|
||||
_columns = DEFAULT_DATAFRAME_COLUMNS
|
||||
|
||||
def ohlcv_store(
|
||||
self, pair: str, timeframe: str, data: DataFrame, candle_type: CandleType) -> None:
|
||||
"""
|
||||
Store data in json format "values".
|
||||
format looks as follows:
|
||||
[[<date>,<open>,<high>,<low>,<close>]]
|
||||
:param pair: Pair - used to generate filename
|
||||
:param timeframe: Timeframe - used to generate filename
|
||||
:param data: Dataframe containing OHLCV data
|
||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||
:return: None
|
||||
"""
|
||||
filename = self._pair_data_filename(self._datadir, pair, timeframe, candle_type)
|
||||
self.create_dir_if_needed(filename)
|
||||
|
||||
data.reset_index(drop=True).loc[:, self._columns].to_feather(
|
||||
filename, compression_level=9, compression='lz4')
|
||||
|
||||
def _ohlcv_load(self, pair: str, timeframe: str,
|
||||
timerange: Optional[TimeRange], candle_type: CandleType
|
||||
) -> DataFrame:
|
||||
"""
|
||||
Internal method used to load data for one pair from disk.
|
||||
Implements the loading and conversion to a Pandas dataframe.
|
||||
Timerange trimming and dataframe validation happens outside of this method.
|
||||
:param pair: Pair to load data
|
||||
:param timeframe: Timeframe (e.g. "5m")
|
||||
:param timerange: Limit data to be loaded to this timerange.
|
||||
Optionally implemented by subclasses to avoid loading
|
||||
all data where possible.
|
||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||
"""
|
||||
filename = self._pair_data_filename(
|
||||
self._datadir, pair, timeframe, candle_type=candle_type)
|
||||
if not filename.exists():
|
||||
# Fallback mode for 1M files
|
||||
filename = self._pair_data_filename(
|
||||
self._datadir, pair, timeframe, candle_type=candle_type, no_timeframe_modify=True)
|
||||
if not filename.exists():
|
||||
return DataFrame(columns=self._columns)
|
||||
|
||||
pairdata = read_feather(filename)
|
||||
pairdata.columns = self._columns
|
||||
pairdata = pairdata.astype(dtype={'open': 'float', 'high': 'float',
|
||||
'low': 'float', 'close': 'float', 'volume': 'float'})
|
||||
pairdata['date'] = to_datetime(pairdata['date'],
|
||||
unit='ms',
|
||||
utc=True,
|
||||
infer_datetime_format=True)
|
||||
return pairdata
|
||||
|
||||
def ohlcv_append(
|
||||
self,
|
||||
pair: str,
|
||||
timeframe: str,
|
||||
data: DataFrame,
|
||||
candle_type: CandleType
|
||||
) -> None:
|
||||
"""
|
||||
Append data to existing data structures
|
||||
:param pair: Pair
|
||||
:param timeframe: Timeframe this ohlcv data is for
|
||||
:param data: Data to append.
|
||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def trades_store(self, pair: str, data: TradeList) -> None:
|
||||
"""
|
||||
Store trades data (list of Dicts) to file
|
||||
:param pair: Pair - used for filename
|
||||
:param data: List of Lists containing trade data,
|
||||
column sequence as in DEFAULT_TRADES_COLUMNS
|
||||
"""
|
||||
# filename = self._pair_trades_filename(self._datadir, pair)
|
||||
|
||||
raise NotImplementedError()
|
||||
# array = pa.array(data)
|
||||
# array
|
||||
# feather.write_feather(data, filename)
|
||||
|
||||
def trades_append(self, pair: str, data: TradeList):
|
||||
"""
|
||||
Append data to existing files
|
||||
:param pair: Pair - used for filename
|
||||
:param data: List of Lists containing trade data,
|
||||
column sequence as in DEFAULT_TRADES_COLUMNS
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def _trades_load(self, pair: str, timerange: Optional[TimeRange] = None) -> TradeList:
|
||||
"""
|
||||
Load a pair from file, either .json.gz or .json
|
||||
# TODO: respect timerange ...
|
||||
:param pair: Load trades for this pair
|
||||
:param timerange: Timerange to load trades for - currently not implemented
|
||||
:return: List of trades
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
# filename = self._pair_trades_filename(self._datadir, pair)
|
||||
# tradesdata = misc.file_load_json(filename)
|
||||
|
||||
# if not tradesdata:
|
||||
# return []
|
||||
|
||||
# return tradesdata
|
||||
|
||||
@classmethod
|
||||
def _get_file_extension(cls):
|
||||
return "feather"
|
@@ -1,15 +1,12 @@
|
||||
import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS,
|
||||
ListPairsWithTimeframes, TradeList)
|
||||
from freqtrade.enums import CandleType, TradingMode
|
||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, TradeList
|
||||
from freqtrade.enums import CandleType
|
||||
|
||||
from .idatahandler import IDataHandler
|
||||
|
||||
@@ -21,49 +18,6 @@ class HDF5DataHandler(IDataHandler):
|
||||
|
||||
_columns = DEFAULT_DATAFRAME_COLUMNS
|
||||
|
||||
@classmethod
|
||||
def ohlcv_get_available_data(
|
||||
cls, datadir: Path, trading_mode: TradingMode) -> ListPairsWithTimeframes:
|
||||
"""
|
||||
Returns a list of all pairs with ohlcv data available in this datadir
|
||||
:param datadir: Directory to search for ohlcv files
|
||||
:param trading_mode: trading-mode to be used
|
||||
:return: List of Tuples of (pair, timeframe)
|
||||
"""
|
||||
if trading_mode == TradingMode.FUTURES:
|
||||
datadir = datadir.joinpath('futures')
|
||||
_tmp = [
|
||||
re.search(
|
||||
cls._OHLCV_REGEX, p.name
|
||||
) for p in datadir.glob("*.h5")
|
||||
]
|
||||
return [
|
||||
(
|
||||
cls.rebuild_pair_from_filename(match[1]),
|
||||
cls.rebuild_timeframe_from_filename(match[2]),
|
||||
CandleType.from_string(match[3])
|
||||
) for match in _tmp if match and len(match.groups()) > 1]
|
||||
|
||||
@classmethod
|
||||
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str, candle_type: CandleType) -> List[str]:
|
||||
"""
|
||||
Returns a list of all pairs with ohlcv data available in this datadir
|
||||
for the specified timeframe
|
||||
:param datadir: Directory to search for ohlcv files
|
||||
:param timeframe: Timeframe to search pairs for
|
||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||
:return: List of Pairs
|
||||
"""
|
||||
candle = ""
|
||||
if candle_type != CandleType.SPOT:
|
||||
datadir = datadir.joinpath('futures')
|
||||
candle = f"-{candle_type}"
|
||||
|
||||
_tmp = [re.search(r'^(\S+)(?=\-' + timeframe + candle + '.h5)', p.name)
|
||||
for p in datadir.glob(f"*{timeframe}{candle}.h5")]
|
||||
# Check if regex found something and only return these results
|
||||
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
||||
|
||||
def ohlcv_store(
|
||||
self, pair: str, timeframe: str, data: pd.DataFrame, candle_type: CandleType) -> None:
|
||||
"""
|
||||
@@ -127,6 +81,7 @@ class HDF5DataHandler(IDataHandler):
|
||||
raise ValueError("Wrong dataframe format")
|
||||
pairdata = pairdata.astype(dtype={'open': 'float', 'high': 'float',
|
||||
'low': 'float', 'close': 'float', 'volume': 'float'})
|
||||
pairdata = pairdata.reset_index(drop=True)
|
||||
return pairdata
|
||||
|
||||
def ohlcv_append(
|
||||
@@ -145,18 +100,6 @@ class HDF5DataHandler(IDataHandler):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@classmethod
|
||||
def trades_get_pairs(cls, datadir: Path) -> List[str]:
|
||||
"""
|
||||
Returns a list of all pairs for which trade data is available in this
|
||||
:param datadir: Directory to search for ohlcv files
|
||||
:return: List of Pairs
|
||||
"""
|
||||
_tmp = [re.search(r'^(\S+)(?=\-trades.h5)', p.name)
|
||||
for p in datadir.glob("*trades.h5")]
|
||||
# Check if regex found something and only return these results to avoid exceptions.
|
||||
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
||||
|
||||
def trades_store(self, pair: str, data: TradeList) -> None:
|
||||
"""
|
||||
Store trades data (list of Dicts) to file
|
||||
|
@@ -26,7 +26,7 @@ def load_pair_history(pair: str,
|
||||
datadir: Path, *,
|
||||
timerange: Optional[TimeRange] = None,
|
||||
fill_up_missing: bool = True,
|
||||
drop_incomplete: bool = True,
|
||||
drop_incomplete: bool = False,
|
||||
startup_candles: int = 0,
|
||||
data_format: str = None,
|
||||
data_handler: IDataHandler = None,
|
||||
@@ -56,7 +56,7 @@ def load_pair_history(pair: str,
|
||||
fill_missing=fill_up_missing,
|
||||
drop_incomplete=drop_incomplete,
|
||||
startup_candles=startup_candles,
|
||||
candle_type=candle_type
|
||||
candle_type=candle_type,
|
||||
)
|
||||
|
||||
|
||||
@@ -97,14 +97,15 @@ def load_data(datadir: Path,
|
||||
fill_up_missing=fill_up_missing,
|
||||
startup_candles=startup_candles,
|
||||
data_handler=data_handler,
|
||||
candle_type=candle_type
|
||||
candle_type=candle_type,
|
||||
)
|
||||
if not hist.empty:
|
||||
result[pair] = hist
|
||||
else:
|
||||
if candle_type is CandleType.FUNDING_RATE and user_futures_funding_rate is not None:
|
||||
logger.warn(f"{pair} using user specified [{user_futures_funding_rate}]")
|
||||
result[pair] = DataFrame(columns=["open", "close", "high", "low", "volume"])
|
||||
elif candle_type not in (CandleType.SPOT, CandleType.FUTURES):
|
||||
result[pair] = DataFrame(columns=["date", "open", "close", "high", "low", "volume"])
|
||||
|
||||
if fail_without_data and not result:
|
||||
raise OperationalException("No data found. Terminating.")
|
||||
@@ -227,9 +228,9 @@ def _download_pair_history(pair: str, *,
|
||||
)
|
||||
|
||||
logger.debug("Current Start: %s",
|
||||
f"{data.iloc[0]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
||||
f"{data.iloc[0]['date']:DATETIME_PRINT_FORMAT}" if not data.empty else 'None')
|
||||
logger.debug("Current End: %s",
|
||||
f"{data.iloc[-1]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
||||
f"{data.iloc[-1]['date']:DATETIME_PRINT_FORMAT}" if not data.empty else 'None')
|
||||
|
||||
# Default since_ms to 30 days if nothing is given
|
||||
new_data = exchange.get_historic_ohlcv(pair=pair,
|
||||
@@ -253,9 +254,9 @@ def _download_pair_history(pair: str, *,
|
||||
fill_missing=False, drop_incomplete=False)
|
||||
|
||||
logger.debug("New Start: %s",
|
||||
f"{data.iloc[0]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
||||
f"{data.iloc[0]['date']:DATETIME_PRINT_FORMAT}" if not data.empty else 'None')
|
||||
logger.debug("New End: %s",
|
||||
f"{data.iloc[-1]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
||||
f"{data.iloc[-1]['date']:DATETIME_PRINT_FORMAT}" if not data.empty else 'None')
|
||||
|
||||
data_handler.ohlcv_store(pair, timeframe, data=data, candle_type=candle_type)
|
||||
return True
|
||||
@@ -301,8 +302,8 @@ def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes
|
||||
if trading_mode == 'futures':
|
||||
# Predefined candletype (and timeframe) depending on exchange
|
||||
# Downloads what is necessary to backtest based on futures data.
|
||||
tf_mark = exchange._ft_has['mark_ohlcv_timeframe']
|
||||
fr_candle_type = CandleType.from_string(exchange._ft_has['mark_ohlcv_price'])
|
||||
tf_mark = exchange.get_option('mark_ohlcv_timeframe')
|
||||
fr_candle_type = CandleType.from_string(exchange.get_option('mark_ohlcv_price'))
|
||||
# All exchanges need FundingRate for futures trading.
|
||||
# The timeframe is aligned to the mark-price timeframe.
|
||||
for funding_candle_type in (CandleType.FUNDING_RATE, fr_candle_type):
|
||||
@@ -329,13 +330,12 @@ def _download_trades_history(exchange: Exchange,
|
||||
try:
|
||||
|
||||
until = None
|
||||
since = 0
|
||||
if timerange:
|
||||
if timerange.starttype == 'date':
|
||||
since = timerange.startts * 1000
|
||||
if timerange.stoptype == 'date':
|
||||
until = timerange.stopts * 1000
|
||||
else:
|
||||
since = arrow.utcnow().shift(days=-new_pairs_days).int_timestamp * 1000
|
||||
|
||||
trades = data_handler.trades_load(pair)
|
||||
|
||||
@@ -348,6 +348,9 @@ def _download_trades_history(exchange: Exchange,
|
||||
logger.info(f"Start earlier than available data. Redownloading trades for {pair}...")
|
||||
trades = []
|
||||
|
||||
if not since:
|
||||
since = arrow.utcnow().shift(days=-new_pairs_days).int_timestamp * 1000
|
||||
|
||||
from_id = trades[-1][1] if trades else None
|
||||
if trades and since < trades[-1][0]:
|
||||
# Reset since to the last available point
|
||||
|
@@ -9,7 +9,7 @@ from abc import ABC, abstractmethod
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Type
|
||||
from typing import List, Optional, Tuple, Type
|
||||
|
||||
from pandas import DataFrame
|
||||
|
||||
@@ -26,7 +26,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
class IDataHandler(ABC):
|
||||
|
||||
_OHLCV_REGEX = r'^([a-zA-Z_-]+)\-(\d+[a-zA-Z]{1,2})\-?([a-zA-Z_]*)?(?=\.)'
|
||||
_OHLCV_REGEX = r'^([a-zA-Z_\d-]+)\-(\d+[a-zA-Z]{1,2})\-?([a-zA-Z_]*)?(?=\.)'
|
||||
|
||||
def __init__(self, datadir: Path) -> None:
|
||||
self._datadir = datadir
|
||||
@@ -39,18 +39,28 @@ class IDataHandler(ABC):
|
||||
raise NotImplementedError()
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def ohlcv_get_available_data(
|
||||
cls, datadir: Path, trading_mode: TradingMode) -> ListPairsWithTimeframes:
|
||||
"""
|
||||
Returns a list of all pairs with ohlcv data available in this datadir
|
||||
:param datadir: Directory to search for ohlcv files
|
||||
:param trading_mode: trading-mode to be used
|
||||
:return: List of Tuples of (pair, timeframe)
|
||||
:return: List of Tuples of (pair, timeframe, CandleType)
|
||||
"""
|
||||
if trading_mode == TradingMode.FUTURES:
|
||||
datadir = datadir.joinpath('futures')
|
||||
_tmp = [
|
||||
re.search(
|
||||
cls._OHLCV_REGEX, p.name
|
||||
) for p in datadir.glob(f"*.{cls._get_file_extension()}")]
|
||||
return [
|
||||
(
|
||||
cls.rebuild_pair_from_filename(match[1]),
|
||||
cls.rebuild_timeframe_from_filename(match[2]),
|
||||
CandleType.from_string(match[3])
|
||||
) for match in _tmp if match and len(match.groups()) > 1]
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str, candle_type: CandleType) -> List[str]:
|
||||
"""
|
||||
Returns a list of all pairs with ohlcv data available in this datadir
|
||||
@@ -60,6 +70,15 @@ class IDataHandler(ABC):
|
||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||
:return: List of Pairs
|
||||
"""
|
||||
candle = ""
|
||||
if candle_type != CandleType.SPOT:
|
||||
datadir = datadir.joinpath('futures')
|
||||
candle = f"-{candle_type}"
|
||||
ext = cls._get_file_extension()
|
||||
_tmp = [re.search(r'^(\S+)(?=\-' + timeframe + candle + f'.{ext})', p.name)
|
||||
for p in datadir.glob(f"*{timeframe}{candle}.{ext}")]
|
||||
# Check if regex found something and only return these results
|
||||
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
||||
|
||||
@abstractmethod
|
||||
def ohlcv_store(
|
||||
@@ -73,6 +92,18 @@ class IDataHandler(ABC):
|
||||
:return: None
|
||||
"""
|
||||
|
||||
def ohlcv_data_min_max(self, pair: str, timeframe: str,
|
||||
candle_type: CandleType) -> Tuple[datetime, datetime]:
|
||||
"""
|
||||
Returns the min and max timestamp for the given pair and timeframe.
|
||||
:param pair: Pair to get min/max for
|
||||
:param timeframe: Timeframe to get min/max for
|
||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||
:return: (min, max)
|
||||
"""
|
||||
data = self._ohlcv_load(pair, timeframe, None, candle_type)
|
||||
return data.iloc[0]['date'].to_pydatetime(), data.iloc[-1]['date'].to_pydatetime()
|
||||
|
||||
@abstractmethod
|
||||
def _ohlcv_load(self, pair: str, timeframe: str, timerange: Optional[TimeRange],
|
||||
candle_type: CandleType
|
||||
@@ -121,13 +152,17 @@ class IDataHandler(ABC):
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def trades_get_pairs(cls, datadir: Path) -> List[str]:
|
||||
"""
|
||||
Returns a list of all pairs for which trade data is available in this
|
||||
:param datadir: Directory to search for ohlcv files
|
||||
:return: List of Pairs
|
||||
"""
|
||||
_ext = cls._get_file_extension()
|
||||
_tmp = [re.search(r'^(\S+)(?=\-trades.' + _ext + ')', p.name)
|
||||
for p in datadir.glob(f"*trades.{_ext}")]
|
||||
# Check if regex found something and only return these results to avoid exceptions.
|
||||
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
||||
|
||||
@abstractmethod
|
||||
def trades_store(self, pair: str, data: TradeList) -> None:
|
||||
@@ -232,15 +267,15 @@ class IDataHandler(ABC):
|
||||
Rebuild pair name from filename
|
||||
Assumes a asset name of max. 7 length to also support BTC-PERP and BTC-PERP:USD names.
|
||||
"""
|
||||
res = re.sub(r'^(([A-Za-z]{1,10})|^([A-Za-z\-]{1,6}))(_)', r'\g<1>/', pair, 1)
|
||||
res = re.sub(r'^(([A-Za-z\d]{1,10})|^([A-Za-z\-]{1,6}))(_)', r'\g<1>/', pair, 1)
|
||||
res = re.sub('_', ':', res, 1)
|
||||
return res
|
||||
|
||||
def ohlcv_load(self, pair, timeframe: str,
|
||||
candle_type: CandleType,
|
||||
candle_type: CandleType, *,
|
||||
timerange: Optional[TimeRange] = None,
|
||||
fill_missing: bool = True,
|
||||
drop_incomplete: bool = True,
|
||||
drop_incomplete: bool = False,
|
||||
startup_candles: int = 0,
|
||||
warn_no_data: bool = True,
|
||||
) -> DataFrame:
|
||||
@@ -340,6 +375,12 @@ def get_datahandlerclass(datatype: str) -> Type[IDataHandler]:
|
||||
elif datatype == 'hdf5':
|
||||
from .hdf5datahandler import HDF5DataHandler
|
||||
return HDF5DataHandler
|
||||
elif datatype == 'feather':
|
||||
from .featherdatahandler import FeatherDataHandler
|
||||
return FeatherDataHandler
|
||||
elif datatype == 'parquet':
|
||||
from .parquetdatahandler import ParquetDataHandler
|
||||
return ParquetDataHandler
|
||||
else:
|
||||
raise ValueError(f"No datahandler for datatype {datatype} available.")
|
||||
|
||||
|
@@ -1,16 +1,14 @@
|
||||
import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
from pandas import DataFrame, read_json, to_datetime
|
||||
|
||||
from freqtrade import misc
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, ListPairsWithTimeframes, TradeList
|
||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, TradeList
|
||||
from freqtrade.data.converter import trades_dict_to_list
|
||||
from freqtrade.enums import CandleType, TradingMode
|
||||
from freqtrade.enums import CandleType
|
||||
|
||||
from .idatahandler import IDataHandler
|
||||
|
||||
@@ -23,48 +21,6 @@ class JsonDataHandler(IDataHandler):
|
||||
_use_zip = False
|
||||
_columns = DEFAULT_DATAFRAME_COLUMNS
|
||||
|
||||
@classmethod
|
||||
def ohlcv_get_available_data(
|
||||
cls, datadir: Path, trading_mode: TradingMode) -> ListPairsWithTimeframes:
|
||||
"""
|
||||
Returns a list of all pairs with ohlcv data available in this datadir
|
||||
:param datadir: Directory to search for ohlcv files
|
||||
:param trading_mode: trading-mode to be used
|
||||
:return: List of Tuples of (pair, timeframe)
|
||||
"""
|
||||
if trading_mode == 'futures':
|
||||
datadir = datadir.joinpath('futures')
|
||||
_tmp = [
|
||||
re.search(
|
||||
cls._OHLCV_REGEX, p.name
|
||||
) for p in datadir.glob(f"*.{cls._get_file_extension()}")]
|
||||
return [
|
||||
(
|
||||
cls.rebuild_pair_from_filename(match[1]),
|
||||
cls.rebuild_timeframe_from_filename(match[2]),
|
||||
CandleType.from_string(match[3])
|
||||
) for match in _tmp if match and len(match.groups()) > 1]
|
||||
|
||||
@classmethod
|
||||
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str, candle_type: CandleType) -> List[str]:
|
||||
"""
|
||||
Returns a list of all pairs with ohlcv data available in this datadir
|
||||
for the specified timeframe
|
||||
:param datadir: Directory to search for ohlcv files
|
||||
:param timeframe: Timeframe to search pairs for
|
||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||
:return: List of Pairs
|
||||
"""
|
||||
candle = ""
|
||||
if candle_type != CandleType.SPOT:
|
||||
datadir = datadir.joinpath('futures')
|
||||
candle = f"-{candle_type}"
|
||||
|
||||
_tmp = [re.search(r'^(\S+)(?=\-' + timeframe + candle + '.json)', p.name)
|
||||
for p in datadir.glob(f"*{timeframe}{candle}.{cls._get_file_extension()}")]
|
||||
# Check if regex found something and only return these results
|
||||
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
||||
|
||||
def ohlcv_store(
|
||||
self, pair: str, timeframe: str, data: DataFrame, candle_type: CandleType) -> None:
|
||||
"""
|
||||
@@ -141,18 +97,6 @@ class JsonDataHandler(IDataHandler):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@classmethod
|
||||
def trades_get_pairs(cls, datadir: Path) -> List[str]:
|
||||
"""
|
||||
Returns a list of all pairs for which trade data is available in this
|
||||
:param datadir: Directory to search for ohlcv files
|
||||
:return: List of Pairs
|
||||
"""
|
||||
_tmp = [re.search(r'^(\S+)(?=\-trades.json)', p.name)
|
||||
for p in datadir.glob(f"*trades.{cls._get_file_extension()}")]
|
||||
# Check if regex found something and only return these results to avoid exceptions.
|
||||
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
||||
|
||||
def trades_store(self, pair: str, data: TradeList) -> None:
|
||||
"""
|
||||
Store trades data (list of Dicts) to file
|
||||
|
129
freqtrade/data/history/parquetdatahandler.py
Normal file
@@ -0,0 +1,129 @@
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from pandas import DataFrame, read_parquet, to_datetime
|
||||
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, TradeList
|
||||
from freqtrade.enums import CandleType
|
||||
|
||||
from .idatahandler import IDataHandler
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ParquetDataHandler(IDataHandler):
|
||||
|
||||
_columns = DEFAULT_DATAFRAME_COLUMNS
|
||||
|
||||
def ohlcv_store(
|
||||
self, pair: str, timeframe: str, data: DataFrame, candle_type: CandleType) -> None:
|
||||
"""
|
||||
Store data in json format "values".
|
||||
format looks as follows:
|
||||
[[<date>,<open>,<high>,<low>,<close>]]
|
||||
:param pair: Pair - used to generate filename
|
||||
:param timeframe: Timeframe - used to generate filename
|
||||
:param data: Dataframe containing OHLCV data
|
||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||
:return: None
|
||||
"""
|
||||
filename = self._pair_data_filename(self._datadir, pair, timeframe, candle_type)
|
||||
self.create_dir_if_needed(filename)
|
||||
|
||||
data.reset_index(drop=True).loc[:, self._columns].to_parquet(filename)
|
||||
|
||||
def _ohlcv_load(self, pair: str, timeframe: str,
|
||||
timerange: Optional[TimeRange], candle_type: CandleType
|
||||
) -> DataFrame:
|
||||
"""
|
||||
Internal method used to load data for one pair from disk.
|
||||
Implements the loading and conversion to a Pandas dataframe.
|
||||
Timerange trimming and dataframe validation happens outside of this method.
|
||||
:param pair: Pair to load data
|
||||
:param timeframe: Timeframe (e.g. "5m")
|
||||
:param timerange: Limit data to be loaded to this timerange.
|
||||
Optionally implemented by subclasses to avoid loading
|
||||
all data where possible.
|
||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||
"""
|
||||
filename = self._pair_data_filename(
|
||||
self._datadir, pair, timeframe, candle_type=candle_type)
|
||||
if not filename.exists():
|
||||
# Fallback mode for 1M files
|
||||
filename = self._pair_data_filename(
|
||||
self._datadir, pair, timeframe, candle_type=candle_type, no_timeframe_modify=True)
|
||||
if not filename.exists():
|
||||
return DataFrame(columns=self._columns)
|
||||
|
||||
pairdata = read_parquet(filename)
|
||||
pairdata.columns = self._columns
|
||||
pairdata = pairdata.astype(dtype={'open': 'float', 'high': 'float',
|
||||
'low': 'float', 'close': 'float', 'volume': 'float'})
|
||||
pairdata['date'] = to_datetime(pairdata['date'],
|
||||
unit='ms',
|
||||
utc=True,
|
||||
infer_datetime_format=True)
|
||||
return pairdata
|
||||
|
||||
def ohlcv_append(
|
||||
self,
|
||||
pair: str,
|
||||
timeframe: str,
|
||||
data: DataFrame,
|
||||
candle_type: CandleType
|
||||
) -> None:
|
||||
"""
|
||||
Append data to existing data structures
|
||||
:param pair: Pair
|
||||
:param timeframe: Timeframe this ohlcv data is for
|
||||
:param data: Data to append.
|
||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def trades_store(self, pair: str, data: TradeList) -> None:
|
||||
"""
|
||||
Store trades data (list of Dicts) to file
|
||||
:param pair: Pair - used for filename
|
||||
:param data: List of Lists containing trade data,
|
||||
column sequence as in DEFAULT_TRADES_COLUMNS
|
||||
"""
|
||||
# filename = self._pair_trades_filename(self._datadir, pair)
|
||||
|
||||
raise NotImplementedError()
|
||||
# array = pa.array(data)
|
||||
# array
|
||||
# feather.write_feather(data, filename)
|
||||
|
||||
def trades_append(self, pair: str, data: TradeList):
|
||||
"""
|
||||
Append data to existing files
|
||||
:param pair: Pair - used for filename
|
||||
:param data: List of Lists containing trade data,
|
||||
column sequence as in DEFAULT_TRADES_COLUMNS
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def _trades_load(self, pair: str, timerange: Optional[TimeRange] = None) -> TradeList:
|
||||
"""
|
||||
Load a pair from file, either .json.gz or .json
|
||||
# TODO: respect timerange ...
|
||||
:param pair: Load trades for this pair
|
||||
:param timerange: Timerange to load trades for - currently not implemented
|
||||
:return: List of trades
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
# filename = self._pair_trades_filename(self._datadir, pair)
|
||||
# tradesdata = misc.file_load_json(filename)
|
||||
|
||||
# if not tradesdata:
|
||||
# return []
|
||||
|
||||
# return tradesdata
|
||||
|
||||
@classmethod
|
||||
def _get_file_extension(cls):
|
||||
return "parquet"
|
@@ -11,11 +11,11 @@ import utils_find_1st as utf1st
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.constants import DATETIME_PRINT_FORMAT, UNLIMITED_STAKE_AMOUNT
|
||||
from freqtrade.constants import DATETIME_PRINT_FORMAT, UNLIMITED_STAKE_AMOUNT, Config
|
||||
from freqtrade.data.history import get_timerange, load_data, refresh_data
|
||||
from freqtrade.enums import CandleType, ExitType, RunMode
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange.exchange import timeframe_to_seconds
|
||||
from freqtrade.exchange import timeframe_to_seconds
|
||||
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
||||
from freqtrade.strategy.interface import IStrategy
|
||||
|
||||
@@ -42,10 +42,9 @@ class Edge:
|
||||
Author: https://github.com/mishaker
|
||||
"""
|
||||
|
||||
config: Dict = {}
|
||||
_cached_pairs: Dict[str, Any] = {} # Keeps a list of pairs
|
||||
|
||||
def __init__(self, config: Dict[str, Any], exchange, strategy) -> None:
|
||||
def __init__(self, config: Config, exchange, strategy) -> None:
|
||||
|
||||
self.config = config
|
||||
self.exchange = exchange
|
||||
|
@@ -3,9 +3,10 @@ from freqtrade.enums.backteststate import BacktestState
|
||||
from freqtrade.enums.candletype import CandleType
|
||||
from freqtrade.enums.exitchecktuple import ExitCheckTuple
|
||||
from freqtrade.enums.exittype import ExitType
|
||||
from freqtrade.enums.hyperoptstate import HyperoptState
|
||||
from freqtrade.enums.marginmode import MarginMode
|
||||
from freqtrade.enums.ordertypevalue import OrderTypeValues
|
||||
from freqtrade.enums.rpcmessagetype import RPCMessageType
|
||||
from freqtrade.enums.rpcmessagetype import RPCMessageType, RPCRequestType
|
||||
from freqtrade.enums.runmode import NON_UTIL_MODES, OPTIMIZE_MODES, TRADING_MODES, RunMode
|
||||
from freqtrade.enums.signaltype import SignalDirection, SignalTagType, SignalType
|
||||
from freqtrade.enums.state import State
|
||||
|
@@ -9,10 +9,12 @@ class ExitType(Enum):
|
||||
STOP_LOSS = "stop_loss"
|
||||
STOPLOSS_ON_EXCHANGE = "stoploss_on_exchange"
|
||||
TRAILING_STOP_LOSS = "trailing_stop_loss"
|
||||
LIQUIDATION = "liquidation"
|
||||
EXIT_SIGNAL = "exit_signal"
|
||||
FORCE_EXIT = "force_exit"
|
||||
EMERGENCY_EXIT = "emergency_exit"
|
||||
CUSTOM_EXIT = "custom_exit"
|
||||
PARTIAL_EXIT = "partial_exit"
|
||||
NONE = ""
|
||||
|
||||
def __str__(self):
|
||||
|
12
freqtrade/enums/hyperoptstate.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class HyperoptState(Enum):
|
||||
""" Hyperopt states """
|
||||
STARTUP = 1
|
||||
DATALOAD = 2
|
||||
INDICATORS = 3
|
||||
OPTIMIZE = 4
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.name.lower()}"
|
@@ -1,7 +1,7 @@
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class RPCMessageType(Enum):
|
||||
class RPCMessageType(str, Enum):
|
||||
STATUS = 'status'
|
||||
WARNING = 'warning'
|
||||
STARTUP = 'startup'
|
||||
@@ -17,8 +17,21 @@ class RPCMessageType(Enum):
|
||||
PROTECTION_TRIGGER = 'protection_trigger'
|
||||
PROTECTION_TRIGGER_GLOBAL = 'protection_trigger_global'
|
||||
|
||||
STRATEGY_MSG = 'strategy_msg'
|
||||
|
||||
WHITELIST = 'whitelist'
|
||||
ANALYZED_DF = 'analyzed_df'
|
||||
|
||||
def __repr__(self):
|
||||
return self.value
|
||||
|
||||
def __str__(self):
|
||||
return self.value
|
||||
|
||||
|
||||
# Enum for parsing requests from ws consumers
|
||||
class RPCRequestType(str, Enum):
|
||||
SUBSCRIBE = 'subscribe'
|
||||
|
||||
WHITELIST = 'whitelist'
|
||||
ANALYZED_DF = 'analyzed_df'
|
||||
|
@@ -9,12 +9,14 @@ from freqtrade.exchange.bitpanda import Bitpanda
|
||||
from freqtrade.exchange.bittrex import Bittrex
|
||||
from freqtrade.exchange.bybit import Bybit
|
||||
from freqtrade.exchange.coinbasepro import Coinbasepro
|
||||
from freqtrade.exchange.exchange import (available_exchanges, ccxt_exchanges,
|
||||
is_exchange_known_ccxt, is_exchange_officially_supported,
|
||||
market_is_active, timeframe_to_minutes, timeframe_to_msecs,
|
||||
timeframe_to_next_date, timeframe_to_prev_date,
|
||||
timeframe_to_seconds, validate_exchange,
|
||||
validate_exchanges)
|
||||
from freqtrade.exchange.exchange import (amount_to_contract_precision, amount_to_contracts,
|
||||
amount_to_precision, available_exchanges, ccxt_exchanges,
|
||||
contracts_to_amount, date_minus_candles,
|
||||
is_exchange_known_ccxt, market_is_active,
|
||||
price_to_precision, timeframe_to_minutes,
|
||||
timeframe_to_msecs, timeframe_to_next_date,
|
||||
timeframe_to_prev_date, timeframe_to_seconds,
|
||||
validate_exchange, validate_exchanges)
|
||||
from freqtrade.exchange.ftx import Ftx
|
||||
from freqtrade.exchange.gateio import Gateio
|
||||
from freqtrade.exchange.hitbtc import Hitbtc
|
||||
|
@@ -1,5 +1,4 @@
|
||||
""" Binance exchange subclass """
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -12,7 +11,7 @@ from freqtrade.enums import CandleType, MarginMode, TradingMode
|
||||
from freqtrade.exceptions import DDosProtection, OperationalException, TemporaryError
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.exchange.common import retrier
|
||||
from freqtrade.misc import deep_merge_dicts
|
||||
from freqtrade.misc import deep_merge_dicts, json_load
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -23,8 +22,7 @@ class Binance(Exchange):
|
||||
_ft_has: Dict = {
|
||||
"stoploss_on_exchange": True,
|
||||
"stoploss_order_types": {"limit": "stop_loss_limit"},
|
||||
"order_time_in_force": ['gtc', 'fok', 'ioc'],
|
||||
"time_in_force_parameter": "timeInForce",
|
||||
"order_time_in_force": ['GTC', 'FOK', 'IOC'],
|
||||
"ohlcv_candle_limit": 1000,
|
||||
"trades_pagination": "id",
|
||||
"trades_pagination_arg": "fromId",
|
||||
@@ -32,7 +30,7 @@ class Binance(Exchange):
|
||||
"ccxt_futures_name": "future"
|
||||
}
|
||||
_ft_has_futures: Dict = {
|
||||
"stoploss_order_types": {"limit": "stop"},
|
||||
"stoploss_order_types": {"limit": "limit", "market": "market"},
|
||||
"tickers_have_price": False,
|
||||
}
|
||||
|
||||
@@ -49,13 +47,12 @@ class Binance(Exchange):
|
||||
Returns True if adjustment is necessary.
|
||||
:param side: "buy" or "sell"
|
||||
"""
|
||||
|
||||
ordertype = 'stop' if self.trading_mode == TradingMode.FUTURES else 'stop_loss_limit'
|
||||
order_types = ('stop_loss_limit', 'stop', 'stop_market')
|
||||
|
||||
return (
|
||||
order.get('stopPrice', None) is None
|
||||
or (
|
||||
order['type'] == ordertype
|
||||
order['type'] in order_types
|
||||
and (
|
||||
(side == "sell" and stop_loss > float(order['stopPrice'])) or
|
||||
(side == "buy" and stop_loss < float(order['stopPrice']))
|
||||
@@ -71,6 +68,37 @@ class Binance(Exchange):
|
||||
tickers = deep_merge_dicts(bidsasks, tickers, allow_null_overrides=False)
|
||||
return tickers
|
||||
|
||||
@retrier
|
||||
def additional_exchange_init(self) -> None:
|
||||
"""
|
||||
Additional exchange initialization logic.
|
||||
.api will be available at this point.
|
||||
Must be overridden in child methods if required.
|
||||
"""
|
||||
try:
|
||||
if self.trading_mode == TradingMode.FUTURES and not self._config['dry_run']:
|
||||
position_side = self._api.fapiPrivateGetPositionsideDual()
|
||||
self._log_exchange_response('position_side_setting', position_side)
|
||||
assets_margin = self._api.fapiPrivateGetMultiAssetsMargin()
|
||||
self._log_exchange_response('multi_asset_margin', assets_margin)
|
||||
msg = ""
|
||||
if position_side.get('dualSidePosition') is True:
|
||||
msg += (
|
||||
"\nHedge Mode is not supported by freqtrade. "
|
||||
"Please change 'Position Mode' on your binance futures account.")
|
||||
if assets_margin.get('multiAssetsMargin') is True:
|
||||
msg += ("\nMulti-Asset Mode is not supported by freqtrade. "
|
||||
"Please change 'Asset Mode' on your binance futures account.")
|
||||
if msg:
|
||||
raise OperationalException(msg)
|
||||
except ccxt.DDoSProtection as e:
|
||||
raise DDosProtection(e) from e
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not set leverage due to {e.__class__.__name__}. Message: {e}') from e
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e) from e
|
||||
|
||||
@retrier
|
||||
def _set_leverage(
|
||||
self,
|
||||
@@ -137,23 +165,27 @@ class Binance(Exchange):
|
||||
pair: str,
|
||||
open_rate: float, # Entry price of position
|
||||
is_short: bool,
|
||||
position: float, # Absolute value of position size
|
||||
amount: float,
|
||||
stake_amount: float,
|
||||
wallet_balance: float, # Or margin balance
|
||||
mm_ex_1: float = 0.0, # (Binance) Cross only
|
||||
upnl_ex_1: float = 0.0, # (Binance) Cross only
|
||||
) -> Optional[float]:
|
||||
"""
|
||||
Important: Must be fetching data from cached values as this is used by backtesting!
|
||||
MARGIN: https://www.binance.com/en/support/faq/f6b010588e55413aa58b7d63ee0125ed
|
||||
PERPETUAL: https://www.binance.com/en/support/faq/b3c689c1f50a44cabb3a84e663b81d93
|
||||
|
||||
:param exchange_name:
|
||||
:param open_rate: (EP1) Entry price of position
|
||||
:param open_rate: Entry price of position
|
||||
:param is_short: True if the trade is a short, false otherwise
|
||||
:param position: Absolute value of position size (in base currency)
|
||||
:param wallet_balance: (WB)
|
||||
:param amount: Absolute value of position size incl. leverage (in base currency)
|
||||
:param stake_amount: Stake amount - Collateral in settle currency.
|
||||
:param trading_mode: SPOT, MARGIN, FUTURES, etc.
|
||||
:param margin_mode: Either ISOLATED or CROSS
|
||||
:param wallet_balance: Amount of margin_mode in the wallet being used to trade
|
||||
Cross-Margin Mode: crossWalletBalance
|
||||
Isolated-Margin Mode: isolatedWalletBalance
|
||||
:param maintenance_amt:
|
||||
|
||||
# * Only required for Cross
|
||||
:param mm_ex_1: (TMM)
|
||||
@@ -165,12 +197,11 @@ class Binance(Exchange):
|
||||
"""
|
||||
|
||||
side_1 = -1 if is_short else 1
|
||||
position = abs(position)
|
||||
cross_vars = upnl_ex_1 - mm_ex_1 if self.margin_mode == MarginMode.CROSS else 0.0
|
||||
|
||||
# mm_ratio: Binance's formula specifies maintenance margin rate which is mm_ratio * 100%
|
||||
# maintenance_amt: (CUM) Maintenance Amount of position
|
||||
mm_ratio, maintenance_amt = self.get_maintenance_ratio_and_amt(pair, position)
|
||||
mm_ratio, maintenance_amt = self.get_maintenance_ratio_and_amt(pair, stake_amount)
|
||||
|
||||
if (maintenance_amt is None):
|
||||
raise OperationalException(
|
||||
@@ -182,9 +213,9 @@ class Binance(Exchange):
|
||||
return (
|
||||
(
|
||||
(wallet_balance + cross_vars + maintenance_amt) -
|
||||
(side_1 * position * open_rate)
|
||||
(side_1 * amount * open_rate)
|
||||
) / (
|
||||
(position * mm_ratio) - (side_1 * position)
|
||||
(amount * mm_ratio) - (side_1 * amount)
|
||||
)
|
||||
)
|
||||
else:
|
||||
@@ -199,7 +230,7 @@ class Binance(Exchange):
|
||||
Path(__file__).parent / 'binance_leverage_tiers.json'
|
||||
)
|
||||
with open(leverage_tiers_path) as json_file:
|
||||
return json.load(json_file)
|
||||
return json_load(json_file)
|
||||
else:
|
||||
try:
|
||||
return self._api.fetch_leverage_tiers()
|
||||
|
@@ -1,16 +1,16 @@
|
||||
import logging
|
||||
from typing import Any, Dict
|
||||
|
||||
from freqtrade.constants import Config
|
||||
from freqtrade.enums import RunMode
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange import (available_exchanges, is_exchange_known_ccxt,
|
||||
is_exchange_officially_supported, validate_exchange)
|
||||
from freqtrade.exchange import available_exchanges, is_exchange_known_ccxt, validate_exchange
|
||||
from freqtrade.exchange.common import MAP_EXCHANGE_CHILDCLASS, SUPPORTED_EXCHANGES
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
||||
def check_exchange(config: Config, check_for_bad: bool = True) -> bool:
|
||||
"""
|
||||
Check if the exchange name in the config file is supported by Freqtrade
|
||||
:param check_for_bad: if True, check the exchange against the list of known 'bad'
|
||||
@@ -52,7 +52,7 @@ def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
||||
else:
|
||||
logger.warning(f'Exchange "{exchange}" will not work with Freqtrade. Reason: {reason}')
|
||||
|
||||
if is_exchange_officially_supported(exchange):
|
||||
if MAP_EXCHANGE_CHILDCLASS.get(exchange, exchange) in SUPPORTED_EXCHANGES:
|
||||
logger.info(f'Exchange "{exchange}" is officially supported '
|
||||
f'by the Freqtrade development team.')
|
||||
else:
|
@@ -1,6 +1,6 @@
|
||||
""" FTX exchange subclass """
|
||||
import logging
|
||||
from typing import Any, Dict, List, Tuple
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import ccxt
|
||||
|
||||
@@ -19,6 +19,7 @@ logger = logging.getLogger(__name__)
|
||||
class Ftx(Exchange):
|
||||
|
||||
_ft_has: Dict = {
|
||||
"order_time_in_force": ['GTC', 'IOC', 'PO'],
|
||||
"stoploss_on_exchange": True,
|
||||
"ohlcv_candle_limit": 1500,
|
||||
"ohlcv_require_since": True,
|
||||
@@ -116,9 +117,17 @@ class Ftx(Exchange):
|
||||
if len(order) == 1:
|
||||
if order[0].get('status') == 'closed':
|
||||
# Trigger order was triggered ...
|
||||
real_order_id = order[0].get('info', {}).get('orderId')
|
||||
real_order_id: Optional[str] = order[0].get('info', {}).get('orderId')
|
||||
# OrderId may be None for stoploss-market orders
|
||||
# But contains "average" in these cases.
|
||||
# So we need to get it through the endpoint
|
||||
# /conditional_orders/{conditional_order_id}/triggers
|
||||
if not real_order_id:
|
||||
res = self._api.privateGetConditionalOrdersConditionalOrderIdTriggers(
|
||||
params={'conditional_order_id': order_id})
|
||||
self._log_exchange_response('fetch_stoploss_order2', res)
|
||||
real_order_id = res['result'][0]['orderId'] if res.get(
|
||||
'result', []) else None
|
||||
|
||||
if real_order_id:
|
||||
order1 = self._api.fetch_order(real_order_id, pair)
|
||||
self._log_exchange_response('fetch_stoploss_order1', order1)
|
||||
|
@@ -25,9 +25,7 @@ class Gateio(Exchange):
|
||||
|
||||
_ft_has: Dict = {
|
||||
"ohlcv_candle_limit": 1000,
|
||||
"ohlcv_volume_currency": "quote",
|
||||
"time_in_force_parameter": "timeInForce",
|
||||
"order_time_in_force": ['gtc', 'ioc'],
|
||||
"order_time_in_force": ['GTC', 'IOC'],
|
||||
"stoploss_order_types": {"limit": "limit"},
|
||||
"stoploss_on_exchange": True,
|
||||
}
|
||||
@@ -58,7 +56,7 @@ class Gateio(Exchange):
|
||||
ordertype: str,
|
||||
leverage: float,
|
||||
reduceOnly: bool,
|
||||
time_in_force: str = 'gtc',
|
||||
time_in_force: str = 'GTC',
|
||||
) -> Dict:
|
||||
params = super()._get_params(
|
||||
side=side,
|
||||
@@ -70,7 +68,7 @@ class Gateio(Exchange):
|
||||
if ordertype == 'market' and self.trading_mode == TradingMode.FUTURES:
|
||||
params['type'] = 'market'
|
||||
param = self._ft_has.get('time_in_force_parameter', '')
|
||||
params.update({param: 'ioc'})
|
||||
params.update({param: 'IOC'})
|
||||
return params
|
||||
|
||||
def get_trades_for_order(self, order_id: str, pair: str, since: datetime,
|
||||
|
@@ -171,7 +171,7 @@ class Kraken(Exchange):
|
||||
ordertype: str,
|
||||
leverage: float,
|
||||
reduceOnly: bool,
|
||||
time_in_force: str = 'gtc'
|
||||
time_in_force: str = 'GTC'
|
||||
) -> Dict:
|
||||
params = super()._get_params(
|
||||
side=side,
|
||||
|
@@ -23,8 +23,7 @@ class Kucoin(Exchange):
|
||||
"stoploss_order_types": {"limit": "limit", "market": "market"},
|
||||
"l2_limit_range": [20, 100],
|
||||
"l2_limit_range_required": False,
|
||||
"order_time_in_force": ['gtc', 'fok', 'ioc'],
|
||||
"time_in_force_parameter": "timeInForce",
|
||||
"order_time_in_force": ['GTC', 'FOK', 'IOC'],
|
||||
"ohlcv_candle_limit": 1500,
|
||||
}
|
||||
|
||||
|
@@ -4,12 +4,10 @@ from typing import Dict, List, Optional, Tuple
|
||||
import ccxt
|
||||
|
||||
from freqtrade.constants import BuySell
|
||||
from freqtrade.enums import MarginMode, TradingMode
|
||||
from freqtrade.enums.candletype import CandleType
|
||||
from freqtrade.enums import CandleType, MarginMode, TradingMode
|
||||
from freqtrade.exceptions import DDosProtection, OperationalException, TemporaryError
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.exchange import Exchange, date_minus_candles
|
||||
from freqtrade.exchange.common import retrier
|
||||
from freqtrade.exchange.exchange import date_minus_candles
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -40,6 +38,8 @@ class Okx(Exchange):
|
||||
|
||||
net_only = True
|
||||
|
||||
_ccxt_params: Dict = {'options': {'brokerId': 'ffb5405ad327SUDE'}}
|
||||
|
||||
def ohlcv_candle_limit(
|
||||
self, timeframe: str, candle_type: CandleType, since_ms: Optional[int] = None) -> int:
|
||||
"""
|
||||
@@ -71,13 +71,15 @@ class Okx(Exchange):
|
||||
try:
|
||||
if self.trading_mode == TradingMode.FUTURES and not self._config['dry_run']:
|
||||
accounts = self._api.fetch_accounts()
|
||||
self._log_exchange_response('fetch_accounts', accounts)
|
||||
if len(accounts) > 0:
|
||||
self.net_only = accounts[0].get('info', {}).get('posMode') == 'net_mode'
|
||||
except ccxt.DDoSProtection as e:
|
||||
raise DDosProtection(e) from e
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not set leverage due to {e.__class__.__name__}. Message: {e}') from e
|
||||
f'Error in additional_exchange_init due to {e.__class__.__name__}. Message: {e}'
|
||||
) from e
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e) from e
|
||||
|
||||
@@ -97,7 +99,7 @@ class Okx(Exchange):
|
||||
ordertype: str,
|
||||
leverage: float,
|
||||
reduceOnly: bool,
|
||||
time_in_force: str = 'gtc',
|
||||
time_in_force: str = 'GTC',
|
||||
) -> Dict:
|
||||
params = super()._get_params(
|
||||
side=side,
|
||||
@@ -145,4 +147,4 @@ class Okx(Exchange):
|
||||
return float('inf')
|
||||
|
||||
pair_tiers = self._leverage_tiers[pair]
|
||||
return pair_tiers[-1]['max'] / leverage
|
||||
return pair_tiers[-1]['maxNotional'] / leverage
|
||||
|