Strategy · Pine Script v4 · Own pane

B-Xtrender [Backtest Edition] @QuantTherapy

by hasnocool· code credited to QuantTherapy

This strategy implements the B-Xtrender indicator, calculating short-term and long-term momentum oscillators using RSI applied to moving average spreads and smoothings.

View on GitHub

GitHub stars106on the repository
Pine versionv4older, still runs
Lines of code91
Settings16inputs
LicenceGPL-3.0
Last update2 years ago18 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

91 lines of Pine Script v4 from B-Xtrender [Backtest Edition] @QuantTherapy.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

B-Xtrender [Backtest Edition] @QuantTherapy.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © QuantTherapy
//@version=4
strategy("B-Xtrender [Backtest Edition] @QuantTherapy")
// === DATE & TIME SELECTION ===
i_fromMonth  = input(defval = 1,       title = "[Backtest] From Month",      type = input.integer, minval = 1, maxval = 12)
i_fromDay    = input(defval = 1,       title = "[Backtest] From Day",        type = input.integer, minval = 1, maxval = 31)
i_fromYear   = input(defval = 2010,    title = "[Backtest] From Year",       type = input.integer, minval = 1970)
i_thruMonth  = input(defval = 1,       title = "[Backtest] Thru Month",      type = input.integer, minval = 1, maxval = 12)
i_thruDay    = input(defval = 1,       title = "[Backtest] Thru Day",        type = input.integer, minval = 1, maxval = 31)
i_thruYear   = input(defval = 2345,    title = "[Backtest] Thru Year",       type = input.integer, minval = 1970)
// === DATE & TIME RANGE FUNCTIONS ===
f_isDate() =>                                                      // create function "within window of dates"
    start  = timestamp(i_fromYear, i_fromMonth, i_fromDay, 00, 00)     // date start
    finish = timestamp(i_thruYear, i_thruMonth, i_thruDay, 23, 59)     // date finish
    isDate = time >= start and time <= finish                    // current date is "within window of dates"
    
