Strategy · Pine Script v4 · On the chart

CBB 2023 Strategy Default

by codybbrown· code credited to bright_infinite

This strategy serves as a backtesting boilerplate and starter template using normalized price metrics.

View on GitHub

GitHub stars2on the repository
Pine versionv4older, still runs
Lines of code147
Settings7inputs
LicenceNone statedfile: MPL-2.0
Last update3 years ago11 Apr 2023

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

147 lines of Pine Script v4 from cbb-boilerplate-utils-backtest-StrategyStarterDefault-2023.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

cbb-boilerplate-utils-backtest-StrategyStarterDefault-2023.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © bright_infinite
//@version=4
// ============================================================================= 
strategy("[CBB] 2023 Strategy Default  ", 
      shorttitle="2023 strat default",
      pyramiding=0,
      calc_on_every_tick=false,
      initial_capital=1000000,
      default_qty_type=strategy.percent_of_equity,
      default_qty_value=20,
      max_bars_back = 5000,
      overlay = true)
     
// ============================================================================= 
//              USER INPUT
// =============================================================================        
in_lookback                 = input(10, type=input.integer, title="in_lookback in_lookback")
in_len_normHigh             = input(20, type=input.integer, title="Normalized High Length")
in_len_normLow              = input(20, type=input.integer, title="Normalized Low Length")
in_trendThresh              = input(3, type=input.integer, title="Directional Bias Threshhold")
in_divThresh                = input(2, type = input.integer, title = "Divergence Threshhold")
in_stratLong                = input(defval=0, type=input.integer, title="Long Strategy Selector", options = [0, 1, 2, 3, 4, 5] )
in_stratShort               = input(defval=0, type=input.integer, title="Short Strategy Selector", options = [0, 1, 2, 3, 4, 5] )

// ============================================================================= 
//              CONSTANTS
// =============================================================================   
FLAT                        = strategy.position_size == 0
LONG                        = strategy.position_size > 0
SHORT                       = strategy.position_size < 0
confirmed                    = barstate.isconfirmed
entry                       = strategy.position_avg_price

var lookForExit             = false   
var tradeStopPrice          = 0.0
var tradeTargetPrice        = 0.0
var trailingStop            = 0.0
var tradeExitTriggerPrice   = 0.0
var tradeStopDistance       = 0.0
var tradeTriggerPrice       = 0.0


h0                          = (high + high[1]) / 2
l0                          = (low + low[1]) / 2
    
normHigh                    = (high - lowest(high, in_len_normHigh)) / (highest(high, in_len_normHigh) - lowest(high, in_len_normHigh))     // * 100
normLow                     = (low - lowest(low, in_len_normLow)) / (highest(low, in_len_normLow) - lowest(low, in_len_normLow))         // * 100

// ============================================================================= 
//              FUNCTIONS
// =============================================================================   

// ============================================================================= 
//              VARIABLES
// =============================================================================    



// ============================================================================= 
//              CONDITIONS
// ============================================================================= 
up1                         = crossover(normLow, 0.5)
dn1                         = crossunder(normLow, 0.5)

// ------------ TREND & PRIMARY SIGNALS
bull                        = rising(normHigh, in_trendThresh) and rising(normLow, in_trendThresh)        // and both > .5
bear                        = falling(normHigh, in_trendThresh) and falling(normLow, in_trendThresh)      // and both < .5
eqLo                        = (normHigh == 0) and (normLow == 0) ? 1 : 0
eqHi                        = (normHigh == 1.0) and (normLow == 1.0) ? 1 : 0

// ------------ DIVERGENCES
// hh              = highest(high, )
hiDiv                       = (normHigh < 0.5) and (normLow > 0.5) ? 1 : 0
regDiv                      = (normHigh > 0.5) and (normLow < 0.5) ? 1 : 0
bearDiv                     = (rising(normLow, in_divThresh) and falling(normHigh, in_divThresh))
bullDiv                     = (rising(normHigh, in_divThresh) and falling(normLow, in_divThresh))
dirBullDiv                  = (bearDiv or bullDiv) and (normLow < 0.5) and (normHigh < 0.5)
dirBearDiv                  = (bearDiv or bullDiv) and(normLow > 0.5) and(normHigh > 0.5)

// ============================================================================= 
//              RISK MANAGEMENT
// ============================================================================= 

