Strategy · Pine Script v5 · On the chart

Bitcoin Momentum Strategy

by Web3Degenerate

This strategy enters long positions when price trades above a higher-timeframe exponential moving average and momentum conditions are clear.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code74
Settings8inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago13 Sep 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

74 lines of Pine Script v5 from advanced-pine-script/9.Strategy-Scripts/20.Bitcoin-Momentum-Strategy-Example.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

20.Bitcoin-Momentum-Strategy-Example.pine
// This breaks down the source code to a Bitcoin Momentum trading system which achieves a +15,000% return with only a -34% max drawdown.

// remake of old lesson "New and improved" version, a strategy he uses in his own trading

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

// @version=5
strategy("Bitcoin Momentum Strategy", 
     overlay=true, 
     initial_capital=10000, 
     currency=currency.USDT,
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=100,
     commission_type=strategy.commission.percent,
     commission_value=0.1)

// Get user input
var const string    G_STRATEGY  = "Strategy Entry Settings"
var const string    G_EXIT      = "Strategy Exit Settings"
var const string    G_FILTER    = "Strategy Filters"
i_HigherTimeframe   = input.timeframe("W", "Higher Timeframe", group=G_STRATEGY, tooltip="Higher timeframe MA reference")
i_EmaLength         = input.int(20, "EMA Length", group=G_STRATEGY, tooltip="Moving average period length")
i_AtrLength         = input.int(5, "ATR Length", group=G_STRATEGY, tooltip="ATR period length")
i_TrailStopSource   = input.source(low, "Trail Stop Source", group=G_EXIT, tooltip="Lowest price source for trailing stop")
i_TrailStopLookback = input.int(7, "Trail Stop Lookback", group=G_EXIT, tooltip="How many bars to look back for trailing price source")
i_TrailStopMulti    = input.float(0.2, "Trailing Stop Ratchet Multiplier", group=G_EXIT, tooltip="When momentum is yellow (caution), shrink ATR distance for TS by this much")
i_StartTime         = input.time(timestamp("01 Jan 2000 13:30 +0000"), "Start Filter", group=G_FILTER, tooltip="Start date & time to begin searching for setups")
i_EndTime           = input.time(timestamp("1 Jan 2099 19:30 +0000"), "End Filter", group=G_FILTER, tooltip="End date & time to stop searching for setups")

// Define custom security function which does not repaint
RequestSecurity_NonRP(_market, _res, _exp) => request.security(_market, _res, _exp[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]

// Define date filter check
DateFilter(int start, int end) => time >= start and time <= end

// Get indicator values
float   atrValue    = ta.atr(i_AtrLength)
float   emaValue    = ta.ema(close, i_EmaLength)
float   htfEmaValue = RequestSecurity_NonRP(syminfo.tickerid, i_HigherTimeframe, emaValue)

// Check if trading timeframe price is above higher timeframe EMA
float   marketPrice = close
bool    isBullish   = marketPrice > htfEmaValue //+ (atrValue * 0.25)

// Check for bearish volatility caution
bool    isCaution   = isBullish and (ta.highest(high, 7) - low > (atrValue * 1.5) or close < emaValue) 

// Set momentum color
color   bgCol = color.red
if isBullish[1]
    bgCol := color.green
if isCaution[1]
    bgCol := color.orange

// Handle strategy entry, and reset trailing stop
var float trailStop = na
if isBullish and strategy.position_size == 0 and DateFilter(i_StartTime, i_EndTime) and not isCaution
    strategy.entry(id="Buy", direction=strategy.long)
    trailStop := na

// Update trailing stop
float temp_trailStop = ta.highest(i_TrailStopSource, i_TrailStopLookback) - (isCaution[1] ? atrValue * i_TrailStopMulti : atrValue)
if strategy.position_size > 0
    if temp_trailStop > trailStop or na(trailStop)
        trailStop := temp_trailStop

// Handle strategy exit
if (close < trailStop or close < htfEmaValue) and barstate.isconfirmed
    strategy.close("Buy", comment="Sell")

// Draw trailing stop, HTF EMA and color-coded momentum indicator
plotshape(true, color=bgCol, style=shape.square, location=location.bottom, size=size.auto, title="Momentum Strength")
plot(htfEmaValue, color=close > htfEmaValue ? color.green : color.red, linewidth=2, title="HTF EMA")
plot(strategy.position_size[1] > 0 ? trailStop : na, style=plot.style_linebr, color=color.red, title="Stop Loss")

Overview

Bitcoin Momentum Strategy avoids new entries during volatility caution periods, which trigger when pullbacks exceed specified Average True Range thresholds. Trades are exited via a dynamic trailing stop based on historical price lows and ATR distance—which tightens during caution phases—or when price drops below the higher-timeframe EMA. Inputs allow adjustment of higher-timeframe resolutions, EMA lengths, and ATR trailing stop multipliers.

Details

Published by

Web3Degenerate on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Oscillators & momentum, Moving averages, Volatility & bands

Markets

Crypto

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Higher TimeframetimeframeWi_HigherTimeframe
EMA Lengthint20i_EmaLength
ATR Lengthint5i_AtrLength
Trail Stop Sourcesourcelowi_TrailStopSource
Trail Stop Lookbackint7i_TrailStopLookback
Trailing Stop Ratchet Multiplierfloat0.2i_TrailStopMulti
Start Filtertimetimestamp("01 Jan 2000 13:30 +0000")i_StartTime
End Filtertimetimestamp("1 Jan 2099 19:30 +0000")i_EndTime
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

106 stars

This trading strategy combines three Exponential Moving Averages (8, 14, and 50 periods by default) with Stochastic RSI and Average True Range (ATR). It enters a long position when EMA 1 is above EMA 2, EMA 2 is above EMA 3, and the Stochastic RSI %K line cros

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 3 x EMA + Stochastic RSI + ATR

Momentum Rider DAILY FINAL

by greenpeas007
58 stars

This strategy combines exponential moving averages (EMA 9, 21, 50), RSI, MACD, and Supertrend indicators to enter long positions. It triggers trades using six dynamic setups based on momentum breakouts, EMA crossovers, and pullbacks. Position sizing is compute

Strategy v6 TrendOscillators & momentum Repaints
Updated 4 months ago · Custom licence GitHub repository of Momentum Rider DAILY FINAL

CombinedBinHAndClucV6

by viktors1982
36 stars

CombinedBinHAndClucV6 is a trading strategy based on the popular BinHV45 and ClucMay72018 algorithms. It calculates dual Bollinger Bands, Exponential Moving Averages, Relative Strength Index, Average True Range, and volume metrics across primary and one-hour h

Strategy v4 Volatility & bandsOscillators & momentum Repaints
Updated 2 years ago · None stated GitHub repository of CombinedBinHAndClucV6

BB Swing

by benso87
24 stars

This strategy calculates Bollinger Bands, a configurable moving average slope, Stochastic RSI, ATR, and ADX directly on the price chart. It evaluates trend bias and momentum conditions to generate long and short swing entries using percent-of-equity sizing. Th

Strategy v5 Volatility & bandsOscillators & momentum
Updated 4 years ago · MPL-2.0 GitHub repository of BB Swing

This strategy trades long and short on the price chart using a multi-timeframe TradingLatino setup. It requires EMA 10 to cross or sit above or below EMA 55 on the one-hour, four-hour, and daily charts, together with a positive ADX slope, a directional monitor

Strategy v5 TrendMoving averages
Updated 1 year ago · None stated GitHub repository of Ruckard ABCBitcoin TradingLatino A010

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers