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 2: Stochastic Oscillator and Bollinger Bands

This algorithm is designed to trade the cryptocurrency Ethereum (ETH) based on Bollinger Bands and Stochastic Oscillator indicators. However it can also be used for any cryptocurrency.

PreviousStrategy 1: Candlestick Trading Pattern (Hammer and Hanging Man candles)NextStrategy 3: Diversified Crypto Portfolio Investing with Stochastics & Bollinger Bands

Last updated 1 year ago

Bollinger Bands are a popular technical analysis tool that consists of a middle band (typically a simple moving average) and two outer bands that represent the standard deviations from the middle band. The purpose of Bollinger Bands is to provide a statistical representation of price volatility. When the price is closer to the outer bands, it suggests higher volatility, while prices near the middle band indicate lower volatility. Traders often use Bollinger Bands to identify potential price reversals, breakouts, and overbought or oversold conditions.

The Stochastic Oscillator is another widely used technical indicator that measures the momentum of price movements. It compares the closing price of an asset to its price range over a given period. The oscillator consists of two lines: %K (fast line) and %D (slow line). The values range from 0 to 100, with readings above 80 considered overbought and readings below 20 considered oversold.

Traders use the Stochastic Oscillator to identify potential trend reversals, divergences, and overbought/oversold conditions. When used together, Bollinger Bands and Stochastic Oscillator provide valuable insights to traders. Bollinger Bands help identify periods of high or low volatility, while the Stochastic Oscillator confirms overbought or oversold conditions. This combination allows traders to seek potential trend reversals when the price reaches the outer bands and the Stochastic Oscillator signals extremes, or to confirm breakouts and trend continuations during periods of low volatility. By leveraging the complementary information from these indicators, traders can enhance their analysis and make more informed trading decisions.

The Algorithim:

Initialization: In this section, you're setting up the parameters for the algorithm.

self.SetStartDate(2016, 6, 18) and self.SetEndDate(2023, 6, 19) set the time frame for the backtest from mid-June 2016 to mid-June 2023.

self.SetCash(self._cash) sets the initial cash amount to $100,000.

self.AddCrypto(self.ticker, Resolution.Daily) adds the Ethereum/USD trading pair to the algorithm.

from AlgorithmImports import *

class RetrospectiveYellowGreenAlligator(QCAlgorithm):

    def Initialize(self):
        # INITIALIZE
        self.SetStartDate(2016, 6, 18)
        self.SetEndDate(2023, 6, 19)
        self._cash = 100000
        self.SetCash(self._cash)

        self.ticker = "ETHUSD"
        self.AddCrypto(self.ticker, Resolution.Daily)

Set the Technical Indicators (Stochastic & Bollinger Bands):

self.BB(self.ticker, 20, 0.3, MovingAverageType.Simple, Resolution.Daily) sets up a Bollinger Bands indicator with a period of 20 days and a standard deviation of 0.3, calculated on the closing prices of the ETH/USD trading pair.

self.STO(self.ticker, 8, 5, 5, Resolution.Daily) sets up a Stochastic Oscillator with a period of 8 days, smoothing period K of 5, and smoothing period D of 5.

 # SET TECHNICAL INDICATORS
        self.Bolband = self.BB(self.ticker, 20, 0.3, MovingAverageType.Simple, Resolution.Daily)
        self.sto = self.STO(self.ticker, 8, 5, 5, Resolution.Daily)

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

TrailingStopRiskManagementModel(0.06) will sell the asset if its price drops by 6% from the highest value since the asset was bought.

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

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

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

If the closing price of the Ethereum/USD pair is above the upper Bollinger Band and the Stochastic Oscillator is above 50, the algorithm will buy the ETH/USD trading pair (self.SetHoldings(self.ticker, 1)).

If the closing price of the Ethereum/USD pair is above the middle Bollinger Band and below the upper Bollinger Band, the algorithm will sell the ETH/USD trading pair (self.Liquidate(self.ticker)).

def OnData(self, data):
        price = self.Securities[self.ticker].Close
        sto_value = self.sto.Current.Value

        if price > self.Bolband.UpperBand.Current.Value and sto_value > 50:
            self.SetHoldings(self.ticker, 1)
            self.Debug("Long position triggered")

        elif price > self.Bolband.MiddleBand.Current.Value and price < self.Bolband.UpperBand.Current.Value:
            self.Liquidate(self.ticker)
            self.Debug("Trade closed")

Plotting: The algorithm plots three charts: "Strategy Equity", "Bollinger", and "Stochastic".

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

The "Bollinger" chart shows the three Bollinger Bands (upper, middle, lower) and the closing price of the ETH/USD trading pair.

The "Stochastic" chart shows the three lines of the Stochastic Oscillator: fast stochastic, stochastic %K, and stochastic %D.

 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("Bollinger", 'BB Lower', self.Bolband.LowerBand.Current.Value)
        self.Plot("Bollinger", 'BB Upper', self.Bolband.UpperBand.Current.Value)
        self.Plot("Bollinger", 'BB Middle', self.Bolband.MiddleBand.Current.Value)
        self.Plot("Bollinger", str(self.ticker), self.Securities[self.ticker].Close)
        self.Plot("Stochastic", "faststoch", self.sto.FastStoch.Current.Value)
        self.Plot("Stochastic", "stochk", self.sto.StochK.Current.Value)
        self.Plot("Stochastic", "stochd", self.sto.StochD.Current.Value)

Backtesting the performance of the Algorithm:

The strategy has done extremely well over the 7 year backtesting period. However before using it, you need to backtest it over different time periods to see how it would've performed in the short,medium and long-term.

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

Link to view the backtest yourself:

https://www.quantconnect.com/terminal/processCache?request=embedded_backtest_24f613769cbc59408fc6d456e9b134f7.html
Page cover image
An example showing what Bollinger Bands look like
Backtesting results
Backtest metrics