This is a strategy template to get you started. More information in https://www.freqtrade.io/en/stable/strategy-customization/
Timeframe
5m
Direction
Long Only
Stoploss
-4.5%
Trailing Stop
Yes
ROI
0m: 3.5%, 30m: 2.0%, 90m: 0.8%, 180m: 0.4%
Interface Version
3
Startup Candles
N/A
Indicators
19
freqtrade/freqtrade-strategies
Strategy 003 author@: Gerald Lonlas github@: https://github.com/freqtrade/freqtrade-strategies
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
# flake8: noqa: F401
# isort: skip_file
# Candidate V2 - FVG Pullback Long Only
# Backtest 20260101-20260508:
# Trades: 76
# Profit: +1.82%
# PF: 1.85
# DD: 1.06%
# --- Do not remove these imports ---
import logging
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.persistence import Trade
from freqtrade.strategy import (
IStrategy,
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
logger = logging.getLogger(__name__)
class FAST_V34_RECOVERED_20260511(IStrategy):
"""
This is a strategy template to get you started.
More information in https://www.freqtrade.io/en/stable/strategy-customization/
You can:
:return: a Dataframe with all mandatory indicators for the strategies
- Rename the class name (Do not forget to update class_name)
- Add any methods you want to build your strategy
- Add any lib you need to build your strategy
You must keep:
- the lib in the section "Do not remove these libs"
- the methods: populate_indicators, populate_entry_trend, populate_exit_trend
You should keep:
- timeframe, minimal_roi, stoploss, trailing_*
"""
# Strategy interface version - allow new iterations of the strategy interface.
# Check the documentation or the Sample strategy to get the latest 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.
# This attribute will be overridden if the config file contains "minimal_roi".
minimal_roi = {
"0": 0.035,
"30": 0.020,
"90": 0.008,
"180": 0.004
}
# Optimal stoploss designed for the strategy.
# This attribute will be overridden if the config file contains "stoploss".
stoploss = -0.045
# Trailing stoploss
trailing_stop = True
trailing_stop_positive = 0.012
trailing_stop_positive_offset = 0.025
trailing_only_offset_is_reached = True
# Run "populate_indicators()" only for new candle.
process_only_new_candles = True
# These values can be overridden in the config.
use_exit_signal = False
exit_profit_only = False
ignore_roi_if_entry_signal = False
# Number of candles the strategy requires before producing valid signals
startup_candle_count: int = 200
protections = [
{
"method": "StoplossGuard",
"lookback_period_candles": 48,
"trade_limit": 2,
"stop_duration_candles": 24,
"only_per_pair": False
},
{
"method": "MaxDrawdown",
"lookback_period_candles": 96,
"trade_limit": 10,
"stop_duration_candles": 48,
"max_allowed_drawdown": 0.08
},
{
"method": "CooldownPeriod",
"stop_duration_candles": 4
}
]
# 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 indicators (Moving averages, ...)
"main_plot": {
"tema": {},
"sar": {"color": "white"},
},
"subplots": {
# Subplots - each dict defines one additional plot
"MACD": {
"macd": {"color": "blue"},
"macdsignal": {"color": "orange"},
},
"RSI": {
"rsi": {"color": "red"},
}
}
}
def informative_pairs(self):
"""
Define additional, informative pair/interval combinations to be cached from the exchange.
These pair/interval combinations are non-tradeable, unless they are part
of the whitelist as well.
For more information, please consult the documentation
:return: List of tuples in the format (pair, interval)
Sample: return [("ETH/USDT", "5m"),
("BTC/USDT", "15m"),
]
"""
return []
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
"""
Adds several different TA indicators to the given DataFrame
Performance Note: For the best performance be frugal on the number of indicators
you are using. Let uncomment only the indicator you are using in your strategies
or your hyperopt configuration, otherwise you will waste your memory and CPU usage.
:param dataframe: Dataframe with data from the exchange
:param metadata: Additional information, like the currently traded pair
:return: a Dataframe with all mandatory indicators for the strategies
"""
# Momentum Indicators
# ------------------------------------
# ADX
dataframe["adx"] = ta.ADX(dataframe)
# # Plus Directional Indicator / Movement
# dataframe["plus_dm"] = ta.PLUS_DM(dataframe)
# dataframe["plus_di"] = ta.PLUS_DI(dataframe)
# # Minus Directional Indicator / Movement
# dataframe["minus_dm"] = ta.MINUS_DM(dataframe)
# dataframe["minus_di"] = ta.MINUS_DI(dataframe)
# # Aroon, Aroon Oscillator
# aroon = ta.AROON(dataframe)
# dataframe["aroonup"] = aroon["aroonup"]
# dataframe["aroondown"] = aroon["aroondown"]
# dataframe["aroonosc"] = ta.AROONOSC(dataframe)
# # Awesome Oscillator
# dataframe["ao"] = qtpylib.awesome_oscillator(dataframe)
# # Keltner Channel
# keltner = qtpylib.keltner_channel(dataframe)
# dataframe["kc_upperband"] = keltner["upper"]
# dataframe["kc_lowerband"] = keltner["lower"]
# dataframe["kc_middleband"] = keltner["mid"]
# dataframe["kc_percent"] = (
# (dataframe["close"] - dataframe["kc_lowerband"]) /
# (dataframe["kc_upperband"] - dataframe["kc_lowerband"])
# )
# dataframe["kc_width"] = (
# (dataframe["kc_upperband"] - dataframe["kc_lowerband"]) / dataframe["kc_middleband"]
# )
# # Ultimate Oscillator
# dataframe["uo"] = ta.ULTOSC(dataframe)
# # Commodity Channel Index: values [Oversold:-100, Overbought:100]
# dataframe["cci"] = ta.CCI(dataframe)
# EMA
dataframe["ema20"] = ta.EMA(dataframe, timeperiod=20)
dataframe["ema50"] = ta.EMA(dataframe, timeperiod=50)
dataframe["ema200"] = ta.EMA(dataframe, timeperiod=200)
# RSI
dataframe["rsi"] = ta.RSI(dataframe, timeperiod=14)
dataframe["adx"] = ta.ADX(dataframe, timeperiod=14)
dataframe["plus_di"] = ta.PLUS_DI(dataframe, timeperiod=14)
dataframe["minus_di"] = ta.MINUS_DI(dataframe, timeperiod=14)
# # Inverse Fisher transform on RSI: values [-1.0, 1.0] (https://goo.gl/2JGGoy)
# rsi = 0.1 * (dataframe["rsi"] - 50)
# dataframe["fisher_rsi"] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1)
# # Inverse Fisher transform on RSI normalized: values [0.0, 100.0] (https://goo.gl/2JGGoy)
# dataframe["fisher_rsi_norma"] = 50 * (dataframe["fisher_rsi"] + 1)
# # Stochastic Slow
# stoch = ta.STOCH(dataframe)
# dataframe["slowd"] = stoch["slowd"]
# dataframe["slowk"] = stoch["slowk"]
# Stochastic Fast
stoch_fast = ta.STOCHF(dataframe)
dataframe["fastd"] = stoch_fast["fastd"]
dataframe["fastk"] = stoch_fast["fastk"]
# # Stochastic RSI
# Please read https://github.com/freqtrade/freqtrade/issues/2961 before using this.
# STOCHRSI is NOT aligned with tradingview, which may result in non-expected results.
# stoch_rsi = ta.STOCHRSI(dataframe)
# dataframe["fastd_rsi"] = stoch_rsi["fastd"]
# dataframe["fastk_rsi"] = stoch_rsi["fastk"]
# MACD
macd = ta.MACD(dataframe)
dataframe["macd"] = macd["macd"]
dataframe["macdsignal"] = macd["macdsignal"]
dataframe["macdhist"] = dataframe["macd"] - dataframe["macdsignal"]
# ATR
dataframe["atr"] = ta.ATR(dataframe, timeperiod=14)
dataframe["atr_mean"] = dataframe["atr"].rolling(20).mean()
dataframe["volatility"] = (
dataframe["high"] - dataframe["low"]
) / dataframe["close"]
dataframe["volume_mean"] = dataframe["volume"].rolling(30).mean()
dataframe["ema50_slope"] = dataframe["ema50"] - dataframe["ema50"].shift(3)
# Bullish FVG Detection
dataframe["bullish_fvg"] = dataframe["low"] > dataframe["high"].shift(2)
dataframe["fvg_bottom_raw"] = dataframe["high"].shift(2)
dataframe["fvg_top_raw"] = dataframe["low"]
dataframe.loc[~dataframe["bullish_fvg"], "fvg_bottom_raw"] = None
dataframe.loc[~dataframe["bullish_fvg"], "fvg_top_raw"] = None
dataframe["fvg_bottom"] = dataframe["fvg_bottom_raw"].ffill()
dataframe["fvg_top"] = dataframe["fvg_top_raw"].ffill()
dataframe["fvg_bottom"] = dataframe["fvg_bottom"].shift(1)
dataframe["fvg_top"] = dataframe["fvg_top"].shift(1)
last_fvg_index = None
fvg_ages = []
for i, is_fvg in enumerate(dataframe["bullish_fvg"]):
if is_fvg:
last_fvg_index = i
if last_fvg_index is None:
fvg_ages.append(999)
else:
fvg_ages.append(i - last_fvg_index)
dataframe["fvg_age"] = fvg_ages
dataframe["fvg_age"] = dataframe["fvg_age"].shift(1)
# Bullish Order Block Detection
dataframe["bearish_candle"] = dataframe["close"] < dataframe["open"]
dataframe["strong_bullish_move"] = (
(dataframe["close"] > dataframe["open"]) &
((dataframe["close"] - dataframe["open"]) > dataframe["atr"] * 0.6)
)
dataframe["bullish_ob"] = (
dataframe["bearish_candle"].shift(1).fillna(False) &
dataframe["strong_bullish_move"]
)
dataframe["ob_low_raw"] = dataframe["low"].shift(1)
dataframe["ob_high_raw"] = dataframe["high"].shift(1)
dataframe.loc[~dataframe["bullish_ob"], "ob_low_raw"] = None
dataframe.loc[~dataframe["bullish_ob"], "ob_high_raw"] = None
dataframe["ob_low"] = dataframe["ob_low_raw"].ffill().shift(1)
dataframe["ob_high"] = dataframe["ob_high_raw"].ffill().shift(1)
last_ob_index = None
ob_ages = []
for i, is_ob in enumerate(dataframe["bullish_ob"]):
if is_ob:
last_ob_index = i
if last_ob_index is None:
ob_ages.append(999)
else:
ob_ages.append(i - last_ob_index)
dataframe["ob_age"] = ob_ages
dataframe["ob_age"] = dataframe["ob_age"].shift(1)
btc_df = self.dp.get_pair_dataframe(
pair="BTC/USDT:USDT",
timeframe=self.timeframe
)
btc_df["btc_ema20"] = ta.EMA(btc_df, timeperiod=20)
btc_df["btc_ema50"] = ta.EMA(btc_df, timeperiod=50)
dataframe["btc_bull"] = (
btc_df["btc_ema20"] > btc_df["btc_ema50"]
).astype(int)
# MFI
dataframe["mfi"] = ta.MFI(dataframe)
# # ROC
# dataframe["roc"] = ta.ROC(dataframe)
# Overlap Studies
# ------------------------------------
# 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"]
)
# Bollinger Bands - Weighted (EMA based instead of SMA)
# weighted_bollinger = qtpylib.weighted_bollinger_bands(
# qtpylib.typical_price(dataframe), window=20, stds=2
# )
# dataframe["wbb_upperband"] = weighted_bollinger["upper"]
# dataframe["wbb_lowerband"] = weighted_bollinger["lower"]
# dataframe["wbb_middleband"] = weighted_bollinger["mid"]
# dataframe["wbb_percent"] = (
# (dataframe["close"] - dataframe["wbb_lowerband"]) /
# (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"])
# )
# dataframe["wbb_width"] = (
# (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) / dataframe["wbb_middleband"]
# )
# # EMA - Exponential Moving Average
# dataframe["ema3"] = ta.EMA(dataframe, timeperiod=3)
# dataframe["ema5"] = ta.EMA(dataframe, timeperiod=5)
# dataframe["ema10"] = ta.EMA(dataframe, timeperiod=10)
# dataframe["ema21"] = ta.EMA(dataframe, timeperiod=21)
# dataframe["ema50"] = ta.EMA(dataframe, timeperiod=50)
# dataframe["ema100"] = ta.EMA(dataframe, timeperiod=100)
# # SMA - Simple Moving Average
# dataframe["sma3"] = ta.SMA(dataframe, timeperiod=3)
# dataframe["sma5"] = ta.SMA(dataframe, timeperiod=5)
# dataframe["sma10"] = ta.SMA(dataframe, timeperiod=10)
# dataframe["sma21"] = ta.SMA(dataframe, timeperiod=21)
# dataframe["sma50"] = ta.SMA(dataframe, timeperiod=50)
# dataframe["sma100"] = ta.SMA(dataframe, timeperiod=100)
# Parabolic SAR
dataframe["sar"] = ta.SAR(dataframe)
# TEMA - Triple Exponential Moving Average
dataframe["tema"] = ta.TEMA(dataframe, timeperiod=9)
# Cycle Indicator
# ------------------------------------
# Hilbert Transform Indicator - SineWave
hilbert = ta.HT_SINE(dataframe)
dataframe["htsine"] = hilbert["sine"]
dataframe["htleadsine"] = hilbert["leadsine"]
# Pattern Recognition - Bullish candlestick patterns
# ------------------------------------
# # Hammer: values [0, 100]
# dataframe["CDLHAMMER"] = ta.CDLHAMMER(dataframe)
# # Inverted Hammer: values [0, 100]
# dataframe["CDLINVERTEDHAMMER"] = ta.CDLINVERTEDHAMMER(dataframe)
# # Dragonfly Doji: values [0, 100]
# dataframe["CDLDRAGONFLYDOJI"] = ta.CDLDRAGONFLYDOJI(dataframe)
# # Piercing Line: values [0, 100]
# dataframe["CDLPIERCING"] = ta.CDLPIERCING(dataframe) # values [0, 100]
# # Morningstar: values [0, 100]
# dataframe["CDLMORNINGSTAR"] = ta.CDLMORNINGSTAR(dataframe) # values [0, 100]
# # Three White Soldiers: values [0, 100]
# dataframe["CDL3WHITESOLDIERS"] = ta.CDL3WHITESOLDIERS(dataframe) # values [0, 100]
# Pattern Recognition - Bearish candlestick patterns
# ------------------------------------
# # Hanging Man: values [0, 100]
# dataframe["CDLHANGINGMAN"] = ta.CDLHANGINGMAN(dataframe)
# # Shooting Star: values [0, 100]
# dataframe["CDLSHOOTINGSTAR"] = ta.CDLSHOOTINGSTAR(dataframe)
# # Gravestone Doji: values [0, 100]
# dataframe["CDLGRAVESTONEDOJI"] = ta.CDLGRAVESTONEDOJI(dataframe)
# # Dark Cloud Cover: values [0, 100]
# dataframe["CDLDARKCLOUDCOVER"] = ta.CDLDARKCLOUDCOVER(dataframe)
# # Evening Doji Star: values [0, 100]
# dataframe["CDLEVENINGDOJISTAR"] = ta.CDLEVENINGDOJISTAR(dataframe)
# # Evening Star: values [0, 100]
# dataframe["CDLEVENINGSTAR"] = ta.CDLEVENINGSTAR(dataframe)
# Pattern Recognition - Bullish/Bearish candlestick patterns
# ------------------------------------
# # Three Line Strike: values [0, -100, 100]
# dataframe["CDL3LINESTRIKE"] = ta.CDL3LINESTRIKE(dataframe)
# # Spinning Top: values [0, -100, 100]
# dataframe["CDLSPINNINGTOP"] = ta.CDLSPINNINGTOP(dataframe) # values [0, -100, 100]
# # Engulfing: values [0, -100, 100]
# dataframe["CDLENGULFING"] = ta.CDLENGULFING(dataframe) # values [0, -100, 100]
# # Harami: values [0, -100, 100]
# dataframe["CDLHARAMI"] = ta.CDLHARAMI(dataframe) # values [0, -100, 100]
# # Three Outside Up/Down: values [0, -100, 100]
# dataframe["CDL3OUTSIDE"] = ta.CDL3OUTSIDE(dataframe) # values [0, -100, 100]
# # Three Inside Up/Down: values [0, -100, 100]
# dataframe["CDL3INSIDE"] = ta.CDL3INSIDE(dataframe) # values [0, -100, 100]
# # Chart type
# # ------------------------------------
# # Heikin Ashi Strategy
# heikinashi = qtpylib.heikinashi(dataframe)
# dataframe["ha_open"] = heikinashi["open"]
# dataframe["ha_close"] = heikinashi["close"]
# dataframe["ha_high"] = heikinashi["high"]
# dataframe["ha_low"] = heikinashi["low"]
# Retrieve best bid and best ask from the orderbook
# ------------------------------------
"""
# first check if dataprovider is available
if self.dp:
if self.dp.runmode.value in ("live", "dry_run"):
ob = self.dp.orderbook(metadata["pair"], 1)
dataframe["best_bid"] = ob["bids"][0][0]
dataframe["best_ask"] = ob["asks"][0][0]
"""
# ============================================================
# Liquidity Sweep + Stochastic RSI - Fast Strategy Addon
# ============================================================
dataframe["prev_swing_low"] = dataframe["low"].rolling(20).min().shift(1)
dataframe["prev_swing_high"] = dataframe["high"].rolling(20).max().shift(1)
dataframe["bullish_liquidity_sweep"] = (
(dataframe["low"] < dataframe["prev_swing_low"]) &
(dataframe["close"] > dataframe["prev_swing_low"])
).astype(int)
dataframe["bearish_liquidity_sweep"] = (
(dataframe["high"] > dataframe["prev_swing_high"]) &
(dataframe["close"] < dataframe["prev_swing_high"])
).astype(int)
dataframe["bullish_sweep_recent"] = (
dataframe["bullish_liquidity_sweep"].rolling(8).max() > 0
).astype(int)
rsi_len = 14
stoch_len = 14
smooth_k = 3
smooth_d = 3
rsi = ta.RSI(dataframe, timeperiod=rsi_len)
rsi_min = rsi.rolling(stoch_len).min()
rsi_max = rsi.rolling(stoch_len).max()
dataframe["stoch_rsi_k"] = (
100 * (rsi - rsi_min) / (rsi_max - rsi_min)
).replace([float("inf"), -float("inf")], 0).fillna(0)
dataframe["stoch_rsi_k"] = dataframe["stoch_rsi_k"].rolling(smooth_k).mean()
dataframe["stoch_rsi_d"] = dataframe["stoch_rsi_k"].rolling(smooth_d).mean()
dataframe["stoch_rsi_bull_cross"] = (
(dataframe["stoch_rsi_k"] > dataframe["stoch_rsi_d"]) &
(dataframe["stoch_rsi_k"].shift(1) <= dataframe["stoch_rsi_d"].shift(1)) &
(dataframe["stoch_rsi_k"] < 45)
).astype(int)
dataframe["fvg_pullback"] = (
(dataframe["fvg_age"] <= 20) &
(dataframe["low"] <= dataframe["fvg_top"] * 1.008) &
(dataframe["close"] >= dataframe["fvg_bottom"] * 0.997)
).astype(int)
dataframe["ob_pullback"] = (
(dataframe["ob_age"] <= 30) &
(dataframe["low"] <= dataframe["ob_high"] * 1.005) &
(dataframe["close"] >= dataframe["ob_low"] * 0.995)
).astype(int)
# ============================================================
# Momentum Breakout Detector
# ============================================================
dataframe["highest_48"] = dataframe["high"].rolling(48).max().shift(1)
dataframe["volume_mean_48"] = dataframe["volume"].rolling(48).mean()
dataframe["price_change_12"] = (
(dataframe["close"] / dataframe["close"].shift(12) - 1) * 100
)
dataframe["breakout_48"] = (
dataframe["close"] > dataframe["highest_48"]
).astype(int)
dataframe["volume_spike_2x"] = (
dataframe["volume"] > dataframe["volume_mean_48"] * 2.0
).astype(int)
dataframe["not_too_extended"] = (
dataframe["close"] < dataframe["ema20"] * 1.06
).astype(int)
# ============================================================
# Breakout Retest Logic
# ============================================================
dataframe["breakout_level"] = dataframe["highest_48"]
dataframe["breakout_recent"] = (
dataframe["breakout_48"].rolling(12).max() > 0
).astype(int)
dataframe["breakout_retest"] = (
(dataframe["breakout_recent"] == 1) &
(dataframe["low"] <= dataframe["breakout_level"] * 1.01) &
(dataframe["close"] > dataframe["breakout_level"]) &
(dataframe["close"] > dataframe["open"])
).astype(int)
dataframe["breakout_extension_ok"] = (
dataframe["close"] < dataframe["ema20"] * 1.035
).astype(int)
dataframe["volume_spike_recent"] = (
dataframe["volume_spike_2x"].rolling(12).max() > 0
).astype(int)
# ============================================================
# V3.4 Weakness Score
# ============================================================
dataframe["ema_extension_pct_v34"] = (
(dataframe["close"] - dataframe["ema20"]).abs() /
dataframe["ema20"] * 100
)
dataframe["di_gap_v34"] = (
dataframe["plus_di"] - dataframe["minus_di"]
).abs()
dataframe["candle_body_v34"] = (
dataframe["close"] - dataframe["open"]
).abs()
dataframe["candle_range_v34"] = (
dataframe["high"] - dataframe["low"]
).replace(0, 0.0000001)
dataframe["body_ratio_v34"] = (
dataframe["candle_body_v34"] / dataframe["candle_range_v34"]
)
dataframe["upper_wick_v34"] = (
dataframe["high"] - dataframe[["open", "close"]].max(axis=1)
)
dataframe["upper_wick_ratio_v34"] = (
dataframe["upper_wick_v34"] / dataframe["candle_range_v34"]
)
dataframe["weak_extension_v34"] = (
dataframe["ema_extension_pct_v34"] > 1.2
).astype(int)
dataframe["weak_adx_v34"] = (
dataframe["adx"] < 20
).astype(int)
dataframe["weak_di_v34"] = (
dataframe["di_gap_v34"] < 3
).astype(int)
dataframe["weak_high_v34"] = (
dataframe["upper_wick_ratio_v34"] > 0.45
).astype(int)
dataframe["weak_candle_v34"] = (
dataframe["body_ratio_v34"] < 0.35
).astype(int)
dataframe["weakness_score_v34"] = (
dataframe["weak_extension_v34"] +
dataframe["weak_adx_v34"] +
dataframe["weak_di_v34"] +
dataframe["weak_high_v34"] +
dataframe["weak_candle_v34"]
)
dataframe["weakness_ok_v34"] = (
dataframe["weakness_score_v34"] < 2
).astype(int)
dataframe["v34_debug"] = dataframe["weakness_score_v34"]
return dataframe
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
"""
Based on TA indicators, populates the entry signal for the given dataframe
:param dataframe: DataFrame
:param metadata: Additional information, like the currently traded pair
:return: DataFrame with entry columns populated
"""
# ============================================================
# Fast V2.1 Entry - Liquidity Sweep + Smart Pullback
# ============================================================
trend_filter = (
(dataframe["ema20"] > dataframe["ema50"]) &
(dataframe["ema50"] > dataframe["ema200"])
)
pullback_filter = (
(dataframe["close"] > dataframe["ema50"]) &
(dataframe["close"] < dataframe["ema50"] * 1.03) &
(dataframe["rsi"] > 45) &
(dataframe["rsi"] < 64)
)
momentum_filter = (
(dataframe["macdhist"] > 0) &
(dataframe["adx"] > 20)
)
volume_filter = (
dataframe["volume"] > dataframe["volume_mean"] * 1.1
)
atr_filter = (
dataframe["atr"] > dataframe["atr_mean"] * 1.2
)
fvg_pullback = dataframe["fvg_pullback"] == 1
ob_pullback = dataframe["ob_pullback"] == 1
smart_zone_filter = (
(dataframe["bullish_sweep_recent"] == 1) |
(dataframe["stoch_rsi_bull_cross"] == 1) |
fvg_pullback |
ob_pullback
)
dataframe.loc[
(
False &
trend_filter &
pullback_filter &
momentum_filter &
volume_filter &
atr_filter &
smart_zone_filter
),
["enter_long", "enter_tag"]
] = (1, "FAST_LIQ_SWEEP_STOCH")
# ============================================================
# Fast Breakout Retest Entry - safer than chasing breakout candle
# ============================================================
breakout_entry = (
(dataframe["ema20"] > dataframe["ema50"]) &
(dataframe["ema50"] > dataframe["ema200"]) &
# Breakout + retest logic
(dataframe["breakout_recent"] == 1) &
(dataframe["volume_spike_recent"] == 1) &
(dataframe["breakout_retest"] == 1) &
# Momentum filters
(dataframe["adx"] >= 25) &
(dataframe["rsi"] > 50) &
(dataframe["rsi"] < 70) &
(dataframe["macdhist"] > 0) &
# Extension protection
(dataframe["breakout_extension_ok"] == 1) &
(dataframe["ema_extension_pct_v34"] <= 1.2) &
# V3.4 Weakness protection
(dataframe["weakness_score_v34"] < 2) &
(dataframe["di_gap_v34"] >= 3) &
# Volume confirmation
(dataframe["volume"] > dataframe["volume_mean"] * 1.05) &
(dataframe["volume"] > 0)
)
# V3.4 diagnostic entry tags.
# These buckets let the backtest show which signal profiles are winning
# or hitting stoploss without changing the entry rules.
dataframe.loc[breakout_entry, "enter_long"] = 1
dataframe.loc[breakout_entry, "enter_tag"] = "FAST_V34_ROI004_30_020_BASE"
dataframe.loc[
breakout_entry & (dataframe["weakness_score_v34"] == 0),
"enter_tag"
] += "_W0"
dataframe.loc[
breakout_entry & (dataframe["weakness_score_v34"] == 1),
"enter_tag"
] += "_W1"
dataframe.loc[
breakout_entry & (dataframe["adx"] >= 25),
"enter_tag"
] += "_ADX25"
dataframe.loc[
breakout_entry & (dataframe["adx"] < 25),
"enter_tag"
] += "_ADX22"
dataframe.loc[
breakout_entry & (dataframe["di_gap_v34"] >= 8),
"enter_tag"
] += "_DI8"
dataframe.loc[
breakout_entry &
(dataframe["di_gap_v34"] >= 5) &
(dataframe["di_gap_v34"] < 8),
"enter_tag"
] += "_DI5"
dataframe.loc[
breakout_entry & (dataframe["di_gap_v34"] < 5),
"enter_tag"
] += "_DI3"
dataframe.loc[
breakout_entry & (dataframe["ema_extension_pct_v34"] <= 0.7),
"enter_tag"
] += "_EXT_LOW"
dataframe.loc[
breakout_entry &
(dataframe["ema_extension_pct_v34"] > 0.7) &
(dataframe["ema_extension_pct_v34"] <= 1.0),
"enter_tag"
] += "_EXT_MID"
dataframe.loc[
breakout_entry & (dataframe["ema_extension_pct_v34"] > 1.0),
"enter_tag"
] += "_EXT_HIGH"
try:
if dataframe["enter_long"].fillna(0).iloc[-1] == 1:
logger.info(
"[ENTRY READY] %s last candle enter_long=1",
metadata.get("pair")
)
except Exception as e:
logger.info("[ENTRY DEBUG ERROR] %s", e)
try:
pair = metadata.get("pair", "UNKNOWN")
trend_count = int(trend_filter.tail(200).sum())
pullback_count = int(pullback_filter.tail(200).sum())
momentum_count = int(momentum_filter.tail(200).sum())
volume_count = int(volume_filter.tail(200).sum())
atr_count = int(atr_filter.tail(200).sum())
fvg_count = int(fvg_pullback.tail(200).sum())
ob_count = int(ob_pullback.tail(200).sum())
zone_count = int(smart_zone_filter.tail(200).sum())
final_count = int(dataframe["enter_long"].tail(200).fillna(0).sum())
logger.warning(
f"[DEBUG {pair}] "
f"trend={trend_count}, "
f"pullback={pullback_count}, "
f"momentum={momentum_count}, "
f"volume={volume_count}, "
f"atr={atr_count}, "
f"fvg={fvg_count}, "
f"ob={ob_count}, "
f"zone={zone_count}, "
f"final={final_count}"
)
except Exception as e:
logger.warning("Debug counter error: %s", e)
if metadata and metadata.get("pair"):
pair = metadata["pair"]
try:
last = dataframe.iloc[-1]
logger.info(
f"[FAST DEBUG {pair}] "
f"trend={int(trend_filter.iloc[-1])} "
f"pullback={int(pullback_filter.iloc[-1])} "
f"momentum={int(momentum_filter.iloc[-1])} "
f"volume={int(volume_filter.iloc[-1])} "
f"atr={int(atr_filter.iloc[-1])} "
f"sweep={int(last.get('bullish_sweep_recent', 0))} "
f"stoch={int(last.get('stoch_rsi_bull_cross', 0))} "
f"fvg={int(last.get('fvg_pullback', 0))} "
f"ob={int(last.get('ob_pullback', 0))} "
f"breakout={int(last.get('breakout_48', 0))} "
f"vol2x={int(last.get('volume_spike_2x', 0))} "
f"v34={int(last.get('weakness_score_v34', 0))} "
f"ema_ext={float(last.get('ema_extension_pct_v34', 0)):.2f} "
f"di_gap={float(last.get('di_gap_v34', 0)):.2f} "
f"final={int(last.get('enter_long', 0))}"
)
except Exception:
pass
# Uncomment to use shorts (Only used in futures/margin mode. Check the documentation for more info)
"""
dataframe.loc[
(
(qtpylib.crossed_above(dataframe["rsi"], self.sell_rsi.value)) & # Signal: RSI crosses above sell_rsi
(dataframe["tema"] > dataframe["bb_middleband"]) & # Guard: tema above BB middle
(dataframe["tema"] < dataframe["tema"].shift(1)) & # Guard: tema is falling
(dataframe['volume'] > 0) # Make sure Volume is not 0
),
'enter_short'] = 1
"""
return dataframe
def custom_exit(
self,
pair: str,
trade: Trade,
current_time: datetime,
current_rate: float,
current_profit: float,
**kwargs
) -> Optional[str]:
"""
Fast Exit V3:
Kill weak losing trades before they reach full stoploss.
Do not touch profitable trades.
"""
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
if dataframe is None or dataframe.empty:
return None
last = dataframe.iloc[-1]
trade_minutes = (current_time - trade.open_date_utc).total_seconds() / 60
if trade_minutes < 25:
return None
if current_profit > -0.006:
return None
weak_price = (
current_rate < last["ema20"]
)
weak_momentum = (
last["rsi"] < 47 and
last["macdhist"] < 0
)
weak_volume_red = (
last["close"] < last["open"] and
last["volume"] > last["volume_mean"] * 1.1
)
if current_profit < -0.018 and weak_price and weak_momentum:
return "FAST_WEAK_EXIT"
if current_profit < -0.012 and weak_price and weak_momentum and weak_volume_red:
return "FAST_RED_VOLUME_EXIT"
return None
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
"""
Fast Exit V2:
Disable manual exit signals.
Let ROI, trailing stop and stoploss manage exits.
"""
dataframe["exit_long"] = 0
dataframe["exit_tag"] = None
return dataframe