### Strategy Example Using IntParameter Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Example strategy demonstrating the use of IntParameter for defining buy hour ranges. The .value attribute is used to access the optimized parameter. ```python class HourBasedStrategy(IStrategy): buy_hour_min = IntParameter(0, 24, default=1, space='buy') buy_hour_max = IntParameter(0, 24, default=0, space='buy') def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe.loc[ (dataframe['hour'].between(self.buy_hour_min.value, self.buy_hour_max.value)), 'enter_long'] = 1 return dataframe ``` -------------------------------- ### Install Hyperopt Dependencies Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/hyperopt-interface.md Install the necessary Python packages for Hyperopt functionality. Ensure these are installed in your environment before running optimization. ```bash pip install ta pip install scikit-optimize ``` -------------------------------- ### Install ta-library Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/strategy-catalog.md Installs the ta-library, which provides a comprehensive set of technical analysis indicators used by the GodStra strategy. This is a prerequisite for using the strategy. ```bash pip install ta ``` -------------------------------- ### Install Optimization Dependencies Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/quick-start.md Install necessary Python packages for strategy optimization. This includes TA-Lib and scikit-optimize. ```bash pip install ta scikit-optimize ``` -------------------------------- ### Strategy Example Using merge_informative_pair Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Demonstrates how to use merge_informative_pair within the populate_indicators method to enrich the main dataframe with data from another pair and timeframe. ```python from freqtrade.strategy import IStrategy, merge_informative_pair class MyStrategy(IStrategy): def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: if self.dp: informative = self.dp.get_pair_dataframe(pair="BTC/USDT", timeframe='15m') informative['sma20'] = informative['close'].rolling(20).mean() dataframe = merge_informative_pair(dataframe, informative, self.timeframe, '15m', ffill=True) return dataframe ``` -------------------------------- ### Define a Custom Strategy with IStrategy Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Example of a basic custom strategy inheriting from IStrategy, setting essential parameters like timeframe and ROI. ```python class MyStrategy(IStrategy): INTERFACE_VERSION = 3 timeframe = '5m' minimal_roi = {"0": 0.10} stoploss = -0.10 ``` -------------------------------- ### Override Strategy Configuration with config.json Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/configuration.md Shows an example of a Freqtrade configuration file (config.json) used to override strategy attributes like minimal_roi and stoploss. ```json { "strategy": "Strategy001", "minimal_roi": { "0": 0.10 }, "stoploss": -0.05 } ``` -------------------------------- ### Calculate Indicators with TA-Lib Abstract Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/patterns-and-examples.md Use the talib.abstract module for calculating common technical indicators like EMAs, SMAs, RSI, MACD, and Bollinger Bands. Ensure TA-Lib is installed. ```python def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: import talib.abstract as ta # Moving Averages dataframe['ema20'] = ta.EMA(dataframe, timeperiod=20) dataframe['sma50'] = ta.SMA(dataframe, timeperiod=50) # Oscillators dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) dataframe['macd'] = ta.MACD(dataframe)[0] # Returns tuple, take first element dataframe['macd_signal'] = ta.MACD(dataframe)[1] # Volatility dataframe['atr'] = ta.ATR(dataframe) dataframe['bbands_upper'] = ta.BBANDS(dataframe)[0] dataframe['bbands_middle'] = ta.BBANDS(dataframe)[1] dataframe['bbands_lower'] = ta.BBANDS(dataframe)[2] return dataframe ``` -------------------------------- ### Informative Pairs Return Format Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Example of the expected return format for informative pairs, which is a list of tuples. Each tuple contains a trading pair and its timeframe. ```python [("BTC/USDT", "15m"), ("ETH/USDT", "5m")] ``` -------------------------------- ### Custom Stoploss Logic Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Implement custom stoploss logic within the custom_stoploss method. This example shows how to adjust the stoploss based on current profit. ```python def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: # Calculate stoploss based on trade entry risk = current_rate - trade.open_rate if current_profit > 0.05: # Move stoploss to 2% profit new_stoploss = (trade.open_rate * 1.02 - current_rate) / current_rate return new_stoploss return -0.10 # Default stoploss ``` -------------------------------- ### Adding Indicators to DataFrame Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/types-and-structures.md During populate_indicators(), strategies add calculated columns to the DataFrame. This example shows adding moving averages, oscillators, and volatility indicators. ```python # Moving Averages dataframe['ema20'] = ta.EMA(dataframe, timeperiod=20) dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50) dataframe['sma20'] = dataframe['close'].rolling(20).mean() # Oscillators dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) dataframe['macd'] = ta.MACD(dataframe)[0] # Volatility dataframe['atr'] = ta.ATR(dataframe) ``` -------------------------------- ### Optimize Strategy Parameters with Hyperopt Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/quick-start.md Runs the Hyperopt process to find optimal parameters for MyFirstStrategy using the MyFirstStrategyHO configuration. This command optimizes for Sharpe ratio over 100 epochs. ```bash freqtrade hyperopt \ --strategy MyFirstStrategy \ --hyperopt MyFirstStrategyHO \ --hyperopt-loss SharpeHyperOptLoss \ -e 100 ``` -------------------------------- ### Perform Simple Backtesting Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/README.md Execute a basic backtest for a specified strategy. Ensure the strategy file is correctly placed in the user_data/strategies directory. ```bash freqtrade backtesting --strategy Strategy001 ``` -------------------------------- ### Build Buy/Sell Logic from Optimized Parameters Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/patterns-and-examples.md Dynamically build entry conditions for a strategy using parameters optimized by hyperopt. This function combines multiple conditions using logical AND. ```python from functools import reduce def buy_strategy_generator(params: Dict[str, Any]) -> Callable: def populate_entry_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: conditions = [] # Build conditions from hyperopt parameters OPR = params['buy-oper-0'] IND = params['buy-indicator-0'] CRS = params['buy-cross-0'] INT = params['buy-int-0'] REAL = params['buy-real-0'] DFIND = dataframe[IND] DFCRS = dataframe[CRS] if OPR == ">": conditions.append(DFIND > DFCRS) elif OPR == "<": conditions.append(DFIND < DFCRS) elif OPR == "CA": conditions.append(qtpylib.crossed_above(DFIND, DFCRS)) elif OPR == "CB": conditions.append(qtpylib.crossed_below(DFIND, DFCRS)) elif OPR == ">R": conditions.append(DFIND > REAL) elif OPR == " List: return [ Integer(10, 50, name='buy-ema-short'), Integer(20, 100, name='buy-ema-long'), ] @staticmethod def buy_strategy_generator(params: Dict[str, Any]) -> Callable: def populate_entry_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: import talib.abstract as ta short_ema = ta.EMA(dataframe, timeperiod=params['buy-ema-short']) long_ema = ta.EMA(dataframe, timeperiod=params['buy-ema-long']) dataframe.loc[(short_ema > long_ema), 'enter_long'] = 1 return dataframe return populate_entry_trend @staticmethod def sell_indicator_space() -> List: return [] @staticmethod def sell_strategy_generator(params: Dict[str, Any]) -> Callable: def populate_exit_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe.loc[:, 'exit_long'] = 0 return dataframe return populate_exit_trend ``` -------------------------------- ### Run Hyperopt for Epochs Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/quick-start.md Optimizes strategy parameters using hyperopt for a specified number of epochs. This helps find optimal trading conditions. ```bash # Optimize for 100 epochs freqtrade hyperopt --strategy MyFirstStrategy --hyperopt MyFirstStrategyHO -e 100 ``` -------------------------------- ### Define Real Hyperopt Dimension Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Example of defining a real (float) dimension for hyperoptimization, setting a range and name for the floating-point parameter to be optimized. ```python Real(0.0, 1.0, name='threshold') ``` -------------------------------- ### Configure Startup Candle Count Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/configuration.md Sets the minimum number of historical candles needed before the strategy produces valid signals, required for indicator warm-up. ```python startup_candle_count = 199 # Need 199 previous candles before first signal ``` -------------------------------- ### Define Categorical Hyperopt Dimension Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Example of defining a categorical dimension for hyperoptimization, allowing the optimizer to choose from a list of predefined string values. ```python Categorical(['ema', 'rsi', 'macd'], name='indicator-type') ``` -------------------------------- ### Run Hyperopt for Specific Spaces Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/quick-start.md Optimizes strategy parameters within specified spaces (e.g., 'buy', 'sell') for a given number of epochs. Focuses optimization efforts. ```bash # Optimize specific spaces freqtrade hyperopt --strategy MyFirstStrategy --hyperopt MyFirstStrategyHO --spaces buy sell -e 100 ``` -------------------------------- ### Minimal ROI Configuration Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/types-and-structures.md Configures the minimum profit targets at specific time intervals for trade exits. Keys are time in seconds, values are profit percentages. ```python minimal_roi = { "60": 0.01, # After 60 seconds in trade, exit if 1% profit "30": 0.03, # After 30 seconds in trade, exit if 3% profit "0": 0.05 # Immediately, require 5% profit minimum } ``` -------------------------------- ### Configure Minimal ROI Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/configuration.md Maps time-in-trade to minimum required profit. Earlier keys override later ones. The last key should be '0' for the overall profit requirement. ```python minimal_roi = { "60": 0.01, # After 60 seconds: exit if 1% profit "30": 0.03, # After 30 seconds: exit if 3% profit "20": 0.04, # After 20 seconds: exit if 4% profit "0": 0.05 # Immediately: require 5% profit minimum } ``` -------------------------------- ### Get Last Candle Data Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/patterns-and-examples.md Access the most recent candle's data from the analyzed dataframe. This is useful for calculations based on the latest market conditions. ```python def custom_stoploss(self, pair: str, trade: 'Trade', ...) -> float: if self.dp: dataframe, _ = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) # Get last row as Series last_candle = dataframe.iloc[-1].squeeze() # Access individual values current_close = last_candle['close'] current_sar = last_candle['sar'] return (current_close - current_sar) / current_close - 1 ``` -------------------------------- ### Run Hyperopt with Custom Loss Function Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/quick-start.md Optimizes strategy parameters using a custom hyperopt loss function, such as SharpeHyperOptLossDaily. Enhances optimization goals. ```bash # Use specific loss function freqtrade hyperopt --strategy MyFirstStrategy --hyperopt MyFirstStrategyHO \ --hyperopt-loss SharpeHyperOptLossDaily -e 100 ``` -------------------------------- ### Run Freqtrade with a Specific Strategy Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/README.md Use this command to run the Freqtrade bot with a particular strategy. Replace `` with the actual name of your strategy class. ```bash freqtrade trade --strategy Strategy001 ``` -------------------------------- ### Add All Technical Indicators with TA Library Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/patterns-and-examples.md Use the `ta` library to efficiently add over 80 technical indicators to your dataframe in one call. Requires the `ta` library to be installed and handles NaN values. ```python from ta import add_all_ta_features from ta.utils import dropna def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # Add all available technical indicators at once dataframe = dropna(dataframe) dataframe = add_all_ta_features( dataframe, open="open", high="high", low="low", close="close", volume="volume", fillna=True ) return dataframe ``` -------------------------------- ### Custom Stoploss Calculation with Trade Object Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/types-and-structures.md Example of using the Trade object within the custom_stoploss method to calculate risk and adjust stop-loss levels based on current profit and entry details. Assumes the Trade object is available. ```python def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: # Calculate risk from entry entry_price = trade.open_rate risk_pct = (current_rate - entry_price) / entry_price # Account for fees fee_adjusted_entry = entry_price * (1 + trade.fee_open + trade.fee_close) # Decision logic if risk_pct > 0.10: # 10% profit return -0.02 # Tighten to 2% loss return -0.10 ``` -------------------------------- ### Run Hyperopt Optimization Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/hyperopt-interface.md Use this command to run the Hyperopt process for a specific strategy and loss function. Specify the strategy, configuration file, and number of epochs. ```bash freqtrade hyperopt \ --hyperopt GodStraHo \ --hyperopt-loss SharpeHyperOptLossDaily \ --spaces all \ --strategy GodStra \ --config config.json \ -e 100 ``` -------------------------------- ### Import Hyperopt Interface Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/hyperopt-interface.md Import the IHyperOpt interface from the freqtrade optimize module. ```python from freqtrade.optimize.hyperopt_interface import IHyperOpt ``` -------------------------------- ### QTPyLib Indicators for Crossover and Heikin-Ashi Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Shows how to detect if one series has crossed above or below another, and how to generate Heikin-Ashi candlesticks using the qtpylib.indicators library. Requires pre-defined series1 and series2. ```python import freqtrade.vendor.qtpylib.indicators as qtpylib # Crossed above detection crossed = qtpylib.crossed_above(series1, series2) # Crossed below detection crossed = qtpylib.crossed_below(series1, series2) # Heikin-Ashi candlesticks ha = qtpylib.heikinashi(dataframe) # Returns DataFrame with columns: open, high, low, close ``` -------------------------------- ### Execute Freqtrade Strategy Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Command to run a Freqtrade strategy for live trading. ```bash freqtrade trade --strategy Strategy001 ``` -------------------------------- ### QtPyLib Indicator Calculations Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/strategy-interface.md Utilize QtPyLib indicators for custom calculations like detecting crossovers or generating Heikin Ashi data. Ensure the library is imported correctly. ```python import freqtrade.vendor.qtpylib.indicators as qtpylib dataframe['crossed'] = qtpylib.crossed_above(dataframe['ema20'], dataframe['ema50']) dataframe['heikinashi'] = qtpylib.heikinashi(dataframe) ``` -------------------------------- ### Importing Logging for Strategy Execution Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Import the logging module to log messages during strategy execution. Use logger.info for general information and logger.warning for potential issues. ```python import logging logger = logging.getLogger(__name__) # Log messages during strategy execution logger.info("Strategy signal generated") logger.warning("Low volume detected") ``` -------------------------------- ### Time-Based Parameter Optimization Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/patterns-and-examples.md Use IntParameter to define hour-of-day ranges for strategy entry signals. This allows hyperopt to find optimal buy and sell hours. ```python from freqtrade.strategy import IntParameter class HourBasedStrategy(IStrategy): timeframe = '1h' buy_hour_min = IntParameter(0, 24, default=1, space='buy') buy_hour_max = IntParameter(0, 24, default=0, space='buy') sell_hour_min = IntParameter(0, 24, default=1, space='sell') sell_hour_max = IntParameter(0, 24, default=0, space='sell') def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe['hour'] = dataframe['date'].dt.hour return dataframe def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe.loc[ (dataframe['hour'].between(self.buy_hour_min.value, self.buy_hour_max.value)), 'enter_long'] = 1 return dataframe ``` ```bash freqtrade hyperopt --strategy HourBasedStrategy -e 100 # Finds optimal buy_hour_min and buy_hour_max for your pairs ``` -------------------------------- ### Backtest a Freqtrade Strategy Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/quick-start.md Execute a backtest for a specified strategy using the Freqtrade CLI. This command simulates the strategy's performance on historical data. ```bash freqtrade backtesting --strategy MyFirstStrategy ``` -------------------------------- ### Python Type Hinting for Strategy Methods Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/types-and-structures.md Demonstrates type annotations for common Freqtrade strategy methods. Ensure necessary imports from `typing`, `pandas`, `freqtrade.persistence`, and `datetime` are included. ```python from typing import Dict, List, Callable, Any, Tuple, Union from pandas import DataFrame from freqtrade.persistence import Trade from datetime import datetime def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: pass def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: pass def indicator_space(self) -> List[Dimension]: pass ``` -------------------------------- ### Informative Pairs Configuration Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/strategy-catalog.md Defines the additional trading pairs to fetch data for. Use this to include reference markets for your strategy. ```python def informative_pairs(self): return [(f"BTC/USDT", '15m')] ``` -------------------------------- ### Run Hyperopt Optimization Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/strategy-interface.md Optimize strategy parameters using hyperopt with a specified loss function and strategy. The `-e` flag sets the number of epochs for the optimization process. ```bash freqtrade hyperopt --hyperopt-loss SharpeHyperOptLoss --strategy YourStrategy -e 100 ``` -------------------------------- ### Populate Indicators with Metadata Dictionary Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/types-and-structures.md Demonstrates how to access the trading pair from the metadata dictionary within the populate_indicators method to perform pair-specific data processing and storage. ```python def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: pair = metadata['pair'] print(f"Processing {pair}") # Store pair-specific data self.custom_info[pair] = dataframe[['date', 'indicator']].copy() return dataframe ``` -------------------------------- ### Generate Heikin-Ashi Candles and Entry Signals Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/patterns-and-examples.md Utilize the qtpylib.indicators module to generate Heikin-Ashi candles. This pattern is useful for smoothing price action and identifying trends based on HA candle colors. ```python def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: import freqtrade.vendor.qtpylib.indicators as qtpylib heikinashi = qtpylib.heikinashi(dataframe) dataframe['ha_open'] = heikinashi['open'] dataframe['ha_high'] = heikinashi['high'] dataframe['ha_low'] = heikinashi['low'] dataframe['ha_close'] = heikinashi['close'] return dataframe def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe.loc[ ( (dataframe['ha_open'] < dataframe['ha_close']) # Green HA candle ), 'enter_long'] = 1 return dataframe ``` -------------------------------- ### Run Backtest with Date Range Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/quick-start.md Performs a backtest for a specified strategy within a given date range. Allows for focused performance analysis during specific periods. ```bash # With date range freqtrade backtesting --strategy MyFirstStrategy --timerange 20210101-20210331 ``` -------------------------------- ### Strategy Configuration Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/strategy-catalog.md Defines the basic configuration for the strategy, including interface version, timeframe, initial stoploss, and custom stoploss usage. ```python INTERFACE_VERSION = 3 timeframe = '1h' stoploss = -0.2 custom_info = {} use_custom_stoploss = True startup_candle_count = 199 ``` -------------------------------- ### Create a Basic Freqtrade Strategy Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/quick-start.md Defines a simple trading strategy named MyFirstStrategy using EMA crossovers. This strategy populates indicators and generates entry/exit signals based on the relative positions of two Exponential Moving Averages. ```python from freqtrade.strategy import IStrategy from pandas import DataFrame import talib.abstract as ta class MyFirstStrategy(IStrategy): INTERFACE_VERSION = 3 # Configuration timeframe = '5m' minimal_roi = {"0": 0.10} stoploss = -0.10 def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # Calculate indicators dataframe['ema20'] = ta.EMA(dataframe, timeperiod=20) dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50) return dataframe def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # Generate buy signals dataframe.loc[ (dataframe['ema20'] > dataframe['ema50']), 'enter_long'] = 1 return dataframe def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # Generate sell signals dataframe.loc[ (dataframe['ema20'] < dataframe['ema50']), 'exit_long'] = 1 return dataframe ``` -------------------------------- ### Populate Indicators with TA-Lib and Informative Data Source: https://github.com/freqtrade/freqtrade-strategies/wiki/Informative-Pairs-annotated The `populate_indicators` method calculates technical indicators like EMAs and SMAs. It also fetches data for informative pairs (e.g., stake_currency/USDT) and merges it into the main dataframe for comparison. ```python dataframe['ema20'] = ta.EMA(dataframe, timeperiod=20) dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50) dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100) if self.dp: # Get ohlcv data for informative pair. data = self.dp.get_pair_dataframe(pair=f"{self.stake_currency}/USDT", ### (4) timeframe=self.ticker_interval) # Combine the 2 dataframes using 'close'. # This will result in a column named 'closeETH' or 'closeBTC' - depending on stake_currency. dataframe = dataframe.merge(data[["date", "close"]], on="date", how="left", ### (5) suffixes=("", self.config['stake_currency'])) # Calculate SMA20 on 'close' data for stake_currency/USDT. Resulting column is named as 'smaETH20' (if stake_currency is ETH) dataframe[f"sma{self.config['stake_currency']}20"] = ### (6) dataframe[f'close{self.stake_currency}'].rolling(20).mean() ``` -------------------------------- ### Configure Strategy Timeframe Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/configuration.md Sets the candle timeframe for the strategy. Must be a valid freqtrade timeframe string. ```python timeframe = '5m' # 5-minute candles ``` -------------------------------- ### HourBasedStrategy Configuration Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/strategy-catalog.md Defines the strategy's timeframe, ROI, stoploss, and hyperopt parameters for buy and sell hours. These parameters allow optimization of trading times. ```python INTERFACE_VERSION = 3 timeframe = '1h' minimal_roi = {"0": 0.528, "169": 0.113, "528": 0.089, "1837": 0} stoploss = -0.10 # Hyperopt parameters buy_hour_min = IntParameter(0, 24, default=1, space='buy') buy_hour_max = IntParameter(0, 24, default=0, space='buy') sell_hour_min = IntParameter(0, 24, default=1, space='sell') sell_hour_max = IntParameter(0, 24, default=0, space='sell') ``` -------------------------------- ### Run Freqtrade Hyperopt for GodStra Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/strategy-catalog.md Executes the hyperopt process for the GodStra strategy, optimizing buy and sell parameters across 100 generations. This command is used to find optimal trading conditions. ```bash freqtrade hyperopt --hyperopt GodStraHo --strategy GodStra --spaces buy,sell -e 100 ``` -------------------------------- ### Define Buy Indicator Search Space Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/hyperopt-interface.md Defines the search space for buy strategy parameters using skopt dimension objects. Use this to specify the parameters that hyperopt will optimize for entry signals. ```python from skopt.space import Categorical, Integer, Real @staticmethod def indicator_space() -> List[Dimension]: return [ Categorical(['ema20', 'ema50', 'rsi'], name='buy-indicator'), Integer(5, 50, name='buy-period'), Real(0.0, 1.0, name='buy-threshold'), ] ``` -------------------------------- ### Run Backtest with Specific Pairs Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/quick-start.md Performs a backtest for a specified strategy on a list of trading pairs. Useful for testing performance across different markets. ```bash # With specific pairs freqtrade backtesting --strategy MyFirstStrategy --pair BTC/USDT ETH/USDT ``` -------------------------------- ### Import skopt Dimension Types Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Import necessary classes from skopt.space for defining hyperoptimization search dimensions, including Categorical, Integer, and Real. ```python from skopt.space import Categorical, Integer, Real, Dimension ``` -------------------------------- ### InformativeSample Strategy Configuration Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/strategy-catalog.md Sets the interface version, timeframe, ROI table, and stoploss for the InformativeSample strategy. Trailing stop is disabled. ```python INTERFACE_VERSION = 3 timeframe = '5m' minimal_roi = {"60": 0.01, "30": 0.03, "20": 0.04, "0": 0.05} stoploss = -0.10 trailing_stop = False trailing_stop_positive = 0.02 trailing_stop_positive_offset = 0.04 ``` -------------------------------- ### Import Core Freqtrade Strategy Libraries Source: https://github.com/freqtrade/freqtrade-strategies/wiki/Informative-Pairs-annotated These are the fundamental libraries that must be imported when creating a Freqtrade strategy. They provide the necessary interfaces and tools for strategy development. ```python # --- Do not remove these libs --- from freqtrade.strategy.interface import IStrategy from typing import Dict, List from functools import reduce from pandas import DataFrame ``` -------------------------------- ### Informative Pair Integration for Signal Confirmation Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/patterns-and-examples.md Uses data from a reference pair (e.g., BTC/USDT) to confirm signals on the main trading pair. Ensure the merge happens before using the informative columns, which are suffixed with the timeframe. ```python from freqtrade.strategy import merge_informative_pair def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # Calculate indicators on main pair dataframe['ema20'] = ta.EMA(dataframe, timeperiod=20) dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50) # Fetch and prepare informative pair if self.dp: informative = self.dp.get_pair_dataframe(pair="BTC/USDT", timeframe='15m') informative['sma20'] = informative['close'].rolling(20).mean() # Merge them by timestamp dataframe = merge_informative_pair(dataframe, informative, self.timeframe, '15m', ffill=True) return dataframe def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe.loc[ ( (dataframe['ema20'] > dataframe['ema50']) & # Main pair condition (dataframe['close_15m'] > dataframe['sma20_15m']) # Informative pair confirmation ), 'enter_long'] = 1 return dataframe ``` -------------------------------- ### Strategy001 Configuration Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/strategy-catalog.md Configuration settings for Strategy001, including ROI, stoploss, timeframe, and candle processing. ```python INTERFACE_VERSION = 3 minimal_roi = {"60": 0.01, "30": 0.03, "20": 0.04, "0": 0.05} stoploss = -0.10 timeframe = '5m' trailing_stop = False process_only_new_candles = True ``` -------------------------------- ### Populate Entry Trend Logic Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/quick-start.md Define buy entry signals based on indicators. Set the 'enter_long' column to 1 where a buy signal is true. This method is called after populate_indicators. ```python def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe.loc[ (dataframe['ema20'] > dataframe['ema50']), 'enter_long'] = 1 return dataframe ``` -------------------------------- ### Configure Stoploss Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/configuration.md Sets the maximum loss allowed on a trade as a negative decimal. -0.10 means sell if price drops 10% below entry. ```python stoploss = -0.10 # Exit if loss exceeds 10% ``` -------------------------------- ### indicator_space() Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/hyperopt-interface.md Defines the search space for buy strategy parameters. This method returns a list of dimension objects that specify the parameters hyperopt will optimize. ```APIDOC ## indicator_space() ### Description Defines the search space for buy strategy parameters. Returns a list of dimension objects that determine what parameters hyperopt will optimize. ### Returns List of skopt dimension objects (Categorical, Integer, Real) ### Example ```python from skopt.space import Categorical, Integer, Real @staticmethod def indicator_space() -> List[Dimension]: return [ Categorical(['ema20', 'ema50', 'rsi'], name='buy-indicator'), Integer(5, 50, name='buy-period'), Real(0.0, 1.0, name='buy-threshold'), ] ``` ``` -------------------------------- ### Enable Debug Logging in Freqtrade Strategy Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/quick-start.md Configure Python's logging module to output debug information from your strategy. Useful for tracing execution flow and variable states during development. ```python import logging logger = logging.getLogger(__name__) class MyStrategy(IStrategy): def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: logger.info(f"Pair: {metadata['pair']}") logger.debug(f"Close: {dataframe['close'].iloc[-1]}") # ... signal logic ... return dataframe ``` -------------------------------- ### Static Stoploss Configuration Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/patterns-and-examples.md Set a fixed percentage-based stoploss for your strategy. This is the simplest form of stoploss, exiting the trade if the loss exceeds the defined threshold. ```python class MyStrategy(IStrategy): stoploss = -0.10 # Exit if loss exceeds 10% ``` -------------------------------- ### Configure New Candle Processing Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/configuration.md If True, only process completed candles. If False, process every update within a candle interval. This improves performance but may miss signals. ```python process_only_new_candles = True # Only analyze complete 5m candles ``` -------------------------------- ### Hyperopt Optimization Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Command to perform hyperparameter optimization for a Freqtrade strategy. Specify the strategy, hyperopt loss function, search spaces, and number of epochs. ```bash freqtrade hyperopt \ --strategy HourBasedStrategy \ --hyperopt-loss SharpeHyperOptLoss \ --spaces buy,sell \ -e 100 ``` -------------------------------- ### buy_strategy_generator() Return Type (Hyperopt) Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/types-and-structures.md This static method returns a callable function that implements the populate_entry_trend logic, using parameters generated by hyperopt. ```python @staticmethod def buy_strategy_generator(params: Dict[str, Any]) -> Callable: def populate_entry_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: # Use params to build conditions dataframe.loc[(condition), 'enter_long'] = 1 return dataframe return populate_entry_trend # Return the function ``` -------------------------------- ### Read Environment Variable in Strategy Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/configuration.md Demonstrates how to read an environment variable within a Freqtrade strategy using Python's os module. Provides a default value if the environment variable is not set. ```python import os custom_setting = os.getenv('STRATEGY_SETTING', 'default_value') ``` -------------------------------- ### Download Historical Trading Data Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/README.md Refresh your local trading data by downloading data for a specified number of past days. This is useful for ensuring your backtests use up-to-date information. ```bash freqtrade download-data --days 100 ``` -------------------------------- ### indicator_space() Return Type (Hyperopt) Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/types-and-structures.md This static method should return a list of skopt.space.Dimension objects, defining the search space for indicators during hyperoptimization. ```python @staticmethod def indicator_space() -> List[Dimension]: from skopt.space import Categorical, Integer, Real return [ Categorical(['ema', 'sma'], name='type'), Integer(5, 50, name='period'), Real(0.0, 1.0, name='threshold'), ] ``` -------------------------------- ### Download Historical Data Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Command to download historical market data for a specified number of days. ```bash freqtrade download-data --days 100 ``` -------------------------------- ### Import IStrategy Base Class Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/strategy-interface.md Import the IStrategy base class from the freqtrade strategy module. This is a required step for all custom trading strategies. ```python from freqtrade.strategy import IStrategy ``` -------------------------------- ### Signal Generation with Pandas Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/quick-start.md Use pandas DataFrame operations to set buy/sell signals. Supports single conditions, multiple conditions (AND logic), alternative conditions (OR logic), and negation. ```python # Single condition dataframe.loc[(condition), 'enter_long'] = 1 ``` ```python # Multiple conditions (all must be true) dataframe.loc[ ( (condition1) & (condition2) & (condition3) ), 'enter_long'] = 1 ``` ```python # Alternative conditions (any can be true) dataframe.loc[ ( (condition1) | (condition2) ), 'enter_long'] = 1 ``` ```python # Negation dataframe.loc[ (~condition), 'enter_long'] = 1 ``` -------------------------------- ### Trailing Stoploss Configuration Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/patterns-and-examples.md Implement a trailing stoploss that follows the price upwards after a certain profit threshold is reached, but does not trail downwards. This helps to lock in profits while allowing for further upside potential. ```python class MyStrategy(IStrategy): trailing_stop = True trailing_stop_positive = 0.01 # When profit > 1%, enable trailing trailing_stop_positive_offset = 0.02 # Trail by 2% from peak trailing_only_offset_is_reached = True # Only after offset reached ``` -------------------------------- ### DataProvider Methods Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/api-reference.md Methods available within strategy objects for accessing market data. These methods are accessed via `self.dp`. ```APIDOC ## get_pair_dataframe pair timeframe ### Description Retrieves a pandas DataFrame containing historical market data for a specified trading pair and timeframe, along with the index of the last candle. ### Method `self.dp.get_pair_dataframe(pair: str, timeframe: str)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python dataframe, last_candle = self.dp.get_pair_dataframe(pair='BTC/USDT', timeframe='15m') ``` ### Response #### Success Response - **dataframe** (DataFrame) - DataFrame with all indicators calculated. - **last_candle** (int) - Index of the last candle. #### Response Example ```json { "dataframe": "[pandas DataFrame]", "last_candle": 1678886400 } ``` ## get_analyzed_dataframe pair timeframe ### Description Retrieves a pandas DataFrame with indicators already calculated for the specified trading pair and timeframe, tailored for the current strategy. ### Method `self.dp.get_analyzed_dataframe(pair: str, timeframe: str)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python dataframe, _ = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) last_candle = dataframe.iloc[-1].squeeze() ``` ### Response #### Success Response - **dataframe** (DataFrame) - DataFrame with indicators already calculated for this strategy. #### Response Example ```json { "dataframe": "[pandas DataFrame with indicators]" } ``` ``` -------------------------------- ### GodStra Strategy Configuration Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/strategy-catalog.md Defines the core configuration for the GodStra strategy, including interface version, timeframe, ROI, and stoploss settings. Ensure these parameters align with your trading objectives. ```python INTERFACE_VERSION = 3 timeframe = '12h' minimal_roi = {"0": 0.3556, "4818": 0.21275, "6395": 0.09024, "22372": 0} stoploss = -0.34549 trailing_stop = True trailing_stop_positive = 0.22673 trailing_stop_positive_offset = 0.2684 trailing_only_offset_is_reached = True ``` -------------------------------- ### Generate Buy Strategy Function Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/hyperopt-interface.md Generates a populate_entry_trend function based on optimized hyperparameters. The returned function is used during backtesting to generate buy signals. ```python from typing import Dict, Any, Callable from pandas import DataFrame from functools import reduce @staticmethod def buy_strategy_generator(params: Dict[str, Any]) -> Callable: def populate_entry_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: conditions = [] if params['buy-indicator'] == 'ema': conditions.append(dataframe['ema20'] > dataframe['ema50']) elif params['buy-indicator'] == 'rsi': conditions.append(dataframe['rsi'] < params['buy-threshold']) if conditions: dataframe.loc[ reduce(lambda x, y: x & y, conditions), 'enter_long'] = 1 return dataframe return populate_entry_trend ``` -------------------------------- ### FixedRiskRewardLoss Strategy Configuration Source: https://github.com/freqtrade/freqtrade-strategies/blob/main/_autodocs/strategy-catalog.md Configures the FixedRiskRewardLoss strategy with a risk/reward ratio and a profit threshold for activating break-even stoploss. A loose default stoploss is set, to be overridden by custom logic. ```python INTERFACE_VERSION = 3 custom_info = { 'risk_reward_ratio': 3.5, 'set_to_break_even_at_profit': 1, } use_custom_stoploss = True stoploss = -0.9 # Very loose default, real stoploss set in custom_stoploss() ```