Unveiling the MacheteV8b: A Trend-Following Powerhouse Freqtrade Strategy

The world of algorithmic trading thrives on strategies like the MacheteV8b, designed to capitalize on price movements aligned with the prevailing trend. This guide equips you with a solid understanding of the MacheteV8b.

1. Unveiling the MacheteV8b Strategy

Core Concept: The MacheteV8b flourishes in trending markets, aiming to capture profits by riding the momentum of a strong uptrend or downtrend. It employs a multi-layered filter system to refine entry and exit signals, potentially mitigating false positives and increasing effectiveness.

Key Components:

  • ADX (Average Directional Index): A technical indicator that measures the strength of a trend, regardless of its direction (up or down).
  • AO (Awesome Oscillator): A technical indicator that measures the difference between two moving averages of a price momentum indicator, typically used to identify potential trend reversals.
  • MACD (Moving Average Convergence Divergence): A technical indicator that uses the relationship between two exponential moving averages (EMAs) of a security’s price to identify changes in momentum, potential trend reversals, and buying/selling opportunities.
  • RMI (Relative Strength Index): A technical indicator that measures the magnitude of recent price changes to evaluate overbought or oversold conditions.
  • SSL (Standard Stochastic Oscillator): A technical indicator that compares the closing price of a security to its price range over a specific period to identify potential turning points in the market.

Buy Conditions:

buy_should_use_get_buy_signal_awesome_macd.value must be True: 

  1. MACD value in the dataframe must be greater than 0: This suggests the strategy looks for an upward trend based on the MACD indicator.
  2. AO value in the dataframe must be greater than 0: This indicates a search for upward momentum using the Awesome Oscillator.
  3. Previous AO value must be less than 0: This suggests a potential bullish reversal, as the AO value transitioned from negative to positive.

Sell Conditions:

The MacheteV8b strategy seems to have two main sell conditions:

  1. Minimum ROI: The minimal_roi table defines the minimum acceptable profit for a trade based on the duration it’s been open (represented by hours). If the price reaches a point where the profit percentage exceeds the minimum ROI for the current timeframe, the strategy might consider selling to lock in those profits.
  2. Stoploss: The stoploss variable defines the maximum acceptable loss for a trade. If the price falls below a certain percentage (defined by the stoploss value) from the buy price, the strategy will automatically sell to limit potential losses.

2.1. Imports:

import pandas as pd
from freqtrade.strategy import IStrategy, DecimalParameter, IntParameter, BooleanParameter
import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib

These lines import essential libraries for the strategy’s operation:

  • pandas (pd): A powerful library for data manipulation and analysis, crucial for working with historical price data.
  • freqtrade.strategy: Classes and functions for defining trading strategies within the Freqtrade framework.
  • IStrategy: The base class for creating custom strategies.
  • DecimalParameter, IntParameter, BooleanParameter: Classes used to define strategy parameters that can be optimized.
  • talib.abstract as ta: Provides technical analysis indicators like ADX and RSI.
  • freqtrade.vendor.qtpylib.indicators: Offers additional technical analysis indicators.

2.2. Class Definition and Strategy Parameters (Optional):

class MacheteV8bStrategy(IStrategy):

    # Strategy parameters (timeframe, minimal_roi, etc.)

This section defines a new class named MacheteV8bStrategy that inherits from the IStrategy class. This class will house the core logic of the strategy.

