Elffuss BraidHub

kikocis/freqtrade public

develop · 22.7 KiBRenderedRawPermalink
1# Advanced Strategies
2
3This page explains some advanced concepts available for strategies.
4If you're just getting started, please be familiar with the methods described in the [Strategy Customization](strategy-customization.md) documentation and with the [Freqtrade basics](bot-basics.md) first.
5
6[Freqtrade basics](bot-basics.md) describes in which sequence each method described below is called, which can be helpful to understand which method to use for your custom needs.
7
8!!! Note
9 All callback methods described below should only be implemented in a strategy if they are actually used.
10
11!!! Tip
12 You can get a strategy template containing all below methods by running `freqtrade new-strategy --strategy MyAwesomeStrategy --template advanced`
13
14## Storing information
15
16Storing information can be accomplished by creating a new dictionary within the strategy class.
17
18The name of the variable can be chosen at will, but should be prefixed with `cust_` to avoid naming collisions with predefined strategy variables.
19
20```python
21class AwesomeStrategy(IStrategy):
22 # Create custom dictionary
23 custom_info = {}
24
25 def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
26 # Check if the entry already exists
27 if not metadata["pair"] in self.custom_info:
28 # Create empty entry for this pair
29 self.custom_info[metadata["pair"]] = {}
30
31 if "crosstime" in self.custom_info[metadata["pair"]]:
32 self.custom_info[metadata["pair"]]["crosstime"] += 1
33 else:
34 self.custom_info[metadata["pair"]]["crosstime"] = 1
35```
36
37!!! Warning
38 The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash.
39
40!!! Note
41 If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.
42
43***
44
45### Storing custom information using DatetimeIndex from `dataframe`
46
47Imagine you need to store an indicator like `ATR` or `RSI` into `custom_info`. To use this in a meaningful way, you will not only need the raw data of the indicator, but probably also need to keep the right timestamps.
48
49```python
50import talib.abstract as ta
51class AwesomeStrategy(IStrategy):
52 # Create custom dictionary
53 custom_info = {}
54
55 def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
56 # using "ATR" here as example
57 dataframe['atr'] = ta.ATR(dataframe)
58 if self.dp.runmode.value in ('backtest', 'hyperopt'):
59 # add indicator mapped to correct DatetimeIndex to custom_info
60 self.custom_info[metadata['pair']] = dataframe[['date', 'atr']].set_index('date')
61 return dataframe
62```
63
64!!! Warning
65 The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash.
66
67!!! Note
68 If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.
69
70See `custom_stoploss` examples below on how to access the saved dataframe columns
71
72## Custom stoploss
73
74The stoploss price can only ever move upwards - if the stoploss value returned from `custom_stoploss` would result in a lower stoploss price than was previously set, it will be ignored. The traditional `stoploss` value serves as an absolute lower level and will be instated as the initial stoploss.
75
76The usage of the custom stoploss method must be enabled by setting `use_custom_stoploss=True` on the strategy object.
77The method must return a stoploss value (float / number) as a percentage of the current price.
78E.g. If the `current_rate` is 200 USD, then returning `0.02` will set the stoploss price 2% lower, at 196 USD.
79
80The absolute value of the return value is used (the sign is ignored), so returning `0.05` or `-0.05` have the same result, a stoploss 5% below the current price.
81
82To simulate a regular trailing stoploss of 4% (trailing 4% behind the maximum reached price) you would use the following very simple method:
83
84``` python
85# additional imports required
86from datetime import datetime
87from freqtrade.persistence import Trade
88
89class AwesomeStrategy(IStrategy):
90
91 # ... populate_* methods
92
93 use_custom_stoploss = True
94
95 def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
96 current_rate: float, current_profit: float, **kwargs) -> float:
97 """
98 Custom stoploss logic, returning the new distance relative to current_rate (as ratio).
99 e.g. returning -0.05 would create a stoploss 5% below current_rate.
100 The custom stoploss can never be below self.stoploss, which serves as a hard maximum loss.
101
102 For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
103
104 When not implemented by a strategy, returns the initial stoploss value
105 Only called when use_custom_stoploss is set to True.
106
107 :param pair: Pair that's currently analyzed
108 :param trade: trade object.
109 :param current_time: datetime object, containing the current datetime
110 :param current_rate: Rate, calculated based on pricing settings in ask_strategy.
111 :param current_profit: Current profit (as ratio), calculated based on current_rate.
112 :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
113 :return float: New stoploss value, relative to the currentrate
114 """
115 return -0.04
116```
117
118Stoploss on exchange works similar to `trailing_stop`, and the stoploss on exchange is updated as configured in `stoploss_on_exchange_interval` ([More details about stoploss on exchange](stoploss.md#stop-loss-on-exchange-freqtrade)).
119
120!!! Note "Use of dates"
121 All time-based calculations should be done based on `current_time` - using `datetime.now()` or `datetime.utcnow()` is discouraged, as this will break backtesting support.
122
123!!! Tip "Trailing stoploss"
124 It's recommended to disable `trailing_stop` when using custom stoploss values. Both can work in tandem, but you might encounter the trailing stop to move the price higher while your custom function would not want this, causing conflicting behavior.
125
126### Custom stoploss examples
127
128The next section will show some examples on what's possible with the custom stoploss function.
129Of course, many more things are possible, and all examples can be combined at will.
130
131#### Time based trailing stop
132
133Use the initial stoploss for the first 60 minutes, after this change to 10% trailing stoploss, and after 2 hours (120 minutes) we use a 5% trailing stoploss.
134
135``` python
136from datetime import datetime, timedelta
137from freqtrade.persistence import Trade
138
139class AwesomeStrategy(IStrategy):
140
141 # ... populate_* methods
142
143 use_custom_stoploss = True
144
145 def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
146 current_rate: float, current_profit: float, **kwargs) -> float:
147
148 # Make sure you have the longest interval first - these conditions are evaluated from top to bottom.
149 if current_time - timedelta(minutes=120) > trade.open_date_utc:
150 return -0.05
151 elif current_time - timedelta(minutes=60) > trade.open_date_utc:
152 return -0.10
153 return 1
154```
155
156#### Different stoploss per pair
157
158Use a different stoploss depending on the pair.
159In this example, we'll trail the highest price with 10% trailing stoploss for `ETH/BTC` and `XRP/BTC`, with 5% trailing stoploss for `LTC/BTC` and with 15% for all other pairs.
160
161``` python
162from datetime import datetime
163from freqtrade.persistence import Trade
164
165class AwesomeStrategy(IStrategy):
166
167 # ... populate_* methods
168
169 use_custom_stoploss = True
170
171 def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
172 current_rate: float, current_profit: float, **kwargs) -> float:
173
174 if pair in ('ETH/BTC', 'XRP/BTC'):
175 return -0.10
176 elif pair in ('LTC/BTC'):
177 return -0.05
178 return -0.15
179```
180
181#### Trailing stoploss with positive offset
182
183Use the initial stoploss until the profit is above 4%, then use a trailing stoploss of 50% of the current profit with a minimum of 2.5% and a maximum of 5%.
184
185Please note that the stoploss can only increase, values lower than the current stoploss are ignored.
186
187``` python
188from datetime import datetime, timedelta
189from freqtrade.persistence import Trade
190
191class AwesomeStrategy(IStrategy):
192
193 # ... populate_* methods
194
195 use_custom_stoploss = True
196
197 def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
198 current_rate: float, current_profit: float, **kwargs) -> float:
199
200 if current_profit < 0.04:
201 return -1 # return a value bigger than the inital stoploss to keep using the inital stoploss
202
203 # After reaching the desired offset, allow the stoploss to trail by half the profit
204 desired_stoploss = current_profit / 2
205
206 # Use a minimum of 2.5% and a maximum of 5%
207 return max(min(desired_stoploss, 0.05), 0.025)
208```
209
210#### Calculating stoploss relative to open price
211
212Stoploss values returned from `custom_stoploss()` always specify a percentage relative to `current_rate`. In order to set a stoploss relative to the *open* price, we need to use `current_profit` to calculate what percentage relative to the `current_rate` will give you the same result as if the percentage was specified from the open price.
213
214The helper function [`stoploss_from_open()`](strategy-customization.md#stoploss_from_open) can be used to convert from an open price relative stop, to a current price relative stop which can be returned from `custom_stoploss()`.
215
216#### Stepped stoploss
217
218Instead of continuously trailing behind the current price, this example sets fixed stoploss price levels based on the current profit.
219
220* Use the regular stoploss until 20% profit is reached
221* Once profit is > 20% - set stoploss to 7% above open price.
222* Once profit is > 25% - set stoploss to 15% above open price.
223* Once profit is > 40% - set stoploss to 25% above open price.
224
225
226``` python
227from datetime import datetime
228from freqtrade.persistence import Trade
229from freqtrade.strategy import stoploss_from_open
230
231class AwesomeStrategy(IStrategy):
232
233 # ... populate_* methods
234
235 use_custom_stoploss = True
236
237 def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
238 current_rate: float, current_profit: float, **kwargs) -> float:
239
240 # evaluate highest to lowest, so that highest possible stop is used
241 if current_profit > 0.40:
242 return stoploss_from_open(0.25, current_profit)
243 elif current_profit > 0.25:
244 return stoploss_from_open(0.15, current_profit)
245 elif current_profit > 0.20:
246 return stoploss_from_open(0.07, current_profit)
247
248 # return maximum stoploss value, keeping current stoploss price unchanged
249 return 1
250```
251#### Custom stoploss using an indicator from dataframe example
252
253Imagine you want to use `custom_stoploss()` to use a trailing indicator like e.g. "ATR"
254
255See: "Storing custom information using DatetimeIndex from `dataframe`" example above) on how to store the indicator into `custom_info`
256
257!!! Warning
258 only use .iat[-1] in live mode, not in backtesting/hyperopt
259 otherwise you will look into the future
260 see [Common mistakes when developing strategies](strategy-customization.md#common-mistakes-when-developing-strategies) for more info.
261
262``` python
263from freqtrade.persistence import Trade
264from freqtrade.state import RunMode
265
266class AwesomeStrategy(IStrategy):
267
268 # ... populate_* methods
269
270 use_custom_stoploss = True
271
272 def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
273 current_rate: float, current_profit: float, **kwargs) -> float:
274
275 result = 1
276 if self.custom_info and pair in self.custom_info and trade:
277 # using current_time directly (like below) will only work in backtesting.
278 # so check "runmode" to make sure that it's only used in backtesting/hyperopt
279 if self.dp and self.dp.runmode.value in ('backtest', 'hyperopt'):
280 relative_sl = self.custom_info[pair].loc[current_time]['atr']
281 # in live / dry-run, it'll be really the current time
282 else:
283 # but we can just use the last entry from an already analyzed dataframe instead
284 dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair,
285 timeframe=self.timeframe)
286 # WARNING
287 # only use .iat[-1] in live mode, not in backtesting/hyperopt
288 # otherwise you will look into the future
289 # see: https://www.freqtrade.io/en/latest/strategy-customization/#common-mistakes-when-developing-strategies
290 relative_sl = dataframe['atr'].iat[-1]
291
292 if (relative_sl is not None):
293 # new stoploss relative to current_rate
294 new_stoploss = (current_rate-relative_sl)/current_rate
295 # turn into relative negative offset required by `custom_stoploss` return implementation
296 result = new_stoploss - 1
297
298 return result
299```
300
301---
302
303## Custom order timeout rules
304
305Simple, time-based order-timeouts can be configured either via strategy or in the configuration in the `unfilledtimeout` section.
306
307However, freqtrade also offers a custom callback for both order types, which allows you to decide based on custom criteria if a order did time out or not.
308
309!!! Note
310 Unfilled order timeouts are not relevant during backtesting or hyperopt, and are only relevant during real (live) trading. Therefore these methods are only called in these circumstances.
311
312### Custom order timeout example
313
314A simple example, which applies different unfilled-timeouts depending on the price of the asset can be seen below.
315It applies a tight timeout for higher priced assets, while allowing more time to fill on cheap coins.
316
317The function must return either `True` (cancel order) or `False` (keep order alive).
318
319``` python
320from datetime import datetime, timedelta, timezone
321from freqtrade.persistence import Trade
322
323class AwesomeStrategy(IStrategy):
324
325 # ... populate_* methods
326
327 # Set unfilledtimeout to 25 hours, since our maximum timeout from below is 24 hours.
328 unfilledtimeout = {
329 'buy': 60 * 25,
330 'sell': 60 * 25
331 }
332
333 def check_buy_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool:
334 if trade.open_rate > 100 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=5):
335 return True
336 elif trade.open_rate > 10 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=3):
337 return True
338 elif trade.open_rate < 1 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(hours=24):
339 return True
340 return False
341
342
343 def check_sell_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool:
344 if trade.open_rate > 100 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=5):
345 return True
346 elif trade.open_rate > 10 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=3):
347 return True
348 elif trade.open_rate < 1 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(hours=24):
349 return True
350 return False
351```
352
353!!! Note
354 For the above example, `unfilledtimeout` must be set to something bigger than 24h, otherwise that type of timeout will apply first.
355
356### Custom order timeout example (using additional data)
357
358``` python
359from datetime import datetime
360from freqtrade.persistence import Trade
361
362class AwesomeStrategy(IStrategy):
363
364 # ... populate_* methods
365
366 # Set unfilledtimeout to 25 hours, since our maximum timeout from below is 24 hours.
367 unfilledtimeout = {
368 'buy': 60 * 25,
369 'sell': 60 * 25
370 }
371
372 def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool:
373 ob = self.dp.orderbook(pair, 1)
374 current_price = ob['bids'][0][0]
375 # Cancel buy order if price is more than 2% above the order.
376 if current_price > order['price'] * 1.02:
377 return True
378 return False
379
380
381 def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool:
382 ob = self.dp.orderbook(pair, 1)
383 current_price = ob['asks'][0][0]
384 # Cancel sell order if price is more than 2% below the order.
385 if current_price < order['price'] * 0.98:
386 return True
387 return False
388```
389
390---
391
392## Bot loop start callback
393
394A simple callback which is called once at the start of every bot throttling iteration.
395This can be used to perform calculations which are pair independent (apply to all pairs), loading of external data, etc.
396
397``` python
398import requests
399
400class AwesomeStrategy(IStrategy):
401
402 # ... populate_* methods
403
404 def bot_loop_start(self, **kwargs) -> None:
405 """
406 Called at the start of the bot iteration (one loop).
407 Might be used to perform pair-independent tasks
408 (e.g. gather some remote resource for comparison)
409 :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
410 """
411 if self.config['runmode'].value in ('live', 'dry_run'):
412 # Assign this to the class by using self.*
413 # can then be used by populate_* methods
414 self.remote_data = requests.get('https://some_remote_source.example.com')
415
416```
417
418## Bot order confirmation
419
420### Trade entry (buy order) confirmation
421
422`confirm_trade_entry()` can be used to abort a trade entry at the latest second (maybe because the price is not what we expect).
423
424``` python
425class AwesomeStrategy(IStrategy):
426
427 # ... populate_* methods
428
429 def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,
430 time_in_force: str, **kwargs) -> bool:
431 """
432 Called right before placing a buy order.
433 Timing for this function is critical, so avoid doing heavy computations or
434 network requests in this method.
435
436 For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
437
438 When not implemented by a strategy, returns True (always confirming).
439
440 :param pair: Pair that's about to be bought.
441 :param order_type: Order type (as configured in order_types). usually limit or market.
442 :param amount: Amount in target (quote) currency that's going to be traded.
443 :param rate: Rate that's going to be used when using limit orders
444 :param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
445 :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
446 :return bool: When True is returned, then the buy-order is placed on the exchange.
447 False aborts the process
448 """
449 return True
450
451```
452
453### Trade exit (sell order) confirmation
454
455`confirm_trade_exit()` can be used to abort a trade exit (sell) at the latest second (maybe because the price is not what we expect).
456
457``` python
458from freqtrade.persistence import Trade
459
460
461class AwesomeStrategy(IStrategy):
462
463 # ... populate_* methods
464
465 def confirm_trade_exit(self, pair: str, trade: Trade, order_type: str, amount: float,
466 rate: float, time_in_force: str, sell_reason: str, **kwargs) -> bool:
467 """
468 Called right before placing a regular sell order.
469 Timing for this function is critical, so avoid doing heavy computations or
470 network requests in this method.
471
472 For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
473
474 When not implemented by a strategy, returns True (always confirming).
475
476 :param pair: Pair that's about to be sold.
477 :param order_type: Order type (as configured in order_types). usually limit or market.
478 :param amount: Amount in quote currency.
479 :param rate: Rate that's going to be used when using limit orders
480 :param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
481 :param sell_reason: Sell reason.
482 Can be any of ['roi', 'stop_loss', 'stoploss_on_exchange', 'trailing_stop_loss',
483 'sell_signal', 'force_sell', 'emergency_sell']
484 :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
485 :return bool: When True is returned, then the sell-order is placed on the exchange.
486 False aborts the process
487 """
488 if sell_reason == 'force_sell' and trade.calc_profit_ratio(rate) < 0:
489 # Reject force-sells with negative profit
490 # This is just a sample, please adjust to your needs
491 # (this does not necessarily make sense, assuming you know when you're force-selling)
492 return False
493 return True
494
495```
496
497---
498
499## Derived strategies
500
501The strategies can be derived from other strategies. This avoids duplication of your custom strategy code. You can use this technique to override small parts of your main strategy, leaving the rest untouched:
502
503``` python
504class MyAwesomeStrategy(IStrategy):
505 ...
506 stoploss = 0.13
507 trailing_stop = False
508 # All other attributes and methods are here as they
509 # should be in any custom strategy...
510 ...
511
512class MyAwesomeStrategy2(MyAwesomeStrategy):
513 # Override something
514 stoploss = 0.08
515 trailing_stop = True
516```
517
518Both attributes and methods may be overridden, altering behavior of the original strategy in a way you need.
519
520!!! Note "Parent-strategy in different files"
521 If you have the parent-strategy in a different file, you'll need to add the following to the top of your "child"-file to ensure proper loading, otherwise freqtrade may not be able to load the parent strategy correctly.
522
523 ``` python
524 import sys
525 from pathlib import Path
526 sys.path.append(str(Path(__file__).parent))
527
528 from myawesomestrategy import MyAwesomeStrategy
529 ```
530
531## Embedding Strategies
532
533Freqtrade provides you with with an easy way to embed the strategy into your configuration file.
534This is done by utilizing BASE64 encoding and providing this string at the strategy configuration field,
535in your chosen config file.
536
537### Encoding a string as BASE64
538
539This is a quick example, how to generate the BASE64 string in python
540
541```python
542from base64 import urlsafe_b64encode
543
544with open(file, 'r') as f:
545 content = f.read()
546content = urlsafe_b64encode(content.encode('utf-8'))
547```
548
549The variable 'content', will contain the strategy file in a BASE64 encoded form. Which can now be set in your configurations file as following
550
551```json
552"strategy": "NameOfStrategy:BASE64String"
553```
554
555Please ensure that 'NameOfStrategy' is identical to the strategy name!