// ============================================================================= 
//              ORDER MANAGEMENT
// ============================================================================= 
L0                          = up1
S0                          = dn1
L1                          = bull
S1                          = bear
L2                          = eqLo
S2                          = eqHi
L3                          = hiDiv
S3                          = regDiv
L4                          = bullDiv
S4                          = bearDiv
L5                          = dirBullDiv
S5                          = dirBearDiv


selStratL                   = in_stratLong  == 0 ? L0 :  in_stratLong  == 1 ? L1 : in_stratLong  == 2 ? L2 : in_stratLong  == 3 ? L3 : in_stratLong  == 4 ? L4 : in_stratLong  == 5 ? L5 : na
selStratS                   = in_stratShort == 0 ? S0 :  in_stratShort == 1 ? S1 : in_stratShort == 2 ? S2 : in_stratShort == 3 ? S3 : in_stratShort == 4 ? S4 : in_stratShort == 5 ? S5 : na

// ============================================================================= 
//          STRATEGY EXECUTION 
// ============================================================================= 
if(selStratL)
    strategy.entry("Buy", strategy.long) // enter long by market if current open great then previous high
strategy.close("Buy", selStratL) 

if(selStratS)
    strategy.entry("Sell", strategy.short) // enter long by market if current open great then previous high
strategy.close("Sell", selStratS) //


// ============================================================================= 
//              PLOTS & COLORING
// ============================================================================= 
plot(normHigh, color=color.blue)
plot(normLow, color=color.red)
plot(eqLo ? 0.0 : na, color=color.green, style=plot.style_circles, linewidth=3)      // if eqLo is true, circle is plotted on 0.0
plot(eqHi ? 1.0 : na, color=color.fuchsia, style=plot.style_circles, linewidth=3)    // if eqHi is truem circle is plotted on 1.0

// plot(dirBullDiv ? normLow : na, color=color.yellow, style=plot.style_cross, linewidth=5)    // if eqHi is truem circle is plotted on 1.0
// plot(dirBearDiv ? normHigh: na, color=color.aqua, style=plot.style_cross, linewidth=5)    // if eqHi is truem circle is plotted on 1.0

// barcolor(hiDiv ? color.yellow : na)
// barcolor(regDiv ? color.fuchsia : na)
bgcolor(bull ? color.blue : na, transp=50)
bgcolor(bear ? color.red : na, transp=50)
// bgcolor(dirBearDiv ? color.orange : na, transp=50)
// bgcolor(dirBullDiv ? color.green : na, transp=50)


// ============================================================================= 
//          RESOURCES 
// ============================================================================= 
// How to normalize time series:

//     # time series normalization equation
//     y = (x - min) / (max - min)

// x ... price from input time series
// y ... normalized time series value
// min ... minimum price in the time seies
// max ... maximum price of the time series

Overview

CBB 2023 Strategy Default calculates normalized high and low values across user-defined lookback periods to establish directional bias and evaluate divergence thresholds. Users can configure strategy selector options to route different long and short entry conditions. Plotted directly on the price chart, it tracks market position states, though the template structure lacks default protective stop-loss rules.

Details

Published by

codybbrown on GitHub

Code credit

bright_infinite, as written in the script's header

Type

Strategy, Pine Script v4

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Topics

momentum-trading-strategypinescripttrading-strategiestradingviewvolatility-tradingtrading-indcators

Settings

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

SettingTypeDefaultVariable
in_lookback in_lookbackint10in_lookback
Normalized High Lengthint20in_len_normHigh
Normalized Low Lengthint20in_len_normLow
Directional Bias Threshholdint3in_trendThresh
Divergence Threshholdint2in_divThresh
Long Strategy Selectorint0in_stratLong
Short Strategy Selectorint0in_stratShort
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

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy
285 stars

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns. It generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish

Strategy v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Strategy
228 stars

This strategy generates trading signals based on a selectable momentum engine, supporting MACD, RSI, Stochastic, or Rate of Change. Entries trigger on signal crosses, zero-line crosses, or threshold crosses, with an optional moving average trend filter. Risk m

Strategy v6 Oscillators & momentumTrend
Updated 3 months ago · None stated GitHub repository of Momentum Strategy Template

255 EMA Strategy

by hasnocool
106 stars

255 EMA Strategy combines an exponential moving average with Average True Range bands and standard MACD crossovers to generate entry signals. Drawn directly on the price chart, it plots the central 255 EMA along with upper and lower volatility envelopes. Trade

Strategy v4 Moving averagesOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 255 EMA Strategy

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers