Elffuss BraidHub

kikocis/freqtrade public

develop · 17.2 KiBRenderedRawPermalink
1# Development Help
2
3This page is intended for developers of Freqtrade, people who want to contribute to the Freqtrade codebase or documentation, or people who want to understand the source code of the application they're running.
4
5All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We [track issues](https://github.com/freqtrade/freqtrade/issues) on [GitHub](https://github.com) and also have a dev channel on [discord](https://discord.gg/MA9v74M) or [slack](https://join.slack.com/t/highfrequencybot/shared_invite/zt-mm786y93-Fxo37glxMY9g8OQC5AoOIw) where you can ask questions.
6
7## Documentation
8
9Documentation is available at [https://freqtrade.io](https://www.freqtrade.io/) and needs to be provided with every new feature PR.
10
11Special fields for the documentation (like Note boxes, ...) can be found [here](https://squidfunk.github.io/mkdocs-material/extensions/admonition/).
12
13To test the documentation locally use the following commands.
14
15``` bash
16pip install -r docs/requirements-docs.txt
17mkdocs serve
18```
19
20This will spin up a local server (usually on port 8000) so you can see if everything looks as you'd like it to.
21
22## Developer setup
23
24To configure a development environment, you can either use the provided [DevContainer](#devcontainer-setup), or use the `setup.sh` script and answer "y" when asked "Do you want to install dependencies for dev [y/N]? ".
25Alternatively (e.g. if your system is not supported by the setup.sh script), follow the manual installation process and run `pip3 install -e .[all]`.
26
27This will install all required tools for development, including `pytest`, `flake8`, `mypy`, and `coveralls`.
28
29### Devcontainer setup
30
31The fastest and easiest way to get started is to use [VSCode](https://code.visualstudio.com/) with the Remote container extension.
32This gives developers the ability to start the bot with all required dependencies *without* needing to install any freqtrade specific dependencies on your local machine.
33
34#### Devcontainer dependencies
35
36* [VSCode](https://code.visualstudio.com/)
37* [docker](https://docs.docker.com/install/)
38* [Remote container extension documentation](https://code.visualstudio.com/docs/remote)
39
40For more information about the [Remote container extension](https://code.visualstudio.com/docs/remote), best consult the documentation.
41
42### Tests
43
44New code should be covered by basic unittests. Depending on the complexity of the feature, Reviewers may request more in-depth unittests.
45If necessary, the Freqtrade team can assist and give guidance with writing good tests (however please don't expect anyone to write the tests for you).
46
47#### Checking log content in tests
48
49Freqtrade uses 2 main methods to check log content in tests, `log_has()` and `log_has_re()` (to check using regex, in case of dynamic log-messages).
50These are available from `conftest.py` and can be imported in any test module.
51
52A sample check looks as follows:
53
54``` python
55from tests.conftest import log_has, log_has_re
56
57def test_method_to_test(caplog):
58 method_to_test()
59
60 assert log_has("This event happened", caplog)
61 # Check regex with trailing number ...
62 assert log_has_re(r"This dynamic event happened and produced \d+", caplog)
63
64```
65
66## ErrorHandling
67
68Freqtrade Exceptions all inherit from `FreqtradeException`.
69This general class of error should however not be used directly. Instead, multiple specialized sub-Exceptions exist.
70
71Below is an outline of exception inheritance hierarchy:
72
73```
74+ FreqtradeException
75|
76+---+ OperationalException
77|
78+---+ DependencyException
79| |
80| +---+ PricingError
81| |
82| +---+ ExchangeError
83| |
84| +---+ TemporaryError
85| |
86| +---+ DDosProtection
87| |
88| +---+ InvalidOrderException
89| |
90| +---+ RetryableOrderError
91| |
92| +---+ InsufficientFundsError
93|
94+---+ StrategyError
95```
96
97---
98
99## Plugins
100
101### Pairlists
102
103You have a great idea for a new pair selection algorithm you would like to try out? Great.
104Hopefully you also want to contribute this back upstream.
105
106Whatever your motivations are - This should get you off the ground in trying to develop a new Pairlist Handler.
107
108First of all, have a look at the [VolumePairList](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/pairlist/VolumePairList.py) Handler, and best copy this file with a name of your new Pairlist Handler.
109
110This is a simple Handler, which however serves as a good example on how to start developing.
111
112Next, modify the class-name of the Handler (ideally align this with the module filename).
113
114The base-class provides an instance of the exchange (`self._exchange`) the pairlist manager (`self._pairlistmanager`), as well as the main configuration (`self._config`), the pairlist dedicated configuration (`self._pairlistconfig`) and the absolute position within the list of pairlists.
115
116```python
117 self._exchange = exchange
118 self._pairlistmanager = pairlistmanager
119 self._config = config
120 self._pairlistconfig = pairlistconfig
121 self._pairlist_pos = pairlist_pos
122```
123
124!!! Tip
125 Don't forget to register your pairlist in `constants.py` under the variable `AVAILABLE_PAIRLISTS` - otherwise it will not be selectable.
126
127Now, let's step through the methods which require actions:
128
129#### Pairlist configuration
130
131Configuration for the chain of Pairlist Handlers is done in the bot configuration file in the element `"pairlists"`, an array of configuration parameters for each Pairlist Handlers in the chain.
132
133By convention, `"number_assets"` is used to specify the maximum number of pairs to keep in the pairlist. Please follow this to ensure a consistent user experience.
134
135Additional parameters can be configured as needed. For instance, `VolumePairList` uses `"sort_key"` to specify the sorting value - however feel free to specify whatever is necessary for your great algorithm to be successful and dynamic.
136
137#### short_desc
138
139Returns a description used for Telegram messages.
140
141This should contain the name of the Pairlist Handler, as well as a short description containing the number of assets. Please follow the format `"PairlistName - top/bottom X pairs"`.
142
143#### gen_pairlist
144
145Override this method if the Pairlist Handler can be used as the leading Pairlist Handler in the chain, defining the initial pairlist which is then handled by all Pairlist Handlers in the chain. Examples are `StaticPairList` and `VolumePairList`.
146
147This is called with each iteration of the bot (only if the Pairlist Handler is at the first location) - so consider implementing caching for compute/network heavy calculations.
148
149It must return the resulting pairlist (which may then be passed into the chain of Pairlist Handlers).
150
151Validations are optional, the parent class exposes a `_verify_blacklist(pairlist)` and `_whitelist_for_active_markets(pairlist)` to do default filtering. Use this if you limit your result to a certain number of pairs - so the end-result is not shorter than expected.
152
153#### filter_pairlist
154
155This method is called for each Pairlist Handler in the chain by the pairlist manager.
156
157This is called with each iteration of the bot - so consider implementing caching for compute/network heavy calculations.
158
159It gets passed a pairlist (which can be the result of previous pairlists) as well as `tickers`, a pre-fetched version of `get_tickers()`.
160
161The default implementation in the base class simply calls the `_validate_pair()` method for each pair in the pairlist, but you may override it. So you should either implement the `_validate_pair()` in your Pairlist Handler or override `filter_pairlist()` to do something else.
162
163If overridden, it must return the resulting pairlist (which may then be passed into the next Pairlist Handler in the chain).
164
165Validations are optional, the parent class exposes a `_verify_blacklist(pairlist)` and `_whitelist_for_active_markets(pairlist)` to do default filters. Use this if you limit your result to a certain number of pairs - so the end result is not shorter than expected.
166
167In `VolumePairList`, this implements different methods of sorting, does early validation so only the expected number of pairs is returned.
168
169##### sample
170
171``` python
172 def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
173 # Generate dynamic whitelist
174 pairs = self._calculate_pairlist(pairlist, tickers)
175 return pairs
176```
177
178### Protections
179
180Best read the [Protection documentation](plugins.md#protections) to understand protections.
181This Guide is directed towards Developers who want to develop a new protection.
182
183No protection should use datetime directly, but use the provided `date_now` variable for date calculations. This preserves the ability to backtest protections.
184
185!!! Tip "Writing a new Protection"
186 Best copy one of the existing Protections to have a good example.
187 Don't forget to register your protection in `constants.py` under the variable `AVAILABLE_PROTECTIONS` - otherwise it will not be selectable.
188
189#### Implementation of a new protection
190
191All Protection implementations must have `IProtection` as parent class.
192For that reason, they must implement the following methods:
193
194* `short_desc()`
195* `global_stop()`
196* `stop_per_pair()`.
197
198`global_stop()` and `stop_per_pair()` must return a ProtectionReturn tuple, which consists of:
199
200* lock pair - boolean
201* lock until - datetime - until when should the pair be locked (will be rounded up to the next new candle)
202* reason - string, used for logging and storage in the database
203
204The `until` portion should be calculated using the provided `calculate_lock_end()` method.
205
206All Protections should use `"stop_duration"` / `"stop_duration_candles"` to define how long a a pair (or all pairs) should be locked.
207The content of this is made available as `self._stop_duration` to the each Protection.
208
209If your protection requires a look-back period, please use `"lookback_period"` / `"lockback_period_candles"` to keep all protections aligned.
210
211#### Global vs. local stops
212
213Protections can have 2 different ways to stop trading for a limited :
214
215* Per pair (local)
216* For all Pairs (globally)
217
218##### Protections - per pair
219
220Protections that implement the per pair approach must set `has_local_stop=True`.
221The method `stop_per_pair()` will be called whenever a trade closed (sell order completed).
222
223##### Protections - global protection
224
225These Protections should do their evaluation across all pairs, and consequently will also lock all pairs from trading (called a global PairLock).
226Global protection must set `has_global_stop=True` to be evaluated for global stops.
227The method `global_stop()` will be called whenever a trade closed (sell order completed).
228
229##### Protections - calculating lock end time
230
231Protections should calculate the lock end time based on the last trade it considers.
232This avoids re-locking should the lookback-period be longer than the actual lock period.
233
234The `IProtection` parent class provides a helper method for this in `calculate_lock_end()`.
235
236---
237
238## Implement a new Exchange (WIP)
239
240!!! Note
241 This section is a Work in Progress and is not a complete guide on how to test a new exchange with Freqtrade.
242
243Most exchanges supported by CCXT should work out of the box.
244
245To quickly test the public endpoints of an exchange, add a configuration for your exchange to `test_ccxt_compat.py` and run these tests with `pytest --longrun tests/exchange/test_ccxt_compat.py`.
246Completing these tests successfully a good basis point (it's a requirement, actually), however these won't guarantee correct exchange functioning, as this only tests public endpoints, but no private endpoint (like generate order or similar).
247
248### Stoploss On Exchange
249
250Check if the new exchange supports Stoploss on Exchange orders through their API.
251
252Since CCXT does not provide unification for Stoploss On Exchange yet, we'll need to implement the exchange-specific parameters ourselves. Best look at `binance.py` for an example implementation of this. You'll need to dig through the documentation of the Exchange's API on how exactly this can be done. [CCXT Issues](https://github.com/ccxt/ccxt/issues) may also provide great help, since others may have implemented something similar for their projects.
253
254### Incomplete candles
255
256While fetching candle (OHLCV) data, we may end up getting incomplete candles (depending on the exchange).
257To demonstrate this, we'll use daily candles (`"1d"`) to keep things simple.
258We query the api (`ct.fetch_ohlcv()`) for the timeframe and look at the date of the last entry. If this entry changes or shows the date of a "incomplete" candle, then we should drop this since having incomplete candles is problematic because indicators assume that only complete candles are passed to them, and will generate a lot of false buy signals. By default, we're therefore removing the last candle assuming it's incomplete.
259
260To check how the new exchange behaves, you can use the following snippet:
261
262``` python
263import ccxt
264from datetime import datetime
265from freqtrade.data.converter import ohlcv_to_dataframe
266ct = ccxt.binance()
267timeframe = "1d"
268pair = "XLM/BTC" # Make sure to use a pair that exists on that exchange!
269raw = ct.fetch_ohlcv(pair, timeframe=timeframe)
270
271# convert to dataframe
272df1 = ohlcv_to_dataframe(raw, timeframe, pair=pair, drop_incomplete=False)
273
274print(df1.tail(1))
275print(datetime.utcnow())
276```
277
278``` output
279 date open high low close volume
280499 2019-06-08 00:00:00+00:00 0.000007 0.000007 0.000007 0.000007 26264344.0
2812019-06-09 12:30:27.873327
282```
283
284The output will show the last entry from the Exchange as well as the current UTC date.
285If the day shows the same day, then the last candle can be assumed as incomplete and should be dropped (leave the setting `"ohlcv_partial_candle"` from the exchange-class untouched / True). Otherwise, set `"ohlcv_partial_candle"` to `False` to not drop Candles (shown in the example above).
286Another way is to run this command multiple times in a row and observe if the volume is changing (while the date remains the same).
287
288## Updating example notebooks
289
290To keep the jupyter notebooks aligned with the documentation, the following should be ran after updating a example notebook.
291
292``` bash
293jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace freqtrade/templates/strategy_analysis_example.ipynb
294jupyter nbconvert --ClearOutputPreprocessor.enabled=True --to markdown freqtrade/templates/strategy_analysis_example.ipynb --stdout > docs/strategy_analysis_example.md
295```
296
297## Continuous integration
298
299This documents some decisions taken for the CI Pipeline.
300
301* CI runs on all OS variants, Linux (ubuntu), macOS and Windows.
302* Docker images are build for the branches `stable` and `develop`.
303* Docker images containing Plot dependencies are also available as `stable_plot` and `develop_plot`.
304* Raspberry PI Docker images are postfixed with `_pi` - so tags will be `:stable_pi` and `develop_pi`.
305* Docker images contain a file, `/freqtrade/freqtrade_commit` containing the commit this image is based of.
306* Full docker image rebuilds are run once a week via schedule.
307* Deployments run on ubuntu.
308* ta-lib binaries are contained in the build_helpers directory to avoid fails related to external unavailability.
309* All tests must pass for a PR to be merged to `stable` or `develop`.
310
311## Creating a release
312
313This part of the documentation is aimed at maintainers, and shows how to create a release.
314
315### Create release branch
316
317First, pick a commit that's about one week old (to not include latest additions to releases).
318
319``` bash
320# create new branch
321git checkout -b new_release <commitid>
322```
323
324Determine if crucial bugfixes have been made between this commit and the current state, and eventually cherry-pick these.
325
326* Merge the release branch (stable) into this branch.
327* 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.
328* Commit this part
329* push that branch to the remote and create a PR against the stable branch
330
331### Create changelog from git commits
332
333!!! Note
334 Make sure that the `stable` branch is up-to-date!
335
336``` bash
337# Needs to be done before merging / pulling that branch.
338git log --oneline --no-decorate --no-merges stable..new_release
339```
340
341To keep the release-log short, best wrap the full git changelog into a collapsible details section.
342
343```markdown
344<details>
345<summary>Expand full changelog</summary>
346
347... Full git changelog
348
349</details>
350```
351
352### Create github release / tag
353
354Once the PR against stable is merged (best right after merging):
355
356* Use the button "Draft a new release" in the Github UI (subsection releases).
357* Use the version-number specified as tag.
358* Use "stable" as reference (this step comes after the above PR is merged).
359* Use the above changelog as release comment (as codeblock)
360
361## Releases
362
363### pypi
364
365!!! Note
366 This process is now automated as part of Github Actions.
367
368To create a pypi release, please run the following commands:
369
370Additional requirement: `wheel`, `twine` (for uploading), account on pypi with proper permissions.
371
372``` bash
373python setup.py sdist bdist_wheel
374
375# For pypi test (to check if some change to the installation did work)
376twine upload --repository-url https://test.pypi.org/legacy/ dist/*
377
378# For production:
379twine upload dist/*
380```
381
382Please don't push non-releases to the productive / real pypi instance.