Indicator · Pine Script v4 · On the chart

Stdev Breakout Strategy

by capissimo

This indicator identifies standard deviation breakout signals by comparing standard deviation against its simple moving average.

View on GitHub

Repaints

GitHub stars114on the repository
Pine versionv4older, still runs
Lines of code151
Settings10inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago7 Nov 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 indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

151 lines of Pine Script v4 from scripts/120-Stdev-Breakout-Strategy.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

120-Stdev-Breakout-Strategy.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © capissimo

//@version=4
study("Stdev Breakout Strategy", '', true)

// Stdev Breakout Strategy

// Description:

// This script generates a long entry signal when the Standard Deviation crosses
// over the Simple Moving Average and the Close is greater than the Open, and/or 
// generates a short entry signal when    the Standard Deviation crosses under the
// Simple Moving Average and the Close is less than the Open.

//-------------------- Inputs

ptype      = input('Close','Dataset',                     options=['Open','High','Low','Close','HL2','OC2','OHL3','HLC3','OHLC4'])
reso       = input('',     'Resolution',                  input.resolution)
lag        = input(10,     'Lag |1..n|',                  minval=1)
malag      = input(200,    'MA Lag |1..n|',               minval=1)
tthres     = input(0.01,   'Time Threshold |0.1..100.0|', minval=0.0, maxval=100.0, step=0.01)
ftype      = input('None', 'Filter Signals by',           options=['Volatility','Volume','Both','None'])
holding_p  = input(2,      'Holding Period |1..n|',       minval=1)

//-------------------- System Variables

var int BUY  =  1
var int SELL = -1
var int HOLD =  0

//-------------------- Series 

var int   signal     = HOLD
var int   hp_counter = 0

//-------------------- Custom Functions

volumeBreak(thres) =>  
    rsivol   = rsi(volume, 14)  
    osc      = hma(rsivol, 10)  
    osc > thres                     

volatilityBreak(volmin, volmax) => atr(volmin) > atr(volmax)

//-------------------- Logic

tbase   = (time - time[1]) / 1000
tcurr   = (timenow - time_close[1]) / 1000
barlife = tcurr / tbase

dset   =   ptype=='Open'  ? open 
         : ptype=='High'  ? high 
         : ptype=='Low'   ? low 
         : ptype=='Close' ? close 
         : ptype=='OC2'   ? (open+close)/2 
         : ptype=='HL2'   ? hl2 
         : ptype=='OHL3'  ? (open+high+low)/3 
         : ptype=='HLC3'  ? hlc3 
         :                  ohlc4

filter =   ftype=='Volatility' ? volatilityBreak(1, 10) 
         : ftype=='Volume'     ? volumeBreak(49) 
         : ftype=='Both'       ? volatilityBreak(1, 10) and volumeBreak(49)
         :                       true

//-- Core
c  = security('', reso, dset)
sd = stdev(c, 10)
ma = sma(sd, 200)

long    = crossover(sd, ma)  and close > open
short   = crossunder(sd, ma) and close < open
signal := long and filter ? BUY : short and filter ? SELL : nz(signal[1])

changed = change(signal)

hp_counter := changed ? 0 : hp_counter + 1
//--

startLongTrade  = barlife > tthres and changed and signal==BUY    
startShortTrade = barlife > tthres and changed and signal==SELL   
endLongTrade    = (changed and signal==SELL) or (signal==BUY  and hp_counter==holding_p and not changed) 
endShortTrade   = (changed and signal==BUY)  or (signal==SELL and hp_counter==holding_p and not changed) 

//-------------------- Visualization

plotshape(startLongTrade  ? low  : na, 'Buy',  shape.labelup,   location.belowbar, color.blue, 30, text='', size=size.small)
plotshape(startShortTrade ? high : na, 'Sell', shape.labeldown, location.abovebar, color.red,  30, text='', size=size.small)
plot(endLongTrade         ? high : na, 'StopBuy',  color.blue, 2, plot.style_cross)
plot(endShortTrade        ? low  : na, 'StopSell', color.red,  2, plot.style_cross)

//-------------------- Notification

if changed and signal==BUY 
    alert('Buy Alert', alert.freq_once_per_bar)  // alert.freq_once_per_bar_close
if changed and signal==SELL 
    alert('Sell Alert', alert.freq_once_per_bar)
    
alertcondition(startLongTrade,  'Buy Alert',  'Go Long!')
alertcondition(startShortTrade, 'Sell Alert', 'Go Short!')

//-------------------- Backtest

show_info = input(false, '===Information===')
lot_size  = input(0.01,  'Lot Size', options=[0.01,0.1,0.2,0.3,0.5,1,2,3,5,10,20,30,50,100,1000]) 
ubase     = input(false, 'Use Base Price?')

bidask = ubase ? dset : open 

var float start_long_trade  = bidask  
var float long_trades       = 0.
var float start_short_trade = bidask  
var float short_trades      = 0.
var int   wins              = 0
var int   trade_count       = 0

