mirror of
https://github.com/freqtrade/freqtrade.git
synced 2025-11-29 00:23:07 +00:00
Compare commits
1090 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41e698c482 | ||
|
|
795c2e4aa2 | ||
|
|
031a63d5c2 | ||
|
|
f5ef8f5bc0 | ||
|
|
30f7536cbe | ||
|
|
8abdbc41e1 | ||
|
|
7f229bbf39 | ||
|
|
d4947ba0ee | ||
|
|
2cee716181 | ||
|
|
a7383ad35d | ||
|
|
52cc2d224e | ||
|
|
5db10bdcc7 | ||
|
|
43119efaf0 | ||
|
|
16bf7aa3ab | ||
|
|
b2a623ee16 | ||
|
|
c40406d26e | ||
|
|
87ff5ad1e0 | ||
|
|
aa63f2be1f | ||
|
|
5cb90bdf77 | ||
|
|
4f557af6cb | ||
|
|
5f63797f17 | ||
|
|
bbb32ada4a | ||
|
|
fc33f19b06 | ||
|
|
7efab85b10 | ||
|
|
0ece168833 | ||
|
|
6be4c6af0e | ||
|
|
4f6df73156 | ||
|
|
cd20078bef | ||
|
|
5e0e8de4f6 | ||
|
|
ed5e76adac | ||
|
|
12265b245d | ||
|
|
37b1389f12 | ||
|
|
b679eb1a95 | ||
|
|
2f79cf1304 | ||
|
|
3fe0cb9281 | ||
|
|
9f828224bc | ||
|
|
2153e43969 | ||
|
|
c6d19a4afb | ||
|
|
016e8fde89 | ||
|
|
d87db70ed0 | ||
|
|
c3b9d69919 | ||
|
|
f204af173d | ||
|
|
12ca103f9f | ||
|
|
c2ca899c7e | ||
|
|
902ffa6853 | ||
|
|
93ebf163cb | ||
|
|
f736646ac6 | ||
|
|
262113f9ee | ||
|
|
e75cdd4c27 | ||
|
|
559257ed33 | ||
|
|
71e671f053 | ||
|
|
6856848efc | ||
|
|
ff6967de9e | ||
|
|
5c4170951a | ||
|
|
500eb17449 | ||
|
|
ffdc33d964 | ||
|
|
fb8555a6cc | ||
|
|
ebf1126351 | ||
|
|
3a81eb7d48 | ||
|
|
3ad4d937c5 | ||
|
|
c35e5ca7dd | ||
|
|
4a6c8f3cb2 | ||
|
|
e7c8e62d75 | ||
|
|
d6d16b4696 | ||
|
|
dc1968b968 | ||
|
|
4fef9448bf | ||
|
|
4bb5345e13 | ||
|
|
d294cab933 | ||
|
|
f139178136 | ||
|
|
4eb0ed9f2f | ||
|
|
7a598f32dc | ||
|
|
b776336ebf | ||
|
|
481df98f58 | ||
|
|
8cb1024ff6 | ||
|
|
41ff2a9276 | ||
|
|
acb99a03e3 | ||
|
|
4b2eb22989 | ||
|
|
a505826ec9 | ||
|
|
54d068de44 | ||
|
|
25d8e93a90 | ||
|
|
9712fb2d57 | ||
|
|
2b49a11b2a | ||
|
|
1bfc667515 | ||
|
|
4c5432be6f | ||
|
|
9dc2a30793 | ||
|
|
13e8f25ca9 | ||
|
|
ac1964edb1 | ||
|
|
dbb1bbf101 | ||
|
|
0ac80aacd1 | ||
|
|
7486cb7c64 | ||
|
|
e3cdc0a05b | ||
|
|
6913bce6a1 | ||
|
|
7010c835d2 | ||
|
|
2aa1b43f01 | ||
|
|
32cbb714f9 | ||
|
|
7f4fd6168a | ||
|
|
647534a4f8 | ||
|
|
31fa857319 | ||
|
|
a363d443bf | ||
|
|
75c522e082 | ||
|
|
ebeaf64fbb | ||
|
|
6afe232c4d | ||
|
|
05df7f3394 | ||
|
|
0cdbe714d2 | ||
|
|
9d6d60dcf0 | ||
|
|
65350ad552 | ||
|
|
b437c3cf0c | ||
|
|
5488c66f53 | ||
|
|
ef48193fad | ||
|
|
9ee1dd99eb | ||
|
|
0307ba7883 | ||
|
|
1a5b0969b9 | ||
|
|
3c399fbe3f | ||
|
|
a9a5c4a052 | ||
|
|
d5498c8712 | ||
|
|
09321ccc9c | ||
|
|
a3fe5f5757 | ||
|
|
dfed713647 | ||
|
|
92dc3c89af | ||
|
|
eb610441b5 | ||
|
|
67eeb145e1 | ||
|
|
a3835b1279 | ||
|
|
5f38d5ee63 | ||
|
|
53eaf85969 | ||
|
|
d54acca53a | ||
|
|
2959156070 | ||
|
|
b0ddb33acc | ||
|
|
62141d3d27 | ||
|
|
478c149bbb | ||
|
|
7b39a3084f | ||
|
|
a6daf0d991 | ||
|
|
54f11ad603 | ||
|
|
40df0dcf3d | ||
|
|
99d256422e | ||
|
|
389feda65f | ||
|
|
5a8f0f3557 | ||
|
|
b9b76977b6 | ||
|
|
27917c2d89 | ||
|
|
0cfdce0d5e | ||
|
|
ab0e657d77 | ||
|
|
34b40500c3 | ||
|
|
a3b0135557 | ||
|
|
8546db9dfd | ||
|
|
ab579587f2 | ||
|
|
ecd75e43b0 | ||
|
|
061f91ba41 | ||
|
|
97b31352c2 | ||
|
|
77d2479c75 | ||
|
|
f0b2798c37 | ||
|
|
8002936fe3 | ||
|
|
f440bb193d | ||
|
|
faa5883f09 | ||
|
|
7251e5bd62 | ||
|
|
7be90f71d3 | ||
|
|
19d3a0cbac | ||
|
|
0ddafeeabf | ||
|
|
b2ad402df4 | ||
|
|
e46dac3fbd | ||
|
|
5c8fbe2c6f | ||
|
|
f11a1b0122 | ||
|
|
8f4cca47e9 | ||
|
|
4fa736114c | ||
|
|
13ac1e1957 | ||
|
|
c28a0374f1 | ||
|
|
93229fc54b | ||
|
|
997190a050 | ||
|
|
707a5fca91 | ||
|
|
6d92b9b910 | ||
|
|
9b38c04579 | ||
|
|
06144a1fc4 | ||
|
|
0d152eb907 | ||
|
|
1a61bf7bff | ||
|
|
87a296f728 | ||
|
|
e98c0621d3 | ||
|
|
40c0b4ef2e | ||
|
|
44142706c3 | ||
|
|
208832e847 | ||
|
|
12066411db | ||
|
|
e5008fbf93 | ||
|
|
d4ffdaffc2 | ||
|
|
bb5a310aec | ||
|
|
ba558b2d75 | ||
|
|
82b344db1b | ||
|
|
f2599ffe90 | ||
|
|
50fc63251e | ||
|
|
b1ef39927c | ||
|
|
b4472a165e | ||
|
|
a87fc5f863 | ||
|
|
2f3f5f19cd | ||
|
|
e11eb4775e | ||
|
|
a15a3ae810 | ||
|
|
daeb172ba1 | ||
|
|
0e5b0ebda6 | ||
|
|
d5254dff7b | ||
|
|
146d6bf7fb | ||
|
|
0a8c1528cf | ||
|
|
941921dd0f | ||
|
|
0ca3a38ba6 | ||
|
|
1678a039ae | ||
|
|
e5406ed3cf | ||
|
|
4d9ca71c82 | ||
|
|
6045f07a9c | ||
|
|
9b22d5cab1 | ||
|
|
753b03d581 | ||
|
|
1e37d8ccb3 | ||
|
|
4038cdf70a | ||
|
|
d09b33ae93 | ||
|
|
0687051ffb | ||
|
|
8641da13b9 | ||
|
|
cc32566c92 | ||
|
|
955e2d2826 | ||
|
|
4e57969e4e | ||
|
|
52012003e9 | ||
|
|
3bdc7b9a88 | ||
|
|
a2a2489a97 | ||
|
|
b2c2b42408 | ||
|
|
f5744cc9bf | ||
|
|
56264ea52a | ||
|
|
1f50bc79bc | ||
|
|
c6d2c1e520 | ||
|
|
8aee009a0a | ||
|
|
5ccd618189 | ||
|
|
5161e1abb3 | ||
|
|
e15f2ef11a | ||
|
|
8dea640e9a | ||
|
|
4005b8d1d2 | ||
|
|
85ac99aee0 | ||
|
|
e085fd9e95 | ||
|
|
f26ed1c8c1 | ||
|
|
4cf7282027 | ||
|
|
0ae81d4115 | ||
|
|
226fc3d99b | ||
|
|
bd29b7d031 | ||
|
|
c8b0c9af0a | ||
|
|
01c4f243d4 | ||
|
|
fe9322ecd5 | ||
|
|
904b3008a9 | ||
|
|
66f1e0f4cd | ||
|
|
e8bfeae048 | ||
|
|
fd7278517d | ||
|
|
b13735e4cc | ||
|
|
a8be277ca0 | ||
|
|
1dfbf6eed6 | ||
|
|
29b9bb96f3 | ||
|
|
14167f826b | ||
|
|
96ea27322d | ||
|
|
71d3a7de40 | ||
|
|
fe3836b497 | ||
|
|
49559f1a1a | ||
|
|
042354d00f | ||
|
|
f0d3901b6b | ||
|
|
9d6f629f6a | ||
|
|
7b99d5ebcb | ||
|
|
8b2174d249 | ||
|
|
ffdca7eea7 | ||
|
|
684727b32e | ||
|
|
3a8b69d69b | ||
|
|
1bba9fcc53 | ||
|
|
f7fc9adc63 | ||
|
|
e60d1788b2 | ||
|
|
a7e13e96e4 | ||
|
|
e644493e02 | ||
|
|
06f4e627fc | ||
|
|
e0775546f6 | ||
|
|
0dc96210b6 | ||
|
|
a95f30ce45 | ||
|
|
83a2427a61 | ||
|
|
184b13f2fb | ||
|
|
9a632d9b7c | ||
|
|
c404e9ffd0 | ||
|
|
b1fe8c5325 | ||
|
|
7307084dfd | ||
|
|
40899d08dd | ||
|
|
00e6749d8b | ||
|
|
05466d318a | ||
|
|
6312d785d8 | ||
|
|
34ff946f4d | ||
|
|
158cb307f6 | ||
|
|
e35daf95c0 | ||
|
|
b448890210 | ||
|
|
be6836b0ef | ||
|
|
60afba5592 | ||
|
|
d043542094 | ||
|
|
89145a7711 | ||
|
|
7744989583 | ||
|
|
35d65bc7d7 | ||
|
|
7fdb099097 | ||
|
|
1f55356744 | ||
|
|
00821036bb | ||
|
|
6b89e86a97 | ||
|
|
65f5aa59e6 | ||
|
|
0eff324ce0 | ||
|
|
676c6a784d | ||
|
|
cc369f41f5 | ||
|
|
6c889895bd | ||
|
|
580ada8c4f | ||
|
|
aa15312670 | ||
|
|
df6f3f6f32 | ||
|
|
2b09e3ca3d | ||
|
|
9a61067367 | ||
|
|
c8617e70a8 | ||
|
|
38b959f1a9 | ||
|
|
50ea4c39da | ||
|
|
ff08416b12 | ||
|
|
8d173efe2d | ||
|
|
aa698a8412 | ||
|
|
e6bfedb58b | ||
|
|
37e6b262eb | ||
|
|
9373d0c915 | ||
|
|
a467d76832 | ||
|
|
937399606e | ||
|
|
c2076af43b | ||
|
|
4de4a70be7 | ||
|
|
8afce7e651 | ||
|
|
2bf7f2feae | ||
|
|
8386496456 | ||
|
|
7f9c76a6fc | ||
|
|
d4d37667e1 | ||
|
|
d4543be8eb | ||
|
|
e38a3051a1 | ||
|
|
c907e80c10 | ||
|
|
a241e950f2 | ||
|
|
39232cbcbb | ||
|
|
a7b60f6780 | ||
|
|
05ab1c2e0a | ||
|
|
8c7e8255bb | ||
|
|
f0e5113a7f | ||
|
|
a830bee9c7 | ||
|
|
bdc0134e88 | ||
|
|
190ecb7ada | ||
|
|
a77d513513 | ||
|
|
7b99daebd7 | ||
|
|
2d4a2fd10b | ||
|
|
a0e6cd93b6 | ||
|
|
b3f42dc51e | ||
|
|
b0cad30796 | ||
|
|
fc360608b7 | ||
|
|
01733c94fa | ||
|
|
68a9b14eca | ||
|
|
738ed93221 | ||
|
|
7166a474ae | ||
|
|
e632539b61 | ||
|
|
e7f6df46e8 | ||
|
|
a123246ac9 | ||
|
|
ddb9933c91 | ||
|
|
9f7f089d8a | ||
|
|
e1f48c2b46 | ||
|
|
d7017ce1e4 | ||
|
|
6666d31ee9 | ||
|
|
29aa159827 | ||
|
|
6bfc37309e | ||
|
|
71c530590e | ||
|
|
d596a877fa | ||
|
|
b9b15e5f32 | ||
|
|
d66e6510e3 | ||
|
|
a233a8cc82 | ||
|
|
d42ebab575 | ||
|
|
51af8c27f6 | ||
|
|
44acf2f471 | ||
|
|
ceb1e4c4f7 | ||
|
|
6db6c3b2cc | ||
|
|
2e02e24e70 | ||
|
|
95a3b5c41e | ||
|
|
3fe06b3548 | ||
|
|
1a83eed38f | ||
|
|
4fa1604230 | ||
|
|
edf2cd0b92 | ||
|
|
b5034cf535 | ||
|
|
29305dd070 | ||
|
|
3c99e3b7c7 | ||
|
|
9a226ec7e6 | ||
|
|
2959600f52 | ||
|
|
ff9231eec4 | ||
|
|
6b8f5963a8 | ||
|
|
a1841c35ae | ||
|
|
aa2d747d8f | ||
|
|
ee613b564c | ||
|
|
2bf5a3843d | ||
|
|
29e84c9e88 | ||
|
|
23666858e2 | ||
|
|
5151a4521f | ||
|
|
6b948cfc7e | ||
|
|
9054165e8a | ||
|
|
11cc33a982 | ||
|
|
e2bcaa4d75 | ||
|
|
94b2d48d02 | ||
|
|
0293a61895 | ||
|
|
7ffe65770e | ||
|
|
cb9849e192 | ||
|
|
299e640170 | ||
|
|
954963b40e | ||
|
|
779bcdd990 | ||
|
|
0ffefe44a7 | ||
|
|
deddbda26e | ||
|
|
1a92bf9e8e | ||
|
|
8741017819 | ||
|
|
35c2b961be | ||
|
|
0d980134e7 | ||
|
|
3ad0686bc7 | ||
|
|
df9410cd15 | ||
|
|
041e9957dd | ||
|
|
6b97af4a03 | ||
|
|
e234158cc9 | ||
|
|
c30fb7f590 | ||
|
|
5c840f333f | ||
|
|
b24a22b0b6 | ||
|
|
47cc04c0a3 | ||
|
|
ccad883256 | ||
|
|
3a2aa54d2a | ||
|
|
d423f58566 | ||
|
|
0bcf50f1b5 | ||
|
|
8d5cc42ef5 | ||
|
|
a772ab323e | ||
|
|
f55d75e7fc | ||
|
|
5865688c16 | ||
|
|
3e4c9c8713 | ||
|
|
36e95bc868 | ||
|
|
3e40f5c588 | ||
|
|
643262bc6a | ||
|
|
f1f311e456 | ||
|
|
c1a22dda46 | ||
|
|
d14134ddce | ||
|
|
48d33b070f | ||
|
|
0eb9dd5fe5 | ||
|
|
4705b7da0e | ||
|
|
c0f276a892 | ||
|
|
e666c6850e | ||
|
|
f9aa3c27be | ||
|
|
5fb8100fc5 | ||
|
|
41add9f8ca | ||
|
|
513b96b61c | ||
|
|
8730852d6e | ||
|
|
ca496c13b8 | ||
|
|
0467004144 | ||
|
|
e14739e102 | ||
|
|
0eaac1cd79 | ||
|
|
5f726d697b | ||
|
|
9c1c962aa7 | ||
|
|
c122eab77b | ||
|
|
617d2338c4 | ||
|
|
c56f288b56 | ||
|
|
51b4d5a57a | ||
|
|
43d30180e8 | ||
|
|
3b805813cd | ||
|
|
21cb4eafe5 | ||
|
|
fa4c8110e7 | ||
|
|
25529ad95f | ||
|
|
dba30bbfed | ||
|
|
4cd70138b6 | ||
|
|
0a2cacbba8 | ||
|
|
d213764d19 | ||
|
|
702153d087 | ||
|
|
8babf0d2b5 | ||
|
|
9c1d4183fd | ||
|
|
c4992bd5f3 | ||
|
|
2da0d479e7 | ||
|
|
628d9577a2 | ||
|
|
6b2f4b12fd | ||
|
|
bc7688a69f | ||
|
|
7b901e180a | ||
|
|
e67ffd2d87 | ||
|
|
045de94b49 | ||
|
|
8624d83be0 | ||
|
|
0634e135df | ||
|
|
962cfc5eb9 | ||
|
|
ca64d8a861 | ||
|
|
35250eb230 | ||
|
|
5dd0a72a52 | ||
|
|
735e78f01d | ||
|
|
ae7c4c33c0 | ||
|
|
c032dd0f45 | ||
|
|
ce46555e77 | ||
|
|
2f98dd0429 | ||
|
|
71f5392f89 | ||
|
|
6d63b8e71e | ||
|
|
f6ca97d1dc | ||
|
|
4e50ec81a0 | ||
|
|
386abc5eba | ||
|
|
04ea6dac83 | ||
|
|
f16913a76d | ||
|
|
03ff87d11c | ||
|
|
460e0711c6 | ||
|
|
b8eb3ecb1d | ||
|
|
2208a21a6c | ||
|
|
2d0aca0d20 | ||
|
|
b7a558b951 | ||
|
|
3c5deb9aaf | ||
|
|
4d64124eef | ||
|
|
e2cbb7e7da | ||
|
|
df79098adc | ||
|
|
13ba5ba0db | ||
|
|
2eb2ace539 | ||
|
|
064f6629ab | ||
|
|
786244c0d3 | ||
|
|
e1ae0d7e90 | ||
|
|
c36fa0c7e2 | ||
|
|
24c587518a | ||
|
|
4c1f2b2a5b | ||
|
|
6bcfe65877 | ||
|
|
28a70eba07 | ||
|
|
285db2f40b | ||
|
|
0fc5445003 | ||
|
|
e8ea2e6f05 | ||
|
|
b792f00553 | ||
|
|
4df44d8b32 | ||
|
|
58c296c1ff | ||
|
|
13de66d559 | ||
|
|
e5498ca20f | ||
|
|
0558b203fe | ||
|
|
38d09f9e78 | ||
|
|
768f62a24a | ||
|
|
7e62a4a79c | ||
|
|
761861f0b7 | ||
|
|
4e291795a6 | ||
|
|
7fe9d9520a | ||
|
|
4c2961f0d9 | ||
|
|
ef26484153 | ||
|
|
79aac473b3 | ||
|
|
5c3177cc79 | ||
|
|
6c75b8a36a | ||
|
|
ee0e381d65 | ||
|
|
8cb7a7e7a5 | ||
|
|
bcf5b5fdcb | ||
|
|
ef18ddd866 | ||
|
|
cee4116b80 | ||
|
|
0c53bd6dd4 | ||
|
|
aff334fdd6 | ||
|
|
185bd1e53c | ||
|
|
006635003e | ||
|
|
f2fd5205ef | ||
|
|
31be4d2454 | ||
|
|
5c18346cd5 | ||
|
|
e0b634ba3b | ||
|
|
a05155cb75 | ||
|
|
455b168366 | ||
|
|
06f486a8eb | ||
|
|
42722b2873 | ||
|
|
ecb5137dbe | ||
|
|
2531961bf8 | ||
|
|
417bf2c935 | ||
|
|
3673dba1e2 | ||
|
|
9b288c6933 | ||
|
|
5fac4f7b45 | ||
|
|
c7b6e19872 | ||
|
|
033e9e09fb | ||
|
|
3dcf3f8a82 | ||
|
|
403ed48c3e | ||
|
|
4d797c9232 | ||
|
|
ec6794b9ba | ||
|
|
634ce87bba | ||
|
|
98bca30dfb | ||
|
|
cc0fae8e4e | ||
|
|
8d8da71f20 | ||
|
|
9a097214a6 | ||
|
|
619945b861 | ||
|
|
71774bce6f | ||
|
|
9c54886f14 | ||
|
|
1252bacb7a | ||
|
|
a1b00f9053 | ||
|
|
e4369e06bc | ||
|
|
29b8b79732 | ||
|
|
2c7c19dfb1 | ||
|
|
b79d967371 | ||
|
|
69bb6ebaf6 | ||
|
|
57b2fb4645 | ||
|
|
bf5d2a68f5 | ||
|
|
7738ebbc0f | ||
|
|
905beef8a3 | ||
|
|
6d7f788989 | ||
|
|
be754244a3 | ||
|
|
e0f426d863 | ||
|
|
e987a915e8 | ||
|
|
a79ff1c6c9 | ||
|
|
2dcb4134cc | ||
|
|
e309f75118 | ||
|
|
643402da1c | ||
|
|
a1d1abfffc | ||
|
|
b5758e67f9 | ||
|
|
2851833726 | ||
|
|
c1ef6940b0 | ||
|
|
2aba9c081c | ||
|
|
eb21170691 | ||
|
|
d9129cb9c5 | ||
|
|
af02e34b57 | ||
|
|
4315c157c7 | ||
|
|
9e082ca3a9 | ||
|
|
ba23f58ff3 | ||
|
|
da5bef501e | ||
|
|
4fbba98168 | ||
|
|
87c82dea3d | ||
|
|
c08a2b6638 | ||
|
|
7bc874c7fd | ||
|
|
d76dc3ca0e | ||
|
|
fac0e4e603 | ||
|
|
7dbb7a52ed | ||
|
|
3ec3438acf | ||
|
|
1cd54829cc | ||
|
|
bd6644a91a | ||
|
|
199e3d2234 | ||
|
|
5906d37818 | ||
|
|
ab62bbc0a4 | ||
|
|
e495ffec78 | ||
|
|
84ccb85184 | ||
|
|
686949b258 | ||
|
|
3e2f90a32a | ||
|
|
bb31e64752 | ||
|
|
58864adc4a | ||
|
|
788cbb6776 | ||
|
|
481cf02db9 | ||
|
|
2f225e2340 | ||
|
|
f9d68d919c | ||
|
|
dffb27326e | ||
|
|
6d7834a389 | ||
|
|
f63fdf411d | ||
|
|
cd48556c5a | ||
|
|
eed1c2344d | ||
|
|
4241caef95 | ||
|
|
2103ae5fdf | ||
|
|
6055906eb1 | ||
|
|
e98edc1a1a | ||
|
|
62382809b2 | ||
|
|
0572336ff7 | ||
|
|
9fad83bd15 | ||
|
|
d8feceebb5 | ||
|
|
19625e9e1d | ||
|
|
f1ededf0eb | ||
|
|
da4faacd6b | ||
|
|
39c28626aa | ||
|
|
5e8a7a03c3 | ||
|
|
dd2522d8d0 | ||
|
|
fe792882b5 | ||
|
|
1bbb04da60 | ||
|
|
e785a66768 | ||
|
|
df8067d6c4 | ||
|
|
d3ead2cd09 | ||
|
|
c879591f45 | ||
|
|
c315f63e4b | ||
|
|
2fb36b116d | ||
|
|
ca388a9acf | ||
|
|
32b02c9925 | ||
|
|
54d5bce445 | ||
|
|
b7afcf3416 | ||
|
|
66cc600076 | ||
|
|
ea6d4a9d36 | ||
|
|
e0c420b93f | ||
|
|
67cea9dce6 | ||
|
|
7c651632f1 | ||
|
|
13a16178d2 | ||
|
|
c2bc316e2f | ||
|
|
8ed3658447 | ||
|
|
3aa614b983 | ||
|
|
3953092edd | ||
|
|
ef5a0b9afc | ||
|
|
98bd713624 | ||
|
|
f852be1a9b | ||
|
|
dcc86bfa55 | ||
|
|
aee7b2c29d | ||
|
|
c17eb89e84 | ||
|
|
aaa8567708 | ||
|
|
7e1e09d45a | ||
|
|
b87e15774b | ||
|
|
8e7e670003 | ||
|
|
8fc8c985d8 | ||
|
|
69a24c1272 | ||
|
|
e8daadfb7e | ||
|
|
91629807f7 | ||
|
|
f551fb5ff7 | ||
|
|
e8ef36fb6e | ||
|
|
b9a5899c99 | ||
|
|
607190cd38 | ||
|
|
018cee8413 | ||
|
|
0b5f4dc38e | ||
|
|
160c467e01 | ||
|
|
d91dbf4090 | ||
|
|
69f69d965c | ||
|
|
624ce6707a | ||
|
|
5e741a0f73 | ||
|
|
d6c0c107ac | ||
|
|
7ed15c64ba | ||
|
|
08d35f3e15 | ||
|
|
4dffb17dd6 | ||
|
|
14d6cdf9b2 | ||
|
|
7248537d4a | ||
|
|
b91981f0aa | ||
|
|
585f525879 | ||
|
|
58bd272c0f | ||
|
|
fe2f98c802 | ||
|
|
76187cc3d9 | ||
|
|
3bb9e17b0d | ||
|
|
f0c9064b77 | ||
|
|
e0142526e3 | ||
|
|
e9aba03981 | ||
|
|
9a50771a27 | ||
|
|
92eb951966 | ||
|
|
e6a8ecbf66 | ||
|
|
39626bb520 | ||
|
|
f48936dcde | ||
|
|
395a7b25be | ||
|
|
02698c7493 | ||
|
|
6fd932bf7d | ||
|
|
fcc7cb9892 | ||
|
|
21ffdbb3a2 | ||
|
|
f847bf0b8d | ||
|
|
64891df122 | ||
|
|
218b501119 | ||
|
|
0a71ebce68 | ||
|
|
80440f25cf | ||
|
|
1d940041e3 | ||
|
|
40fea4593f | ||
|
|
02c3552954 | ||
|
|
91ed02134e | ||
|
|
e8ed8a2ea7 | ||
|
|
f2dd32e319 | ||
|
|
5243941c4d | ||
|
|
8d5474d4d5 | ||
|
|
576d893d95 | ||
|
|
697e698abc | ||
|
|
24f779eda7 | ||
|
|
2ce3bd956d | ||
|
|
ba4e5cae54 | ||
|
|
645ec30ec5 | ||
|
|
d07cc5929e | ||
|
|
8d9114aa79 | ||
|
|
68a4e0426e | ||
|
|
10e548dcab | ||
|
|
e3ae8d3f69 | ||
|
|
576d9b8f5c | ||
|
|
0c959c22ec | ||
|
|
6ad1089f45 | ||
|
|
9f87a27465 | ||
|
|
2b71e8de5c | ||
|
|
84b6b8fe97 | ||
|
|
421be5da86 | ||
|
|
09cb043b24 | ||
|
|
cf283344de | ||
|
|
dcfa4d421e | ||
|
|
1a1123a555 | ||
|
|
382215eb70 | ||
|
|
f095492804 | ||
|
|
22e82f5e47 | ||
|
|
69ef743811 | ||
|
|
38f73dafb3 | ||
|
|
e0ad095bc7 | ||
|
|
1d08ada939 | ||
|
|
3446dd1792 | ||
|
|
02d13645b0 | ||
|
|
ba07348b82 | ||
|
|
bfd8609352 | ||
|
|
b112f2f315 | ||
|
|
d222dd6717 | ||
|
|
3bc96c16ac | ||
|
|
da5210ef5b | ||
|
|
e5b0224050 | ||
|
|
e43aaaef9c | ||
|
|
422a0ce114 | ||
|
|
22e7ad8ec1 | ||
|
|
b840b9f53a | ||
|
|
eec7276393 | ||
|
|
5e7ba85dbe | ||
|
|
3c316fe3e4 | ||
|
|
56a3d78128 | ||
|
|
ab8cc5f586 | ||
|
|
bd24646822 | ||
|
|
a97b3ab04a | ||
|
|
3afe54790e | ||
|
|
38d293cc26 | ||
|
|
497a467864 | ||
|
|
dcceb40fab | ||
|
|
9960fe07bc | ||
|
|
74b03d0529 | ||
|
|
ac199b626a | ||
|
|
8750f1be3f | ||
|
|
05d65b81da | ||
|
|
d136cac181 | ||
|
|
97f6a45819 | ||
|
|
ad8b1bbb79 | ||
|
|
5ea332e9be | ||
|
|
06e0616fb0 | ||
|
|
372c5d813a | ||
|
|
fd94b322be | ||
|
|
896c9d34fd | ||
|
|
13e2f71d30 | ||
|
|
c412cd9e57 | ||
|
|
86a0863e30 | ||
|
|
a06593e6e9 | ||
|
|
89ddfe08f4 | ||
|
|
580e9ccaf3 | ||
|
|
7c71b9513c | ||
|
|
188c391444 | ||
|
|
c77607b997 | ||
|
|
3221f883d3 | ||
|
|
1e7431a7b8 | ||
|
|
e66808bb02 | ||
|
|
fc92491a47 | ||
|
|
6e2de75bcb | ||
|
|
d6cdfc58af | ||
|
|
7b138ef3b4 | ||
|
|
27b2021726 | ||
|
|
e7800aa88a | ||
|
|
a2bc1da669 | ||
|
|
1e749a0f9b | ||
|
|
d7df5d5715 | ||
|
|
6525a838d1 | ||
|
|
f0af4601f9 | ||
|
|
a9abc25785 | ||
|
|
0aa0b1d4fe | ||
|
|
5f61da30ed | ||
|
|
d6df3e55c0 | ||
|
|
e503d811bd | ||
|
|
b981cfcaa0 | ||
|
|
a206777fe5 | ||
|
|
06ec106079 | ||
|
|
646e98da55 | ||
|
|
2b029b2a86 | ||
|
|
9edb88051d | ||
|
|
35c8d1dcbe | ||
|
|
8f3ea3608a | ||
|
|
5ecdecd1eb | ||
|
|
58f1abf287 | ||
|
|
d3a37db79a | ||
|
|
f034235af4 | ||
|
|
1340b71633 | ||
|
|
fed3ebfb46 | ||
|
|
a7db4d74cb | ||
|
|
84cc4887ce | ||
|
|
e38c06afe9 | ||
|
|
f1a5a8e20e | ||
|
|
4ab7edd3d6 | ||
|
|
05570732c6 | ||
|
|
7206287b00 | ||
|
|
b119a767de | ||
|
|
a6d74a1463 | ||
|
|
70881f12d2 | ||
|
|
1be3d57b60 | ||
|
|
07577ac18d | ||
|
|
e4a399039b | ||
|
|
34b617065d | ||
|
|
2a16e9b6a0 | ||
|
|
8a3615dea3 | ||
|
|
6fb50e35c9 | ||
|
|
a733630083 | ||
|
|
b48430f922 | ||
|
|
4e760e1a5e | ||
|
|
30e3b52b1e | ||
|
|
b52da0ad09 | ||
|
|
797ac71376 | ||
|
|
e8423d8155 | ||
|
|
b421e437ab | ||
|
|
2b65e3f35c | ||
|
|
c2578c7321 | ||
|
|
87329a393c | ||
|
|
a2618208ef | ||
|
|
70780bb01e | ||
|
|
89eddfd349 | ||
|
|
1c4ee35eca | ||
|
|
e41e45413f | ||
|
|
c7ebd8228e | ||
|
|
cc6466388e | ||
|
|
27d907e71b | ||
|
|
a2c01916e1 | ||
|
|
357c28d5ea | ||
|
|
648def69ca | ||
|
|
97a8341436 | ||
|
|
30cdf85ffa | ||
|
|
75cedfafb8 | ||
|
|
9d6c54791b | ||
|
|
e682eceae4 | ||
|
|
2533112254 | ||
|
|
08d98773f3 | ||
|
|
da51ef40f8 | ||
|
|
91c714c7d1 | ||
|
|
5e2e96acd2 | ||
|
|
611b48dbb9 | ||
|
|
50bc20134f | ||
|
|
baa5cc5b9e | ||
|
|
aa03a864f7 | ||
|
|
a44f781284 | ||
|
|
d108138999 | ||
|
|
cffc9ce890 | ||
|
|
6d588b3b0b | ||
|
|
bfb7121583 | ||
|
|
e31fa8721f | ||
|
|
29439c05d6 | ||
|
|
1cd5abde37 | ||
|
|
12e8108015 | ||
|
|
07b4afedf7 | ||
|
|
399d2d89a3 | ||
|
|
22d3881b6e | ||
|
|
494b905d1e | ||
|
|
f0cfab7940 | ||
|
|
cfe00c2f0c | ||
|
|
678162fada | ||
|
|
da04182287 | ||
|
|
a3897c990d | ||
|
|
929995117f | ||
|
|
04786f09f4 | ||
|
|
9b97e1e8fb | ||
|
|
cd2bccd441 | ||
|
|
e9d61eb35d | ||
|
|
9e0902e72f | ||
|
|
690fbeb907 | ||
|
|
e95351fd04 | ||
|
|
a095ccd1d6 | ||
|
|
3867f73c8c | ||
|
|
d8f2d868c1 | ||
|
|
4920ee3455 | ||
|
|
3f8092192e | ||
|
|
e025ad3918 | ||
|
|
5ac5b18e6d | ||
|
|
c1007f95b3 | ||
|
|
4d52301ee6 | ||
|
|
a494755449 | ||
|
|
2e530a3e03 | ||
|
|
e76ed31b08 | ||
|
|
f4979e0e8a | ||
|
|
dd7d655a63 | ||
|
|
f9a99f4ad3 | ||
|
|
99e2d795c5 | ||
|
|
7a13565efb | ||
|
|
bb3d78757d | ||
|
|
356a17cdaa | ||
|
|
da436c920f | ||
|
|
69eed95a54 | ||
|
|
df97652f6e | ||
|
|
64372ea6fb | ||
|
|
b3f67bb8c6 | ||
|
|
d29c294f6a | ||
|
|
b5adfcf51a | ||
|
|
1a27258469 | ||
|
|
9e133eb32e | ||
|
|
f4ceeca438 | ||
|
|
aed855284c | ||
|
|
f4e0e04462 | ||
|
|
4069e2fdfb | ||
|
|
ec22512fd9 | ||
|
|
c3107272d3 | ||
|
|
b98526d32c | ||
|
|
4fbb9d4462 | ||
|
|
16472535eb | ||
|
|
f620449bec | ||
|
|
440a7ec9c2 | ||
|
|
40b1d8f067 | ||
|
|
5dd1f9b38a | ||
|
|
dd2af86a41 | ||
|
|
821e299afb | ||
|
|
85bca58905 | ||
|
|
f5fc9e69cf | ||
|
|
167088827a | ||
|
|
a0df7b9d7c | ||
|
|
87cbff5d0e | ||
|
|
13800701ce | ||
|
|
3f82dd05aa | ||
|
|
2147bd8847 | ||
|
|
798ae460d8 | ||
|
|
5e08769366 | ||
|
|
68ba1e1f37 | ||
|
|
b731973c7a | ||
|
|
a07353d3c7 | ||
|
|
86023744d9 | ||
|
|
e91be7aff9 | ||
|
|
5af656d3ba | ||
|
|
4a0bc8937d | ||
|
|
506237e3b4 | ||
|
|
f088f43b40 | ||
|
|
01e2dc17b5 | ||
|
|
337ebdeccb | ||
|
|
9e5e485d0a | ||
|
|
31da42a485 | ||
|
|
94aa1aaff3 | ||
|
|
dbf8ec6a20 | ||
|
|
c8d40e81f0 | ||
|
|
16512d9918 | ||
|
|
8505ffbe78 | ||
|
|
f7b96d839d | ||
|
|
f32232ba96 | ||
|
|
cacb9ef3ad | ||
|
|
00c5ac56d4 | ||
|
|
a7dc6b18aa | ||
|
|
5e23442032 | ||
|
|
4599c80e79 | ||
|
|
29db2078d6 | ||
|
|
67cbd5d77f | ||
|
|
26a77e193e | ||
|
|
55235ce20d | ||
|
|
a5ec564fc3 | ||
|
|
f1bb4233c9 | ||
|
|
afffa2f313 | ||
|
|
221bca0aaa | ||
|
|
de278a77d7 | ||
|
|
56924e6909 | ||
|
|
2c31fd662c | ||
|
|
3b5785884f | ||
|
|
3329ffd071 | ||
|
|
05ce7787d6 | ||
|
|
68a9d1b2b8 | ||
|
|
207daf084e | ||
|
|
dcdd7d7436 | ||
|
|
138de389e2 | ||
|
|
41a4621caf | ||
|
|
516217b6cb | ||
|
|
6cc6ce359b | ||
|
|
848af3755e | ||
|
|
71eba2afba | ||
|
|
1b84aa82eb | ||
|
|
2bc76771bf | ||
|
|
1d518885a9 | ||
|
|
b55994cb71 | ||
|
|
da6f1a3945 | ||
|
|
2b5e02fae8 | ||
|
|
e3cf838bc6 | ||
|
|
a54d8f0e16 | ||
|
|
c337a931c2 | ||
|
|
a909322f60 | ||
|
|
672d115eca | ||
|
|
dd1d3430b9 | ||
|
|
fae875f588 | ||
|
|
ef4555735a | ||
|
|
8b9cc45f41 | ||
|
|
0824db03e7 | ||
|
|
7b1f4aec76 | ||
|
|
827a8309d7 | ||
|
|
366980fd62 | ||
|
|
42cc3e525e | ||
|
|
5be21fd9d8 | ||
|
|
361b294e43 | ||
|
|
dd91b5c731 | ||
|
|
a07a004bb6 | ||
|
|
a86b34e41c | ||
|
|
7bf1a92dc3 | ||
|
|
db1c9b8edf | ||
|
|
79ac20636f | ||
|
|
04483da8df | ||
|
|
d409211908 | ||
|
|
03389d961f | ||
|
|
a021cd3ae2 | ||
|
|
be1969adc8 | ||
|
|
689ca76456 | ||
|
|
034bcd64d5 | ||
|
|
faad07aa3d | ||
|
|
4d415205d1 | ||
|
|
c357483eef | ||
|
|
aa542784ab | ||
|
|
49c37692f3 | ||
|
|
f42df56a88 | ||
|
|
808ce3e7ba | ||
|
|
87cbf6aaaa | ||
|
|
863cf303e3 | ||
|
|
b029a98980 | ||
|
|
219e9d9e2b | ||
|
|
da380e6a0d | ||
|
|
83b9732106 | ||
|
|
016522b151 | ||
|
|
cb1d9b6200 | ||
|
|
e215373ad0 | ||
|
|
f32dfc57ca | ||
|
|
b321c66654 | ||
|
|
a6e23e6b9b | ||
|
|
af85080113 | ||
|
|
460900ddd7 | ||
|
|
884e1bd9a9 | ||
|
|
f6ff9b0419 | ||
|
|
0bcadbd854 | ||
|
|
78f29a7454 | ||
|
|
71de820adf | ||
|
|
dcf0feefb9 | ||
|
|
ad696a9d12 | ||
|
|
793dd38445 | ||
|
|
ffbe95ef02 | ||
|
|
9c442455a2 | ||
|
|
a5452d2c75 | ||
|
|
b45af56199 | ||
|
|
cf0e31c5a2 | ||
|
|
305f2b74e8 | ||
|
|
b859fa1e42 | ||
|
|
f286e092fb | ||
|
|
fab7663ab3 | ||
|
|
61f8ce5c0e | ||
|
|
0f86e218c1 | ||
|
|
7dc40cdac5 | ||
|
|
27abdd9788 | ||
|
|
065b469a10 | ||
|
|
c955415cc3 | ||
|
|
98ac2b15ca | ||
|
|
1ce8f416ca | ||
|
|
29e0a45b5b | ||
|
|
1167b24eeb | ||
|
|
9e735de3c6 | ||
|
|
cb654a82db | ||
|
|
407a978e08 | ||
|
|
ecb5cdc9e3 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -81,6 +81,7 @@ target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
*.ipynb
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
|
||||
@@ -21,6 +21,8 @@ search: False
|
||||
requirements:
|
||||
- requirements.txt
|
||||
- requirements-dev.txt
|
||||
- requirements-plot.txt
|
||||
- requirements-pi.txt
|
||||
|
||||
|
||||
# configure the branch prefix the bot is using
|
||||
|
||||
8
.readthedocs.yml
Normal file
8
.readthedocs.yml
Normal file
@@ -0,0 +1,8 @@
|
||||
# .readthedocs.yml
|
||||
|
||||
build:
|
||||
image: latest
|
||||
|
||||
python:
|
||||
version: 3.6
|
||||
setup_py_install: false
|
||||
23
.travis.yml
23
.travis.yml
@@ -1,7 +1,7 @@
|
||||
sudo: true
|
||||
os:
|
||||
- linux
|
||||
dist: trusty
|
||||
dist: xenial
|
||||
language: python
|
||||
python:
|
||||
- 3.6
|
||||
@@ -17,29 +17,31 @@ addons:
|
||||
- libdw-dev
|
||||
- binutils-dev
|
||||
install:
|
||||
- ./build_helpers/install_ta-lib.sh
|
||||
- cd build_helpers && ./install_ta-lib.sh; cd ..
|
||||
- export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
|
||||
- pip install --upgrade flake8 coveralls pytest-random-order pytest-asyncio mypy
|
||||
- pip install --upgrade pytest-random-order
|
||||
- pip install -r requirements-dev.txt
|
||||
- pip install -e .
|
||||
jobs:
|
||||
|
||||
include:
|
||||
- stage: tests
|
||||
script:
|
||||
- pytest --cov=freqtrade --cov-config=.coveragerc freqtrade/tests/
|
||||
- coveralls
|
||||
# Allow failure for coveralls
|
||||
- coveralls || true
|
||||
name: pytest
|
||||
- script:
|
||||
- cp config.json.example config.json
|
||||
- python freqtrade/main.py --datadir freqtrade/tests/testdata backtesting
|
||||
- python freqtrade --datadir freqtrade/tests/testdata backtesting
|
||||
name: backtest
|
||||
- script:
|
||||
- cp config.json.example config.json
|
||||
- python freqtrade/main.py --datadir freqtrade/tests/testdata hyperopt -e 5
|
||||
- python freqtrade --datadir freqtrade/tests/testdata hyperopt -e 5
|
||||
name: hyperopt
|
||||
- script: flake8 freqtrade
|
||||
- script: flake8 freqtrade scripts
|
||||
name: flake8
|
||||
- script: mypy freqtrade
|
||||
- script: mypy freqtrade scripts
|
||||
name: mypy
|
||||
|
||||
- stage: docker
|
||||
@@ -48,11 +50,10 @@ jobs:
|
||||
- build_helpers/publish_docker.sh
|
||||
name: "Build and test and push docker image"
|
||||
|
||||
|
||||
notifications:
|
||||
slack:
|
||||
secure: bKLXmOrx8e2aPZl7W8DA5BdPAXWGpI5UzST33oc1G/thegXcDVmHBTJrBs4sZak6bgAclQQrdZIsRd2eFYzHLalJEaw6pk7hoAw8SvLnZO0ZurWboz7qg2+aZZXfK4eKl/VUe4sM9M4e/qxjkK+yWG7Marg69c4v1ypF7ezUi1fPYILYw8u0paaiX0N5UX8XNlXy+PBlga2MxDjUY70MuajSZhPsY2pDUvYnMY1D/7XN3cFW0g+3O8zXjF0IF4q1Z/1ASQe+eYjKwPQacE+O8KDD+ZJYoTOFBAPllrtpO1jnOPFjNGf3JIbVMZw4bFjIL0mSQaiSUaUErbU3sFZ5Or79rF93XZ81V7uEZ55vD8KMfR2CB1cQJcZcj0v50BxLo0InkFqa0Y8Nra3sbpV4fV5Oe8pDmomPJrNFJnX6ULQhQ1gTCe0M5beKgVms5SITEpt4/Y0CmLUr6iHDT0CUiyMIRWAXdIgbGh1jfaWOMksybeRevlgDsIsNBjXmYI1Sw2ZZR2Eo2u4R6zyfyjOMLwYJ3vgq9IrACv2w5nmf0+oguMWHf6iWi2hiOqhlAN1W74+3HsYQcqnuM3LGOmuCnPprV1oGBqkPXjIFGpy21gNx4vHfO1noLUyJnMnlu2L7SSuN1CdLsnjJ1hVjpJjPfqB4nn8g12x87TqM1bOm+3Q=
|
||||
cache:
|
||||
pip: True
|
||||
directories:
|
||||
- $HOME/.cache/pip
|
||||
- ta-lib
|
||||
- /usr/local/lib
|
||||
|
||||
@@ -14,6 +14,10 @@ Few pointers for contributions:
|
||||
If you are unsure, discuss the feature on our [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE)
|
||||
or in a [issue](https://github.com/freqtrade/freqtrade/issues) before a PR.
|
||||
|
||||
## Getting started
|
||||
|
||||
Best start by reading the [documentation](https://www.freqtrade.io/) to get a feel for what is possible with the bot, or head straight to the [Developer-documentation](https://www.freqtrade.io/en/latest/developer/) (WIP) which should help you getting started.
|
||||
|
||||
## Before sending the PR:
|
||||
|
||||
### 1. Run unit tests
|
||||
@@ -41,12 +45,6 @@ pytest freqtrade/tests/test_<file_name>.py::test_<method_name>
|
||||
|
||||
### 2. Test if your code is PEP8 compliant
|
||||
|
||||
#### Install packages
|
||||
|
||||
```bash
|
||||
pip3.6 install flake8 coveralls
|
||||
```
|
||||
|
||||
#### Run Flake8
|
||||
|
||||
```bash
|
||||
@@ -60,22 +58,12 @@ Guide for installing them is [here](http://flake8.pycqa.org/en/latest/user/using
|
||||
|
||||
### 3. Test if all type-hints are correct
|
||||
|
||||
#### Install packages
|
||||
|
||||
``` bash
|
||||
pip3.6 install mypy
|
||||
```
|
||||
|
||||
#### Run mypy
|
||||
|
||||
``` bash
|
||||
mypy freqtrade
|
||||
```
|
||||
|
||||
## Getting started
|
||||
|
||||
Best start by reading the [documentation](https://github.com/freqtrade/freqtrade/blob/develop/docs/index.md) to get a feel for what is possible with the bot, or head straight to the [Developer-documentation](https://github.com/freqtrade/freqtrade/blob/develop/docs/developer.md) (WIP) which should help you getting started.
|
||||
|
||||
## (Core)-Committer Guide
|
||||
|
||||
### Process: Pull Requests
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
FROM python:3.7.0-slim-stretch
|
||||
FROM python:3.7.3-slim-stretch
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get -y install curl build-essential \
|
||||
&& apt-get -y install curl build-essential libssl-dev \
|
||||
&& apt-get clean \
|
||||
&& pip install --upgrade pip
|
||||
|
||||
|
||||
40
Dockerfile.pi
Normal file
40
Dockerfile.pi
Normal file
@@ -0,0 +1,40 @@
|
||||
FROM balenalib/raspberrypi3-debian:stretch
|
||||
|
||||
RUN [ "cross-build-start" ]
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get -y install wget curl build-essential libssl-dev libffi-dev \
|
||||
&& apt-get clean
|
||||
|
||||
# Prepare environment
|
||||
RUN mkdir /freqtrade
|
||||
WORKDIR /freqtrade
|
||||
|
||||
# Install TA-lib
|
||||
COPY build_helpers/ta-lib-0.4.0-src.tar.gz /freqtrade/
|
||||
RUN tar -xzf /freqtrade/ta-lib-0.4.0-src.tar.gz \
|
||||
&& cd /freqtrade/ta-lib/ \
|
||||
&& ./configure \
|
||||
&& make \
|
||||
&& make install \
|
||||
&& rm /freqtrade/ta-lib-0.4.0-src.tar.gz
|
||||
|
||||
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||
|
||||
# Install berryconda
|
||||
RUN wget https://github.com/jjhelmus/berryconda/releases/download/v2.0.0/Berryconda3-2.0.0-Linux-armv7l.sh \
|
||||
&& bash ./Berryconda3-2.0.0-Linux-armv7l.sh -b \
|
||||
&& rm Berryconda3-2.0.0-Linux-armv7l.sh
|
||||
|
||||
# Install dependencies
|
||||
COPY requirements-pi.txt /freqtrade/
|
||||
RUN ~/berryconda3/bin/conda install -y numpy pandas scipy \
|
||||
&& ~/berryconda3/bin/pip install -r requirements-pi.txt --no-cache-dir
|
||||
|
||||
# Install and execute
|
||||
COPY . /freqtrade/
|
||||
RUN ~/berryconda3/bin/pip install -e . --no-cache-dir
|
||||
|
||||
RUN [ "cross-build-end" ]
|
||||
|
||||
ENTRYPOINT ["/root/berryconda3/bin/python","./freqtrade/main.py"]
|
||||
139
README.md
139
README.md
@@ -1,24 +1,25 @@
|
||||
# freqtrade
|
||||
# Freqtrade
|
||||
|
||||
[](https://travis-ci.org/freqtrade/freqtrade)
|
||||
[](https://coveralls.io/github/freqtrade/freqtrade?branch=develop)
|
||||
[](https://www.freqtrade.io)
|
||||
[](https://codeclimate.com/github/freqtrade/freqtrade/maintainability)
|
||||
|
||||
Simple High frequency trading bot for crypto currencies designed to support multi exchanges and be controlled via Telegram.
|
||||
Freqtrade is a free and open source crypto trading bot written in Python. It is designed to support all major exchanges and be controlled via Telegram. It contains backtesting, plotting and money management tools as well as strategy optimization by machine learning.
|
||||
|
||||

|
||||
|
||||
## Disclaimer
|
||||
|
||||
This software is for educational purposes only. Do not risk money which
|
||||
you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS
|
||||
AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.
|
||||
This software is for educational purposes only. Do not risk money which
|
||||
you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS
|
||||
AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.
|
||||
|
||||
Always start by running a trading bot in Dry-run and do not engage money
|
||||
before you understand how it works and what profit/loss you should
|
||||
expect.
|
||||
|
||||
We strongly recommend you to have coding and Python knowledge. Do not
|
||||
We strongly recommend you to have coding and Python knowledge. Do not
|
||||
hesitate to read the source code and understand the mechanism of this bot.
|
||||
|
||||
## Exchange marketplaces supported
|
||||
@@ -27,48 +28,27 @@ hesitate to read the source code and understand the mechanism of this bot.
|
||||
- [X] [Binance](https://www.binance.com/) ([*Note for binance users](#a-note-on-binance))
|
||||
- [ ] [113 others to tests](https://github.com/ccxt/ccxt/). _(We cannot guarantee they will work)_
|
||||
|
||||
## Documentation
|
||||
|
||||
We invite you to read the bot documentation to ensure you understand how the bot is working.
|
||||
|
||||
Please find the complete documentation on our [website](https://www.freqtrade.io).
|
||||
|
||||
## Features
|
||||
|
||||
- [x] **Based on Python 3.6+**: For botting on any operating system - Windows, macOS and Linux
|
||||
- [x] **Persistence**: Persistence is achieved through sqlite
|
||||
- [x] **Based on Python 3.6+**: For botting on any operating system - Windows, macOS and Linux.
|
||||
- [x] **Persistence**: Persistence is achieved through sqlite.
|
||||
- [x] **Dry-run**: Run the bot without playing money.
|
||||
- [x] **Backtesting**: Run a simulation of your buy/sell strategy.
|
||||
- [x] **Strategy Optimization by machine learning**: Use machine learning to optimize your buy/sell strategy parameters with real exchange data.
|
||||
- [x] **Edge position sizing** Calculate your win rate, risk reward ratio, the best stoploss and adjust your position size before taking a position for each specific market. [Learn more](https://github.com/freqtrade/freqtrade/blob/develop/docs/edge.md)
|
||||
- [x] **Edge position sizing** Calculate your win rate, risk reward ratio, the best stoploss and adjust your position size before taking a position for each specific market. [Learn more](https://www.freqtrade.io/en/latest/edge/).
|
||||
- [x] **Whitelist crypto-currencies**: Select which crypto-currency you want to trade or use dynamic whitelists.
|
||||
- [x] **Blacklist crypto-currencies**: Select which crypto-currency you want to avoid.
|
||||
- [x] **Manageable via Telegram**: Manage the bot with Telegram
|
||||
- [x] **Manageable via Telegram**: Manage the bot with Telegram.
|
||||
- [x] **Display profit/loss in fiat**: Display your profit/loss in 33 fiat.
|
||||
- [x] **Daily summary of profit/loss**: Provide a daily summary of your profit/loss.
|
||||
- [x] **Performance status report**: Provide a performance status of your current trades.
|
||||
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Quick start](#quick-start)
|
||||
- [Documentations](https://github.com/freqtrade/freqtrade/blob/develop/docs/index.md)
|
||||
- [Installation](https://github.com/freqtrade/freqtrade/blob/develop/docs/installation.md)
|
||||
- [Configuration](https://github.com/freqtrade/freqtrade/blob/develop/docs/configuration.md)
|
||||
- [Strategy Optimization](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-optimization.md)
|
||||
- [Backtesting](https://github.com/freqtrade/freqtrade/blob/develop/docs/backtesting.md)
|
||||
- [Hyperopt](https://github.com/freqtrade/freqtrade/blob/develop/docs/hyperopt.md)
|
||||
- [Sandbox Testing](https://github.com/freqtrade/freqtrade/blob/develop/docs/sandbox-testing.md)
|
||||
- [Edge](https://github.com/freqtrade/freqtrade/blob/develop/docs/edge.md)
|
||||
- [Basic Usage](#basic-usage)
|
||||
- [Bot commands](#bot-commands)
|
||||
- [Telegram RPC commands](#telegram-rpc-commands)
|
||||
- [Support](#support)
|
||||
- [Help](#help--slack)
|
||||
- [Bugs](#bugs--issues)
|
||||
- [Feature Requests](#feature-requests)
|
||||
- [Pull Requests](#pull-requests)
|
||||
- [Requirements](#requirements)
|
||||
- [Min hardware required](#min-hardware-required)
|
||||
- [Software requirements](#software-requirements)
|
||||
- [Wanna help?](https://github.com/freqtrade/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||
- [Dev - getting started](https://github.com/freqtrade/freqtrade/blob/develop/docs/developer.md) (WIP)
|
||||
|
||||
|
||||
## Quick start
|
||||
|
||||
Freqtrade provides a Linux/macOS script to install all dependencies and help you to configure the bot.
|
||||
@@ -80,63 +60,53 @@ git checkout develop
|
||||
./setup.sh --install
|
||||
```
|
||||
|
||||
_Windows installation is explained in [Installation doc](https://github.com/freqtrade/freqtrade/blob/develop/docs/installation.md)_
|
||||
For any other type of installation please refer to [Installation doc](https://www.freqtrade.io/en/latest/installation/).
|
||||
|
||||
## Documentation
|
||||
|
||||
We invite you to read the bot documentation to ensure you understand how the bot is working.
|
||||
|
||||
- [Index](https://github.com/freqtrade/freqtrade/blob/develop/docs/index.md)
|
||||
- [Installation](https://github.com/freqtrade/freqtrade/blob/develop/docs/installation.md)
|
||||
- [Configuration](https://github.com/freqtrade/freqtrade/blob/develop/docs/configuration.md)
|
||||
- [Bot usage](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-usage.md)
|
||||
- [How to run the bot](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-usage.md#bot-commands)
|
||||
- [How to use Backtesting](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-usage.md#backtesting-commands)
|
||||
- [How to use Hyperopt](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-usage.md#hyperopt-commands)
|
||||
- [Strategy Optimization](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-optimization.md)
|
||||
- [Backtesting](https://github.com/freqtrade/freqtrade/blob/develop/docs/backtesting.md)
|
||||
- [Hyperopt](https://github.com/freqtrade/freqtrade/blob/develop/docs/hyperopt.md)
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Bot commands
|
||||
|
||||
```bash
|
||||
usage: main.py [-h] [-v] [--version] [-c PATH] [-d PATH] [-s NAME]
|
||||
[--strategy-path PATH] [--dynamic-whitelist [INT]]
|
||||
[--dry-run-db]
|
||||
{backtesting,hyperopt} ...
|
||||
```
|
||||
usage: freqtrade [-h] [-v] [--logfile FILE] [--version] [-c PATH] [-d PATH]
|
||||
[-s NAME] [--strategy-path PATH] [--dynamic-whitelist [INT]]
|
||||
[--db-url PATH] [--sd-notify]
|
||||
{backtesting,edge,hyperopt} ...
|
||||
|
||||
Simple High Frequency Trading Bot for crypto currencies
|
||||
Free, open source crypto trading bot
|
||||
|
||||
positional arguments:
|
||||
{backtesting,hyperopt}
|
||||
backtesting backtesting module
|
||||
hyperopt hyperopt module
|
||||
{backtesting,edge,hyperopt}
|
||||
backtesting Backtesting module.
|
||||
edge Edge module.
|
||||
hyperopt Hyperopt module.
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-v, --verbose be verbose
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified
|
||||
--version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
specify configuration file (default: config.json)
|
||||
Specify configuration file (default: None). Multiple
|
||||
--config options may be used.
|
||||
-d PATH, --datadir PATH
|
||||
path to backtest data (default:
|
||||
freqtrade/tests/testdata
|
||||
Path to backtest data.
|
||||
-s NAME, --strategy NAME
|
||||
specify strategy class name (default: DefaultStrategy)
|
||||
--strategy-path PATH specify additional strategy lookup path
|
||||
Specify strategy class name (default:
|
||||
DefaultStrategy).
|
||||
--strategy-path PATH Specify additional strategy lookup path.
|
||||
--dynamic-whitelist [INT]
|
||||
dynamically generate and update whitelist based on 24h
|
||||
BaseVolume (Default 20 currencies)
|
||||
--dry-run-db Force dry run to use a local DB
|
||||
"tradesv3.dry_run.sqlite" instead of memory DB. Work
|
||||
only if dry_run is enabled.
|
||||
Dynamically generate and update whitelist based on 24h
|
||||
BaseVolume (default: 20). DEPRECATED.
|
||||
--db-url PATH Override trades database URL, this is useful if
|
||||
dry_run is enabled or in custom deployments (default:
|
||||
None).
|
||||
--sd-notify Notify systemd service manager.
|
||||
```
|
||||
|
||||
### Telegram RPC commands
|
||||
|
||||
Telegram is not mandatory. However, this is a great way to control your bot. More details on our [documentation](https://github.com/freqtrade/freqtrade/blob/develop/docs/index.md)
|
||||
Telegram is not mandatory. However, this is a great way to control your bot. More details on our [documentation](https://www.freqtrade.io/en/latest/telegram-usage/)
|
||||
|
||||
- `/start`: Starts the trader
|
||||
- `/stop`: Stops the trader
|
||||
@@ -176,29 +146,29 @@ information about the bot, we encourage you to join our slack channel.
|
||||
|
||||
### [Bugs / Issues](https://github.com/freqtrade/freqtrade/issues?q=is%3Aissue)
|
||||
|
||||
If you discover a bug in the bot, please
|
||||
[search our issue tracker](https://github.com/freqtrade/freqtrade/issues?q=is%3Aissue)
|
||||
first. If it hasn't been reported, please
|
||||
[create a new issue](https://github.com/freqtrade/freqtrade/issues/new) and
|
||||
ensure you follow the template guide so that our team can assist you as
|
||||
If you discover a bug in the bot, please
|
||||
[search our issue tracker](https://github.com/freqtrade/freqtrade/issues?q=is%3Aissue)
|
||||
first. If it hasn't been reported, please
|
||||
[create a new issue](https://github.com/freqtrade/freqtrade/issues/new) and
|
||||
ensure you follow the template guide so that our team can assist you as
|
||||
quickly as possible.
|
||||
|
||||
### [Feature Requests](https://github.com/freqtrade/freqtrade/labels/enhancement)
|
||||
|
||||
Have you a great idea to improve the bot you want to share? Please,
|
||||
first search if this feature was not [already discussed](https://github.com/freqtrade/freqtrade/labels/enhancement).
|
||||
If it hasn't been requested, please
|
||||
[create a new request](https://github.com/freqtrade/freqtrade/issues/new)
|
||||
and ensure you follow the template guide so that it does not get lost
|
||||
If it hasn't been requested, please
|
||||
[create a new request](https://github.com/freqtrade/freqtrade/issues/new)
|
||||
and ensure you follow the template guide so that it does not get lost
|
||||
in the bug reports.
|
||||
|
||||
### [Pull Requests](https://github.com/freqtrade/freqtrade/pulls)
|
||||
|
||||
Feel like our bot is missing a feature? We welcome your pull requests!
|
||||
|
||||
Please read our
|
||||
Please read our
|
||||
[Contributing document](https://github.com/freqtrade/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||
to understand the requirements before sending your pull-requests.
|
||||
to understand the requirements before sending your pull-requests.
|
||||
|
||||
Coding is not a neccessity to contribute - maybe start with improving our documentation?
|
||||
Issues labeled [good first issue](https://github.com/freqtrade/freqtrade/labels/good%20first%20issue) can be good first contributions, and will help get you familiar with the codebase.
|
||||
@@ -221,10 +191,9 @@ To run this bot we recommend you a cloud instance with a minimum of:
|
||||
|
||||
### Software requirements
|
||||
|
||||
- [Python 3.6.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
||||
- [Python 3.6.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
||||
- [pip](https://pip.pypa.io/en/stable/installing/)
|
||||
- [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
- [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html)
|
||||
- [virtualenv](https://virtualenv.pypa.io/en/stable/installation/) (Recommended)
|
||||
- [Docker](https://www.docker.com/products/docker) (Recommended)
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
if [ ! -f "ta-lib/CHANGELOG.TXT" ]; then
|
||||
if [ ! -f "/usr/local/lib/libta_lib.a" ]; then
|
||||
tar zxvf ta-lib-0.4.0-src.tar.gz
|
||||
cd ta-lib \
|
||||
&& sed -i.bak "s|0.00000001|0.000000000000000001 |g" src/ta_func/ta_utility.h \
|
||||
@@ -7,7 +7,5 @@ if [ ! -f "ta-lib/CHANGELOG.TXT" ]; then
|
||||
&& which sudo && sudo make install || make install \
|
||||
&& cd ..
|
||||
else
|
||||
echo "TA-lib already installed, skipping download and build."
|
||||
cd ta-lib && sudo make install && cd ..
|
||||
|
||||
echo "TA-lib already installed, skipping installation"
|
||||
fi
|
||||
|
||||
@@ -13,7 +13,7 @@ if [ "${TRAVIS_EVENT_TYPE}" = "cron" ]; then
|
||||
else
|
||||
echo "event ${TRAVIS_EVENT_TYPE}: building with cache"
|
||||
# Pull last build to avoid rebuilding the whole image
|
||||
docker pull ${REPO}:${TAG}
|
||||
docker pull ${IMAGE_NAME}:${TAG}
|
||||
docker build --cache-from ${IMAGE_NAME}:${TAG} -t freqtrade:${TAG} .
|
||||
fi
|
||||
|
||||
|
||||
@@ -30,7 +30,8 @@
|
||||
"secret": "your_exchange_secret",
|
||||
"ccxt_config": {"enableRateLimit": true},
|
||||
"ccxt_async_config": {
|
||||
"enableRateLimit": false
|
||||
"enableRateLimit": true,
|
||||
"rateLimit": 500
|
||||
},
|
||||
"pair_whitelist": [
|
||||
"ETH/BTC",
|
||||
|
||||
@@ -30,7 +30,8 @@
|
||||
"secret": "your_exchange_secret",
|
||||
"ccxt_config": {"enableRateLimit": true},
|
||||
"ccxt_async_config": {
|
||||
"enableRateLimit": false
|
||||
"enableRateLimit": true,
|
||||
"rateLimit": 200
|
||||
},
|
||||
"pair_whitelist": [
|
||||
"AST/BTC",
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
"stake_currency": "BTC",
|
||||
"stake_amount": 0.05,
|
||||
"fiat_display_currency": "USD",
|
||||
"amount_reserve_percent" : 0.05,
|
||||
"dry_run": false,
|
||||
"ticker_interval": "5m",
|
||||
"trailing_stop": false,
|
||||
"trailing_stop_positive": 0.005,
|
||||
"trailing_stop_positive_offset": 0.0051,
|
||||
"trailing_only_offset_is_reached": false,
|
||||
"minimal_roi": {
|
||||
"40": 0.0,
|
||||
"30": 0.01,
|
||||
@@ -37,17 +39,19 @@
|
||||
"buy": "limit",
|
||||
"sell": "limit",
|
||||
"stoploss": "market",
|
||||
"stoploss_on_exchange": "false"
|
||||
"stoploss_on_exchange": false,
|
||||
"stoploss_on_exchange_interval": 60
|
||||
},
|
||||
"order_time_in_force": {
|
||||
"buy": "gtc",
|
||||
"sell": "gtc",
|
||||
"sell": "gtc"
|
||||
},
|
||||
"pairlist": {
|
||||
"method": "VolumePairList",
|
||||
"config": {
|
||||
"number_assets": 20,
|
||||
"sort_key": "quoteVolume"
|
||||
"sort_key": "quoteVolume",
|
||||
"precision_filter": false
|
||||
}
|
||||
},
|
||||
"exchange": {
|
||||
@@ -57,6 +61,7 @@
|
||||
"ccxt_config": {"enableRateLimit": true},
|
||||
"ccxt_async_config": {
|
||||
"enableRateLimit": false,
|
||||
"rateLimit": 500,
|
||||
"aiohttp_trust_env": false
|
||||
},
|
||||
"pair_whitelist": [
|
||||
@@ -74,7 +79,8 @@
|
||||
"pair_blacklist": [
|
||||
"DOGE/BTC"
|
||||
],
|
||||
"outdated_offset": 5
|
||||
"outdated_offset": 5,
|
||||
"markets_refresh_interval": 60
|
||||
},
|
||||
"edge": {
|
||||
"enabled": false,
|
||||
|
||||
71
config_kraken.json.example
Normal file
71
config_kraken.json.example
Normal file
@@ -0,0 +1,71 @@
|
||||
{
|
||||
"max_open_trades": 5,
|
||||
"stake_currency": "EUR",
|
||||
"stake_amount": 10,
|
||||
"fiat_display_currency": "EUR",
|
||||
"ticker_interval" : "5m",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.dryrun.sqlite",
|
||||
"trailing_stop": false,
|
||||
"unfilledtimeout": {
|
||||
"buy": 10,
|
||||
"sell": 30
|
||||
},
|
||||
"bid_strategy": {
|
||||
"ask_last_balance": 0.0,
|
||||
"use_order_book": false,
|
||||
"order_book_top": 1,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"ask_strategy":{
|
||||
"use_order_book": false,
|
||||
"order_book_min": 1,
|
||||
"order_book_max": 9
|
||||
},
|
||||
"exchange": {
|
||||
"name": "kraken",
|
||||
"key": "",
|
||||
"secret": "",
|
||||
"ccxt_config": {"enableRateLimit": true},
|
||||
"ccxt_async_config": {
|
||||
"enableRateLimit": true,
|
||||
"rateLimit": 1000
|
||||
},
|
||||
"pair_whitelist": [
|
||||
"ETH/EUR",
|
||||
"BTC/EUR",
|
||||
"BCH/EUR"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
|
||||
]
|
||||
},
|
||||
"edge": {
|
||||
"enabled": false,
|
||||
"process_throttle_secs": 3600,
|
||||
"calculate_since_number_of_days": 7,
|
||||
"capital_available_percentage": 0.5,
|
||||
"allowed_risk": 0.01,
|
||||
"stoploss_range_min": -0.01,
|
||||
"stoploss_range_max": -0.1,
|
||||
"stoploss_range_step": -0.01,
|
||||
"minimum_winrate": 0.60,
|
||||
"minimum_expectancy": 0.20,
|
||||
"min_trade_number": 10,
|
||||
"max_trade_duration_minute": 1440,
|
||||
"remove_pumps": false
|
||||
},
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "",
|
||||
"chat_id": ""
|
||||
},
|
||||
"initial_state": "running",
|
||||
"forcebuy_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 5
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,19 @@
|
||||
# Backtesting
|
||||
|
||||
This page explains how to validate your strategy performance by using
|
||||
This page explains how to validate your strategy performance by using
|
||||
Backtesting.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Test your strategy with Backtesting](#test-your-strategy-with-backtesting)
|
||||
- [Understand the backtesting result](#understand-the-backtesting-result)
|
||||
|
||||
## Test your strategy with Backtesting
|
||||
|
||||
Now you have good Buy and Sell strategies, you want to test it against
|
||||
real data. This is what we call
|
||||
real data. This is what we call
|
||||
[backtesting](https://en.wikipedia.org/wiki/Backtesting).
|
||||
|
||||
Backtesting will use the crypto-currencies (pair) from your config file
|
||||
and load static tickers located in
|
||||
[/freqtrade/tests/testdata](https://github.com/freqtrade/freqtrade/tree/develop/freqtrade/tests/testdata).
|
||||
If the 5 min and 1 min ticker for the crypto-currencies to test is not
|
||||
already in the `testdata` folder, backtesting will download them
|
||||
and load static tickers located in
|
||||
[/freqtrade/tests/testdata](https://github.com/freqtrade/freqtrade/tree/develop/freqtrade/tests/testdata).
|
||||
If the 5 min and 1 min ticker for the crypto-currencies to test is not
|
||||
already in the `testdata` folder, backtesting will download them
|
||||
automatically. Testdata files will not be updated until you specify it.
|
||||
|
||||
The result of backtesting will confirm you if your bot has better odds of making a profit than a loss.
|
||||
@@ -29,37 +24,37 @@ The backtesting is very easy with freqtrade.
|
||||
#### With 5 min tickers (Per default)
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting
|
||||
python3 freqtrade backtesting
|
||||
```
|
||||
|
||||
#### With 1 min tickers
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --ticker-interval 1m
|
||||
python3 freqtrade backtesting --ticker-interval 1m
|
||||
```
|
||||
|
||||
#### Update cached pairs with the latest data
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --refresh-pairs-cached
|
||||
python3 freqtrade backtesting --refresh-pairs-cached
|
||||
```
|
||||
|
||||
#### With live data (do not alter your testdata files)
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --live
|
||||
python3 freqtrade backtesting --live
|
||||
```
|
||||
|
||||
#### Using a different on-disk ticker-data source
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --datadir freqtrade/tests/testdata-20180101
|
||||
python3 freqtrade backtesting --datadir freqtrade/tests/testdata-20180101
|
||||
```
|
||||
|
||||
#### With a (custom) strategy file
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py -s TestStrategy backtesting
|
||||
python3 freqtrade -s TestStrategy backtesting
|
||||
```
|
||||
|
||||
Where `-s TestStrategy` refers to the class name within the strategy file `test_strategy.py` found in the `freqtrade/user_data/strategies` directory
|
||||
@@ -67,43 +62,15 @@ Where `-s TestStrategy` refers to the class name within the strategy file `test_
|
||||
#### Exporting trades to file
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --export trades
|
||||
python3 freqtrade backtesting --export trades
|
||||
```
|
||||
|
||||
The exported trades can be read using the following code for manual analysis, or can be used by the plotting script `plot_dataframe.py` in the scripts folder.
|
||||
|
||||
``` python
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pandas as pd
|
||||
|
||||
filename=Path('user_data/backtest_data/backtest-result.json')
|
||||
|
||||
with filename.open() as file:
|
||||
data = json.load(file)
|
||||
|
||||
columns = ["pair", "profit", "opents", "closets", "index", "duration",
|
||||
"open_rate", "close_rate", "open_at_end", "sell_reason"]
|
||||
df = pd.DataFrame(data, columns=columns)
|
||||
|
||||
df['opents'] = pd.to_datetime(df['opents'],
|
||||
unit='s',
|
||||
utc=True,
|
||||
infer_datetime_format=True
|
||||
)
|
||||
df['closets'] = pd.to_datetime(df['closets'],
|
||||
unit='s',
|
||||
utc=True,
|
||||
infer_datetime_format=True
|
||||
)
|
||||
```
|
||||
|
||||
If you have some ideas for interesting / helpful backtest data analysis, feel free to submit a PR so the community can benefit from it.
|
||||
The exported trades can be used for [further analysis](#further-backtest-result-analysis), or can be used by the plotting script `plot_dataframe.py` in the scripts folder.
|
||||
|
||||
#### Exporting trades to file specifying a custom filename
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --export trades --export-filename=backtest_teststrategy.json
|
||||
python3 freqtrade backtesting --export trades --export-filename=backtest_teststrategy.json
|
||||
```
|
||||
|
||||
#### Running backtest with smaller testset
|
||||
@@ -114,7 +81,7 @@ you want to use. The last N ticks/timeframes will be used.
|
||||
Example:
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py backtesting --timerange=-200
|
||||
python3 freqtrade backtesting --timerange=-200
|
||||
```
|
||||
|
||||
#### Advanced use of timerange
|
||||
@@ -171,60 +138,72 @@ The most important in the backtesting is to understand the result.
|
||||
A backtesting result will look like that:
|
||||
|
||||
```
|
||||
======================================== BACKTESTING REPORT =========================================
|
||||
| pair | buy count | avg profit % | total profit BTC | avg duration | profit | loss |
|
||||
|:---------|------------:|---------------:|-------------------:|---------------:|---------:|-------:|
|
||||
| ETH/BTC | 44 | 0.18 | 0.00159118 | 50.9 | 44 | 0 |
|
||||
| LTC/BTC | 27 | 0.10 | 0.00051931 | 103.1 | 26 | 1 |
|
||||
| ETC/BTC | 24 | 0.05 | 0.00022434 | 166.0 | 22 | 2 |
|
||||
| DASH/BTC | 29 | 0.18 | 0.00103223 | 192.2 | 29 | 0 |
|
||||
| ZEC/BTC | 65 | -0.02 | -0.00020621 | 202.7 | 62 | 3 |
|
||||
| XLM/BTC | 35 | 0.02 | 0.00012877 | 242.4 | 32 | 3 |
|
||||
| BCH/BTC | 12 | 0.62 | 0.00149284 | 50.0 | 12 | 0 |
|
||||
| POWR/BTC | 21 | 0.26 | 0.00108215 | 134.8 | 21 | 0 |
|
||||
| ADA/BTC | 54 | -0.19 | -0.00205202 | 191.3 | 47 | 7 |
|
||||
| XMR/BTC | 24 | -0.43 | -0.00206013 | 120.6 | 20 | 4 |
|
||||
| TOTAL | 335 | 0.03 | 0.00175246 | 157.9 | 315 | 20 |
|
||||
2018-06-13 06:57:27,347 - freqtrade.optimize.backtesting - INFO -
|
||||
====================================== LEFT OPEN TRADES REPORT ======================================
|
||||
| pair | buy count | avg profit % | total profit BTC | avg duration | profit | loss |
|
||||
|:---------|------------:|---------------:|-------------------:|---------------:|---------:|-------:|
|
||||
| ETH/BTC | 3 | 0.16 | 0.00009619 | 25.0 | 3 | 0 |
|
||||
| LTC/BTC | 1 | -1.00 | -0.00020118 | 1085.0 | 0 | 1 |
|
||||
| ETC/BTC | 2 | -1.80 | -0.00071933 | 1092.5 | 0 | 2 |
|
||||
| DASH/BTC | 0 | nan | 0.00000000 | nan | 0 | 0 |
|
||||
| ZEC/BTC | 3 | -4.27 | -0.00256826 | 1301.7 | 0 | 3 |
|
||||
| XLM/BTC | 3 | -1.11 | -0.00066744 | 965.0 | 0 | 3 |
|
||||
| BCH/BTC | 0 | nan | 0.00000000 | nan | 0 | 0 |
|
||||
| POWR/BTC | 0 | nan | 0.00000000 | nan | 0 | 0 |
|
||||
| ADA/BTC | 7 | -3.58 | -0.00503604 | 850.0 | 0 | 7 |
|
||||
| XMR/BTC | 4 | -3.79 | -0.00303456 | 291.2 | 0 | 4 |
|
||||
| TOTAL | 23 | -2.63 | -0.01213062 | 750.4 | 3 | 20 |
|
||||
|
||||
========================================================= BACKTESTING REPORT ========================================================
|
||||
| pair | buy count | avg profit % | cum profit % | tot profit BTC | tot profit % | avg duration | profit | loss |
|
||||
|:---------|------------:|---------------:|---------------:|-----------------:|---------------:|:---------------|---------:|-------:|
|
||||
| ADA/BTC | 35 | -0.11 | -3.88 | -0.00019428 | -1.94 | 4:35:00 | 14 | 21 |
|
||||
| ARK/BTC | 11 | -0.41 | -4.52 | -0.00022647 | -2.26 | 2:03:00 | 3 | 8 |
|
||||
| BTS/BTC | 32 | 0.31 | 9.78 | 0.00048938 | 4.89 | 5:05:00 | 18 | 14 |
|
||||
| DASH/BTC | 13 | -0.08 | -1.07 | -0.00005343 | -0.53 | 4:39:00 | 6 | 7 |
|
||||
| ENG/BTC | 18 | 1.36 | 24.54 | 0.00122807 | 12.27 | 2:50:00 | 8 | 10 |
|
||||
| EOS/BTC | 36 | 0.08 | 3.06 | 0.00015304 | 1.53 | 3:34:00 | 16 | 20 |
|
||||
| ETC/BTC | 26 | 0.37 | 9.51 | 0.00047576 | 4.75 | 6:14:00 | 11 | 15 |
|
||||
| ETH/BTC | 33 | 0.30 | 9.96 | 0.00049856 | 4.98 | 7:31:00 | 16 | 17 |
|
||||
| IOTA/BTC | 32 | 0.03 | 1.09 | 0.00005444 | 0.54 | 3:12:00 | 14 | 18 |
|
||||
| LSK/BTC | 15 | 1.75 | 26.26 | 0.00131413 | 13.13 | 2:58:00 | 6 | 9 |
|
||||
| LTC/BTC | 32 | -0.04 | -1.38 | -0.00006886 | -0.69 | 4:49:00 | 11 | 21 |
|
||||
| NANO/BTC | 17 | 1.26 | 21.39 | 0.00107058 | 10.70 | 1:55:00 | 10 | 7 |
|
||||
| NEO/BTC | 23 | 0.82 | 18.97 | 0.00094936 | 9.48 | 2:59:00 | 10 | 13 |
|
||||
| REQ/BTC | 9 | 1.17 | 10.54 | 0.00052734 | 5.27 | 3:47:00 | 4 | 5 |
|
||||
| XLM/BTC | 16 | 1.22 | 19.54 | 0.00097800 | 9.77 | 3:15:00 | 7 | 9 |
|
||||
| XMR/BTC | 23 | -0.18 | -4.13 | -0.00020696 | -2.07 | 5:30:00 | 12 | 11 |
|
||||
| XRP/BTC | 35 | 0.66 | 22.96 | 0.00114897 | 11.48 | 3:49:00 | 12 | 23 |
|
||||
| ZEC/BTC | 22 | -0.46 | -10.18 | -0.00050971 | -5.09 | 2:22:00 | 7 | 15 |
|
||||
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 243 |
|
||||
========================================================= SELL REASON STATS =========================================================
|
||||
| Sell Reason | Count |
|
||||
|:-------------------|--------:|
|
||||
| trailing_stop_loss | 205 |
|
||||
| stop_loss | 166 |
|
||||
| sell_signal | 56 |
|
||||
| force_sell | 2 |
|
||||
====================================================== LEFT OPEN TRADES REPORT ======================================================
|
||||
| pair | buy count | avg profit % | cum profit % | tot profit BTC | tot profit % | avg duration | profit | loss |
|
||||
|:---------|------------:|---------------:|---------------:|-----------------:|---------------:|:---------------|---------:|-------:|
|
||||
| ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 | 0 |
|
||||
| LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 | 0 |
|
||||
| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 | 0 |
|
||||
```
|
||||
|
||||
The 1st table will contain all trades the bot made.
|
||||
|
||||
The 2nd table will contain all trades the bot had to `forcesell` at the end of the backtest period to prsent a full picture.
|
||||
The 2nd table will contain a recap of sell reasons.
|
||||
|
||||
The 3rd table will contain all trades the bot had to `forcesell` at the end of the backtest period to present a full picture.
|
||||
These trades are also included in the first table, but are extracted separately for clarity.
|
||||
|
||||
The last line will give you the overall performance of your strategy,
|
||||
here:
|
||||
|
||||
```
|
||||
TOTAL 419 -0.41 -0.00348593 52.9
|
||||
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 243 |
|
||||
```
|
||||
|
||||
We understand the bot has made `419` trades for an average duration of
|
||||
`52.9` min, with a performance of `-0.41%` (loss), that means it has
|
||||
lost a total of `-0.00348593 BTC`.
|
||||
|
||||
As you will see your strategy performance will be influenced by your buy
|
||||
strategy, your sell strategy, and also by the `minimal_roi` and
|
||||
`stop_loss` you have set.
|
||||
We understand the bot has made `429` trades for an average duration of
|
||||
`4:12:00`, with a performance of `76.20%` (profit), that means it has
|
||||
earned a total of `0.00762792 BTC` starting with a capital of 0.01 BTC.
|
||||
|
||||
The column `avg profit %` shows the average profit for all trades made while the column `cum profit %` sums all the profits/losses.
|
||||
The column `tot profit %` shows instead the total profit % in relation to allocated capital
|
||||
(`max_open_trades * stake_amount`). In the above results we have `max_open_trades=2 stake_amount=0.005` in config
|
||||
so `(76.20/100) * (0.005 * 2) =~ 0.00762792 BTC`.
|
||||
|
||||
As you will see your strategy performance will be influenced by your buy
|
||||
strategy, your sell strategy, and also by the `minimal_roi` and
|
||||
`stop_loss` you have set.
|
||||
|
||||
As for an example if your minimal_roi is only `"0": 0.01`. You cannot
|
||||
expect the bot to make more profit than 1% (because it will sell every
|
||||
expect the bot to make more profit than 1% (because it will sell every
|
||||
time a trade will reach 1%).
|
||||
|
||||
```json
|
||||
@@ -234,21 +213,43 @@ time a trade will reach 1%).
|
||||
```
|
||||
|
||||
On the other hand, if you set a too high `minimal_roi` like `"0": 0.55`
|
||||
(55%), there is a lot of chance that the bot will never reach this
|
||||
profit. Hence, keep in mind that your performance is a mix of your
|
||||
(55%), there is a lot of chance that the bot will never reach this
|
||||
profit. Hence, keep in mind that your performance is a mix of your
|
||||
strategies, your configuration, and the crypto-currency you have set up.
|
||||
|
||||
### Further backtest-result analysis
|
||||
|
||||
To further analyze your backtest results, you can [export the trades](#exporting-trades-to-file).
|
||||
You can then load the trades to perform further analysis.
|
||||
|
||||
A good way for this is using Jupyter (notebook or lab) - which provides an interactive environment to analyze the data.
|
||||
|
||||
Freqtrade provides an easy to load the backtest results, which is `load_backtest_data` - and takes a path to the backtest-results file.
|
||||
|
||||
``` python
|
||||
from freqtrade.data.btanalysis import load_backtest_data
|
||||
df = load_backtest_data("user_data/backtest-result.json")
|
||||
|
||||
# Show value-counts per pair
|
||||
df.groupby("pair")["sell_reason"].value_counts()
|
||||
|
||||
```
|
||||
|
||||
This will allow you to drill deeper into your backtest results, and perform analysis which would make the regular backtest-output unreadable.
|
||||
|
||||
If you have some ideas for interesting / helpful backtest data analysis ideas, please submit a PR so the community can benefit from it.
|
||||
|
||||
## Backtesting multiple strategies
|
||||
|
||||
To backtest multiple strategies, a list of Strategies can be provided.
|
||||
|
||||
This is limited to 1 ticker-interval per run, however, data is only loaded once from disk so if you have multiple
|
||||
This is limited to 1 ticker-interval per run, however, data is only loaded once from disk so if you have multiple
|
||||
strategies you'd like to compare, this should give a nice runtime boost.
|
||||
|
||||
All listed Strategies need to be in the same folder.
|
||||
|
||||
``` bash
|
||||
freqtrade backtesting --timerange 20180401-20180410 --ticker-interval 5m --strategy-list Strategy001 Strategy002 --export trades
|
||||
freqtrade backtesting --timerange 20180401-20180410 --ticker-interval 5m --strategy-list Strategy001 Strategy002 --export trades
|
||||
```
|
||||
|
||||
This will save the results to `user_data/backtest_data/backtest-result-<strategy>.json`, injecting the strategy-name into the target filename.
|
||||
@@ -256,15 +257,15 @@ 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.
|
||||
|
||||
```
|
||||
=================================================== Strategy Summary ====================================================
|
||||
| Strategy | buy count | avg profit % | cum profit % | total profit ETH | avg duration | profit | loss |
|
||||
|:-----------|------------:|---------------:|---------------:|-------------------:|:----------------|---------:|-------:|
|
||||
| Strategy1 | 19 | -0.76 | -14.39 | -0.01440287 | 15:48:00 | 15 | 4 |
|
||||
| Strategy2 | 6 | -2.73 | -16.40 | -0.01641299 | 1 day, 14:12:00 | 3 | 3 |
|
||||
=========================================================== Strategy Summary ===========================================================
|
||||
| Strategy | buy count | avg profit % | cum profit % | tot profit BTC | tot profit % | avg duration | profit | loss |
|
||||
|:------------|------------:|---------------:|---------------:|-----------------:|---------------:|:---------------|---------:|-------:|
|
||||
| Strategy1 | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 243 |
|
||||
| Strategy2 | 1487 | -0.13 | -197.58 | -0.00988917 | -98.79 | 4:43:00 | 662 | 825 |
|
||||
```
|
||||
|
||||
## Next step
|
||||
|
||||
Great, your strategy is profitable. What if the bot can give your the
|
||||
optimal parameters to use for your strategy?
|
||||
Your next step is to learn [how to find optimal parameters with Hyperopt](https://github.com/freqtrade/freqtrade/blob/develop/docs/hyperopt.md)
|
||||
optimal parameters to use for your strategy?
|
||||
Your next step is to learn [how to find optimal parameters with Hyperopt](hyperopt.md)
|
||||
|
||||
@@ -1,28 +1,8 @@
|
||||
# Bot Optimization
|
||||
# Optimization
|
||||
|
||||
This page explains where to customize your strategies, and add new
|
||||
indicators.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Install a custom strategy file](#install-a-custom-strategy-file)
|
||||
- [Customize your strategy](#change-your-strategy)
|
||||
- [Anatomy of a strategy](#anatomy-of-a-strategy)
|
||||
- [Customize indicators](#customize-indicators)
|
||||
- [Buy signal rules](#buy-signal-rules)
|
||||
- [Sell signal rules](#sell-signal-rules)
|
||||
- [Minimal ROI](#minimal-roi)
|
||||
- [Stoploss](#stoploss)
|
||||
- [Ticker interval](#ticker-interval)
|
||||
- [Metadata dict](#metadata-dict)
|
||||
- [Where is the default strategy](#where-is-the-default-strategy)
|
||||
- [Specify custom strategy location](#specify-custom-strategy-location)
|
||||
- [Further strategy ideas](#further-strategy-ideas)
|
||||
|
||||
- [Where is the default strategy](#where-is-the-default-strategy)
|
||||
|
||||
Since the version `0.16.0` the bot allows using custom strategy file.
|
||||
|
||||
## Install a custom strategy file
|
||||
|
||||
This is very simple. Copy paste your strategy file into the folder
|
||||
@@ -34,7 +14,7 @@ Let assume you have a class called `AwesomeStrategy` in the file `awesome-strate
|
||||
2. Start the bot with the param `--strategy AwesomeStrategy` (the parameter is the class name)
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy
|
||||
python3 freqtrade --strategy AwesomeStrategy
|
||||
```
|
||||
|
||||
## Change your strategy
|
||||
@@ -60,13 +40,19 @@ A strategy file contains all the information needed to build a good strategy:
|
||||
The bot also include a sample strategy called `TestStrategy` you can update: `user_data/strategies/test_strategy.py`.
|
||||
You can test it with the parameter: `--strategy TestStrategy`
|
||||
|
||||
``` bash
|
||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy
|
||||
```bash
|
||||
python3 freqtrade --strategy AwesomeStrategy
|
||||
```
|
||||
|
||||
**For the following section we will use the [user_data/strategies/test_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/strategies/test_strategy.py)
|
||||
file as reference.**
|
||||
|
||||
!!! Note Strategies and Backtesting
|
||||
To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware
|
||||
that during backtesting the full time-interval is passed to the `populate_*()` methods at once.
|
||||
It is therefore best to use vectorized operations (across the whole dataframe, not loops) and
|
||||
avoid index referencing (`df.iloc[-1]`), but instead use `df.shift()` to get to the previous candle.
|
||||
|
||||
### Customize Indicators
|
||||
|
||||
Buy and sell strategies need indicators. You can add more indicators by extending the list contained in the method `populate_indicators()` from your strategy file.
|
||||
@@ -118,10 +104,10 @@ def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame
|
||||
return dataframe
|
||||
```
|
||||
|
||||
#### Want more indicator examples
|
||||
|
||||
Look into the [user_data/strategies/test_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/strategies/test_strategy.py).
|
||||
Then uncomment indicators you need.
|
||||
!!! Note "Want more indicator examples?"
|
||||
Look into the [user_data/strategies/test_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/user_data/strategies/test_strategy.py).<br/>
|
||||
Then uncomment indicators you need.
|
||||
|
||||
### Buy signal rules
|
||||
|
||||
@@ -187,7 +173,7 @@ This dict defines the minimal Return On Investment (ROI) a trade should reach be
|
||||
|
||||
It is of the following format, with the dict key (left side of the colon) being the minutes passed since the trade opened, and the value (right side of the colon) being the percentage.
|
||||
|
||||
```python
|
||||
```python
|
||||
minimal_roi = {
|
||||
"40": 0.0,
|
||||
"30": 0.01,
|
||||
@@ -199,10 +185,9 @@ minimal_roi = {
|
||||
The above configuration would therefore mean:
|
||||
|
||||
- Sell whenever 4% profit was reached
|
||||
- Sell after 20 minutes when 2% profit was reached
|
||||
- Sell after 20 minutes when 2% profit was reached
|
||||
- Sell after 30 minutes when 1% profit was reached
|
||||
- Sell after 40 minutes when the trade is non-loosing (no profit)
|
||||
- Sell when 2% profit was reached (in effect after 20 minutes)
|
||||
- Sell when 1% profit was reached (in effect after 30 minutes)
|
||||
- Sell when trade is non-loosing (in effect after 40 minutes)
|
||||
|
||||
The calculation does include fees.
|
||||
|
||||
@@ -227,7 +212,7 @@ stoploss = -0.10
|
||||
```
|
||||
|
||||
This would signify a stoploss of -10%.
|
||||
If your exchange supports it, it's recommended to also set `"stoploss_on_exchange"` in the order dict, so your stoploss is on the exchange and cannot be missed for network-problems (or other problems).
|
||||
If your exchange supports it, it's recommended to also set `"stoploss_on_exchange"` in the order dict, so your stoploss is on the exchange and cannot be missed for network-problems (or other problems).
|
||||
|
||||
For more information on order_types please look [here](https://github.com/freqtrade/freqtrade/blob/develop/docs/configuration.md#understand-order_types).
|
||||
|
||||
@@ -237,12 +222,129 @@ This is the set of candles the bot should download and use for the analysis.
|
||||
Common values are `"1m"`, `"5m"`, `"15m"`, `"1h"`, however all values supported by your exchange should work.
|
||||
|
||||
Please note that the same buy/sell signals may work with one interval, but not the other.
|
||||
This setting is accessible within the strategy by using `self.ticker_interval`.
|
||||
|
||||
### Metadata dict
|
||||
|
||||
The metadata-dict (available for `populate_buy_trend`, `populate_sell_trend`, `populate_indicators`) contains additional information.
|
||||
Currently this is `pair`, which can be accessed using `metadata['pair']` - and will return a pair in the format `XRP/BTC`.
|
||||
|
||||
The Metadata-dict should not be modified and does not persist information across multiple calls.
|
||||
Instead, have a look at the section [Storing information](#Storing-information)
|
||||
|
||||
### Storing information
|
||||
|
||||
Storing information can be accomplished by crating a new dictionary within the strategy class.
|
||||
|
||||
The name of the variable can be choosen at will, but should be prefixed with `cust_` to avoid naming collisions with predefined strategy variables.
|
||||
|
||||
```python
|
||||
class Awesomestrategy(IStrategy):
|
||||
# Create custom dictionary
|
||||
cust_info = {}
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
# Check if the entry already exists
|
||||
if "crosstime" in self.cust_info[metadata["pair"]:
|
||||
self.cust_info[metadata["pair"]["crosstime"] += 1
|
||||
else:
|
||||
self.cust_info[metadata["pair"]["crosstime"] = 1
|
||||
```
|
||||
|
||||
!!! Warning
|
||||
The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash.
|
||||
|
||||
!!! Note
|
||||
If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.
|
||||
|
||||
### Additional data (DataProvider)
|
||||
|
||||
The strategy provides access to the `DataProvider`. This allows you to get additional data to use in your strategy.
|
||||
|
||||
All methods return `None` in case of failure (do not raise an exception).
|
||||
|
||||
Please always check the mode of operation to select the correct method to get data (samples see below).
|
||||
|
||||
#### Possible options for DataProvider
|
||||
|
||||
- `available_pairs` - Property with tuples listing cached pairs with their intervals. (pair, interval)
|
||||
- `ohlcv(pair, ticker_interval)` - Currently cached ticker data for all pairs in the whitelist, returns DataFrame or empty DataFrame
|
||||
- `historic_ohlcv(pair, ticker_interval)` - Data stored on disk
|
||||
- `runmode` - Property containing the current runmode.
|
||||
|
||||
#### ohlcv / historic_ohlcv
|
||||
|
||||
``` python
|
||||
if self.dp:
|
||||
if self.dp.runmode in ('live', 'dry_run'):
|
||||
if (f'{self.stake_currency}/BTC', self.ticker_interval) in self.dp.available_pairs:
|
||||
data_eth = self.dp.ohlcv(pair='{self.stake_currency}/BTC',
|
||||
ticker_interval=self.ticker_interval)
|
||||
else:
|
||||
# Get historic ohlcv data (cached on disk).
|
||||
history_eth = self.dp.historic_ohlcv(pair='{self.stake_currency}/BTC',
|
||||
ticker_interval='1h')
|
||||
```
|
||||
|
||||
!!! Warning Warning about backtesting
|
||||
Be carefull when using dataprovider in backtesting. `historic_ohlcv()` provides the full time-range in one go,
|
||||
so please be aware of it and make sure to not "look into the future" to avoid surprises when running in dry/live mode).
|
||||
|
||||
!!! Warning Warning in hyperopt
|
||||
This option cannot currently be used during hyperopt.
|
||||
|
||||
#### Available Pairs
|
||||
|
||||
``` python
|
||||
if self.dp:
|
||||
for pair, ticker in self.dp.available_pairs:
|
||||
print(f"available {pair}, {ticker}")
|
||||
```
|
||||
|
||||
#### Get data for non-tradeable pairs
|
||||
|
||||
Data for additional, informative pairs (reference pairs) can be beneficial for some strategies.
|
||||
Ohlcv data for these pairs will be downloaded as part of the regular whitelist refresh process and is available via `DataProvider` just as other pairs (see above).
|
||||
These parts will **not** be traded unless they are also specified in the pair whitelist, or have been selected by Dynamic Whitelisting.
|
||||
|
||||
The pairs need to be specified as tuples in the format `("pair", "interval")`, with pair as the first and time interval as the second argument.
|
||||
|
||||
Sample:
|
||||
|
||||
``` python
|
||||
def informative_pairs(self):
|
||||
return [("ETH/USDT", "5m"),
|
||||
("BTC/TUSD", "15m"),
|
||||
]
|
||||
```
|
||||
|
||||
!!! Warning
|
||||
As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short.
|
||||
All intervals and all pairs can be specified as long as they are available (and active) on the used exchange.
|
||||
It is however better to use resampling to longer time-intervals when possible
|
||||
to avoid hammering the exchange with too many requests and risk beeing blocked.
|
||||
|
||||
### Additional data - Wallets
|
||||
|
||||
The strategy provides access to the `Wallets` object. This contains the current balances on the exchange.
|
||||
|
||||
!!! Note
|
||||
Wallets is not available during backtesting / hyperopt.
|
||||
|
||||
Please always check if `Wallets` is available to avoid failures during backtesting.
|
||||
|
||||
``` python
|
||||
if self.wallets:
|
||||
free_eth = self.wallets.get_free('ETH')
|
||||
used_eth = self.wallets.get_used('ETH')
|
||||
total_eth = self.wallets.get_total('ETH')
|
||||
```
|
||||
|
||||
#### Possible options for Wallets
|
||||
|
||||
- `get_free(asset)` - currently available balance to trade
|
||||
- `get_used(asset)` - currently tied up balance (open orders)
|
||||
- `get_total(asset)` - total available balance - sum of the 2 above
|
||||
|
||||
### Where is the default strategy?
|
||||
|
||||
The default buy strategy is located in the file
|
||||
@@ -253,7 +355,7 @@ The default buy strategy is located in the file
|
||||
If you want to use a strategy from a different folder you can pass `--strategy-path`
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy --strategy-path /some/folder
|
||||
python3 freqtrade --strategy AwesomeStrategy --strategy-path /some/folder
|
||||
```
|
||||
|
||||
### Further strategy ideas
|
||||
@@ -267,4 +369,4 @@ We also got a *strategy-sharing* channel in our [Slack community](https://join.s
|
||||
## Next step
|
||||
|
||||
Now you have a perfect strategy you probably want to backtest it.
|
||||
Your next step is to learn [How to use the Backtesting](https://github.com/freqtrade/freqtrade/blob/develop/docs/backtesting.md).
|
||||
Your next step is to learn [How to use the Backtesting](backtesting.md).
|
||||
|
||||
@@ -1,57 +1,87 @@
|
||||
# Bot usage
|
||||
# Start the bot
|
||||
|
||||
This page explains the difference parameters of the bot and how to run it.
|
||||
This page explains the different parameters of the bot and how to run it.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Bot commands](#bot-commands)
|
||||
- [Backtesting commands](#backtesting-commands)
|
||||
- [Hyperopt commands](#hyperopt-commands)
|
||||
|
||||
## Bot commands
|
||||
|
||||
```
|
||||
usage: freqtrade [-h] [-v] [--version] [-c PATH] [-d PATH] [-s NAME]
|
||||
[--strategy-path PATH] [--dynamic-whitelist [INT]]
|
||||
[--db-url PATH]
|
||||
{backtesting,hyperopt} ...
|
||||
usage: freqtrade [-h] [-v] [--logfile FILE] [--version] [-c PATH] [-d PATH]
|
||||
[-s NAME] [--strategy-path PATH] [--dynamic-whitelist [INT]]
|
||||
[--db-url PATH] [--sd-notify]
|
||||
{backtesting,edge,hyperopt} ...
|
||||
|
||||
Simple High Frequency Trading Bot for crypto currencies
|
||||
Free, open source crypto trading bot
|
||||
|
||||
positional arguments:
|
||||
{backtesting,hyperopt}
|
||||
backtesting backtesting module
|
||||
hyperopt hyperopt module
|
||||
{backtesting,edge,hyperopt}
|
||||
backtesting Backtesting module.
|
||||
edge Edge module.
|
||||
hyperopt Hyperopt module.
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-v, --verbose be verbose
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified
|
||||
--version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
specify configuration file (default: config.json)
|
||||
Specify configuration file (default: None). Multiple
|
||||
--config options may be used.
|
||||
-d PATH, --datadir PATH
|
||||
path to backtest data
|
||||
Path to backtest data.
|
||||
-s NAME, --strategy NAME
|
||||
specify strategy class name (default: DefaultStrategy)
|
||||
--strategy-path PATH specify additional strategy lookup path
|
||||
Specify strategy class name (default:
|
||||
DefaultStrategy).
|
||||
--strategy-path PATH Specify additional strategy lookup path.
|
||||
--dynamic-whitelist [INT]
|
||||
dynamically generate and update whitelist based on 24h
|
||||
BaseVolume (default: 20) DEPRECATED
|
||||
Dynamically generate and update whitelist based on 24h
|
||||
BaseVolume (default: 20). DEPRECATED.
|
||||
--db-url PATH Override trades database URL, this is useful if
|
||||
dry_run is enabled or in custom deployments (default:
|
||||
sqlite:///tradesv3.sqlite)
|
||||
None).
|
||||
--sd-notify Notify systemd service manager.
|
||||
```
|
||||
|
||||
### How to use a different config file?
|
||||
### How to use a different configuration file?
|
||||
|
||||
The bot allows you to select which config file you want to use. Per
|
||||
The bot allows you to select which configuration file you want to use. Per
|
||||
default, the bot will load the file `./config.json`
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py -c path/far/far/away/config.json
|
||||
python3 freqtrade -c path/far/far/away/config.json
|
||||
```
|
||||
|
||||
### How to use --strategy?
|
||||
### How to use multiple configuration files?
|
||||
|
||||
The bot allows you to use multiple configuration files by specifying multiple
|
||||
`-c/--config` configuration options in the command line. Configuration parameters
|
||||
defined in the last configuration file override parameters with the same name
|
||||
defined in the previous configuration file specified in the command line.
|
||||
|
||||
For example, you can make a separate configuration file with your key and secrete
|
||||
for the Exchange you use for trading, specify default configuration file with
|
||||
empty key and secrete values while running in the Dry Mode (which does not actually
|
||||
require them):
|
||||
|
||||
```bash
|
||||
python3 freqtrade -c ./config.json
|
||||
```
|
||||
|
||||
and specify both configuration files when running in the normal Live Trade Mode:
|
||||
|
||||
```bash
|
||||
python3 freqtrade -c ./config.json -c path/to/secrets/keys.config.json
|
||||
```
|
||||
|
||||
This could help you hide your private Exchange key and Exchange secrete on you local machine
|
||||
by setting appropriate file permissions for the file which contains actual secrets and, additionally,
|
||||
prevent unintended disclosure of sensitive private data when you publish examples
|
||||
of your configuration in the project issues or in the Internet.
|
||||
|
||||
See more details on this technique with examples in the documentation page on
|
||||
[configuration](configuration.md).
|
||||
|
||||
### How to use **--strategy**?
|
||||
|
||||
This parameter will allow you to load your custom strategy class.
|
||||
Per default without `--strategy` or `-s` the bot will load the
|
||||
@@ -66,20 +96,21 @@ In `user_data/strategies` you have a file `my_awesome_strategy.py` which has
|
||||
a strategy class called `AwesomeStrategy` to load it:
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy
|
||||
python3 freqtrade --strategy AwesomeStrategy
|
||||
```
|
||||
|
||||
If the bot does not find your strategy file, it will display in an error
|
||||
message the reason (File not found, or errors in your code).
|
||||
|
||||
Learn more about strategy file in [optimize your bot](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-optimization.md).
|
||||
Learn more about strategy file in
|
||||
[optimize your bot](bot-optimization.md).
|
||||
|
||||
### How to use --strategy-path?
|
||||
### How to use **--strategy-path**?
|
||||
|
||||
This parameter allows you to add an additional strategy lookup path, which gets
|
||||
checked before the default locations (The passed path must be a folder!):
|
||||
```bash
|
||||
python3 ./freqtrade/main.py --strategy AwesomeStrategy --strategy-path /some/folder
|
||||
python3 freqtrade --strategy AwesomeStrategy --strategy-path /some/folder
|
||||
```
|
||||
|
||||
#### How to install a strategy?
|
||||
@@ -87,33 +118,18 @@ python3 ./freqtrade/main.py --strategy AwesomeStrategy --strategy-path /some/fol
|
||||
This is very simple. Copy paste your strategy file into the folder
|
||||
`user_data/strategies` or use `--strategy-path`. And voila, the bot is ready to use it.
|
||||
|
||||
### How to use --dynamic-whitelist?
|
||||
### How to use **--dynamic-whitelist**?
|
||||
|
||||
> Dynamic-whitelist is deprecated. Please move your configurations to the configuration as outlined [here](docs/configuration.md#Dynamic-Pairlists)
|
||||
!!! danger "DEPRECATED"
|
||||
This command line option is deprecated. Please move your configurations using it
|
||||
to the configurations that utilize the `StaticPairList` or `VolumePairList` methods set
|
||||
in the configuration file
|
||||
as outlined [here](configuration/#dynamic-pairlists)
|
||||
|
||||
Per default `--dynamic-whitelist` will retrieve the 20 currencies based
|
||||
on BaseVolume. This value can be changed when you run the script.
|
||||
Description of this deprecated feature was moved to [here](deprecated.md).
|
||||
Please no longer use it.
|
||||
|
||||
**By Default**
|
||||
Get the 20 currencies based on BaseVolume.
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py --dynamic-whitelist
|
||||
```
|
||||
|
||||
**Customize the number of currencies to retrieve**
|
||||
Get the 30 currencies based on BaseVolume.
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py --dynamic-whitelist 30
|
||||
```
|
||||
|
||||
**Exception**
|
||||
`--dynamic-whitelist` must be greater than 0. If you enter 0 or a
|
||||
negative value (e.g -2), `--dynamic-whitelist` will use the default
|
||||
value (20).
|
||||
|
||||
### How to use --db-url?
|
||||
### How to use **--db-url**?
|
||||
|
||||
When you run the bot in Dry-run mode, per default no transactions are
|
||||
stored in a database. If you want to store your bot actions in a DB
|
||||
@@ -121,7 +137,7 @@ using `--db-url`. This can also be used to specify a custom database
|
||||
in production mode. Example command:
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite
|
||||
python3 freqtrade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite
|
||||
```
|
||||
|
||||
## Backtesting commands
|
||||
@@ -129,27 +145,27 @@ python3 ./freqtrade/main.py -c config.json --db-url sqlite:///tradesv3.dry_run.s
|
||||
Backtesting also uses the config specified via `-c/--config`.
|
||||
|
||||
```
|
||||
usage: freqtrade backtesting [-h] [-i TICKER_INTERVAL] [--eps] [--dmmp]
|
||||
[--timerange TIMERANGE] [-l] [-r]
|
||||
usage: freqtrade backtesting [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
||||
[--eps] [--dmmp] [-l] [-r]
|
||||
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
||||
[--export EXPORT] [--export-filename PATH]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||
specify ticker interval (1m, 5m, 30m, 1h, 1d)
|
||||
Specify ticker interval (1m, 5m, 30m, 1h, 1d).
|
||||
--timerange TIMERANGE
|
||||
Specify what timerange of data to use.
|
||||
--eps, --enable-position-stacking
|
||||
Allow buying the same pair multiple times (position
|
||||
stacking)
|
||||
stacking).
|
||||
--dmmp, --disable-max-market-positions
|
||||
Disable applying `max_open_trades` during backtest
|
||||
(same as setting `max_open_trades` to a very high
|
||||
number)
|
||||
--timerange TIMERANGE
|
||||
specify what timerange of data to use.
|
||||
-l, --live using live data
|
||||
number).
|
||||
-l, --live Use live data.
|
||||
-r, --refresh-pairs-cached
|
||||
refresh the pairs files in tests/testdata with the
|
||||
Refresh the pairs files in tests/testdata with the
|
||||
latest data from the exchange. Use it if you want to
|
||||
run your backtesting with up-to-date data.
|
||||
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
|
||||
@@ -159,7 +175,7 @@ optional arguments:
|
||||
this together with --export trades, the strategy-name
|
||||
is injected into the filename (so backtest-data.json
|
||||
becomes backtest-data-DefaultStrategy.json
|
||||
--export EXPORT export backtest results, argument are: trades Example
|
||||
--export EXPORT Export backtest results, argument are: trades. Example
|
||||
--export=trades
|
||||
--export-filename PATH
|
||||
Save backtest results to this filename requires
|
||||
@@ -167,18 +183,18 @@ optional arguments:
|
||||
filename=user_data/backtest_data/backtest_today.json
|
||||
(default: user_data/backtest_data/backtest-
|
||||
result.json)
|
||||
|
||||
```
|
||||
|
||||
### How to use --refresh-pairs-cached parameter?
|
||||
### How to use **--refresh-pairs-cached** parameter?
|
||||
|
||||
The first time your run Backtesting, it will take the pairs you have
|
||||
set in your config file and download data from Bittrex.
|
||||
|
||||
If for any reason you want to update your data set, you use
|
||||
`--refresh-pairs-cached` to force Backtesting to update the data it has.
|
||||
**Use it only if you want to update your data set. You will not be able
|
||||
to come back to the previous version.**
|
||||
|
||||
!!! Note
|
||||
Use it only if you want to update your data set. You will not be able to come back to the previous version.
|
||||
|
||||
To test your strategy with latest data, we recommend continuing using
|
||||
the parameter `-l` or `--live`.
|
||||
@@ -189,29 +205,30 @@ To optimize your strategy, you can use hyperopt parameter hyperoptimization
|
||||
to find optimal parameter values for your stategy.
|
||||
|
||||
```
|
||||
usage: freqtrade hyperopt [-h] [-i TICKER_INTERVAL] [--eps] [--dmmp]
|
||||
[--timerange TIMERANGE] [-e INT]
|
||||
[-s {all,buy,roi,stoploss} [{all,buy,roi,stoploss} ...]]
|
||||
usage: freqtrade hyperopt [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
||||
[--customhyperopt NAME] [--eps] [--dmmp] [-e INT]
|
||||
[-s {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...]]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||
specify ticker interval (1m, 5m, 30m, 1h, 1d)
|
||||
Specify ticker interval (1m, 5m, 30m, 1h, 1d).
|
||||
--timerange TIMERANGE
|
||||
Specify what timerange of data to use.
|
||||
--customhyperopt NAME
|
||||
Specify hyperopt class name (default:
|
||||
DefaultHyperOpts).
|
||||
--eps, --enable-position-stacking
|
||||
Allow buying the same pair multiple times (position
|
||||
stacking)
|
||||
stacking).
|
||||
--dmmp, --disable-max-market-positions
|
||||
Disable applying `max_open_trades` during backtest
|
||||
(same as setting `max_open_trades` to a very high
|
||||
number)
|
||||
--timerange TIMERANGE
|
||||
specify what timerange of data to use.
|
||||
--hyperopt PATH specify hyperopt file (default:
|
||||
freqtrade/optimize/default_hyperopt.py)
|
||||
-e INT, --epochs INT specify number of epochs (default: 100)
|
||||
-s {all,buy,roi,stoploss} [{all,buy,roi,stoploss} ...], --spaces {all,buy,roi,stoploss} [{all,buy,roi,stoploss} ...]
|
||||
number).
|
||||
-e INT, --epochs INT Specify number of epochs (default: 100).
|
||||
-s {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...], --spaces {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...]
|
||||
Specify which parameters to hyperopt. Space separate
|
||||
list. Default: all
|
||||
list. Default: all.
|
||||
|
||||
```
|
||||
|
||||
@@ -220,22 +237,22 @@ optional arguments:
|
||||
To know your trade expectacny and winrate against historical data, you can use Edge.
|
||||
|
||||
```
|
||||
usage: main.py edge [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE] [-r]
|
||||
[--stoplosses STOPLOSS_RANGE]
|
||||
usage: freqtrade edge [-h] [-i TICKER_INTERVAL] [--timerange TIMERANGE] [-r]
|
||||
[--stoplosses STOPLOSS_RANGE]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||
specify ticker interval (1m, 5m, 30m, 1h, 1d)
|
||||
Specify ticker interval (1m, 5m, 30m, 1h, 1d).
|
||||
--timerange TIMERANGE
|
||||
specify what timerange of data to use.
|
||||
Specify what timerange of data to use.
|
||||
-r, --refresh-pairs-cached
|
||||
refresh the pairs files in tests/testdata with the
|
||||
Refresh the pairs files in tests/testdata with the
|
||||
latest data from the exchange. Use it if you want to
|
||||
run your edge with up-to-date data.
|
||||
--stoplosses STOPLOSS_RANGE
|
||||
defines a range of stoploss against which edge will
|
||||
assess the strategythe format is "min,max,step"
|
||||
Defines a range of stoploss against which edge will
|
||||
assess the strategy the format is "min,max,step"
|
||||
(without any space).example:
|
||||
--stoplosses=-0.01,-0.1,-0.001
|
||||
```
|
||||
@@ -250,4 +267,4 @@ in [misc.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/misc.
|
||||
## Next step
|
||||
|
||||
The optimal strategy of the bot will change with time depending of the market trends. The next step is to
|
||||
[optimize your bot](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-optimization.md).
|
||||
[optimize your bot](bot-optimization.md).
|
||||
|
||||
@@ -2,12 +2,6 @@
|
||||
|
||||
This page explains how to configure your `config.json` file.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Bot commands](#bot-commands)
|
||||
- [Backtesting commands](#backtesting-commands)
|
||||
- [Hyperopt commands](#hyperopt-commands)
|
||||
|
||||
## Setup config.json
|
||||
|
||||
We recommend to copy and use the `config.json.example` as a template
|
||||
@@ -15,78 +9,113 @@ for your bot configuration.
|
||||
|
||||
The table below will list all configuration parameters.
|
||||
|
||||
| Command | Default | Mandatory | Description |
|
||||
|----------|---------|----------|-------------|
|
||||
| `max_open_trades` | 3 | Yes | Number of trades open your bot will have. If -1 then it is ignored (i.e. potentially unlimited open trades)
|
||||
| `stake_currency` | BTC | Yes | Crypto-currency used for trading.
|
||||
| `stake_amount` | 0.05 | Yes | Amount of crypto-currency your bot will use for each trade. Per default, the bot will use (0.05 BTC x 3) = 0.15 BTC in total will be always engaged. Set it to 'unlimited' to allow the bot to use all avaliable balance.
|
||||
| `ticker_interval` | [1m, 5m, 30m, 1h, 1d] | No | The ticker interval to use (1min, 5 min, 30 min, 1 hour or 1 day). Default is 5 minutes
|
||||
| `fiat_display_currency` | USD | Yes | Fiat currency used to show your profits. More information below.
|
||||
| `dry_run` | true | Yes | Define if the bot must be in Dry-run or production mode.
|
||||
| `process_only_new_candles` | false | No | If set to true indicators are processed only once a new candle arrives. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. Can be set either in Configuration or in the strategy.
|
||||
| `minimal_roi` | See below | No | Set the threshold in percent the bot will use to sell a trade. More information below. If set, this parameter will override `minimal_roi` from your strategy file.
|
||||
| `stoploss` | -0.10 | No | Value of the stoploss in percent used by the bot. More information below. If set, this parameter will override `stoploss` from your strategy file.
|
||||
| `trailing_stop` | false | No | Enables trailing stop-loss (based on `stoploss` in either configuration or strategy file).
|
||||
| `trailing_stop_positve` | 0 | No | Changes stop-loss once profit has been reached.
|
||||
| `trailing_stop_positve_offset` | 0 | No | Offset on when to apply `trailing_stop_positive`. Percentage value which should be positive.
|
||||
| `unfilledtimeout.buy` | 10 | Yes | How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled.
|
||||
| `unfilledtimeout.sell` | 10 | Yes | How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled.
|
||||
| `bid_strategy.ask_last_balance` | 0.0 | Yes | Set the bidding price. More information below.
|
||||
| `bid_strategy.use_order_book` | false | No | Allows buying of pair using the rates in Order Book Bids.
|
||||
| `bid_strategy.order_book_top` | 0 | No | Bot will use the top N rate in Order Book Bids. Ie. a value of 2 will allow the bot to pick the 2nd bid rate in Order Book Bids.
|
||||
| `bid_strategy. check_depth_of_market.enabled` | false | No | Does not buy if the % difference of buy orders and sell orders is met in Order Book.
|
||||
| `bid_strategy. check_depth_of_market.bids_to_ask_delta` | 0 | No | The % difference of buy orders and sell orders found in Order Book. A value lesser than 1 means sell orders is greater, while value greater than 1 means buy orders is higher.
|
||||
| `ask_strategy.use_order_book` | false | No | Allows selling of open traded pair using the rates in Order Book Asks.
|
||||
| `ask_strategy.order_book_min` | 0 | No | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
||||
| `ask_strategy.order_book_max` | 0 | No | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
||||
| `order_types` | None | No | Configure order-types depending on the action (`"buy"`, `"sell"`, `"stoploss"`, `"stoploss_on_exchange"`). [More information below](#understand-order_types).
|
||||
| `order_time_in_force` | None | No | Configure time in force for buy and sell orders. [More information below](#understand-order_time_in_force).
|
||||
| `exchange.name` | bittrex | Yes | Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename).
|
||||
| `exchange.key` | key | No | API key to use for the exchange. Only required when you are in production mode.
|
||||
| `exchange.secret` | secret | No | API secret to use for the exchange. Only required when you are in production mode.
|
||||
| `exchange.pair_whitelist` | [] | No | List of currency to use by the bot. Can be overrided with `--dynamic-whitelist` param.
|
||||
| `exchange.pair_blacklist` | [] | No | List of currency the bot must avoid. Useful when using `--dynamic-whitelist` param.
|
||||
| `exchange.ccxt_rate_limit` | True | No | DEPRECATED!! Have CCXT handle Exchange rate limits. Depending on the exchange, having this to false can lead to temporary bans from the exchange.
|
||||
| `exchange.ccxt_config` | None | No | Additional CCXT parameters passed to the regular ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation)
|
||||
| `exchange.ccxt_async_config` | None | No | Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation)
|
||||
| `edge` | false | No | Please refer to [edge configuration document](edge.md) for detailed explanation.
|
||||
| `experimental.use_sell_signal` | false | No | Use your sell strategy in addition of the `minimal_roi`.
|
||||
| `experimental.sell_profit_only` | false | No | waits until you have made a positive profit before taking a sell decision.
|
||||
| `experimental.ignore_roi_if_buy_signal` | false | No | Does not sell if the buy-signal is still active. Takes preference over `minimal_roi` and `use_sell_signal`
|
||||
| `pairlist.method` | StaticPairList | No | Use Static whitelist. [More information below](#dynamic-pairlists).
|
||||
| `pairlist.config` | None | No | Additional configuration for dynamic pairlists. [More information below](#dynamic-pairlists).
|
||||
| `telegram.enabled` | true | Yes | Enable or not the usage of Telegram.
|
||||
| `telegram.token` | token | No | Your Telegram bot token. Only required if `telegram.enabled` is `true`.
|
||||
| `telegram.chat_id` | chat_id | No | Your personal Telegram account id. Only required if `telegram.enabled` is `true`.
|
||||
| `webhook.enabled` | false | No | Enable usage of Webhook notifications
|
||||
| `webhook.url` | false | No | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details.
|
||||
| `webhook.webhookbuy` | false | No | Payload to send on buy. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details.
|
||||
| `webhook.webhooksell` | false | No | Payload to send on sell. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details.
|
||||
| `webhook.webhookstatus` | false | No | Payload to send on status calls. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details.
|
||||
| `db_url` | `sqlite:///tradesv3.sqlite` | No | Declares database URL to use. NOTE: This defaults to `sqlite://` if `dry_run` is `True`.
|
||||
| `initial_state` | running | No | Defines the initial application state. More information below.
|
||||
| `forcebuy_enable` | false | No | Enables the RPC Commands to force a buy. More information below.
|
||||
| `strategy` | DefaultStrategy | No | Defines Strategy class to use.
|
||||
| `strategy_path` | null | No | Adds an additional strategy lookup path (must be a folder).
|
||||
| `internals.process_throttle_secs` | 5 | Yes | Set the process throttle. Value in second.
|
||||
Mandatory Parameters are marked as **Required**.
|
||||
|
||||
The definition of each config parameters is in [misc.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/misc.py#L205).
|
||||
| Command | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `max_open_trades` | 3 | **Required.** Number of trades open your bot will have. If -1 then it is ignored (i.e. potentially unlimited open trades)
|
||||
| `stake_currency` | BTC | **Required.** Crypto-currency used for trading. [Strategy Override](#parameters-in-the-strategy).
|
||||
| `stake_amount` | 0.05 | **Required.** Amount of crypto-currency your bot will use for each trade. Per default, the bot will use (0.05 BTC x 3) = 0.15 BTC in total will be always engaged. Set it to `"unlimited"` to allow the bot to use all available balance. [Strategy Override](#parameters-in-the-strategy).
|
||||
| `amount_reserve_percent` | 0.05 | Reserve some amount in min pair stake amount. Default is 5%. The bot will reserve `amount_reserve_percent` + stop-loss value when calculating min pair stake amount in order to avoid possible trade refusals.
|
||||
| `ticker_interval` | [1m, 5m, 15m, 30m, 1h, 1d, ...] | The ticker interval to use (1min, 5 min, 15 min, 30 min, 1 hour or 1 day). Default is 5 minutes. [Strategy Override](#parameters-in-the-strategy).
|
||||
| `fiat_display_currency` | USD | **Required.** Fiat currency used to show your profits. More information below.
|
||||
| `dry_run` | true | **Required.** Define if the bot must be in Dry-run or production mode.
|
||||
| `dry_run_wallet` | 999.9 | Overrides the default amount of 999.9 stake currency units in the wallet used by the bot running in the Dry Run mode if you need it for any reason.
|
||||
| `process_only_new_candles` | false | If set to true indicators are processed only once a new candle arrives. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. [Strategy Override](#parameters-in-the-strategy).
|
||||
| `minimal_roi` | See below | Set the threshold in percent the bot will use to sell a trade. More information below. [Strategy Override](#parameters-in-the-strategy).
|
||||
| `stoploss` | -0.10 | Value of the stoploss in percent used by the bot. More information below. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
||||
| `trailing_stop` | false | Enables trailing stop-loss (based on `stoploss` in either configuration or strategy file). More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
||||
| `trailing_stop_positive` | 0 | Changes stop-loss once profit has been reached. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
||||
| `trailing_stop_positive_offset` | 0 | Offset on when to apply `trailing_stop_positive`. Percentage value which should be positive. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
||||
| `trailing_only_offset_is_reached` | false | Only apply trailing stoploss when the offset is reached. [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy).
|
||||
| `unfilledtimeout.buy` | 10 | **Required.** How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled.
|
||||
| `unfilledtimeout.sell` | 10 | **Required.** How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled.
|
||||
| `bid_strategy.ask_last_balance` | 0.0 | **Required.** Set the bidding price. More information [below](#understand-ask_last_balance).
|
||||
| `bid_strategy.use_order_book` | false | Allows buying of pair using the rates in Order Book Bids.
|
||||
| `bid_strategy.order_book_top` | 0 | Bot will use the top N rate in Order Book Bids. Ie. a value of 2 will allow the bot to pick the 2nd bid rate in Order Book Bids.
|
||||
| `bid_strategy. check_depth_of_market.enabled` | false | Does not buy if the % difference of buy orders and sell orders is met in Order Book.
|
||||
| `bid_strategy. check_depth_of_market.bids_to_ask_delta` | 0 | The % difference of buy orders and sell orders found in Order Book. A value lesser than 1 means sell orders is greater, while value greater than 1 means buy orders is higher.
|
||||
| `ask_strategy.use_order_book` | false | Allows selling of open traded pair using the rates in Order Book Asks.
|
||||
| `ask_strategy.order_book_min` | 0 | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
||||
| `ask_strategy.order_book_max` | 0 | Bot will scan from the top min to max Order Book Asks searching for a profitable rate.
|
||||
| `order_types` | None | Configure order-types depending on the action (`"buy"`, `"sell"`, `"stoploss"`, `"stoploss_on_exchange"`). [More information below](#understand-order_types). [Strategy Override](#parameters-in-the-strategy).
|
||||
| `order_time_in_force` | None | Configure time in force for buy and sell orders. [More information below](#understand-order_time_in_force). [Strategy Override](#parameters-in-the-strategy).
|
||||
| `exchange.name` | bittrex | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename).
|
||||
| `exchange.sandbox` | false | Use the 'sandbox' version of the exchange, where the exchange provides a sandbox for risk-free integration. See [here](sandbox-testing.md) in more details.
|
||||
| `exchange.key` | key | API key to use for the exchange. Only required when you are in production mode.
|
||||
| `exchange.secret` | secret | API secret to use for the exchange. Only required when you are in production mode.
|
||||
| `exchange.pair_whitelist` | [] | List of currency to use by the bot. Can be overrided with `--dynamic-whitelist` param.
|
||||
| `exchange.pair_blacklist` | [] | List of currency the bot must avoid. Useful when using `--dynamic-whitelist` param.
|
||||
| `exchange.ccxt_config` | None | Additional CCXT parameters passed to the regular ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation)
|
||||
| `exchange.ccxt_async_config` | None | Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation)
|
||||
| `exchange.markets_refresh_interval` | 60 | The interval in minutes in which markets are reloaded.
|
||||
| `edge` | false | Please refer to [edge configuration document](edge.md) for detailed explanation.
|
||||
| `experimental.use_sell_signal` | false | Use your sell strategy in addition of the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy).
|
||||
| `experimental.sell_profit_only` | false | Waits until you have made a positive profit before taking a sell decision. [Strategy Override](#parameters-in-the-strategy).
|
||||
| `experimental.ignore_roi_if_buy_signal` | false | Does not sell if the buy-signal is still active. Takes preference over `minimal_roi` and `use_sell_signal`. [Strategy Override](#parameters-in-the-strategy).
|
||||
| `pairlist.method` | StaticPairList | Use Static whitelist. [More information below](#dynamic-pairlists).
|
||||
| `pairlist.config` | None | Additional configuration for dynamic pairlists. [More information below](#dynamic-pairlists).
|
||||
| `telegram.enabled` | true | **Required.** Enable or not the usage of Telegram.
|
||||
| `telegram.token` | token | Your Telegram bot token. Only required if `telegram.enabled` is `true`.
|
||||
| `telegram.chat_id` | chat_id | Your personal Telegram account id. Only required if `telegram.enabled` is `true`.
|
||||
| `webhook.enabled` | false | Enable usage of Webhook notifications
|
||||
| `webhook.url` | false | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details.
|
||||
| `webhook.webhookbuy` | false | Payload to send on buy. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details.
|
||||
| `webhook.webhooksell` | false | Payload to send on sell. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details.
|
||||
| `webhook.webhookstatus` | false | Payload to send on status calls. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details.
|
||||
| `db_url` | `sqlite:///tradesv3.sqlite`| Declares database URL to use. NOTE: This defaults to `sqlite://` if `dry_run` is `True`.
|
||||
| `initial_state` | running | Defines the initial application state. More information below.
|
||||
| `forcebuy_enable` | false | Enables the RPC Commands to force a buy. More information below.
|
||||
| `strategy` | DefaultStrategy | Defines Strategy class to use.
|
||||
| `strategy_path` | null | Adds an additional strategy lookup path (must be a folder).
|
||||
| `internals.process_throttle_secs` | 5 | **Required.** Set the process throttle. Value in second.
|
||||
| `internals.sd_notify` | false | Enables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See [here](installation.md#7-optional-configure-freqtrade-as-a-systemd-service) for more details.
|
||||
| `logfile` | | Specify Logfile. Uses a rolling strategy of 10 files, with 1Mb per file.
|
||||
|
||||
### Parameters in the strategy
|
||||
|
||||
The following parameters can be set in either configuration file or strategy.
|
||||
Values set in the configuration file always overwrite values set in the strategy.
|
||||
|
||||
* `stake_currency`
|
||||
* `stake_amount`
|
||||
* `ticker_interval`
|
||||
* `minimal_roi`
|
||||
* `stoploss`
|
||||
* `trailing_stop`
|
||||
* `trailing_stop_positive`
|
||||
* `trailing_stop_positive_offset`
|
||||
* `process_only_new_candles`
|
||||
* `order_types`
|
||||
* `order_time_in_force`
|
||||
* `use_sell_signal` (experimental)
|
||||
* `sell_profit_only` (experimental)
|
||||
* `ignore_roi_if_buy_signal` (experimental)
|
||||
|
||||
### Understand stake_amount
|
||||
|
||||
`stake_amount` is an amount of crypto-currency your bot will use for each trade.
|
||||
The `stake_amount` configuration parameter is an amount of crypto-currency your bot will use for each trade.
|
||||
The minimal value is 0.0005. If there is not enough crypto-currency in
|
||||
the account an exception is generated.
|
||||
To allow the bot to trade all the avaliable `stake_currency` in your account set `stake_amount` = `unlimited`.
|
||||
In this case a trade amount is calclulated as `currency_balanse / (max_open_trades - current_open_trades)`.
|
||||
To allow the bot to trade all the available `stake_currency` in your account set
|
||||
|
||||
```json
|
||||
"stake_amount" : "unlimited",
|
||||
```
|
||||
|
||||
In this case a trade amount is calclulated as:
|
||||
|
||||
```python
|
||||
currency_balanse / (max_open_trades - current_open_trades)
|
||||
```
|
||||
|
||||
### Understand minimal_roi
|
||||
|
||||
`minimal_roi` is a JSON object where the key is a duration
|
||||
The `minimal_roi` configuration parameter is a JSON object where the key is a duration
|
||||
in minutes and the value is the minimum ROI in percent.
|
||||
See the example below:
|
||||
|
||||
```
|
||||
```json
|
||||
"minimal_roi": {
|
||||
"40": 0.0, # Sell after 40 minutes if the profit is not negative
|
||||
"30": 0.01, # Sell after 30 minutes if there is at least 1% profit
|
||||
@@ -95,18 +124,19 @@ See the example below:
|
||||
},
|
||||
```
|
||||
|
||||
Most of the strategy files already include the optimal `minimal_roi`
|
||||
value. This parameter is optional. If you use it, it will take over the
|
||||
Most of the strategy files already include the optimal `minimal_roi` value.
|
||||
This parameter can be set in either Strategy or Configuration file. If you use it in the configuration file, it will override the
|
||||
`minimal_roi` value from the strategy file.
|
||||
If it is not set in either Strategy or Configuration, a default of 1000% `{"0": 10}` is used, and minimal roi is disabled unless your trade generates 1000% profit.
|
||||
|
||||
### Understand stoploss
|
||||
|
||||
`stoploss` is loss in percentage that should trigger a sale.
|
||||
For example value `-0.10` will cause immediate sell if the
|
||||
The `stoploss` configuration parameter is loss in percentage that should trigger a sale.
|
||||
For example, value `-0.10` will cause immediate sell if the
|
||||
profit dips below -10% for a given trade. This parameter is optional.
|
||||
|
||||
Most of the strategy files already include the optimal `stoploss`
|
||||
value. This parameter is optional. If you use it, it will take over the
|
||||
value. This parameter is optional. If you use it in the configuration file, it will take over the
|
||||
`stoploss` value from the strategy file.
|
||||
|
||||
### Understand trailing stoploss
|
||||
@@ -115,75 +145,116 @@ Go to the [trailing stoploss Documentation](stoploss.md) for details on trailing
|
||||
|
||||
### Understand initial_state
|
||||
|
||||
`initial_state` is an optional field that defines the initial application state.
|
||||
The `initial_state` configuration parameter is an optional field that defines the initial application state.
|
||||
Possible values are `running` or `stopped`. (default=`running`)
|
||||
If the value is `stopped` the bot has to be started with `/start` first.
|
||||
|
||||
### Understand forcebuy_enable
|
||||
|
||||
`forcebuy_enable` enables the usage of forcebuy commands via Telegram.
|
||||
The `forcebuy_enable` configuration parameter enables the usage of forcebuy commands via Telegram.
|
||||
This is disabled for security reasons by default, and will show a warning message on startup if enabled.
|
||||
You send `/forcebuy ETH/BTC` to the bot, who buys the pair and holds it until a regular sell-signal appears (ROI, stoploss, /forcesell).
|
||||
For example, you can send `/forcebuy ETH/BTC` Telegram command when this feature if enabled to the bot,
|
||||
who then buys the pair and holds it until a regular sell-signal (ROI, stoploss, /forcesell) appears.
|
||||
|
||||
This can be dangerous with some strategies, so use with care.
|
||||
|
||||
Can be dangerous with some strategies, so use with care
|
||||
See [the telegram documentation](telegram-usage.md) for details on usage.
|
||||
|
||||
### Understand process_throttle_secs
|
||||
|
||||
`process_throttle_secs` is an optional field that defines in seconds how long the bot should wait
|
||||
The `process_throttle_secs` configuration parameter is an optional field that defines in seconds how long the bot should wait
|
||||
before asking the strategy if we should buy or a sell an asset. After each wait period, the strategy is asked again for
|
||||
every opened trade wether or not we should sell, and for all the remaining pairs (either the dynamic list of pairs or
|
||||
the static list of pairs) if we should buy.
|
||||
|
||||
### Understand ask_last_balance
|
||||
|
||||
`ask_last_balance` sets the bidding price. Value `0.0` will use `ask` price, `1.0` will
|
||||
The `ask_last_balance` configuration parameter sets the bidding price. Value `0.0` will use `ask` price, `1.0` will
|
||||
use the `last` price and values between those interpolate between ask and last
|
||||
price. Using `ask` price will guarantee quick success in bid, but bot will also
|
||||
end up paying more then would probably have been necessary.
|
||||
|
||||
### Understand order_types
|
||||
|
||||
`order_types` contains a dict mapping order-types to market-types as well as stoploss on or off exchange type. This allows to buy using limit orders, sell using limit-orders, and create stoploss orders using market. It also allows to set the stoploss "on exchange" which means stoploss order would be placed immediately once the buy order is fulfilled.
|
||||
This can be set in the configuration or in the strategy. Configuration overwrites strategy configurations.
|
||||
The `order_types` configuration parameter contains a dict mapping order-types to
|
||||
market-types as well as stoploss on or off exchange type and stoploss on exchange
|
||||
update interval in seconds. This allows to buy using limit orders, sell using
|
||||
limit-orders, and create stoploss orders using market. It also allows to set the
|
||||
stoploss "on exchange" which means stoploss order would be placed immediately once
|
||||
the buy order is fulfilled. In case stoploss on exchange and `trailing_stop` are
|
||||
both set, then the bot will use `stoploss_on_exchange_interval` to check it periodically
|
||||
and update it if necessary (e.x. in case of trailing stoploss).
|
||||
This can be set in the configuration file or in the strategy.
|
||||
Values set in the configuration file overwrites values set in the strategy.
|
||||
|
||||
If this is configured, all 4 values (`"buy"`, `"sell"`, `"stoploss"`, `"stoploss_on_exchange"`) need to be present, otherwise the bot warn about it and will fail to start.
|
||||
The below is the default which is used if this is not configured in either Strategy or configuration.
|
||||
If this is configured, all 4 values (`buy`, `sell`, `stoploss` and
|
||||
`stoploss_on_exchange`) need to be present, otherwise the bot will warn about it and fail to start.
|
||||
The below is the default which is used if this is not configured in either strategy or configuration file.
|
||||
|
||||
``` python
|
||||
"order_types": {
|
||||
"buy": "limit",
|
||||
"sell": "limit",
|
||||
"stoploss": "market",
|
||||
"stoploss_on_exchange": False
|
||||
},
|
||||
```python
|
||||
"order_types": {
|
||||
"buy": "limit",
|
||||
"sell": "limit",
|
||||
"stoploss": "market",
|
||||
"stoploss_on_exchange": False,
|
||||
"stoploss_on_exchange_interval": 60
|
||||
},
|
||||
```
|
||||
|
||||
**NOTE**: Not all exchanges support "market" orders.
|
||||
The following message will be shown if your exchange does not support market orders: `"Exchange <yourexchange> does not support market orders."`
|
||||
!!! Note
|
||||
Not all exchanges support "market" orders.
|
||||
The following message will be shown if your exchange does not support market orders:
|
||||
`"Exchange <yourexchange> does not support market orders."`
|
||||
|
||||
!!! Note
|
||||
Stoploss on exchange interval is not mandatory. Do not change its value if you are
|
||||
unsure of what you are doing. For more information about how stoploss works please
|
||||
read [the stoploss documentation](stoploss.md).
|
||||
|
||||
!!! Note
|
||||
In case of stoploss on exchange if the stoploss is cancelled manually then
|
||||
the bot would recreate one.
|
||||
|
||||
### Understand order_time_in_force
|
||||
Order time in force defines the policy by which the order is executed on the exchange. Three commonly used time in force are:<br/>
|
||||
**GTC (Goog Till Canceled):**
|
||||
This is most of the time the default time in force. It means the order will remain on exchange till it is canceled by user. It can be fully or partially fulfilled. If partially fulfilled, the remaining will stay on the exchange till cancelled.<br/>
|
||||
|
||||
The `order_time_in_force` configuration parameter defines the policy by which the order
|
||||
is executed on the exchange. Three commonly used time in force are:
|
||||
|
||||
**GTC (Good Till Canceled):**
|
||||
|
||||
This is most of the time the default time in force. It means the order will remain
|
||||
on exchange till it is canceled by user. It can be fully or partially fulfilled.
|
||||
If partially fulfilled, the remaining will stay on the exchange till cancelled.
|
||||
|
||||
**FOK (Full Or Kill):**
|
||||
It means if the order is not executed immediately AND fully then it is canceled by the exchange.<br/>
|
||||
|
||||
It means if the order is not executed immediately AND fully then it is canceled by the exchange.
|
||||
|
||||
**IOC (Immediate Or Canceled):**
|
||||
It is the same as FOK (above) except it can be partially fulfilled. The remaining part is automatically cancelled by the exchange.
|
||||
<br/>
|
||||
`order_time_in_force` contains a dict buy and sell time in force policy. This can be set in the configuration or in the strategy. Configuration overwrites strategy configurations.<br/>
|
||||
possible values are: `gtc` (default), `fok` or `ioc`.<br/>
|
||||
|
||||
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.
|
||||
This can be set in the configuration file or in the strategy.
|
||||
Values set in the configuration file overwrites values set in the strategy.
|
||||
|
||||
The possible values are: `gtc` (default), `fok` or `ioc`.
|
||||
|
||||
``` python
|
||||
"order_time_in_force": {
|
||||
"buy": "gtc",
|
||||
"sell": "gtc"
|
||||
},
|
||||
"order_time_in_force": {
|
||||
"buy": "gtc",
|
||||
"sell": "gtc"
|
||||
},
|
||||
```
|
||||
**NOTE**: This is an ongoing work. For now it is supported only for binance and only for buy orders. Please don't change the default value unless you know what you are doing.<br/>
|
||||
|
||||
### What values for exchange.name?
|
||||
!!! Warning
|
||||
This is an ongoing work. For now it is supported only for binance and only for buy orders.
|
||||
Please don't change the default value unless you know what you are doing.
|
||||
|
||||
Freqtrade is based on [CCXT library](https://github.com/ccxt/ccxt) that supports 115 cryptocurrency
|
||||
### Exchange configuration
|
||||
|
||||
Freqtrade is based on [CCXT library](https://github.com/ccxt/ccxt) that supports over 100 cryptocurrency
|
||||
exchange markets and trading APIs. The complete up-to-date list can be found in the
|
||||
[CCXT repo homepage](https://github.com/ccxt/ccxt/tree/master/python). However, the bot was tested
|
||||
with only Bittrex and Binance.
|
||||
@@ -195,31 +266,65 @@ The bot was tested with the following exchanges:
|
||||
|
||||
Feel free to test other exchanges and submit your PR to improve the bot.
|
||||
|
||||
### What values for fiat_display_currency?
|
||||
#### Sample exchange configuration
|
||||
|
||||
`fiat_display_currency` set the base currency to use for the conversion from coin to fiat in Telegram.
|
||||
The valid values are: "AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR", "USD".
|
||||
In addition to central bank currencies, a range of cryto currencies are supported.
|
||||
The valid values are: "BTC", "ETH", "XRP", "LTC", "BCH", "USDT".
|
||||
A exchange configuration for "binance" would look as follows:
|
||||
|
||||
## Switch to dry-run mode
|
||||
```json
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "your_exchange_key",
|
||||
"secret": "your_exchange_secret",
|
||||
"ccxt_config": {"enableRateLimit": true},
|
||||
"ccxt_async_config": {
|
||||
"enableRateLimit": true,
|
||||
"rateLimit": 200
|
||||
},
|
||||
```
|
||||
|
||||
We recommend starting the bot in dry-run mode to see how your bot will
|
||||
behave and how is the performance of your strategy. In Dry-run mode the
|
||||
This configuration enables binance, as well as rate limiting to avoid bans from the exchange.
|
||||
`"rateLimit": 200` defines a wait-event of 0.2s between each call. This can also be completely disabled by setting `"enableRateLimit"` to false.
|
||||
|
||||
!!! Note
|
||||
Optimal settings for rate limiting depend on the exchange and the size of the whitelist, so an ideal parameter will vary on many other settings.
|
||||
We try to provide sensible defaults per exchange where possible, if you encounter bans please make sure that `"enableRateLimit"` is enabled and increase the `"rateLimit"` parameter step by step.
|
||||
|
||||
|
||||
### What values can be used for fiat_display_currency?
|
||||
|
||||
The `fiat_display_currency` configuration parameter sets the base currency to use for the
|
||||
conversion from coin to fiat in the bot Telegram reports.
|
||||
|
||||
The valid values are:
|
||||
|
||||
```json
|
||||
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR", "USD"
|
||||
```
|
||||
|
||||
In addition to fiat currencies, a range of cryto currencies are supported.
|
||||
|
||||
The valid values are:
|
||||
|
||||
```json
|
||||
"BTC", "ETH", "XRP", "LTC", "BCH", "USDT"
|
||||
```
|
||||
|
||||
## Switch to Dry-run mode
|
||||
|
||||
We recommend starting the bot in the Dry-run mode to see how your bot will
|
||||
behave and what is the performance of your strategy. In the Dry-run mode the
|
||||
bot does not engage your money. It only runs a live simulation without
|
||||
creating trades.
|
||||
creating trades on the exchange.
|
||||
|
||||
### To switch your bot in Dry-run mode:
|
||||
|
||||
1. Edit your `config.json` file
|
||||
2. Switch dry-run to true and specify db_url for a persistent db
|
||||
1. Edit your `config.json` configuration file.
|
||||
2. Switch `dry-run` to `true` and specify `db_url` for a persistence database.
|
||||
|
||||
```json
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite///tradesv3.dryrun.sqlite",
|
||||
"db_url": "sqlite:///tradesv3.dryrun.sqlite",
|
||||
```
|
||||
|
||||
3. Remove your Exchange API key (change them by fake api credentials)
|
||||
3. Remove your Exchange API key and secrete (change them by empty values or fake credentials):
|
||||
|
||||
```json
|
||||
"exchange": {
|
||||
@@ -230,51 +335,61 @@ creating trades.
|
||||
}
|
||||
```
|
||||
|
||||
Once you will be happy with your bot performance, you can switch it to
|
||||
production mode.
|
||||
Once you will be happy with your bot performance running in the Dry-run mode,
|
||||
you can switch it to production mode.
|
||||
|
||||
### Dynamic Pairlists
|
||||
|
||||
Dynamic pairlists select pairs for you based on the logic configured.
|
||||
The bot runs against all pairs (with that stake) on the exchange, and a number of assets (`number_assets`) is selected based on the selected criteria.
|
||||
The bot runs against all pairs (with that stake) on the exchange, and a number of assets
|
||||
(`number_assets`) is selected based on the selected criteria.
|
||||
|
||||
By *default*, a Static Pairlist is used (configured as `"pair_whitelist"` under the `"exchange"` section of this configuration).
|
||||
By default, the `StaticPairList` method is used.
|
||||
The Pairlist method is configured as `pair_whitelist` parameter under the `exchange`
|
||||
section of the configuration.
|
||||
|
||||
#### Available Pairlist methods
|
||||
**Available Pairlist methods:**
|
||||
|
||||
* `"StaticPairList"`
|
||||
* uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`
|
||||
* `"VolumePairList"`
|
||||
* Formerly available as `--dynamic-whitelist [<number_assets>]`
|
||||
* Selects `number_assets` top pairs based on `sort_key`, which can be one of `askVolume`, `bidVolume` and `quoteVolume`, defaults to `quoteVolume`.
|
||||
* `StaticPairList`
|
||||
* It uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`.
|
||||
* `VolumePairList`
|
||||
* Formerly available as `--dynamic-whitelist [<number_assets>]`. This command line
|
||||
option is deprecated and should no longer be used.
|
||||
* It selects `number_assets` top pairs based on `sort_key`, which can be one of
|
||||
`askVolume`, `bidVolume` and `quoteVolume`, defaults to `quoteVolume`.
|
||||
* There is a possibility to filter low-value coins that would not allow setting a stop loss
|
||||
(set `precision_filter` parameter to `true` for this).
|
||||
|
||||
Example:
|
||||
|
||||
```json
|
||||
"pairlist": {
|
||||
"method": "VolumePairList",
|
||||
"config": {
|
||||
"number_assets": 20,
|
||||
"sort_key": "quoteVolume"
|
||||
"sort_key": "quoteVolume",
|
||||
"precision_filter": false
|
||||
}
|
||||
},
|
||||
```
|
||||
|
||||
## Switch to production mode
|
||||
|
||||
In production mode, the bot will engage your money. Be careful a wrong
|
||||
In production mode, the bot will engage your money. Be careful, since a wrong
|
||||
strategy can lose all your money. Be aware of what you are doing when
|
||||
you run it in production mode.
|
||||
|
||||
### To switch your bot in production mode
|
||||
|
||||
1. Edit your `config.json` file
|
||||
**Edit your `config.json` file.**
|
||||
|
||||
2. Switch dry-run to false and don't forget to adapt your database URL if set
|
||||
**Switch dry-run to false and don't forget to adapt your database URL if set:**
|
||||
|
||||
```json
|
||||
"dry_run": false,
|
||||
```
|
||||
|
||||
3. Insert your Exchange API key (change them by fake api keys)
|
||||
**Insert your Exchange API key (change them by fake api keys):**
|
||||
|
||||
```json
|
||||
"exchange": {
|
||||
@@ -285,8 +400,8 @@ you run it in production mode.
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
If you have not your Bittrex API key yet, [see our tutorial](https://github.com/freqtrade/freqtrade/blob/develop/docs/pre-requisite.md).
|
||||
!!! Note
|
||||
If you have an exchange API key yet, [see our tutorial](/pre-requisite).
|
||||
|
||||
### Using proxy with FreqTrade
|
||||
|
||||
@@ -337,4 +452,4 @@ Please ensure that 'NameOfStrategy' is identical to the strategy name!
|
||||
|
||||
## Next step
|
||||
|
||||
Now you have configured your config.json, the next step is to [start your bot](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-usage.md).
|
||||
Now you have configured your config.json, the next step is to [start your bot](bot-usage.md).
|
||||
|
||||
31
docs/deprecated.md
Normal file
31
docs/deprecated.md
Normal file
@@ -0,0 +1,31 @@
|
||||
# Deprecated features
|
||||
|
||||
This page contains description of the command line arguments, configuration parameters
|
||||
and the bot features that were declared as DEPRECATED by the bot development team
|
||||
and are no longer supported. Please avoid their usage in your configuration.
|
||||
|
||||
### The **--dynamic-whitelist** command line option
|
||||
|
||||
Per default `--dynamic-whitelist` will retrieve the 20 currencies based
|
||||
on BaseVolume. This value can be changed when you run the script.
|
||||
|
||||
**By Default**
|
||||
Get the 20 currencies based on BaseVolume.
|
||||
|
||||
```bash
|
||||
python3 freqtrade --dynamic-whitelist
|
||||
```
|
||||
|
||||
**Customize the number of currencies to retrieve**
|
||||
Get the 30 currencies based on BaseVolume.
|
||||
|
||||
```bash
|
||||
python3 freqtrade --dynamic-whitelist 30
|
||||
```
|
||||
|
||||
**Exception**
|
||||
`--dynamic-whitelist` must be greater than 0. If you enter 0 or a
|
||||
negative value (e.g -2), `--dynamic-whitelist` will use the default
|
||||
value (20).
|
||||
|
||||
|
||||
@@ -4,8 +4,20 @@ This page is intended for developers of FreqTrade, people who want to contribute
|
||||
|
||||
All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We [track issues](https://github.com/freqtrade/freqtrade/issues) on [GitHub](https://github.com) and also have a dev channel in [slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE) where you can ask questions.
|
||||
|
||||
## Documentation
|
||||
|
||||
## Module
|
||||
Documentation is available at [https://freqtrade.io](https://www.freqtrade.io/) and needs to be provided with every new feature PR.
|
||||
|
||||
Special fields for the documentation (like Note boxes, ...) can be found [here](https://squidfunk.github.io/mkdocs-material/extensions/admonition/).
|
||||
|
||||
## Developer setup
|
||||
|
||||
To configure a development environment, use best use the `setup.sh` script and answer "y" when asked "Do you want to install dependencies for dev [y/N]? ".
|
||||
Alternatively (if your system is not supported by the setup.sh script), follow the manual installation process and run `pip3 install -r requirements-dev.txt`.
|
||||
|
||||
This will install all required tools for development, including `pytest`, `flake8`, `mypy`, and `coveralls`.
|
||||
|
||||
## Modules
|
||||
|
||||
### Dynamic Pairlist
|
||||
|
||||
@@ -68,3 +80,38 @@ Please also run `self._validate_whitelist(pairs)` and to check and remove pairs
|
||||
|
||||
This is a simple method used by `VolumePairList` - however serves as a good example.
|
||||
It implements caching (`@cached(TTLCache(maxsize=1, ttl=1800))`) as well as a configuration option to allow different (but similar) strategies to work with the same PairListProvider.
|
||||
|
||||
## Creating a release
|
||||
|
||||
This part of the documentation is aimed at maintainers, and shows how to create a release.
|
||||
|
||||
### create release branch
|
||||
|
||||
``` bash
|
||||
# make sure you're in develop branch
|
||||
git checkout develop
|
||||
|
||||
# create new branch
|
||||
git checkout -b new_release
|
||||
```
|
||||
|
||||
* edit `freqtrade/__init__.py` and add the desired version (for example `0.18.0`)
|
||||
* Commit this part
|
||||
* push that branch to the remote and create a PR
|
||||
|
||||
### create changelog from git commits
|
||||
|
||||
``` bash
|
||||
# Needs to be done before merging / pulling that branch.
|
||||
git log --oneline --no-decorate --no-merges master..develop
|
||||
```
|
||||
|
||||
### Create github release / tag
|
||||
|
||||
* Use the version-number specified as tag.
|
||||
* Use "master" as reference (this step comes after the above PR is merged).
|
||||
* use the above changelog as release comment (as codeblock)
|
||||
|
||||
### After-release
|
||||
|
||||
* update version in develop to next valid version and postfix that with `-dev` (`0.18.0 -> 0.18.1-dev`)
|
||||
|
||||
225
docs/edge.md
225
docs/edge.md
@@ -2,170 +2,214 @@
|
||||
|
||||
This page explains how to use Edge Positioning module in your bot in order to enter into a trade only if the trade has a reasonable win rate and risk reward ratio, and consequently adjust your position size and stoploss.
|
||||
|
||||
**NOTICE:** Edge positioning is not compatible with dynamic whitelist. it overrides dynamic whitelist.
|
||||
**NOTICE2:** Edge won't consider anything else than buy/sell/stoploss signals. So trailing stoploss, ROI, and everything else will be ignored in its calculation.
|
||||
!!! Warning
|
||||
Edge positioning is not compatible with dynamic whitelist. If enabled, it overrides the dynamic whitelist option.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Introduction](#introduction)
|
||||
- [How does it work?](#how-does-it-work?)
|
||||
- [Configurations](#configurations)
|
||||
- [Running Edge independently](#running-edge-independently)
|
||||
!!! Note
|
||||
Edge does not consider anything else than buy/sell/stoploss signals. So trailing stoploss, ROI, and everything else are ignored in its calculation.
|
||||
|
||||
## Introduction
|
||||
Trading is all about probability. No one can claim that he has a strategy working all the time. You have to assume that sometimes you lose.<br/><br/>
|
||||
But it doesn't mean there is no rule, it only means rules should work "most of the time". Let's play a game: we toss a coin, heads: I give you 10$, tails: You give me 10$. Is it an interesting game ? no, it is quite boring, isn't it?<br/><br/>
|
||||
But let's say the probability that we have heads is 80%, and the probability that we have tails is 20%. Now it is becoming interesting ...
|
||||
That means 10$ x 80% versus 10$ x 20%. 8$ versus 2$. That means over time you will win 8$ risking only 2$ on each toss of coin.<br/><br/>
|
||||
Let's complicate it more: you win 80% of the time but only 2$, I win 20% of the time but 8$. The calculation is: 80% * 2$ versus 20% * 8$. It is becoming boring again because overtime you win $1.6$ (80% x 2$) and me $1.6 (20% * 8$) too.<br/><br/>
|
||||
The question is: How do you calculate that? how do you know if you wanna play?
|
||||
Trading is all about probability. No one can claim that he has a strategy working all the time. You have to assume that sometimes you lose.
|
||||
|
||||
But it doesn't mean there is no rule, it only means rules should work "most of the time". Let's play a game: we toss a coin, heads: I give you 10$, tails: you give me 10$. Is it an interesting game? No, it's quite boring, isn't it?
|
||||
|
||||
But let's say the probability that we have heads is 80% (because our coin has the displaced distribution of mass or other defect), and the probability that we have tails is 20%. Now it is becoming interesting...
|
||||
|
||||
That means 10$ X 80% versus 10$ X 20%. 8$ versus 2$. That means over time you will win 8$ risking only 2$ on each toss of coin.
|
||||
|
||||
Let's complicate it more: you win 80% of the time but only 2$, I win 20% of the time but 8$. The calculation is: 80% X 2$ versus 20% X 8$. It is becoming boring again because overtime you win $1.6$ (80% X 2$) and me $1.6 (20% X 8$) too.
|
||||
|
||||
The question is: How do you calculate that? How do you know if you wanna play?
|
||||
|
||||
The answer comes to two factors:
|
||||
- Win Rate
|
||||
- Risk Reward Ratio
|
||||
|
||||
|
||||
### Win Rate
|
||||
Means over X trades what is the percentage of winning trades to total number of trades (note that we don't consider how much you gained but only If you won or not).
|
||||
Win Rate (*W*) is is the mean over some amount of trades (*N*) what is the percentage of winning trades to total number of trades (note that we don't consider how much you gained but only if you won or not).
|
||||
|
||||
W = (Number of winning trades) / (Total number of trades) = (Number of winning trades) / N
|
||||
|
||||
`W = (Number of winning trades) / (Number of losing trades)`
|
||||
Complementary Loss Rate (*L*) is defined as
|
||||
|
||||
L = (Number of losing trades) / (Total number of trades) = (Number of losing trades) / N
|
||||
|
||||
or, which is the same, as
|
||||
|
||||
L = 1 – W
|
||||
|
||||
### Risk Reward Ratio
|
||||
Risk Reward Ratio is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose:
|
||||
Risk Reward Ratio (*R*) is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose:
|
||||
|
||||
`R = Profit / Loss`
|
||||
R = Profit / Loss
|
||||
|
||||
Over time, on many trades, you can calculate your risk reward by dividing your average profit on winning trades by your average loss on losing trades:
|
||||
|
||||
`Average profit = (Sum of profits) / (Number of winning trades)`
|
||||
Average profit = (Sum of profits) / (Number of winning trades)
|
||||
|
||||
`Average loss = (Sum of losses) / (Number of losing trades)`
|
||||
Average loss = (Sum of losses) / (Number of losing trades)
|
||||
|
||||
`R = (Average profit) / (Average loss)`
|
||||
R = (Average profit) / (Average loss)
|
||||
|
||||
### Expectancy
|
||||
At this point we can combine *W* and *R* to create an expectancy ratio. This is a simple process of multiplying the risk reward ratio by the percentage of winning trades and subtracting the percentage of losing trades, which is calculated as follows:
|
||||
|
||||
At this point we can combine W and R to create an expectancy ratio. This is a simple process of multiplying the risk reward ratio by the percentage of winning trades, and subtracting the percentage of losing trades, which is calculated as follows:
|
||||
|
||||
Expectancy Ratio = (Risk Reward Ratio x Win Rate) – Loss Rate
|
||||
Expectancy Ratio = (Risk Reward Ratio X Win Rate) – Loss Rate = (R X W) – L
|
||||
|
||||
So lets say your Win rate is 28% and your Risk Reward Ratio is 5:
|
||||
|
||||
`Expectancy = (5 * 0.28) - 0.72 = 0.68`
|
||||
Expectancy = (5 X 0.28) – 0.72 = 0.68
|
||||
|
||||
Superficially, this means that on average you expect this strategy’s trades to return .68 times the size of your losers. This is important for two reasons: First, it may seem obvious, but you know right away that you have a positive return. Second, you now have a number you can compare to other candidate systems to make decisions about which ones you employ.
|
||||
Superficially, this means that on average you expect this strategy’s trades to return .68 times the size of your loses. This is important for two reasons: First, it may seem obvious, but you know right away that you have a positive return. Second, you now have a number you can compare to other candidate systems to make decisions about which ones you employ.
|
||||
|
||||
It is important to remember that any system with an expectancy greater than 0 is profitable using past data. The key is finding one that will be profitable in the future.
|
||||
|
||||
You can also use this number to evaluate the effectiveness of modifications to this system.
|
||||
You can also use this value to evaluate the effectiveness of modifications to this system.
|
||||
|
||||
**NOTICE:** It's important to keep in mind that Edge is testing your expectancy using historical data , there's no guarantee that you will have a similar edge in the future. It's still vital to do this testing in order to build confidence in your methodology, but be wary of "curve-fitting" your approach to the historical data as things are unlikely to play out the exact same way for future trades.
|
||||
**NOTICE:** It's important to keep in mind that Edge is testing your expectancy using historical data, there's no guarantee that you will have a similar edge in the future. It's still vital to do this testing in order to build confidence in your methodology, but be wary of "curve-fitting" your approach to the historical data as things are unlikely to play out the exact same way for future trades.
|
||||
|
||||
## How does it work?
|
||||
If enabled in config, Edge will go through historical data with a range of stoplosses in order to find buy and sell/stoploss signals. It then calculates win rate and expectancy over X trades for each stoploss. Here is an example:
|
||||
If enabled in config, Edge will go through historical data with a range of stoplosses in order to find buy and sell/stoploss signals. It then calculates win rate and expectancy over *N* trades for each stoploss. Here is an example:
|
||||
|
||||
| Pair | Stoploss | Win Rate | Risk Reward Ratio | Expectancy |
|
||||
|----------|:-------------:|-------------:|------------------:|-----------:|
|
||||
| XZC/ETH | -0.03 | 0.52 |1.359670 | 0.228 |
|
||||
| XZC/ETH | -0.01 | 0.50 |1.176384 | 0.088 |
|
||||
| XZC/ETH | -0.02 | 0.51 |1.115941 | 0.079 |
|
||||
| XZC/ETH | -0.03 | 0.52 |1.359670 | 0.228 |
|
||||
| XZC/ETH | -0.04 | 0.51 |1.234539 | 0.117 |
|
||||
|
||||
The goal here is to find the best stoploss for the strategy in order to have the maximum expectancy. In the above example stoploss at 3% leads to the maximum expectancy according to historical data.
|
||||
|
||||
Edge then forces stoploss to your strategy dynamically.
|
||||
Edge module then forces stoploss value it evaluated to your strategy dynamically.
|
||||
|
||||
### Position size
|
||||
Edge dictates the stake amount for each trade to the bot according to the following factors:
|
||||
Edge also dictates the stake amount for each trade to the bot according to the following factors:
|
||||
|
||||
- Allowed capital at risk
|
||||
- Stoploss
|
||||
|
||||
Allowed capital at risk is calculated as follows:
|
||||
|
||||
**allowed capital at risk** = **capital_available_percentage** X **allowed risk per trade**
|
||||
Allowed capital at risk = (Capital available_percentage) X (Allowed risk per trade)
|
||||
|
||||
**Stoploss** is calculated as described above against historical data.
|
||||
Stoploss is calculated as described above against historical data.
|
||||
|
||||
Your position size then will be:
|
||||
|
||||
**position size** = **allowed capital at risk** / **stoploss**
|
||||
Position size = (Allowed capital at risk) / Stoploss
|
||||
|
||||
Example:<br/>
|
||||
Let's say the stake currency is ETH and you have 10 ETH on the exchange, your **capital_available_percentage** is 50% and you would allow 1% of risk for each trade. thus your available capital for trading is **10 x 0.5 = 5 ETH** and allowed capital at risk would be **5 x 0.01 = 0.05 ETH**. <br/>
|
||||
Let's assume Edge has calculated that for **XLM/ETH** market your stoploss should be at 2%. So your position size will be **0.05 / 0.02 = 2.5ETH**.<br/>
|
||||
Bot takes a position of 2.5ETH on XLM/ETH (call it trade 1). Up next, you receive another buy signal while trade 1 is still open. This time on BTC/ETH market. Edge calculated stoploss for this market at 4%. So your position size would be 0.05 / 0.04 = 1.25ETH (call it trade 2).<br/>
|
||||
Note that available capital for trading didn’t change for trade 2 even if you had already trade 1. The available capital doesn’t mean the free amount on your wallet.<br/>
|
||||
Now you have two trades open. The Bot receives yet another buy signal for another market: **ADA/ETH**. This time the stoploss is calculated at 1%. So your position size is **0.05 / 0.01 = 5ETH**. But there are already 4ETH blocked in two previous trades. So the position size for this third trade would be 1ETH.<br/>
|
||||
Available capital doesn’t change before a position is sold. Let’s assume that trade 1 receives a sell signal and it is sold with a profit of 1ETH. Your total capital on exchange would be 11 ETH and the available capital for trading becomes 5.5ETH. <br/>
|
||||
So the Bot receives another buy signal for trade 4 with a stoploss at 2% then your position size would be **0.055 / 0.02 = 2.75**.
|
||||
Example:
|
||||
|
||||
Let's say the stake currency is ETH and you have 10 ETH on the exchange, your capital available percentage is 50% and you would allow 1% of risk for each trade. thus your available capital for trading is **10 x 0.5 = 5 ETH** and allowed capital at risk would be **5 x 0.01 = 0.05 ETH**.
|
||||
|
||||
Let's assume Edge has calculated that for **XLM/ETH** market your stoploss should be at 2%. So your position size will be **0.05 / 0.02 = 2.5 ETH**.
|
||||
|
||||
Bot takes a position of 2.5 ETH on XLM/ETH (call it trade 1). Up next, you receive another buy signal while trade 1 is still open. This time on **BTC/ETH** market. Edge calculated stoploss for this market at 4%. So your position size would be 0.05 / 0.04 = 1.25 ETH (call it trade 2).
|
||||
|
||||
Note that available capital for trading didn’t change for trade 2 even if you had already trade 1. The available capital doesn’t mean the free amount on your wallet.
|
||||
|
||||
Now you have two trades open. The bot receives yet another buy signal for another market: **ADA/ETH**. This time the stoploss is calculated at 1%. So your position size is **0.05 / 0.01 = 5 ETH**. But there are already 3.75 ETH blocked in two previous trades. So the position size for this third trade would be **5 – 3.75 = 1.25 ETH**.
|
||||
|
||||
Available capital doesn’t change before a position is sold. Let’s assume that trade 1 receives a sell signal and it is sold with a profit of 1 ETH. Your total capital on exchange would be 11 ETH and the available capital for trading becomes 5.5 ETH.
|
||||
|
||||
So the Bot receives another buy signal for trade 4 with a stoploss at 2% then your position size would be **0.055 / 0.02 = 2.75 ETH**.
|
||||
|
||||
## Configurations
|
||||
Edge has following configurations:
|
||||
Edge module has following configuration options:
|
||||
|
||||
#### enabled
|
||||
If true, then Edge will run periodically.<br/>
|
||||
(default to false)
|
||||
If true, then Edge will run periodically.
|
||||
|
||||
(defaults to false)
|
||||
|
||||
#### process_throttle_secs
|
||||
How often should Edge run in seconds? <br/>
|
||||
(default to 3600 so one hour)
|
||||
How often should Edge run in seconds?
|
||||
|
||||
(defaults to 3600 so one hour)
|
||||
|
||||
#### calculate_since_number_of_days
|
||||
Number of days of data against which Edge calculates Win Rate, Risk Reward and Expectancy
|
||||
Note that it downloads historical data so increasing this number would lead to slowing down the bot.<br/>
|
||||
(default to 7)
|
||||
Note that it downloads historical data so increasing this number would lead to slowing down the bot.
|
||||
|
||||
(defaults to 7)
|
||||
|
||||
#### capital_available_percentage
|
||||
This is the percentage of the total capital on exchange in stake currency. <br/>
|
||||
As an example if you have 10 ETH available in your wallet on the exchange and this value is 0.5 (which is 50%), then the bot will use a maximum amount of 5 ETH for trading and considers it as available capital.<br/>
|
||||
(default to 0.5)
|
||||
This is the percentage of the total capital on exchange in stake currency.
|
||||
|
||||
As an example if you have 10 ETH available in your wallet on the exchange and this value is 0.5 (which is 50%), then the bot will use a maximum amount of 5 ETH for trading and considers it as available capital.
|
||||
|
||||
(defaults to 0.5)
|
||||
|
||||
#### allowed_risk
|
||||
Percentage of allowed risk per trade.<br/>
|
||||
(default to 0.01 [1%])
|
||||
Percentage of allowed risk per trade.
|
||||
|
||||
(defaults to 0.01 so 1%)
|
||||
|
||||
#### stoploss_range_min
|
||||
Minimum stoploss.<br/>
|
||||
(default to -0.01)
|
||||
|
||||
Minimum stoploss.
|
||||
|
||||
(defaults to -0.01)
|
||||
|
||||
#### stoploss_range_max
|
||||
Maximum stoploss.<br/>
|
||||
(default to -0.10)
|
||||
|
||||
Maximum stoploss.
|
||||
|
||||
(defaults to -0.10)
|
||||
|
||||
#### stoploss_range_step
|
||||
As an example if this is set to -0.01 then Edge will test the strategy for [-0.01, -0,02, -0,03 ..., -0.09, -0.10] ranges.
|
||||
Note than having a smaller step means having a bigger range which could lead to slow calculation. <br/>
|
||||
if you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10. <br/>
|
||||
(default to -0.01)
|
||||
|
||||
As an example if this is set to -0.01 then Edge will test the strategy for \[-0.01, -0,02, -0,03 ..., -0.09, -0.10\] ranges.
|
||||
Note than having a smaller step means having a bigger range which could lead to slow calculation.
|
||||
|
||||
If you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10.
|
||||
|
||||
(defaults to -0.01)
|
||||
|
||||
#### minimum_winrate
|
||||
It filters pairs which don't have at least minimum_winrate.
|
||||
This comes handy if you want to be conservative and don't comprise win rate in favor of risk reward ratio.<br/>
|
||||
(default to 0.60)
|
||||
|
||||
It filters out pairs which don't have at least minimum_winrate.
|
||||
|
||||
This comes handy if you want to be conservative and don't comprise win rate in favour of risk reward ratio.
|
||||
|
||||
(defaults to 0.60)
|
||||
|
||||
#### minimum_expectancy
|
||||
It filters paris which have an expectancy lower than this number .
|
||||
Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return.<br/>
|
||||
(default to 0.20)
|
||||
|
||||
It filters out pairs which have the expectancy lower than this number.
|
||||
|
||||
Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return.
|
||||
|
||||
(defaults to 0.20)
|
||||
|
||||
#### min_trade_number
|
||||
When calculating W and R and E (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable. Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something. <br/>
|
||||
(default to 10, it is highly recommended not to decrease this number)
|
||||
|
||||
When calculating *W*, *R* and *E* (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable.
|
||||
|
||||
Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something.
|
||||
|
||||
(defaults to 10, it is highly recommended not to decrease this number)
|
||||
|
||||
#### max_trade_duration_minute
|
||||
Edge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign.<br/>
|
||||
**NOTICE:** While configuring this value, you should take into consideration your ticker interval. as an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. default value is set assuming your strategy interval is relatively small (1m or 5m, etc).<br/>
|
||||
(default to 1 day, 1440 = 60 * 24)
|
||||
|
||||
Edge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign.
|
||||
|
||||
**NOTICE:** While configuring this value, you should take into consideration your ticker interval. As an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. Default value is set assuming your strategy interval is relatively small (1m or 5m, etc.).
|
||||
|
||||
(defaults to 1 day, i.e. to 60 * 24 = 1440 minutes)
|
||||
|
||||
#### remove_pumps
|
||||
Edge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off.<br/>
|
||||
(default to false)
|
||||
|
||||
Edge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off.
|
||||
|
||||
(defaults to false)
|
||||
|
||||
## Running Edge independently
|
||||
|
||||
You can run Edge independently in order to see in details the result. Here is an example:
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py edge
|
||||
python3 freqtrade edge
|
||||
```
|
||||
|
||||
An example of its output:
|
||||
@@ -189,28 +233,31 @@ An example of its output:
|
||||
| NEBL/BTC | -0.03 | 0.63 | 1.29 | 0.58 | 0.44 | 19 | 59 |
|
||||
|
||||
### Update cached pairs with the latest data
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py edge --refresh-pairs-cached
|
||||
python3 freqtrade edge --refresh-pairs-cached
|
||||
```
|
||||
|
||||
### Precising stoploss range
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py edge --stoplosses=-0.01,-0.1,-0.001 #min,max,step
|
||||
python3 freqtrade edge --stoplosses=-0.01,-0.1,-0.001 #min,max,step
|
||||
```
|
||||
|
||||
### Advanced use of timerange
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py edge --timerange=20181110-20181113
|
||||
python3 freqtrade edge --timerange=20181110-20181113
|
||||
```
|
||||
|
||||
Doing --timerange=-200 will get the last 200 timeframes from your inputdata. You can also specify specific dates, or a range span indexed by start and stop.
|
||||
Doing `--timerange=-200` will get the last 200 timeframes from your inputdata. You can also specify specific dates, or a range span indexed by start and stop.
|
||||
|
||||
The full timerange specification:
|
||||
|
||||
* Use last 123 tickframes of data: --timerange=-123
|
||||
* Use first 123 tickframes of data: --timerange=123-
|
||||
* Use tickframes from line 123 through 456: --timerange=123-456
|
||||
* Use tickframes till 2018/01/31: --timerange=-20180131
|
||||
* Use tickframes since 2018/01/31: --timerange=20180131-
|
||||
* Use tickframes since 2018/01/31 till 2018/03/01 : --timerange=20180131-20180301
|
||||
* Use tickframes between POSIX timestamps 1527595200 1527618600: --timerange=1527595200-1527618600
|
||||
* Use last 123 tickframes of data: `--timerange=-123`
|
||||
* Use first 123 tickframes of data: `--timerange=123-`
|
||||
* Use tickframes from line 123 through 456: `--timerange=123-456`
|
||||
* Use tickframes till 2018/01/31: `--timerange=-20180131`
|
||||
* Use tickframes since 2018/01/31: `--timerange=20180131-`
|
||||
* Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
|
||||
* Use tickframes between POSIX timestamps 1527595200 1527618600: `--timerange=1527595200-1527618600`
|
||||
|
||||
86
docs/faq.md
86
docs/faq.md
@@ -1,71 +1,89 @@
|
||||
# freqtrade FAQ
|
||||
# Freqtrade FAQ
|
||||
|
||||
### Freqtrade commons
|
||||
|
||||
#### I have waited 5 minutes, why hasn't the bot made any trades yet?!
|
||||
|
||||
Depending on the buy strategy, the amount of whitelisted coins, the
|
||||
situation of the market etc, it can take up to hours to find good entry
|
||||
Depending on the buy strategy, the amount of whitelisted coins, the
|
||||
situation of the market etc, it can take up to hours to find good entry
|
||||
position for a trade. Be patient!
|
||||
|
||||
#### I have made 12 trades already, why is my total profit negative?!
|
||||
|
||||
I understand your disappointment but unfortunately 12 trades is just
|
||||
not enough to say anything. If you run backtesting, you can see that our
|
||||
current algorithm does leave you on the plus side, but that is after
|
||||
thousands of trades and even there, you will be left with losses on
|
||||
specific coins that you have traded tens if not hundreds of times. We
|
||||
of course constantly aim to improve the bot but it will _always_ be a
|
||||
gamble, which should leave you with modest wins on monthly basis but
|
||||
I understand your disappointment but unfortunately 12 trades is just
|
||||
not enough to say anything. If you run backtesting, you can see that our
|
||||
current algorithm does leave you on the plus side, but that is after
|
||||
thousands of trades and even there, you will be left with losses on
|
||||
specific coins that you have traded tens if not hundreds of times. We
|
||||
of course constantly aim to improve the bot but it will _always_ be a
|
||||
gamble, which should leave you with modest wins on monthly basis but
|
||||
you can't say much from few trades.
|
||||
|
||||
#### I’d like to change the stake amount. Can I just stop the bot with
|
||||
/stop and then change the config.json and run it again?
|
||||
#### I’d like to change the stake amount. Can I just stop the bot with /stop and then change the config.json and run it again?
|
||||
|
||||
Not quite. Trades are persisted to a database but the configuration is
|
||||
currently only read when the bot is killed and restarted. `/stop` more
|
||||
Not quite. Trades are persisted to a database but the configuration is
|
||||
currently only read when the bot is killed and restarted. `/stop` more
|
||||
like pauses. You can stop your bot, adjust settings and start it again.
|
||||
|
||||
#### I want to improve the bot with a new strategy
|
||||
|
||||
That's great. We have a nice backtesting and hyperoptimizing setup. See
|
||||
the tutorial [here|Testing-new-strategies-with-Hyperopt](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-usage.md#hyperopt-commands).
|
||||
That's great. We have a nice backtesting and hyperoptimizing setup. See
|
||||
the tutorial [here|Testing-new-strategies-with-Hyperopt](bot-usage.md#hyperopt-commands).
|
||||
|
||||
#### Is there a setting to only SELL the coins being held and not
|
||||
perform anymore BUYS?
|
||||
#### Is there a setting to only SELL the coins being held and not perform anymore BUYS?
|
||||
|
||||
You can use the `/forcesell all` command from Telegram.
|
||||
You can use the `/forcesell all` command from Telegram.
|
||||
|
||||
### How many epoch do I need to get a good Hyperopt result?
|
||||
Per default Hyperopts without `-e` or `--epochs` parameter will only
|
||||
run 100 epochs, means 100 evals of your triggers, guards, .... Too few
|
||||
to find a great result (unless if you are very lucky), so you probably
|
||||
have to run it for 10.000 or more. But it will take an eternity to
|
||||
### Hyperopt module
|
||||
|
||||
#### How many epoch do I need to get a good Hyperopt result?
|
||||
|
||||
Per default Hyperopts without `-e` or `--epochs` parameter will only
|
||||
run 100 epochs, means 100 evals of your triggers, guards, ... Too few
|
||||
to find a great result (unless if you are very lucky), so you probably
|
||||
have to run it for 10.000 or more. But it will take an eternity to
|
||||
compute.
|
||||
|
||||
We recommend you to run it at least 10.000 epochs:
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py hyperopt -e 10000
|
||||
python3 freqtrade hyperopt -e 10000
|
||||
```
|
||||
|
||||
or if you want intermediate result to see
|
||||
|
||||
```bash
|
||||
for i in {1..100}; do python3 ./freqtrade/main.py hyperopt -e 100; done
|
||||
for i in {1..100}; do python3 freqtrade hyperopt -e 100; done
|
||||
```
|
||||
|
||||
#### Why it is so long to run hyperopt?
|
||||
Finding a great Hyperopt results takes time.
|
||||
|
||||
Finding a great Hyperopt results takes time.
|
||||
|
||||
If you wonder why it takes a while to find great hyperopt results
|
||||
|
||||
This answer was written during the under the release 0.15.1, when we had
|
||||
:
|
||||
This answer was written during the under the release 0.15.1, when we had:
|
||||
|
||||
- 8 triggers
|
||||
- 9 guards: let's say we evaluate even 10 values from each
|
||||
- 1 stoploss calculation: let's say we want 10 values from that too to
|
||||
be evaluated
|
||||
- 1 stoploss calculation: let's say we want 10 values from that too to be evaluated
|
||||
|
||||
The following calculation is still very rough and not very precise
|
||||
but it will give the idea. With only these triggers and guards there is
|
||||
already 8*10^9*10 evaluations. A roughly total of 80 billion evals.
|
||||
Did you run 100 000 evals? Congrats, you've done roughly 1 / 100 000 th
|
||||
but it will give the idea. With only these triggers and guards there is
|
||||
already 8\*10^9\*10 evaluations. A roughly total of 80 billion evals.
|
||||
Did you run 100 000 evals? Congrats, you've done roughly 1 / 100 000 th
|
||||
of the search space.
|
||||
|
||||
### Edge module
|
||||
|
||||
#### Edge implements interesting approach for controlling position size, is there any theory behind it?
|
||||
|
||||
The Edge module is mostly a result of brainstorming of [@mishaker](https://github.com/mishaker) and [@creslinux](https://github.com/creslinux) freqtrade team members.
|
||||
|
||||
You can find further info on expectancy, winrate, risk management and position size in the following sources:
|
||||
- https://www.tradeciety.com/ultimate-math-guide-for-traders/
|
||||
- http://www.vantharp.com/tharp-concepts/expectancy.asp
|
||||
- https://samuraitradingacademy.com/trading-expectancy/
|
||||
- https://www.learningmarkets.com/determining-expectancy-in-your-trading/
|
||||
- http://www.lonestocktrader.com/make-money-trading-positive-expectancy/
|
||||
- https://www.babypips.com/trading/trade-expectancy-matter
|
||||
|
||||
183
docs/hyperopt.md
183
docs/hyperopt.md
@@ -1,69 +1,87 @@
|
||||
# Hyperopt
|
||||
|
||||
This page explains how to tune your strategy by finding the optimal
|
||||
parameters, a process called hyperparameter optimization. The bot uses several
|
||||
This page explains how to tune your strategy by finding the optimal
|
||||
parameters, a process called hyperparameter optimization. The bot uses several
|
||||
algorithms included in the `scikit-optimize` package to accomplish this. The
|
||||
search will burn all your CPU cores, make your laptop sound like a fighter jet
|
||||
and still take a long time.
|
||||
|
||||
*Note:* Hyperopt will crash when used with only 1 CPU Core as found out in [Issue #1133](https://github.com/freqtrade/freqtrade/issues/1133)
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Prepare your Hyperopt](#prepare-hyperopt)
|
||||
- [Configure your Guards and Triggers](#configure-your-guards-and-triggers)
|
||||
- [Solving a Mystery](#solving-a-mystery)
|
||||
- [Adding New Indicators](#adding-new-indicators)
|
||||
- [Execute Hyperopt](#execute-hyperopt)
|
||||
- [Understand the hyperopt result](#understand-the-hyperopt-result)
|
||||
!!! Bug
|
||||
Hyperopt will crash when used with only 1 CPU Core as found out in [Issue #1133](https://github.com/freqtrade/freqtrade/issues/1133)
|
||||
|
||||
## Prepare Hyperopting
|
||||
|
||||
Before we start digging in Hyperopt, we recommend you to take a look at
|
||||
an example hyperopt file located into [user_data/hyperopts/](https://github.com/gcarq/freqtrade/blob/develop/user_data/hyperopts/test_hyperopt.py)
|
||||
Before we start digging into Hyperopt, we recommend you to take a look at
|
||||
an example hyperopt file located into [user_data/hyperopts/](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/test_hyperopt.py)
|
||||
|
||||
Configuring hyperopt is similar to writing your own strategy, and many tasks will be similar and a lot of code can be copied across from the strategy.
|
||||
|
||||
### Checklist on all tasks / possibilities in hyperopt
|
||||
|
||||
Depending on the space you want to optimize, only some of the below are required.
|
||||
|
||||
* fill `populate_indicators` - probably a copy from your strategy
|
||||
* fill `buy_strategy_generator` - for buy signal optimization
|
||||
* fill `indicator_space` - for buy signal optimzation
|
||||
* fill `sell_strategy_generator` - for sell signal optimization
|
||||
* fill `sell_indicator_space` - for sell signal optimzation
|
||||
* fill `roi_space` - for ROI optimization
|
||||
* fill `generate_roi_table` - for ROI optimization (if you need more than 3 entries)
|
||||
* fill `stoploss_space` - stoploss optimization
|
||||
* Optional but recommended
|
||||
* copy `populate_buy_trend` from your strategy - otherwise default-strategy will be used
|
||||
* copy `populate_sell_trend` from your strategy - otherwise default-strategy will be used
|
||||
|
||||
### 1. Install a Custom Hyperopt File
|
||||
This is very simple. Put your hyperopt file into the folder
|
||||
`user_data/hyperopts`.
|
||||
|
||||
Let assume you want a hyperopt file `awesome_hyperopt.py`:
|
||||
1. Copy the file `user_data/hyperopts/sample_hyperopt.py` into `user_data/hyperopts/awesome_hyperopt.py`
|
||||
Put your hyperopt file into the folder`user_data/hyperopts`.
|
||||
|
||||
Let assume you want a hyperopt file `awesome_hyperopt.py`:
|
||||
Copy the file `user_data/hyperopts/sample_hyperopt.py` into `user_data/hyperopts/awesome_hyperopt.py`
|
||||
|
||||
|
||||
### 2. Configure your Guards and Triggers
|
||||
There are two places you need to change in your hyperopt file to add a
|
||||
new buy hyperopt for testing:
|
||||
- Inside [populate_buy_trend()](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/test_hyperopt.py#L230-L251).
|
||||
- Inside [indicator_space()](https://github.com/freqtrade/freqtrade/blob/develop/user_data/hyperopts/test_hyperopt.py#L207-L223).
|
||||
|
||||
There are two places you need to change in your hyperopt file to add a new buy hyperopt for testing:
|
||||
|
||||
- Inside `indicator_space()` - the parameters hyperopt shall be optimizing.
|
||||
- Inside `populate_buy_trend()` - applying the parameters.
|
||||
|
||||
There you have two different types of indicators: 1. `guards` and 2. `triggers`.
|
||||
|
||||
1. Guards are conditions like "never buy if ADX < 10", or never buy if
|
||||
current price is over EMA10.
|
||||
2. Triggers are ones that actually trigger buy in specific moment, like
|
||||
"buy when EMA5 crosses over EMA10" or "buy when close price touches lower
|
||||
bollinger band".
|
||||
1. Guards are conditions like "never buy if ADX < 10", or never buy if current price is over EMA10.
|
||||
2. Triggers are ones that actually trigger buy in specific moment, like "buy when EMA5 crosses over EMA10" or "buy when close price touches lower bollinger band".
|
||||
|
||||
Hyperoptimization will, for each eval round, pick one trigger and possibly
|
||||
multiple guards. The constructed strategy will be something like
|
||||
"*buy exactly when close price touches lower bollinger band, BUT only if
|
||||
Hyperoptimization will, for each eval round, pick one trigger and possibly
|
||||
multiple guards. The constructed strategy will be something like
|
||||
"*buy exactly when close price touches lower bollinger band, BUT only if
|
||||
ADX > 10*".
|
||||
|
||||
If you have updated the buy strategy, ie. changed the contents of
|
||||
`populate_buy_trend()` method you have to update the `guards` and
|
||||
`populate_buy_trend()` method you have to update the `guards` and
|
||||
`triggers` hyperopts must use.
|
||||
|
||||
#### Sell optimization
|
||||
|
||||
Similar to the buy-signal above, sell-signals can also be optimized.
|
||||
Place the corresponding settings into the following methods
|
||||
|
||||
* Inside `sell_indicator_space()` - the parameters hyperopt shall be optimizing.
|
||||
* Inside `populate_sell_trend()` - applying the parameters.
|
||||
|
||||
The configuration and rules are the same than for buy signals.
|
||||
To avoid naming collisions in the search-space, please prefix all sell-spaces with `sell-`.
|
||||
|
||||
## Solving a Mystery
|
||||
|
||||
Let's say you are curious: should you use MACD crossings or lower Bollinger
|
||||
Bands to trigger your buys. And you also wonder should you use RSI or ADX to
|
||||
help with those buy decisions. If you decide to use RSI or ADX, which values
|
||||
should I use for them? So let's use hyperparameter optimization to solve this
|
||||
Let's say you are curious: should you use MACD crossings or lower Bollinger
|
||||
Bands to trigger your buys. And you also wonder should you use RSI or ADX to
|
||||
help with those buy decisions. If you decide to use RSI or ADX, which values
|
||||
should I use for them? So let's use hyperparameter optimization to solve this
|
||||
mystery.
|
||||
|
||||
We will start by defining a search space:
|
||||
|
||||
```
|
||||
```python
|
||||
def indicator_space() -> List[Dimension]:
|
||||
"""
|
||||
Define your Hyperopt space for searching strategy parameters
|
||||
@@ -77,8 +95,8 @@ We will start by defining a search space:
|
||||
]
|
||||
```
|
||||
|
||||
Above definition says: I have five parameters I want you to randomly combine
|
||||
to find the best combination. Two of them are integer values (`adx-value`
|
||||
Above definition says: I have five parameters I want you to randomly combine
|
||||
to find the best combination. Two of them are integer values (`adx-value`
|
||||
and `rsi-value`) and I want you test in the range of values 20 to 40.
|
||||
Then we have three category variables. First two are either `True` or `False`.
|
||||
We use these to either enable or disable the ADX and RSI guards. The last
|
||||
@@ -86,7 +104,7 @@ one we call `trigger` and use it to decide which buy trigger we want to use.
|
||||
|
||||
So let's write the buy strategy using these values:
|
||||
|
||||
```
|
||||
``` python
|
||||
def populate_buy_trend(dataframe: DataFrame) -> DataFrame:
|
||||
conditions = []
|
||||
# GUARDS AND TRENDS
|
||||
@@ -96,12 +114,13 @@ So let's write the buy strategy using these values:
|
||||
conditions.append(dataframe['rsi'] < params['rsi-value'])
|
||||
|
||||
# TRIGGERS
|
||||
if params['trigger'] == 'bb_lower':
|
||||
conditions.append(dataframe['close'] < dataframe['bb_lowerband'])
|
||||
if params['trigger'] == 'macd_cross_signal':
|
||||
conditions.append(qtpylib.crossed_above(
|
||||
dataframe['macd'], dataframe['macdsignal']
|
||||
))
|
||||
if 'trigger' in params:
|
||||
if params['trigger'] == 'bb_lower':
|
||||
conditions.append(dataframe['close'] < dataframe['bb_lowerband'])
|
||||
if params['trigger'] == 'macd_cross_signal':
|
||||
conditions.append(qtpylib.crossed_above(
|
||||
dataframe['macd'], dataframe['macdsignal']
|
||||
))
|
||||
|
||||
dataframe.loc[
|
||||
reduce(lambda x, y: x & y, conditions),
|
||||
@@ -117,12 +136,12 @@ with different value combinations. It will then use the given historical data an
|
||||
buys based on the buy signals generated with the above function and based on the results
|
||||
it will end with telling you which paramter combination produced the best profits.
|
||||
|
||||
The search for best parameters starts with a few random combinations and then uses a
|
||||
The search for best parameters starts with a few random combinations and then uses a
|
||||
regressor algorithm (currently ExtraTreesRegressor) to quickly find a parameter combination
|
||||
that minimizes the value of the objective function `calculate_loss` in `hyperopt.py`.
|
||||
|
||||
The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators.
|
||||
When you want to test an indicator that isn't used by the bot currently, remember to
|
||||
When you want to test an indicator that isn't used by the bot currently, remember to
|
||||
add it to the `populate_indicators()` method in `hyperopt.py`.
|
||||
|
||||
## Execute Hyperopt
|
||||
@@ -133,15 +152,19 @@ Because hyperopt tries a lot of combinations to find the best parameters it will
|
||||
We strongly recommend to use `screen` or `tmux` to prevent any connection loss.
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py -s <strategyname> --hyperopt <hyperoptname> -c config.json hyperopt -e 5000
|
||||
python3 freqtrade -c config.json hyperopt --customhyperopt <hyperoptname> -e 5000 --spaces all
|
||||
```
|
||||
|
||||
Use `<strategyname>` and `<hyperoptname>` as the names of the custom strategy
|
||||
(only required for generating sells) and the custom hyperopt used.
|
||||
Use `<hyperoptname>` as the name of the custom hyperopt used.
|
||||
|
||||
The `-e` flag will set how many evaluations hyperopt will do. We recommend
|
||||
running at least several thousand evaluations.
|
||||
|
||||
The `--spaces all` flag determines that all possible parameters should be optimized. Possibilities are listed below.
|
||||
|
||||
!!! Warning
|
||||
When switching parameters or changing configuration options, the file `user_data/hyperopt_results.pickle` should be removed. It's used to be able to continue interrupted calculations, but does not detect changes to settings or the hyperopt file.
|
||||
|
||||
### Execute Hyperopt with Different Ticker-Data Source
|
||||
|
||||
If you would like to hyperopt parameters using an alternate ticker data that
|
||||
@@ -155,21 +178,22 @@ you want to use. The last N ticks/timeframes will be used.
|
||||
Example:
|
||||
|
||||
```bash
|
||||
python3 ./freqtrade/main.py hyperopt --timerange -200
|
||||
python3 freqtrade hyperopt --timerange -200
|
||||
```
|
||||
|
||||
### Running Hyperopt with Smaller Search Space
|
||||
|
||||
Use the `--spaces` argument to limit the search space used by hyperopt.
|
||||
Letting Hyperopt optimize everything is a huuuuge search space. Often it
|
||||
might make more sense to start by just searching for initial buy algorithm.
|
||||
Or maybe you just want to optimize your stoploss or roi table for that awesome
|
||||
Letting Hyperopt optimize everything is a huuuuge search space. Often it
|
||||
might make more sense to start by just searching for initial buy algorithm.
|
||||
Or maybe you just want to optimize your stoploss or roi table for that awesome
|
||||
new buy strategy you have.
|
||||
|
||||
Legal values are:
|
||||
|
||||
- `all`: optimize everything
|
||||
- `buy`: just search for a new buy strategy
|
||||
- `sell`: just search for a new sell strategy
|
||||
- `roi`: just optimize the minimal profit table for your strategy
|
||||
- `stoploss`: search for the best stoploss value
|
||||
- space-separated list of any of the above values for example `--spaces roi stoploss`
|
||||
@@ -183,25 +207,29 @@ Given the following result from hyperopt:
|
||||
Best result:
|
||||
135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins.
|
||||
with values:
|
||||
{'adx-value': 44, 'rsi-value': 29, 'adx-enabled': False, 'rsi-enabled': True, 'trigger': 'bb_lower'}
|
||||
{ 'adx-value': 44,
|
||||
'rsi-value': 29,
|
||||
'adx-enabled': False,
|
||||
'rsi-enabled': True,
|
||||
'trigger': 'bb_lower'}
|
||||
```
|
||||
|
||||
You should understand this result like:
|
||||
|
||||
- The buy trigger that worked best was `bb_lower`.
|
||||
- You should not use ADX because `adx-enabled: False`)
|
||||
- You should not use ADX because `adx-enabled: False`)
|
||||
- You should **consider** using the RSI indicator (`rsi-enabled: True` and the best value is `29.0` (`rsi-value: 29.0`)
|
||||
|
||||
You have to look inside your strategy file into `buy_strategy_generator()`
|
||||
You have to look inside your strategy file into `buy_strategy_generator()`
|
||||
method, what those values match to.
|
||||
|
||||
|
||||
So for example you had `rsi-value: 29.0` so we would look at `rsi`-block, that translates to the following code block:
|
||||
|
||||
```
|
||||
(dataframe['rsi'] < 29.0)
|
||||
```
|
||||
|
||||
Translating your whole hyperopt result as the new buy-signal
|
||||
|
||||
Translating your whole hyperopt result as the new buy-signal
|
||||
would then look like:
|
||||
|
||||
```python
|
||||
@@ -223,9 +251,24 @@ If you are optimizing ROI, you're result will look as follows and include a ROI
|
||||
Best result:
|
||||
135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins.
|
||||
with values:
|
||||
{'adx-value': 44, 'rsi-value': 29, 'adx-enabled': False, 'rsi-enabled': True, 'trigger': 'bb_lower', 'roi_t1': 40, 'roi_t2': 57, 'roi_t3': 21, 'roi_p1': 0.03634636907306948, 'roi_p2': 0.055237357937802885, 'roi_p3': 0.015163796015548354, 'stoploss': -0.37996664668703606}
|
||||
{ 'adx-value': 44,
|
||||
'rsi-value': 29,
|
||||
'adx-enabled': false,
|
||||
'rsi-enabled': True,
|
||||
'trigger': 'bb_lower',
|
||||
'roi_t1': 40,
|
||||
'roi_t2': 57,
|
||||
'roi_t3': 21,
|
||||
'roi_p1': 0.03634636907306948,
|
||||
'roi_p2': 0.055237357937802885,
|
||||
'roi_p3': 0.015163796015548354,
|
||||
'stoploss': -0.37996664668703606
|
||||
}
|
||||
ROI table:
|
||||
{0: 0.10674752302642071, 21: 0.09158372701087236, 78: 0.03634636907306948, 118: 0}
|
||||
{ 0: 0.10674752302642071,
|
||||
21: 0.09158372701087236,
|
||||
78: 0.03634636907306948,
|
||||
118: 0}
|
||||
```
|
||||
|
||||
This would translate to the following ROI table:
|
||||
@@ -242,12 +285,18 @@ This would translate to the following ROI table:
|
||||
### Validate backtest result
|
||||
|
||||
Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.
|
||||
To archive the same results (number of trades, ...) than during hyperopt, please use the command line flag `--disable-max-market-positions`.
|
||||
This setting is the default for hyperopt for speed reasons. You can overwrite this in the configuration by setting `"position_stacking"=false` or by changing the relevant line in your hyperopt file [here](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/optimize/hyperopt.py#L283).
|
||||
To archive the same results (number of trades, ...) than during hyperopt, please use the command line flags `--disable-max-market-positions` and `--enable-position-stacking` for backtesting.
|
||||
|
||||
Dry/live runs will **NOT** use position stacking - therefore it does make sense to also validate the strategy without this as it's closer to reality.
|
||||
This configuration is the default in hyperopt for performance reasons.
|
||||
|
||||
You can overwrite position stacking in the configuration by explicitly setting `"position_stacking"=false` or by changing the relevant line in your hyperopt file [here](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/optimize/hyperopt.py#L191).
|
||||
|
||||
Enabling the market-position for hyperopt is currently not possible.
|
||||
|
||||
!!! Note
|
||||
Dry/live runs will **NOT** use position stacking - therefore it does make sense to also validate the strategy without this as it's closer to reality.
|
||||
|
||||
## Next Step
|
||||
|
||||
Now you have a perfect bot and want to control it from Telegram. Your
|
||||
next step is to learn the [Telegram usage](https://github.com/freqtrade/freqtrade/blob/develop/docs/telegram-usage.md).
|
||||
next step is to learn the [Telegram usage](telegram-usage.md).
|
||||
|
||||
BIN
docs/images/logo.png
Normal file
BIN
docs/images/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
100
docs/index.md
100
docs/index.md
@@ -1,39 +1,67 @@
|
||||
# freqtrade documentation
|
||||
# Freqtrade
|
||||
[](https://travis-ci.org/freqtrade/freqtrade)
|
||||
[](https://coveralls.io/github/freqtrade/freqtrade?branch=develop)
|
||||
[](https://codeclimate.com/github/freqtrade/freqtrade/maintainability)
|
||||
|
||||
Welcome to freqtrade documentation. Please feel free to contribute to
|
||||
this documentation if you see it became outdated by sending us a
|
||||
Pull-request. Do not hesitate to reach us on
|
||||
[Slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE)
|
||||
if you do not find the answer to your questions.
|
||||
<!-- Place this tag where you want the button to render. -->
|
||||
<a class="github-button" href="https://github.com/freqtrade/freqtrade" data-icon="octicon-star" data-size="large" aria-label="Star freqtrade/freqtrade on GitHub">Star</a>
|
||||
<!-- Place this tag where you want the button to render. -->
|
||||
<a class="github-button" href="https://github.com/freqtrade/freqtrade/fork" data-icon="octicon-repo-forked" data-size="large" aria-label="Fork freqtrade/freqtrade on GitHub">Fork</a>
|
||||
<!-- Place this tag where you want the button to render. -->
|
||||
<a class="github-button" href="https://github.com/freqtrade/freqtrade/archive/master.zip" data-icon="octicon-cloud-download" data-size="large" aria-label="Download freqtrade/freqtrade on GitHub">Download</a>
|
||||
<!-- Place this tag where you want the button to render. -->
|
||||
<a class="github-button" href="https://github.com/freqtrade" data-size="large" aria-label="Follow @freqtrade on GitHub">Follow @freqtrade</a>
|
||||
## Introduction
|
||||
Freqtrade is a cryptocurrency trading bot written in Python.
|
||||
|
||||
## Table of Contents
|
||||
!!! Danger "DISCLAIMER"
|
||||
This software is for educational purposes only. Do not risk money which you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.
|
||||
|
||||
- [Pre-requisite](https://github.com/freqtrade/freqtrade/blob/develop/docs/pre-requisite.md)
|
||||
- [Setup your Bittrex account](https://github.com/freqtrade/freqtrade/blob/develop/docs/pre-requisite.md#setup-your-bittrex-account)
|
||||
- [Setup your Telegram bot](https://github.com/freqtrade/freqtrade/blob/develop/docs/pre-requisite.md#setup-your-telegram-bot)
|
||||
- [Bot Installation](https://github.com/freqtrade/freqtrade/blob/develop/docs/installation.md)
|
||||
- [Install with Docker (all platforms)](https://github.com/freqtrade/freqtrade/blob/develop/docs/installation.md#docker)
|
||||
- [Install on Linux Ubuntu](https://github.com/freqtrade/freqtrade/blob/develop/docs/installation.md#21-linux---ubuntu-1604)
|
||||
- [Install on MacOS](https://github.com/freqtrade/freqtrade/blob/develop/docs/installation.md#23-macos-installation)
|
||||
- [Install on Windows](https://github.com/freqtrade/freqtrade/blob/develop/docs/installation.md#windows)
|
||||
- [Bot Configuration](https://github.com/freqtrade/freqtrade/blob/develop/docs/configuration.md)
|
||||
- [Bot usage (Start your bot)](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-usage.md)
|
||||
- [Bot commands](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-usage.md#bot-commands)
|
||||
- [Backtesting commands](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-usage.md#backtesting-commands)
|
||||
- [Hyperopt commands](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-usage.md#hyperopt-commands)
|
||||
- [Edge commands](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-usage.md#edge-commands)
|
||||
- [Bot Optimization](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-optimization.md)
|
||||
- [Change your strategy](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-optimization.md#change-your-strategy)
|
||||
- [Add more Indicator](https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-optimization.md#add-more-indicator)
|
||||
- [Test your strategy with Backtesting](https://github.com/freqtrade/freqtrade/blob/develop/docs/backtesting.md)
|
||||
- [Edge positioning](https://github.com/freqtrade/freqtrade/blob/develop/docs/edge.md)
|
||||
- [Find optimal parameters with Hyperopt](https://github.com/freqtrade/freqtrade/blob/develop/docs/hyperopt.md)
|
||||
- [Control the bot with telegram](https://github.com/freqtrade/freqtrade/blob/develop/docs/telegram-usage.md)
|
||||
- [Receive notifications via webhook](https://github.com/freqtrade/freqtrade/blob/develop/docs/webhook-config.md)
|
||||
- [Contribute to the project](https://github.com/freqtrade/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||
- [How to contribute](https://github.com/freqtrade/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||
- [Run tests & Check PEP8 compliance](https://github.com/freqtrade/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||
- [FAQ](https://github.com/freqtrade/freqtrade/blob/develop/docs/faq.md)
|
||||
- [SQL cheatsheet](https://github.com/freqtrade/freqtrade/blob/develop/docs/sql_cheatsheet.md)
|
||||
- [Sandbox Testing](https://github.com/freqtrade/freqtrade/blob/develop/docs/sandbox-testing.md)
|
||||
- [Developer Docs](https://github.com/freqtrade/freqtrade/blob/develop/docs/developer.md)
|
||||
Always start by running a trading bot in Dry-run and do not engage money before you understand how it works and what profit/loss you should expect.
|
||||
|
||||
We strongly recommend you to have basic coding skills and Python knowledge. Do not hesitate to read the source code and understand the mechanisms of this bot, algorithms and techniques implemented in it.
|
||||
|
||||
|
||||
## Features
|
||||
- Based on Python 3.6+: For botting on any operating system — Windows, macOS and Linux.
|
||||
- Persistence: Persistence is achieved through sqlite database.
|
||||
- Dry-run mode: Run the bot without playing money.
|
||||
- Backtesting: Run a simulation of your buy/sell strategy with historical data.
|
||||
- Strategy Optimization by machine learning: Use machine learning to optimize your buy/sell strategy parameters with real exchange data.
|
||||
- Edge position sizing: Calculate your win rate, risk reward ratio, the best stoploss and adjust your position size before taking a position for each specific market.
|
||||
- Whitelist crypto-currencies: Select which crypto-currency you want to trade or use dynamic whitelists based on market (pair) trade volume.
|
||||
- Blacklist crypto-currencies: Select which crypto-currency you want to avoid.
|
||||
- Manageable via Telegram: Manage the bot with Telegram.
|
||||
- Display profit/loss in fiat: Display your profit/loss in any of 33 fiat currencies supported.
|
||||
- Daily summary of profit/loss: Receive the daily summary of your profit/loss.
|
||||
- Performance status report: Receive the performance status of your current trades.
|
||||
|
||||
|
||||
## Requirements
|
||||
### Up to date clock
|
||||
The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges.
|
||||
|
||||
### Hardware requirements
|
||||
To run this bot we recommend you a cloud instance with a minimum of:
|
||||
|
||||
- 2GB RAM
|
||||
- 1GB disk space
|
||||
- 2vCPU
|
||||
|
||||
### Software requirements
|
||||
- Python 3.6.x
|
||||
- pip (pip3)
|
||||
- git
|
||||
- TA-Lib
|
||||
- virtualenv (Recommended)
|
||||
- Docker (Recommended)
|
||||
|
||||
|
||||
## Support
|
||||
Help / Slack
|
||||
For any questions not covered by the documentation or for further information about the bot, we encourage you to join our Slack channel.
|
||||
|
||||
Click [here](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE) to join Slack channel.
|
||||
|
||||
## Ready to try?
|
||||
Begin by reading our installation guide [here](installation).
|
||||
|
||||
@@ -1,25 +1,69 @@
|
||||
# Installation
|
||||
|
||||
This page explains how to prepare your environment for running the bot.
|
||||
|
||||
To understand how to set up the bot please read the [Bot Configuration](https://github.com/freqtrade/freqtrade/blob/develop/docs/configuration.md) page.
|
||||
## Prerequisite
|
||||
Before running your bot in production you will need to setup few
|
||||
external API. In production mode, the bot required valid Bittrex API
|
||||
credentials and a Telegram bot (optional but recommended).
|
||||
|
||||
## Table of Contents
|
||||
- [Setup your exchange account](#setup-your-exchange-account)
|
||||
- [Backtesting commands](#setup-your-telegram-bot)
|
||||
|
||||
* [Table of Contents](#table-of-contents)
|
||||
* [Easy Installation - Linux Script](#easy-installation---linux-script)
|
||||
* [Automatic Installation - Docker](#automatic-installation---docker)
|
||||
* [Custom Linux MacOS Installation](#custom-installation)
|
||||
- [Requirements](#requirements)
|
||||
- [Linux - Ubuntu 16.04](#linux---ubuntu-1604)
|
||||
- [MacOS](#macos)
|
||||
- [Setup Config and virtual env](#setup-config-and-virtual-env)
|
||||
* [Windows](#windows)
|
||||
### Setup your exchange account
|
||||
*To be completed, please feel free to complete this section.*
|
||||
|
||||
<!-- /TOC -->
|
||||
### Setup your Telegram bot
|
||||
The only things you need is a working Telegram bot and its API token.
|
||||
Below we explain how to create your Telegram Bot, and how to get your
|
||||
Telegram user id.
|
||||
|
||||
------
|
||||
### 1. Create your Telegram bot
|
||||
|
||||
**1.1. Start a chat with https://telegram.me/BotFather**
|
||||
|
||||
**1.2. Send the message `/newbot`. ** *BotFather response:*
|
||||
```
|
||||
Alright, a new bot. How are we going to call it? Please choose a name for your bot.
|
||||
```
|
||||
|
||||
**1.3. Choose the public name of your bot (e.x. `Freqtrade bot`)**
|
||||
*BotFather response:*
|
||||
```
|
||||
Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.
|
||||
```
|
||||
**1.4. Choose the name id of your bot (e.x "`My_own_freqtrade_bot`")**
|
||||
|
||||
**1.5. Father bot will return you the token (API key)**<br/>
|
||||
Copy it and keep it you will use it for the config parameter `token`.
|
||||
*BotFather response:*
|
||||
```hl_lines="4"
|
||||
Done! Congratulations on your new bot. You will find it at t.me/My_own_freqtrade_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.
|
||||
|
||||
Use this token to access the HTTP API:
|
||||
521095879:AAEcEZEL7ADJ56FtG_qD0bQJSKETbXCBCi0
|
||||
|
||||
For a description of the Bot API, see this page: https://core.telegram.org/bots/api
|
||||
```
|
||||
**1.6. Don't forget to start the conversation with your bot, by clicking /START button**
|
||||
|
||||
### 2. Get your user id
|
||||
**2.1. Talk to https://telegram.me/userinfobot**
|
||||
|
||||
**2.2. Get your "Id", you will use it for the config parameter
|
||||
`chat_id`.**
|
||||
<hr/>
|
||||
## Quick start
|
||||
Freqtrade provides a Linux/MacOS script to install all dependencies and help you to configure the bot.
|
||||
|
||||
```bash
|
||||
git clone git@github.com:freqtrade/freqtrade.git
|
||||
cd freqtrade
|
||||
git checkout develop
|
||||
./setup.sh --install
|
||||
```
|
||||
!!! Note
|
||||
Windows installation is explained [here](#windows).
|
||||
<hr/>
|
||||
## Easy Installation - Linux Script
|
||||
|
||||
If you are on Debian, Ubuntu or MacOS a freqtrade provides a script to Install, Update, Configure, and Reset your bot.
|
||||
@@ -33,7 +77,7 @@ usage:
|
||||
-c,--config Easy config generator (Will override your existing file).
|
||||
```
|
||||
|
||||
### --install
|
||||
** --install **
|
||||
|
||||
This script will install everything you need to run the bot:
|
||||
|
||||
@@ -43,15 +87,15 @@ This script will install everything you need to run the bot:
|
||||
|
||||
This script is a combination of `install script` `--reset`, `--config`
|
||||
|
||||
### --update
|
||||
** --update **
|
||||
|
||||
Update parameter will pull the last version of your current branch and update your virtualenv.
|
||||
|
||||
### --reset
|
||||
** --reset **
|
||||
|
||||
Reset parameter will hard reset your branch (only if you are on `master` or `develop`) and recreate your virtualenv.
|
||||
|
||||
### --config
|
||||
** --config **
|
||||
|
||||
Config parameter is a `config.json` configurator. This script will ask you questions to setup your bot and create your `config.json`.
|
||||
|
||||
@@ -69,33 +113,39 @@ Once you have Docker installed, simply create the config file (e.g. `config.json
|
||||
|
||||
### 1. Prepare the Bot
|
||||
|
||||
#### 1.1. Clone the git repository
|
||||
**1.1. Clone the git repository**
|
||||
|
||||
Linux/Mac/Windows with WSL
|
||||
```bash
|
||||
git clone https://github.com/freqtrade/freqtrade.git
|
||||
```
|
||||
|
||||
#### 1.2. (Optional) Checkout the develop branch
|
||||
Windows with docker
|
||||
```bash
|
||||
git clone --config core.autocrlf=input https://github.com/freqtrade/freqtrade.git
|
||||
```
|
||||
|
||||
**1.2. (Optional) Checkout the develop branch**
|
||||
|
||||
```bash
|
||||
git checkout develop
|
||||
```
|
||||
|
||||
#### 1.3. Go into the new directory
|
||||
**1.3. Go into the new directory**
|
||||
|
||||
```bash
|
||||
cd freqtrade
|
||||
```
|
||||
|
||||
#### 1.4. Copy `config.json.example` to `config.json`
|
||||
**1.4. Copy `config.json.example` to `config.json`**
|
||||
|
||||
```bash
|
||||
cp -n config.json.example config.json
|
||||
```
|
||||
|
||||
> To edit the config please refer to the [Bot Configuration](https://github.com/freqtrade/freqtrade/blob/develop/docs/configuration.md) page.
|
||||
> To edit the config please refer to the [Bot Configuration](configuration.md) page.
|
||||
|
||||
#### 1.5. Create your database file *(optional - the bot will create it if it is missing)*
|
||||
**1.5. Create your database file *(optional - the bot will create it if it is missing)**
|
||||
|
||||
Production
|
||||
|
||||
@@ -115,7 +165,7 @@ Either use the prebuilt image from docker hub - or build the image yourself if y
|
||||
|
||||
Branches / tags available can be checked out on [Dockerhub](https://hub.docker.com/r/freqtradeorg/freqtrade/tags/).
|
||||
|
||||
#### 2.1. Download the docker image
|
||||
**2.1. Download the docker image**
|
||||
|
||||
Pull the image from docker hub and (optionally) change the name of the image
|
||||
|
||||
@@ -127,7 +177,7 @@ docker tag freqtradeorg/freqtrade:develop freqtrade
|
||||
|
||||
To update the image, simply run the above commands again and restart your running container.
|
||||
|
||||
#### 2.2. Build the Docker image
|
||||
**2.2. Build the Docker image**
|
||||
|
||||
```bash
|
||||
cd freqtrade
|
||||
@@ -164,7 +214,7 @@ There is known issue in OSX Docker versions after 17.09.1, whereby /etc/localtim
|
||||
docker run --rm -e TZ=`ls -la /etc/localtime | cut -d/ -f8-9` -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
||||
```
|
||||
|
||||
More information on this docker issue and work-around can be read [here](https://github.com/docker/for-mac/issues/2396)
|
||||
More information on this docker issue and work-around can be read [here](https://github.com/docker/for-mac/issues/2396).
|
||||
|
||||
In this example, the database will be created inside the docker instance and will be lost when you will refresh your image.
|
||||
|
||||
@@ -172,7 +222,7 @@ In this example, the database will be created inside the docker instance and wil
|
||||
|
||||
To run a restartable instance in the background (feel free to place your configuration and database files wherever it feels comfortable on your filesystem).
|
||||
|
||||
#### 5.1. Move your config file and database
|
||||
**5.1. Move your config file and database**
|
||||
|
||||
```bash
|
||||
mkdir ~/.freqtrade
|
||||
@@ -180,7 +230,7 @@ mv config.json ~/.freqtrade
|
||||
mv tradesv3.sqlite ~/.freqtrade
|
||||
```
|
||||
|
||||
#### 5.2. Run the docker image
|
||||
**5.2. Run the docker image**
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
@@ -191,8 +241,9 @@ docker run -d \
|
||||
freqtrade --db-url sqlite:///tradesv3.sqlite
|
||||
```
|
||||
|
||||
*Note*: db-url defaults to `sqlite:///tradesv3.sqlite` but it defaults to `sqlite://` if `dry_run=True` is being used.
|
||||
To override this behaviour use a custom db-url value: i.e.: `--db-url sqlite:///tradesv3.dryrun.sqlite`
|
||||
!!! Note
|
||||
db-url defaults to `sqlite:///tradesv3.sqlite` but it defaults to `sqlite://` if `dry_run=True` is being used.
|
||||
To override this behaviour use a custom db-url value: i.e.: `--db-url sqlite:///tradesv3.dryrun.sqlite`
|
||||
|
||||
### 6. Monitor your Docker instance
|
||||
|
||||
@@ -208,14 +259,15 @@ docker start freqtrade
|
||||
|
||||
For more information on how to operate Docker, please refer to the [official Docker documentation](https://docs.docker.com/).
|
||||
|
||||
*Note*: You do not need to rebuild the image for configuration changes, it will suffice to edit `config.json` and restart the container.
|
||||
!!! Note
|
||||
You do not need to rebuild the image for configuration changes, it will suffice to edit `config.json` and restart the container.
|
||||
|
||||
### 7. Backtest with docker
|
||||
|
||||
The following assumes that the above steps (1-4) have been completed successfully.
|
||||
Also, backtest-data should be available at `~/.freqtrade/user_data/`.
|
||||
|
||||
``` bash
|
||||
```bash
|
||||
docker run -d \
|
||||
--name freqtrade \
|
||||
-v /etc/localtime:/etc/localtime:ro \
|
||||
@@ -225,16 +277,17 @@ docker run -d \
|
||||
freqtrade --strategy AwsomelyProfitableStrategy backtesting
|
||||
```
|
||||
|
||||
Head over to the [Backtesting Documentation](https://github.com/freqtrade/freqtrade/blob/develop/docs/backtesting.md) for more details.
|
||||
Head over to the [Backtesting Documentation](backtesting.md) for more details.
|
||||
|
||||
*Note*: Additional parameters can be appended after the image name (`freqtrade` in the above example).
|
||||
!!! Note
|
||||
Additional parameters can be appended after the image name (`freqtrade` in the above example).
|
||||
|
||||
------
|
||||
|
||||
## Custom Installation
|
||||
|
||||
We've included/collected install instructions for Ubuntu 16.04, MacOS, and Windows. These are guidelines and your success may vary with other distros.
|
||||
OS Specific steps are listed first, the [common](#common) section below is necessary for all systems.
|
||||
OS Specific steps are listed first, the [Common](#common) section below is necessary for all systems.
|
||||
|
||||
### Requirements
|
||||
|
||||
@@ -262,7 +315,6 @@ Before installing FreqTrade on a Raspberry Pi running the official Raspbian Imag
|
||||
|
||||
The following assumes that miniconda3 is installed and available in your environment. Last miniconda3 installation file use python 3.4, we will update to python 3.6 on this installation.
|
||||
It's recommended to use (mini)conda for this as installation/compilation of `numpy`, `scipy` and `pandas` takes a long time.
|
||||
If you have installed it from (mini)conda, you can remove `numpy`, `scipy`, and `pandas` from `requirements.txt` before you install it with `pip`.
|
||||
|
||||
Additional package to install on your Raspbian, `libffi-dev` required by cryptography (from python-telegram-bot).
|
||||
|
||||
@@ -274,7 +326,7 @@ conda activate freqtrade
|
||||
conda install scipy pandas numpy
|
||||
|
||||
sudo apt install libffi-dev
|
||||
python3 -m pip install -r requirements.txt
|
||||
python3 -m pip install -r requirements-pi.txt
|
||||
python3 -m pip install -e .
|
||||
```
|
||||
|
||||
@@ -286,7 +338,7 @@ python3 -m pip install -e .
|
||||
brew install python3 git wget
|
||||
```
|
||||
|
||||
### common
|
||||
### Common
|
||||
|
||||
#### 1. Install TA-Lib
|
||||
|
||||
@@ -304,11 +356,13 @@ cd ..
|
||||
rm -rf ./ta-lib*
|
||||
```
|
||||
|
||||
*Note*: An already downloaded version of ta-lib is included in the repository, as the sourceforge.net source seems to have problems frequently.
|
||||
!!! Note
|
||||
An already downloaded version of ta-lib is included in the repository, as the sourceforge.net source seems to have problems frequently.
|
||||
|
||||
#### 2. Setup your Python virtual environment (virtualenv)
|
||||
|
||||
*Note*: This step is optional but strongly recommended to keep your system organized
|
||||
!!! Note
|
||||
This step is optional but strongly recommended to keep your system organized
|
||||
|
||||
```bash
|
||||
python3 -m venv .env
|
||||
@@ -337,7 +391,7 @@ cd freqtrade
|
||||
cp config.json.example config.json
|
||||
```
|
||||
|
||||
> *To edit the config please refer to [Bot Configuration](https://github.com/freqtrade/freqtrade/blob/develop/docs/configuration.md).*
|
||||
> *To edit the config please refer to [Bot Configuration](configuration.md).*
|
||||
|
||||
#### 5. Install python dependencies
|
||||
|
||||
@@ -352,7 +406,7 @@ pip3 install -e .
|
||||
If this is the first time you run the bot, ensure you are running it in Dry-run `"dry_run": true,` otherwise it will start to buy and sell coins.
|
||||
|
||||
```bash
|
||||
python3.6 ./freqtrade/main.py -c config.json
|
||||
python3.6 freqtrade -c config.json
|
||||
```
|
||||
|
||||
*Note*: If you run the bot on a server, you should consider using [Docker](#automatic-installation---docker) a terminal multiplexer like `screen` or [`tmux`](https://en.wikipedia.org/wiki/Tmux) to avoid that the bot is stopped on logout.
|
||||
@@ -373,6 +427,19 @@ For this to be persistent (run when user is logged out) you'll need to enable `l
|
||||
sudo loginctl enable-linger "$USER"
|
||||
```
|
||||
|
||||
If you run the bot as a service, you can use systemd service manager as a software watchdog monitoring freqtrade bot
|
||||
state and restarting it in the case of failures. If the `internals.sd_notify` parameter is set to true in the
|
||||
configuration or the `--sd-notify` command line option is used, the bot will send keep-alive ping messages to systemd
|
||||
using the sd_notify (systemd notifications) protocol and will also tell systemd its current state (Running or Stopped)
|
||||
when it changes.
|
||||
|
||||
The `freqtrade.service.watchdog` file contains an example of the service unit configuration file which uses systemd
|
||||
as the watchdog.
|
||||
|
||||
!!! Note
|
||||
The sd_notify communication between the bot and the systemd service manager will not work if the bot runs in a
|
||||
Docker container.
|
||||
|
||||
------
|
||||
|
||||
## Windows
|
||||
@@ -396,7 +463,7 @@ copy paste `config.json` to ``\path\freqtrade-develop\freqtrade`
|
||||
|
||||
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 inofficial precompiled windows Wheels [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib), which needs to be downloaded and installed using `pip install TA_Lib‑0.4.17‑cp36‑cp36m‑win32.whl` (make sure to use the version matching your python version)
|
||||
As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial precompiled windows Wheels [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib), which needs to be downloaded and installed using `pip install TA_Lib‑0.4.17‑cp36‑cp36m‑win32.whl` (make sure to use the version matching your python version)
|
||||
|
||||
```cmd
|
||||
>cd \path\freqtrade-develop
|
||||
@@ -426,4 +493,4 @@ The easiest way is to download install Microsoft Visual Studio Community [here](
|
||||
---
|
||||
|
||||
Now you have an environment ready, the next step is
|
||||
[Bot Configuration](https://github.com/freqtrade/freqtrade/blob/develop/docs/configuration.md)...
|
||||
[Bot Configuration](configuration.md).
|
||||
|
||||
52
docs/partials/header.html
Normal file
52
docs/partials/header.html
Normal file
@@ -0,0 +1,52 @@
|
||||
<header class="md-header" data-md-component="header">
|
||||
<nav class="md-header-nav md-grid">
|
||||
<div class="md-flex">
|
||||
<div class="md-flex__cell md-flex__cell--shrink">
|
||||
<a href="{{ config.site_url | default(nav.homepage.url, true) | url }}" title="{{ config.site_name }}"
|
||||
class="md-header-nav__button md-logo">
|
||||
{% if config.theme.logo.icon %}
|
||||
<i class="md-icon">{{ config.theme.logo.icon }}</i>
|
||||
{% else %}
|
||||
<img src="{{ config.theme.logo | url }}" width="24" height="24">
|
||||
{% endif %}
|
||||
</a>
|
||||
</div>
|
||||
<div class="md-flex__cell md-flex__cell--shrink">
|
||||
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
|
||||
</div>
|
||||
<div class="md-flex__cell md-flex__cell--stretch">
|
||||
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
|
||||
{% block site_name %}
|
||||
{% if config.site_name == page.title %}
|
||||
{{ config.site_name }}
|
||||
{% else %}
|
||||
<span class="md-header-nav__topic">
|
||||
{{ config.site_name }}
|
||||
</span>
|
||||
<span class="md-header-nav__topic">
|
||||
{{ page.title }}
|
||||
</span>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="md-flex__cell md-flex__cell--shrink">
|
||||
{% block search_box %}
|
||||
{% if "search" in config["plugins"] %}
|
||||
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
|
||||
{% include "partials/search.html" %}
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
</div>
|
||||
{% if config.repo_url %}
|
||||
<div class="md-flex__cell md-flex__cell--shrink">
|
||||
<div class="md-header-nav__source">
|
||||
{% include "partials/source.html" %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</nav>
|
||||
<!-- Place this tag in your head or just before your close body tag. -->
|
||||
<script async defer src="https://buttons.github.io/buttons.js"></script>
|
||||
</header>
|
||||
@@ -1,10 +1,6 @@
|
||||
# Plotting
|
||||
This page explains how to plot prices, indicator, profits.
|
||||
|
||||
## Table of Contents
|
||||
- [Plot price and indicators](#plot-price-and-indicators)
|
||||
- [Plot profit](#plot-profit)
|
||||
|
||||
## Installation
|
||||
|
||||
Plotting scripts use Plotly library. Install/upgrade it with:
|
||||
@@ -19,7 +15,7 @@ At least version 2.3.0 is required.
|
||||
Usage for the price plotter:
|
||||
|
||||
```
|
||||
script/plot_dataframe.py [-h] [-p pair] [--live]
|
||||
script/plot_dataframe.py [-h] [-p pairs] [--live]
|
||||
```
|
||||
|
||||
Example
|
||||
@@ -27,11 +23,16 @@ Example
|
||||
python scripts/plot_dataframe.py -p BTC/ETH
|
||||
```
|
||||
|
||||
The `-p` pair argument, can be used to specify what
|
||||
pair you would like to plot.
|
||||
The `-p` pairs argument, can be used to specify
|
||||
pairs you would like to plot.
|
||||
|
||||
**Advanced use**
|
||||
|
||||
To plot multiple pairs, separate them with a comma:
|
||||
```
|
||||
python scripts/plot_dataframe.py -p BTC/ETH,XRP/ETH
|
||||
```
|
||||
|
||||
To plot the current live price use the `--live` flag:
|
||||
```
|
||||
python scripts/plot_dataframe.py -p BTC/ETH --live
|
||||
@@ -48,7 +49,7 @@ To plot trades stored in a database use `--db-url` argument:
|
||||
python scripts/plot_dataframe.py --db-url sqlite:///tradesv3.dry_run.sqlite -p BTC/ETH
|
||||
```
|
||||
|
||||
To plot a test strategy the strategy should have first be backtested.
|
||||
To plot a test strategy the strategy should have first be backtested.
|
||||
The results may then be plotted with the -s argument:
|
||||
```
|
||||
python scripts/plot_dataframe.py -s Strategy_Name -p BTC/ETH --datadir user_data/data/<exchange_name>/
|
||||
@@ -83,5 +84,5 @@ The `-p` pair argument, can be used to plot a single pair
|
||||
|
||||
Example
|
||||
```
|
||||
python3 scripts/plot_profit.py --datadir ../freqtrade/freqtrade/tests/testdata-20171221/ -p BTC_LTC
|
||||
python3 scripts/plot_profit.py --datadir ../freqtrade/freqtrade/tests/testdata-20171221/ -p LTC/BTC
|
||||
```
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
# Pre-requisite
|
||||
Before running your bot in production you will need to setup few
|
||||
external API. In production mode, the bot required valid Bittrex API
|
||||
credentials and a Telegram bot (optional but recommended).
|
||||
|
||||
## Table of Contents
|
||||
- [Setup your Bittrex account](#setup-your-bittrex-account)
|
||||
- [Backtesting commands](#setup-your-telegram-bot)
|
||||
|
||||
## Setup your Bittrex account
|
||||
*To be completed, please feel free to complete this section.*
|
||||
|
||||
## Setup your Telegram bot
|
||||
The only things you need is a working Telegram bot and its API token.
|
||||
Below we explain how to create your Telegram Bot, and how to get your
|
||||
Telegram user id.
|
||||
|
||||
### 1. Create your Telegram bot
|
||||
**1.1. Start a chat with https://telegram.me/BotFather**
|
||||
**1.2. Send the message** `/newbot`
|
||||
*BotFather response:*
|
||||
```
|
||||
Alright, a new bot. How are we going to call it? Please choose a name for your bot.
|
||||
```
|
||||
**1.3. Choose the public name of your bot (e.g "`Freqtrade bot`")**
|
||||
*BotFather response:*
|
||||
```
|
||||
Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.
|
||||
```
|
||||
**1.4. Choose the name id of your bot (e.g "`My_own_freqtrade_bot`")**
|
||||
**1.5. Father bot will return you the token (API key)**
|
||||
Copy it and keep it you will use it for the config parameter `token`.
|
||||
*BotFather response:*
|
||||
```
|
||||
Done! Congratulations on your new bot. You will find it at t.me/My_own_freqtrade_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.
|
||||
|
||||
Use this token to access the HTTP API:
|
||||
521095879:AAEcEZEL7ADJ56FtG_qD0bQJSKETbXCBCi0
|
||||
|
||||
For a description of the Bot API, see this page: https://core.telegram.org/bots/api
|
||||
```
|
||||
**1.6. Don't forget to start the conversation with your bot, by clicking /START button**
|
||||
|
||||
### 2. Get your user id
|
||||
**2.1. Talk to https://telegram.me/userinfobot**
|
||||
**2.2. Get your "Id", you will use it for the config parameter
|
||||
`chat_id`.**
|
||||
|
||||
1
docs/requirements-docs.txt
Normal file
1
docs/requirements-docs.txt
Normal file
@@ -0,0 +1 @@
|
||||
mkdocs-material==3.1.0
|
||||
@@ -1,5 +1,5 @@
|
||||
# SQL Helper
|
||||
This page constains some help if you want to edit your sqlite db.
|
||||
This page contains some help if you want to edit your sqlite db.
|
||||
|
||||
## Install sqlite3
|
||||
**Ubuntu/Debian installation**
|
||||
@@ -44,6 +44,14 @@ CREATE TABLE trades (
|
||||
open_date DATETIME NOT NULL,
|
||||
close_date DATETIME,
|
||||
open_order_id VARCHAR,
|
||||
stop_loss FLOAT,
|
||||
initial_stop_loss FLOAT,
|
||||
stoploss_order_id VARCHAR,
|
||||
stoploss_last_update DATETIME,
|
||||
max_rate FLOAT,
|
||||
sell_reason VARCHAR,
|
||||
strategy VARCHAR,
|
||||
ticker_interval INTEGER,
|
||||
PRIMARY KEY (id),
|
||||
CHECK (is_open IN (0, 1))
|
||||
);
|
||||
@@ -55,38 +63,45 @@ CREATE TABLE trades (
|
||||
SELECT * FROM trades;
|
||||
```
|
||||
|
||||
## Fix trade still open after a /forcesell
|
||||
## Fix trade still open after a manual sell on the exchange
|
||||
|
||||
!!! Warning
|
||||
Manually selling a pair on the exchange will not be detected by the bot and it will try to sell anyway. Whenever possible, forcesell <tradeid> should be used to accomplish the same thing.
|
||||
It is strongly advised to backup your database file before making any manual changes.
|
||||
|
||||
!!! Note
|
||||
This should not be necessary after /forcesell, as forcesell orders are closed automatically by the bot on the next iteration.
|
||||
|
||||
```sql
|
||||
UPDATE trades
|
||||
SET is_open=0, close_date=<close_date>, close_rate=<close_rate>, close_profit=close_rate/open_rate-1
|
||||
SET is_open=0, close_date=<close_date>, close_rate=<close_rate>, close_profit=close_rate/open_rate-1, sell_reason=<sell_reason>
|
||||
WHERE id=<trade_ID_to_update>;
|
||||
```
|
||||
|
||||
**Example:**
|
||||
##### Example
|
||||
|
||||
```sql
|
||||
UPDATE trades
|
||||
SET is_open=0, close_date='2017-12-20 03:08:45.103418', close_rate=0.19638016, close_profit=0.0496
|
||||
SET is_open=0, close_date='2017-12-20 03:08:45.103418', close_rate=0.19638016, close_profit=0.0496, sell_reason='force_sell'
|
||||
WHERE id=31;
|
||||
```
|
||||
|
||||
## Insert manually a new trade
|
||||
|
||||
```sql
|
||||
INSERT
|
||||
INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date)
|
||||
VALUES ('BITTREX', 'BTC_<COIN>', 1, 0.0025, 0.0025, <open_rate>, <stake_amount>, <amount>, '<datetime>')
|
||||
INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date)
|
||||
VALUES ('bittrex', 'ETH/BTC', 1, 0.0025, 0.0025, <open_rate>, <stake_amount>, <amount>, '<datetime>')
|
||||
```
|
||||
|
||||
**Example:**
|
||||
##### Example:
|
||||
|
||||
```sql
|
||||
INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date) VALUES ('BITTREX', 'BTC_ETC', 1, 0.0025, 0.0025, 0.00258580, 0.002, 0.7715262081, '2017-11-28 12:44:24.000000')
|
||||
INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date)
|
||||
VALUES ('bittrex', 'ETH/BTC', 1, 0.0025, 0.0025, 0.00258580, 0.002, 0.7715262081, '2017-11-28 12:44:24.000000')
|
||||
```
|
||||
|
||||
## Fix wrong fees in the table
|
||||
If your DB was created before
|
||||
[PR#200](https://github.com/freqtrade/freqtrade/pull/200) was merged
|
||||
(before 12/23/17).
|
||||
If your DB was created before [PR#200](https://github.com/freqtrade/freqtrade/pull/200) was merged (before 12/23/17).
|
||||
|
||||
```sql
|
||||
UPDATE trades SET fee=0.0025 WHERE fee=0.005;
|
||||
|
||||
@@ -2,9 +2,20 @@
|
||||
|
||||
At this stage the bot contains the following stoploss support modes:
|
||||
|
||||
1. static stop loss, defined in either the strategy or configuration
|
||||
2. trailing stop loss, defined in the configuration
|
||||
3. trailing stop loss, custom positive loss, defined in configuration
|
||||
1. static stop loss, defined in either the strategy or configuration.
|
||||
2. trailing stop loss, defined in the configuration.
|
||||
3. trailing stop loss, custom positive loss, defined in configuration.
|
||||
|
||||
!!! Note
|
||||
All stoploss properties can be configured in either Strategy or configuration. Configuration values override strategy values.
|
||||
|
||||
Those stoploss modes can be *on exchange* or *off exchange*. If the stoploss is *on exchange* it means a stoploss limit order is placed on the exchange immediately after buy order happens successfuly. This will protect you against sudden crashes in market as the order will be in the queue immediately and if market goes down then the order has more chance of being fulfilled.
|
||||
|
||||
In case of stoploss on exchange there is another parameter called `stoploss_on_exchange_interval`. This configures the interval in seconds at which the bot will check the stoploss and update it if necessary. As an example in case of trailing stoploss if the order is on the exchange and the market is going up then the bot automatically cancels the previous stoploss order and put a new one with a stop value higher than previous one. It is clear that the bot cannot do it every 5 seconds otherwise it gets banned. So this parameter will tell the bot how often it should update the stoploss order. The default value is 60 (1 minute).
|
||||
|
||||
!!! Note
|
||||
Stoploss on exchange is only supported for Binance as of now.
|
||||
|
||||
|
||||
## Static Stop Loss
|
||||
|
||||
@@ -44,8 +55,11 @@ Both values can be configured in the main configuration file and requires `"trai
|
||||
``` json
|
||||
"trailing_stop_positive": 0.01,
|
||||
"trailing_stop_positive_offset": 0.011,
|
||||
"trailing_only_offset_is_reached": false
|
||||
```
|
||||
|
||||
The 0.01 would translate to a 1% stop loss, once you hit 1.1% profit.
|
||||
|
||||
You should also make sure to have this value (`trailing_stop_positive_offset`) lower than your minimal ROI, otherwise minimal ROI will apply first and sell your trade.
|
||||
|
||||
If `"trailing_only_offset_is_reached": true` then the trailing stoploss is only activated once the offset is reached. Until then, the stoploss remains at the configured`stoploss`.
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
# Telegram usage
|
||||
|
||||
This page explains how to command your bot with Telegram.
|
||||
## Prerequisite
|
||||
|
||||
## Pre-requisite
|
||||
To control your bot with Telegram, you need first to
|
||||
[set up a Telegram bot](https://github.com/freqtrade/freqtrade/blob/develop/docs/pre-requisite.md)
|
||||
To control your bot with Telegram, you need first to
|
||||
[set up a Telegram bot](installation.md)
|
||||
and add your Telegram API keys into your config file.
|
||||
|
||||
## Telegram commands
|
||||
Per default, the Telegram bot shows predefined commands. Some commands
|
||||
are only available by sending them to the bot. The table below list the
|
||||
|
||||
Per default, the Telegram bot shows predefined commands. Some commands
|
||||
are only available by sending them to the bot. The table below list the
|
||||
official commands. You can ask at any moment for help with `/help`.
|
||||
|
||||
| Command | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `/start` | | Starts the trader
|
||||
| `/stop` | | Stops the trader
|
||||
| `/stopbuy` | | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
||||
| `/reload_conf` | | Reloads the configuration file
|
||||
| `/status` | | Lists all open trades
|
||||
| `/status table` | | List all open trades in a table format
|
||||
@@ -27,6 +28,9 @@ official commands. You can ask at any moment for help with `/help`.
|
||||
| `/performance` | | Show performance of each finished trade grouped by pair
|
||||
| `/balance` | | Show account balance per currency
|
||||
| `/daily <n>` | 7 | Shows profit or loss per day, over the last n days
|
||||
| `/whitelist` | | Show the current whitelist
|
||||
| `/blacklist [pair]` | | Show the current blacklist, or adds a pair to the blacklist.
|
||||
| `/edge` | | Show validated pairs by Edge if it is enabled.
|
||||
| `/help` | | Show help message
|
||||
| `/version` | | Show version
|
||||
|
||||
@@ -40,44 +44,56 @@ Below, example of Telegram message you will receive for each command.
|
||||
|
||||
### /stop
|
||||
|
||||
> `Stopping trader ...`
|
||||
> `Stopping trader ...`
|
||||
> **Status:** `stopped`
|
||||
|
||||
## /status
|
||||
### /stopbuy
|
||||
|
||||
> **status:** `Setting max_open_trades to 0. Run /reload_conf to reset.`
|
||||
|
||||
Prevents the bot from opening new trades by temporarily setting "max_open_trades" to 0. Open trades will be handled via their regular rules (ROI / Sell-signal, stoploss, ...).
|
||||
|
||||
After this, give the bot time to close off open trades (can be checked via `/status table`).
|
||||
Once all positions are sold, run `/stop` to completely stop the bot.
|
||||
|
||||
`/reload_conf` resets "max_open_trades" to the value set in the configuration and resets this command.
|
||||
|
||||
!!! warning
|
||||
The stop-buy signal is ONLY active while the bot is running, and is not persisted anyway, so restarting the bot will cause this to reset.
|
||||
|
||||
### /status
|
||||
|
||||
For each open trade, the bot will send you the following message.
|
||||
|
||||
> **Trade ID:** `123`
|
||||
> **Current Pair:** CVC/BTC
|
||||
> **Trade ID:** `123` `(since 1 days ago)`
|
||||
> **Current Pair:** CVC/BTC
|
||||
> **Open Since:** `1 days ago`
|
||||
> **Amount:** `26.64180098`
|
||||
> **Open Rate:** `0.00007489`
|
||||
> **Close Rate:** `None`
|
||||
> **Current Rate:** `0.00007489`
|
||||
> **Close Profit:** `None`
|
||||
> **Current Profit:** `12.95%`
|
||||
> **Open Order:** `None`
|
||||
> **Stoploss:** `0.00007389 (-0.02%)`
|
||||
|
||||
## /status table
|
||||
### /status table
|
||||
|
||||
Return the status of all open trades in a table format.
|
||||
```
|
||||
ID Pair Since Profit
|
||||
---- -------- ------- --------
|
||||
ID Pair Since Profit
|
||||
---- -------- ------- --------
|
||||
67 SC/BTC 1 d 13.33%
|
||||
123 CVC/BTC 1 h 12.95%
|
||||
```
|
||||
|
||||
## /count
|
||||
### /count
|
||||
|
||||
Return the number of trades used and available.
|
||||
```
|
||||
current max
|
||||
--------- -----
|
||||
2 10
|
||||
--------- -----
|
||||
2 10
|
||||
```
|
||||
|
||||
## /profit
|
||||
### /profit
|
||||
|
||||
Return a summary of your profit/loss and performance.
|
||||
|
||||
@@ -87,35 +103,37 @@ Return a summary of your profit/loss and performance.
|
||||
> **ROI:** All trades
|
||||
> ∙ `0.00255280 BTC (143.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%`
|
||||
> **Best Performing:** `PAY/BTC: 50.23%`
|
||||
|
||||
## /forcesell <trade_id>
|
||||
### /forcesell <trade_id>
|
||||
|
||||
> **BITTREX:** Selling BTC/LTC with limit `0.01650000 (profit: ~-4.07%, -0.00008168)`
|
||||
|
||||
## /forcebuy <pair>
|
||||
### /forcebuy <pair>
|
||||
|
||||
> **BITTREX**: Buying ETH/BTC with limit `0.03400000` (`1.000000 ETH`, `225.290 USD`)
|
||||
|
||||
Note that for this to work, `forcebuy_enable` needs to be set to true.
|
||||
|
||||
## /performance
|
||||
[More details](configuration.md/#understand-forcebuy_enable)
|
||||
|
||||
### /performance
|
||||
|
||||
Return the performance of each crypto-currency the bot has sold.
|
||||
> Performance:
|
||||
> 1. `RCN/BTC 57.77%`
|
||||
> 2. `PAY/BTC 56.91%`
|
||||
> 3. `VIB/BTC 47.07%`
|
||||
> 4. `SALT/BTC 30.24%`
|
||||
> 5. `STORJ/BTC 27.24%`
|
||||
> ...
|
||||
> Performance:
|
||||
> 1. `RCN/BTC 57.77%`
|
||||
> 2. `PAY/BTC 56.91%`
|
||||
> 3. `VIB/BTC 47.07%`
|
||||
> 4. `SALT/BTC 30.24%`
|
||||
> 5. `STORJ/BTC 27.24%`
|
||||
> ...
|
||||
|
||||
## /balance
|
||||
### /balance
|
||||
|
||||
Return the balance of all crypto-currency your have on the exchange.
|
||||
|
||||
@@ -127,23 +145,54 @@ Return the balance of all crypto-currency your have on the exchange.
|
||||
> **Currency:** CVC
|
||||
> **Available:** 86.64180098
|
||||
> **Balance:** 86.64180098
|
||||
> **Pending:** 0.0
|
||||
> **Pending:** 0.0
|
||||
|
||||
## /daily <n>
|
||||
### /daily <n>
|
||||
|
||||
Per default `/daily` will return the 7 last days.
|
||||
Per default `/daily` will return the 7 last days.
|
||||
The example below if for `/daily 3`:
|
||||
|
||||
> **Daily Profit over the last 3 days:**
|
||||
```
|
||||
Day Profit BTC Profit USD
|
||||
---------- -------------- ------------
|
||||
2018-01-03 0.00224175 BTC 29,142 USD
|
||||
2018-01-02 0.00033131 BTC 4,307 USD
|
||||
Day Profit BTC Profit USD
|
||||
---------- -------------- ------------
|
||||
2018-01-03 0.00224175 BTC 29,142 USD
|
||||
2018-01-02 0.00033131 BTC 4,307 USD
|
||||
2018-01-01 0.00269130 BTC 34.986 USD
|
||||
```
|
||||
|
||||
## /version
|
||||
### /whitelist
|
||||
|
||||
> **Version:** `0.14.3`
|
||||
Shows the current whitelist
|
||||
|
||||
> Using whitelist `StaticPairList` with 22 pairs
|
||||
> `IOTA/BTC, NEO/BTC, TRX/BTC, VET/BTC, ADA/BTC, ETC/BTC, NCASH/BTC, DASH/BTC, XRP/BTC, XVG/BTC, EOS/BTC, LTC/BTC, OMG/BTC, BTG/BTC, LSK/BTC, ZEC/BTC, HOT/BTC, IOTX/BTC, XMR/BTC, AST/BTC, XLM/BTC, NANO/BTC`
|
||||
|
||||
### /blacklist [pair]
|
||||
|
||||
Shows the current blacklist.
|
||||
If Pair is set, then this pair will be added to the pairlist.
|
||||
Also supports multiple pairs, seperated by a space.
|
||||
Use `/reload_conf` to reset the blacklist.
|
||||
|
||||
> Using blacklist `StaticPairList` with 2 pairs
|
||||
>`DODGE/BTC`, `HOT/BTC`.
|
||||
|
||||
### /edge
|
||||
|
||||
Shows pairs validated by Edge along with their corresponding winrate, expectancy and stoploss values.
|
||||
|
||||
> **Edge only validated following pairs:**
|
||||
```
|
||||
Pair Winrate Expectancy Stoploss
|
||||
-------- --------- ------------ ----------
|
||||
DOCK/ETH 0.522727 0.881821 -0.03
|
||||
PHX/ETH 0.677419 0.560488 -0.03
|
||||
HOT/ETH 0.733333 0.490492 -0.03
|
||||
HC/ETH 0.588235 0.280988 -0.02
|
||||
ARDR/ETH 0.366667 0.143059 -0.01
|
||||
```
|
||||
|
||||
### /version
|
||||
|
||||
> **Version:** `0.14.3`
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
# Webhook usage
|
||||
|
||||
This page explains how to configure your bot to talk to webhooks.
|
||||
|
||||
## Configuration
|
||||
|
||||
Enable webhooks by adding a webhook-section to your configuration file, and setting `webhook.enabled` to `true`.
|
||||
@@ -39,34 +37,30 @@ Different payloads can be configured for different events. Not all fields are ne
|
||||
The fields in `webhook.webhookbuy` are filled when the bot executes a buy. Parameters are filled using string.format.
|
||||
Possible parameters are:
|
||||
|
||||
* exchange
|
||||
* pair
|
||||
* market_url
|
||||
* limit
|
||||
* stake_amount
|
||||
* stake_amount_fiat
|
||||
* stake_currency
|
||||
* fiat_currency
|
||||
* `exchange`
|
||||
* `pair`
|
||||
* `limit`
|
||||
* `stake_amount`
|
||||
* `stake_currency`
|
||||
* `fiat_currency`
|
||||
|
||||
### Webhooksell
|
||||
|
||||
The fields in `webhook.webhooksell` are filled when the bot sells a trade. Parameters are filled using string.format.
|
||||
Possible parameters are:
|
||||
|
||||
* exchange
|
||||
* pair
|
||||
* gain
|
||||
* market_url
|
||||
* limit
|
||||
* amount
|
||||
* open_rate
|
||||
* current_rate
|
||||
* profit_amount
|
||||
* profit_percent
|
||||
* profit_fiat
|
||||
* stake_currency
|
||||
* fiat_currency
|
||||
* sell_reason
|
||||
* `exchange`
|
||||
* `pair`
|
||||
* `gain`
|
||||
* `limit`
|
||||
* `amount`
|
||||
* `open_rate`
|
||||
* `current_rate`
|
||||
* `profit_amount`
|
||||
* `profit_percent`
|
||||
* `stake_currency`
|
||||
* `fiat_currency`
|
||||
* `sell_reason`
|
||||
|
||||
### Webhookstatus
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ After=network.target
|
||||
# Set WorkingDirectory and ExecStart to your file paths accordingly
|
||||
# NOTE: %h will be resolved to /home/<username>
|
||||
WorkingDirectory=%h/freqtrade
|
||||
ExecStart=/usr/bin/freqtrade --dynamic-whitelist 40
|
||||
ExecStart=/usr/bin/freqtrade
|
||||
Restart=on-failure
|
||||
|
||||
[Install]
|
||||
|
||||
30
freqtrade.service.watchdog
Normal file
30
freqtrade.service.watchdog
Normal file
@@ -0,0 +1,30 @@
|
||||
[Unit]
|
||||
Description=Freqtrade Daemon
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
# Set WorkingDirectory and ExecStart to your file paths accordingly
|
||||
# NOTE: %h will be resolved to /home/<username>
|
||||
WorkingDirectory=%h/freqtrade
|
||||
ExecStart=/usr/bin/freqtrade --sd-notify
|
||||
|
||||
Restart=always
|
||||
#Restart=on-failure
|
||||
|
||||
# Note that we use Type=notify here
|
||||
Type=notify
|
||||
|
||||
# Currently required if Type=notify
|
||||
NotifyAccess=all
|
||||
|
||||
StartLimitInterval=1min
|
||||
StartLimitBurst=5
|
||||
|
||||
TimeoutStartSec=1min
|
||||
|
||||
# Use here (process_throttle_secs * 2) or longer time interval
|
||||
WatchdogSec=20
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
""" FreqTrade bot """
|
||||
__version__ = '0.18.0'
|
||||
__version__ = '0.18.5'
|
||||
|
||||
|
||||
class DependencyException(BaseException):
|
||||
@@ -17,6 +17,14 @@ class OperationalException(BaseException):
|
||||
"""
|
||||
|
||||
|
||||
class InvalidOrderException(BaseException):
|
||||
"""
|
||||
This is returned when the order is not valid. Example:
|
||||
If stoploss on exchange order is hit, then trying to cancel the order
|
||||
should return this exception.
|
||||
"""
|
||||
|
||||
|
||||
class TemporaryError(BaseException):
|
||||
"""
|
||||
Temporary network or exchange related error.
|
||||
|
||||
@@ -6,9 +6,7 @@ import argparse
|
||||
import os
|
||||
import re
|
||||
from typing import List, NamedTuple, Optional
|
||||
|
||||
import arrow
|
||||
|
||||
from freqtrade import __version__, constants
|
||||
|
||||
|
||||
@@ -55,6 +53,11 @@ class Arguments(object):
|
||||
"""
|
||||
parsed_arg = self.parser.parse_args(self.args)
|
||||
|
||||
# Workaround issue in argparse with action='append' and default value
|
||||
# (see https://bugs.python.org/issue16399)
|
||||
if parsed_arg.config is None:
|
||||
parsed_arg.config = [constants.DEFAULT_CONFIG]
|
||||
|
||||
return parsed_arg
|
||||
|
||||
def common_args_parser(self) -> None:
|
||||
@@ -63,11 +66,18 @@ class Arguments(object):
|
||||
"""
|
||||
self.parser.add_argument(
|
||||
'-v', '--verbose',
|
||||
help='verbose mode (-vv for more, -vvv to get all messages)',
|
||||
help='Verbose mode (-vv for more, -vvv to get all messages).',
|
||||
action='count',
|
||||
dest='loglevel',
|
||||
default=0,
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'--logfile',
|
||||
help='Log to the file specified',
|
||||
dest='logfile',
|
||||
type=str,
|
||||
metavar='FILE'
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'--version',
|
||||
action='version',
|
||||
@@ -75,15 +85,16 @@ class Arguments(object):
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'-c', '--config',
|
||||
help='specify configuration file (default: %(default)s)',
|
||||
help='Specify configuration file (default: %(default)s). '
|
||||
'Multiple --config options may be used.',
|
||||
dest='config',
|
||||
default='config.json',
|
||||
action='append',
|
||||
type=str,
|
||||
metavar='PATH',
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'-d', '--datadir',
|
||||
help='path to backtest data',
|
||||
help='Path to backtest data.',
|
||||
dest='datadir',
|
||||
default=None,
|
||||
type=str,
|
||||
@@ -91,7 +102,7 @@ class Arguments(object):
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'-s', '--strategy',
|
||||
help='specify strategy class name (default: %(default)s)',
|
||||
help='Specify strategy class name (default: %(default)s).',
|
||||
dest='strategy',
|
||||
default='DefaultStrategy',
|
||||
type=str,
|
||||
@@ -99,23 +110,15 @@ class Arguments(object):
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'--strategy-path',
|
||||
help='specify additional strategy lookup path',
|
||||
help='Specify additional strategy lookup path.',
|
||||
dest='strategy_path',
|
||||
type=str,
|
||||
metavar='PATH',
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'--customhyperopt',
|
||||
help='specify hyperopt class name (default: %(default)s)',
|
||||
dest='hyperopt',
|
||||
default=constants.DEFAULT_HYPEROPT,
|
||||
type=str,
|
||||
metavar='NAME',
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'--dynamic-whitelist',
|
||||
help='dynamically generate and update whitelist'
|
||||
' based on 24h BaseVolume (default: %(const)s)'
|
||||
help='Dynamically generate and update whitelist'
|
||||
' based on 24h BaseVolume (default: %(const)s).'
|
||||
' DEPRECATED.',
|
||||
dest='dynamic_whitelist',
|
||||
const=constants.DYNAMIC_WHITELIST,
|
||||
@@ -126,11 +129,17 @@ class Arguments(object):
|
||||
self.parser.add_argument(
|
||||
'--db-url',
|
||||
help='Override trades database URL, this is useful if dry_run is enabled'
|
||||
' or in custom deployments (default: %(default)s)',
|
||||
' or in custom deployments (default: %(default)s).',
|
||||
dest='db_url',
|
||||
type=str,
|
||||
metavar='PATH',
|
||||
)
|
||||
self.parser.add_argument(
|
||||
'--sd-notify',
|
||||
help='Notify systemd service manager.',
|
||||
action='store_true',
|
||||
dest='sd_notify',
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def backtesting_options(parser: argparse.ArgumentParser) -> None:
|
||||
@@ -139,29 +148,28 @@ class Arguments(object):
|
||||
"""
|
||||
parser.add_argument(
|
||||
'--eps', '--enable-position-stacking',
|
||||
help='Allow buying the same pair multiple times (position stacking)',
|
||||
help='Allow buying the same pair multiple times (position stacking).',
|
||||
action='store_true',
|
||||
dest='position_stacking',
|
||||
default=False
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--dmmp', '--disable-max-market-positions',
|
||||
help='Disable applying `max_open_trades` during backtest '
|
||||
'(same as setting `max_open_trades` to a very high number)',
|
||||
'(same as setting `max_open_trades` to a very high number).',
|
||||
action='store_false',
|
||||
dest='use_max_market_positions',
|
||||
default=True
|
||||
)
|
||||
parser.add_argument(
|
||||
'-l', '--live',
|
||||
help='using live data',
|
||||
help='Use live data.',
|
||||
action='store_true',
|
||||
dest='live',
|
||||
)
|
||||
parser.add_argument(
|
||||
'-r', '--refresh-pairs-cached',
|
||||
help='refresh the pairs files in tests/testdata with the latest data from the '
|
||||
help='Refresh the pairs files in tests/testdata with the latest data from the '
|
||||
'exchange. Use it if you want to run your backtesting with up-to-date data.',
|
||||
action='store_true',
|
||||
dest='refresh_pairs',
|
||||
@@ -178,8 +186,8 @@ class Arguments(object):
|
||||
)
|
||||
parser.add_argument(
|
||||
'--export',
|
||||
help='export backtest results, argument are: trades\
|
||||
Example --export=trades',
|
||||
help='Export backtest results, argument are: trades. '
|
||||
'Example --export=trades',
|
||||
type=str,
|
||||
default=None,
|
||||
dest='export',
|
||||
@@ -203,14 +211,14 @@ class Arguments(object):
|
||||
"""
|
||||
parser.add_argument(
|
||||
'-r', '--refresh-pairs-cached',
|
||||
help='refresh the pairs files in tests/testdata with the latest data from the '
|
||||
help='Refresh the pairs files in tests/testdata with the latest data from the '
|
||||
'exchange. Use it if you want to run your edge with up-to-date data.',
|
||||
action='store_true',
|
||||
dest='refresh_pairs',
|
||||
)
|
||||
parser.add_argument(
|
||||
'--stoplosses',
|
||||
help='defines a range of stoploss against which edge will assess the strategy '
|
||||
help='Defines a range of stoploss against which edge will assess the strategy '
|
||||
'the format is "min,max,step" (without any space).'
|
||||
'example: --stoplosses=-0.01,-0.1,-0.001',
|
||||
type=str,
|
||||
@@ -226,27 +234,51 @@ class Arguments(object):
|
||||
"""
|
||||
parser.add_argument(
|
||||
'-i', '--ticker-interval',
|
||||
help='specify ticker interval (1m, 5m, 30m, 1h, 1d)',
|
||||
help='Specify ticker interval (1m, 5m, 30m, 1h, 1d).',
|
||||
dest='ticker_interval',
|
||||
type=str,
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--timerange',
|
||||
help='specify what timerange of data to use.',
|
||||
help='Specify what timerange of data to use.',
|
||||
default=None,
|
||||
type=str,
|
||||
dest='timerange',
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--max_open_trades',
|
||||
help='Specify max_open_trades to use.',
|
||||
default=None,
|
||||
type=int,
|
||||
dest='max_open_trades',
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--stake_amount',
|
||||
help='Specify stake_amount.',
|
||||
default=None,
|
||||
type=float,
|
||||
dest='stake_amount',
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def hyperopt_options(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
Parses given arguments for Hyperopt scripts.
|
||||
"""
|
||||
parser.add_argument(
|
||||
'--customhyperopt',
|
||||
help='Specify hyperopt class name (default: %(default)s).',
|
||||
dest='hyperopt',
|
||||
default=constants.DEFAULT_HYPEROPT,
|
||||
type=str,
|
||||
metavar='NAME',
|
||||
)
|
||||
parser.add_argument(
|
||||
'--eps', '--enable-position-stacking',
|
||||
help='Allow buying the same pair multiple times (position stacking)',
|
||||
help='Allow buying the same pair multiple times (position stacking).',
|
||||
action='store_true',
|
||||
dest='position_stacking',
|
||||
default=False
|
||||
@@ -255,14 +287,14 @@ class Arguments(object):
|
||||
parser.add_argument(
|
||||
'--dmmp', '--disable-max-market-positions',
|
||||
help='Disable applying `max_open_trades` during backtest '
|
||||
'(same as setting `max_open_trades` to a very high number)',
|
||||
'(same as setting `max_open_trades` to a very high number).',
|
||||
action='store_false',
|
||||
dest='use_max_market_positions',
|
||||
default=True
|
||||
)
|
||||
parser.add_argument(
|
||||
'-e', '--epochs',
|
||||
help='specify number of epochs (default: %(default)d)',
|
||||
help='Specify number of epochs (default: %(default)d).',
|
||||
dest='epochs',
|
||||
default=constants.HYPEROPT_EPOCH,
|
||||
type=int,
|
||||
@@ -271,8 +303,8 @@ class Arguments(object):
|
||||
parser.add_argument(
|
||||
'-s', '--spaces',
|
||||
help='Specify which parameters to hyperopt. Space separate list. \
|
||||
Default: %(default)s',
|
||||
choices=['all', 'buy', 'roi', 'stoploss'],
|
||||
Default: %(default)s.',
|
||||
choices=['all', 'buy', 'sell', 'roi', 'stoploss'],
|
||||
default='all',
|
||||
nargs='+',
|
||||
dest='spaces',
|
||||
@@ -288,19 +320,19 @@ class Arguments(object):
|
||||
subparsers = self.parser.add_subparsers(dest='subparser')
|
||||
|
||||
# Add backtesting subcommand
|
||||
backtesting_cmd = subparsers.add_parser('backtesting', help='backtesting module')
|
||||
backtesting_cmd = subparsers.add_parser('backtesting', help='Backtesting module.')
|
||||
backtesting_cmd.set_defaults(func=backtesting.start)
|
||||
self.optimizer_shared_options(backtesting_cmd)
|
||||
self.backtesting_options(backtesting_cmd)
|
||||
|
||||
# Add edge subcommand
|
||||
edge_cmd = subparsers.add_parser('edge', help='edge module')
|
||||
edge_cmd = subparsers.add_parser('edge', help='Edge module.')
|
||||
edge_cmd.set_defaults(func=edge_cli.start)
|
||||
self.optimizer_shared_options(edge_cmd)
|
||||
self.edge_options(edge_cmd)
|
||||
|
||||
# Add hyperopt subcommand
|
||||
hyperopt_cmd = subparsers.add_parser('hyperopt', help='hyperopt module')
|
||||
hyperopt_cmd = subparsers.add_parser('hyperopt', help='Hyperopt module.')
|
||||
hyperopt_cmd.set_defaults(func=hyperopt.start)
|
||||
self.optimizer_shared_options(hyperopt_cmd)
|
||||
self.hyperopt_options(hyperopt_cmd)
|
||||
@@ -352,9 +384,9 @@ class Arguments(object):
|
||||
Parses given arguments for scripts.
|
||||
"""
|
||||
self.parser.add_argument(
|
||||
'-p', '--pair',
|
||||
'-p', '--pairs',
|
||||
help='Show profits for only this pairs. Pairs are comma-separated.',
|
||||
dest='pair',
|
||||
dest='pairs',
|
||||
default=None
|
||||
)
|
||||
|
||||
@@ -364,7 +396,7 @@ class Arguments(object):
|
||||
"""
|
||||
self.parser.add_argument(
|
||||
'--pairs-file',
|
||||
help='File containing a list of pairs to download',
|
||||
help='File containing a list of pairs to download.',
|
||||
dest='pairs_file',
|
||||
default=None,
|
||||
metavar='PATH',
|
||||
@@ -372,7 +404,7 @@ class Arguments(object):
|
||||
|
||||
self.parser.add_argument(
|
||||
'--export',
|
||||
help='Export files to given dir',
|
||||
help='Export files to given dir.',
|
||||
dest='export',
|
||||
default=None,
|
||||
metavar='PATH',
|
||||
@@ -380,16 +412,17 @@ class Arguments(object):
|
||||
|
||||
self.parser.add_argument(
|
||||
'-c', '--config',
|
||||
help='specify configuration file, used for additional exchange parameters',
|
||||
help='Specify configuration file (default: %(default)s). '
|
||||
'Multiple --config options may be used.',
|
||||
dest='config',
|
||||
default=None,
|
||||
action='append',
|
||||
type=str,
|
||||
metavar='PATH',
|
||||
)
|
||||
|
||||
self.parser.add_argument(
|
||||
'--days',
|
||||
help='Download data for number of days',
|
||||
help='Download data for given number of days.',
|
||||
dest='days',
|
||||
type=int,
|
||||
metavar='INT',
|
||||
@@ -398,7 +431,7 @@ class Arguments(object):
|
||||
|
||||
self.parser.add_argument(
|
||||
'--exchange',
|
||||
help='Exchange name (default: %(default)s). Only valid if no config is provided',
|
||||
help='Exchange name (default: %(default)s). Only valid if no config is provided.',
|
||||
dest='exchange',
|
||||
type=str,
|
||||
default='bittrex'
|
||||
@@ -407,7 +440,7 @@ class Arguments(object):
|
||||
self.parser.add_argument(
|
||||
'-t', '--timeframes',
|
||||
help='Specify which tickers to download. Space separated list. \
|
||||
Default: %(default)s',
|
||||
Default: %(default)s.',
|
||||
choices=['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h',
|
||||
'6h', '8h', '12h', '1d', '3d', '1w'],
|
||||
default=['1m', '5m'],
|
||||
@@ -417,7 +450,7 @@ class Arguments(object):
|
||||
|
||||
self.parser.add_argument(
|
||||
'--erase',
|
||||
help='Clean all existing data for the selected exchange/pairs/timeframes',
|
||||
help='Clean all existing data for the selected exchange/pairs/timeframes.',
|
||||
dest='erase',
|
||||
action='store_true'
|
||||
)
|
||||
|
||||
@@ -4,14 +4,19 @@ This module contains the configuration class
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from argparse import Namespace
|
||||
from typing import Any, Dict, Optional
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import ccxt
|
||||
from jsonschema import Draft4Validator, validate
|
||||
from jsonschema.exceptions import ValidationError, best_match
|
||||
|
||||
from freqtrade import OperationalException, constants
|
||||
from freqtrade.misc import deep_merge_dicts
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -34,17 +39,29 @@ class Configuration(object):
|
||||
Reuse this class for the bot, backtesting, hyperopt and every script that required configuration
|
||||
"""
|
||||
|
||||
def __init__(self, args: Namespace) -> None:
|
||||
def __init__(self, args: Namespace, runmode: RunMode = None) -> None:
|
||||
self.args = args
|
||||
self.config: Optional[Dict[str, Any]] = None
|
||||
self.runmode = runmode
|
||||
|
||||
def load_config(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Extract information for sys.argv and load the bot configuration
|
||||
:return: Configuration dictionary
|
||||
"""
|
||||
logger.info('Using config: %s ...', self.args.config)
|
||||
config = self._load_config_file(self.args.config)
|
||||
config: Dict[str, Any] = {}
|
||||
# Now expecting a list of config filenames here, not a string
|
||||
for path in self.args.config:
|
||||
logger.info('Using config: %s ...', path)
|
||||
# Merge config options, overwriting old values
|
||||
config = deep_merge_dicts(self._load_config_file(path), config)
|
||||
|
||||
if 'internals' not in config:
|
||||
config['internals'] = {}
|
||||
|
||||
logger.info('Validating configuration ...')
|
||||
self._validate_config_schema(config)
|
||||
self._validate_config_consistency(config)
|
||||
|
||||
# Set strategy if not specified in config and or if it's non default
|
||||
if self.args.strategy != constants.DEFAULT_STRATEGY or not config.get('strategy'):
|
||||
@@ -53,9 +70,6 @@ class Configuration(object):
|
||||
if self.args.strategy_path:
|
||||
config.update({'strategy_path': self.args.strategy_path})
|
||||
|
||||
# Add the hyperopt file to use
|
||||
config.update({'hyperopt': self.args.hyperopt})
|
||||
|
||||
# Load Common configuration
|
||||
config = self._load_common_config(config)
|
||||
|
||||
@@ -68,6 +82,13 @@ class Configuration(object):
|
||||
# Load Hyperopt
|
||||
config = self._load_hyperopt_config(config)
|
||||
|
||||
# Set runmode
|
||||
if not self.runmode:
|
||||
# Handle real mode, infer dry/live from config
|
||||
self.runmode = RunMode.DRY_RUN if config.get('dry_run', True) else RunMode.LIVE
|
||||
|
||||
config.update({'runmode': self.runmode})
|
||||
|
||||
return config
|
||||
|
||||
def _load_config_file(self, path: str) -> Dict[str, Any]:
|
||||
@@ -84,11 +105,7 @@ class Configuration(object):
|
||||
f'Config file "{path}" not found!'
|
||||
' Please create a config file or check whether it exists.')
|
||||
|
||||
if 'internals' not in conf:
|
||||
conf['internals'] = {}
|
||||
logger.info('Validating configuration ...')
|
||||
|
||||
return self._validate_config(conf)
|
||||
return conf
|
||||
|
||||
def _load_common_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
@@ -101,13 +118,30 @@ class Configuration(object):
|
||||
config.update({'verbosity': self.args.loglevel})
|
||||
else:
|
||||
config.update({'verbosity': 0})
|
||||
|
||||
# Log to stdout, not stderr
|
||||
log_handlers: List[logging.Handler] = [logging.StreamHandler(sys.stdout)]
|
||||
if 'logfile' in self.args and self.args.logfile:
|
||||
config.update({'logfile': self.args.logfile})
|
||||
|
||||
# Allow setting this as either configuration or argument
|
||||
if 'logfile' in config:
|
||||
log_handlers.append(RotatingFileHandler(config['logfile'],
|
||||
maxBytes=1024 * 1024, # 1Mb
|
||||
backupCount=10))
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO if config['verbosity'] < 1 else logging.DEBUG,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
handlers=log_handlers
|
||||
)
|
||||
set_loggers(config['verbosity'])
|
||||
logger.info('Verbosity set to %s', config['verbosity'])
|
||||
|
||||
# Support for sd_notify
|
||||
if self.args.sd_notify:
|
||||
config['internals'].update({'sd_notify': True})
|
||||
|
||||
# Add dynamic_whitelist if found
|
||||
if 'dynamic_whitelist' in self.args and self.args.dynamic_whitelist:
|
||||
# Update to volumePairList (the previous default)
|
||||
@@ -124,9 +158,6 @@ class Configuration(object):
|
||||
if self.args.db_url and self.args.db_url != constants.DEFAULT_DB_PROD_URL:
|
||||
config.update({'db_url': self.args.db_url})
|
||||
logger.info('Parameter --db-url detected ...')
|
||||
else:
|
||||
# Set default here
|
||||
config.update({'db_url': constants.DEFAULT_DB_PROD_URL})
|
||||
|
||||
if config.get('dry_run', False):
|
||||
logger.info('Dry run is enabled')
|
||||
@@ -152,15 +183,18 @@ class Configuration(object):
|
||||
|
||||
return config
|
||||
|
||||
def _create_default_datadir(self, config: Dict[str, Any]) -> str:
|
||||
exchange_name = config.get('exchange', {}).get('name').lower()
|
||||
default_path = os.path.join('user_data', 'data', exchange_name)
|
||||
if not os.path.isdir(default_path):
|
||||
os.makedirs(default_path)
|
||||
logger.info(f'Created data directory: {default_path}')
|
||||
return default_path
|
||||
def _create_datadir(self, config: Dict[str, Any], datadir: Optional[str] = None) -> str:
|
||||
if not datadir:
|
||||
# set datadir
|
||||
exchange_name = config.get('exchange', {}).get('name').lower()
|
||||
datadir = os.path.join('user_data', 'data', exchange_name)
|
||||
|
||||
def _load_backtesting_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
|
||||
if not os.path.isdir(datadir):
|
||||
os.makedirs(datadir)
|
||||
logger.info(f'Created data directory: {datadir}')
|
||||
return datadir
|
||||
|
||||
def _load_backtesting_config(self, config: Dict[str, Any]) -> Dict[str, Any]: # noqa: C901
|
||||
"""
|
||||
Extract information for sys.argv and load Backtesting configuration
|
||||
:return: configuration as dictionary
|
||||
@@ -183,14 +217,24 @@ class Configuration(object):
|
||||
config.update({'position_stacking': True})
|
||||
logger.info('Parameter --enable-position-stacking detected ...')
|
||||
|
||||
# If --disable-max-market-positions is used we add it to the configuration
|
||||
# If --disable-max-market-positions or --max_open_trades is used we update configuration
|
||||
if 'use_max_market_positions' in self.args and not self.args.use_max_market_positions:
|
||||
config.update({'use_max_market_positions': False})
|
||||
logger.info('Parameter --disable-max-market-positions detected ...')
|
||||
logger.info('max_open_trades set to unlimited ...')
|
||||
elif 'max_open_trades' in self.args and self.args.max_open_trades:
|
||||
config.update({'max_open_trades': self.args.max_open_trades})
|
||||
logger.info('Parameter --max_open_trades detected, '
|
||||
'overriding max_open_trades to: %s ...', config.get('max_open_trades'))
|
||||
else:
|
||||
logger.info('Using max_open_trades: %s ...', config.get('max_open_trades'))
|
||||
|
||||
# If --stake_amount is used we update configuration
|
||||
if 'stake_amount' in self.args and self.args.stake_amount:
|
||||
config.update({'stake_amount': self.args.stake_amount})
|
||||
logger.info('Parameter --stake_amount detected, overriding stake_amount to: %s ...',
|
||||
config.get('stake_amount'))
|
||||
|
||||
# If --timerange is used we add it to the configuration
|
||||
if 'timerange' in self.args and self.args.timerange:
|
||||
config.update({'timerange': self.args.timerange})
|
||||
@@ -198,9 +242,9 @@ class Configuration(object):
|
||||
|
||||
# If --datadir is used we add it to the configuration
|
||||
if 'datadir' in self.args and self.args.datadir:
|
||||
config.update({'datadir': self.args.datadir})
|
||||
config.update({'datadir': self._create_datadir(config, self.args.datadir)})
|
||||
else:
|
||||
config.update({'datadir': self._create_default_datadir(config)})
|
||||
config.update({'datadir': self._create_datadir(config, None)})
|
||||
logger.info('Using data folder: %s ...', config.get('datadir'))
|
||||
|
||||
# If -r/--refresh-pairs-cached is used we add it to the configuration
|
||||
@@ -259,6 +303,11 @@ class Configuration(object):
|
||||
Extract information for sys.argv and load Hyperopt configuration
|
||||
:return: configuration as dictionary
|
||||
"""
|
||||
|
||||
if "hyperopt" in self.args:
|
||||
# Add the hyperopt file to use
|
||||
config.update({'hyperopt': self.args.hyperopt})
|
||||
|
||||
# If --epochs is used we add it to the configuration
|
||||
if 'epochs' in self.args and self.args.epochs:
|
||||
config.update({'epochs': self.args.epochs})
|
||||
@@ -272,7 +321,7 @@ class Configuration(object):
|
||||
|
||||
return config
|
||||
|
||||
def _validate_config(self, conf: Dict[str, Any]) -> Dict[str, Any]:
|
||||
def _validate_config_schema(self, conf: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Validate the configuration follow the Config Schema
|
||||
:param conf: Config in JSON format
|
||||
@@ -290,6 +339,35 @@ class Configuration(object):
|
||||
best_match(Draft4Validator(constants.CONF_SCHEMA).iter_errors(conf)).message
|
||||
)
|
||||
|
||||
def _validate_config_consistency(self, conf: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Validate the configuration consistency
|
||||
:param conf: Config in JSON format
|
||||
:return: Returns None if everything is ok, otherwise throw an OperationalException
|
||||
"""
|
||||
|
||||
# validating trailing stoploss
|
||||
self._validate_trailing_stoploss(conf)
|
||||
|
||||
def _validate_trailing_stoploss(self, conf: Dict[str, Any]) -> None:
|
||||
# Skip if trailing stoploss is not activated
|
||||
if not conf.get('trailing_stop', False):
|
||||
return
|
||||
|
||||
tsl_positive = float(conf.get('trailing_stop_positive', 0))
|
||||
tsl_offset = float(conf.get('trailing_stop_positive_offset', 0))
|
||||
tsl_only_offset = conf.get('trailing_only_offset_is_reached', False)
|
||||
|
||||
if tsl_only_offset:
|
||||
if tsl_positive == 0.0:
|
||||
raise OperationalException(
|
||||
f'The config trailing_only_offset_is_reached needs '
|
||||
'trailing_stop_positive_offset to be more than 0 in your config.')
|
||||
if tsl_positive > 0 and 0 < tsl_offset <= tsl_positive:
|
||||
raise OperationalException(
|
||||
f'The config trailing_stop_positive_offset needs '
|
||||
'to be greater than trailing_stop_positive_offset in your config.')
|
||||
|
||||
def get_config(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Return the config. Use this method to get the bot config
|
||||
@@ -315,11 +393,6 @@ class Configuration(object):
|
||||
raise OperationalException(
|
||||
exception_msg
|
||||
)
|
||||
# Depreciation warning
|
||||
if 'ccxt_rate_limit' in config.get('exchange', {}):
|
||||
logger.warning("`ccxt_rate_limit` has been deprecated in favor of "
|
||||
"`ccxt_config` and `ccxt_async_config` and will be removed "
|
||||
"in a future version.")
|
||||
|
||||
logger.debug('Exchange "%s" supported', exchange)
|
||||
return True
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
"""
|
||||
bot constants
|
||||
"""
|
||||
DEFAULT_CONFIG = 'config.json'
|
||||
DYNAMIC_WHITELIST = 20 # pairs
|
||||
PROCESS_THROTTLE_SECS = 5 # sec
|
||||
TICKER_INTERVAL = 5 # min
|
||||
DEFAULT_TICKER_INTERVAL = 5 # min
|
||||
HYPEROPT_EPOCH = 100 # epochs
|
||||
RETRY_TIMEOUT = 30 # sec
|
||||
DEFAULT_STRATEGY = 'DefaultStrategy'
|
||||
@@ -13,28 +14,19 @@ DEFAULT_HYPEROPT = 'DefaultHyperOpts'
|
||||
DEFAULT_DB_PROD_URL = 'sqlite:///tradesv3.sqlite'
|
||||
DEFAULT_DB_DRYRUN_URL = 'sqlite://'
|
||||
UNLIMITED_STAKE_AMOUNT = 'unlimited'
|
||||
DEFAULT_AMOUNT_RESERVE_PERCENT = 0.05
|
||||
REQUIRED_ORDERTIF = ['buy', 'sell']
|
||||
REQUIRED_ORDERTYPES = ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
||||
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
||||
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
||||
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList']
|
||||
DRY_RUN_WALLET = 999.9
|
||||
|
||||
TICKER_INTERVAL_MINUTES = {
|
||||
'1m': 1,
|
||||
'3m': 3,
|
||||
'5m': 5,
|
||||
'15m': 15,
|
||||
'30m': 30,
|
||||
'1h': 60,
|
||||
'2h': 120,
|
||||
'4h': 240,
|
||||
'6h': 360,
|
||||
'8h': 480,
|
||||
'12h': 720,
|
||||
'1d': 1440,
|
||||
'3d': 4320,
|
||||
'1w': 10080,
|
||||
}
|
||||
TICKER_INTERVALS = [
|
||||
'1m', '3m', '5m', '15m', '30m',
|
||||
'1h', '2h', '4h', '6h', '8h', '12h',
|
||||
'1d', '3d', '1w',
|
||||
]
|
||||
|
||||
SUPPORTED_FIAT = [
|
||||
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK",
|
||||
@@ -49,7 +41,7 @@ CONF_SCHEMA = {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'max_open_trades': {'type': 'integer', 'minimum': -1},
|
||||
'ticker_interval': {'type': 'string', 'enum': list(TICKER_INTERVAL_MINUTES.keys())},
|
||||
'ticker_interval': {'type': 'string', 'enum': TICKER_INTERVALS},
|
||||
'stake_currency': {'type': 'string', 'enum': ['BTC', 'XBT', 'ETH', 'USDT', 'EUR', 'USD']},
|
||||
'stake_amount': {
|
||||
"type": ["number", "string"],
|
||||
@@ -58,6 +50,7 @@ CONF_SCHEMA = {
|
||||
},
|
||||
'fiat_display_currency': {'type': 'string', 'enum': SUPPORTED_FIAT},
|
||||
'dry_run': {'type': 'boolean'},
|
||||
'dry_run_wallet': {'type': 'number'},
|
||||
'process_only_new_candles': {'type': 'boolean'},
|
||||
'minimal_roi': {
|
||||
'type': 'object',
|
||||
@@ -66,10 +59,12 @@ CONF_SCHEMA = {
|
||||
},
|
||||
'minProperties': 1
|
||||
},
|
||||
'amount_reserve_percent': {'type': 'number', 'minimum': 0.0, 'maximum': 0.5},
|
||||
'stoploss': {'type': 'number', 'maximum': 0, 'exclusiveMaximum': True},
|
||||
'trailing_stop': {'type': 'boolean'},
|
||||
'trailing_stop_positive': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
||||
'trailing_stop_positive_offset': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
||||
'trailing_only_offset_is_reached': {'type': 'boolean'},
|
||||
'unfilledtimeout': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
@@ -112,7 +107,8 @@ CONF_SCHEMA = {
|
||||
'buy': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||
'sell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||
'stoploss': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||
'stoploss_on_exchange': {'type': 'boolean'}
|
||||
'stoploss_on_exchange': {'type': 'boolean'},
|
||||
'stoploss_on_exchange_interval': {'type': 'number'}
|
||||
},
|
||||
'required': ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
||||
},
|
||||
@@ -137,7 +133,7 @@ CONF_SCHEMA = {
|
||||
'pairlist': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'method': {'type': 'string', 'enum': AVAILABLE_PAIRLISTS},
|
||||
'method': {'type': 'string', 'enum': AVAILABLE_PAIRLISTS},
|
||||
'config': {'type': 'object'}
|
||||
},
|
||||
'required': ['method']
|
||||
@@ -167,7 +163,8 @@ CONF_SCHEMA = {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'process_throttle_secs': {'type': 'number'},
|
||||
'interval': {'type': 'integer'}
|
||||
'interval': {'type': 'integer'},
|
||||
'sd_notify': {'type': 'boolean'},
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -198,6 +195,7 @@ CONF_SCHEMA = {
|
||||
'uniqueItems': True
|
||||
},
|
||||
'outdated_offset': {'type': 'integer', 'minimum': 1},
|
||||
'markets_refresh_interval': {'type': 'integer'},
|
||||
'ccxt_config': {'type': 'object'},
|
||||
'ccxt_async_config': {'type': 'object'}
|
||||
},
|
||||
|
||||
67
freqtrade/data/btanalysis.py
Normal file
67
freqtrade/data/btanalysis.py
Normal file
@@ -0,0 +1,67 @@
|
||||
"""
|
||||
Helpers when analyzing backtest data
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from freqtrade.misc import json_load
|
||||
|
||||
# must align with columns in backtest.py
|
||||
BT_DATA_COLUMNS = ["pair", "profitperc", "open_time", "close_time", "index", "duration",
|
||||
"open_rate", "close_rate", "open_at_end", "sell_reason"]
|
||||
|
||||
|
||||
def load_backtest_data(filename) -> pd.DataFrame:
|
||||
"""
|
||||
Load backtest data file.
|
||||
:param filename: pathlib.Path object, or string pointing to the file.
|
||||
:return a dataframe with the analysis results
|
||||
"""
|
||||
if isinstance(filename, str):
|
||||
filename = Path(filename)
|
||||
|
||||
if not filename.is_file():
|
||||
raise ValueError("File {filename} does not exist.")
|
||||
|
||||
with filename.open() as file:
|
||||
data = json_load(file)
|
||||
|
||||
df = pd.DataFrame(data, columns=BT_DATA_COLUMNS)
|
||||
|
||||
df['open_time'] = pd.to_datetime(df['open_time'],
|
||||
unit='s',
|
||||
utc=True,
|
||||
infer_datetime_format=True
|
||||
)
|
||||
df['close_time'] = pd.to_datetime(df['close_time'],
|
||||
unit='s',
|
||||
utc=True,
|
||||
infer_datetime_format=True
|
||||
)
|
||||
df['profitabs'] = df['close_rate'] - df['open_rate']
|
||||
df = df.sort_values("open_time").reset_index(drop=True)
|
||||
return df
|
||||
|
||||
|
||||
def evaluate_result_multi(results: pd.DataFrame, freq: str, max_open_trades: int) -> pd.DataFrame:
|
||||
"""
|
||||
Find overlapping trades by expanding each trade once per period it was open
|
||||
and then counting overlaps
|
||||
:param results: Results Dataframe - can be loaded
|
||||
:param freq: Frequency used for the backtest
|
||||
:param max_open_trades: parameter max_open_trades used during backtest run
|
||||
:return: dataframe with open-counts per time-period in freq
|
||||
"""
|
||||
dates = [pd.Series(pd.date_range(row[1].open_time, row[1].close_time, freq=freq))
|
||||
for row in results[['open_time', 'close_time']].iterrows()]
|
||||
deltas = [len(x) for x in dates]
|
||||
dates = pd.Series(pd.concat(dates).values, name='date')
|
||||
df2 = pd.DataFrame(np.repeat(results.values, deltas, axis=0), columns=results.columns)
|
||||
|
||||
df2 = df2.astype(dtype={"open_time": "datetime64", "close_time": "datetime64"})
|
||||
df2 = pd.concat([dates, df2], axis=1)
|
||||
df2 = df2.set_index('date')
|
||||
df_final = df2.resample(freq)[['pair']].count()
|
||||
return df_final[df_final['pair'] > max_open_trades]
|
||||
@@ -4,14 +4,20 @@ Functions to convert data from one format to another
|
||||
import logging
|
||||
import pandas as pd
|
||||
from pandas import DataFrame, to_datetime
|
||||
from freqtrade.misc import timeframe_to_minutes
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def parse_ticker_dataframe(ticker: list) -> DataFrame:
|
||||
def parse_ticker_dataframe(ticker: list, ticker_interval: str,
|
||||
fill_missing: bool = True) -> DataFrame:
|
||||
"""
|
||||
Converts a ticker-list (format ccxt.fetch_ohlcv) to a Dataframe
|
||||
:param ticker: ticker list, as returned by exchange.async_get_candle_history
|
||||
:param ticker_interval: ticker_interval (e.g. 5m). Used to fill up eventual missing data
|
||||
:param fill_missing: fill up missing candles with 0 candles
|
||||
(see ohlcv_fill_up_missing_data for details)
|
||||
:return: DataFrame
|
||||
"""
|
||||
logger.debug("Parsing tickerlist to dataframe")
|
||||
@@ -23,6 +29,12 @@ def parse_ticker_dataframe(ticker: list) -> DataFrame:
|
||||
utc=True,
|
||||
infer_datetime_format=True)
|
||||
|
||||
# Some exchanges return int values for volume and even for ohlc.
|
||||
# Convert them since TA-LIB indicators used in the strategy assume floats
|
||||
# and fail with exception...
|
||||
frame = frame.astype(dtype={'open': 'float', 'high': 'float', 'low': 'float', 'close': 'float',
|
||||
'volume': 'float'})
|
||||
|
||||
# group by index and aggregate results to eliminate duplicate ticks
|
||||
frame = frame.groupby(by='date', as_index=False, sort=True).agg({
|
||||
'open': 'first',
|
||||
@@ -33,7 +45,41 @@ def parse_ticker_dataframe(ticker: list) -> DataFrame:
|
||||
})
|
||||
frame.drop(frame.tail(1).index, inplace=True) # eliminate partial candle
|
||||
logger.debug('Dropping last candle')
|
||||
return frame
|
||||
|
||||
if fill_missing:
|
||||
return ohlcv_fill_up_missing_data(frame, ticker_interval)
|
||||
else:
|
||||
return frame
|
||||
|
||||
|
||||
def ohlcv_fill_up_missing_data(dataframe: DataFrame, ticker_interval: str) -> DataFrame:
|
||||
"""
|
||||
Fills up missing data with 0 volume rows,
|
||||
using the previous close as price for "open", "high" "low" and "close", volume is set to 0
|
||||
|
||||
"""
|
||||
ohlc_dict = {
|
||||
'open': 'first',
|
||||
'high': 'max',
|
||||
'low': 'min',
|
||||
'close': 'last',
|
||||
'volume': 'sum'
|
||||
}
|
||||
ticker_minutes = timeframe_to_minutes(ticker_interval)
|
||||
# Resample to create "NAN" values
|
||||
df = dataframe.resample(f'{ticker_minutes}min', on='date').agg(ohlc_dict)
|
||||
|
||||
# Forwardfill close for missing columns
|
||||
df['close'] = df['close'].fillna(method='ffill')
|
||||
# Use close for "open, high, low"
|
||||
df.loc[:, ['open', 'high', 'low']] = df[['open', 'high', 'low']].fillna(
|
||||
value={'open': df['close'],
|
||||
'high': df['close'],
|
||||
'low': df['close'],
|
||||
})
|
||||
df.reset_index(inplace=True)
|
||||
logger.debug(f"Missing data fillup: before: {len(dataframe)} - after: {len(df)}")
|
||||
return df
|
||||
|
||||
|
||||
def order_book_to_dataframe(bids: list, asks: list) -> DataFrame:
|
||||
|
||||
97
freqtrade/data/dataprovider.py
Normal file
97
freqtrade/data/dataprovider.py
Normal file
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
Dataprovider
|
||||
Responsible to provide data to the bot
|
||||
including Klines, tickers, historic data
|
||||
Common Interface for bot and strategy to access data.
|
||||
"""
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import List, Tuple
|
||||
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.data.history import load_pair_history
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DataProvider(object):
|
||||
|
||||
def __init__(self, config: dict, exchange: Exchange) -> None:
|
||||
self._config = config
|
||||
self._exchange = exchange
|
||||
|
||||
def refresh(self,
|
||||
pairlist: List[Tuple[str, str]],
|
||||
helping_pairs: List[Tuple[str, str]] = None) -> None:
|
||||
"""
|
||||
Refresh data, called with each cycle
|
||||
"""
|
||||
if helping_pairs:
|
||||
self._exchange.refresh_latest_ohlcv(pairlist + helping_pairs)
|
||||
else:
|
||||
self._exchange.refresh_latest_ohlcv(pairlist)
|
||||
|
||||
@property
|
||||
def available_pairs(self) -> List[Tuple[str, str]]:
|
||||
"""
|
||||
Return a list of tuples containing pair, ticker_interval for which data is currently cached.
|
||||
Should be whitelist + open trades.
|
||||
"""
|
||||
return list(self._exchange._klines.keys())
|
||||
|
||||
def ohlcv(self, pair: str, ticker_interval: str = None, copy: bool = True) -> DataFrame:
|
||||
"""
|
||||
get ohlcv data for the given pair as DataFrame
|
||||
Please check `available_pairs` to verify which pairs are currently cached.
|
||||
:param pair: pair to get the data for
|
||||
:param ticker_interval: ticker_interval to get pair for
|
||||
:param copy: copy dataframe before returning.
|
||||
Use false only for RO operations (where the dataframe is not modified)
|
||||
"""
|
||||
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
||||
if ticker_interval:
|
||||
pairtick = (pair, ticker_interval)
|
||||
else:
|
||||
pairtick = (pair, self._config['ticker_interval'])
|
||||
|
||||
return self._exchange.klines(pairtick, copy=copy)
|
||||
else:
|
||||
return DataFrame()
|
||||
|
||||
def historic_ohlcv(self, pair: str, ticker_interval: str) -> DataFrame:
|
||||
"""
|
||||
get stored historic ohlcv data
|
||||
:param pair: pair to get the data for
|
||||
:param ticker_interval: ticker_interval to get pair for
|
||||
"""
|
||||
return load_pair_history(pair=pair,
|
||||
ticker_interval=ticker_interval,
|
||||
refresh_pairs=False,
|
||||
datadir=Path(self._config['datadir']) if self._config.get(
|
||||
'datadir') else None
|
||||
)
|
||||
|
||||
def ticker(self, pair: str):
|
||||
"""
|
||||
Return last ticker data
|
||||
"""
|
||||
# TODO: Implement me
|
||||
pass
|
||||
|
||||
def orderbook(self, pair: str, max: int):
|
||||
"""
|
||||
return latest orderbook data
|
||||
"""
|
||||
# TODO: Implement me
|
||||
pass
|
||||
|
||||
@property
|
||||
def runmode(self) -> RunMode:
|
||||
"""
|
||||
Get runmode of the bot
|
||||
can be "live", "dry-run", "backtest", "edgecli", "hyperopt" or "other".
|
||||
"""
|
||||
return RunMode(self._config.get('runmode', RunMode.OTHER))
|
||||
@@ -5,33 +5,23 @@ includes:
|
||||
* download data from exchange and store to disk
|
||||
"""
|
||||
|
||||
import gzip
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Optional, List, Dict, Tuple, Any
|
||||
|
||||
import arrow
|
||||
from pandas import DataFrame
|
||||
import ujson
|
||||
|
||||
from freqtrade import misc, constants, OperationalException
|
||||
from freqtrade import misc, OperationalException
|
||||
from freqtrade.arguments import TimeRange
|
||||
from freqtrade.data.converter import parse_ticker_dataframe
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.arguments import TimeRange
|
||||
from freqtrade.misc import timeframe_to_minutes
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def json_load(data):
|
||||
"""
|
||||
load data with ujson
|
||||
Use this to have a consistent experience,
|
||||
otherwise "precise_float" needs to be passed to all load operations
|
||||
"""
|
||||
return ujson.load(data, precise_float=True)
|
||||
|
||||
|
||||
def trim_tickerlist(tickerlist: List[Dict], timerange: TimeRange) -> List[Dict]:
|
||||
"""
|
||||
Trim tickerlist based on given timerange
|
||||
@@ -77,18 +67,10 @@ def load_tickerdata_file(
|
||||
path = make_testdata_path(datadir)
|
||||
pair_s = pair.replace('/', '_')
|
||||
file = path.joinpath(f'{pair_s}-{ticker_interval}.json')
|
||||
gzipfile = file.with_suffix(file.suffix + '.gz')
|
||||
|
||||
# Try gzip file first, otherwise regular json file.
|
||||
if gzipfile.is_file():
|
||||
logger.debug('Loading ticker data from file %s', gzipfile)
|
||||
with gzip.open(gzipfile) as tickerdata:
|
||||
pairdata = json_load(tickerdata)
|
||||
elif file.is_file():
|
||||
logger.debug('Loading ticker data from file %s', file)
|
||||
with open(file) as tickerdata:
|
||||
pairdata = json_load(tickerdata)
|
||||
else:
|
||||
pairdata = misc.file_load_json(file)
|
||||
|
||||
if not pairdata:
|
||||
return None
|
||||
|
||||
if timerange:
|
||||
@@ -102,26 +84,28 @@ def load_pair_history(pair: str,
|
||||
timerange: TimeRange = TimeRange(None, None, 0, 0),
|
||||
refresh_pairs: bool = False,
|
||||
exchange: Optional[Exchange] = None,
|
||||
fill_up_missing: bool = True
|
||||
) -> DataFrame:
|
||||
"""
|
||||
Loads cached ticker history for the given pair.
|
||||
:return: DataFrame with ohlcv data
|
||||
"""
|
||||
|
||||
pairdata = load_tickerdata_file(datadir, pair, ticker_interval, timerange=timerange)
|
||||
# If the user force the refresh of pairs
|
||||
if refresh_pairs:
|
||||
if not exchange:
|
||||
raise OperationalException("Exchange needs to be initialized when "
|
||||
"calling load_data with refresh_pairs=True")
|
||||
|
||||
logger.info('Download data for all pairs and store them in %s', datadir)
|
||||
logger.info('Download data for pair and store them in %s', datadir)
|
||||
download_pair_history(datadir=datadir,
|
||||
exchange=exchange,
|
||||
pair=pair,
|
||||
tick_interval=ticker_interval,
|
||||
ticker_interval=ticker_interval,
|
||||
timerange=timerange)
|
||||
|
||||
pairdata = load_tickerdata_file(datadir, pair, ticker_interval, timerange=timerange)
|
||||
|
||||
if pairdata:
|
||||
if timerange.starttype == 'date' and pairdata[0][0] > timerange.startts * 1000:
|
||||
logger.warning('Missing data at start for pair %s, data starts at %s',
|
||||
@@ -130,7 +114,7 @@ def load_pair_history(pair: str,
|
||||
logger.warning('Missing data at end for pair %s, data ends at %s',
|
||||
pair,
|
||||
arrow.get(pairdata[-1][0] // 1000).strftime('%Y-%m-%d %H:%M:%S'))
|
||||
return parse_ticker_dataframe(pairdata)
|
||||
return parse_ticker_dataframe(pairdata, ticker_interval, fill_up_missing)
|
||||
else:
|
||||
logger.warning('No data for pair: "%s", Interval: %s. '
|
||||
'Use --refresh-pairs-cached to download the data',
|
||||
@@ -143,7 +127,8 @@ def load_data(datadir: Optional[Path],
|
||||
pairs: List[str],
|
||||
refresh_pairs: bool = False,
|
||||
exchange: Optional[Exchange] = None,
|
||||
timerange: TimeRange = TimeRange(None, None, 0, 0)) -> Dict[str, DataFrame]:
|
||||
timerange: TimeRange = TimeRange(None, None, 0, 0),
|
||||
fill_up_missing: bool = True) -> Dict[str, DataFrame]:
|
||||
"""
|
||||
Loads ticker history data for a list of pairs the given parameters
|
||||
:return: dict(<pair>:<tickerlist>)
|
||||
@@ -154,7 +139,8 @@ def load_data(datadir: Optional[Path],
|
||||
hist = load_pair_history(pair=pair, ticker_interval=ticker_interval,
|
||||
datadir=datadir, timerange=timerange,
|
||||
refresh_pairs=refresh_pairs,
|
||||
exchange=exchange)
|
||||
exchange=exchange,
|
||||
fill_up_missing=fill_up_missing)
|
||||
if hist is not None:
|
||||
result[pair] = hist
|
||||
return result
|
||||
@@ -165,7 +151,7 @@ def make_testdata_path(datadir: Optional[Path]) -> Path:
|
||||
return datadir or (Path(__file__).parent.parent / "tests" / "testdata").resolve()
|
||||
|
||||
|
||||
def load_cached_data_for_updating(filename: Path, tick_interval: str,
|
||||
def load_cached_data_for_updating(filename: Path, ticker_interval: str,
|
||||
timerange: Optional[TimeRange]) -> Tuple[List[Any],
|
||||
Optional[int]]:
|
||||
"""
|
||||
@@ -179,13 +165,13 @@ def load_cached_data_for_updating(filename: Path, tick_interval: str,
|
||||
if timerange.starttype == 'date':
|
||||
since_ms = timerange.startts * 1000
|
||||
elif timerange.stoptype == 'line':
|
||||
num_minutes = timerange.stopts * constants.TICKER_INTERVAL_MINUTES[tick_interval]
|
||||
num_minutes = timerange.stopts * timeframe_to_minutes(ticker_interval)
|
||||
since_ms = arrow.utcnow().shift(minutes=num_minutes).timestamp * 1000
|
||||
|
||||
# read the cached file
|
||||
if filename.is_file():
|
||||
with open(filename, "rt") as file:
|
||||
data = json_load(file)
|
||||
data = misc.json_load(file)
|
||||
# remove the last item, could be incomplete candle
|
||||
if data:
|
||||
data.pop()
|
||||
@@ -206,7 +192,7 @@ def load_cached_data_for_updating(filename: Path, tick_interval: str,
|
||||
def download_pair_history(datadir: Optional[Path],
|
||||
exchange: Exchange,
|
||||
pair: str,
|
||||
tick_interval: str = '5m',
|
||||
ticker_interval: str = '5m',
|
||||
timerange: Optional[TimeRange] = None) -> bool:
|
||||
"""
|
||||
Download the latest ticker intervals from the exchange for the pair passed in parameters
|
||||
@@ -216,7 +202,7 @@ def download_pair_history(datadir: Optional[Path],
|
||||
|
||||
Based on @Rybolov work: https://github.com/rybolov/freqtrade-data
|
||||
:param pair: pair to download
|
||||
:param tick_interval: ticker interval
|
||||
:param ticker_interval: ticker interval
|
||||
:param timerange: range of time to download
|
||||
:return: bool with success state
|
||||
|
||||
@@ -224,17 +210,17 @@ def download_pair_history(datadir: Optional[Path],
|
||||
try:
|
||||
path = make_testdata_path(datadir)
|
||||
filepair = pair.replace("/", "_")
|
||||
filename = path.joinpath(f'{filepair}-{tick_interval}.json')
|
||||
filename = path.joinpath(f'{filepair}-{ticker_interval}.json')
|
||||
|
||||
logger.info('Download the pair: "%s", Interval: %s', pair, tick_interval)
|
||||
logger.info('Download the pair: "%s", Interval: %s', pair, ticker_interval)
|
||||
|
||||
data, since_ms = load_cached_data_for_updating(filename, tick_interval, timerange)
|
||||
data, since_ms = load_cached_data_for_updating(filename, ticker_interval, timerange)
|
||||
|
||||
logger.debug("Current Start: %s", misc.format_ms_time(data[1][0]) if data else 'None')
|
||||
logger.debug("Current End: %s", misc.format_ms_time(data[-1][0]) if data else 'None')
|
||||
|
||||
# Default since_ms to 30 days if nothing is given
|
||||
new_data = exchange.get_history(pair=pair, tick_interval=tick_interval,
|
||||
new_data = exchange.get_history(pair=pair, ticker_interval=ticker_interval,
|
||||
since_ms=since_ms if since_ms
|
||||
else
|
||||
int(arrow.utcnow().shift(days=-30).float_timestamp) * 1000)
|
||||
@@ -246,6 +232,6 @@ def download_pair_history(datadir: Optional[Path],
|
||||
misc.file_dump_json(filename, data)
|
||||
return True
|
||||
except BaseException:
|
||||
logger.info('Failed to download the pair: "%s", Interval: %s',
|
||||
pair, tick_interval)
|
||||
return False
|
||||
logger.info('Failed to download the pair: "%s", Interval: %s',
|
||||
pair, ticker_interval)
|
||||
return False
|
||||
|
||||
@@ -59,7 +59,7 @@ class Edge():
|
||||
|
||||
# checking max_open_trades. it should be -1 as with Edge
|
||||
# the number of trades is determined by position size
|
||||
if self.config['max_open_trades'] != -1:
|
||||
if self.config['max_open_trades'] != float('inf'):
|
||||
logger.critical('max_open_trades should be -1 in config !')
|
||||
|
||||
if self.config['stake_amount'] != constants.UNLIMITED_STAKE_AMOUNT:
|
||||
@@ -190,12 +190,35 @@ class Edge():
|
||||
if self._final_pairs != final:
|
||||
self._final_pairs = final
|
||||
if self._final_pairs:
|
||||
logger.info('Edge validated only %s', self._final_pairs)
|
||||
logger.info(
|
||||
'Minimum expectancy and minimum winrate are met only for %s,'
|
||||
' so other pairs are filtered out.',
|
||||
self._final_pairs
|
||||
)
|
||||
else:
|
||||
logger.info('Edge removed all pairs as no pair with minimum expectancy was found !')
|
||||
logger.info(
|
||||
'Edge removed all pairs as no pair with minimum expectancy '
|
||||
'and minimum winrate was found !'
|
||||
)
|
||||
|
||||
return self._final_pairs
|
||||
|
||||
def accepted_pairs(self) -> list:
|
||||
"""
|
||||
return a list of accepted pairs along with their winrate, expectancy and stoploss
|
||||
"""
|
||||
final = []
|
||||
for pair, info in self._cached_pairs.items():
|
||||
if info.expectancy > float(self.edge_config.get('minimum_expectancy', 0.2)) and \
|
||||
info.winrate > float(self.edge_config.get('minimum_winrate', 0.60)):
|
||||
final.append({
|
||||
'Pair': pair,
|
||||
'Winrate': info.winrate,
|
||||
'Expectancy': info.expectancy,
|
||||
'Stoploss': info.stoploss,
|
||||
})
|
||||
return final
|
||||
|
||||
def _fill_calculable_fields(self, result: DataFrame) -> DataFrame:
|
||||
"""
|
||||
The result frame contains a number of columns that are calculable
|
||||
@@ -344,91 +367,93 @@ class Edge():
|
||||
return result
|
||||
|
||||
def _detect_next_stop_or_sell_point(self, buy_column, sell_column, date_column,
|
||||
ohlc_columns, stoploss, pair, start_point=0):
|
||||
ohlc_columns, stoploss, pair):
|
||||
"""
|
||||
Iterate through ohlc_columns recursively in order to find the next trade
|
||||
Iterate through ohlc_columns in order to find the next trade
|
||||
Next trade opens from the first buy signal noticed to
|
||||
The sell or stoploss signal after it.
|
||||
It then calls itself cutting OHLC, buy_column, sell_colum and date_column
|
||||
Cut from (the exit trade index) + 1
|
||||
It then cuts OHLC, buy_column, sell_column and date_column.
|
||||
Cut from (the exit trade index) + 1.
|
||||
|
||||
Author: https://github.com/mishaker
|
||||
"""
|
||||
|
||||
result: list = []
|
||||
open_trade_index = utf1st.find_1st(buy_column, 1, utf1st.cmp_equal)
|
||||
start_point = 0
|
||||
|
||||
# return empty if we don't find trade entry (i.e. buy==1) or
|
||||
# we find a buy but at the of array
|
||||
if open_trade_index == -1 or open_trade_index == len(buy_column) - 1:
|
||||
return []
|
||||
else:
|
||||
open_trade_index += 1 # when a buy signal is seen,
|
||||
# trade opens in reality on the next candle
|
||||
while True:
|
||||
open_trade_index = utf1st.find_1st(buy_column, 1, utf1st.cmp_equal)
|
||||
|
||||
stop_price_percentage = stoploss + 1
|
||||
open_price = ohlc_columns[open_trade_index, 0]
|
||||
stop_price = (open_price * stop_price_percentage)
|
||||
# Return empty if we don't find trade entry (i.e. buy==1) or
|
||||
# we find a buy but at the end of array
|
||||
if open_trade_index == -1 or open_trade_index == len(buy_column) - 1:
|
||||
break
|
||||
else:
|
||||
# When a buy signal is seen,
|
||||
# trade opens in reality on the next candle
|
||||
open_trade_index += 1
|
||||
|
||||
# Searching for the index where stoploss is hit
|
||||
stop_index = utf1st.find_1st(
|
||||
ohlc_columns[open_trade_index:, 2], stop_price, utf1st.cmp_smaller)
|
||||
stop_price_percentage = stoploss + 1
|
||||
open_price = ohlc_columns[open_trade_index, 0]
|
||||
stop_price = (open_price * stop_price_percentage)
|
||||
|
||||
# If we don't find it then we assume stop_index will be far in future (infinite number)
|
||||
if stop_index == -1:
|
||||
stop_index = float('inf')
|
||||
# Searching for the index where stoploss is hit
|
||||
stop_index = utf1st.find_1st(
|
||||
ohlc_columns[open_trade_index:, 2], stop_price, utf1st.cmp_smaller)
|
||||
|
||||
# Searching for the index where sell is hit
|
||||
sell_index = utf1st.find_1st(sell_column[open_trade_index:], 1, utf1st.cmp_equal)
|
||||
# If we don't find it then we assume stop_index will be far in future (infinite number)
|
||||
if stop_index == -1:
|
||||
stop_index = float('inf')
|
||||
|
||||
# If we don't find it then we assume sell_index will be far in future (infinite number)
|
||||
if sell_index == -1:
|
||||
sell_index = float('inf')
|
||||
# Searching for the index where sell is hit
|
||||
sell_index = utf1st.find_1st(sell_column[open_trade_index:], 1, utf1st.cmp_equal)
|
||||
|
||||
# Check if we don't find any stop or sell point (in that case trade remains open)
|
||||
# It is not interesting for Edge to consider it so we simply ignore the trade
|
||||
# And stop iterating there is no more entry
|
||||
if stop_index == sell_index == float('inf'):
|
||||
return []
|
||||
# If we don't find it then we assume sell_index will be far in future (infinite number)
|
||||
if sell_index == -1:
|
||||
sell_index = float('inf')
|
||||
|
||||
if stop_index <= sell_index:
|
||||
exit_index = open_trade_index + stop_index
|
||||
exit_type = SellType.STOP_LOSS
|
||||
exit_price = stop_price
|
||||
elif stop_index > sell_index:
|
||||
# if exit is SELL then we exit at the next candle
|
||||
exit_index = open_trade_index + sell_index + 1
|
||||
# Check if we don't find any stop or sell point (in that case trade remains open)
|
||||
# It is not interesting for Edge to consider it so we simply ignore the trade
|
||||
# And stop iterating there is no more entry
|
||||
if stop_index == sell_index == float('inf'):
|
||||
break
|
||||
|
||||
# check if we have the next candle
|
||||
if len(ohlc_columns) - 1 < exit_index:
|
||||
return []
|
||||
if stop_index <= sell_index:
|
||||
exit_index = open_trade_index + stop_index
|
||||
exit_type = SellType.STOP_LOSS
|
||||
exit_price = stop_price
|
||||
elif stop_index > sell_index:
|
||||
# If exit is SELL then we exit at the next candle
|
||||
exit_index = open_trade_index + sell_index + 1
|
||||
|
||||
exit_type = SellType.SELL_SIGNAL
|
||||
exit_price = ohlc_columns[exit_index, 0]
|
||||
# Check if we have the next candle
|
||||
if len(ohlc_columns) - 1 < exit_index:
|
||||
break
|
||||
|
||||
trade = {'pair': pair,
|
||||
'stoploss': stoploss,
|
||||
'profit_percent': '',
|
||||
'profit_abs': '',
|
||||
'open_time': date_column[open_trade_index],
|
||||
'close_time': date_column[exit_index],
|
||||
'open_index': start_point + open_trade_index,
|
||||
'close_index': start_point + exit_index,
|
||||
'trade_duration': '',
|
||||
'open_rate': round(open_price, 15),
|
||||
'close_rate': round(exit_price, 15),
|
||||
'exit_type': exit_type
|
||||
}
|
||||
exit_type = SellType.SELL_SIGNAL
|
||||
exit_price = ohlc_columns[exit_index, 0]
|
||||
|
||||
result.append(trade)
|
||||
trade = {'pair': pair,
|
||||
'stoploss': stoploss,
|
||||
'profit_percent': '',
|
||||
'profit_abs': '',
|
||||
'open_time': date_column[open_trade_index],
|
||||
'close_time': date_column[exit_index],
|
||||
'open_index': start_point + open_trade_index,
|
||||
'close_index': start_point + exit_index,
|
||||
'trade_duration': '',
|
||||
'open_rate': round(open_price, 15),
|
||||
'close_rate': round(exit_price, 15),
|
||||
'exit_type': exit_type
|
||||
}
|
||||
|
||||
# Calling again the same function recursively but giving
|
||||
# it a view of exit_index till the end of array
|
||||
return result + self._detect_next_stop_or_sell_point(
|
||||
buy_column[exit_index:],
|
||||
sell_column[exit_index:],
|
||||
date_column[exit_index:],
|
||||
ohlc_columns[exit_index:],
|
||||
stoploss,
|
||||
pair,
|
||||
(start_point + exit_index)
|
||||
)
|
||||
result.append(trade)
|
||||
|
||||
# Giving a view of exit_index till the end of array
|
||||
buy_column = buy_column[exit_index:]
|
||||
sell_column = sell_column[exit_index:]
|
||||
date_column = date_column[exit_index:]
|
||||
ohlc_columns = ohlc_columns[exit_index:]
|
||||
start_point += exit_index
|
||||
|
||||
return result
|
||||
|
||||
@@ -1,713 +1,3 @@
|
||||
# pragma pylint: disable=W0603
|
||||
""" Cryptocurrency Exchanges support """
|
||||
import logging
|
||||
import inspect
|
||||
from random import randint
|
||||
from typing import List, Dict, Tuple, Any, Optional
|
||||
from datetime import datetime
|
||||
from math import floor, ceil
|
||||
|
||||
import arrow
|
||||
import asyncio
|
||||
import ccxt
|
||||
import ccxt.async_support as ccxt_async
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade import constants, OperationalException, DependencyException, TemporaryError
|
||||
from freqtrade.data.converter import parse_ticker_dataframe
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
API_RETRY_COUNT = 4
|
||||
|
||||
|
||||
# Urls to exchange markets, insert quote and base with .format()
|
||||
_EXCHANGE_URLS = {
|
||||
ccxt.bittrex.__name__: '/Market/Index?MarketName={quote}-{base}',
|
||||
ccxt.binance.__name__: '/tradeDetail.html?symbol={base}_{quote}'
|
||||
}
|
||||
|
||||
|
||||
def retrier_async(f):
|
||||
async def wrapper(*args, **kwargs):
|
||||
count = kwargs.pop('count', API_RETRY_COUNT)
|
||||
try:
|
||||
return await f(*args, **kwargs)
|
||||
except (TemporaryError, DependencyException) as ex:
|
||||
logger.warning('%s() returned exception: "%s"', f.__name__, ex)
|
||||
if count > 0:
|
||||
count -= 1
|
||||
kwargs.update({'count': count})
|
||||
logger.warning('retrying %s() still for %s times', f.__name__, count)
|
||||
return await wrapper(*args, **kwargs)
|
||||
else:
|
||||
logger.warning('Giving up retrying: %s()', f.__name__)
|
||||
raise ex
|
||||
return wrapper
|
||||
|
||||
|
||||
def retrier(f):
|
||||
def wrapper(*args, **kwargs):
|
||||
count = kwargs.pop('count', API_RETRY_COUNT)
|
||||
try:
|
||||
return f(*args, **kwargs)
|
||||
except (TemporaryError, DependencyException) as ex:
|
||||
logger.warning('%s() returned exception: "%s"', f.__name__, ex)
|
||||
if count > 0:
|
||||
count -= 1
|
||||
kwargs.update({'count': count})
|
||||
logger.warning('retrying %s() still for %s times', f.__name__, count)
|
||||
return wrapper(*args, **kwargs)
|
||||
else:
|
||||
logger.warning('Giving up retrying: %s()', f.__name__)
|
||||
raise ex
|
||||
return wrapper
|
||||
|
||||
|
||||
class Exchange(object):
|
||||
|
||||
_conf: Dict = {}
|
||||
|
||||
def __init__(self, config: dict) -> None:
|
||||
"""
|
||||
Initializes this module with the given config,
|
||||
it does basic validation whether the specified
|
||||
exchange and pairs are valid.
|
||||
:return: None
|
||||
"""
|
||||
self._conf.update(config)
|
||||
|
||||
self._cached_ticker: Dict[str, Any] = {}
|
||||
|
||||
# Holds last candle refreshed time of each pair
|
||||
self._pairs_last_refresh_time: Dict[str, int] = {}
|
||||
|
||||
# Holds candles
|
||||
self._klines: Dict[str, DataFrame] = {}
|
||||
|
||||
# Holds all open sell orders for dry_run
|
||||
self._dry_run_open_orders: Dict[str, Any] = {}
|
||||
|
||||
if config['dry_run']:
|
||||
logger.info('Instance is running with dry_run enabled')
|
||||
|
||||
exchange_config = config['exchange']
|
||||
self._api: ccxt.Exchange = self._init_ccxt(
|
||||
exchange_config, ccxt_kwargs=exchange_config.get('ccxt_config'))
|
||||
self._api_async: ccxt_async.Exchange = self._init_ccxt(
|
||||
exchange_config, ccxt_async, ccxt_kwargs=exchange_config.get('ccxt_async_config'))
|
||||
|
||||
logger.info('Using Exchange "%s"', self.name)
|
||||
|
||||
self.markets = self._load_markets()
|
||||
# Check if all pairs are available
|
||||
self.validate_pairs(config['exchange']['pair_whitelist'])
|
||||
self.validate_ordertypes(config.get('order_types', {}))
|
||||
self.validate_order_time_in_force(config.get('order_time_in_force', {}))
|
||||
if config.get('ticker_interval'):
|
||||
# Check if timeframe is available
|
||||
self.validate_timeframes(config['ticker_interval'])
|
||||
|
||||
def __del__(self):
|
||||
"""
|
||||
Destructor - clean up async stuff
|
||||
"""
|
||||
logger.debug("Exchange object destroyed, closing async loop")
|
||||
if self._api_async and inspect.iscoroutinefunction(self._api_async.close):
|
||||
asyncio.get_event_loop().run_until_complete(self._api_async.close())
|
||||
|
||||
def _init_ccxt(self, exchange_config: dict, ccxt_module=ccxt,
|
||||
ccxt_kwargs: dict = None) -> ccxt.Exchange:
|
||||
"""
|
||||
Initialize ccxt with given config and return valid
|
||||
ccxt instance.
|
||||
"""
|
||||
# Find matching class for the given exchange name
|
||||
name = exchange_config['name']
|
||||
|
||||
if name not in ccxt_module.exchanges:
|
||||
raise OperationalException(f'Exchange {name} is not supported')
|
||||
|
||||
ex_config = {
|
||||
'apiKey': exchange_config.get('key'),
|
||||
'secret': exchange_config.get('secret'),
|
||||
'password': exchange_config.get('password'),
|
||||
'uid': exchange_config.get('uid', ''),
|
||||
'enableRateLimit': exchange_config.get('ccxt_rate_limit', True)
|
||||
}
|
||||
if ccxt_kwargs:
|
||||
logger.info('Applying additional ccxt config: %s', ccxt_kwargs)
|
||||
ex_config.update(ccxt_kwargs)
|
||||
try:
|
||||
|
||||
api = getattr(ccxt_module, name.lower())(ex_config)
|
||||
except (KeyError, AttributeError):
|
||||
raise OperationalException(f'Exchange {name} is not supported')
|
||||
|
||||
self.set_sandbox(api, exchange_config, name)
|
||||
|
||||
return api
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""exchange Name (from ccxt)"""
|
||||
return self._api.name
|
||||
|
||||
@property
|
||||
def id(self) -> str:
|
||||
"""exchange ccxt id"""
|
||||
return self._api.id
|
||||
|
||||
def klines(self, pair: str, copy=True) -> DataFrame:
|
||||
if pair in self._klines:
|
||||
return self._klines[pair].copy() if copy else self._klines[pair]
|
||||
else:
|
||||
return None
|
||||
|
||||
def set_sandbox(self, api, exchange_config: dict, name: str):
|
||||
if exchange_config.get('sandbox'):
|
||||
if api.urls.get('test'):
|
||||
api.urls['api'] = api.urls['test']
|
||||
logger.info("Enabled Sandbox API on %s", name)
|
||||
else:
|
||||
logger.warning(name, "No Sandbox URL in CCXT, exiting. "
|
||||
"Please check your config.json")
|
||||
raise OperationalException(f'Exchange {name} does not provide a sandbox api')
|
||||
|
||||
def _load_async_markets(self) -> None:
|
||||
try:
|
||||
if self._api_async:
|
||||
asyncio.get_event_loop().run_until_complete(self._api_async.load_markets())
|
||||
|
||||
except ccxt.BaseError as e:
|
||||
logger.warning('Could not load async markets. Reason: %s', e)
|
||||
return
|
||||
|
||||
def _load_markets(self) -> Dict[str, Any]:
|
||||
""" Initialize markets both sync and async """
|
||||
try:
|
||||
markets = self._api.load_markets()
|
||||
self._load_async_markets()
|
||||
return markets
|
||||
except ccxt.BaseError as e:
|
||||
logger.warning('Unable to initialize markets. Reason: %s', e)
|
||||
return {}
|
||||
|
||||
def validate_pairs(self, pairs: List[str]) -> None:
|
||||
"""
|
||||
Checks if all given pairs are tradable on the current exchange.
|
||||
Raises OperationalException if one pair is not available.
|
||||
:param pairs: list of pairs
|
||||
:return: None
|
||||
"""
|
||||
|
||||
if not self.markets:
|
||||
logger.warning('Unable to validate pairs (assuming they are correct).')
|
||||
# return
|
||||
|
||||
stake_cur = self._conf['stake_currency']
|
||||
for pair in pairs:
|
||||
# Note: ccxt has BaseCurrency/QuoteCurrency format for pairs
|
||||
# TODO: add a support for having coins in BTC/USDT format
|
||||
if not pair.endswith(stake_cur):
|
||||
raise OperationalException(
|
||||
f'Pair {pair} not compatible with stake_currency: {stake_cur}')
|
||||
if self.markets and pair not in self.markets:
|
||||
raise OperationalException(
|
||||
f'Pair {pair} is not available at {self.name}'
|
||||
f'Please remove {pair} from your whitelist.')
|
||||
|
||||
def validate_timeframes(self, timeframe: List[str]) -> None:
|
||||
"""
|
||||
Checks if ticker interval from config is a supported timeframe on the exchange
|
||||
"""
|
||||
timeframes = self._api.timeframes
|
||||
if timeframe not in timeframes:
|
||||
raise OperationalException(
|
||||
f'Invalid ticker {timeframe}, this Exchange supports {timeframes}')
|
||||
|
||||
def validate_ordertypes(self, order_types: Dict) -> None:
|
||||
"""
|
||||
Checks if order-types configured in strategy/config are supported
|
||||
"""
|
||||
if any(v == 'market' for k, v in order_types.items()):
|
||||
if not self.exchange_has('createMarketOrder'):
|
||||
raise OperationalException(
|
||||
f'Exchange {self.name} does not support market orders.')
|
||||
|
||||
if order_types.get('stoploss_on_exchange'):
|
||||
if self.name is not 'Binance':
|
||||
raise OperationalException(
|
||||
'On exchange stoploss is not supported for %s.' % self.name
|
||||
)
|
||||
|
||||
def validate_order_time_in_force(self, order_time_in_force: Dict) -> None:
|
||||
"""
|
||||
Checks if order time in force configured in strategy/config are supported
|
||||
"""
|
||||
if any(v != 'gtc' for k, v in order_time_in_force.items()):
|
||||
if self.name is not 'Binance':
|
||||
raise OperationalException(
|
||||
f'Time in force policies are not supporetd for {self.name} yet.')
|
||||
|
||||
def exchange_has(self, endpoint: str) -> bool:
|
||||
"""
|
||||
Checks if exchange implements a specific API endpoint.
|
||||
Wrapper around ccxt 'has' attribute
|
||||
:param endpoint: Name of endpoint (e.g. 'fetchOHLCV', 'fetchTickers')
|
||||
:return: bool
|
||||
"""
|
||||
return endpoint in self._api.has and self._api.has[endpoint]
|
||||
|
||||
def symbol_amount_prec(self, pair, amount: float):
|
||||
'''
|
||||
Returns the amount to buy or sell to a precision the Exchange accepts
|
||||
Rounded down
|
||||
'''
|
||||
if self._api.markets[pair]['precision']['amount']:
|
||||
symbol_prec = self._api.markets[pair]['precision']['amount']
|
||||
big_amount = amount * pow(10, symbol_prec)
|
||||
amount = floor(big_amount) / pow(10, symbol_prec)
|
||||
return amount
|
||||
|
||||
def symbol_price_prec(self, pair, price: float):
|
||||
'''
|
||||
Returns the price buying or selling with to the precision the Exchange accepts
|
||||
Rounds up
|
||||
'''
|
||||
if self._api.markets[pair]['precision']['price']:
|
||||
symbol_prec = self._api.markets[pair]['precision']['price']
|
||||
big_price = price * pow(10, symbol_prec)
|
||||
price = ceil(big_price) / pow(10, symbol_prec)
|
||||
return price
|
||||
|
||||
def buy(self, pair: str, ordertype: str, amount: float,
|
||||
rate: float, time_in_force) -> Dict:
|
||||
if self._conf['dry_run']:
|
||||
order_id = f'dry_run_buy_{randint(0, 10**6)}'
|
||||
self._dry_run_open_orders[order_id] = {
|
||||
'pair': pair,
|
||||
'price': rate,
|
||||
'amount': amount,
|
||||
'type': ordertype,
|
||||
'side': 'buy',
|
||||
'remaining': 0.0,
|
||||
'datetime': arrow.utcnow().isoformat(),
|
||||
'status': 'closed',
|
||||
'fee': None
|
||||
}
|
||||
return {'id': order_id}
|
||||
|
||||
try:
|
||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
||||
amount = self.symbol_amount_prec(pair, amount)
|
||||
rate = self.symbol_price_prec(pair, rate) if ordertype != 'market' else None
|
||||
|
||||
if time_in_force == 'gtc':
|
||||
return self._api.create_order(pair, ordertype, 'buy', amount, rate)
|
||||
else:
|
||||
return self._api.create_order(pair, ordertype, 'buy',
|
||||
amount, rate, {'timeInForce': time_in_force})
|
||||
|
||||
except ccxt.InsufficientFunds as e:
|
||||
raise DependencyException(
|
||||
f'Insufficient funds to create limit buy order on market {pair}.'
|
||||
f'Tried to buy amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not create limit buy order on market {pair}.'
|
||||
f'Tried to buy amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not place buy order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
def sell(self, pair: str, ordertype: str, amount: float,
|
||||
rate: float, time_in_force='gtc') -> Dict:
|
||||
if self._conf['dry_run']:
|
||||
order_id = f'dry_run_sell_{randint(0, 10**6)}'
|
||||
self._dry_run_open_orders[order_id] = {
|
||||
'pair': pair,
|
||||
'price': rate,
|
||||
'amount': amount,
|
||||
'type': ordertype,
|
||||
'side': 'sell',
|
||||
'remaining': 0.0,
|
||||
'datetime': arrow.utcnow().isoformat(),
|
||||
'status': 'closed'
|
||||
}
|
||||
return {'id': order_id}
|
||||
|
||||
try:
|
||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
||||
amount = self.symbol_amount_prec(pair, amount)
|
||||
rate = self.symbol_price_prec(pair, rate) if ordertype != 'market' else None
|
||||
|
||||
if time_in_force == 'gtc':
|
||||
return self._api.create_order(pair, ordertype, 'sell', amount, rate)
|
||||
else:
|
||||
return self._api.create_order(pair, ordertype, 'sell',
|
||||
amount, rate, {'timeInForce': time_in_force})
|
||||
|
||||
except ccxt.InsufficientFunds as e:
|
||||
raise DependencyException(
|
||||
f'Insufficient funds to create limit sell order on market {pair}.'
|
||||
f'Tried to sell amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not create limit sell order on market {pair}.'
|
||||
f'Tried to sell amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not place sell order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
def stoploss_limit(self, pair: str, amount: float, stop_price: float, rate: float) -> Dict:
|
||||
"""
|
||||
creates a stoploss limit order.
|
||||
NOTICE: it is not supported by all exchanges. only binance is tested for now.
|
||||
"""
|
||||
|
||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
||||
amount = self.symbol_amount_prec(pair, amount)
|
||||
rate = self.symbol_price_prec(pair, rate)
|
||||
stop_price = self.symbol_price_prec(pair, stop_price)
|
||||
|
||||
# Ensure rate is less than stop price
|
||||
if stop_price <= rate:
|
||||
raise OperationalException(
|
||||
'In stoploss limit order, stop price should be more than limit price')
|
||||
|
||||
if self._conf['dry_run']:
|
||||
order_id = f'dry_run_buy_{randint(0, 10**6)}'
|
||||
self._dry_run_open_orders[order_id] = {
|
||||
'info': {},
|
||||
'id': order_id,
|
||||
'pair': pair,
|
||||
'price': stop_price,
|
||||
'amount': amount,
|
||||
'type': 'stop_loss_limit',
|
||||
'side': 'sell',
|
||||
'remaining': amount,
|
||||
'datetime': arrow.utcnow().isoformat(),
|
||||
'status': 'open',
|
||||
'fee': None
|
||||
}
|
||||
return self._dry_run_open_orders[order_id]
|
||||
|
||||
try:
|
||||
return self._api.create_order(pair, 'stop_loss_limit', 'sell',
|
||||
amount, rate, {'stopPrice': stop_price})
|
||||
|
||||
except ccxt.InsufficientFunds as e:
|
||||
raise DependencyException(
|
||||
f'Insufficient funds to place stoploss limit order on market {pair}. '
|
||||
f'Tried to put a stoploss amount {amount} with '
|
||||
f'stop {stop_price} and limit {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not place stoploss limit order on market {pair}.'
|
||||
f'Tried to place stoploss amount {amount} with '
|
||||
f'stop {stop_price} and limit {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not place stoploss limit order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_balance(self, currency: str) -> float:
|
||||
if self._conf['dry_run']:
|
||||
return 999.9
|
||||
|
||||
# ccxt exception is already handled by get_balances
|
||||
balances = self.get_balances()
|
||||
balance = balances.get(currency)
|
||||
if balance is None:
|
||||
raise TemporaryError(
|
||||
f'Could not get {currency} balance due to malformed exchange response: {balances}')
|
||||
return balance['free']
|
||||
|
||||
@retrier
|
||||
def get_balances(self) -> dict:
|
||||
if self._conf['dry_run']:
|
||||
return {}
|
||||
|
||||
try:
|
||||
balances = self._api.fetch_balance()
|
||||
# Remove additional info from ccxt results
|
||||
balances.pop("info", None)
|
||||
balances.pop("free", None)
|
||||
balances.pop("total", None)
|
||||
balances.pop("used", None)
|
||||
|
||||
return balances
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get balance due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_tickers(self) -> Dict:
|
||||
try:
|
||||
return self._api.fetch_tickers()
|
||||
except ccxt.NotSupported as e:
|
||||
raise OperationalException(
|
||||
f'Exchange {self._api.name} does not support fetching tickers in batch.'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not load tickers due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_ticker(self, pair: str, refresh: Optional[bool] = True) -> dict:
|
||||
if refresh or pair not in self._cached_ticker.keys():
|
||||
try:
|
||||
if pair not in self._api.markets:
|
||||
raise DependencyException(f"Pair {pair} not available")
|
||||
data = self._api.fetch_ticker(pair)
|
||||
try:
|
||||
self._cached_ticker[pair] = {
|
||||
'bid': float(data['bid']),
|
||||
'ask': float(data['ask']),
|
||||
}
|
||||
except KeyError:
|
||||
logger.debug("Could not cache ticker data for %s", pair)
|
||||
return data
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not load ticker due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
else:
|
||||
logger.info("returning cached ticker-data for %s", pair)
|
||||
return self._cached_ticker[pair]
|
||||
|
||||
def get_history(self, pair: str, tick_interval: str,
|
||||
since_ms: int) -> List:
|
||||
"""
|
||||
Gets candle history using asyncio and returns the list of candles.
|
||||
Handles all async doing.
|
||||
"""
|
||||
return asyncio.get_event_loop().run_until_complete(
|
||||
self._async_get_history(pair=pair, tick_interval=tick_interval,
|
||||
since_ms=since_ms))
|
||||
|
||||
async def _async_get_history(self, pair: str,
|
||||
tick_interval: str,
|
||||
since_ms: int) -> List:
|
||||
# Assume exchange returns 500 candles
|
||||
_LIMIT = 500
|
||||
|
||||
one_call = constants.TICKER_INTERVAL_MINUTES[tick_interval] * 60 * _LIMIT * 1000
|
||||
logger.debug("one_call: %s", one_call)
|
||||
input_coroutines = [self._async_get_candle_history(
|
||||
pair, tick_interval, since) for since in
|
||||
range(since_ms, arrow.utcnow().timestamp * 1000, one_call)]
|
||||
tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
|
||||
|
||||
# Combine tickers
|
||||
data: List = []
|
||||
for p, ticker in tickers:
|
||||
if p == pair:
|
||||
data.extend(ticker)
|
||||
# Sort data again after extending the result - above calls return in "async order" order
|
||||
data = sorted(data, key=lambda x: x[0])
|
||||
logger.info("downloaded %s with length %s.", pair, len(data))
|
||||
return data
|
||||
|
||||
def refresh_tickers(self, pair_list: List[str], ticker_interval: str) -> None:
|
||||
"""
|
||||
Refresh tickers asyncronously and set `_klines` of this object with the result
|
||||
"""
|
||||
logger.debug("Refreshing klines for %d pairs", len(pair_list))
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
self.async_get_candles_history(pair_list, ticker_interval))
|
||||
|
||||
async def async_get_candles_history(self, pairs: List[str],
|
||||
tick_interval: str) -> List[Tuple[str, List]]:
|
||||
"""Download ohlcv history for pair-list asyncronously """
|
||||
# Calculating ticker interval in second
|
||||
interval_in_sec = constants.TICKER_INTERVAL_MINUTES[tick_interval] * 60
|
||||
input_coroutines = []
|
||||
|
||||
# Gather corotines to run
|
||||
for pair in pairs:
|
||||
if not (self._pairs_last_refresh_time.get(pair, 0) + interval_in_sec >=
|
||||
arrow.utcnow().timestamp and pair in self._klines):
|
||||
input_coroutines.append(self._async_get_candle_history(pair, tick_interval))
|
||||
else:
|
||||
logger.debug("Using cached klines data for %s ...", pair)
|
||||
|
||||
tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
|
||||
|
||||
# handle caching
|
||||
for pair, ticks in tickers:
|
||||
# keeping last candle time as last refreshed time of the pair
|
||||
if ticks:
|
||||
self._pairs_last_refresh_time[pair] = ticks[-1][0] // 1000
|
||||
# keeping parsed dataframe in cache
|
||||
self._klines[pair] = parse_ticker_dataframe(ticks)
|
||||
return tickers
|
||||
|
||||
@retrier_async
|
||||
async def _async_get_candle_history(self, pair: str, tick_interval: str,
|
||||
since_ms: Optional[int] = None) -> Tuple[str, List]:
|
||||
try:
|
||||
# fetch ohlcv asynchronously
|
||||
logger.debug("fetching %s since %s ...", pair, since_ms)
|
||||
|
||||
data = await self._api_async.fetch_ohlcv(pair, timeframe=tick_interval,
|
||||
since=since_ms)
|
||||
|
||||
# Because some exchange sort Tickers ASC and other DESC.
|
||||
# Ex: Bittrex returns a list of tickers ASC (oldest first, newest last)
|
||||
# when GDAX returns a list of tickers DESC (newest first, oldest last)
|
||||
# Only sort if necessary to save computing time
|
||||
if data and data[0][0] > data[-1][0]:
|
||||
data = sorted(data, key=lambda x: x[0])
|
||||
|
||||
logger.debug("done fetching %s ...", pair)
|
||||
return pair, data
|
||||
|
||||
except ccxt.NotSupported as e:
|
||||
raise OperationalException(
|
||||
f'Exchange {self._api.name} does not support fetching historical candlestick data.'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not load ticker history due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(f'Could not fetch ticker data. Msg: {e}')
|
||||
|
||||
@retrier
|
||||
def cancel_order(self, order_id: str, pair: str) -> None:
|
||||
if self._conf['dry_run']:
|
||||
return
|
||||
|
||||
try:
|
||||
return self._api.cancel_order(order_id, pair)
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not cancel order. Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not cancel order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_order(self, order_id: str, pair: str) -> Dict:
|
||||
if self._conf['dry_run']:
|
||||
order = self._dry_run_open_orders[order_id]
|
||||
order.update({
|
||||
'id': order_id
|
||||
})
|
||||
return order
|
||||
try:
|
||||
return self._api.fetch_order(order_id, pair)
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not get order. Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_order_book(self, pair: str, limit: int = 100) -> dict:
|
||||
"""
|
||||
get order book level 2 from exchange
|
||||
|
||||
Notes:
|
||||
20180619: bittrex doesnt support limits -.-
|
||||
20180619: binance support limits but only on specific range
|
||||
"""
|
||||
try:
|
||||
if self._api.name == 'Binance':
|
||||
limit_range = [5, 10, 20, 50, 100, 500, 1000]
|
||||
# get next-higher step in the limit_range list
|
||||
limit = min(list(filter(lambda x: limit <= x, limit_range)))
|
||||
# above script works like loop below (but with slightly better performance):
|
||||
# for limitx in limit_range:
|
||||
# if limit <= limitx:
|
||||
# limit = limitx
|
||||
# break
|
||||
|
||||
return self._api.fetch_l2_order_book(pair, limit)
|
||||
except ccxt.NotSupported as e:
|
||||
raise OperationalException(
|
||||
f'Exchange {self._api.name} does not support fetching order book.'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get order book due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_trades_for_order(self, order_id: str, pair: str, since: datetime) -> List:
|
||||
if self._conf['dry_run']:
|
||||
return []
|
||||
if not self.exchange_has('fetchMyTrades'):
|
||||
return []
|
||||
try:
|
||||
# Allow 5s offset to catch slight time offsets (discovered in #1185)
|
||||
my_trades = self._api.fetch_my_trades(pair, since.timestamp() - 5)
|
||||
matched_trades = [trade for trade in my_trades if trade['order'] == order_id]
|
||||
|
||||
return matched_trades
|
||||
|
||||
except ccxt.NetworkError as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get trades due to networking error. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
def get_pair_detail_url(self, pair: str) -> str:
|
||||
try:
|
||||
url_base = self._api.urls.get('www')
|
||||
base, quote = pair.split('/')
|
||||
|
||||
return url_base + _EXCHANGE_URLS[self._api.id].format(base=base, quote=quote)
|
||||
except KeyError:
|
||||
logger.warning('Could not get exchange url for %s', self.name)
|
||||
return ""
|
||||
|
||||
@retrier
|
||||
def get_markets(self) -> List[dict]:
|
||||
try:
|
||||
return self._api.fetch_markets()
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not load markets due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_fee(self, symbol='ETH/BTC', type='', side='', amount=1,
|
||||
price=1, taker_or_maker='maker') -> float:
|
||||
try:
|
||||
# validate that markets are loaded before trying to get fee
|
||||
if self._api.markets is None or len(self._api.markets) == 0:
|
||||
self._api.load_markets()
|
||||
|
||||
return self._api.calculate_fee(symbol=symbol, type=type, side=side, amount=amount,
|
||||
price=price, takerOrMaker=taker_or_maker)['rate']
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get fee info due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
from freqtrade.exchange.exchange import Exchange # noqa: F401
|
||||
from freqtrade.exchange.kraken import Kraken # noqa: F401
|
||||
from freqtrade.exchange.binance import Binance # noqa: F401
|
||||
|
||||
27
freqtrade/exchange/binance.py
Normal file
27
freqtrade/exchange/binance.py
Normal file
@@ -0,0 +1,27 @@
|
||||
""" Binance exchange subclass """
|
||||
import logging
|
||||
from typing import Dict
|
||||
|
||||
from freqtrade.exchange import Exchange
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Binance(Exchange):
|
||||
|
||||
_ft_has: Dict = {
|
||||
"stoploss_on_exchange": True,
|
||||
"order_time_in_force": ['gtc', 'fok', 'ioc'],
|
||||
}
|
||||
|
||||
def get_order_book(self, pair: str, limit: int = 100) -> dict:
|
||||
"""
|
||||
get order book level 2 from exchange
|
||||
|
||||
20180619: binance support limits but only on specific range
|
||||
"""
|
||||
limit_range = [5, 10, 20, 50, 100, 500, 1000]
|
||||
# get next-higher step in the limit_range list
|
||||
limit = min(list(filter(lambda x: limit <= x, limit_range)))
|
||||
|
||||
return super().get_order_book(pair, limit)
|
||||
691
freqtrade/exchange/exchange.py
Normal file
691
freqtrade/exchange/exchange.py
Normal file
@@ -0,0 +1,691 @@
|
||||
# pragma pylint: disable=W0603
|
||||
""" Cryptocurrency Exchanges support """
|
||||
import logging
|
||||
import inspect
|
||||
from random import randint
|
||||
from typing import List, Dict, Tuple, Any, Optional
|
||||
from datetime import datetime
|
||||
from math import floor, ceil
|
||||
|
||||
import arrow
|
||||
import asyncio
|
||||
import ccxt
|
||||
import ccxt.async_support as ccxt_async
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade import (constants, DependencyException, OperationalException,
|
||||
TemporaryError, InvalidOrderException)
|
||||
from freqtrade.data.converter import parse_ticker_dataframe
|
||||
from freqtrade.misc import timeframe_to_seconds, timeframe_to_msecs
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
API_RETRY_COUNT = 4
|
||||
|
||||
|
||||
def retrier_async(f):
|
||||
async def wrapper(*args, **kwargs):
|
||||
count = kwargs.pop('count', API_RETRY_COUNT)
|
||||
try:
|
||||
return await f(*args, **kwargs)
|
||||
except (TemporaryError, DependencyException) as ex:
|
||||
logger.warning('%s() returned exception: "%s"', f.__name__, ex)
|
||||
if count > 0:
|
||||
count -= 1
|
||||
kwargs.update({'count': count})
|
||||
logger.warning('retrying %s() still for %s times', f.__name__, count)
|
||||
return await wrapper(*args, **kwargs)
|
||||
else:
|
||||
logger.warning('Giving up retrying: %s()', f.__name__)
|
||||
raise ex
|
||||
return wrapper
|
||||
|
||||
|
||||
def retrier(f):
|
||||
def wrapper(*args, **kwargs):
|
||||
count = kwargs.pop('count', API_RETRY_COUNT)
|
||||
try:
|
||||
return f(*args, **kwargs)
|
||||
except (TemporaryError, DependencyException) as ex:
|
||||
logger.warning('%s() returned exception: "%s"', f.__name__, ex)
|
||||
if count > 0:
|
||||
count -= 1
|
||||
kwargs.update({'count': count})
|
||||
logger.warning('retrying %s() still for %s times', f.__name__, count)
|
||||
return wrapper(*args, **kwargs)
|
||||
else:
|
||||
logger.warning('Giving up retrying: %s()', f.__name__)
|
||||
raise ex
|
||||
return wrapper
|
||||
|
||||
|
||||
class Exchange(object):
|
||||
|
||||
_config: Dict = {}
|
||||
_params: Dict = {}
|
||||
|
||||
# Dict to specify which options each exchange implements
|
||||
# TODO: this should be merged with attributes from subclasses
|
||||
# To avoid having to copy/paste this to all subclasses.
|
||||
_ft_has: Dict = {
|
||||
"stoploss_on_exchange": False,
|
||||
"order_time_in_force": ["gtc"],
|
||||
}
|
||||
|
||||
def __init__(self, config: dict) -> None:
|
||||
"""
|
||||
Initializes this module with the given config,
|
||||
it does basic validation whether the specified exchange and pairs are valid.
|
||||
:return: None
|
||||
"""
|
||||
self._config.update(config)
|
||||
|
||||
self._cached_ticker: Dict[str, Any] = {}
|
||||
|
||||
# Holds last candle refreshed time of each pair
|
||||
self._pairs_last_refresh_time: Dict[Tuple[str, str], int] = {}
|
||||
# Timestamp of last markets refresh
|
||||
self._last_markets_refresh: int = 0
|
||||
|
||||
# Holds candles
|
||||
self._klines: Dict[Tuple[str, str], DataFrame] = {}
|
||||
|
||||
# Holds all open sell orders for dry_run
|
||||
self._dry_run_open_orders: Dict[str, Any] = {}
|
||||
|
||||
if config['dry_run']:
|
||||
logger.info('Instance is running with dry_run enabled')
|
||||
|
||||
exchange_config = config['exchange']
|
||||
self._api: ccxt.Exchange = self._init_ccxt(
|
||||
exchange_config, ccxt_kwargs=exchange_config.get('ccxt_config'))
|
||||
self._api_async: ccxt_async.Exchange = self._init_ccxt(
|
||||
exchange_config, ccxt_async, ccxt_kwargs=exchange_config.get('ccxt_async_config'))
|
||||
|
||||
logger.info('Using Exchange "%s"', self.name)
|
||||
|
||||
# Converts the interval provided in minutes in config to seconds
|
||||
self.markets_refresh_interval: int = exchange_config.get(
|
||||
"markets_refresh_interval", 60) * 60
|
||||
# Initial markets load
|
||||
self._load_markets()
|
||||
|
||||
# Check if all pairs are available
|
||||
self.validate_pairs(config['exchange']['pair_whitelist'])
|
||||
self.validate_ordertypes(config.get('order_types', {}))
|
||||
self.validate_order_time_in_force(config.get('order_time_in_force', {}))
|
||||
|
||||
if config.get('ticker_interval'):
|
||||
# Check if timeframe is available
|
||||
self.validate_timeframes(config['ticker_interval'])
|
||||
|
||||
def __del__(self):
|
||||
"""
|
||||
Destructor - clean up async stuff
|
||||
"""
|
||||
logger.debug("Exchange object destroyed, closing async loop")
|
||||
if self._api_async and inspect.iscoroutinefunction(self._api_async.close):
|
||||
asyncio.get_event_loop().run_until_complete(self._api_async.close())
|
||||
|
||||
def _init_ccxt(self, exchange_config: dict, ccxt_module=ccxt,
|
||||
ccxt_kwargs: dict = None) -> ccxt.Exchange:
|
||||
"""
|
||||
Initialize ccxt with given config and return valid
|
||||
ccxt instance.
|
||||
"""
|
||||
# Find matching class for the given exchange name
|
||||
name = exchange_config['name']
|
||||
|
||||
if name not in ccxt_module.exchanges:
|
||||
raise OperationalException(f'Exchange {name} is not supported')
|
||||
|
||||
ex_config = {
|
||||
'apiKey': exchange_config.get('key'),
|
||||
'secret': exchange_config.get('secret'),
|
||||
'password': exchange_config.get('password'),
|
||||
'uid': exchange_config.get('uid', ''),
|
||||
}
|
||||
if ccxt_kwargs:
|
||||
logger.info('Applying additional ccxt config: %s', ccxt_kwargs)
|
||||
ex_config.update(ccxt_kwargs)
|
||||
try:
|
||||
|
||||
api = getattr(ccxt_module, name.lower())(ex_config)
|
||||
except (KeyError, AttributeError):
|
||||
raise OperationalException(f'Exchange {name} is not supported')
|
||||
|
||||
self.set_sandbox(api, exchange_config, name)
|
||||
|
||||
return api
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""exchange Name (from ccxt)"""
|
||||
return self._api.name
|
||||
|
||||
@property
|
||||
def id(self) -> str:
|
||||
"""exchange ccxt id"""
|
||||
return self._api.id
|
||||
|
||||
@property
|
||||
def markets(self) -> Dict:
|
||||
"""exchange ccxt markets"""
|
||||
if not self._api.markets:
|
||||
logger.warning("Markets were not loaded. Loading them now..")
|
||||
self._load_markets()
|
||||
return self._api.markets
|
||||
|
||||
def klines(self, pair_interval: Tuple[str, str], copy=True) -> DataFrame:
|
||||
if pair_interval in self._klines:
|
||||
return self._klines[pair_interval].copy() if copy else self._klines[pair_interval]
|
||||
else:
|
||||
return DataFrame()
|
||||
|
||||
def set_sandbox(self, api, exchange_config: dict, name: str):
|
||||
if exchange_config.get('sandbox'):
|
||||
if api.urls.get('test'):
|
||||
api.urls['api'] = api.urls['test']
|
||||
logger.info("Enabled Sandbox API on %s", name)
|
||||
else:
|
||||
logger.warning(name, "No Sandbox URL in CCXT, exiting. "
|
||||
"Please check your config.json")
|
||||
raise OperationalException(f'Exchange {name} does not provide a sandbox api')
|
||||
|
||||
def _load_async_markets(self, reload=False) -> None:
|
||||
try:
|
||||
if self._api_async:
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
self._api_async.load_markets(reload=reload))
|
||||
|
||||
except ccxt.BaseError as e:
|
||||
logger.warning('Could not load async markets. Reason: %s', e)
|
||||
return
|
||||
|
||||
def _load_markets(self) -> None:
|
||||
""" Initialize markets both sync and async """
|
||||
try:
|
||||
self._api.load_markets()
|
||||
self._load_async_markets()
|
||||
self._last_markets_refresh = arrow.utcnow().timestamp
|
||||
except ccxt.BaseError as e:
|
||||
logger.warning('Unable to initialize markets. Reason: %s', e)
|
||||
|
||||
def _reload_markets(self) -> None:
|
||||
"""Reload markets both sync and async, if refresh interval has passed"""
|
||||
# Check whether markets have to be reloaded
|
||||
if (self._last_markets_refresh > 0) and (
|
||||
self._last_markets_refresh + self.markets_refresh_interval
|
||||
> arrow.utcnow().timestamp):
|
||||
return None
|
||||
logger.debug("Performing scheduled market reload..")
|
||||
self._api.load_markets(reload=True)
|
||||
self._last_markets_refresh = arrow.utcnow().timestamp
|
||||
|
||||
def validate_pairs(self, pairs: List[str]) -> None:
|
||||
"""
|
||||
Checks if all given pairs are tradable on the current exchange.
|
||||
Raises OperationalException if one pair is not available.
|
||||
:param pairs: list of pairs
|
||||
:return: None
|
||||
"""
|
||||
|
||||
if not self.markets:
|
||||
logger.warning('Unable to validate pairs (assuming they are correct).')
|
||||
# return
|
||||
|
||||
for pair in pairs:
|
||||
# Note: ccxt has BaseCurrency/QuoteCurrency format for pairs
|
||||
# TODO: add a support for having coins in BTC/USDT format
|
||||
if self.markets and pair not in self.markets:
|
||||
raise OperationalException(
|
||||
f'Pair {pair} is not available on {self.name}. '
|
||||
f'Please remove {pair} from your whitelist.')
|
||||
|
||||
def validate_timeframes(self, timeframe: List[str]) -> None:
|
||||
"""
|
||||
Checks if ticker interval from config is a supported timeframe on the exchange
|
||||
"""
|
||||
timeframes = self._api.timeframes
|
||||
if timeframe not in timeframes:
|
||||
raise OperationalException(
|
||||
f'Invalid ticker {timeframe}, this Exchange supports {timeframes}')
|
||||
|
||||
def validate_ordertypes(self, order_types: Dict) -> None:
|
||||
"""
|
||||
Checks if order-types configured in strategy/config are supported
|
||||
"""
|
||||
if any(v == 'market' for k, v in order_types.items()):
|
||||
if not self.exchange_has('createMarketOrder'):
|
||||
raise OperationalException(
|
||||
f'Exchange {self.name} does not support market orders.')
|
||||
|
||||
if (order_types.get("stoploss_on_exchange")
|
||||
and not self._ft_has.get("stoploss_on_exchange", False)):
|
||||
raise OperationalException(
|
||||
'On exchange stoploss is not supported for %s.' % self.name
|
||||
)
|
||||
|
||||
def validate_order_time_in_force(self, order_time_in_force: Dict) -> None:
|
||||
"""
|
||||
Checks if order time in force configured in strategy/config are supported
|
||||
"""
|
||||
if any(v not in self._ft_has["order_time_in_force"]
|
||||
for k, v in order_time_in_force.items()):
|
||||
raise OperationalException(
|
||||
f'Time in force policies are not supported for {self.name} yet.')
|
||||
|
||||
def exchange_has(self, endpoint: str) -> bool:
|
||||
"""
|
||||
Checks if exchange implements a specific API endpoint.
|
||||
Wrapper around ccxt 'has' attribute
|
||||
:param endpoint: Name of endpoint (e.g. 'fetchOHLCV', 'fetchTickers')
|
||||
:return: bool
|
||||
"""
|
||||
return endpoint in self._api.has and self._api.has[endpoint]
|
||||
|
||||
def symbol_amount_prec(self, pair, amount: float):
|
||||
'''
|
||||
Returns the amount to buy or sell to a precision the Exchange accepts
|
||||
Rounded down
|
||||
'''
|
||||
if self.markets[pair]['precision']['amount']:
|
||||
symbol_prec = self.markets[pair]['precision']['amount']
|
||||
big_amount = amount * pow(10, symbol_prec)
|
||||
amount = floor(big_amount) / pow(10, symbol_prec)
|
||||
return amount
|
||||
|
||||
def symbol_price_prec(self, pair, price: float):
|
||||
'''
|
||||
Returns the price buying or selling with to the precision the Exchange accepts
|
||||
Rounds up
|
||||
'''
|
||||
if self.markets[pair]['precision']['price']:
|
||||
symbol_prec = self.markets[pair]['precision']['price']
|
||||
big_price = price * pow(10, symbol_prec)
|
||||
price = ceil(big_price) / pow(10, symbol_prec)
|
||||
return price
|
||||
|
||||
def dry_run_order(self, pair: str, ordertype: str, side: str, amount: float,
|
||||
rate: float, params: Dict = {}) -> Dict[str, Any]:
|
||||
order_id = f'dry_run_{side}_{randint(0, 10**6)}'
|
||||
dry_order = { # TODO: additional entry should be added for stoploss limit
|
||||
"id": order_id,
|
||||
'pair': pair,
|
||||
'price': rate,
|
||||
'amount': amount,
|
||||
"cost": amount * rate,
|
||||
'type': ordertype,
|
||||
'side': side,
|
||||
'remaining': amount,
|
||||
'datetime': arrow.utcnow().isoformat(),
|
||||
'status': "open",
|
||||
'fee': None,
|
||||
"info": {}
|
||||
}
|
||||
self._store_dry_order(dry_order)
|
||||
return dry_order
|
||||
|
||||
def _store_dry_order(self, dry_order: Dict) -> None:
|
||||
closed_order = dry_order.copy()
|
||||
if closed_order["type"] in ["market", "limit"]:
|
||||
closed_order.update({
|
||||
"status": "closed",
|
||||
"filled": closed_order["amount"],
|
||||
"remaining": 0
|
||||
})
|
||||
self._dry_run_open_orders[closed_order["id"]] = closed_order
|
||||
|
||||
def create_order(self, pair: str, ordertype: str, side: str, amount: float,
|
||||
rate: float, params: Dict = {}) -> Dict:
|
||||
try:
|
||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
||||
amount = self.symbol_amount_prec(pair, amount)
|
||||
rate = self.symbol_price_prec(pair, rate) if ordertype != 'market' else None
|
||||
|
||||
return self._api.create_order(pair, ordertype, side,
|
||||
amount, rate, params)
|
||||
|
||||
except ccxt.InsufficientFunds as e:
|
||||
raise DependencyException(
|
||||
f'Insufficient funds to create {ordertype} {side} order on market {pair}.'
|
||||
f'Tried to {side} amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not create {ordertype} {side} order on market {pair}.'
|
||||
f'Tried to {side} amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not place {side} order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
def buy(self, pair: str, ordertype: str, amount: float,
|
||||
rate: float, time_in_force) -> Dict:
|
||||
|
||||
if self._config['dry_run']:
|
||||
dry_order = self.dry_run_order(pair, ordertype, "buy", amount, rate)
|
||||
return dry_order
|
||||
|
||||
params = self._params.copy()
|
||||
if time_in_force != 'gtc' and ordertype != 'market':
|
||||
params.update({'timeInForce': time_in_force})
|
||||
|
||||
return self.create_order(pair, ordertype, 'buy', amount, rate, params)
|
||||
|
||||
def sell(self, pair: str, ordertype: str, amount: float,
|
||||
rate: float, time_in_force='gtc') -> Dict:
|
||||
|
||||
if self._config['dry_run']:
|
||||
dry_order = self.dry_run_order(pair, ordertype, "sell", amount, rate)
|
||||
return dry_order
|
||||
|
||||
params = self._params.copy()
|
||||
if time_in_force != 'gtc' and ordertype != 'market':
|
||||
params.update({'timeInForce': time_in_force})
|
||||
|
||||
return self.create_order(pair, ordertype, 'sell', amount, rate, params)
|
||||
|
||||
def stoploss_limit(self, pair: str, amount: float, stop_price: float, rate: float) -> Dict:
|
||||
"""
|
||||
creates a stoploss limit order.
|
||||
NOTICE: it is not supported by all exchanges. only binance is tested for now.
|
||||
TODO: implementation maybe needs to be moved to the binance subclass
|
||||
"""
|
||||
ordertype = "stop_loss_limit"
|
||||
|
||||
stop_price = self.symbol_price_prec(pair, stop_price)
|
||||
|
||||
# Ensure rate is less than stop price
|
||||
if stop_price <= rate:
|
||||
raise OperationalException(
|
||||
'In stoploss limit order, stop price should be more than limit price')
|
||||
|
||||
if self._config['dry_run']:
|
||||
dry_order = self.dry_run_order(
|
||||
pair, ordertype, "sell", amount, stop_price)
|
||||
return dry_order
|
||||
|
||||
params = self._params.copy()
|
||||
params.update({'stopPrice': stop_price})
|
||||
|
||||
order = self.create_order(pair, ordertype, 'sell', amount, rate, params)
|
||||
logger.info('stoploss limit order added for %s. '
|
||||
'stop price: %s. limit: %s' % (pair, stop_price, rate))
|
||||
return order
|
||||
|
||||
@retrier
|
||||
def get_balance(self, currency: str) -> float:
|
||||
if self._config['dry_run']:
|
||||
return constants.DRY_RUN_WALLET
|
||||
|
||||
# ccxt exception is already handled by get_balances
|
||||
balances = self.get_balances()
|
||||
balance = balances.get(currency)
|
||||
if balance is None:
|
||||
raise TemporaryError(
|
||||
f'Could not get {currency} balance due to malformed exchange response: {balances}')
|
||||
return balance['free']
|
||||
|
||||
@retrier
|
||||
def get_balances(self) -> dict:
|
||||
if self._config['dry_run']:
|
||||
return {}
|
||||
|
||||
try:
|
||||
balances = self._api.fetch_balance()
|
||||
# Remove additional info from ccxt results
|
||||
balances.pop("info", None)
|
||||
balances.pop("free", None)
|
||||
balances.pop("total", None)
|
||||
balances.pop("used", None)
|
||||
|
||||
return balances
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get balance due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_tickers(self) -> Dict:
|
||||
try:
|
||||
return self._api.fetch_tickers()
|
||||
except ccxt.NotSupported as e:
|
||||
raise OperationalException(
|
||||
f'Exchange {self._api.name} does not support fetching tickers in batch.'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not load tickers due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_ticker(self, pair: str, refresh: Optional[bool] = True) -> dict:
|
||||
if refresh or pair not in self._cached_ticker.keys():
|
||||
try:
|
||||
if pair not in self._api.markets:
|
||||
raise DependencyException(f"Pair {pair} not available")
|
||||
data = self._api.fetch_ticker(pair)
|
||||
try:
|
||||
self._cached_ticker[pair] = {
|
||||
'bid': float(data['bid']),
|
||||
'ask': float(data['ask']),
|
||||
}
|
||||
except KeyError:
|
||||
logger.debug("Could not cache ticker data for %s", pair)
|
||||
return data
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not load ticker due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
else:
|
||||
logger.info("returning cached ticker-data for %s", pair)
|
||||
return self._cached_ticker[pair]
|
||||
|
||||
def get_history(self, pair: str, ticker_interval: str,
|
||||
since_ms: int) -> List:
|
||||
"""
|
||||
Gets candle history using asyncio and returns the list of candles.
|
||||
Handles all async doing.
|
||||
"""
|
||||
return asyncio.get_event_loop().run_until_complete(
|
||||
self._async_get_history(pair=pair, ticker_interval=ticker_interval,
|
||||
since_ms=since_ms))
|
||||
|
||||
async def _async_get_history(self, pair: str,
|
||||
ticker_interval: str,
|
||||
since_ms: int) -> List:
|
||||
# Assume exchange returns 500 candles
|
||||
_LIMIT = 500
|
||||
|
||||
one_call = timeframe_to_msecs(ticker_interval) * _LIMIT
|
||||
logger.debug("one_call: %s msecs", one_call)
|
||||
input_coroutines = [self._async_get_candle_history(
|
||||
pair, ticker_interval, since) for since in
|
||||
range(since_ms, arrow.utcnow().timestamp * 1000, one_call)]
|
||||
|
||||
tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
|
||||
|
||||
# Combine tickers
|
||||
data: List = []
|
||||
for p, ticker_interval, ticker in tickers:
|
||||
if p == pair:
|
||||
data.extend(ticker)
|
||||
# Sort data again after extending the result - above calls return in "async order"
|
||||
data = sorted(data, key=lambda x: x[0])
|
||||
logger.info("downloaded %s with length %s.", pair, len(data))
|
||||
return data
|
||||
|
||||
def refresh_latest_ohlcv(self, pair_list: List[Tuple[str, str]]) -> List[Tuple[str, List]]:
|
||||
"""
|
||||
Refresh in-memory ohlcv asyncronously and set `_klines` with the result
|
||||
"""
|
||||
logger.debug("Refreshing ohlcv data for %d pairs", len(pair_list))
|
||||
|
||||
input_coroutines = []
|
||||
|
||||
# Gather coroutines to run
|
||||
for pair, ticker_interval in set(pair_list):
|
||||
if (not ((pair, ticker_interval) in self._klines)
|
||||
or self._now_is_time_to_refresh(pair, ticker_interval)):
|
||||
input_coroutines.append(self._async_get_candle_history(pair, ticker_interval))
|
||||
else:
|
||||
logger.debug("Using cached ohlcv data for %s, %s ...", pair, ticker_interval)
|
||||
|
||||
tickers = asyncio.get_event_loop().run_until_complete(
|
||||
asyncio.gather(*input_coroutines, return_exceptions=True))
|
||||
|
||||
# handle caching
|
||||
for res in tickers:
|
||||
if isinstance(res, Exception):
|
||||
logger.warning("Async code raised an exception: %s", res.__class__.__name__)
|
||||
continue
|
||||
pair = res[0]
|
||||
ticker_interval = res[1]
|
||||
ticks = res[2]
|
||||
# keeping last candle time as last refreshed time of the pair
|
||||
if ticks:
|
||||
self._pairs_last_refresh_time[(pair, ticker_interval)] = ticks[-1][0] // 1000
|
||||
# keeping parsed dataframe in cache
|
||||
self._klines[(pair, ticker_interval)] = parse_ticker_dataframe(
|
||||
ticks, ticker_interval, fill_missing=True)
|
||||
return tickers
|
||||
|
||||
def _now_is_time_to_refresh(self, pair: str, ticker_interval: str) -> bool:
|
||||
# Calculating ticker interval in seconds
|
||||
interval_in_sec = timeframe_to_seconds(ticker_interval)
|
||||
|
||||
return not ((self._pairs_last_refresh_time.get((pair, ticker_interval), 0)
|
||||
+ interval_in_sec) >= arrow.utcnow().timestamp)
|
||||
|
||||
@retrier_async
|
||||
async def _async_get_candle_history(self, pair: str, ticker_interval: str,
|
||||
since_ms: Optional[int] = None) -> Tuple[str, str, List]:
|
||||
"""
|
||||
Asyncronously gets candle histories using fetch_ohlcv
|
||||
returns tuple: (pair, ticker_interval, ohlcv_list)
|
||||
"""
|
||||
try:
|
||||
# fetch ohlcv asynchronously
|
||||
logger.debug("fetching %s, %s since %s ...", pair, ticker_interval, since_ms)
|
||||
|
||||
data = await self._api_async.fetch_ohlcv(pair, timeframe=ticker_interval,
|
||||
since=since_ms)
|
||||
|
||||
# Because some exchange sort Tickers ASC and other DESC.
|
||||
# Ex: Bittrex returns a list of tickers ASC (oldest first, newest last)
|
||||
# when GDAX returns a list of tickers DESC (newest first, oldest last)
|
||||
# Only sort if necessary to save computing time
|
||||
try:
|
||||
if data and data[0][0] > data[-1][0]:
|
||||
data = sorted(data, key=lambda x: x[0])
|
||||
except IndexError:
|
||||
logger.exception("Error loading %s. Result was %s.", pair, data)
|
||||
return pair, ticker_interval, []
|
||||
logger.debug("done fetching %s, %s ...", pair, ticker_interval)
|
||||
return pair, ticker_interval, data
|
||||
|
||||
except ccxt.NotSupported as e:
|
||||
raise OperationalException(
|
||||
f'Exchange {self._api.name} does not support fetching historical candlestick data.'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not load ticker history due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(f'Could not fetch ticker data. Msg: {e}')
|
||||
|
||||
@retrier
|
||||
def cancel_order(self, order_id: str, pair: str) -> None:
|
||||
if self._config['dry_run']:
|
||||
return
|
||||
|
||||
try:
|
||||
return self._api.cancel_order(order_id, pair)
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise InvalidOrderException(
|
||||
f'Could not cancel order. Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not cancel order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_order(self, order_id: str, pair: str) -> Dict:
|
||||
if self._config['dry_run']:
|
||||
order = self._dry_run_open_orders[order_id]
|
||||
return order
|
||||
try:
|
||||
return self._api.fetch_order(order_id, pair)
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise InvalidOrderException(
|
||||
f'Tried to get an invalid order (id: {order_id}). Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_order_book(self, pair: str, limit: int = 100) -> dict:
|
||||
"""
|
||||
get order book level 2 from exchange
|
||||
|
||||
Notes:
|
||||
20180619: bittrex doesnt support limits -.-
|
||||
"""
|
||||
try:
|
||||
|
||||
return self._api.fetch_l2_order_book(pair, limit)
|
||||
except ccxt.NotSupported as e:
|
||||
raise OperationalException(
|
||||
f'Exchange {self._api.name} does not support fetching order book.'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get order book due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_trades_for_order(self, order_id: str, pair: str, since: datetime) -> List:
|
||||
if self._config['dry_run']:
|
||||
return []
|
||||
if not self.exchange_has('fetchMyTrades'):
|
||||
return []
|
||||
try:
|
||||
# Allow 5s offset to catch slight time offsets (discovered in #1185)
|
||||
my_trades = self._api.fetch_my_trades(pair, since.timestamp() - 5)
|
||||
matched_trades = [trade for trade in my_trades if trade['order'] == order_id]
|
||||
|
||||
return matched_trades
|
||||
|
||||
except ccxt.NetworkError as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get trades due to networking error. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_fee(self, symbol='ETH/BTC', type='', side='', amount=1,
|
||||
price=1, taker_or_maker='maker') -> float:
|
||||
try:
|
||||
# validate that markets are loaded before trying to get fee
|
||||
if self._api.markets is None or len(self._api.markets) == 0:
|
||||
self._api.load_markets()
|
||||
|
||||
return self._api.calculate_fee(symbol=symbol, type=type, side=side, amount=amount,
|
||||
price=price, takerOrMaker=taker_or_maker)['rate']
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not get fee info due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
12
freqtrade/exchange/kraken.py
Normal file
12
freqtrade/exchange/kraken.py
Normal file
@@ -0,0 +1,12 @@
|
||||
""" Kraken exchange subclass """
|
||||
import logging
|
||||
from typing import Dict
|
||||
|
||||
from freqtrade.exchange import Exchange
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Kraken(Exchange):
|
||||
|
||||
_params: Dict = {"trading_agreement": "agree"}
|
||||
@@ -4,22 +4,22 @@ Freqtrade is the main module of this bot. It contains the class Freqtrade()
|
||||
|
||||
import copy
|
||||
import logging
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import arrow
|
||||
from requests.exceptions import RequestException
|
||||
|
||||
from freqtrade import (DependencyException, OperationalException,
|
||||
TemporaryError, __version__, constants, persistence)
|
||||
from freqtrade import (DependencyException, OperationalException, InvalidOrderException,
|
||||
__version__, constants, persistence)
|
||||
from freqtrade.data.converter import order_book_to_dataframe
|
||||
from freqtrade.data.dataprovider import DataProvider
|
||||
from freqtrade.edge import Edge
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.misc import timeframe_to_minutes
|
||||
from freqtrade.persistence import Trade
|
||||
from freqtrade.rpc import RPCManager, RPCMessageType
|
||||
from freqtrade.resolvers import StrategyResolver, PairListResolver
|
||||
from freqtrade.resolvers import ExchangeResolver, StrategyResolver, PairListResolver
|
||||
from freqtrade.state import State
|
||||
from freqtrade.strategy.interface import SellType, IStrategy
|
||||
from freqtrade.wallets import Wallets
|
||||
@@ -34,29 +34,36 @@ class FreqtradeBot(object):
|
||||
This is from here the bot start its logic.
|
||||
"""
|
||||
|
||||
def __init__(self, config: Dict[str, Any])-> None:
|
||||
def __init__(self, config: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Init all variables and object the bot need to work
|
||||
:param config: configuration dict, you can use the Configuration.get_config()
|
||||
method to get the config dict.
|
||||
Init all variables and objects the bot needs to work
|
||||
:param config: configuration dict, you can use Configuration.get_config()
|
||||
to get the config dict.
|
||||
"""
|
||||
|
||||
logger.info(
|
||||
'Starting freqtrade %s',
|
||||
__version__,
|
||||
)
|
||||
logger.info('Starting freqtrade %s', __version__)
|
||||
|
||||
# Init bot states
|
||||
# Init bot state
|
||||
self.state = State.STOPPED
|
||||
|
||||
# Init objects
|
||||
self.config = config
|
||||
|
||||
self.strategy: IStrategy = StrategyResolver(self.config).strategy
|
||||
|
||||
self.rpc: RPCManager = RPCManager(self)
|
||||
self.persistence = None
|
||||
self.exchange = Exchange(self.config)
|
||||
self.wallets = Wallets(self.exchange)
|
||||
|
||||
exchange_name = self.config.get('exchange', {}).get('name', 'bittrex').title()
|
||||
self.exchange = ExchangeResolver(exchange_name, self.config).exchange
|
||||
|
||||
self.wallets = Wallets(self.config, self.exchange)
|
||||
self.dataprovider = DataProvider(self.config, self.exchange)
|
||||
|
||||
# Attach Dataprovider to Strategy baseclass
|
||||
IStrategy.dp = self.dataprovider
|
||||
# Attach Wallets to Strategy baseclass
|
||||
IStrategy.wallets = self.wallets
|
||||
|
||||
pairlistname = self.config.get('pairlist', {}).get('method', 'StaticPairList')
|
||||
self.pairlists = PairListResolver(pairlistname, self, self.config).pairlist
|
||||
|
||||
@@ -65,24 +72,12 @@ class FreqtradeBot(object):
|
||||
self.config.get('edge', {}).get('enabled', False) else None
|
||||
|
||||
self.active_pair_whitelist: List[str] = self.config['exchange']['pair_whitelist']
|
||||
self._init_modules()
|
||||
|
||||
def _init_modules(self) -> None:
|
||||
"""
|
||||
Initializes all modules and updates the config
|
||||
:return: None
|
||||
"""
|
||||
# Initialize all modules
|
||||
|
||||
persistence.init(self.config)
|
||||
|
||||
# Set initial application state
|
||||
# Set initial bot state from config
|
||||
initial_state = self.config.get('initial_state')
|
||||
|
||||
if initial_state:
|
||||
self.state = State[initial_state.upper()]
|
||||
else:
|
||||
self.state = State.STOPPED
|
||||
self.state = State[initial_state.upper()] if initial_state else State.STOPPED
|
||||
|
||||
def cleanup(self) -> None:
|
||||
"""
|
||||
@@ -90,125 +85,73 @@ class FreqtradeBot(object):
|
||||
:return: None
|
||||
"""
|
||||
logger.info('Cleaning up modules ...')
|
||||
|
||||
self.rpc.cleanup()
|
||||
persistence.cleanup()
|
||||
|
||||
def worker(self, old_state: State = None) -> State:
|
||||
"""
|
||||
Trading routine that must be run at each loop
|
||||
:param old_state: the previous service state from the previous call
|
||||
:return: current service state
|
||||
"""
|
||||
# Log state transition
|
||||
state = self.state
|
||||
if state != old_state:
|
||||
self.rpc.send_msg({
|
||||
'type': RPCMessageType.STATUS_NOTIFICATION,
|
||||
'status': f'{state.name.lower()}'
|
||||
})
|
||||
logger.info('Changing state to: %s', state.name)
|
||||
if state == State.RUNNING:
|
||||
self.rpc.startup_messages(self.config, self.pairlists)
|
||||
|
||||
if state == State.STOPPED:
|
||||
time.sleep(1)
|
||||
elif state == State.RUNNING:
|
||||
min_secs = self.config.get('internals', {}).get(
|
||||
'process_throttle_secs',
|
||||
constants.PROCESS_THROTTLE_SECS
|
||||
)
|
||||
|
||||
self._throttle(func=self._process,
|
||||
min_secs=min_secs)
|
||||
return state
|
||||
|
||||
def _throttle(self, func: Callable[..., Any], min_secs: float, *args, **kwargs) -> Any:
|
||||
"""
|
||||
Throttles the given callable that it
|
||||
takes at least `min_secs` to finish execution.
|
||||
:param func: Any callable
|
||||
:param min_secs: minimum execution time in seconds
|
||||
:return: Any
|
||||
"""
|
||||
start = time.time()
|
||||
result = func(*args, **kwargs)
|
||||
end = time.time()
|
||||
duration = max(min_secs - (end - start), 0.0)
|
||||
logger.debug('Throttling %s for %.2f seconds', func.__name__, duration)
|
||||
time.sleep(duration)
|
||||
return result
|
||||
|
||||
def _process(self) -> bool:
|
||||
def process(self) -> bool:
|
||||
"""
|
||||
Queries the persistence layer for open trades and handles them,
|
||||
otherwise a new trade is created.
|
||||
:return: True if one or more trades has been created or closed, False otherwise
|
||||
"""
|
||||
state_changed = False
|
||||
try:
|
||||
# Refresh whitelist
|
||||
self.pairlists.refresh_pairlist()
|
||||
self.active_pair_whitelist = self.pairlists.whitelist
|
||||
|
||||
# Calculating Edge positiong
|
||||
# Should be called before refresh_tickers
|
||||
# Otherwise it will override cached klines in exchange
|
||||
# with delta value (klines only from last refresh_pairs)
|
||||
if self.edge:
|
||||
self.edge.calculate()
|
||||
self.active_pair_whitelist = self.edge.adjust(self.active_pair_whitelist)
|
||||
# Check whether markets have to be reloaded
|
||||
self.exchange._reload_markets()
|
||||
|
||||
# Query trades from persistence layer
|
||||
trades = Trade.query.filter(Trade.is_open.is_(True)).all()
|
||||
# Refresh whitelist
|
||||
self.pairlists.refresh_pairlist()
|
||||
self.active_pair_whitelist = self.pairlists.whitelist
|
||||
|
||||
# Extend active-pair whitelist with pairs from open trades
|
||||
# ensures that tickers are downloaded for open trades
|
||||
self.active_pair_whitelist.extend([trade.pair for trade in trades
|
||||
if trade.pair not in self.active_pair_whitelist])
|
||||
# Calculating Edge positioning
|
||||
if self.edge:
|
||||
self.edge.calculate()
|
||||
self.active_pair_whitelist = self.edge.adjust(self.active_pair_whitelist)
|
||||
|
||||
# Refreshing candles
|
||||
self.exchange.refresh_tickers(self.active_pair_whitelist, self.strategy.ticker_interval)
|
||||
# Query trades from persistence layer
|
||||
trades = Trade.get_open_trades()
|
||||
|
||||
# First process current opened trades
|
||||
for trade in trades:
|
||||
state_changed |= self.process_maybe_execute_sell(trade)
|
||||
# Extend active-pair whitelist with pairs from open trades
|
||||
# It ensures that tickers are downloaded for open trades
|
||||
self._extend_whitelist_with_trades(self.active_pair_whitelist, trades)
|
||||
|
||||
# Then looking for buy opportunities
|
||||
if len(trades) < self.config['max_open_trades']:
|
||||
state_changed = self.process_maybe_execute_buy()
|
||||
# Refreshing candles
|
||||
self.dataprovider.refresh(self._create_pair_whitelist(self.active_pair_whitelist),
|
||||
self.strategy.informative_pairs())
|
||||
|
||||
if 'unfilledtimeout' in self.config:
|
||||
# Check and handle any timed out open orders
|
||||
self.check_handle_timedout()
|
||||
Trade.session.flush()
|
||||
# First process current opened trades
|
||||
for trade in trades:
|
||||
state_changed |= self.process_maybe_execute_sell(trade)
|
||||
|
||||
# Then looking for buy opportunities
|
||||
if len(trades) < self.config['max_open_trades']:
|
||||
state_changed = self.process_maybe_execute_buy()
|
||||
|
||||
if 'unfilledtimeout' in self.config:
|
||||
# Check and handle any timed out open orders
|
||||
self.check_handle_timedout()
|
||||
Trade.session.flush()
|
||||
|
||||
except TemporaryError as error:
|
||||
logger.warning('%s, retrying in 30 seconds...', error)
|
||||
time.sleep(constants.RETRY_TIMEOUT)
|
||||
except OperationalException:
|
||||
tb = traceback.format_exc()
|
||||
hint = 'Issue `/start` if you think it is safe to restart.'
|
||||
self.rpc.send_msg({
|
||||
'type': RPCMessageType.STATUS_NOTIFICATION,
|
||||
'status': f'OperationalException:\n```\n{tb}```{hint}'
|
||||
})
|
||||
logger.exception('OperationalException. Stopping trader ...')
|
||||
self.state = State.STOPPED
|
||||
return state_changed
|
||||
|
||||
def get_target_bid(self, pair: str, ticker: Dict[str, float]) -> float:
|
||||
def _extend_whitelist_with_trades(self, whitelist: List[str], trades: List[Any]):
|
||||
"""
|
||||
Extend whitelist with pairs from open trades
|
||||
"""
|
||||
whitelist.extend([trade.pair for trade in trades if trade.pair not in whitelist])
|
||||
|
||||
def _create_pair_whitelist(self, pairs: List[str]) -> List[Tuple[str, str]]:
|
||||
"""
|
||||
Create pair-whitelist tuple with (pair, ticker_interval)
|
||||
"""
|
||||
return [(pair, self.config['ticker_interval']) for pair in pairs]
|
||||
|
||||
def get_target_bid(self, pair: str, tick: Dict = None) -> float:
|
||||
"""
|
||||
Calculates bid target between current ask price and last price
|
||||
:param ticker: Ticker to use for getting Ask and Last Price
|
||||
:return: float: Price
|
||||
"""
|
||||
if ticker['ask'] < ticker['last']:
|
||||
ticker_rate = ticker['ask']
|
||||
else:
|
||||
balance = self.config['bid_strategy']['ask_last_balance']
|
||||
ticker_rate = ticker['ask'] + balance * (ticker['last'] - ticker['ask'])
|
||||
|
||||
used_rate = ticker_rate
|
||||
config_bid_strategy = self.config.get('bid_strategy', {})
|
||||
if 'use_order_book' in config_bid_strategy and\
|
||||
config_bid_strategy.get('use_order_book', False):
|
||||
@@ -218,15 +161,19 @@ class FreqtradeBot(object):
|
||||
logger.debug('order_book %s', order_book)
|
||||
# top 1 = index 0
|
||||
order_book_rate = order_book['bids'][order_book_top - 1][0]
|
||||
# if ticker has lower rate, then use ticker ( usefull if down trending )
|
||||
logger.info('...top %s order book buy rate %0.8f', order_book_top, order_book_rate)
|
||||
if ticker_rate < order_book_rate:
|
||||
logger.info('...using ticker rate instead %0.8f', ticker_rate)
|
||||
used_rate = ticker_rate
|
||||
else:
|
||||
used_rate = order_book_rate
|
||||
used_rate = order_book_rate
|
||||
else:
|
||||
logger.info('Using Last Ask / Last Price')
|
||||
if not tick:
|
||||
logger.info('Using Last Ask / Last Price')
|
||||
ticker = self.exchange.get_ticker(pair)
|
||||
else:
|
||||
ticker = tick
|
||||
if ticker['ask'] < ticker['last']:
|
||||
ticker_rate = ticker['ask']
|
||||
else:
|
||||
balance = self.config['bid_strategy']['ask_last_balance']
|
||||
ticker_rate = ticker['ask'] + balance * (ticker['last'] - ticker['ask'])
|
||||
used_rate = ticker_rate
|
||||
|
||||
return used_rate
|
||||
@@ -250,7 +197,7 @@ class FreqtradeBot(object):
|
||||
avaliable_amount = self.wallets.get_free(self.config['stake_currency'])
|
||||
|
||||
if stake_amount == constants.UNLIMITED_STAKE_AMOUNT:
|
||||
open_trades = len(Trade.query.filter(Trade.is_open.is_(True)).all())
|
||||
open_trades = len(Trade.get_open_trades())
|
||||
if open_trades >= self.config['max_open_trades']:
|
||||
logger.warning('Can\'t open a new trade: max number of trades is reached')
|
||||
return None
|
||||
@@ -259,20 +206,17 @@ class FreqtradeBot(object):
|
||||
# Check if stake_amount is fulfilled
|
||||
if avaliable_amount < stake_amount:
|
||||
raise DependencyException(
|
||||
'Available balance(%f %s) is lower than stake amount(%f %s)' % (
|
||||
avaliable_amount, self.config['stake_currency'],
|
||||
stake_amount, self.config['stake_currency'])
|
||||
f"Available balance({avaliable_amount} {self.config['stake_currency']}) is "
|
||||
f"lower than stake amount({stake_amount} {self.config['stake_currency']})"
|
||||
)
|
||||
|
||||
return stake_amount
|
||||
|
||||
def _get_min_pair_stake_amount(self, pair: str, price: float) -> Optional[float]:
|
||||
markets = self.exchange.get_markets()
|
||||
markets = [m for m in markets if m['symbol'] == pair]
|
||||
if not markets:
|
||||
raise ValueError(f'Can\'t get market information for symbol {pair}')
|
||||
|
||||
market = markets[0]
|
||||
try:
|
||||
market = self.exchange.markets[pair]
|
||||
except KeyError:
|
||||
raise ValueError(f"Can't get market information for symbol {pair}")
|
||||
|
||||
if 'limits' not in market:
|
||||
return None
|
||||
@@ -290,7 +234,9 @@ class FreqtradeBot(object):
|
||||
if not min_stake_amounts:
|
||||
return None
|
||||
|
||||
amount_reserve_percent = 1 - 0.05 # reserve 5% + stoploss
|
||||
# reserve some percent defined in config (5% default) + stoploss
|
||||
amount_reserve_percent = 1.0 - self.config.get('amount_reserve_percent',
|
||||
constants.DEFAULT_AMOUNT_RESERVE_PERCENT)
|
||||
if self.strategy.stoploss is not None:
|
||||
amount_reserve_percent += self.strategy.stoploss
|
||||
# it should not be more than 50%
|
||||
@@ -306,27 +252,32 @@ class FreqtradeBot(object):
|
||||
interval = self.strategy.ticker_interval
|
||||
whitelist = copy.deepcopy(self.active_pair_whitelist)
|
||||
|
||||
if not whitelist:
|
||||
logger.warning("Whitelist is empty.")
|
||||
return False
|
||||
|
||||
# Remove currently opened and latest pairs from whitelist
|
||||
for trade in Trade.query.filter(Trade.is_open.is_(True)).all():
|
||||
for trade in Trade.get_open_trades():
|
||||
if trade.pair in whitelist:
|
||||
whitelist.remove(trade.pair)
|
||||
logger.debug('Ignoring %s in pair whitelist', trade.pair)
|
||||
|
||||
if not whitelist:
|
||||
raise DependencyException('No currency pairs in whitelist')
|
||||
logger.info("No currency pair in whitelist, but checking to sell open trades.")
|
||||
return False
|
||||
|
||||
# running get_signal on historical data fetched
|
||||
for _pair in whitelist:
|
||||
(buy, sell) = self.strategy.get_signal(_pair, interval, self.exchange.klines(_pair))
|
||||
(buy, sell) = self.strategy.get_signal(
|
||||
_pair, interval, self.dataprovider.ohlcv(_pair, self.strategy.ticker_interval))
|
||||
|
||||
if buy and not sell:
|
||||
stake_amount = self._get_trade_stake_amount(_pair)
|
||||
if not stake_amount:
|
||||
return False
|
||||
|
||||
logger.info(
|
||||
'Buy signal found: about create a new trade with stake_amount: %f ...',
|
||||
stake_amount
|
||||
)
|
||||
logger.info(f"Buy signal found: about create a new trade with stake_amount: "
|
||||
f"{stake_amount} ...")
|
||||
|
||||
bidstrat_check_depth_of_market = self.config.get('bid_strategy', {}).\
|
||||
get('check_depth_of_market', {})
|
||||
@@ -364,7 +315,6 @@ class FreqtradeBot(object):
|
||||
:return: None
|
||||
"""
|
||||
pair_s = pair.replace('_', '/')
|
||||
pair_url = self.exchange.get_pair_detail_url(pair)
|
||||
stake_currency = self.config['stake_currency']
|
||||
fiat_currency = self.config.get('fiat_display_currency', None)
|
||||
time_in_force = self.strategy.order_time_in_force['buy']
|
||||
@@ -373,13 +323,13 @@ class FreqtradeBot(object):
|
||||
buy_limit_requested = price
|
||||
else:
|
||||
# Calculate amount
|
||||
buy_limit_requested = self.get_target_bid(pair, self.exchange.get_ticker(pair))
|
||||
buy_limit_requested = self.get_target_bid(pair)
|
||||
|
||||
min_stake_amount = self._get_min_pair_stake_amount(pair_s, buy_limit_requested)
|
||||
if min_stake_amount is not None and min_stake_amount > stake_amount:
|
||||
logger.warning(
|
||||
f'Can\'t open a new trade for {pair_s}: stake amount'
|
||||
f' is too small ({stake_amount} < {min_stake_amount})'
|
||||
f'Can\'t open a new trade for {pair_s}: stake amount '
|
||||
f'is too small ({stake_amount} < {min_stake_amount})'
|
||||
)
|
||||
return False
|
||||
|
||||
@@ -423,13 +373,11 @@ class FreqtradeBot(object):
|
||||
stake_amount = order['cost']
|
||||
amount = order['amount']
|
||||
buy_limit_filled_price = order['price']
|
||||
order_id = None
|
||||
|
||||
self.rpc.send_msg({
|
||||
'type': RPCMessageType.BUY_NOTIFICATION,
|
||||
'exchange': self.exchange.name.capitalize(),
|
||||
'pair': pair_s,
|
||||
'market_url': pair_url,
|
||||
'limit': buy_limit_filled_price,
|
||||
'stake_amount': stake_amount,
|
||||
'stake_currency': stake_currency,
|
||||
@@ -450,9 +398,13 @@ class FreqtradeBot(object):
|
||||
exchange=self.exchange.id,
|
||||
open_order_id=order_id,
|
||||
strategy=self.strategy.get_strategy_name(),
|
||||
ticker_interval=constants.TICKER_INTERVAL_MINUTES[self.config['ticker_interval']]
|
||||
ticker_interval=timeframe_to_minutes(self.config['ticker_interval'])
|
||||
)
|
||||
|
||||
# Update fees if order is closed
|
||||
if order_status == 'closed':
|
||||
self.update_trade_state(trade, order)
|
||||
|
||||
Trade.session.add(trade)
|
||||
Trade.session.flush()
|
||||
|
||||
@@ -483,23 +435,7 @@ class FreqtradeBot(object):
|
||||
:return: True if executed
|
||||
"""
|
||||
try:
|
||||
# Get order details for actual price per unit
|
||||
if trade.open_order_id:
|
||||
# Update trade with order values
|
||||
logger.info('Found open order for %s', trade)
|
||||
order = self.exchange.get_order(trade.open_order_id, trade.pair)
|
||||
# Try update amount (binance-fix)
|
||||
try:
|
||||
new_amount = self.get_real_amount(trade, order)
|
||||
if order['amount'] != new_amount:
|
||||
order['amount'] = new_amount
|
||||
# Fee was applied, so set to 0
|
||||
trade.fee_open = 0
|
||||
|
||||
except OperationalException as exception:
|
||||
logger.warning("could not update trade amount: %s", exception)
|
||||
|
||||
trade.update(order)
|
||||
self.update_trade_state(trade)
|
||||
|
||||
if self.strategy.order_types.get('stoploss_on_exchange') and trade.is_open:
|
||||
result = self.handle_stoploss_on_exchange(trade)
|
||||
@@ -556,30 +492,71 @@ class FreqtradeBot(object):
|
||||
fee_abs += exectrade['fee']['cost']
|
||||
|
||||
if amount != order_amount:
|
||||
logger.warning(f"amount {amount} does not match amount {trade.amount}")
|
||||
logger.warning(f"Amount {amount} does not match amount {trade.amount}")
|
||||
raise OperationalException("Half bought? Amounts don't match")
|
||||
real_amount = amount - fee_abs
|
||||
if fee_abs != 0:
|
||||
logger.info(f"""Applying fee on amount for {trade} \
|
||||
(from {order_amount} to {real_amount}) from Trades""")
|
||||
logger.info(f"Applying fee on amount for {trade} "
|
||||
f"(from {order_amount} to {real_amount}) from Trades")
|
||||
return real_amount
|
||||
|
||||
def update_trade_state(self, trade, action_order: dict = None):
|
||||
"""
|
||||
Checks trades with open orders and updates the amount if necessary
|
||||
"""
|
||||
# Get order details for actual price per unit
|
||||
if trade.open_order_id:
|
||||
# Update trade with order values
|
||||
logger.info('Found open order for %s', trade)
|
||||
order = action_order or self.exchange.get_order(trade.open_order_id, trade.pair)
|
||||
# Try update amount (binance-fix)
|
||||
try:
|
||||
new_amount = self.get_real_amount(trade, order)
|
||||
if order['amount'] != new_amount:
|
||||
order['amount'] = new_amount
|
||||
# Fee was applied, so set to 0
|
||||
trade.fee_open = 0
|
||||
|
||||
except OperationalException as exception:
|
||||
logger.warning("Could not update trade amount: %s", exception)
|
||||
|
||||
trade.update(order)
|
||||
|
||||
def get_sell_rate(self, pair: str, refresh: bool) -> float:
|
||||
"""
|
||||
Get sell rate - either using get-ticker bid or first bid based on orderbook
|
||||
The orderbook portion is only used for rpc messaging, which would otherwise fail
|
||||
for BitMex (has no bid/ask in get_ticker)
|
||||
or remain static in any other case since it's not updating.
|
||||
:return: Bid rate
|
||||
"""
|
||||
config_ask_strategy = self.config.get('ask_strategy', {})
|
||||
if config_ask_strategy.get('use_order_book', False):
|
||||
logger.debug('Using order book to get sell rate')
|
||||
|
||||
order_book = self.exchange.get_order_book(pair, 1)
|
||||
rate = order_book['bids'][0][0]
|
||||
|
||||
else:
|
||||
rate = self.exchange.get_ticker(pair, refresh)['bid']
|
||||
return rate
|
||||
|
||||
def handle_trade(self, trade: Trade) -> bool:
|
||||
"""
|
||||
Sells the current pair if the threshold is reached and updates the trade record.
|
||||
:return: True if trade has been sold, False otherwise
|
||||
"""
|
||||
if not trade.is_open:
|
||||
raise ValueError(f'attempt to handle closed trade: {trade}')
|
||||
raise ValueError(f'Attempt to handle closed trade: {trade}')
|
||||
|
||||
logger.debug('Handling %s ...', trade)
|
||||
sell_rate = self.exchange.get_ticker(trade.pair)['bid']
|
||||
|
||||
(buy, sell) = (False, False)
|
||||
experimental = self.config.get('experimental', {})
|
||||
if experimental.get('use_sell_signal') or experimental.get('ignore_roi_if_buy_signal'):
|
||||
(buy, sell) = self.strategy.get_signal(trade.pair, self.strategy.ticker_interval,
|
||||
self.exchange.klines(trade.pair))
|
||||
(buy, sell) = self.strategy.get_signal(
|
||||
trade.pair, self.strategy.ticker_interval,
|
||||
self.dataprovider.ohlcv(trade.pair, self.strategy.ticker_interval))
|
||||
|
||||
config_ask_strategy = self.config.get('ask_strategy', {})
|
||||
if config_ask_strategy.get('use_order_book', False):
|
||||
@@ -592,18 +569,15 @@ class FreqtradeBot(object):
|
||||
|
||||
for i in range(order_book_min, order_book_max + 1):
|
||||
order_book_rate = order_book['asks'][i - 1][0]
|
||||
|
||||
# if orderbook has higher rate (high profit),
|
||||
# use orderbook, otherwise just use bids rate
|
||||
logger.info(' order book asks top %s: %0.8f', i, order_book_rate)
|
||||
if sell_rate < order_book_rate:
|
||||
sell_rate = order_book_rate
|
||||
sell_rate = order_book_rate
|
||||
|
||||
if self.check_sell(trade, sell_rate, buy, sell):
|
||||
return True
|
||||
break
|
||||
|
||||
else:
|
||||
logger.debug('checking sell')
|
||||
sell_rate = self.get_sell_rate(trade.pair, True)
|
||||
if self.check_sell(trade, sell_rate, buy, sell):
|
||||
return True
|
||||
|
||||
@@ -613,15 +587,29 @@ class FreqtradeBot(object):
|
||||
def handle_stoploss_on_exchange(self, trade: Trade) -> bool:
|
||||
"""
|
||||
Check if trade is fulfilled in which case the stoploss
|
||||
on exchange should be added immediately if stoploss on exchnage
|
||||
on exchange should be added immediately if stoploss on exchange
|
||||
is enabled.
|
||||
"""
|
||||
|
||||
result = False
|
||||
logger.debug('Handling stoploss on exchange %s ...', trade)
|
||||
|
||||
# If trade is open and the buy order is fulfilled but there is no stoploss,
|
||||
# then we add a stoploss on exchange
|
||||
if not trade.open_order_id and not trade.stoploss_order_id:
|
||||
stoploss_order = None
|
||||
|
||||
try:
|
||||
# First we check if there is already a stoploss on exchange
|
||||
stoploss_order = self.exchange.get_order(trade.stoploss_order_id, trade.pair) \
|
||||
if trade.stoploss_order_id else None
|
||||
except InvalidOrderException as exception:
|
||||
logger.warning('Unable to fetch stoploss order: %s', exception)
|
||||
|
||||
# If trade open order id does not exist: buy order is fulfilled
|
||||
buy_order_fulfilled = not trade.open_order_id
|
||||
|
||||
# Limit price threshold: As limit price should always be below price
|
||||
limit_price_pct = 0.99
|
||||
|
||||
# If buy order is fulfilled but there is no stoploss, we add a stoploss on exchange
|
||||
if (buy_order_fulfilled and not stoploss_order):
|
||||
if self.edge:
|
||||
stoploss = self.edge.stoploss(pair=trade.pair)
|
||||
else:
|
||||
@@ -630,26 +618,71 @@ class FreqtradeBot(object):
|
||||
stop_price = trade.open_rate * (1 + stoploss)
|
||||
|
||||
# limit price should be less than stop price.
|
||||
# 0.98 is arbitrary here.
|
||||
limit_price = stop_price * 0.98
|
||||
limit_price = stop_price * limit_price_pct
|
||||
|
||||
stoploss_order_id = self.exchange.stoploss_limit(
|
||||
pair=trade.pair, amount=trade.amount, stop_price=stop_price, rate=limit_price
|
||||
)['id']
|
||||
trade.stoploss_order_id = str(stoploss_order_id)
|
||||
try:
|
||||
stoploss_order_id = self.exchange.stoploss_limit(
|
||||
pair=trade.pair, amount=trade.amount, stop_price=stop_price, rate=limit_price
|
||||
)['id']
|
||||
trade.stoploss_order_id = str(stoploss_order_id)
|
||||
trade.stoploss_last_update = datetime.now()
|
||||
return False
|
||||
|
||||
# Or the trade open and there is already a stoploss on exchange.
|
||||
# so we check if it is hit ...
|
||||
elif trade.stoploss_order_id:
|
||||
logger.debug('Handling stoploss on exchange %s ...', trade)
|
||||
order = self.exchange.get_order(trade.stoploss_order_id, trade.pair)
|
||||
if order['status'] == 'closed':
|
||||
trade.sell_reason = SellType.STOPLOSS_ON_EXCHANGE.value
|
||||
trade.update(order)
|
||||
result = True
|
||||
else:
|
||||
result = False
|
||||
return result
|
||||
except DependencyException as exception:
|
||||
logger.warning('Unable to place a stoploss order on exchange: %s', exception)
|
||||
|
||||
# If stoploss order is canceled for some reason we add it
|
||||
if stoploss_order and stoploss_order['status'] == 'canceled':
|
||||
try:
|
||||
stoploss_order_id = self.exchange.stoploss_limit(
|
||||
pair=trade.pair, amount=trade.amount,
|
||||
stop_price=trade.stop_loss, rate=trade.stop_loss * limit_price_pct
|
||||
)['id']
|
||||
trade.stoploss_order_id = str(stoploss_order_id)
|
||||
return False
|
||||
except DependencyException as exception:
|
||||
logger.warning('Stoploss order was cancelled, '
|
||||
'but unable to recreate one: %s', exception)
|
||||
|
||||
# We check if stoploss order is fulfilled
|
||||
if stoploss_order and stoploss_order['status'] == 'closed':
|
||||
trade.sell_reason = SellType.STOPLOSS_ON_EXCHANGE.value
|
||||
trade.update(stoploss_order)
|
||||
self.notify_sell(trade)
|
||||
return True
|
||||
|
||||
# Finally we check if stoploss on exchange should be moved up because of trailing.
|
||||
if stoploss_order and self.config.get('trailing_stop', False):
|
||||
# if trailing stoploss is enabled we check if stoploss value has changed
|
||||
# in which case we cancel stoploss order and put another one with new
|
||||
# value immediately
|
||||
self.handle_trailing_stoploss_on_exchange(trade, stoploss_order)
|
||||
|
||||
return False
|
||||
|
||||
def handle_trailing_stoploss_on_exchange(self, trade: Trade, order):
|
||||
"""
|
||||
Check to see if stoploss on exchange should be updated
|
||||
in case of trailing stoploss on exchange
|
||||
:param Trade: Corresponding Trade
|
||||
:param order: Current on exchange stoploss order
|
||||
:return: None
|
||||
"""
|
||||
|
||||
if trade.stop_loss > float(order['info']['stopPrice']):
|
||||
# we check if the update is neccesary
|
||||
update_beat = self.strategy.order_types.get('stoploss_on_exchange_interval', 60)
|
||||
if (datetime.utcnow() - trade.stoploss_last_update).total_seconds() > update_beat:
|
||||
# cancelling the current stoploss on exchange first
|
||||
logger.info('Trailing stoploss: cancelling current stoploss on exchange (id:{%s})'
|
||||
'in order to add another one ...', order['id'])
|
||||
if self.exchange.cancel_order(order['id'], trade.pair):
|
||||
# creating the new one
|
||||
stoploss_order_id = self.exchange.stoploss_limit(
|
||||
pair=trade.pair, amount=trade.amount,
|
||||
stop_price=trade.stop_loss, rate=trade.stop_loss * 0.99
|
||||
)['id']
|
||||
trade.stoploss_order_id = str(stoploss_order_id)
|
||||
|
||||
def check_sell(self, trade: Trade, sell_rate: float, buy: bool, sell: bool) -> bool:
|
||||
if self.edge:
|
||||
@@ -698,8 +731,15 @@ class FreqtradeBot(object):
|
||||
self.wallets.update()
|
||||
continue
|
||||
|
||||
# Check if trade is still actually open
|
||||
if order['status'] == 'open':
|
||||
# Handle cancelled on exchange
|
||||
if order['status'] == 'canceled':
|
||||
if order['side'] == 'buy':
|
||||
self.handle_buy_order_full_cancel(trade, "canceled on Exchange")
|
||||
elif order['side'] == 'sell':
|
||||
self.handle_timedout_limit_sell(trade, order)
|
||||
self.wallets.update()
|
||||
# Check if order is still actually open
|
||||
elif order['status'] == 'open':
|
||||
if order['side'] == 'buy' and ordertime < buy_timeoutthreashold:
|
||||
self.handle_timedout_limit_buy(trade, order)
|
||||
self.wallets.update()
|
||||
@@ -707,24 +747,24 @@ class FreqtradeBot(object):
|
||||
self.handle_timedout_limit_sell(trade, order)
|
||||
self.wallets.update()
|
||||
|
||||
# FIX: 20180110, why is cancel.order unconditionally here, whereas
|
||||
# it is conditionally called in the
|
||||
# handle_timedout_limit_sell()?
|
||||
def handle_buy_order_full_cancel(self, trade: Trade, reason: str) -> None:
|
||||
"""Close trade in database and send message"""
|
||||
Trade.session.delete(trade)
|
||||
Trade.session.flush()
|
||||
logger.info('Buy order %s for %s.', reason, trade)
|
||||
self.rpc.send_msg({
|
||||
'type': RPCMessageType.STATUS_NOTIFICATION,
|
||||
'status': f'Unfilled buy order for {trade.pair} {reason}'
|
||||
})
|
||||
|
||||
def handle_timedout_limit_buy(self, trade: Trade, order: Dict) -> bool:
|
||||
"""Buy timeout - cancel order
|
||||
:return: True if order was fully cancelled
|
||||
"""
|
||||
pair_s = trade.pair.replace('_', '/')
|
||||
self.exchange.cancel_order(trade.open_order_id, trade.pair)
|
||||
if order['remaining'] == order['amount']:
|
||||
# if trade is not partially completed, just delete the trade
|
||||
Trade.session.delete(trade)
|
||||
Trade.session.flush()
|
||||
logger.info('Buy order timeout for %s.', trade)
|
||||
self.rpc.send_msg({
|
||||
'type': RPCMessageType.STATUS_NOTIFICATION,
|
||||
'status': f'Unfilled buy order for {pair_s} cancelled due to timeout'
|
||||
})
|
||||
self.handle_buy_order_full_cancel(trade, "cancelled due to timeout")
|
||||
return True
|
||||
|
||||
# if trade is partially complete, edit the stake details for the trade
|
||||
@@ -735,20 +775,24 @@ class FreqtradeBot(object):
|
||||
logger.info('Partial buy order timeout for %s.', trade)
|
||||
self.rpc.send_msg({
|
||||
'type': RPCMessageType.STATUS_NOTIFICATION,
|
||||
'status': f'Remaining buy order for {pair_s} cancelled due to timeout'
|
||||
'status': f'Remaining buy order for {trade.pair} cancelled due to timeout'
|
||||
})
|
||||
return False
|
||||
|
||||
# FIX: 20180110, should cancel_order() be cond. or unconditionally called?
|
||||
def handle_timedout_limit_sell(self, trade: Trade, order: Dict) -> bool:
|
||||
"""
|
||||
Sell timeout - cancel order and update trade
|
||||
:return: True if order was fully cancelled
|
||||
"""
|
||||
pair_s = trade.pair.replace('_', '/')
|
||||
if order['remaining'] == order['amount']:
|
||||
# if trade is not partially completed, just cancel the trade
|
||||
self.exchange.cancel_order(trade.open_order_id, trade.pair)
|
||||
if order["status"] != "canceled":
|
||||
reason = "due to timeout"
|
||||
self.exchange.cancel_order(trade.open_order_id, trade.pair)
|
||||
logger.info('Sell order timeout for %s.', trade)
|
||||
else:
|
||||
reason = "on exchange"
|
||||
logger.info('Sell order canceled on exchange for %s.', trade)
|
||||
trade.close_rate = None
|
||||
trade.close_profit = None
|
||||
trade.close_date = None
|
||||
@@ -756,9 +800,9 @@ class FreqtradeBot(object):
|
||||
trade.open_order_id = None
|
||||
self.rpc.send_msg({
|
||||
'type': RPCMessageType.STATUS_NOTIFICATION,
|
||||
'status': f'Unfilled sell order for {pair_s} cancelled due to timeout'
|
||||
'status': f'Unfilled sell order for {trade.pair} cancelled {reason}'
|
||||
})
|
||||
logger.info('Sell order timeout for %s.', trade)
|
||||
|
||||
return True
|
||||
|
||||
# TODO: figure out how to handle partially complete sell orders
|
||||
@@ -780,7 +824,7 @@ class FreqtradeBot(object):
|
||||
# we consider the sell price stop price
|
||||
if self.config.get('dry_run', False) and sell_type == 'stoploss' \
|
||||
and self.strategy.order_types['stoploss_on_exchange']:
|
||||
limit = trade.stop_loss
|
||||
limit = trade.stop_loss
|
||||
|
||||
# First cancelling stoploss on exchange ...
|
||||
if self.strategy.order_types.get('stoploss_on_exchange') and trade.stoploss_order_id:
|
||||
@@ -796,11 +840,18 @@ class FreqtradeBot(object):
|
||||
trade.open_order_id = order_id
|
||||
trade.close_rate_requested = limit
|
||||
trade.sell_reason = sell_reason.value
|
||||
Trade.session.flush()
|
||||
self.notify_sell(trade)
|
||||
|
||||
profit_trade = trade.calc_profit(rate=limit)
|
||||
current_rate = self.exchange.get_ticker(trade.pair)['bid']
|
||||
profit_percent = trade.calc_profit_percent(limit)
|
||||
pair_url = self.exchange.get_pair_detail_url(trade.pair)
|
||||
def notify_sell(self, trade: Trade):
|
||||
"""
|
||||
Sends rpc notification when a sell occured.
|
||||
"""
|
||||
profit_rate = trade.close_rate if trade.close_rate else trade.close_rate_requested
|
||||
profit_trade = trade.calc_profit(rate=profit_rate)
|
||||
# Use cached ticker here - it was updated seconds ago.
|
||||
current_rate = self.get_sell_rate(trade.pair, False)
|
||||
profit_percent = trade.calc_profit_percent(profit_rate)
|
||||
gain = "profit" if profit_percent > 0 else "loss"
|
||||
|
||||
msg = {
|
||||
@@ -808,14 +859,13 @@ class FreqtradeBot(object):
|
||||
'exchange': trade.exchange.capitalize(),
|
||||
'pair': trade.pair,
|
||||
'gain': gain,
|
||||
'market_url': pair_url,
|
||||
'limit': limit,
|
||||
'limit': trade.close_rate_requested,
|
||||
'amount': trade.amount,
|
||||
'open_rate': trade.open_rate,
|
||||
'current_rate': current_rate,
|
||||
'profit_amount': profit_trade,
|
||||
'profit_percent': profit_percent,
|
||||
'sell_reason': sell_reason.value
|
||||
'sell_reason': trade.sell_reason
|
||||
}
|
||||
|
||||
# For regular case, when the configuration exists
|
||||
@@ -829,4 +879,3 @@ class FreqtradeBot(object):
|
||||
|
||||
# Send the message
|
||||
self.rpc.send_msg(msg)
|
||||
Trade.session.flush()
|
||||
|
||||
@@ -10,10 +10,9 @@ from typing import List
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.arguments import Arguments
|
||||
from freqtrade.configuration import Configuration, set_loggers
|
||||
from freqtrade.freqtradebot import FreqtradeBot
|
||||
from freqtrade.state import State
|
||||
from freqtrade.rpc import RPCMessageType
|
||||
from freqtrade.configuration import set_loggers
|
||||
from freqtrade.worker import Worker
|
||||
|
||||
|
||||
logger = logging.getLogger('freqtrade')
|
||||
|
||||
@@ -25,9 +24,9 @@ def main(sysargv: List[str]) -> None:
|
||||
"""
|
||||
arguments = Arguments(
|
||||
sysargv,
|
||||
'Simple High Frequency Trading Bot for crypto currencies'
|
||||
'Free, open source crypto trading bot'
|
||||
)
|
||||
args = arguments.get_parsed_arg()
|
||||
args: Namespace = arguments.get_parsed_arg()
|
||||
|
||||
# A subcommand has been issued.
|
||||
# Means if Backtesting or Hyperopt have been called we exit the bot
|
||||
@@ -35,20 +34,12 @@ def main(sysargv: List[str]) -> None:
|
||||
args.func(args)
|
||||
return
|
||||
|
||||
freqtrade = None
|
||||
worker = None
|
||||
return_code = 1
|
||||
try:
|
||||
# Load and validate configuration
|
||||
config = Configuration(args).get_config()
|
||||
|
||||
# Init the bot
|
||||
freqtrade = FreqtradeBot(config)
|
||||
|
||||
state = None
|
||||
while 1:
|
||||
state = freqtrade.worker(old_state=state)
|
||||
if state == State.RELOAD_CONF:
|
||||
freqtrade = reconfigure(freqtrade, args)
|
||||
# Load and run worker
|
||||
worker = Worker(args)
|
||||
worker.run()
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.info('SIGINT received, aborting ...')
|
||||
@@ -59,31 +50,11 @@ def main(sysargv: List[str]) -> None:
|
||||
except BaseException:
|
||||
logger.exception('Fatal exception!')
|
||||
finally:
|
||||
if freqtrade:
|
||||
freqtrade.rpc.send_msg({
|
||||
'type': RPCMessageType.STATUS_NOTIFICATION,
|
||||
'status': 'process died'
|
||||
})
|
||||
freqtrade.cleanup()
|
||||
if worker:
|
||||
worker.exit()
|
||||
sys.exit(return_code)
|
||||
|
||||
|
||||
def reconfigure(freqtrade: FreqtradeBot, args: Namespace) -> FreqtradeBot:
|
||||
"""
|
||||
Cleans up current instance, reloads the configuration and returns the new instance
|
||||
"""
|
||||
# Clean up current modules
|
||||
freqtrade.cleanup()
|
||||
|
||||
# Create new instance
|
||||
freqtrade = FreqtradeBot(Configuration(args).get_config())
|
||||
freqtrade.rpc.send_msg({
|
||||
'type': RPCMessageType.STATUS_NOTIFICATION,
|
||||
'status': 'config reloaded'
|
||||
})
|
||||
return freqtrade
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
set_loggers()
|
||||
main(sys.argv[1:])
|
||||
|
||||
@@ -3,14 +3,15 @@ Various tool function for Freqtrade and scripts
|
||||
"""
|
||||
|
||||
import gzip
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Dict
|
||||
|
||||
from ccxt import Exchange
|
||||
import numpy as np
|
||||
from pandas import DataFrame
|
||||
import rapidjson
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -38,12 +39,7 @@ def datesarray_to_datetimearray(dates: np.ndarray) -> np.ndarray:
|
||||
An numpy-array of datetimes
|
||||
:return: numpy-array of datetime
|
||||
"""
|
||||
times = []
|
||||
dates = dates.astype(datetime)
|
||||
for index in range(0, dates.size):
|
||||
date = dates[index].to_pydatetime()
|
||||
times.append(date)
|
||||
return np.array(times)
|
||||
return dates.dt.to_pydatetime()
|
||||
|
||||
|
||||
def common_datearray(dfs: Dict[str, DataFrame]) -> np.ndarray:
|
||||
@@ -71,16 +67,45 @@ def file_dump_json(filename, data, is_zip=False) -> None:
|
||||
:param data: JSON Data to save
|
||||
:return:
|
||||
"""
|
||||
print(f'dumping json to "{filename}"')
|
||||
logger.info(f'dumping json to "{filename}"')
|
||||
|
||||
if is_zip:
|
||||
if not filename.endswith('.gz'):
|
||||
filename = filename + '.gz'
|
||||
with gzip.open(filename, 'w') as fp:
|
||||
json.dump(data, fp, default=str)
|
||||
rapidjson.dump(data, fp, default=str, number_mode=rapidjson.NM_NATIVE)
|
||||
else:
|
||||
with open(filename, 'w') as fp:
|
||||
json.dump(data, fp, default=str)
|
||||
rapidjson.dump(data, fp, default=str, number_mode=rapidjson.NM_NATIVE)
|
||||
|
||||
logger.debug(f'done json to "{filename}"')
|
||||
|
||||
|
||||
def json_load(datafile):
|
||||
"""
|
||||
load data with rapidjson
|
||||
Use this to have a consistent experience,
|
||||
sete number_mode to "NM_NATIVE" for greatest speed
|
||||
"""
|
||||
return rapidjson.load(datafile, number_mode=rapidjson.NM_NATIVE)
|
||||
|
||||
|
||||
def file_load_json(file):
|
||||
|
||||
gzipfile = file.with_suffix(file.suffix + '.gz')
|
||||
|
||||
# Try gzip file first, otherwise regular json file.
|
||||
if gzipfile.is_file():
|
||||
logger.debug('Loading ticker data from file %s', gzipfile)
|
||||
with gzip.open(gzipfile) as tickerdata:
|
||||
pairdata = json_load(tickerdata)
|
||||
elif file.is_file():
|
||||
logger.debug('Loading ticker data from file %s', file)
|
||||
with open(file) as tickerdata:
|
||||
pairdata = json_load(tickerdata)
|
||||
else:
|
||||
return None
|
||||
return pairdata
|
||||
|
||||
|
||||
def format_ms_time(date: int) -> str:
|
||||
@@ -89,3 +114,44 @@ def format_ms_time(date: int) -> str:
|
||||
: epoch-string in ms
|
||||
"""
|
||||
return datetime.fromtimestamp(date/1000.0).strftime('%Y-%m-%dT%H:%M:%S')
|
||||
|
||||
|
||||
def deep_merge_dicts(source, destination):
|
||||
"""
|
||||
>>> a = { 'first' : { 'rows' : { 'pass' : 'dog', 'number' : '1' } } }
|
||||
>>> b = { 'first' : { 'rows' : { 'fail' : 'cat', 'number' : '5' } } }
|
||||
>>> merge(b, a) == { 'first' : { 'rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }
|
||||
True
|
||||
"""
|
||||
for key, value in source.items():
|
||||
if isinstance(value, dict):
|
||||
# get node or create one
|
||||
node = destination.setdefault(key, {})
|
||||
deep_merge_dicts(value, node)
|
||||
else:
|
||||
destination[key] = value
|
||||
|
||||
return destination
|
||||
|
||||
|
||||
def timeframe_to_seconds(ticker_interval: str) -> int:
|
||||
"""
|
||||
Translates the timeframe interval value written in the human readable
|
||||
form ('1m', '5m', '1h', '1d', '1w', etc.) to the number
|
||||
of seconds for one timeframe interval.
|
||||
"""
|
||||
return Exchange.parse_timeframe(ticker_interval)
|
||||
|
||||
|
||||
def timeframe_to_minutes(ticker_interval: str) -> int:
|
||||
"""
|
||||
Same as above, but returns minutes.
|
||||
"""
|
||||
return Exchange.parse_timeframe(ticker_interval) // 60
|
||||
|
||||
|
||||
def timeframe_to_msecs(ticker_interval: str) -> int:
|
||||
"""
|
||||
Same as above, but returns milliseconds.
|
||||
"""
|
||||
return Exchange.parse_timeframe(ticker_interval) * 1000
|
||||
|
||||
@@ -13,15 +13,16 @@ from typing import Any, Dict, List, NamedTuple, Optional
|
||||
from pandas import DataFrame
|
||||
from tabulate import tabulate
|
||||
|
||||
import freqtrade.optimize as optimize
|
||||
from freqtrade import optimize
|
||||
from freqtrade import DependencyException, constants
|
||||
from freqtrade.arguments import Arguments
|
||||
from freqtrade.configuration import Configuration
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.data import history
|
||||
from freqtrade.misc import file_dump_json
|
||||
from freqtrade.data.dataprovider import DataProvider
|
||||
from freqtrade.misc import file_dump_json, timeframe_to_minutes
|
||||
from freqtrade.persistence import Trade
|
||||
from freqtrade.resolvers import StrategyResolver
|
||||
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.strategy.interface import SellType, IStrategy
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -64,10 +65,19 @@ class Backtesting(object):
|
||||
self.config['exchange']['uid'] = ''
|
||||
self.config['dry_run'] = True
|
||||
self.strategylist: List[IStrategy] = []
|
||||
|
||||
exchange_name = self.config.get('exchange', {}).get('name', 'bittrex').title()
|
||||
self.exchange = ExchangeResolver(exchange_name, self.config).exchange
|
||||
self.fee = self.exchange.get_fee()
|
||||
|
||||
if self.config.get('runmode') != RunMode.HYPEROPT:
|
||||
self.dataprovider = DataProvider(self.config, self.exchange)
|
||||
IStrategy.dp = self.dataprovider
|
||||
|
||||
if self.config.get('strategy_list', None):
|
||||
# Force one interval
|
||||
self.ticker_interval = str(self.config.get('ticker_interval'))
|
||||
self.ticker_interval_mins = constants.TICKER_INTERVAL_MINUTES[self.ticker_interval]
|
||||
self.ticker_interval_mins = timeframe_to_minutes(self.ticker_interval)
|
||||
for strat in list(self.config['strategy_list']):
|
||||
stratconf = deepcopy(self.config)
|
||||
stratconf['strategy'] = strat
|
||||
@@ -79,19 +89,21 @@ class Backtesting(object):
|
||||
# Load one strategy
|
||||
self._set_strategy(self.strategylist[0])
|
||||
|
||||
self.exchange = Exchange(self.config)
|
||||
self.fee = self.exchange.get_fee()
|
||||
|
||||
def _set_strategy(self, strategy):
|
||||
"""
|
||||
Load strategy into backtesting
|
||||
"""
|
||||
self.strategy = strategy
|
||||
|
||||
self.ticker_interval = self.config.get('ticker_interval')
|
||||
self.ticker_interval_mins = constants.TICKER_INTERVAL_MINUTES[self.ticker_interval]
|
||||
self.ticker_interval_mins = timeframe_to_minutes(self.ticker_interval)
|
||||
self.tickerdata_to_dataframe = strategy.tickerdata_to_dataframe
|
||||
self.advise_buy = strategy.advise_buy
|
||||
self.advise_sell = strategy.advise_sell
|
||||
# Set stoploss_on_exchange to false for backtesting,
|
||||
# since a "perfect" stoploss-sell is assumed anyway
|
||||
# And the regular "stoploss" function would not apply to that case
|
||||
self.strategy.order_types['stoploss_on_exchange'] = False
|
||||
|
||||
def _generate_text_table(self, data: Dict[str, Dict], results: DataFrame,
|
||||
skip_nan: bool = False) -> str:
|
||||
@@ -100,11 +112,13 @@ class Backtesting(object):
|
||||
:return: pretty printed table with tabulate as str
|
||||
"""
|
||||
stake_currency = str(self.config.get('stake_currency'))
|
||||
max_open_trades = self.config.get('max_open_trades')
|
||||
|
||||
floatfmt = ('s', 'd', '.2f', '.2f', '.8f', 'd', '.1f', '.1f')
|
||||
floatfmt = ('s', 'd', '.2f', '.2f', '.8f', '.2f', 'd', '.1f', '.1f')
|
||||
tabular_data = []
|
||||
headers = ['pair', 'buy count', 'avg profit %', 'cum profit %',
|
||||
'total profit ' + stake_currency, 'avg duration', 'profit', 'loss']
|
||||
'tot profit ' + stake_currency, 'tot profit %', 'avg duration',
|
||||
'profit', 'loss']
|
||||
for pair in data:
|
||||
result = results[results.pair == pair]
|
||||
if skip_nan and result.profit_abs.isnull().all():
|
||||
@@ -116,6 +130,7 @@ class Backtesting(object):
|
||||
result.profit_percent.mean() * 100.0,
|
||||
result.profit_percent.sum() * 100.0,
|
||||
result.profit_abs.sum(),
|
||||
result.profit_percent.sum() * 100.0 / max_open_trades,
|
||||
str(timedelta(
|
||||
minutes=round(result.trade_duration.mean()))) if not result.empty else '0:00',
|
||||
len(result[result.profit_abs > 0]),
|
||||
@@ -129,12 +144,15 @@ class Backtesting(object):
|
||||
results.profit_percent.mean() * 100.0,
|
||||
results.profit_percent.sum() * 100.0,
|
||||
results.profit_abs.sum(),
|
||||
results.profit_percent.sum() * 100.0 / max_open_trades,
|
||||
str(timedelta(
|
||||
minutes=round(results.trade_duration.mean()))) if not results.empty else '0:00',
|
||||
len(results[results.profit_abs > 0]),
|
||||
len(results[results.profit_abs < 0])
|
||||
])
|
||||
return tabulate(tabular_data, headers=headers, floatfmt=floatfmt, tablefmt="pipe")
|
||||
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
||||
return tabulate(tabular_data, headers=headers, # type: ignore
|
||||
floatfmt=floatfmt, tablefmt="pipe")
|
||||
|
||||
def _generate_text_table_sell_reason(self, data: Dict[str, Dict], results: DataFrame) -> str:
|
||||
"""
|
||||
@@ -151,11 +169,13 @@ class Backtesting(object):
|
||||
Generate summary table per strategy
|
||||
"""
|
||||
stake_currency = str(self.config.get('stake_currency'))
|
||||
max_open_trades = self.config.get('max_open_trades')
|
||||
|
||||
floatfmt = ('s', 'd', '.2f', '.2f', '.8f', 'd', '.1f', '.1f')
|
||||
floatfmt = ('s', 'd', '.2f', '.2f', '.8f', '.2f', 'd', '.1f', '.1f')
|
||||
tabular_data = []
|
||||
headers = ['Strategy', 'buy count', 'avg profit %', 'cum profit %',
|
||||
'total profit ' + stake_currency, 'avg duration', 'profit', 'loss']
|
||||
'tot profit ' + stake_currency, 'tot profit %', 'avg duration',
|
||||
'profit', 'loss']
|
||||
for strategy, results in all_results.items():
|
||||
tabular_data.append([
|
||||
strategy,
|
||||
@@ -163,12 +183,15 @@ class Backtesting(object):
|
||||
results.profit_percent.mean() * 100.0,
|
||||
results.profit_percent.sum() * 100.0,
|
||||
results.profit_abs.sum(),
|
||||
results.profit_percent.sum() * 100.0 / max_open_trades,
|
||||
str(timedelta(
|
||||
minutes=round(results.trade_duration.mean()))) if not results.empty else '0:00',
|
||||
len(results[results.profit_abs > 0]),
|
||||
len(results[results.profit_abs < 0])
|
||||
])
|
||||
return tabulate(tabular_data, headers=headers, floatfmt=floatfmt, tablefmt="pipe")
|
||||
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
||||
return tabulate(tabular_data, headers=headers, # type: ignore
|
||||
floatfmt=floatfmt, tablefmt="pipe")
|
||||
|
||||
def _store_backtest_result(self, recordfilename: str, results: DataFrame,
|
||||
strategyname: Optional[str] = None) -> None:
|
||||
@@ -187,6 +210,32 @@ class Backtesting(object):
|
||||
logger.info('Dumping backtest results to %s', recordfilename)
|
||||
file_dump_json(recordfilename, records)
|
||||
|
||||
def _get_ticker_list(self, processed) -> Dict[str, DataFrame]:
|
||||
"""
|
||||
Helper function to convert a processed tickerlist into a list for performance reasons.
|
||||
|
||||
Used by backtest() - so keep this optimized for performance.
|
||||
"""
|
||||
headers = ['date', 'buy', 'open', 'close', 'sell', 'low', 'high']
|
||||
ticker: Dict = {}
|
||||
# Create ticker dict
|
||||
for pair, pair_data in processed.items():
|
||||
pair_data['buy'], pair_data['sell'] = 0, 0 # cleanup from previous run
|
||||
|
||||
ticker_data = self.advise_sell(
|
||||
self.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy()
|
||||
|
||||
# to avoid using data from future, we buy/sell with signal from previous candle
|
||||
ticker_data.loc[:, 'buy'] = ticker_data['buy'].shift(1)
|
||||
ticker_data.loc[:, 'sell'] = ticker_data['sell'].shift(1)
|
||||
|
||||
ticker_data.drop(ticker_data.head(1).index, inplace=True)
|
||||
|
||||
# Convert from Pandas to list for performance reasons
|
||||
# (Looping Pandas is slow.)
|
||||
ticker[pair] = [x for x in ticker_data.itertuples()]
|
||||
return ticker
|
||||
|
||||
def _get_sell_trade_entry(
|
||||
self, pair: str, buy_row: DataFrame,
|
||||
partial_ticker: List, trade_count_lock: Dict, args: Dict) -> Optional[BacktestResult]:
|
||||
@@ -219,7 +268,8 @@ class Backtesting(object):
|
||||
# Set close_rate to stoploss
|
||||
closerate = trade.stop_loss
|
||||
elif sell.sell_type == (SellType.ROI):
|
||||
# get entry in min_roi >= to trade duration
|
||||
# get next entry in min_roi > to trade duration
|
||||
# Interface.py skips on trade_duration <= duration
|
||||
roi_entry = max(list(filter(lambda x: trade_dur >= x,
|
||||
self.strategy.minimal_roi.keys())))
|
||||
roi = self.strategy.minimal_roi[roi_entry]
|
||||
@@ -280,7 +330,6 @@ class Backtesting(object):
|
||||
position_stacking: do we allow position stacking? (default: False)
|
||||
:return: DataFrame
|
||||
"""
|
||||
headers = ['date', 'buy', 'open', 'close', 'sell', 'low', 'high']
|
||||
processed = args['processed']
|
||||
max_open_trades = args.get('max_open_trades', 0)
|
||||
position_stacking = args.get('position_stacking', False)
|
||||
@@ -288,54 +337,50 @@ class Backtesting(object):
|
||||
end_date = args['end_date']
|
||||
trades = []
|
||||
trade_count_lock: Dict = {}
|
||||
ticker: Dict = {}
|
||||
pairs = []
|
||||
# Create ticker dict
|
||||
for pair, pair_data in processed.items():
|
||||
pair_data['buy'], pair_data['sell'] = 0, 0 # cleanup from previous run
|
||||
|
||||
ticker_data = self.advise_sell(
|
||||
self.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy()
|
||||
|
||||
# to avoid using data from future, we buy/sell with signal from previous candle
|
||||
ticker_data.loc[:, 'buy'] = ticker_data['buy'].shift(1)
|
||||
ticker_data.loc[:, 'sell'] = ticker_data['sell'].shift(1)
|
||||
|
||||
ticker_data.drop(ticker_data.head(1).index, inplace=True)
|
||||
|
||||
# Convert from Pandas to list for performance reasons
|
||||
# (Looping Pandas is slow.)
|
||||
ticker[pair] = [x for x in ticker_data.itertuples()]
|
||||
pairs.append(pair)
|
||||
# Dict of ticker-lists for performance (looping lists is a lot faster than dataframes)
|
||||
ticker: Dict = self._get_ticker_list(processed)
|
||||
|
||||
lock_pair_until: Dict = {}
|
||||
# Indexes per pair, so some pairs are allowed to have a missing start.
|
||||
indexes: Dict = {}
|
||||
tmp = start_date + timedelta(minutes=self.ticker_interval_mins)
|
||||
index = 0
|
||||
# Loop timerange and test per pair
|
||||
|
||||
# Loop timerange and get candle for each pair at that point in time
|
||||
while tmp < end_date:
|
||||
# print(f"time: {tmp}")
|
||||
|
||||
for i, pair in enumerate(ticker):
|
||||
if pair not in indexes:
|
||||
indexes[pair] = 0
|
||||
|
||||
try:
|
||||
row = ticker[pair][index]
|
||||
row = ticker[pair][indexes[pair]]
|
||||
except IndexError:
|
||||
# missing Data for one pair ...
|
||||
# missing Data for one pair at the end.
|
||||
# Warnings for this are shown by `validate_backtest_data`
|
||||
continue
|
||||
|
||||
# Waits until the time-counter reaches the start of the data for this pair.
|
||||
if row.date > tmp.datetime:
|
||||
continue
|
||||
|
||||
indexes[pair] += 1
|
||||
|
||||
if row.buy == 0 or row.sell == 1:
|
||||
continue # skip rows where no buy signal or that would immediately sell off
|
||||
|
||||
if not position_stacking:
|
||||
if pair in lock_pair_until and row.date <= lock_pair_until[pair]:
|
||||
continue
|
||||
if (not position_stacking and pair in lock_pair_until
|
||||
and row.date <= lock_pair_until[pair]):
|
||||
# without positionstacking, we can only have one open trade per pair.
|
||||
continue
|
||||
|
||||
if max_open_trades > 0:
|
||||
# Check if max_open_trades has already been reached for the given date
|
||||
if not trade_count_lock.get(row.date, 0) < max_open_trades:
|
||||
continue
|
||||
|
||||
trade_count_lock[row.date] = trade_count_lock.get(row.date, 0) + 1
|
||||
|
||||
trade_entry = self._get_sell_trade_entry(pair, row, ticker[pair][index + 1:],
|
||||
trade_entry = self._get_sell_trade_entry(pair, row, ticker[pair][indexes[pair]:],
|
||||
trade_count_lock, args)
|
||||
|
||||
if trade_entry:
|
||||
@@ -343,11 +388,10 @@ class Backtesting(object):
|
||||
trades.append(trade_entry)
|
||||
else:
|
||||
# Set lock_pair_until to end of testing period if trade could not be closed
|
||||
# This happens only if the buy-signal was with the last candle
|
||||
lock_pair_until[pair] = end_date
|
||||
lock_pair_until[pair] = end_date.datetime
|
||||
|
||||
# Move time one configured time_interval ahead.
|
||||
tmp += timedelta(minutes=self.ticker_interval_mins)
|
||||
index += 1
|
||||
return DataFrame.from_records(trades, columns=BacktestResult._fields)
|
||||
|
||||
def start(self) -> None:
|
||||
@@ -362,8 +406,9 @@ class Backtesting(object):
|
||||
|
||||
if self.config.get('live'):
|
||||
logger.info('Downloading data for all pairs in whitelist ...')
|
||||
self.exchange.refresh_tickers(pairs, self.ticker_interval)
|
||||
data = self.exchange._klines
|
||||
self.exchange.refresh_latest_ohlcv([(pair, self.ticker_interval) for pair in pairs])
|
||||
data = {key[0]: value for key, value in self.exchange._klines.items()}
|
||||
|
||||
else:
|
||||
logger.info('Using local backtesting data (using whitelist in given config) ...')
|
||||
|
||||
@@ -393,19 +438,18 @@ class Backtesting(object):
|
||||
logger.info("Running backtesting for Strategy %s", strat.get_strategy_name())
|
||||
self._set_strategy(strat)
|
||||
|
||||
# need to reprocess data every time to populate signals
|
||||
preprocessed = self.strategy.tickerdata_to_dataframe(data)
|
||||
|
||||
min_date, max_date = optimize.get_timeframe(preprocessed)
|
||||
# Validate dataframe for missing values
|
||||
optimize.validate_backtest_data(preprocessed, min_date, max_date,
|
||||
constants.TICKER_INTERVAL_MINUTES[self.ticker_interval])
|
||||
min_date, max_date = optimize.get_timeframe(data)
|
||||
# Validate dataframe for missing values (mainly at start and end, as fillup is called)
|
||||
optimize.validate_backtest_data(data, min_date, max_date,
|
||||
timeframe_to_minutes(self.ticker_interval))
|
||||
logger.info(
|
||||
'Measuring data from %s up to %s (%s days)..',
|
||||
min_date.isoformat(),
|
||||
max_date.isoformat(),
|
||||
(max_date - min_date).days
|
||||
)
|
||||
# need to reprocess data every time to populate signals
|
||||
preprocessed = self.strategy.tickerdata_to_dataframe(data)
|
||||
|
||||
# Execute backtest and print results
|
||||
all_results[self.strategy.get_strategy_name()] = self.backtest(
|
||||
@@ -426,18 +470,18 @@ class Backtesting(object):
|
||||
strategy if len(self.strategylist) > 1 else None)
|
||||
|
||||
print(f"Result for strategy {strategy}")
|
||||
print(' BACKTESTING REPORT '.center(119, '='))
|
||||
print(' BACKTESTING REPORT '.center(133, '='))
|
||||
print(self._generate_text_table(data, results))
|
||||
|
||||
print(' SELL REASON STATS '.center(119, '='))
|
||||
print(' SELL REASON STATS '.center(133, '='))
|
||||
print(self._generate_text_table_sell_reason(data, results))
|
||||
|
||||
print(' LEFT OPEN TRADES REPORT '.center(119, '='))
|
||||
print(' LEFT OPEN TRADES REPORT '.center(133, '='))
|
||||
print(self._generate_text_table(data, results.loc[results.open_at_end], True))
|
||||
print()
|
||||
if len(all_results) > 1:
|
||||
# Print Strategy summary table
|
||||
print(' Strategy Summary '.center(119, '='))
|
||||
print(' Strategy Summary '.center(133, '='))
|
||||
print(self._generate_text_table_strategy(all_results))
|
||||
print('\nFor more details, please look at the detail tables above')
|
||||
|
||||
@@ -448,7 +492,7 @@ def setup_configuration(args: Namespace) -> Dict[str, Any]:
|
||||
:param args: Cli args from Arguments()
|
||||
:return: Configuration
|
||||
"""
|
||||
configuration = Configuration(args)
|
||||
configuration = Configuration(args, RunMode.BACKTEST)
|
||||
config = configuration.get_config()
|
||||
|
||||
# Ensure we do not use Exchange credentials
|
||||
|
||||
@@ -33,6 +33,7 @@ class DefaultHyperOpts(IHyperOpt):
|
||||
# Bollinger bands
|
||||
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
|
||||
dataframe['bb_lowerband'] = bollinger['lower']
|
||||
dataframe['bb_upperband'] = bollinger['upper']
|
||||
dataframe['sar'] = ta.SAR(dataframe)
|
||||
return dataframe
|
||||
|
||||
@@ -57,16 +58,17 @@ class DefaultHyperOpts(IHyperOpt):
|
||||
conditions.append(dataframe['rsi'] < params['rsi-value'])
|
||||
|
||||
# TRIGGERS
|
||||
if params['trigger'] == 'bb_lower':
|
||||
conditions.append(dataframe['close'] < dataframe['bb_lowerband'])
|
||||
if params['trigger'] == 'macd_cross_signal':
|
||||
conditions.append(qtpylib.crossed_above(
|
||||
dataframe['macd'], dataframe['macdsignal']
|
||||
))
|
||||
if params['trigger'] == 'sar_reversal':
|
||||
conditions.append(qtpylib.crossed_above(
|
||||
dataframe['close'], dataframe['sar']
|
||||
))
|
||||
if 'trigger' in params:
|
||||
if params['trigger'] == 'bb_lower':
|
||||
conditions.append(dataframe['close'] < dataframe['bb_lowerband'])
|
||||
if params['trigger'] == 'macd_cross_signal':
|
||||
conditions.append(qtpylib.crossed_above(
|
||||
dataframe['macd'], dataframe['macdsignal']
|
||||
))
|
||||
if params['trigger'] == 'sar_reversal':
|
||||
conditions.append(qtpylib.crossed_above(
|
||||
dataframe['close'], dataframe['sar']
|
||||
))
|
||||
|
||||
dataframe.loc[
|
||||
reduce(lambda x, y: x & y, conditions),
|
||||
@@ -93,6 +95,67 @@ class DefaultHyperOpts(IHyperOpt):
|
||||
Categorical(['bb_lower', 'macd_cross_signal', 'sar_reversal'], name='trigger')
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def sell_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||
"""
|
||||
Define the sell strategy parameters to be used by hyperopt
|
||||
"""
|
||||
def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Sell strategy Hyperopt will build and use
|
||||
"""
|
||||
# print(params)
|
||||
conditions = []
|
||||
# GUARDS AND TRENDS
|
||||
if 'sell-mfi-enabled' in params and params['sell-mfi-enabled']:
|
||||
conditions.append(dataframe['mfi'] > params['sell-mfi-value'])
|
||||
if 'sell-fastd-enabled' in params and params['sell-fastd-enabled']:
|
||||
conditions.append(dataframe['fastd'] > params['sell-fastd-value'])
|
||||
if 'sell-adx-enabled' in params and params['sell-adx-enabled']:
|
||||
conditions.append(dataframe['adx'] < params['sell-adx-value'])
|
||||
if 'sell-rsi-enabled' in params and params['sell-rsi-enabled']:
|
||||
conditions.append(dataframe['rsi'] > params['sell-rsi-value'])
|
||||
|
||||
# TRIGGERS
|
||||
if 'sell-trigger' in params:
|
||||
if params['sell-trigger'] == 'sell-bb_upper':
|
||||
conditions.append(dataframe['close'] > dataframe['bb_upperband'])
|
||||
if params['sell-trigger'] == 'sell-macd_cross_signal':
|
||||
conditions.append(qtpylib.crossed_above(
|
||||
dataframe['macdsignal'], dataframe['macd']
|
||||
))
|
||||
if params['sell-trigger'] == 'sell-sar_reversal':
|
||||
conditions.append(qtpylib.crossed_above(
|
||||
dataframe['sar'], dataframe['close']
|
||||
))
|
||||
|
||||
dataframe.loc[
|
||||
reduce(lambda x, y: x & y, conditions),
|
||||
'sell'] = 1
|
||||
|
||||
return dataframe
|
||||
|
||||
return populate_sell_trend
|
||||
|
||||
@staticmethod
|
||||
def sell_indicator_space() -> List[Dimension]:
|
||||
"""
|
||||
Define your Hyperopt space for searching sell strategy parameters
|
||||
"""
|
||||
return [
|
||||
Integer(75, 100, name='sell-mfi-value'),
|
||||
Integer(50, 100, name='sell-fastd-value'),
|
||||
Integer(50, 100, name='sell-adx-value'),
|
||||
Integer(60, 100, name='sell-rsi-value'),
|
||||
Categorical([True, False], name='sell-mfi-enabled'),
|
||||
Categorical([True, False], name='sell-fastd-enabled'),
|
||||
Categorical([True, False], name='sell-adx-enabled'),
|
||||
Categorical([True, False], name='sell-rsi-enabled'),
|
||||
Categorical(['sell-bb_upper',
|
||||
'sell-macd_cross_signal',
|
||||
'sell-sar_reversal'], name='sell-trigger')
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def generate_roi_table(params: Dict) -> Dict[int, float]:
|
||||
"""
|
||||
@@ -128,3 +191,36 @@ class DefaultHyperOpts(IHyperOpt):
|
||||
Real(0.01, 0.07, name='roi_p2'),
|
||||
Real(0.01, 0.20, name='roi_p3'),
|
||||
]
|
||||
|
||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators. Should be a copy of from strategy
|
||||
must align to populate_indicators in this file
|
||||
Only used when --spaces does not include buy
|
||||
"""
|
||||
dataframe.loc[
|
||||
(
|
||||
(dataframe['close'] < dataframe['bb_lowerband']) &
|
||||
(dataframe['mfi'] < 16) &
|
||||
(dataframe['adx'] > 25) &
|
||||
(dataframe['rsi'] < 21)
|
||||
),
|
||||
'buy'] = 1
|
||||
|
||||
return dataframe
|
||||
|
||||
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators. Should be a copy of from strategy
|
||||
must align to populate_indicators in this file
|
||||
Only used when --spaces does not include sell
|
||||
"""
|
||||
dataframe.loc[
|
||||
(
|
||||
(qtpylib.crossed_above(
|
||||
dataframe['macdsignal'], dataframe['macd']
|
||||
)) &
|
||||
(dataframe['fastd'] > 54)
|
||||
),
|
||||
'sell'] = 1
|
||||
return dataframe
|
||||
|
||||
@@ -9,10 +9,11 @@ from typing import Dict, Any
|
||||
from tabulate import tabulate
|
||||
from freqtrade.edge import Edge
|
||||
|
||||
from freqtrade.configuration import Configuration
|
||||
from freqtrade.arguments import Arguments
|
||||
from freqtrade.configuration import Configuration
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.resolvers import StrategyResolver
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -67,7 +68,9 @@ class EdgeCli(object):
|
||||
round(result[1].avg_trade_duration)
|
||||
])
|
||||
|
||||
return tabulate(tabular_data, headers=headers, floatfmt=floatfmt, tablefmt="pipe")
|
||||
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
||||
return tabulate(tabular_data, headers=headers, # type: ignore
|
||||
floatfmt=floatfmt, tablefmt="pipe")
|
||||
|
||||
def start(self) -> None:
|
||||
self.edge.calculate()
|
||||
@@ -81,7 +84,7 @@ def setup_configuration(args: Namespace) -> Dict[str, Any]:
|
||||
:param args: Cli args from Arguments()
|
||||
:return: Configuration
|
||||
"""
|
||||
configuration = Configuration(args)
|
||||
configuration = Configuration(args, RunMode.EDGECLI)
|
||||
config = configuration.get_config()
|
||||
|
||||
# Ensure we do not use Exchange credentials
|
||||
|
||||
@@ -5,17 +5,18 @@ This module contains the hyperopt logic
|
||||
"""
|
||||
|
||||
import logging
|
||||
from argparse import Namespace
|
||||
import multiprocessing
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from argparse import Namespace
|
||||
from math import exp
|
||||
import multiprocessing
|
||||
from operator import itemgetter
|
||||
from pathlib import Path
|
||||
from pprint import pprint
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from pandas import DataFrame
|
||||
from joblib import Parallel, delayed, dump, load, wrap_non_picklable_objects
|
||||
from pandas import DataFrame
|
||||
from skopt import Optimizer
|
||||
from skopt.space import Dimension
|
||||
|
||||
@@ -24,9 +25,9 @@ from freqtrade.configuration import Configuration
|
||||
from freqtrade.data.history import load_data
|
||||
from freqtrade.optimize import get_timeframe
|
||||
from freqtrade.optimize.backtesting import Backtesting
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.resolvers import HyperOptResolver
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_LOSS = 100000 # just a big enough number to be bad result in loss optimization
|
||||
@@ -102,13 +103,13 @@ class Hyperopt(Backtesting):
|
||||
results = sorted(self.trials, key=itemgetter('loss'))
|
||||
best_result = results[0]
|
||||
logger.info(
|
||||
'Best result:\n%s\nwith values:\n%s',
|
||||
best_result['result'],
|
||||
best_result['params']
|
||||
'Best result:\n%s\nwith values:\n',
|
||||
best_result['result']
|
||||
)
|
||||
pprint(best_result['params'], indent=4)
|
||||
if 'roi_t1' in best_result['params']:
|
||||
logger.info('ROI table:\n%s',
|
||||
self.custom_hyperopt.generate_roi_table(best_result['params']))
|
||||
logger.info('ROI table:')
|
||||
pprint(self.custom_hyperopt.generate_roi_table(best_result['params']), indent=4)
|
||||
|
||||
def log_results(self, results) -> None:
|
||||
"""
|
||||
@@ -151,6 +152,12 @@ class Hyperopt(Backtesting):
|
||||
spaces: List[Dimension] = []
|
||||
if self.has_space('buy'):
|
||||
spaces += self.custom_hyperopt.indicator_space()
|
||||
if self.has_space('sell'):
|
||||
spaces += self.custom_hyperopt.sell_indicator_space()
|
||||
# Make sure experimental is enabled
|
||||
if 'experimental' not in self.config:
|
||||
self.config['experimental'] = {}
|
||||
self.config['experimental']['use_sell_signal'] = True
|
||||
if self.has_space('roi'):
|
||||
spaces += self.custom_hyperopt.roi_space()
|
||||
if self.has_space('stoploss'):
|
||||
@@ -164,6 +171,13 @@ class Hyperopt(Backtesting):
|
||||
|
||||
if self.has_space('buy'):
|
||||
self.advise_buy = self.custom_hyperopt.buy_strategy_generator(params)
|
||||
elif hasattr(self.custom_hyperopt, 'populate_buy_trend'):
|
||||
self.advise_buy = self.custom_hyperopt.populate_buy_trend # type: ignore
|
||||
|
||||
if self.has_space('sell'):
|
||||
self.advise_sell = self.custom_hyperopt.sell_strategy_generator(params)
|
||||
elif hasattr(self.custom_hyperopt, 'populate_sell_trend'):
|
||||
self.advise_sell = self.custom_hyperopt.populate_sell_trend # type: ignore
|
||||
|
||||
if self.has_space('stoploss'):
|
||||
self.strategy.stoploss = params['stoploss']
|
||||
@@ -247,7 +261,7 @@ class Hyperopt(Backtesting):
|
||||
timerange=timerange
|
||||
)
|
||||
|
||||
if self.has_space('buy'):
|
||||
if self.has_space('buy') or self.has_space('sell'):
|
||||
self.strategy.advise_indicators = \
|
||||
self.custom_hyperopt.populate_indicators # type: ignore
|
||||
dump(self.strategy.tickerdata_to_dataframe(data), TICKERDATA_PICKLE)
|
||||
@@ -293,7 +307,7 @@ def start(args: Namespace) -> None:
|
||||
|
||||
# Initialize configuration
|
||||
# Monkey patch the configuration with hyperopt_conf.py
|
||||
configuration = Configuration(args)
|
||||
configuration = Configuration(args, RunMode.HYPEROPT)
|
||||
logger.info('Starting freqtrade in Hyperopt mode')
|
||||
config = configuration.load_config()
|
||||
|
||||
|
||||
@@ -37,6 +37,13 @@ class IHyperOpt(ABC):
|
||||
Create a buy strategy generator
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@abstractmethod
|
||||
def sell_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||
"""
|
||||
Create a sell strategy generator
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@abstractmethod
|
||||
def indicator_space() -> List[Dimension]:
|
||||
@@ -44,6 +51,13 @@ class IHyperOpt(ABC):
|
||||
Create an indicator space
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@abstractmethod
|
||||
def sell_indicator_space() -> List[Dimension]:
|
||||
"""
|
||||
Create a sell indicator space
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@abstractmethod
|
||||
def generate_roi_table(params: Dict) -> Dict[int, float]:
|
||||
|
||||
@@ -60,32 +60,27 @@ class IPairList(ABC):
|
||||
def _validate_whitelist(self, whitelist: List[str]) -> List[str]:
|
||||
"""
|
||||
Check available markets and remove pair from whitelist if necessary
|
||||
:param whitelist: the sorted list (based on BaseVolume) of pairs the user might want to
|
||||
trade
|
||||
:return: the list of pairs the user wants to trade without the one unavailable or
|
||||
:param whitelist: the sorted list of pairs the user might want to trade
|
||||
:return: the list of pairs the user wants to trade without those unavailable or
|
||||
black_listed
|
||||
"""
|
||||
sanitized_whitelist = whitelist
|
||||
markets = self._freqtrade.exchange.get_markets()
|
||||
markets = self._freqtrade.exchange.markets
|
||||
|
||||
# Filter to markets in stake currency
|
||||
markets = [m for m in markets if m['quote'] == self._config['stake_currency']]
|
||||
known_pairs = set()
|
||||
|
||||
for market in markets:
|
||||
pair = market['symbol']
|
||||
# pair is not int the generated dynamic market, or in the blacklist ... ignore it
|
||||
if pair not in whitelist or pair in self.blacklist:
|
||||
sanitized_whitelist = set()
|
||||
for pair in whitelist:
|
||||
# pair is not in the generated dynamic market, or in the blacklist ... ignore it
|
||||
if (pair in self.blacklist or pair not in markets
|
||||
or not pair.endswith(self._config['stake_currency'])):
|
||||
logger.warning(f"Pair {pair} is not compatible with exchange "
|
||||
f"{self._freqtrade.exchange.name} or contained in "
|
||||
f"your blacklist. Removing it from whitelist..")
|
||||
continue
|
||||
# else the pair is valid
|
||||
known_pairs.add(pair)
|
||||
# Market is not active
|
||||
# Check if market is active
|
||||
market = markets[pair]
|
||||
if not market['active']:
|
||||
sanitized_whitelist.remove(pair)
|
||||
logger.info(
|
||||
'Ignoring %s from whitelist. Market is not active.',
|
||||
pair
|
||||
)
|
||||
logger.info(f"Ignoring {pair} from whitelist. Market is not active.")
|
||||
continue
|
||||
sanitized_whitelist.add(pair)
|
||||
|
||||
# We need to remove pairs that are unknown
|
||||
return [x for x in sanitized_whitelist if x in known_pairs]
|
||||
return list(sanitized_whitelist)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
Static List provider
|
||||
Volume PairList provider
|
||||
|
||||
Provides lists as configured in config.json
|
||||
|
||||
@@ -26,6 +26,7 @@ class VolumePairList(IPairList):
|
||||
'for "pairlist.config.number_assets"')
|
||||
self._number_pairs = self._whitelistconf['number_assets']
|
||||
self._sort_key = self._whitelistconf.get('sort_key', 'quoteVolume')
|
||||
self._precision_filter = self._whitelistconf.get('precision_filter', False)
|
||||
|
||||
if not self._freqtrade.exchange.exchange_has('fetchTickers'):
|
||||
raise OperationalException(
|
||||
@@ -52,9 +53,9 @@ class VolumePairList(IPairList):
|
||||
-> Please overwrite in subclasses
|
||||
"""
|
||||
# Generate dynamic whitelist
|
||||
pairs = self._gen_pair_whitelist(self._config['stake_currency'], self._sort_key)
|
||||
# Validate whitelist to only have active market pairs
|
||||
self._whitelist = self._validate_whitelist(pairs)[:self._number_pairs]
|
||||
self._whitelist = self._gen_pair_whitelist(
|
||||
self._config['stake_currency'], self._sort_key)[:self._number_pairs]
|
||||
logger.info(f"Searching pairs: {self._whitelist}")
|
||||
|
||||
@cached(TTLCache(maxsize=1, ttl=1800))
|
||||
def _gen_pair_whitelist(self, base_currency: str, key: str) -> List[str]:
|
||||
@@ -68,8 +69,27 @@ class VolumePairList(IPairList):
|
||||
tickers = self._freqtrade.exchange.get_tickers()
|
||||
# check length so that we make sure that '/' is actually in the string
|
||||
tickers = [v for k, v in tickers.items()
|
||||
if len(k.split('/')) == 2 and k.split('/')[1] == base_currency]
|
||||
|
||||
if (len(k.split('/')) == 2 and k.split('/')[1] == base_currency
|
||||
and v[key] is not None)]
|
||||
sorted_tickers = sorted(tickers, reverse=True, key=lambda t: t[key])
|
||||
pairs = [s['symbol'] for s in sorted_tickers]
|
||||
# Validate whitelist to only have active market pairs
|
||||
valid_pairs = self._validate_whitelist([s['symbol'] for s in sorted_tickers])
|
||||
valid_tickers = [t for t in sorted_tickers if t["symbol"] in valid_pairs]
|
||||
|
||||
if self._freqtrade.strategy.stoploss is not None and self._precision_filter:
|
||||
|
||||
stop_prices = [self._freqtrade.get_target_bid(t["symbol"], t)
|
||||
* (1 - abs(self._freqtrade.strategy.stoploss)) for t in valid_tickers]
|
||||
rates = [sp * 0.99 for sp in stop_prices]
|
||||
logger.debug("\n".join([f"{sp} : {r}" for sp, r in zip(stop_prices[:10], rates[:10])]))
|
||||
for i, t in enumerate(valid_tickers):
|
||||
sp = self._freqtrade.exchange.symbol_price_prec(t["symbol"], stop_prices[i])
|
||||
r = self._freqtrade.exchange.symbol_price_prec(t["symbol"], rates[i])
|
||||
logger.debug(f"{t['symbol']} - {sp} : {r}")
|
||||
if sp <= r:
|
||||
logger.info(f"Removed {t['symbol']} from whitelist, "
|
||||
f"because stop price {sp} would be <= stop limit {r}")
|
||||
valid_tickers.remove(t)
|
||||
|
||||
pairs = [s['symbol'] for s in valid_tickers]
|
||||
return pairs
|
||||
|
||||
@@ -5,7 +5,7 @@ This module contains the class to persist trades into SQLite
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import arrow
|
||||
from sqlalchemy import (Boolean, Column, DateTime, Float, Integer, String,
|
||||
@@ -83,7 +83,7 @@ def check_migrate(engine) -> None:
|
||||
logger.debug(f'trying {table_back_name}')
|
||||
|
||||
# Check for latest column
|
||||
if not has_column(cols, 'stoploss_order_id'):
|
||||
if not has_column(cols, 'stop_loss_pct'):
|
||||
logger.info(f'Running database migration - backup available as {table_back_name}')
|
||||
|
||||
fee_open = get_column_def(cols, 'fee_open', 'fee')
|
||||
@@ -91,9 +91,13 @@ def check_migrate(engine) -> None:
|
||||
open_rate_requested = get_column_def(cols, 'open_rate_requested', 'null')
|
||||
close_rate_requested = get_column_def(cols, 'close_rate_requested', 'null')
|
||||
stop_loss = get_column_def(cols, 'stop_loss', '0.0')
|
||||
stop_loss_pct = get_column_def(cols, 'stop_loss_pct', 'null')
|
||||
initial_stop_loss = get_column_def(cols, 'initial_stop_loss', '0.0')
|
||||
initial_stop_loss_pct = get_column_def(cols, 'initial_stop_loss_pct', 'null')
|
||||
stoploss_order_id = get_column_def(cols, 'stoploss_order_id', 'null')
|
||||
stoploss_last_update = get_column_def(cols, 'stoploss_last_update', 'null')
|
||||
max_rate = get_column_def(cols, 'max_rate', '0.0')
|
||||
min_rate = get_column_def(cols, 'min_rate', 'null')
|
||||
sell_reason = get_column_def(cols, 'sell_reason', 'null')
|
||||
strategy = get_column_def(cols, 'strategy', 'null')
|
||||
ticker_interval = get_column_def(cols, 'ticker_interval', 'null')
|
||||
@@ -111,7 +115,9 @@ def check_migrate(engine) -> None:
|
||||
(id, exchange, pair, is_open, fee_open, fee_close, open_rate,
|
||||
open_rate_requested, close_rate, close_rate_requested, close_profit,
|
||||
stake_amount, amount, open_date, close_date, open_order_id,
|
||||
stop_loss, initial_stop_loss, stoploss_order_id, max_rate, sell_reason, strategy,
|
||||
stop_loss, stop_loss_pct, initial_stop_loss, initial_stop_loss_pct,
|
||||
stoploss_order_id, stoploss_last_update,
|
||||
max_rate, min_rate, sell_reason, strategy,
|
||||
ticker_interval
|
||||
)
|
||||
select id, lower(exchange),
|
||||
@@ -126,10 +132,12 @@ def check_migrate(engine) -> None:
|
||||
open_rate, {open_rate_requested} open_rate_requested, close_rate,
|
||||
{close_rate_requested} close_rate_requested, close_profit,
|
||||
stake_amount, amount, open_date, close_date, open_order_id,
|
||||
{stop_loss} stop_loss, {initial_stop_loss} initial_stop_loss,
|
||||
{stoploss_order_id} stoploss_order_id, {max_rate} max_rate,
|
||||
{sell_reason} sell_reason, {strategy} strategy,
|
||||
{ticker_interval} ticker_interval
|
||||
{stop_loss} stop_loss, {stop_loss_pct} stop_loss_pct,
|
||||
{initial_stop_loss} initial_stop_loss,
|
||||
{initial_stop_loss_pct} initial_stop_loss_pct,
|
||||
{stoploss_order_id} stoploss_order_id, {stoploss_last_update} stoploss_last_update,
|
||||
{max_rate} max_rate, {min_rate} min_rate, {sell_reason} sell_reason,
|
||||
{strategy} strategy, {ticker_interval} ticker_interval
|
||||
from {table_back_name}
|
||||
""")
|
||||
|
||||
@@ -181,12 +189,20 @@ class Trade(_DECL_BASE):
|
||||
open_order_id = Column(String)
|
||||
# absolute value of the stop loss
|
||||
stop_loss = Column(Float, nullable=True, default=0.0)
|
||||
# percentage value of the stop loss
|
||||
stop_loss_pct = Column(Float, nullable=True)
|
||||
# absolute value of the initial stop loss
|
||||
initial_stop_loss = Column(Float, nullable=True, default=0.0)
|
||||
# percentage value of the initial stop loss
|
||||
initial_stop_loss_pct = Column(Float, nullable=True)
|
||||
# stoploss order id which is on exchange
|
||||
stoploss_order_id = Column(String, nullable=True, index=True)
|
||||
# last update time of the stoploss order on exchange
|
||||
stoploss_last_update = Column(DateTime, nullable=True)
|
||||
# absolute value of the highest reached price
|
||||
max_rate = Column(Float, nullable=True, default=0.0)
|
||||
# Lowest price reached
|
||||
min_rate = Column(Float, nullable=True)
|
||||
sell_reason = Column(String, nullable=True)
|
||||
strategy = Column(String, nullable=True)
|
||||
ticker_interval = Column(Integer, nullable=True)
|
||||
@@ -197,8 +213,22 @@ class Trade(_DECL_BASE):
|
||||
return (f'Trade(id={self.id}, pair={self.pair}, amount={self.amount:.8f}, '
|
||||
f'open_rate={self.open_rate:.8f}, open_since={open_since})')
|
||||
|
||||
def adjust_min_max_rates(self, current_price: float):
|
||||
"""
|
||||
Adjust the max_rate and min_rate.
|
||||
"""
|
||||
logger.debug("Adjusting min/max rates")
|
||||
self.max_rate = max(current_price, self.max_rate or self.open_rate)
|
||||
self.min_rate = min(current_price, self.min_rate or self.open_rate)
|
||||
|
||||
def adjust_stop_loss(self, current_price: float, stoploss: float, initial: bool = False):
|
||||
"""this adjusts the stop loss to it's most recently observed setting"""
|
||||
"""
|
||||
This adjusts the stop loss to it's most recently observed setting
|
||||
:param current_price: Current rate the asset is traded
|
||||
:param stoploss: Stoploss as factor (sample -0.05 -> -5% below current price).
|
||||
:param initial: Called to initiate stop_loss.
|
||||
Skips everything if self.stop_loss is already set.
|
||||
"""
|
||||
|
||||
if initial and not (self.stop_loss is None or self.stop_loss == 0):
|
||||
# Don't modify if called with initial and nothing to do
|
||||
@@ -206,23 +236,21 @@ class Trade(_DECL_BASE):
|
||||
|
||||
new_loss = float(current_price * (1 - abs(stoploss)))
|
||||
|
||||
# keeping track of the highest observed rate for this trade
|
||||
if self.max_rate is None:
|
||||
self.max_rate = current_price
|
||||
else:
|
||||
if current_price > self.max_rate:
|
||||
self.max_rate = current_price
|
||||
|
||||
# no stop loss assigned yet
|
||||
if not self.stop_loss:
|
||||
logger.debug("assigning new stop loss")
|
||||
self.stop_loss = new_loss
|
||||
self.stop_loss_pct = -1 * abs(stoploss)
|
||||
self.initial_stop_loss = new_loss
|
||||
self.initial_stop_loss_pct = -1 * abs(stoploss)
|
||||
self.stoploss_last_update = datetime.utcnow()
|
||||
|
||||
# evaluate if the stop loss needs to be updated
|
||||
else:
|
||||
if new_loss > self.stop_loss: # stop losses only walk up, never down!
|
||||
self.stop_loss = new_loss
|
||||
self.stop_loss_pct = -1 * abs(stoploss)
|
||||
self.stoploss_last_update = datetime.utcnow()
|
||||
logger.debug("adjusted stop loss")
|
||||
else:
|
||||
logger.debug("keeping current stop loss")
|
||||
@@ -260,6 +288,7 @@ class Trade(_DECL_BASE):
|
||||
logger.info('%s_SELL has been fulfilled for %s.', order_type.upper(), self)
|
||||
elif order_type == 'stop_loss_limit':
|
||||
self.stoploss_order_id = None
|
||||
self.close_rate_requested = self.stop_loss
|
||||
logger.info('STOP_LOSS_LIMIT is hit for %s.', self)
|
||||
self.close(order['average'])
|
||||
else:
|
||||
@@ -365,3 +394,10 @@ class Trade(_DECL_BASE):
|
||||
.filter(Trade.is_open.is_(True))\
|
||||
.scalar()
|
||||
return total_open_stake_amount or 0
|
||||
|
||||
@staticmethod
|
||||
def get_open_trades() -> List[Any]:
|
||||
"""
|
||||
Query trades from persistence layer
|
||||
"""
|
||||
return Trade.query.filter(Trade.is_open.is_(True)).all()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from freqtrade.resolvers.iresolver import IResolver # noqa: F401
|
||||
from freqtrade.resolvers.exchange_resolver import ExchangeResolver # noqa: F401
|
||||
from freqtrade.resolvers.hyperopt_resolver import HyperOptResolver # noqa: F401
|
||||
from freqtrade.resolvers.pairlist_resolver import PairListResolver # noqa: F401
|
||||
from freqtrade.resolvers.strategy_resolver import StrategyResolver # noqa: F401
|
||||
|
||||
55
freqtrade/resolvers/exchange_resolver.py
Normal file
55
freqtrade/resolvers/exchange_resolver.py
Normal file
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
This module loads custom exchanges
|
||||
"""
|
||||
import logging
|
||||
|
||||
from freqtrade.exchange import Exchange
|
||||
import freqtrade.exchange as exchanges
|
||||
from freqtrade.resolvers import IResolver
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ExchangeResolver(IResolver):
|
||||
"""
|
||||
This class contains all the logic to load a custom exchange class
|
||||
"""
|
||||
|
||||
__slots__ = ['exchange']
|
||||
|
||||
def __init__(self, exchange_name: str, config: dict) -> None:
|
||||
"""
|
||||
Load the custom class from config parameter
|
||||
:param config: configuration dictionary
|
||||
"""
|
||||
try:
|
||||
self.exchange = self._load_exchange(exchange_name, kwargs={'config': config})
|
||||
except ImportError:
|
||||
logger.info(
|
||||
f"No {exchange_name} specific subclass found. Using the generic class instead.")
|
||||
self.exchange = Exchange(config)
|
||||
|
||||
def _load_exchange(
|
||||
self, exchange_name: str, kwargs: dict) -> Exchange:
|
||||
"""
|
||||
Loads the specified exchange.
|
||||
Only checks for exchanges exported in freqtrade.exchanges
|
||||
:param exchange_name: name of the module to import
|
||||
:return: Exchange instance or None
|
||||
"""
|
||||
|
||||
try:
|
||||
ex_class = getattr(exchanges, exchange_name)
|
||||
|
||||
exchange = ex_class(kwargs['config'])
|
||||
if exchange:
|
||||
logger.info("Using resolved exchange %s", exchange_name)
|
||||
return exchange
|
||||
except AttributeError:
|
||||
# Pass and raise ImportError instead
|
||||
pass
|
||||
|
||||
raise ImportError(
|
||||
"Impossible to load Exchange '{}'. This class does not exist"
|
||||
" or contains Python code errors".format(exchange_name)
|
||||
)
|
||||
@@ -32,6 +32,13 @@ class HyperOptResolver(IResolver):
|
||||
hyperopt_name = config.get('hyperopt') or DEFAULT_HYPEROPT
|
||||
self.hyperopt = self._load_hyperopt(hyperopt_name, extra_dir=config.get('hyperopt_path'))
|
||||
|
||||
if not hasattr(self.hyperopt, 'populate_buy_trend'):
|
||||
logger.warning("Custom Hyperopt does not provide populate_buy_trend. "
|
||||
"Using populate_buy_trend from DefaultStrategy.")
|
||||
if not hasattr(self.hyperopt, 'populate_sell_trend'):
|
||||
logger.warning("Custom Hyperopt does not provide populate_sell_trend. "
|
||||
"Using populate_sell_trend from DefaultStrategy.")
|
||||
|
||||
def _load_hyperopt(
|
||||
self, hyperopt_name: str, extra_dir: Optional[str] = None) -> IHyperOpt:
|
||||
"""
|
||||
@@ -56,7 +63,7 @@ class HyperOptResolver(IResolver):
|
||||
hyperopt = self._search_object(directory=_path, object_type=IHyperOpt,
|
||||
object_name=hyperopt_name)
|
||||
if hyperopt:
|
||||
logger.info('Using resolved hyperopt %s from \'%s\'', hyperopt_name, _path)
|
||||
logger.info("Using resolved hyperopt %s from '%s'", hyperopt_name, _path)
|
||||
return hyperopt
|
||||
except FileNotFoundError:
|
||||
logger.warning('Path "%s" does not exist', _path.relative_to(Path.cwd()))
|
||||
|
||||
@@ -31,7 +31,11 @@ class IResolver(object):
|
||||
# Generate spec based on absolute path
|
||||
spec = importlib.util.spec_from_file_location('unknown', str(module_path))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module) # type: ignore # importlib does not use typehints
|
||||
try:
|
||||
spec.loader.exec_module(module) # type: ignore # importlib does not use typehints
|
||||
except (ModuleNotFoundError, SyntaxError) as err:
|
||||
# Catch errors in case a specific module is not installed
|
||||
logger.warning(f"Could not import {module_path} due to '{err}'")
|
||||
|
||||
valid_objects_gen = (
|
||||
obj for name, obj in inspect.getmembers(module, inspect.isclass)
|
||||
@@ -47,7 +51,7 @@ class IResolver(object):
|
||||
:param directory: relative or absolute directory path
|
||||
:return: object instance
|
||||
"""
|
||||
logger.debug('Searching for %s %s in \'%s\'', object_type.__name__, object_name, directory)
|
||||
logger.debug("Searching for %s %s in '%s'", object_type.__name__, object_name, directory)
|
||||
for entry in directory.iterdir():
|
||||
# Only consider python files
|
||||
if not str(entry).endswith('.py'):
|
||||
|
||||
@@ -48,7 +48,7 @@ class PairListResolver(IResolver):
|
||||
object_name=pairlist_name,
|
||||
kwargs=kwargs)
|
||||
if pairlist:
|
||||
logger.info('Using resolved pairlist %s from \'%s\'', pairlist_name, _path)
|
||||
logger.info("Using resolved pairlist %s from '%s'", pairlist_name, _path)
|
||||
return pairlist
|
||||
except FileNotFoundError:
|
||||
logger.warning('Path "%s" does not exist', _path.relative_to(Path.cwd()))
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
"""
|
||||
This module load custom strategies
|
||||
"""
|
||||
import inspect
|
||||
import logging
|
||||
import tempfile
|
||||
from base64 import urlsafe_b64decode
|
||||
from collections import OrderedDict
|
||||
from inspect import getfullargspec
|
||||
from pathlib import Path
|
||||
from typing import Dict, Optional
|
||||
|
||||
@@ -39,59 +39,70 @@ class StrategyResolver(IResolver):
|
||||
config=config,
|
||||
extra_dir=config.get('strategy_path'))
|
||||
|
||||
# make sure experimental dict is available
|
||||
if 'experimental' not in config:
|
||||
config['experimental'] = {}
|
||||
|
||||
# Set attributes
|
||||
# Check if we need to override configuration
|
||||
if 'minimal_roi' in config:
|
||||
self.strategy.minimal_roi = config['minimal_roi']
|
||||
logger.info("Override strategy 'minimal_roi' with value in config file: %s.",
|
||||
config['minimal_roi'])
|
||||
else:
|
||||
config['minimal_roi'] = self.strategy.minimal_roi
|
||||
# (Attribute name, default, experimental)
|
||||
attributes = [("minimal_roi", {"0": 10.0}, False),
|
||||
("ticker_interval", None, False),
|
||||
("stoploss", None, False),
|
||||
("trailing_stop", None, False),
|
||||
("trailing_stop_positive", None, False),
|
||||
("trailing_stop_positive_offset", 0.0, False),
|
||||
("trailing_only_offset_is_reached", None, False),
|
||||
("process_only_new_candles", None, False),
|
||||
("order_types", None, False),
|
||||
("order_time_in_force", None, False),
|
||||
("stake_currency", None, False),
|
||||
("stake_amount", None, False),
|
||||
("use_sell_signal", False, True),
|
||||
("sell_profit_only", False, True),
|
||||
("ignore_roi_if_buy_signal", False, True),
|
||||
]
|
||||
for attribute, default, experimental in attributes:
|
||||
if experimental:
|
||||
self._override_attribute_helper(config['experimental'], attribute, default)
|
||||
else:
|
||||
self._override_attribute_helper(config, attribute, default)
|
||||
|
||||
if 'stoploss' in config:
|
||||
self.strategy.stoploss = config['stoploss']
|
||||
logger.info(
|
||||
"Override strategy 'stoploss' with value in config file: %s.", config['stoploss']
|
||||
)
|
||||
else:
|
||||
config['stoploss'] = self.strategy.stoploss
|
||||
# Loop this list again to have output combined
|
||||
for attribute, _, exp in attributes:
|
||||
if exp and attribute in config['experimental']:
|
||||
logger.info("Strategy using %s: %s", attribute, config['experimental'][attribute])
|
||||
elif attribute in config:
|
||||
logger.info("Strategy using %s: %s", attribute, config[attribute])
|
||||
|
||||
if 'ticker_interval' in config:
|
||||
self.strategy.ticker_interval = config['ticker_interval']
|
||||
logger.info(
|
||||
"Override strategy 'ticker_interval' with value in config file: %s.",
|
||||
config['ticker_interval']
|
||||
)
|
||||
else:
|
||||
config['ticker_interval'] = self.strategy.ticker_interval
|
||||
# Sort and apply type conversions
|
||||
self.strategy.minimal_roi = OrderedDict(sorted(
|
||||
{int(key): value for (key, value) in self.strategy.minimal_roi.items()}.items(),
|
||||
key=lambda t: t[0]))
|
||||
self.strategy.stoploss = float(self.strategy.stoploss)
|
||||
|
||||
if 'process_only_new_candles' in config:
|
||||
self.strategy.process_only_new_candles = config['process_only_new_candles']
|
||||
logger.info(
|
||||
"Override process_only_new_candles 'process_only_new_candles' "
|
||||
"with value in config file: %s.", config['process_only_new_candles']
|
||||
)
|
||||
else:
|
||||
config['process_only_new_candles'] = self.strategy.process_only_new_candles
|
||||
self._strategy_sanity_validations()
|
||||
|
||||
if 'order_types' in config:
|
||||
self.strategy.order_types = config['order_types']
|
||||
logger.info(
|
||||
"Override strategy 'order_types' with value in config file: %s.",
|
||||
config['order_types']
|
||||
)
|
||||
else:
|
||||
config['order_types'] = self.strategy.order_types
|
||||
|
||||
if 'order_time_in_force' in config:
|
||||
self.strategy.order_time_in_force = config['order_time_in_force']
|
||||
logger.info(
|
||||
"Override strategy 'order_time_in_force' with value in config file: %s.",
|
||||
config['order_time_in_force']
|
||||
)
|
||||
else:
|
||||
config['order_time_in_force'] = self.strategy.order_time_in_force
|
||||
def _override_attribute_helper(self, config, attribute: str, default):
|
||||
"""
|
||||
Override attributes in the strategy.
|
||||
Prevalence:
|
||||
- Configuration
|
||||
- Strategy
|
||||
- default (if not None)
|
||||
"""
|
||||
if attribute in config:
|
||||
setattr(self.strategy, attribute, config[attribute])
|
||||
logger.info("Override strategy '%s' with value in config file: %s.",
|
||||
attribute, config[attribute])
|
||||
elif hasattr(self.strategy, attribute):
|
||||
config[attribute] = getattr(self.strategy, attribute)
|
||||
# Explicitly check for None here as other "falsy" values are possible
|
||||
elif default is not None:
|
||||
setattr(self.strategy, attribute, default)
|
||||
config[attribute] = default
|
||||
|
||||
def _strategy_sanity_validations(self):
|
||||
if not all(k in self.strategy.order_types for k in constants.REQUIRED_ORDERTYPES):
|
||||
raise ImportError(f"Impossible to load Strategy '{self.strategy.__class__.__name__}'. "
|
||||
f"Order-types mapping is incomplete.")
|
||||
@@ -100,12 +111,6 @@ class StrategyResolver(IResolver):
|
||||
raise ImportError(f"Impossible to load Strategy '{self.strategy.__class__.__name__}'. "
|
||||
f"Order-time-in-force mapping is incomplete.")
|
||||
|
||||
# Sort and apply type conversions
|
||||
self.strategy.minimal_roi = OrderedDict(sorted(
|
||||
{int(key): value for (key, value) in self.strategy.minimal_roi.items()}.items(),
|
||||
key=lambda t: t[0]))
|
||||
self.strategy.stoploss = float(self.strategy.stoploss)
|
||||
|
||||
def _load_strategy(
|
||||
self, strategy_name: str, config: dict, extra_dir: Optional[str] = None) -> IStrategy:
|
||||
"""
|
||||
@@ -147,19 +152,20 @@ class StrategyResolver(IResolver):
|
||||
strategy = self._search_object(directory=_path, object_type=IStrategy,
|
||||
object_name=strategy_name, kwargs={'config': config})
|
||||
if strategy:
|
||||
logger.info('Using resolved strategy %s from \'%s\'', strategy_name, _path)
|
||||
logger.info("Using resolved strategy %s from '%s'", strategy_name, _path)
|
||||
strategy._populate_fun_len = len(
|
||||
inspect.getfullargspec(strategy.populate_indicators).args)
|
||||
strategy._buy_fun_len = len(
|
||||
inspect.getfullargspec(strategy.populate_buy_trend).args)
|
||||
strategy._sell_fun_len = len(
|
||||
inspect.getfullargspec(strategy.populate_sell_trend).args)
|
||||
|
||||
return import_strategy(strategy, config=config)
|
||||
getfullargspec(strategy.populate_indicators).args)
|
||||
strategy._buy_fun_len = len(getfullargspec(strategy.populate_buy_trend).args)
|
||||
strategy._sell_fun_len = len(getfullargspec(strategy.populate_sell_trend).args)
|
||||
try:
|
||||
return import_strategy(strategy, config=config)
|
||||
except TypeError as e:
|
||||
logger.warning(
|
||||
f"Impossible to load strategy '{strategy}' from {_path}. Error: {e}")
|
||||
except FileNotFoundError:
|
||||
logger.warning('Path "%s" does not exist', _path.relative_to(Path.cwd()))
|
||||
|
||||
raise ImportError(
|
||||
"Impossible to load Strategy '{}'. This class does not exist"
|
||||
" or contains Python code errors".format(strategy_name)
|
||||
f"Impossible to load Strategy '{strategy_name}'. This class does not exist"
|
||||
" or contains Python code errors"
|
||||
)
|
||||
|
||||
@@ -83,7 +83,7 @@ class RPC(object):
|
||||
a remotely exposed function
|
||||
"""
|
||||
# Fetch open trade
|
||||
trades = Trade.query.filter(Trade.is_open.is_(True)).all()
|
||||
trades = Trade.get_open_trades()
|
||||
if not trades:
|
||||
raise RPCException('no active trade')
|
||||
else:
|
||||
@@ -94,7 +94,7 @@ class RPC(object):
|
||||
order = self._freqtrade.exchange.get_order(trade.open_order_id, trade.pair)
|
||||
# calculate profit and send message to user
|
||||
try:
|
||||
current_rate = self._freqtrade.exchange.get_ticker(trade.pair, False)['bid']
|
||||
current_rate = self._freqtrade.get_sell_rate(trade.pair, False)
|
||||
except DependencyException:
|
||||
current_rate = NAN
|
||||
current_profit = trade.calc_profit_percent(current_rate)
|
||||
@@ -103,22 +103,29 @@ class RPC(object):
|
||||
results.append(dict(
|
||||
trade_id=trade.id,
|
||||
pair=trade.pair,
|
||||
market_url=self._freqtrade.exchange.get_pair_detail_url(trade.pair),
|
||||
base_currency=self._freqtrade.config['stake_currency'],
|
||||
date=arrow.get(trade.open_date),
|
||||
open_rate=trade.open_rate,
|
||||
close_rate=trade.close_rate,
|
||||
current_rate=current_rate,
|
||||
amount=round(trade.amount, 8),
|
||||
stake_amount=round(trade.stake_amount, 8),
|
||||
close_profit=fmt_close_profit,
|
||||
current_profit=round(current_profit * 100, 2),
|
||||
stop_loss=trade.stop_loss,
|
||||
stop_loss_pct=(trade.stop_loss_pct * 100)
|
||||
if trade.stop_loss_pct else None,
|
||||
initial_stop_loss=trade.initial_stop_loss,
|
||||
initial_stop_loss_pct=(trade.initial_stop_loss_pct * 100)
|
||||
if trade.initial_stop_loss_pct else None,
|
||||
open_order='({} {} rem={:.8f})'.format(
|
||||
order['type'], order['side'], order['remaining']
|
||||
order['type'], order['side'], order['remaining']
|
||||
) if order else None,
|
||||
))
|
||||
return results
|
||||
|
||||
def _rpc_status_table(self) -> DataFrame:
|
||||
trades = Trade.query.filter(Trade.is_open.is_(True)).all()
|
||||
trades = Trade.get_open_trades()
|
||||
if not trades:
|
||||
raise RPCException('no active order')
|
||||
else:
|
||||
@@ -126,7 +133,7 @@ class RPC(object):
|
||||
for trade in trades:
|
||||
# calculate profit and send message to user
|
||||
try:
|
||||
current_rate = self._freqtrade.exchange.get_ticker(trade.pair, False)['bid']
|
||||
current_rate = self._freqtrade.get_sell_rate(trade.pair, False)
|
||||
except DependencyException:
|
||||
current_rate = NAN
|
||||
trade_perc = (100 * trade.calc_profit_percent(current_rate))
|
||||
@@ -214,7 +221,7 @@ class RPC(object):
|
||||
else:
|
||||
# Get current rate
|
||||
try:
|
||||
current_rate = self._freqtrade.exchange.get_ticker(trade.pair, False)['bid']
|
||||
current_rate = self._freqtrade.get_sell_rate(trade.pair, False)
|
||||
except DependencyException:
|
||||
current_rate = NAN
|
||||
profit_percent = trade.calc_profit_percent(rate=current_rate)
|
||||
@@ -281,9 +288,9 @@ class RPC(object):
|
||||
else:
|
||||
try:
|
||||
if coin == 'USDT':
|
||||
rate = 1.0 / self._freqtrade.exchange.get_ticker('BTC/USDT', False)['bid']
|
||||
rate = 1.0 / self._freqtrade.get_sell_rate('BTC/USDT', False)
|
||||
else:
|
||||
rate = self._freqtrade.exchange.get_ticker(coin + '/BTC', False)['bid']
|
||||
rate = self._freqtrade.get_sell_rate(coin + '/BTC', False)
|
||||
except (TemporaryError, DependencyException):
|
||||
continue
|
||||
est_btc: float = rate * balance['total']
|
||||
@@ -329,6 +336,16 @@ class RPC(object):
|
||||
self._freqtrade.state = State.RELOAD_CONF
|
||||
return {'status': 'reloading config ...'}
|
||||
|
||||
def _rpc_stopbuy(self) -> Dict[str, str]:
|
||||
"""
|
||||
Handler to stop buying, but handle open trades gracefully.
|
||||
"""
|
||||
if self._freqtrade.state == State.RUNNING:
|
||||
# Set 'max_open_trades' to 0
|
||||
self._freqtrade.config['max_open_trades'] = 0
|
||||
|
||||
return {'status': 'No more buy will occur from now. Run /reload_conf to reset.'}
|
||||
|
||||
def _rpc_forcesell(self, trade_id) -> None:
|
||||
"""
|
||||
Handler for forcesell <id>.
|
||||
@@ -357,7 +374,7 @@ class RPC(object):
|
||||
return
|
||||
|
||||
# Get current rate and execute sell
|
||||
current_rate = self._freqtrade.exchange.get_ticker(trade.pair, False)['bid']
|
||||
current_rate = self._freqtrade.get_sell_rate(trade.pair, False)
|
||||
self._freqtrade.execute_sell(trade, current_rate, SellType.FORCE_SELL)
|
||||
# ---- EOF def _exec_forcesell ----
|
||||
|
||||
@@ -366,7 +383,7 @@ class RPC(object):
|
||||
|
||||
if trade_id == 'all':
|
||||
# Execute sell for all open orders
|
||||
for trade in Trade.query.filter(Trade.is_open.is_(True)).all():
|
||||
for trade in Trade.get_open_trades():
|
||||
_exec_forcesell(trade)
|
||||
Trade.session.flush()
|
||||
return
|
||||
@@ -437,17 +454,43 @@ class RPC(object):
|
||||
for pair, rate, count in pair_rates
|
||||
]
|
||||
|
||||
def _rpc_count(self) -> List[Trade]:
|
||||
def _rpc_count(self) -> Dict[str, float]:
|
||||
""" Returns the number of trades running """
|
||||
if self._freqtrade.state != State.RUNNING:
|
||||
raise RPCException('trader is not running')
|
||||
|
||||
return Trade.query.filter(Trade.is_open.is_(True)).all()
|
||||
trades = Trade.get_open_trades()
|
||||
return {
|
||||
'current': len(trades),
|
||||
'max': float(self._freqtrade.config['max_open_trades']),
|
||||
'total_stake': sum((trade.open_rate * trade.amount) for trade in trades)
|
||||
}
|
||||
|
||||
def _rpc_whitelist(self) -> Dict:
|
||||
""" Returns the currently active whitelist"""
|
||||
res = {'method': self._freqtrade.pairlists.name,
|
||||
'length': len(self._freqtrade.pairlists.whitelist),
|
||||
'length': len(self._freqtrade.active_pair_whitelist),
|
||||
'whitelist': self._freqtrade.active_pair_whitelist
|
||||
}
|
||||
return res
|
||||
|
||||
def _rpc_blacklist(self, add: List[str]) -> Dict:
|
||||
""" Returns the currently active blacklist"""
|
||||
if add:
|
||||
stake_currency = self._freqtrade.config.get('stake_currency')
|
||||
for pair in add:
|
||||
if (pair.endswith(stake_currency)
|
||||
and pair not in self._freqtrade.pairlists.blacklist):
|
||||
self._freqtrade.pairlists.blacklist.append(pair)
|
||||
|
||||
res = {'method': self._freqtrade.pairlists.name,
|
||||
'length': len(self._freqtrade.pairlists.blacklist),
|
||||
'blacklist': self._freqtrade.pairlists.blacklist,
|
||||
}
|
||||
return res
|
||||
|
||||
def _rpc_edge(self) -> List[Dict[str, Any]]:
|
||||
""" Returns information related to Edge """
|
||||
if not self._freqtrade.edge:
|
||||
raise RPCException(f'Edge is not enabled.')
|
||||
return self._freqtrade.edge.accepted_pairs()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
This module contains class to manage RPC communications (Telegram, Slack, ...)
|
||||
"""
|
||||
import logging
|
||||
from typing import List, Dict, Any
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from freqtrade.rpc import RPC, RPCMessageType
|
||||
|
||||
@@ -61,6 +61,8 @@ class RPCManager(object):
|
||||
stake_currency = config['stake_currency']
|
||||
stake_amount = config['stake_amount']
|
||||
minimal_roi = config['minimal_roi']
|
||||
stoploss = config['stoploss']
|
||||
trailing_stop = config['trailing_stop']
|
||||
ticker_interval = config['ticker_interval']
|
||||
exchange_name = config['exchange']['name']
|
||||
strategy_name = config.get('strategy', '')
|
||||
@@ -69,6 +71,7 @@ class RPCManager(object):
|
||||
'status': f'*Exchange:* `{exchange_name}`\n'
|
||||
f'*Stake per trade:* `{stake_amount} {stake_currency}`\n'
|
||||
f'*Minimum ROI:* `{minimal_roi}`\n'
|
||||
f'*{"Trailing " if trailing_stop else ""}Stoploss:* `{stoploss}`\n'
|
||||
f'*Ticker Interval:* `{ticker_interval}`\n'
|
||||
f'*Strategy:* `{strategy_name}`'
|
||||
})
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
This module manage Telegram communication
|
||||
"""
|
||||
import logging
|
||||
from typing import Any, Callable, Dict
|
||||
from typing import Any, Callable, Dict, List
|
||||
|
||||
from tabulate import tabulate
|
||||
from telegram import Bot, ParseMode, ReplyKeyboardMarkup, Update
|
||||
@@ -20,7 +20,10 @@ logger = logging.getLogger(__name__)
|
||||
logger.debug('Included module rpc.telegram ...')
|
||||
|
||||
|
||||
def authorized_only(command_handler: Callable[[Any, Bot, Update], None]) -> Callable[..., Any]:
|
||||
MAX_TELEGRAM_MESSAGE_LENGTH = 4096
|
||||
|
||||
|
||||
def authorized_only(command_handler: Callable[..., None]) -> Callable[..., Any]:
|
||||
"""
|
||||
Decorator to check if the message comes from the correct chat_id
|
||||
:param command_handler: Telegram CommandHandler
|
||||
@@ -91,7 +94,10 @@ class Telegram(RPC):
|
||||
CommandHandler('daily', self._daily),
|
||||
CommandHandler('count', self._count),
|
||||
CommandHandler('reload_conf', self._reload_conf),
|
||||
CommandHandler('stopbuy', self._stopbuy),
|
||||
CommandHandler('whitelist', self._whitelist),
|
||||
CommandHandler('blacklist', self._blacklist, pass_args=True),
|
||||
CommandHandler('edge', self._edge),
|
||||
CommandHandler('help', self._help),
|
||||
CommandHandler('version', self._version),
|
||||
]
|
||||
@@ -125,7 +131,7 @@ class Telegram(RPC):
|
||||
else:
|
||||
msg['stake_amount_fiat'] = 0
|
||||
|
||||
message = ("*{exchange}:* Buying [{pair}]({market_url})\n"
|
||||
message = ("*{exchange}:* Buying {pair}\n"
|
||||
"with limit `{limit:.8f}\n"
|
||||
"({stake_amount:.6f} {stake_currency}").format(**msg)
|
||||
|
||||
@@ -137,7 +143,7 @@ class Telegram(RPC):
|
||||
msg['amount'] = round(msg['amount'], 8)
|
||||
msg['profit_percent'] = round(msg['profit_percent'] * 100, 2)
|
||||
|
||||
message = ("*{exchange}:* Selling [{pair}]({market_url})\n"
|
||||
message = ("*{exchange}:* Selling {pair}\n"
|
||||
"*Limit:* `{limit:.8f}`\n"
|
||||
"*Amount:* `{amount:.8f}`\n"
|
||||
"*Open Rate:* `{open_rate:.8f}`\n"
|
||||
@@ -191,21 +197,34 @@ class Telegram(RPC):
|
||||
for result in results:
|
||||
result['date'] = result['date'].humanize()
|
||||
|
||||
messages = [
|
||||
"*Trade ID:* `{trade_id}`\n"
|
||||
"*Current Pair:* [{pair}]({market_url})\n"
|
||||
"*Open Since:* `{date}`\n"
|
||||
"*Amount:* `{amount}`\n"
|
||||
"*Open Rate:* `{open_rate:.8f}`\n"
|
||||
"*Close Rate:* `{close_rate}`\n"
|
||||
"*Current Rate:* `{current_rate:.8f}`\n"
|
||||
"*Close Profit:* `{close_profit}`\n"
|
||||
"*Current Profit:* `{current_profit:.2f}%`\n"
|
||||
"*Open Order:* `{open_order}`".format(**result)
|
||||
for result in results
|
||||
]
|
||||
messages = []
|
||||
for r in results:
|
||||
lines = [
|
||||
"*Trade ID:* `{trade_id}` `(since {date})`",
|
||||
"*Current Pair:* {pair}",
|
||||
"*Amount:* `{amount} ({stake_amount} {base_currency})`",
|
||||
"*Open Rate:* `{open_rate:.8f}`",
|
||||
"*Close Rate:* `{close_rate}`" if r['close_rate'] else "",
|
||||
"*Current Rate:* `{current_rate:.8f}`",
|
||||
"*Close Profit:* `{close_profit}`" if r['close_profit'] else "",
|
||||
"*Current Profit:* `{current_profit:.2f}%`",
|
||||
|
||||
# Adding initial stoploss only if it is different from stoploss
|
||||
"*Initial Stoploss:* `{initial_stop_loss:.8f}` " +
|
||||
("`({initial_stop_loss_pct:.2f}%)`" if r['initial_stop_loss_pct'] else "")
|
||||
if r['stop_loss'] != r['initial_stop_loss'] else "",
|
||||
|
||||
# Adding stoploss and stoploss percentage only if it is not None
|
||||
"*Stoploss:* `{stop_loss:.8f}` " +
|
||||
("`({stop_loss_pct:.2f}%)`" if r['stop_loss_pct'] else ""),
|
||||
|
||||
"*Open Order:* `{open_order}`" if r['open_order'] else ""
|
||||
]
|
||||
messages.append("\n".join(filter(None, lines)).format(**r))
|
||||
|
||||
for msg in messages:
|
||||
self._send_msg(msg, bot=bot)
|
||||
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
@@ -246,14 +265,15 @@ class Telegram(RPC):
|
||||
stake_cur,
|
||||
fiat_disp_cur
|
||||
)
|
||||
stats = tabulate(stats,
|
||||
headers=[
|
||||
'Day',
|
||||
f'Profit {stake_cur}',
|
||||
f'Profit {fiat_disp_cur}'
|
||||
],
|
||||
tablefmt='simple')
|
||||
message = f'<b>Daily Profit over the last {timescale} days</b>:\n<pre>{stats}</pre>'
|
||||
stats_tab = tabulate(stats,
|
||||
headers=[
|
||||
'Day',
|
||||
f'Profit {stake_cur}',
|
||||
f'Profit {fiat_disp_cur}',
|
||||
f'Trades'
|
||||
],
|
||||
tablefmt='simple')
|
||||
message = f'<b>Daily Profit over the last {timescale} days</b>:\n<pre>{stats_tab}</pre>'
|
||||
self._send_msg(message, bot=bot, parse_mode=ParseMode.HTML)
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
@@ -311,13 +331,20 @@ class Telegram(RPC):
|
||||
output = ''
|
||||
for currency in result['currencies']:
|
||||
if currency['est_btc'] > 0.0001:
|
||||
output += "*{currency}:*\n" \
|
||||
curr_output = "*{currency}:*\n" \
|
||||
"\t`Available: {available: .8f}`\n" \
|
||||
"\t`Balance: {balance: .8f}`\n" \
|
||||
"\t`Pending: {pending: .8f}`\n" \
|
||||
"\t`Est. BTC: {est_btc: .8f}`\n".format(**currency)
|
||||
else:
|
||||
output += "*{currency}:* not showing <1$ amount \n".format(**currency)
|
||||
curr_output = "*{currency}:* not showing <1$ amount \n".format(**currency)
|
||||
|
||||
# Handle overflowing messsage length
|
||||
if len(output + curr_output) >= MAX_TELEGRAM_MESSAGE_LENGTH:
|
||||
self._send_msg(output, bot=bot)
|
||||
output = curr_output
|
||||
else:
|
||||
output += curr_output
|
||||
|
||||
output += "\n*Estimated Value*:\n" \
|
||||
"\t`BTC: {total: .8f}`\n" \
|
||||
@@ -362,6 +389,18 @@ class Telegram(RPC):
|
||||
msg = self._rpc_reload_conf()
|
||||
self._send_msg('Status: `{status}`'.format(**msg), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _stopbuy(self, bot: Bot, update: Update) -> None:
|
||||
"""
|
||||
Handler for /stop_buy.
|
||||
Sets max_open_trades to 0 and gracefully sells all open trades
|
||||
:param bot: telegram bot
|
||||
:param update: message update
|
||||
:return: None
|
||||
"""
|
||||
msg = self._rpc_stopbuy()
|
||||
self._send_msg('Status: `{status}`'.format(**msg), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _forcesell(self, bot: Bot, update: Update) -> None:
|
||||
"""
|
||||
@@ -428,12 +467,10 @@ class Telegram(RPC):
|
||||
:return: None
|
||||
"""
|
||||
try:
|
||||
trades = self._rpc_count()
|
||||
message = tabulate({
|
||||
'current': [len(trades)],
|
||||
'max': [self._config['max_open_trades']],
|
||||
'total stake': [sum((trade.open_rate * trade.amount) for trade in trades)]
|
||||
}, headers=['current', 'max', 'total stake'], tablefmt='simple')
|
||||
counts = self._rpc_count()
|
||||
message = tabulate({k: [v] for k, v in counts.items()},
|
||||
headers=['current', 'max', 'total stake'],
|
||||
tablefmt='simple')
|
||||
message = "<pre>{}</pre>".format(message)
|
||||
logger.debug(message)
|
||||
self._send_msg(message, parse_mode=ParseMode.HTML)
|
||||
@@ -457,6 +494,38 @@ class Telegram(RPC):
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _blacklist(self, bot: Bot, update: Update, args: List[str]) -> None:
|
||||
"""
|
||||
Handler for /blacklist
|
||||
Shows the currently active blacklist
|
||||
"""
|
||||
try:
|
||||
|
||||
blacklist = self._rpc_blacklist(args)
|
||||
|
||||
message = f"Blacklist contains {blacklist['length']} pairs\n"
|
||||
message += f"`{', '.join(blacklist['blacklist'])}`"
|
||||
|
||||
logger.debug(message)
|
||||
self._send_msg(message)
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _edge(self, bot: Bot, update: Update) -> None:
|
||||
"""
|
||||
Handler for /edge
|
||||
Shows information related to Edge
|
||||
"""
|
||||
try:
|
||||
edge_pairs = self._rpc_edge()
|
||||
edge_pairs_tab = tabulate(edge_pairs, headers='keys', tablefmt='simple')
|
||||
message = f'<b>Edge only validated following pairs:</b>\n<pre>{edge_pairs_tab}</pre>'
|
||||
self._send_msg(message, bot=bot, parse_mode=ParseMode.HTML)
|
||||
except RPCException as e:
|
||||
self._send_msg(str(e), bot=bot)
|
||||
|
||||
@authorized_only
|
||||
def _help(self, bot: Bot, update: Update) -> None:
|
||||
"""
|
||||
@@ -466,6 +535,8 @@ class Telegram(RPC):
|
||||
:param update: message update
|
||||
:return: None
|
||||
"""
|
||||
forcebuy_text = "*/forcebuy <pair> [<rate>]:* `Instantly buys the given pair. " \
|
||||
"Optionally takes a rate at which to buy.` \n"
|
||||
message = "*/start:* `Starts the trader`\n" \
|
||||
"*/stop:* `Stops the trader`\n" \
|
||||
"*/status [table]:* `Lists all open trades`\n" \
|
||||
@@ -473,13 +544,18 @@ class Telegram(RPC):
|
||||
"*/profit:* `Lists cumulative profit from all finished trades`\n" \
|
||||
"*/forcesell <trade_id>|all:* `Instantly sells the given trade or all trades, " \
|
||||
"regardless of profit`\n" \
|
||||
f"{forcebuy_text if self._config.get('forcebuy_enable', False) else '' }" \
|
||||
"*/performance:* `Show performance of each finished trade grouped by pair`\n" \
|
||||
"*/daily <n>:* `Shows profit or loss per day, over the last n days`\n" \
|
||||
"*/count:* `Show number of trades running compared to allowed number of trades`" \
|
||||
"\n" \
|
||||
"*/balance:* `Show account balance per currency`\n" \
|
||||
"*/stopbuy:* `Stops buying, but handles open trades gracefully` \n" \
|
||||
"*/reload_conf:* `Reload configuration file` \n" \
|
||||
"*/whitelist:* `Show current whitelist` \n" \
|
||||
"*/blacklist [pair]:* `Show current blacklist, or adds one or more pairs " \
|
||||
"to the blacklist.` \n" \
|
||||
"*/edge:* `Shows validated pairs by Edge if it is enabeld` \n" \
|
||||
"*/help:* `This help message`\n" \
|
||||
"*/version:* `Show version`"
|
||||
|
||||
|
||||
@@ -3,13 +3,26 @@
|
||||
"""
|
||||
Bot state constant
|
||||
"""
|
||||
import enum
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class State(enum.Enum):
|
||||
class State(Enum):
|
||||
"""
|
||||
Bot application states
|
||||
"""
|
||||
RUNNING = 0
|
||||
STOPPED = 1
|
||||
RELOAD_CONF = 2
|
||||
RUNNING = 1
|
||||
STOPPED = 2
|
||||
RELOAD_CONF = 3
|
||||
|
||||
|
||||
class RunMode(Enum):
|
||||
"""
|
||||
Bot running mode (backtest, hyperopt, ...)
|
||||
can be "live", "dry-run", "backtest", "edgecli", "hyperopt".
|
||||
"""
|
||||
LIVE = "live"
|
||||
DRY_RUN = "dry_run"
|
||||
BACKTEST = "backtest"
|
||||
EDGECLI = "edgecli"
|
||||
HYPEROPT = "hyperopt"
|
||||
OTHER = "other" # Used for plotting scripts and test
|
||||
|
||||
@@ -42,6 +42,19 @@ class DefaultStrategy(IStrategy):
|
||||
'sell': 'gtc',
|
||||
}
|
||||
|
||||
def informative_pairs(self):
|
||||
"""
|
||||
Define additional, informative pair/interval combinations to be cached from the exchange.
|
||||
These pair/interval combinations are non-tradeable, unless they are part
|
||||
of the whitelist as well.
|
||||
For more information, please consult the documentation
|
||||
:return: List of tuples in the format (pair, interval)
|
||||
Sample: return [("ETH/USDT", "5m"),
|
||||
("BTC/USDT", "15m"),
|
||||
]
|
||||
"""
|
||||
return []
|
||||
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Adds several different TA indicators to the given DataFrame
|
||||
|
||||
@@ -12,8 +12,10 @@ import warnings
|
||||
import arrow
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade import constants
|
||||
from freqtrade.data.dataprovider import DataProvider
|
||||
from freqtrade.misc import timeframe_to_minutes
|
||||
from freqtrade.persistence import Trade
|
||||
from freqtrade.wallets import Wallets
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -67,6 +69,12 @@ class IStrategy(ABC):
|
||||
# associated stoploss
|
||||
stoploss: float
|
||||
|
||||
# trailing stoploss
|
||||
trailing_stop: bool = False
|
||||
trailing_stop_positive: float
|
||||
trailing_stop_positive_offset: float
|
||||
trailing_only_offset_is_reached = False
|
||||
|
||||
# associated ticker interval
|
||||
ticker_interval: str
|
||||
|
||||
@@ -75,7 +83,8 @@ class IStrategy(ABC):
|
||||
'buy': 'limit',
|
||||
'sell': 'limit',
|
||||
'stoploss': 'limit',
|
||||
'stoploss_on_exchange': False
|
||||
'stoploss_on_exchange': False,
|
||||
'stoploss_on_exchange_interval': 60,
|
||||
}
|
||||
|
||||
# Optional time in force
|
||||
@@ -87,12 +96,16 @@ class IStrategy(ABC):
|
||||
# run "populate_indicators" only for new candle
|
||||
process_only_new_candles: bool = False
|
||||
|
||||
# Dict to determine if analysis is necessary
|
||||
_last_candle_seen_per_pair: Dict[str, datetime] = {}
|
||||
# Class level variables (intentional) containing
|
||||
# the dataprovider (dp) (access to other candles, historic data, ...)
|
||||
# and wallets - access to the current balance.
|
||||
dp: DataProvider
|
||||
wallets: Wallets
|
||||
|
||||
def __init__(self, config: dict) -> None:
|
||||
self.config = config
|
||||
self._last_candle_seen_per_pair = {}
|
||||
# Dict to determine if analysis is necessary
|
||||
self._last_candle_seen_per_pair: Dict[str, datetime] = {}
|
||||
|
||||
@abstractmethod
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
@@ -121,6 +134,19 @@ class IStrategy(ABC):
|
||||
:return: DataFrame with sell column
|
||||
"""
|
||||
|
||||
def informative_pairs(self) -> List[Tuple[str, str]]:
|
||||
"""
|
||||
Define additional, informative pair/interval combinations to be cached from the exchange.
|
||||
These pair/interval combinations are non-tradeable, unless they are part
|
||||
of the whitelist as well.
|
||||
For more information, please consult the documentation
|
||||
:return: List of tuples in the format (pair, interval)
|
||||
Sample: return [("ETH/USDT", "5m"),
|
||||
("BTC/USDT", "15m"),
|
||||
]
|
||||
"""
|
||||
return []
|
||||
|
||||
def get_strategy_name(self) -> str:
|
||||
"""
|
||||
Returns strategy class name
|
||||
@@ -141,19 +167,19 @@ class IStrategy(ABC):
|
||||
if (not self.process_only_new_candles or
|
||||
self._last_candle_seen_per_pair.get(pair, None) != dataframe.iloc[-1]['date']):
|
||||
# Defs that only make change on new candle data.
|
||||
logging.debug("TA Analysis Launched")
|
||||
logger.debug("TA Analysis Launched")
|
||||
dataframe = self.advise_indicators(dataframe, metadata)
|
||||
dataframe = self.advise_buy(dataframe, metadata)
|
||||
dataframe = self.advise_sell(dataframe, metadata)
|
||||
self._last_candle_seen_per_pair[pair] = dataframe.iloc[-1]['date']
|
||||
else:
|
||||
logging.debug("Skippinig TA Analysis for already analyzed candle")
|
||||
logger.debug("Skipping TA Analysis for already analyzed candle")
|
||||
dataframe['buy'] = 0
|
||||
dataframe['sell'] = 0
|
||||
|
||||
# Other Defs in strategy that want to be called every loop here
|
||||
# twitter_sell = self.watch_twitter_feed(dataframe, metadata)
|
||||
logging.debug("Loop Analysis Launched")
|
||||
logger.debug("Loop Analysis Launched")
|
||||
|
||||
return dataframe
|
||||
|
||||
@@ -195,7 +221,7 @@ class IStrategy(ABC):
|
||||
|
||||
# Check if dataframe is out of date
|
||||
signal_date = arrow.get(latest['date'])
|
||||
interval_minutes = constants.TICKER_INTERVAL_MINUTES[interval]
|
||||
interval_minutes = timeframe_to_minutes(interval)
|
||||
offset = self.config.get('exchange', {}).get('outdated_offset', 5)
|
||||
if signal_date < (arrow.utcnow().shift(minutes=-(interval_minutes * 2 + offset))):
|
||||
logger.warning(
|
||||
@@ -221,6 +247,9 @@ class IStrategy(ABC):
|
||||
"""
|
||||
This function evaluate if on the condition required to trigger a sell has been reached
|
||||
if the threshold is reached and updates the trade record.
|
||||
:param low: Only used during backtesting to simulate stoploss
|
||||
:param high: Only used during backtesting, to simulate ROI
|
||||
:param force_stoploss: Externally provided stoploss
|
||||
:return: True if trade should be sold, False otherwise
|
||||
"""
|
||||
|
||||
@@ -228,17 +257,16 @@ class IStrategy(ABC):
|
||||
current_rate = low or rate
|
||||
current_profit = trade.calc_profit_percent(current_rate)
|
||||
|
||||
if self.order_types.get('stoploss_on_exchange'):
|
||||
stoplossflag = SellCheckTuple(sell_flag=False, sell_type=SellType.NONE)
|
||||
else:
|
||||
stoplossflag = self.stop_loss_reached(current_rate=current_rate, trade=trade,
|
||||
current_time=date, current_profit=current_profit,
|
||||
force_stoploss=force_stoploss)
|
||||
trade.adjust_min_max_rates(high or current_rate)
|
||||
|
||||
stoplossflag = self.stop_loss_reached(current_rate=current_rate, trade=trade,
|
||||
current_time=date, current_profit=current_profit,
|
||||
force_stoploss=force_stoploss, high=high)
|
||||
|
||||
if stoplossflag.sell_flag:
|
||||
return stoplossflag
|
||||
|
||||
# Set current rate to low for backtesting sell
|
||||
# Set current rate to high for backtesting sell
|
||||
current_rate = high or rate
|
||||
current_profit = trade.calc_profit_percent(current_rate)
|
||||
experimental = self.config.get('experimental', {})
|
||||
@@ -262,8 +290,9 @@ class IStrategy(ABC):
|
||||
|
||||
return SellCheckTuple(sell_flag=False, sell_type=SellType.NONE)
|
||||
|
||||
def stop_loss_reached(self, current_rate: float, trade: Trade, current_time: datetime,
|
||||
current_profit: float, force_stoploss: float) -> SellCheckTuple:
|
||||
def stop_loss_reached(self, current_rate: float, trade: Trade,
|
||||
current_time: datetime, current_profit: float,
|
||||
force_stoploss: float, high: float = None) -> SellCheckTuple:
|
||||
"""
|
||||
Based on current profit of the trade and configured (trailing) stoploss,
|
||||
decides to sell or not
|
||||
@@ -271,14 +300,36 @@ class IStrategy(ABC):
|
||||
"""
|
||||
|
||||
trailing_stop = self.config.get('trailing_stop', False)
|
||||
stop_loss_value = force_stoploss if force_stoploss else self.stoploss
|
||||
|
||||
trade.adjust_stop_loss(trade.open_rate, force_stoploss if force_stoploss
|
||||
else self.stoploss, initial=True)
|
||||
# Initiate stoploss with open_rate. Does nothing if stoploss is already set.
|
||||
trade.adjust_stop_loss(trade.open_rate, stop_loss_value, initial=True)
|
||||
|
||||
if trailing_stop:
|
||||
# trailing stoploss handling
|
||||
|
||||
sl_offset = self.config.get('trailing_stop_positive_offset') or 0.0
|
||||
tsl_only_offset = self.config.get('trailing_only_offset_is_reached', False)
|
||||
|
||||
# Don't update stoploss if trailing_only_offset_is_reached is true.
|
||||
if not (tsl_only_offset and current_profit < sl_offset):
|
||||
# Specific handling for trailing_stop_positive
|
||||
if 'trailing_stop_positive' in self.config and current_profit > sl_offset:
|
||||
# Ignore mypy error check in configuration that this is a float
|
||||
stop_loss_value = self.config.get('trailing_stop_positive') # type: ignore
|
||||
logger.debug(f"using positive stop loss: {stop_loss_value} "
|
||||
f"offset: {sl_offset:.4g} profit: {current_profit:.4f}%")
|
||||
|
||||
trade.adjust_stop_loss(high or current_rate, stop_loss_value)
|
||||
|
||||
# evaluate if the stoploss was hit if stoploss is not on exchange
|
||||
if ((self.stoploss is not None) and
|
||||
(trade.stop_loss >= current_rate) and
|
||||
(not self.order_types.get('stoploss_on_exchange'))):
|
||||
|
||||
# evaluate if the stoploss was hit
|
||||
if self.stoploss is not None and trade.stop_loss >= current_rate:
|
||||
selltype = SellType.STOP_LOSS
|
||||
if trailing_stop:
|
||||
# If Trailing stop (and max-rate did move above open rate)
|
||||
if trailing_stop and trade.open_rate != trade.max_rate:
|
||||
selltype = SellType.TRAILING_STOP_LOSS
|
||||
logger.debug(
|
||||
f"HIT STOP: current price at {current_rate:.6f}, "
|
||||
@@ -290,40 +341,23 @@ class IStrategy(ABC):
|
||||
logger.debug('Stop loss hit.')
|
||||
return SellCheckTuple(sell_flag=True, sell_type=selltype)
|
||||
|
||||
# update the stop loss afterwards, after all by definition it's supposed to be hanging
|
||||
if trailing_stop:
|
||||
|
||||
# check if we have a special stop loss for positive condition
|
||||
# and if profit is positive
|
||||
stop_loss_value = self.stoploss
|
||||
sl_offset = self.config.get('trailing_stop_positive_offset', 0.0)
|
||||
|
||||
if 'trailing_stop_positive' in self.config and current_profit > sl_offset:
|
||||
|
||||
# Ignore mypy error check in configuration that this is a float
|
||||
stop_loss_value = self.config.get('trailing_stop_positive') # type: ignore
|
||||
logger.debug(f"using positive stop loss mode: {stop_loss_value} "
|
||||
f"with offset {sl_offset:.4g} "
|
||||
f"since we have profit {current_profit:.4f}%")
|
||||
|
||||
trade.adjust_stop_loss(current_rate, stop_loss_value)
|
||||
|
||||
return SellCheckTuple(sell_flag=False, sell_type=SellType.NONE)
|
||||
|
||||
def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool:
|
||||
"""
|
||||
Based an earlier trade and current price and ROI configuration, decides whether bot should
|
||||
sell
|
||||
sell. Requires current_profit to be in percent!!
|
||||
:return True if bot should sell at current rate
|
||||
"""
|
||||
|
||||
# Check if time matches and current rate is above threshold
|
||||
time_diff = (current_time.timestamp() - trade.open_date.timestamp()) / 60
|
||||
for duration, threshold in self.minimal_roi.items():
|
||||
if time_diff <= duration:
|
||||
return False
|
||||
if current_profit > threshold:
|
||||
return True
|
||||
trade_dur = (current_time.timestamp() - trade.open_date.timestamp()) / 60
|
||||
|
||||
# Get highest entry in ROI dict where key >= trade-duration
|
||||
roi_entry = max(list(filter(lambda x: trade_dur >= x, self.minimal_roi.keys())))
|
||||
threshold = self.minimal_roi[roi_entry]
|
||||
if current_profit > threshold:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
# pragma pylint: disable=missing-docstring
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
from functools import reduce
|
||||
from typing import Dict, Optional
|
||||
from unittest.mock import MagicMock, PropertyMock
|
||||
|
||||
import arrow
|
||||
@@ -12,9 +12,11 @@ from telegram import Chat, Message, Update
|
||||
|
||||
from freqtrade import constants
|
||||
from freqtrade.data.converter import parse_ticker_dataframe
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.edge import Edge, PairInfo
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.freqtradebot import FreqtradeBot
|
||||
from freqtrade.resolvers import ExchangeResolver
|
||||
from freqtrade.worker import Worker
|
||||
|
||||
logging.getLogger('').setLevel(logging.INFO)
|
||||
|
||||
@@ -27,8 +29,15 @@ def log_has(line, logs):
|
||||
False)
|
||||
|
||||
|
||||
def log_has_re(line, logs):
|
||||
return reduce(lambda a, b: a or b,
|
||||
filter(lambda x: re.match(line, x[2]), logs),
|
||||
False)
|
||||
|
||||
|
||||
def patch_exchange(mocker, api_mock=None, id='bittrex') -> None:
|
||||
mocker.patch('freqtrade.exchange.Exchange._load_markets', MagicMock(return_value={}))
|
||||
mocker.patch('freqtrade.exchange.Exchange.validate_pairs', MagicMock())
|
||||
mocker.patch('freqtrade.exchange.Exchange.validate_timeframes', MagicMock())
|
||||
mocker.patch('freqtrade.exchange.Exchange.validate_ordertypes', MagicMock())
|
||||
mocker.patch('freqtrade.exchange.Exchange.id', PropertyMock(return_value=id))
|
||||
@@ -42,7 +51,11 @@ def patch_exchange(mocker, api_mock=None, id='bittrex') -> None:
|
||||
|
||||
def get_patched_exchange(mocker, config, api_mock=None, id='bittrex') -> Exchange:
|
||||
patch_exchange(mocker, api_mock, id)
|
||||
exchange = Exchange(config)
|
||||
config["exchange"]["name"] = id
|
||||
try:
|
||||
exchange = ExchangeResolver(id.title(), config).exchange
|
||||
except ImportError:
|
||||
exchange = Exchange(config)
|
||||
return exchange
|
||||
|
||||
|
||||
@@ -75,24 +88,32 @@ def get_patched_edge(mocker, config) -> Edge:
|
||||
# Functions for recurrent object patching
|
||||
|
||||
|
||||
def get_patched_freqtradebot(mocker, config) -> FreqtradeBot:
|
||||
def patch_freqtradebot(mocker, config) -> None:
|
||||
"""
|
||||
This function patch _init_modules() to not call dependencies
|
||||
:param mocker: a Mocker object to apply patches
|
||||
:param config: Config to pass to the bot
|
||||
:return: None
|
||||
"""
|
||||
patch_coinmarketcap(mocker, {'price_usd': 12345.0})
|
||||
mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock())
|
||||
mocker.patch('freqtrade.freqtradebot.persistence.init', MagicMock())
|
||||
patch_exchange(mocker, None)
|
||||
mocker.patch('freqtrade.freqtradebot.RPCManager._init', MagicMock())
|
||||
mocker.patch('freqtrade.freqtradebot.RPCManager.send_msg', MagicMock())
|
||||
|
||||
|
||||
def get_patched_freqtradebot(mocker, config) -> FreqtradeBot:
|
||||
patch_freqtradebot(mocker, config)
|
||||
return FreqtradeBot(config)
|
||||
|
||||
|
||||
def patch_coinmarketcap(mocker, value: Optional[Dict[str, float]] = None) -> None:
|
||||
def get_patched_worker(mocker, config) -> Worker:
|
||||
patch_freqtradebot(mocker, config)
|
||||
return Worker(args=None, config=config)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def patch_coinmarketcap(mocker) -> None:
|
||||
"""
|
||||
Mocker to coinmarketcap to speed up tests
|
||||
:param mocker: mocker to patch coinmarketcap class
|
||||
@@ -158,6 +179,10 @@ def default_conf():
|
||||
"LTC/BTC",
|
||||
"XRP/BTC",
|
||||
"NEO/BTC"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"DOGE/BTC",
|
||||
"HOT/BTC",
|
||||
]
|
||||
},
|
||||
"telegram": {
|
||||
@@ -213,8 +238,8 @@ def ticker_sell_down():
|
||||
|
||||
@pytest.fixture
|
||||
def markets():
|
||||
return MagicMock(return_value=[
|
||||
{
|
||||
return {
|
||||
'ETH/BTC': {
|
||||
'id': 'ethbtc',
|
||||
'symbol': 'ETH/BTC',
|
||||
'base': 'ETH',
|
||||
@@ -239,7 +264,7 @@ def markets():
|
||||
},
|
||||
'info': '',
|
||||
},
|
||||
{
|
||||
'TKN/BTC': {
|
||||
'id': 'tknbtc',
|
||||
'symbol': 'TKN/BTC',
|
||||
'base': 'TKN',
|
||||
@@ -264,7 +289,7 @@ def markets():
|
||||
},
|
||||
'info': '',
|
||||
},
|
||||
{
|
||||
'BLK/BTC': {
|
||||
'id': 'blkbtc',
|
||||
'symbol': 'BLK/BTC',
|
||||
'base': 'BLK',
|
||||
@@ -289,7 +314,7 @@ def markets():
|
||||
},
|
||||
'info': '',
|
||||
},
|
||||
{
|
||||
'LTC/BTC': {
|
||||
'id': 'ltcbtc',
|
||||
'symbol': 'LTC/BTC',
|
||||
'base': 'LTC',
|
||||
@@ -314,7 +339,7 @@ def markets():
|
||||
},
|
||||
'info': '',
|
||||
},
|
||||
{
|
||||
'XRP/BTC': {
|
||||
'id': 'xrpbtc',
|
||||
'symbol': 'XRP/BTC',
|
||||
'base': 'XRP',
|
||||
@@ -339,7 +364,7 @@ def markets():
|
||||
},
|
||||
'info': '',
|
||||
},
|
||||
{
|
||||
'NEO/BTC': {
|
||||
'id': 'neobtc',
|
||||
'symbol': 'NEO/BTC',
|
||||
'base': 'NEO',
|
||||
@@ -363,8 +388,80 @@ def markets():
|
||||
},
|
||||
},
|
||||
'info': '',
|
||||
},
|
||||
'BTT/BTC': {
|
||||
'id': 'BTTBTC',
|
||||
'symbol': 'BTT/BTC',
|
||||
'base': 'BTT',
|
||||
'quote': 'BTC',
|
||||
'active': True,
|
||||
'precision': {
|
||||
'base': 8,
|
||||
'quote': 8,
|
||||
'amount': 0,
|
||||
'price': 8
|
||||
},
|
||||
'limits': {
|
||||
'amount': {
|
||||
'min': 1.0,
|
||||
'max': 90000000.0
|
||||
},
|
||||
'price': {
|
||||
'min': None,
|
||||
'max': None
|
||||
},
|
||||
'cost': {
|
||||
'min': 0.001,
|
||||
'max': None
|
||||
}
|
||||
},
|
||||
'info': "",
|
||||
},
|
||||
'ETH/USDT': {
|
||||
'id': 'USDT-ETH',
|
||||
'symbol': 'ETH/USDT',
|
||||
'base': 'ETH',
|
||||
'quote': 'USDT',
|
||||
'precision': {
|
||||
'amount': 8,
|
||||
'price': 8
|
||||
},
|
||||
'limits': {
|
||||
'amount': {
|
||||
'min': 0.02214286,
|
||||
'max': None
|
||||
},
|
||||
'price': {
|
||||
'min': 1e-08,
|
||||
'max': None
|
||||
}
|
||||
},
|
||||
'active': True,
|
||||
'info': ""
|
||||
},
|
||||
'LTC/USDT': {
|
||||
'id': 'USDT-LTC',
|
||||
'symbol': 'LTC/USDT',
|
||||
'base': 'LTC',
|
||||
'quote': 'USDT',
|
||||
'active': True,
|
||||
'precision': {
|
||||
'amount': 8,
|
||||
'price': 8
|
||||
},
|
||||
'limits': {
|
||||
'amount': {
|
||||
'min': 0.06646786,
|
||||
'max': None
|
||||
},
|
||||
'price': {
|
||||
'min': 1e-08,
|
||||
'max': None
|
||||
}
|
||||
},
|
||||
'info': ""
|
||||
}
|
||||
])
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -542,7 +639,7 @@ def ticker_history_list():
|
||||
|
||||
@pytest.fixture
|
||||
def ticker_history(ticker_history_list):
|
||||
return parse_ticker_dataframe(ticker_history_list)
|
||||
return parse_ticker_dataframe(ticker_history_list, "5m", True)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -583,6 +680,7 @@ def tickers():
|
||||
'vwap': 0.01869197,
|
||||
'open': 0.018585,
|
||||
'close': 0.018573,
|
||||
'last': 0.018799,
|
||||
'baseVolume': 81058.66,
|
||||
'quoteVolume': 2247.48374509,
|
||||
},
|
||||
@@ -630,6 +728,28 @@ def tickers():
|
||||
'quoteVolume': 1401.65697943,
|
||||
'info': {}
|
||||
},
|
||||
'BTT/BTC': {
|
||||
'symbol': 'BTT/BTC',
|
||||
'timestamp': 1550936557206,
|
||||
'datetime': '2019-02-23T15:42:37.206Z',
|
||||
'high': 0.00000026,
|
||||
'low': 0.00000024,
|
||||
'bid': 0.00000024,
|
||||
'bidVolume': 2446894197.0,
|
||||
'ask': 0.00000025,
|
||||
'askVolume': 2447913837.0,
|
||||
'vwap': 0.00000025,
|
||||
'open': 0.00000026,
|
||||
'close': 0.00000024,
|
||||
'last': 0.00000024,
|
||||
'previousClose': 0.00000026,
|
||||
'change': -0.00000002,
|
||||
'percentage': -7.692,
|
||||
'average': None,
|
||||
'baseVolume': 4886464537.0,
|
||||
'quoteVolume': 1215.14489611,
|
||||
'info': {}
|
||||
},
|
||||
'ETH/USDT': {
|
||||
'symbol': 'ETH/USDT',
|
||||
'timestamp': 1522014804118,
|
||||
@@ -724,7 +844,7 @@ def tickers():
|
||||
@pytest.fixture
|
||||
def result():
|
||||
with open('freqtrade/tests/testdata/UNITTEST_BTC-1m.json') as data_file:
|
||||
return parse_ticker_dataframe(json.load(data_file))
|
||||
return parse_ticker_dataframe(json.load(data_file), '1m', True)
|
||||
|
||||
# FIX:
|
||||
# Create an fixture/function
|
||||
|
||||
21
freqtrade/tests/data/test_btanalysis.py
Normal file
21
freqtrade/tests/data/test_btanalysis.py
Normal file
@@ -0,0 +1,21 @@
|
||||
import pytest
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.data.btanalysis import BT_DATA_COLUMNS, load_backtest_data
|
||||
from freqtrade.data.history import make_testdata_path
|
||||
|
||||
|
||||
def test_load_backtest_data():
|
||||
|
||||
filename = make_testdata_path(None) / "backtest-result_test.json"
|
||||
bt_data = load_backtest_data(filename)
|
||||
assert isinstance(bt_data, DataFrame)
|
||||
assert list(bt_data.columns) == BT_DATA_COLUMNS + ["profitabs"]
|
||||
assert len(bt_data) == 179
|
||||
|
||||
# Test loading from string (must yield same result)
|
||||
bt_data2 = load_backtest_data(str(filename))
|
||||
assert bt_data.equals(bt_data2)
|
||||
|
||||
with pytest.raises(ValueError, match=r"File .* does not exist\."):
|
||||
load_backtest_data(str("filename") + "nofile")
|
||||
@@ -1,25 +1,99 @@
|
||||
# pragma pylint: disable=missing-docstring, C0103
|
||||
import logging
|
||||
|
||||
from freqtrade.data.converter import parse_ticker_dataframe
|
||||
from freqtrade.data.converter import parse_ticker_dataframe, ohlcv_fill_up_missing_data
|
||||
from freqtrade.data.history import load_pair_history
|
||||
from freqtrade.optimize import validate_backtest_data, get_timeframe
|
||||
from freqtrade.tests.conftest import log_has
|
||||
|
||||
|
||||
def test_dataframe_correct_length(result):
|
||||
dataframe = parse_ticker_dataframe(result)
|
||||
assert len(result.index) - 1 == len(dataframe.index) # last partial candle removed
|
||||
|
||||
|
||||
def test_dataframe_correct_columns(result):
|
||||
assert result.columns.tolist() == \
|
||||
['date', 'open', 'high', 'low', 'close', 'volume']
|
||||
assert result.columns.tolist() == ['date', 'open', 'high', 'low', 'close', 'volume']
|
||||
|
||||
|
||||
def test_parse_ticker_dataframe(ticker_history, caplog):
|
||||
def test_parse_ticker_dataframe(ticker_history_list, caplog):
|
||||
columns = ['date', 'open', 'high', 'low', 'close', 'volume']
|
||||
|
||||
caplog.set_level(logging.DEBUG)
|
||||
# Test file with BV data
|
||||
dataframe = parse_ticker_dataframe(ticker_history)
|
||||
dataframe = parse_ticker_dataframe(ticker_history_list, '5m', fill_missing=True)
|
||||
assert dataframe.columns.tolist() == columns
|
||||
assert log_has('Parsing tickerlist to dataframe', caplog.record_tuples)
|
||||
|
||||
|
||||
def test_ohlcv_fill_up_missing_data(caplog):
|
||||
data = load_pair_history(datadir=None,
|
||||
ticker_interval='1m',
|
||||
refresh_pairs=False,
|
||||
pair='UNITTEST/BTC',
|
||||
fill_up_missing=False)
|
||||
caplog.set_level(logging.DEBUG)
|
||||
data2 = ohlcv_fill_up_missing_data(data, '1m')
|
||||
assert len(data2) > len(data)
|
||||
# Column names should not change
|
||||
assert (data.columns == data2.columns).all()
|
||||
|
||||
assert log_has(f"Missing data fillup: before: {len(data)} - after: {len(data2)}",
|
||||
caplog.record_tuples)
|
||||
|
||||
# Test fillup actually fixes invalid backtest data
|
||||
min_date, max_date = get_timeframe({'UNITTEST/BTC': data})
|
||||
assert validate_backtest_data({'UNITTEST/BTC': data}, min_date, max_date, 1)
|
||||
assert not validate_backtest_data({'UNITTEST/BTC': data2}, min_date, max_date, 1)
|
||||
|
||||
|
||||
def test_ohlcv_fill_up_missing_data2(caplog):
|
||||
ticker_interval = '5m'
|
||||
ticks = [[
|
||||
1511686200000, # 8:50:00
|
||||
8.794e-05, # open
|
||||
8.948e-05, # high
|
||||
8.794e-05, # low
|
||||
8.88e-05, # close
|
||||
2255, # volume (in quote currency)
|
||||
],
|
||||
[
|
||||
1511686500000, # 8:55:00
|
||||
8.88e-05,
|
||||
8.942e-05,
|
||||
8.88e-05,
|
||||
8.893e-05,
|
||||
9911,
|
||||
],
|
||||
[
|
||||
1511687100000, # 9:05:00
|
||||
8.891e-05,
|
||||
8.893e-05,
|
||||
8.875e-05,
|
||||
8.877e-05,
|
||||
2251
|
||||
],
|
||||
[
|
||||
1511687400000, # 9:10:00
|
||||
8.877e-05,
|
||||
8.883e-05,
|
||||
8.895e-05,
|
||||
8.817e-05,
|
||||
123551
|
||||
]
|
||||
]
|
||||
|
||||
# Generate test-data without filling missing
|
||||
data = parse_ticker_dataframe(ticks, ticker_interval, fill_missing=False)
|
||||
assert len(data) == 3
|
||||
caplog.set_level(logging.DEBUG)
|
||||
data2 = ohlcv_fill_up_missing_data(data, ticker_interval)
|
||||
assert len(data2) == 4
|
||||
# 3rd candle has been filled
|
||||
row = data2.loc[2, :]
|
||||
assert row['volume'] == 0
|
||||
# close shoult match close of previous candle
|
||||
assert row['close'] == data.loc[1, 'close']
|
||||
assert row['open'] == row['close']
|
||||
assert row['high'] == row['close']
|
||||
assert row['low'] == row['close']
|
||||
# Column names should not change
|
||||
assert (data.columns == data2.columns).all()
|
||||
|
||||
assert log_has(f"Missing data fillup: before: {len(data)} - after: {len(data2)}",
|
||||
caplog.record_tuples)
|
||||
|
||||
92
freqtrade/tests/data/test_dataprovider.py
Normal file
92
freqtrade/tests/data/test_dataprovider.py
Normal file
@@ -0,0 +1,92 @@
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.data.dataprovider import DataProvider
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.tests.conftest import get_patched_exchange
|
||||
|
||||
|
||||
def test_ohlcv(mocker, default_conf, ticker_history):
|
||||
default_conf["runmode"] = RunMode.DRY_RUN
|
||||
ticker_interval = default_conf["ticker_interval"]
|
||||
exchange = get_patched_exchange(mocker, default_conf)
|
||||
exchange._klines[("XRP/BTC", ticker_interval)] = ticker_history
|
||||
exchange._klines[("UNITTEST/BTC", ticker_interval)] = ticker_history
|
||||
dp = DataProvider(default_conf, exchange)
|
||||
assert dp.runmode == RunMode.DRY_RUN
|
||||
assert ticker_history.equals(dp.ohlcv("UNITTEST/BTC", ticker_interval))
|
||||
assert isinstance(dp.ohlcv("UNITTEST/BTC", ticker_interval), DataFrame)
|
||||
assert dp.ohlcv("UNITTEST/BTC", ticker_interval) is not ticker_history
|
||||
assert dp.ohlcv("UNITTEST/BTC", ticker_interval, copy=False) is ticker_history
|
||||
assert not dp.ohlcv("UNITTEST/BTC", ticker_interval).empty
|
||||
assert dp.ohlcv("NONESENSE/AAA", ticker_interval).empty
|
||||
|
||||
# Test with and without parameter
|
||||
assert dp.ohlcv("UNITTEST/BTC", ticker_interval).equals(dp.ohlcv("UNITTEST/BTC"))
|
||||
|
||||
default_conf["runmode"] = RunMode.LIVE
|
||||
dp = DataProvider(default_conf, exchange)
|
||||
assert dp.runmode == RunMode.LIVE
|
||||
assert isinstance(dp.ohlcv("UNITTEST/BTC", ticker_interval), DataFrame)
|
||||
|
||||
default_conf["runmode"] = RunMode.BACKTEST
|
||||
dp = DataProvider(default_conf, exchange)
|
||||
assert dp.runmode == RunMode.BACKTEST
|
||||
assert dp.ohlcv("UNITTEST/BTC", ticker_interval).empty
|
||||
|
||||
|
||||
def test_historic_ohlcv(mocker, default_conf, ticker_history):
|
||||
|
||||
historymock = MagicMock(return_value=ticker_history)
|
||||
mocker.patch("freqtrade.data.dataprovider.load_pair_history", historymock)
|
||||
|
||||
# exchange = get_patched_exchange(mocker, default_conf)
|
||||
dp = DataProvider(default_conf, None)
|
||||
data = dp.historic_ohlcv("UNITTEST/BTC", "5m")
|
||||
assert isinstance(data, DataFrame)
|
||||
assert historymock.call_count == 1
|
||||
assert historymock.call_args_list[0][1]["datadir"] is None
|
||||
assert historymock.call_args_list[0][1]["refresh_pairs"] is False
|
||||
assert historymock.call_args_list[0][1]["ticker_interval"] == "5m"
|
||||
|
||||
|
||||
def test_available_pairs(mocker, default_conf, ticker_history):
|
||||
exchange = get_patched_exchange(mocker, default_conf)
|
||||
|
||||
ticker_interval = default_conf["ticker_interval"]
|
||||
exchange._klines[("XRP/BTC", ticker_interval)] = ticker_history
|
||||
exchange._klines[("UNITTEST/BTC", ticker_interval)] = ticker_history
|
||||
dp = DataProvider(default_conf, exchange)
|
||||
|
||||
assert len(dp.available_pairs) == 2
|
||||
assert dp.available_pairs == [
|
||||
("XRP/BTC", ticker_interval),
|
||||
("UNITTEST/BTC", ticker_interval),
|
||||
]
|
||||
|
||||
|
||||
def test_refresh(mocker, default_conf, ticker_history):
|
||||
refresh_mock = MagicMock()
|
||||
mocker.patch("freqtrade.exchange.Exchange.refresh_latest_ohlcv", refresh_mock)
|
||||
|
||||
exchange = get_patched_exchange(mocker, default_conf, id="binance")
|
||||
ticker_interval = default_conf["ticker_interval"]
|
||||
pairs = [("XRP/BTC", ticker_interval), ("UNITTEST/BTC", ticker_interval)]
|
||||
|
||||
pairs_non_trad = [("ETH/USDT", ticker_interval), ("BTC/TUSD", "1h")]
|
||||
|
||||
dp = DataProvider(default_conf, exchange)
|
||||
dp.refresh(pairs)
|
||||
|
||||
assert refresh_mock.call_count == 1
|
||||
assert len(refresh_mock.call_args[0]) == 1
|
||||
assert len(refresh_mock.call_args[0][0]) == len(pairs)
|
||||
assert refresh_mock.call_args[0][0] == pairs
|
||||
|
||||
refresh_mock.reset_mock()
|
||||
dp.refresh(pairs, pairs_non_trad)
|
||||
assert refresh_mock.call_count == 1
|
||||
assert len(refresh_mock.call_args[0]) == 1
|
||||
assert len(refresh_mock.call_args[0][0]) == len(pairs) + len(pairs_non_trad)
|
||||
assert refresh_mock.call_args[0][0] == pairs + pairs_non_trad
|
||||
@@ -242,10 +242,10 @@ def test_download_pair_history(ticker_history_list, mocker, default_conf) -> Non
|
||||
|
||||
assert download_pair_history(datadir=None, exchange=exchange,
|
||||
pair='MEME/BTC',
|
||||
tick_interval='1m')
|
||||
ticker_interval='1m')
|
||||
assert download_pair_history(datadir=None, exchange=exchange,
|
||||
pair='CFI/BTC',
|
||||
tick_interval='1m')
|
||||
ticker_interval='1m')
|
||||
assert not exchange._pairs_last_refresh_time
|
||||
assert os.path.isfile(file1_1) is True
|
||||
assert os.path.isfile(file2_1) is True
|
||||
@@ -259,10 +259,10 @@ def test_download_pair_history(ticker_history_list, mocker, default_conf) -> Non
|
||||
|
||||
assert download_pair_history(datadir=None, exchange=exchange,
|
||||
pair='MEME/BTC',
|
||||
tick_interval='5m')
|
||||
ticker_interval='5m')
|
||||
assert download_pair_history(datadir=None, exchange=exchange,
|
||||
pair='CFI/BTC',
|
||||
tick_interval='5m')
|
||||
ticker_interval='5m')
|
||||
assert not exchange._pairs_last_refresh_time
|
||||
assert os.path.isfile(file1_5) is True
|
||||
assert os.path.isfile(file2_5) is True
|
||||
@@ -280,8 +280,8 @@ def test_download_pair_history2(mocker, default_conf) -> None:
|
||||
json_dump_mock = mocker.patch('freqtrade.misc.file_dump_json', return_value=None)
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_history', return_value=tick)
|
||||
exchange = get_patched_exchange(mocker, default_conf)
|
||||
download_pair_history(None, exchange, pair="UNITTEST/BTC", tick_interval='1m')
|
||||
download_pair_history(None, exchange, pair="UNITTEST/BTC", tick_interval='3m')
|
||||
download_pair_history(None, exchange, pair="UNITTEST/BTC", ticker_interval='1m')
|
||||
download_pair_history(None, exchange, pair="UNITTEST/BTC", ticker_interval='3m')
|
||||
assert json_dump_mock.call_count == 2
|
||||
|
||||
|
||||
@@ -298,7 +298,7 @@ def test_download_backtesting_data_exception(ticker_history, mocker, caplog, def
|
||||
|
||||
assert not download_pair_history(datadir=None, exchange=exchange,
|
||||
pair='MEME/BTC',
|
||||
tick_interval='1m')
|
||||
ticker_interval='1m')
|
||||
# clean files freshly downloaded
|
||||
_clean_test_file(file1_1)
|
||||
_clean_test_file(file1_5)
|
||||
@@ -450,7 +450,7 @@ def test_trim_tickerlist() -> None:
|
||||
assert not ticker
|
||||
|
||||
|
||||
def test_file_dump_json() -> None:
|
||||
def test_file_dump_json_tofile() -> None:
|
||||
file = os.path.join(os.path.dirname(__file__), '..', 'testdata',
|
||||
'test_{id}.json'.format(id=str(uuid.uuid4())))
|
||||
data = {'bar': 'foo'}
|
||||
|
||||
@@ -122,8 +122,8 @@ def test_edge_results(edge_conf, mocker, caplog, data) -> None:
|
||||
for c, trade in enumerate(data.trades):
|
||||
res = results.iloc[c]
|
||||
assert res.exit_type == trade.sell_reason
|
||||
assert res.open_time == _get_frame_time_from_offset(trade.open_tick)
|
||||
assert res.close_time == _get_frame_time_from_offset(trade.close_tick)
|
||||
assert arrow.get(res.open_time) == _get_frame_time_from_offset(trade.open_tick)
|
||||
assert arrow.get(res.close_time) == _get_frame_time_from_offset(trade.close_tick)
|
||||
|
||||
|
||||
def test_adjust(mocker, edge_conf):
|
||||
@@ -281,8 +281,8 @@ def mocked_load_data(datadir, pairs=[], ticker_interval='0m', refresh_pairs=Fals
|
||||
123.45
|
||||
] for x in range(0, 500)]
|
||||
|
||||
pairdata = {'NEO/BTC': parse_ticker_dataframe(ETHBTC),
|
||||
'LTC/BTC': parse_ticker_dataframe(LTCBTC)}
|
||||
pairdata = {'NEO/BTC': parse_ticker_dataframe(ETHBTC, '1h', fill_missing=True),
|
||||
'LTC/BTC': parse_ticker_dataframe(LTCBTC, '1h', fill_missing=True)}
|
||||
return pairdata
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
67
freqtrade/tests/exchange/test_kraken.py
Normal file
67
freqtrade/tests/exchange/test_kraken.py
Normal file
@@ -0,0 +1,67 @@
|
||||
# pragma pylint: disable=missing-docstring, C0103, bad-continuation, global-statement
|
||||
# pragma pylint: disable=protected-access
|
||||
from random import randint
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from freqtrade.tests.conftest import get_patched_exchange
|
||||
|
||||
|
||||
def test_buy_kraken_trading_agreement(default_conf, mocker):
|
||||
api_mock = MagicMock()
|
||||
order_id = 'test_prod_buy_{}'.format(randint(0, 10 ** 6))
|
||||
order_type = 'limit'
|
||||
time_in_force = 'ioc'
|
||||
api_mock.create_order = MagicMock(return_value={
|
||||
'id': order_id,
|
||||
'info': {
|
||||
'foo': 'bar'
|
||||
}
|
||||
})
|
||||
default_conf['dry_run'] = False
|
||||
|
||||
mocker.patch('freqtrade.exchange.Exchange.symbol_amount_prec', lambda s, x, y: y)
|
||||
mocker.patch('freqtrade.exchange.Exchange.symbol_price_prec', lambda s, x, y: y)
|
||||
exchange = get_patched_exchange(mocker, default_conf, api_mock, id="kraken")
|
||||
|
||||
order = exchange.buy(pair='ETH/BTC', ordertype=order_type,
|
||||
amount=1, rate=200, time_in_force=time_in_force)
|
||||
|
||||
assert 'id' in order
|
||||
assert 'info' in order
|
||||
assert order['id'] == order_id
|
||||
assert api_mock.create_order.call_args[0][0] == 'ETH/BTC'
|
||||
assert api_mock.create_order.call_args[0][1] == order_type
|
||||
assert api_mock.create_order.call_args[0][2] == 'buy'
|
||||
assert api_mock.create_order.call_args[0][3] == 1
|
||||
assert api_mock.create_order.call_args[0][4] == 200
|
||||
assert api_mock.create_order.call_args[0][5] == {'timeInForce': 'ioc',
|
||||
'trading_agreement': 'agree'}
|
||||
|
||||
|
||||
def test_sell_kraken_trading_agreement(default_conf, mocker):
|
||||
api_mock = MagicMock()
|
||||
order_id = 'test_prod_sell_{}'.format(randint(0, 10 ** 6))
|
||||
order_type = 'market'
|
||||
api_mock.create_order = MagicMock(return_value={
|
||||
'id': order_id,
|
||||
'info': {
|
||||
'foo': 'bar'
|
||||
}
|
||||
})
|
||||
default_conf['dry_run'] = False
|
||||
|
||||
mocker.patch('freqtrade.exchange.Exchange.symbol_amount_prec', lambda s, x, y: y)
|
||||
mocker.patch('freqtrade.exchange.Exchange.symbol_price_prec', lambda s, x, y: y)
|
||||
exchange = get_patched_exchange(mocker, default_conf, api_mock, id="kraken")
|
||||
|
||||
order = exchange.sell(pair='ETH/BTC', ordertype=order_type, amount=1, rate=200)
|
||||
|
||||
assert 'id' in order
|
||||
assert 'info' in order
|
||||
assert order['id'] == order_id
|
||||
assert api_mock.create_order.call_args[0][0] == 'ETH/BTC'
|
||||
assert api_mock.create_order.call_args[0][1] == order_type
|
||||
assert api_mock.create_order.call_args[0][2] == 'sell'
|
||||
assert api_mock.create_order.call_args[0][3] == 1
|
||||
assert api_mock.create_order.call_args[0][4] is None
|
||||
assert api_mock.create_order.call_args[0][5] == {'trading_agreement': 'agree'}
|
||||
@@ -3,11 +3,11 @@ from typing import NamedTuple, List
|
||||
import arrow
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.misc import timeframe_to_minutes
|
||||
from freqtrade.strategy.interface import SellType
|
||||
from freqtrade.constants import TICKER_INTERVAL_MINUTES
|
||||
|
||||
ticker_start_time = arrow.get(2018, 10, 3)
|
||||
tests_ticker_interval = "1h"
|
||||
tests_ticker_interval = '1h'
|
||||
|
||||
|
||||
class BTrade(NamedTuple):
|
||||
@@ -28,11 +28,12 @@ class BTContainer(NamedTuple):
|
||||
roi: float
|
||||
trades: List[BTrade]
|
||||
profit_perc: float
|
||||
trailing_stop: bool = False
|
||||
|
||||
|
||||
def _get_frame_time_from_offset(offset):
|
||||
return ticker_start_time.shift(minutes=(offset * TICKER_INTERVAL_MINUTES[tests_ticker_interval])
|
||||
).datetime.replace(tzinfo=None)
|
||||
return ticker_start_time.shift(minutes=(offset * timeframe_to_minutes(tests_ticker_interval))
|
||||
).datetime
|
||||
|
||||
|
||||
def _build_backtest_dataframe(ticker_with_signals):
|
||||
|
||||
@@ -14,10 +14,10 @@ from freqtrade.tests.optimize import (BTrade, BTContainer, _build_backtest_dataf
|
||||
from freqtrade.tests.conftest import patch_exchange
|
||||
|
||||
|
||||
# Test 0 Minus 8% Close
|
||||
# Test 1 Minus 8% Close
|
||||
# Test with Stop-loss at 1%
|
||||
# TC1: Stop-Loss Triggered 1% loss
|
||||
tc0 = BTContainer(data=[
|
||||
tc1 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 0], # enter trade (signal on last candle)
|
||||
@@ -30,10 +30,10 @@ tc0 = BTContainer(data=[
|
||||
)
|
||||
|
||||
|
||||
# Test 1 Minus 4% Low, minus 1% close
|
||||
# Test 2 Minus 4% Low, minus 1% close
|
||||
# Test with Stop-Loss at 3%
|
||||
# TC2: Stop-Loss Triggered 3% Loss
|
||||
tc1 = BTContainer(data=[
|
||||
tc2 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 0], # enter trade (signal on last candle)
|
||||
@@ -49,11 +49,10 @@ tc1 = BTContainer(data=[
|
||||
# Test 3 Candle drops 4%, Recovers 1%.
|
||||
# Entry Criteria Met
|
||||
# Candle drops 20%
|
||||
# Candle Data for test 3
|
||||
# Test with Stop-Loss at 2%
|
||||
# TC3: Trade-A: Stop-Loss Triggered 2% Loss
|
||||
# Trade-B: Stop-Loss Triggered 2% Loss
|
||||
tc2 = BTContainer(data=[
|
||||
tc3 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 0], # enter trade (signal on last candle)
|
||||
@@ -71,7 +70,7 @@ tc2 = BTContainer(data=[
|
||||
# Candle Data for test 3 – Candle drops 3% Closed 15% up
|
||||
# Test with Stop-loss at 2% ROI 6%
|
||||
# TC4: Stop-Loss Triggered 2% Loss
|
||||
tc3 = BTContainer(data=[
|
||||
tc4 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 0], # enter trade (signal on last candle)
|
||||
@@ -83,10 +82,10 @@ tc3 = BTContainer(data=[
|
||||
trades=[BTrade(sell_reason=SellType.STOP_LOSS, open_tick=1, close_tick=2)]
|
||||
)
|
||||
|
||||
# Test 4 / Drops 0.5% Closes +20%
|
||||
# Test 5 / Drops 0.5% Closes +20%
|
||||
# Set stop-loss at 1% ROI 3%
|
||||
# TC5: ROI triggers 3% Gain
|
||||
tc4 = BTContainer(data=[
|
||||
tc5 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4980, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4980, 4987, 6172, 0, 0], # enter trade (signal on last candle)
|
||||
@@ -99,10 +98,9 @@ tc4 = BTContainer(data=[
|
||||
)
|
||||
|
||||
# Test 6 / Drops 3% / Recovers 6% Positive / Closes 1% positve
|
||||
# Candle Data for test 6
|
||||
# Set stop-loss at 2% ROI at 5%
|
||||
# TC6: Stop-Loss triggers 2% Loss
|
||||
tc5 = BTContainer(data=[
|
||||
tc6 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 0], # enter trade (signal on last candle)
|
||||
@@ -115,10 +113,9 @@ tc5 = BTContainer(data=[
|
||||
)
|
||||
|
||||
# Test 7 - 6% Positive / 1% Negative / Close 1% Positve
|
||||
# Candle Data for test 7
|
||||
# Set stop-loss at 2% ROI at 3%
|
||||
# TC7: ROI Triggers 3% Gain
|
||||
tc6 = BTContainer(data=[
|
||||
tc7 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5025, 4975, 4987, 6172, 1, 0],
|
||||
[1, 5000, 5025, 4975, 4987, 6172, 0, 0],
|
||||
@@ -130,14 +127,47 @@ tc6 = BTContainer(data=[
|
||||
trades=[BTrade(sell_reason=SellType.ROI, open_tick=1, close_tick=2)]
|
||||
)
|
||||
|
||||
|
||||
# Test 8 - trailing_stop should raise so candle 3 causes a stoploss.
|
||||
# Set stop-loss at 10%, ROI at 10% (should not apply)
|
||||
# TC8: Trailing stoploss - stoploss should be adjusted candle 2
|
||||
tc8 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5050, 4950, 5000, 6172, 1, 0],
|
||||
[1, 5000, 5050, 4950, 5000, 6172, 0, 0],
|
||||
[2, 5000, 5250, 4750, 4850, 6172, 0, 0],
|
||||
[3, 4850, 5050, 4650, 4750, 6172, 0, 0],
|
||||
[4, 4750, 4950, 4350, 4750, 6172, 0, 0]],
|
||||
stop_loss=-0.10, roi=0.10, profit_perc=-0.055, trailing_stop=True,
|
||||
trades=[BTrade(sell_reason=SellType.TRAILING_STOP_LOSS, open_tick=1, close_tick=3)]
|
||||
)
|
||||
|
||||
|
||||
# Test 9 - trailing_stop should raise - high and low in same candle.
|
||||
# Candle Data for test 9
|
||||
# Set stop-loss at 10%, ROI at 10% (should not apply)
|
||||
# TC9: Trailing stoploss - stoploss should be adjusted candle 2
|
||||
tc9 = BTContainer(data=[
|
||||
# D O H L C V B S
|
||||
[0, 5000, 5050, 4950, 5000, 6172, 1, 0],
|
||||
[1, 5000, 5050, 4950, 5000, 6172, 0, 0],
|
||||
[2, 5000, 5050, 4950, 5000, 6172, 0, 0],
|
||||
[3, 5000, 5200, 4550, 4850, 6172, 0, 0],
|
||||
[4, 4750, 4950, 4350, 4750, 6172, 0, 0]],
|
||||
stop_loss=-0.10, roi=0.10, profit_perc=-0.064, trailing_stop=True,
|
||||
trades=[BTrade(sell_reason=SellType.TRAILING_STOP_LOSS, open_tick=1, close_tick=3)]
|
||||
)
|
||||
|
||||
TESTS = [
|
||||
tc0,
|
||||
tc1,
|
||||
tc2,
|
||||
tc3,
|
||||
tc4,
|
||||
tc5,
|
||||
tc6,
|
||||
tc7,
|
||||
tc8,
|
||||
tc9,
|
||||
]
|
||||
|
||||
|
||||
@@ -148,8 +178,9 @@ def test_backtest_results(default_conf, fee, mocker, caplog, data) -> None:
|
||||
"""
|
||||
default_conf["stoploss"] = data.stop_loss
|
||||
default_conf["minimal_roi"] = {"0": data.roi}
|
||||
default_conf['ticker_interval'] = tests_ticker_interval
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_fee', MagicMock(return_value=0.0))
|
||||
default_conf["ticker_interval"] = tests_ticker_interval
|
||||
default_conf["trailing_stop"] = data.trailing_stop
|
||||
mocker.patch("freqtrade.exchange.Exchange.get_fee", MagicMock(return_value=0.0))
|
||||
patch_exchange(mocker)
|
||||
frame = _build_backtest_dataframe(data.data)
|
||||
backtesting = Backtesting(default_conf)
|
||||
@@ -157,7 +188,7 @@ def test_backtest_results(default_conf, fee, mocker, caplog, data) -> None:
|
||||
backtesting.advise_sell = lambda a, m: frame
|
||||
caplog.set_level(logging.DEBUG)
|
||||
|
||||
pair = 'UNITTEST/BTC'
|
||||
pair = "UNITTEST/BTC"
|
||||
# Dummy data as we mock the analyze functions
|
||||
data_processed = {pair: DataFrame()}
|
||||
min_date, max_date = get_timeframe({pair: frame})
|
||||
|
||||
@@ -14,10 +14,13 @@ from arrow import Arrow
|
||||
from freqtrade import DependencyException, constants
|
||||
from freqtrade.arguments import Arguments, TimeRange
|
||||
from freqtrade.data import history
|
||||
from freqtrade.data.btanalysis import evaluate_result_multi
|
||||
from freqtrade.data.converter import parse_ticker_dataframe
|
||||
from freqtrade.data.dataprovider import DataProvider
|
||||
from freqtrade.optimize import get_timeframe
|
||||
from freqtrade.optimize.backtesting import (Backtesting, setup_configuration,
|
||||
start)
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.strategy.default_strategy import DefaultStrategy
|
||||
from freqtrade.strategy.interface import SellType
|
||||
from freqtrade.tests.conftest import log_has, patch_exchange
|
||||
@@ -75,7 +78,7 @@ def load_data_test(what):
|
||||
pair[x][5] # Keep old volume
|
||||
] for x in range(0, datalen)
|
||||
]
|
||||
return {'UNITTEST/BTC': parse_ticker_dataframe(data)}
|
||||
return {'UNITTEST/BTC': parse_ticker_dataframe(data, '1m', fill_missing=True)}
|
||||
|
||||
|
||||
def simple_backtest(config, contour, num_results, mocker) -> None:
|
||||
@@ -104,7 +107,7 @@ def simple_backtest(config, contour, num_results, mocker) -> None:
|
||||
def mocked_load_data(datadir, pairs=[], ticker_interval='0m', refresh_pairs=False,
|
||||
timerange=None, exchange=None):
|
||||
tickerdata = history.load_tickerdata_file(datadir, 'UNITTEST/BTC', '1m', timerange=timerange)
|
||||
pairdata = {'UNITTEST/BTC': parse_ticker_dataframe(tickerdata)}
|
||||
pairdata = {'UNITTEST/BTC': parse_ticker_dataframe(tickerdata, '1m', fill_missing=True)}
|
||||
return pairdata
|
||||
|
||||
|
||||
@@ -200,12 +203,15 @@ def test_setup_configuration_without_arguments(mocker, default_conf, caplog) ->
|
||||
|
||||
assert 'timerange' not in config
|
||||
assert 'export' not in config
|
||||
assert 'runmode' in config
|
||||
assert config['runmode'] == RunMode.BACKTEST
|
||||
|
||||
|
||||
def test_setup_configuration_with_arguments(mocker, default_conf, caplog) -> None:
|
||||
def test_setup_bt_configuration_with_arguments(mocker, default_conf, caplog) -> None:
|
||||
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
||||
read_data=json.dumps(default_conf)
|
||||
))
|
||||
mocker.patch('freqtrade.configuration.Configuration._create_datadir', lambda s, c, x: x)
|
||||
|
||||
args = [
|
||||
'--config', 'config.json',
|
||||
@@ -229,6 +235,8 @@ def test_setup_configuration_with_arguments(mocker, default_conf, caplog) -> Non
|
||||
assert 'exchange' in config
|
||||
assert 'pair_whitelist' in config['exchange']
|
||||
assert 'datadir' in config
|
||||
assert config['runmode'] == RunMode.BACKTEST
|
||||
|
||||
assert log_has(
|
||||
'Using data folder: {} ...'.format(config['datadir']),
|
||||
caplog.record_tuples
|
||||
@@ -309,7 +317,28 @@ def test_start(mocker, fee, default_conf, caplog) -> None:
|
||||
assert start_mock.call_count == 1
|
||||
|
||||
|
||||
def test_backtesting_init(mocker, default_conf) -> None:
|
||||
ORDER_TYPES = [
|
||||
{
|
||||
'buy': 'limit',
|
||||
'sell': 'limit',
|
||||
'stoploss': 'limit',
|
||||
'stoploss_on_exchange': False
|
||||
},
|
||||
{
|
||||
'buy': 'limit',
|
||||
'sell': 'limit',
|
||||
'stoploss': 'limit',
|
||||
'stoploss_on_exchange': True
|
||||
}]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("order_types", ORDER_TYPES)
|
||||
def test_backtesting_init(mocker, default_conf, order_types) -> None:
|
||||
"""
|
||||
Check that stoploss_on_exchange is set to False while backtesting
|
||||
since backtesting assumes a perfect stoploss anyway.
|
||||
"""
|
||||
default_conf["order_types"] = order_types
|
||||
patch_exchange(mocker)
|
||||
get_fee = mocker.patch('freqtrade.exchange.Exchange.get_fee', MagicMock(return_value=0.5))
|
||||
backtesting = Backtesting(default_conf)
|
||||
@@ -318,19 +347,21 @@ def test_backtesting_init(mocker, default_conf) -> None:
|
||||
assert callable(backtesting.strategy.tickerdata_to_dataframe)
|
||||
assert callable(backtesting.advise_buy)
|
||||
assert callable(backtesting.advise_sell)
|
||||
assert isinstance(backtesting.strategy.dp, DataProvider)
|
||||
get_fee.assert_called()
|
||||
assert backtesting.fee == 0.5
|
||||
assert not backtesting.strategy.order_types["stoploss_on_exchange"]
|
||||
|
||||
|
||||
def test_tickerdata_to_dataframe(default_conf, mocker) -> None:
|
||||
def test_tickerdata_to_dataframe_bt(default_conf, mocker) -> None:
|
||||
patch_exchange(mocker)
|
||||
timerange = TimeRange(None, 'line', 0, -100)
|
||||
tick = history.load_tickerdata_file(None, 'UNITTEST/BTC', '1m', timerange=timerange)
|
||||
tickerlist = {'UNITTEST/BTC': parse_ticker_dataframe(tick)}
|
||||
tickerlist = {'UNITTEST/BTC': parse_ticker_dataframe(tick, '1m', fill_missing=True)}
|
||||
|
||||
backtesting = Backtesting(default_conf)
|
||||
data = backtesting.strategy.tickerdata_to_dataframe(tickerlist)
|
||||
assert len(data['UNITTEST/BTC']) == 99
|
||||
assert len(data['UNITTEST/BTC']) == 102
|
||||
|
||||
# Load strategy to compare the result between Backtesting function and strategy are the same
|
||||
strategy = DefaultStrategy(default_conf)
|
||||
@@ -340,6 +371,7 @@ def test_tickerdata_to_dataframe(default_conf, mocker) -> None:
|
||||
|
||||
def test_generate_text_table(default_conf, mocker):
|
||||
patch_exchange(mocker)
|
||||
default_conf['max_open_trades'] = 2
|
||||
backtesting = Backtesting(default_conf)
|
||||
|
||||
results = pd.DataFrame(
|
||||
@@ -355,13 +387,13 @@ def test_generate_text_table(default_conf, mocker):
|
||||
|
||||
result_str = (
|
||||
'| pair | buy count | avg profit % | cum profit % | '
|
||||
'total profit BTC | avg duration | profit | loss |\n'
|
||||
'tot profit BTC | tot profit % | avg duration | profit | loss |\n'
|
||||
'|:--------|------------:|---------------:|---------------:|'
|
||||
'-------------------:|:---------------|---------:|-------:|\n'
|
||||
'| ETH/BTC | 2 | 15.00 | 30.00 | '
|
||||
'0.60000000 | 0:20:00 | 2 | 0 |\n'
|
||||
'| TOTAL | 2 | 15.00 | 30.00 | '
|
||||
'0.60000000 | 0:20:00 | 2 | 0 |'
|
||||
'-----------------:|---------------:|:---------------|---------:|-------:|\n'
|
||||
'| ETH/BTC | 2 | 15.00 | 30.00 | '
|
||||
'0.60000000 | 15.00 | 0:20:00 | 2 | 0 |\n'
|
||||
'| TOTAL | 2 | 15.00 | 30.00 | '
|
||||
'0.60000000 | 15.00 | 0:20:00 | 2 | 0 |'
|
||||
)
|
||||
assert backtesting._generate_text_table(data={'ETH/BTC': {}}, results=results) == result_str
|
||||
|
||||
@@ -397,6 +429,7 @@ def test_generate_text_table_strategyn(default_conf, mocker):
|
||||
Test Backtesting.generate_text_table_sell_reason() method
|
||||
"""
|
||||
patch_exchange(mocker)
|
||||
default_conf['max_open_trades'] = 2
|
||||
backtesting = Backtesting(default_conf)
|
||||
results = {}
|
||||
results['ETH/BTC'] = pd.DataFrame(
|
||||
@@ -424,13 +457,13 @@ def test_generate_text_table_strategyn(default_conf, mocker):
|
||||
|
||||
result_str = (
|
||||
'| Strategy | buy count | avg profit % | cum profit % '
|
||||
'| total profit BTC | avg duration | profit | loss |\n'
|
||||
'| tot profit BTC | tot profit % | avg duration | profit | loss |\n'
|
||||
'|:-----------|------------:|---------------:|---------------:'
|
||||
'|-------------------:|:---------------|---------:|-------:|\n'
|
||||
'|-----------------:|---------------:|:---------------|---------:|-------:|\n'
|
||||
'| ETH/BTC | 3 | 20.00 | 60.00 '
|
||||
'| 1.10000000 | 0:17:00 | 3 | 0 |\n'
|
||||
'| 1.10000000 | 30.00 | 0:17:00 | 3 | 0 |\n'
|
||||
'| LTC/BTC | 3 | 30.00 | 90.00 '
|
||||
'| 1.30000000 | 0:20:00 | 3 | 0 |'
|
||||
'| 1.30000000 | 45.00 | 0:20:00 | 3 | 0 |'
|
||||
)
|
||||
print(backtesting._generate_text_table_strategy(all_results=results))
|
||||
assert backtesting._generate_text_table_strategy(all_results=results) == result_str
|
||||
@@ -442,7 +475,7 @@ def test_backtesting_start(default_conf, mocker, caplog) -> None:
|
||||
|
||||
mocker.patch('freqtrade.data.history.load_data', mocked_load_data)
|
||||
mocker.patch('freqtrade.optimize.get_timeframe', get_timeframe)
|
||||
mocker.patch('freqtrade.exchange.Exchange.refresh_tickers', MagicMock())
|
||||
mocker.patch('freqtrade.exchange.Exchange.refresh_latest_ohlcv', MagicMock())
|
||||
patch_exchange(mocker)
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.optimize.backtesting.Backtesting',
|
||||
@@ -477,7 +510,7 @@ def test_backtesting_start_no_data(default_conf, mocker, caplog) -> None:
|
||||
|
||||
mocker.patch('freqtrade.data.history.load_data', MagicMock(return_value={}))
|
||||
mocker.patch('freqtrade.optimize.get_timeframe', get_timeframe)
|
||||
mocker.patch('freqtrade.exchange.Exchange.refresh_tickers', MagicMock())
|
||||
mocker.patch('freqtrade.exchange.Exchange.refresh_latest_ohlcv', MagicMock())
|
||||
patch_exchange(mocker)
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.optimize.backtesting.Backtesting',
|
||||
@@ -526,13 +559,14 @@ def test_backtest(default_conf, fee, mocker) -> None:
|
||||
{'pair': [pair, pair],
|
||||
'profit_percent': [0.0, 0.0],
|
||||
'profit_abs': [0.0, 0.0],
|
||||
'open_time': [Arrow(2018, 1, 29, 18, 40, 0).datetime,
|
||||
Arrow(2018, 1, 30, 3, 30, 0).datetime],
|
||||
'close_time': [Arrow(2018, 1, 29, 22, 35, 0).datetime,
|
||||
Arrow(2018, 1, 30, 4, 15, 0).datetime],
|
||||
'open_time': pd.to_datetime([Arrow(2018, 1, 29, 18, 40, 0).datetime,
|
||||
Arrow(2018, 1, 30, 3, 30, 0).datetime], utc=True
|
||||
),
|
||||
'close_time': pd.to_datetime([Arrow(2018, 1, 29, 22, 35, 0).datetime,
|
||||
Arrow(2018, 1, 30, 4, 10, 0).datetime], utc=True),
|
||||
'open_index': [78, 184],
|
||||
'close_index': [125, 193],
|
||||
'trade_duration': [235, 45],
|
||||
'close_index': [125, 192],
|
||||
'trade_duration': [235, 40],
|
||||
'open_at_end': [False, False],
|
||||
'open_rate': [0.104445, 0.10302485],
|
||||
'close_rate': [0.104969, 0.103541],
|
||||
@@ -593,7 +627,7 @@ def test_processed(default_conf, mocker) -> None:
|
||||
|
||||
def test_backtest_pricecontours(default_conf, fee, mocker) -> None:
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
|
||||
tests = [['raise', 18], ['lower', 0], ['sine', 19]]
|
||||
tests = [['raise', 19], ['lower', 0], ['sine', 18]]
|
||||
# We need to enable sell-signal - otherwise it sells on ROI!!
|
||||
default_conf['experimental'] = {"use_sell_signal": True}
|
||||
|
||||
@@ -651,40 +685,32 @@ def test_backtest_alternate_buy_sell(default_conf, fee, mocker):
|
||||
assert len(results.loc[results.open_at_end]) == 0
|
||||
|
||||
|
||||
def test_backtest_multi_pair(default_conf, fee, mocker):
|
||||
|
||||
def evaluate_result_multi(results, freq, max_open_trades):
|
||||
# Find overlapping trades by expanding each trade once per period
|
||||
# and then counting overlaps
|
||||
dates = [pd.Series(pd.date_range(row[1].open_time, row[1].close_time, freq=freq))
|
||||
for row in results[['open_time', 'close_time']].iterrows()]
|
||||
deltas = [len(x) for x in dates]
|
||||
dates = pd.Series(pd.concat(dates).values, name='date')
|
||||
df2 = pd.DataFrame(np.repeat(results.values, deltas, axis=0), columns=results.columns)
|
||||
|
||||
df2 = df2.astype(dtype={"open_time": "datetime64", "close_time": "datetime64"})
|
||||
df2 = pd.concat([dates, df2], axis=1)
|
||||
df2 = df2.set_index('date')
|
||||
df_final = df2.resample(freq)[['pair']].count()
|
||||
return df_final[df_final['pair'] > max_open_trades]
|
||||
@pytest.mark.parametrize("pair", ['ADA/BTC', 'LTC/BTC'])
|
||||
@pytest.mark.parametrize("tres", [0, 20, 30])
|
||||
def test_backtest_multi_pair(default_conf, fee, mocker, tres, pair):
|
||||
|
||||
def _trend_alternate_hold(dataframe=None, metadata=None):
|
||||
"""
|
||||
Buy every 8th candle - sell every other 8th -2 (hold on to pairs a bit)
|
||||
Buy every xth candle - sell every other xth -2 (hold on to pairs a bit)
|
||||
"""
|
||||
multi = 8
|
||||
if metadata['pair'] in('ETH/BTC', 'LTC/BTC'):
|
||||
multi = 20
|
||||
else:
|
||||
multi = 18
|
||||
dataframe['buy'] = np.where(dataframe.index % multi == 0, 1, 0)
|
||||
dataframe['sell'] = np.where((dataframe.index + multi - 2) % multi == 0, 1, 0)
|
||||
if metadata['pair'] in('ETH/BTC', 'LTC/BTC'):
|
||||
dataframe['buy'] = dataframe['buy'].shift(-4)
|
||||
dataframe['sell'] = dataframe['sell'].shift(-4)
|
||||
return dataframe
|
||||
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
|
||||
patch_exchange(mocker)
|
||||
|
||||
pairs = ['ADA/BTC', 'DASH/BTC', 'ETH/BTC', 'LTC/BTC', 'NXT/BTC']
|
||||
data = history.load_data(datadir=None, ticker_interval='5m', pairs=pairs)
|
||||
# Only use 500 lines to increase performance
|
||||
data = trim_dictlist(data, -500)
|
||||
|
||||
# Remove data for one pair from the beginning of the data
|
||||
data[pair] = data[pair][tres:]
|
||||
# We need to enable sell-signal - otherwise it sells on ROI!!
|
||||
default_conf['experimental'] = {"use_sell_signal": True}
|
||||
default_conf['ticker_interval'] = '5m'
|
||||
|
||||
@@ -7,6 +7,7 @@ from typing import List
|
||||
from freqtrade.edge import PairInfo
|
||||
from freqtrade.arguments import Arguments
|
||||
from freqtrade.optimize.edge_cli import (EdgeCli, setup_configuration, start)
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.tests.conftest import log_has, patch_exchange
|
||||
|
||||
|
||||
@@ -26,6 +27,8 @@ def test_setup_configuration_without_arguments(mocker, default_conf, caplog) ->
|
||||
]
|
||||
|
||||
config = setup_configuration(get_args(args))
|
||||
assert config['runmode'] == RunMode.EDGECLI
|
||||
|
||||
assert 'max_open_trades' in config
|
||||
assert 'stake_currency' in config
|
||||
assert 'stake_amount' in config
|
||||
@@ -46,10 +49,11 @@ def test_setup_configuration_without_arguments(mocker, default_conf, caplog) ->
|
||||
assert 'stoploss_range' not in config
|
||||
|
||||
|
||||
def test_setup_configuration_with_arguments(mocker, edge_conf, caplog) -> None:
|
||||
def test_setup_edge_configuration_with_arguments(mocker, edge_conf, caplog) -> None:
|
||||
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
||||
read_data=json.dumps(edge_conf)
|
||||
))
|
||||
mocker.patch('freqtrade.configuration.Configuration._create_datadir', lambda s, c, x: x)
|
||||
|
||||
args = [
|
||||
'--config', 'config.json',
|
||||
@@ -69,6 +73,7 @@ def test_setup_configuration_with_arguments(mocker, edge_conf, caplog) -> None:
|
||||
assert 'exchange' in config
|
||||
assert 'pair_whitelist' in config['exchange']
|
||||
assert 'datadir' in config
|
||||
assert config['runmode'] == RunMode.EDGECLI
|
||||
assert log_has(
|
||||
'Using data folder: {} ...'.format(config['datadir']),
|
||||
caplog.record_tuples
|
||||
|
||||
@@ -9,7 +9,8 @@ import pytest
|
||||
from freqtrade.data.converter import parse_ticker_dataframe
|
||||
from freqtrade.data.history import load_tickerdata_file
|
||||
from freqtrade.optimize.hyperopt import Hyperopt, start
|
||||
from freqtrade.resolvers import StrategyResolver
|
||||
from freqtrade.optimize.default_hyperopt import DefaultHyperOpts
|
||||
from freqtrade.resolvers import StrategyResolver, HyperOptResolver
|
||||
from freqtrade.tests.conftest import log_has, patch_exchange
|
||||
from freqtrade.tests.optimize.test_backtesting import get_args
|
||||
|
||||
@@ -38,6 +39,28 @@ def create_trials(mocker, hyperopt) -> None:
|
||||
return [{'loss': 1, 'result': 'foo', 'params': {}}]
|
||||
|
||||
|
||||
def test_hyperoptresolver(mocker, default_conf, caplog) -> None:
|
||||
|
||||
mocker.patch(
|
||||
'freqtrade.configuration.Configuration._load_config_file',
|
||||
lambda *args, **kwargs: default_conf
|
||||
)
|
||||
hyperopts = DefaultHyperOpts
|
||||
delattr(hyperopts, 'populate_buy_trend')
|
||||
delattr(hyperopts, 'populate_sell_trend')
|
||||
mocker.patch(
|
||||
'freqtrade.resolvers.hyperopt_resolver.HyperOptResolver._load_hyperopt',
|
||||
MagicMock(return_value=hyperopts)
|
||||
)
|
||||
x = HyperOptResolver(default_conf, ).hyperopt
|
||||
assert not hasattr(x, 'populate_buy_trend')
|
||||
assert not hasattr(x, 'populate_sell_trend')
|
||||
assert log_has("Custom Hyperopt does not provide populate_sell_trend. "
|
||||
"Using populate_sell_trend from DefaultStrategy.", caplog.record_tuples)
|
||||
assert log_has("Custom Hyperopt does not provide populate_buy_trend. "
|
||||
"Using populate_buy_trend from DefaultStrategy.", caplog.record_tuples)
|
||||
|
||||
|
||||
def test_start(mocker, default_conf, caplog) -> None:
|
||||
start_mock = MagicMock()
|
||||
mocker.patch(
|
||||
@@ -201,7 +224,7 @@ def test_start_calls_optimizer(mocker, default_conf, caplog) -> None:
|
||||
hyperopt.start()
|
||||
parallel.assert_called_once()
|
||||
|
||||
assert 'Best result:\nfoo result\nwith values:\n{}' in caplog.text
|
||||
assert 'Best result:\nfoo result\nwith values:\n\n' in caplog.text
|
||||
assert dumper.called
|
||||
|
||||
|
||||
@@ -243,7 +266,7 @@ def test_has_space(hyperopt):
|
||||
|
||||
def test_populate_indicators(hyperopt) -> None:
|
||||
tick = load_tickerdata_file(None, 'UNITTEST/BTC', '1m')
|
||||
tickerlist = {'UNITTEST/BTC': parse_ticker_dataframe(tick)}
|
||||
tickerlist = {'UNITTEST/BTC': parse_ticker_dataframe(tick, '1m', fill_missing=True)}
|
||||
dataframes = hyperopt.strategy.tickerdata_to_dataframe(tickerlist)
|
||||
dataframe = hyperopt.custom_hyperopt.populate_indicators(dataframes['UNITTEST/BTC'],
|
||||
{'pair': 'UNITTEST/BTC'})
|
||||
@@ -256,7 +279,7 @@ def test_populate_indicators(hyperopt) -> None:
|
||||
|
||||
def test_buy_strategy_generator(hyperopt) -> None:
|
||||
tick = load_tickerdata_file(None, 'UNITTEST/BTC', '1m')
|
||||
tickerlist = {'UNITTEST/BTC': parse_ticker_dataframe(tick)}
|
||||
tickerlist = {'UNITTEST/BTC': parse_ticker_dataframe(tick, '1m', fill_missing=True)}
|
||||
dataframes = hyperopt.strategy.tickerdata_to_dataframe(tickerlist)
|
||||
dataframe = hyperopt.custom_hyperopt.populate_indicators(dataframes['UNITTEST/BTC'],
|
||||
{'pair': 'UNITTEST/BTC'})
|
||||
@@ -312,6 +335,15 @@ def test_generate_optimizer(mocker, default_conf) -> None:
|
||||
'mfi-enabled': False,
|
||||
'rsi-enabled': False,
|
||||
'trigger': 'macd_cross_signal',
|
||||
'sell-adx-value': 0,
|
||||
'sell-fastd-value': 75,
|
||||
'sell-mfi-value': 0,
|
||||
'sell-rsi-value': 0,
|
||||
'sell-adx-enabled': False,
|
||||
'sell-fastd-enabled': True,
|
||||
'sell-mfi-enabled': False,
|
||||
'sell-rsi-enabled': False,
|
||||
'sell-trigger': 'macd_cross_signal',
|
||||
'roi_t1': 60.0,
|
||||
'roi_t2': 30.0,
|
||||
'roi_t3': 20.0,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
# pragma pylint: disable=missing-docstring, protected-access, C0103
|
||||
from freqtrade import optimize, constants
|
||||
from freqtrade import optimize
|
||||
from freqtrade.arguments import TimeRange
|
||||
from freqtrade.data import history
|
||||
from freqtrade.misc import timeframe_to_minutes
|
||||
from freqtrade.strategy.default_strategy import DefaultStrategy
|
||||
from freqtrade.tests.conftest import log_has, patch_exchange
|
||||
|
||||
@@ -30,13 +31,14 @@ def test_validate_backtest_data_warn(default_conf, mocker, caplog) -> None:
|
||||
history.load_data(
|
||||
datadir=None,
|
||||
ticker_interval='1m',
|
||||
pairs=['UNITTEST/BTC']
|
||||
pairs=['UNITTEST/BTC'],
|
||||
fill_up_missing=False
|
||||
)
|
||||
)
|
||||
min_date, max_date = optimize.get_timeframe(data)
|
||||
caplog.clear()
|
||||
assert optimize.validate_backtest_data(data, min_date, max_date,
|
||||
constants.TICKER_INTERVAL_MINUTES["1m"])
|
||||
timeframe_to_minutes('1m'))
|
||||
assert len(caplog.record_tuples) == 1
|
||||
assert log_has(
|
||||
"UNITTEST/BTC has missing frames: expected 14396, got 13680, that's 716 missing values",
|
||||
@@ -60,5 +62,5 @@ def test_validate_backtest_data(default_conf, mocker, caplog) -> None:
|
||||
min_date, max_date = optimize.get_timeframe(data)
|
||||
caplog.clear()
|
||||
assert not optimize.validate_backtest_data(data, min_date, max_date,
|
||||
constants.TICKER_INTERVAL_MINUTES["5m"])
|
||||
timeframe_to_minutes('5m'))
|
||||
assert len(caplog.record_tuples) == 0
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# pragma pylint: disable=missing-docstring,C0103,protected-access
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
from unittest.mock import MagicMock, PropertyMock
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.constants import AVAILABLE_PAIRLISTS
|
||||
@@ -33,7 +33,7 @@ def whitelist_conf(default_conf):
|
||||
|
||||
def test_load_pairlist_noexist(mocker, markets, default_conf):
|
||||
freqtradebot = get_patched_freqtradebot(mocker, default_conf)
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_markets', markets)
|
||||
mocker.patch('freqtrade.exchange.Exchange.markets', PropertyMock(return_value=markets))
|
||||
with pytest.raises(ImportError,
|
||||
match=r"Impossible to load Pairlist 'NonexistingPairList'."
|
||||
r" This class does not exist or contains Python code errors"):
|
||||
@@ -44,7 +44,7 @@ def test_refresh_market_pair_not_in_whitelist(mocker, markets, whitelist_conf):
|
||||
|
||||
freqtradebot = get_patched_freqtradebot(mocker, whitelist_conf)
|
||||
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_markets', markets)
|
||||
mocker.patch('freqtrade.exchange.Exchange.markets', PropertyMock(return_value=markets))
|
||||
freqtradebot.pairlists.refresh_pairlist()
|
||||
# List ordered by BaseVolume
|
||||
whitelist = ['ETH/BTC', 'TKN/BTC']
|
||||
@@ -58,7 +58,7 @@ def test_refresh_market_pair_not_in_whitelist(mocker, markets, whitelist_conf):
|
||||
def test_refresh_pairlists(mocker, markets, whitelist_conf):
|
||||
freqtradebot = get_patched_freqtradebot(mocker, whitelist_conf)
|
||||
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_markets', markets)
|
||||
mocker.patch('freqtrade.exchange.Exchange.markets', PropertyMock(return_value=markets))
|
||||
freqtradebot.pairlists.refresh_pairlist()
|
||||
# List ordered by BaseVolume
|
||||
whitelist = ['ETH/BTC', 'TKN/BTC']
|
||||
@@ -73,14 +73,14 @@ def test_refresh_pairlist_dynamic(mocker, markets, tickers, whitelist_conf):
|
||||
}
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_markets=markets,
|
||||
markets=PropertyMock(return_value=markets),
|
||||
get_tickers=tickers,
|
||||
exchange_has=MagicMock(return_value=True)
|
||||
)
|
||||
freqtradebot = get_patched_freqtradebot(mocker, whitelist_conf)
|
||||
|
||||
# argument: use the whitelist dynamically by exchange-volume
|
||||
whitelist = ['ETH/BTC', 'TKN/BTC']
|
||||
whitelist = ['ETH/BTC', 'TKN/BTC', 'BTT/BTC']
|
||||
freqtradebot.pairlists.refresh_pairlist()
|
||||
|
||||
assert whitelist == freqtradebot.pairlists.whitelist
|
||||
@@ -96,7 +96,7 @@ def test_refresh_pairlist_dynamic(mocker, markets, tickers, whitelist_conf):
|
||||
|
||||
def test_VolumePairList_refresh_empty(mocker, markets_empty, whitelist_conf):
|
||||
freqtradebot = get_patched_freqtradebot(mocker, whitelist_conf)
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_markets', markets_empty)
|
||||
mocker.patch('freqtrade.exchange.Exchange.markets', PropertyMock(return_value=markets_empty))
|
||||
|
||||
# argument: use the whitelist dynamically by exchange-volume
|
||||
whitelist = []
|
||||
@@ -107,28 +107,27 @@ def test_VolumePairList_refresh_empty(mocker, markets_empty, whitelist_conf):
|
||||
assert set(whitelist) == set(pairslist)
|
||||
|
||||
|
||||
def test_VolumePairList_whitelist_gen(mocker, whitelist_conf, markets, tickers) -> None:
|
||||
@pytest.mark.parametrize("precision_filter,base_currency,key,whitelist_result", [
|
||||
(False, "BTC", "quoteVolume", ['ETH/BTC', 'TKN/BTC', 'BTT/BTC']),
|
||||
(False, "BTC", "bidVolume", ['BTT/BTC', 'TKN/BTC', 'ETH/BTC']),
|
||||
(False, "USDT", "quoteVolume", ['ETH/USDT', 'LTC/USDT']),
|
||||
(False, "ETH", "quoteVolume", []), # this replaces tests that were removed from test_exchange
|
||||
(True, "BTC", "quoteVolume", ["ETH/BTC", "TKN/BTC"]),
|
||||
(True, "BTC", "bidVolume", ["TKN/BTC", "ETH/BTC"])
|
||||
])
|
||||
def test_VolumePairList_whitelist_gen(mocker, whitelist_conf, markets, tickers, base_currency, key,
|
||||
whitelist_result, precision_filter) -> None:
|
||||
whitelist_conf['pairlist']['method'] = 'VolumePairList'
|
||||
mocker.patch('freqtrade.exchange.Exchange.exchange_has', MagicMock(return_value=True))
|
||||
freqtrade = get_patched_freqtradebot(mocker, whitelist_conf)
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_markets', markets)
|
||||
mocker.patch('freqtrade.exchange.Exchange.markets', PropertyMock(return_value=markets))
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_tickers', tickers)
|
||||
mocker.patch('freqtrade.exchange.Exchange.symbol_price_prec', lambda s, p, r: round(r, 8))
|
||||
|
||||
# Test to retrieved BTC sorted on quoteVolume (default)
|
||||
whitelist = freqtrade.pairlists._gen_pair_whitelist(base_currency='BTC', key='quoteVolume')
|
||||
assert whitelist == ['ETH/BTC', 'TKN/BTC', 'BLK/BTC', 'LTC/BTC']
|
||||
|
||||
# Test to retrieve BTC sorted on bidVolume
|
||||
whitelist = freqtrade.pairlists._gen_pair_whitelist(base_currency='BTC', key='bidVolume')
|
||||
assert whitelist == ['LTC/BTC', 'TKN/BTC', 'ETH/BTC', 'BLK/BTC']
|
||||
|
||||
# Test with USDT sorted on quoteVolume (default)
|
||||
whitelist = freqtrade.pairlists._gen_pair_whitelist(base_currency='USDT', key='quoteVolume')
|
||||
assert whitelist == ['TKN/USDT', 'ETH/USDT', 'LTC/USDT', 'BLK/USDT']
|
||||
|
||||
# Test with ETH (our fixture does not have ETH, so result should be empty)
|
||||
whitelist = freqtrade.pairlists._gen_pair_whitelist(base_currency='ETH', key='quoteVolume')
|
||||
assert whitelist == []
|
||||
freqtrade.pairlists._precision_filter = precision_filter
|
||||
freqtrade.config['stake_currency'] = base_currency
|
||||
whitelist = freqtrade.pairlists._gen_pair_whitelist(base_currency=base_currency, key=key)
|
||||
assert whitelist == whitelist_result
|
||||
|
||||
|
||||
def test_gen_pair_whitelist_not_supported(mocker, default_conf, tickers) -> None:
|
||||
@@ -145,7 +144,7 @@ def test_gen_pair_whitelist_not_supported(mocker, default_conf, tickers) -> None
|
||||
@pytest.mark.parametrize("pairlist", AVAILABLE_PAIRLISTS)
|
||||
def test_pairlist_class(mocker, whitelist_conf, markets, pairlist):
|
||||
whitelist_conf['pairlist']['method'] = pairlist
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_markets', markets)
|
||||
mocker.patch('freqtrade.exchange.Exchange.markets', PropertyMock(return_value=markets))
|
||||
mocker.patch('freqtrade.exchange.Exchange.exchange_has', MagicMock(return_value=True))
|
||||
freqtrade = get_patched_freqtradebot(mocker, whitelist_conf)
|
||||
|
||||
@@ -154,17 +153,24 @@ def test_pairlist_class(mocker, whitelist_conf, markets, pairlist):
|
||||
assert isinstance(freqtrade.pairlists.whitelist, list)
|
||||
assert isinstance(freqtrade.pairlists.blacklist, list)
|
||||
|
||||
whitelist = ['ETH/BTC', 'TKN/BTC']
|
||||
|
||||
@pytest.mark.parametrize("pairlist", AVAILABLE_PAIRLISTS)
|
||||
@pytest.mark.parametrize("whitelist,log_message", [
|
||||
(['ETH/BTC', 'TKN/BTC'], ""),
|
||||
(['ETH/BTC', 'TKN/BTC', 'TRX/ETH'], "is not compatible with exchange"), # TRX/ETH wrong stake
|
||||
(['ETH/BTC', 'TKN/BTC', 'BCH/BTC'], "is not compatible with exchange"), # BCH/BTC not available
|
||||
(['ETH/BTC', 'TKN/BTC', 'BLK/BTC'], "is not compatible with exchange"), # BLK/BTC in blacklist
|
||||
(['ETH/BTC', 'TKN/BTC', 'LTC/BTC'], "Market is not active") # LTC/BTC is inactive
|
||||
])
|
||||
def test_validate_whitelist(mocker, whitelist_conf, markets, pairlist, whitelist, caplog,
|
||||
log_message):
|
||||
whitelist_conf['pairlist']['method'] = pairlist
|
||||
mocker.patch('freqtrade.exchange.Exchange.markets', PropertyMock(return_value=markets))
|
||||
mocker.patch('freqtrade.exchange.Exchange.exchange_has', MagicMock(return_value=True))
|
||||
freqtrade = get_patched_freqtradebot(mocker, whitelist_conf)
|
||||
caplog.clear()
|
||||
|
||||
new_whitelist = freqtrade.pairlists._validate_whitelist(whitelist)
|
||||
|
||||
assert set(whitelist) == set(new_whitelist)
|
||||
|
||||
whitelist = ['ETH/BTC', 'TKN/BTC', 'TRX/ETH']
|
||||
new_whitelist = freqtrade.pairlists._validate_whitelist(whitelist)
|
||||
# TRX/ETH was removed
|
||||
assert set(['ETH/BTC', 'TKN/BTC']) == set(new_whitelist)
|
||||
|
||||
whitelist = ['ETH/BTC', 'TKN/BTC', 'BLK/BTC']
|
||||
new_whitelist = freqtrade.pairlists._validate_whitelist(whitelist)
|
||||
# BLK/BTC is in blacklist ...
|
||||
assert set(['ETH/BTC', 'TKN/BTC']) == set(new_whitelist)
|
||||
assert set(new_whitelist) == set(['ETH/BTC', 'TKN/BTC'])
|
||||
assert log_message in caplog.text
|
||||
|
||||
@@ -8,7 +8,7 @@ import pytest
|
||||
from requests.exceptions import RequestException
|
||||
|
||||
from freqtrade.rpc.fiat_convert import CryptoFiat, CryptoToFiatConverter
|
||||
from freqtrade.tests.conftest import log_has, patch_coinmarketcap
|
||||
from freqtrade.tests.conftest import log_has
|
||||
|
||||
|
||||
def test_pair_convertion_object():
|
||||
@@ -40,7 +40,6 @@ def test_pair_convertion_object():
|
||||
|
||||
|
||||
def test_fiat_convert_is_supported(mocker):
|
||||
patch_coinmarketcap(mocker)
|
||||
fiat_convert = CryptoToFiatConverter()
|
||||
assert fiat_convert._is_supported_fiat(fiat='USD') is True
|
||||
assert fiat_convert._is_supported_fiat(fiat='usd') is True
|
||||
@@ -49,7 +48,6 @@ def test_fiat_convert_is_supported(mocker):
|
||||
|
||||
|
||||
def test_fiat_convert_add_pair(mocker):
|
||||
patch_coinmarketcap(mocker)
|
||||
|
||||
fiat_convert = CryptoToFiatConverter()
|
||||
|
||||
@@ -72,8 +70,6 @@ def test_fiat_convert_add_pair(mocker):
|
||||
|
||||
|
||||
def test_fiat_convert_find_price(mocker):
|
||||
patch_coinmarketcap(mocker)
|
||||
|
||||
fiat_convert = CryptoToFiatConverter()
|
||||
|
||||
with pytest.raises(ValueError, match=r'The fiat ABC is not supported.'):
|
||||
@@ -93,15 +89,12 @@ def test_fiat_convert_find_price(mocker):
|
||||
|
||||
def test_fiat_convert_unsupported_crypto(mocker, caplog):
|
||||
mocker.patch('freqtrade.rpc.fiat_convert.CryptoToFiatConverter._cryptomap', return_value=[])
|
||||
patch_coinmarketcap(mocker)
|
||||
fiat_convert = CryptoToFiatConverter()
|
||||
assert fiat_convert._find_price(crypto_symbol='CRYPTO_123', fiat_symbol='EUR') == 0.0
|
||||
assert log_has('unsupported crypto-symbol CRYPTO_123 - returning 0.0', caplog.record_tuples)
|
||||
|
||||
|
||||
def test_fiat_convert_get_price(mocker):
|
||||
patch_coinmarketcap(mocker)
|
||||
|
||||
mocker.patch('freqtrade.rpc.fiat_convert.CryptoToFiatConverter._find_price',
|
||||
return_value=28000.0)
|
||||
|
||||
@@ -117,7 +110,7 @@ def test_fiat_convert_get_price(mocker):
|
||||
assert fiat_convert._pairs[0].crypto_symbol == 'BTC'
|
||||
assert fiat_convert._pairs[0].fiat_symbol == 'USD'
|
||||
assert fiat_convert._pairs[0].price == 28000.0
|
||||
assert fiat_convert._pairs[0]._expiration is not 0
|
||||
assert fiat_convert._pairs[0]._expiration != 0
|
||||
assert len(fiat_convert._pairs) == 1
|
||||
|
||||
# Verify the cached is used
|
||||
@@ -134,21 +127,18 @@ def test_fiat_convert_get_price(mocker):
|
||||
|
||||
|
||||
def test_fiat_convert_same_currencies(mocker):
|
||||
patch_coinmarketcap(mocker)
|
||||
fiat_convert = CryptoToFiatConverter()
|
||||
|
||||
assert fiat_convert.get_price(crypto_symbol='USD', fiat_symbol='USD') == 1.0
|
||||
|
||||
|
||||
def test_fiat_convert_two_FIAT(mocker):
|
||||
patch_coinmarketcap(mocker)
|
||||
fiat_convert = CryptoToFiatConverter()
|
||||
|
||||
assert fiat_convert.get_price(crypto_symbol='USD', fiat_symbol='EUR') == 0.0
|
||||
|
||||
|
||||
def test_loadcryptomap(mocker):
|
||||
patch_coinmarketcap(mocker)
|
||||
|
||||
fiat_convert = CryptoToFiatConverter()
|
||||
assert len(fiat_convert._cryptomap) == 2
|
||||
@@ -174,7 +164,6 @@ def test_fiat_init_network_exception(mocker):
|
||||
|
||||
def test_fiat_convert_without_network(mocker):
|
||||
# Because CryptoToFiatConverter is a Singleton we reset the value of _coinmarketcap
|
||||
patch_coinmarketcap(mocker)
|
||||
|
||||
fiat_convert = CryptoToFiatConverter()
|
||||
|
||||
@@ -205,7 +194,6 @@ def test_fiat_invalid_response(mocker, caplog):
|
||||
|
||||
|
||||
def test_convert_amount(mocker):
|
||||
patch_coinmarketcap(mocker)
|
||||
mocker.patch('freqtrade.rpc.fiat_convert.CryptoToFiatConverter.get_price', return_value=12345.0)
|
||||
|
||||
fiat_convert = CryptoToFiatConverter()
|
||||
|
||||
@@ -2,19 +2,20 @@
|
||||
# pragma pylint: disable=invalid-sequence-index, invalid-name, too-many-arguments
|
||||
|
||||
from datetime import datetime
|
||||
from unittest.mock import MagicMock, ANY
|
||||
from unittest.mock import ANY, MagicMock, PropertyMock
|
||||
|
||||
import pytest
|
||||
from numpy import isnan
|
||||
|
||||
from freqtrade import TemporaryError, DependencyException
|
||||
from freqtrade import DependencyException, TemporaryError
|
||||
from freqtrade.edge import PairInfo
|
||||
from freqtrade.freqtradebot import FreqtradeBot
|
||||
from freqtrade.persistence import Trade
|
||||
from freqtrade.rpc import RPC, RPCException
|
||||
from freqtrade.rpc.fiat_convert import CryptoToFiatConverter
|
||||
from freqtrade.state import State
|
||||
from freqtrade.tests.conftest import patch_exchange
|
||||
from freqtrade.tests.test_freqtradebot import patch_get_signal
|
||||
from freqtrade.tests.conftest import patch_coinmarketcap, patch_exchange
|
||||
|
||||
|
||||
# Functions for recurrent object patching
|
||||
@@ -27,14 +28,13 @@ def prec_satoshi(a, b) -> float:
|
||||
|
||||
# Unit tests
|
||||
def test_rpc_trade_status(default_conf, ticker, fee, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
_load_markets=MagicMock(return_value={}),
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(return_value=markets)
|
||||
)
|
||||
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
@@ -51,14 +51,19 @@ def test_rpc_trade_status(default_conf, ticker, fee, markets, mocker) -> None:
|
||||
assert {
|
||||
'trade_id': 1,
|
||||
'pair': 'ETH/BTC',
|
||||
'market_url': 'https://bittrex.com/Market/Index?MarketName=BTC-ETH',
|
||||
'base_currency': 'BTC',
|
||||
'date': ANY,
|
||||
'open_rate': 1.099e-05,
|
||||
'close_rate': None,
|
||||
'current_rate': 1.098e-05,
|
||||
'amount': 90.99181074,
|
||||
'stake_amount': 0.001,
|
||||
'close_profit': None,
|
||||
'current_profit': -0.59,
|
||||
'stop_loss': 0.0,
|
||||
'initial_stop_loss': 0.0,
|
||||
'initial_stop_loss_pct': None,
|
||||
'stop_loss_pct': None,
|
||||
'open_order': '(limit buy rem=0.00000000)'
|
||||
} == results[0]
|
||||
|
||||
@@ -72,27 +77,31 @@ def test_rpc_trade_status(default_conf, ticker, fee, markets, mocker) -> None:
|
||||
assert {
|
||||
'trade_id': 1,
|
||||
'pair': 'ETH/BTC',
|
||||
'market_url': 'https://bittrex.com/Market/Index?MarketName=BTC-ETH',
|
||||
'base_currency': 'BTC',
|
||||
'date': ANY,
|
||||
'open_rate': 1.099e-05,
|
||||
'close_rate': None,
|
||||
'current_rate': ANY,
|
||||
'amount': 90.99181074,
|
||||
'stake_amount': 0.001,
|
||||
'close_profit': None,
|
||||
'current_profit': ANY,
|
||||
'stop_loss': 0.0,
|
||||
'initial_stop_loss': 0.0,
|
||||
'initial_stop_loss_pct': None,
|
||||
'stop_loss_pct': None,
|
||||
'open_order': '(limit buy rem=0.00000000)'
|
||||
} == results[0]
|
||||
|
||||
|
||||
def test_rpc_status_table(default_conf, ticker, fee, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(return_value=markets)
|
||||
)
|
||||
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
@@ -121,14 +130,13 @@ def test_rpc_status_table(default_conf, ticker, fee, markets, mocker) -> None:
|
||||
|
||||
def test_rpc_daily_profit(default_conf, update, ticker, fee,
|
||||
limit_buy_order, limit_sell_order, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker, value={'price_usd': 15000.0})
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(return_value=markets)
|
||||
)
|
||||
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
@@ -174,7 +182,6 @@ def test_rpc_trade_statistics(default_conf, ticker, ticker_sell_up, fee,
|
||||
'freqtrade.rpc.fiat_convert.Market',
|
||||
ticker=MagicMock(return_value={'price_usd': 15000.0}),
|
||||
)
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.rpc.CryptoToFiatConverter._find_price', return_value=15000.0)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
@@ -182,7 +189,7 @@ def test_rpc_trade_statistics(default_conf, ticker, ticker_sell_up, fee,
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(return_value=markets)
|
||||
)
|
||||
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
@@ -270,7 +277,7 @@ def test_rpc_trade_statistics_closed(mocker, default_conf, ticker, fee, markets,
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(return_value=markets)
|
||||
)
|
||||
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
@@ -332,7 +339,6 @@ def test_rpc_balance_handle(default_conf, mocker):
|
||||
'freqtrade.rpc.fiat_convert.Market',
|
||||
ticker=MagicMock(return_value={'price_usd': 15000.0}),
|
||||
)
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.rpc.CryptoToFiatConverter._find_price', return_value=15000.0)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
@@ -362,7 +368,6 @@ def test_rpc_balance_handle(default_conf, mocker):
|
||||
|
||||
|
||||
def test_rpc_start(mocker, default_conf) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
mocker.patch.multiple(
|
||||
@@ -385,7 +390,6 @@ def test_rpc_start(mocker, default_conf) -> None:
|
||||
|
||||
|
||||
def test_rpc_stop(mocker, default_conf) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
mocker.patch.multiple(
|
||||
@@ -408,8 +412,26 @@ def test_rpc_stop(mocker, default_conf) -> None:
|
||||
assert freqtradebot.state == State.STOPPED
|
||||
|
||||
|
||||
def test_rpc_stopbuy(mocker, default_conf) -> None:
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_ticker=MagicMock()
|
||||
)
|
||||
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
patch_get_signal(freqtradebot, (True, False))
|
||||
rpc = RPC(freqtradebot)
|
||||
freqtradebot.state = State.RUNNING
|
||||
|
||||
assert freqtradebot.config['max_open_trades'] != 0
|
||||
result = rpc._rpc_stopbuy()
|
||||
assert {'status': 'No more buy will occur from now. Run /reload_conf to reset.'} == result
|
||||
assert freqtradebot.config['max_open_trades'] == 0
|
||||
|
||||
|
||||
def test_rpc_forcesell(default_conf, ticker, fee, mocker, markets) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
|
||||
@@ -426,7 +448,7 @@ def test_rpc_forcesell(default_conf, ticker, fee, mocker, markets) -> None:
|
||||
}
|
||||
),
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(return_value=markets)
|
||||
)
|
||||
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
@@ -510,7 +532,6 @@ def test_rpc_forcesell(default_conf, ticker, fee, mocker, markets) -> None:
|
||||
|
||||
def test_performance_handle(default_conf, ticker, limit_buy_order, fee,
|
||||
limit_sell_order, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
mocker.patch.multiple(
|
||||
@@ -518,7 +539,7 @@ def test_performance_handle(default_conf, ticker, limit_buy_order, fee,
|
||||
get_balances=MagicMock(return_value=ticker),
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(return_value=markets)
|
||||
)
|
||||
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
@@ -546,7 +567,6 @@ def test_performance_handle(default_conf, ticker, limit_buy_order, fee,
|
||||
|
||||
|
||||
def test_rpc_count(mocker, default_conf, ticker, fee, markets) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
mocker.patch.multiple(
|
||||
@@ -554,27 +574,24 @@ def test_rpc_count(mocker, default_conf, ticker, fee, markets) -> None:
|
||||
get_balances=MagicMock(return_value=ticker),
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(return_value=markets)
|
||||
)
|
||||
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
patch_get_signal(freqtradebot, (True, False))
|
||||
rpc = RPC(freqtradebot)
|
||||
|
||||
trades = rpc._rpc_count()
|
||||
nb_trades = len(trades)
|
||||
assert nb_trades == 0
|
||||
counts = rpc._rpc_count()
|
||||
assert counts["current"] == 0
|
||||
|
||||
# Create some test data
|
||||
freqtradebot.create_trade()
|
||||
trades = rpc._rpc_count()
|
||||
nb_trades = len(trades)
|
||||
assert nb_trades == 1
|
||||
counts = rpc._rpc_count()
|
||||
assert counts["current"] == 1
|
||||
|
||||
|
||||
def test_rpcforcebuy(mocker, default_conf, ticker, fee, markets, limit_buy_order) -> None:
|
||||
default_conf['forcebuy_enable'] = True
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
buy_mm = MagicMock(return_value={'id': limit_buy_order['id']})
|
||||
@@ -583,7 +600,7 @@ def test_rpcforcebuy(mocker, default_conf, ticker, fee, markets, limit_buy_order
|
||||
get_balances=MagicMock(return_value=ticker),
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets,
|
||||
markets=PropertyMock(return_value=markets),
|
||||
buy=buy_mm
|
||||
)
|
||||
|
||||
@@ -623,7 +640,6 @@ def test_rpcforcebuy(mocker, default_conf, ticker, fee, markets, limit_buy_order
|
||||
def test_rpcforcebuy_stopped(mocker, default_conf) -> None:
|
||||
default_conf['forcebuy_enable'] = True
|
||||
default_conf['initial_state'] = 'stopped'
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
|
||||
@@ -636,7 +652,6 @@ def test_rpcforcebuy_stopped(mocker, default_conf) -> None:
|
||||
|
||||
|
||||
def test_rpcforcebuy_disabled(mocker, default_conf) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
|
||||
@@ -649,7 +664,6 @@ def test_rpcforcebuy_disabled(mocker, default_conf) -> None:
|
||||
|
||||
|
||||
def test_rpc_whitelist(mocker, default_conf) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
|
||||
@@ -661,7 +675,6 @@ def test_rpc_whitelist(mocker, default_conf) -> None:
|
||||
|
||||
|
||||
def test_rpc_whitelist_dynamic(mocker, default_conf) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
default_conf['pairlist'] = {'method': 'VolumePairList',
|
||||
'config': {'number_assets': 4}
|
||||
@@ -675,3 +688,51 @@ def test_rpc_whitelist_dynamic(mocker, default_conf) -> None:
|
||||
assert ret['method'] == 'VolumePairList'
|
||||
assert ret['length'] == 4
|
||||
assert ret['whitelist'] == default_conf['exchange']['pair_whitelist']
|
||||
|
||||
|
||||
def test_rpc_blacklist(mocker, default_conf) -> None:
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
rpc = RPC(freqtradebot)
|
||||
ret = rpc._rpc_blacklist(None)
|
||||
assert ret['method'] == 'StaticPairList'
|
||||
assert len(ret['blacklist']) == 2
|
||||
assert ret['blacklist'] == default_conf['exchange']['pair_blacklist']
|
||||
assert ret['blacklist'] == ['DOGE/BTC', 'HOT/BTC']
|
||||
|
||||
ret = rpc._rpc_blacklist(["ETH/BTC"])
|
||||
assert ret['method'] == 'StaticPairList'
|
||||
assert len(ret['blacklist']) == 3
|
||||
assert ret['blacklist'] == default_conf['exchange']['pair_blacklist']
|
||||
assert ret['blacklist'] == ['DOGE/BTC', 'HOT/BTC', 'ETH/BTC']
|
||||
|
||||
|
||||
def test_rpc_edge_disabled(mocker, default_conf) -> None:
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
rpc = RPC(freqtradebot)
|
||||
with pytest.raises(RPCException, match=r'Edge is not enabled.'):
|
||||
rpc._rpc_edge()
|
||||
|
||||
|
||||
def test_rpc_edge_enabled(mocker, edge_conf) -> None:
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
|
||||
mocker.patch('freqtrade.edge.Edge._cached_pairs', mocker.PropertyMock(
|
||||
return_value={
|
||||
'E/F': PairInfo(-0.02, 0.66, 3.71, 0.50, 1.71, 10, 60),
|
||||
}
|
||||
))
|
||||
freqtradebot = FreqtradeBot(edge_conf)
|
||||
|
||||
rpc = RPC(freqtradebot)
|
||||
ret = rpc._rpc_edge()
|
||||
|
||||
assert len(ret) == 1
|
||||
assert ret[0]['Pair'] == 'E/F'
|
||||
assert ret[0]['Winrate'] == 0.66
|
||||
assert ret[0]['Expectancy'] == 1.71
|
||||
assert ret[0]['Stoploss'] == -0.02
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
from random import randint
|
||||
from unittest.mock import MagicMock, ANY
|
||||
from random import choice, randint
|
||||
from string import ascii_uppercase
|
||||
from unittest.mock import MagicMock, PropertyMock
|
||||
|
||||
import arrow
|
||||
import pytest
|
||||
@@ -13,16 +14,16 @@ from telegram import Chat, Message, Update
|
||||
from telegram.error import NetworkError
|
||||
|
||||
from freqtrade import __version__
|
||||
from freqtrade.edge import PairInfo
|
||||
from freqtrade.freqtradebot import FreqtradeBot
|
||||
from freqtrade.persistence import Trade
|
||||
from freqtrade.rpc import RPCMessageType
|
||||
from freqtrade.rpc.telegram import Telegram, authorized_only
|
||||
from freqtrade.strategy.interface import SellType
|
||||
from freqtrade.state import State
|
||||
from freqtrade.strategy.interface import SellType
|
||||
from freqtrade.tests.conftest import (get_patched_freqtradebot, log_has,
|
||||
patch_exchange)
|
||||
from freqtrade.tests.test_freqtradebot import patch_get_signal
|
||||
from freqtrade.tests.conftest import patch_coinmarketcap
|
||||
|
||||
|
||||
class DummyCls(Telegram):
|
||||
@@ -74,7 +75,7 @@ def test_init(default_conf, mocker, caplog) -> None:
|
||||
message_str = "rpc.telegram is listening for following commands: [['status'], ['profit'], " \
|
||||
"['balance'], ['start'], ['stop'], ['forcesell'], ['forcebuy'], " \
|
||||
"['performance'], ['daily'], ['count'], ['reload_conf'], " \
|
||||
"['whitelist'], ['help'], ['version']]"
|
||||
"['stopbuy'], ['whitelist'], ['blacklist'], ['edge'], ['help'], ['version']]"
|
||||
|
||||
assert log_has(message_str, caplog.record_tuples)
|
||||
|
||||
@@ -90,7 +91,6 @@ def test_cleanup(default_conf, mocker) -> None:
|
||||
|
||||
|
||||
def test_authorized_only(default_conf, mocker, caplog) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker, None)
|
||||
|
||||
chat = Chat(0, 0)
|
||||
@@ -118,7 +118,6 @@ def test_authorized_only(default_conf, mocker, caplog) -> None:
|
||||
|
||||
|
||||
def test_authorized_only_unauthorized(default_conf, mocker, caplog) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker, None)
|
||||
chat = Chat(0xdeadbeef, 0)
|
||||
update = Update(randint(1, 100))
|
||||
@@ -145,7 +144,6 @@ def test_authorized_only_unauthorized(default_conf, mocker, caplog) -> None:
|
||||
|
||||
|
||||
def test_authorized_only_exception(default_conf, mocker, caplog) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
|
||||
update = Update(randint(1, 100))
|
||||
@@ -178,14 +176,12 @@ def test_status(default_conf, update, mocker, fee, ticker, markets) -> None:
|
||||
default_conf['telegram']['enabled'] = False
|
||||
default_conf['telegram']['chat_id'] = 123
|
||||
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_ticker=ticker,
|
||||
get_pair_detail_url=MagicMock(),
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(markets)
|
||||
)
|
||||
msg_mock = MagicMock()
|
||||
status_table = MagicMock()
|
||||
@@ -195,14 +191,19 @@ def test_status(default_conf, update, mocker, fee, ticker, markets) -> None:
|
||||
_rpc_trade_status=MagicMock(return_value=[{
|
||||
'trade_id': 1,
|
||||
'pair': 'ETH/BTC',
|
||||
'market_url': 'https://bittrex.com/Market/Index?MarketName=BTC-ETH',
|
||||
'base_currency': 'BTC',
|
||||
'date': arrow.utcnow(),
|
||||
'open_rate': 1.099e-05,
|
||||
'close_rate': None,
|
||||
'current_rate': 1.098e-05,
|
||||
'amount': 90.99181074,
|
||||
'stake_amount': 90.99181074,
|
||||
'close_profit': None,
|
||||
'current_profit': -0.59,
|
||||
'initial_stop_loss': 1.098e-05,
|
||||
'stop_loss': 1.099e-05,
|
||||
'initial_stop_loss_pct': -0.05,
|
||||
'stop_loss_pct': -0.01,
|
||||
'open_order': '(limit buy rem=0.00000000)'
|
||||
}]),
|
||||
_status_table=status_table,
|
||||
@@ -228,13 +229,12 @@ def test_status(default_conf, update, mocker, fee, ticker, markets) -> None:
|
||||
|
||||
|
||||
def test_status_handle(default_conf, update, ticker, fee, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(markets)
|
||||
)
|
||||
msg_mock = MagicMock()
|
||||
status_table = MagicMock()
|
||||
@@ -269,19 +269,25 @@ def test_status_handle(default_conf, update, ticker, fee, markets, mocker) -> No
|
||||
# Trigger status while we have a fulfilled order for the open trade
|
||||
telegram._status(bot=MagicMock(), update=update)
|
||||
|
||||
# close_rate should not be included in the message as the trade is not closed
|
||||
# and no line should be empty
|
||||
lines = msg_mock.call_args_list[0][0][0].split('\n')
|
||||
assert '' not in lines
|
||||
assert 'Close Rate' not in ''.join(lines)
|
||||
assert 'Close Profit' not in ''.join(lines)
|
||||
|
||||
assert msg_mock.call_count == 1
|
||||
assert '[ETH/BTC]' in msg_mock.call_args_list[0][0][0]
|
||||
assert 'ETH/BTC' in msg_mock.call_args_list[0][0][0]
|
||||
|
||||
|
||||
def test_status_table_handle(default_conf, update, ticker, fee, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_ticker=ticker,
|
||||
buy=MagicMock(return_value={'id': 'mocked_order_id'}),
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(markets)
|
||||
)
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
@@ -326,7 +332,6 @@ def test_status_table_handle(default_conf, update, ticker, fee, markets, mocker)
|
||||
|
||||
def test_daily_handle(default_conf, update, ticker, limit_buy_order, fee,
|
||||
limit_sell_order, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker, value={'price_usd': 15000.0})
|
||||
patch_exchange(mocker)
|
||||
mocker.patch(
|
||||
'freqtrade.rpc.rpc.CryptoToFiatConverter._find_price',
|
||||
@@ -336,7 +341,7 @@ def test_daily_handle(default_conf, update, ticker, limit_buy_order, fee,
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(markets)
|
||||
)
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
@@ -397,7 +402,6 @@ def test_daily_handle(default_conf, update, ticker, limit_buy_order, fee,
|
||||
|
||||
|
||||
def test_daily_wrong_input(default_conf, update, ticker, mocker) -> None:
|
||||
patch_coinmarketcap(mocker, value={'price_usd': 15000.0})
|
||||
patch_exchange(mocker)
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
@@ -433,14 +437,13 @@ def test_daily_wrong_input(default_conf, update, ticker, mocker) -> None:
|
||||
|
||||
def test_profit_handle(default_conf, update, ticker, ticker_sell_up, fee,
|
||||
limit_buy_order, limit_sell_order, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker, value={'price_usd': 15000.0})
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.rpc.CryptoToFiatConverter._find_price', return_value=15000.0)
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(markets)
|
||||
)
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
@@ -538,7 +541,6 @@ def test_telegram_balance_handle(default_conf, update, mocker) -> None:
|
||||
'last': 0.1,
|
||||
}
|
||||
|
||||
patch_coinmarketcap(mocker, value={'price_usd': 15000.0})
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_balances', return_value=mock_balance)
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_ticker', side_effect=mock_ticker)
|
||||
|
||||
@@ -587,6 +589,45 @@ def test_balance_handle_empty_response(default_conf, update, mocker) -> None:
|
||||
assert 'all balances are zero' in result
|
||||
|
||||
|
||||
def test_balance_handle_too_large_response(default_conf, update, mocker) -> None:
|
||||
balances = []
|
||||
for i in range(100):
|
||||
curr = choice(ascii_uppercase) + choice(ascii_uppercase) + choice(ascii_uppercase)
|
||||
balances.append({
|
||||
'currency': curr,
|
||||
'available': 1.0,
|
||||
'pending': 0.5,
|
||||
'balance': i,
|
||||
'est_btc': 1
|
||||
})
|
||||
mocker.patch('freqtrade.rpc.rpc.RPC._rpc_balance', return_value={
|
||||
'currencies': balances,
|
||||
'total': 100.0,
|
||||
'symbol': 100.0,
|
||||
'value': 1000.0,
|
||||
})
|
||||
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.rpc.telegram.Telegram',
|
||||
_init=MagicMock(),
|
||||
_send_msg=msg_mock
|
||||
)
|
||||
|
||||
freqtradebot = get_patched_freqtradebot(mocker, default_conf)
|
||||
patch_get_signal(freqtradebot, (True, False))
|
||||
|
||||
telegram = Telegram(freqtradebot)
|
||||
|
||||
telegram._balance(bot=MagicMock(), update=update)
|
||||
assert msg_mock.call_count > 1
|
||||
# Test if wrap happens around 4000 -
|
||||
# and each single currency-output is around 120 characters long so we need
|
||||
# an offset to avoid random test failures
|
||||
assert len(msg_mock.call_args_list[0][0][0]) < 4096
|
||||
assert len(msg_mock.call_args_list[0][0][0]) > (4096 - 120)
|
||||
|
||||
|
||||
def test_start_handle(default_conf, update, mocker) -> None:
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
@@ -625,7 +666,6 @@ def test_start_handle_already_running(default_conf, update, mocker) -> None:
|
||||
|
||||
|
||||
def test_stop_handle(default_conf, update, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.rpc.telegram.Telegram',
|
||||
@@ -645,7 +685,6 @@ def test_stop_handle(default_conf, update, mocker) -> None:
|
||||
|
||||
|
||||
def test_stop_handle_already_stopped(default_conf, update, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.rpc.telegram.Telegram',
|
||||
@@ -664,8 +703,26 @@ def test_stop_handle_already_stopped(default_conf, update, mocker) -> None:
|
||||
assert 'already stopped' in msg_mock.call_args_list[0][0][0]
|
||||
|
||||
|
||||
def test_stopbuy_handle(default_conf, update, mocker) -> None:
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.rpc.telegram.Telegram',
|
||||
_init=MagicMock(),
|
||||
_send_msg=msg_mock
|
||||
)
|
||||
|
||||
freqtradebot = get_patched_freqtradebot(mocker, default_conf)
|
||||
telegram = Telegram(freqtradebot)
|
||||
|
||||
assert freqtradebot.config['max_open_trades'] != 0
|
||||
telegram._stopbuy(bot=MagicMock(), update=update)
|
||||
assert freqtradebot.config['max_open_trades'] == 0
|
||||
assert msg_mock.call_count == 1
|
||||
assert 'No more buy will occur from now. Run /reload_conf to reset.' \
|
||||
in msg_mock.call_args_list[0][0][0]
|
||||
|
||||
|
||||
def test_reload_conf_handle(default_conf, update, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.rpc.telegram.Telegram',
|
||||
@@ -686,7 +743,6 @@ def test_reload_conf_handle(default_conf, update, mocker) -> None:
|
||||
|
||||
def test_forcesell_handle(default_conf, update, ticker, fee,
|
||||
ticker_sell_up, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker, value={'price_usd': 15000.0})
|
||||
mocker.patch('freqtrade.rpc.rpc.CryptoToFiatConverter._find_price', return_value=15000.0)
|
||||
rpc_mock = mocker.patch('freqtrade.rpc.telegram.Telegram.send_msg', MagicMock())
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram._init', MagicMock())
|
||||
@@ -695,7 +751,8 @@ def test_forcesell_handle(default_conf, update, ticker, fee,
|
||||
_load_markets=MagicMock(return_value={}),
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(return_value=markets),
|
||||
validate_pairs=MagicMock(return_value={})
|
||||
)
|
||||
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
@@ -721,7 +778,6 @@ def test_forcesell_handle(default_conf, update, ticker, fee,
|
||||
'exchange': 'Bittrex',
|
||||
'pair': 'ETH/BTC',
|
||||
'gain': 'profit',
|
||||
'market_url': 'https://bittrex.com/Market/Index?MarketName=BTC-ETH',
|
||||
'limit': 1.172e-05,
|
||||
'amount': 90.99181073703367,
|
||||
'open_rate': 1.099e-05,
|
||||
@@ -736,7 +792,6 @@ def test_forcesell_handle(default_conf, update, ticker, fee,
|
||||
|
||||
def test_forcesell_down_handle(default_conf, update, ticker, fee,
|
||||
ticker_sell_down, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker, value={'price_usd': 15000.0})
|
||||
mocker.patch('freqtrade.rpc.fiat_convert.CryptoToFiatConverter._find_price',
|
||||
return_value=15000.0)
|
||||
rpc_mock = mocker.patch('freqtrade.rpc.telegram.Telegram.send_msg', MagicMock())
|
||||
@@ -746,7 +801,8 @@ def test_forcesell_down_handle(default_conf, update, ticker, fee,
|
||||
_load_markets=MagicMock(return_value={}),
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(return_value=markets),
|
||||
validate_pairs=MagicMock(return_value={})
|
||||
)
|
||||
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
@@ -776,7 +832,6 @@ def test_forcesell_down_handle(default_conf, update, ticker, fee,
|
||||
'exchange': 'Bittrex',
|
||||
'pair': 'ETH/BTC',
|
||||
'gain': 'loss',
|
||||
'market_url': 'https://bittrex.com/Market/Index?MarketName=BTC-ETH',
|
||||
'limit': 1.044e-05,
|
||||
'amount': 90.99181073703367,
|
||||
'open_rate': 1.099e-05,
|
||||
@@ -790,18 +845,17 @@ def test_forcesell_down_handle(default_conf, update, ticker, fee,
|
||||
|
||||
|
||||
def test_forcesell_all_handle(default_conf, update, ticker, fee, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker, value={'price_usd': 15000.0})
|
||||
patch_exchange(mocker)
|
||||
mocker.patch('freqtrade.rpc.fiat_convert.CryptoToFiatConverter._find_price',
|
||||
return_value=15000.0)
|
||||
rpc_mock = mocker.patch('freqtrade.rpc.telegram.Telegram.send_msg', MagicMock())
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram._init', MagicMock())
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_pair_detail_url', MagicMock())
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(return_value=markets),
|
||||
validate_pairs=MagicMock(return_value={})
|
||||
)
|
||||
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
@@ -823,7 +877,6 @@ def test_forcesell_all_handle(default_conf, update, ticker, fee, markets, mocker
|
||||
'exchange': 'Bittrex',
|
||||
'pair': 'ETH/BTC',
|
||||
'gain': 'loss',
|
||||
'market_url': ANY,
|
||||
'limit': 1.098e-05,
|
||||
'amount': 90.99181073703367,
|
||||
'open_rate': 1.099e-05,
|
||||
@@ -837,7 +890,6 @@ def test_forcesell_all_handle(default_conf, update, ticker, fee, markets, mocker
|
||||
|
||||
|
||||
def test_forcesell_handle_invalid(default_conf, update, mocker) -> None:
|
||||
patch_coinmarketcap(mocker, value={'price_usd': 15000.0})
|
||||
mocker.patch('freqtrade.rpc.fiat_convert.CryptoToFiatConverter._find_price',
|
||||
return_value=15000.0)
|
||||
msg_mock = MagicMock()
|
||||
@@ -877,14 +929,14 @@ def test_forcesell_handle_invalid(default_conf, update, mocker) -> None:
|
||||
|
||||
|
||||
def test_forcebuy_handle(default_conf, update, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker, value={'price_usd': 15000.0})
|
||||
mocker.patch('freqtrade.rpc.rpc.CryptoToFiatConverter._find_price', return_value=15000.0)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram._send_msg', MagicMock())
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram._init', MagicMock())
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
_load_markets=MagicMock(return_value={}),
|
||||
get_markets=markets
|
||||
markets=PropertyMock(markets),
|
||||
validate_pairs=MagicMock(return_value={})
|
||||
)
|
||||
fbuy_mock = MagicMock(return_value=None)
|
||||
mocker.patch('freqtrade.rpc.RPC._rpc_forcebuy', fbuy_mock)
|
||||
@@ -913,14 +965,14 @@ def test_forcebuy_handle(default_conf, update, markets, mocker) -> None:
|
||||
|
||||
|
||||
def test_forcebuy_handle_exception(default_conf, update, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker, value={'price_usd': 15000.0})
|
||||
mocker.patch('freqtrade.rpc.rpc.CryptoToFiatConverter._find_price', return_value=15000.0)
|
||||
rpc_mock = mocker.patch('freqtrade.rpc.telegram.Telegram._send_msg', MagicMock())
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram._init', MagicMock())
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
_load_markets=MagicMock(return_value={}),
|
||||
get_markets=markets
|
||||
markets=PropertyMock(markets),
|
||||
validate_pairs=MagicMock(return_value={})
|
||||
)
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
patch_get_signal(freqtradebot, (True, False))
|
||||
@@ -935,7 +987,6 @@ def test_forcebuy_handle_exception(default_conf, update, markets, mocker) -> Non
|
||||
|
||||
def test_performance_handle(default_conf, update, ticker, fee,
|
||||
limit_buy_order, limit_sell_order, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
@@ -947,7 +998,8 @@ def test_performance_handle(default_conf, update, ticker, fee,
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_ticker=ticker,
|
||||
get_fee=fee,
|
||||
get_markets=markets
|
||||
markets=PropertyMock(markets),
|
||||
validate_pairs=MagicMock(return_value={})
|
||||
)
|
||||
mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock())
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
@@ -974,7 +1026,6 @@ def test_performance_handle(default_conf, update, ticker, fee,
|
||||
|
||||
|
||||
def test_count_handle(default_conf, update, ticker, fee, markets, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
patch_exchange(mocker)
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
@@ -986,7 +1037,7 @@ def test_count_handle(default_conf, update, ticker, fee, markets, mocker) -> Non
|
||||
'freqtrade.exchange.Exchange',
|
||||
get_ticker=ticker,
|
||||
buy=MagicMock(return_value={'id': 'mocked_order_id'}),
|
||||
get_markets=markets
|
||||
markets=PropertyMock(markets)
|
||||
)
|
||||
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
|
||||
freqtradebot = FreqtradeBot(default_conf)
|
||||
@@ -1015,7 +1066,6 @@ def test_count_handle(default_conf, update, ticker, fee, markets, mocker) -> Non
|
||||
|
||||
|
||||
def test_whitelist_static(default_conf, update, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.rpc.telegram.Telegram',
|
||||
@@ -1033,7 +1083,6 @@ def test_whitelist_static(default_conf, update, mocker) -> None:
|
||||
|
||||
|
||||
def test_whitelist_dynamic(default_conf, update, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.rpc.telegram.Telegram',
|
||||
@@ -1054,8 +1103,71 @@ def test_whitelist_dynamic(default_conf, update, mocker) -> None:
|
||||
in msg_mock.call_args_list[0][0][0])
|
||||
|
||||
|
||||
def test_blacklist_static(default_conf, update, mocker) -> None:
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.rpc.telegram.Telegram',
|
||||
_init=MagicMock(),
|
||||
_send_msg=msg_mock
|
||||
)
|
||||
freqtradebot = get_patched_freqtradebot(mocker, default_conf)
|
||||
|
||||
telegram = Telegram(freqtradebot)
|
||||
|
||||
telegram._blacklist(bot=MagicMock(), update=update, args=[])
|
||||
assert msg_mock.call_count == 1
|
||||
assert ("Blacklist contains 2 pairs\n`DOGE/BTC, HOT/BTC`"
|
||||
in msg_mock.call_args_list[0][0][0])
|
||||
|
||||
msg_mock.reset_mock()
|
||||
telegram._blacklist(bot=MagicMock(), update=update, args=["ETH/BTC"])
|
||||
assert msg_mock.call_count == 1
|
||||
assert ("Blacklist contains 3 pairs\n`DOGE/BTC, HOT/BTC, ETH/BTC`"
|
||||
in msg_mock.call_args_list[0][0][0])
|
||||
assert freqtradebot.pairlists.blacklist == ["DOGE/BTC", "HOT/BTC", "ETH/BTC"]
|
||||
|
||||
|
||||
def test_edge_disabled(default_conf, update, mocker) -> None:
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.rpc.telegram.Telegram',
|
||||
_init=MagicMock(),
|
||||
_send_msg=msg_mock
|
||||
)
|
||||
|
||||
freqtradebot = get_patched_freqtradebot(mocker, default_conf)
|
||||
|
||||
telegram = Telegram(freqtradebot)
|
||||
|
||||
telegram._edge(bot=MagicMock(), update=update)
|
||||
assert msg_mock.call_count == 1
|
||||
assert "Edge is not enabled." in msg_mock.call_args_list[0][0][0]
|
||||
|
||||
|
||||
def test_edge_enabled(edge_conf, update, mocker) -> None:
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch('freqtrade.edge.Edge._cached_pairs', mocker.PropertyMock(
|
||||
return_value={
|
||||
'E/F': PairInfo(-0.01, 0.66, 3.71, 0.50, 1.71, 10, 60),
|
||||
}
|
||||
))
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.rpc.telegram.Telegram',
|
||||
_init=MagicMock(),
|
||||
_send_msg=msg_mock
|
||||
)
|
||||
|
||||
freqtradebot = get_patched_freqtradebot(mocker, edge_conf)
|
||||
|
||||
telegram = Telegram(freqtradebot)
|
||||
|
||||
telegram._edge(bot=MagicMock(), update=update)
|
||||
assert msg_mock.call_count == 1
|
||||
assert '<b>Edge only validated following pairs:</b>\n<pre>' in msg_mock.call_args_list[0][0][0]
|
||||
assert 'Pair Winrate Expectancy Stoploss' in msg_mock.call_args_list[0][0][0]
|
||||
|
||||
|
||||
def test_help_handle(default_conf, update, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.rpc.telegram.Telegram',
|
||||
@@ -1072,7 +1184,6 @@ def test_help_handle(default_conf, update, mocker) -> None:
|
||||
|
||||
|
||||
def test_version_handle(default_conf, update, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
msg_mock = MagicMock()
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.rpc.telegram.Telegram',
|
||||
@@ -1100,7 +1211,6 @@ def test_send_msg_buy_notification(default_conf, mocker) -> None:
|
||||
'type': RPCMessageType.BUY_NOTIFICATION,
|
||||
'exchange': 'Bittrex',
|
||||
'pair': 'ETH/BTC',
|
||||
'market_url': 'https://bittrex.com/Market/Index?MarketName=BTC-ETH',
|
||||
'limit': 1.099e-05,
|
||||
'stake_amount': 0.001,
|
||||
'stake_amount_fiat': 0.0,
|
||||
@@ -1108,7 +1218,7 @@ def test_send_msg_buy_notification(default_conf, mocker) -> None:
|
||||
'fiat_currency': 'USD'
|
||||
})
|
||||
assert msg_mock.call_args[0][0] \
|
||||
== '*Bittrex:* Buying [ETH/BTC](https://bittrex.com/Market/Index?MarketName=BTC-ETH)\n' \
|
||||
== '*Bittrex:* Buying ETH/BTC\n' \
|
||||
'with limit `0.00001099\n' \
|
||||
'(0.001000 BTC,0.000 USD)`'
|
||||
|
||||
@@ -1129,7 +1239,6 @@ def test_send_msg_sell_notification(default_conf, mocker) -> None:
|
||||
'exchange': 'Binance',
|
||||
'pair': 'KEY/ETH',
|
||||
'gain': 'loss',
|
||||
'market_url': 'https://www.binance.com/tradeDetail.html?symbol=KEY_ETH',
|
||||
'limit': 3.201e-05,
|
||||
'amount': 1333.3333333333335,
|
||||
'open_rate': 7.5e-05,
|
||||
@@ -1141,8 +1250,7 @@ def test_send_msg_sell_notification(default_conf, mocker) -> None:
|
||||
'sell_reason': SellType.STOP_LOSS.value
|
||||
})
|
||||
assert msg_mock.call_args[0][0] \
|
||||
== ('*Binance:* Selling [KEY/ETH]'
|
||||
'(https://www.binance.com/tradeDetail.html?symbol=KEY_ETH)\n'
|
||||
== ('*Binance:* Selling KEY/ETH\n'
|
||||
'*Limit:* `0.00003201`\n'
|
||||
'*Amount:* `1333.33333333`\n'
|
||||
'*Open Rate:* `0.00007500`\n'
|
||||
@@ -1156,7 +1264,6 @@ def test_send_msg_sell_notification(default_conf, mocker) -> None:
|
||||
'exchange': 'Binance',
|
||||
'pair': 'KEY/ETH',
|
||||
'gain': 'loss',
|
||||
'market_url': 'https://www.binance.com/tradeDetail.html?symbol=KEY_ETH',
|
||||
'limit': 3.201e-05,
|
||||
'amount': 1333.3333333333335,
|
||||
'open_rate': 7.5e-05,
|
||||
@@ -1167,8 +1274,7 @@ def test_send_msg_sell_notification(default_conf, mocker) -> None:
|
||||
'sell_reason': SellType.STOP_LOSS.value
|
||||
})
|
||||
assert msg_mock.call_args[0][0] \
|
||||
== ('*Binance:* Selling [KEY/ETH]'
|
||||
'(https://www.binance.com/tradeDetail.html?symbol=KEY_ETH)\n'
|
||||
== ('*Binance:* Selling KEY/ETH\n'
|
||||
'*Limit:* `0.00003201`\n'
|
||||
'*Amount:* `1333.33333333`\n'
|
||||
'*Open Rate:* `0.00007500`\n'
|
||||
@@ -1256,7 +1362,6 @@ def test_send_msg_buy_notification_no_fiat(default_conf, mocker) -> None:
|
||||
'type': RPCMessageType.BUY_NOTIFICATION,
|
||||
'exchange': 'Bittrex',
|
||||
'pair': 'ETH/BTC',
|
||||
'market_url': 'https://bittrex.com/Market/Index?MarketName=BTC-ETH',
|
||||
'limit': 1.099e-05,
|
||||
'stake_amount': 0.001,
|
||||
'stake_amount_fiat': 0.0,
|
||||
@@ -1264,7 +1369,7 @@ def test_send_msg_buy_notification_no_fiat(default_conf, mocker) -> None:
|
||||
'fiat_currency': None
|
||||
})
|
||||
assert msg_mock.call_args[0][0] \
|
||||
== '*Bittrex:* Buying [ETH/BTC](https://bittrex.com/Market/Index?MarketName=BTC-ETH)\n' \
|
||||
== '*Bittrex:* Buying ETH/BTC\n' \
|
||||
'with limit `0.00001099\n' \
|
||||
'(0.001000 BTC)`'
|
||||
|
||||
@@ -1284,7 +1389,6 @@ def test_send_msg_sell_notification_no_fiat(default_conf, mocker) -> None:
|
||||
'exchange': 'Binance',
|
||||
'pair': 'KEY/ETH',
|
||||
'gain': 'loss',
|
||||
'market_url': 'https://www.binance.com/tradeDetail.html?symbol=KEY_ETH',
|
||||
'limit': 3.201e-05,
|
||||
'amount': 1333.3333333333335,
|
||||
'open_rate': 7.5e-05,
|
||||
@@ -1296,8 +1400,7 @@ def test_send_msg_sell_notification_no_fiat(default_conf, mocker) -> None:
|
||||
'sell_reason': SellType.STOP_LOSS.value
|
||||
})
|
||||
assert msg_mock.call_args[0][0] \
|
||||
== '*Binance:* Selling [KEY/ETH]' \
|
||||
'(https://www.binance.com/tradeDetail.html?symbol=KEY_ETH)\n' \
|
||||
== '*Binance:* Selling KEY/ETH\n' \
|
||||
'*Limit:* `0.00003201`\n' \
|
||||
'*Amount:* `1333.33333333`\n' \
|
||||
'*Open Rate:* `0.00007500`\n' \
|
||||
@@ -1307,7 +1410,6 @@ def test_send_msg_sell_notification_no_fiat(default_conf, mocker) -> None:
|
||||
|
||||
|
||||
def test__send_msg(default_conf, mocker) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram._init', MagicMock())
|
||||
bot = MagicMock()
|
||||
freqtradebot = get_patched_freqtradebot(mocker, default_conf)
|
||||
@@ -1319,7 +1421,6 @@ def test__send_msg(default_conf, mocker) -> None:
|
||||
|
||||
|
||||
def test__send_msg_network_error(default_conf, mocker, caplog) -> None:
|
||||
patch_coinmarketcap(mocker)
|
||||
mocker.patch('freqtrade.rpc.telegram.Telegram._init', MagicMock())
|
||||
bot = MagicMock()
|
||||
bot.send_message = MagicMock(side_effect=NetworkError('Oh snap'))
|
||||
|
||||
@@ -48,7 +48,6 @@ def test_send_msg(default_conf, mocker):
|
||||
'type': RPCMessageType.BUY_NOTIFICATION,
|
||||
'exchange': 'Bittrex',
|
||||
'pair': 'ETH/BTC',
|
||||
'market_url': "http://mockedurl/ETH_BTC",
|
||||
'limit': 0.005,
|
||||
'stake_amount': 0.8,
|
||||
'stake_amount_fiat': 500,
|
||||
@@ -73,7 +72,6 @@ def test_send_msg(default_conf, mocker):
|
||||
'exchange': 'Bittrex',
|
||||
'pair': 'ETH/BTC',
|
||||
'gain': "profit",
|
||||
'market_url': "http://mockedurl/ETH_BTC",
|
||||
'limit': 0.005,
|
||||
'amount': 0.8,
|
||||
'open_rate': 0.004,
|
||||
@@ -127,7 +125,6 @@ def test_exception_send_msg(default_conf, mocker, caplog):
|
||||
'type': RPCMessageType.BUY_NOTIFICATION,
|
||||
'exchange': 'Bittrex',
|
||||
'pair': 'ETH/BTC',
|
||||
'market_url': "http://mockedurl/ETH_BTC",
|
||||
'limit': 0.005,
|
||||
'stake_amount': 0.8,
|
||||
'stake_amount_fiat': 500,
|
||||
|
||||
@@ -10,7 +10,7 @@ from freqtrade.strategy.default_strategy import DefaultStrategy
|
||||
@pytest.fixture
|
||||
def result():
|
||||
with open('freqtrade/tests/testdata/ETH_BTC-1m.json') as data_file:
|
||||
return parse_ticker_dataframe(json.load(data_file))
|
||||
return parse_ticker_dataframe(json.load(data_file), '1m', fill_missing=True)
|
||||
|
||||
|
||||
def test_default_strategy_structure():
|
||||
|
||||
@@ -111,32 +111,78 @@ def test_tickerdata_to_dataframe(default_conf) -> None:
|
||||
|
||||
timerange = TimeRange(None, 'line', 0, -100)
|
||||
tick = load_tickerdata_file(None, 'UNITTEST/BTC', '1m', timerange=timerange)
|
||||
tickerlist = {'UNITTEST/BTC': parse_ticker_dataframe(tick)}
|
||||
tickerlist = {'UNITTEST/BTC': parse_ticker_dataframe(tick, '1m', True)}
|
||||
data = strategy.tickerdata_to_dataframe(tickerlist)
|
||||
assert len(data['UNITTEST/BTC']) == 99 # partial candle was removed
|
||||
assert len(data['UNITTEST/BTC']) == 102 # partial candle was removed
|
||||
|
||||
|
||||
def test_min_roi_reached(default_conf, fee) -> None:
|
||||
strategy = DefaultStrategy(default_conf)
|
||||
strategy.minimal_roi = {0: 0.1, 20: 0.05, 55: 0.01}
|
||||
trade = Trade(
|
||||
pair='ETH/BTC',
|
||||
stake_amount=0.001,
|
||||
open_date=arrow.utcnow().shift(hours=-1).datetime,
|
||||
fee_open=fee.return_value,
|
||||
fee_close=fee.return_value,
|
||||
exchange='bittrex',
|
||||
open_rate=1,
|
||||
)
|
||||
|
||||
assert not strategy.min_roi_reached(trade, 0.01, arrow.utcnow().shift(minutes=-55).datetime)
|
||||
assert strategy.min_roi_reached(trade, 0.12, arrow.utcnow().shift(minutes=-55).datetime)
|
||||
# Use list to confirm sequence does not matter
|
||||
min_roi_list = [{20: 0.05, 55: 0.01, 0: 0.1},
|
||||
{0: 0.1, 20: 0.05, 55: 0.01}]
|
||||
for roi in min_roi_list:
|
||||
strategy = DefaultStrategy(default_conf)
|
||||
strategy.minimal_roi = roi
|
||||
trade = Trade(
|
||||
pair='ETH/BTC',
|
||||
stake_amount=0.001,
|
||||
open_date=arrow.utcnow().shift(hours=-1).datetime,
|
||||
fee_open=fee.return_value,
|
||||
fee_close=fee.return_value,
|
||||
exchange='bittrex',
|
||||
open_rate=1,
|
||||
)
|
||||
|
||||
assert not strategy.min_roi_reached(trade, 0.04, arrow.utcnow().shift(minutes=-39).datetime)
|
||||
assert strategy.min_roi_reached(trade, 0.06, arrow.utcnow().shift(minutes=-39).datetime)
|
||||
assert not strategy.min_roi_reached(trade, 0.02, arrow.utcnow().shift(minutes=-56).datetime)
|
||||
assert strategy.min_roi_reached(trade, 0.12, arrow.utcnow().shift(minutes=-56).datetime)
|
||||
|
||||
assert not strategy.min_roi_reached(trade, -0.01, arrow.utcnow().shift(minutes=-1).datetime)
|
||||
assert strategy.min_roi_reached(trade, 0.02, arrow.utcnow().shift(minutes=-1).datetime)
|
||||
assert not strategy.min_roi_reached(trade, 0.04, arrow.utcnow().shift(minutes=-39).datetime)
|
||||
assert strategy.min_roi_reached(trade, 0.06, arrow.utcnow().shift(minutes=-39).datetime)
|
||||
|
||||
assert not strategy.min_roi_reached(trade, -0.01, arrow.utcnow().shift(minutes=-1).datetime)
|
||||
assert strategy.min_roi_reached(trade, 0.02, arrow.utcnow().shift(minutes=-1).datetime)
|
||||
|
||||
|
||||
def test_min_roi_reached2(default_conf, fee) -> None:
|
||||
|
||||
# test with ROI raising after last interval
|
||||
min_roi_list = [{20: 0.07,
|
||||
30: 0.05,
|
||||
55: 0.30,
|
||||
0: 0.1
|
||||
},
|
||||
{0: 0.1,
|
||||
20: 0.07,
|
||||
30: 0.05,
|
||||
55: 0.30
|
||||
},
|
||||
]
|
||||
for roi in min_roi_list:
|
||||
strategy = DefaultStrategy(default_conf)
|
||||
strategy.minimal_roi = roi
|
||||
trade = Trade(
|
||||
pair='ETH/BTC',
|
||||
stake_amount=0.001,
|
||||
open_date=arrow.utcnow().shift(hours=-1).datetime,
|
||||
fee_open=fee.return_value,
|
||||
fee_close=fee.return_value,
|
||||
exchange='bittrex',
|
||||
open_rate=1,
|
||||
)
|
||||
|
||||
assert not strategy.min_roi_reached(trade, 0.02, arrow.utcnow().shift(minutes=-56).datetime)
|
||||
assert strategy.min_roi_reached(trade, 0.12, arrow.utcnow().shift(minutes=-56).datetime)
|
||||
|
||||
assert not strategy.min_roi_reached(trade, 0.04, arrow.utcnow().shift(minutes=-39).datetime)
|
||||
assert strategy.min_roi_reached(trade, 0.071, arrow.utcnow().shift(minutes=-39).datetime)
|
||||
|
||||
assert not strategy.min_roi_reached(trade, 0.04, arrow.utcnow().shift(minutes=-26).datetime)
|
||||
assert strategy.min_roi_reached(trade, 0.06, arrow.utcnow().shift(minutes=-26).datetime)
|
||||
|
||||
# Should not trigger with 20% profit since after 55 minutes only 30% is active.
|
||||
assert not strategy.min_roi_reached(trade, 0.20, arrow.utcnow().shift(minutes=-2).datetime)
|
||||
assert strategy.min_roi_reached(trade, 0.31, arrow.utcnow().shift(minutes=-2).datetime)
|
||||
|
||||
|
||||
def test_analyze_ticker_default(ticker_history, mocker, caplog) -> None:
|
||||
@@ -158,7 +204,7 @@ def test_analyze_ticker_default(ticker_history, mocker, caplog) -> None:
|
||||
assert buy_mock.call_count == 1
|
||||
|
||||
assert log_has('TA Analysis Launched', caplog.record_tuples)
|
||||
assert not log_has('Skippinig TA Analysis for already analyzed candle',
|
||||
assert not log_has('Skipping TA Analysis for already analyzed candle',
|
||||
caplog.record_tuples)
|
||||
caplog.clear()
|
||||
|
||||
@@ -168,7 +214,7 @@ def test_analyze_ticker_default(ticker_history, mocker, caplog) -> None:
|
||||
assert buy_mock.call_count == 2
|
||||
assert buy_mock.call_count == 2
|
||||
assert log_has('TA Analysis Launched', caplog.record_tuples)
|
||||
assert not log_has('Skippinig TA Analysis for already analyzed candle',
|
||||
assert not log_has('Skipping TA Analysis for already analyzed candle',
|
||||
caplog.record_tuples)
|
||||
|
||||
|
||||
@@ -196,7 +242,7 @@ def test_analyze_ticker_skip_analyze(ticker_history, mocker, caplog) -> None:
|
||||
assert buy_mock.call_count == 1
|
||||
assert buy_mock.call_count == 1
|
||||
assert log_has('TA Analysis Launched', caplog.record_tuples)
|
||||
assert not log_has('Skippinig TA Analysis for already analyzed candle',
|
||||
assert not log_has('Skipping TA Analysis for already analyzed candle',
|
||||
caplog.record_tuples)
|
||||
caplog.clear()
|
||||
|
||||
@@ -211,5 +257,5 @@ def test_analyze_ticker_skip_analyze(ticker_history, mocker, caplog) -> None:
|
||||
assert ret['buy'].sum() == 0
|
||||
assert ret['sell'].sum() == 0
|
||||
assert not log_has('TA Analysis Launched', caplog.record_tuples)
|
||||
assert log_has('Skippinig TA Analysis for already analyzed candle',
|
||||
assert log_has('Skipping TA Analysis for already analyzed candle',
|
||||
caplog.record_tuples)
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
# pragma pylint: disable=missing-docstring, protected-access, C0103
|
||||
import logging
|
||||
import warnings
|
||||
from base64 import urlsafe_b64encode
|
||||
from os import path
|
||||
from pathlib import Path
|
||||
import warnings
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.resolvers import StrategyResolver
|
||||
from freqtrade.strategy import import_strategy
|
||||
from freqtrade.strategy.default_strategy import DefaultStrategy
|
||||
from freqtrade.strategy.interface import IStrategy
|
||||
from freqtrade.resolvers import StrategyResolver
|
||||
from freqtrade.tests.conftest import log_has_re
|
||||
|
||||
|
||||
def test_import_strategy(caplog):
|
||||
@@ -94,6 +96,16 @@ def test_load_not_found_strategy():
|
||||
strategy._load_strategy(strategy_name='NotFoundStrategy', config={})
|
||||
|
||||
|
||||
def test_load_staticmethod_importerror(mocker, caplog):
|
||||
mocker.patch("freqtrade.resolvers.strategy_resolver.import_strategy", Mock(
|
||||
side_effect=TypeError("can't pickle staticmethod objects")))
|
||||
with pytest.raises(ImportError,
|
||||
match=r"Impossible to load Strategy 'DefaultStrategy'."
|
||||
r" This class does not exist or contains Python code errors"):
|
||||
StrategyResolver()
|
||||
assert log_has_re(r".*Error: can't pickle staticmethod objects", caplog.record_tuples)
|
||||
|
||||
|
||||
def test_strategy(result):
|
||||
config = {'strategy': 'DefaultStrategy'}
|
||||
|
||||
@@ -150,16 +162,57 @@ def test_strategy_override_stoploss(caplog):
|
||||
) in caplog.record_tuples
|
||||
|
||||
|
||||
def test_strategy_override_trailing_stop(caplog):
|
||||
caplog.set_level(logging.INFO)
|
||||
config = {
|
||||
'strategy': 'DefaultStrategy',
|
||||
'trailing_stop': True
|
||||
}
|
||||
resolver = StrategyResolver(config)
|
||||
|
||||
assert resolver.strategy.trailing_stop
|
||||
assert isinstance(resolver.strategy.trailing_stop, bool)
|
||||
assert ('freqtrade.resolvers.strategy_resolver',
|
||||
logging.INFO,
|
||||
"Override strategy 'trailing_stop' with value in config file: True."
|
||||
) in caplog.record_tuples
|
||||
|
||||
|
||||
def test_strategy_override_trailing_stop_positive(caplog):
|
||||
caplog.set_level(logging.INFO)
|
||||
config = {
|
||||
'strategy': 'DefaultStrategy',
|
||||
'trailing_stop_positive': -0.1,
|
||||
'trailing_stop_positive_offset': -0.2
|
||||
|
||||
}
|
||||
resolver = StrategyResolver(config)
|
||||
|
||||
assert resolver.strategy.trailing_stop_positive == -0.1
|
||||
assert ('freqtrade.resolvers.strategy_resolver',
|
||||
logging.INFO,
|
||||
"Override strategy 'trailing_stop_positive' with value in config file: -0.1."
|
||||
) in caplog.record_tuples
|
||||
|
||||
assert resolver.strategy.trailing_stop_positive_offset == -0.2
|
||||
assert ('freqtrade.resolvers.strategy_resolver',
|
||||
logging.INFO,
|
||||
"Override strategy 'trailing_stop_positive' with value in config file: -0.1."
|
||||
) in caplog.record_tuples
|
||||
|
||||
|
||||
def test_strategy_override_ticker_interval(caplog):
|
||||
caplog.set_level(logging.INFO)
|
||||
|
||||
config = {
|
||||
'strategy': 'DefaultStrategy',
|
||||
'ticker_interval': 60
|
||||
'ticker_interval': 60,
|
||||
'stake_currency': 'ETH'
|
||||
}
|
||||
resolver = StrategyResolver(config)
|
||||
|
||||
assert resolver.strategy.ticker_interval == 60
|
||||
assert resolver.strategy.stake_currency == 'ETH'
|
||||
assert ('freqtrade.resolvers.strategy_resolver',
|
||||
logging.INFO,
|
||||
"Override strategy 'ticker_interval' with value in config file: 60."
|
||||
@@ -178,8 +231,7 @@ def test_strategy_override_process_only_new_candles(caplog):
|
||||
assert resolver.strategy.process_only_new_candles
|
||||
assert ('freqtrade.resolvers.strategy_resolver',
|
||||
logging.INFO,
|
||||
"Override process_only_new_candles 'process_only_new_candles' "
|
||||
"with value in config file: True."
|
||||
"Override strategy 'process_only_new_candles' with value in config file: True."
|
||||
) in caplog.record_tuples
|
||||
|
||||
|
||||
@@ -256,6 +308,62 @@ def test_strategy_override_order_tif(caplog):
|
||||
StrategyResolver(config)
|
||||
|
||||
|
||||
def test_strategy_override_use_sell_signal(caplog):
|
||||
caplog.set_level(logging.INFO)
|
||||
config = {
|
||||
'strategy': 'DefaultStrategy',
|
||||
}
|
||||
resolver = StrategyResolver(config)
|
||||
assert not resolver.strategy.use_sell_signal
|
||||
assert isinstance(resolver.strategy.use_sell_signal, bool)
|
||||
# must be inserted to configuration
|
||||
assert 'use_sell_signal' in config['experimental']
|
||||
assert not config['experimental']['use_sell_signal']
|
||||
|
||||
config = {
|
||||
'strategy': 'DefaultStrategy',
|
||||
'experimental': {
|
||||
'use_sell_signal': True,
|
||||
},
|
||||
}
|
||||
resolver = StrategyResolver(config)
|
||||
|
||||
assert resolver.strategy.use_sell_signal
|
||||
assert isinstance(resolver.strategy.use_sell_signal, bool)
|
||||
assert ('freqtrade.resolvers.strategy_resolver',
|
||||
logging.INFO,
|
||||
"Override strategy 'use_sell_signal' with value in config file: True."
|
||||
) in caplog.record_tuples
|
||||
|
||||
|
||||
def test_strategy_override_use_sell_profit_only(caplog):
|
||||
caplog.set_level(logging.INFO)
|
||||
config = {
|
||||
'strategy': 'DefaultStrategy',
|
||||
}
|
||||
resolver = StrategyResolver(config)
|
||||
assert not resolver.strategy.sell_profit_only
|
||||
assert isinstance(resolver.strategy.sell_profit_only, bool)
|
||||
# must be inserted to configuration
|
||||
assert 'sell_profit_only' in config['experimental']
|
||||
assert not config['experimental']['sell_profit_only']
|
||||
|
||||
config = {
|
||||
'strategy': 'DefaultStrategy',
|
||||
'experimental': {
|
||||
'sell_profit_only': True,
|
||||
},
|
||||
}
|
||||
resolver = StrategyResolver(config)
|
||||
|
||||
assert resolver.strategy.sell_profit_only
|
||||
assert isinstance(resolver.strategy.sell_profit_only, bool)
|
||||
assert ('freqtrade.resolvers.strategy_resolver',
|
||||
logging.INFO,
|
||||
"Override strategy 'sell_profit_only' with value in config file: True."
|
||||
) in caplog.record_tuples
|
||||
|
||||
|
||||
def test_deprecate_populate_indicators(result):
|
||||
default_location = path.join(path.dirname(path.realpath(__file__)))
|
||||
resolver = StrategyResolver({'strategy': 'TestStrategyLegacy',
|
||||
@@ -270,7 +378,7 @@ def test_deprecate_populate_indicators(result):
|
||||
in str(w[-1].message)
|
||||
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
# Cause all warnings to always be triggered.
|
||||
# Cause all warnings to always be triggered.
|
||||
warnings.simplefilter("always")
|
||||
resolver.strategy.advise_buy(indicators, 'ETH/BTC')
|
||||
assert len(w) == 1
|
||||
|
||||
@@ -16,7 +16,7 @@ def test_parse_args_none() -> None:
|
||||
|
||||
def test_parse_args_defaults() -> None:
|
||||
args = Arguments([], '').get_parsed_arg()
|
||||
assert args.config == 'config.json'
|
||||
assert args.config == ['config.json']
|
||||
assert args.strategy_path is None
|
||||
assert args.datadir is None
|
||||
assert args.loglevel == 0
|
||||
@@ -24,10 +24,15 @@ def test_parse_args_defaults() -> None:
|
||||
|
||||
def test_parse_args_config() -> None:
|
||||
args = Arguments(['-c', '/dev/null'], '').get_parsed_arg()
|
||||
assert args.config == '/dev/null'
|
||||
assert args.config == ['/dev/null']
|
||||
|
||||
args = Arguments(['--config', '/dev/null'], '').get_parsed_arg()
|
||||
assert args.config == '/dev/null'
|
||||
assert args.config == ['/dev/null']
|
||||
|
||||
args = Arguments(['--config', '/dev/null',
|
||||
'--config', '/dev/zero'],
|
||||
'').get_parsed_arg()
|
||||
assert args.config == ['/dev/null', '/dev/zero']
|
||||
|
||||
|
||||
def test_parse_args_db_url() -> None:
|
||||
@@ -47,7 +52,7 @@ def test_scripts_options() -> None:
|
||||
arguments = Arguments(['-p', 'ETH/BTC'], '')
|
||||
arguments.scripts_options()
|
||||
args = arguments.get_parsed_arg()
|
||||
assert args.pair == 'ETH/BTC'
|
||||
assert args.pairs == 'ETH/BTC'
|
||||
|
||||
|
||||
def test_parse_args_version() -> None:
|
||||
@@ -139,7 +144,7 @@ def test_parse_args_backtesting_custom() -> None:
|
||||
'TestStrategy'
|
||||
]
|
||||
call_args = Arguments(args, '').get_parsed_arg()
|
||||
assert call_args.config == 'test_conf.json'
|
||||
assert call_args.config == ['test_conf.json']
|
||||
assert call_args.live is True
|
||||
assert call_args.loglevel == 0
|
||||
assert call_args.subparser == 'backtesting'
|
||||
@@ -158,7 +163,7 @@ def test_parse_args_hyperopt_custom() -> None:
|
||||
'--spaces', 'buy'
|
||||
]
|
||||
call_args = Arguments(args, '').get_parsed_arg()
|
||||
assert call_args.config == 'test_conf.json'
|
||||
assert call_args.config == ['test_conf.json']
|
||||
assert call_args.epochs == 20
|
||||
assert call_args.loglevel == 0
|
||||
assert call_args.subparser == 'hyperopt'
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
# pragma pylint: disable=missing-docstring, protected-access, invalid-name
|
||||
|
||||
import json
|
||||
from argparse import Namespace
|
||||
import logging
|
||||
from argparse import Namespace
|
||||
from copy import deepcopy
|
||||
from unittest.mock import MagicMock
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from jsonschema import validate, ValidationError, Draft4Validator
|
||||
from jsonschema import Draft4Validator, ValidationError, validate
|
||||
|
||||
from freqtrade import constants
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade import OperationalException, constants
|
||||
from freqtrade.arguments import Arguments
|
||||
from freqtrade.configuration import Configuration, set_loggers
|
||||
from freqtrade.constants import DEFAULT_DB_DRYRUN_URL, DEFAULT_DB_PROD_URL
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.tests.conftest import log_has
|
||||
|
||||
|
||||
@@ -21,7 +23,7 @@ def test_load_config_invalid_pair(default_conf) -> None:
|
||||
|
||||
with pytest.raises(ValidationError, match=r'.*does not match.*'):
|
||||
configuration = Configuration(Namespace())
|
||||
configuration._validate_config(default_conf)
|
||||
configuration._validate_config_schema(default_conf)
|
||||
|
||||
|
||||
def test_load_config_missing_attributes(default_conf) -> None:
|
||||
@@ -29,7 +31,7 @@ def test_load_config_missing_attributes(default_conf) -> None:
|
||||
|
||||
with pytest.raises(ValidationError, match=r'.*\'exchange\' is a required property.*'):
|
||||
configuration = Configuration(Namespace())
|
||||
configuration._validate_config(default_conf)
|
||||
configuration._validate_config_schema(default_conf)
|
||||
|
||||
|
||||
def test_load_config_incorrect_stake_amount(default_conf) -> None:
|
||||
@@ -37,7 +39,7 @@ def test_load_config_incorrect_stake_amount(default_conf) -> None:
|
||||
|
||||
with pytest.raises(ValidationError, match=r'.*\'fake\' does not match \'unlimited\'.*'):
|
||||
configuration = Configuration(Namespace())
|
||||
configuration._validate_config(default_conf)
|
||||
configuration._validate_config_schema(default_conf)
|
||||
|
||||
|
||||
def test_load_config_file(default_conf, mocker, caplog) -> None:
|
||||
@@ -49,18 +51,49 @@ def test_load_config_file(default_conf, mocker, caplog) -> None:
|
||||
validated_conf = configuration._load_config_file('somefile')
|
||||
assert file_mock.call_count == 1
|
||||
assert validated_conf.items() >= default_conf.items()
|
||||
assert 'internals' in validated_conf
|
||||
assert log_has('Validating configuration ...', caplog.record_tuples)
|
||||
|
||||
|
||||
def test_load_config_max_open_trades_zero(default_conf, mocker, caplog) -> None:
|
||||
default_conf['max_open_trades'] = 0
|
||||
file_mock = mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
||||
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
||||
read_data=json.dumps(default_conf)
|
||||
))
|
||||
|
||||
Configuration(Namespace())._load_config_file('somefile')
|
||||
assert file_mock.call_count == 1
|
||||
args = Arguments([], '').get_parsed_arg()
|
||||
configuration = Configuration(args)
|
||||
validated_conf = configuration.load_config()
|
||||
|
||||
assert validated_conf['max_open_trades'] == 0
|
||||
assert 'internals' in validated_conf
|
||||
assert log_has('Validating configuration ...', caplog.record_tuples)
|
||||
|
||||
|
||||
def test_load_config_combine_dicts(default_conf, mocker, caplog) -> None:
|
||||
conf1 = deepcopy(default_conf)
|
||||
conf2 = deepcopy(default_conf)
|
||||
del conf1['exchange']['key']
|
||||
del conf1['exchange']['secret']
|
||||
del conf2['exchange']['name']
|
||||
conf2['exchange']['pair_whitelist'] += ['NANO/BTC']
|
||||
|
||||
config_files = [conf1, conf2]
|
||||
|
||||
configsmock = MagicMock(side_effect=config_files)
|
||||
mocker.patch('freqtrade.configuration.Configuration._load_config_file', configsmock)
|
||||
|
||||
arg_list = ['-c', 'test_conf.json', '--config', 'test2_conf.json', ]
|
||||
args = Arguments(arg_list, '').get_parsed_arg()
|
||||
configuration = Configuration(args)
|
||||
validated_conf = configuration.load_config()
|
||||
|
||||
exchange_conf = default_conf['exchange']
|
||||
assert validated_conf['exchange']['name'] == exchange_conf['name']
|
||||
assert validated_conf['exchange']['key'] == exchange_conf['key']
|
||||
assert validated_conf['exchange']['secret'] == exchange_conf['secret']
|
||||
assert validated_conf['exchange']['pair_whitelist'] != conf1['exchange']['pair_whitelist']
|
||||
assert validated_conf['exchange']['pair_whitelist'] == conf2['exchange']['pair_whitelist']
|
||||
|
||||
assert 'internals' in validated_conf
|
||||
assert log_has('Validating configuration ...', caplog.record_tuples)
|
||||
|
||||
|
||||
@@ -73,11 +106,12 @@ def test_load_config_max_open_trades_minus_one(default_conf, mocker, caplog) ->
|
||||
args = Arguments([], '').get_parsed_arg()
|
||||
configuration = Configuration(args)
|
||||
validated_conf = configuration.load_config()
|
||||
print(validated_conf)
|
||||
|
||||
assert validated_conf['max_open_trades'] > 999999999
|
||||
assert validated_conf['max_open_trades'] == float('inf')
|
||||
assert log_has('Validating configuration ...', caplog.record_tuples)
|
||||
assert "runmode" in validated_conf
|
||||
assert validated_conf['runmode'] == RunMode.DRY_RUN
|
||||
|
||||
|
||||
def test_load_config_file_exception(mocker) -> None:
|
||||
@@ -125,6 +159,43 @@ def test_load_config_with_params(default_conf, mocker) -> None:
|
||||
assert validated_conf.get('strategy_path') == '/some/path'
|
||||
assert validated_conf.get('db_url') == 'sqlite:///someurl'
|
||||
|
||||
# Test conf provided db_url prod
|
||||
conf = default_conf.copy()
|
||||
conf["dry_run"] = False
|
||||
conf["db_url"] = "sqlite:///path/to/db.sqlite"
|
||||
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
||||
read_data=json.dumps(conf)
|
||||
))
|
||||
|
||||
arglist = [
|
||||
'--strategy', 'TestStrategy',
|
||||
'--strategy-path', '/some/path'
|
||||
]
|
||||
args = Arguments(arglist, '').get_parsed_arg()
|
||||
|
||||
configuration = Configuration(args)
|
||||
validated_conf = configuration.load_config()
|
||||
assert validated_conf.get('db_url') == "sqlite:///path/to/db.sqlite"
|
||||
|
||||
# Test conf provided db_url dry_run
|
||||
conf = default_conf.copy()
|
||||
conf["dry_run"] = True
|
||||
conf["db_url"] = "sqlite:///path/to/db.sqlite"
|
||||
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
||||
read_data=json.dumps(conf)
|
||||
))
|
||||
|
||||
arglist = [
|
||||
'--strategy', 'TestStrategy',
|
||||
'--strategy-path', '/some/path'
|
||||
]
|
||||
args = Arguments(arglist, '').get_parsed_arg()
|
||||
|
||||
configuration = Configuration(args)
|
||||
validated_conf = configuration.load_config()
|
||||
assert validated_conf.get('db_url') == "sqlite:///path/to/db.sqlite"
|
||||
|
||||
# Test args provided db_url prod
|
||||
conf = default_conf.copy()
|
||||
conf["dry_run"] = False
|
||||
del conf["db_url"]
|
||||
@@ -141,8 +212,10 @@ def test_load_config_with_params(default_conf, mocker) -> None:
|
||||
configuration = Configuration(args)
|
||||
validated_conf = configuration.load_config()
|
||||
assert validated_conf.get('db_url') == DEFAULT_DB_PROD_URL
|
||||
assert "runmode" in validated_conf
|
||||
assert validated_conf['runmode'] == RunMode.LIVE
|
||||
|
||||
# Test dry=run with ProdURL
|
||||
# Test args provided db_url dry_run
|
||||
conf = default_conf.copy()
|
||||
conf["dry_run"] = True
|
||||
conf["db_url"] = DEFAULT_DB_PROD_URL
|
||||
@@ -247,6 +320,7 @@ def test_setup_configuration_with_arguments(mocker, default_conf, caplog) -> Non
|
||||
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
||||
read_data=json.dumps(default_conf)
|
||||
))
|
||||
mocker.patch('freqtrade.configuration.Configuration._create_datadir', lambda s, c, x: x)
|
||||
|
||||
arglist = [
|
||||
'--config', 'config.json',
|
||||
@@ -328,8 +402,9 @@ def test_setup_configuration_with_stratlist(mocker, default_conf, caplog) -> Non
|
||||
|
||||
args = Arguments(arglist, '').get_parsed_arg()
|
||||
|
||||
configuration = Configuration(args)
|
||||
configuration = Configuration(args, RunMode.BACKTEST)
|
||||
config = configuration.get_config()
|
||||
assert config['runmode'] == RunMode.BACKTEST
|
||||
assert 'max_open_trades' in config
|
||||
assert 'stake_currency' in config
|
||||
assert 'stake_amount' in config
|
||||
@@ -374,7 +449,7 @@ def test_hyperopt_with_arguments(mocker, default_conf, caplog) -> None:
|
||||
]
|
||||
args = Arguments(arglist, '').get_parsed_arg()
|
||||
|
||||
configuration = Configuration(args)
|
||||
configuration = Configuration(args, RunMode.HYPEROPT)
|
||||
config = configuration.get_config()
|
||||
|
||||
assert 'epochs' in config
|
||||
@@ -385,6 +460,8 @@ def test_hyperopt_with_arguments(mocker, default_conf, caplog) -> None:
|
||||
assert 'spaces' in config
|
||||
assert config['spaces'] == ['all']
|
||||
assert log_has('Parameter -s/--spaces detected: [\'all\']', caplog.record_tuples)
|
||||
assert "runmode" in config
|
||||
assert config['runmode'] == RunMode.HYPEROPT
|
||||
|
||||
|
||||
def test_check_exchange(default_conf, caplog) -> None:
|
||||
@@ -408,15 +485,6 @@ def test_check_exchange(default_conf, caplog) -> None:
|
||||
):
|
||||
configuration.check_exchange(default_conf)
|
||||
|
||||
# Test ccxt_rate_limit depreciation
|
||||
default_conf.get('exchange').update({'name': 'binance'})
|
||||
default_conf['exchange']['ccxt_rate_limit'] = True
|
||||
configuration.check_exchange(default_conf)
|
||||
assert log_has("`ccxt_rate_limit` has been deprecated in favor of "
|
||||
"`ccxt_config` and `ccxt_async_config` and will be removed "
|
||||
"in a future version.",
|
||||
caplog.record_tuples)
|
||||
|
||||
|
||||
def test_cli_verbose_with_params(default_conf, mocker, caplog) -> None:
|
||||
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
||||
@@ -471,6 +539,23 @@ def test_set_loggers() -> None:
|
||||
assert logging.getLogger('telegram').level is logging.INFO
|
||||
|
||||
|
||||
def test_set_logfile(default_conf, mocker):
|
||||
mocker.patch('freqtrade.configuration.open',
|
||||
mocker.mock_open(read_data=json.dumps(default_conf)))
|
||||
|
||||
arglist = [
|
||||
'--logfile', 'test_file.log',
|
||||
]
|
||||
args = Arguments(arglist, '').get_parsed_arg()
|
||||
configuration = Configuration(args)
|
||||
validated_conf = configuration.load_config()
|
||||
|
||||
assert validated_conf['logfile'] == "test_file.log"
|
||||
f = Path("test_file.log")
|
||||
assert f.is_file()
|
||||
f.unlink()
|
||||
|
||||
|
||||
def test_load_config_warn_forcebuy(default_conf, mocker, caplog) -> None:
|
||||
default_conf['forcebuy_enable'] = True
|
||||
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
||||
@@ -487,3 +572,39 @@ def test_load_config_warn_forcebuy(default_conf, mocker, caplog) -> None:
|
||||
|
||||
def test_validate_default_conf(default_conf) -> None:
|
||||
validate(default_conf, constants.CONF_SCHEMA, Draft4Validator)
|
||||
|
||||
|
||||
def test__create_datadir(mocker, default_conf, caplog) -> None:
|
||||
mocker.patch('os.path.isdir', MagicMock(return_value=False))
|
||||
md = MagicMock()
|
||||
mocker.patch('os.makedirs', md)
|
||||
cfg = Configuration(Namespace())
|
||||
cfg._create_datadir(default_conf, '/foo/bar')
|
||||
assert md.call_args[0][0] == "/foo/bar"
|
||||
assert log_has('Created data directory: /foo/bar', caplog.record_tuples)
|
||||
|
||||
|
||||
def test_validate_tsl(default_conf):
|
||||
default_conf['trailing_stop'] = True
|
||||
default_conf['trailing_stop_positive'] = 0
|
||||
default_conf['trailing_stop_positive_offset'] = 0
|
||||
|
||||
default_conf['trailing_only_offset_is_reached'] = True
|
||||
with pytest.raises(OperationalException,
|
||||
match=r'The config trailing_only_offset_is_reached needs '
|
||||
'trailing_stop_positive_offset to be more than 0 in your config.'):
|
||||
configuration = Configuration(Namespace())
|
||||
configuration._validate_config_consistency(default_conf)
|
||||
|
||||
default_conf['trailing_stop_positive_offset'] = 0.01
|
||||
default_conf['trailing_stop_positive'] = 0.015
|
||||
with pytest.raises(OperationalException,
|
||||
match=r'The config trailing_stop_positive_offset needs '
|
||||
'to be greater than trailing_stop_positive_offset in your config.'):
|
||||
configuration = Configuration(Namespace())
|
||||
configuration._validate_config_consistency(default_conf)
|
||||
|
||||
default_conf['trailing_stop_positive'] = 0.01
|
||||
default_conf['trailing_stop_positive_offset'] = 0.015
|
||||
Configuration(Namespace())
|
||||
configuration._validate_config_consistency(default_conf)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,8 +7,8 @@ import pytest
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.arguments import Arguments
|
||||
from freqtrade.freqtradebot import FreqtradeBot
|
||||
from freqtrade.main import main, reconfigure
|
||||
from freqtrade.worker import Worker
|
||||
from freqtrade.main import main
|
||||
from freqtrade.state import State
|
||||
from freqtrade.tests.conftest import log_has, patch_exchange
|
||||
|
||||
@@ -22,7 +22,7 @@ def test_parse_args_backtesting(mocker) -> None:
|
||||
main(['backtesting'])
|
||||
assert backtesting_mock.call_count == 1
|
||||
call_args = backtesting_mock.call_args[0][0]
|
||||
assert call_args.config == 'config.json'
|
||||
assert call_args.config == ['config.json']
|
||||
assert call_args.live is False
|
||||
assert call_args.loglevel == 0
|
||||
assert call_args.subparser == 'backtesting'
|
||||
@@ -35,7 +35,7 @@ def test_main_start_hyperopt(mocker) -> None:
|
||||
main(['hyperopt'])
|
||||
assert hyperopt_mock.call_count == 1
|
||||
call_args = hyperopt_mock.call_args[0][0]
|
||||
assert call_args.config == 'config.json'
|
||||
assert call_args.config == ['config.json']
|
||||
assert call_args.loglevel == 0
|
||||
assert call_args.subparser == 'hyperopt'
|
||||
assert call_args.func is not None
|
||||
@@ -43,17 +43,14 @@ def test_main_start_hyperopt(mocker) -> None:
|
||||
|
||||
def test_main_fatal_exception(mocker, default_conf, caplog) -> None:
|
||||
patch_exchange(mocker)
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.freqtradebot.FreqtradeBot',
|
||||
_init_modules=MagicMock(),
|
||||
worker=MagicMock(side_effect=Exception),
|
||||
cleanup=MagicMock(),
|
||||
)
|
||||
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.cleanup', MagicMock())
|
||||
mocker.patch('freqtrade.worker.Worker._worker', MagicMock(side_effect=Exception))
|
||||
mocker.patch(
|
||||
'freqtrade.configuration.Configuration._load_config_file',
|
||||
lambda *args, **kwargs: default_conf
|
||||
)
|
||||
mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock())
|
||||
mocker.patch('freqtrade.freqtradebot.persistence.init', MagicMock())
|
||||
|
||||
args = ['-c', 'config.json.example']
|
||||
|
||||
@@ -66,17 +63,14 @@ def test_main_fatal_exception(mocker, default_conf, caplog) -> None:
|
||||
|
||||
def test_main_keyboard_interrupt(mocker, default_conf, caplog) -> None:
|
||||
patch_exchange(mocker)
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.freqtradebot.FreqtradeBot',
|
||||
_init_modules=MagicMock(),
|
||||
worker=MagicMock(side_effect=KeyboardInterrupt),
|
||||
cleanup=MagicMock(),
|
||||
)
|
||||
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.cleanup', MagicMock())
|
||||
mocker.patch('freqtrade.worker.Worker._worker', MagicMock(side_effect=KeyboardInterrupt))
|
||||
mocker.patch(
|
||||
'freqtrade.configuration.Configuration._load_config_file',
|
||||
lambda *args, **kwargs: default_conf
|
||||
)
|
||||
mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock())
|
||||
mocker.patch('freqtrade.freqtradebot.persistence.init', MagicMock())
|
||||
|
||||
args = ['-c', 'config.json.example']
|
||||
|
||||
@@ -89,17 +83,17 @@ def test_main_keyboard_interrupt(mocker, default_conf, caplog) -> None:
|
||||
|
||||
def test_main_operational_exception(mocker, default_conf, caplog) -> None:
|
||||
patch_exchange(mocker)
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.freqtradebot.FreqtradeBot',
|
||||
_init_modules=MagicMock(),
|
||||
worker=MagicMock(side_effect=OperationalException('Oh snap!')),
|
||||
cleanup=MagicMock(),
|
||||
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.cleanup', MagicMock())
|
||||
mocker.patch(
|
||||
'freqtrade.worker.Worker._worker',
|
||||
MagicMock(side_effect=OperationalException('Oh snap!'))
|
||||
)
|
||||
mocker.patch(
|
||||
'freqtrade.configuration.Configuration._load_config_file',
|
||||
lambda *args, **kwargs: default_conf
|
||||
)
|
||||
mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock())
|
||||
mocker.patch('freqtrade.freqtradebot.persistence.init', MagicMock())
|
||||
|
||||
args = ['-c', 'config.json.example']
|
||||
|
||||
@@ -112,21 +106,18 @@ def test_main_operational_exception(mocker, default_conf, caplog) -> None:
|
||||
|
||||
def test_main_reload_conf(mocker, default_conf, caplog) -> None:
|
||||
patch_exchange(mocker)
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.freqtradebot.FreqtradeBot',
|
||||
_init_modules=MagicMock(),
|
||||
worker=MagicMock(return_value=State.RELOAD_CONF),
|
||||
cleanup=MagicMock(),
|
||||
)
|
||||
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.cleanup', MagicMock())
|
||||
mocker.patch('freqtrade.worker.Worker._worker', MagicMock(return_value=State.RELOAD_CONF))
|
||||
mocker.patch(
|
||||
'freqtrade.configuration.Configuration._load_config_file',
|
||||
lambda *args, **kwargs: default_conf
|
||||
)
|
||||
mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock())
|
||||
mocker.patch('freqtrade.freqtradebot.persistence.init', MagicMock())
|
||||
|
||||
# Raise exception as side effect to avoid endless loop
|
||||
reconfigure_mock = mocker.patch(
|
||||
'freqtrade.main.reconfigure', MagicMock(side_effect=Exception)
|
||||
'freqtrade.main.Worker._reconfigure', MagicMock(side_effect=Exception)
|
||||
)
|
||||
|
||||
with pytest.raises(SystemExit):
|
||||
@@ -138,19 +129,21 @@ def test_main_reload_conf(mocker, default_conf, caplog) -> None:
|
||||
|
||||
def test_reconfigure(mocker, default_conf) -> None:
|
||||
patch_exchange(mocker)
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.freqtradebot.FreqtradeBot',
|
||||
_init_modules=MagicMock(),
|
||||
worker=MagicMock(side_effect=OperationalException('Oh snap!')),
|
||||
cleanup=MagicMock(),
|
||||
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.cleanup', MagicMock())
|
||||
mocker.patch(
|
||||
'freqtrade.worker.Worker._worker',
|
||||
MagicMock(side_effect=OperationalException('Oh snap!'))
|
||||
)
|
||||
mocker.patch(
|
||||
'freqtrade.configuration.Configuration._load_config_file',
|
||||
lambda *args, **kwargs: default_conf
|
||||
)
|
||||
mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock())
|
||||
mocker.patch('freqtrade.freqtradebot.persistence.init', MagicMock())
|
||||
|
||||
freqtrade = FreqtradeBot(default_conf)
|
||||
args = Arguments(['-c', 'config.json.example'], '').get_parsed_arg()
|
||||
worker = Worker(args=args, config=default_conf)
|
||||
freqtrade = worker.freqtrade
|
||||
|
||||
# Renew mock to return modified data
|
||||
conf = deepcopy(default_conf)
|
||||
@@ -160,11 +153,10 @@ def test_reconfigure(mocker, default_conf) -> None:
|
||||
lambda *args, **kwargs: conf
|
||||
)
|
||||
|
||||
worker._config = conf
|
||||
# reconfigure should return a new instance
|
||||
freqtrade2 = reconfigure(
|
||||
freqtrade,
|
||||
Arguments(['-c', 'config.json.example'], '').get_parsed_arg()
|
||||
)
|
||||
worker._reconfigure()
|
||||
freqtrade2 = worker.freqtrade
|
||||
|
||||
# Verify we have a new instance with the new config
|
||||
assert freqtrade is not freqtrade2
|
||||
|
||||
@@ -5,8 +5,8 @@ from unittest.mock import MagicMock
|
||||
|
||||
from freqtrade.data.converter import parse_ticker_dataframe
|
||||
from freqtrade.misc import (common_datearray, datesarray_to_datetimearray,
|
||||
file_dump_json, format_ms_time, shorten_date)
|
||||
from freqtrade.data.history import load_tickerdata_file
|
||||
file_dump_json, file_load_json, format_ms_time, shorten_date)
|
||||
from freqtrade.data.history import load_tickerdata_file, make_testdata_path
|
||||
from freqtrade.strategy.default_strategy import DefaultStrategy
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ def test_shorten_date() -> None:
|
||||
|
||||
|
||||
def test_datesarray_to_datetimearray(ticker_history_list):
|
||||
dataframes = parse_ticker_dataframe(ticker_history_list)
|
||||
dataframes = parse_ticker_dataframe(ticker_history_list, "5m", fill_missing=True)
|
||||
dates = datesarray_to_datetimearray(dataframes['date'])
|
||||
|
||||
assert isinstance(dates[0], datetime.datetime)
|
||||
@@ -34,29 +34,42 @@ def test_datesarray_to_datetimearray(ticker_history_list):
|
||||
def test_common_datearray(default_conf) -> None:
|
||||
strategy = DefaultStrategy(default_conf)
|
||||
tick = load_tickerdata_file(None, 'UNITTEST/BTC', '1m')
|
||||
tickerlist = {'UNITTEST/BTC': parse_ticker_dataframe(tick)}
|
||||
tickerlist = {'UNITTEST/BTC': parse_ticker_dataframe(tick, "1m", fill_missing=True)}
|
||||
dataframes = strategy.tickerdata_to_dataframe(tickerlist)
|
||||
|
||||
dates = common_datearray(dataframes)
|
||||
|
||||
assert dates.size == dataframes['UNITTEST/BTC']['date'].size
|
||||
assert dates[0] == dataframes['UNITTEST/BTC']['date'][0]
|
||||
assert dates[-1] == dataframes['UNITTEST/BTC']['date'][-1]
|
||||
assert dates[-1] == dataframes['UNITTEST/BTC']['date'].iloc[-1]
|
||||
|
||||
|
||||
def test_file_dump_json(mocker) -> None:
|
||||
file_open = mocker.patch('freqtrade.misc.open', MagicMock())
|
||||
json_dump = mocker.patch('json.dump', MagicMock())
|
||||
json_dump = mocker.patch('rapidjson.dump', MagicMock())
|
||||
file_dump_json('somefile', [1, 2, 3])
|
||||
assert file_open.call_count == 1
|
||||
assert json_dump.call_count == 1
|
||||
file_open = mocker.patch('freqtrade.misc.gzip.open', MagicMock())
|
||||
json_dump = mocker.patch('json.dump', MagicMock())
|
||||
json_dump = mocker.patch('rapidjson.dump', MagicMock())
|
||||
file_dump_json('somefile', [1, 2, 3], True)
|
||||
assert file_open.call_count == 1
|
||||
assert json_dump.call_count == 1
|
||||
|
||||
|
||||
def test_file_load_json(mocker) -> None:
|
||||
|
||||
# 7m .json does not exist
|
||||
ret = file_load_json(make_testdata_path(None).joinpath('UNITTEST_BTC-7m.json'))
|
||||
assert not ret
|
||||
# 1m json exists (but no .gz exists)
|
||||
ret = file_load_json(make_testdata_path(None).joinpath('UNITTEST_BTC-1m.json'))
|
||||
assert ret
|
||||
# 8 .json is empty and will fail if it's loaded. .json.gz is a copy of 1.json
|
||||
ret = file_load_json(make_testdata_path(None).joinpath('UNITTEST_BTC-8m.json'))
|
||||
assert ret
|
||||
|
||||
|
||||
def test_format_ms_time() -> None:
|
||||
# Date 2018-04-10 18:02:01
|
||||
date_in_epoch_ms = 1523383321000
|
||||
|
||||
@@ -510,12 +510,14 @@ def test_migrate_new(mocker, default_conf, fee, caplog):
|
||||
assert trade.pair == "ETC/BTC"
|
||||
assert trade.exchange == "binance"
|
||||
assert trade.max_rate == 0.0
|
||||
assert trade.min_rate is None
|
||||
assert trade.stop_loss == 0.0
|
||||
assert trade.initial_stop_loss == 0.0
|
||||
assert trade.sell_reason is None
|
||||
assert trade.strategy is None
|
||||
assert trade.ticker_interval is None
|
||||
assert trade.stoploss_order_id is None
|
||||
assert trade.stoploss_last_update is None
|
||||
assert log_has("trying trades_bak1", caplog.record_tuples)
|
||||
assert log_has("trying trades_bak2", caplog.record_tuples)
|
||||
assert log_has("Running database migration - backup available as trades_bak2",
|
||||
@@ -584,7 +586,58 @@ def test_migrate_mid_state(mocker, default_conf, fee, caplog):
|
||||
caplog.record_tuples)
|
||||
|
||||
|
||||
def test_adjust_stop_loss(limit_buy_order, limit_sell_order, fee):
|
||||
def test_adjust_stop_loss(fee):
|
||||
trade = Trade(
|
||||
pair='ETH/BTC',
|
||||
stake_amount=0.001,
|
||||
fee_open=fee.return_value,
|
||||
fee_close=fee.return_value,
|
||||
exchange='bittrex',
|
||||
open_rate=1,
|
||||
max_rate=1,
|
||||
)
|
||||
|
||||
trade.adjust_stop_loss(trade.open_rate, 0.05, True)
|
||||
assert trade.stop_loss == 0.95
|
||||
assert trade.stop_loss_pct == -0.05
|
||||
assert trade.initial_stop_loss == 0.95
|
||||
assert trade.initial_stop_loss_pct == -0.05
|
||||
|
||||
# Get percent of profit with a lower rate
|
||||
trade.adjust_stop_loss(0.96, 0.05)
|
||||
assert trade.stop_loss == 0.95
|
||||
assert trade.stop_loss_pct == -0.05
|
||||
assert trade.initial_stop_loss == 0.95
|
||||
assert trade.initial_stop_loss_pct == -0.05
|
||||
|
||||
# Get percent of profit with a custom rate (Higher than open rate)
|
||||
trade.adjust_stop_loss(1.3, -0.1)
|
||||
assert round(trade.stop_loss, 8) == 1.17
|
||||
assert trade.stop_loss_pct == -0.1
|
||||
assert trade.initial_stop_loss == 0.95
|
||||
assert trade.initial_stop_loss_pct == -0.05
|
||||
|
||||
# current rate lower again ... should not change
|
||||
trade.adjust_stop_loss(1.2, 0.1)
|
||||
assert round(trade.stop_loss, 8) == 1.17
|
||||
assert trade.initial_stop_loss == 0.95
|
||||
assert trade.initial_stop_loss_pct == -0.05
|
||||
|
||||
# current rate higher... should raise stoploss
|
||||
trade.adjust_stop_loss(1.4, 0.1)
|
||||
assert round(trade.stop_loss, 8) == 1.26
|
||||
assert trade.initial_stop_loss == 0.95
|
||||
assert trade.initial_stop_loss_pct == -0.05
|
||||
|
||||
# Initial is true but stop_loss set - so doesn't do anything
|
||||
trade.adjust_stop_loss(1.7, 0.1, True)
|
||||
assert round(trade.stop_loss, 8) == 1.26
|
||||
assert trade.initial_stop_loss == 0.95
|
||||
assert trade.initial_stop_loss_pct == -0.05
|
||||
assert trade.stop_loss_pct == -0.1
|
||||
|
||||
|
||||
def test_adjust_min_max_rates(fee):
|
||||
trade = Trade(
|
||||
pair='ETH/BTC',
|
||||
stake_amount=0.001,
|
||||
@@ -594,37 +647,66 @@ def test_adjust_stop_loss(limit_buy_order, limit_sell_order, fee):
|
||||
open_rate=1,
|
||||
)
|
||||
|
||||
trade.adjust_stop_loss(trade.open_rate, 0.05, True)
|
||||
assert trade.stop_loss == 0.95
|
||||
trade.adjust_min_max_rates(trade.open_rate)
|
||||
assert trade.max_rate == 1
|
||||
assert trade.initial_stop_loss == 0.95
|
||||
assert trade.min_rate == 1
|
||||
|
||||
# Get percent of profit with a lowre rate
|
||||
trade.adjust_stop_loss(0.96, 0.05)
|
||||
assert trade.stop_loss == 0.95
|
||||
# check min adjusted, max remained
|
||||
trade.adjust_min_max_rates(0.96)
|
||||
assert trade.max_rate == 1
|
||||
assert trade.initial_stop_loss == 0.95
|
||||
assert trade.min_rate == 0.96
|
||||
|
||||
# Get percent of profit with a custom rate (Higher than open rate)
|
||||
trade.adjust_stop_loss(1.3, -0.1)
|
||||
assert round(trade.stop_loss, 8) == 1.17
|
||||
assert trade.max_rate == 1.3
|
||||
assert trade.initial_stop_loss == 0.95
|
||||
# check max adjusted, min remains
|
||||
trade.adjust_min_max_rates(1.05)
|
||||
assert trade.max_rate == 1.05
|
||||
assert trade.min_rate == 0.96
|
||||
|
||||
# current rate lower again ... should not change
|
||||
trade.adjust_stop_loss(1.2, 0.1)
|
||||
assert round(trade.stop_loss, 8) == 1.17
|
||||
assert trade.max_rate == 1.3
|
||||
assert trade.initial_stop_loss == 0.95
|
||||
# current rate "in the middle" - no adjustment
|
||||
trade.adjust_min_max_rates(1.03)
|
||||
assert trade.max_rate == 1.05
|
||||
assert trade.min_rate == 0.96
|
||||
|
||||
# current rate higher... should raise stoploss
|
||||
trade.adjust_stop_loss(1.4, 0.1)
|
||||
assert round(trade.stop_loss, 8) == 1.26
|
||||
assert trade.max_rate == 1.4
|
||||
assert trade.initial_stop_loss == 0.95
|
||||
|
||||
# Initial is true but stop_loss set - so doesn't do anything
|
||||
trade.adjust_stop_loss(1.7, 0.1, True)
|
||||
assert round(trade.stop_loss, 8) == 1.26
|
||||
assert trade.max_rate == 1.4
|
||||
assert trade.initial_stop_loss == 0.95
|
||||
def test_get_open(default_conf, fee):
|
||||
init(default_conf)
|
||||
|
||||
# Simulate dry_run entries
|
||||
trade = Trade(
|
||||
pair='ETH/BTC',
|
||||
stake_amount=0.001,
|
||||
amount=123.0,
|
||||
fee_open=fee.return_value,
|
||||
fee_close=fee.return_value,
|
||||
open_rate=0.123,
|
||||
exchange='bittrex',
|
||||
open_order_id='dry_run_buy_12345'
|
||||
)
|
||||
Trade.session.add(trade)
|
||||
|
||||
trade = Trade(
|
||||
pair='ETC/BTC',
|
||||
stake_amount=0.001,
|
||||
amount=123.0,
|
||||
fee_open=fee.return_value,
|
||||
fee_close=fee.return_value,
|
||||
open_rate=0.123,
|
||||
exchange='bittrex',
|
||||
is_open=False,
|
||||
open_order_id='dry_run_sell_12345'
|
||||
)
|
||||
Trade.session.add(trade)
|
||||
|
||||
# Simulate prod entry
|
||||
trade = Trade(
|
||||
pair='ETC/BTC',
|
||||
stake_amount=0.001,
|
||||
amount=123.0,
|
||||
fee_open=fee.return_value,
|
||||
fee_close=fee.return_value,
|
||||
open_rate=0.123,
|
||||
exchange='bittrex',
|
||||
open_order_id='prod_buy_12345'
|
||||
)
|
||||
Trade.session.add(trade)
|
||||
|
||||
assert len(Trade.get_open_trades()) == 2
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user