0% found this document useful (0 votes)
154 views8 pages

SuperTrend Indicator with Buy/Sell Signals

This document is a Pine Script code for a trading indicator titled 'X4815162342', which includes various calculations for price movements, trend analysis, and buy/sell signals based on multiple technical indicators. It incorporates features like SuperTrend, EMA, and Stochastic RSI to assist traders in making informed decisions. The script also allows for customization of parameters and includes alert conditions for trading signals.

Uploaded by

Son Nguyen
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
154 views8 pages

SuperTrend Indicator with Buy/Sell Signals

This document is a Pine Script code for a trading indicator titled 'X4815162342', which includes various calculations for price movements, trend analysis, and buy/sell signals based on multiple technical indicators. It incorporates features like SuperTrend, EMA, and Stochastic RSI to assist traders in making informed decisions. The script also allows for customization of parameters and includes alert conditions for trading signals.

Uploaded by

Son Nguyen
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

//@version=5

indicator(title='X4815162342', overlay=true)

source = close
hilow = (high - low) * 100
openclose = (close - open) * 100
vol = volume / hilow
spreadvol = openclose * vol
VPT = spreadvol + [Link](spreadvol)
window_len = 28

v_len = 14
price_spread = [Link](high - low, window_len)

v = spreadvol + [Link](spreadvol)
smooth = [Link](v, v_len)
v_spread = [Link](v - smooth, window_len)
shadow = (v - smooth) / v_spread * price_spread

out = shadow > 0 ? high + shadow : low + shadow


//
src = out
src1 = open
src2 = low
src3 = high
tf = input(15)
len = [Link] and [Link] >= 1 ? tf /
[Link] * 7 : [Link] and [Link] < 60 ?
60 / [Link] * 24 * 7 : 7

c = [Link](src, len)
//plot(c, color=[Link]([Link], 0))
o = [Link](src1, len)
//plot(o, color=[Link]([Link], 0))
//h = ema(src3,len)
//l=ema(src2,len)
//
col = c > o ? [Link] : [Link]
vis = true
vl = c
ll = o
//m1 = //plot(vl, color=col, linewidth=1, transp=60)
//m2 = //plot(vis ? ll : na, color=col, linewidth=2, transp=80)

//fill(m1, m2, color=col, transp=70)


//

vpt = [Link](out, len)

// INPUTS //
st_mult = [Link](1.9, title='SuperTrend Multiplier', minval=0, maxval=100,
step=0.01)
st_period = [Link](7, title='SuperTrend Period', minval=1)

// CALCULATIONS //
up_lev = vpt - st_mult * [Link](st_period)
dn_lev = vpt + st_mult * [Link](st_period)

up_trend = 0.0
up_trend := close[1] > up_trend[1] ? [Link](up_lev, up_trend[1]) : up_lev

down_trend = 0.0
down_trend := close[1] < down_trend[1] ? [Link](dn_lev, down_trend[1]) : dn_lev

// Calculate trend var


trend = 0
trend := close > down_trend[1] ? 1 : close < up_trend[1] ? -1 : nz(trend[1], 1)

// Calculate SuperTrend Line


st_line = trend == 1 ? up_trend : down_trend

// Plotting
//plot(st_line[1], color=trend == 1 ? [Link] : [Link],
style=plot.style_cross, linewidth=2, title='SuperTrend')
buy = [Link](close, st_line) and close > o
sell = [Link](close, st_line) and close < o
//plotshape(crossover( close, st_line), location = [Link], color =
[Link],size=[Link])
//plotshape(crossunder(close, st_line), location = [Link], color =
[Link],size=[Link])
plotshape(buy, title='buy', text='Buy', color=[Link]([Link], 0),
style=[Link], location=[Link], size=[Link],
textcolor=[Link]([Link], 0)) //plot for buy icon
plotshape(sell, title='sell', text='Sell', color=[Link]([Link], 0),
style=[Link], location=[Link], size=[Link],
textcolor=[Link]([Link], 0)) //plot for sell icon

//
multiplier = [Link](title='TP', defval=2, minval=1)
src5 = close
len5 = [Link](title='TP length', defval=150, minval=1)
offset = 0

