Elffuss BraidHub

kikocis/freqtrade public

develop · 34.5 KiBRenderedRawPermalink
1# Strategy Customization
2
3This page explains how to customize your strategies, add new indicators and set up trading rules.
4
5Please familiarize yourself with [Freqtrade basics](bot-basics.md) first, which provides overall info on how the bot operates.
6
7## Install a custom strategy file
8
9This is very simple. Copy paste your strategy file into the directory `user_data/strategies`.
10
11Let assume you have a class called `AwesomeStrategy` in the file `AwesomeStrategy.py`:
12
131. Move your file into `user_data/strategies` (you should have `user_data/strategies/AwesomeStrategy.py`
142. Start the bot with the param `--strategy AwesomeStrategy` (the parameter is the class name)
15
16```bash
17freqtrade trade --strategy AwesomeStrategy
18```
19
20## Develop your own strategy
21
22The bot includes a default strategy file.
23Also, several other strategies are available in the [strategy repository](https://github.com/freqtrade/freqtrade-strategies).
24
25You will however most likely have your own idea for a strategy.
26This document intends to help you develop one for yourself.
27
28To get started, use `freqtrade new-strategy --strategy AwesomeStrategy`.
29This will create a new strategy file from a template, which will be located under `user_data/strategies/AwesomeStrategy.py`.
30
31!!! Note
32 This is just a template file, which will most likely not be profitable out of the box.
33
34### Anatomy of a strategy
35
36A strategy file contains all the information needed to build a good strategy:
37
38- Indicators
39- Buy strategy rules
40- Sell strategy rules
41- Minimal ROI recommended
42- Stoploss strongly recommended
43
44The bot also include a sample strategy called `SampleStrategy` you can update: `user_data/strategies/sample_strategy.py`.
45You can test it with the parameter: `--strategy SampleStrategy`
46
47Additionally, there is an attribute called `INTERFACE_VERSION`, which defines the version of the strategy interface the bot should use.
48The current version is 2 - which is also the default when it's not set explicitly in the strategy.
49
50Future versions will require this to be set.
51
52```bash
53freqtrade trade --strategy AwesomeStrategy
54```
55
56**For the following section we will use the [user_data/strategies/sample_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_strategy.py)
57file as reference.**
58
59!!! Note "Strategies and Backtesting"
60 To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware
61 that during backtesting the full time range is passed to the `populate_*()` methods at once.
62 It is therefore best to use vectorized operations (across the whole dataframe, not loops) and
63 avoid index referencing (`df.iloc[-1]`), but instead use `df.shift()` to get to the previous candle.
64
65!!! Warning "Warning: Using future data"
66 Since backtesting passes the full time range to the `populate_*()` methods, the strategy author
67 needs to take care to avoid having the strategy utilize data from the future.
68 Some common patterns for this are listed in the [Common Mistakes](#common-mistakes-when-developing-strategies) section of this document.
69
70### Customize Indicators
71
72Buy and sell strategies need indicators. You can add more indicators by extending the list contained in the method `populate_indicators()` from your strategy file.
73
74You should only add the indicators used in either `populate_buy_trend()`, `populate_sell_trend()`, or to populate another indicator, otherwise performance may suffer.
75
76It's important to always return the dataframe without removing/modifying the columns `"open", "high", "low", "close", "volume"`, otherwise these fields would contain something unexpected.
77
78Sample:
79
80```python
81def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
82 """
83 Adds several different TA indicators to the given DataFrame
84
85 Performance Note: For the best performance be frugal on the number of indicators
86 you are using. Let uncomment only the indicator you are using in your strategies
87 or your hyperopt configuration, otherwise you will waste your memory and CPU usage.
88 :param dataframe: Dataframe with data from the exchange
89 :param metadata: Additional information, like the currently traded pair
90 :return: a Dataframe with all mandatory indicators for the strategies
91 """
92 dataframe['sar'] = ta.SAR(dataframe)
93 dataframe['adx'] = ta.ADX(dataframe)
94 stoch = ta.STOCHF(dataframe)
95 dataframe['fastd'] = stoch['fastd']
96 dataframe['fastk'] = stoch['fastk']
97 dataframe['blower'] = ta.BBANDS(dataframe, nbdevup=2, nbdevdn=2)['lowerband']
98 dataframe['sma'] = ta.SMA(dataframe, timeperiod=40)
99 dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)
100 dataframe['mfi'] = ta.MFI(dataframe)
101 dataframe['rsi'] = ta.RSI(dataframe)
102 dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5)
103 dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10)
104 dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)
105 dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)
106 dataframe['ao'] = awesome_oscillator(dataframe)
107 macd = ta.MACD(dataframe)
108 dataframe['macd'] = macd['macd']
109 dataframe['macdsignal'] = macd['macdsignal']
110 dataframe['macdhist'] = macd['macdhist']
111 hilbert = ta.HT_SINE(dataframe)
112 dataframe['htsine'] = hilbert['sine']
113 dataframe['htleadsine'] = hilbert['leadsine']
114 dataframe['plus_dm'] = ta.PLUS_DM(dataframe)
115 dataframe['plus_di'] = ta.PLUS_DI(dataframe)
116 dataframe['minus_dm'] = ta.MINUS_DM(dataframe)
117 dataframe['minus_di'] = ta.MINUS_DI(dataframe)
118 return dataframe
119```
120
121!!! Note "Want more indicator examples?"
122 Look into the [user_data/strategies/sample_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_strategy.py).
123 Then uncomment indicators you need.
124
125### Strategy startup period
126
127Most indicators have an instable startup period, in which they are either not available, or the calculation is incorrect. This can lead to inconsistencies, since Freqtrade does not know how long this instable period should be.
128To account for this, the strategy can be assigned the `startup_candle_count` attribute.
129This should be set to the maximum number of candles that the strategy requires to calculate stable indicators.
130
131In this example strategy, this should be set to 100 (`startup_candle_count = 100`), since the longest needed history is 100 candles.
132
133``` python
134 dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)
135```
136
137By letting the bot know how much history is needed, backtest trades can start at the specified timerange during backtesting and hyperopt.
138
139!!! Warning
140 `startup_candle_count` should be below `ohlcv_candle_limit` (which is 500 for most exchanges) - since only this amount of candles will be available during Dry-Run/Live Trade operations.
141
142#### Example
143
144Let's try to backtest 1 month (January 2019) of 5m candles using an example strategy with EMA100, as above.
145
146``` bash
147freqtrade backtesting --timerange 20190101-20190201 --timeframe 5m
148```
149
150Assuming `startup_candle_count` is set to 100, backtesting knows it needs 100 candles to generate valid buy signals. It will load data from `20190101 - (100 * 5m)` - which is ~2018-12-31 15:30:00.
151If this data is available, indicators will be calculated with this extended timerange. The instable startup period (up to 2019-01-01 00:00:00) will then be removed before starting backtesting.
152
153!!! Note
154 If data for the startup period is not available, then the timerange will be adjusted to account for this startup period - so Backtesting would start at 2019-01-01 08:30:00.
155
156### Buy signal rules
157
158Edit the method `populate_buy_trend()` in your strategy file to update your buy strategy.
159
160It's important to always return the dataframe without removing/modifying the columns `"open", "high", "low", "close", "volume"`, otherwise these fields would contain something unexpected.
161
162This will method will also define a new column, `"buy"`, which needs to contain 1 for buys, and 0 for "no action".
163
164Sample from `user_data/strategies/sample_strategy.py`:
165
166```python
167def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
168 """
169 Based on TA indicators, populates the buy signal for the given dataframe
170 :param dataframe: DataFrame populated with indicators
171 :param metadata: Additional information, like the currently traded pair
172 :return: DataFrame with buy column
173 """
174 dataframe.loc[
175 (
176 (qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30
177 (dataframe['tema'] <= dataframe['bb_middleband']) & # Guard
178 (dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard
179 (dataframe['volume'] > 0) # Make sure Volume is not 0
180 ),
181 'buy'] = 1
182
183 return dataframe
184```
185
186!!! Note
187 Buying requires sellers to buy from - therefore volume needs to be > 0 (`dataframe['volume'] > 0`) to make sure that the bot does not buy/sell in no-activity periods.
188
189### Sell signal rules
190
191Edit the method `populate_sell_trend()` into your strategy file to update your sell strategy.
192Please note that the sell-signal is only used if `use_sell_signal` is set to true in the configuration.
193
194It's important to always return the dataframe without removing/modifying the columns `"open", "high", "low", "close", "volume"`, otherwise these fields would contain something unexpected.
195
196This will method will also define a new column, `"sell"`, which needs to contain 1 for sells, and 0 for "no action".
197
198Sample from `user_data/strategies/sample_strategy.py`:
199
200```python
201def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
202 """
203 Based on TA indicators, populates the sell signal for the given dataframe
204 :param dataframe: DataFrame populated with indicators
205 :param metadata: Additional information, like the currently traded pair
206 :return: DataFrame with buy column
207 """
208 dataframe.loc[
209 (
210 (qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70
211 (dataframe['tema'] > dataframe['bb_middleband']) & # Guard
212 (dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard
213 (dataframe['volume'] > 0) # Make sure Volume is not 0
214 ),
215 'sell'] = 1
216 return dataframe
217```
218
219### Minimal ROI
220
221This dict defines the minimal Return On Investment (ROI) a trade should reach before selling, independent from the sell signal.
222
223It is of the following format, with the dict key (left side of the colon) being the minutes passed since the trade opened, and the value (right side of the colon) being the percentage.
224
225```python
226minimal_roi = {
227 "40": 0.0,
228 "30": 0.01,
229 "20": 0.02,
230 "0": 0.04
231}
232```
233
234The above configuration would therefore mean:
235
236- Sell whenever 4% profit was reached
237- Sell when 2% profit was reached (in effect after 20 minutes)
238- Sell when 1% profit was reached (in effect after 30 minutes)
239- Sell when trade is non-loosing (in effect after 40 minutes)
240
241The calculation does include fees.
242
243To disable ROI completely, set it to an insanely high number:
244
245```python
246minimal_roi = {
247 "0": 100
248}
249```
250
251While technically not completely disabled, this would sell once the trade reaches 10000% Profit.
252
253To use times based on candle duration (timeframe), the following snippet can be handy.
254This will allow you to change the timeframe for the strategy, and ROI times will still be set as candles (e.g. after 3 candles ...)
255
256``` python
257from freqtrade.exchange import timeframe_to_minutes
258
259class AwesomeStrategy(IStrategy):
260
261 timeframe = "1d"
262 timeframe_mins = timeframe_to_minutes(timeframe)
263 minimal_roi = {
264 "0": 0.05, # 5% for the first 3 candles
265 str(timeframe_mins * 3)): 0.02, # 2% after 3 candles
266 str(timeframe_mins * 6)): 0.01, # 1% After 6 candles
267 }
268```
269
270### Stoploss
271
272Setting a stoploss is highly recommended to protect your capital from strong moves against you.
273
274Sample:
275
276``` python
277stoploss = -0.10
278```
279
280This would signify a stoploss of -10%.
281
282For the full documentation on stoploss features, look at the dedicated [stoploss page](stoploss.md).
283
284If your exchange supports it, it's recommended to also set `"stoploss_on_exchange"` in the order_types dictionary, so your stoploss is on the exchange and cannot be missed due to network problems, high load or other reasons.
285
286For more information on order_types please look [here](configuration.md#understand-order_types).
287
288### Timeframe (formerly ticker interval)
289
290This is the set of candles the bot should download and use for the analysis.
291Common values are `"1m"`, `"5m"`, `"15m"`, `"1h"`, however all values supported by your exchange should work.
292
293Please note that the same buy/sell signals may work well with one timeframe, but not with the others.
294
295This setting is accessible within the strategy methods as the `self.timeframe` attribute.
296
297### Metadata dict
298
299The metadata-dict (available for `populate_buy_trend`, `populate_sell_trend`, `populate_indicators`) contains additional information.
300Currently this is `pair`, which can be accessed using `metadata['pair']` - and will return a pair in the format `XRP/BTC`.
301
302The Metadata-dict should not be modified and does not persist information across multiple calls.
303Instead, have a look at the section [Storing information](strategy-advanced.md#Storing-information)
304
305## Additional data (informative_pairs)
306
307### Get data for non-tradeable pairs
308
309Data for additional, informative pairs (reference pairs) can be beneficial for some strategies.
310OHLCV data for these pairs will be downloaded as part of the regular whitelist refresh process and is available via `DataProvider` just as other pairs (see below).
311These parts will **not** be traded unless they are also specified in the pair whitelist, or have been selected by Dynamic Whitelisting.
312
313The pairs need to be specified as tuples in the format `("pair", "timeframe")`, with pair as the first and timeframe as the second argument.
314
315Sample:
316
317``` python
318def informative_pairs(self):
319 return [("ETH/USDT", "5m"),
320 ("BTC/TUSD", "15m"),
321 ]
322```
323
324A full sample can be found [in the DataProvider section](#complete-data-provider-sample).
325
326!!! Warning
327 As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short.
328 All timeframes and all pairs can be specified as long as they are available (and active) on the used exchange.
329 It is however better to use resampling to longer timeframes whenever possible
330 to avoid hammering the exchange with too many requests and risk being blocked.
331
332***
333
334## Additional data (DataProvider)
335
336The strategy provides access to the `DataProvider`. This allows you to get additional data to use in your strategy.
337
338All methods return `None` in case of failure (do not raise an exception).
339
340Please always check the mode of operation to select the correct method to get data (samples see below).
341
342!!! Warning "Hyperopt"
343 Dataprovider is available during hyperopt, however it can only be used in `populate_indicators()` within a strategy.
344 It is not available in `populate_buy()` and `populate_sell()` methods, nor in `populate_indicators()`, if this method located in the hyperopt file.
345
346### Possible options for DataProvider
347
348- [`available_pairs`](#available_pairs) - Property with tuples listing cached pairs with their timeframe (pair, timeframe).
349- [`current_whitelist()`](#current_whitelist) - Returns a current list of whitelisted pairs. Useful for accessing dynamic whitelists (i.e. VolumePairlist)
350- [`get_pair_dataframe(pair, timeframe)`](#get_pair_dataframepair-timeframe) - This is a universal method, which returns either historical data (for backtesting) or cached live data (for the Dry-Run and Live-Run modes).
351- [`get_analyzed_dataframe(pair, timeframe)`](#get_analyzed_dataframepair-timeframe) - Returns the analyzed dataframe (after calling `populate_indicators()`, `populate_buy()`, `populate_sell()`) and the time of the latest analysis.
352- `historic_ohlcv(pair, timeframe)` - Returns historical data stored on disk.
353- `market(pair)` - Returns market data for the pair: fees, limits, precisions, activity flag, etc. See [ccxt documentation](https://github.com/ccxt/ccxt/wiki/Manual#markets) for more details on the Market data structure.
354- `ohlcv(pair, timeframe)` - Currently cached candle (OHLCV) data for the pair, returns DataFrame or empty DataFrame.
355- [`orderbook(pair, maximum)`](#orderbookpair-maximum) - Returns latest orderbook data for the pair, a dict with bids/asks with a total of `maximum` entries.
356- [`ticker(pair)`](#tickerpair) - Returns current ticker data for the pair. See [ccxt documentation](https://github.com/ccxt/ccxt/wiki/Manual#price-tickers) for more details on the Ticker data structure.
357- `runmode` - Property containing the current runmode.
358
359### Example Usages
360
361### *available_pairs*
362
363``` python
364if self.dp:
365 for pair, timeframe in self.dp.available_pairs:
366 print(f"available {pair}, {timeframe}")
367```
368
369### *current_whitelist()*
370
371Imagine you've developed a strategy that trades the `5m` timeframe using signals generated from a `1d` timeframe on the top 10 volume pairs by volume.
372
373The strategy might look something like this:
374
375*Scan through the top 10 pairs by volume using the `VolumePairList` every 5 minutes and use a 14 day RSI to buy and sell.*
376
377Due to the limited available data, it's very difficult to resample our `5m` candles into daily candles for use in a 14 day RSI. Most exchanges limit us to just 500 candles which effectively gives us around 1.74 daily candles. We need 14 days at least!
378
379Since we can't resample our data we will have to use an informative pair; and since our whitelist will be dynamic we don't know which pair(s) to use.
380
381This is where calling `self.dp.current_whitelist()` comes in handy.
382
383```python
384 def informative_pairs(self):
385
386 # get access to all pairs available in whitelist.
387 pairs = self.dp.current_whitelist()
388 # Assign tf to each pair so they can be downloaded and cached for strategy.
389 informative_pairs = [(pair, '1d') for pair in pairs]
390 return informative_pairs
391```
392
393### *get_pair_dataframe(pair, timeframe)*
394
395``` python
396# fetch live / historical candle (OHLCV) data for the first informative pair
397if self.dp:
398 inf_pair, inf_timeframe = self.informative_pairs()[0]
399 informative = self.dp.get_pair_dataframe(pair=inf_pair,
400 timeframe=inf_timeframe)
401```
402
403!!! Warning "Warning about backtesting"
404 Be careful when using dataprovider in backtesting. `historic_ohlcv()` (and `get_pair_dataframe()`
405 for the backtesting runmode) provides the full time-range in one go,
406 so please be aware of it and make sure to not "look into the future" to avoid surprises when running in dry/live mode.
407
408### *get_analyzed_dataframe(pair, timeframe)*
409
410This method is used by freqtrade internally to determine the last signal.
411It can also be used in specific callbacks to get the signal that caused the action (see [Advanced Strategy Documentation](strategy-advanced.md) for more details on available callbacks).
412
413``` python
414# fetch current dataframe
415if self.dp:
416 if self.dp.runmode.value in ('live', 'dry_run'):
417 dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=metadata['pair'],
418 timeframe=self.timeframe)
419```
420
421!!! Note "No data available"
422 Returns an empty dataframe if the requested pair was not cached.
423 This should not happen when using whitelisted pairs.
424
425
426!!! Warning "Warning about backtesting"
427 This method will return an empty dataframe during backtesting.
428
429### *orderbook(pair, maximum)*
430
431``` python
432if self.dp:
433 if self.dp.runmode.value in ('live', 'dry_run'):
434 ob = self.dp.orderbook(metadata['pair'], 1)
435 dataframe['best_bid'] = ob['bids'][0][0]
436 dataframe['best_ask'] = ob['asks'][0][0]
437```
438
439The orderbook structure is aligned with the order structure from [ccxt](https://github.com/ccxt/ccxt/wiki/Manual#order-book-structure), so the result will look as follows:
440
441``` js
442{
443 'bids': [
444 [ price, amount ], // [ float, float ]
445 [ price, amount ],
446 ...
447 ],
448 'asks': [
449 [ price, amount ],
450 [ price, amount ],
451 //...
452 ],
453 //...
454}
455```
456
457Therefore, using `ob['bids'][0][0]` as demonstrated above will result in using the best bid price. `ob['bids'][0][1]` would look at the amount at this orderbook position.
458
459!!! Warning "Warning about backtesting"
460 The order book is not part of the historic data which means backtesting and hyperopt will not work correctly if this method is used, as the method will return uptodate values.
461
462### *ticker(pair)*
463
464``` python
465if self.dp:
466 if self.dp.runmode.value in ('live', 'dry_run'):
467 ticker = self.dp.ticker(metadata['pair'])
468 dataframe['last_price'] = ticker['last']
469 dataframe['volume24h'] = ticker['quoteVolume']
470 dataframe['vwap'] = ticker['vwap']
471```
472
473!!! Warning
474 Although the ticker data structure is a part of the ccxt Unified Interface, the values returned by this method can
475 vary for different exchanges. For instance, many exchanges do not return `vwap` values, the FTX exchange
476 does not always fills in the `last` field (so it can be None), etc. So you need to carefully verify the ticker
477 data returned from the exchange and add appropriate error handling / defaults.
478
479!!! Warning "Warning about backtesting"
480 This method will always return up-to-date values - so usage during backtesting / hyperopt will lead to wrong results.
481
482### Complete Data-provider sample
483
484```python
485from freqtrade.strategy import IStrategy, merge_informative_pair
486from pandas import DataFrame
487
488class SampleStrategy(IStrategy):
489 # strategy init stuff...
490
491 timeframe = '5m'
492
493 # more strategy init stuff..
494
495 def informative_pairs(self):
496
497 # get access to all pairs available in whitelist.
498 pairs = self.dp.current_whitelist()
499 # Assign tf to each pair so they can be downloaded and cached for strategy.
500 informative_pairs = [(pair, '1d') for pair in pairs]
501 # Optionally Add additional "static" pairs
502 informative_pairs += [("ETH/USDT", "5m"),
503 ("BTC/TUSD", "15m"),
504 ]
505 return informative_pairs
506
507 def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
508 if not self.dp:
509 # Don't do anything if DataProvider is not available.
510 return dataframe
511
512 inf_tf = '1d'
513 # Get the informative pair
514 informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf)
515 # Get the 14 day rsi
516 informative['rsi'] = ta.RSI(informative, timeperiod=14)
517
518 # Use the helper function merge_informative_pair to safely merge the pair
519 # Automatically renames the columns and merges a shorter timeframe dataframe and a longer timeframe informative pair
520 # use ffill to have the 1d value available in every row throughout the day.
521 # Without this, comparisons between columns of the original and the informative pair would only work once per day.
522 # Full documentation of this method, see below
523 dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True)
524
525 # Calculate rsi of the original dataframe (5m timeframe)
526 dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
527
528 # Do other stuff
529 # ...
530
531 return dataframe
532
533 def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
534
535 dataframe.loc[
536 (
537 (qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30
538 (dataframe['rsi_1d'] < 30) & # Ensure daily RSI is < 30
539 (dataframe['volume'] > 0) # Ensure this candle had volume (important for backtesting)
540 ),
541 'buy'] = 1
542
543```
544
545***
546
547## Helper functions
548
549### *merge_informative_pair()*
550
551This method helps you merge an informative pair to a regular dataframe without lookahead bias.
552It's there to help you merge the dataframe in a safe and consistent way.
553
554Options:
555
556- Rename the columns for you to create unique columns
557- Merge the dataframe without lookahead bias
558- Forward-fill (optional)
559
560All columns of the informative dataframe will be available on the returning dataframe in a renamed fashion:
561
562!!! Example "Column renaming"
563 Assuming `inf_tf = '1d'` the resulting columns will be:
564
565 ``` python
566 'date', 'open', 'high', 'low', 'close', 'rsi' # from the original dataframe
567 'date_1d', 'open_1d', 'high_1d', 'low_1d', 'close_1d', 'rsi_1d' # from the informative dataframe
568 ```
569
570??? Example "Column renaming - 1h"
571 Assuming `inf_tf = '1h'` the resulting columns will be:
572
573 ``` python
574 'date', 'open', 'high', 'low', 'close', 'rsi' # from the original dataframe
575 'date_1h', 'open_1h', 'high_1h', 'low_1h', 'close_1h', 'rsi_1h' # from the informative dataframe
576 ```
577
578??? Example "Custom implementation"
579 A custom implementation for this is possible, and can be done as follows:
580
581 ``` python
582
583 # Shift date by 1 candle
584 # This is necessary since the data is always the "open date"
585 # and a 15m candle starting at 12:15 should not know the close of the 1h candle from 12:00 to 13:00
586 minutes = timeframe_to_minutes(inf_tf)
587 # Only do this if the timeframes are different:
588 informative['date_merge'] = informative["date"] + pd.to_timedelta(minutes, 'm')
589
590 # Rename columns to be unique
591 informative.columns = [f"{col}_{inf_tf}" for col in informative.columns]
592 # Assuming inf_tf = '1d' - then the columns will now be:
593 # date_1d, open_1d, high_1d, low_1d, close_1d, rsi_1d
594
595 # Combine the 2 dataframes
596 # all indicators on the informative sample MUST be calculated before this point
597 dataframe = pd.merge(dataframe, informative, left_on='date', right_on=f'date_merge_{inf_tf}', how='left')
598 # FFill to have the 1d value available in every row throughout the day.
599 # Without this, comparisons would only work once per day.
600 dataframe = dataframe.ffill()
601
602 ```
603
604!!! Warning "Informative timeframe < timeframe"
605 Using informative timeframes smaller than the dataframe timeframe is not recommended with this method, as it will not use any of the additional information this would provide.
606 To use the more detailed information properly, more advanced methods should be applied (which are out of scope for freqtrade documentation, as it'll depend on the respective need).
607
608***
609
610### *stoploss_from_open()*
611
612Stoploss values returned from `custom_stoploss` must specify a percentage relative to `current_rate`, but sometimes you may want to specify a stoploss relative to the open price instead. `stoploss_from_open()` is a helper function to calculate a stoploss value that can be returned from `custom_stoploss` which will be equivalent to the desired percentage above the open price.
613
614??? Example "Returning a stoploss relative to the open price from the custom stoploss function"
615
616 Say the open price was $100, and `current_price` is $121 (`current_profit` will be `0.21`).
617
618 If we want a stop price at 7% above the open price we can call `stoploss_from_open(0.07, current_profit)` which will return `0.1157024793`. 11.57% below $121 is $107, which is the same as 7% above $100.
619
620
621 ``` python
622
623 from datetime import datetime
624 from freqtrade.persistence import Trade
625 from freqtrade.strategy import IStrategy, stoploss_from_open
626
627 class AwesomeStrategy(IStrategy):
628
629 # ... populate_* methods
630
631 use_custom_stoploss = True
632
633 def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
634 current_rate: float, current_profit: float, **kwargs) -> float:
635
636 # once the profit has risin above 10%, keep the stoploss at 7% above the open price
637 if current_profit > 0.10:
638 return stoploss_from_open(0.07, current_profit)
639
640 return 1
641
642 ```
643
644 Full examples can be found in the [Custom stoploss](strategy-advanced.md#custom-stoploss) section of the Documentation.
645
646
647## Additional data (Wallets)
648
649The strategy provides access to the `Wallets` object. This contains the current balances on the exchange.
650
651!!! Note
652 Wallets is not available during backtesting / hyperopt.
653
654Please always check if `Wallets` is available to avoid failures during backtesting.
655
656``` python
657if self.wallets:
658 free_eth = self.wallets.get_free('ETH')
659 used_eth = self.wallets.get_used('ETH')
660 total_eth = self.wallets.get_total('ETH')
661```
662
663### Possible options for Wallets
664
665- `get_free(asset)` - currently available balance to trade
666- `get_used(asset)` - currently tied up balance (open orders)
667- `get_total(asset)` - total available balance - sum of the 2 above
668
669***
670
671## Additional data (Trades)
672
673A history of Trades can be retrieved in the strategy by querying the database.
674
675At the top of the file, import Trade.
676
677```python
678from freqtrade.persistence import Trade
679```
680
681The following example queries for the current pair and trades from today, however other filters can easily be added.
682
683``` python
684if self.config['runmode'].value in ('live', 'dry_run'):
685 trades = Trade.get_trades([Trade.pair == metadata['pair'],
686 Trade.open_date > datetime.utcnow() - timedelta(days=1),
687 Trade.is_open.is_(False),
688 ]).order_by(Trade.close_date).all()
689 # Summarize profit for this pair.
690 curdayprofit = sum(trade.close_profit for trade in trades)
691```
692
693Get amount of stake_currency currently invested in Trades:
694
695``` python
696if self.config['runmode'].value in ('live', 'dry_run'):
697 total_stakes = Trade.total_open_trades_stakes()
698```
699
700Retrieve performance per pair.
701Returns a List of dicts per pair.
702
703``` python
704if self.config['runmode'].value in ('live', 'dry_run'):
705 performance = Trade.get_overall_performance()
706```
707
708Sample return value: ETH/BTC had 5 trades, with a total profit of 1.5% (ratio of 0.015).
709
710``` json
711{'pair': "ETH/BTC", 'profit': 0.015, 'count': 5}
712```
713
714!!! Warning
715 Trade history is not available during backtesting or hyperopt.
716
717## Prevent trades from happening for a specific pair
718
719Freqtrade locks pairs automatically for the current candle (until that candle is over) when a pair is sold, preventing an immediate re-buy of that pair.
720
721Locked pairs will show the message `Pair <pair> is currently locked.`.
722
723### Locking pairs from within the strategy
724
725Sometimes it may be desired to lock a pair after certain events happen (e.g. multiple losing trades in a row).
726
727Freqtrade has an easy method to do this from within the strategy, by calling `self.lock_pair(pair, until, [reason])`.
728`until` must be a datetime object in the future, after which trading will be re-enabled for that pair, while `reason` is an optional string detailing why the pair was locked.
729
730Locks can also be lifted manually, by calling `self.unlock_pair(pair)`.
731
732To verify if a pair is currently locked, use `self.is_pair_locked(pair)`.
733
734!!! Note
735 Locked pairs will always be rounded up to the next candle. So assuming a `5m` timeframe, a lock with `until` set to 10:18 will lock the pair until the candle from 10:15-10:20 will be finished.
736
737!!! Warning
738 Manually locking pairs is not available during backtesting, only locks via Protections are allowed.
739
740#### Pair locking example
741
742``` python
743from freqtrade.persistence import Trade
744from datetime import timedelta, datetime, timezone
745# Put the above lines a the top of the strategy file, next to all the other imports
746# --------
747
748# Within populate indicators (or populate_buy):
749if self.config['runmode'].value in ('live', 'dry_run'):
750 # fetch closed trades for the last 2 days
751 trades = Trade.get_trades([Trade.pair == metadata['pair'],
752 Trade.open_date > datetime.utcnow() - timedelta(days=2),
753 Trade.is_open.is_(False),
754 ]).all()
755 # Analyze the conditions you'd like to lock the pair .... will probably be different for every strategy
756 sumprofit = sum(trade.close_profit for trade in trades)
757 if sumprofit < 0:
758 # Lock pair for 12 hours
759 self.lock_pair(metadata['pair'], until=datetime.now(timezone.utc) + timedelta(hours=12))
760```
761
762## Print created dataframe
763
764To inspect the created dataframe, you can issue a print-statement in either `populate_buy_trend()` or `populate_sell_trend()`.
765You may also want to print the pair so it's clear what data is currently shown.
766
767``` python
768def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
769 dataframe.loc[
770 (
771 #>> whatever condition<<<
772 ),
773 'buy'] = 1
774
775 # Print the Analyzed pair
776 print(f"result for {metadata['pair']}")
777
778 # Inspect the last 5 rows
779 print(dataframe.tail())
780
781 return dataframe
782```
783
784Printing more than a few rows is also possible (simply use `print(dataframe)` instead of `print(dataframe.tail())`), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds).
785
786## Common mistakes when developing strategies
787
788Backtesting analyzes the whole time-range at once for performance reasons. Because of this, strategy authors need to make sure that strategies do not look-ahead into the future.
789This is a common pain-point, which can cause huge differences between backtesting and dry/live run methods, since they all use data which is not available during dry/live runs, so these strategies will perform well during backtesting, but will fail / perform badly in real conditions.
790
791The following lists some common patterns which should be avoided to prevent frustration:
792
793- don't use `shift(-1)`. This uses data from the future, which is not available.
794- don't use `.iloc[-1]` or any other absolute position in the dataframe, this will be different between dry-run and backtesting.
795- 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
796- 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.
797
798## Further strategy ideas
799
800To get additional Ideas for strategies, head over to our [strategy repository](https://github.com/freqtrade/freqtrade-strategies). Feel free to use them as they are - but results will depend on the current market situation, pairs used etc. - therefore please backtest the strategy for your exchange/desired pairs first, evaluate carefully, use at your own risk.
801Feel free to use any of them as inspiration for your own strategies.
802We're happy to accept Pull Requests containing new Strategies to that repo.
803
804## Next step
805
806Now you have a perfect strategy you probably want to backtest it.
807Your next step is to learn [How to use the Backtesting](backtesting.md).