// === TRADE DIRECTION ===
i_tradeDirection = input(title="[Backtest] Trade Direction", defval=strategy.direction.all, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])    
strategy.risk.allow_entry_in(i_tradeDirection)
// === LONG/ SHORT EXTRENDER SELECTION ===
i_short_l1  = input(5 , title="[Short] L1")
i_short_l2  = input(20, title="[Short] L2")
i_short_l3  = input(15, title="[Short] L3")
i_long_l1   = input(20, title="[Long] L1")
i_long_l2   = input(15, title="[Long] L2")
// === TSL SELECTION ===
i_ma_use    = input(true , title="[MA Filter] Yes/No" )
i_ma_len    = input(200  , title="[MA Filter] length" )
i_ma_type   = input("EMA", title="[MA Filter] type", options = ["SMA", "EMA"])
shortTermXtrender = rsi( ema(close, i_short_l1) - ema(close, i_short_l2), i_short_l3 ) - 50
longTermXtrender  = rsi( ema(close, i_long_l1), i_long_l2 ) - 50
shortXtrenderCol = shortTermXtrender > 0 ? shortTermXtrender > shortTermXtrender[1] ? color.lime : #228B22 : shortTermXtrender > shortTermXtrender[1] ? color.red : #8B0000
plot(shortTermXtrender, color=shortXtrenderCol, style=plot.style_columns, linewidth=1, title="B-Xtrender Osc. - Histogram", transp = 40)
longXtrenderCol   = longTermXtrender> 0 ? longTermXtrender > longTermXtrender[1] ? color.lime : #228B22 : longTermXtrender > longTermXtrender[1] ? color.red : #8B0000
macollongXtrenderCol =  longTermXtrender > longTermXtrender[1] ? color.lime : color.red
plot(longTermXtrender , color=longXtrenderCol, style=plot.style_columns, linewidth=2, title="B-Xtrender Trend - Histogram", transp = 90)
plot(longTermXtrender , color=#000000             , style=plot.style_line, linewidth=5, title="B-Xtrender Trend - Line", transp = 100)
plot(longTermXtrender , color=macollongXtrenderCol, style=plot.style_line, linewidth=3, title="B-Xtrender Trend - Line", transp = 100)
// === INIT MA FILTER
ma = i_ma_type == "EMA" ? ema(close, i_ma_len) : sma(close, i_ma_len)
maFilterLong = true
maFilterShort = true
if i_ma_use
    maFilterLong  := close > ma ? true : false
    maFilterShort := close < ma ? true : false
long  = shortTermXtrender > 0 and longTermXtrender > 0 and maFilterLong
closeLong = shortTermXtrender < 0 or longTermXtrender < 0 
short = shortTermXtrender < 0 and longTermXtrender < 0 and maFilterShort
closeShort = shortTermXtrender > 0 or longTermXtrender > 0 
plotshape(long[1]==true  and long[2]==false  ? 0 : na , location=location.absolute, style=shape.labelup  , color=color.lime, size=size.small, transp=10)
plotshape(short[1]==true and short[2]==false ? 0 : na, location=location.absolute, style=shape.labeldown, color=color.red , size=size.small, transp=10)
plotshape(closeLong[1]==true and closeLong[2]==false
 or closeShort[1]==true and closeShort[2]==false ? 0 : na, location=location.absolute, style=shape.circle, color=color.orange , size=size.small)
i_perc     = input(defval = 20.0, title = "[TSL-%] Percent"  , minval = 0.1 )
i_src = close // constant for calculation
sl_val = i_src * i_perc / 100
toLong = long and f_isDate()
toShort = short and f_isDate()
// === WHEN POSITION IS OPEN AN DATE IS OUT OF BOUND CLOSE ALL TRADES
if not f_isDate() and strategy.position_size != 0
    strategy.close_all()
strategy.entry("Long", strategy.long, when = toLong ) 
strategy.close("Long", when = closeLong)
strategy.entry("Short", strategy.short, when = toShort) 
strategy.close("Short", when = closeShort)
// Calculate SL
longStopPrice = 0.0, shortStopPrice = 0.0
longStopPrice := if (strategy.position_size > 0)
    stopValue = close - sl_val
    max(stopValue, longStopPrice[1])
else
    0
shortStopPrice := if (strategy.position_size < 0)
    stopValue = close + sl_val
    min(stopValue, shortStopPrice[1])
else
    syminfo.mintick*1000000
// For TSL Visualisation on Chart    
// plot(series=(strategy.position_size > 0) ? longStopPrice : na,
//      color=color.fuchsia, style = plot.style_circles,
//      linewidth=1, title="Long Trail Stop")
     
// plot(series=(strategy.position_size < 0) ? shortStopPrice : na,
//      color=color.fuchsia, style = plot.style_circles,
//      linewidth=1, title="Short Trail Stop")
if (strategy.position_size > 0)
    strategy.exit(id="TSL Long", stop=longStopPrice)
if (strategy.position_size < 0)
    strategy.exit(id="TSL Short", stop=shortStopPrice)    
Expand (111 lines)

Overview

B-Xtrender [Backtest Edition] @QuantTherapy plots the momentum oscillators as colored histograms in a separate pane. Trades are filtered by an optional baseline EMA or SMA and restricted to a user-defined date window. Entries trigger based on oscillator alignments with the trend filter, and positions are protected by a configurable percentage trailing stop loss.

Details

Published by

hasnocool on GitHub

Code credit

QuantTherapy, as written in the script's header

Type

Strategy, Pine Script v4

Draws

Separate pane below the chart

Category

Oscillators & momentum, Trend, Moving averages

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
[Backtest] From Monthint1i_fromMonth
[Backtest] From Dayint1i_fromDay
[Backtest] From Yearint2010i_fromYear
[Backtest] Thru Monthint1i_thruMonth
[Backtest] Thru Dayint1i_thruDay
[Backtest] Thru Yearint2345i_thruYear
[Backtest] Trade Directioninputstrategy.direction.alli_tradeDirection
[Short] L1int5i_short_l1
[Short] L2int20i_short_l2
[Short] L3int15i_short_l3
[Long] L1int20i_long_l1
[Long] L2int15i_long_l2
Show all 16 settings
SettingTypeDefaultVariable
[MA Filter] Yes/Nobooltruei_ma_use
[MA Filter] lengthint200i_ma_len
[MA Filter] typestringEMAi_ma_type
[TSL-%] Percentfloat20.0i_perc
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

330 stars

MACD + Divergences [Alorse] is a momentum strategy that calculates the MACD oscillator and identifies regular and hidden divergences using pivot high and low points. It filters trade signals with dual Exponential Moving Averages (EMA 150 and 600) to ensure tra

Strategy v4 Oscillators & momentumDivergence Repaints
Updated 2 months ago · None stated GitHub repository of MACD + Divergences [Alorse]

MACD Crossover (tutorial)

by pineforge-4pass
193 stars

This strategy calculates the Moving Average Convergence Divergence indicator and plots the MACD line, signal line, and histogram in a separate pane. It enters long positions when the MACD line crosses above the signal line and enters short positions when it cr

Strategy v6 Oscillators & momentumMoving averages
Updated today · Apache-2.0 GitHub repository of MACD Crossover (tutorial)

EMA Ribbon MACD

by iamrichardD
57 stars

This strategy combines an EMA ribbon with MACD confirmation and plots in a separate pane. It enters when ribbon alignment, optional MACD zero or signal crosses, volume, smart-money, and multi-timeframe filters agree, then exits with percentage stop loss and ta

Strategy v6 TrendMoving averages
Updated 1 year ago · Apache-2.0 GitHub repository of EMA Ribbon MACD

This strategy evaluates the dynamic relationship between price and a chosen moving average across six diagnostic dimensions: trend, respect, extension, compression, acceleration, and exhaustion. It plots a normalized relationship oscillator bounded between -10

Strategy v6 TrendMoving averages
Updated yesterday · MIT GitHub repository of Market–Average Relationship Engine [WavesUnchained]
7 stars

This strategy combines the Moving Average Convergence Divergence oscillator with an Exponential Moving Average trend filter. It enters long positions when the MACD histogram crosses above zero while price stays above the long-term EMA filter. Long trades close

Strategy v5 TrendOscillators & momentum
Updated 1 year ago · MPL-2.0 GitHub repository of MACD EMA Filter Strategy

MACD Signal Cross

by latentwill
4 stars

This strategy evaluates EMA momentum crossovers filtered by an RSI oscillator. It enters a long position when a fast EMA crosses above a slow EMA while RSI remains above 40. Conversely, it enters a short position when the fast EMA crosses below the slow EMA wh

Strategy v5 Moving averagesOscillators & momentum
Updated 6 days ago · None stated GitHub repository of MACD Signal Cross

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