calcSlope(src5, len5) =>


sumX = 0.0
sumY = 0.0
sumXSqr = 0.0
sumXY = 0.0
for i = 1 to len5 by 1
val = src5[len5 - i]
per = i + 1.0
sumX += per
sumY += val
sumXSqr += per * per
sumXY += val * per
sumXY

slope = (len5 * sumXY - sumX * sumY) / (len5 * sumXSqr - sumX * sumX)


average = sumY / len5
intercept = average - slope * sumX / len5 + slope
[slope, average, intercept]

var float tmp = na


[s, a, i] = calcSlope(src5, len5)

vwap1 = i + s * (len5 - offset)


sdev = [Link](close, len5)
dev = multiplier * sdev
top = vwap1 + dev
bott = vwap1 - dev

//
z1 = vwap1 + dev
x1 = vwap1 - dev

low1 = [Link](close, x1)


high1 = [Link](close, z1)

plotshape(low1, title='low', text='TP', color=[Link]([Link], 0),


style=[Link], location=[Link], size=[Link],
textcolor=[Link]([Link], 0)) //plot for buy icon
plotshape(high1, title='high', text='TP', color=[Link]([Link], 0),
style=[Link], location=[Link], size=[Link],
textcolor=[Link]([Link], 0)) //plot for sell icon

/////// Alerts /////


alertcondition(buy, title='buy')
alertcondition(sell, title='sell')
alertcondition(low1, title='sell tp')
alertcondition(high1, title='buy tp')

ATRlength = [Link](200, minval=1)


ATRMult = [Link](2.272, minval=1)

ATR = [Link]([Link](true), ATRlength)

len6 = [Link](175, minval=1, title='EMA Length')


