2020-02-22 07:14:08 +00:00
# Advanced Strategies
This page explains some advanced concepts available for strategies.
2020-06-14 09:38:56 +00:00
If 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.
2020-07-04 07:43:49 +00:00
[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.
2020-02-22 07:14:08 +00:00
2020-06-14 08:08:19 +00:00
!!! Note
2020-07-04 14:41:19 +00:00
All callback methods described below should only be implemented in a strategy if they are actually used.
2020-06-14 08:08:19 +00:00
2020-12-20 09:13:47 +00:00
!!! Tip
You can get a strategy template containing all below methods by running `freqtrade new-strategy --strategy MyAwesomeStrategy --template advanced`
2021-03-04 13:44:51 +00:00
## Storing information
Storing information can be accomplished by creating a new dictionary within the strategy class.
The name of the variable can be chosen at will, but should be prefixed with `cust_` to avoid naming collisions with predefined strategy variables.
```python
class AwesomeStrategy(IStrategy):
# Create custom dictionary
custom_info = {}
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# Check if the entry already exists
if not metadata["pair"] in self.custom_info:
# Create empty entry for this pair
self.custom_info[metadata["pair"]] = {}
if "crosstime" in self.custom_info[metadata["pair"]]:
self.custom_info[metadata["pair"]]["crosstime"] += 1
else:
self.custom_info[metadata["pair"]]["crosstime"] = 1
```
!!! Warning
The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash.
!!! Note
If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.
2021-05-12 06:30:35 +00:00
## Dataframe access
You may access dataframe in various strategy functions by querying it from dataprovider.
``` python
from freqtrade.exchange import timeframe_to_prev_date
class AwesomeStrategy(IStrategy):
def confirm_trade_exit(self, pair: str, trade: 'Trade', order_type: str, amount: float,
rate: float, time_in_force: str, sell_reason: str,
current_time: 'datetime', **kwargs) -> bool:
# Obtain pair dataframe.
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
# Obtain last available candle. Do not use current_time to look up latest candle, because
2021-07-04 12:02:11 +00:00
# current_time points to current incomplete candle whose data is not available.
2021-05-12 06:30:35 +00:00
last_candle = dataframe.iloc[-1].squeeze()
# < ... >
# In dry/live runs trade open date will not match candle open date therefore it must be
# rounded.
2021-05-14 07:43:48 +00:00
trade_date = timeframe_to_prev_date(self.timeframe, trade.open_date_utc)
2021-05-12 06:30:35 +00:00
# Look up trade candle.
trade_candle = dataframe.loc[dataframe['date'] == trade_date]
2021-05-17 09:40:57 +00:00
# trade_candle may be empty for trades that just opened as it is still incomplete.
2021-05-22 11:26:59 +00:00
if not trade_candle.empty:
2021-05-21 06:06:27 +00:00
trade_candle = trade_candle.squeeze()
2021-05-12 06:30:35 +00:00
# < ... >
```
!!! Warning "Using .iloc[-1]"
You can use `.iloc[-1]` here because `get_analyzed_dataframe()` only returns candles that backtesting is allowed to see.
This will not work in `populate_*` methods, so make sure to not use `.iloc[]` in that area.
Also, this will only work starting with version 2021.5.
2021-03-04 13:44:51 +00:00
***
2021-07-21 13:05:35 +00:00
## Buy Tag
2021-07-20 09:39:20 +00:00
2021-07-22 18:16:10 +00:00
When your strategy has multiple buy signals, you can name the signal that triggered.
2021-07-20 09:39:20 +00:00
Then you can access you buy signal on `custom_sell`
```python
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe.loc[
(
(dataframe['rsi'] < 35 ) &
(dataframe['volume'] > 0)
),
2021-07-22 18:16:24 +00:00
['buy', 'buy_tag']] = (1, 'buy_signal_rsi')
2021-07-20 09:39:20 +00:00
return dataframe
def custom_sell(self, pair: str, trade: Trade, current_time: datetime, current_rate: float,
current_profit: float, **kwargs):
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
last_candle = dataframe.iloc[-1].squeeze()
2021-07-21 13:05:35 +00:00
if trade.buy_tag == 'buy_signal_rsi' and last_candle['rsi'] > 80:
2021-07-20 09:39:20 +00:00
return 'sell_signal_rsi'
return None
```
2021-07-22 18:25:15 +00:00
!!! Note
`buy_tag` is limited to 100 characters, remaining data will be truncated.
2021-11-13 08:13:32 +00:00
## Exit tag
Similar to [Buy Tagging ](#buy-tag ), you can also specify a sell tag.
``` python
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe.loc[
(
(dataframe['rsi'] > 70) &
(dataframe['volume'] > 0)
),
['sell', 'exit_tag']] = (1, 'exit_rsi')
return dataframe
```
The provided exit-tag is then used as sell-reason - and shown as such in backtest results.
!!! Note
`sell_reason` is limited to 100 characters, remaining data will be truncated.
2021-12-04 13:44:03 +00:00
## Strategy version
You can implement custom strategy versioning by using the "version" method, and returning the version you would like this strategy to have.
``` python
def version(self) -> str:
"""
Returns version of the strategy.
"""
return "1.1"
```
!!! Note
You should make sure to implement proper version control (like a git repository) alongside this, as freqtrade will not keep historic versions of your strategy, so it's up to the user to be able to eventually roll back to a prior version of the strategy.
2020-08-08 15:08:38 +00:00
## Derived strategies
The 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:
``` python
class MyAwesomeStrategy(IStrategy):
...
stoploss = 0.13
trailing_stop = False
# All other attributes and methods are here as they
# should be in any custom strategy...
...
class MyAwesomeStrategy2(MyAwesomeStrategy):
# Override something
stoploss = 0.08
trailing_stop = True
```
2020-12-19 10:39:21 +00:00
Both attributes and methods may be overridden, altering behavior of the original strategy in a way you need.
2021-01-19 21:07:10 +00:00
2021-02-01 18:48:29 +00:00
!!! Note "Parent-strategy in different files"
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.
``` python
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent))
from myawesomestrategy import MyAwesomeStrategy
```
2021-01-19 21:07:10 +00:00
## Embedding Strategies
2021-05-24 14:08:17 +00:00
Freqtrade provides you with an easy way to embed the strategy into your configuration file.
2021-01-19 21:07:10 +00:00
This is done by utilizing BASE64 encoding and providing this string at the strategy configuration field,
in your chosen config file.
### Encoding a string as BASE64
This is a quick example, how to generate the BASE64 string in python
```python
from base64 import urlsafe_b64encode
with open(file, 'r') as f:
content = f.read()
content = urlsafe_b64encode(content.encode('utf-8'))
```
The variable 'content', will contain the strategy file in a BASE64 encoded form. Which can now be set in your configurations file as following
```json
"strategy": "NameOfStrategy:BASE64String"
```
Please ensure that 'NameOfStrategy' is identical to the strategy name!
2021-09-23 05:25:11 +00:00
## Performance warning
When executing a strategy, one can sometimes be greeted by the following in the logs
> PerformanceWarning: DataFrame is highly fragmented.
This is a warning from [`pandas` ](https://github.com/pandas-dev/pandas ) and as the warning continues to say:
use `pd.concat(axis=1)` .
This can have slight performance implications, which are usually only visible during hyperopt (when optimizing an indicator).
For example:
```python
for val in self.buy_ema_short.range:
dataframe[f'ema_short_{val}'] = ta.EMA(dataframe, timeperiod=val)
```
should be rewritten to
```python
frames = [dataframe]
for val in self.buy_ema_short.range:
frames.append({
f'ema_short_{val}': ta.EMA(dataframe, timeperiod=val)
})
# Append columns to existing dataframe
merged_frame = pd.concat(frames, axis=1)
```
2021-12-11 15:14:04 +00:00
2021-12-18 16:55:12 +00:00
## Adjust trade position
2021-12-11 15:14:04 +00:00
2021-12-24 10:38:43 +00:00
The `position_adjustment_enable` strategy property enables the usage of `adjust_trade_position()` callback in strategy.
For performance reasons, it's disabled by default and freqtrade will show a warning message on startup if enabled.
2021-12-11 15:14:04 +00:00
`adjust_trade_position()` can be used to perform additional orders to manage risk with DCA (Dollar Cost Averaging) for example.
2021-12-20 22:11:01 +00:00
The strategy is expected to return a stake_amount if and when an additional buy order should be made (position is increased).
If there is not enough funds in the wallet then nothing will happen.
Additional orders also mean additional fees and those orders don't count towards `max_open_trades` .
2021-12-26 14:29:10 +00:00
Using unlimited stake amount with DCA orders requires you to also implement `custom_stake_amount` callback to avoid allocating all funds to initial order.
2021-12-11 15:14:04 +00:00
2021-12-18 16:55:12 +00:00
!!! Warning
Stoploss is still calculated from the initial opening price, not averaged price.
2021-12-11 15:14:04 +00:00
``` python
from freqtrade.persistence import Trade
class DigDeeperStrategy(IStrategy):
# Attempts to handle large drops with DCA. High stoploss is required.
stoploss = -0.30
2021-12-24 10:38:43 +00:00
max_dca_orders = 3
2021-12-24 17:02:39 +00:00
# This number is explained a bit further down
max_dca_multiplier = 5.5
2021-12-24 10:38:43 +00:00
2021-12-11 15:14:04 +00:00
# ... populate_* methods
2021-12-24 10:38:43 +00:00
# Let unlimited stakes leave funds open for DCA orders
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
proposed_stake: float, min_stake: float, max_stake: float,
**kwargs) -> float:
if self.config['stake_amount'] == 'unlimited':
2021-12-24 17:02:39 +00:00
return proposed_stake / self.max_dca_multiplier
2021-12-24 10:38:43 +00:00
# Use default stake amount.
return proposed_stake
2021-12-11 15:14:04 +00:00
def adjust_trade_position(self, pair: str, trade: Trade,
current_time: datetime, current_rate: float, current_profit: float,
**kwargs) -> Optional[float]:
"""
Custom trade adjustment logic, returning the stake amount that a trade should be increased.
This means extra buy orders with additional fees.
:param pair: Pair that's currently analyzed
:param trade: trade object.
:param current_time: datetime object, containing the current datetime
:param current_rate: Rate, calculated based on pricing settings in ask_strategy.
:param current_profit: Current profit (as ratio), calculated based on current_rate.
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
:return float: Stake amount to adjust your trade
"""
2021-12-24 10:38:43 +00:00
2021-12-11 15:14:04 +00:00
if current_profit > -0.05:
return None
# Obtain pair dataframe.
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
# Only buy when not actively falling price.
2021-12-11 17:45:30 +00:00
last_candle = dataframe.iloc[-1].squeeze()
previous_candle = dataframe.iloc[-2].squeeze()
2021-12-18 16:55:12 +00:00
if last_candle['close'] < previous_candle [ ' close ' ] :
2021-12-11 15:14:04 +00:00
return None
count_of_buys = 0
for order in trade.orders:
if order.ft_order_side == 'buy' and order.status == "closed":
count_of_buys += 1
# Allow up to 3 additional increasingly larger buys (4 in total)
# Initial buy is 1x
# If that falls to -5% profit, we buy 1.25x more, average profit should increase to roughly -2.2%
2021-12-26 14:29:10 +00:00
# If that falls down to -5% again, we buy 1.5x more
# If that falls once again down to -5%, we buy 1.75x more
2021-12-11 15:14:04 +00:00
# Total stake for this trade would be 1 + 1.25 + 1.5 + 1.75 = 5.5x of the initial allowed stake.
2021-12-24 17:02:39 +00:00
# That is why max_dca_multiplier is 5.5
2021-12-11 15:14:04 +00:00
# Hope you have a deep wallet!
2021-12-24 10:38:43 +00:00
if 0 < count_of_buys < = self . max_dca_orders:
2021-12-11 15:14:04 +00:00
try:
2021-12-24 17:02:39 +00:00
# This returns max stakes for one trade
2021-12-11 15:14:04 +00:00
stake_amount = self.wallets.get_trade_stake_amount(pair, None)
2021-12-24 17:02:39 +00:00
# This calculates base order size
stake_amount = stake_amount / self.max_dca_multiplier
# This then calculates current safety order size
2021-12-11 15:14:04 +00:00
stake_amount = stake_amount * (1 + (count_of_buys * 0.25))
return stake_amount
except Exception as exception:
return None
return None
```