if startLongTrade 
    start_long_trade := bidask 
if endLongTrade
    ldiff         = (bidask - start_long_trade)
    wins         := ldiff > 0 ? 1 : 0
    long_trades  := ldiff * lot_size   
    trade_count  := 1
if startShortTrade 
    start_short_trade := bidask
if endShortTrade
    sdiff         = (start_short_trade - bidask)
    wins         := sdiff > 0 ? 1 : 0
    short_trades := sdiff * lot_size 
    trade_count  := 1
    
cumreturn   = cum(long_trades) + cum(short_trades)  //-- cumulative return 
totaltrades = cum(trade_count)
totalwins   = cum(wins)  
totallosses = totaltrades - totalwins == 0 ? 1 : totaltrades - totalwins

//------------------- Information

var label lbl = na

info =  'CR='          + tostring(cumreturn,             '#.#') 
      + '\nTrades: '   + tostring(totaltrades,           '#')
      + '\nWin/Loss: ' + tostring(totalwins/totallosses, '#.##') 
      + '\nWinrate: '  + tostring(totalwins/totaltrades, '#.#%')       
      + '\nBar Time: ' + tostring(barlife,               '#.#%')

if show_info and barstate.islast  
    lbl := label.new(bar_index, ohlc4, info, xloc.bar_index, yloc.price, 
                     color.new(color.blue, 100), label.style_label_left, color.black, size.small, text.align_left)
    label.delete(lbl[1])

Overview

A long signal triggers when standard deviation crosses above its moving average during a bullish candle, while a short signal occurs when it crosses below during a bearish candle. Signals can be filtered by ATR volatility, volume RSI, or both. Positions automatically close after a configurable holding period or when an opposite signal triggers. Buy and sell labels display directly on the price chart. Signal timing relies on live time calculations, causing historical bars to evaluate differently than live bars.

Details

Published by

capissimo on GitHub

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

Volatility & bands, Breakout, Oscillators & momentum

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)

Settings

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

SettingTypeDefaultVariable
DatasetstringCloseptype
Resolutiontimeframereso
Lag |1..n|int10lag
MA Lag |1..n|int200malag
Time Threshold |0.1..100.0|float0.01tthres
Filter Signals bystringNoneftype
Holding Period |1..n|int2holding_p
===Information===boolfalseshow_info
Lot Sizefloat0.01lot_size
Use Base Price?boolfalseubase
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

Raschke Patterns

by TradersPost
218 stars

This overlay indicator marks Linda Raschke short-term bar setups on the price chart. It flags Turtle Soup and Turtle Soup plus one false breakouts of a prior extreme, 80-20 bars, inside bars, failed inside-bar breakouts, outside up and down bars, NR4 and NR7 c

Indicator v6 Candlestick patternsBreakout Repaints
Updated 3 months ago · None stated GitHub repository of Raschke Patterns

Squeeze Momentum

by mihakralj
99 stars

This indicator plots Squeeze Momentum in a separate pane. It compares Bollinger Bands with a Keltner Channel to mark a squeeze when the bands sit inside the channel. Momentum is a linear regression of price relative to a Donchian midline and an SMA, shown as a

Indicator v6 Volatility & bandsOscillators & momentum
Updated 4 weeks ago · Apache-2.0 GitHub repository of Squeeze Momentum

Renko Acceleration

by f-cksociety
11 stars

Calculates the time elapsed between consecutive bars to measure market speed and volatility, designed primarily for Renko chart blocks where bar duration varies. In Momentum mode, it contrasts the current duration against a 100-period moving average baseline,

Indicator v4 Volatility & bandsOscillators & momentum
Updated 4 years ago · MPL-2.0 GitHub repository of Renko Acceleration

The Momentum Setup is a multi-indicator visual tool designed for trend and momentum analysis directly on the price chart. It combines Relative Strength Index (RSI), Money Flow Index (MFI), Commodity Channel Index (CCI), Supertrend, and a 250-bar percentage cha

Indicator v5 Oscillators & momentumTrend
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - Ankush Bajaj Momentum Investing Setup

This indicator plots trade entry and exit signals on the price chart by combining Bollinger Bands with optional filter conditions. It calculates standard Bollinger Bands along with RSI, Aroon, and moving average filters. Reversal signals trigger when price bre

Indicator v4 Volatility & bandsOscillators & momentum
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner IND [Alorse]
257 stars

An overlay indicator that combines an ATR-based SuperTrend trailing stop with an integrated RSI-derived midline calculation on the price chart. The SuperTrend uses an ATR period and factor multiplier to plot dynamic green or red trend lines based on price dire

Indicator v5 TrendVolatility & bands
Updated 6 weeks ago · None stated GitHub repository of SuperTrend ATR + RSI

More indicators

Trade Your Charts With a Regulated Broker

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

Compare brokers