src6 = input(low, title='Source')
out6 = [Link](src6, len6)
plot(out6, title='EMA', color=#FFFFFF)

//emaup = out + ATR * ATRMult


//emadw = out - ATR * ATRMult

//plot(emaup, title='EMAUP')
//plot(emadw, title='EMADW')

conversionPeriods = [Link](200, minval=1)


basePeriods = [Link](26, minval=1)
laggingSpan2Periods = [Link](52, minval=1)
displacement = [Link](26, minval=1)

donchian(len) =>
[Link]([Link](len), [Link](len))

conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = [Link](conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)

//plot(conversionLine, title='Conversion Line')


//plot(baseLine, linewidth=2, title='Base Line', transp=5)
//p3 = plot(leadLine1, offset=displacement, title='Lead 1', transp=85)
//p4 = plot(leadLine2, offset=displacement, title='Lead 2', transp=85)

//*****CDC-Actionzone**************************************************//

//longest = [Link](close, 175)


//plot(longest)

xsrc = [Link](title='Source Data', defval=close)


xprd1 = [Link](title='Fast EMA period', defval=12)
xprd2 = [Link](title='Slow EMA period', defval=26)
xsmooth = [Link](title='Smoothing period (1 = no smoothing)', defval=1)
fillSW = [Link](title='Paint Bar Colors', defval=true)
fastSW = [Link](title='Show fast moving average line', defval=true)
slowSW = [Link](title='Show slow moving average line', defval=true)
labelSwitch = [Link](title='Turn on assistive text', defval=true)
plotSigsw = [Link](title='Plot Buy/Sell Signals? ', defval=true)
plotRibsw = [Link](title='Plot Buy/Sell Ribbon', defval=false)
plotRibbonPos = [Link](title='Ribbon Position', options=['Top', 'Bottom'],
defval='Top')

xfixtf = [Link](title='** Use Fixed time frame Mode (advanced) **',


defval=false)
xtf = [Link](title='** Fix chart to which time frame ? **)', defval='D')

plotSig2sw = [Link](title='Plot momentum based Buy/Sell Signals? ',


defval=false)
plotSig2lv = [Link](title='Set signal threshold (higher = stricter)', defval=1,
minval=0, maxval=1)

//****************************************************************************//
//Calculate Indicators

f_secureSecurity(_symbol, _res, _src) => [Link](_symbol, _res, _src[1],


lookahead = barmerge.lookahead_on) // Using f_secureSecurity to avoid repainting

xPrice = [Link](xsrc, xsmooth)

FastMA = xfixtf ?
[Link](f_secureSecurity([Link], xtf, [Link](xsrc, xprd1)), xsmooth)
:
[Link](xPrice, xprd1)

SlowMA = xfixtf ?
[Link](f_secureSecurity([Link], xtf, [Link](xsrc, xprd2)), xsmooth)
:
[Link](xPrice, xprd2)

Bull = FastMA > SlowMA


Bear = FastMA < SlowMA

//****************************************************************************//
// Define Color Zones

Green = Bull and xPrice > FastMA // Buy


Blue = Bear and xPrice > FastMA and xPrice > SlowMA //Pre Buy 2
LBlue = Bear and xPrice > FastMA and xPrice < SlowMA //Pre Buy 1
Red = Bear and xPrice < FastMA // Sell
Orange = Bull and xPrice < FastMA and xPrice < SlowMA // Pre Sell 2
Yellow = Bull and xPrice < FastMA and xPrice > SlowMA // Pre Sell 1

//****************************************************************************//
// Display color on chart

bColor = Green ? [Link] :


Blue ? [Link] :
LBlue ? [Link] :
Red ? [Link] :
Orange ? [Link] :
Yellow ? [Link] :
[Link]
barcolor(color=fillSW ? bColor : na)

//****************************************************************************//
// Display MA lines

FastL = plot(fastSW ? FastMA : na, 'Fast EMA', color=[Link]([Link], 0), style


= xfixtf ? plot.style_stepline : plot.style_line)
SlowL = plot(slowSW ? SlowMA : na, 'Slow EMA', color=[Link]([Link], 0),
style = xfixtf ? plot.style_stepline : plot.style_line)
fillcolor = Bull ? [Link]([Link],90) : Bear ? [Link]([Link],90) :
[Link]([Link],90) // fillcolor = Bull ? [Link] : Bear ? [Link] :
[Link]
fill(FastL, SlowL, fillcolor) // fill(FastL, SlowL, fillcolor, transp=90)

//****************************************************************************//
// Define Buy and Sell condition
// This is only for thebasic usage of CDC Actionzone (EMA Crossover)
// ie. Buy on first green bar and sell on first red bar

buycond = Green and Green[1] == 0


sellcond = Red and Red[1] == 0

bullish = [Link](buycond) < [Link](sellcond)


bearish = [Link](sellcond) < [Link](buycond)

buy1 = bearish[1] and buycond


sell1 = bullish[1] and sellcond

bColor_BullBear = bullish ? [Link] : bearish ? [Link] : [Link]

//****************************************************************************//
// Plot Buy and Sell point on chart

plotshape(plotSigsw ? buy : na,


style=[Link],
title='Buy Signal',
location=[Link],
color=[Link]([Link], 0))
plotshape(plotSigsw ? sell : na,
style=[Link],
title='Sell Signal',
location=[Link],
color=[Link]([Link], 0))
// Display Buy/Sell Ribbon

plotshape(plotRibsw ? plotRibbonPos == 'Top' ? close : na : na,


style=[Link],
title='Buy/Sell Ribbon',
location=[Link],
color=bColor_BullBear)

plotshape(plotRibsw ? plotRibbonPos == 'Bottom' ? close : na : na,


style=[Link],
title='Buy/Sell Ribbon',
location=[Link],
color=bColor_BullBear)

//****************************************************************************//
// Label

labelstyle = close > SlowMA ? label.style_label_down : label.style_label_up


labelyloc = close > SlowMA ? [Link] : [Link]
labeltcolor = buy1 ? [Link] :
sell1 ? [Link] :
close > close[1] ? [Link] :
[Link]
labelbgcolor = buy1 ? [Link] : sell ? [Link] : [Link]
labeltext = buy1 ? 'BUY next bar\n' : sell ? 'SELL next bar\n' : ' '
trendText = bullish ? 'bullish' : bearish ? 'bearish' : 'sideways'

//l1 = [Link](bar_index, na, //ชุดคำสั่งนี้ คือ ป้ายแจ้งเตือน Bull or Bear และ


ราคา
// text=labeltext + [Link] + ' ' + [Link](close) + ' ' +
[Link] + '\n currently in a ' + trendText + ' trend \n',
// color=labelbgcolor,
// textcolor=labeltcolor,
// yloc=labelyloc,
// style=labelstyle)
// [Link](labelSwitch ? l1[1] : l1)

// Momentum Signal using StochRSI

// Adds a momentum based signal following trends to the script


// Default is hidden, only use with caution
// Parameters for STOCH RSI is hard-coded to avoid cluttering the input screen
further
// If you need to change anything, make a copy of the code and change it.
// Inputs are commented out, to enable them comment out the hard coded variables
first!

// fixed inputs //

smoothK = 3
smoothD = 3
RSIlen = 14
STOlen = 14
SRsrc = close
OSlevel = 30
OBlevel = 70

// User inputs // // COMMENT ABOVE VARIABLES FIRST!!

// smoothK = input(3,"StochRSI smooth K",type=[Link],minval=1)


// smoothD = input(3,"StochRSI smooth D",type=[Link],minval=1)
// RSIlen = input(14,"RSI length",type=[Link],minval=1)
// STOlen = input(14,"Stochastic length",type=[Link],minval=1)
// SRsrc = input(close,"Source for StochasticRSI",type=[Link])
// OSlevel = input(30,"Oversold Threshold",type=[Link],minval=0.00)
// OBlevel = input(70,"Oversold Threshold",type=[Link],minval=0.00)

// calculations //
rsi1 = [Link](SRsrc, RSIlen)
k = [Link]([Link](rsi1, rsi1, rsi1, STOlen), smoothK)
d = [Link](k, smoothD)

// storsiBuySig = if bullish
// if (d < OSlevel and crossover(k,d))
// 3
// else if crossover(k,OSlevel)
// 2
// else if d > OSlevel and crossover(k,d)
// 1
// else
// 0
// else
// 0

crossover_1 = [Link](k, d)
crossover_2 = [Link](k, d)
iff_1 = d > OSlevel and crossover_2 ?
1 : 0
iff_2 = d < OSlevel and crossover_1 ?
2 : iff_1
storsiBuySig = bullish ? iff_2 : 0

crossunder_1 = [Link](k, d)
crossunder_2 = [Link](k, d)
iff_3 = d < OBlevel and crossunder_2 ?
1 : 0
iff_4 = d > OBlevel and crossunder_1 ?
2 : iff_3
storsiSellSig = bearish ? iff_4 : 0

plotshape(plotSig2sw ? storsiBuySig > plotSig2lv ? storsiBuySig : na : na,


'Buy more signals', style=[Link],
location=[Link], color=[Link]([Link], 0))
plotshape(plotSig2sw ? storsiSellSig > plotSig2lv ? storsiSellSig : na : na,
'Sell more signals', style=[Link],
location=[Link], color=[Link]([Link], 0))

//****************************************************************************//
// Alert conditions

alertcondition(buy,
title='*Buy Alert',
message='Buy {{exchange}}:{{ticker}}')
alertcondition(sell,
title='*Sell Alert',
message='Sell {{exchange}}:{{ticker}}')

alertcondition(bullish,
title='is Bullish')

alertcondition(bearish,
title='is Bearish')

alertcondition(Green,
title='is Green')

alertcondition(Blue,
title='is Blue (Strong Rally)')

alertcondition(LBlue,
title='is Light Blue (Rally)')

alertcondition(Red,
title='is Red')

alertcondition(Orange,
title='is Orange (Strong Dip)')

alertcondition(Yellow,
title='is Yellow (Dip)')

//****************************************************************************//

Common questions

Powered by AI

Colors in the document represent discrete market conditions, essential for quick visual analysis. Green indicates buying potential when the Bull condition and xPrice cross above FastMA. Red, conversely, signals selling when Bear conditions and xPrice cross below FastMA. Other transitional colors (Blue, LBlue, Orange, Yellow) mark 'pre' periods suggesting potential shifts but lacking confirmation. These thoughtfully arranged colors visually encode the results of EMA crossing strategies, simplifying market condition recognition for traders .

The document determines the trend by calculating SuperTrend lines using the formula: st_line = trend == 1 ? up_trend : down_trend. This is based on an uptrend being defined by the condition that the close is greater than the down_trend[1], and a downtrend is defined by the close being less than the up_trend[1]. The up and down trend levels are calculated through: up_lev = vpt - st_mult * ta.atr(st_period) and dn_lev = vpt + st_mult * ta.atr(st_period). Up_trend is updated only if the close[1] is greater than the previous up_trend, using math.max. Similarly, down_trend is updated using math.min if close[1] is less than the previous down_trend .

The document utilizes the function f_secureSecurity to handle repainting issues, which ensures values are secured and accurate by not using lookahead. It reinforces this approach by associating calculations with the security syminfo.tickerid parameter and fixing them to a certain timeframe through the xtf parameter. This technique avoids the usage of future data points in the current bar, preventing retrospective corrections that could alter past outputs .

VWAP (Volume Weighted Average Price) is calculated in the document as vwap1 = i + s * (len5 - offset), where 'i' represents the intercept from the calcSlope function and 's' is the slope. This calculation aims to provide a more robust and averaged price level considering volume, thereby informing traders about the average price a security has traded at, over the given time. It is enhanced by deviations (dev) which are dynamically adjusted using multiplier * sdev, reflecting volatility adjustments to VWAP boundaries determining potential buy or sell zones .

Buy and Sell signals are extracted from crossing conditions with zones marked by FastMA and SlowMA, and corresponding trend colors like Green, Blue, LBlue, Red, Orange, and Yellow. Buy conditions occur when Green appears the first time, indicating xPrice greater than FastMA and aligning Bull conditions, while the first Red indicates Sell, marking a crossover of xPrice lower than SlowMA. Additionally, conditions evaluate Bullish or Bearish scenarios through ta.barssince function comparisons to reinforce signal accuracy .

The spreadvol variable represents the product of price change and volume, providing a weighted measure of how much volume corresponds to a certain price movement. It is calculated as openclose * vol, where openclose is the price change expressed as (close - open) * 100, and vol is volume normalized by price range (volume / hilow). This metric helps in evaluating the overall strength of price movements by incorporating volume as an integral factor, thereby giving more contextual information about the price changes .

The document differentiates moving averages' periods by assigning distinct lengths for trend detection via parameters like xprd1 for the Fast EMA and xprd2 for the Slow EMA. Using different periods allows the detection of short-term vs. long-term trends. Fast EMA reacts sooner to price changes than Slow EMA, capturing short bursts in price, while Slow EMA confirms sustained trend directions. This separation into multiple periods aids in distinguishing genuine momentum shifts from temporary fluctuations, enhancing reliable trend detection through compounded signal weighting .

Stochastic RSI values help in refining buy and sell signals by indicating overbought (OB) and oversold (OS) conditions. Calculated by taking the RSI of a close and smoothing these with k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, STOlen), smoothK) and d = ta.sma(k, smoothD), they further identify transition points where k crosses d in the context of OS and OB thresholds (e.g., crossover with OSlevel signals a buy; crossover with OBlevel signals a sell). This dynamic assists in verifying momentum-based decisions alongside primary trend signals .

ATR (Average True Range) provides a measure of the market's current volatility, impacting EMA readings by adjusting them for significant price changes. Within the document, the ATR variable is calculated via ta.rma(ta.tr(true), ATRlength), where true range accounts for adding the current high minus the current low. This ATR adjustment is used to determine upper or lower volatility thresholds around the EMA using multiples like ATRMult, thus delineating probable continuation levels or breaks in trends, assisting in robust trend interpretation .

Alerts are structured to map directly onto key market conditions using descriptive signals such as '*Buy Alert' and '*Sell Alert', oriented around dynamic transitions like crossover/crossunder of price against calculated trend lines. Conditions like 'is Bullish' and 'is Bearish' inform users of broader market orientations. Historically verified conditions result in prompt alerts, leveraging current trend data to ensure timely responses. By embedding conditions within both visual plots and alert mechanisms, traders gain insights grounded in real-time fluctuations, promoting decisive and timely actions .

You might also like