Strategy · Pine Script v4 · On the chart

ATR_Trade_strategy

by hasnocool· code credited to arameshraju

This strategy plots daily ATR bands, an optional midline, and an exponential moving average directly on the price chart.

View on GitHub

Repaints

GitHub stars106on the repository
Pine versionv4older, still runs
Lines of code61
Settings10inputs
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

61 lines of Pine Script v4 from ATR_Trade_strategy.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

ATR_Trade_strategy.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © arameshraju
//Thanks to Vamsikrishna Kona  who planned this Idea in my mind. helped ot inprove it
//@version=4
strategy("ATR_Trade_strategy-2",shorttitle="ATR_Trade", overlay=true) 
showMiddle = input(false, title="Show Middle Line", type=input.bool)
showEMA = input(true, title="Show EMA Line", type=input.bool)
showTypical = input(false, title="Show Typical Line", type=input.bool)
length = input(title="Length", defval=14, minval=1)
smoothing = input(title="Smoothing", defval="EMA", options=["RMA", "SMA", "EMA", "WMA"])
maxLoss = input(0.5, title="Max Loss on one Trade", type=input.float)
emaCount = input(10, title="EMA Periods", type=input.integer)
tradeQty = input(10, title="Trade Quanity", type=input.integer)
SlasMiddle = input(false, title="Stop Loss as Middle", type=input.bool)
onTypical = input(false, title="Trade on Typical", type=input.bool)
getSeries(_e, _timeFrame) => security(syminfo.tickerid, _timeFrame, _e, lookahead=barmerge.lookahead_on) 
previousClose= getSeries(close[1], 'D')
previousHigh= getSeries(high[1], 'D')
previousLow= getSeries(low[1], 'D')
typicalPrice=(close+high+low)/3
mxloss=close*maxLoss
 
ma_function(source, length) =>
    if smoothing == "RMA"
        rma(source, length)
    else
        if smoothing == "SMA"
            sma(source, length)
        else
            if smoothing == "EMA"
                ema(source, length)
            else
                wma(source, length)
ATRH=ma_function(tr(true), length)+previousClose
ATRL=previousClose-ma_function(tr(true), length)
ATRM= (ATRH+ATRL)/2
plot(ATRH, title = "ATR-HIGH", color=#991515, transp=80)
plot(ATRL, title = "ATR-LOW", color=#991515, transp=80)
plot(showMiddle?ATRM:na, title = "ATR-MIDDLE", color=#80cbc4, transp=60)
plot(showTypical?typicalPrice:na, title = "ATR-MIDDLE", color=color.black)
plot(showEMA?ema(close, emaCount):na, color=color.blue)
lognCondition =  onTypical? typicalPrice> (ATRH):close> (ATRH*1.01) 
shortCondition = onTypical ? typicalPrice< (ATRL)  :  close< (ATRL) 
// if onTypical
//     lognCondition=typicalPrice> (ATRH)  
//     shortCondition = typicalPrice< (ATRL) 
// else
//     lognCondition=close> (ATRH*1.01) 
//     shortCondition = close< (ATRL) 
if(lognCondition  and year>2009)   
    strategy.entry("Buy", strategy.long, tradeQty,when=strategy.position_size <= 0)    
if(shortCondition and year>2009)   
    strategy.entry("sell", strategy.short, tradeQty,when=strategy.position_size > 0)
strategy.close("buy", when = close < ema(close, emaCount),  comment = "close if blow ema")
strategy.close("sell", when = close > ema(close, emaCount),  comment = "close if blow ema")
strategy.close("buy", when = (close < ATRM) and SlasMiddle,  comment = "close if blow ATRM")
strategy.close("sell", when = (close > ATRM) and SlasMiddle,  comment = "close if ABOVE ATRM")
strategy.exit("Buy", "long", loss = mxloss)
strategy.exit("sell", "long", loss = mxloss)
//plot(strategy.equity)
Expand (84 lines)

Overview

ATR_Trade_strategy executes long trades when price breaks above the upper ATR band and opens short positions when price falls below the lower band, with an option to trigger on typical price. Positions exit upon crossing the moving average, crossing the midline if enabled, or reaching a percentage-based maximum loss limit. Key settings adjust the ATR length, smoothing method, moving average period, and trade quantities. A notable limitation is the use of higher-timeframe security calls with lookahead enabled, causing lookahead bias.

Details

Published by

hasnocool on GitHub

Code credit

arameshraju, as written in the script's header

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Volatility & bands, Breakout, Moving averages

Markets

Crypto

Timeframes

M1-M5, M15-H1

Risk Notes

  • Reads higher-timeframe data with lookahead on, so the history can show signals that were not there in real time

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
Show Middle LineboolfalseshowMiddle
Show EMA LinebooltrueshowEMA
Show Typical LineboolfalseshowTypical
Lengthint14length
SmoothingstringEMAsmoothing
Max Loss on one Tradefloat0.5maxLoss
EMA Periodsint10emaCount
Trade Quanityint10tradeQty
Stop Loss as MiddleboolfalseSlasMiddle
Trade on TypicalboolfalseonTypical
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

Bollinger Breakout

by hackingthemarkets
189 stars

This price-chart strategy plots a simple moving average and upper and lower bands built from the standard deviation of close, scaled by separate offset inputs. It enters a fixed quantity long when close crosses above the upper band and a fixed quantity short w

Strategy v4 Volatility & bandsBreakout
Updated 3 years ago · None stated GitHub repository of Bollinger Breakout

均线突破交易系统

by tangly1024
76 stars

This strategy trades long breakouts of a fast and a slow moving average on the price chart. It opens a long position when price crosses above either average, using a percentage of equity as size. It reduces the position by a set share when the high reaches the

Strategy v5 TrendMoving averages
Updated 4 months ago · None stated GitHub repository of 均线突破交易系统

Bollinger bands examples

by tradingstrategy-ai
53 stars

This strategy plots exponential-moving-average Bollinger bands on the price chart and calculates RSI. It opens a long position when close crosses above the upper band while RSI is at or above a threshold, the date filter allows trading, and no position is open

Strategy v5 Volatility & bandsOscillators & momentum
Updated 3 years ago · None stated GitHub repository of Bollinger bands examples

Keltner Channels Strategy

by TWODS-CAPITAL
37 stars

This strategy builds Keltner-style bands around an exponential or simple moving average of the chosen source. Band width uses average true range, raw true range, or a smoothed high-low range, scaled by a multiplier. When the source crosses above the upper band

Strategy v5 Volatility & bandsBreakout
Updated 3 years ago · MIT GitHub repository of Keltner Channels Strategy
16 stars

This strategy plots Donchian channels, trailing stops, and profit targets directly on the price chart. It enters breakout trades using a 55-bar Donchian channel and sizes positions according to an ATR-based risk percentage per unit. The system adds units as pr

Strategy v6 TrendBreakout
Updated 11 months ago · None stated GitHub repository of Seykota Alt 10: Profit Targets

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