2021-11-20 10:44:56 +00:00
# Strategy Callbacks
2022-03-12 09:50:01 +00:00
While the main strategy functions (`populate_indicators()`, `populate_entry_trend()` , `populate_exit_trend()` ) should be used in a vectorized way, and are only called [once during backtesting ](bot-basics.md#backtesting-hyperopt-execution-logic ), callbacks are called "whenever needed".
2021-11-20 10:44:56 +00:00
As such, you should avoid doing heavy calculations in callbacks to avoid delays during operations.
Depending on the callback used, they may be called when entering / exiting a trade, or throughout the duration of a trade.
Currently available callbacks:
2022-04-25 23:59:50 +00:00
* [`bot_start()` ](#bot-start )
2021-11-20 10:44:56 +00:00
* [`bot_loop_start()` ](#bot-loop-start )
2022-03-22 06:02:40 +00:00
* [`custom_stake_amount()` ](#stake-size-management )
2022-03-12 10:07:31 +00:00
* [`custom_exit()` ](#custom-exit-signal )
2021-11-20 10:44:56 +00:00
* [`custom_stoploss()` ](#custom-stoploss )
* [`custom_entry_price()` and `custom_exit_price()` ](#custom-order-price-rules )
2022-03-25 18:46:56 +00:00
* [`check_entry_timeout()` and `check_exit_timeout()` ](#custom-order-timeout-rules )
2021-11-20 10:44:56 +00:00
* [`confirm_trade_entry()` ](#trade-entry-buy-order-confirmation )
* [`confirm_trade_exit()` ](#trade-exit-sell-order-confirmation )
2021-12-11 15:14:04 +00:00
* [`adjust_trade_position()` ](#adjust-trade-position )
2022-04-18 18:13:50 +00:00
* [`adjust_entry_price()` ](#adjust-entry-price )
2022-03-22 06:02:40 +00:00
* [`leverage()` ](#leverage-callback )
2024-03-28 05:49:02 +00:00
* [`order_filled()` ](#order-filled-callback )
2021-11-20 10:44:56 +00:00
!!! Tip "Callback calling sequence"
You can find the callback calling sequence in [bot-basics ](bot-basics.md#bot-execution-logic )
2022-04-25 23:59:50 +00:00
## Bot start
2022-04-30 06:55:07 +00:00
A simple callback which is called once when the strategy is loaded.
2022-04-25 23:59:50 +00:00
This can be used to perform actions that must only be performed once and runs after dataprovider and wallet are set
``` python
2022-04-30 06:55:07 +00:00
import requests
2022-04-25 23:59:50 +00:00
class AwesomeStrategy(IStrategy):
# ... populate_* methods
def bot_start(self, **kwargs) -> None:
"""
Called only once after bot instantiation.
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
"""
2022-04-30 04:20:26 +00:00
if self.config['runmode'].value in ('live', 'dry_run'):
# Assign this to the class by using self.*
# can then be used by populate_* methods
2023-04-20 05:36:14 +00:00
self.custom_remote_data = requests.get('https://some_remote_source.example.com')
2022-04-25 23:59:50 +00:00
```
2022-05-30 04:32:35 +00:00
During hyperopt, this runs only once at startup.
2021-11-20 10:44:56 +00:00
## Bot loop start
2023-03-03 20:46:43 +00:00
A simple callback which is called once at the start of every bot throttling iteration in dry/live mode (roughly every 5
seconds, unless configured differently) or once per candle in backtest/hyperopt mode.
2021-11-20 10:44:56 +00:00
This can be used to perform calculations which are pair independent (apply to all pairs), loading of external data, etc.
``` python
import requests
class AwesomeStrategy(IStrategy):
# ... populate_* methods
2023-03-26 09:21:18 +00:00
def bot_loop_start(self, current_time: datetime, **kwargs) -> None:
2021-11-20 10:44:56 +00:00
"""
Called at the start of the bot iteration (one loop).
Might be used to perform pair-independent tasks
(e.g. gather some remote resource for comparison)
2023-03-26 09:21:18 +00:00
:param current_time: datetime object, containing the current datetime
2021-11-20 10:44:56 +00:00
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
"""
if self.config['runmode'].value in ('live', 'dry_run'):
# Assign this to the class by using self.*
# can then be used by populate_* methods
self.remote_data = requests.get('https://some_remote_source.example.com')
```
2022-08-21 06:24:14 +00:00
## Stake size management
2021-11-20 10:44:56 +00:00
Called before entering a trade, makes it possible to manage your position size when placing a new trade.
```python
class AwesomeStrategy(IStrategy):
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
2022-07-08 17:44:20 +00:00
proposed_stake: float, min_stake: Optional[float], max_stake: float,
leverage: float, entry_tag: Optional[str], side: str,
**kwargs) -> float:
2021-11-20 10:44:56 +00:00
dataframe, _ = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe)
current_candle = dataframe.iloc[-1].squeeze()
if current_candle['fastk_rsi_1h'] > current_candle['fastd_rsi_1h']:
if self.config['stake_amount'] == 'unlimited':
# Use entire available wallet during favorable conditions when in compounding mode.
return max_stake
else:
# Compound profits during favorable conditions instead of using a static stake.
return self.wallets.get_total_stake_amount() / self.config['max_open_trades']
# Use default stake amount.
return proposed_stake
```
Freqtrade will fall back to the `proposed_stake` value should your code raise an exception. The exception itself will be logged.
!!! Tip
2022-01-31 19:04:19 +00:00
You do not _have_ to ensure that `min_stake <= returned_value <= max_stake` . Trades will succeed as the returned value will be clamped to supported range and this action will be logged.
2021-11-20 10:44:56 +00:00
!!! Tip
Returning `0` or `None` will prevent trades from being placed.
2022-03-12 10:07:31 +00:00
## Custom exit signal
2021-11-20 10:44:56 +00:00
Called for open trade every throttling iteration (roughly every 5 seconds) until a trade is closed.
2022-04-07 17:43:56 +00:00
Allows to define custom exit signals, indicating that specified position should be sold. This is very useful when we need to customize exit conditions for each individual trade, or if you need trade data to make an exit decision.
2021-11-20 10:44:56 +00:00
2022-03-12 10:07:31 +00:00
For example you could implement a 1:2 risk-reward ROI with `custom_exit()` .
2021-11-20 10:44:56 +00:00
2022-04-09 15:17:49 +00:00
Using `custom_exit()` signals in place of stoploss though *is not recommended* . It is a inferior method to using `custom_stoploss()` in this regard - which also allows you to keep the stoploss on exchange.
2021-11-20 10:44:56 +00:00
!!! Note
2022-04-09 14:50:38 +00:00
Returning a (none-empty) `string` or `True` from this method is equal to setting exit signal on a candle at specified time. This method is not called when exit signal is set already, or if exit signals are disabled (`use_exit_signal=False`). `string` max length is 64 characters. Exceeding this limit will cause the message to be truncated to 64 characters.
2022-04-09 15:17:49 +00:00
`custom_exit()` will ignore `exit_profit_only` , and will always be called unless `use_exit_signal=False` , even if there is a new enter signal.
2021-11-20 10:44:56 +00:00
2022-04-07 17:43:56 +00:00
An example of how we can use different indicators depending on the current profit and also exit trades that were open longer than one day:
2021-11-20 10:44:56 +00:00
``` python
class AwesomeStrategy(IStrategy):
2022-03-12 10:07:31 +00:00
def custom_exit(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float,
2021-11-20 10:44:56 +00:00
current_profit: float, **kwargs):
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
last_candle = dataframe.iloc[-1].squeeze()
# Above 20% profit, sell when rsi < 80
if current_profit > 0.2:
if last_candle['rsi'] < 80:
return 'rsi_below_80'
# Between 2% and 10%, sell if EMA-long above EMA-short
if 0.02 < current_profit < 0 . 1:
if last_candle['emalong'] > last_candle['emashort']:
return 'ema_long_below_80'
# Sell any positions at a loss if they are held for more than one day.
if current_profit < 0.0 and ( current_time - trade . open_date_utc ) . days > = 1:
return 'unclog'
```
2021-11-20 15:15:03 +00:00
See [Dataframe access ](strategy-advanced.md#dataframe-access ) for more information about dataframe use in strategy callbacks.
2021-11-20 10:44:56 +00:00
## Custom stoploss
2022-04-29 09:53:05 +00:00
Called for open trade every iteration (roughly every 5 seconds) until a trade is closed.
2021-11-21 08:13:53 +00:00
2021-11-20 10:44:56 +00:00
The usage of the custom stoploss method must be enabled by setting `use_custom_stoploss=True` on the strategy object.
2022-04-29 09:53:05 +00:00
The 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 (before this method is called for the first time for a trade), and is still mandatory.
2021-11-20 10:44:56 +00:00
The method must return a stoploss value (float / number) as a percentage of the current price.
E.g. If the `current_rate` is 200 USD, then returning `0.02` will set the stoploss price 2% lower, at 196 USD.
2022-10-22 13:20:41 +00:00
During backtesting, `current_rate` (and `current_profit` ) are provided against the candle's high (or low for short trades) - while the resulting stoploss is evaluated against the candle's low (or high for short trades).
2021-11-20 10:44:56 +00:00
The 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.
2024-06-21 14:43:07 +00:00
Returning `None` will be interpreted as "no desire to change", and is the only safe way to return when you'd like to not modify the stoploss.
`NaN` and `inf` values are considered invalid and will be ignored (identical to `None` ).
2021-11-20 10:44:56 +00:00
2024-04-29 05:12:19 +00:00
Stoploss 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-exchangefreqtrade)).
2023-08-14 14:31:01 +00:00
!!! Note "Use of dates"
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.
!!! Tip "Trailing stoploss"
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.
### Adjust stoploss after position adjustments
Depending on your strategy, you may encounter the need to adjust the stoploss in both directions after a [position adjustment ](#adjust-trade-position ).
For this, freqtrade will make an additional call with `after_fill=True` after an order fills, which will allow the strategy to move the stoploss in any direction (also widening the gap between stoploss and current price, which is otherwise forbidden).
!!! Note "backwards compatibility"
This call will only be made if the `after_fill` parameter is part of the function definition of your `custom_stoploss` function.
As such, this will not impact (and with that, surprise) existing, running strategies.
### Custom stoploss examples
The next section will show some examples on what's possible with the custom stoploss function.
Of course, many more things are possible, and all examples can be combined at will.
#### Trailing stop via custom stoploss
2021-11-20 10:44:56 +00:00
To simulate a regular trailing stoploss of 4% (trailing 4% behind the maximum reached price) you would use the following very simple method:
``` python
# additional imports required
from datetime import datetime
from freqtrade.persistence import Trade
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
2023-08-14 14:16:23 +00:00
current_rate: float, current_profit: float, after_fill: bool,
2023-08-14 14:20:54 +00:00
**kwargs) -> Optional[float]:
2021-11-20 10:44:56 +00:00
"""
Custom stoploss logic, returning the new distance relative to current_rate (as ratio).
e.g. returning -0.05 would create a stoploss 5% below current_rate.
The custom stoploss can never be below self.stoploss, which serves as a hard maximum loss.
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
2023-08-14 14:16:23 +00:00
When not implemented by a strategy, returns the initial stoploss value.
2021-11-20 10:44:56 +00:00
Only called when use_custom_stoploss is set to True.
:param pair: Pair that's currently analyzed
:param trade: trade object.
:param current_time: datetime object, containing the current datetime
2022-03-27 16:03:49 +00:00
:param current_rate: Rate, calculated based on pricing settings in exit_pricing.
2021-11-20 10:44:56 +00:00
:param current_profit: Current profit (as ratio), calculated based on current_rate.
2023-08-14 14:16:23 +00:00
:param after_fill: True if the stoploss is called after the order was filled.
2021-11-20 10:44:56 +00:00
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
2023-08-14 14:16:23 +00:00
:return float: New stoploss value, relative to the current_rate
2021-11-20 10:44:56 +00:00
"""
return -0.04
```
#### Time based trailing stop
Use 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.
``` python
from datetime import datetime, timedelta
from freqtrade.persistence import Trade
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
2023-08-14 14:16:23 +00:00
current_rate: float, current_profit: float, after_fill: bool,
2023-08-14 14:20:54 +00:00
**kwargs) -> Optional[float]:
2021-11-20 10:44:56 +00:00
# Make sure you have the longest interval first - these conditions are evaluated from top to bottom.
if current_time - timedelta(minutes=120) > trade.open_date_utc:
return -0.05
elif current_time - timedelta(minutes=60) > trade.open_date_utc:
return -0.10
2023-08-14 14:20:54 +00:00
return None
2021-11-20 10:44:56 +00:00
```
2023-08-18 08:14:32 +00:00
#### Time based trailing stop with after-fill adjustments
Use 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.
If an additional order fills, set stoploss to -10% below the new `open_rate` ([Averaged across all entries](#position-adjust-calculations)).
``` python
from datetime import datetime, timedelta
from freqtrade.persistence import Trade
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
current_rate: float, current_profit: float, after_fill: bool,
**kwargs) -> Optional[float]:
if after_fill:
# After an additional order, start with a stoploss of 10% below the new open rate
return stoploss_from_open(0.10, current_profit, is_short=trade.is_short, leverage=trade.leverage)
# Make sure you have the longest interval first - these conditions are evaluated from top to bottom.
if current_time - timedelta(minutes=120) > trade.open_date_utc:
return -0.05
elif current_time - timedelta(minutes=60) > trade.open_date_utc:
return -0.10
return None
```
2021-11-20 10:44:56 +00:00
#### Different stoploss per pair
Use a different stoploss depending on the pair.
In 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.
``` python
from datetime import datetime
from freqtrade.persistence import Trade
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
2023-08-14 14:16:23 +00:00
current_rate: float, current_profit: float, after_fill: bool,
2023-08-14 14:20:54 +00:00
**kwargs) -> Optional[float]:
2021-11-20 10:44:56 +00:00
if pair in ('ETH/BTC', 'XRP/BTC'):
return -0.10
elif pair in ('LTC/BTC'):
return -0.05
return -0.15
```
#### Trailing stoploss with positive offset
Use 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%.
Please note that the stoploss can only increase, values lower than the current stoploss are ignored.
``` python
from datetime import datetime, timedelta
from freqtrade.persistence import Trade
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
2023-08-14 14:16:23 +00:00
current_rate: float, current_profit: float, after_fill: bool,
2023-08-14 14:20:54 +00:00
**kwargs) -> Optional[float]:
2021-11-20 10:44:56 +00:00
if current_profit < 0.04:
2024-04-05 18:15:43 +00:00
return None # return None to keep using the initial stoploss
2021-11-20 10:44:56 +00:00
# After reaching the desired offset, allow the stoploss to trail by half the profit
desired_stoploss = current_profit / 2
# Use a minimum of 2.5% and a maximum of 5%
return max(min(desired_stoploss, 0.05), 0.025)
```
#### Stepped stoploss
Instead of continuously trailing behind the current price, this example sets fixed stoploss price levels based on the current profit.
* Use the regular stoploss until 20% profit is reached
* Once profit is > 20% - set stoploss to 7% above open price.
* Once profit is > 25% - set stoploss to 15% above open price.
* Once profit is > 40% - set stoploss to 25% above open price.
``` python
from datetime import datetime
from freqtrade.persistence import Trade
from freqtrade.strategy import stoploss_from_open
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
2023-08-14 14:16:23 +00:00
current_rate: float, current_profit: float, after_fill: bool,
2023-08-14 14:20:54 +00:00
**kwargs) -> Optional[float]:
2021-11-20 10:44:56 +00:00
# evaluate highest to lowest, so that highest possible stop is used
if current_profit > 0.40:
2023-04-19 11:22:52 +00:00
return stoploss_from_open(0.25, current_profit, is_short=trade.is_short, leverage=trade.leverage)
2021-11-20 10:44:56 +00:00
elif current_profit > 0.25:
2023-04-19 11:22:52 +00:00
return stoploss_from_open(0.15, current_profit, is_short=trade.is_short, leverage=trade.leverage)
2021-11-20 10:44:56 +00:00
elif current_profit > 0.20:
2023-04-19 11:22:52 +00:00
return stoploss_from_open(0.07, current_profit, is_short=trade.is_short, leverage=trade.leverage)
2021-11-20 10:44:56 +00:00
# return maximum stoploss value, keeping current stoploss price unchanged
2023-08-14 14:20:54 +00:00
return None
2021-11-20 10:44:56 +00:00
```
#### Custom stoploss using an indicator from dataframe example
Absolute stoploss value may be derived from indicators stored in dataframe. Example uses parabolic SAR below the price as stoploss.
``` python
class AwesomeStrategy(IStrategy):
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# < ... >
dataframe['sar'] = ta.SAR(dataframe)
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
2023-08-14 14:16:23 +00:00
current_rate: float, current_profit: float, after_fill: bool,
2023-08-14 14:20:54 +00:00
**kwargs) -> Optional[float]:
2021-11-20 10:44:56 +00:00
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
last_candle = dataframe.iloc[-1].squeeze()
# Use parabolic sar as absolute stoploss price
stoploss_price = last_candle['sar']
# Convert absolute price to percentage relative to current_rate
if stoploss_price < current_rate:
2023-04-19 13:26:33 +00:00
return stoploss_from_absolute(stoploss_price, current_rate, is_short=trade.is_short)
2021-11-20 10:44:56 +00:00
# return maximum stoploss value, keeping current stoploss price unchanged
2023-08-14 14:20:54 +00:00
return None
2021-11-20 10:44:56 +00:00
```
2021-11-20 15:15:03 +00:00
See [Dataframe access ](strategy-advanced.md#dataframe-access ) for more information about dataframe use in strategy callbacks.
2021-11-20 10:44:56 +00:00
### Common helpers for stoploss calculations
#### Stoploss relative to open price
2023-09-02 10:06:16 +00:00
Stoploss 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 _entry_ 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 trade profit above the entry point.
2021-11-20 10:44:56 +00:00
2023-09-02 10:06:16 +00:00
??? Example "Returning a stoploss relative to the open price from the custom stoploss function"
Say the open price was $100, and `current_price` is $121 (`current_profit` will be `0.21` ).
If we want a stop price at 7% above the open price we can call `stoploss_from_open(0.07, current_profit, False)` which will return `0.1157024793` . 11.57% below $121 is $107, which is the same as 7% above $100.
This function will consider leverage - so at 10x leverage, the actual stoploss would be 0.7% above $100 (0.7% * 10x = 7%).
``` python
from datetime import datetime
from freqtrade.persistence import Trade
from freqtrade.strategy import IStrategy, stoploss_from_open
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
current_rate: float, current_profit: float, after_fill: bool,
**kwargs) -> Optional[float]:
# once the profit has risen above 10%, keep the stoploss at 7% above the open price
if current_profit > 0.10:
return stoploss_from_open(0.07, current_profit, is_short=trade.is_short, leverage=trade.leverage)
return 1
```
2024-04-29 05:12:19 +00:00
Full examples can be found in the [Custom stoploss ](strategy-callbacks.md#custom-stoploss ) section of the Documentation.
2023-09-02 10:06:16 +00:00
!!! Note
Providing invalid input to `stoploss_from_open()` may produce "CustomStoploss function did not return valid stoploss" warnings.
This may happen if `current_profit` parameter is below specified `open_relative_stop` . Such situations may arise when closing trade
is blocked by `confirm_trade_exit()` method. Warnings can be solved by never blocking stop loss sells by checking `exit_reason` in
`confirm_trade_exit()` , or by using `return stoploss_from_open(...) or 1` idiom, which will request to not change stop loss when
`current_profit < open_relative_stop` .
2021-11-20 10:44:56 +00:00
#### Stoploss percentage from absolute price
Stoploss values returned from `custom_stoploss()` always specify a percentage relative to `current_rate` . In order to set a stoploss at specified absolute price level, we need to use `stop_rate` 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.
2023-09-02 10:06:16 +00:00
The helper function `stoploss_from_absolute()` can be used to convert from an absolute price, to a current price relative stop which can be returned from `custom_stoploss()` .
??? Example "Returning a stoploss using absolute price from the custom stoploss function"
2024-06-11 04:35:22 +00:00
If we want to trail a stop price at 2xATR below current price we can call `stoploss_from_absolute(current_rate + (side * candle['atr'] * 2), current_rate=current_rate, is_short=trade.is_short, leverage=trade.leverage)` .
2023-09-02 10:06:16 +00:00
For futures, we need to adjust the direction (up or down), as well as adjust for leverage, since the [`custom_stoploss` ](strategy-callbacks.md#custom-stoploss ) callback returns the ["risk for this trade" ](stoploss.md#stoploss-and-leverage ) - not the relative price movement.
``` python
from datetime import datetime
from freqtrade.persistence import Trade
from freqtrade.strategy import IStrategy, stoploss_from_absolute, timeframe_to_prev_date
class AwesomeStrategy(IStrategy):
use_custom_stoploss = True
def populate_indicators_1h(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe['atr'] = ta.ATR(dataframe, timeperiod=14)
return dataframe
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
current_rate: float, current_profit: float, after_fill: bool,
**kwargs) -> Optional[float]:
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
trade_date = timeframe_to_prev_date(self.timeframe, trade.open_date_utc)
candle = dataframe.iloc[-1].squeeze()
2023-12-25 03:02:22 +00:00
side = 1 if trade.is_short else -1
2023-09-02 10:06:16 +00:00
return stoploss_from_absolute(current_rate + (side * candle['atr'] * 2),
2024-06-11 04:35:22 +00:00
current_rate=current_rate,
is_short=trade.is_short,
2023-09-02 10:06:16 +00:00
leverage=trade.leverage)
```
2021-11-20 10:44:56 +00:00
---
## Custom order price rules
By default, freqtrade use the orderbook to automatically set an order price([Relevant documentation](configuration.md#prices-used-for-orders)), you also have the option to create custom order prices based on your strategy.
You can use this feature by creating a `custom_entry_price()` function in your strategy file to customize entry prices and `custom_exit_price()` for exits.
Each of these methods are called right before placing an order on the exchange.
!!! Note
If your custom pricing function return None or an invalid value, price will fall back to `proposed_rate` , which is based on the regular pricing configuration.
2023-09-16 17:13:23 +00:00
!!! Note
2023-09-17 07:30:03 +00:00
Using custom_entry_price, the Trade object will be available as soon as the first entry order associated with the trade is created, for the first entry, `trade` parameter value will be `None` .
2023-09-17 17:57:13 +00:00
2021-11-20 10:44:56 +00:00
### Custom order entry and exit price example
``` python
from datetime import datetime, timedelta, timezone
from freqtrade.persistence import Trade
class AwesomeStrategy(IStrategy):
# ... populate_* methods
2023-09-17 07:06:00 +00:00
def custom_entry_price(self, pair: str, trade: Optional['Trade'], current_time: datetime, proposed_rate: float,
2022-04-04 14:48:27 +00:00
entry_tag: Optional[str], side: str, **kwargs) -> float:
2021-11-20 10:44:56 +00:00
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair,
timeframe=self.timeframe)
new_entryprice = dataframe['bollinger_10_lowerband'].iat[-1]
2022-04-16 11:42:41 +00:00
2021-11-20 10:44:56 +00:00
return new_entryprice
def custom_exit_price(self, pair: str, trade: Trade,
current_time: datetime, proposed_rate: float,
2022-04-27 04:42:56 +00:00
current_profit: float, exit_tag: Optional[str], **kwargs) -> float:
2021-11-20 10:44:56 +00:00
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair,
timeframe=self.timeframe)
new_exitprice = dataframe['bollinger_10_upperband'].iat[-1]
2022-04-16 11:42:41 +00:00
2021-11-20 10:44:56 +00:00
return new_exitprice
```
!!! Warning
2022-04-16 11:42:41 +00:00
Modifying entry and exit prices will only work for limit orders. Depending on the price chosen, this can result in a lot of unfilled orders. By default the maximum allowed distance between the current price and the custom price is 2%, this value can be changed in config with the `custom_price_max_distance_ratio` parameter.
2022-04-29 09:53:05 +00:00
**Example** :
2021-11-20 15:15:03 +00:00
If the new_entryprice is 97, the proposed_rate is 100 and the `custom_price_max_distance_ratio` is set to 2%, The retained valid custom entry price will be 98, which is 2% below the current (proposed) rate.
2021-11-20 10:44:56 +00:00
2021-12-03 16:44:53 +00:00
!!! Warning "Backtesting"
2022-02-06 13:33:31 +00:00
Custom prices are supported in backtesting (starting with 2021.12), and orders will fill if the price falls within the candle's low/high range.
2022-02-08 05:47:55 +00:00
Orders that don't fill immediately are subject to regular timeout handling, which happens once per (detail) candle.
2022-08-27 06:50:09 +00:00
`custom_exit_price()` is only called for sells of type exit_signal, Custom exit and partial exits. All other exit-types will use regular backtesting prices.
2021-11-20 10:44:56 +00:00
## Custom order timeout rules
Simple, time-based order-timeouts can be configured either via strategy or in the configuration in the `unfilledtimeout` section.
However, freqtrade also offers a custom callback for both order types, which allows you to decide based on custom criteria if an order did time out or not.
!!! Note
2022-02-06 13:33:31 +00:00
Backtesting fills orders if their price falls within the candle's low/high range.
2022-02-08 05:47:55 +00:00
The below callbacks will be called once per (detail) candle for orders that don't fill immediately (which use custom pricing).
2021-11-20 10:44:56 +00:00
### Custom order timeout example
Called for every open order until that order is either filled or cancelled.
2022-03-25 18:46:56 +00:00
`check_entry_timeout()` is called for trade entries, while `check_exit_timeout()` is called for trade exit orders.
2021-11-20 10:44:56 +00:00
A simple example, which applies different unfilled-timeouts depending on the price of the asset can be seen below.
It applies a tight timeout for higher priced assets, while allowing more time to fill on cheap coins.
The function must return either `True` (cancel order) or `False` (keep order alive).
``` python
2022-01-22 15:05:13 +00:00
from datetime import datetime, timedelta
2022-04-16 04:47:56 +00:00
from freqtrade.persistence import Trade, Order
2021-11-20 10:44:56 +00:00
class AwesomeStrategy(IStrategy):
# ... populate_* methods
# Set unfilledtimeout to 25 hours, since the maximum timeout from below is 24 hours.
unfilledtimeout = {
2022-03-26 10:55:11 +00:00
'entry': 60 * 25,
'exit': 60 * 25
2021-11-20 10:44:56 +00:00
}
2022-04-16 12:20:50 +00:00
def check_entry_timeout(self, pair: str, trade: 'Trade', order: 'Order',
2022-03-25 18:46:56 +00:00
current_time: datetime, **kwargs) -> bool:
2022-01-22 15:05:13 +00:00
if trade.open_rate > 100 and trade.open_date_utc < current_time - timedelta ( minutes = 5):
2021-11-20 10:44:56 +00:00
return True
2022-01-22 15:05:13 +00:00
elif trade.open_rate > 10 and trade.open_date_utc < current_time - timedelta ( minutes = 3):
2021-11-20 10:44:56 +00:00
return True
2022-01-22 15:05:13 +00:00
elif trade.open_rate < 1 and trade . open_date_utc < current_time - timedelta ( hours = 24):
2021-11-20 10:44:56 +00:00
return True
return False
2022-04-16 04:47:56 +00:00
def check_exit_timeout(self, pair: str, trade: Trade, order: 'Order',
2022-01-22 15:05:13 +00:00
current_time: datetime, **kwargs) -> bool:
if trade.open_rate > 100 and trade.open_date_utc < current_time - timedelta ( minutes = 5):
2021-11-20 10:44:56 +00:00
return True
2022-01-22 15:05:13 +00:00
elif trade.open_rate > 10 and trade.open_date_utc < current_time - timedelta ( minutes = 3):
2021-11-20 10:44:56 +00:00
return True
2022-01-22 15:05:13 +00:00
elif trade.open_rate < 1 and trade . open_date_utc < current_time - timedelta ( hours = 24):
2021-11-20 10:44:56 +00:00
return True
return False
```
!!! Note
For the above example, `unfilledtimeout` must be set to something bigger than 24h, otherwise that type of timeout will apply first.
### Custom order timeout example (using additional data)
``` python
from datetime import datetime
2022-04-16 04:47:56 +00:00
from freqtrade.persistence import Trade, Order
2021-11-20 10:44:56 +00:00
class AwesomeStrategy(IStrategy):
# ... populate_* methods
# Set unfilledtimeout to 25 hours, since the maximum timeout from below is 24 hours.
unfilledtimeout = {
2022-03-26 10:55:11 +00:00
'entry': 60 * 25,
'exit': 60 * 25
2021-11-20 10:44:56 +00:00
}
2022-04-16 04:47:56 +00:00
def check_entry_timeout(self, pair: str, trade: 'Trade', order: 'Order',
2022-03-25 18:46:56 +00:00
current_time: datetime, **kwargs) -> bool:
2021-11-20 10:44:56 +00:00
ob = self.dp.orderbook(pair, 1)
current_price = ob['bids'][0][0]
# Cancel buy order if price is more than 2% above the order.
2022-04-16 04:47:56 +00:00
if current_price > order.price * 1.02:
2021-11-20 10:44:56 +00:00
return True
return False
2022-04-16 04:47:56 +00:00
def check_exit_timeout(self, pair: str, trade: 'Trade', order: 'Order',
2022-02-06 12:37:31 +00:00
current_time: datetime, **kwargs) -> bool:
2021-11-20 10:44:56 +00:00
ob = self.dp.orderbook(pair, 1)
current_price = ob['asks'][0][0]
# Cancel sell order if price is more than 2% below the order.
2022-04-16 04:47:56 +00:00
if current_price < order.price * 0 . 98:
2021-11-20 10:44:56 +00:00
return True
return False
```
---
## Bot order confirmation
2021-11-20 15:15:03 +00:00
Confirm trade entry / exits.
This are the last methods that will be called before an order is placed.
2021-11-20 10:44:56 +00:00
### Trade entry (buy order) confirmation
`confirm_trade_entry()` can be used to abort a trade entry at the latest second (maybe because the price is not what we expect).
``` python
class AwesomeStrategy(IStrategy):
# ... populate_* methods
def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,
2022-04-16 11:42:41 +00:00
time_in_force: str, current_time: datetime, entry_tag: Optional[str],
2021-11-21 08:13:53 +00:00
side: str, **kwargs) -> bool:
2021-11-20 10:44:56 +00:00
"""
2021-11-21 08:13:53 +00:00
Called right before placing a entry order.
2021-11-20 10:44:56 +00:00
Timing for this function is critical, so avoid doing heavy computations or
network requests in this method.
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
When not implemented by a strategy, returns True (always confirming).
2021-11-21 08:13:53 +00:00
:param pair: Pair that's about to be bought/shorted.
2021-11-20 10:44:56 +00:00
:param order_type: Order type (as configured in order_types). usually limit or market.
2022-05-31 15:52:45 +00:00
:param amount: Amount in target (base) currency that's going to be traded.
2022-06-09 17:41:08 +00:00
:param rate: Rate that's going to be used when using limit orders
or current rate for market orders.
2021-11-20 10:44:56 +00:00
:param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
:param current_time: datetime object, containing the current datetime
2022-05-31 15:52:45 +00:00
:param entry_tag: Optional entry_tag (buy_tag) if provided with the buy signal.
2021-11-21 08:13:53 +00:00
:param side: 'long' or 'short' - indicating the direction of the proposed trade
2021-11-20 10:44:56 +00:00
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
:return bool: When True is returned, then the buy-order is placed on the exchange.
False aborts the process
"""
return True
```
### Trade exit (sell order) confirmation
`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).
2022-05-22 09:28:11 +00:00
`confirm_trade_exit()` may be called multiple times within one iteration for the same trade if different exit-reasons apply.
The exit-reasons (if applicable) will be in the following sequence:
* `exit_signal` / `custom_exit`
* `stop_loss`
* `roi`
* `trailing_stop_loss`
2021-11-20 10:44:56 +00:00
``` python
from freqtrade.persistence import Trade
class AwesomeStrategy(IStrategy):
# ... populate_* methods
def confirm_trade_exit(self, pair: str, trade: Trade, order_type: str, amount: float,
2022-03-25 05:37:40 +00:00
rate: float, time_in_force: str, exit_reason: str,
2021-11-20 10:44:56 +00:00
current_time: datetime, **kwargs) -> bool:
"""
2022-05-31 15:52:45 +00:00
Called right before placing a regular exit order.
2021-11-20 10:44:56 +00:00
Timing for this function is critical, so avoid doing heavy computations or
network requests in this method.
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
When not implemented by a strategy, returns True (always confirming).
2022-05-31 15:52:45 +00:00
:param pair: Pair for trade that's about to be exited.
:param trade: trade object.
2021-11-20 10:44:56 +00:00
:param order_type: Order type (as configured in order_types). usually limit or market.
2022-05-31 15:52:45 +00:00
:param amount: Amount in base currency.
2022-06-09 17:41:08 +00:00
:param rate: Rate that's going to be used when using limit orders
or current rate for market orders.
2021-11-20 10:44:56 +00:00
:param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
2022-03-25 05:37:40 +00:00
:param exit_reason: Exit reason.
2021-11-20 10:44:56 +00:00
Can be any of ['roi', 'stop_loss', 'stoploss_on_exchange', 'trailing_stop_loss',
2022-04-04 15:10:02 +00:00
'exit_signal', 'force_exit', 'emergency_exit']
2021-11-20 10:44:56 +00:00
:param current_time: datetime object, containing the current datetime
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
2022-05-31 15:52:45 +00:00
:return bool: When True, then the exit-order is placed on the exchange.
2021-11-20 10:44:56 +00:00
False aborts the process
"""
2022-04-04 14:59:27 +00:00
if exit_reason == 'force_exit' and trade.calc_profit_ratio(rate) < 0:
2021-11-20 10:44:56 +00:00
# Reject force-sells with negative profit
# This is just a sample, please adjust to your needs
# (this does not necessarily make sense, assuming you know when you're force-selling)
return False
return True
```
2021-11-21 08:13:53 +00:00
2022-05-22 09:28:11 +00:00
!!! Warning
`confirm_trade_exit()` can prevent stoploss exits, causing significant losses as this would ignore stoploss exits.
2022-07-30 05:27:24 +00:00
`confirm_trade_exit()` will not be called for Liquidations - as liquidations are forced by the exchange, and therefore cannot be rejected.
2022-05-22 09:28:11 +00:00
2021-12-18 16:55:12 +00:00
## Adjust trade position
2021-12-11 15:14:04 +00:00
2022-01-15 14:11:13 +00:00
The `position_adjustment_enable` strategy property enables the usage of `adjust_trade_position()` callback in the strategy.
2021-12-24 10:38:43 +00:00
For performance reasons, it's disabled by default and freqtrade will show a warning message on startup if enabled.
2022-07-31 12:19:04 +00:00
`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.
2022-01-15 14:11:13 +00:00
Additional orders also result in additional fees and those orders don't count towards `max_open_trades` .
2022-07-31 12:19:04 +00:00
This callback is **not** called when there is an open order (either buy or sell) waiting for execution.
2022-01-15 14:11:13 +00:00
`adjust_trade_position()` is called very frequently for the duration of a trade, so you must keep your implementation as performant as possible.
2021-12-12 06:32:15 +00:00
2023-11-11 12:11:17 +00:00
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.
2024-01-30 06:20:39 +00:00
Adjustment orders can be assigned with a tag by returning a 2 element Tuple, with the first element being the adjustment amount, and the 2nd element the tag (e.g. `return 250, 'increase_favorable_conditions'` ).
2023-11-11 12:11:17 +00:00
Modifications to leverage are not possible, and the stake-amount returned is assumed to be before applying leverage.
2022-02-13 14:10:09 +00:00
2023-12-14 19:06:45 +00:00
### Increase position
2023-12-29 17:32:33 +00:00
The strategy is expected to return a positive **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).
2023-12-14 19:06:45 +00:00
2023-12-29 17:32:33 +00:00
If there are not enough funds in the wallet (the return value is above `max_stake` ) then the signal will be ignored.
2023-12-14 19:06:45 +00:00
`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.
2023-11-11 12:11:17 +00:00
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.
2022-07-31 12:19:04 +00:00
2023-12-14 19:06:45 +00:00
### Decrease position
2023-11-11 12:11:17 +00:00
2023-12-14 19:06:45 +00:00
The strategy is expected to return a negative stake_amount (in stake currency) for a partial exit.
2024-03-11 13:01:09 +00:00
Returning the full owned stake at that point (`-trade.stake_amount`) results in a full exit.
2023-12-29 17:32:33 +00:00
Returning a value more than the above (so remaining stake_amount would become negative) will result in the bot ignoring the signal.
2022-02-13 14:10:09 +00:00
2021-12-27 17:56:45 +00:00
!!! Note "About stake size"
2022-01-12 04:06:23 +00:00
Using fixed stake size means it will be the amount used for the first order, just like without position adjustment.
If you wish to buy additional orders with DCA, then make sure to leave enough funds in the wallet for that.
2022-01-15 14:11:13 +00:00
Using 'unlimited' stake amount with DCA orders requires you to also implement the `custom_stake_amount()` callback to avoid allocating all funds to the initial order.
2021-12-27 17:41:33 +00:00
2024-02-26 17:03:34 +00:00
!!! Warning "Stoploss calculation"
2021-12-27 17:41:33 +00:00
Stoploss is still calculated from the initial opening price, not averaged price.
2022-07-31 12:19:04 +00:00
Regular stoploss rules still apply (cannot move down).
2021-12-27 17:41:33 +00:00
2022-08-28 09:32:53 +00:00
While `/stopentry` command stops the bot from entering new trades, the position adjustment feature will continue buying new orders on existing trades.
2022-01-12 04:06:23 +00:00
2022-01-08 13:06:05 +00:00
!!! Warning "Backtesting"
2022-07-31 12:19:04 +00:00
During backtesting this callback is called for each candle in `timeframe` or `timeframe_detail` , so run-time performance will be affected.
2023-01-20 06:08:15 +00:00
This can also cause deviating results between live and backtesting, since backtesting can adjust the trade only once per candle, whereas live could adjust the trade multiple times per candle.
2022-01-08 13:06:05 +00:00
2024-02-26 17:03:34 +00:00
!!! Warning "Performance with many position adjustments"
Position adjustments can be a good approach to increase a strategy's output - but it can also have drawbacks if using this feature extensively.
Each of the orders will be attached to the trade object for the duration of the trade - hence increasing memory usage.
Trades with long duration and 10s or even 100ds of position adjustments are therefore not recommended, and should be closed at regular intervals to not affect performance.
2021-12-27 17:41:33 +00:00
``` python
from freqtrade.persistence import Trade
2024-04-09 17:26:52 +00:00
from typing import Optional, Tuple, Union
2021-12-27 17:41:33 +00:00
class DigDeeperStrategy(IStrategy):
2022-04-16 11:42:41 +00:00
2022-01-12 03:02:42 +00:00
position_adjustment_enable = True
2022-04-16 11:42:41 +00:00
2021-12-27 17:41:33 +00:00
# Attempts to handle large drops with DCA. High stoploss is required.
stoploss = -0.30
2022-04-16 11:42:41 +00:00
2022-01-12 03:02:42 +00:00
# ... populate_* methods
2022-04-16 11:42:41 +00:00
2022-01-12 03:02:42 +00:00
# Example specific variables
2022-01-27 15:57:50 +00:00
max_entry_position_adjustment = 3
2021-12-27 17:41:33 +00:00
# This number is explained a bit further down
max_dca_multiplier = 5.5
2022-04-16 11:42:41 +00:00
2021-12-27 17:41:33 +00:00
# This is called when placing the initial order (opening trade)
2022-07-31 12:19:04 +00:00
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
2022-05-07 09:55:49 +00:00
proposed_stake: float, min_stake: Optional[float], max_stake: float,
2022-07-08 17:44:20 +00:00
leverage: float, entry_tag: Optional[str], side: str,
**kwargs) -> float:
2022-04-16 11:42:41 +00:00
2021-12-27 17:41:33 +00:00
# We need to leave most of the funds for possible further DCA orders
# This also applies to fixed stakes
return proposed_stake / self.max_dca_multiplier
2022-04-16 11:42:41 +00:00
2022-01-12 03:09:52 +00:00
def adjust_trade_position(self, trade: Trade, current_time: datetime,
2022-07-31 12:19:04 +00:00
current_rate: float, current_profit: float,
min_stake: Optional[float], max_stake: float,
current_entry_rate: float, current_exit_rate: float,
current_entry_profit: float, current_exit_profit: float,
2024-01-30 06:20:39 +00:00
**kwargs
) -> Union[Optional[float], Tuple[Optional[float], Optional[str]]]:
2021-12-27 17:41:33 +00:00
"""
2022-07-31 12:19:04 +00:00
Custom trade adjustment logic, returning the stake amount that a trade should be
increased or decreased.
2023-09-14 16:27:41 +00:00
This means extra entry or exit orders with additional fees.
2022-07-31 12:19:04 +00:00
Only called when `position_adjustment_enable` is set to True.
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
When not implemented by a strategy, returns None
2022-04-16 11:42:41 +00:00
2021-12-27 17:41:33 +00:00
:param trade: trade object.
:param current_time: datetime object, containing the current datetime
2023-09-14 16:27:41 +00:00
:param current_rate: Current entry rate (same as current_entry_profit)
:param current_profit: Current profit (as ratio), calculated based on current_rate
(same as current_entry_profit).
2022-07-31 12:19:04 +00:00
:param min_stake: Minimal stake size allowed by exchange (for both entries and exits)
:param max_stake: Maximum stake allowed (either through balance, or by exchange limits).
:param current_entry_rate: Current rate using entry pricing.
:param current_exit_rate: Current rate using exit pricing.
:param current_entry_profit: Current profit using entry pricing.
:param current_exit_profit: Current profit using exit pricing.
2021-12-27 17:41:33 +00:00
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
2022-07-31 12:19:04 +00:00
:return float: Stake amount to adjust your trade,
Positive values to increase position, Negative values to decrease position.
Return None for no action.
2024-01-30 06:20:39 +00:00
Optionally, return a tuple with a 2nd element with an order reason
2021-12-27 17:41:33 +00:00
"""
2022-04-16 11:42:41 +00:00
2022-07-31 12:19:04 +00:00
if current_profit > 0.05 and trade.nr_of_successful_exits == 0:
# Take half of the profit at +5%
2024-01-30 06:20:39 +00:00
return -(trade.stake_amount / 2), 'half_profit_5%'
2022-07-31 12:19:04 +00:00
2021-12-27 17:41:33 +00:00
if current_profit > -0.05:
return None
# Obtain pair dataframe (just to show how to access it)
2022-01-12 04:09:06 +00:00
dataframe, _ = self.dp.get_analyzed_dataframe(trade.pair, self.timeframe)
2021-12-27 17:41:33 +00:00
# Only buy when not actively falling price.
last_candle = dataframe.iloc[-1].squeeze()
previous_candle = dataframe.iloc[-2].squeeze()
if last_candle['close'] < previous_candle [ ' close ' ] :
return None
2022-04-06 01:02:13 +00:00
filled_entries = trade.select_filled_orders(trade.entry_side)
2022-02-13 14:10:09 +00:00
count_of_entries = trade.nr_of_successful_entries
2021-12-27 17:41:33 +00:00
# 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%
# 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
# Total stake for this trade would be 1 + 1.25 + 1.5 + 1.75 = 5.5x of the initial allowed stake.
# That is why max_dca_multiplier is 5.5
# Hope you have a deep wallet!
2022-01-19 13:16:42 +00:00
try:
# This returns first order stake size
2023-07-15 08:14:08 +00:00
stake_amount = filled_entries[0].stake_amount
2022-01-19 13:16:42 +00:00
# This then calculates current safety order size
2022-02-13 14:10:09 +00:00
stake_amount = stake_amount * (1 + (count_of_entries * 0.25))
2024-01-30 06:20:39 +00:00
return stake_amount, '1/3rd_increase'
2022-01-19 13:16:42 +00:00
except Exception as exception:
return None
2021-12-27 17:41:33 +00:00
return None
```
2022-01-22 16:25:21 +00:00
2022-07-31 12:19:04 +00:00
### Position adjust calculations
* Entry rates are calculated using weighted averages.
* Exits will not influence the average entry rate.
* Partial exit relative profit is relative to the average entry price at this point.
* Final exit relative profit is calculated based on the total invested capital. (See example below)
??? example "Calculation example"
*This example assumes 0 fees for simplicity, and a long position on an imaginary coin.*
* Buy 100@8\$
* Buy 100@9\$ -> Avg price: 8.5\$
* Sell 100@10\$ -> Avg price: 8.5\$, realized profit 150\$, 17.65%
* Buy 150@11\$ -> Avg price: 10\$, realized profit 150\$, 17.65%
* Sell 100@12\$ -> Avg price: 10\$, total realized profit 350\$, 20%
2022-12-15 05:51:15 +00:00
* Sell 150@14\$ -> Avg price: 10\$, total realized profit 950\$, 40% < - *This will be the last "Exit" message*
2022-07-31 12:19:04 +00:00
The total profit for this trade was 950$ on a 3350$ investment (`100@8$ + 100@9$ + 150@11$`). As such - the final relative profit is 28.35% (`950 / 3350`).
2022-04-18 18:13:50 +00:00
## Adjust Entry Price
2022-04-16 11:42:41 +00:00
2022-04-18 18:13:50 +00:00
The `adjust_entry_price()` callback may be used by strategy developer to refresh/replace limit orders upon arrival of new candles.
2022-04-16 11:42:41 +00:00
Be aware that `custom_entry_price()` is still the one dictating initial entry limit order price target at the time of entry trigger.
2022-05-06 07:13:29 +00:00
Orders can be cancelled out of this callback by returning `None` .
2022-04-16 11:42:41 +00:00
2022-05-06 04:23:06 +00:00
Returning `current_order_rate` will keep the order on the exchange "as is".
Returning any other price will cancel the existing order, and replace it with a new order.
2022-04-28 21:10:17 +00:00
2022-05-06 04:23:06 +00:00
The trade open-date (`trade.open_date_utc`) will remain at the time of the very first order placed.
2022-05-06 07:13:29 +00:00
Please make sure to be aware of this - and eventually adjust your logic in other callbacks to account for this, and use the date of the first filled order instead.
2022-05-06 04:23:06 +00:00
2023-09-21 18:45:06 +00:00
If the cancellation of the original order fails, then the order will not be replaced - though the order will most likely have been canceled on exchange. Having this happen on initial entries will result in the deletion of the order, while on position adjustment orders, it'll result in the trade size remaining as is.
2022-05-06 04:23:06 +00:00
!!! Warning "Regular timeout"
Entry `unfilledtimeout` mechanism (as well as `check_entry_timeout()` ) takes precedence over this.
Entry Orders that are cancelled via the above methods will not have this callback called. Be sure to update timeout values to match your expectations.
2022-04-16 11:42:41 +00:00
```python
from freqtrade.persistence import Trade
2024-04-09 17:26:52 +00:00
from datetime import timedelta, datetime
2022-04-16 11:42:41 +00:00
class AwesomeStrategy(IStrategy):
# ... populate_* methods
2022-04-28 21:10:17 +00:00
def adjust_entry_price(self, trade: Trade, order: Optional[Order], pair: str,
current_time: datetime, proposed_rate: float, current_order_rate: float,
entry_tag: Optional[str], side: str, **kwargs) -> float:
2022-04-16 11:42:41 +00:00
"""
2022-04-18 18:13:50 +00:00
Entry price re-adjustment logic, returning the user desired limit price.
2022-05-06 04:23:06 +00:00
This only executes when a order was already placed, still open (unfilled fully or partially)
2022-04-18 18:13:50 +00:00
and not timed out on subsequent candles after entry trigger.
2022-04-16 11:42:41 +00:00
2022-04-28 21:10:17 +00:00
When not implemented by a strategy, returns current_order_rate as default.
If current_order_rate is returned then the existing order is maintained.
If None is returned then order gets canceled but not replaced by a new one.
2022-04-16 11:42:41 +00:00
:param pair: Pair that's currently analyzed
:param trade: Trade object.
2022-04-18 18:13:50 +00:00
:param order: Order object
2022-04-16 11:42:41 +00:00
:param current_time: datetime object, containing the current datetime
2022-04-28 21:10:17 +00:00
:param proposed_rate: Rate, calculated based on pricing settings in entry_pricing.
:param current_order_rate: Rate of the existing order in place.
2022-04-16 11:42:41 +00:00
:param entry_tag: Optional entry_tag (buy_tag) if provided with the buy signal.
:param side: 'long' or 'short' - indicating the direction of the proposed trade
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
:return float: New entry price value if provided
"""
# Limit orders to use and follow SMA200 as price target for the first 10 minutes since entry trigger for BTC/USDT pair.
2023-01-22 10:17:31 +00:00
if pair == 'BTC/USDT' and entry_tag == 'long_sma200' and side == 'long' and (current_time - timedelta(minutes=10)) > trade.open_date_utc:
2022-05-07 15:47:37 +00:00
# just cancel the order if it has been filled more than half of the amount
2022-04-18 18:13:50 +00:00
if order.filled > order.remaining:
return None
else:
dataframe, _ = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe)
current_candle = dataframe.iloc[-1].squeeze()
2022-04-28 21:10:17 +00:00
# desired price
2022-04-18 18:13:50 +00:00
return current_candle['sma_200']
2022-04-28 21:10:17 +00:00
# default: maintain existing order
return current_order_rate
2022-04-16 11:42:41 +00:00
```
2021-11-21 08:13:53 +00:00
## Leverage Callback
When trading in markets that allow leverage, this method must return the desired Leverage (Defaults to 1 -> No leverage).
Assuming a capital of 500USDT, a trade with leverage=3 would result in a position with 500 x 3 = 1500 USDT.
Values that are above `max_leverage` will be adjusted to `max_leverage` .
For markets / exchanges that don't support leverage, this method is ignored.
``` python
class AwesomeStrategy(IStrategy):
2022-06-05 08:21:06 +00:00
def leverage(self, pair: str, current_time: datetime, current_rate: float,
proposed_leverage: float, max_leverage: float, entry_tag: Optional[str], side: str,
2021-11-21 08:13:53 +00:00
**kwargs) -> float:
"""
2022-06-05 08:21:06 +00:00
Customize leverage for each new trade. This method is only called in futures mode.
2021-11-21 08:13:53 +00:00
:param pair: Pair that's currently analyzed
:param current_time: datetime object, containing the current datetime
2022-03-27 16:03:49 +00:00
:param current_rate: Rate, calculated based on pricing settings in exit_pricing.
2021-11-21 08:13:53 +00:00
:param proposed_leverage: A leverage proposed by the bot.
:param max_leverage: Max leverage allowed on this pair
2022-06-05 08:21:06 +00:00
:param entry_tag: Optional entry_tag (buy_tag) if provided with the buy signal.
2021-11-21 08:13:53 +00:00
:param side: 'long' or 'short' - indicating the direction of the proposed trade
:return: A leverage amount, which is between 1.0 and max_leverage.
"""
return 1.0
2022-03-05 14:05:03 +00:00
```
2022-06-16 17:50:13 +00:00
All profit calculations include leverage. Stoploss / ROI also include leverage in their calculation.
Defining a stoploss of 10% at 10x leverage would trigger the stoploss with a 1% move to the downside.
2024-03-19 01:38:58 +00:00
## Order filled Callback
2024-03-28 05:49:02 +00:00
The `order_filled()` callback may be used to perform specific actions based on the current trade state after an order is filled.
2024-03-28 18:36:43 +00:00
It will be called independent of the order type (entry, exit, stoploss or position adjustment).
2024-03-19 01:38:58 +00:00
2024-03-28 05:49:02 +00:00
Assuming that your strategy needs to store the high value of the candle at trade entry, this is possible with this callback as the following example show.
2024-03-19 01:38:58 +00:00
``` python
class AwesomeStrategy(IStrategy):
def order_filled(self, pair: str, trade: Trade, order: Order, current_time: datetime, **kwargs) -> None:
"""
2024-03-28 05:49:02 +00:00
Called right after an order fills.
Will be called for all order types (entry, exit, stoploss, position adjustment).
:param pair: Pair for trade
2024-03-19 01:38:58 +00:00
:param trade: trade object.
2024-03-28 05:49:02 +00:00
:param order: Order object.
2024-03-19 01:38:58 +00:00
:param current_time: datetime object, containing the current datetime
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
"""
# Obtain pair dataframe (just to show how to access it)
dataframe, _ = self.dp.get_analyzed_dataframe(trade.pair, self.timeframe)
last_candle = dataframe.iloc[-1].squeeze()
if (trade.nr_of_successful_entries == 1) and (order.ft_order_side == trade.entry_side):
trade.set_custom_data(key='entry_candle_high', value=last_candle['high'])
return None
```