Compare commits
670 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5c8c53cff8 | |||
| 846b7734e1 | |||
| c72d18270e | |||
| 02836368fb | |||
| d282027858 | |||
| d329ad28c2 | |||
| 2de86af51e | |||
| 97780ee5bf | |||
| e162f98cf5 | |||
| c6967b11be | |||
| 1e5d353cf7 | |||
| 17a538b5ba | |||
| fc746214f6 | |||
| 58432c1cfa | |||
| 69119764bf | |||
| a20e641bcd | |||
| ad68eff8f4 | |||
| 68552a61bd | |||
| b7419305d4 | |||
| 8cc2c5010a | |||
| 872154a6fc | |||
| c8ee8e82f9 | |||
| 5cbcf72501 | |||
| 35876cf8ee | |||
| ac60871ff9 | |||
| 866e34a983 | |||
| 7107971820 | |||
| 3484590640 | |||
| 971b7d074c | |||
| ec89aad10b | |||
| fc13a99b33 | |||
| 03fb204408 | |||
| 0a96aa69b9 | |||
| ddbfce01b5 | |||
| 12e75e849d | |||
| 916a847639 | |||
| 4769b50709 | |||
| 18dd9cf803 | |||
| def204448a | |||
| 63e652619f | |||
| 3cb4b10656 | |||
| 23c3757c7a | |||
| b20aee7653 | |||
| 4d7c4352a7 | |||
| a5c914951f | |||
| 9ab08d513a | |||
| 87ce7dc02c | |||
| 3c7c4bc02f | |||
| 0484b891f1 | |||
| 71689d9d6f | |||
| 881247a823 | |||
| d26154f994 | |||
| 0e14dd6190 | |||
| 3676514ba6 | |||
| 9ec23a0292 | |||
| 1272a15c35 | |||
| a3a175e332 | |||
| 71b777ef34 | |||
| c4cd547451 | |||
| b4e8122fd3 | |||
| b1393f1bd4 | |||
| 34c5c68a91 | |||
| c9a018cf0e | |||
| 0333abcbdc | |||
| 0440b3ef75 | |||
| d9ed8c6560 | |||
| 2f2467256c | |||
| 26f0fe2383 | |||
| 5e3da30ab9 | |||
| 651d2c06b9 | |||
| b371593084 | |||
| 3096cddbcf | |||
| 5bbe6aacfd | |||
| fe4bf271b4 | |||
| 0d3d1e6d9a | |||
| 57e01329ce | |||
| 99359a7f85 | |||
| 5f0932f5ed | |||
| fece88e7cd | |||
| c8eb2523ac | |||
| 964b439119 | |||
| ee4f4f2d0d | |||
| 7c215688c0 | |||
| 087ca2bd4a | |||
| 6193df36a3 | |||
| 893b43766f | |||
| a70ca6f612 | |||
| e5c783d2db | |||
| e1b652d890 | |||
| 4e98b5f710 | |||
| 901b3f6fe7 | |||
| d0a9d927dd | |||
| 16eb95c71d | |||
| 054ed0a7b6 | |||
| 82853e37a1 | |||
| 81c6336e11 | |||
| 6404bd8b2b | |||
| 9a9a6eaa63 | |||
| 67cdab6ee9 | |||
| 546ea430c9 | |||
| 4cc4f0ffa2 | |||
| 58470ba9d0 | |||
| c580e8783f | |||
| bc1ad3acbd | |||
| d2e328b8bd | |||
| 93e9c4fa65 | |||
| 8d231dbf31 | |||
| b178cc5f31 | |||
| 6ee0f16e4f | |||
| 1d701967b7 | |||
| d6b43c5eed | |||
| 3670699ea2 | |||
| 9b11091fc7 | |||
| 58dfffe87a | |||
| e573409925 | |||
| e3fda16d16 | |||
| 71d3572c27 | |||
| 62667d123f | |||
| cfd5af67ca | |||
| 47a952e41c | |||
| c9f43587ec | |||
| e79a58e1c4 | |||
| c62e52c759 | |||
| 5ab61d9da4 | |||
| 55efaec83d | |||
| c5c2c8c185 | |||
| 755ce3a858 | |||
| 105cd99395 | |||
| db7799d2fb | |||
| 30f94ef5b7 | |||
| 6c259ddca1 | |||
| 0f82ea8767 | |||
| eac5d53a64 | |||
| 4b43ccae11 | |||
| 8a2763d275 | |||
| 4b3230689c | |||
| aa86c49640 | |||
| 1adc8836dd | |||
| 92993c0c4c | |||
| 9b2c116d9b | |||
| 2ad85a6957 | |||
| a0e92f5a47 | |||
| 17f0697c43 | |||
| 199e3f91f2 | |||
| cc14cf23b1 | |||
| 327f750ead | |||
| a304080c08 | |||
| 020d4b5b4d | |||
| 78cb1e608f | |||
| b84a2fcac7 | |||
| c0119d7baa | |||
| 0bd513012a | |||
| 3f6cd9ee51 | |||
| 8964c138f1 | |||
| ef23f0fcba | |||
| 074343f0f1 | |||
| 966eb59fd3 | |||
| 778bd7b3b0 | |||
| b4cd46d6db | |||
| 1d73b57e8c | |||
| 476703bf76 | |||
| cd09d3567f | |||
| 4c25e9d21a | |||
| dd08c134b4 | |||
| aa8bb27cf0 | |||
| d428d48393 | |||
| 3bdfa85237 | |||
| 95a824fbe7 | |||
| bb85efd6ad | |||
| 7321a14c35 | |||
| 2745a5d334 | |||
| d123d3bb82 | |||
| b14873400d | |||
| d9b95a4c27 | |||
| 71178ff1d2 | |||
| d3d9f3281e | |||
| 3b4b833dd0 | |||
| fcc87399cd | |||
| 654f8a7573 | |||
| 2fdb9663d7 | |||
| 3739a10735 | |||
| 9a425af76f | |||
| 3c48208b31 | |||
| 68db8d0201 | |||
| 2207773678 | |||
| cbe6d52a73 | |||
| b7fc0190f7 | |||
| 4061eaf888 | |||
| ef042ae5ec | |||
| 6ee792069d | |||
| 46c81d7018 | |||
| caac77c90b | |||
| af05e3d747 | |||
| 59a287106d | |||
| 8b5e6bf9be | |||
| d9882978d5 | |||
| 04f2b7bad6 | |||
| 8597709b2e | |||
| 2fea75e312 | |||
| 511e4d16d5 | |||
| e0f780f10e | |||
| 44689d058b | |||
| 1431b2b44a | |||
| 106bda51d4 | |||
| 90e4eb59b2 | |||
| 701f6fc050 | |||
| 0235db48a8 | |||
| e9e7bf3caf | |||
| 4464b02719 | |||
| 4ed9ffbf31 | |||
| c017366086 | |||
| 34bce4d251 | |||
| 6754072bca | |||
| 15771043f7 | |||
| b417a0297b | |||
| 5daafaabc2 | |||
| 08db2f05aa | |||
| 0654186400 | |||
| d85518ccb2 | |||
| c34cb9eb12 | |||
| cb01a46089 | |||
| 0bcbb28d51 | |||
| e2a47ee95a | |||
| 36836ea803 | |||
| 19d9adaf9c | |||
| cf078f8093 | |||
| 5ddca4e9f9 | |||
| 6db66b1e58 | |||
| 0a903e45f2 | |||
| d0a2b9403e | |||
| a18c85ec64 | |||
| 0914b8b5f4 | |||
| cb2a871538 | |||
| ef877b5fcc | |||
| 2738f3e437 | |||
| 79f765a930 | |||
| 696f8b308a | |||
| 4a2473e7e9 | |||
| a0caa7c5a2 | |||
| 388a0c605c | |||
| 55e4d08fd8 | |||
| 7c00a4ed13 | |||
| 793cc1acc0 | |||
| 33d910ccea | |||
| 8a44337c30 | |||
| 35871d7b4b | |||
| 786d4e03fc | |||
| 5e5b56e445 | |||
| 384ebc5b38 | |||
| 8567af8d28 | |||
| 88e818926a | |||
| 4bcb4fdd82 | |||
| 0b3a6aa9de | |||
| 12ea1cde80 | |||
| df73b8288c | |||
| a50291cd90 | |||
| be8ea685de | |||
| d050beb627 | |||
| 1380cadf15 | |||
| 72eeb6561c | |||
| eeb460e55c | |||
| e8d0b01991 | |||
| 94020a664b | |||
| 8c5194d5e2 | |||
| 67e81c9018 | |||
| 25ebdb4cb3 | |||
| 1657fd1f0f | |||
| 63e702a3bf | |||
| e9f21d0209 | |||
| a044649eef | |||
| 48317c2307 | |||
| d598c91de3 | |||
| 5003c2af21 | |||
| 6963a92332 | |||
| e2863e1620 | |||
| 869756d87d | |||
| 203890844b | |||
| ba76b87952 | |||
| fbab18b081 | |||
| f7178ecd6f | |||
| 59cbac7147 | |||
| fbc70a60f7 | |||
| b45365d385 | |||
| 9990780e6b | |||
| 65df2f30c1 | |||
| e7aa706f73 | |||
| 3619247123 | |||
| 047dac7b7d | |||
| 7646849405 | |||
| 10ae0ed9c1 | |||
| e060e729df | |||
| d81bbba4c2 | |||
| d52936fd42 | |||
| 21a5abf25d | |||
| c3980a2746 | |||
| 2cadbd1229 | |||
| 0f57291aa7 | |||
| 0e9169e1ec | |||
| 8680b5faa0 | |||
| 03149cfa42 | |||
| 4eb4732de7 | |||
| 3a5b22c397 | |||
| c3a5d4b4e4 | |||
| b97ff3a784 | |||
| 806af7d796 | |||
| 3c25737f38 | |||
| bf98851dc1 | |||
| 202b72fd8e | |||
| 6f60117319 | |||
| 7070ec30e4 | |||
| bf77019d1c | |||
| b776e5a8e0 | |||
| ca208305a0 | |||
| 972c5c327c | |||
| 80edfd1531 | |||
| 58cd455642 | |||
| caf59d25e8 | |||
| 7df32a34a0 | |||
| 48097f4a7d | |||
| ca3f349d84 | |||
| 0815bb6244 | |||
| 835cb54876 | |||
| 08c2765633 | |||
| f9202c3f6b | |||
| eb186e22d6 | |||
| cbc323875b | |||
| 736b583ff4 | |||
| 757ec53877 | |||
| 7814927dd1 | |||
| 5f8ff373ab | |||
| f286cb0a90 | |||
| 59bd1a1f1f | |||
| e52f6ca6c0 | |||
| e6663c0304 | |||
| ced92300e0 | |||
| f9d061b648 | |||
| e6661a33f9 | |||
| d2afe281bf | |||
| c237aa00b8 | |||
| 23efa4c9c3 | |||
| 8b028734c2 | |||
| 51feeddc5c | |||
| af3e42f59d | |||
| 34d58eb7d5 | |||
| ca0a04fba5 | |||
| 84b3f9924a | |||
| 50b264c6f8 | |||
| 88e8a9fe2b | |||
| d65aef72e8 | |||
| 8273c0c2cd | |||
| c7624b1ed6 | |||
| 54536a1c8e | |||
| 7daa06a207 | |||
| da647735b6 | |||
| 7d0ecfde93 | |||
| 2ef716e94c | |||
| de68850d28 | |||
| 59cefda283 | |||
| babcd5887f | |||
| c9a5e5a98c | |||
| 51dc5811c2 | |||
| 05e36f7b21 | |||
| 0738cae4a0 | |||
| da3c42bbbc | |||
| e728e3bc75 | |||
| 315783441d | |||
| 62f1421cfb | |||
| 52f12b704b | |||
| ee5051f788 | |||
| b30b1227e3 | |||
| dd2f8db392 | |||
| 5a76d81529 | |||
| b9851c78ad | |||
| 777cf2ae7a | |||
| 3729b3d793 | |||
| 39fc78205d | |||
| 46a67e8d4f | |||
| 69017805c0 | |||
| bcec611973 | |||
| fbb11a394a | |||
| 5cb916977e | |||
| 7d4c9bc0cf | |||
| ea2beb46e7 | |||
| 216ee8117a | |||
| 9c1210b34e | |||
| 921e034266 | |||
| 6f358b16c0 | |||
| 264ab2c471 | |||
| a9d6f0023a | |||
| 31af1d5dc7 | |||
| 588bbb45b5 | |||
| 278c999f1f | |||
| 825ae15109 | |||
| 30cacc7cca | |||
| 7ed037bad7 | |||
| 77b00b2a12 | |||
| 773bc386f7 | |||
| 90dacaca09 | |||
| 3689ad16b5 | |||
| ab9954350e | |||
| 533f11d9eb | |||
| 551033a7c3 | |||
| e003930e18 | |||
| 2efef72ec2 | |||
| eb40fc698d | |||
| 751db2be78 | |||
| 6ea353447e | |||
| 5a3839320d | |||
| 555f4b51e1 | |||
| be82248e01 | |||
| 7bed7801cc | |||
| eb409de916 | |||
| 8ce39a6d75 | |||
| 72dc65cb6a | |||
| c94c667fb1 | |||
| 2a0175f629 | |||
| cd68173440 | |||
| c920e3a031 | |||
| 83afc4ac7e | |||
| 19f62649ea | |||
| e4186cde9e | |||
| 61ed6aee62 | |||
| 051b6e9458 | |||
| 44a24685ac | |||
| 1cde980c08 | |||
| 05ef4f9b6f | |||
| 53f00f248e | |||
| a9cd282500 | |||
| f142abfb76 | |||
| c98c6c38dc | |||
| 26aa14dbfc | |||
| 04cd931cc8 | |||
| b8a6330c3f | |||
| 949c3c660b | |||
| 9297a90d7f | |||
| b19f17fdfa | |||
| bbdc6c0f5c | |||
| 528c65c194 | |||
| a932df7320 | |||
| 2d9b05a3ab | |||
| 7cf1d25dc6 | |||
| 19c955d505 | |||
| bd243da47e | |||
| bf24c3b279 | |||
| e9c72acff2 | |||
| 09fd22c2f8 | |||
| 45721ed62e | |||
| 5182045cda | |||
| 51ab8fecfc | |||
| b36907133c | |||
| b6d899344e | |||
| 095f9fc1ab | |||
| 0ab9eb7b05 | |||
| d0c582e137 | |||
| d3d4464983 | |||
| 1d0934074c | |||
| 9382fb3be8 | |||
| 223af95da7 | |||
| 8b68b55de4 | |||
| 99592d1a12 | |||
| b69f5aaac3 | |||
| 0c1fefe6e7 | |||
| a049ff9371 | |||
| 0c51e2637f | |||
| 7492b75e1c | |||
| 9a73f7a7b8 | |||
| 7813d1acd6 | |||
| 24dfd9b93b | |||
| 7d65b3e1b4 | |||
| 2c20464983 | |||
| e97d9013d5 | |||
| cf43427be5 | |||
| 7ae41be975 | |||
| 1e18b35f22 | |||
| bb78285661 | |||
| b47ba8cfd3 | |||
| 1dccdf0594 | |||
| 5da48d8ffc | |||
| 4f4b7c5625 | |||
| 9dcf236387 | |||
| 97bc5804fd | |||
| beab966851 | |||
| 00a7e8f9a2 | |||
| 59dc526683 | |||
| aef7f9dc03 | |||
| abc6a08397 | |||
| eb4da8a6f6 | |||
| 494fd734bc | |||
| 9174f60b1d | |||
| c2905a4522 | |||
| adf03e2ee3 | |||
| fe5f085ec1 | |||
| 748ac50d83 | |||
| d2069c1729 | |||
| 38cf50830a | |||
| bf96a43efb | |||
| 22b4555926 | |||
| 7fb3632e7b | |||
| e5f0fe288a | |||
| 58aaaffe2b | |||
| c62aefbfde | |||
| 16dfde22fc | |||
| bbbc8a760c | |||
| 9b45bb2e24 | |||
| e69c21c9f5 | |||
| 72933859cf | |||
| 0a5cee6a73 | |||
| a80c979482 | |||
| 4a4b695b94 | |||
| a8c246ce0d | |||
| c6e979ddda | |||
| 1a78346cf1 | |||
| e6d0d53e47 | |||
| 68680bb2c6 | |||
| 7de415a6a4 | |||
| f46fa440f0 | |||
| 56177d7e92 | |||
| 41584317e4 | |||
| 3264e2c31d | |||
| fadc7a2051 | |||
| cebc55687b | |||
| 5940279f7b | |||
| 35f6333b67 | |||
| 262b044969 | |||
| a571df784c | |||
| 078aa8327b | |||
| 10945edbe6 | |||
| 5d9b69cbfe | |||
| 89117dd53f | |||
| 4af9654696 | |||
| 1e0ce7d47a | |||
| 27cd54b42c | |||
| ec64a182f9 | |||
| dd30df7057 | |||
| 4c6e33aa82 | |||
| 8cb934849a | |||
| c627aee096 | |||
| 9d552d45c2 | |||
| 1e1b8dbe53 | |||
| 2d9d8dc976 | |||
| ba674fc796 | |||
| 58550515ad | |||
| 27bae60b68 | |||
| 646dd63faf | |||
| 8d2b389e27 | |||
| fa174a392a | |||
| 042e35e8d3 | |||
| b76513ce33 | |||
| 368bfcf476 | |||
| fee3c598d0 | |||
| 69264cc164 | |||
| e81929bc55 | |||
| 0843b19b6c | |||
| 813b472c6c | |||
| 2f079711ec | |||
| 97e9d2dc42 | |||
| 7344f20803 | |||
| bfe04464b4 | |||
| 2225f5661b | |||
| 9e77c93a54 | |||
| b65fa98cee | |||
| b57821b273 | |||
| db7f9598b0 | |||
| e547da10de | |||
| 5a0c15f377 | |||
| 0f5b69b4f2 | |||
| 86d4497aaf | |||
| 4b80961c65 | |||
| 785cc9df85 | |||
| 1bfecb0313 | |||
| b88a561eb5 | |||
| 4bf026605e | |||
| db6933856f | |||
| 01107ffa59 | |||
| 74f678a26f | |||
| bf93648198 | |||
| 51dccaeb4c | |||
| ed4252af53 | |||
| 2fde902c82 | |||
| 4ea75af2d9 | |||
| 1bba0cf7fc | |||
| b1fd0c73c7 | |||
| 29eb6d938b | |||
| 19620470bd | |||
| 7a69b01b9b | |||
| bc531cf846 | |||
| 14908e52e2 | |||
| a86bf8d6d7 | |||
| 3662ca3ca6 | |||
| 5fae03f7be | |||
| f7f0f3bebb | |||
| ccbab6ee6f | |||
| ef12dafea8 | |||
| 08a65b50aa | |||
| d28d6cbdb4 | |||
| 41a6709ece | |||
| 756f5d5408 | |||
| 422b9c8fbc | |||
| 40ec2c4921 | |||
| 5cf7ad85a0 | |||
| f02c9f0435 | |||
| c59b5e7781 | |||
| e525c6694b | |||
| 897c14e2e5 | |||
| 6c00bf423b | |||
| 094984eb2f | |||
| 081411fba4 | |||
| 178c0972ff | |||
| 910e317a45 | |||
| 1ef5adbb0e | |||
| f5db856a75 | |||
| b2ad40253f | |||
| 1e0d622d80 | |||
| 1d941249ed | |||
| 5bfd3fdc33 | |||
| 753b807a45 | |||
| 04409602a6 | |||
| b2796b850b | |||
| 8c633aab19 | |||
| f14b4133c3 | |||
| 8f2e4aa4fd | |||
| 3c2e043e82 | |||
| 609ed2d7b3 | |||
| 183166b3fb | |||
| 12dc91719e | |||
| cd071c3bdc | |||
| 0618ecce47 | |||
| 13438ad8de | |||
| 60c2b1d6ca | |||
| eaf4ffcbaf | |||
| 79e59bdda0 | |||
| b409ab5ead | |||
| 790c7036a1 | |||
| 73902f507a | |||
| 1a80f6bc4e | |||
| 5feb7fe654 | |||
| 980960bc6a | |||
| 52c614733f | |||
| e913d12c71 | |||
| 5dc24232ca | |||
| ef2115d667 | |||
| 74476eae43 | |||
| 84335d58b3 | |||
| f175fc6e9b | |||
| 9edd7e6bc8 | |||
| 7478c56ca5 | |||
| 1f36f4802a | |||
| 4d920d7866 | |||
| 19fb3f9b54 | |||
| fafc102573 | |||
| 3868f9c698 | |||
| 0204f666b3 | |||
| f32a13bfb0 | |||
| 4809c9f07a | |||
| 19af144b33 | |||
| 4db7962048 | |||
| 7e6f2cba53 | |||
| c6199e5ca6 | |||
| f7ff1dc610 | |||
| 8ad6eb9896 | |||
| 74709461e3 | |||
| 9e6cc5ebbd | |||
| a2d8f92e05 | |||
| a7d90e2a25 | |||
| 83b37e2f78 | |||
| 488629096b | |||
| a3f167f6df | |||
| 1e8814b43e | |||
| 2e430519e3 | |||
| 2164b02c66 |
+96
-61
@@ -31,7 +31,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python-version }}
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
@@ -44,7 +44,6 @@ jobs:
|
|||||||
|
|
||||||
- name: pip cache (linux)
|
- name: pip cache (linux)
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v3
|
||||||
if: runner.os == 'Linux'
|
|
||||||
with:
|
with:
|
||||||
path: ~/.cache/pip
|
path: ~/.cache/pip
|
||||||
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
||||||
@@ -55,7 +54,6 @@ jobs:
|
|||||||
cd build_helpers && ./install_ta-lib.sh ${HOME}/dependencies/; cd ..
|
cd build_helpers && ./install_ta-lib.sh ${HOME}/dependencies/; cd ..
|
||||||
|
|
||||||
- name: Installation - *nix
|
- name: Installation - *nix
|
||||||
if: runner.os == 'Linux'
|
|
||||||
run: |
|
run: |
|
||||||
python -m pip install --upgrade pip wheel
|
python -m pip install --upgrade pip wheel
|
||||||
export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH
|
export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH
|
||||||
@@ -90,7 +88,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Backtesting (multi)
|
- name: Backtesting (multi)
|
||||||
run: |
|
run: |
|
||||||
cp config_examples/config_bittrex.example.json config.json
|
cp tests/testdata/config.tests.json config.json
|
||||||
freqtrade create-userdir --userdir user_data
|
freqtrade create-userdir --userdir user_data
|
||||||
freqtrade new-strategy -s AwesomeStrategy
|
freqtrade new-strategy -s AwesomeStrategy
|
||||||
freqtrade new-strategy -s AwesomeStrategyMin --template minimal
|
freqtrade new-strategy -s AwesomeStrategyMin --template minimal
|
||||||
@@ -98,7 +96,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Hyperopt
|
- name: Hyperopt
|
||||||
run: |
|
run: |
|
||||||
cp config_examples/config_bittrex.example.json config.json
|
cp tests/testdata/config.tests.json config.json
|
||||||
freqtrade create-userdir --userdir user_data
|
freqtrade create-userdir --userdir user_data
|
||||||
freqtrade hyperopt --datadir tests/testdata -e 6 --strategy SampleStrategy --hyperopt-loss SharpeHyperOptLossDaily --print-all
|
freqtrade hyperopt --datadir tests/testdata -e 6 --strategy SampleStrategy --hyperopt-loss SharpeHyperOptLossDaily --print-all
|
||||||
|
|
||||||
@@ -108,7 +106,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Run Ruff
|
- name: Run Ruff
|
||||||
run: |
|
run: |
|
||||||
ruff check --format=github .
|
ruff check --output-format=github .
|
||||||
|
|
||||||
- name: Mypy
|
- name: Mypy
|
||||||
run: |
|
run: |
|
||||||
@@ -122,18 +120,18 @@ jobs:
|
|||||||
details: Freqtrade CI failed on ${{ matrix.os }}
|
details: Freqtrade CI failed on ${{ matrix.os }}
|
||||||
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
||||||
|
|
||||||
build_macos:
|
build-macos:
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [ macos-latest ]
|
os: [ "macos-latest", "macos-13" ]
|
||||||
python-version: ["3.9", "3.10", "3.11"]
|
python-version: ["3.9", "3.10", "3.11"]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python-version }}
|
python-version: ${{ matrix.python-version }}
|
||||||
check-latest: true
|
check-latest: true
|
||||||
@@ -143,14 +141,13 @@ jobs:
|
|||||||
id: cache
|
id: cache
|
||||||
with:
|
with:
|
||||||
path: ~/dependencies/
|
path: ~/dependencies/
|
||||||
key: ${{ runner.os }}-dependencies
|
key: ${{ matrix.os }}-dependencies
|
||||||
|
|
||||||
- name: pip cache (macOS)
|
- name: pip cache (macOS)
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v3
|
||||||
if: runner.os == 'macOS'
|
|
||||||
with:
|
with:
|
||||||
path: ~/Library/Caches/pip
|
path: ~/Library/Caches/pip
|
||||||
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
key: ${{ matrix.os }}-${{ matrix.python-version }}-pip
|
||||||
|
|
||||||
- name: TA binary *nix
|
- name: TA binary *nix
|
||||||
if: steps.cache.outputs.cache-hit != 'true'
|
if: steps.cache.outputs.cache-hit != 'true'
|
||||||
@@ -158,7 +155,6 @@ jobs:
|
|||||||
cd build_helpers && ./install_ta-lib.sh ${HOME}/dependencies/; cd ..
|
cd build_helpers && ./install_ta-lib.sh ${HOME}/dependencies/; cd ..
|
||||||
|
|
||||||
- name: Installation - macOS
|
- name: Installation - macOS
|
||||||
if: runner.os == 'macOS'
|
|
||||||
run: |
|
run: |
|
||||||
# brew update
|
# brew update
|
||||||
# TODO: Should be the brew upgrade
|
# TODO: Should be the brew upgrade
|
||||||
@@ -166,16 +162,21 @@ jobs:
|
|||||||
# https://github.com/actions/runner-images/issues/6817
|
# https://github.com/actions/runner-images/issues/6817
|
||||||
rm /usr/local/bin/2to3 || true
|
rm /usr/local/bin/2to3 || true
|
||||||
rm /usr/local/bin/2to3-3.11 || true
|
rm /usr/local/bin/2to3-3.11 || true
|
||||||
|
rm /usr/local/bin/2to3-3.12 || true
|
||||||
rm /usr/local/bin/idle3 || true
|
rm /usr/local/bin/idle3 || true
|
||||||
rm /usr/local/bin/idle3.11 || true
|
rm /usr/local/bin/idle3.11 || true
|
||||||
|
rm /usr/local/bin/idle3.12 || true
|
||||||
rm /usr/local/bin/pydoc3 || true
|
rm /usr/local/bin/pydoc3 || true
|
||||||
rm /usr/local/bin/pydoc3.11 || true
|
rm /usr/local/bin/pydoc3.11 || true
|
||||||
|
rm /usr/local/bin/pydoc3.12 || true
|
||||||
rm /usr/local/bin/python3 || true
|
rm /usr/local/bin/python3 || true
|
||||||
rm /usr/local/bin/python3.11 || true
|
rm /usr/local/bin/python3.11 || true
|
||||||
|
rm /usr/local/bin/python3.12 || true
|
||||||
rm /usr/local/bin/python3-config || true
|
rm /usr/local/bin/python3-config || true
|
||||||
rm /usr/local/bin/python3.11-config || true
|
rm /usr/local/bin/python3.11-config || true
|
||||||
|
rm /usr/local/bin/python3.12-config || true
|
||||||
|
|
||||||
brew install hdf5 c-blosc
|
brew install hdf5 c-blosc libomp
|
||||||
python -m pip install --upgrade pip wheel
|
python -m pip install --upgrade pip wheel
|
||||||
export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH
|
export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH
|
||||||
export TA_LIBRARY_PATH=${HOME}/dependencies/lib
|
export TA_LIBRARY_PATH=${HOME}/dependencies/lib
|
||||||
@@ -200,14 +201,14 @@ jobs:
|
|||||||
|
|
||||||
- name: Backtesting
|
- name: Backtesting
|
||||||
run: |
|
run: |
|
||||||
cp config_examples/config_bittrex.example.json config.json
|
cp tests/testdata/config.tests.json config.json
|
||||||
freqtrade create-userdir --userdir user_data
|
freqtrade create-userdir --userdir user_data
|
||||||
freqtrade new-strategy -s AwesomeStrategyAdv --template advanced
|
freqtrade new-strategy -s AwesomeStrategyAdv --template advanced
|
||||||
freqtrade backtesting --datadir tests/testdata --strategy AwesomeStrategyAdv
|
freqtrade backtesting --datadir tests/testdata --strategy AwesomeStrategyAdv
|
||||||
|
|
||||||
- name: Hyperopt
|
- name: Hyperopt
|
||||||
run: |
|
run: |
|
||||||
cp config_examples/config_bittrex.example.json config.json
|
cp tests/testdata/config.tests.json config.json
|
||||||
freqtrade create-userdir --userdir user_data
|
freqtrade create-userdir --userdir user_data
|
||||||
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt-loss SharpeHyperOptLossDaily --print-all
|
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt-loss SharpeHyperOptLossDaily --print-all
|
||||||
|
|
||||||
@@ -217,7 +218,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Run Ruff
|
- name: Run Ruff
|
||||||
run: |
|
run: |
|
||||||
ruff check --format=github .
|
ruff check --output-format=github .
|
||||||
|
|
||||||
- name: Mypy
|
- name: Mypy
|
||||||
run: |
|
run: |
|
||||||
@@ -231,7 +232,7 @@ jobs:
|
|||||||
details: Test Succeeded!
|
details: Test Succeeded!
|
||||||
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
||||||
|
|
||||||
build_windows:
|
build-windows:
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
strategy:
|
strategy:
|
||||||
@@ -243,7 +244,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python-version }}
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
@@ -275,19 +276,19 @@ jobs:
|
|||||||
|
|
||||||
- name: Backtesting
|
- name: Backtesting
|
||||||
run: |
|
run: |
|
||||||
cp config_examples/config_bittrex.example.json config.json
|
cp tests/testdata/config.tests.json config.json
|
||||||
freqtrade create-userdir --userdir user_data
|
freqtrade create-userdir --userdir user_data
|
||||||
freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
|
freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
|
||||||
|
|
||||||
- name: Hyperopt
|
- name: Hyperopt
|
||||||
run: |
|
run: |
|
||||||
cp config_examples/config_bittrex.example.json config.json
|
cp tests/testdata/config.tests.json config.json
|
||||||
freqtrade create-userdir --userdir user_data
|
freqtrade create-userdir --userdir user_data
|
||||||
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt-loss SharpeHyperOptLossDaily --print-all
|
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt-loss SharpeHyperOptLossDaily --print-all
|
||||||
|
|
||||||
- name: Run Ruff
|
- name: Run Ruff
|
||||||
run: |
|
run: |
|
||||||
ruff check --format=github .
|
ruff check --output-format=github .
|
||||||
|
|
||||||
- name: Mypy
|
- name: Mypy
|
||||||
run: |
|
run: |
|
||||||
@@ -301,13 +302,13 @@ jobs:
|
|||||||
details: Test Failed
|
details: Test Failed
|
||||||
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
||||||
|
|
||||||
mypy_version_check:
|
mypy-version-check:
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-22.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version: "3.10"
|
python-version: "3.10"
|
||||||
|
|
||||||
@@ -321,12 +322,12 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- uses: actions/setup-python@v4
|
- uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version: "3.10"
|
python-version: "3.10"
|
||||||
- uses: pre-commit/action@v3.0.0
|
- uses: pre-commit/action@v3.0.0
|
||||||
|
|
||||||
docs_check:
|
docs-check:
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-22.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
@@ -336,7 +337,7 @@ jobs:
|
|||||||
./tests/test_docs.sh
|
./tests/test_docs.sh
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version: "3.11"
|
python-version: "3.11"
|
||||||
|
|
||||||
@@ -362,9 +363,9 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version: "3.9"
|
python-version: "3.11"
|
||||||
|
|
||||||
- name: Cache_dependencies
|
- name: Cache_dependencies
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v3
|
||||||
@@ -375,7 +376,6 @@ jobs:
|
|||||||
|
|
||||||
- name: pip cache (linux)
|
- name: pip cache (linux)
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v3
|
||||||
if: runner.os == 'Linux'
|
|
||||||
with:
|
with:
|
||||||
path: ~/.cache/pip
|
path: ~/.cache/pip
|
||||||
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
||||||
@@ -386,7 +386,6 @@ jobs:
|
|||||||
cd build_helpers && ./install_ta-lib.sh ${HOME}/dependencies/; cd ..
|
cd build_helpers && ./install_ta-lib.sh ${HOME}/dependencies/; cd ..
|
||||||
|
|
||||||
- name: Installation - *nix
|
- name: Installation - *nix
|
||||||
if: runner.os == 'Linux'
|
|
||||||
run: |
|
run: |
|
||||||
python -m pip install --upgrade pip wheel
|
python -m pip install --upgrade pip wheel
|
||||||
export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH
|
export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH
|
||||||
@@ -399,17 +398,17 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
CI_WEB_PROXY: http://152.67.78.211:13128
|
CI_WEB_PROXY: http://152.67.78.211:13128
|
||||||
run: |
|
run: |
|
||||||
pytest --random-order --cov=freqtrade --cov-config=.coveragerc --longrun
|
pytest --random-order --longrun --durations 20 -n auto --dist loadscope
|
||||||
|
|
||||||
|
|
||||||
# Notify only once - when CI completes (and after deploy) in case it's successfull
|
# Notify only once - when CI completes (and after deploy) in case it's successfull
|
||||||
notify-complete:
|
notify-complete:
|
||||||
needs: [
|
needs: [
|
||||||
build_linux,
|
build_linux,
|
||||||
build_macos,
|
build-macos,
|
||||||
build_windows,
|
build-windows,
|
||||||
docs_check,
|
docs-check,
|
||||||
mypy_version_check,
|
mypy-version-check,
|
||||||
pre-commit,
|
pre-commit,
|
||||||
build_linux_online
|
build_linux_online
|
||||||
]
|
]
|
||||||
@@ -436,8 +435,63 @@ jobs:
|
|||||||
details: Test Completed!
|
details: Test Completed!
|
||||||
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
||||||
|
|
||||||
deploy:
|
build:
|
||||||
needs: [ build_linux, build_macos, build_windows, docs_check, mypy_version_check, pre-commit ]
|
name: "Build"
|
||||||
|
needs: [ build_linux, build-macos, build-windows, docs-check, mypy-version-check, pre-commit ]
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.11"
|
||||||
|
|
||||||
|
- name: Build distribution
|
||||||
|
run: |
|
||||||
|
pip install -U build
|
||||||
|
python -m build --sdist --wheel
|
||||||
|
|
||||||
|
- name: Upload artifacts 📦
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: freqtrade-build
|
||||||
|
path: |
|
||||||
|
dist
|
||||||
|
retention-days: 10
|
||||||
|
|
||||||
|
deploy-pypi:
|
||||||
|
name: "Deploy to PyPI"
|
||||||
|
needs: [ build ]
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
if: (github.event_name == 'release')
|
||||||
|
environment:
|
||||||
|
name: release
|
||||||
|
url: https://pypi.org/p/freqtrade
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Download artifact 📦
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: freqtrade-build
|
||||||
|
path: dist
|
||||||
|
|
||||||
|
- name: Publish to PyPI (Test)
|
||||||
|
uses: pypa/gh-action-pypi-publish@v1.8.11
|
||||||
|
with:
|
||||||
|
repository-url: https://test.pypi.org/legacy/
|
||||||
|
|
||||||
|
- name: Publish to PyPI
|
||||||
|
uses: pypa/gh-action-pypi-publish@v1.8.11
|
||||||
|
|
||||||
|
|
||||||
|
deploy-docker:
|
||||||
|
needs: [ build_linux, build-macos, build-windows, docs-check, mypy-version-check, pre-commit ]
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-22.04
|
||||||
|
|
||||||
if: (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'release') && github.repository == 'freqtrade/freqtrade'
|
if: (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'release') && github.repository == 'freqtrade/freqtrade'
|
||||||
@@ -446,7 +500,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version: "3.11"
|
python-version: "3.11"
|
||||||
|
|
||||||
@@ -455,26 +509,6 @@ jobs:
|
|||||||
run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF##*/})"
|
run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF##*/})"
|
||||||
id: extract_branch
|
id: extract_branch
|
||||||
|
|
||||||
- name: Build distribution
|
|
||||||
run: |
|
|
||||||
pip install -U setuptools wheel
|
|
||||||
python setup.py sdist bdist_wheel
|
|
||||||
|
|
||||||
- name: Publish to PyPI (Test)
|
|
||||||
uses: pypa/gh-action-pypi-publish@v1.8.10
|
|
||||||
if: (github.event_name == 'release')
|
|
||||||
with:
|
|
||||||
user: __token__
|
|
||||||
password: ${{ secrets.pypi_test_password }}
|
|
||||||
repository_url: https://test.pypi.org/legacy/
|
|
||||||
|
|
||||||
- name: Publish to PyPI
|
|
||||||
uses: pypa/gh-action-pypi-publish@v1.8.10
|
|
||||||
if: (github.event_name == 'release')
|
|
||||||
with:
|
|
||||||
user: __token__
|
|
||||||
password: ${{ secrets.pypi_password }}
|
|
||||||
|
|
||||||
- name: Dockerhub login
|
- name: Dockerhub login
|
||||||
env:
|
env:
|
||||||
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
|
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
@@ -506,10 +540,11 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
build_helpers/publish_docker_multi.sh
|
build_helpers/publish_docker_multi.sh
|
||||||
|
|
||||||
deploy_arm:
|
deploy-arm:
|
||||||
|
name: "Deploy Docker"
|
||||||
permissions:
|
permissions:
|
||||||
packages: write
|
packages: write
|
||||||
needs: [ deploy ]
|
needs: [ deploy-docker ]
|
||||||
# Only run on 64bit machines
|
# Only run on 64bit machines
|
||||||
runs-on: [self-hosted, linux, ARM64]
|
runs-on: [self-hosted, linux, ARM64]
|
||||||
if: (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'release') && github.repository == 'freqtrade/freqtrade'
|
if: (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'release') && github.repository == 'freqtrade/freqtrade'
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
name: Pre-commit auto-update
|
||||||
|
|
||||||
|
on:
|
||||||
|
# every day at midnight
|
||||||
|
schedule:
|
||||||
|
- cron: "0 3 * * 2"
|
||||||
|
# on demand
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
auto-update:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.11"
|
||||||
|
|
||||||
|
|
||||||
|
- name: Install pre-commit
|
||||||
|
run: pip install pre-commit
|
||||||
|
|
||||||
|
- name: Run auto-update
|
||||||
|
run: pre-commit autoupdate
|
||||||
|
|
||||||
|
- name: Run pre-commit
|
||||||
|
run: pre-commit run --all-files
|
||||||
|
|
||||||
|
- uses: peter-evans/create-pull-request@v5
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.REPO_SCOPED_TOKEN }}
|
||||||
|
add-paths: .pre-commit-config.yaml
|
||||||
|
labels: |
|
||||||
|
Tech maintenance
|
||||||
|
branch: update/pre-commit-hooks
|
||||||
|
title: Update pre-commit hooks
|
||||||
|
commit-message: "chore: update pre-commit hooks"
|
||||||
|
committer: Freqtrade Bot <noreply@github.com>
|
||||||
|
body: Update versions of pre-commit hooks to latest version.
|
||||||
|
delete-branch: true
|
||||||
@@ -111,7 +111,6 @@ target/
|
|||||||
#exceptions
|
#exceptions
|
||||||
!*.gitkeep
|
!*.gitkeep
|
||||||
!config_examples/config_binance.example.json
|
!config_examples/config_binance.example.json
|
||||||
!config_examples/config_bittrex.example.json
|
|
||||||
!config_examples/config_full.example.json
|
!config_examples/config_full.example.json
|
||||||
!config_examples/config_kraken.example.json
|
!config_examples/config_kraken.example.json
|
||||||
!config_examples/config_freqai.example.json
|
!config_examples/config_freqai.example.json
|
||||||
|
|||||||
@@ -2,27 +2,28 @@
|
|||||||
# See https://pre-commit.com/hooks.html for more hooks
|
# See https://pre-commit.com/hooks.html for more hooks
|
||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/pycqa/flake8
|
- repo: https://github.com/pycqa/flake8
|
||||||
rev: "6.0.0"
|
rev: "6.1.0"
|
||||||
hooks:
|
hooks:
|
||||||
- id: flake8
|
- id: flake8
|
||||||
|
additional_dependencies: [Flake8-pyproject]
|
||||||
# stages: [push]
|
# stages: [push]
|
||||||
|
|
||||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||||
rev: "v1.5.1"
|
rev: "v1.8.0"
|
||||||
hooks:
|
hooks:
|
||||||
- id: mypy
|
- id: mypy
|
||||||
exclude: build_helpers
|
exclude: build_helpers
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- types-cachetools==5.3.0.6
|
- types-cachetools==5.3.0.7
|
||||||
- types-filelock==3.2.7
|
- types-filelock==3.2.7
|
||||||
- types-requests==2.31.0.4
|
- types-requests==2.31.0.10
|
||||||
- types-tabulate==0.9.0.3
|
- types-tabulate==0.9.0.3
|
||||||
- types-python-dateutil==2.8.19.14
|
- types-python-dateutil==2.8.19.14
|
||||||
- SQLAlchemy==2.0.21
|
- SQLAlchemy==2.0.23
|
||||||
# stages: [push]
|
# stages: [push]
|
||||||
|
|
||||||
- repo: https://github.com/pycqa/isort
|
- repo: https://github.com/pycqa/isort
|
||||||
rev: "5.12.0"
|
rev: "5.13.2"
|
||||||
hooks:
|
hooks:
|
||||||
- id: isort
|
- id: isort
|
||||||
name: isort (python)
|
name: isort (python)
|
||||||
@@ -30,12 +31,12 @@ repos:
|
|||||||
|
|
||||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||||
# Ruff version.
|
# Ruff version.
|
||||||
rev: 'v0.0.270'
|
rev: 'v0.1.9'
|
||||||
hooks:
|
hooks:
|
||||||
- id: ruff
|
- id: ruff
|
||||||
|
|
||||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
rev: v4.4.0
|
rev: v4.5.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: end-of-file-fixer
|
- id: end-of-file-fixer
|
||||||
exclude: |
|
exclude: |
|
||||||
|
|||||||
+1
-1
@@ -125,7 +125,7 @@ Exceptions:
|
|||||||
|
|
||||||
Contributors may be given commit privileges. Preference will be given to those with:
|
Contributors may be given commit privileges. Preference will be given to those with:
|
||||||
|
|
||||||
1. Past contributions to Freqtrade and other related open-source projects. Contributions to Freqtrade include both code (both accepted and pending) and friendly participation in the issue tracker and Pull request reviews. Quantity and quality are considered.
|
1. Past contributions to Freqtrade and other related open-source projects. Contributions to Freqtrade include both code (both accepted and pending) and friendly participation in the issue tracker and Pull request reviews. Both quantity and quality are considered.
|
||||||
1. A coding style that the other core committers find simple, minimal, and clean.
|
1. A coding style that the other core committers find simple, minimal, and clean.
|
||||||
1. Access to resources for cross-platform development and testing.
|
1. Access to resources for cross-platform development and testing.
|
||||||
1. Time to devote to the project regularly.
|
1. Time to devote to the project regularly.
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
FROM python:3.11.5-slim-bullseye as base
|
FROM python:3.11.6-slim-bookworm as base
|
||||||
|
|
||||||
# Setup env
|
# Setup env
|
||||||
ENV LANG C.UTF-8
|
ENV LANG C.UTF-8
|
||||||
|
|||||||
@@ -5,3 +5,5 @@ recursive-include freqtrade/templates/ *.j2 *.ipynb
|
|||||||
include freqtrade/exchange/binance_leverage_tiers.json
|
include freqtrade/exchange/binance_leverage_tiers.json
|
||||||
include freqtrade/rpc/api_server/ui/fallback_file.html
|
include freqtrade/rpc/api_server/ui/fallback_file.html
|
||||||
include freqtrade/rpc/api_server/ui/favicon.ico
|
include freqtrade/rpc/api_server/ui/favicon.ico
|
||||||
|
|
||||||
|
prune tests
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ hesitate to read the source code and understand the mechanism of this bot.
|
|||||||
Please read the [exchange specific notes](docs/exchanges.md) to learn about eventual, special configurations needed for each exchange.
|
Please read the [exchange specific notes](docs/exchanges.md) to learn about eventual, special configurations needed for each exchange.
|
||||||
|
|
||||||
- [X] [Binance](https://www.binance.com/)
|
- [X] [Binance](https://www.binance.com/)
|
||||||
- [X] [Bittrex](https://bittrex.com/)
|
- [X] [Bitmart](https://bitmart.com/)
|
||||||
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
||||||
- [X] [Huobi](http://huobi.com/)
|
- [X] [Huobi](http://huobi.com/)
|
||||||
- [X] [Kraken](https://kraken.com/)
|
- [X] [Kraken](https://kraken.com/)
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -54,7 +54,7 @@ docker tag freqtrade:$TAG_FREQAI_ARM ${CACHE_IMAGE}:$TAG_FREQAI_ARM
|
|||||||
docker tag freqtrade:$TAG_FREQAI_RL_ARM ${CACHE_IMAGE}:$TAG_FREQAI_RL_ARM
|
docker tag freqtrade:$TAG_FREQAI_RL_ARM ${CACHE_IMAGE}:$TAG_FREQAI_RL_ARM
|
||||||
|
|
||||||
# Run backtest
|
# Run backtest
|
||||||
docker run --rm -v $(pwd)/config_examples/config_bittrex.example.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG_ARM} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV3
|
docker run --rm -v $(pwd)/tests/testdata/config.tests.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG_ARM} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV3
|
||||||
|
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "failed running backtest"
|
echo "failed running backtest"
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ docker tag freqtrade:$TAG_FREQAI ${CACHE_IMAGE}:$TAG_FREQAI
|
|||||||
docker tag freqtrade:$TAG_FREQAI_RL ${CACHE_IMAGE}:$TAG_FREQAI_RL
|
docker tag freqtrade:$TAG_FREQAI_RL ${CACHE_IMAGE}:$TAG_FREQAI_RL
|
||||||
|
|
||||||
# Run backtest
|
# Run backtest
|
||||||
docker run --rm -v $(pwd)/config_examples/config_bittrex.example.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV3
|
docker run --rm -v $(pwd)/tests/testdata/config.tests.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV3
|
||||||
|
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "failed running backtest"
|
echo "failed running backtest"
|
||||||
|
|||||||
BIN
Binary file not shown.
Binary file not shown.
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"max_open_trades": 3,
|
"max_open_trades": 3,
|
||||||
"stake_currency": "BTC",
|
"stake_currency": "USDT",
|
||||||
"stake_amount": 0.05,
|
"stake_amount": 0.05,
|
||||||
"tradable_balance_ratio": 0.99,
|
"tradable_balance_ratio": 0.99,
|
||||||
"fiat_display_currency": "USD",
|
"fiat_display_currency": "USD",
|
||||||
@@ -36,21 +36,21 @@
|
|||||||
"ccxt_async_config": {
|
"ccxt_async_config": {
|
||||||
},
|
},
|
||||||
"pair_whitelist": [
|
"pair_whitelist": [
|
||||||
"ALGO/BTC",
|
"ALGO/USDT",
|
||||||
"ATOM/BTC",
|
"ATOM/USDT",
|
||||||
"BAT/BTC",
|
"BAT/USDT",
|
||||||
"BCH/BTC",
|
"BCH/USDT",
|
||||||
"BRD/BTC",
|
"BRD/USDT",
|
||||||
"EOS/BTC",
|
"EOS/USDT",
|
||||||
"ETH/BTC",
|
"ETH/USDT",
|
||||||
"IOTA/BTC",
|
"IOTA/USDT",
|
||||||
"LINK/BTC",
|
"LINK/USDT",
|
||||||
"LTC/BTC",
|
"LTC/USDT",
|
||||||
"NEO/BTC",
|
"NEO/USDT",
|
||||||
"NXS/BTC",
|
"NXS/USDT",
|
||||||
"XMR/BTC",
|
"XMR/USDT",
|
||||||
"XRP/BTC",
|
"XRP/USDT",
|
||||||
"XTZ/BTC"
|
"XTZ/USDT"
|
||||||
],
|
],
|
||||||
"pair_blacklist": [
|
"pair_blacklist": [
|
||||||
"BNB/.*"
|
"BNB/.*"
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
FROM python:3.9.16-slim-bullseye as base
|
FROM python:3.11.6-slim-bookworm as base
|
||||||
|
|
||||||
# Setup env
|
# Setup env
|
||||||
ENV LANG C.UTF-8
|
ENV LANG C.UTF-8
|
||||||
@@ -11,12 +11,13 @@ ENV FT_APP_ENV="docker"
|
|||||||
# Prepare environment
|
# Prepare environment
|
||||||
RUN mkdir /freqtrade \
|
RUN mkdir /freqtrade \
|
||||||
&& apt-get update \
|
&& apt-get update \
|
||||||
&& apt-get -y install sudo libatlas3-base curl sqlite3 libhdf5-dev libutf8proc-dev libsnappy-dev \
|
&& apt-get -y install sudo libatlas3-base libopenblas-dev curl sqlite3 libhdf5-dev libutf8proc-dev libsnappy-dev \
|
||||||
&& apt-get clean \
|
&& apt-get clean \
|
||||||
&& useradd -u 1000 -G sudo -U -m ftuser \
|
&& useradd -u 1000 -G sudo -U -m ftuser \
|
||||||
&& chown ftuser:ftuser /freqtrade \
|
&& chown ftuser:ftuser /freqtrade \
|
||||||
# Allow sudoers
|
# Allow sudoers
|
||||||
&& echo "ftuser ALL=(ALL) NOPASSWD: /bin/chown" >> /etc/sudoers
|
&& echo "ftuser ALL=(ALL) NOPASSWD: /bin/chown" >> /etc/sudoers \
|
||||||
|
&& pip install --upgrade pip
|
||||||
|
|
||||||
WORKDIR /freqtrade
|
WORKDIR /freqtrade
|
||||||
|
|
||||||
@@ -25,20 +26,16 @@ FROM base as python-deps
|
|||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get -y install build-essential libssl-dev libffi-dev libgfortran5 pkg-config cmake gcc \
|
&& apt-get -y install build-essential libssl-dev libffi-dev libgfortran5 pkg-config cmake gcc \
|
||||||
&& apt-get clean \
|
&& apt-get clean \
|
||||||
&& pip install --upgrade pip \
|
|
||||||
&& echo "[global]\nextra-index-url=https://www.piwheels.org/simple" > /etc/pip.conf
|
&& echo "[global]\nextra-index-url=https://www.piwheels.org/simple" > /etc/pip.conf
|
||||||
|
|
||||||
# Install TA-lib
|
# Install TA-lib
|
||||||
COPY build_helpers/* /tmp/
|
COPY build_helpers/* /tmp/
|
||||||
RUN cd /tmp && /tmp/install_ta-lib.sh && rm -r /tmp/*ta-lib*
|
|
||||||
ENV LD_LIBRARY_PATH /usr/local/lib
|
|
||||||
|
|
||||||
# Install dependencies
|
# Install dependencies
|
||||||
COPY --chown=ftuser:ftuser requirements.txt /freqtrade/
|
COPY --chown=ftuser:ftuser requirements.txt /freqtrade/
|
||||||
USER ftuser
|
USER ftuser
|
||||||
RUN pip install --user --no-cache-dir numpy==1.25.2 \
|
RUN pip install --user --no-cache-dir numpy \
|
||||||
&& pip install --user /tmp/pyarrow-*.whl \
|
&& pip install --user --no-index --find-links /tmp/ pyarrow TA-Lib==0.4.28 \
|
||||||
&& pip install --user --no-build-isolation TA-Lib==0.4.28 \
|
|
||||||
&& pip install --user --no-cache-dir -r requirements.txt
|
&& pip install --user --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
# Copy dependencies to runtime-image
|
# Copy dependencies to runtime-image
|
||||||
|
|||||||
+6
-6
@@ -31,9 +31,9 @@ optional arguments:
|
|||||||
Specify timeframe (`1m`, `5m`, `30m`, `1h`, `1d`).
|
Specify timeframe (`1m`, `5m`, `30m`, `1h`, `1d`).
|
||||||
--timerange TIMERANGE
|
--timerange TIMERANGE
|
||||||
Specify what timerange of data to use.
|
Specify what timerange of data to use.
|
||||||
--data-format-ohlcv {json,jsongz,hdf5}
|
--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}
|
||||||
Storage format for downloaded candle (OHLCV) data.
|
Storage format for downloaded candle (OHLCV) data.
|
||||||
(default: `json`).
|
(default: `feather`).
|
||||||
--max-open-trades INT
|
--max-open-trades INT
|
||||||
Override the value of the `max_open_trades`
|
Override the value of the `max_open_trades`
|
||||||
configuration setting.
|
configuration setting.
|
||||||
@@ -170,11 +170,11 @@ freqtrade backtesting --strategy AwesomeStrategy --dry-run-wallet 1000
|
|||||||
|
|
||||||
Using a different on-disk historical candle (OHLCV) data source
|
Using a different on-disk historical candle (OHLCV) data source
|
||||||
|
|
||||||
Assume you downloaded the history data from the Bittrex exchange and kept it in the `user_data/data/bittrex-20180101` directory.
|
Assume you downloaded the history data from the Binance exchange and kept it in the `user_data/data/binance-20180101` directory.
|
||||||
You can then use this data for backtesting as follows:
|
You can then use this data for backtesting as follows:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade backtesting --strategy AwesomeStrategy --datadir user_data/data/bittrex-20180101
|
freqtrade backtesting --strategy AwesomeStrategy --datadir user_data/data/binance-20180101
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -618,13 +618,13 @@ To compare multiple strategies, a list of Strategies can be provided to backtest
|
|||||||
This is limited to 1 timeframe value per run. However, data is only loaded once from disk so if you have multiple
|
This is limited to 1 timeframe value per run. However, data is only loaded once from disk so if you have multiple
|
||||||
strategies you'd like to compare, this will give a nice runtime boost.
|
strategies you'd like to compare, this will give a nice runtime boost.
|
||||||
|
|
||||||
All listed Strategies need to be in the same directory.
|
All listed Strategies need to be in the same directory, unless also `--recursive-strategy-search` is specified, where sub-directories within the strategy directory are also considered.
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade backtesting --timerange 20180401-20180410 --timeframe 5m --strategy-list Strategy001 Strategy002 --export trades
|
freqtrade backtesting --timerange 20180401-20180410 --timeframe 5m --strategy-list Strategy001 Strategy002 --export trades
|
||||||
```
|
```
|
||||||
|
|
||||||
This will save the results to `user_data/backtest_results/backtest-result-<strategy>.json`, injecting the strategy-name into the target filename.
|
This will save the results to `user_data/backtest_results/backtest-result-<datetime>.json`, including results for both `Strategy001` and `Strategy002`.
|
||||||
There will be an additional table comparing win/losses of the different strategies (identical to the "Total" row in the first table).
|
There will be an additional table comparing win/losses of the different strategies (identical to the "Total" row in the first table).
|
||||||
Detailed output for all strategies one after the other will be available, so make sure to scroll up to see the details per strategy.
|
Detailed output for all strategies one after the other will be available, so make sure to scroll up to see the details per strategy.
|
||||||
|
|
||||||
|
|||||||
@@ -321,7 +321,7 @@ For example, if you have 10 ETH available in your wallet on the exchange and `tr
|
|||||||
To fully utilize compounding profits when using multiple bots on the same exchange account, you'll want to limit each bot to a certain starting balance.
|
To fully utilize compounding profits when using multiple bots on the same exchange account, you'll want to limit each bot to a certain starting balance.
|
||||||
This can be accomplished by setting `available_capital` to the desired starting balance.
|
This can be accomplished by setting `available_capital` to the desired starting balance.
|
||||||
|
|
||||||
Assuming your account has 10.000 USDT and you want to run 2 different strategies on this exchange.
|
Assuming your account has 10000 USDT and you want to run 2 different strategies on this exchange.
|
||||||
You'd set `available_capital=5000` - granting each bot an initial capital of 5000 USDT.
|
You'd set `available_capital=5000` - granting each bot an initial capital of 5000 USDT.
|
||||||
The bot will then split this starting balance equally into `max_open_trades` buckets.
|
The bot will then split this starting balance equally into `max_open_trades` buckets.
|
||||||
Profitable trades will result in increased stake-sizes for this bot - without affecting the stake-sizes of the other bot.
|
Profitable trades will result in increased stake-sizes for this bot - without affecting the stake-sizes of the other bot.
|
||||||
@@ -594,7 +594,7 @@ creating trades on the exchange.
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "bittrex",
|
"name": "binance",
|
||||||
"key": "key",
|
"key": "key",
|
||||||
"secret": "secret",
|
"secret": "secret",
|
||||||
...
|
...
|
||||||
@@ -644,7 +644,7 @@ API Keys are usually only required for live trading (trading for real money, bot
|
|||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "bittrex",
|
"name": "binance",
|
||||||
"key": "af8ddd35195e9dc500b9a6f799f6f5c93d89193b",
|
"key": "af8ddd35195e9dc500b9a6f799f6f5c93d89193b",
|
||||||
"secret": "08a9dc6db3d7b53e1acebd9275677f4b0a04f1a5",
|
"secret": "08a9dc6db3d7b53e1acebd9275677f4b0a04f1a5",
|
||||||
//"password": "", // Optional, not needed by all exchanges)
|
//"password": "", // Optional, not needed by all exchanges)
|
||||||
|
|||||||
+5
-4
@@ -318,6 +318,7 @@ Additional tests / steps to complete:
|
|||||||
* Check if balance shows correctly (*)
|
* Check if balance shows correctly (*)
|
||||||
* Create market order (*)
|
* Create market order (*)
|
||||||
* Create limit order (*)
|
* Create limit order (*)
|
||||||
|
* Cancel order (*)
|
||||||
* Complete trade (enter + exit) (*)
|
* Complete trade (enter + exit) (*)
|
||||||
* Compare result calculation between exchange and bot
|
* Compare result calculation between exchange and bot
|
||||||
* Ensure fees are applied correctly (check the database against the exchange)
|
* Ensure fees are applied correctly (check the database against the exchange)
|
||||||
@@ -418,6 +419,9 @@ This part of the documentation is aimed at maintainers, and shows how to create
|
|||||||
|
|
||||||
### Create release branch
|
### Create release branch
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Make sure that the `stable` branch is up-to-date!
|
||||||
|
|
||||||
First, pick a commit that's about one week old (to not include latest additions to releases).
|
First, pick a commit that's about one week old (to not include latest additions to releases).
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
@@ -430,14 +434,11 @@ Determine if crucial bugfixes have been made between this commit and the current
|
|||||||
* Merge the release branch (stable) into this branch.
|
* Merge the release branch (stable) into this branch.
|
||||||
* Edit `freqtrade/__init__.py` and add the version matching the current date (for example `2019.7` for July 2019). Minor versions can be `2019.7.1` should we need to do a second release that month. Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi.
|
* Edit `freqtrade/__init__.py` and add the version matching the current date (for example `2019.7` for July 2019). Minor versions can be `2019.7.1` should we need to do a second release that month. Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi.
|
||||||
* Commit this part.
|
* Commit this part.
|
||||||
* push that branch to the remote and create a PR against the stable branch.
|
* Push that branch to the remote and create a PR against the **stable branch**.
|
||||||
* Update develop version to next version following the pattern `2019.8-dev`.
|
* Update develop version to next version following the pattern `2019.8-dev`.
|
||||||
|
|
||||||
### Create changelog from git commits
|
### Create changelog from git commits
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Make sure that the `stable` branch is up-to-date!
|
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
# Needs to be done before merging / pulling that branch.
|
# Needs to be done before merging / pulling that branch.
|
||||||
git log --oneline --no-decorate --no-merges stable..new_release
|
git log --oneline --no-decorate --no-merges stable..new_release
|
||||||
|
|||||||
+55
-42
@@ -136,6 +136,43 @@ Freqtrade will not attempt to change these settings.
|
|||||||
The Kraken API does only provide 720 historic candles, which is sufficient for Freqtrade dry-run and live trade modes, but is a problem for backtesting.
|
The Kraken API does only provide 720 historic candles, which is sufficient for Freqtrade dry-run and live trade modes, but is a problem for backtesting.
|
||||||
To download data for the Kraken exchange, using `--dl-trades` is mandatory, otherwise the bot will download the same 720 candles over and over, and you'll not have enough backtest data.
|
To download data for the Kraken exchange, using `--dl-trades` is mandatory, otherwise the bot will download the same 720 candles over and over, and you'll not have enough backtest data.
|
||||||
|
|
||||||
|
To speed up downloading, you can download the [trades zip files](https://support.kraken.com/hc/en-us/articles/360047543791-Downloadable-historical-market-data-time-and-sales-) kraken provides.
|
||||||
|
These are usually updated once per quarter. Freqtrade expects these files to be placed in `user_data/data/kraken/trades_csv`.
|
||||||
|
|
||||||
|
A structure as follows can make sense if using incremental files, with the "full" history in one directory, and incremental files in different directories.
|
||||||
|
The assumption for this mode is that the data is downloaded and unzipped keeping filenames as they are.
|
||||||
|
Duplicate content will be ignored (based on timestamp) - though the assumption is that there is no gap in the data.
|
||||||
|
|
||||||
|
This means, if your "full" history ends in Q4 2022 - then both incremental updates Q1 2023 and Q2 2023 are available.
|
||||||
|
Not having this will lead to incomplete data, and therefore invalid results while using the data.
|
||||||
|
|
||||||
|
```
|
||||||
|
└── trades_csv
|
||||||
|
├── Kraken_full_history
|
||||||
|
│ ├── BCHEUR.csv
|
||||||
|
│ └── XBTEUR.csv
|
||||||
|
├── Kraken_Trading_History_Q1_2023
|
||||||
|
│ ├── BCHEUR.csv
|
||||||
|
│ └── XBTEUR.csv
|
||||||
|
└── Kraken_Trading_History_Q2_2023
|
||||||
|
├── BCHEUR.csv
|
||||||
|
└── XBTEUR.csv
|
||||||
|
```
|
||||||
|
|
||||||
|
You can convert these files into freqtrade files:
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade convert-trade-data --exchange kraken --format-from kraken_csv --format-to feather
|
||||||
|
# Convert trade data to different ohlcv timeframes
|
||||||
|
freqtrade trades-to-ohlcv -p BTC/EUR BCH/EUR --exchange kraken -t 1m 5m 15m 1h
|
||||||
|
```
|
||||||
|
|
||||||
|
The converted data also makes downloading data possible, and will start the download after the latest loaded trade.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade download-data --exchange kraken --dl-trades -p BTC/EUR BCH/EUR
|
||||||
|
```
|
||||||
|
|
||||||
!!! Warning "Downloading data from kraken"
|
!!! Warning "Downloading data from kraken"
|
||||||
Downloading kraken data will require significantly more memory (RAM) than any other exchange, as the trades-data needs to be converted into candles on your machine.
|
Downloading kraken data will require significantly more memory (RAM) than any other exchange, as the trades-data needs to be converted into candles on your machine.
|
||||||
It will also take a long time, as freqtrade will need to download every single trade that happened on the exchange for the pair / timerange combination, therefore please be patient.
|
It will also take a long time, as freqtrade will need to download every single trade that happened on the exchange for the pair / timerange combination, therefore please be patient.
|
||||||
@@ -144,48 +181,6 @@ To download data for the Kraken exchange, using `--dl-trades` is mandatory, othe
|
|||||||
Please pay attention that rateLimit configuration entry holds delay in milliseconds between requests, NOT requests\sec rate.
|
Please pay attention that rateLimit configuration entry holds delay in milliseconds between requests, NOT requests\sec rate.
|
||||||
So, in order to mitigate Kraken API "Rate limit exceeded" exception, this configuration should be increased, NOT decreased.
|
So, in order to mitigate Kraken API "Rate limit exceeded" exception, this configuration should be increased, NOT decreased.
|
||||||
|
|
||||||
## Bittrex
|
|
||||||
|
|
||||||
### Order types
|
|
||||||
|
|
||||||
Bittrex does not support market orders. If you have a message at the bot startup about this, you should change order type values set in your configuration and/or in the strategy from `"market"` to `"limit"`. See some more details on this [here in the FAQ](faq.md#im-getting-the-exchange-bittrex-does-not-support-market-orders-message-and-cannot-run-my-strategy).
|
|
||||||
|
|
||||||
Bittrex also does not support `VolumePairlist` due to limited / split API constellation at the moment.
|
|
||||||
Please use `StaticPairlist`. Other pairlists (other than `VolumePairlist`) should not be affected.
|
|
||||||
|
|
||||||
### Volume pairlist
|
|
||||||
|
|
||||||
Bittrex does not support the direct usage of VolumePairList. This can however be worked around by using the advanced mode with `lookback_days: 1` (or more), which will emulate 24h volume.
|
|
||||||
|
|
||||||
Read more in the [pairlist documentation](plugins.md#volumepairlist-advanced-mode).
|
|
||||||
|
|
||||||
### Restricted markets
|
|
||||||
|
|
||||||
Bittrex split its exchange into US and International versions.
|
|
||||||
The International version has more pairs available, however the API always returns all pairs, so there is currently no automated way to detect if you're affected by the restriction.
|
|
||||||
|
|
||||||
If you have restricted pairs in your whitelist, you'll get a warning message in the log on Freqtrade startup for each restricted pair.
|
|
||||||
|
|
||||||
The warning message will look similar to the following:
|
|
||||||
|
|
||||||
``` output
|
|
||||||
[...] Message: bittrex {"success":false,"message":"RESTRICTED_MARKET","result":null,"explanation":null}"
|
|
||||||
```
|
|
||||||
|
|
||||||
If you're an "International" customer on the Bittrex exchange, then this warning will probably not impact you.
|
|
||||||
If you're a US customer, the bot will fail to create orders for these pairs, and you should remove them from your whitelist.
|
|
||||||
|
|
||||||
You can get a list of restricted markets by using the following snippet:
|
|
||||||
|
|
||||||
``` python
|
|
||||||
import ccxt
|
|
||||||
ct = ccxt.bittrex()
|
|
||||||
lm = ct.load_markets()
|
|
||||||
|
|
||||||
res = [p for p, x in lm.items() if 'US' in x['info']['prohibitedIn']]
|
|
||||||
print(res)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Kucoin
|
## Kucoin
|
||||||
|
|
||||||
Kucoin requires a passphrase for each api key, you will therefore need to add this key into the configuration so your exchange section looks as follows:
|
Kucoin requires a passphrase for each api key, you will therefore need to add this key into the configuration so your exchange section looks as follows:
|
||||||
@@ -265,6 +260,24 @@ We do strongly recommend to limit all API keys to the IP you're going to use it
|
|||||||
Bybit (futures only) supports `stoploss_on_exchange` and uses `stop-loss-limit` orders. It provides great advantages, so we recommend to benefit from it by enabling stoploss on exchange.
|
Bybit (futures only) supports `stoploss_on_exchange` and uses `stop-loss-limit` orders. It provides great advantages, so we recommend to benefit from it by enabling stoploss on exchange.
|
||||||
On futures, Bybit supports both `stop-limit` as well as `stop-market` orders. You can use either `"limit"` or `"market"` in the `order_types.stoploss` configuration setting to decide which type to use.
|
On futures, Bybit supports both `stop-limit` as well as `stop-market` orders. You can use either `"limit"` or `"market"` in the `order_types.stoploss` configuration setting to decide which type to use.
|
||||||
|
|
||||||
|
## Bitmart
|
||||||
|
|
||||||
|
Bitmart requires the API key Memo (the name you give the API key) to go along with the exchange key and secret.
|
||||||
|
It's therefore required to pass the UID as well.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"exchange": {
|
||||||
|
"name": "bitmart",
|
||||||
|
"uid": "your_bitmart_api_key_memo",
|
||||||
|
"secret": "your_exchange_secret",
|
||||||
|
"password": "your_exchange_api_key_password",
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Warning "Necessary Verification"
|
||||||
|
Bitmart requires Verification Lvl2 to successfully trade on the spot market through the API - even though trading via UI works just fine with just Lvl1 verification.
|
||||||
|
|
||||||
## All exchanges
|
## All exchanges
|
||||||
|
|
||||||
Should you experience constant errors with Nonce (like `InvalidNonce`), it is best to regenerate the API keys. Resetting Nonce is difficult and it's usually easier to regenerate the API keys.
|
Should you experience constant errors with Nonce (like `InvalidNonce`), it is best to regenerate the API keys. Resetting Nonce is difficult and it's usually easier to regenerate the API keys.
|
||||||
|
|||||||
+1
-7
@@ -128,15 +128,9 @@ This warning can point to one of the below problems:
|
|||||||
* Barely traded pair -> Check the pair on the exchange webpage, look at the timeframe your strategy uses. If the pair does not have any volume in some candles (usually visualized with a "volume 0" bar, and a "_" as candle), this pair did not have any trades in this timeframe. These pairs should ideally be avoided, as they can cause problems with order-filling.
|
* Barely traded pair -> Check the pair on the exchange webpage, look at the timeframe your strategy uses. If the pair does not have any volume in some candles (usually visualized with a "volume 0" bar, and a "_" as candle), this pair did not have any trades in this timeframe. These pairs should ideally be avoided, as they can cause problems with order-filling.
|
||||||
* API problem -> API returns wrong data (this only here for completeness, and should not happen with supported exchanges).
|
* API problem -> API returns wrong data (this only here for completeness, and should not happen with supported exchanges).
|
||||||
|
|
||||||
### I'm getting the "RESTRICTED_MARKET" message in the log
|
|
||||||
|
|
||||||
Currently known to happen for US Bittrex users.
|
|
||||||
|
|
||||||
Read [the Bittrex section about restricted markets](exchanges.md#restricted-markets) for more information.
|
|
||||||
|
|
||||||
### I'm getting the "Exchange XXX does not support market orders." message and cannot run my strategy
|
### I'm getting the "Exchange XXX does not support market orders." message and cannot run my strategy
|
||||||
|
|
||||||
As the message says, your exchange does not support market orders and you have one of the [order types](configuration.md/#understand-order_types) set to "market". Your strategy was probably written with other exchanges in mind and sets "market" orders for "stoploss" orders, which is correct and preferable for most of the exchanges supporting market orders (but not for Bittrex and Gate.io).
|
As the message says, your exchange does not support market orders and you have one of the [order types](configuration.md/#understand-order_types) set to "market". Your strategy was probably written with other exchanges in mind and sets "market" orders for "stoploss" orders, which is correct and preferable for most of the exchanges supporting market orders (but not for Gate.io).
|
||||||
|
|
||||||
To fix this, redefine order types in the strategy to use "limit" instead of "market":
|
To fix this, redefine order types in the strategy to use "limit" instead of "market":
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Low level feature engineering is performed in the user strategy within a set of
|
|||||||
| Function | Description |
|
| Function | Description |
|
||||||
|---------------|-------------|
|
|---------------|-------------|
|
||||||
| `feature_engineering_expand_all()` | This optional function will automatically expand the defined features on the config defined `indicator_periods_candles`, `include_timeframes`, `include_shifted_candles`, and `include_corr_pairs`.
|
| `feature_engineering_expand_all()` | This optional function will automatically expand the defined features on the config defined `indicator_periods_candles`, `include_timeframes`, `include_shifted_candles`, and `include_corr_pairs`.
|
||||||
| `feature_engineering_expand_basic()` | This optional function will automatically expand the defined features on the config defined `include_timeframes`, `include_shifted_candles`, and `include_corr_pairs`. Note: this function does *not* expand across `include_periods_candles`.
|
| `feature_engineering_expand_basic()` | This optional function will automatically expand the defined features on the config defined `include_timeframes`, `include_shifted_candles`, and `include_corr_pairs`. Note: this function does *not* expand across `indicator_periods_candles`.
|
||||||
| `feature_engineering_standard()` | This optional function will be called once with the dataframe of the base timeframe. This is the final function to be called, which means that the dataframe entering this function will contain all the features and columns from the base asset created by the other `feature_engineering_expand` functions. This function is a good place to do custom exotic feature extractions (e.g. tsfresh). This function is also a good place for any feature that should not be auto-expanded upon (e.g., day of the week).
|
| `feature_engineering_standard()` | This optional function will be called once with the dataframe of the base timeframe. This is the final function to be called, which means that the dataframe entering this function will contain all the features and columns from the base asset created by the other `feature_engineering_expand` functions. This function is a good place to do custom exotic feature extractions (e.g. tsfresh). This function is also a good place for any feature that should not be auto-expanded upon (e.g., day of the week).
|
||||||
| `set_freqai_targets()` | Required function to set the targets for the model. All targets must be prepended with `&` to be recognized by the FreqAI internals.
|
| `set_freqai_targets()` | Required function to set the targets for the model. All targets must be prepended with `&` to be recognized by the FreqAI internals.
|
||||||
|
|
||||||
|
|||||||
@@ -74,7 +74,6 @@ Mandatory parameters are marked as **Required** and have to be set in one of the
|
|||||||
| | **Reinforcement Learning Parameters within the `freqai.rl_config` sub dictionary**
|
| | **Reinforcement Learning Parameters within the `freqai.rl_config` sub dictionary**
|
||||||
| `rl_config` | A dictionary containing the control parameters for a Reinforcement Learning model. <br> **Datatype:** Dictionary.
|
| `rl_config` | A dictionary containing the control parameters for a Reinforcement Learning model. <br> **Datatype:** Dictionary.
|
||||||
| `train_cycles` | Training time steps will be set based on the `train_cycles * number of training data points. <br> **Datatype:** Integer.
|
| `train_cycles` | Training time steps will be set based on the `train_cycles * number of training data points. <br> **Datatype:** Integer.
|
||||||
| `cpu_count` | Number of processors to dedicate to the Reinforcement Learning training process. <br> **Datatype:** int.
|
|
||||||
| `max_trade_duration_candles`| Guides the agent training to keep trades below desired length. Example usage shown in `prediction_models/ReinforcementLearner.py` within the customizable `calculate_reward()` function. <br> **Datatype:** int.
|
| `max_trade_duration_candles`| Guides the agent training to keep trades below desired length. Example usage shown in `prediction_models/ReinforcementLearner.py` within the customizable `calculate_reward()` function. <br> **Datatype:** int.
|
||||||
| `model_type` | Model string from stable_baselines3 or SBcontrib. Available strings include: `'TRPO', 'ARS', 'RecurrentPPO', 'MaskablePPO', 'PPO', 'A2C', 'DQN'`. User should ensure that `model_training_parameters` match those available to the corresponding stable_baselines3 model by visiting their documentaiton. [PPO doc](https://stable-baselines3.readthedocs.io/en/master/modules/ppo.html) (external website) <br> **Datatype:** string.
|
| `model_type` | Model string from stable_baselines3 or SBcontrib. Available strings include: `'TRPO', 'ARS', 'RecurrentPPO', 'MaskablePPO', 'PPO', 'A2C', 'DQN'`. User should ensure that `model_training_parameters` match those available to the corresponding stable_baselines3 model by visiting their documentaiton. [PPO doc](https://stable-baselines3.readthedocs.io/en/master/modules/ppo.html) (external website) <br> **Datatype:** string.
|
||||||
| `policy_type` | One of the available policy types from stable_baselines3 <br> **Datatype:** string.
|
| `policy_type` | One of the available policy types from stable_baselines3 <br> **Datatype:** string.
|
||||||
|
|||||||
+9
-5
@@ -337,11 +337,15 @@ There are four parameter types each suited for different purposes.
|
|||||||
* `CategoricalParameter` - defines a parameter with a predetermined number of choices.
|
* `CategoricalParameter` - defines a parameter with a predetermined number of choices.
|
||||||
* `BooleanParameter` - Shorthand for `CategoricalParameter([True, False])` - great for "enable" parameters.
|
* `BooleanParameter` - Shorthand for `CategoricalParameter([True, False])` - great for "enable" parameters.
|
||||||
|
|
||||||
!!! Tip "Disabling parameter optimization"
|
### Parameter options
|
||||||
Each parameter takes two boolean parameters:
|
|
||||||
* `load` - when set to `False` it will not load values configured in `buy_params` and `sell_params`.
|
There are two parameter options that can help you to quickly test various ideas:
|
||||||
* `optimize` - when set to `False` parameter will not be included in optimization process.
|
|
||||||
Use these parameters to quickly prototype various ideas.
|
* `optimize` - when set to `False`, the parameter will not be included in optimization process. (Default: True)
|
||||||
|
* `load` - when set to `False`, results of a previous hyperopt run (in `buy_params` and `sell_params` either in your strategy or the JSON output file) will not be used as the starting value for subsequent hyperopts. The default value specified in the parameter will be used instead. (Default: True)
|
||||||
|
|
||||||
|
!!! Tip "Effects of `load=False` on backtesting"
|
||||||
|
Be aware that setting the `load` option to `False` will mean backtesting will also use the default value specified in the parameter and *not* the value found through hyperoptimisation.
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
Hyperoptable parameters cannot be used in `populate_indicators` - as hyperopt does not recalculate indicators for each epoch, so the starting value would be used in this case.
|
Hyperoptable parameters cannot be used in `populate_indicators` - as hyperopt does not recalculate indicators for each epoch, so the starting value would be used in this case.
|
||||||
|
|||||||
@@ -112,8 +112,8 @@ For convenience `lookback_days` can be specified, which will imply that 1d candl
|
|||||||
!!! Warning "Performance implications when using lookback range"
|
!!! Warning "Performance implications when using lookback range"
|
||||||
If used in first position in combination with lookback, the computation of the range based volume can be time and resource consuming, as it downloads candles for all tradable pairs. Hence it's highly advised to use the standard approach with `VolumeFilter` to narrow the pairlist down for further range volume calculation.
|
If used in first position in combination with lookback, the computation of the range based volume can be time and resource consuming, as it downloads candles for all tradable pairs. Hence it's highly advised to use the standard approach with `VolumeFilter` to narrow the pairlist down for further range volume calculation.
|
||||||
|
|
||||||
??? Tip "Unsupported exchanges (Bittrex, Gemini)"
|
??? Tip "Unsupported exchanges"
|
||||||
On some exchanges (like Bittrex and Gemini), regular VolumePairList does not work as the api does not natively provide 24h volume. This can be worked around by using candle data to build the volume.
|
On some exchanges (like Gemini), regular VolumePairList does not work as the api does not natively provide 24h volume. This can be worked around by using candle data to build the volume.
|
||||||
To roughly simulate 24h volume, you can use the following configuration.
|
To roughly simulate 24h volume, you can use the following configuration.
|
||||||
Please note that These pairlists will only refresh once per day.
|
Please note that These pairlists will only refresh once per day.
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -40,7 +40,7 @@ Freqtrade is a free and open source crypto trading bot written in Python. It is
|
|||||||
Please read the [exchange specific notes](exchanges.md) to learn about eventual, special configurations needed for each exchange.
|
Please read the [exchange specific notes](exchanges.md) to learn about eventual, special configurations needed for each exchange.
|
||||||
|
|
||||||
- [X] [Binance](https://www.binance.com/)
|
- [X] [Binance](https://www.binance.com/)
|
||||||
- [X] [Bittrex](https://bittrex.com/)
|
- [X] [Bitmart](https://bitmart.com/)
|
||||||
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
||||||
- [X] [Huobi](http://huobi.com/)
|
- [X] [Huobi](http://huobi.com/)
|
||||||
- [X] [Kraken](https://kraken.com/)
|
- [X] [Kraken](https://kraken.com/)
|
||||||
|
|||||||
@@ -40,11 +40,41 @@ usage: freqtrade recursive-analysis [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
|||||||
[--startup-candle STARTUP_CANDLES [STARTUP_CANDLES ...]]
|
[--startup-candle STARTUP_CANDLES [STARTUP_CANDLES ...]]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-p PAIR, --pairs PAIR
|
-h, --help show this help message and exit
|
||||||
|
-i TIMEFRAME, --timeframe TIMEFRAME
|
||||||
|
Specify timeframe (`1m`, `5m`, `30m`, `1h`, `1d`).
|
||||||
|
--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}
|
||||||
|
Storage format for downloaded candle (OHLCV) data.
|
||||||
|
(default: `feather`).
|
||||||
|
-p PAIR, --pairs PAIR
|
||||||
Limit command to this pair.
|
Limit command to this pair.
|
||||||
--startup-candle STARTUP_CANDLE [STARTUP_CANDLE ...]
|
--startup-candle STARTUP_CANDLE [STARTUP_CANDLE ...]
|
||||||
Provide a space-separated list of startup_candle_count to
|
Provide a space-separated list of startup_candle_count to
|
||||||
be checked. Default : `199 399 499 999 1999`.
|
be checked. Default : `199 399 499 999 1999`.
|
||||||
|
|
||||||
|
Common arguments:
|
||||||
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
|
--logfile FILE Log to the file specified. Special values are:
|
||||||
|
'syslog', 'journald'. See the documentation for more
|
||||||
|
details.
|
||||||
|
-V, --version show program's version number and exit
|
||||||
|
-c PATH, --config PATH
|
||||||
|
Specify configuration file (default:
|
||||||
|
`userdir/config.json` or `config.json` whichever
|
||||||
|
exists). Multiple --config options may be used. Can be
|
||||||
|
set to `-` to read config from stdin.
|
||||||
|
-d PATH, --datadir PATH
|
||||||
|
Path to directory with historical backtesting data.
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
|
||||||
|
Strategy arguments:
|
||||||
|
-s NAME, --strategy NAME
|
||||||
|
Specify strategy class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
|
--timerange TIMERANGE
|
||||||
|
Specify what timerange of data to use.
|
||||||
```
|
```
|
||||||
|
|
||||||
### Why are odd-numbered default startup candles used?
|
### Why are odd-numbered default startup candles used?
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
markdown==3.4.4
|
markdown==3.5.1
|
||||||
mkdocs==1.5.3
|
mkdocs==1.5.3
|
||||||
mkdocs-material==9.4.1
|
mkdocs-material==9.5.3
|
||||||
mdx_truly_sane_lists==1.3
|
mdx_truly_sane_lists==1.3
|
||||||
pymdown-extensions==10.3
|
pymdown-extensions==10.5
|
||||||
jinja2==3.1.2
|
jinja2==3.1.2
|
||||||
|
|||||||
+6
-3
@@ -134,13 +134,16 @@ python3 scripts/rest_client.py --config rest_config.json <command> [optional par
|
|||||||
| `reload_config` | Reloads the configuration file.
|
| `reload_config` | Reloads the configuration file.
|
||||||
| `trades` | List last trades. Limited to 500 trades per call.
|
| `trades` | List last trades. Limited to 500 trades per call.
|
||||||
| `trade/<tradeid>` | Get specific trade.
|
| `trade/<tradeid>` | Get specific trade.
|
||||||
| `trade/<tradeid>` | DELETE - Remove trade from the database. Tries to close open orders. Requires manual handling of this trade on the exchange.
|
| `trades/<tradeid>` | DELETE - Remove trade from the database. Tries to close open orders. Requires manual handling of this trade on the exchange.
|
||||||
| `trade/<tradeid>/open-order` | DELETE - Cancel open order for this trade.
|
| `trades/<tradeid>/open-order` | DELETE - Cancel open order for this trade.
|
||||||
| `trade/<tradeid>/reload` | GET - Reload a trade from the Exchange. Only works in live, and can potentially help recover a trade that was manually sold on the exchange.
|
| `trades/<tradeid>/reload` | GET - Reload a trade from the Exchange. Only works in live, and can potentially help recover a trade that was manually sold on the exchange.
|
||||||
| `show_config` | Shows part of the current configuration with relevant settings to operation.
|
| `show_config` | Shows part of the current configuration with relevant settings to operation.
|
||||||
| `logs` | Shows last log messages.
|
| `logs` | Shows last log messages.
|
||||||
| `status` | Lists all open trades.
|
| `status` | Lists all open trades.
|
||||||
| `count` | Displays number of trades used and available.
|
| `count` | Displays number of trades used and available.
|
||||||
|
| `entries [pair]` | Shows profit statistics for each enter tags for given pair (or all pairs if pair isn't given). Pair is optional.
|
||||||
|
| `exits [pair]` | Shows profit statistics for each exit reasons for given pair (or all pairs if pair isn't given). Pair is optional.
|
||||||
|
| `mix_tags [pair]` | Shows profit statistics for each combinations of enter tag + exit reasons for given pair (or all pairs if pair isn't given). Pair is optional.
|
||||||
| `locks` | Displays currently locked pairs.
|
| `locks` | Displays currently locked pairs.
|
||||||
| `delete_lock <lock_id>` | Deletes (disables) the lock by id.
|
| `delete_lock <lock_id>` | Deletes (disables) the lock by id.
|
||||||
| `profit` | Display a summary of your profit/loss from close trades and some stats about your performance.
|
| `profit` | Display a summary of your profit/loss from close trades and some stats about your performance.
|
||||||
|
|||||||
@@ -489,7 +489,7 @@ The helper function `stoploss_from_absolute()` can be used to convert from an ab
|
|||||||
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
||||||
trade_date = timeframe_to_prev_date(self.timeframe, trade.open_date_utc)
|
trade_date = timeframe_to_prev_date(self.timeframe, trade.open_date_utc)
|
||||||
candle = dataframe.iloc[-1].squeeze()
|
candle = dataframe.iloc[-1].squeeze()
|
||||||
sign = 1 if trade.is_short else -1
|
side = 1 if trade.is_short else -1
|
||||||
return stoploss_from_absolute(current_rate + (side * candle['atr'] * 2),
|
return stoploss_from_absolute(current_rate + (side * candle['atr'] * 2),
|
||||||
current_rate, is_short=trade.is_short,
|
current_rate, is_short=trade.is_short,
|
||||||
leverage=trade.leverage)
|
leverage=trade.leverage)
|
||||||
@@ -760,9 +760,9 @@ The `position_adjustment_enable` strategy property enables the usage of `adjust_
|
|||||||
For performance reasons, it's disabled by default and freqtrade will show a warning message on startup if enabled.
|
For performance reasons, it's disabled by default and freqtrade will show a warning message on startup if enabled.
|
||||||
`adjust_trade_position()` can be used to perform additional orders, for example to manage risk with DCA (Dollar Cost Averaging) or to increase or decrease positions.
|
`adjust_trade_position()` can be used to perform additional orders, for example to manage risk with DCA (Dollar Cost Averaging) or to increase or decrease positions.
|
||||||
|
|
||||||
`max_entry_position_adjustment` property is used to limit the number of additional buys per trade (on top of the first buy) that the bot can execute. By default, the value is -1 which means the bot have no limit on number of adjustment buys.
|
`max_entry_position_adjustment` property is used to limit the number of additional entries per trade (on top of the first entry order) that the bot can execute. By default, the value is -1 which means the bot have no limit on number of adjustment entries.
|
||||||
|
|
||||||
The strategy is expected to return a stake_amount (in stake currency) between `min_stake` and `max_stake` if and when an additional buy order should be made (position is increased).
|
The strategy is expected to return a stake_amount (in stake currency) between `min_stake` and `max_stake` if and when an additional entry order should be made (position is increased -> buy order for long trades, sell order for short trades).
|
||||||
If there are not enough funds in the wallet (the return value is above `max_stake`) then the signal will be ignored.
|
If there are not enough funds in the wallet (the return value is above `max_stake`) then the signal will be ignored.
|
||||||
Additional orders also result in additional fees and those orders don't count towards `max_open_trades`.
|
Additional orders also result in additional fees and those orders don't count towards `max_open_trades`.
|
||||||
|
|
||||||
@@ -770,9 +770,11 @@ This callback is **not** called when there is an open order (either buy or sell)
|
|||||||
|
|
||||||
`adjust_trade_position()` is called very frequently for the duration of a trade, so you must keep your implementation as performant as possible.
|
`adjust_trade_position()` is called very frequently for the duration of a trade, so you must keep your implementation as performant as possible.
|
||||||
|
|
||||||
Additional Buys are ignored once you have reached the maximum amount of extra buys that you have set on `max_entry_position_adjustment`, but the callback is called anyway looking for partial exits.
|
Additional entries are ignored once you have reached the maximum amount of extra entries that you have set on `max_entry_position_adjustment`, but the callback is called anyway looking for partial exits.
|
||||||
|
|
||||||
Position adjustments will always be applied in the direction of the trade, so a positive value will always increase your position (negative values will decrease your position), no matter if it's a long or short trade. Modifications to leverage are not possible, and the stake-amount is assumed to be before applying leverage.
|
Position adjustments will always be applied in the direction of the trade, so a positive value will always increase your position (negative values will decrease your position), no matter if it's a long or short trade.
|
||||||
|
|
||||||
|
Modifications to leverage are not possible, and the stake-amount returned is assumed to be before applying leverage.
|
||||||
|
|
||||||
!!! Note "About stake size"
|
!!! Note "About stake size"
|
||||||
Using fixed stake size means it will be the amount used for the first order, just like without position adjustment.
|
Using fixed stake size means it will be the amount used for the first order, just like without position adjustment.
|
||||||
|
|||||||
@@ -173,7 +173,7 @@ You can use [recursive-analysis](recursive-analysis.md) to check and find the co
|
|||||||
In this example strategy, this should be set to 400 (`startup_candle_count = 400`), since the minimum needed history for ema100 calculation to make sure the value is correct is 400 candles.
|
In this example strategy, this should be set to 400 (`startup_candle_count = 400`), since the minimum needed history for ema100 calculation to make sure the value is correct is 400 candles.
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
dataframe['ema100'] = ta.EMA(dataframe, timeperiod=400)
|
dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)
|
||||||
```
|
```
|
||||||
|
|
||||||
By letting the bot know how much history is needed, backtest trades can start at the specified timerange during backtesting and hyperopt.
|
By letting the bot know how much history is needed, backtest trades can start at the specified timerange during backtesting and hyperopt.
|
||||||
@@ -486,17 +486,18 @@ for more information.
|
|||||||
|
|
||||||
:param timeframe: Informative timeframe. Must always be equal or higher than strategy timeframe.
|
:param timeframe: Informative timeframe. Must always be equal or higher than strategy timeframe.
|
||||||
:param asset: Informative asset, for example BTC, BTC/USDT, ETH/BTC. Do not specify to use
|
:param asset: Informative asset, for example BTC, BTC/USDT, ETH/BTC. Do not specify to use
|
||||||
current pair.
|
current pair. Also supports limited pair format strings (see below)
|
||||||
:param fmt: Column format (str) or column formatter (callable(name, asset, timeframe)). When not
|
:param fmt: Column format (str) or column formatter (callable(name, asset, timeframe)). When not
|
||||||
specified, defaults to:
|
specified, defaults to:
|
||||||
* {base}_{quote}_{column}_{timeframe} if asset is specified.
|
* {base}_{quote}_{column}_{timeframe} if asset is specified.
|
||||||
* {column}_{timeframe} if asset is not specified.
|
* {column}_{timeframe} if asset is not specified.
|
||||||
Format string supports these format variables:
|
Pair format supports these format variables:
|
||||||
* {asset} - full name of the asset, for example 'BTC/USDT'.
|
|
||||||
* {base} - base currency in lower case, for example 'eth'.
|
* {base} - base currency in lower case, for example 'eth'.
|
||||||
* {BASE} - same as {base}, except in upper case.
|
* {BASE} - same as {base}, except in upper case.
|
||||||
* {quote} - quote currency in lower case, for example 'usdt'.
|
* {quote} - quote currency in lower case, for example 'usdt'.
|
||||||
* {QUOTE} - same as {quote}, except in upper case.
|
* {QUOTE} - same as {quote}, except in upper case.
|
||||||
|
Format string additionally supports this variables.
|
||||||
|
* {asset} - full name of the asset, for example 'BTC/USDT'.
|
||||||
* {column} - name of dataframe column.
|
* {column} - name of dataframe column.
|
||||||
* {timeframe} - timeframe of informative dataframe.
|
* {timeframe} - timeframe of informative dataframe.
|
||||||
:param ffill: ffill dataframe after merging informative pair.
|
:param ffill: ffill dataframe after merging informative pair.
|
||||||
@@ -1008,6 +1009,10 @@ The following lists some common patterns which should be avoided to prevent frus
|
|||||||
- don't use `dataframe['volume'].mean()`. This uses the full DataFrame for backtesting, including data from the future. Use `dataframe['volume'].rolling(<window>).mean()` instead
|
- don't use `dataframe['volume'].mean()`. This uses the full DataFrame for backtesting, including data from the future. Use `dataframe['volume'].rolling(<window>).mean()` instead
|
||||||
- don't use `.resample('1h')`. This uses the left border of the interval, so moves data from an hour to the start of the hour. Use `.resample('1h', label='right')` instead.
|
- don't use `.resample('1h')`. This uses the left border of the interval, so moves data from an hour to the start of the hour. Use `.resample('1h', label='right')` instead.
|
||||||
|
|
||||||
|
!!! Tip "Identifying problems"
|
||||||
|
You may also want to check the 2 helper commands [lookahead-analysis](lookahead-analysis.md) and [recursive-analysis](recursive-analysis.md), which can each help you figure out problems with your strategy in different ways.
|
||||||
|
Please treat them as what they are - helpers to identify most common problems. A negative result of each does not guarantee that there's none of the above errors included.
|
||||||
|
|
||||||
### Colliding signals
|
### Colliding signals
|
||||||
|
|
||||||
When conflicting signals collide (e.g. both `'enter_long'` and `'exit_long'` are 1), freqtrade will do nothing and ignore the entry signal. This will avoid trades that enter, and exit immediately. Obviously, this can potentially lead to missed entries.
|
When conflicting signals collide (e.g. both `'enter_long'` and `'exit_long'` are 1), freqtrade will do nothing and ignore the entry signal. This will avoid trades that enter, and exit immediately. Obviously, this can potentially lead to missed entries.
|
||||||
|
|||||||
@@ -570,7 +570,7 @@ def populate_any_indicators(
|
|||||||
```
|
```
|
||||||
|
|
||||||
1. Features - Move to `feature_engineering_expand_all`
|
1. Features - Move to `feature_engineering_expand_all`
|
||||||
2. Basic features, not expanded across `include_periods_candles` - move to`feature_engineering_expand_basic()`.
|
2. Basic features, not expanded across `indicator_periods_candles` - move to`feature_engineering_expand_basic()`.
|
||||||
3. Standard features which should not be expanded - move to `feature_engineering_standard()`.
|
3. Standard features which should not be expanded - move to `feature_engineering_standard()`.
|
||||||
4. Targets - Move this part to `set_freqai_targets()`.
|
4. Targets - Move this part to `set_freqai_targets()`.
|
||||||
|
|
||||||
|
|||||||
@@ -175,6 +175,7 @@ official commands. You can ask at any moment for help with `/help`.
|
|||||||
| `/status` | Lists all open trades
|
| `/status` | Lists all open trades
|
||||||
| `/status <trade_id>` | Lists one or more specific trade. Separate multiple <trade_id> with a blank space.
|
| `/status <trade_id>` | Lists one or more specific trade. Separate multiple <trade_id> with a blank space.
|
||||||
| `/status table` | List all open trades in a table format. Pending buy orders are marked with an asterisk (*) Pending sell orders are marked with a double asterisk (**)
|
| `/status table` | List all open trades in a table format. Pending buy orders are marked with an asterisk (*) Pending sell orders are marked with a double asterisk (**)
|
||||||
|
| `/order <trade_id>` | Lists orders of one or more specific trade. Separate multiple <trade_id> with a blank space.
|
||||||
| `/trades [limit]` | List all recently closed trades in a table format.
|
| `/trades [limit]` | List all recently closed trades in a table format.
|
||||||
| `/count` | Displays number of trades used and available
|
| `/count` | Displays number of trades used and available
|
||||||
| `/locks` | Show currently locked pairs.
|
| `/locks` | Show currently locked pairs.
|
||||||
|
|||||||
+30
-26
@@ -242,7 +242,6 @@ bitkk True missing opt: fetchMyTrades
|
|||||||
bitmart True
|
bitmart True
|
||||||
bitmax True missing opt: fetchMyTrades
|
bitmax True missing opt: fetchMyTrades
|
||||||
bitpanda True
|
bitpanda True
|
||||||
bittrex True
|
|
||||||
bitvavo True
|
bitvavo True
|
||||||
bitz True missing opt: fetchMyTrades
|
bitz True missing opt: fetchMyTrades
|
||||||
btcalpha True missing opt: fetchTicker, fetchTickers
|
btcalpha True missing opt: fetchTicker, fetchTickers
|
||||||
@@ -324,7 +323,6 @@ bitpanda True
|
|||||||
bitso False missing: fetchOHLCV
|
bitso False missing: fetchOHLCV
|
||||||
bitstamp True missing opt: fetchTickers
|
bitstamp True missing opt: fetchTickers
|
||||||
bitstamp1 False missing: fetchOrder, fetchOHLCV
|
bitstamp1 False missing: fetchOrder, fetchOHLCV
|
||||||
bittrex True
|
|
||||||
bitvavo True
|
bitvavo True
|
||||||
bitz True missing opt: fetchMyTrades
|
bitz True missing opt: fetchMyTrades
|
||||||
bl3p False missing: fetchOrder, fetchOHLCV
|
bl3p False missing: fetchOrder, fetchOHLCV
|
||||||
@@ -427,25 +425,33 @@ zb True missing opt: fetchMyTrades
|
|||||||
Use the `list-timeframes` subcommand to see the list of timeframes available for the exchange.
|
Use the `list-timeframes` subcommand to see the list of timeframes available for the exchange.
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade list-timeframes [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--exchange EXCHANGE] [-1]
|
usage: freqtrade list-timeframes [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
|
[-d PATH] [--userdir PATH]
|
||||||
|
[--exchange EXCHANGE] [-1]
|
||||||
|
|
||||||
optional arguments:
|
options:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no config is provided.
|
--exchange EXCHANGE Exchange name. Only valid if no config is provided.
|
||||||
-1, --one-column Print output in one column.
|
-1, --one-column Print output in one column.
|
||||||
|
|
||||||
Common arguments:
|
Common arguments:
|
||||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
--logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details.
|
--logfile FILE, --log-file FILE
|
||||||
|
Log to the file specified. Special values are:
|
||||||
|
'syslog', 'journald'. See the documentation for more
|
||||||
|
details.
|
||||||
-V, --version show program's version number and exit
|
-V, --version show program's version number and exit
|
||||||
-c PATH, --config PATH
|
-c PATH, --config PATH
|
||||||
Specify configuration file (default: `config.json`). Multiple --config options may be used. Can be set to `-`
|
Specify configuration file (default:
|
||||||
to read config from stdin.
|
`userdir/config.json` or `config.json` whichever
|
||||||
-d PATH, --datadir PATH
|
exists). Multiple --config options may be used. Can be
|
||||||
|
set to `-` to read config from stdin.
|
||||||
|
-d PATH, --datadir PATH, --data-dir PATH
|
||||||
Path to directory with historical backtesting data.
|
Path to directory with historical backtesting data.
|
||||||
--userdir PATH, --user-data-dir PATH
|
--userdir PATH, --user-data-dir PATH
|
||||||
Path to userdata directory.
|
Path to userdata directory.
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
* Example: see the timeframes for the 'binance' exchange, set in the configuration file:
|
* Example: see the timeframes for the 'binance' exchange, set in the configuration file:
|
||||||
@@ -479,20 +485,17 @@ usage: freqtrade list-markets [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
|||||||
[-d PATH] [--userdir PATH] [--exchange EXCHANGE]
|
[-d PATH] [--userdir PATH] [--exchange EXCHANGE]
|
||||||
[--print-list] [--print-json] [-1] [--print-csv]
|
[--print-list] [--print-json] [-1] [--print-csv]
|
||||||
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
||||||
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a]
|
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]
|
||||||
[--trading-mode {spot,margin,futures}]
|
[-a] [--trading-mode {spot,margin,futures}]
|
||||||
|
|
||||||
usage: freqtrade list-pairs [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
usage: freqtrade list-pairs [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
[-d PATH] [--userdir PATH] [--exchange EXCHANGE]
|
[-d PATH] [--userdir PATH] [--exchange EXCHANGE]
|
||||||
[--print-list] [--print-json] [-1] [--print-csv]
|
[--print-list] [--print-json] [-1] [--print-csv]
|
||||||
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
||||||
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a]
|
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a]
|
||||||
[--trading-mode {spot,margin,futures}]
|
[--trading-mode {spot,margin,futures}]
|
||||||
|
options:
|
||||||
optional arguments:
|
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
--exchange EXCHANGE Exchange name. Only valid if no config is provided.
|
||||||
config is provided.
|
|
||||||
--print-list Print list of pairs or market symbols. By default data
|
--print-list Print list of pairs or market symbols. By default data
|
||||||
is printed in the tabular format.
|
is printed in the tabular format.
|
||||||
--print-json Print list of pairs or market symbols in JSON format.
|
--print-json Print list of pairs or market symbols in JSON format.
|
||||||
@@ -504,20 +507,22 @@ optional arguments:
|
|||||||
Specify quote currency(-ies). Space-separated list.
|
Specify quote currency(-ies). Space-separated list.
|
||||||
-a, --all Print all pairs or market symbols. By default only
|
-a, --all Print all pairs or market symbols. By default only
|
||||||
active ones are shown.
|
active ones are shown.
|
||||||
--trading-mode {spot,margin,futures}
|
--trading-mode {spot,margin,futures}, --tradingmode {spot,margin,futures}
|
||||||
Select Trading mode
|
Select Trading mode
|
||||||
|
|
||||||
Common arguments:
|
Common arguments:
|
||||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
--logfile FILE Log to the file specified. Special values are:
|
--logfile FILE, --log-file FILE
|
||||||
|
Log to the file specified. Special values are:
|
||||||
'syslog', 'journald'. See the documentation for more
|
'syslog', 'journald'. See the documentation for more
|
||||||
details.
|
details.
|
||||||
-V, --version show program's version number and exit
|
-V, --version show program's version number and exit
|
||||||
-c PATH, --config PATH
|
-c PATH, --config PATH
|
||||||
Specify configuration file (default: `config.json`).
|
Specify configuration file (default:
|
||||||
Multiple --config options may be used. Can be set to
|
`userdir/config.json` or `config.json` whichever
|
||||||
`-` to read config from stdin.
|
exists). Multiple --config options may be used. Can be
|
||||||
-d PATH, --datadir PATH
|
set to `-` to read config from stdin.
|
||||||
|
-d PATH, --datadir PATH, --data-dir PATH
|
||||||
Path to directory with historical backtesting data.
|
Path to directory with historical backtesting data.
|
||||||
--userdir PATH, --user-data-dir PATH
|
--userdir PATH, --user-data-dir PATH
|
||||||
Path to userdata directory.
|
Path to userdata directory.
|
||||||
@@ -532,7 +537,7 @@ Pairs/markets are sorted by its symbol string in the printed output.
|
|||||||
### Examples
|
### Examples
|
||||||
|
|
||||||
* Print the list of active pairs with quote currency USD on exchange, specified in the default
|
* Print the list of active pairs with quote currency USD on exchange, specified in the default
|
||||||
configuration file (i.e. pairs on the "Bittrex" exchange) in JSON format:
|
configuration file (i.e. pairs on the "Binance" exchange) in JSON format:
|
||||||
|
|
||||||
```
|
```
|
||||||
$ freqtrade list-pairs --quote USD --print-json
|
$ freqtrade list-pairs --quote USD --print-json
|
||||||
@@ -564,7 +569,7 @@ usage: freqtrade test-pairlist [-h] [--userdir PATH] [-v] [-c PATH]
|
|||||||
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]
|
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]
|
||||||
[-1] [--print-json] [--exchange EXCHANGE]
|
[-1] [--print-json] [--exchange EXCHANGE]
|
||||||
|
|
||||||
optional arguments:
|
options:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
--userdir PATH, --user-data-dir PATH
|
--userdir PATH, --user-data-dir PATH
|
||||||
Path to userdata directory.
|
Path to userdata directory.
|
||||||
@@ -578,8 +583,7 @@ optional arguments:
|
|||||||
Specify quote currency(-ies). Space-separated list.
|
Specify quote currency(-ies). Space-separated list.
|
||||||
-1, --one-column Print output in one column.
|
-1, --one-column Print output in one column.
|
||||||
--print-json Print list of pairs or market symbols in JSON format.
|
--print-json Print list of pairs or market symbols in JSON format.
|
||||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
--exchange EXCHANGE Exchange name. Only valid if no config is provided.
|
||||||
config is provided.
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -302,6 +302,7 @@ You can configure this as follows:
|
|||||||
```
|
```
|
||||||
|
|
||||||
The above represents the default (`exit_fill` and `entry_fill` are optional and will default to the above configuration) - modifications are obviously possible.
|
The above represents the default (`exit_fill` and `entry_fill` are optional and will default to the above configuration) - modifications are obviously possible.
|
||||||
|
To disable either of the two default values (`entry_fill` / `exit_fill`), you can assign them an empty array (`exit_fill: []`).
|
||||||
|
|
||||||
Available fields correspond to the fields for webhooks and are documented in the corresponding webhook sections.
|
Available fields correspond to the fields for webhooks and are documented in the corresponding webhook sections.
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
""" Freqtrade bot """
|
""" Freqtrade bot """
|
||||||
__version__ = '2023.9'
|
__version__ = '2023.12'
|
||||||
|
|
||||||
if 'dev' in __version__:
|
if 'dev' in __version__:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|||||||
@@ -65,8 +65,8 @@ ARGS_BUILD_CONFIG = ["config"]
|
|||||||
|
|
||||||
ARGS_BUILD_STRATEGY = ["user_data_dir", "strategy", "template"]
|
ARGS_BUILD_STRATEGY = ["user_data_dir", "strategy", "template"]
|
||||||
|
|
||||||
|
ARGS_CONVERT_DATA_TRADES = ["pairs", "format_from_trades", "format_to", "erase", "exchange"]
|
||||||
ARGS_CONVERT_DATA = ["pairs", "format_from", "format_to", "erase", "exchange"]
|
ARGS_CONVERT_DATA = ["pairs", "format_from", "format_to", "erase", "exchange"]
|
||||||
|
|
||||||
ARGS_CONVERT_DATA_OHLCV = ARGS_CONVERT_DATA + ["timeframes", "trading_mode", "candle_types"]
|
ARGS_CONVERT_DATA_OHLCV = ARGS_CONVERT_DATA + ["timeframes", "trading_mode", "candle_types"]
|
||||||
|
|
||||||
ARGS_CONVERT_TRADES = ["pairs", "timeframes", "exchange", "dataformat_ohlcv", "dataformat_trades"]
|
ARGS_CONVERT_TRADES = ["pairs", "timeframes", "exchange", "dataformat_ohlcv", "dataformat_trades"]
|
||||||
@@ -268,7 +268,7 @@ class Arguments:
|
|||||||
parents=[_common_parser],
|
parents=[_common_parser],
|
||||||
)
|
)
|
||||||
convert_trade_data_cmd.set_defaults(func=partial(start_convert_data, ohlcv=False))
|
convert_trade_data_cmd.set_defaults(func=partial(start_convert_data, ohlcv=False))
|
||||||
self._build_args(optionlist=ARGS_CONVERT_DATA, parser=convert_trade_data_cmd)
|
self._build_args(optionlist=ARGS_CONVERT_DATA_TRADES, parser=convert_trade_data_cmd)
|
||||||
|
|
||||||
# Add trades-to-ohlcv subcommand
|
# Add trades-to-ohlcv subcommand
|
||||||
convert_trade_data_cmd = subparsers.add_parser(
|
convert_trade_data_cmd = subparsers.add_parser(
|
||||||
|
|||||||
@@ -108,7 +108,6 @@ def ask_user_config() -> Dict[str, Any]:
|
|||||||
"choices": [
|
"choices": [
|
||||||
"binance",
|
"binance",
|
||||||
"binanceus",
|
"binanceus",
|
||||||
"bittrex",
|
|
||||||
"gate",
|
"gate",
|
||||||
"huobi",
|
"huobi",
|
||||||
"kraken",
|
"kraken",
|
||||||
|
|||||||
@@ -421,6 +421,12 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
'desired timeframe as specified as --timeframes/-t.',
|
'desired timeframe as specified as --timeframes/-t.',
|
||||||
action='store_true',
|
action='store_true',
|
||||||
),
|
),
|
||||||
|
"format_from_trades": Arg(
|
||||||
|
'--format-from',
|
||||||
|
help='Source format for data conversion.',
|
||||||
|
choices=constants.AVAILABLE_DATAHANDLERS + ['kraken_csv'],
|
||||||
|
required=True,
|
||||||
|
),
|
||||||
"format_from": Arg(
|
"format_from": Arg(
|
||||||
'--format-from',
|
'--format-from',
|
||||||
help='Source format for data conversion.',
|
help='Source format for data conversion.',
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ def start_convert_data(args: Dict[str, Any], ohlcv: bool = True) -> None:
|
|||||||
erase=args['erase'])
|
erase=args['erase'])
|
||||||
else:
|
else:
|
||||||
convert_trades_format(config,
|
convert_trades_format(config,
|
||||||
convert_from=args['format_from'], convert_to=args['format_to'],
|
convert_from=args['format_from_trades'], convert_to=args['format_to'],
|
||||||
erase=args['erase'])
|
erase=args['erase'])
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -140,7 +140,7 @@ def start_lookahead_analysis(args: Dict[str, Any]) -> None:
|
|||||||
:param args: Cli args from Arguments()
|
:param args: Cli args from Arguments()
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
from freqtrade.optimize.lookahead_analysis_helpers import LookaheadAnalysisSubFunctions
|
from freqtrade.optimize.analysis.lookahead_helpers import LookaheadAnalysisSubFunctions
|
||||||
|
|
||||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||||
LookaheadAnalysisSubFunctions.start(config)
|
LookaheadAnalysisSubFunctions.start(config)
|
||||||
@@ -152,7 +152,7 @@ def start_recursive_analysis(args: Dict[str, Any]) -> None:
|
|||||||
:param args: Cli args from Arguments()
|
:param args: Cli args from Arguments()
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
from freqtrade.optimize.recursive_analysis_helpers import RecursiveAnalysisSubFunctions
|
from freqtrade.optimize.analysis.recursive_helpers import RecursiveAnalysisSubFunctions
|
||||||
|
|
||||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||||
RecursiveAnalysisSubFunctions.start(config)
|
RecursiveAnalysisSubFunctions.start(config)
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ def validate_config_schema(conf: Dict[str, Any], preliminary: bool = False) -> D
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def validate_config_consistency(conf: Dict[str, Any], preliminary: bool = False) -> None:
|
def validate_config_consistency(conf: Dict[str, Any], *, preliminary: bool = False) -> None:
|
||||||
"""
|
"""
|
||||||
Validate the configuration consistency.
|
Validate the configuration consistency.
|
||||||
Should be ran after loading both configuration and strategy,
|
Should be ran after loading both configuration and strategy,
|
||||||
@@ -86,7 +86,7 @@ def validate_config_consistency(conf: Dict[str, Any], preliminary: bool = False)
|
|||||||
_validate_ask_orderbook(conf)
|
_validate_ask_orderbook(conf)
|
||||||
_validate_freqai_hyperopt(conf)
|
_validate_freqai_hyperopt(conf)
|
||||||
_validate_freqai_backtest(conf)
|
_validate_freqai_backtest(conf)
|
||||||
_validate_freqai_include_timeframes(conf)
|
_validate_freqai_include_timeframes(conf, preliminary=preliminary)
|
||||||
_validate_consumers(conf)
|
_validate_consumers(conf)
|
||||||
validate_migrated_strategy_settings(conf)
|
validate_migrated_strategy_settings(conf)
|
||||||
|
|
||||||
@@ -335,7 +335,7 @@ def _validate_freqai_hyperopt(conf: Dict[str, Any]) -> None:
|
|||||||
'Using analyze-per-epoch parameter is not supported with a FreqAI strategy.')
|
'Using analyze-per-epoch parameter is not supported with a FreqAI strategy.')
|
||||||
|
|
||||||
|
|
||||||
def _validate_freqai_include_timeframes(conf: Dict[str, Any]) -> None:
|
def _validate_freqai_include_timeframes(conf: Dict[str, Any], preliminary: bool) -> None:
|
||||||
freqai_enabled = conf.get('freqai', {}).get('enabled', False)
|
freqai_enabled = conf.get('freqai', {}).get('enabled', False)
|
||||||
if freqai_enabled:
|
if freqai_enabled:
|
||||||
main_tf = conf.get('timeframe', '5m')
|
main_tf = conf.get('timeframe', '5m')
|
||||||
@@ -355,7 +355,7 @@ def _validate_freqai_include_timeframes(conf: Dict[str, Any]) -> None:
|
|||||||
f"`include_timeframes`.Offending include-timeframes: {', '.join(offending_lines)}")
|
f"`include_timeframes`.Offending include-timeframes: {', '.join(offending_lines)}")
|
||||||
|
|
||||||
# Ensure that the base timeframe is included in the include_timeframes list
|
# Ensure that the base timeframe is included in the include_timeframes list
|
||||||
if main_tf not in freqai_include_timeframes:
|
if not preliminary and main_tf not in freqai_include_timeframes:
|
||||||
feature_parameters = conf.get('freqai', {}).get('feature_parameters', {})
|
feature_parameters = conf.get('freqai', {}).get('feature_parameters', {})
|
||||||
include_timeframes = [main_tf] + freqai_include_timeframes
|
include_timeframes = [main_tf] + freqai_include_timeframes
|
||||||
conf.get('freqai', {}).get('feature_parameters', {}) \
|
conf.get('freqai', {}).get('feature_parameters', {}) \
|
||||||
|
|||||||
@@ -326,7 +326,10 @@ def load_backtest_data(filename: Union[Path, str], strategy: Optional[str] = Non
|
|||||||
"Please specify a strategy.")
|
"Please specify a strategy.")
|
||||||
|
|
||||||
if strategy not in data['strategy']:
|
if strategy not in data['strategy']:
|
||||||
raise ValueError(f"Strategy {strategy} not available in the backtest result.")
|
raise ValueError(
|
||||||
|
f"Strategy {strategy} not available in the backtest result. "
|
||||||
|
f"Available strategies are '{','.join(data['strategy'].keys())}'"
|
||||||
|
)
|
||||||
|
|
||||||
data = data['strategy'][strategy]['trades']
|
data = data['strategy'][strategy]['trades']
|
||||||
df = pd.DataFrame(data)
|
df = pd.DataFrame(data)
|
||||||
|
|||||||
@@ -116,8 +116,8 @@ def ohlcv_fill_up_missing_data(dataframe: DataFrame, timeframe: str, pair: str)
|
|||||||
len_after = len(df)
|
len_after = len(df)
|
||||||
pct_missing = (len_after - len_before) / len_before if len_before > 0 else 0
|
pct_missing = (len_after - len_before) / len_before if len_before > 0 else 0
|
||||||
if len_before != len_after:
|
if len_before != len_after:
|
||||||
message = (f"Missing data fillup for {pair}: before: {len_before} - after: {len_after}"
|
message = (f"Missing data fillup for {pair}, {timeframe}: "
|
||||||
f" - {pct_missing:.2%}")
|
f"before: {len_before} - after: {len_after} - {pct_missing:.2%}")
|
||||||
if pct_missing > 0.01:
|
if pct_missing > 0.01:
|
||||||
logger.info(message)
|
logger.info(message)
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from freqtrade.configuration import TimeRange
|
|||||||
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, TRADES_DTYPES,
|
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, TRADES_DTYPES,
|
||||||
Config, TradeList)
|
Config, TradeList)
|
||||||
from freqtrade.enums import CandleType
|
from freqtrade.enums import CandleType
|
||||||
|
from freqtrade.exceptions import OperationalException
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -127,6 +128,16 @@ def convert_trades_format(config: Config, convert_from: str, convert_to: str, er
|
|||||||
:param convert_to: Target format
|
:param convert_to: Target format
|
||||||
:param erase: Erase source data (does not apply if source and target format are identical)
|
:param erase: Erase source data (does not apply if source and target format are identical)
|
||||||
"""
|
"""
|
||||||
|
if convert_from == 'kraken_csv':
|
||||||
|
if config['exchange']['name'] != 'kraken':
|
||||||
|
raise OperationalException(
|
||||||
|
'Converting from csv is only supported for kraken.'
|
||||||
|
'Please refer to the documentation for details about this special mode.'
|
||||||
|
)
|
||||||
|
from freqtrade.data.converter.trade_converter_kraken import import_kraken_trades_from_csv
|
||||||
|
import_kraken_trades_from_csv(config, convert_to)
|
||||||
|
return
|
||||||
|
|
||||||
from freqtrade.data.history.idatahandler import get_datahandler
|
from freqtrade.data.history.idatahandler import get_datahandler
|
||||||
src = get_datahandler(config['datadir'], convert_from)
|
src = get_datahandler(config['datadir'], convert_from)
|
||||||
trg = get_datahandler(config['datadir'], convert_to)
|
trg = get_datahandler(config['datadir'], convert_to)
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from freqtrade.constants import DATETIME_PRINT_FORMAT, DEFAULT_TRADES_COLUMNS, Config
|
||||||
|
from freqtrade.data.converter.trade_converter import (trades_convert_types,
|
||||||
|
trades_df_remove_duplicates)
|
||||||
|
from freqtrade.data.history.idatahandler import get_datahandler
|
||||||
|
from freqtrade.exceptions import OperationalException
|
||||||
|
from freqtrade.resolvers import ExchangeResolver
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
KRAKEN_CSV_TRADE_COLUMNS = ['timestamp', 'price', 'amount']
|
||||||
|
|
||||||
|
|
||||||
|
def import_kraken_trades_from_csv(config: Config, convert_to: str):
|
||||||
|
"""
|
||||||
|
Import kraken trades from csv
|
||||||
|
"""
|
||||||
|
if config['exchange']['name'] != 'kraken':
|
||||||
|
raise OperationalException('This function is only for the kraken exchange.')
|
||||||
|
|
||||||
|
datadir: Path = config['datadir']
|
||||||
|
data_handler = get_datahandler(datadir, data_format=convert_to)
|
||||||
|
|
||||||
|
tradesdir: Path = config['datadir'] / 'trades_csv'
|
||||||
|
exchange = ExchangeResolver.load_exchange(config, validate=False)
|
||||||
|
# iterate through directories in this directory
|
||||||
|
data_symbols = {p.stem for p in tradesdir.rglob('*.csv')}
|
||||||
|
|
||||||
|
# create pair/filename mapping
|
||||||
|
markets = {
|
||||||
|
(m['symbol'], m['altname']) for m in exchange.markets.values()
|
||||||
|
if m.get('altname') in data_symbols
|
||||||
|
}
|
||||||
|
logger.info(f"Found csv files for {', '.join(data_symbols)}.")
|
||||||
|
|
||||||
|
for pair, name in markets:
|
||||||
|
dfs = []
|
||||||
|
# Load and combine all csv files for this pair
|
||||||
|
for f in tradesdir.rglob(f"{name}.csv"):
|
||||||
|
df = pd.read_csv(f, names=KRAKEN_CSV_TRADE_COLUMNS)
|
||||||
|
dfs.append(df)
|
||||||
|
|
||||||
|
# Load existing trades data
|
||||||
|
if not dfs:
|
||||||
|
# edgecase, can only happen if the file was deleted between the above glob and here
|
||||||
|
logger.info(f"No data found for pair {pair}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
trades = pd.concat(dfs, ignore_index=True)
|
||||||
|
|
||||||
|
trades.loc[:, 'timestamp'] = trades['timestamp'] * 1e3
|
||||||
|
trades.loc[:, 'cost'] = trades['price'] * trades['amount']
|
||||||
|
for col in DEFAULT_TRADES_COLUMNS:
|
||||||
|
if col not in trades.columns:
|
||||||
|
trades[col] = ''
|
||||||
|
|
||||||
|
trades = trades[DEFAULT_TRADES_COLUMNS]
|
||||||
|
trades = trades_convert_types(trades)
|
||||||
|
|
||||||
|
trades_df = trades_df_remove_duplicates(trades)
|
||||||
|
logger.info(f"{pair}: {len(trades_df)} trades, from "
|
||||||
|
f"{trades_df['date'].min():{DATETIME_PRINT_FORMAT}} to "
|
||||||
|
f"{trades_df['date'].max():{DATETIME_PRINT_FORMAT}}")
|
||||||
|
|
||||||
|
data_handler.trades_store(pair, trades_df)
|
||||||
@@ -211,8 +211,9 @@ def prepare_results(analysed_trades, stratname,
|
|||||||
timerange=None):
|
timerange=None):
|
||||||
res_df = pd.DataFrame()
|
res_df = pd.DataFrame()
|
||||||
for pair, trades in analysed_trades[stratname].items():
|
for pair, trades in analysed_trades[stratname].items():
|
||||||
trades.dropna(subset=['close_date'], inplace=True)
|
if (trades.shape[0] > 0):
|
||||||
res_df = pd.concat([res_df, trades], ignore_index=True)
|
trades.dropna(subset=['close_date'], inplace=True)
|
||||||
|
res_df = pd.concat([res_df, trades], ignore_index=True)
|
||||||
|
|
||||||
res_df = _select_rows_within_dates(res_df, timerange)
|
res_df = _select_rows_within_dates(res_df, timerange)
|
||||||
|
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ from freqtrade.exchange.common import remove_exchange_credentials, MAP_EXCHANGE_
|
|||||||
from freqtrade.exchange.exchange import Exchange
|
from freqtrade.exchange.exchange import Exchange
|
||||||
# isort: on
|
# isort: on
|
||||||
from freqtrade.exchange.binance import Binance
|
from freqtrade.exchange.binance import Binance
|
||||||
|
from freqtrade.exchange.bitmart import Bitmart
|
||||||
from freqtrade.exchange.bitpanda import Bitpanda
|
from freqtrade.exchange.bitpanda import Bitpanda
|
||||||
from freqtrade.exchange.bittrex import Bittrex
|
|
||||||
from freqtrade.exchange.bitvavo import Bitvavo
|
from freqtrade.exchange.bitvavo import Bitvavo
|
||||||
from freqtrade.exchange.bybit import Bybit
|
from freqtrade.exchange.bybit import Bybit
|
||||||
from freqtrade.exchange.coinbasepro import Coinbasepro
|
from freqtrade.exchange.coinbasepro import Coinbasepro
|
||||||
|
|||||||
@@ -123,10 +123,14 @@ class Binance(Exchange):
|
|||||||
|
|
||||||
def funding_fee_cutoff(self, open_date: datetime):
|
def funding_fee_cutoff(self, open_date: datetime):
|
||||||
"""
|
"""
|
||||||
|
Funding fees are only charged at full hours (usually every 4-8h).
|
||||||
|
Therefore a trade opening at 10:00:01 will not be charged a funding fee until the next hour.
|
||||||
|
On binance, this cutoff is 15s.
|
||||||
|
https://github.com/freqtrade/freqtrade/pull/5779#discussion_r740175931
|
||||||
:param open_date: The open date for a trade
|
:param open_date: The open date for a trade
|
||||||
:return: The cutoff open time for when a funding fee is charged
|
:return: True if the date falls on a full hour, False otherwise
|
||||||
"""
|
"""
|
||||||
return open_date.minute > 0 or (open_date.minute == 0 and open_date.second > 15)
|
return open_date.minute == 0 and open_date.second < 15
|
||||||
|
|
||||||
def dry_run_liquidation_price(
|
def dry_run_liquidation_price(
|
||||||
self,
|
self,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,20 @@
|
|||||||
|
""" Bitmart exchange subclass """
|
||||||
|
import logging
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
from freqtrade.exchange import Exchange
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class Bitmart(Exchange):
|
||||||
|
"""
|
||||||
|
Bitmart exchange class. Contains adjustments needed for Freqtrade to work
|
||||||
|
with this exchange.
|
||||||
|
"""
|
||||||
|
|
||||||
|
_ft_has: Dict = {
|
||||||
|
"stoploss_on_exchange": False, # Bitmart API does not support stoploss orders
|
||||||
|
"ohlcv_candle_limit": 200,
|
||||||
|
}
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
""" Bittrex exchange subclass """
|
|
||||||
import logging
|
|
||||||
from typing import Dict
|
|
||||||
|
|
||||||
from freqtrade.exchange import Exchange
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class Bittrex(Exchange):
|
|
||||||
"""
|
|
||||||
Bittrex exchange class. Contains adjustments needed for Freqtrade to work
|
|
||||||
with this exchange.
|
|
||||||
"""
|
|
||||||
|
|
||||||
_ft_has: Dict = {
|
|
||||||
"ohlcv_candle_limit_per_timeframe": {
|
|
||||||
'1m': 1440,
|
|
||||||
'5m': 288,
|
|
||||||
'1h': 744,
|
|
||||||
'1d': 365,
|
|
||||||
},
|
|
||||||
"l2_limit_range": [1, 25, 500],
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,7 @@ import ccxt
|
|||||||
|
|
||||||
from freqtrade.constants import BuySell
|
from freqtrade.constants import BuySell
|
||||||
from freqtrade.enums import CandleType, MarginMode, PriceType, TradingMode
|
from freqtrade.enums import CandleType, MarginMode, PriceType, TradingMode
|
||||||
from freqtrade.exceptions import DDosProtection, OperationalException, TemporaryError
|
from freqtrade.exceptions import DDosProtection, ExchangeError, OperationalException, TemporaryError
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
from freqtrade.exchange.common import retrier
|
from freqtrade.exchange.common import retrier
|
||||||
from freqtrade.util.datetime_helpers import dt_now, dt_ts
|
from freqtrade.util.datetime_helpers import dt_now, dt_ts
|
||||||
@@ -29,6 +29,7 @@ class Bybit(Exchange):
|
|||||||
_ft_has: Dict = {
|
_ft_has: Dict = {
|
||||||
"ohlcv_candle_limit": 1000,
|
"ohlcv_candle_limit": 1000,
|
||||||
"ohlcv_has_history": True,
|
"ohlcv_has_history": True,
|
||||||
|
"order_time_in_force": ["GTC", "FOK", "IOC", "PO"],
|
||||||
}
|
}
|
||||||
_ft_has_futures: Dict = {
|
_ft_has_futures: Dict = {
|
||||||
"ohlcv_has_history": True,
|
"ohlcv_has_history": True,
|
||||||
@@ -202,8 +203,11 @@ class Bybit(Exchange):
|
|||||||
"""
|
"""
|
||||||
# Bybit does not provide "applied" funding fees per position.
|
# Bybit does not provide "applied" funding fees per position.
|
||||||
if self.trading_mode == TradingMode.FUTURES:
|
if self.trading_mode == TradingMode.FUTURES:
|
||||||
return self._fetch_and_calculate_funding_fees(
|
try:
|
||||||
pair, amount, is_short, open_date)
|
return self._fetch_and_calculate_funding_fees(
|
||||||
|
pair, amount, is_short, open_date)
|
||||||
|
except ExchangeError:
|
||||||
|
logger.warning(f"Could not update funding fees for {pair}.")
|
||||||
return 0.0
|
return 0.0
|
||||||
|
|
||||||
def fetch_orders(self, pair: str, since: datetime, params: Optional[Dict] = None) -> List[Dict]:
|
def fetch_orders(self, pair: str, since: datetime, params: Optional[Dict] = None) -> List[Dict]:
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ MAP_EXCHANGE_CHILDCLASS = {
|
|||||||
|
|
||||||
SUPPORTED_EXCHANGES = [
|
SUPPORTED_EXCHANGES = [
|
||||||
'binance',
|
'binance',
|
||||||
'bittrex',
|
'bitmart',
|
||||||
'gate',
|
'gate',
|
||||||
'huobi',
|
'huobi',
|
||||||
'kraken',
|
'kraken',
|
||||||
|
|||||||
@@ -330,6 +330,7 @@ class Exchange:
|
|||||||
Exchange ohlcv candle limit
|
Exchange ohlcv candle limit
|
||||||
Uses ohlcv_candle_limit_per_timeframe if the exchange has different limits
|
Uses ohlcv_candle_limit_per_timeframe if the exchange has different limits
|
||||||
per timeframe (e.g. bittrex), otherwise falls back to ohlcv_candle_limit
|
per timeframe (e.g. bittrex), otherwise falls back to ohlcv_candle_limit
|
||||||
|
TODO: this is most likely no longer needed since only bittrex needed this.
|
||||||
:param timeframe: Timeframe to check
|
:param timeframe: Timeframe to check
|
||||||
:param candle_type: Candle-type
|
:param candle_type: Candle-type
|
||||||
:param since_ms: Starting timestamp
|
:param since_ms: Starting timestamp
|
||||||
@@ -486,11 +487,14 @@ class Exchange:
|
|||||||
except ccxt.BaseError:
|
except ccxt.BaseError:
|
||||||
logger.exception('Unable to initialize markets.')
|
logger.exception('Unable to initialize markets.')
|
||||||
|
|
||||||
def reload_markets(self) -> None:
|
def reload_markets(self, force: bool = False) -> None:
|
||||||
"""Reload markets both sync and async if refresh interval has passed """
|
"""Reload markets both sync and async if refresh interval has passed """
|
||||||
# Check whether markets have to be reloaded
|
# Check whether markets have to be reloaded
|
||||||
if (self._last_markets_refresh > 0) and (
|
if (
|
||||||
self._last_markets_refresh + self.markets_refresh_interval > dt_ts()):
|
not force
|
||||||
|
and self._last_markets_refresh > 0
|
||||||
|
and (self._last_markets_refresh + self.markets_refresh_interval > dt_ts())
|
||||||
|
):
|
||||||
return None
|
return None
|
||||||
logger.debug("Performing scheduled market reload..")
|
logger.debug("Performing scheduled market reload..")
|
||||||
try:
|
try:
|
||||||
@@ -1228,16 +1232,16 @@ class Exchange:
|
|||||||
return order
|
return order
|
||||||
except ccxt.InsufficientFunds as e:
|
except ccxt.InsufficientFunds as e:
|
||||||
raise InsufficientFundsError(
|
raise InsufficientFundsError(
|
||||||
f'Insufficient funds to create {ordertype} sell order on market {pair}. '
|
f'Insufficient funds to create {ordertype} {side} order on market {pair}. '
|
||||||
f'Tried to sell amount {amount} at rate {limit_rate}. '
|
f'Tried to {side} amount {amount} at rate {limit_rate} with '
|
||||||
f'Message: {e}') from e
|
f'stop-price {stop_price_norm}. Message: {e}') from e
|
||||||
except ccxt.InvalidOrder as e:
|
except (ccxt.InvalidOrder, ccxt.BadRequest) as e:
|
||||||
# Errors:
|
# Errors:
|
||||||
# `Order would trigger immediately.`
|
# `Order would trigger immediately.`
|
||||||
raise InvalidOrderException(
|
raise InvalidOrderException(
|
||||||
f'Could not create {ordertype} sell order on market {pair}. '
|
f'Could not create {ordertype} {side} order on market {pair}. '
|
||||||
f'Tried to sell amount {amount} at rate {limit_rate}. '
|
f'Tried to {side} amount {amount} at rate {limit_rate} with '
|
||||||
f'Message: {e}') from e
|
f'stop-price {stop_price_norm}. Message: {e}') from e
|
||||||
except ccxt.DDoSProtection as e:
|
except ccxt.DDoSProtection as e:
|
||||||
raise DDosProtection(e) from e
|
raise DDosProtection(e) from e
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||||
@@ -1496,8 +1500,9 @@ class Exchange:
|
|||||||
@retrier
|
@retrier
|
||||||
def fetch_bids_asks(self, symbols: Optional[List[str]] = None, cached: bool = False) -> Dict:
|
def fetch_bids_asks(self, symbols: Optional[List[str]] = None, cached: bool = False) -> Dict:
|
||||||
"""
|
"""
|
||||||
|
:param symbols: List of symbols to fetch
|
||||||
:param cached: Allow cached result
|
:param cached: Allow cached result
|
||||||
:return: fetch_tickers result
|
:return: fetch_bids_asks result
|
||||||
"""
|
"""
|
||||||
if not self.exchange_has('fetchBidsAsks'):
|
if not self.exchange_has('fetchBidsAsks'):
|
||||||
return {}
|
return {}
|
||||||
@@ -1546,6 +1551,12 @@ class Exchange:
|
|||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f'Exchange {self._api.name} does not support fetching tickers in batch. '
|
f'Exchange {self._api.name} does not support fetching tickers in batch. '
|
||||||
f'Message: {e}') from e
|
f'Message: {e}') from e
|
||||||
|
except ccxt.BadSymbol as e:
|
||||||
|
logger.warning(f"Could not load tickers due to {e.__class__.__name__}. Message: {e} ."
|
||||||
|
"Reloading markets.")
|
||||||
|
self.reload_markets(True)
|
||||||
|
# Re-raise exception to repeat the call.
|
||||||
|
raise TemporaryError from e
|
||||||
except ccxt.DDoSProtection as e:
|
except ccxt.DDoSProtection as e:
|
||||||
raise DDosProtection(e) from e
|
raise DDosProtection(e) from e
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||||
@@ -1954,7 +1965,7 @@ class Exchange:
|
|||||||
|
|
||||||
results = await asyncio.gather(*input_coro, return_exceptions=True)
|
results = await asyncio.gather(*input_coro, return_exceptions=True)
|
||||||
for res in results:
|
for res in results:
|
||||||
if isinstance(res, Exception):
|
if isinstance(res, BaseException):
|
||||||
logger.warning(f"Async code raised an exception: {repr(res)}")
|
logger.warning(f"Async code raised an exception: {repr(res)}")
|
||||||
if raise_:
|
if raise_:
|
||||||
raise
|
raise
|
||||||
@@ -2279,6 +2290,7 @@ class Exchange:
|
|||||||
|
|
||||||
from_id = t[-1][1]
|
from_id = t[-1][1]
|
||||||
else:
|
else:
|
||||||
|
logger.debug("Stopping as no more trades were returned.")
|
||||||
break
|
break
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
logger.debug("Async operation Interrupted, breaking trades DL loop.")
|
logger.debug("Async operation Interrupted, breaking trades DL loop.")
|
||||||
@@ -2304,6 +2316,11 @@ class Exchange:
|
|||||||
try:
|
try:
|
||||||
t = await self._async_fetch_trades(pair, since=since)
|
t = await self._async_fetch_trades(pair, since=since)
|
||||||
if t:
|
if t:
|
||||||
|
# No more trades to download available at the exchange,
|
||||||
|
# So we repeatedly get the same trade over and over again.
|
||||||
|
if since == t[-1][0] and len(t) == 1:
|
||||||
|
logger.debug("Stopping because no more trades are available.")
|
||||||
|
break
|
||||||
since = t[-1][0]
|
since = t[-1][0]
|
||||||
trades.extend(t)
|
trades.extend(t)
|
||||||
# Reached the end of the defined-download period
|
# Reached the end of the defined-download period
|
||||||
@@ -2312,6 +2329,7 @@ class Exchange:
|
|||||||
f"Stopping because until was reached. {t[-1][0]} > {until}")
|
f"Stopping because until was reached. {t[-1][0]} > {until}")
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
|
logger.debug("Stopping as no more trades were returned.")
|
||||||
break
|
break
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
logger.debug("Async operation Interrupted, breaking trades DL loop.")
|
logger.debug("Async operation Interrupted, breaking trades DL loop.")
|
||||||
@@ -2653,12 +2671,14 @@ class Exchange:
|
|||||||
"""
|
"""
|
||||||
return 0.0
|
return 0.0
|
||||||
|
|
||||||
def funding_fee_cutoff(self, open_date: datetime):
|
def funding_fee_cutoff(self, open_date: datetime) -> bool:
|
||||||
"""
|
"""
|
||||||
|
Funding fees are only charged at full hours (usually every 4-8h).
|
||||||
|
Therefore a trade opening at 10:00:01 will not be charged a funding fee until the next hour.
|
||||||
:param open_date: The open date for a trade
|
:param open_date: The open date for a trade
|
||||||
:return: The cutoff open time for when a funding fee is charged
|
:return: True if the date falls on a full hour, False otherwise
|
||||||
"""
|
"""
|
||||||
return open_date.minute > 0 or open_date.second > 0
|
return open_date.minute == 0 and open_date.second == 0
|
||||||
|
|
||||||
@retrier
|
@retrier
|
||||||
def set_margin_mode(self, pair: str, margin_mode: MarginMode, accept_fail: bool = False,
|
def set_margin_mode(self, pair: str, margin_mode: MarginMode, accept_fail: bool = False,
|
||||||
@@ -2706,15 +2726,16 @@ class Exchange:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
if self.funding_fee_cutoff(open_date):
|
if self.funding_fee_cutoff(open_date):
|
||||||
open_date += timedelta(hours=1)
|
# Shift back to 1h candle to avoid missing funding fees
|
||||||
|
# Only really relevant for trades very close to the full hour
|
||||||
|
open_date = timeframe_to_prev_date('1h', open_date)
|
||||||
timeframe = self._ft_has['mark_ohlcv_timeframe']
|
timeframe = self._ft_has['mark_ohlcv_timeframe']
|
||||||
timeframe_ff = self._ft_has.get('funding_fee_timeframe',
|
timeframe_ff = self._ft_has.get('funding_fee_timeframe',
|
||||||
self._ft_has['mark_ohlcv_timeframe'])
|
self._ft_has['mark_ohlcv_timeframe'])
|
||||||
|
|
||||||
if not close_date:
|
if not close_date:
|
||||||
close_date = datetime.now(timezone.utc)
|
close_date = datetime.now(timezone.utc)
|
||||||
open_timestamp = int(timeframe_to_prev_date(timeframe, open_date).timestamp()) * 1000
|
since_ms = int(timeframe_to_prev_date(timeframe, open_date).timestamp()) * 1000
|
||||||
# close_timestamp = int(close_date.timestamp()) * 1000
|
|
||||||
|
|
||||||
mark_comb: PairWithTimeframe = (
|
mark_comb: PairWithTimeframe = (
|
||||||
pair, timeframe, CandleType.from_string(self._ft_has["mark_ohlcv_price"]))
|
pair, timeframe, CandleType.from_string(self._ft_has["mark_ohlcv_price"]))
|
||||||
@@ -2722,7 +2743,7 @@ class Exchange:
|
|||||||
funding_comb: PairWithTimeframe = (pair, timeframe_ff, CandleType.FUNDING_RATE)
|
funding_comb: PairWithTimeframe = (pair, timeframe_ff, CandleType.FUNDING_RATE)
|
||||||
candle_histories = self.refresh_latest_ohlcv(
|
candle_histories = self.refresh_latest_ohlcv(
|
||||||
[mark_comb, funding_comb],
|
[mark_comb, funding_comb],
|
||||||
since_ms=open_timestamp,
|
since_ms=since_ms,
|
||||||
cache=False,
|
cache=False,
|
||||||
drop_incomplete=False,
|
drop_incomplete=False,
|
||||||
)
|
)
|
||||||
@@ -2733,8 +2754,7 @@ class Exchange:
|
|||||||
except KeyError:
|
except KeyError:
|
||||||
raise ExchangeError("Could not find funding rates.") from None
|
raise ExchangeError("Could not find funding rates.") from None
|
||||||
|
|
||||||
funding_mark_rates = self.combine_funding_and_mark(
|
funding_mark_rates = self.combine_funding_and_mark(funding_rates, mark_rates)
|
||||||
funding_rates=funding_rates, mark_rates=mark_rates)
|
|
||||||
|
|
||||||
return self.calculate_funding_fees(
|
return self.calculate_funding_fees(
|
||||||
funding_mark_rates,
|
funding_mark_rates,
|
||||||
@@ -2781,7 +2801,7 @@ class Exchange:
|
|||||||
amount: float,
|
amount: float,
|
||||||
is_short: bool,
|
is_short: bool,
|
||||||
open_date: datetime,
|
open_date: datetime,
|
||||||
close_date: Optional[datetime] = None,
|
close_date: datetime,
|
||||||
time_in_ratio: Optional[float] = None
|
time_in_ratio: Optional[float] = None
|
||||||
) -> float:
|
) -> float:
|
||||||
"""
|
"""
|
||||||
@@ -2797,8 +2817,8 @@ class Exchange:
|
|||||||
fees: float = 0
|
fees: float = 0
|
||||||
|
|
||||||
if not df.empty:
|
if not df.empty:
|
||||||
df = df[(df['date'] >= open_date) & (df['date'] <= close_date)]
|
df1 = df[(df['date'] >= open_date) & (df['date'] <= close_date)]
|
||||||
fees = sum(df['open_fund'] * df['open_mark'] * amount)
|
fees = sum(df1['open_fund'] * df1['open_mark'] * amount)
|
||||||
|
|
||||||
# Negate fees for longs as funding_fees expects it this way based on live endpoints.
|
# Negate fees for longs as funding_fees expects it this way based on live endpoints.
|
||||||
return fees if is_short else -fees
|
return fees if is_short else -fees
|
||||||
@@ -2813,17 +2833,19 @@ class Exchange:
|
|||||||
:param amount: Trade amount
|
:param amount: Trade amount
|
||||||
:param open_date: Open date of the trade
|
:param open_date: Open date of the trade
|
||||||
:return: funding fee since open_date
|
:return: funding fee since open_date
|
||||||
:raises: ExchangeError if something goes wrong.
|
|
||||||
"""
|
"""
|
||||||
if self.trading_mode == TradingMode.FUTURES:
|
if self.trading_mode == TradingMode.FUTURES:
|
||||||
if self._config['dry_run']:
|
try:
|
||||||
funding_fees = self._fetch_and_calculate_funding_fees(
|
if self._config['dry_run']:
|
||||||
pair, amount, is_short, open_date)
|
funding_fees = self._fetch_and_calculate_funding_fees(
|
||||||
else:
|
pair, amount, is_short, open_date)
|
||||||
funding_fees = self._get_funding_fees_from_exchange(pair, open_date)
|
else:
|
||||||
return funding_fees
|
funding_fees = self._get_funding_fees_from_exchange(pair, open_date)
|
||||||
else:
|
return funding_fees
|
||||||
return 0.0
|
except ExchangeError:
|
||||||
|
logger.warning(f"Could not update funding fees for {pair}.")
|
||||||
|
|
||||||
|
return 0.0
|
||||||
|
|
||||||
def get_liquidation_price(
|
def get_liquidation_price(
|
||||||
self,
|
self,
|
||||||
|
|||||||
@@ -195,7 +195,7 @@ class Kraken(Exchange):
|
|||||||
amount: float,
|
amount: float,
|
||||||
is_short: bool,
|
is_short: bool,
|
||||||
open_date: datetime,
|
open_date: datetime,
|
||||||
close_date: Optional[datetime] = None,
|
close_date: datetime,
|
||||||
time_in_ratio: Optional[float] = None
|
time_in_ratio: Optional[float] = None
|
||||||
) -> float:
|
) -> float:
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -159,7 +159,7 @@ class BaseEnvironment(gym.Env):
|
|||||||
function is designed for tracking incremented objects,
|
function is designed for tracking incremented objects,
|
||||||
events, actions inside the training environment.
|
events, actions inside the training environment.
|
||||||
For example, a user can call this to track the
|
For example, a user can call this to track the
|
||||||
frequency of occurence of an `is_valid` call in
|
frequency of occurrence of an `is_valid` call in
|
||||||
their `calculate_reward()`:
|
their `calculate_reward()`:
|
||||||
|
|
||||||
def calculate_reward(self, action: int) -> float:
|
def calculate_reward(self, action: int) -> float:
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import numpy as np
|
|||||||
import pandas as pd
|
import pandas as pd
|
||||||
import psutil
|
import psutil
|
||||||
import rapidjson
|
import rapidjson
|
||||||
from joblib import dump, load
|
|
||||||
from joblib.externals import cloudpickle
|
from joblib.externals import cloudpickle
|
||||||
from numpy.typing import NDArray
|
from numpy.typing import NDArray
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
@@ -285,6 +284,10 @@ class FreqaiDataDrawer:
|
|||||||
new_pred["date_pred"] = dataframe["date"]
|
new_pred["date_pred"] = dataframe["date"]
|
||||||
hist_preds = self.historic_predictions[pair].copy()
|
hist_preds = self.historic_predictions[pair].copy()
|
||||||
|
|
||||||
|
# ensure both dataframes have the same date format so they can be merged
|
||||||
|
new_pred["date_pred"] = pd.to_datetime(new_pred["date_pred"])
|
||||||
|
hist_preds["date_pred"] = pd.to_datetime(hist_preds["date_pred"])
|
||||||
|
|
||||||
# find the closest common date between new_pred and historic predictions
|
# find the closest common date between new_pred and historic predictions
|
||||||
# and cut off the new_pred dataframe at that date
|
# and cut off the new_pred dataframe at that date
|
||||||
common_dates = pd.merge(new_pred, hist_preds, on="date_pred", how="inner")
|
common_dates = pd.merge(new_pred, hist_preds, on="date_pred", how="inner")
|
||||||
@@ -295,9 +298,10 @@ class FreqaiDataDrawer:
|
|||||||
"predictions. You likely left your FreqAI instance offline "
|
"predictions. You likely left your FreqAI instance offline "
|
||||||
f"for more than {len(dataframe.index)} candles.")
|
f"for more than {len(dataframe.index)} candles.")
|
||||||
|
|
||||||
df_concat = pd.concat([hist_preds, new_pred], ignore_index=True, keys=hist_preds.keys())
|
# reindex new_pred columns to match the historic predictions dataframe
|
||||||
# remove last row because we will append that later in append_model_predictions()
|
new_pred_reindexed = new_pred.reindex(columns=hist_preds.columns)
|
||||||
df_concat = df_concat.iloc[:-1]
|
df_concat = pd.concat([hist_preds, new_pred_reindexed], ignore_index=True)
|
||||||
|
|
||||||
# any missing values will get zeroed out so users can see the exact
|
# any missing values will get zeroed out so users can see the exact
|
||||||
# downtime in FreqUI
|
# downtime in FreqUI
|
||||||
df_concat = df_concat.fillna(0)
|
df_concat = df_concat.fillna(0)
|
||||||
@@ -319,9 +323,9 @@ class FreqaiDataDrawer:
|
|||||||
index = self.historic_predictions[pair].index[-1:]
|
index = self.historic_predictions[pair].index[-1:]
|
||||||
columns = self.historic_predictions[pair].columns
|
columns = self.historic_predictions[pair].columns
|
||||||
|
|
||||||
nan_df = pd.DataFrame(np.nan, index=index, columns=columns)
|
zeros_df = pd.DataFrame(np.zeros((1, len(columns))), index=index, columns=columns)
|
||||||
self.historic_predictions[pair] = pd.concat(
|
self.historic_predictions[pair] = pd.concat(
|
||||||
[self.historic_predictions[pair], nan_df], ignore_index=True, axis=0)
|
[self.historic_predictions[pair], zeros_df], ignore_index=True, axis=0)
|
||||||
df = self.historic_predictions[pair]
|
df = self.historic_predictions[pair]
|
||||||
|
|
||||||
# model outputs and associated statistics
|
# model outputs and associated statistics
|
||||||
@@ -472,7 +476,8 @@ class FreqaiDataDrawer:
|
|||||||
|
|
||||||
# Save the trained model
|
# Save the trained model
|
||||||
if self.model_type == 'joblib':
|
if self.model_type == 'joblib':
|
||||||
dump(model, save_path / f"{dk.model_filename}_model.joblib")
|
with (save_path / f"{dk.model_filename}_model.joblib").open("wb") as fp:
|
||||||
|
cloudpickle.dump(model, fp)
|
||||||
elif self.model_type == 'keras':
|
elif self.model_type == 'keras':
|
||||||
model.save(save_path / f"{dk.model_filename}_model.h5")
|
model.save(save_path / f"{dk.model_filename}_model.h5")
|
||||||
elif self.model_type in ["stable_baselines3", "sb3_contrib", "pytorch"]:
|
elif self.model_type in ["stable_baselines3", "sb3_contrib", "pytorch"]:
|
||||||
@@ -559,7 +564,8 @@ class FreqaiDataDrawer:
|
|||||||
if dk.live and coin in self.model_dictionary:
|
if dk.live and coin in self.model_dictionary:
|
||||||
model = self.model_dictionary[coin]
|
model = self.model_dictionary[coin]
|
||||||
elif self.model_type == 'joblib':
|
elif self.model_type == 'joblib':
|
||||||
model = load(dk.data_path / f"{dk.model_filename}_model.joblib")
|
with (dk.data_path / f"{dk.model_filename}_model.joblib").open("rb") as fp:
|
||||||
|
model = cloudpickle.load(fp)
|
||||||
elif 'stable_baselines' in self.model_type or 'sb3_contrib' == self.model_type:
|
elif 'stable_baselines' in self.model_type or 'sb3_contrib' == self.model_type:
|
||||||
mod = importlib.import_module(
|
mod = importlib.import_module(
|
||||||
self.model_type, self.freqai_info['rl_config']['model_type'])
|
self.model_type, self.freqai_info['rl_config']['model_type'])
|
||||||
|
|||||||
@@ -244,7 +244,7 @@ class FreqaiDataKitchen:
|
|||||||
f"{self.pair}: dropped {len(unfiltered_df) - len(filtered_df)} training points"
|
f"{self.pair}: dropped {len(unfiltered_df) - len(filtered_df)} training points"
|
||||||
f" due to NaNs in populated dataset {len(unfiltered_df)}."
|
f" due to NaNs in populated dataset {len(unfiltered_df)}."
|
||||||
)
|
)
|
||||||
if len(unfiltered_df) == 0 and not self.live:
|
if len(filtered_df) == 0 and not self.live:
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f"{self.pair}: all training data dropped due to NaNs. "
|
f"{self.pair}: all training data dropped due to NaNs. "
|
||||||
"You likely did not download enough training data prior "
|
"You likely did not download enough training data prior "
|
||||||
|
|||||||
@@ -27,6 +27,12 @@ class PyTorchTransformerRegressor(BasePyTorchRegressor):
|
|||||||
...
|
...
|
||||||
"freqai": {
|
"freqai": {
|
||||||
...
|
...
|
||||||
|
"conv_width": 30, // PyTorchTransformer is based on windowing
|
||||||
|
"feature_parameters": {
|
||||||
|
...
|
||||||
|
"include_shifted_candles": 0, // which removes the need for shifted candles
|
||||||
|
...
|
||||||
|
},
|
||||||
"model_training_parameters" : {
|
"model_training_parameters" : {
|
||||||
"learning_rate": 3e-4,
|
"learning_rate": 3e-4,
|
||||||
"trainer_kwargs": {
|
"trainer_kwargs": {
|
||||||
@@ -120,16 +126,16 @@ class PyTorchTransformerRegressor(BasePyTorchRegressor):
|
|||||||
# create empty torch tensor
|
# create empty torch tensor
|
||||||
self.model.model.eval()
|
self.model.model.eval()
|
||||||
yb = torch.empty(0).to(self.device)
|
yb = torch.empty(0).to(self.device)
|
||||||
if x.shape[1] > 1:
|
if x.shape[1] > self.window_size:
|
||||||
ws = self.window_size
|
ws = self.window_size
|
||||||
for i in range(0, x.shape[1] - ws):
|
for i in range(0, x.shape[1] - ws):
|
||||||
xb = x[:, i:i + ws, :].to(self.device)
|
xb = x[:, i:i + ws, :].to(self.device)
|
||||||
y = self.model.model(xb)
|
y = self.model.model(xb)
|
||||||
yb = torch.cat((yb, y), dim=0)
|
yb = torch.cat((yb, y), dim=1)
|
||||||
else:
|
else:
|
||||||
yb = self.model.model(x)
|
yb = self.model.model(x)
|
||||||
|
|
||||||
yb = yb.cpu().squeeze()
|
yb = yb.cpu().squeeze(0)
|
||||||
pred_df = pd.DataFrame(yb.detach().numpy(), columns=dk.label_list)
|
pred_df = pd.DataFrame(yb.detach().numpy(), columns=dk.label_list)
|
||||||
pred_df, _, _ = dk.label_pipeline.inverse_transform(pred_df)
|
pred_df, _, _ = dk.label_pipeline.inverse_transform(pred_df)
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import logging
|
import logging
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, Type
|
from typing import Any, Dict, List, Optional, Type
|
||||||
|
|
||||||
import torch as th
|
import torch as th
|
||||||
|
from stable_baselines3.common.callbacks import ProgressBarCallback
|
||||||
|
|
||||||
from freqtrade.freqai.data_kitchen import FreqaiDataKitchen
|
from freqtrade.freqai.data_kitchen import FreqaiDataKitchen
|
||||||
from freqtrade.freqai.RL.Base5ActionRLEnv import Actions, Base5ActionRLEnv, Positions
|
from freqtrade.freqai.RL.Base5ActionRLEnv import Actions, Base5ActionRLEnv, Positions
|
||||||
@@ -73,19 +74,27 @@ class ReinforcementLearner(BaseReinforcementLearningModel):
|
|||||||
'trained agent.')
|
'trained agent.')
|
||||||
model = self.dd.model_dictionary[dk.pair]
|
model = self.dd.model_dictionary[dk.pair]
|
||||||
model.set_env(self.train_env)
|
model.set_env(self.train_env)
|
||||||
|
callbacks: List[Any] = [self.eval_callback, self.tensorboard_callback]
|
||||||
|
progressbar_callback: Optional[ProgressBarCallback] = None
|
||||||
|
if self.rl_config.get('progress_bar', False):
|
||||||
|
progressbar_callback = ProgressBarCallback()
|
||||||
|
callbacks.insert(0, progressbar_callback)
|
||||||
|
|
||||||
model.learn(
|
try:
|
||||||
total_timesteps=int(total_timesteps),
|
model.learn(
|
||||||
callback=[self.eval_callback, self.tensorboard_callback],
|
total_timesteps=int(total_timesteps),
|
||||||
progress_bar=self.rl_config.get('progress_bar', False)
|
callback=callbacks,
|
||||||
)
|
)
|
||||||
|
finally:
|
||||||
|
if progressbar_callback:
|
||||||
|
progressbar_callback.on_training_end()
|
||||||
|
|
||||||
if Path(dk.data_path / "best_model.zip").is_file():
|
if Path(dk.data_path / "best_model.zip").is_file():
|
||||||
logger.info('Callback found a best model.')
|
logger.info('Callback found a best model.')
|
||||||
best_model = self.MODELCLASS.load(dk.data_path / "best_model")
|
best_model = self.MODELCLASS.load(dk.data_path / "best_model")
|
||||||
return best_model
|
return best_model
|
||||||
|
|
||||||
logger.info('Couldnt find best model, using final model instead.')
|
logger.info("Couldn't find best model, using final model instead.")
|
||||||
|
|
||||||
return model
|
return model
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import logging
|
||||||
|
from typing import Any, Dict, Tuple
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import numpy.typing as npt
|
||||||
|
from pandas import DataFrame
|
||||||
|
from sklearn.ensemble import RandomForestClassifier
|
||||||
|
from sklearn.preprocessing import LabelEncoder
|
||||||
|
|
||||||
|
from freqtrade.freqai.base_models.BaseClassifierModel import BaseClassifierModel
|
||||||
|
from freqtrade.freqai.data_kitchen import FreqaiDataKitchen
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class SKLearnRandomForestClassifier(BaseClassifierModel):
|
||||||
|
"""
|
||||||
|
User created prediction model. The class inherits IFreqaiModel, which
|
||||||
|
means it has full access to all Frequency AI functionality. Typically,
|
||||||
|
users would use this to override the common `fit()`, `train()`, or
|
||||||
|
`predict()` methods to add their custom data handling tools or change
|
||||||
|
various aspects of the training that cannot be configured via the
|
||||||
|
top level config.json file.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def fit(self, data_dictionary: Dict, dk: FreqaiDataKitchen, **kwargs) -> Any:
|
||||||
|
"""
|
||||||
|
User sets up the training and test data to fit their desired model here
|
||||||
|
:param data_dictionary: the dictionary holding all data for train, test,
|
||||||
|
labels, weights
|
||||||
|
:param dk: The datakitchen object for the current coin/model
|
||||||
|
"""
|
||||||
|
|
||||||
|
X = data_dictionary["train_features"].to_numpy()
|
||||||
|
y = data_dictionary["train_labels"].to_numpy()[:, 0]
|
||||||
|
|
||||||
|
if self.freqai_info.get('data_split_parameters', {}).get('test_size', 0.1) == 0:
|
||||||
|
eval_set = None
|
||||||
|
else:
|
||||||
|
test_features = data_dictionary["test_features"].to_numpy()
|
||||||
|
test_labels = data_dictionary["test_labels"].to_numpy()[:, 0]
|
||||||
|
|
||||||
|
eval_set = (test_features, test_labels)
|
||||||
|
|
||||||
|
if self.freqai_info.get("continual_learning", False):
|
||||||
|
logger.warning("Continual learning is not supported for "
|
||||||
|
"SKLearnRandomForestClassifier, ignoring.")
|
||||||
|
|
||||||
|
train_weights = data_dictionary["train_weights"]
|
||||||
|
|
||||||
|
model = RandomForestClassifier(**self.model_training_parameters)
|
||||||
|
|
||||||
|
model.fit(X=X, y=y, sample_weight=train_weights)
|
||||||
|
if eval_set:
|
||||||
|
logger.info("Score: %s", model.score(eval_set[0], eval_set[1]))
|
||||||
|
|
||||||
|
return model
|
||||||
|
|
||||||
|
def predict(
|
||||||
|
self, unfiltered_df: DataFrame, dk: FreqaiDataKitchen, **kwargs
|
||||||
|
) -> Tuple[DataFrame, npt.NDArray[np.int_]]:
|
||||||
|
"""
|
||||||
|
Filter the prediction features data and predict with it.
|
||||||
|
:param unfiltered_df: Full dataframe for the current backtest period.
|
||||||
|
:return:
|
||||||
|
:pred_df: dataframe containing the predictions
|
||||||
|
:do_predict: np.array of 1s and 0s to indicate places where freqai needed to remove
|
||||||
|
data (NaNs) or felt uncertain about data (PCA and DI index)
|
||||||
|
"""
|
||||||
|
|
||||||
|
(pred_df, dk.do_predict) = super().predict(unfiltered_df, dk, **kwargs)
|
||||||
|
|
||||||
|
le = LabelEncoder()
|
||||||
|
label = dk.label_list[0]
|
||||||
|
labels_before = list(dk.data['labels_std'].keys())
|
||||||
|
labels_after = le.fit_transform(labels_before).tolist()
|
||||||
|
pred_df[label] = le.inverse_transform(pred_df[label])
|
||||||
|
pred_df = pred_df.rename(
|
||||||
|
columns={labels_after[i]: labels_before[i] for i in range(len(labels_before))})
|
||||||
|
|
||||||
|
return (pred_df, dk.do_predict)
|
||||||
@@ -45,7 +45,7 @@ class XGBoostRFRegressor(BaseRegressionModel):
|
|||||||
|
|
||||||
model = XGBRFRegressor(**self.model_training_parameters)
|
model = XGBRFRegressor(**self.model_training_parameters)
|
||||||
|
|
||||||
model.set_params(callbacks=[TBCallback(dk.data_path)], activate=self.activate_tensorboard)
|
model.set_params(callbacks=[TBCallback(dk.data_path)])
|
||||||
model.fit(X=X, y=y, sample_weight=sample_weight, eval_set=eval_set,
|
model.fit(X=X, y=y, sample_weight=sample_weight, eval_set=eval_set,
|
||||||
sample_weight_eval_set=eval_weights, xgb_model=xgb_model)
|
sample_weight_eval_set=eval_weights, xgb_model=xgb_model)
|
||||||
# set the callbacks to empty so that we can serialize to disk later
|
# set the callbacks to empty so that we can serialize to disk later
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ class XGBoostRegressor(BaseRegressionModel):
|
|||||||
|
|
||||||
model = XGBRegressor(**self.model_training_parameters)
|
model = XGBRegressor(**self.model_training_parameters)
|
||||||
|
|
||||||
model.set_params(callbacks=[TBCallback(dk.data_path)], activate=self.activate_tensorboard)
|
model.set_params(callbacks=[TBCallback(dk.data_path)])
|
||||||
model.fit(X=X, y=y, sample_weight=sample_weight, eval_set=eval_set,
|
model.fit(X=X, y=y, sample_weight=sample_weight, eval_set=eval_set,
|
||||||
sample_weight_eval_set=eval_weights, xgb_model=xgb_model)
|
sample_weight_eval_set=eval_weights, xgb_model=xgb_model)
|
||||||
# set the callbacks to empty so that we can serialize to disk later
|
# set the callbacks to empty so that we can serialize to disk later
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ from typing import Any, Dict, Type, Union
|
|||||||
|
|
||||||
from stable_baselines3.common.callbacks import BaseCallback
|
from stable_baselines3.common.callbacks import BaseCallback
|
||||||
from stable_baselines3.common.logger import HParam
|
from stable_baselines3.common.logger import HParam
|
||||||
from stable_baselines3.common.vec_env import VecEnv
|
|
||||||
|
|
||||||
from freqtrade.freqai.RL.BaseEnvironment import BaseActions
|
from freqtrade.freqai.RL.BaseEnvironment import BaseActions
|
||||||
|
|
||||||
@@ -13,13 +12,9 @@ class TensorboardCallback(BaseCallback):
|
|||||||
Custom callback for plotting additional values in tensorboard and
|
Custom callback for plotting additional values in tensorboard and
|
||||||
episodic summary reports.
|
episodic summary reports.
|
||||||
"""
|
"""
|
||||||
# Override training_env type to fix type errors
|
|
||||||
training_env: Union[VecEnv, None] = None
|
|
||||||
|
|
||||||
def __init__(self, verbose=1, actions: Type[Enum] = BaseActions):
|
def __init__(self, verbose=1, actions: Type[Enum] = BaseActions):
|
||||||
super().__init__(verbose)
|
super().__init__(verbose)
|
||||||
self.model: Any = None
|
self.model: Any = None
|
||||||
self.logger: Any = None
|
|
||||||
self.actions: Type[Enum] = actions
|
self.actions: Type[Enum] = actions
|
||||||
|
|
||||||
def _on_training_start(self) -> None:
|
def _on_training_start(self) -> None:
|
||||||
@@ -47,9 +42,13 @@ class TensorboardCallback(BaseCallback):
|
|||||||
def _on_step(self) -> bool:
|
def _on_step(self) -> bool:
|
||||||
|
|
||||||
local_info = self.locals["infos"][0]
|
local_info = self.locals["infos"][0]
|
||||||
if self.training_env is None:
|
|
||||||
return True
|
if hasattr(self.training_env, 'envs'):
|
||||||
tensorboard_metrics = self.training_env.get_attr("tensorboard_metrics")[0]
|
tensorboard_metrics = self.training_env.envs[0].unwrapped.tensorboard_metrics
|
||||||
|
|
||||||
|
else:
|
||||||
|
# For RL-multiproc - usage of [0] might need to be evaluated
|
||||||
|
tensorboard_metrics = self.training_env.get_attr("tensorboard_metrics")[0]
|
||||||
|
|
||||||
for metric in local_info:
|
for metric in local_info:
|
||||||
if metric not in ["episode", "terminal_observation"]:
|
if metric not in ["episode", "terminal_observation"]:
|
||||||
|
|||||||
+85
-74
@@ -33,8 +33,8 @@ from freqtrade.plugins.protectionmanager import ProtectionManager
|
|||||||
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||||
from freqtrade.rpc import RPCManager
|
from freqtrade.rpc import RPCManager
|
||||||
from freqtrade.rpc.external_message_consumer import ExternalMessageConsumer
|
from freqtrade.rpc.external_message_consumer import ExternalMessageConsumer
|
||||||
from freqtrade.rpc.rpc_types import (RPCBuyMsg, RPCCancelMsg, RPCProtectionMsg, RPCSellCancelMsg,
|
from freqtrade.rpc.rpc_types import (ProfitLossStr, RPCCancelMsg, RPCEntryMsg, RPCExitCancelMsg,
|
||||||
RPCSellMsg)
|
RPCExitMsg, RPCProtectionMsg)
|
||||||
from freqtrade.strategy.interface import IStrategy
|
from freqtrade.strategy.interface import IStrategy
|
||||||
from freqtrade.strategy.strategy_wrapper import strategy_safe_wrapper
|
from freqtrade.strategy.strategy_wrapper import strategy_safe_wrapper
|
||||||
from freqtrade.util import FtPrecise
|
from freqtrade.util import FtPrecise
|
||||||
@@ -132,7 +132,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
# TODO: This would be more efficient if scheduled in utc time, and performed at each
|
# TODO: This would be more efficient if scheduled in utc time, and performed at each
|
||||||
# TODO: funding interval, specified by funding_fee_times on the exchange classes
|
# TODO: funding interval, specified by funding_fee_times on the exchange classes
|
||||||
for time_slot in range(0, 24):
|
for time_slot in range(0, 24):
|
||||||
for minutes in [0, 15, 30, 45]:
|
for minutes in [1, 31]:
|
||||||
t = str(time(time_slot, minutes, 2))
|
t = str(time(time_slot, minutes, 2))
|
||||||
self._schedule.every().day.at(t).do(update)
|
self._schedule.every().day.at(t).do(update)
|
||||||
self.last_process: Optional[datetime] = None
|
self.last_process: Optional[datetime] = None
|
||||||
@@ -199,6 +199,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
# Only update open orders on startup
|
# Only update open orders on startup
|
||||||
# This will update the database after the initial migration
|
# This will update the database after the initial migration
|
||||||
self.startup_update_open_orders()
|
self.startup_update_open_orders()
|
||||||
|
self.update_funding_fees()
|
||||||
|
|
||||||
def process(self) -> None:
|
def process(self) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -312,22 +313,19 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
open_trades = Trade.get_open_trade_count()
|
open_trades = Trade.get_open_trade_count()
|
||||||
return max(0, self.config['max_open_trades'] - open_trades)
|
return max(0, self.config['max_open_trades'] - open_trades)
|
||||||
|
|
||||||
def update_funding_fees(self):
|
def update_funding_fees(self) -> None:
|
||||||
if self.trading_mode == TradingMode.FUTURES:
|
if self.trading_mode == TradingMode.FUTURES:
|
||||||
trades = Trade.get_open_trades()
|
trades: List[Trade] = Trade.get_open_trades()
|
||||||
try:
|
for trade in trades:
|
||||||
for trade in trades:
|
trade.set_funding_fees(
|
||||||
funding_fees = self.exchange.get_funding_fees(
|
self.exchange.get_funding_fees(
|
||||||
pair=trade.pair,
|
pair=trade.pair,
|
||||||
amount=trade.amount,
|
amount=trade.amount,
|
||||||
is_short=trade.is_short,
|
is_short=trade.is_short,
|
||||||
open_date=trade.date_last_filled_utc
|
open_date=trade.date_last_filled_utc)
|
||||||
)
|
)
|
||||||
trade.funding_fees = funding_fees
|
|
||||||
except ExchangeError:
|
|
||||||
logger.warning("Could not update funding fees for open trades.")
|
|
||||||
|
|
||||||
def startup_backpopulate_precision(self):
|
def startup_backpopulate_precision(self) -> None:
|
||||||
|
|
||||||
trades = Trade.get_trades([Trade.contract_size.is_(None)])
|
trades = Trade.get_trades([Trade.contract_size.is_(None)])
|
||||||
for trade in trades:
|
for trade in trades:
|
||||||
@@ -374,17 +372,13 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
fo = order.to_ccxt_object()
|
fo = order.to_ccxt_object()
|
||||||
fo['status'] = 'canceled'
|
fo['status'] = 'canceled'
|
||||||
self.handle_cancel_order(
|
self.handle_cancel_order(
|
||||||
fo, order.order_id, order.trade,
|
fo, order, order.trade, constants.CANCEL_REASON['TIMEOUT']
|
||||||
constants.CANCEL_REASON['TIMEOUT']
|
|
||||||
)
|
)
|
||||||
|
|
||||||
except ExchangeError as e:
|
except ExchangeError as e:
|
||||||
|
|
||||||
logger.warning(f"Error updating Order {order.order_id} due to {e}")
|
logger.warning(f"Error updating Order {order.order_id} due to {e}")
|
||||||
|
|
||||||
if self.trading_mode == TradingMode.FUTURES:
|
|
||||||
self._schedule.run_pending()
|
|
||||||
|
|
||||||
def update_trades_without_assigned_fees(self) -> None:
|
def update_trades_without_assigned_fees(self) -> None:
|
||||||
"""
|
"""
|
||||||
Update closed trades without close fees assigned.
|
Update closed trades without close fees assigned.
|
||||||
@@ -586,7 +580,8 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
else:
|
else:
|
||||||
self.log_once(f"Pair {pair} is currently locked.", logger.info)
|
self.log_once(f"Pair {pair} is currently locked.", logger.info)
|
||||||
return False
|
return False
|
||||||
stake_amount = self.wallets.get_trade_stake_amount(pair, self.edge)
|
stake_amount = self.wallets.get_trade_stake_amount(
|
||||||
|
pair, self.config['max_open_trades'], self.edge)
|
||||||
|
|
||||||
bid_check_dom = self.config.get('entry_pricing', {}).get('check_depth_of_market', {})
|
bid_check_dom = self.config.get('entry_pricing', {}).get('check_depth_of_market', {})
|
||||||
if ((bid_check_dom.get('enabled', False)) and
|
if ((bid_check_dom.get('enabled', False)) and
|
||||||
@@ -749,6 +744,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
:param pair: pair for which we want to create a LIMIT_BUY
|
:param pair: pair for which we want to create a LIMIT_BUY
|
||||||
:param stake_amount: amount of stake-currency for the pair
|
:param stake_amount: amount of stake-currency for the pair
|
||||||
:return: True if a buy order is created, false if it fails.
|
:return: True if a buy order is created, false if it fails.
|
||||||
|
:raise: DependencyException or it's subclasses like ExchangeError.
|
||||||
"""
|
"""
|
||||||
time_in_force = self.strategy.order_time_in_force['entry']
|
time_in_force = self.strategy.order_time_in_force['entry']
|
||||||
|
|
||||||
@@ -835,14 +831,15 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
base_currency = self.exchange.get_pair_base_currency(pair)
|
base_currency = self.exchange.get_pair_base_currency(pair)
|
||||||
open_date = datetime.now(timezone.utc)
|
open_date = datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
funding_fees = self.exchange.get_funding_fees(
|
||||||
|
pair=pair,
|
||||||
|
amount=amount + trade.amount if trade else amount,
|
||||||
|
is_short=is_short,
|
||||||
|
open_date=trade.date_last_filled_utc if trade else open_date
|
||||||
|
)
|
||||||
|
|
||||||
# This is a new trade
|
# This is a new trade
|
||||||
if trade is None:
|
if trade is None:
|
||||||
funding_fees = 0.0
|
|
||||||
try:
|
|
||||||
funding_fees = self.exchange.get_funding_fees(
|
|
||||||
pair=pair, amount=amount, is_short=is_short, open_date=open_date)
|
|
||||||
except ExchangeError:
|
|
||||||
logger.warning("Could not find funding fee.")
|
|
||||||
|
|
||||||
trade = Trade(
|
trade = Trade(
|
||||||
pair=pair,
|
pair=pair,
|
||||||
@@ -878,6 +875,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
trade.is_open = True
|
trade.is_open = True
|
||||||
trade.fee_open_currency = None
|
trade.fee_open_currency = None
|
||||||
trade.open_rate_requested = enter_limit_requested
|
trade.open_rate_requested = enter_limit_requested
|
||||||
|
trade.set_funding_fees(funding_fees)
|
||||||
|
|
||||||
trade.orders.append(order_obj)
|
trade.orders.append(order_obj)
|
||||||
trade.recalc_trade_from_orders()
|
trade.recalc_trade_from_orders()
|
||||||
@@ -906,7 +904,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
# First cancelling stoploss on exchange ...
|
# First cancelling stoploss on exchange ...
|
||||||
if trade.stoploss_order_id:
|
if trade.stoploss_order_id:
|
||||||
try:
|
try:
|
||||||
logger.info(f"Canceling stoploss on exchange for {trade}")
|
logger.info(f"Cancelling stoploss on exchange for {trade}")
|
||||||
co = self.exchange.cancel_stoploss_order_with_result(
|
co = self.exchange.cancel_stoploss_order_with_result(
|
||||||
trade.stoploss_order_id, trade.pair, trade.amount)
|
trade.stoploss_order_id, trade.pair, trade.amount)
|
||||||
self.update_trade_state(trade, trade.stoploss_order_id, co, stoploss_order=True)
|
self.update_trade_state(trade, trade.stoploss_order_id, co, stoploss_order=True)
|
||||||
@@ -1017,7 +1015,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
current_rate = self.exchange.get_rate(
|
current_rate = self.exchange.get_rate(
|
||||||
trade.pair, side='entry', is_short=trade.is_short, refresh=False)
|
trade.pair, side='entry', is_short=trade.is_short, refresh=False)
|
||||||
|
|
||||||
msg: RPCBuyMsg = {
|
msg: RPCEntryMsg = {
|
||||||
'trade_id': trade.id,
|
'trade_id': trade.id,
|
||||||
'type': RPCMessageType.ENTRY_FILL if fill else RPCMessageType.ENTRY,
|
'type': RPCMessageType.ENTRY_FILL if fill else RPCMessageType.ENTRY,
|
||||||
'buy_tag': trade.enter_tag,
|
'buy_tag': trade.enter_tag,
|
||||||
@@ -1087,7 +1085,11 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
trades_closed = 0
|
trades_closed = 0
|
||||||
for trade in trades:
|
for trade in trades:
|
||||||
|
|
||||||
if not trade.has_open_orders and not self.wallets.check_exit_amount(trade):
|
if (
|
||||||
|
not trade.has_open_orders
|
||||||
|
and not trade.stoploss_order_id
|
||||||
|
and not self.wallets.check_exit_amount(trade)
|
||||||
|
):
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f'Not enough {trade.safe_base_currency} in wallet to exit {trade}. '
|
f'Not enough {trade.safe_base_currency} in wallet to exit {trade}. '
|
||||||
'Trying to recover.')
|
'Trying to recover.')
|
||||||
@@ -1331,6 +1333,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
for trade in Trade.get_open_trades():
|
for trade in Trade.get_open_trades():
|
||||||
|
open_order: Order
|
||||||
for open_order in trade.open_orders:
|
for open_order in trade.open_orders:
|
||||||
try:
|
try:
|
||||||
order = self.exchange.fetch_order(open_order.order_id, trade.pair)
|
order = self.exchange.fetch_order(open_order.order_id, trade.pair)
|
||||||
@@ -1351,22 +1354,23 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
)
|
)
|
||||||
):
|
):
|
||||||
self.handle_cancel_order(
|
self.handle_cancel_order(
|
||||||
order, open_order.order_id, trade, constants.CANCEL_REASON['TIMEOUT']
|
order, open_order, trade, constants.CANCEL_REASON['TIMEOUT']
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
self.replace_order(order, open_order, trade)
|
self.replace_order(order, open_order, trade)
|
||||||
|
|
||||||
def handle_cancel_order(self, order: Dict, order_id: str, trade: Trade, reason: str) -> None:
|
def handle_cancel_order(self, order: Dict, order_obj: Order, trade: Trade, reason: str) -> None:
|
||||||
"""
|
"""
|
||||||
Check if current analyzed order timed out and cancel if necessary.
|
Check if current analyzed order timed out and cancel if necessary.
|
||||||
:param order: Order dict grabbed with exchange.fetch_order()
|
:param order: Order dict grabbed with exchange.fetch_order()
|
||||||
|
:param order_obj: Order object from the database.
|
||||||
:param trade: Trade object.
|
:param trade: Trade object.
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
if order['side'] == trade.entry_side:
|
if order['side'] == trade.entry_side:
|
||||||
self.handle_cancel_enter(trade, order, order_id, reason)
|
self.handle_cancel_enter(trade, order, order_obj, reason)
|
||||||
else:
|
else:
|
||||||
canceled = self.handle_cancel_exit(trade, order, order_id, reason)
|
canceled = self.handle_cancel_exit(trade, order, order_obj, reason)
|
||||||
canceled_count = trade.get_canceled_exit_order_count()
|
canceled_count = trade.get_canceled_exit_order_count()
|
||||||
max_timeouts = self.config.get('unfilledtimeout', {}).get('exit_timeout_count', 0)
|
max_timeouts = self.config.get('unfilledtimeout', {}).get('exit_timeout_count', 0)
|
||||||
if (canceled and max_timeouts > 0 and canceled_count >= max_timeouts):
|
if (canceled and max_timeouts > 0 and canceled_count >= max_timeouts):
|
||||||
@@ -1431,7 +1435,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
trade=trade, order=order_obj, pair=trade.pair,
|
trade=trade, order=order_obj, pair=trade.pair,
|
||||||
current_time=datetime.now(timezone.utc), proposed_rate=proposed_rate,
|
current_time=datetime.now(timezone.utc), proposed_rate=proposed_rate,
|
||||||
current_order_rate=order_obj.safe_price, entry_tag=trade.enter_tag,
|
current_order_rate=order_obj.safe_price, entry_tag=trade.enter_tag,
|
||||||
side=trade.entry_side)
|
side=trade.trade_direction)
|
||||||
|
|
||||||
replacing = True
|
replacing = True
|
||||||
cancel_reason = constants.CANCEL_REASON['REPLACE']
|
cancel_reason = constants.CANCEL_REASON['REPLACE']
|
||||||
@@ -1440,7 +1444,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
cancel_reason = constants.CANCEL_REASON['USER_CANCEL']
|
cancel_reason = constants.CANCEL_REASON['USER_CANCEL']
|
||||||
if order_obj.price != adjusted_entry_price:
|
if order_obj.price != adjusted_entry_price:
|
||||||
# cancel existing order if new price is supplied or None
|
# cancel existing order if new price is supplied or None
|
||||||
res = self.handle_cancel_enter(trade, order, order_obj.order_id, cancel_reason,
|
res = self.handle_cancel_enter(trade, order, order_obj, cancel_reason,
|
||||||
replacing=replacing)
|
replacing=replacing)
|
||||||
if not res:
|
if not res:
|
||||||
self.replace_order_failed(
|
self.replace_order_failed(
|
||||||
@@ -1448,15 +1452,21 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
return
|
return
|
||||||
if adjusted_entry_price:
|
if adjusted_entry_price:
|
||||||
# place new order only if new price is supplied
|
# place new order only if new price is supplied
|
||||||
if not self.execute_entry(
|
try:
|
||||||
pair=trade.pair,
|
if not self.execute_entry(
|
||||||
stake_amount=(
|
pair=trade.pair,
|
||||||
order_obj.safe_remaining * order_obj.safe_price / trade.leverage),
|
stake_amount=(
|
||||||
price=adjusted_entry_price,
|
order_obj.safe_remaining * order_obj.safe_price / trade.leverage),
|
||||||
trade=trade,
|
price=adjusted_entry_price,
|
||||||
is_short=trade.is_short,
|
trade=trade,
|
||||||
mode='replace',
|
is_short=trade.is_short,
|
||||||
):
|
mode='replace',
|
||||||
|
):
|
||||||
|
self.replace_order_failed(
|
||||||
|
trade, f"Could not replace order for {trade}.")
|
||||||
|
except DependencyException as exception:
|
||||||
|
logger.warning(
|
||||||
|
f'Unable to replace order for {trade.pair}: {exception}')
|
||||||
self.replace_order_failed(trade, f"Could not replace order for {trade}.")
|
self.replace_order_failed(trade, f"Could not replace order for {trade}.")
|
||||||
|
|
||||||
def cancel_all_open_orders(self) -> None:
|
def cancel_all_open_orders(self) -> None:
|
||||||
@@ -1475,29 +1485,28 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
|
|
||||||
if order['side'] == trade.entry_side:
|
if order['side'] == trade.entry_side:
|
||||||
self.handle_cancel_enter(
|
self.handle_cancel_enter(
|
||||||
trade, order, open_order.order_id, constants.CANCEL_REASON['ALL_CANCELLED']
|
trade, order, open_order, constants.CANCEL_REASON['ALL_CANCELLED']
|
||||||
)
|
)
|
||||||
|
|
||||||
elif order['side'] == trade.exit_side:
|
elif order['side'] == trade.exit_side:
|
||||||
self.handle_cancel_exit(
|
self.handle_cancel_exit(
|
||||||
trade, order, open_order.order_id, constants.CANCEL_REASON['ALL_CANCELLED']
|
trade, order, open_order, constants.CANCEL_REASON['ALL_CANCELLED']
|
||||||
)
|
)
|
||||||
Trade.commit()
|
Trade.commit()
|
||||||
|
|
||||||
def handle_cancel_enter(
|
def handle_cancel_enter(
|
||||||
self, trade: Trade, order: Dict, order_id: str,
|
self, trade: Trade, order: Dict, order_obj: Order,
|
||||||
reason: str, replacing: Optional[bool] = False
|
reason: str, replacing: Optional[bool] = False
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
entry cancel - cancel order
|
entry cancel - cancel order
|
||||||
|
:param order_obj: Order object from the database.
|
||||||
:param replacing: Replacing order - prevent trade deletion.
|
:param replacing: Replacing order - prevent trade deletion.
|
||||||
:return: True if trade was fully cancelled
|
:return: True if trade was fully cancelled
|
||||||
"""
|
"""
|
||||||
was_trade_fully_canceled = False
|
was_trade_fully_canceled = False
|
||||||
|
order_id = order_obj.order_id
|
||||||
side = trade.entry_side.capitalize()
|
side = trade.entry_side.capitalize()
|
||||||
if not trade.has_open_orders:
|
|
||||||
logger.warning(f"No open order for {trade}.")
|
|
||||||
return False
|
|
||||||
|
|
||||||
if order['status'] not in constants.NON_OPEN_EXCHANGE_STATES:
|
if order['status'] not in constants.NON_OPEN_EXCHANGE_STATES:
|
||||||
filled_val: float = order.get('filled', 0.0) or 0.0
|
filled_val: float = order.get('filled', 0.0) or 0.0
|
||||||
@@ -1510,8 +1519,8 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
f"Order {order_id} for {trade.pair} not cancelled, "
|
f"Order {order_id} for {trade.pair} not cancelled, "
|
||||||
f"as the filled amount of {filled_val} would result in an unexitable trade.")
|
f"as the filled amount of {filled_val} would result in an unexitable trade.")
|
||||||
return False
|
return False
|
||||||
corder = self.exchange.cancel_order_with_result(order_id, trade.pair,
|
corder = self.exchange.cancel_order_with_result(order_id, trade.pair, trade.amount)
|
||||||
trade.amount)
|
order_obj.ft_cancel_reason = reason
|
||||||
# if replacing, retry fetching the order 3 times if the status is not what we need
|
# if replacing, retry fetching the order 3 times if the status is not what we need
|
||||||
if replacing:
|
if replacing:
|
||||||
retry_count = 0
|
retry_count = 0
|
||||||
@@ -1532,9 +1541,10 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
else:
|
else:
|
||||||
# Order was cancelled already, so we can reuse the existing dict
|
# Order was cancelled already, so we can reuse the existing dict
|
||||||
corder = order
|
corder = order
|
||||||
reason = constants.CANCEL_REASON['CANCELLED_ON_EXCHANGE']
|
if order_obj.ft_cancel_reason is None:
|
||||||
|
order_obj.ft_cancel_reason = constants.CANCEL_REASON['CANCELLED_ON_EXCHANGE']
|
||||||
|
|
||||||
logger.info(f'{side} order {reason} for {trade}.')
|
logger.info(f'{side} order {order_obj.ft_cancel_reason} for {trade}.')
|
||||||
|
|
||||||
# Using filled to determine the filled amount
|
# Using filled to determine the filled amount
|
||||||
filled_amount = safe_value_fallback2(corder, order, 'filled', 'filled')
|
filled_amount = safe_value_fallback2(corder, order, 'filled', 'filled')
|
||||||
@@ -1547,7 +1557,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
if open_order_count < 1 and trade.nr_of_successful_entries == 0 and not replacing:
|
if open_order_count < 1 and trade.nr_of_successful_entries == 0 and not replacing:
|
||||||
logger.info(f'{side} order fully cancelled. Removing {trade} from database.')
|
logger.info(f'{side} order fully cancelled. Removing {trade} from database.')
|
||||||
trade.delete()
|
trade.delete()
|
||||||
reason += f", {constants.CANCEL_REASON['FULLY_CANCELLED']}"
|
order_obj.ft_cancel_reason += f", {constants.CANCEL_REASON['FULLY_CANCELLED']}"
|
||||||
else:
|
else:
|
||||||
self.update_trade_state(trade, order_id, corder)
|
self.update_trade_state(trade, order_id, corder)
|
||||||
logger.info(f'{side} Order timeout for {trade}.')
|
logger.info(f'{side} Order timeout for {trade}.')
|
||||||
@@ -1557,21 +1567,21 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
self.update_trade_state(trade, order_id, corder)
|
self.update_trade_state(trade, order_id, corder)
|
||||||
|
|
||||||
logger.info(f'Partial {trade.entry_side} order timeout for {trade}.')
|
logger.info(f'Partial {trade.entry_side} order timeout for {trade}.')
|
||||||
reason += f", {constants.CANCEL_REASON['PARTIALLY_FILLED']}"
|
order_obj.ft_cancel_reason += f", {constants.CANCEL_REASON['PARTIALLY_FILLED']}"
|
||||||
|
|
||||||
self.wallets.update()
|
self.wallets.update()
|
||||||
self._notify_enter_cancel(trade, order_type=self.strategy.order_types['entry'],
|
self._notify_enter_cancel(trade, order_type=self.strategy.order_types['entry'],
|
||||||
reason=reason)
|
reason=order_obj.ft_cancel_reason)
|
||||||
return was_trade_fully_canceled
|
return was_trade_fully_canceled
|
||||||
|
|
||||||
def handle_cancel_exit(
|
def handle_cancel_exit(
|
||||||
self, trade: Trade, order: Dict, order_id: str,
|
self, trade: Trade, order: Dict, order_obj: Order, reason: str
|
||||||
reason: str
|
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
exit order cancel - cancel order and update trade
|
exit order cancel - cancel order and update trade
|
||||||
:return: True if exit order was cancelled, false otherwise
|
:return: True if exit order was cancelled, false otherwise
|
||||||
"""
|
"""
|
||||||
|
order_id = order_obj.order_id
|
||||||
cancelled = False
|
cancelled = False
|
||||||
# Cancelled orders may have the status of 'canceled' or 'closed'
|
# Cancelled orders may have the status of 'canceled' or 'closed'
|
||||||
if order['status'] not in constants.NON_OPEN_EXCHANGE_STATES:
|
if order['status'] not in constants.NON_OPEN_EXCHANGE_STATES:
|
||||||
@@ -1596,7 +1606,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
sub_trade=trade.amount != order['amount']
|
sub_trade=trade.amount != order['amount']
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
order_obj.ft_cancel_reason = reason
|
||||||
try:
|
try:
|
||||||
order = self.exchange.cancel_order_with_result(
|
order = self.exchange.cancel_order_with_result(
|
||||||
order['id'], trade.pair, trade.amount)
|
order['id'], trade.pair, trade.amount)
|
||||||
@@ -1615,19 +1625,22 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
trade.exit_reason = exit_reason_prev
|
trade.exit_reason = exit_reason_prev
|
||||||
cancelled = True
|
cancelled = True
|
||||||
else:
|
else:
|
||||||
reason = constants.CANCEL_REASON['CANCELLED_ON_EXCHANGE']
|
if order_obj.ft_cancel_reason is None:
|
||||||
|
order_obj.ft_cancel_reason = constants.CANCEL_REASON['CANCELLED_ON_EXCHANGE']
|
||||||
trade.exit_reason = None
|
trade.exit_reason = None
|
||||||
|
|
||||||
self.update_trade_state(trade, order['id'], order)
|
self.update_trade_state(trade, order['id'], order)
|
||||||
|
|
||||||
logger.info(f'{trade.exit_side.capitalize()} order {reason} for {trade}.')
|
logger.info(
|
||||||
|
f'{trade.exit_side.capitalize()} order {order_obj.ft_cancel_reason} for {trade}.')
|
||||||
trade.close_rate = None
|
trade.close_rate = None
|
||||||
trade.close_rate_requested = None
|
trade.close_rate_requested = None
|
||||||
|
|
||||||
self._notify_exit_cancel(
|
self._notify_exit_cancel(
|
||||||
trade,
|
trade,
|
||||||
order_type=self.strategy.order_types['exit'],
|
order_type=self.strategy.order_types['exit'],
|
||||||
reason=reason, order_id=order['id'], sub_trade=trade.amount != order['amount']
|
reason=order_obj.ft_cancel_reason, order_id=order['id'],
|
||||||
|
sub_trade=trade.amount != order['amount']
|
||||||
)
|
)
|
||||||
return cancelled
|
return cancelled
|
||||||
|
|
||||||
@@ -1679,15 +1692,13 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
:param exit_check: CheckTuple with signal and reason
|
:param exit_check: CheckTuple with signal and reason
|
||||||
:return: True if it succeeds False
|
:return: True if it succeeds False
|
||||||
"""
|
"""
|
||||||
try:
|
trade.set_funding_fees(
|
||||||
trade.funding_fees = self.exchange.get_funding_fees(
|
self.exchange.get_funding_fees(
|
||||||
pair=trade.pair,
|
pair=trade.pair,
|
||||||
amount=trade.amount,
|
amount=trade.amount,
|
||||||
is_short=trade.is_short,
|
is_short=trade.is_short,
|
||||||
open_date=trade.date_last_filled_utc,
|
open_date=trade.date_last_filled_utc)
|
||||||
)
|
)
|
||||||
except ExchangeError:
|
|
||||||
logger.warning("Could not update funding fee.")
|
|
||||||
|
|
||||||
exit_type = 'exit'
|
exit_type = 'exit'
|
||||||
exit_reason = exit_tag or exit_check.exit_reason
|
exit_reason = exit_tag or exit_check.exit_reason
|
||||||
@@ -1781,9 +1792,9 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
order_rate = trade.safe_close_rate
|
order_rate = trade.safe_close_rate
|
||||||
profit = trade.calculate_profit(rate=order_rate)
|
profit = trade.calculate_profit(rate=order_rate)
|
||||||
amount = trade.amount
|
amount = trade.amount
|
||||||
gain = "profit" if profit.profit_ratio > 0 else "loss"
|
gain: ProfitLossStr = "profit" if profit.profit_ratio > 0 else "loss"
|
||||||
|
|
||||||
msg: RPCSellMsg = {
|
msg: RPCExitMsg = {
|
||||||
'type': (RPCMessageType.EXIT_FILL if fill
|
'type': (RPCMessageType.EXIT_FILL if fill
|
||||||
else RPCMessageType.EXIT),
|
else RPCMessageType.EXIT),
|
||||||
'trade_id': trade.id,
|
'trade_id': trade.id,
|
||||||
@@ -1835,9 +1846,9 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
profit = trade.calculate_profit(rate=profit_rate)
|
profit = trade.calculate_profit(rate=profit_rate)
|
||||||
current_rate = self.exchange.get_rate(
|
current_rate = self.exchange.get_rate(
|
||||||
trade.pair, side='exit', is_short=trade.is_short, refresh=False)
|
trade.pair, side='exit', is_short=trade.is_short, refresh=False)
|
||||||
gain = "profit" if profit.profit_ratio > 0 else "loss"
|
gain: ProfitLossStr = "profit" if profit.profit_ratio > 0 else "loss"
|
||||||
|
|
||||||
msg: RPCSellCancelMsg = {
|
msg: RPCExitCancelMsg = {
|
||||||
'type': RPCMessageType.EXIT_CANCEL,
|
'type': RPCMessageType.EXIT_CANCEL,
|
||||||
'trade_id': trade.id,
|
'trade_id': trade.id,
|
||||||
'exchange': trade.exchange.capitalize(),
|
'exchange': trade.exchange.capitalize(),
|
||||||
@@ -1910,7 +1921,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
|
|
||||||
if self.exchange.check_order_canceled_empty(order):
|
if self.exchange.check_order_canceled_empty(order):
|
||||||
# Trade has been cancelled on exchange
|
# Trade has been cancelled on exchange
|
||||||
# Handling of this will happen in check_handle_timedout.
|
# Handling of this will happen in handle_cancel_order.
|
||||||
return True
|
return True
|
||||||
|
|
||||||
order_obj_or_none = trade.select_order_by_order_id(order_id)
|
order_obj_or_none = trade.select_order_by_order_id(order_id)
|
||||||
|
|||||||
@@ -8,15 +8,13 @@ logger = logging.getLogger(__name__)
|
|||||||
def set_loggers(verbosity: int = 0, api_verbosity: str = 'info') -> None:
|
def set_loggers(verbosity: int = 0, api_verbosity: str = 'info') -> None:
|
||||||
"""
|
"""
|
||||||
Set the logging level for third party libraries
|
Set the logging level for third party libraries
|
||||||
|
:param verbosity: Verbosity level. amount of `-v` passed to the command line
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
|
for logger_name in ('requests', 'urllib3', 'httpcore'):
|
||||||
logging.getLogger('requests').setLevel(
|
logging.getLogger(logger_name).setLevel(
|
||||||
logging.INFO if verbosity <= 1 else logging.DEBUG
|
logging.INFO if verbosity <= 1 else logging.DEBUG
|
||||||
)
|
)
|
||||||
logging.getLogger("urllib3").setLevel(
|
|
||||||
logging.INFO if verbosity <= 1 else logging.DEBUG
|
|
||||||
)
|
|
||||||
logging.getLogger('ccxt.base.exchange').setLevel(
|
logging.getLogger('ccxt.base.exchange').setLevel(
|
||||||
logging.INFO if verbosity <= 2 else logging.DEBUG
|
logging.INFO if verbosity <= 2 else logging.DEBUG
|
||||||
)
|
)
|
||||||
|
|||||||
+2
-1
@@ -3,6 +3,7 @@ Various tool function for Freqtrade and scripts
|
|||||||
"""
|
"""
|
||||||
import gzip
|
import gzip
|
||||||
import logging
|
import logging
|
||||||
|
from io import StringIO
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, Iterator, List, Mapping, Optional, TextIO, Union
|
from typing import Any, Dict, Iterator, List, Mapping, Optional, TextIO, Union
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
@@ -231,7 +232,7 @@ def json_to_dataframe(data: str) -> pd.DataFrame:
|
|||||||
:param data: A JSON string
|
:param data: A JSON string
|
||||||
:returns: A pandas DataFrame from the JSON string
|
:returns: A pandas DataFrame from the JSON string
|
||||||
"""
|
"""
|
||||||
dataframe = pd.read_json(data, orient='split')
|
dataframe = pd.read_json(StringIO(data), orient='split')
|
||||||
if 'date' in dataframe.columns:
|
if 'date' in dataframe.columns:
|
||||||
dataframe['date'] = pd.to_datetime(dataframe['date'], unit='ms', utc=True)
|
dataframe['date'] = pd.to_datetime(dataframe['date'], unit='ms', utc=True)
|
||||||
|
|
||||||
|
|||||||
@@ -94,8 +94,8 @@ class LookaheadAnalysis(BaseAnalysis):
|
|||||||
# compare_df now comprises tuples with [1] having either 'self' or 'other'
|
# compare_df now comprises tuples with [1] having either 'self' or 'other'
|
||||||
if 'other' in col_name[1]:
|
if 'other' in col_name[1]:
|
||||||
continue
|
continue
|
||||||
self_value = compare_df_row[col_idx]
|
self_value = compare_df_row.iloc[col_idx]
|
||||||
other_value = compare_df_row[col_idx + 1]
|
other_value = compare_df_row.iloc[col_idx + 1]
|
||||||
|
|
||||||
# output differences
|
# output differences
|
||||||
if self_value != other_value:
|
if self_value != other_value:
|
||||||
+1
-1
@@ -7,7 +7,7 @@ import pandas as pd
|
|||||||
|
|
||||||
from freqtrade.constants import Config
|
from freqtrade.constants import Config
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.optimize.lookahead_analysis import LookaheadAnalysis
|
from freqtrade.optimize.analysis.lookahead import LookaheadAnalysis
|
||||||
from freqtrade.resolvers import StrategyResolver
|
from freqtrade.resolvers import StrategyResolver
|
||||||
|
|
||||||
|
|
||||||
@@ -64,7 +64,7 @@ class RecursiveAnalysis(BaseAnalysis):
|
|||||||
self.dict_recursive[indicator][part.startup_candle] = f"{diff:.3f}%"
|
self.dict_recursive[indicator][part.startup_candle] = f"{diff:.3f}%"
|
||||||
|
|
||||||
else:
|
else:
|
||||||
logger.info("No difference found. Stop the process.")
|
logger.info("No variance on indicator(s) found due to recursive formula.")
|
||||||
break
|
break
|
||||||
|
|
||||||
# For lookahead bias check
|
# For lookahead bias check
|
||||||
@@ -100,7 +100,7 @@ class RecursiveAnalysis(BaseAnalysis):
|
|||||||
# logger.info("part value {:.5f}".format(values_diff_other))
|
# logger.info("part value {:.5f}".format(values_diff_other))
|
||||||
|
|
||||||
else:
|
else:
|
||||||
logger.info("No lookahead bias on indicators found. Stop the process.")
|
logger.info("No lookahead bias on indicators found.")
|
||||||
|
|
||||||
def prepare_data(self, varholder: VarHolder, pairs_to_load: List[DataFrame]):
|
def prepare_data(self, varholder: VarHolder, pairs_to_load: List[DataFrame]):
|
||||||
|
|
||||||
@@ -120,6 +120,7 @@ class RecursiveAnalysis(BaseAnalysis):
|
|||||||
prepare_data_config['exchange']['pair_whitelist'] = pairs_to_load
|
prepare_data_config['exchange']['pair_whitelist'] = pairs_to_load
|
||||||
|
|
||||||
backtesting = Backtesting(prepare_data_config, self.exchange)
|
backtesting = Backtesting(prepare_data_config, self.exchange)
|
||||||
|
self.exchange = backtesting.exchange
|
||||||
backtesting._set_strategy(backtesting.strategylist[0])
|
backtesting._set_strategy(backtesting.strategylist[0])
|
||||||
|
|
||||||
varholder.data, varholder.timerange = backtesting.load_bt_data()
|
varholder.data, varholder.timerange = backtesting.load_bt_data()
|
||||||
+10
-10
@@ -5,7 +5,7 @@ from typing import Any, Dict, List
|
|||||||
|
|
||||||
from freqtrade.constants import Config
|
from freqtrade.constants import Config
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.optimize.recursive_analysis import RecursiveAnalysis
|
from freqtrade.optimize.analysis.recursive import RecursiveAnalysis
|
||||||
from freqtrade.resolvers import StrategyResolver
|
from freqtrade.resolvers import StrategyResolver
|
||||||
|
|
||||||
|
|
||||||
@@ -31,10 +31,13 @@ class RecursiveAnalysisSubFunctions:
|
|||||||
temp_data.append(values.get(int(candle), '-'))
|
temp_data.append(values.get(int(candle), '-'))
|
||||||
data.append(temp_data)
|
data.append(temp_data)
|
||||||
|
|
||||||
from tabulate import tabulate
|
if len(data) > 0:
|
||||||
table = tabulate(data, headers=headers, tablefmt="orgtbl")
|
from tabulate import tabulate
|
||||||
print(table)
|
table = tabulate(data, headers=headers, tablefmt="orgtbl")
|
||||||
return table, headers, data
|
print(table)
|
||||||
|
return table, headers, data
|
||||||
|
|
||||||
|
return None, None, data
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def calculate_config_overrides(config: Config):
|
def calculate_config_overrides(config: Config):
|
||||||
@@ -81,8 +84,7 @@ class RecursiveAnalysisSubFunctions:
|
|||||||
if not (strategy_list := config.get('strategy_list', [])):
|
if not (strategy_list := config.get('strategy_list', [])):
|
||||||
if config.get('strategy') is None:
|
if config.get('strategy') is None:
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
"No Strategy specified. Please specify a strategy via --strategy or "
|
"No Strategy specified. Please specify a strategy via --strategy"
|
||||||
"--strategy-list"
|
|
||||||
)
|
)
|
||||||
strategy_list = [config['strategy']]
|
strategy_list = [config['strategy']]
|
||||||
|
|
||||||
@@ -100,7 +102,5 @@ class RecursiveAnalysisSubFunctions:
|
|||||||
RecursiveAnalysisSubFunctions.text_table_recursive_analysis_instances(
|
RecursiveAnalysisSubFunctions.text_table_recursive_analysis_instances(
|
||||||
RecursiveAnalysis_instances)
|
RecursiveAnalysis_instances)
|
||||||
else:
|
else:
|
||||||
logger.error("There were no strategies specified neither through "
|
logger.error("There was no strategy specified through --strategy "
|
||||||
"--strategy nor through "
|
|
||||||
"--strategy-list "
|
|
||||||
"or timeframe was not specified.")
|
"or timeframe was not specified.")
|
||||||
@@ -276,11 +276,13 @@ class Backtesting:
|
|||||||
else:
|
else:
|
||||||
self.detail_data = {}
|
self.detail_data = {}
|
||||||
if self.trading_mode == TradingMode.FUTURES:
|
if self.trading_mode == TradingMode.FUTURES:
|
||||||
|
self.funding_fee_timeframe: str = self.exchange.get_option('mark_ohlcv_timeframe')
|
||||||
|
self.funding_fee_timeframe_secs: int = timeframe_to_seconds(self.funding_fee_timeframe)
|
||||||
# Load additional futures data.
|
# Load additional futures data.
|
||||||
funding_rates_dict = history.load_data(
|
funding_rates_dict = history.load_data(
|
||||||
datadir=self.config['datadir'],
|
datadir=self.config['datadir'],
|
||||||
pairs=self.pairlists.whitelist,
|
pairs=self.pairlists.whitelist,
|
||||||
timeframe=self.exchange.get_option('mark_ohlcv_timeframe'),
|
timeframe=self.funding_fee_timeframe,
|
||||||
timerange=self.timerange,
|
timerange=self.timerange,
|
||||||
startup_candles=0,
|
startup_candles=0,
|
||||||
fail_without_data=True,
|
fail_without_data=True,
|
||||||
@@ -292,7 +294,7 @@ class Backtesting:
|
|||||||
mark_rates_dict = history.load_data(
|
mark_rates_dict = history.load_data(
|
||||||
datadir=self.config['datadir'],
|
datadir=self.config['datadir'],
|
||||||
pairs=self.pairlists.whitelist,
|
pairs=self.pairlists.whitelist,
|
||||||
timeframe=self.exchange.get_option('mark_ohlcv_timeframe'),
|
timeframe=self.funding_fee_timeframe,
|
||||||
timerange=self.timerange,
|
timerange=self.timerange,
|
||||||
startup_candles=0,
|
startup_candles=0,
|
||||||
fail_without_data=True,
|
fail_without_data=True,
|
||||||
@@ -525,10 +527,10 @@ class Backtesting:
|
|||||||
# This should not be reached...
|
# This should not be reached...
|
||||||
return row[OPEN_IDX]
|
return row[OPEN_IDX]
|
||||||
|
|
||||||
def _get_adjust_trade_entry_for_candle(self, trade: LocalTrade, row: Tuple
|
def _get_adjust_trade_entry_for_candle(
|
||||||
) -> LocalTrade:
|
self, trade: LocalTrade, row: Tuple, current_time: datetime
|
||||||
|
) -> LocalTrade:
|
||||||
current_rate = row[OPEN_IDX]
|
current_rate = row[OPEN_IDX]
|
||||||
current_date = row[DATE_IDX].to_pydatetime()
|
|
||||||
current_profit = trade.calc_profit_ratio(current_rate)
|
current_profit = trade.calc_profit_ratio(current_rate)
|
||||||
min_stake = self.exchange.get_min_pair_stake_amount(trade.pair, current_rate, -0.1)
|
min_stake = self.exchange.get_min_pair_stake_amount(trade.pair, current_rate, -0.1)
|
||||||
max_stake = self.exchange.get_max_pair_stake_amount(trade.pair, current_rate)
|
max_stake = self.exchange.get_max_pair_stake_amount(trade.pair, current_rate)
|
||||||
@@ -536,7 +538,7 @@ class Backtesting:
|
|||||||
stake_amount = strategy_safe_wrapper(self.strategy.adjust_trade_position,
|
stake_amount = strategy_safe_wrapper(self.strategy.adjust_trade_position,
|
||||||
default_retval=None, supress_error=True)(
|
default_retval=None, supress_error=True)(
|
||||||
trade=trade, # type: ignore[arg-type]
|
trade=trade, # type: ignore[arg-type]
|
||||||
current_time=current_date, current_rate=current_rate,
|
current_time=current_time, current_rate=current_rate,
|
||||||
current_profit=current_profit, min_stake=min_stake,
|
current_profit=current_profit, min_stake=min_stake,
|
||||||
max_stake=min(max_stake, stake_available),
|
max_stake=min(max_stake, stake_available),
|
||||||
current_entry_rate=current_rate, current_exit_rate=current_rate,
|
current_entry_rate=current_rate, current_exit_rate=current_rate,
|
||||||
@@ -569,10 +571,10 @@ class Backtesting:
|
|||||||
# Remaining stake is too low to be sold.
|
# Remaining stake is too low to be sold.
|
||||||
return trade
|
return trade
|
||||||
exit_ = ExitCheckTuple(ExitType.PARTIAL_EXIT)
|
exit_ = ExitCheckTuple(ExitType.PARTIAL_EXIT)
|
||||||
pos_trade = self._get_exit_for_signal(trade, row, exit_, amount)
|
pos_trade = self._get_exit_for_signal(trade, row, exit_, current_time, amount)
|
||||||
if pos_trade is not None:
|
if pos_trade is not None:
|
||||||
order = pos_trade.orders[-1]
|
order = pos_trade.orders[-1]
|
||||||
if self._try_close_open_order(order, trade, current_date, row):
|
if self._try_close_open_order(order, trade, current_time, row):
|
||||||
trade.recalc_trade_from_orders()
|
trade.recalc_trade_from_orders()
|
||||||
self.wallets.update()
|
self.wallets.update()
|
||||||
return pos_trade
|
return pos_trade
|
||||||
@@ -597,6 +599,8 @@ class Backtesting:
|
|||||||
"""
|
"""
|
||||||
if order and self._get_order_filled(order.ft_price, row):
|
if order and self._get_order_filled(order.ft_price, row):
|
||||||
order.close_bt_order(current_date, trade)
|
order.close_bt_order(current_date, trade)
|
||||||
|
self._run_funding_fees(trade, current_date, force=True)
|
||||||
|
|
||||||
if not (order.ft_order_side == trade.exit_side and order.safe_amount == trade.amount):
|
if not (order.ft_order_side == trade.exit_side and order.safe_amount == trade.amount):
|
||||||
# trade is still open
|
# trade is still open
|
||||||
trade.set_liquidation_price(self.exchange.get_liquidation_price(
|
trade.set_liquidation_price(self.exchange.get_liquidation_price(
|
||||||
@@ -615,11 +619,11 @@ class Backtesting:
|
|||||||
|
|
||||||
def _get_exit_for_signal(
|
def _get_exit_for_signal(
|
||||||
self, trade: LocalTrade, row: Tuple, exit_: ExitCheckTuple,
|
self, trade: LocalTrade, row: Tuple, exit_: ExitCheckTuple,
|
||||||
|
current_time: datetime,
|
||||||
amount: Optional[float] = None) -> Optional[LocalTrade]:
|
amount: Optional[float] = None) -> Optional[LocalTrade]:
|
||||||
|
|
||||||
exit_candle_time: datetime = row[DATE_IDX].to_pydatetime()
|
|
||||||
if exit_.exit_flag:
|
if exit_.exit_flag:
|
||||||
trade.close_date = exit_candle_time
|
trade.close_date = current_time
|
||||||
exit_reason = exit_.exit_reason
|
exit_reason = exit_.exit_reason
|
||||||
amount_ = amount if amount is not None else trade.amount
|
amount_ = amount if amount is not None else trade.amount
|
||||||
trade_dur = int((trade.close_date_utc - trade.open_date_utc).total_seconds() // 60)
|
trade_dur = int((trade.close_date_utc - trade.open_date_utc).total_seconds() // 60)
|
||||||
@@ -647,10 +651,10 @@ class Backtesting:
|
|||||||
default_retval=close_rate)(
|
default_retval=close_rate)(
|
||||||
pair=trade.pair,
|
pair=trade.pair,
|
||||||
trade=trade, # type: ignore[arg-type]
|
trade=trade, # type: ignore[arg-type]
|
||||||
current_time=exit_candle_time,
|
current_time=current_time,
|
||||||
proposed_rate=close_rate, current_profit=current_profit,
|
proposed_rate=close_rate, current_profit=current_profit,
|
||||||
exit_tag=exit_reason)
|
exit_tag=exit_reason)
|
||||||
if rate != close_rate:
|
if rate is not None and rate != close_rate:
|
||||||
close_rate = price_to_precision(rate, trade.price_precision,
|
close_rate = price_to_precision(rate, trade.price_precision,
|
||||||
self.precision_mode)
|
self.precision_mode)
|
||||||
# We can't place orders lower than current low.
|
# We can't place orders lower than current low.
|
||||||
@@ -673,7 +677,7 @@ class Backtesting:
|
|||||||
time_in_force=time_in_force,
|
time_in_force=time_in_force,
|
||||||
sell_reason=exit_reason, # deprecated
|
sell_reason=exit_reason, # deprecated
|
||||||
exit_reason=exit_reason,
|
exit_reason=exit_reason,
|
||||||
current_time=exit_candle_time)):
|
current_time=current_time)):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
trade.exit_reason = exit_reason
|
trade.exit_reason = exit_reason
|
||||||
@@ -714,21 +718,15 @@ class Backtesting:
|
|||||||
trade.orders.append(order)
|
trade.orders.append(order)
|
||||||
return trade
|
return trade
|
||||||
|
|
||||||
def _check_trade_exit(self, trade: LocalTrade, row: Tuple) -> Optional[LocalTrade]:
|
def _check_trade_exit(
|
||||||
exit_candle_time: datetime = row[DATE_IDX].to_pydatetime()
|
self, trade: LocalTrade, row: Tuple, current_time: datetime
|
||||||
|
) -> Optional[LocalTrade]:
|
||||||
|
|
||||||
if self.trading_mode == TradingMode.FUTURES:
|
self._run_funding_fees(trade, current_time)
|
||||||
trade.funding_fees = self.exchange.calculate_funding_fees(
|
|
||||||
self.futures_data[trade.pair],
|
|
||||||
amount=trade.amount,
|
|
||||||
is_short=trade.is_short,
|
|
||||||
open_date=trade.date_last_filled_utc,
|
|
||||||
close_date=exit_candle_time,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Check if we need to adjust our current positions
|
# Check if we need to adjust our current positions
|
||||||
if self.strategy.position_adjustment_enable:
|
if self.strategy.position_adjustment_enable:
|
||||||
trade = self._get_adjust_trade_entry_for_candle(trade, row)
|
trade = self._get_adjust_trade_entry_for_candle(trade, row, current_time)
|
||||||
|
|
||||||
enter = row[SHORT_IDX] if trade.is_short else row[LONG_IDX]
|
enter = row[SHORT_IDX] if trade.is_short else row[LONG_IDX]
|
||||||
exit_sig = row[ESHORT_IDX] if trade.is_short else row[ELONG_IDX]
|
exit_sig = row[ESHORT_IDX] if trade.is_short else row[ELONG_IDX]
|
||||||
@@ -738,11 +736,32 @@ class Backtesting:
|
|||||||
low=row[LOW_IDX], high=row[HIGH_IDX]
|
low=row[LOW_IDX], high=row[HIGH_IDX]
|
||||||
)
|
)
|
||||||
for exit_ in exits:
|
for exit_ in exits:
|
||||||
t = self._get_exit_for_signal(trade, row, exit_)
|
t = self._get_exit_for_signal(trade, row, exit_, current_time)
|
||||||
if t:
|
if t:
|
||||||
return t
|
return t
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def _run_funding_fees(self, trade: LocalTrade, current_time: datetime, force: bool = False):
|
||||||
|
"""
|
||||||
|
Calculate funding fees if necessary and add them to the trade.
|
||||||
|
"""
|
||||||
|
if self.trading_mode == TradingMode.FUTURES:
|
||||||
|
|
||||||
|
if (
|
||||||
|
force
|
||||||
|
or (current_time.timestamp() % self.funding_fee_timeframe_secs) == 0
|
||||||
|
):
|
||||||
|
# Funding fee interval.
|
||||||
|
trade.set_funding_fees(
|
||||||
|
self.exchange.calculate_funding_fees(
|
||||||
|
self.futures_data[trade.pair],
|
||||||
|
amount=trade.amount,
|
||||||
|
is_short=trade.is_short,
|
||||||
|
open_date=trade.date_last_filled_utc,
|
||||||
|
close_date=current_time
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
def get_valid_price_and_stake(
|
def get_valid_price_and_stake(
|
||||||
self, pair: str, row: Tuple, propose_rate: float, stake_amount: float,
|
self, pair: str, row: Tuple, propose_rate: float, stake_amount: float,
|
||||||
direction: LongShort, current_time: datetime, entry_tag: Optional[str],
|
direction: LongShort, current_time: datetime, entry_tag: Optional[str],
|
||||||
@@ -760,7 +779,7 @@ class Backtesting:
|
|||||||
) # default value is the open rate
|
) # default value is the open rate
|
||||||
# We can't place orders higher than current high (otherwise it'd be a stop limit entry)
|
# We can't place orders higher than current high (otherwise it'd be a stop limit entry)
|
||||||
# which freqtrade does not support in live.
|
# which freqtrade does not support in live.
|
||||||
if new_rate != propose_rate:
|
if new_rate is not None and new_rate != propose_rate:
|
||||||
propose_rate = price_to_precision(new_rate, price_precision,
|
propose_rate = price_to_precision(new_rate, price_precision,
|
||||||
self.precision_mode)
|
self.precision_mode)
|
||||||
if direction == "short":
|
if direction == "short":
|
||||||
@@ -772,7 +791,8 @@ class Backtesting:
|
|||||||
leverage = trade.leverage if trade else 1.0
|
leverage = trade.leverage if trade else 1.0
|
||||||
if not pos_adjust:
|
if not pos_adjust:
|
||||||
try:
|
try:
|
||||||
stake_amount = self.wallets.get_trade_stake_amount(pair, None, update=False)
|
stake_amount = self.wallets.get_trade_stake_amount(
|
||||||
|
pair, self.strategy.max_open_trades, update=False)
|
||||||
except DependencyException:
|
except DependencyException:
|
||||||
return 0, 0, 0, 0
|
return 0, 0, 0, 0
|
||||||
|
|
||||||
@@ -954,7 +974,7 @@ class Backtesting:
|
|||||||
|
|
||||||
def trade_slot_available(self, open_trade_count: int) -> bool:
|
def trade_slot_available(self, open_trade_count: int) -> bool:
|
||||||
# Always allow trades when max_open_trades is enabled.
|
# Always allow trades when max_open_trades is enabled.
|
||||||
max_open_trades: IntOrInf = self.config['max_open_trades']
|
max_open_trades: IntOrInf = self.strategy.max_open_trades
|
||||||
if max_open_trades <= 0 or open_trade_count < max_open_trades:
|
if max_open_trades <= 0 or open_trade_count < max_open_trades:
|
||||||
return True
|
return True
|
||||||
# Rejected trade
|
# Rejected trade
|
||||||
@@ -1145,7 +1165,7 @@ class Backtesting:
|
|||||||
|
|
||||||
# 4. Create exit orders (if any)
|
# 4. Create exit orders (if any)
|
||||||
if not trade.has_open_orders:
|
if not trade.has_open_orders:
|
||||||
self._check_trade_exit(trade, row) # Place exit order if necessary
|
self._check_trade_exit(trade, row, current_time) # Place exit order if necessary
|
||||||
|
|
||||||
# 5. Process exit orders.
|
# 5. Process exit orders.
|
||||||
order = trade.select_order(trade.exit_side, is_open=True)
|
order = trade.select_order(trade.exit_side, is_open=True)
|
||||||
|
|||||||
@@ -500,7 +500,7 @@ class Hyperopt:
|
|||||||
while i < 5 and len(asked_non_tried) < n_points:
|
while i < 5 and len(asked_non_tried) < n_points:
|
||||||
if i < 3:
|
if i < 3:
|
||||||
self.opt.cache_ = {}
|
self.opt.cache_ = {}
|
||||||
asked = unique_list(self.opt.ask(n_points=n_points * 5))
|
asked = unique_list(self.opt.ask(n_points=n_points * 5 if i > 0 else n_points))
|
||||||
is_random = [False for _ in range(len(asked))]
|
is_random = [False for _ in range(len(asked))]
|
||||||
else:
|
else:
|
||||||
asked = unique_list(self.opt.space.rvs(n_samples=n_points * 5))
|
asked = unique_list(self.opt.space.rvs(n_samples=n_points * 5))
|
||||||
@@ -637,6 +637,10 @@ class Hyperopt:
|
|||||||
|
|
||||||
HyperoptTools.show_epoch_details(self.current_best_epoch, self.total_epochs,
|
HyperoptTools.show_epoch_details(self.current_best_epoch, self.total_epochs,
|
||||||
self.print_json)
|
self.print_json)
|
||||||
|
elif self.num_epochs_saved > 0:
|
||||||
|
print(
|
||||||
|
f"No good result found for given optimization function in {self.num_epochs_saved} "
|
||||||
|
f"{plural(self.num_epochs_saved, 'epoch')}.")
|
||||||
else:
|
else:
|
||||||
# This is printed when Ctrl+C is pressed quickly, before first epochs have
|
# This is printed when Ctrl+C is pressed quickly, before first epochs have
|
||||||
# a chance to be evaluated.
|
# a chance to be evaluated.
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
def _format_exception_message(space: str, ignore_missing_space: bool) -> None:
|
def _format_exception_message(space: str, ignore_missing_space: bool) -> None:
|
||||||
msg = (f"The '{space}' space is included into the hyperoptimization "
|
msg = (f"The '{space}' space is included into the hyperoptimization "
|
||||||
f"but no parameter for this space was not found in your Strategy. "
|
f"but no parameter for this space was found in your Strategy. "
|
||||||
)
|
)
|
||||||
if ignore_missing_space:
|
if ignore_missing_space:
|
||||||
logger.warning(msg + "This space will be ignored.")
|
logger.warning(msg + "This space will be ignored.")
|
||||||
|
|||||||
@@ -429,14 +429,18 @@ class HyperoptTools:
|
|||||||
trials = trials.drop(columns=['Total profit'])
|
trials = trials.drop(columns=['Total profit'])
|
||||||
|
|
||||||
if print_colorized:
|
if print_colorized:
|
||||||
|
trials2 = trials.astype(str)
|
||||||
for i in range(len(trials)):
|
for i in range(len(trials)):
|
||||||
if trials.loc[i]['is_profit']:
|
if trials.loc[i]['is_profit']:
|
||||||
for j in range(len(trials.loc[i]) - 3):
|
for j in range(len(trials.loc[i]) - 3):
|
||||||
trials.iat[i, j] = f"{Fore.GREEN}{str(trials.loc[i][j])}{Fore.RESET}"
|
trials2.iat[i, j] = f"{Fore.GREEN}{str(trials.iloc[i, j])}{Fore.RESET}"
|
||||||
if trials.loc[i]['is_best'] and highlight_best:
|
if trials.loc[i]['is_best'] and highlight_best:
|
||||||
for j in range(len(trials.loc[i]) - 3):
|
for j in range(len(trials.loc[i]) - 3):
|
||||||
trials.iat[i, j] = f"{Style.BRIGHT}{str(trials.loc[i][j])}{Style.RESET_ALL}"
|
trials2.iat[i, j] = (
|
||||||
|
f"{Style.BRIGHT}{str(trials.iloc[i, j])}{Style.RESET_ALL}"
|
||||||
|
)
|
||||||
|
trials = trials2
|
||||||
|
del trials2
|
||||||
trials = trials.drop(columns=['is_initial_point', 'is_best', 'is_profit', 'is_random'])
|
trials = trials.drop(columns=['is_initial_point', 'is_best', 'is_profit', 'is_random'])
|
||||||
if remove_header > 0:
|
if remove_header > 0:
|
||||||
table = tabulate.tabulate(
|
table = tabulate.tabulate(
|
||||||
|
|||||||
@@ -219,8 +219,10 @@ def _get_resample_from_period(period: str) -> str:
|
|||||||
raise ValueError(f"Period {period} is not supported.")
|
raise ValueError(f"Period {period} is not supported.")
|
||||||
|
|
||||||
|
|
||||||
def generate_periodic_breakdown_stats(trade_list: List, period: str) -> List[Dict[str, Any]]:
|
def generate_periodic_breakdown_stats(
|
||||||
results = DataFrame.from_records(trade_list)
|
trade_list: Union[List, DataFrame], period: str) -> List[Dict[str, Any]]:
|
||||||
|
|
||||||
|
results = trade_list if not isinstance(trade_list, list) else DataFrame.from_records(trade_list)
|
||||||
if len(results) == 0:
|
if len(results) == 0:
|
||||||
return []
|
return []
|
||||||
results['close_date'] = to_datetime(results['close_date'], utc=True)
|
results['close_date'] = to_datetime(results['close_date'], utc=True)
|
||||||
|
|||||||
@@ -115,6 +115,7 @@ def migrate_trades_and_orders_table(
|
|||||||
# Futures Properties
|
# Futures Properties
|
||||||
interest_rate = get_column_def(cols, 'interest_rate', '0.0')
|
interest_rate = get_column_def(cols, 'interest_rate', '0.0')
|
||||||
funding_fees = get_column_def(cols, 'funding_fees', '0.0')
|
funding_fees = get_column_def(cols, 'funding_fees', '0.0')
|
||||||
|
funding_fee_running = get_column_def(cols, 'funding_fee_running', 'null')
|
||||||
max_stake_amount = get_column_def(cols, 'max_stake_amount', 'stake_amount')
|
max_stake_amount = get_column_def(cols, 'max_stake_amount', 'stake_amount')
|
||||||
|
|
||||||
# If ticker-interval existed use that, else null.
|
# If ticker-interval existed use that, else null.
|
||||||
@@ -163,7 +164,7 @@ def migrate_trades_and_orders_table(
|
|||||||
max_rate, min_rate, exit_reason, exit_order_status, strategy, enter_tag,
|
max_rate, min_rate, exit_reason, exit_order_status, strategy, enter_tag,
|
||||||
timeframe, open_trade_value, close_profit_abs,
|
timeframe, open_trade_value, close_profit_abs,
|
||||||
trading_mode, leverage, liquidation_price, is_short,
|
trading_mode, leverage, liquidation_price, is_short,
|
||||||
interest_rate, funding_fees, realized_profit,
|
interest_rate, funding_fees, funding_fee_running, realized_profit,
|
||||||
amount_precision, price_precision, precision_mode, contract_size,
|
amount_precision, price_precision, precision_mode, contract_size,
|
||||||
max_stake_amount
|
max_stake_amount
|
||||||
)
|
)
|
||||||
@@ -192,7 +193,8 @@ def migrate_trades_and_orders_table(
|
|||||||
{open_trade_value} open_trade_value, {close_profit_abs} close_profit_abs,
|
{open_trade_value} open_trade_value, {close_profit_abs} close_profit_abs,
|
||||||
{trading_mode} trading_mode, {leverage} leverage, {liquidation_price} liquidation_price,
|
{trading_mode} trading_mode, {leverage} leverage, {liquidation_price} liquidation_price,
|
||||||
{is_short} is_short, {interest_rate} interest_rate,
|
{is_short} is_short, {interest_rate} interest_rate,
|
||||||
{funding_fees} funding_fees, {realized_profit} realized_profit,
|
{funding_fees} funding_fees, {funding_fee_running} funding_fee_running,
|
||||||
|
{realized_profit} realized_profit,
|
||||||
{amount_precision} amount_precision, {price_precision} price_precision,
|
{amount_precision} amount_precision, {price_precision} price_precision,
|
||||||
{precision_mode} precision_mode, {contract_size} contract_size,
|
{precision_mode} precision_mode, {contract_size} contract_size,
|
||||||
{max_stake_amount} max_stake_amount
|
{max_stake_amount} max_stake_amount
|
||||||
@@ -220,6 +222,7 @@ def migrate_orders_table(engine, table_back_name: str, cols_order: List):
|
|||||||
funding_fee = get_column_def(cols_order, 'funding_fee', '0.0')
|
funding_fee = get_column_def(cols_order, 'funding_fee', '0.0')
|
||||||
ft_amount = get_column_def(cols_order, 'ft_amount', 'coalesce(amount, 0.0)')
|
ft_amount = get_column_def(cols_order, 'ft_amount', 'coalesce(amount, 0.0)')
|
||||||
ft_price = get_column_def(cols_order, 'ft_price', 'coalesce(price, 0.0)')
|
ft_price = get_column_def(cols_order, 'ft_price', 'coalesce(price, 0.0)')
|
||||||
|
ft_cancel_reason = get_column_def(cols_order, 'ft_cancel_reason', 'null')
|
||||||
|
|
||||||
# sqlite does not support literals for booleans
|
# sqlite does not support literals for booleans
|
||||||
with engine.begin() as connection:
|
with engine.begin() as connection:
|
||||||
@@ -227,13 +230,13 @@ def migrate_orders_table(engine, table_back_name: str, cols_order: List):
|
|||||||
insert into orders (id, ft_trade_id, ft_order_side, ft_pair, ft_is_open, order_id,
|
insert into orders (id, ft_trade_id, ft_order_side, ft_pair, ft_is_open, order_id,
|
||||||
status, symbol, order_type, side, price, amount, filled, average, remaining, cost,
|
status, symbol, order_type, side, price, amount, filled, average, remaining, cost,
|
||||||
stop_price, order_date, order_filled_date, order_update_date, ft_fee_base, funding_fee,
|
stop_price, order_date, order_filled_date, order_update_date, ft_fee_base, funding_fee,
|
||||||
ft_amount, ft_price
|
ft_amount, ft_price, ft_cancel_reason
|
||||||
)
|
)
|
||||||
select id, ft_trade_id, ft_order_side, ft_pair, ft_is_open, order_id,
|
select id, ft_trade_id, ft_order_side, ft_pair, ft_is_open, order_id,
|
||||||
status, symbol, order_type, side, price, amount, filled, {average} average, remaining,
|
status, symbol, order_type, side, price, amount, filled, {average} average, remaining,
|
||||||
cost, {stop_price} stop_price, order_date, order_filled_date,
|
cost, {stop_price} stop_price, order_date, order_filled_date,
|
||||||
order_update_date, {ft_fee_base} ft_fee_base, {funding_fee} funding_fee,
|
order_update_date, {ft_fee_base} ft_fee_base, {funding_fee} funding_fee,
|
||||||
{ft_amount} ft_amount, {ft_price} ft_price
|
{ft_amount} ft_amount, {ft_price} ft_price, {ft_cancel_reason} ft_cancel_reason
|
||||||
from {table_back_name}
|
from {table_back_name}
|
||||||
"""))
|
"""))
|
||||||
|
|
||||||
@@ -328,8 +331,8 @@ def check_migrate(engine, decl_base, previous_tables) -> None:
|
|||||||
# if ('orders' not in previous_tables
|
# if ('orders' not in previous_tables
|
||||||
# or not has_column(cols_orders, 'funding_fee')):
|
# or not has_column(cols_orders, 'funding_fee')):
|
||||||
migrating = False
|
migrating = False
|
||||||
# if not has_column(cols_orders, 'ft_price'):
|
# if not has_column(cols_orders, 'ft_cancel_reason'):
|
||||||
if not has_column(cols_trades, 'is_stop_loss_trailing'):
|
if not has_column(cols_trades, 'funding_fee_running'):
|
||||||
migrating = True
|
migrating = True
|
||||||
logger.info(f"Running database migration for trades - "
|
logger.info(f"Running database migration for trades - "
|
||||||
f"backup: {table_back_name}, {order_table_bak_name}")
|
f"backup: {table_back_name}, {order_table_bak_name}")
|
||||||
|
|||||||
@@ -68,6 +68,7 @@ class Order(ModelBase):
|
|||||||
ft_is_open: Mapped[bool] = mapped_column(nullable=False, default=True, index=True)
|
ft_is_open: Mapped[bool] = mapped_column(nullable=False, default=True, index=True)
|
||||||
ft_amount: Mapped[float] = mapped_column(Float(), nullable=False)
|
ft_amount: Mapped[float] = mapped_column(Float(), nullable=False)
|
||||||
ft_price: Mapped[float] = mapped_column(Float(), nullable=False)
|
ft_price: Mapped[float] = mapped_column(Float(), nullable=False)
|
||||||
|
ft_cancel_reason: Mapped[str] = mapped_column(String(CUSTOM_TAG_MAX_LENGTH), nullable=True)
|
||||||
|
|
||||||
order_id: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
order_id: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
||||||
status: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
status: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||||
@@ -155,28 +156,24 @@ class Order(ModelBase):
|
|||||||
if self.order_id != str(order['id']):
|
if self.order_id != str(order['id']):
|
||||||
raise DependencyException("Order-id's don't match")
|
raise DependencyException("Order-id's don't match")
|
||||||
|
|
||||||
self.status = order.get('status', self.status)
|
self.status = safe_value_fallback(order, 'status', default_value=self.status)
|
||||||
self.symbol = order.get('symbol', self.symbol)
|
self.symbol = safe_value_fallback(order, 'symbol', default_value=self.symbol)
|
||||||
self.order_type = order.get('type', self.order_type)
|
self.order_type = safe_value_fallback(order, 'type', default_value=self.order_type)
|
||||||
self.side = order.get('side', self.side)
|
self.side = safe_value_fallback(order, 'side', default_value=self.side)
|
||||||
self.price = order.get('price', self.price)
|
self.price = safe_value_fallback(order, 'price', default_value=self.price)
|
||||||
self.amount = order.get('amount', self.amount)
|
self.amount = safe_value_fallback(order, 'amount', default_value=self.amount)
|
||||||
self.filled = order.get('filled', self.filled)
|
self.filled = safe_value_fallback(order, 'filled', default_value=self.filled)
|
||||||
self.average = order.get('average', self.average)
|
self.average = safe_value_fallback(order, 'average', default_value=self.average)
|
||||||
self.remaining = order.get('remaining', self.remaining)
|
self.remaining = safe_value_fallback(order, 'remaining', default_value=self.remaining)
|
||||||
self.cost = order.get('cost', self.cost)
|
self.cost = safe_value_fallback(order, 'cost', default_value=self.cost)
|
||||||
self.stop_price = order.get('stopPrice', self.stop_price)
|
self.stop_price = safe_value_fallback(order, 'stopPrice', default_value=self.stop_price)
|
||||||
|
order_date = safe_value_fallback(order, 'timestamp')
|
||||||
if 'timestamp' in order and order['timestamp'] is not None:
|
if order_date:
|
||||||
self.order_date = datetime.fromtimestamp(order['timestamp'] / 1000, tz=timezone.utc)
|
self.order_date = datetime.fromtimestamp(order_date / 1000, tz=timezone.utc)
|
||||||
|
|
||||||
self.ft_is_open = True
|
self.ft_is_open = True
|
||||||
if self.status in NON_OPEN_EXCHANGE_STATES:
|
if self.status in NON_OPEN_EXCHANGE_STATES:
|
||||||
self.ft_is_open = False
|
self.ft_is_open = False
|
||||||
if self.trade:
|
|
||||||
# Assign funding fee up to this point
|
|
||||||
# (represents the funding fee since the last order)
|
|
||||||
self.funding_fee = self.trade.funding_fees
|
|
||||||
if (order.get('filled', 0.0) or 0.0) > 0 and not self.order_filled_date:
|
if (order.get('filled', 0.0) or 0.0) > 0 and not self.order_filled_date:
|
||||||
self.order_filled_date = dt_from_ts(
|
self.order_filled_date = dt_from_ts(
|
||||||
safe_value_fallback(order, 'lastTradeTimestamp', default_value=dt_ts())
|
safe_value_fallback(order, 'lastTradeTimestamp', default_value=dt_ts())
|
||||||
@@ -237,6 +234,7 @@ class Order(ModelBase):
|
|||||||
'price': self.price,
|
'price': self.price,
|
||||||
'remaining': self.remaining,
|
'remaining': self.remaining,
|
||||||
'ft_fee_base': self.ft_fee_base,
|
'ft_fee_base': self.ft_fee_base,
|
||||||
|
'funding_fee': self.funding_fee,
|
||||||
})
|
})
|
||||||
return resp
|
return resp
|
||||||
|
|
||||||
@@ -248,7 +246,8 @@ class Order(ModelBase):
|
|||||||
self.ft_is_open = False
|
self.ft_is_open = False
|
||||||
# Assign funding fees to Order.
|
# Assign funding fees to Order.
|
||||||
# Assumes backtesting will use date_last_filled_utc to calculate future funding fees.
|
# Assumes backtesting will use date_last_filled_utc to calculate future funding fees.
|
||||||
self.funding_fee = trade.funding_fees
|
self.funding_fee = trade.funding_fee_running
|
||||||
|
trade.funding_fee_running = 0.0
|
||||||
|
|
||||||
if (self.ft_order_side == trade.entry_side and self.price):
|
if (self.ft_order_side == trade.entry_side and self.price):
|
||||||
trade.open_rate = self.price
|
trade.open_rate = self.price
|
||||||
@@ -395,6 +394,9 @@ class LocalTrade:
|
|||||||
|
|
||||||
# Futures properties
|
# Futures properties
|
||||||
funding_fees: Optional[float] = None
|
funding_fees: Optional[float] = None
|
||||||
|
# Used to keep running funding fees - between the last filled order and now
|
||||||
|
# Shall not be used for calculations!
|
||||||
|
funding_fee_running: Optional[float] = None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def stoploss_or_liquidation(self) -> float:
|
def stoploss_or_liquidation(self) -> float:
|
||||||
@@ -534,6 +536,7 @@ class LocalTrade:
|
|||||||
for key in kwargs:
|
for key in kwargs:
|
||||||
setattr(self, key, kwargs[key])
|
setattr(self, key, kwargs[key])
|
||||||
self.recalc_open_trade_value()
|
self.recalc_open_trade_value()
|
||||||
|
self.orders = []
|
||||||
if self.trading_mode == TradingMode.MARGIN and self.interest_rate is None:
|
if self.trading_mode == TradingMode.MARGIN and self.interest_rate is None:
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f"{self.trading_mode.value} trading requires param interest_rate on trades")
|
f"{self.trading_mode.value} trading requires param interest_rate on trades")
|
||||||
@@ -660,6 +663,16 @@ class LocalTrade:
|
|||||||
return
|
return
|
||||||
self.liquidation_price = liquidation_price
|
self.liquidation_price = liquidation_price
|
||||||
|
|
||||||
|
def set_funding_fees(self, funding_fee: float) -> None:
|
||||||
|
"""
|
||||||
|
Assign funding fees to Trade.
|
||||||
|
"""
|
||||||
|
if funding_fee is None:
|
||||||
|
return
|
||||||
|
self.funding_fee_running = funding_fee
|
||||||
|
prior_funding_fees = sum([o.funding_fee for o in self.orders if o.funding_fee])
|
||||||
|
self.funding_fees = prior_funding_fees + funding_fee
|
||||||
|
|
||||||
def __set_stop_loss(self, stop_loss: float, percent: float):
|
def __set_stop_loss(self, stop_loss: float, percent: float):
|
||||||
"""
|
"""
|
||||||
Method used internally to set self.stop_loss.
|
Method used internally to set self.stop_loss.
|
||||||
@@ -740,6 +753,10 @@ class LocalTrade:
|
|||||||
return
|
return
|
||||||
|
|
||||||
logger.info(f'Updating trade (id={self.id}) ...')
|
logger.info(f'Updating trade (id={self.id}) ...')
|
||||||
|
if order.ft_order_side != 'stoploss':
|
||||||
|
order.funding_fee = self.funding_fee_running
|
||||||
|
# Reset running funding fees
|
||||||
|
self.funding_fee_running = 0.0
|
||||||
|
|
||||||
if order.ft_order_side == self.entry_side:
|
if order.ft_order_side == self.entry_side:
|
||||||
# Update open rate and actual amount
|
# Update open rate and actual amount
|
||||||
@@ -1036,7 +1053,7 @@ class LocalTrade:
|
|||||||
price = avg_price if is_exit else tmp_price
|
price = avg_price if is_exit else tmp_price
|
||||||
current_stake += price * tmp_amount * side
|
current_stake += price * tmp_amount * side
|
||||||
|
|
||||||
if current_amount > ZERO:
|
if current_amount > ZERO and not is_exit:
|
||||||
avg_price = current_stake / current_amount
|
avg_price = current_stake / current_amount
|
||||||
|
|
||||||
if is_exit:
|
if is_exit:
|
||||||
@@ -1049,7 +1066,10 @@ class LocalTrade:
|
|||||||
exit_amount = o.safe_amount_after_fee
|
exit_amount = o.safe_amount_after_fee
|
||||||
prof = self.calculate_profit(exit_rate, exit_amount, float(avg_price))
|
prof = self.calculate_profit(exit_rate, exit_amount, float(avg_price))
|
||||||
close_profit_abs += prof.profit_abs
|
close_profit_abs += prof.profit_abs
|
||||||
close_profit = prof.profit_ratio
|
if total_stake > 0:
|
||||||
|
# This needs to be calculated based on the last occuring exit to be aligned
|
||||||
|
# with realized_profit.
|
||||||
|
close_profit = (close_profit_abs / total_stake) * self.leverage
|
||||||
else:
|
else:
|
||||||
total_stake = total_stake + self._calc_open_trade_value(tmp_amount, price)
|
total_stake = total_stake + self._calc_open_trade_value(tmp_amount, price)
|
||||||
max_stake_amount += (tmp_amount * price)
|
max_stake_amount += (tmp_amount * price)
|
||||||
@@ -1285,6 +1305,99 @@ class LocalTrade:
|
|||||||
trade.adjust_stop_loss(trade.open_rate, desired_stoploss)
|
trade.adjust_stop_loss(trade.open_rate, desired_stoploss)
|
||||||
logger.info(f"New stoploss: {trade.stop_loss}.")
|
logger.info(f"New stoploss: {trade.stop_loss}.")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_json(cls, json_str: str) -> Self:
|
||||||
|
"""
|
||||||
|
Create a Trade instance from a json string.
|
||||||
|
|
||||||
|
Used for debugging purposes - please keep.
|
||||||
|
:param json_str: json string to parse
|
||||||
|
:return: Trade instance
|
||||||
|
"""
|
||||||
|
import rapidjson
|
||||||
|
data = rapidjson.loads(json_str)
|
||||||
|
trade = cls(
|
||||||
|
__FROM_JSON=True,
|
||||||
|
id=data["trade_id"],
|
||||||
|
pair=data["pair"],
|
||||||
|
base_currency=data["base_currency"],
|
||||||
|
stake_currency=data["quote_currency"],
|
||||||
|
is_open=data["is_open"],
|
||||||
|
exchange=data["exchange"],
|
||||||
|
amount=data["amount"],
|
||||||
|
amount_requested=data["amount_requested"],
|
||||||
|
stake_amount=data["stake_amount"],
|
||||||
|
strategy=data["strategy"],
|
||||||
|
enter_tag=data["enter_tag"],
|
||||||
|
timeframe=data["timeframe"],
|
||||||
|
fee_open=data["fee_open"],
|
||||||
|
fee_open_cost=data["fee_open_cost"],
|
||||||
|
fee_open_currency=data["fee_open_currency"],
|
||||||
|
fee_close=data["fee_close"],
|
||||||
|
fee_close_cost=data["fee_close_cost"],
|
||||||
|
fee_close_currency=data["fee_close_currency"],
|
||||||
|
open_date=datetime.fromtimestamp(data["open_timestamp"] // 1000, tz=timezone.utc),
|
||||||
|
open_rate=data["open_rate"],
|
||||||
|
open_rate_requested=data["open_rate_requested"],
|
||||||
|
open_trade_value=data["open_trade_value"],
|
||||||
|
close_date=(datetime.fromtimestamp(data["close_timestamp"] // 1000, tz=timezone.utc)
|
||||||
|
if data["close_timestamp"] else None),
|
||||||
|
realized_profit=data["realized_profit"],
|
||||||
|
close_rate=data["close_rate"],
|
||||||
|
close_rate_requested=data["close_rate_requested"],
|
||||||
|
close_profit=data["close_profit"],
|
||||||
|
close_profit_abs=data["close_profit_abs"],
|
||||||
|
exit_reason=data["exit_reason"],
|
||||||
|
exit_order_status=data["exit_order_status"],
|
||||||
|
stop_loss=data["stop_loss_abs"],
|
||||||
|
stop_loss_pct=data["stop_loss_ratio"],
|
||||||
|
stoploss_order_id=data["stoploss_order_id"],
|
||||||
|
stoploss_last_update=(
|
||||||
|
datetime.fromtimestamp(data["stoploss_last_update_timestamp"] // 1000,
|
||||||
|
tz=timezone.utc)
|
||||||
|
if data["stoploss_last_update_timestamp"] else None),
|
||||||
|
initial_stop_loss=data["initial_stop_loss_abs"],
|
||||||
|
initial_stop_loss_pct=data["initial_stop_loss_ratio"],
|
||||||
|
min_rate=data["min_rate"],
|
||||||
|
max_rate=data["max_rate"],
|
||||||
|
leverage=data["leverage"],
|
||||||
|
interest_rate=data["interest_rate"],
|
||||||
|
liquidation_price=data["liquidation_price"],
|
||||||
|
is_short=data["is_short"],
|
||||||
|
trading_mode=data["trading_mode"],
|
||||||
|
funding_fees=data["funding_fees"],
|
||||||
|
amount_precision=data.get('amount_precision', None),
|
||||||
|
price_precision=data.get('price_precision', None),
|
||||||
|
precision_mode=data.get('precision_mode', None),
|
||||||
|
contract_size=data.get('contract_size', None),
|
||||||
|
)
|
||||||
|
for order in data["orders"]:
|
||||||
|
|
||||||
|
order_obj = Order(
|
||||||
|
amount=order["amount"],
|
||||||
|
ft_amount=order["amount"],
|
||||||
|
ft_order_side=order["ft_order_side"],
|
||||||
|
ft_pair=order["pair"],
|
||||||
|
ft_is_open=order["is_open"],
|
||||||
|
order_id=order["order_id"],
|
||||||
|
status=order["status"],
|
||||||
|
average=order["average"],
|
||||||
|
cost=order["cost"],
|
||||||
|
filled=order["filled"],
|
||||||
|
order_date=datetime.strptime(order["order_date"], DATETIME_PRINT_FORMAT),
|
||||||
|
order_filled_date=(datetime.fromtimestamp(
|
||||||
|
order["order_filled_timestamp"] // 1000, tz=timezone.utc)
|
||||||
|
if order["order_filled_timestamp"] else None),
|
||||||
|
order_type=order["order_type"],
|
||||||
|
price=order["price"],
|
||||||
|
ft_price=order["price"],
|
||||||
|
remaining=order["remaining"],
|
||||||
|
funding_fee=order.get("funding_fee", None),
|
||||||
|
)
|
||||||
|
trade.orders.append(order_obj)
|
||||||
|
|
||||||
|
return trade
|
||||||
|
|
||||||
|
|
||||||
class Trade(ModelBase, LocalTrade):
|
class Trade(ModelBase, LocalTrade):
|
||||||
"""
|
"""
|
||||||
@@ -1388,6 +1501,8 @@ class Trade(ModelBase, LocalTrade):
|
|||||||
# Futures properties
|
# Futures properties
|
||||||
funding_fees: Mapped[Optional[float]] = mapped_column(
|
funding_fees: Mapped[Optional[float]] = mapped_column(
|
||||||
Float(), nullable=True, default=None) # type: ignore
|
Float(), nullable=True, default=None) # type: ignore
|
||||||
|
funding_fee_running: Mapped[Optional[float]] = mapped_column(
|
||||||
|
Float(), nullable=True, default=None) # type: ignore
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
from_json = kwargs.pop('__FROM_JSON', None)
|
from_json = kwargs.pop('__FROM_JSON', None)
|
||||||
@@ -1668,7 +1783,7 @@ class Trade(ModelBase, LocalTrade):
|
|||||||
.order_by(desc('profit_sum_abs'))
|
.order_by(desc('profit_sum_abs'))
|
||||||
).all()
|
).all()
|
||||||
|
|
||||||
return_list: List[Dict] = []
|
resp: List[Dict] = []
|
||||||
for id, enter_tag, exit_reason, profit, profit_abs, count in mix_tag_perf:
|
for id, enter_tag, exit_reason, profit, profit_abs, count in mix_tag_perf:
|
||||||
enter_tag = enter_tag if enter_tag is not None else "Other"
|
enter_tag = enter_tag if enter_tag is not None else "Other"
|
||||||
exit_reason = exit_reason if exit_reason is not None else "Other"
|
exit_reason = exit_reason if exit_reason is not None else "Other"
|
||||||
@@ -1676,24 +1791,25 @@ class Trade(ModelBase, LocalTrade):
|
|||||||
if (exit_reason is not None and enter_tag is not None):
|
if (exit_reason is not None and enter_tag is not None):
|
||||||
mix_tag = enter_tag + " " + exit_reason
|
mix_tag = enter_tag + " " + exit_reason
|
||||||
i = 0
|
i = 0
|
||||||
if not any(item["mix_tag"] == mix_tag for item in return_list):
|
if not any(item["mix_tag"] == mix_tag for item in resp):
|
||||||
return_list.append({'mix_tag': mix_tag,
|
resp.append({'mix_tag': mix_tag,
|
||||||
'profit': profit,
|
'profit_ratio': profit,
|
||||||
'profit_pct': round(profit * 100, 2),
|
'profit_pct': round(profit * 100, 2),
|
||||||
'profit_abs': profit_abs,
|
'profit_abs': profit_abs,
|
||||||
'count': count})
|
'count': count})
|
||||||
else:
|
else:
|
||||||
while i < len(return_list):
|
while i < len(resp):
|
||||||
if return_list[i]["mix_tag"] == mix_tag:
|
if resp[i]["mix_tag"] == mix_tag:
|
||||||
return_list[i] = {
|
resp[i] = {
|
||||||
'mix_tag': mix_tag,
|
'mix_tag': mix_tag,
|
||||||
'profit': profit + return_list[i]["profit"],
|
'profit_ratio': profit + resp[i]["profit_ratio"],
|
||||||
'profit_pct': round(profit + return_list[i]["profit"] * 100, 2),
|
'profit_pct': round(profit + resp[i]["profit_ratio"] * 100, 2),
|
||||||
'profit_abs': profit_abs + return_list[i]["profit_abs"],
|
'profit_abs': profit_abs + resp[i]["profit_abs"],
|
||||||
'count': 1 + return_list[i]["count"]}
|
'count': 1 + resp[i]["count"]
|
||||||
|
}
|
||||||
i += 1
|
i += 1
|
||||||
|
|
||||||
return return_list
|
return resp
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_best_pair(start_date: datetime = datetime.fromtimestamp(0)):
|
def get_best_pair(start_date: datetime = datetime.fromtimestamp(0)):
|
||||||
@@ -1728,95 +1844,3 @@ class Trade(ModelBase, LocalTrade):
|
|||||||
Order.status == 'closed'
|
Order.status == 'closed'
|
||||||
)).scalar_one()
|
)).scalar_one()
|
||||||
return trading_volume
|
return trading_volume
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def from_json(cls, json_str: str) -> Self:
|
|
||||||
"""
|
|
||||||
Create a Trade instance from a json string.
|
|
||||||
|
|
||||||
Used for debugging purposes - please keep.
|
|
||||||
:param json_str: json string to parse
|
|
||||||
:return: Trade instance
|
|
||||||
"""
|
|
||||||
import rapidjson
|
|
||||||
data = rapidjson.loads(json_str)
|
|
||||||
trade = cls(
|
|
||||||
__FROM_JSON=True,
|
|
||||||
id=data["trade_id"],
|
|
||||||
pair=data["pair"],
|
|
||||||
base_currency=data["base_currency"],
|
|
||||||
stake_currency=data["quote_currency"],
|
|
||||||
is_open=data["is_open"],
|
|
||||||
exchange=data["exchange"],
|
|
||||||
amount=data["amount"],
|
|
||||||
amount_requested=data["amount_requested"],
|
|
||||||
stake_amount=data["stake_amount"],
|
|
||||||
strategy=data["strategy"],
|
|
||||||
enter_tag=data["enter_tag"],
|
|
||||||
timeframe=data["timeframe"],
|
|
||||||
fee_open=data["fee_open"],
|
|
||||||
fee_open_cost=data["fee_open_cost"],
|
|
||||||
fee_open_currency=data["fee_open_currency"],
|
|
||||||
fee_close=data["fee_close"],
|
|
||||||
fee_close_cost=data["fee_close_cost"],
|
|
||||||
fee_close_currency=data["fee_close_currency"],
|
|
||||||
open_date=datetime.fromtimestamp(data["open_timestamp"] // 1000, tz=timezone.utc),
|
|
||||||
open_rate=data["open_rate"],
|
|
||||||
open_rate_requested=data["open_rate_requested"],
|
|
||||||
open_trade_value=data["open_trade_value"],
|
|
||||||
close_date=(datetime.fromtimestamp(data["close_timestamp"] // 1000, tz=timezone.utc)
|
|
||||||
if data["close_timestamp"] else None),
|
|
||||||
realized_profit=data["realized_profit"],
|
|
||||||
close_rate=data["close_rate"],
|
|
||||||
close_rate_requested=data["close_rate_requested"],
|
|
||||||
close_profit=data["close_profit"],
|
|
||||||
close_profit_abs=data["close_profit_abs"],
|
|
||||||
exit_reason=data["exit_reason"],
|
|
||||||
exit_order_status=data["exit_order_status"],
|
|
||||||
stop_loss=data["stop_loss_abs"],
|
|
||||||
stop_loss_pct=data["stop_loss_ratio"],
|
|
||||||
stoploss_order_id=data["stoploss_order_id"],
|
|
||||||
stoploss_last_update=(
|
|
||||||
datetime.fromtimestamp(data["stoploss_last_update_timestamp"] // 1000,
|
|
||||||
tz=timezone.utc)
|
|
||||||
if data["stoploss_last_update_timestamp"] else None),
|
|
||||||
initial_stop_loss=data["initial_stop_loss_abs"],
|
|
||||||
initial_stop_loss_pct=data["initial_stop_loss_ratio"],
|
|
||||||
min_rate=data["min_rate"],
|
|
||||||
max_rate=data["max_rate"],
|
|
||||||
leverage=data["leverage"],
|
|
||||||
interest_rate=data["interest_rate"],
|
|
||||||
liquidation_price=data["liquidation_price"],
|
|
||||||
is_short=data["is_short"],
|
|
||||||
trading_mode=data["trading_mode"],
|
|
||||||
funding_fees=data["funding_fees"],
|
|
||||||
amount_precision=data.get('amount_precision', None),
|
|
||||||
price_precision=data.get('price_precision', None),
|
|
||||||
precision_mode=data.get('precision_mode', None),
|
|
||||||
contract_size=data.get('contract_size', None),
|
|
||||||
)
|
|
||||||
for order in data["orders"]:
|
|
||||||
|
|
||||||
order_obj = Order(
|
|
||||||
amount=order["amount"],
|
|
||||||
ft_amount=order["amount"],
|
|
||||||
ft_order_side=order["ft_order_side"],
|
|
||||||
ft_pair=order["pair"],
|
|
||||||
ft_is_open=order["is_open"],
|
|
||||||
order_id=order["order_id"],
|
|
||||||
status=order["status"],
|
|
||||||
average=order["average"],
|
|
||||||
cost=order["cost"],
|
|
||||||
filled=order["filled"],
|
|
||||||
order_date=datetime.strptime(order["order_date"], DATETIME_PRINT_FORMAT),
|
|
||||||
order_filled_date=(datetime.fromtimestamp(
|
|
||||||
order["order_filled_timestamp"] // 1000, tz=timezone.utc)
|
|
||||||
if order["order_filled_timestamp"] else None),
|
|
||||||
order_type=order["order_type"],
|
|
||||||
price=order["price"],
|
|
||||||
ft_price=order["price"],
|
|
||||||
remaining=order["remaining"],
|
|
||||||
)
|
|
||||||
trade.orders.append(order_obj)
|
|
||||||
|
|
||||||
return trade
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ from freqtrade.misc import pair_to_filename
|
|||||||
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
||||||
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||||
from freqtrade.strategy import IStrategy
|
from freqtrade.strategy import IStrategy
|
||||||
|
from freqtrade.strategy.strategy_wrapper import strategy_safe_wrapper
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -636,7 +637,7 @@ def load_and_plot_trades(config: Config):
|
|||||||
exchange = ExchangeResolver.load_exchange(config)
|
exchange = ExchangeResolver.load_exchange(config)
|
||||||
IStrategy.dp = DataProvider(config, exchange)
|
IStrategy.dp = DataProvider(config, exchange)
|
||||||
strategy.ft_bot_start()
|
strategy.ft_bot_start()
|
||||||
strategy.bot_loop_start(datetime.now(timezone.utc))
|
strategy_safe_wrapper(strategy.bot_loop_start)(current_time=datetime.now(timezone.utc))
|
||||||
plot_elements = init_plotscript(config, list(exchange.markets), strategy.startup_candle_count)
|
plot_elements = init_plotscript(config, list(exchange.markets), strategy.startup_candle_count)
|
||||||
timerange = plot_elements['timerange']
|
timerange = plot_elements['timerange']
|
||||||
trades = plot_elements['trades']
|
trades = plot_elements['trades']
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from typing import Any, Dict, List, Optional, Union
|
from typing import Any, Dict, List, Optional, Union
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, RootModel, SerializeAsAny
|
from pydantic import BaseModel, RootModel, SerializeAsAny
|
||||||
|
|
||||||
from freqtrade.constants import DATETIME_PRINT_FORMAT, IntOrInf
|
from freqtrade.constants import IntOrInf
|
||||||
from freqtrade.enums import MarginMode, OrderTypeValues, SignalDirection, TradingMode
|
from freqtrade.enums import MarginMode, OrderTypeValues, SignalDirection, TradingMode
|
||||||
from freqtrade.types import ValidExchangesType
|
from freqtrade.types import ValidExchangesType
|
||||||
|
|
||||||
@@ -95,15 +95,30 @@ class Count(BaseModel):
|
|||||||
total_stake: float
|
total_stake: float
|
||||||
|
|
||||||
|
|
||||||
class PerformanceEntry(BaseModel):
|
class __BaseStatsModel(BaseModel):
|
||||||
pair: str
|
|
||||||
profit: float
|
|
||||||
profit_ratio: float
|
profit_ratio: float
|
||||||
profit_pct: float
|
profit_pct: float
|
||||||
profit_abs: float
|
profit_abs: float
|
||||||
count: int
|
count: int
|
||||||
|
|
||||||
|
|
||||||
|
class Entry(__BaseStatsModel):
|
||||||
|
enter_tag: str
|
||||||
|
|
||||||
|
|
||||||
|
class Exit(__BaseStatsModel):
|
||||||
|
exit_reason: str
|
||||||
|
|
||||||
|
|
||||||
|
class MixTag(__BaseStatsModel):
|
||||||
|
mix_tag: str
|
||||||
|
|
||||||
|
|
||||||
|
class PerformanceEntry(__BaseStatsModel):
|
||||||
|
pair: str
|
||||||
|
profit: float
|
||||||
|
|
||||||
|
|
||||||
class Profit(BaseModel):
|
class Profit(BaseModel):
|
||||||
profit_closed_coin: float
|
profit_closed_coin: float
|
||||||
profit_closed_percent_mean: float
|
profit_closed_percent_mean: float
|
||||||
@@ -456,6 +471,7 @@ class FreqAIModelListResponse(BaseModel):
|
|||||||
class StrategyResponse(BaseModel):
|
class StrategyResponse(BaseModel):
|
||||||
strategy: str
|
strategy: str
|
||||||
code: str
|
code: str
|
||||||
|
timeframe: Optional[str]
|
||||||
|
|
||||||
|
|
||||||
class AvailablePairs(BaseModel):
|
class AvailablePairs(BaseModel):
|
||||||
@@ -484,11 +500,6 @@ class PairHistory(BaseModel):
|
|||||||
data_start: str
|
data_start: str
|
||||||
data_stop: str
|
data_stop: str
|
||||||
data_stop_ts: int
|
data_stop_ts: int
|
||||||
# TODO[pydantic]: The following keys were removed: `json_encoders`.
|
|
||||||
# Check https://docs.pydantic.dev/dev-v2/migration/#changes-to-config for more information.
|
|
||||||
model_config = ConfigDict(json_encoders={
|
|
||||||
datetime: lambda v: v.strftime(DATETIME_PRINT_FORMAT),
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
class BacktestFreqAIInputs(BaseModel):
|
class BacktestFreqAIInputs(BaseModel):
|
||||||
|
|||||||
@@ -12,15 +12,15 @@ from freqtrade.exceptions import OperationalException
|
|||||||
from freqtrade.rpc import RPC
|
from freqtrade.rpc import RPC
|
||||||
from freqtrade.rpc.api_server.api_schemas import (AvailablePairs, Balances, BlacklistPayload,
|
from freqtrade.rpc.api_server.api_schemas import (AvailablePairs, Balances, BlacklistPayload,
|
||||||
BlacklistResponse, Count, DailyWeeklyMonthly,
|
BlacklistResponse, Count, DailyWeeklyMonthly,
|
||||||
DeleteLockRequest, DeleteTrade,
|
DeleteLockRequest, DeleteTrade, Entry,
|
||||||
ExchangeListResponse, ForceEnterPayload,
|
ExchangeListResponse, Exit, ForceEnterPayload,
|
||||||
ForceEnterResponse, ForceExitPayload,
|
ForceEnterResponse, ForceExitPayload,
|
||||||
FreqAIModelListResponse, Health, Locks, Logs,
|
FreqAIModelListResponse, Health, Locks, Logs,
|
||||||
OpenTradeSchema, PairHistory, PerformanceEntry,
|
MixTag, OpenTradeSchema, PairHistory,
|
||||||
Ping, PlotConfig, Profit, ResultMsg, ShowConfig,
|
PerformanceEntry, Ping, PlotConfig, Profit,
|
||||||
Stats, StatusMsg, StrategyListResponse,
|
ResultMsg, ShowConfig, Stats, StatusMsg,
|
||||||
StrategyResponse, SysInfo, Version,
|
StrategyListResponse, StrategyResponse, SysInfo,
|
||||||
WhitelistResponse)
|
Version, WhitelistResponse)
|
||||||
from freqtrade.rpc.api_server.deps import get_config, get_exchange, get_rpc, get_rpc_optional
|
from freqtrade.rpc.api_server.deps import get_config, get_exchange, get_rpc, get_rpc_optional
|
||||||
from freqtrade.rpc.rpc import RPCException
|
from freqtrade.rpc.rpc import RPCException
|
||||||
|
|
||||||
@@ -52,7 +52,8 @@ logger = logging.getLogger(__name__)
|
|||||||
# 2.31: new /backtest/history/ delete endpoint
|
# 2.31: new /backtest/history/ delete endpoint
|
||||||
# 2.32: new /backtest/history/ patch endpoint
|
# 2.32: new /backtest/history/ patch endpoint
|
||||||
# 2.33: Additional weekly/monthly metrics
|
# 2.33: Additional weekly/monthly metrics
|
||||||
API_VERSION = 2.33
|
# 2.34: new entries/exits/mix_tags endpoints
|
||||||
|
API_VERSION = 2.34
|
||||||
|
|
||||||
# Public API, requires no auth.
|
# Public API, requires no auth.
|
||||||
router_public = APIRouter()
|
router_public = APIRouter()
|
||||||
@@ -83,6 +84,21 @@ def count(rpc: RPC = Depends(get_rpc)):
|
|||||||
return rpc._rpc_count()
|
return rpc._rpc_count()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/entries', response_model=List[Entry], tags=['info'])
|
||||||
|
def entries(pair: Optional[str] = None, rpc: RPC = Depends(get_rpc)):
|
||||||
|
return rpc._rpc_enter_tag_performance(pair)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/exits', response_model=List[Exit], tags=['info'])
|
||||||
|
def exits(pair: Optional[str] = None, rpc: RPC = Depends(get_rpc)):
|
||||||
|
return rpc._rpc_exit_reason_performance(pair)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/mix_tags', response_model=List[MixTag], tags=['info'])
|
||||||
|
def mix_tags(pair: Optional[str] = None, rpc: RPC = Depends(get_rpc)):
|
||||||
|
return rpc._rpc_mix_tag_performance(pair)
|
||||||
|
|
||||||
|
|
||||||
@router.get('/performance', response_model=List[PerformanceEntry], tags=['info'])
|
@router.get('/performance', response_model=List[PerformanceEntry], tags=['info'])
|
||||||
def performance(rpc: RPC = Depends(get_rpc)):
|
def performance(rpc: RPC = Depends(get_rpc)):
|
||||||
return rpc._rpc_performance()
|
return rpc._rpc_performance()
|
||||||
@@ -334,6 +350,7 @@ def get_strategy(strategy: str, config=Depends(get_config)):
|
|||||||
return {
|
return {
|
||||||
'strategy': strategy_obj.get_strategy_name(),
|
'strategy': strategy_obj.get_strategy_name(),
|
||||||
'code': strategy_obj.__source__,
|
'code': strategy_obj.__source__,
|
||||||
|
'timeframe': getattr(strategy_obj, 'timeframe', None),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ def get_exchange(config=Depends(get_config)):
|
|||||||
if not (exchange := ApiBG.exchanges.get(exchange_key)):
|
if not (exchange := ApiBG.exchanges.get(exchange_key)):
|
||||||
from freqtrade.resolvers import ExchangeResolver
|
from freqtrade.resolvers import ExchangeResolver
|
||||||
exchange = ExchangeResolver.load_exchange(
|
exchange = ExchangeResolver.load_exchange(
|
||||||
config, load_leverage_tiers=False)
|
config, validate=False, load_leverage_tiers=False)
|
||||||
ApiBG.exchanges[exchange_key] = exchange
|
ApiBG.exchanges[exchange_key] = exchange
|
||||||
return exchange
|
return exchange
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ class Discord(Webhook):
|
|||||||
self.rpc = rpc
|
self.rpc = rpc
|
||||||
self.strategy = config.get('strategy', '')
|
self.strategy = config.get('strategy', '')
|
||||||
self.timeframe = config.get('timeframe', '')
|
self.timeframe = config.get('timeframe', '')
|
||||||
|
self.bot_name = config.get('bot_name', '')
|
||||||
|
|
||||||
self._url = config['discord']['webhook_url']
|
self._url = config['discord']['webhook_url']
|
||||||
self._format = 'json'
|
self._format = 'json'
|
||||||
@@ -31,12 +32,12 @@ class Discord(Webhook):
|
|||||||
|
|
||||||
def send_msg(self, msg) -> None:
|
def send_msg(self, msg) -> None:
|
||||||
|
|
||||||
if msg['type'].value in self._config['discord']:
|
if (fields := self._config['discord'].get(msg['type'].value)):
|
||||||
logger.info(f"Sending discord message: {msg}")
|
logger.info(f"Sending discord message: {msg}")
|
||||||
|
|
||||||
msg['strategy'] = self.strategy
|
msg['strategy'] = self.strategy
|
||||||
msg['timeframe'] = self.timeframe
|
msg['timeframe'] = self.timeframe
|
||||||
fields = self._config['discord'].get(msg['type'].value)
|
msg['bot_name'] = self.bot_name
|
||||||
color = 0x0000FF
|
color = 0x0000FF
|
||||||
if msg['type'] in (RPCMessageType.EXIT, RPCMessageType.EXIT_FILL):
|
if msg['type'] in (RPCMessageType.EXIT, RPCMessageType.EXIT_FILL):
|
||||||
profit_ratio = msg.get('profit_ratio')
|
profit_ratio = msg.get('profit_ratio')
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ coingecko_mapping = {
|
|||||||
'usdt': 'tether',
|
'usdt': 'tether',
|
||||||
'busd': 'binance-usd',
|
'busd': 'binance-usd',
|
||||||
'tusd': 'true-usd',
|
'tusd': 'true-usd',
|
||||||
|
'usdc': 'usd-coin',
|
||||||
|
'btc': 'bitcoin'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -121,8 +121,8 @@ class RPC:
|
|||||||
'stake_currency_decimals': decimals_per_coin(config['stake_currency']),
|
'stake_currency_decimals': decimals_per_coin(config['stake_currency']),
|
||||||
'stake_amount': str(config['stake_amount']),
|
'stake_amount': str(config['stake_amount']),
|
||||||
'available_capital': config.get('available_capital'),
|
'available_capital': config.get('available_capital'),
|
||||||
'max_open_trades': (config['max_open_trades']
|
'max_open_trades': (config.get('max_open_trades', 0)
|
||||||
if config['max_open_trades'] != float('inf') else -1),
|
if config.get('max_open_trades', 0) != float('inf') else -1),
|
||||||
'minimal_roi': config['minimal_roi'].copy() if 'minimal_roi' in config else {},
|
'minimal_roi': config['minimal_roi'].copy() if 'minimal_roi' in config else {},
|
||||||
'stoploss': config.get('stoploss'),
|
'stoploss': config.get('stoploss'),
|
||||||
'stoploss_on_exchange': config.get('order_types',
|
'stoploss_on_exchange': config.get('order_types',
|
||||||
@@ -795,14 +795,14 @@ class RPC:
|
|||||||
|
|
||||||
if order['side'] == trade.entry_side:
|
if order['side'] == trade.entry_side:
|
||||||
fully_canceled = self._freqtrade.handle_cancel_enter(
|
fully_canceled = self._freqtrade.handle_cancel_enter(
|
||||||
trade, order, oo.order_id, CANCEL_REASON['FORCE_EXIT'])
|
trade, order, oo, CANCEL_REASON['FORCE_EXIT'])
|
||||||
trade_entry_cancelation_res['cancel_state'] = fully_canceled
|
trade_entry_cancelation_res['cancel_state'] = fully_canceled
|
||||||
trade_entry_cancelation_registry.append(trade_entry_cancelation_res)
|
trade_entry_cancelation_registry.append(trade_entry_cancelation_res)
|
||||||
|
|
||||||
if order['side'] == trade.exit_side:
|
if order['side'] == trade.exit_side:
|
||||||
# Cancel order - so it is placed anew with a fresh price.
|
# Cancel order - so it is placed anew with a fresh price.
|
||||||
self._freqtrade.handle_cancel_exit(
|
self._freqtrade.handle_cancel_exit(
|
||||||
trade, order, oo.order_id, CANCEL_REASON['FORCE_EXIT'])
|
trade, order, oo, CANCEL_REASON['FORCE_EXIT'])
|
||||||
|
|
||||||
if all(tocr['cancel_state'] is False for tocr in trade_entry_cancelation_registry):
|
if all(tocr['cancel_state'] is False for tocr in trade_entry_cancelation_registry):
|
||||||
if trade.has_open_orders:
|
if trade.has_open_orders:
|
||||||
@@ -914,7 +914,8 @@ class RPC:
|
|||||||
|
|
||||||
if not stake_amount:
|
if not stake_amount:
|
||||||
# gen stake amount
|
# gen stake amount
|
||||||
stake_amount = self._freqtrade.wallets.get_trade_stake_amount(pair)
|
stake_amount = self._freqtrade.wallets.get_trade_stake_amount(
|
||||||
|
pair, self._config['max_open_trades'])
|
||||||
|
|
||||||
# execute buy
|
# execute buy
|
||||||
if not order_type:
|
if not order_type:
|
||||||
@@ -955,7 +956,7 @@ class RPC:
|
|||||||
logger.info(f"Cannot query order for {trade} due to {e}.", exc_info=True)
|
logger.info(f"Cannot query order for {trade} due to {e}.", exc_info=True)
|
||||||
raise RPCException("Order not found.")
|
raise RPCException("Order not found.")
|
||||||
self._freqtrade.handle_cancel_order(
|
self._freqtrade.handle_cancel_order(
|
||||||
order, open_order.order_id, trade, CANCEL_REASON['USER_CANCEL'])
|
order, open_order, trade, CANCEL_REASON['USER_CANCEL'])
|
||||||
Trade.commit()
|
Trade.commit()
|
||||||
|
|
||||||
def _rpc_delete(self, trade_id: int) -> Dict[str, Union[str, int]]:
|
def _rpc_delete(self, trade_id: int) -> Dict[str, Union[str, int]]:
|
||||||
|
|||||||
+13
-10
@@ -5,6 +5,9 @@ from freqtrade.constants import PairWithTimeframe
|
|||||||
from freqtrade.enums import RPCMessageType
|
from freqtrade.enums import RPCMessageType
|
||||||
|
|
||||||
|
|
||||||
|
ProfitLossStr = Literal["profit", "loss"]
|
||||||
|
|
||||||
|
|
||||||
class RPCSendMsgBase(TypedDict):
|
class RPCSendMsgBase(TypedDict):
|
||||||
pass
|
pass
|
||||||
# ty1pe: Literal[RPCMessageType]
|
# ty1pe: Literal[RPCMessageType]
|
||||||
@@ -41,7 +44,7 @@ class RPCWhitelistMsg(RPCSendMsgBase):
|
|||||||
data: List[str]
|
data: List[str]
|
||||||
|
|
||||||
|
|
||||||
class __RPCBuyMsgBase(RPCSendMsgBase):
|
class __RPCEntryExitMsgBase(RPCSendMsgBase):
|
||||||
trade_id: int
|
trade_id: int
|
||||||
buy_tag: Optional[str]
|
buy_tag: Optional[str]
|
||||||
enter_tag: Optional[str]
|
enter_tag: Optional[str]
|
||||||
@@ -62,19 +65,19 @@ class __RPCBuyMsgBase(RPCSendMsgBase):
|
|||||||
sub_trade: bool
|
sub_trade: bool
|
||||||
|
|
||||||
|
|
||||||
class RPCBuyMsg(__RPCBuyMsgBase):
|
class RPCEntryMsg(__RPCEntryExitMsgBase):
|
||||||
type: Literal[RPCMessageType.ENTRY, RPCMessageType.ENTRY_FILL]
|
type: Literal[RPCMessageType.ENTRY, RPCMessageType.ENTRY_FILL]
|
||||||
|
|
||||||
|
|
||||||
class RPCCancelMsg(__RPCBuyMsgBase):
|
class RPCCancelMsg(__RPCEntryExitMsgBase):
|
||||||
type: Literal[RPCMessageType.ENTRY_CANCEL]
|
type: Literal[RPCMessageType.ENTRY_CANCEL]
|
||||||
reason: str
|
reason: str
|
||||||
|
|
||||||
|
|
||||||
class RPCSellMsg(__RPCBuyMsgBase):
|
class RPCExitMsg(__RPCEntryExitMsgBase):
|
||||||
type: Literal[RPCMessageType.EXIT, RPCMessageType.EXIT_FILL]
|
type: Literal[RPCMessageType.EXIT, RPCMessageType.EXIT_FILL]
|
||||||
cumulative_profit: float
|
cumulative_profit: float
|
||||||
gain: str # Literal["profit", "loss"]
|
gain: ProfitLossStr
|
||||||
close_rate: float
|
close_rate: float
|
||||||
profit_amount: float
|
profit_amount: float
|
||||||
profit_ratio: float
|
profit_ratio: float
|
||||||
@@ -85,10 +88,10 @@ class RPCSellMsg(__RPCBuyMsgBase):
|
|||||||
order_rate: Optional[float]
|
order_rate: Optional[float]
|
||||||
|
|
||||||
|
|
||||||
class RPCSellCancelMsg(__RPCBuyMsgBase):
|
class RPCExitCancelMsg(__RPCEntryExitMsgBase):
|
||||||
type: Literal[RPCMessageType.EXIT_CANCEL]
|
type: Literal[RPCMessageType.EXIT_CANCEL]
|
||||||
reason: str
|
reason: str
|
||||||
gain: str # Literal["profit", "loss"]
|
gain: ProfitLossStr
|
||||||
profit_amount: float
|
profit_amount: float
|
||||||
profit_ratio: float
|
profit_ratio: float
|
||||||
sell_reason: Optional[str]
|
sell_reason: Optional[str]
|
||||||
@@ -119,10 +122,10 @@ RPCSendMsg = Union[
|
|||||||
RPCStrategyMsg,
|
RPCStrategyMsg,
|
||||||
RPCProtectionMsg,
|
RPCProtectionMsg,
|
||||||
RPCWhitelistMsg,
|
RPCWhitelistMsg,
|
||||||
RPCBuyMsg,
|
RPCEntryMsg,
|
||||||
RPCCancelMsg,
|
RPCCancelMsg,
|
||||||
RPCSellMsg,
|
RPCExitMsg,
|
||||||
RPCSellCancelMsg,
|
RPCExitCancelMsg,
|
||||||
RPCAnalyzedDFMsg,
|
RPCAnalyzedDFMsg,
|
||||||
RPCNewCandleMsg
|
RPCNewCandleMsg
|
||||||
]
|
]
|
||||||
|
|||||||
+63
-15
@@ -223,7 +223,8 @@ class Telegram(RPCHandler):
|
|||||||
CommandHandler('health', self._health),
|
CommandHandler('health', self._health),
|
||||||
CommandHandler('help', self._help),
|
CommandHandler('help', self._help),
|
||||||
CommandHandler('version', self._version),
|
CommandHandler('version', self._version),
|
||||||
CommandHandler('marketdir', self._changemarketdir)
|
CommandHandler('marketdir', self._changemarketdir),
|
||||||
|
CommandHandler('order', self._order),
|
||||||
]
|
]
|
||||||
callbacks = [
|
callbacks = [
|
||||||
CallbackQueryHandler(self._status_table, pattern='update_status_table'),
|
CallbackQueryHandler(self._status_table, pattern='update_status_table'),
|
||||||
@@ -240,7 +241,7 @@ class Telegram(RPCHandler):
|
|||||||
CallbackQueryHandler(self._mix_tag_performance, pattern='update_mix_tag_performance'),
|
CallbackQueryHandler(self._mix_tag_performance, pattern='update_mix_tag_performance'),
|
||||||
CallbackQueryHandler(self._count, pattern='update_count'),
|
CallbackQueryHandler(self._count, pattern='update_count'),
|
||||||
CallbackQueryHandler(self._force_exit_inline, pattern=r"force_exit__\S+"),
|
CallbackQueryHandler(self._force_exit_inline, pattern=r"force_exit__\S+"),
|
||||||
CallbackQueryHandler(self._force_enter_inline, pattern=r"\S+\/\S+"),
|
CallbackQueryHandler(self._force_enter_inline, pattern=r"force_enter__\S+"),
|
||||||
]
|
]
|
||||||
for handle in handles:
|
for handle in handles:
|
||||||
self._app.add_handler(handle)
|
self._app.add_handler(handle)
|
||||||
@@ -555,6 +556,47 @@ class Telegram(RPCHandler):
|
|||||||
|
|
||||||
return lines_detail
|
return lines_detail
|
||||||
|
|
||||||
|
@authorized_only
|
||||||
|
async def _order(self, update: Update, context: CallbackContext) -> None:
|
||||||
|
"""
|
||||||
|
Handler for /order.
|
||||||
|
Returns the orders of the trade
|
||||||
|
:param bot: telegram bot
|
||||||
|
:param update: message update
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
|
||||||
|
trade_ids = []
|
||||||
|
if context.args and len(context.args) > 0:
|
||||||
|
trade_ids = [int(i) for i in context.args if i.isnumeric()]
|
||||||
|
|
||||||
|
results = self._rpc._rpc_trade_status(trade_ids=trade_ids)
|
||||||
|
for r in results:
|
||||||
|
lines = [
|
||||||
|
"*Order List for Trade #*`{trade_id}`"
|
||||||
|
]
|
||||||
|
|
||||||
|
lines_detail = self._prepare_order_details(
|
||||||
|
r['orders'], r['quote_currency'], r['is_open'])
|
||||||
|
lines.extend(lines_detail if lines_detail else "")
|
||||||
|
await self.__send_order_msg(lines, r)
|
||||||
|
|
||||||
|
async def __send_order_msg(self, lines: List[str], r: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Send status message.
|
||||||
|
"""
|
||||||
|
msg = ''
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
if line:
|
||||||
|
if (len(msg) + len(line) + 1) < MAX_MESSAGE_LENGTH:
|
||||||
|
msg += line + '\n'
|
||||||
|
else:
|
||||||
|
await self._send_msg(msg.format(**r))
|
||||||
|
msg = "*Order List for Trade #*`{trade_id}` - continued\n" + line + '\n'
|
||||||
|
|
||||||
|
await self._send_msg(msg.format(**r))
|
||||||
|
|
||||||
@authorized_only
|
@authorized_only
|
||||||
async def _status(self, update: Update, context: CallbackContext) -> None:
|
async def _status(self, update: Update, context: CallbackContext) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -652,9 +694,6 @@ class Telegram(RPCHandler):
|
|||||||
"*Open Order:* `{open_orders}`"
|
"*Open Order:* `{open_orders}`"
|
||||||
+ ("- `{exit_order_status}`" if r['exit_order_status'] else ""))
|
+ ("- `{exit_order_status}`" if r['exit_order_status'] else ""))
|
||||||
|
|
||||||
lines_detail = self._prepare_order_details(
|
|
||||||
r['orders'], r['quote_currency'], r['is_open'])
|
|
||||||
lines.extend(lines_detail if lines_detail else "")
|
|
||||||
await self.__send_status_msg(lines, r)
|
await self.__send_status_msg(lines, r)
|
||||||
|
|
||||||
async def __send_status_msg(self, lines: List[str], r: Dict[str, Any]) -> None:
|
async def __send_status_msg(self, lines: List[str], r: Dict[str, Any]) -> None:
|
||||||
@@ -1149,12 +1188,19 @@ class Telegram(RPCHandler):
|
|||||||
async def _force_enter_inline(self, update: Update, _: CallbackContext) -> None:
|
async def _force_enter_inline(self, update: Update, _: CallbackContext) -> None:
|
||||||
if update.callback_query:
|
if update.callback_query:
|
||||||
query = update.callback_query
|
query = update.callback_query
|
||||||
if query.data and '_||_' in query.data:
|
if query.data and '__' in query.data:
|
||||||
pair, side = query.data.split('_||_')
|
# Input data is "force_enter__<pair|cancel>_<side>"
|
||||||
order_side = SignalDirection(side)
|
payload = query.data.split("__")[1]
|
||||||
await query.answer()
|
if payload == 'cancel':
|
||||||
await query.edit_message_text(text=f"Manually entering {order_side} for {pair}")
|
await query.answer()
|
||||||
await self._force_enter_action(pair, None, order_side)
|
await query.edit_message_text(text="Force enter canceled.")
|
||||||
|
return
|
||||||
|
if payload and '_||_' in payload:
|
||||||
|
pair, side = payload.split('_||_')
|
||||||
|
order_side = SignalDirection(side)
|
||||||
|
await query.answer()
|
||||||
|
await query.edit_message_text(text=f"Manually entering {order_side} for {pair}")
|
||||||
|
await self._force_enter_action(pair, None, order_side)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _layout_inline_keyboard(
|
def _layout_inline_keyboard(
|
||||||
@@ -1183,12 +1229,14 @@ class Telegram(RPCHandler):
|
|||||||
else:
|
else:
|
||||||
whitelist = self._rpc._rpc_whitelist()['whitelist']
|
whitelist = self._rpc._rpc_whitelist()['whitelist']
|
||||||
pair_buttons = [
|
pair_buttons = [
|
||||||
InlineKeyboardButton(text=pair, callback_data=f"{pair}_||_{order_side}")
|
InlineKeyboardButton(
|
||||||
for pair in sorted(whitelist)
|
text=pair, callback_data=f"force_enter__{pair}_||_{order_side}"
|
||||||
|
) for pair in sorted(whitelist)
|
||||||
]
|
]
|
||||||
buttons_aligned = self._layout_inline_keyboard(pair_buttons)
|
buttons_aligned = self._layout_inline_keyboard(pair_buttons)
|
||||||
|
|
||||||
buttons_aligned.append([InlineKeyboardButton(text='Cancel', callback_data='cancel')])
|
buttons_aligned.append([InlineKeyboardButton(text='Cancel',
|
||||||
|
callback_data='force_enter__cancel')])
|
||||||
await self._send_msg(msg="Which pair?",
|
await self._send_msg(msg="Which pair?",
|
||||||
keyboard=buttons_aligned,
|
keyboard=buttons_aligned,
|
||||||
query=update.callback_query)
|
query=update.callback_query)
|
||||||
@@ -1369,7 +1417,7 @@ class Telegram(RPCHandler):
|
|||||||
stat_line = (
|
stat_line = (
|
||||||
f"{i+1}.\t <code>{trade['mix_tag']}\t"
|
f"{i+1}.\t <code>{trade['mix_tag']}\t"
|
||||||
f"{round_coin_value(trade['profit_abs'], self._config['stake_currency'])} "
|
f"{round_coin_value(trade['profit_abs'], self._config['stake_currency'])} "
|
||||||
f"({trade['profit']:.2%}) "
|
f"({trade['profit_ratio']:.2%}) "
|
||||||
f"({trade['count']})</code>\n")
|
f"({trade['count']})</code>\n")
|
||||||
|
|
||||||
if len(output + stat_line) >= MAX_MESSAGE_LENGTH:
|
if len(output + stat_line) >= MAX_MESSAGE_LENGTH:
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ class Webhook(RPCHandler):
|
|||||||
valuedict = self._get_value_dict(msg)
|
valuedict = self._get_value_dict(msg)
|
||||||
|
|
||||||
if not valuedict:
|
if not valuedict:
|
||||||
logger.info("Message type '%s' not configured for webhooks", msg['type'])
|
logger.debug("Message type '%s' not configured for webhooks", msg['type'])
|
||||||
return
|
return
|
||||||
|
|
||||||
payload = {key: value.format(**msg) for (key, value) in valuedict.items()}
|
payload = {key: value.format(**msg) for (key, value) in valuedict.items()}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Any, Callable, Optional, Union
|
from typing import Any, Callable, Dict, Optional, Union
|
||||||
|
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
@@ -38,17 +38,18 @@ def informative(timeframe: str, asset: str = '',
|
|||||||
|
|
||||||
:param timeframe: Informative timeframe. Must always be equal or higher than strategy timeframe.
|
:param timeframe: Informative timeframe. Must always be equal or higher than strategy timeframe.
|
||||||
:param asset: Informative asset, for example BTC, BTC/USDT, ETH/BTC. Do not specify to use
|
:param asset: Informative asset, for example BTC, BTC/USDT, ETH/BTC. Do not specify to use
|
||||||
current pair.
|
current pair. Also supports limited pair format strings (see below)
|
||||||
:param fmt: Column format (str) or column formatter (callable(name, asset, timeframe)). When not
|
:param fmt: Column format (str) or column formatter (callable(name, asset, timeframe)). When not
|
||||||
specified, defaults to:
|
specified, defaults to:
|
||||||
* {base}_{quote}_{column}_{timeframe} if asset is specified.
|
* {base}_{quote}_{column}_{timeframe} if asset is specified.
|
||||||
* {column}_{timeframe} if asset is not specified.
|
* {column}_{timeframe} if asset is not specified.
|
||||||
Format string supports these format variables:
|
Pair format supports these format variables:
|
||||||
* {asset} - full name of the asset, for example 'BTC/USDT'.
|
|
||||||
* {base} - base currency in lower case, for example 'eth'.
|
* {base} - base currency in lower case, for example 'eth'.
|
||||||
* {BASE} - same as {base}, except in upper case.
|
* {BASE} - same as {base}, except in upper case.
|
||||||
* {quote} - quote currency in lower case, for example 'usdt'.
|
* {quote} - quote currency in lower case, for example 'usdt'.
|
||||||
* {QUOTE} - same as {quote}, except in upper case.
|
* {QUOTE} - same as {quote}, except in upper case.
|
||||||
|
Format string additionally supports this variables.
|
||||||
|
* {asset} - full name of the asset, for example 'BTC/USDT'.
|
||||||
* {column} - name of dataframe column.
|
* {column} - name of dataframe column.
|
||||||
* {timeframe} - timeframe of informative dataframe.
|
* {timeframe} - timeframe of informative dataframe.
|
||||||
:param ffill: ffill dataframe after merging informative pair.
|
:param ffill: ffill dataframe after merging informative pair.
|
||||||
@@ -68,9 +69,25 @@ def informative(timeframe: str, asset: str = '',
|
|||||||
return decorator
|
return decorator
|
||||||
|
|
||||||
|
|
||||||
def _format_pair_name(config, pair: str) -> str:
|
def __get_pair_formats(market: Optional[Dict[str, Any]]) -> Dict[str, str]:
|
||||||
return pair.format(stake_currency=config['stake_currency'],
|
if not market:
|
||||||
stake=config['stake_currency']).upper()
|
return {}
|
||||||
|
base = market['base']
|
||||||
|
quote = market['quote']
|
||||||
|
return {
|
||||||
|
'base': base.lower(),
|
||||||
|
'BASE': base.upper(),
|
||||||
|
'quote': quote.lower(),
|
||||||
|
'QUOTE': quote.upper(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _format_pair_name(config, pair: str, market: Optional[Dict[str, Any]] = None) -> str:
|
||||||
|
return pair.format(
|
||||||
|
stake_currency=config['stake_currency'],
|
||||||
|
stake=config['stake_currency'],
|
||||||
|
**__get_pair_formats(market),
|
||||||
|
).upper()
|
||||||
|
|
||||||
|
|
||||||
def _create_and_merge_informative_pair(strategy, dataframe: DataFrame, metadata: dict,
|
def _create_and_merge_informative_pair(strategy, dataframe: DataFrame, metadata: dict,
|
||||||
@@ -85,7 +102,8 @@ def _create_and_merge_informative_pair(strategy, dataframe: DataFrame, metadata:
|
|||||||
|
|
||||||
if asset:
|
if asset:
|
||||||
# Insert stake currency if needed.
|
# Insert stake currency if needed.
|
||||||
asset = _format_pair_name(config, asset)
|
market1 = strategy.dp.market(metadata['pair'])
|
||||||
|
asset = _format_pair_name(config, asset, market1)
|
||||||
else:
|
else:
|
||||||
# Not specifying an asset will define informative dataframe for current pair.
|
# Not specifying an asset will define informative dataframe for current pair.
|
||||||
asset = metadata['pair']
|
asset = metadata['pair']
|
||||||
@@ -93,8 +111,6 @@ def _create_and_merge_informative_pair(strategy, dataframe: DataFrame, metadata:
|
|||||||
market = strategy.dp.market(asset)
|
market = strategy.dp.market(asset)
|
||||||
if market is None:
|
if market is None:
|
||||||
raise OperationalException(f'Market {asset} is not available.')
|
raise OperationalException(f'Market {asset} is not available.')
|
||||||
base = market['base']
|
|
||||||
quote = market['quote']
|
|
||||||
|
|
||||||
# Default format. This optimizes for the common case: informative pairs using same stake
|
# Default format. This optimizes for the common case: informative pairs using same stake
|
||||||
# currency. When quote currency matches stake currency, column name will omit base currency.
|
# currency. When quote currency matches stake currency, column name will omit base currency.
|
||||||
@@ -117,10 +133,7 @@ def _create_and_merge_informative_pair(strategy, dataframe: DataFrame, metadata:
|
|||||||
formatter = fmt.format # A default string formatter.
|
formatter = fmt.format # A default string formatter.
|
||||||
|
|
||||||
fmt_args = {
|
fmt_args = {
|
||||||
'BASE': base.upper(),
|
**__get_pair_formats(market),
|
||||||
'QUOTE': quote.upper(),
|
|
||||||
'base': base.lower(),
|
|
||||||
'quote': quote.lower(),
|
|
||||||
'asset': asset,
|
'asset': asset,
|
||||||
'timeframe': timeframe,
|
'timeframe': timeframe,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -756,12 +756,23 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
candle_type = (inf_data.candle_type if inf_data.candle_type
|
candle_type = (inf_data.candle_type if inf_data.candle_type
|
||||||
else self.config.get('candle_type_def', CandleType.SPOT))
|
else self.config.get('candle_type_def', CandleType.SPOT))
|
||||||
if inf_data.asset:
|
if inf_data.asset:
|
||||||
pair_tf = (
|
if any(s in inf_data.asset for s in ("{BASE}", "{base}")):
|
||||||
_format_pair_name(self.config, inf_data.asset),
|
for pair in self.dp.current_whitelist():
|
||||||
inf_data.timeframe,
|
|
||||||
candle_type,
|
pair_tf = (
|
||||||
)
|
_format_pair_name(self.config, inf_data.asset, self.dp.market(pair)),
|
||||||
informative_pairs.append(pair_tf)
|
inf_data.timeframe,
|
||||||
|
candle_type,
|
||||||
|
)
|
||||||
|
informative_pairs.append(pair_tf)
|
||||||
|
|
||||||
|
else:
|
||||||
|
pair_tf = (
|
||||||
|
_format_pair_name(self.config, inf_data.asset),
|
||||||
|
inf_data.timeframe,
|
||||||
|
candle_type,
|
||||||
|
)
|
||||||
|
informative_pairs.append(pair_tf)
|
||||||
else:
|
else:
|
||||||
for pair in self.dp.current_whitelist():
|
for pair in self.dp.current_whitelist():
|
||||||
informative_pairs.append((pair, inf_data.timeframe, candle_type))
|
informative_pairs.append((pair, inf_data.timeframe, candle_type))
|
||||||
@@ -1006,7 +1017,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
exit_ = latest.get(SignalType.EXIT_LONG.value, 0) == 1
|
exit_ = latest.get(SignalType.EXIT_LONG.value, 0) == 1
|
||||||
exit_tag = latest.get(SignalTagType.EXIT_TAG.value, None)
|
exit_tag = latest.get(SignalTagType.EXIT_TAG.value, None)
|
||||||
# Tags can be None, which does not resolve to False.
|
# Tags can be None, which does not resolve to False.
|
||||||
exit_tag = exit_tag if isinstance(exit_tag, str) else None
|
exit_tag = exit_tag if isinstance(exit_tag, str) and exit_tag != 'nan' else None
|
||||||
|
|
||||||
logger.debug(f"exit-trigger: {latest['date']} (pair={pair}) "
|
logger.debug(f"exit-trigger: {latest['date']} (pair={pair}) "
|
||||||
f"enter={enter} exit={exit_}")
|
f"enter={enter} exit={exit_}")
|
||||||
@@ -1038,17 +1049,17 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
exit_short = latest.get(SignalType.EXIT_SHORT.value, 0) == 1
|
exit_short = latest.get(SignalType.EXIT_SHORT.value, 0) == 1
|
||||||
|
|
||||||
enter_signal: Optional[SignalDirection] = None
|
enter_signal: Optional[SignalDirection] = None
|
||||||
enter_tag_value: Optional[str] = None
|
enter_tag: Optional[str] = None
|
||||||
if enter_long == 1 and not any([exit_long, enter_short]):
|
if enter_long == 1 and not any([exit_long, enter_short]):
|
||||||
enter_signal = SignalDirection.LONG
|
enter_signal = SignalDirection.LONG
|
||||||
enter_tag_value = latest.get(SignalTagType.ENTER_TAG.value, None)
|
enter_tag = latest.get(SignalTagType.ENTER_TAG.value, None)
|
||||||
if (self.config.get('trading_mode', TradingMode.SPOT) != TradingMode.SPOT
|
if (self.config.get('trading_mode', TradingMode.SPOT) != TradingMode.SPOT
|
||||||
and self.can_short
|
and self.can_short
|
||||||
and enter_short == 1 and not any([exit_short, enter_long])):
|
and enter_short == 1 and not any([exit_short, enter_long])):
|
||||||
enter_signal = SignalDirection.SHORT
|
enter_signal = SignalDirection.SHORT
|
||||||
enter_tag_value = latest.get(SignalTagType.ENTER_TAG.value, None)
|
enter_tag = latest.get(SignalTagType.ENTER_TAG.value, None)
|
||||||
|
|
||||||
enter_tag_value = enter_tag_value if isinstance(enter_tag_value, str) else None
|
enter_tag = enter_tag if isinstance(enter_tag, str) and enter_tag != 'nan' else None
|
||||||
|
|
||||||
timeframe_seconds = timeframe_to_seconds(timeframe)
|
timeframe_seconds = timeframe_to_seconds(timeframe)
|
||||||
|
|
||||||
@@ -1058,11 +1069,11 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
timeframe_seconds=timeframe_seconds,
|
timeframe_seconds=timeframe_seconds,
|
||||||
enter=bool(enter_signal)
|
enter=bool(enter_signal)
|
||||||
):
|
):
|
||||||
return None, enter_tag_value
|
return None, enter_tag
|
||||||
|
|
||||||
logger.debug(f"entry trigger: {latest['date']} (pair={pair}) "
|
logger.debug(f"entry trigger: {latest['date']} (pair={pair}) "
|
||||||
f"enter={enter_long} enter_tag_value={enter_tag_value}")
|
f"enter={enter_long} enter_tag_value={enter_tag}")
|
||||||
return enter_signal, enter_tag_value
|
return enter_signal, enter_tag
|
||||||
|
|
||||||
def ignore_expired_candle(
|
def ignore_expired_candle(
|
||||||
self,
|
self,
|
||||||
@@ -1244,10 +1255,6 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
and trade.liquidation_price <= (high or current_rate)
|
and trade.liquidation_price <= (high or current_rate)
|
||||||
and trade.is_short)
|
and trade.is_short)
|
||||||
|
|
||||||
if (liq_higher_long or liq_lower_short):
|
|
||||||
logger.debug(f"{trade.pair} - Liquidation price hit. exit_type=ExitType.LIQUIDATION")
|
|
||||||
return ExitCheckTuple(exit_type=ExitType.LIQUIDATION)
|
|
||||||
|
|
||||||
# evaluate if the stoploss was hit if stoploss is not on exchange
|
# evaluate if the stoploss was hit if stoploss is not on exchange
|
||||||
# in Dry-Run, this handles stoploss logic as well, as the logic will not be different to
|
# in Dry-Run, this handles stoploss logic as well, as the logic will not be different to
|
||||||
# regular stoploss handling.
|
# regular stoploss handling.
|
||||||
@@ -1268,6 +1275,10 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
|
|
||||||
return ExitCheckTuple(exit_type=exit_type)
|
return ExitCheckTuple(exit_type=exit_type)
|
||||||
|
|
||||||
|
if (liq_higher_long or liq_lower_short):
|
||||||
|
logger.debug(f"{trade.pair} - Liquidation price hit. exit_type=ExitType.LIQUIDATION")
|
||||||
|
return ExitCheckTuple(exit_type=ExitType.LIQUIDATION)
|
||||||
|
|
||||||
return ExitCheckTuple(exit_type=ExitType.NONE)
|
return ExitCheckTuple(exit_type=ExitType.NONE)
|
||||||
|
|
||||||
def min_roi_reached_entry(self, trade_dur: int) -> Tuple[Optional[int], Optional[float]]:
|
def min_roi_reached_entry(self, trade_dur: int) -> Tuple[Optional[int], Optional[float]]:
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ def merge_informative_pair(dataframe: pd.DataFrame, informative: pd.DataFrame,
|
|||||||
:return: Merged dataframe
|
:return: Merged dataframe
|
||||||
:raise: ValueError if the secondary timeframe is shorter than the dataframe timeframe
|
:raise: ValueError if the secondary timeframe is shorter than the dataframe timeframe
|
||||||
"""
|
"""
|
||||||
|
informative = informative.copy()
|
||||||
minutes_inf = timeframe_to_minutes(timeframe_inf)
|
minutes_inf = timeframe_to_minutes(timeframe_inf)
|
||||||
minutes = timeframe_to_minutes(timeframe)
|
minutes = timeframe_to_minutes(timeframe)
|
||||||
if minutes == minutes_inf:
|
if minutes == minutes_inf:
|
||||||
@@ -46,10 +46,16 @@ def merge_informative_pair(dataframe: pd.DataFrame, informative: pd.DataFrame,
|
|||||||
# Subtract "small" timeframe so merging is not delayed by 1 small candle
|
# Subtract "small" timeframe so merging is not delayed by 1 small candle
|
||||||
# Detailed explanation in https://github.com/freqtrade/freqtrade/issues/4073
|
# Detailed explanation in https://github.com/freqtrade/freqtrade/issues/4073
|
||||||
if not informative.empty:
|
if not informative.empty:
|
||||||
informative['date_merge'] = (
|
if timeframe_inf == '1M':
|
||||||
informative[date_column] + pd.to_timedelta(minutes_inf, 'm') -
|
informative['date_merge'] = (
|
||||||
pd.to_timedelta(minutes, 'm')
|
(informative[date_column] + pd.offsets.MonthBegin(1))
|
||||||
)
|
- pd.to_timedelta(minutes, 'm')
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
informative['date_merge'] = (
|
||||||
|
informative[date_column] + pd.to_timedelta(minutes_inf, 'm') -
|
||||||
|
pd.to_timedelta(minutes, 'm')
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
informative['date_merge'] = informative[date_column]
|
informative['date_merge'] = informative[date_column]
|
||||||
else:
|
else:
|
||||||
@@ -80,9 +86,6 @@ def merge_informative_pair(dataframe: pd.DataFrame, informative: pd.DataFrame,
|
|||||||
right_on=date_merge, how='left')
|
right_on=date_merge, how='left')
|
||||||
dataframe = dataframe.drop(date_merge, axis=1)
|
dataframe = dataframe.drop(date_merge, axis=1)
|
||||||
|
|
||||||
# if ffill:
|
|
||||||
# dataframe = dataframe.ffill()
|
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import talib.abstract as ta
|
|||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
from technical import qtpylib
|
from technical import qtpylib
|
||||||
|
|
||||||
from freqtrade.strategy import CategoricalParameter, IStrategy
|
from freqtrade.strategy import IStrategy
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -45,11 +45,6 @@ class FreqaiExampleStrategy(IStrategy):
|
|||||||
startup_candle_count: int = 40
|
startup_candle_count: int = 40
|
||||||
can_short = True
|
can_short = True
|
||||||
|
|
||||||
std_dev_multiplier_buy = CategoricalParameter(
|
|
||||||
[0.75, 1, 1.25, 1.5, 1.75], default=1.25, space="buy", optimize=True)
|
|
||||||
std_dev_multiplier_sell = CategoricalParameter(
|
|
||||||
[0.75, 1, 1.25, 1.5, 1.75], space="sell", default=1.25, optimize=True)
|
|
||||||
|
|
||||||
def feature_engineering_expand_all(self, dataframe: DataFrame, period: int,
|
def feature_engineering_expand_all(self, dataframe: DataFrame, period: int,
|
||||||
metadata: Dict, **kwargs) -> DataFrame:
|
metadata: Dict, **kwargs) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
@@ -239,21 +234,13 @@ class FreqaiExampleStrategy(IStrategy):
|
|||||||
|
|
||||||
dataframe = self.freqai.start(dataframe, metadata, self)
|
dataframe = self.freqai.start(dataframe, metadata, self)
|
||||||
|
|
||||||
for val in self.std_dev_multiplier_buy.range:
|
|
||||||
dataframe[f'target_roi_{val}'] = (
|
|
||||||
dataframe["&-s_close_mean"] + dataframe["&-s_close_std"] * val
|
|
||||||
)
|
|
||||||
for val in self.std_dev_multiplier_sell.range:
|
|
||||||
dataframe[f'sell_roi_{val}'] = (
|
|
||||||
dataframe["&-s_close_mean"] - dataframe["&-s_close_std"] * val
|
|
||||||
)
|
|
||||||
return dataframe
|
return dataframe
|
||||||
|
|
||||||
def populate_entry_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
|
def populate_entry_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
|
||||||
enter_long_conditions = [
|
enter_long_conditions = [
|
||||||
df["do_predict"] == 1,
|
df["do_predict"] == 1,
|
||||||
df["&-s_close"] > df[f"target_roi_{self.std_dev_multiplier_buy.value}"],
|
df["&-s_close"] > 0.01,
|
||||||
]
|
]
|
||||||
|
|
||||||
if enter_long_conditions:
|
if enter_long_conditions:
|
||||||
@@ -263,7 +250,7 @@ class FreqaiExampleStrategy(IStrategy):
|
|||||||
|
|
||||||
enter_short_conditions = [
|
enter_short_conditions = [
|
||||||
df["do_predict"] == 1,
|
df["do_predict"] == 1,
|
||||||
df["&-s_close"] < df[f"sell_roi_{self.std_dev_multiplier_sell.value}"],
|
df["&-s_close"] < -0.01,
|
||||||
]
|
]
|
||||||
|
|
||||||
if enter_short_conditions:
|
if enter_short_conditions:
|
||||||
@@ -276,23 +263,20 @@ class FreqaiExampleStrategy(IStrategy):
|
|||||||
def populate_exit_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
|
def populate_exit_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
|
||||||
exit_long_conditions = [
|
exit_long_conditions = [
|
||||||
df["do_predict"] == 1,
|
df["do_predict"] == 1,
|
||||||
df["&-s_close"] < df[f"sell_roi_{self.std_dev_multiplier_sell.value}"] * 0.25,
|
df["&-s_close"] < 0
|
||||||
]
|
]
|
||||||
if exit_long_conditions:
|
if exit_long_conditions:
|
||||||
df.loc[reduce(lambda x, y: x & y, exit_long_conditions), "exit_long"] = 1
|
df.loc[reduce(lambda x, y: x & y, exit_long_conditions), "exit_long"] = 1
|
||||||
|
|
||||||
exit_short_conditions = [
|
exit_short_conditions = [
|
||||||
df["do_predict"] == 1,
|
df["do_predict"] == 1,
|
||||||
df["&-s_close"] > df[f"target_roi_{self.std_dev_multiplier_buy.value}"] * 0.25,
|
df["&-s_close"] > 0
|
||||||
]
|
]
|
||||||
if exit_short_conditions:
|
if exit_short_conditions:
|
||||||
df.loc[reduce(lambda x, y: x & y, exit_short_conditions), "exit_short"] = 1
|
df.loc[reduce(lambda x, y: x & y, exit_short_conditions), "exit_short"] = 1
|
||||||
|
|
||||||
return df
|
return df
|
||||||
|
|
||||||
def get_ticker_indicator(self):
|
|
||||||
return int(self.config["timeframe"][:-1])
|
|
||||||
|
|
||||||
def confirm_trade_entry(
|
def confirm_trade_entry(
|
||||||
self,
|
self,
|
||||||
pair: str,
|
pair: str,
|
||||||
|
|||||||
@@ -39,7 +39,7 @@
|
|||||||
},
|
},
|
||||||
{{ exchange | indent(4) }},
|
{{ exchange | indent(4) }},
|
||||||
"pairlists": [
|
"pairlists": [
|
||||||
{{ '{"method": "StaticPairList"}' if exchange_name == 'bittrex' else volume_pairlist }}
|
{{ volume_pairlist }}
|
||||||
],
|
],
|
||||||
"telegram": {
|
"telegram": {
|
||||||
"enabled": {{ telegram | lower }},
|
"enabled": {{ telegram | lower }},
|
||||||
|
|||||||
+1
-1
@@ -226,7 +226,7 @@ def crossed(series1, series2, direction=None):
|
|||||||
series1.shift(1) >= series2.shift(1)))
|
series1.shift(1) >= series2.shift(1)))
|
||||||
|
|
||||||
if direction is None:
|
if direction is None:
|
||||||
return above or below
|
return above | below
|
||||||
|
|
||||||
return above if direction == "above" else below
|
return above if direction == "above" else below
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from copy import deepcopy
|
|||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import Dict, NamedTuple, Optional
|
from typing import Dict, NamedTuple, Optional
|
||||||
|
|
||||||
from freqtrade.constants import UNLIMITED_STAKE_AMOUNT, Config
|
from freqtrade.constants import UNLIMITED_STAKE_AMOUNT, Config, IntOrInf
|
||||||
from freqtrade.enums import RunMode, TradingMode
|
from freqtrade.enums import RunMode, TradingMode
|
||||||
from freqtrade.exceptions import DependencyException
|
from freqtrade.exceptions import DependencyException
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
@@ -262,15 +262,15 @@ class Wallets:
|
|||||||
return min(self.get_total_stake_amount() - Trade.total_open_trades_stakes(), free)
|
return min(self.get_total_stake_amount() - Trade.total_open_trades_stakes(), free)
|
||||||
|
|
||||||
def _calculate_unlimited_stake_amount(self, available_amount: float,
|
def _calculate_unlimited_stake_amount(self, available_amount: float,
|
||||||
val_tied_up: float) -> float:
|
val_tied_up: float, max_open_trades: IntOrInf) -> float:
|
||||||
"""
|
"""
|
||||||
Calculate stake amount for "unlimited" stake amount
|
Calculate stake amount for "unlimited" stake amount
|
||||||
:return: 0 if max number of trades reached, else stake_amount to use.
|
:return: 0 if max number of trades reached, else stake_amount to use.
|
||||||
"""
|
"""
|
||||||
if self._config['max_open_trades'] == 0:
|
if max_open_trades == 0:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
possible_stake = (available_amount + val_tied_up) / self._config['max_open_trades']
|
possible_stake = (available_amount + val_tied_up) / max_open_trades
|
||||||
# Theoretical amount can be above available amount - therefore limit to available amount!
|
# Theoretical amount can be above available amount - therefore limit to available amount!
|
||||||
return min(possible_stake, available_amount)
|
return min(possible_stake, available_amount)
|
||||||
|
|
||||||
@@ -298,7 +298,8 @@ class Wallets:
|
|||||||
|
|
||||||
return stake_amount
|
return stake_amount
|
||||||
|
|
||||||
def get_trade_stake_amount(self, pair: str, edge=None, update: bool = True) -> float:
|
def get_trade_stake_amount(
|
||||||
|
self, pair: str, max_open_trades: IntOrInf, edge=None, update: bool = True) -> float:
|
||||||
"""
|
"""
|
||||||
Calculate stake amount for the trade
|
Calculate stake amount for the trade
|
||||||
:return: float: Stake amount
|
:return: float: Stake amount
|
||||||
@@ -322,7 +323,7 @@ class Wallets:
|
|||||||
stake_amount = self._config['stake_amount']
|
stake_amount = self._config['stake_amount']
|
||||||
if stake_amount == UNLIMITED_STAKE_AMOUNT:
|
if stake_amount == UNLIMITED_STAKE_AMOUNT:
|
||||||
stake_amount = self._calculate_unlimited_stake_amount(
|
stake_amount = self._calculate_unlimited_stake_amount(
|
||||||
available_amount, val_tied_up)
|
available_amount, val_tied_up, max_open_trades)
|
||||||
|
|
||||||
return self._check_available_stake_amount(stake_amount, available_amount)
|
return self._check_available_stake_amount(stake_amount, available_amount)
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,55 @@
|
|||||||
requires = ["setuptools >= 64.0.0", "wheel"]
|
requires = ["setuptools >= 64.0.0", "wheel"]
|
||||||
build-backend = "setuptools.build_meta"
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "freqtrade"
|
||||||
|
dynamic = ["version", "dependencies", "optional-dependencies"]
|
||||||
|
|
||||||
|
authors = [
|
||||||
|
{name = "Freqtrade Team"},
|
||||||
|
{name = "Freqtrade Team", email = "freqtrade@protonmail.com"},
|
||||||
|
]
|
||||||
|
|
||||||
|
description = "Freqtrade - Crypto Trading Bot"
|
||||||
|
readme = "README.md"
|
||||||
|
requires-python = ">=3.9"
|
||||||
|
license = {text = "GPLv3"}
|
||||||
|
# license = "GPLv3"
|
||||||
|
classifiers = [
|
||||||
|
"Environment :: Console",
|
||||||
|
"Intended Audience :: Science/Research",
|
||||||
|
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
|
||||||
|
"Programming Language :: Python :: 3.9",
|
||||||
|
"Programming Language :: Python :: 3.10",
|
||||||
|
"Programming Language :: Python :: 3.11",
|
||||||
|
"Operating System :: MacOS",
|
||||||
|
"Operating System :: Unix",
|
||||||
|
"Topic :: Office/Business :: Financial :: Investment",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
[project.urls]
|
||||||
|
Homepage = "https://github.com/freqtrade/freqtrade"
|
||||||
|
Documentation = "https://freqtrade.io"
|
||||||
|
"Bug Tracker" = "https://github.com/freqtrade/freqtrade/issues"
|
||||||
|
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
freqtrade = "freqtrade.main:main"
|
||||||
|
|
||||||
|
[tool.setuptools]
|
||||||
|
include-package-data = true
|
||||||
|
zip-safe = false
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
where = ["."]
|
||||||
|
include = ["freqtrade*"]
|
||||||
|
exclude = ["tests", "tests.*"]
|
||||||
|
namespaces = true
|
||||||
|
|
||||||
|
[tool.setuptools.dynamic]
|
||||||
|
version = {attr = "freqtrade.__version__"}
|
||||||
|
|
||||||
[tool.black]
|
[tool.black]
|
||||||
line-length = 100
|
line-length = 100
|
||||||
exclude = '''
|
exclude = '''
|
||||||
@@ -31,6 +80,7 @@ skip_glob = ["**/.env*", "**/env/*", "**/.venv/*", "**/docs/*", "**/user_data/*"
|
|||||||
|
|
||||||
[tool.pytest.ini_options]
|
[tool.pytest.ini_options]
|
||||||
asyncio_mode = "auto"
|
asyncio_mode = "auto"
|
||||||
|
addopts = "--dist loadscope"
|
||||||
|
|
||||||
[tool.mypy]
|
[tool.mypy]
|
||||||
ignore_missing_imports = true
|
ignore_missing_imports = true
|
||||||
@@ -82,9 +132,29 @@ extend-select = [
|
|||||||
# "TCH", # flake8-type-checking
|
# "TCH", # flake8-type-checking
|
||||||
"PTH", # flake8-use-pathlib
|
"PTH", # flake8-use-pathlib
|
||||||
]
|
]
|
||||||
|
extend-ignore = [
|
||||||
|
"E241", # Multiple spaces after comma
|
||||||
|
"E272", # Multiple spaces before keyword
|
||||||
|
"E221", # Multiple spaces before operator
|
||||||
|
]
|
||||||
|
|
||||||
[tool.ruff.mccabe]
|
[tool.ruff.mccabe]
|
||||||
max-complexity = 12
|
max-complexity = 12
|
||||||
|
|
||||||
[tool.ruff.per-file-ignores]
|
[tool.ruff.per-file-ignores]
|
||||||
"tests/*" = ["S"]
|
"tests/*" = ["S"]
|
||||||
|
|
||||||
|
[tool.flake8]
|
||||||
|
# Default from https://flake8.pycqa.org/en/latest/user/options.html#cmdoption-flake8-ignore
|
||||||
|
# minus E226
|
||||||
|
ignore = ["E121","E123","E126","E24","E704","W503","W504"]
|
||||||
|
max-line-length = 100
|
||||||
|
max-complexity = 12
|
||||||
|
exclude = [
|
||||||
|
".git",
|
||||||
|
"__pycache__",
|
||||||
|
".eggs",
|
||||||
|
"user_data",
|
||||||
|
".venv",
|
||||||
|
".env",
|
||||||
|
]
|
||||||
|
|||||||
+10
-9
@@ -7,24 +7,25 @@
|
|||||||
-r docs/requirements-docs.txt
|
-r docs/requirements-docs.txt
|
||||||
|
|
||||||
coveralls==3.3.1
|
coveralls==3.3.1
|
||||||
ruff==0.0.291
|
ruff==0.1.9
|
||||||
mypy==1.5.1
|
mypy==1.8.0
|
||||||
pre-commit==3.4.0
|
pre-commit==3.6.0
|
||||||
pytest==7.4.2
|
pytest==7.4.3
|
||||||
pytest-asyncio==0.21.1
|
pytest-asyncio==0.21.1
|
||||||
pytest-cov==4.1.0
|
pytest-cov==4.1.0
|
||||||
pytest-mock==3.11.1
|
pytest-mock==3.12.0
|
||||||
pytest-random-order==1.1.0
|
pytest-random-order==1.1.0
|
||||||
isort==5.12.0
|
pytest-xdist==3.5.0
|
||||||
|
isort==5.13.2
|
||||||
# For datetime mocking
|
# For datetime mocking
|
||||||
time-machine==2.13.0
|
time-machine==2.13.0
|
||||||
|
|
||||||
# Convert jupyter notebooks to markdown documents
|
# Convert jupyter notebooks to markdown documents
|
||||||
nbconvert==7.8.0
|
nbconvert==7.13.1
|
||||||
|
|
||||||
# mypy types
|
# mypy types
|
||||||
types-cachetools==5.3.0.6
|
types-cachetools==5.3.0.7
|
||||||
types-filelock==3.2.7
|
types-filelock==3.2.7
|
||||||
types-requests==2.31.0.4
|
types-requests==2.31.0.10
|
||||||
types-tabulate==0.9.0.3
|
types-tabulate==0.9.0.3
|
||||||
types-python-dateutil==2.8.19.14
|
types-python-dateutil==2.8.19.14
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user