Algorithmic Trading Strategies
  • Cryptocurrency Algorithmic Trading Strategies
    • Building Blocks Of Creating an Algo Trading Strategy
    • How To Apply The Strategies In This Library
    • Strategy 1: Candlestick Trading Pattern (Hammer and Hanging Man candles)
    • Strategy 2: Stochastic Oscillator and Bollinger Bands
    • Strategy 3: Diversified Crypto Portfolio Investing with Stochastics & Bollinger Bands
Powered by GitBook
On this page
  1. Cryptocurrency Algorithmic Trading Strategies

Strategy 1: Candlestick Trading Pattern (Hammer and Hanging Man candles)

This algorithm is designed to trade the cryptocurrency Bitcoin (BTC) but can be used for any other cryptocurrency. The main logic is based on two candlestick patterns: the Hammer and the Hanging Man.

PreviousHow To Apply The Strategies In This LibraryNextStrategy 2: Stochastic Oscillator and Bollinger Bands

Last updated 1 year ago

The hammer candlestick pattern is characterized by a small body located at the top of the candle, with a long lower shadow. It resembles a hammer, hence its name. This pattern typically forms after a downtrend and suggests a potential bullish reversal. It indicates that despite initial selling pressure, buyers have stepped in and pushed the price back up. This can be interpreted as a signal of strength and a possible shift in market sentiment.

Similarly, the hanging man candlestick pattern also has a small body located at the top of the candle, but with a long lower shadow. However, the hanging man pattern forms during an uptrend and signals a potential bearish reversal. It suggests that despite initial buying pressure, sellers have emerged and pushed the price back down. This can be seen as a sign of weakness and a possible shift in market sentiment.

The Algorithm:

```python
from AlgorithmImports import *

class RetrospectiveYellowGreenAlligator(QCAlgorithm):

    def Initialize(self):
        # INITIALIZE
        self.SetStartDate(2023, 1, 1)
        self.SetEndDate(2023, 7, 23)
        self._cash = 100000
        self.SetCash(self._cash)

        self.ticker = "BTCUSD"
        self.AddCrypto(self.ticker, Resolution.Minute, Market.GDAX).Symbol

Initialization: Here, you're setting up the parameters for the algorithm.

The self.SetStartDate(2023, 1, 1) and self.SetEndDate(2023, 7, 23) lines set the time frame for the backtest to the first half of 2023.

self.SetCash(self._cash) sets the initial cash amount to $100,000. This can be changed to whatever you want. I have used $100k just to get a thorough backtesting result.

self.AddCrypto(self.ticker, Resolution.Minute, Market.GDAX,).Symbol adds the Bitcoin/USD trading pair from the GDAX market to the algorithm. This essentially calls the BTC/USD pair from Coinbase, which is known as GDAX on Quantconnect. The resolution can be changed from Minute to Hourly, Daily etc, however because we are using candlesticks, we want to use a short time frame so that the algorithim trades frequently.

# SET Candlestick patterns 
        self.hammer = self.CandlestickPatterns.Hammer(self.ticker, Resolution.Daily)
        self.hangingman = self.CandlestickPatterns.HangingMan(self.ticker, Resolution.Daily)

The self.CandlestickPatterns.Hammer and self.CandlestickPatterns.HangingMan lines are preparing the algorithm to recognize the Hammer and Hanging Man candlestick patterns.

# Risk management
        self.AddRiskManagement(TrailingStopRiskManagementModel(0.03))
        self.Debug("Stop loss hit")
        self.AddRiskManagement(MaximumDrawdownPercentPerSecurity(0.05))
        self.Debug("Drawdown limit hit")

Risk Management: This section adds risk management to the algorithm.

The TrailingStopRiskManagementModel(0.03) will sell the asset if its price drops by 3% from the highest value since the asset was bought. This is effectively a stop loss, and I have used 3% because Candle patterns tend to produce a lot of false signals so at 3% - losses are minimised.

The MaximumDrawdownPercentPerSecurity(0.05) will stop trading if the portfolio value drops by 5% from the highest value it has ever been.

def OnData(self, data):
        price = self.Securities[self.ticker].Close
 
        if self.hangingman.Current.Value == -1:
            self.SetHoldings(self.ticker, -1)
            self.Debug("Hanging man candle")
        
        if self.hammer.Current.Value == 1:
            self.SetHoldings(self.ticker, 1)
            self.Debug("Hammer candle")

        elif self.Portfolio[self.ticker].UnrealizedProfitPercent > 0.05:
            self.Liquidate(self.ticker)
            self.Debug("Take profit triggered")
        

OnData: This is the core logic of the algorithm. It runs every time new data comes in (in this case, every Minute).

If a Hanging Man pattern is identified, the algorithm will short sell the BTC/USD trading pair using 100% of the portfolio - This is what the -1 represents (self.SetHoldings(self.ticker, -1)).

If a Hammer pattern is identified, the algorithm will buy the BTC/USD trading pair using 100% of the portfolio(self.SetHoldings(self.ticker, 1)).

If the unrealized profit from the current holdings is above 5%, the algorithm will take profit from the trade and close it (self.Liquidate(self.ticker)).

 self.Plot("Strategy Equity", str(self.ticker), self._cash * self.Securities[self.ticker].Close / self._initialValue_ticker)
        self.Plot("Strategy Equity", 'Portfolio Value', self.Portfolio.TotalPortfolioValue)
        self.Plot("Hammer", "value", self.hammer.Current.Value)
        self.Plot("HangingMan", "hangingman", self.hangingman.Current.Value)

Plotting: The algorithm plots two charts: "Strategy Equity" and "Candlestick Patterns".

The "Strategy Equity" chart shows the growth of the portfolio value and the relative price of BTC/USD.

The "Candlestick Patterns" chart shows when Hammer and Hanging Man patterns have been identified.

Backtesting the performance of the Algorithm:

Please refer to the Algorithmic Trading Strategies main page to see how to start using this algorithim.

Link to view the backtest:

https://www.quantconnect.com/terminal/processCache?request=embedded_backtest_6eb5aab5800e87b018a8b47eeecbdab0.html
Visualisation of how these 2 patterns are interpreted
Backtest results
Page cover image