Freqtrade: Force Exit After Stoploss Timeout
Hey guys! Let's dive into a common challenge in the world of crypto trading, particularly when you're using Freqtrade: Dealing with stoploss orders and market volatility. Sometimes, you set a custom stoploss, and it gets triggered, but the exit order lingers, causing you to eat a bigger loss than you planned for. I am going to help you with this issue, so you can avoid unnecessary financial setbacks.
The Problem: Delayed Exit Orders and Market Swings
The scenario: You've got your Freqtrade bot running, and you've configured a custom stoploss strategy. The market takes a dive, your stoploss triggers, and an exit order is placed. Now, here's where things can go south. The exit order, perhaps a limit order, needs to be filled. But in the fast-paced world of crypto, market conditions can change drastically in minutes. The price might continue to plummet, leaving your order unfilled and your losses piling up. This is what we are addressing here.
In many situations, the default behavior is to wait for the order to fill. This might be okay in stable markets, but it's a recipe for disaster during volatile times. You are left with a pending order and a sinking feeling as your potential losses increase. What we want is a way to ensure a swift exit when a stoploss is triggered, even if it means accepting a slightly less favorable price.
The Solution: Force Market Exit After a Timeout
So, what's the fix? Implementing a custom stoploss with a forced market exit after a set timeout. This approach combines the precision of a custom stoploss with the immediacy of a market order when the situation demands it. The core idea is simple: When your stoploss is triggered, place your exit order (let's say a limit order). But if it's not filled within a certain timeframe (e.g., 1 minute), automatically switch to a market order to get you out immediately.
This method gives you the best of both worlds. Initially, you try to get the best price with a limit order. But if the market isn't cooperating, you avoid being stuck, protecting your capital by executing the market order.
Implementing the Custom Stoploss Logic
Let's go through the code. First, the usual imports and strategy setup. Then, you'll define your custom_stop_loss
function.
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
# flake8: noqa: F401
# isort: skip_file
# --- Do not remove these imports ---
import numpy as np
import pandas as pd
from datetime import datetime, timedelta, timezone
from pandas import DataFrame
from typing import Dict, Optional, Union, Tuple
from freqtrade.strategy import (
IStrategy,
Trade,
Order,
PairLocks,
informative, # @informative decorator
# Hyperopt Parameters
BooleanParameter,
CategoricalParameter,
DecimalParameter,
IntParameter,
RealParameter,
# timeframe helpers
timeframe_to_minutes,
timeframe_to_next_date,
timeframe_to_prev_date,
# Strategy helper functions
merge_informative_pair,
stoploss_from_absolute,
stoploss_from_open,
AnnotationType,
)
# --------------------------------
# Add your lib to import here
import talib.abstract as ta
from technical import qtpylib
slh: dict[str, dict] = {}
class BBandsRSI(IStrategy):
# Strategy interface version
INTERFACE_VERSION = 3
# Optimal timeframe for the strategy.
timeframe = "5m"
# Can this strategy go short?
can_short: bool = False
# Minimal ROI designed for the strategy.
minimal_roi = {
"60": 0.01,
"30": 0.02,
"0": 0.04
}
# Optimal stoploss designed for the strategy.
stoploss = -0.10
# Trailing stoploss
trailing_stop = False
# Run "populate_indicators()" only for new candle.
process_only_new_candles = True
# These values can be overridden in the config.
use_exit_signal = True
exit_profit_only = False
ignore_roi_if_entry_signal = False
# Number of candles the strategy requires before producing valid signals
startup_candle_count: int = 30
# Strategy parameters
buy_rsi = IntParameter(10, 40, default=30, space="buy")
sell_rsi = IntParameter(60, 90, default=70, space="sell")
# Optional order type mapping.
order_types = {
"entry": "limit",
"exit": "limit",
"stoploss": "market",
"stoploss_on_exchange": False
}
# Optional order time in force.
order_time_in_force = {
"entry": "GTC",
"exit": "GTC"
}
@property
def plot_config(self):
return {
"main_plot": {
# Add OHLC data to main plot
"bb_upperband": {"color": "grey"},
"bb_middleband": {"color": "red"},
"bb_lowerband": {"color": "grey"},
},
"subplots": {
# Subplots - each dict defines one additional plot
"RSI": {
"rsi": {"color": "blue"},
"overbought": {"color": "red", "type": "line"},
"oversold": {"color": "green", "type": "line"}
}
}
}
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# RSI
dataframe["rsi"] = ta.RSI(dataframe, timeperiod=14)
dataframe["overbought"] = 70
dataframe["oversold"] = 30
# Bollinger Bands
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
dataframe["bb_lowerband"] = bollinger["lower"]
dataframe["bb_middleband"] = bollinger["mid"]
dataframe["bb_upperband"] = bollinger["upper"]
dataframe["bb_percent"] = (
(dataframe["close"] - dataframe["bb_lowerband"]) /
(dataframe["bb_upperband"] - dataframe["bb_lowerband"])
)
dataframe["bb_width"] = (
(dataframe["bb_upperband"] - dataframe["bb_lowerband"]) / dataframe["bb_middleband"]
)
return dataframe
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe.loc[
(
(dataframe["rsi"] < self.buy_rsi.value) & # RSI oversold
(dataframe["close"] <= dataframe["bb_lowerband"]) & # Price at lower BB
(dataframe["volume"] > 0) # Make sure Volume is not 0
),
"enter_long"] = 1
return dataframe
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe.loc[
(
(dataframe["rsi"] > self.sell_rsi.value) | # RSI overbought
(dataframe["close"] >= dataframe["bb_upperband"]) & # Price at upper BB
(dataframe["volume"] > 0) # Make sure Volume is not 0
),
"exit_long"] = 1
return dataframe
# even after 1 minute after stoploss hit, if exit order is still pending, use market price to exit immediately
def custom_exit(self, pair: str, trade: Trade, current_time: datetime, current_rate: float,
current_profit: float, **kwargs):
tradeID = trade.id
if current_profit < self.stoploss:
if tradeID in slh:
# Stop loss already hit, check if > 1 minute
when_hit = slh[tradeID]["when_hit"]
if datetime.now() - when_hit > timedelta(minutes=1):
# sell at market price immediately
del slh[tradeID]
return {
"exit_reason": "force_stoploss",
"sell_type": "force_exit" # ensures market order if configured
}
return True
else:
slh[tradeID] = {
"is_stop_loss_hit": True,
"when_hit": datetime.now()
}
return None
Step-by-Step Implementation
- Import Necessary Libraries: Make sure you have the required libraries like
pandas
,datetime
, and anything else your strategy needs. - Define the
slh
Dictionary: This is a dictionary we will be using for tracking the time when the stoploss was hit for a given trade. It's crucial for timing. - Implement the
custom_exit
Function: This function will handle the logic for your custom stoploss. It checks for the stoploss condition.- Check Profit: It first checks if the
current_profit
is below your stoploss level. - Track Stoploss Trigger: If the stoploss is triggered, the code checks if this is the first time the stoploss has been hit for this trade using
slh
. If it is the first time, it stores the current time to be able to check for the timeout. - Timeout Check: If the stoploss has been triggered before, the code calculates if more than 1 minute has passed since the stoploss was hit using
datetime.now() - when_hit > timedelta(minutes=1)
. If the timeout has passed, the code will return a dictionary to execute the market order. - Force Market Exit: If the timeout has been reached, the function returns a dictionary with
exit_reason
set to `
- Check Profit: It first checks if the