Indicator · Pine Script v4 · On the chart

Trend Magic

by capissimo

Calculates and plots a dynamic trend line on the price chart using Commodity Channel Index (CCI) and Average True Range (ATR).

View on GitHub

GitHub stars114on the repository
Pine versionv4older, still runs
Lines of code150
Settings12inputs
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

150 lines of Pine Script v4 from third-party/Trend-Magic.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Trend-Magic.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("Trend Magic", "TM", true, format=format.price, precision=2)

// This is my modification of the Trend Magic script © KivancOzbilgic
// featuring signal generator and performance measurement modules

//-------------------- inputs

ptype      = input('Close','Dataset',                           options=['Open','High','Low','Close','HL2','OC2','OHL3','HLC3','OHLC4'])
period     = input(20,     "CCI period",                        minval=1)
coeff      = input(1,      "ATR Multiplier",                    minval=1)  
AP         = input(5,      "ATR Period",                        minval=1)

ftype      = input('Volatility', 'Filter Signals by',           options=['Volatility','Volume','Both','None'])
minatr     = input(1,      'Min ATR Lag for the Filter |1..n|', minval=1)
maxatr     = input(10,     'Max ATR Lag for the Filter |1..n|', minval=1)
vol        = input(55,     'Volume Lag for the Filter |1..n|',  minval=1)
holding_p  = input(1,      '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
var float MagicTrend = 0.0

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

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

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

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

ds       =  ptype=='Open'  ? open
          : ptype=='High'  ? high 
          : ptype=='Low'   ? low 
          : ptype=='Close' ? close 
          : ptype=='HL2'   ? (high+low)/2 
          : ptype=='OC2'   ? (open+close)/2 
          : ptype=='OHL3'  ? (open+high+low)/3 
          : ptype=='HLC3'  ? (high+low+close)/3 
          :                  (open+high+low+close)/4

ATR         = sma(tr, AP)
upT         = low-ATR*coeff
downT       = high+ATR*coeff
MagicTrend := cci(ds, period)>=0 ? (upT<nz(MagicTrend[1]) ? nz(MagicTrend[1]) : upT) : (downT>nz(MagicTrend[1]) ? nz(MagicTrend[1]) : downT)
color1      = cci(ds, period)>=0 ? #0022FC : #FC0400

filter =   ftype=='Volatility' ? volatilityBreak(minatr, maxatr) 
         : ftype=='Volume'     ? volumeBreak(vol) 
         : ftype=='Both'       ? volatilityBreak(minatr, maxatr) and volumeBreak(vol)
         :                       true

signal := color1[1]==#0022FC and color1==#FC0400 and filter ? SELL : color1[1]==#FC0400 and color1==#0022FC and filter ? BUY : nz(signal[1]) 

changed = change(signal)
    
hp_counter := changed ? 0 : hp_counter + 1

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

//-------------------- Rendering

plot(MagicTrend, color=color1, linewidth=3)

plotshape(startLongTrade  ? low  : na, 'Buy',  shape.labelup,   location.belowbar, color.teal,   text='l', textcolor=color.white, size=size.tiny)  
plotshape(startShortTrade ? high : na, 'Sell', shape.labeldown, location.abovebar, color.maroon, text='l', textcolor=color.white, size=size.tiny)
plot(endLongTrade         ? high : na, 'StopBuy',  color.teal,   2, plot.style_cross)
plot(endShortTrade        ? low  : na, 'StopSell', color.maroon, 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!")

//-------------------- Backtesting

show_info = input(true, '===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]) 
useopen   = input(true, 'Use OHL3=false, Open=true in calculation')

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

bidask  = useopen ? open :(open+high+low)/3

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 =  'HPeriod: '    + tostring(holding_p,             '#') 
      + '\nCR='        + 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

The trend direction is established by whether CCI is above or below zero, which controls an ATR-based trailing line. Generates buy and sell signals on trend reversals, with optional filtering via ATR volatility comparisons, volume RSI, or both. Includes trade tracking markers based on a user-defined holding period. The indicator functions as an analysis tool rather than a native TradingView strategy.

Details

Published by

capissimo on GitHub

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

Trend, Volatility & bands

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.

Settings

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

SettingTypeDefaultVariable
DatasetstringCloseptype
CCI periodint20period
ATR Multiplierint1coeff
ATR Periodint5AP
Filter Signals bystringVolatilityftype
Min ATR Lag for the Filter |1..n|int1minatr
Max ATR Lag for the Filter |1..n|int10maxatr
Volume Lag for the Filter |1..n|int55vol
Holding Period |1..n|int1holding_p
===Information===booltrueshow_info
Lot Sizefloat0.01lot_size
Use OHL3=false, Open=true in calculationbooltrueuseopen
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

Chandelier Exit

by everget
948 stars

This indicator plots an ATR-based Chandelier Exit trailing stop on the price chart. It tracks a long stop under recent highs and a short stop above recent lows, then switches direction when price crosses the opposite stop. Buy and sell labels mark those flips.

Indicator v6 Volatility & bandsTrend Repaints
Updated 10 days ago · GPL-3.0 GitHub repository of Chandelier Exit

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
330 stars

Range Filter [Alorse] is a technical indicator overlay for TradingView designed to filter market volatility and identify price trends. It calculates a smoothed range based on historical volatility using a configurable sampling period and multiplier applied to

Indicator v5 TrendVolatility & bands
Updated 2 months ago · None stated GitHub repository of Range Filter [Alorse]
318 stars

This indicator calculates an ATR trailing stop line derived from the highest high minus an average true range multiple over a specified lookback period. It plots the trailing stop line directly on the price chart and colors price bars based on whether the clos

Indicator v5 TrendVolatility & bands
Updated 2 months ago · MIT GitHub repository of ATR Trailing Stoploss

NVDA Trend Ribbon

by longsurf-ai
277 stars

This indicator plots three exponential moving averages and ATR volatility envelopes on the price chart. It compares the fast and slow EMAs to shade a trend ribbon and marks confirmed upward and downward crossovers with triangle labels. Settings change the thre

Indicator v6 TrendMoving averages
Updated yesterday · MIT GitHub repository of NVDA Trend Ribbon

[RS]Donchian Fans

by ricardosantos79
261 stars

This indicator plots Donchian Channel boundary lines along with dynamic fan projections directly on the price chart. It calculates the highest high, lowest low, and median price over a customizable lookback period. Whenever price establishes a new channel high

Indicator v4 Support & resistanceTrend
Updated 4 years ago · None stated GitHub repository of [RS]Donchian Fans

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