The commented-out line (# Strategy parameters (timeframe, minimal_roi, etc.)) indicates a potential section where you could define various parameters to customize the strategy for your specific needs. These parameters might include:

  • timeframe: The timeframe used for analyzing price data (e.g., ‘1h’, ‘4h’).
  • minimal_roi: The minimum profit percentage for closing a winning trade.
  • stoploss: The maximum tolerable loss percentage for closing a losing trade.

2.3. Hyperparameter Definition:

# Hyperopt parameters (tailored to your strategy)
adx_threshold = DecimalParameter(low=20, high=60, default=30, space='buy', optimize=True, load=True)
rsi_entry_threshold = DecimalParameter(low=30, high=50, default=40, space='buy', optimize=True, load=True)
rsi_exit_threshold = DecimalParameter(low=70, high=90, default=80, space='sell', optimize=True, load=True)
min_volume = IntParameter(low=100, high=10000, default=500, space='buy', optimize=True, load=True)
trailing_stop = DecimalParameter(low=0.01, high=0.1, default=0.05, space='sell', optimize=True, load=True)

These lines define a set of hyperparameters that can be fine-tuned to potentially improve the strategy’s performance. Here’s what each line means:

  • # Hyperopt parameters (tailored to your strategy): This comment indicates that these parameters can be adjusted to fit your specific trading strategy.
  • Each line defines a parameter using a DecimalParameter or IntParameter class depending on whether it requires a decimal value (e.g., percentages) or an integer (e.g., volume).
  • The parameter has a name (e.g., adx_threshold), a range of allowed values (low and high), and a default value.
  • space specifies whether the parameter is used for buy ('buy') or sell ('sell') signals.
  • optimize=True indicates the parameter will be considered during a process called hyperoptimization, which automatically tests different parameter combinations to find the best performing set.
  • load=True allows the parameter to be loaded from a previous optimization run, saving you time if you’ve already optimized the strategy.

Here’s a breakdown of the specific parameters defined in this example:

  • adx_threshold: This defines the minimum value of the Average Directional Index (ADX) for a strong trend (considered for buy signals).
  • rsi_entry_threshold: This defines the RSI level below which the strategy might consider entering a buy position (indicating not yet overbought).
  • rsi_exit_threshold: This defines the RSI level above which the strategy might consider exiting a buy position (indicating potentially overbought).
  • min_volume: This sets a minimum volume threshold for the market. The strategy will only consider buying or selling assets with sufficient trading activity (liquidity).
  • trailing_stop: This defines the percentage price movement that triggers a trailing stop loss. When the price moves against your position by this percentage, the strategy will automatically sell to limit potential losses.

2.4. Informative Pairs (Optional):

This section (usually commented out) allows you to specify additional trading pairs that might influence the strategy’s decisions for the main pair you’re focusing on. For example, if you’re trading Bitcoin (BTC), you might consider including the Ethereum (ETH) price data as an informative pair, as their prices often move in correlation.

2.5. Populating Indicators:

Python

def informative_pairs(self):
    # ... (consider informative pairs if needed)

def populate_indicators(self, dataframe: pd.DataFrame, metadata: dict) -> pd.DataFrame:
    # Calculate ADX for trend direction
    dataframe['adx'] = ta.ADX(dataframe)

    # Calculate RSI for momentum and potential entry/exit points
    dataframe['rsi'] = ta.RSI(dataframe)

    # ... (add other indicators as needed)

    return dataframe

These functions handle calculating the technical indicators used by the strategy:

  • informative_pairs(self): This function is typically commented out as it’s not used in this basic example. If needed, you could define informative pairs here.
  • populate_indicators(self, dataframe: pd.DataFrame, metadata: dict) -> pd.DataFrame This function takes the historical price data (dataframe) and calculates the indicators needed for the strategy.
    • dataframe['adx'] = ta.ADX(dataframe): This line calculates the ADX (Average Directional Index) and adds a new column named ‘adx’ to the DataFrame. ADX helps identify strong trends.
    • dataframe['rsi'] = ta.RSI(dataframe):

4. Hyperparameter Optimization: Fine-Tuning the MacheteV8b

Hyperoptimization is an iterative process that refines a strategy’s parameters to potentially improve its performance. Here are some key parameters to consider for the MacheteV8b:

  • ADX Threshold: This sets the minimum ADX value for a strong trend.
  • RSI Entry/Exit Thresholds: These define the RSI levels for entry (not yet overbought) and exit (overbought) signals.
  • Minimum Volume: This ensures the strategy focuses on liquid markets.
  • Trailing Stop: This defines the percentage price movement that triggers a trade exit.

5. Conclusion: When and Why to Use (or Not Use) the MacheteV8b

The MacheteV8b shines in trending markets but may struggle during periods of choppy price action. Here’s a quick guide:

Use MacheteV8b When:

  • Markets exhibit clear uptrends or downtrends.
  • You have a risk management plan in place (e.g., stop-loss).

Avoid MacheteV8b When:

  • Markets are choppy or range-bound.
  • Transaction costs are high (can eat into profits).

Here are the code examples for backtesting and hyperoptimizing the MacheteV8b strategy, as well as important considerations:

Data Downloading:

Bash

#docker compose run --rm freqtrade download-data \
    --config user_data/config.json \
    --timerange 20230101-20240101  -t 15m
 

Backtesting:

Bash

#docker compose run --rm freqtrade backtesting \
    --config user_data/config.json \
    --strategy MacheteV8b

Hyperoptimization:

Bash

#docker compose run --rm freqtrade hyperopt \
    --hyperopt-loss SharpeHyperOptLossDaily \
    --spaces roi stoploss trailing \
    --strategy MacheteV8b \
    --config user_data/config.json -e 10

Remember, backtesting and hyperoptimization are crucial steps to assess and potentially improve the MacheteV8b’s performance for your specific trading needs. Continuously monitor its performance and adapt as necessary.

Github Source Code