Sling Academy
Home/Python/Developing Custom Trading Strategies for freqtrade

Developing Custom Trading Strategies for freqtrade

Last updated: December 22, 2024

Algorithmic trading has become increasingly popular among individual traders and financial institutions. Tools like freqtrade, an open-source cryptocurrency trading bot, allow traders to automate the implementation of trading strategies across various markets and exchanges. In this article, we will explore how to develop custom trading strategies using freqtrade.

Setting Up Freqtrade

To get started with freqtrade, you'll need to have Python installed on your system. Freqtrade requires Python version 3.6 or higher. You should also have a basic understanding of both Python and trading concepts.

$ git clone https://github.com/freqtrade/freqtrade.git
$ cd freqtrade
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

The above steps help you to clone the freqtrade repository, create a virtual environment, and install the necessary dependencies.

Understanding Freqtrade's Architecture

Freqtrade's architecture revolves around the separation of strategy logic from the core bot functionality. This approach allows you to focus on building your strategy without worrying about the other operational aspects of the bot.

Creating a Custom Strategy

Your trading strategy is defined by a Python class that specifies how and when orders should be placed and executed. Let's define a simple example strategy:

from freqtrade.strategy import IStrategy
from pandas import DataFrame

class SimpleStrategy(IStrategy):
    def __init__(self):
        super().__init__()

    # Define the minimal ROI values
    minimal_roi = {
        "0": 0.1,
        "10": 0.02
    }

    # Define stop loss
    stoploss = -0.10

    # Define trailing stop
    trailing_stop = True
    trailing_stop_positive = 0.01

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['ma'] = dataframe['close'].rolling(window=10).mean()  # Simple Moving Average
        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[(dataframe['close'] > dataframe['ma']), 'enter_long'] = 1
        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[(dataframe['close'] < dataframe['ma']), 'exit_long'] = 1
        return dataframe

This simple strategy uses a simple moving average (SMA) to determine entry and exit points. The strategy buys when the price goes above the SMA and sells when it goes below.

Running Your Strategy

To run your custom strategy with freqtrade, you'll need to adjust the bot's configuration file to specify which strategy to use. Here is how you can do it:

{
  "strategy": "SimpleStrategy",
  "start_balance": 1000,
  "fee": 0.1,
  "exchange": {
    "name": "binance",
    "key": "",
    "secret": "",
    "ccxt_config": {},
    "ccxt_async_config": {},
    "pair_whitelist": [
      "BTC/USDT"
    ]
  }
}

After updating the configuration, activate your virtual environment if not already activated and launch the bot:

$ freqtrade trade

Backtesting Strategies

Before running a strategy live, it's crucial to backtest it using historical data to verify its profitability. Freqtrade provides tools to perform thorough backtests.

$ freqtrade backtesting --strategy SimpleStrategy --refresh-pairs-cached

Optimizing the Strategy

Optimization involves tweaking the strategy parameters to achieve better returns. Freqtrade includes optimization capabilities that perform parameter sweeps or genetic optimizations to find the most profitable configuration.

$ freqtrade hyperopt --strategy SimpleStrategy

By fine-tuning your strategy's parameters, you may see substantial improvements in strategy performance while assessing risk factors associated with different configurations.

Final Thoughts

Developing custom trading strategies with freqtrade opens the door to automating your trading, allowing you to explore both simple and complex algorithmic structures. By continuously refining and backtesting your strategies, you can discover new market opportunities and techniques suitable for your risk appetite and investment goals. As with any trading software, it's important to monitor your bots regularly to ensure everything runs smoothly and adjustments can be made as market conditions evolve.

Next Article: Using freqtrade’s Backtesting and Hyperopt Modules

Previous Article: Debugging Common freqtrade Errors: Exchange Connectivity and More

Series: Algorithmic trading with Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots
  • Monitoring Order Book Imbalances for Trading Signals via cryptofeed