name
stringlengths 1
64
| url
stringlengths 44
135
| author
stringlengths 3
30
| author_url
stringlengths 34
61
| likes_count
int64 0
33.2k
| kind
stringclasses 3
values | pine_version
int64 1
5
| license
stringclasses 3
values | source
stringlengths 177
279k
|
---|---|---|---|---|---|---|---|---|
BB Order Blocks | https://www.tradingview.com/script/387pRGG2-BB-Order-Blocks/ | TradingWolf | https://www.tradingview.com/u/TradingWolf/ | 797 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MensaTrader
//@version=5
indicator(shorttitle="OB", title="BB Order Blocks", overlay=true, timeframe="", timeframe_gaps=true)
//Inputs
length = input.int(20, minval=1, title="Bollinger Band Length", group="=== Bollinger Bands ===", step=5, tooltip="Lengths 20,50,100 & 200 Give interesting levels of confluence")
src = input(close, title="Band Source", group="=== Bollinger Bands ===")
mult = input.float(2.0, minval=0.001, maxval=50, title="Band StdDev", group="=== Bollinger Bands ===")
//OB In
lookback = input.int(100, title="Lookback Length", step=10, group="=== Order Block ===", tooltip="Range from 20-200")
plotBands = input.bool(false, title="Plot Bollinger Bands", group="=== Plots ===")
plotOb = input.bool(true, title="Plot OB Levels", group="=== Plots ===")
plotCon = input.bool(true, title="Plot Solid OB only", group="=== Plots ===")
//Calc Bands
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
offset = 0
reachDev = (mult + 0.1) * ta.stdev(src, length)
upper2 = basis + reachDev
lower2 = basis - reachDev
//Order Blocks
obHigh = ta.highest(upper, lookback)
obLow = ta.lowest(lower, lookback)
obHigh2 = ta.highest(upper2, lookback)
obLow2 = ta.lowest(lower2, lookback)
//Plots
//Upper Order Block
o1 = plot(plotOb ? plotCon ? obHigh==obHigh[1] ? obHigh : na : obHigh :na, title="Order Block High", color=#FF0000, style=plot.style_linebr)
o2 = plot(plotOb ? plotCon ? obHigh==obHigh[1] ? obHigh2 : na : obHigh2 :na, title="Order Block High 2", color=#FF0000, style=plot.style_linebr)
fill(o1,o2, color=color.new(#FF0000,80), title="Sell Fill")
//Lower Order Block
o3 = plot(plotOb ? plotCon ? obLow==obLow[1] ? obLow : na : obLow :na, title="Order Block Low", color=#00E600, style=plot.style_linebr)
o4 = plot(plotOb ? plotCon ? obLow==obLow[1] ? obLow2 : na : obLow2 :na, title="Order Block Low 2", color=#00E600, style=plot.style_linebr)
fill(o3,o4, color=color.new(#00E600,80), title="Buy Fill")
//Plot bands
plot(plotBands ? basis : na, "Basis", color=#FF6D00, offset = offset)
p1 = plot(plotBands ? upper : na, "Upper", color=#2962FF, offset = offset)
p2 = plot(plotBands ? lower : na, "Lower", color=#2962FF, offset = offset)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95)) |
4C ATR w/ Reference Line | https://www.tradingview.com/script/PsGvv0Cr-4C-ATR-w-Reference-Line/ | FourC | https://www.tradingview.com/u/FourC/ | 38 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © FourC
//Simple script that adds a horizontal renference line for minimum ATR criteria.
//Updated version of 4C ATR that includes decimal increments in the ATR Reference Line input, and ATR slope color change.
//Apadted from original Tradingview ATR indicator by 4C.
//@version=5
indicator(title="4C ATR w/ Reference Line", shorttitle="4C ATR", overlay=false, timeframe="", timeframe_gaps=true)
source = input.source(title="Source", defval=close)
length = input.int(title="Length", defval=14, minval=1)
showrefline = input.bool(true, title = "Show Reference Line")
atrline = input.float(title="ATR Reference Line", defval=2, step=0.1)
atrslopesmoothing = input.int(title="ATR Slope Smoothing", defval=8, minval=1)
smoothing = input.string(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"])
ma_function(source, length) =>
switch smoothing
"RMA" => ta.rma(source, length)
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"WMA" => ta.wma(source, length)
atravg = ta.sma(ma_function(ta.tr(true), length), atrslopesmoothing)
x = if atravg[0] > atravg[1]
color.rgb(0, 255, 255)
else
color.rgb(255, 0, 0)
plot(ma_function(ta.tr(true), length), title = "ATR", color=x, linewidth=2)
hline(showrefline ? atrline : na, 'ATR Ref', color.white, linestyle=hline.style_solid, linewidth=1)
|
Koalafied RVWAP | https://www.tradingview.com/script/xND0YDF3-Koalafied-RVWAP/ | Koalafied_3 | https://www.tradingview.com/u/Koalafied_3/ | 369 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TJ_667
//VWAP is the abbreviation for volume-weighted average price, which is a technical analysis tool that shows the ratio of an asset's price to its total trade volume. It provides traders
//and investors with a measure of the average price at which a stock is traded over a given period of time. This indicator shows both the Rolling VWAP and Standard Deviations as set by the user.
//The Rolling VWAP calculation is similar to the stardard VWAP although it caclulates the volume weighted average price over the specified period of time (lookback) resetting for each subsequent bar.
//The unique aspect of this indicator is that instead of calculating the RVWAP over the current timeframes lookback period the option is available to select a High-Time-Frame setting instead.
//This has two different methods of calculation
//1 - Based on HTF security requests (both repainting and non-repainting)
//2 - Automatic calculation of number of current timeframe bars that make up the HTF lookback period (smoother and non-repainting plot)
//Addionally a smooth function is included for the HTF input setting.
//@version=5
indicator('Koalafied RVWAP', overlay=true)
// ---------- FUNCTIONS ---------- //
computeVWAP(src, vol, len, stDevMultiplier1, stDevMultiplier2, stDevMultiplier3) =>
sumSrcVol = 0.0
sumVol = 0.0
sumSrcSrcVol = 0.0
for i = 1 to len - 1 by 1
sumSrcVol := vol[i] + sumSrcVol
sumVol := vol[i] * src[i] + sumVol
sumSrcSrcVol := vol[i] * math.pow(src[i], 2) + sumSrcSrcVol
sumSrcSrcVol
_vwap = sumVol / sumSrcVol
variance = sumSrcSrcVol / sumSrcVol - math.pow(_vwap, 2)
variance := variance < 0 ? 0 : variance
stDev = math.sqrt(variance)
upperBand3 = _vwap + stDev * stDevMultiplier3
upperBand2 = _vwap + stDev * stDevMultiplier2
upperBand1 = _vwap + stDev * stDevMultiplier1
lowerBand1 = _vwap - stDev * stDevMultiplier1
lowerBand2 = _vwap - stDev * stDevMultiplier2
lowerBand3 = _vwap - stDev * stDevMultiplier3
[_vwap, upperBand3, upperBand2, upperBand1, lowerBand1, lowerBand2, lowerBand3 ]
// ————— Converts current "timeframe.multiplier" plus the TF into minutes of type float.
f_resInMinutes() =>
_resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1. / 60. :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 1440. :
timeframe.isweekly ? 10080. :
timeframe.ismonthly ? 43800. : na)
// ————— Returns resolution of _resolution period in minutes.
f_tfResInMinutes(_res) =>
// _res: resolution of any TF (in "timeframe.period" string format).
request.security(syminfo.tickerid, _res, f_resInMinutes())
// Returns the theoretical numbers of current chart bars in the given target HTF resolution (note that this number maybe very different from actual number on certain symbols).
f_theoreticalDilationOf(_res) =>
// _res: resolution of any TF (in "timeframe.period" string format).
f_tfResInMinutes(_res) / f_resInMinutes()
// ---------- INPUTS ---------- //
var GRP1 = "INPUTS"
_len = input(30, 'rVWAP Length', group = GRP1)
HTF = input.timeframe("D", "Resolution", group = GRP1)
showStd = input(false, 'Show Deviations', group = GRP1)
fill_bands = input(true, 'Fill Std Dev bands')
stDevMultiplier_1 = input(1.0, "StDev mult 1", group = GRP1)
stDevMultiplier_2 = input(2.0, "StDev mult 2", group = GRP1)
stDevMultiplier_3 = input(3.0, "StDev mult 2", group = GRP1)
var GRP2 = "HTF PARAMETERS"
HTF_switch = input(false, "Use HTF input", group = GRP2)
HTFRepaints = input(false, "Allow HTF Repainting", group = GRP2)
HTF_Smooth = input(false, "Smooth Higher Timeframes", group = GRP2)
HTF_Smooth_len = input.int(1, "Smoothing Factor", minval = 1, group = GRP2)
src = hlc3
vol = volume
_mult = f_theoreticalDilationOf(HTF)
// ---------- RVWAP ---------- //
[rVWAP, stup3, stup2, stup1, stdn1, stdn2, stdn3] = computeVWAP(src, vol, HTF_switch ? _len : _len * _mult, stDevMultiplier_1, stDevMultiplier_2, stDevMultiplier_3)
vHtfSmoothLen = math.max(2, _len / HTF_Smooth_len)
rVWAP_out = not HTF_switch ? rVWAP : HTFRepaints ? request.security(syminfo.tickerid, HTF, rVWAP) : request.security(syminfo.tickerid, HTF, rVWAP[1], lookahead = barmerge.lookahead_on)
rVWAP_out := HTF_switch and HTF_Smooth ? ta.ema(ta.ema(ta.ema(rVWAP_out, vHtfSmoothLen), vHtfSmoothLen), vHtfSmoothLen) : rVWAP_out
stup3_out = not HTF_switch ? stup3 : HTFRepaints ? request.security(syminfo.tickerid, HTF, stup3) : request.security(syminfo.tickerid, HTF, stup3[1], lookahead = barmerge.lookahead_on)
stup3_out := HTF_switch and HTF_Smooth ? ta.ema(ta.ema(ta.ema(stup3_out, vHtfSmoothLen), vHtfSmoothLen), vHtfSmoothLen) : stup3_out
stup2_out = not HTF_switch ? stup2 : HTFRepaints ? request.security(syminfo.tickerid, HTF, stup2) : request.security(syminfo.tickerid, HTF, stup2[1], lookahead = barmerge.lookahead_on)
stup2_out := HTF_switch and HTF_Smooth ? ta.ema(ta.ema(ta.ema(stup2_out, vHtfSmoothLen), vHtfSmoothLen), vHtfSmoothLen) : stup2_out
stup1_out = not HTF_switch ? stup1 : HTFRepaints ? request.security(syminfo.tickerid, HTF, stup1) : request.security(syminfo.tickerid, HTF, stup1[1], lookahead = barmerge.lookahead_on)
stup1_out := HTF_switch and HTF_Smooth ? ta.ema(ta.ema(ta.ema(stup1_out, vHtfSmoothLen), vHtfSmoothLen), vHtfSmoothLen) : stup1_out
stdn1_out = not HTF_switch ? stdn1 : HTFRepaints ? request.security(syminfo.tickerid, HTF, stdn1) : request.security(syminfo.tickerid, HTF, stdn1[1], lookahead = barmerge.lookahead_on)
stdn1_out := HTF_switch and HTF_Smooth ? ta.ema(ta.ema(ta.ema(stdn1_out, vHtfSmoothLen), vHtfSmoothLen), vHtfSmoothLen) : stdn1_out
stdn2_out = not HTF_switch ? stdn2 : HTFRepaints ? request.security(syminfo.tickerid, HTF, stdn2) : request.security(syminfo.tickerid, HTF, stdn2[1], lookahead = barmerge.lookahead_on)
stdn2_out := HTF_switch and HTF_Smooth ? ta.ema(ta.ema(ta.ema(stdn2_out, vHtfSmoothLen), vHtfSmoothLen), vHtfSmoothLen) : stdn2_out
stdn3_out = not HTF_switch ? stdn3 : HTFRepaints ? request.security(syminfo.tickerid, HTF, stdn3) : request.security(syminfo.tickerid, HTF, stdn3[1], lookahead = barmerge.lookahead_on)
stdn3_out := HTF_switch and HTF_Smooth ? ta.ema(ta.ema(ta.ema(stdn3_out, vHtfSmoothLen), vHtfSmoothLen), vHtfSmoothLen) : stdn3_out
// ---------- Plots ---------- //
fill_colup = color.new(color.red, 95)
fill_colmid = color.new(color.gray, 95)
fill_coldown = color.new(color.blue, 95)
rVWAP_col = not HTF_switch ? close > rVWAP ? color.blue : color.red : close > rVWAP_out ? color.blue : color.red
Mid = plot(rVWAP_out, color = rVWAP_col, style=plot.style_stepline, linewidth=1)
s3up_A = plot(showStd ? stup3_out : na, title='VWAP - STDEV 3U', color=color.new(color.red, 90), style=plot.style_stepline, linewidth=2)
s2up_A = plot(showStd ? stup2_out : na, title='VWAP - STDEV 2U', color=color.new(color.red, 80), style=plot.style_stepline, linewidth=2)
s1up_A = plot(showStd ? stup1_out : na, title='VWAP - STDEV 1U', color=color.new(color.gray, 70), style=plot.style_stepline, linewidth=2)
s1dn_A = plot(showStd ? stdn1_out : na, title='VWAP - STDEV 1D', color=color.new(color.gray, 70), style=plot.style_stepline, linewidth=2)
s2dn_A = plot(showStd ? stdn2_out : na, title='VWAP - STDEV 2D', color=color.new(color.blue, 80), style=plot.style_stepline, linewidth=2)
s3dn_A = plot(showStd ? stdn3_out : na, title='VWAP - STDEV 3D', color=color.new(color.blue, 90), style=plot.style_stepline, linewidth=2)
fill(s3up_A, s1up_A, color = fill_bands ? fill_colup : na)
fill(s2up_A, s1up_A, color = fill_bands ? fill_colup : na)
fill(s1up_A, Mid, color = fill_bands ? fill_colmid : na)
fill(s1dn_A, Mid, color = fill_bands ? fill_colmid : na)
fill(s2dn_A, s1dn_A, color = fill_bands ? fill_coldown : na)
fill(s3dn_A, s1dn_A, color = fill_bands ? fill_coldown : na)
|
Up Volume vs Down Volume | https://www.tradingview.com/script/60ol3tQx-Up-Volume-vs-Down-Volume/ | ChartingCycles | https://www.tradingview.com/u/ChartingCycles/ | 402 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartingCycles
// Credit to @MagicEins for the original script
// @version=5
indicator(title = "Up Volume vs Down Volume", shorttitle="UVol vs DVol", precision=0)
ticker = input.string("NY","Choose Market:",options=["NY","NQ","US","DJ","AM","AX"])
string cumrel = input.string("Cumulative","Cumulative or Relative",options=["Cumulative","Relative"])
string spl = input.string("Split","Split or Stacked (only use with Cumulative)",options=["Split","Stacked"])
ninety = input(false,"90% Underlay (only use with Split)")
//Calcs
upvol = request.security("UPVOL."+ticker, "", close)
downvol = request.security("DNVOL."+ticker, "", close)
uratio = upvol/(upvol+downvol)
dratio = downvol/(upvol+downvol)
p80 = 0.8 * (upvol+downvol)
p90 = 0.9 * (upvol+downvol)
is_u80 = upvol>p80 and upvol<p90 ? true : false
is_d80 = downvol>p80 and downvol<p90 ? true : false
is_u90 = upvol>p90 ? true : false
is_d90 = downvol>p90 ? true : false
float cru = switch cumrel
"Cumulative" => upvol
"Relative" => uratio
float crd = switch cumrel
"Cumulative" => downvol
"Relative" => dratio
float u90 = switch cumrel
"Cumulative" => p90
"Relative" => .9
float d90 = switch cumrel
"Cumulative" => p90*-1
"Relative" => -.9
float ss = switch spl
"Split" => -1
"Stacked" => 1
float sa = switch spl
"Split" => 0
"Stacked" => upvol
//Plot
plot(ninety ? u90 : na, title="90% Up",style=plot.style_columns,color=color.white, transp=90)
plot(ninety ? d90 : na, title="90% Down",style=plot.style_columns,color=color.white,transp=90)
plot(crd*ss+sa, title="Down Volume",style=plot.style_columns,color= is_d90 ? color.new(#ff1200,transp=25) : color.new(color.red,transp=25))
plot(cru, title="Up Volume",style=plot.style_columns,color= is_u90 ? color.new(#00ffd5,transp=25) : color.new(color.teal,transp=25))
plotshape((is_u80), title="is 80 Up-day?", style=shape.triangleup, size=size.tiny,text="8",textcolor=color.teal,color=color.teal, location=location.bottom)
plotshape((is_d80), title="is 80 Down-day?", style=shape.triangledown, size=size.tiny,text="8",textcolor=color.red,color=color.red, location=location.top)
plotshape((is_u90), title="is 90 Up-day?", style=shape.triangleup, size=size.tiny,text="9",textcolor=#00ffd5,color=#00ffd5, location=location.bottom)
plotshape((is_d90), title="is 90 Down-day?", style=shape.triangledown, size=size.tiny,text="9",textcolor=#ff1200,color=#ff1200, location=location.top)
//Panel
var string GP2 = 'Display'
show_header = input.bool(true, title='Show Table', inline='10', group=GP2)
string i_tableYpos = input.string('bottom', 'Panel Position', inline='11', options=['top', 'middle', 'bottom'], group=GP2)
string i_tableXpos = input.string('right', '', inline='11', options=['left', 'center', 'right'], group=GP2)
string textsize = input.string('normal', 'Text Size', inline='12', options=['small', 'normal', 'large'], group=GP2)
var table dtrDisplay = table.new(i_tableYpos + '_' + i_tableXpos, 3, 2, frame_width=1, frame_color=color.black, border_width=1, border_color=color.black)
first_time = 0
first_time := bar_index == 0 ? time : first_time[1]
if barstate.islast
// We only populate the table on the last bar.
if show_header == true
table.cell(dtrDisplay, 1, 0, 'Up Volume', bgcolor=color.black, text_size=textsize, text_color=color.white)
table.cell(dtrDisplay, 1, 1, str.tostring(math.round(uratio,3)*100) + '%', bgcolor=color.black, text_size=textsize, text_color=color.white)
table.cell(dtrDisplay, 2, 0, 'Down Volume', bgcolor=color.black, text_size=textsize, text_color=color.white)
table.cell(dtrDisplay, 2, 1, str.tostring(math.round(dratio,3)*100) + '%', bgcolor=color.black, text_size=textsize, text_color=color.white)
|
Rupesh Govardhane Support Resistance | https://www.tradingview.com/script/7vk7Y2Yr-Rupesh-Govardhane-Support-Resistance/ | rgovardhane001 | https://www.tradingview.com/u/rgovardhane001/ | 18 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LonesomeTheBlue
//@version=4
study("Rupesh Govardhane Support Resistance", overlay = true, max_bars_back = 600)
rb = input(10, title = "Period", minval = 10)
prd = input(284, title = "Loopback Period", minval = 100, maxval = 500)
nump = input(2, title ="S/R strength", minval = 1)
ChannelW = input(10, title = "Channel Width %", minval = 5)
label_location = input(10, title = "Label Location +-", tooltip = "0 means last bar. for example if you set it -5 then label is shown on last 5. bar. + means future bars")
linestyle = input('Dashed', title = "Line Style", options = ['Solid', 'Dotted', 'Dashed'])
LineColor = input(color.blue, title = "Line Color", type = input.color)
drawhl = input(true, title = "Draw Highest/Lowest Pivots in Period")
showpp = input(false, title = "Show Point Points")
ph = pivothigh(rb, rb)
pl = pivotlow(rb, rb)
plotshape(ph and showpp, text="PH", style=shape.labeldown, color=color.new(color.white, 100), textcolor = color.red, location=location.abovebar, offset = -rb)
plotshape(pl and showpp, text="PL", style=shape.labelup, color=color.new(color.white, 100), textcolor = color.lime, location=location.belowbar, offset = -rb)
// S/R levels
sr_levels = array.new_float(21, na)
// if number of bars is less then the loop then pine highest() fundtion brings 'na'. we need highest/lowest to claculate channel size
// so you cannot see S/R until the number of bars is equal/greater then the "Loopback Period"
prdhighest = highest(prd)
prdlowest = lowest(prd)
cwidth = (prdhighest - prdlowest) * ChannelW / 100
//availability of the PPs
aas = array.new_bool(41, true)
// last privot points have more priority to be support/resistance, so we start from them
// if we met new Pivot Point then we calculate all supports/resistances again
u1 = 0.0, u1 := nz(u1[1])
d1 = 0.0, d1 := nz(d1[1])
highestph = 0.0
lowestpl = 0.0
highestph := highestph[1]
lowestpl := lowestpl[1]
if ph or pl
//old S/Rs not valid anymore
for x = 0 to array.size(sr_levels) - 1
array.set(sr_levels, x, na)
highestph := prdlowest
lowestpl := prdhighest
countpp = 0 // keep position of the PP
for x = 0 to prd
if na(close[x])
break
if not na(ph[x]) or not na(pl[x]) // is it PP?
highestph := max(highestph, nz(ph[x], prdlowest), nz(pl[x], prdlowest))
lowestpl := min(lowestpl, nz(ph[x], prdhighest), nz(pl[x], prdhighest))
countpp := countpp + 1
if countpp > 40
break
if array.get(aas, countpp) // if PP is not used in a channel
upl = (ph[x] ? high[x+rb] : low[x+rb]) + cwidth
dnl = (ph[x] ? high[x+rb] : low[x+rb]) - cwidth
u1 := countpp == 1 ? upl : u1
d1 := countpp == 1 ? dnl : d1
// to keep the PPs which will be in current channel
tmp = array.new_bool(41, true)
cnt = 0 // keep which pivot point we are on
tpoint = 0 // number of PPs in the channel
for xx = 0 to prd
if na(close[xx])
break
if not na(ph[xx]) or not na(pl[xx])
chg = false
cnt := cnt + 1
if cnt > 40
break
if array.get(aas, cnt) // if PP not used in other channels
if not na(ph[xx])
if high[xx+rb] <= upl and high[xx+rb] >= dnl // PP is in the channel?
tpoint := tpoint + 1
chg := true
if not na(pl[xx])
if low[xx+rb] <= upl and low[xx+rb] >= dnl // PP is in the channel?
tpoint := tpoint + 1
chg := true
// set if PP is used in the channel
if chg and cnt < 41
array.set(tmp, cnt, false)
if tpoint >= nump // met enough PP in the channel? mark the PP as used for a channel and set the SR level
for g = 0 to 40
if not array.get(tmp, g)
array.set(aas, g, false)
if ph[x] and countpp < 21
array.set(sr_levels, countpp, high[x+rb])
if pl[x] and countpp < 21
array.set(sr_levels, countpp, low[x+rb])
setline( level) =>
LineStyle = linestyle == 'Solid' ? line.style_solid :
linestyle == 'Dotted' ? line.style_dotted :
line.style_dashed
_ret = line.new(bar_index - 1 , level, bar_index , level, color = LineColor, width = 2, style = LineStyle, extend = extend.both)
if ph or pl
var line highest_ = na
var line lowest_ = na
line.delete(highest_)
line.delete(lowest_)
if drawhl
highest_ := line.new(bar_index - 1 , highestph, bar_index , highestph, color = color.blue, style = line.style_dashed, width = 1, extend = extend.both)
lowest_ := line.new(bar_index - 1 , lowestpl, bar_index , lowestpl, color = color.blue, style = line.style_dashed, width = 1, extend = extend.both)
var sr_lines = array.new_line(21, na)
for x = 0 to array.size(sr_lines) - 1
line.delete(array.get(sr_lines, x))
if array.get(sr_levels, x)
array.set(sr_lines, x, setline(array.get(sr_levels, x)))
// set new labels if changed
var sr_levs = array.new_float(21, na)
if ph or pl
for x = 0 to array.size(sr_levs) - 1
array.set(sr_levs, x, array.get(sr_levels, x))
// define and delete old labels
label hlabel = na
label llabel = na
label.delete(hlabel[1])
label.delete(llabel[1])
var sr_labels = array.new_label(21, na)
bool resistance_broken = false
bool support_broken = false
float r_s_level = na
// set labels
for x = 0 to array.size(sr_labels) - 1
label.delete(array.get(sr_labels, x))
if array.get(sr_levs, x)
if close[1] <= array.get(sr_levs, x) and close > array.get(sr_levs, x)
resistance_broken := true
r_s_level := array.get(sr_levs, x)
if close[1] >= array.get(sr_levs, x) and close < array.get(sr_levs, x)
support_broken := true
r_s_level := array.get(sr_levs, x)
lab_loc = (close >= array.get(sr_levs, x) ? label.style_labelup : label.style_labeldown)
array.set(sr_labels, x,
label.new(x = bar_index + label_location, y = array.get(sr_levs, x), text = tostring(round_to_mintick(array.get(sr_levs, x))), color = color.lime, textcolor = color.black, style = lab_loc))
hlabel := drawhl ? label.new(x = bar_index + label_location + round(sign(label_location)) * 20, y = highestph, text = "Highest PH " + tostring(highestph), color = color.silver, textcolor=color.black, style=label.style_labeldown) : na
llabel := drawhl ? label.new(x = bar_index + label_location + round(sign(label_location)) * 20, y = lowestpl, text = "Lowest PL " + tostring(lowestpl), color = color.silver, textcolor=color.black, style=label.style_labelup) : na
plot(r_s_level, title = "RS_level", display = display.none)
alertcondition(resistance_broken, title='Resistance Broken', message='Resistance Broken, Close Price: {{close}}, Resistance level = {{plot("RS_level")}}')
alertcondition(support_broken, title='Support Broken', message='Support Broken, Close Price: {{close}}, Support level = {{plot("RS_level")}}')
|
Hi-Lo Trend Bars | https://www.tradingview.com/script/BHCE3fPE/ | trademasterf | https://www.tradingview.com/u/trademasterf/ | 32 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MGULHANN
//@version=5
indicator("Hi-Lo Trend Bars", overlay=true)
mlthhv = input.float(2.0, title="HHV Çarpanı", step=0.01)
mltllv = input.float(2.0, title="LLV Çarpanı", step=0.01)
hhvDeger = input.int(15, title="HHV Periyot")
llvDeger = input.int(5, title="LLV Periyot")
src = input(close, title="Kaynak")
hhv = ta.highest(src,hhvDeger) - mlthhv
llv = ta.lowest(src,llvDeger) - mltllv
plot(hhv, color = color.purple, title="HHV")
plot(llv, color= color.aqua, title="LLV")
barcolor(low < llv ? color.red : high > hhv ? color.green : color.red) |
MM Chop Filter | https://www.tradingview.com/script/OnKfG9cF-MM-Chop-Filter/ | MoneyMovesInvestments | https://www.tradingview.com/u/MoneyMovesInvestments/ | 382 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MoneyMovesInvestments
//@version=5
indicator("MM Chop Filter", shorttitle = "MM Chop Filter")
cae_len = input.int(21, minval=1, title="Length",inline="cae1")
cae_src = input.source(close, "Source",inline="cae1")
ch_ut=input.float(60.0, "Choppy Thresholds: Upper", inline = "choppy1")
ch_lt=input.float(40.0, "Lower", inline = "choppy1")
bc_buy = input.bool(true, "Breakup",inline="caebc")
bc_sell = input.bool(true, "Breakdown <- Color Bars",inline="caebc")
buy_alerts = input.bool(true,"Buy", inline="caeal")
sell_alerts = input.bool(true,"Sell", inline="caeal")
choppy_alerts = input.bool(true,"Choppy <- Alerts", inline="caeal")
//User has to agree to have the indi loading on the chart.
var user_consensus = input.string(defval="", title="TYPE 'agree' TO ADD TO CHART. \nTrading involves a risk of loss, and may not be appropriate for every one. Please consider carefully if trading is appropriate for you. Past performance is not indicative of future results. Any and all indicator signals provided by 'MM Chop And Explode' are for educational purposes only. Is your responsibility knowing that by typing 'agree' you are accepting that the AI would trade on your behalf at your own risk. \nRELEASE INFORMATION 2021 © Money Moves Investments", confirm = true, group="consensus")
var icc = false
if user_consensus == "agree"
icc := true
else
icc := false
cae_up = ta.rma(math.max(ta.change(cae_src), 0), cae_len)
cae_down = ta.rma(-math.min(ta.change(cae_src), 0), cae_len)
cae_rsi = cae_down == 0 ? 100 : cae_up == 0 ? 0 : 100 - (100 / (1 + cae_up / cae_down))
plot(icc?cae_rsi:na, color=color.black)
cae_change1 = cae_rsi[1] > ch_ut ? color.aqua :na
cae_change2= cae_rsi[1] < ch_lt ? color.red: na
p1 = plot(icc?cae_rsi:na, style=plot.style_linebr, linewidth=3, color=cae_change1)
p2 = plot(icc?cae_rsi:na, style=plot.style_linebr, linewidth=3, color=cae_change2)
band1 = hline(70)
band2 = hline(30)
band3 = hline (60)
band4 = hline (40)
midline= hline (50)
band5=hline(55)
band6=hline(45)
//fill(band1, band3, color=color.green, transp=90)
fill(band3, band4, color=icc?color.yellow:#00000000, transp=90)
//fill(band4, band2, color=color.red, transp=90)
//fill (band5,band6, color=color.black, transp=50)
choppy_bup = ta.crossover(cae_rsi, ch_ut)
choppy_bdown = ta.crossunder(cae_rsi, ch_lt)
up_to_choppy = ta.crossunder(cae_rsi, ch_ut)
down_to_choppy = ta.crossover(cae_rsi, ch_lt)
bgcolor(icc and choppy_bup ? color.new(color.aqua, 70) : na)
bgcolor(icc and choppy_bdown ? color.new(color.red, 70) : na)
plotshape(icc and choppy_bup, title="Choppy Range Break-ups", style=shape.triangleup,color=color.aqua,location=location.bottom)
plotshape(icc and choppy_bdown, title = "Choppy Range Break-downs",style = shape.triangledown,color=color.red,location=location.top)
barcolor(icc and choppy_bup and bc_buy ? color.aqua : na)
barcolor(icc and choppy_bdown and bc_sell ? color.red : na)
alertcondition(icc and choppy_bup and buy_alerts, "BUY", "Choppy Range Break-up")
alertcondition(icc and choppy_bdown and sell_alerts, "SELL", "Choppy Range Break-down")
alertcondition(icc and up_to_choppy and choppy_alerts, "BUY EXIT", "Got inside Choppy Range")
alertcondition(icc and down_to_choppy and choppy_alerts, "SELL EXIT", "Got inside Choppy Range")
// cond3 = cae_rsi > 55 and close[1] < cae_rsi and close < 60 ? 1 : 0
// barcolor(cond3 ? color.yellow : na)
// cond4 = cae_rsi > 45 and close[1] < cae_rsi and close [1] < 55 ? 1 : 0
// barcolor(cond4 ? color.black : na)
// cond5 = cae_rsi > 40 and close[1] < cae_rsi and close [1] < 55 ? 1 : 0
// barcolor(cond5 ? color.yellow : na)
|
Correlations P/L Range (in percent) | https://www.tradingview.com/script/x53EVCLc-Correlations-P-L-Range-in-percent/ | mpeick | https://www.tradingview.com/u/mpeick/ | 7 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mpeick (Michael Peick)
// This script shows the inefficiency of the markets.
//
// Comparing two (correlated) symbols, the values above 0 means the main symbol (at the top of the graph)
// outperforms the other. A value below 0 means the main symbol underperforms the other.
//
// The band displays different entries until the last candle. Any P/L (of the band range)
// is visible in the band. Example: given a band range length of 5, then all last 5 values
// are compares with the current value for both symbols. Or in other words:
// If symbol A, lets say ETHUSD outperforms, lets say BITCOIN (the main symbol), in the last
// 5 candles, then we would see all values of the band are negative.
//@version=5
indicator("Correlations P/L Range (in percent)", precision=2)
// input data:
which_symbol = input.symbol("FTX:ETHUSD", "symbol")
length = input.int(5, "Band range length", minval=1)
stretch_factor = input.int(1, "Stretch Correlation Factor", minval=1)
main_data = close
second_data = request.security(which_symbol, "", close)
// define profit/loss function for all values from 1 to length (input value)
pl_range(source1, source2, min_length, max_length) =>
big = 10000.0 // there's no infinity value in pinescript, so we use a ridiculous big number (for P/L)
min_out = big
max_out = -big
for offset = min_length to max_length
pl_source1 = (source1[0] - source1[offset]) / source1[offset]
pl_source2 = (source2[0] - source2[offset]) / source2[offset]
pl_diff = pl_source1 - pl_source2
min_out := math.min(min_out, pl_diff)
max_out := math.max(max_out, pl_diff)
[min_out * 100, max_out * 100]
// plotting:
[min_out, max_out] = pl_range(main_data, second_data, 1, length)
col_min = (min_out > 0) ? color.green : ((min_out < 0) ? color.red : color.white)
plt_max = plot(max_out, color=color.orange, title="Line range max values")
plt_min = plot(min_out, color=color.yellow, title="Line range min values")
plt_max_above_0 = plot(math.max(0, max_out), display=display.none, editable=false)
plt_min_above_0 = plot(math.max(0, min_out), display=display.none, editable=false)
plt_max_below_0 = plot(math.min(0, max_out), display=display.none, editable=false)
plt_min_below_0 = plot(math.min(0, min_out), display=display.none, editable=false)
hline(price=0, linestyle=hline.style_dotted, color=color.white, title="Base line")
fill(plt_max_above_0, plt_min_above_0, color=color.new(color.green, 50), title="Fill above base line")
fill(plt_max_below_0, plt_min_below_0, color=color.new(color.red, 50), title="Fill below base line")
// display correction with a stretch factor to better visualize tops and bottoms
cor = math.pow(ta.correlation(main_data, second_data, length), stretch_factor)
plot(cor, color=color.blue, linewidth=2, title="Correlation", display=display.none) |
Dynamic_Retracement_Target | https://www.tradingview.com/script/xFsGprP4-Dynamic-Retracement-Target/ | jacobfabris | https://www.tradingview.com/u/jacobfabris/ | 30 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jacobfabris
//@version=5
indicator("Dynamic_Retracement_Target",overlay=true)
//--- setting the periods
Period_fast = input.int(defval=34)
Period_medium = input.int(defval=144)
Period_slow = input.int(defval=610)
//--- setting the levels
Target_level_superior = input(defval=1.236)
Fib_level_sup = input(defval=0.764)
Fib_level_mid = input(defval=0.500)
Fib_level_inf = input(defval=0.236)
Target_level_inferior = input(defval=-0.236)
//--- calculating the almas
mf = ta.alma(close,Period_fast,0.786,3.236)
mm = ta.alma(close,Period_medium,0.786,3.236)
ms = ta.alma(close,Period_slow,0.786,3.236)
//--- the highest ema and lowest ema
highest_alma = math.max(mf,mm,ms)
lowest_alma = math.min(mf,mm,ms)
//--- Calculating the targets and the levels
A_level_superior = lowest_alma+(highest_alma - lowest_alma)*Target_level_superior
A_sup = highest_alma
A_level_sup = lowest_alma+(highest_alma - lowest_alma)*Fib_level_sup
A_level_mid = lowest_alma+(highest_alma - lowest_alma)*Fib_level_mid
A_level_inf = lowest_alma+(highest_alma - lowest_alma)*Fib_level_inf
A_inf = lowest_alma
A_level_inferior = lowest_alma+(highest_alma - lowest_alma)*Target_level_inferior
//--- plotting the averages
plot(A_level_superior,color=color.blue)
plot(A_sup,color=color.lime,linewidth=2)
plot(A_level_sup,color=color.green)
plot(A_level_mid,color=color.white,linewidth=2)
plot(A_level_inf,color=color.red)
plot(A_inf,color=color.orange,linewidth=2)
plot(A_level_inferior,color=color.blue)
//--- plotting identifications
plotshape(A_level_superior, style= shape.diamond, location = location.absolute , color = color.blue, offset=5,text = "TS", show_last= 1)
plotshape(A_sup, style= shape.diamond, location = location.absolute , color = color.lime, offset=5,text = "A_S", show_last= 1)
plotshape(A_level_sup, style= shape.diamond, location = location.absolute , color = color.green, offset=5,text = "L_sup", show_last= 1)
plotshape(A_level_mid, style= shape.diamond, location = location.absolute , color = color.white, offset=5,text = "L_mid", show_last= 1)
plotshape(A_level_inf, style= shape.diamond, location = location.absolute , color = color.red, offset=5,text = "L_inf", show_last= 1)
plotshape(A_inf, style= shape.diamond, location = location.absolute , color = color.yellow, offset=5,text = "A_I", show_last= 1)
plotshape(A_level_inferior, style= shape.diamond, location = location.absolute , color = color.blue, offset=5,text = "TI", show_last= 1) |
Periodic Cycle | https://www.tradingview.com/script/A1EKWmiM-Periodic-Cycle/ | estyles_tvr1 | https://www.tradingview.com/u/estyles_tvr1/ | 34 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © estyles_tvr1
//@version=5
indicator("Periodic Cycles", overlay=true)
period = input(defval=7*12, title="Cycle Lenght", inline="1")
period_res = input.timeframe('M', "", options=['1', '60', 'D', 'W', 'M'], inline="1")
periodBound = input(defval=12, title="Cycle up/down boundary")
i_date = input.time(timestamp("9 Sep 2021 00:00 +0300"), "Start Date")
l = label.new(i_date, na, "Start Date", xloc=xloc.bar_time, yloc=yloc.abovebar)
label.delete(l[1])
fillBackground = input(true, "Fill Background?")
newMoonBackgroundColor = input(#44444488, "Cycle Start Background Color")
fullMoonBackgroundColor = input(#22222288, "Cycle End Background Color")
print(string txt) =>
var table t = table.new(position.middle_right, 1, 1)
table.cell(t, 0, 0, txt, bgcolor = color.yellow)
calcPhase2(_year, _month, _day, _hour, _minute) =>
current = timestamp(_year, _month, _day, _hour, _minute)
start = i_date
period_secs = period * timeframe.in_seconds(period_res) * 1000
mod = ((current - start) / period_secs) % 1
(mod < 0 and mod > ((periodBound-period)/period)) or (mod > 0 and mod > (periodBound/period)) ? 1 : -1
moon = calcPhase2(year, month, dayofmonth, hour, minute)
if(moon!=moon[1])
line2 = line.new(time, 1, time, 2, xloc=xloc.bar_time, style=line.style_dashed, extend=extend.both)
line.set_color(line2, color.red)
var color col = na
if moon == 1 and fillBackground
col := fullMoonBackgroundColor
if moon == -1 and fillBackground
col := newMoonBackgroundColor
bgcolor(col, title="Cycle") |
Volatility/Volume Impact | https://www.tradingview.com/script/gRcU3ipP-Volatility-Volume-Impact/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 189 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
// __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __
// / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / |
// $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ |
// $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ |
// $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ |
// $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ |
// $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ |
// $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ |
// $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/
//
//
//
//@version=5
indicator("Volatility/Volume Impact", overlay=false)
import HeWhoMustNotBeNamed/enhanced_ta/13 as eta
atrMaType = input.string(title='', defval='rma', options=['ema', 'sma', 'hma', 'rma', 'vwma', 'wma', 'swma'], group='ATR', inline='a')
atrLength = input.int(22, '', group='ATR', inline='a')
maType = input.string(title='', defval='median', options=['ema', 'sma', 'hma', 'rma', 'vwma', 'wma', 'swma', 'median', 'linreg'], group='High/Low Reference', inline="ma")
length = input.int(100, '', step=10, group='High/Low Reference', inline='ma')
usePercentage = input.bool(false, 'Percentage', group='Correlation')
rangeLength = input.int(500, 'Range', step=100, group='Correlation')
getCorrelation(source)=>
var float pvd = 0
var float nvd = 0
ref = eta.ma(source, maType, length)
diff = nz(close - close[1], 0)
diffPercent = diff/close[1]
diffSource = usePercentage? diffPercent : diff
pvd := source > ref? pvd + diffSource : pvd
nvd := source < ref? nvd + diffSource : nvd
pvdCorrelation = ta.correlation(pvd, close, rangeLength)
nvdCorrelation = ta.correlation(nvd, close, rangeLength)
[pvd, nvd, pvdCorrelation, nvdCorrelation]
tradedVolume = volume*ohlc4
volatility = eta.atr(atrMaType, atrLength)*100/close
[pVolumeD, nVolumeD, pVolumeDCorrelation, nVolumeDCorrelation] = getCorrelation(tradedVolume)
[pVolatilityD, nVolatilityD, pVolatilityDCorrelation, nVolatilityDCorrelation] = getCorrelation(volatility)
plot(pVolumeD, "High Volume Impact", color=pVolumeDCorrelation>nVolumeDCorrelation? color.green: color.silver)
plot(nVolumeD, "Low Volume Impact", color=nVolumeDCorrelation>pVolumeDCorrelation? color.red: color.silver)
plot(pVolatilityD, "High Volatility Impact", color=pVolatilityDCorrelation>nVolatilityDCorrelation? color.lime: color.silver)
plot(nVolatilityD, "Low Volatility Impact", color=nVolatilityDCorrelation>pVolatilityDCorrelation? color.orange: color.silver)
|
ATK EMA 5/50/75/200 | https://www.tradingview.com/script/lHEj8j7e/ | TKMOR | https://www.tradingview.com/u/TKMOR/ | 6 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TKMOR
//@version=5
indicator("ATK EMA 5/50/75/200", overlay=true)
openshort=input(true, title="Show EMA 5")
openshorter=input(true, title="Show EMA 50")
openlong=input(true, title="Show EMA 75")
openlonger=input(true, title="Show EMA 200")
opensrc=input(true, title="Show Close Line")
src = input(close, title="Source")
shortline = ta.ema(src,input.int(5, minval=1))
shorterline = ta.ema(src,input.int(50, minval=1))
longline = ta.ema(src,input.int(75, minval=1))
longerline = ta.ema(src,input.int(200, minval=1))
plot(openshort?shortline:na, color = color.new(color.red,0),linewidth=2)
plot(openshorter?shorterline:na, color = color.new(color.orange,0),linewidth=2)
plot(openlong?longline:na, color = color.new(color.aqua,0),linewidth=2)
plot(openlonger?longerline:na, color = color.new(color.green,0),linewidth=2)
plot(opensrc?src:na)
|
Day Trading [VB] | https://www.tradingview.com/script/6HPRago9-Day-Trading-VB/ | bhosalevishal | https://www.tradingview.com/u/bhosalevishal/ | 41 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © bhosalevishal
//@version=5
indicator('Day Trading [VB]', shorttitle='DTrade [VB]', overlay=true)
// USER INPUTS
showRoundNo = input(group="Round Number Levels", inline="1", title='Show Round Number Levels', defval=true)
roundNo = input.int(group="Round Number Levels", inline="2", title='Round With', defval=100, tooltip="🛑 Plots expanded horizontal lines.")
candlestickPattern = input.bool(group="Candlestick Patterns", inline="1", title='Show Candlestick Patterns', defval=true, tooltip="🛑 Plots candlestick pattern name.")
showTomorrowCPR = input(group="CPR", inline="1", title='Show tomorrow\'s CPR', defval=false)
showHistoricalCPR = input(group="CPR", inline="2", title='Show historical CPR', defval=false)
showReversal = input(group="Reversal", inline="1", title='Show Reversals', defval=true)
_wma = input(group="WMA", inline="1", title='Show WMA', defval=false)
wma_len = input.int(9, minval=1, title="Length")
wma_src = input(close, title="Source")
wma_offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
fastEMA = input(group="EMA(fast)", inline="1", title='Show EMA(fast)', defval=true)
fastEMA_len = input.int(defval=3, minval=1, title='Length')
fastEMA_src = input(defval=close, title='Source')
fastEMA_offset = input.int(title='Offset', defval=0, minval=-500, maxval=500)
medEMA = input(group="EMA(med)", inline="1", title='Show EMA(med)', defval=true)
medEMA_len = input.int(defval=13, minval=1, title='Length')
medEMA_src = input(defval=close, title='Source')
medEMA_offset = input.int(title='Offset', defval=0, minval=-500, maxval=500)
slowEMA = input(group="EMA(slow)", inline="1", title='Show EMA(slow)', defval=false)
slowEMA_len = input.int(defval=20, minval=1, title='Length')
slowEMA_src = input(defval=close, title='Source')
slowEMA_offset = input.int(title='Offset', defval=0, minval=-500, maxval=500)
// CONSTANTS
var lTransp = 30
var color blue = #0000FF
var color cprColor = color.new(blue, lTransp)
var color sColor = color.new(color.green, lTransp)
var color rColor = color.new(color.red, lTransp)
var color pdHLColor = color.new(color.purple, lTransp)
var color labelColor = color.new(color.fuchsia, lTransp)
var color doColor = color.new(color.lime, lTransp)
var color grayColor = color.new(color.blue, lTransp)
var color limeColor = color.new(color.lime, lTransp)
// Today's Start and End time
start = timestamp(year(time), month(time), dayofmonth(time), 09, 00)
end = timestamp(year(time), month(time), dayofmonth(time), 15, 40)
// Tomorrow's Start and End time
tom_start = start + 86400000
tom_end = end + 86400000
// WMA
wma_out = ta.wma(wma_src, wma_len)
// EMAs
fastEMA_out = ta.ema(fastEMA_src, fastEMA_len)
medEMA_out = ta.ema(medEMA_src, medEMA_len)
slowEMA_out = ta.ema(slowEMA_src, slowEMA_len)
// CCI
// cci = ta.cci(hlc3,7)
// ********** FUNCTION ********** //
plotLinesAndLabels(value,_label, _color, start, end) =>
__line = line.new(start, value, end, value, xloc.bar_time, color=_color, style=line.style_solid, width=1)
line.delete(__line[1])
__label = label.new(start, value, text=_label+' ', xloc=xloc.bar_time, textcolor=labelColor, style=label.style_label_center, color=#00000000)
label.delete(__label[1])
plotExtendedLines(value) =>
ex_line = line.new(start, value, end, value, xloc.bar_time, color=limeColor, extend=extend.right, width=2, style=line.style_dotted)
line.delete(ex_line[1])
//Pivot = (High + Low + Close)/3
//Bottom CPR = (High + Low)/ 2
//Top CPR = (Pivot – BC) + Pivot
calCPRSR(H, L, C) =>
Pivot = (H + L + C) / 3
BC = (H + L) / 2
TC = (Pivot - BC) + Pivot
R3 = H + 2 * (Pivot - L)
R2 = Pivot + H - L
R1 = Pivot * 2 - L
S1 = Pivot * 2 - H
S2 = Pivot - (H - L)
S3 = L - 2 * (H - Pivot)
[Pivot, BC, TC, R3, R2, R1, S1, S2, S3]
// calculate camarrila SRs
calCamSR(H, L, C) =>
Pivot_Median = (H + L + C) / 3
Pivot_Range = H - L
R1 = C + Pivot_Range * 1.1 / 12.0
S1 = C - Pivot_Range * 1.1 / 12.0
R2 = C + Pivot_Range * 1.1 / 6.0
S2 = C - Pivot_Range * 1.1 / 6.0
R3 = C + Pivot_Range * 1.1 / 4.0
S3 = C - Pivot_Range * 1.1 / 4.0
R4 = C + Pivot_Range * 1.1 / 2.0
S4 = C - Pivot_Range * 1.1 / 2.0
[R4, R3, R2, R1, S1, S2, S3, S4]
// Todays HLOC
[dayO, dayH, dayL, dayC] = request.security(syminfo.tickerid, 'D', [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
// Previous Day HLOC
[pDayO, pDayH, pDayL, pDayC] = request.security(syminfo.tickerid, 'D', [open[1], high[1], low[1], close[1]], barmerge.gaps_off, barmerge.lookahead_on)
// TODAYS CPR + SR CALCULATIONS
[dayP, dayBC, dayTC, dayR3, dayR2, dayR1, dayS1, dayS2, dayS3] = calCPRSR(pDayH, pDayL, pDayC)
// TOMORROW CPR + SR CALCULATIONS
[tomP, tomBC, tomTC, tomR3, tomR2, tomR1, tomS1, tomS2, tomS3] = calCPRSR(dayH, dayL, dayC)
// TODAYS CAMARRILA SR CALCULATIONS
[camR4, camR3, camR2, camR1, camS1, camS2, camS3, camS4] = calCamSR(pDayH, pDayL, pDayC)
// Weekly Pivot + SR
[WP, WS1, WS2, WS3, WR1, WR2, WR3] = request.security(syminfo.tickerid, 'W', [dayP[1], dayS1[1], dayS2[1], dayS3[1], dayR1[1], dayR2[1], dayR3[1]], barmerge.gaps_off, barmerge.lookahead_on)
// Monthly Pivot + SR
[MP, MS1, MS2, MS3, MR1, MR2, MR3] = request.security(syminfo.tickerid, 'M', [dayP[1], dayS1[1], dayS2[1], dayS3[1], dayR1[1], dayR2[1], dayR3[1]], barmerge.gaps_off, barmerge.lookahead_on)
getRoundUp() =>
_round = math.round(dayO/roundNo)*roundNo
_roundUp_1 = _round + roundNo
_roundUp_2 = _roundUp_1 + roundNo
_roundDwn_1 = _round - roundNo
_roundDwn_2 = _roundDwn_1 - roundNo
[_round, _roundUp_1, _roundUp_2, _roundDwn_1, _roundDwn_2]
// ********** PREVIOUS DAY ********** //
plotLinesAndLabels(pDayO, 'PDO', grayColor, start, end)
plotLinesAndLabels(pDayH, 'PDH', grayColor, start, end)
plotLinesAndLabels(pDayL, 'PDL', grayColor, start, end)
plotLinesAndLabels(pDayC, 'PDC', grayColor, start, end)
// ********** TODAY OPEN ********** //
plotLinesAndLabels(dayO, 'DO', doColor, start, end)
// ********** 1st CANDLE HIGH LOW ********** //
if (session.ismarket) and not session.ismarket[1]
plotLinesAndLabels(high, '1stH', pdHLColor, start, end)
plotLinesAndLabels(low, '1stL', pdHLColor, start, end)
// ********** TODAYS CPR + SR ********** //
plotLinesAndLabels(dayTC, 'TC', cprColor, start, end)
plotLinesAndLabels(dayP, 'P', cprColor, start, end)
plotLinesAndLabels(dayBC, 'BC', cprColor, start, end)
plotLinesAndLabels(dayS1, 'S1', sColor, start, end)
plotLinesAndLabels(dayS2, 'S2', sColor, start, end)
plotLinesAndLabels(dayS3, 'S3', sColor, start, end)
plotLinesAndLabels(dayR1, 'R1', rColor, start, end)
plotLinesAndLabels(dayR2, 'R2', rColor, start, end)
plotLinesAndLabels(dayR3, 'R3', rColor, start, end)
__p_label = label.new(end, dayP, text=' '+'P', xloc=xloc.bar_time, textcolor=labelColor, style=label.style_label_center, color=#00000000)
label.delete(__p_label[1])
__tc_label = label.new(end, dayTC, text=' '+'TC', xloc=xloc.bar_time, textcolor=labelColor, style=label.style_label_center, color=#00000000)
label.delete(__tc_label[1])
__bc_label = label.new(end, dayBC, text=' '+'BC', xloc=xloc.bar_time, textcolor=labelColor, style=label.style_label_center, color=#00000000)
label.delete(__bc_label[1])
// ********** Weekly CPR + SR ********** //
plotLinesAndLabels(WP, 'WP', cprColor, start, end)
plotLinesAndLabels(WS1, 'WS1', sColor, start, end)
plotLinesAndLabels(WS2, 'WS2', sColor, start, end)
plotLinesAndLabels(WS3, 'WS3', sColor, start, end)
plotLinesAndLabels(WR1, 'WR1', rColor, start, end)
plotLinesAndLabels(WR2, 'WR2', rColor, start, end)
plotLinesAndLabels(WR3, 'WR3', rColor, start, end)
// ********** Monthly CPR + SR ********** //
plotLinesAndLabels(MP, 'MP', cprColor, start, end)
plotLinesAndLabels(MS1, 'MS1', sColor, start, end)
plotLinesAndLabels(MS2, 'MS2', sColor, start, end)
plotLinesAndLabels(MS3, 'MS3', sColor, start, end)
plotLinesAndLabels(MR1, 'MR1', rColor, start, end)
plotLinesAndLabels(MR2, 'MR2', rColor, start, end)
plotLinesAndLabels(MR3, 'MR3', rColor, start, end)
// ********** TOMORROWS CPR + SR ********** //
if showTomorrowCPR
plotLinesAndLabels(tomP, 'P', cprColor, tom_start, tom_end)
plotLinesAndLabels(tomTC, 'TC', cprColor, tom_start, tom_end)
plotLinesAndLabels(tomBC, 'BC', cprColor, tom_start, tom_end)
plotLinesAndLabels(tomS1, 'S1', sColor, tom_start, tom_end)
plotLinesAndLabels(tomS2, 'S2', sColor, tom_start, tom_end)
plotLinesAndLabels(tomS3, 'S3', sColor, tom_start, tom_end)
plotLinesAndLabels(tomR1, 'R1', rColor, tom_start, tom_end)
plotLinesAndLabels(tomR2, 'R2', rColor, tom_start, tom_end)
plotLinesAndLabels(tomR3, 'R3', rColor, tom_start, tom_end)
// ********** EMAs ********** //
plot(_wma ? wma_out : na, title='WMA', color=color.new(color.blue, 0), offset=fastEMA_offset, style=plot.style_line, linewidth=2)
plot(fastEMA ? fastEMA_out : na, title='EMA(fast)', color=color.new(color.fuchsia, 0), offset=fastEMA_offset, style=plot.style_line, linewidth=2)
plot(medEMA ? medEMA_out : na, title='EMA(med)', color=color.new(color.green, 0), offset=medEMA_offset, style=plot.style_line, linewidth=2)
plot(slowEMA ? slowEMA_out : na, title='EMA(slow)', color=color.new(color.yellow, 0), offset=slowEMA_offset, style=plot.style_line, linewidth=2)
// ********** Buy Sell Signals ********** //
longCond = ta.crossover(fastEMA_out, medEMA_out)
shortCond = ta.crossunder(fastEMA_out, medEMA_out)
plotshape(longCond, title='Buy Signal', text='B', textcolor=color.new(color.white, 0), style=shape.labelup, size=size.tiny, location=location.belowbar, color=color.new(color.green, 0))
plotshape(shortCond, title='Short Signal', text='S', textcolor=color.new(color.white, 0), style=shape.labeldown, size=size.tiny, location=location.abovebar, color=color.new(color.red, 0))
//strategy.entry("Long", strategy.long, when=longCond and strategy.position_size <= 0)
//strategy.close(id="Long", when = shortCond)
//strategy.entry("Short", strategy.short, when=shortCond and strategy.position_size > 0)
//strategy.close(id="Short", when = longCond)
line hiline = na
line loline = na
float currH = 0.0
float currL = 0.0
if longCond
currH := high
hiline := line.new(bar_index, high, bar_index+5, high, xloc.bar_index, extend.none, color=pdHLColor, style=line.style_dotted, width=2)
if shortCond
currL := low
loline := line.new(bar_index, low, bar_index+5, low, xloc.bar_index, extend.none, color=pdHLColor, style=line.style_dotted, width=2)
for i = 1 to 5
if not na(hiline[i]) and high >= high[i]
line.delete(hiline[i])
if not na(loline[i]) and low <= low[i]
line.delete(loline[i])
// ********** Round Number Lines ********** //
if (showRoundNo)
[_round, _roundUp_1, _roundUp_2, _roundDwn_1, _roundDwn_2] = getRoundUp()
plotExtendedLines(_round)
plotExtendedLines(_roundUp_1)
plotExtendedLines(_roundUp_2)
plotExtendedLines(_roundDwn_1)
plotExtendedLines(_roundDwn_2)
////////////////////////
// Historical CPR //
//////////////////////
lStyle = plot.style_circles
p_r3 = plot(showHistoricalCPR ? dayR3 : na, color=rColor, style=lStyle, title="R3")
p_r2 = plot(showHistoricalCPR ? dayR2 : na, color=rColor, style=lStyle, linewidth=1, title="R2")
p_r1 = plot(showHistoricalCPR ? dayR1 : na, color=rColor, style=lStyle, linewidth=1, title="R1")
p_cprTC = plot(showHistoricalCPR ? dayTC : na, color=cprColor, style=lStyle, linewidth=1, title="TC")
p_cprP = plot(showHistoricalCPR ? dayP : na, color=cprColor, style=lStyle, linewidth=1, title="P")
p_cprBC = plot(showHistoricalCPR ? dayBC : na, color=cprColor, style=lStyle, linewidth=1, title="BC")
s1 = plot(showHistoricalCPR ? dayS1 : na, color=sColor, style=lStyle, linewidth=1, title="S1")
s2 = plot(showHistoricalCPR ? dayS2 : na, color=sColor, style=lStyle, linewidth=1, title="S2")
s3 = plot(showHistoricalCPR ? dayS3 : na, color=sColor, style=lStyle, linewidth=1, title="S3")
fill(p_cprTC, p_cprBC, color=color.new(pdHLColor,80))
// ********** Camarilla SR ********** //
line.new(start, camR4, time, camR4, xloc.bar_time, color=pdHLColor, style=line.style_dashed, width=1)
line.new(start, camR3, time, camR3, xloc.bar_time, color=pdHLColor, style=line.style_dashed, width=1)
line.new(start, camR2, time, camR2, xloc.bar_time, color=pdHLColor, style=line.style_dashed, width=1)
line.new(start, camR1, time, camR1, xloc.bar_time, color=pdHLColor, style=line.style_dashed, width=1)
line.new(start, camS1, time, camS1, xloc.bar_time, color=pdHLColor, style=line.style_dashed, width=1)
line.new(start, camS2, time, camS2, xloc.bar_time, color=pdHLColor, style=line.style_dashed, width=1)
line.new(start, camS3, time, camS3, xloc.bar_time, color=pdHLColor, style=line.style_dashed, width=1)
line.new(start, camS4, time, camS4, xloc.bar_time, color=pdHLColor, style=line.style_dashed, width=1)
//Candle Stick Patterns
DJ1 = math.abs(open - close) < (high - low) * 0.1 and high - low > ta.atr(14)
plotshape(candlestickPattern? DJ1 : na, title='Doji', text='D', location=location.abovebar, color=color.new(color.blue, 0), style=shape.xcross)
OR1 = open[1] > close[1] and open < close and low[1] > low and close > high[1] and high - low > ta.atr(14) * 1.25 // or close[1] > open
plotshape(candlestickPattern? OR1 : na, title='Bullish Engulfing', text='BE', style=shape.labelup, color=color.new(color.black, 0), location=location.belowbar, textcolor=color.new(color.white, 0))
OR2 = open[1] < close[1] and open > close and high[1] < high and close < low[1] and high - low > ta.atr(14) * 1.25 // or close[1] < open
plotshape(candlestickPattern? OR2 : na, title='Bearish Engulfing', text='BE', style=shape.labeldown, color=color.new(color.black, 0), textcolor=color.new(color.white, 0))
WR11 = low < low[1] and math.abs(low - math.min(open, close)) > math.abs(open - close) * 2 and math.abs(high - close) < (high - low) * 0.35 and high - low > ta.atr(14)
plotshape(candlestickPattern? WR11 : na, title='Hammer', text='H', location=location.belowbar, color=color.new(color.black, 0), style=shape.labelup, textcolor=color.new(color.white, 0))
WR21 = high > high[1] and high - math.max(open, close) > math.abs(open - close) * 2 and math.abs(close - low) < (high - low) * 0.35 and high - low > ta.atr(14)
plotshape(candlestickPattern? WR21 : na, title='Shooting Star', text='SS', color=color.new(color.black, 0), style=shape.labeldown, textcolor=color.new(color.white, 0))
ER1 = high[1] - low[1] > ta.atr(14) * 2 and math.abs(open[1] - close[1]) > (high[1] - low[1]) * 0.5 and open[1] > close[1] and open < close //and abs(open[1] - close[1]) < (high[1]-low[1]) * 0.85
plotshape(candlestickPattern? ER1 : na, title='Bullish E.Reversal', text='BR', location=location.belowbar, color=color.new(color.black, 0), style=shape.labelup, textcolor=color.new(color.white, 0)) // E denotes Extreme
ER2 = high[1] - low[1] > ta.atr(14) * 2 and math.abs(open[1] - close[1]) > (high[1] - low[1]) * 0.5 and open[1] < close[1] and open > close //and abs(open[1] - close[1]) < (high[1]-low[1]) * 0.85
plotshape(candlestickPattern? ER2 : na, title='Bearish E.Reversal', text='BR', location=location.abovebar, color=color.new(color.black, 0), style=shape.labeldown, textcolor=color.new(color.white, 0))
bool bullReversal = fastEMA_out > high and fastEMA_out < medEMA_out and (fastEMA_out - high >= 2)
plotshape(bullReversal and showReversal, title='Bullish Reversal', text='R', textcolor=color.new(color.white, 0), style=shape.labelup, size=size.tiny, location=location.belowbar, color=color.new(color.purple, 0))
bool bearReversal = fastEMA_out < low and fastEMA_out > medEMA_out and (low - fastEMA_out >= 2)
plotshape(bearReversal and showReversal, title='Bearish Reversal', text='R', textcolor=color.new(color.white, 0), style=shape.labeldown, size=size.tiny, location=location.abovebar, color=color.new(color.purple, 0))
|
ORB and Camarrila SR [VB] | https://www.tradingview.com/script/wDHAIqy6-ORB-and-Camarrila-SR-VB/ | bhosalevishal | https://www.tradingview.com/u/bhosalevishal/ | 33 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © bhosalevishal
//@version=5
indicator(title="ORB and Camarrila SR [VB]", shorttitle="ORB & SR [VB]", overlay=true)
showCamarilla = input(group="Camarilla", inline="1", title='Show Camarilla\'s SR', defval=true)
showORB = input(group="Open Range Breakout", inline="1", title='Show Open Range Breakout', defval=true)
normal_start = timestamp(year(time), month(time), dayofmonth(time), 09, 15)
normal_end = timestamp(year(time), month(time), dayofmonth(time), 15, 30)
// CONSTANTS
var lTransp = 50
var color blue = #0000FF
var color blueColor = color.new(blue, lTransp)
var color greenColor = color.new(color.green, lTransp)
var color redColor = color.new(color.red, lTransp)
var color purpleColor = color.new(color.purple, lTransp)
var color blackColor = color.new(color.black, lTransp)
var color limeColor = color.new(color.lime, lTransp)
var color grayColor = color.new(color.gray, lTransp)
var __intraday = true
var newHigh = 0.0
var newLow = 0.0
var dayOpen = 0.0
var diffRange = 0.0
// Previous Day HLOC
[pDayO, pDayH, pDayL, pDayC] = request.security(syminfo.tickerid, 'D', [open[1], high[1], low[1], close[1]], barmerge.gaps_off, barmerge.lookahead_on)
// Today 15 minutes HLOC
[dayO, dayH, dayL, dayC] = request.security(syminfo.tickerid, '15', [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
// Today day open
[dO] = request.security(syminfo.tickerid, 'D', [open], barmerge.gaps_off, barmerge.lookahead_on)
if session.ismarket and not session.ismarket[1]
newHigh := dayH
newLow := dayL
dayOpen := dO
newHigh, newLow, dayOpen
diffRange := (newHigh - newLow) / 2.35
// calculate camarrila SRs
calCamSR(H, L, C) =>
Pivot_Median = (H + L + C) / 3
Pivot_Range = H - L
R1 = C + Pivot_Range * 1.1 / 12.0
S1 = C - Pivot_Range * 1.1 / 12.0
R2 = C + Pivot_Range * 1.1 / 6.0
S2 = C - Pivot_Range * 1.1 / 6.0
R3 = C + Pivot_Range * 1.1 / 4.0
S3 = C - Pivot_Range * 1.1 / 4.0
R4 = C + Pivot_Range * 1.1 / 2.0
S4 = C - Pivot_Range * 1.1 / 2.0
[R4, R3, R2, R1, S1, S2, S3, S4]
// TODAYS CAMARRILA SR CALCULATIONS
[camR4, camR3, camR2, camR1, camS1, camS2, camS3, camS4] = calCamSR(pDayH, pDayL, pDayC)
plot(showORB?dayOpen:na, color=limeColor, style=plot.style_stepline, linewidth=2)
var upper1 = plot(showORB?newHigh:na, color=purpleColor, style=plot.style_stepline, linewidth=2)
var upper2 = plot(showORB?newHigh+diffRange:na, color=redColor, style=plot.style_stepline, linewidth=2)
fill(upper1, upper2, color=color.new(color.gray, 90))
var lower1 = plot(showORB?newLow:na, color=purpleColor, style=plot.style_stepline, linewidth=2)
var lower2 = plot(showORB?newLow-diffRange:na, color=greenColor, style=plot.style_stepline, linewidth=2)
fill(lower1, lower2, color=color.new(color.gray, 95))
// ********** Camarrila SR ********** //
plot(showCamarilla?camR4:na, color=blueColor, linewidth=1, style=plot.style_circles)
plot(showCamarilla?camR3:na, color=blueColor, linewidth=1, style=plot.style_circles)
plot(showCamarilla?camR2:na, color=blueColor, linewidth=1, style=plot.style_circles)
plot(showCamarilla?camR1:na, color=blueColor, linewidth=1, style=plot.style_circles)
plot(showCamarilla?camS4:na, color=blueColor, linewidth=1, style=plot.style_circles)
plot(showCamarilla?camS3:na, color=blueColor, linewidth=1, style=plot.style_circles)
plot(showCamarilla?camS2:na, color=blueColor, linewidth=1, style=plot.style_circles)
plot(showCamarilla?camS1:na, color=blueColor, linewidth=1, style=plot.style_circles)
|
[_ParkF]RSI | https://www.tradingview.com/script/tFt0ehE7/ | ParkF | https://www.tradingview.com/u/ParkF/ | 311 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ParkF
//@version=5
indicator('[_ParkF]RSI', overlay=false, max_bars_back=1500)
// rsi divergence
// input
rsig = 'RSI'
rb = input(2, 'How many Right Bars for Pivots', group=rsig)
lb = input(15, 'How many Left Bars for Pivots', group=rsig)
sph = input(close, 'Pivot source for Bear Divs', group=rsig)
spl = input(close, 'Pivots Source for Bull Divs', group=rsig)
len = input.int(14, ' RSI Length', minval=1, group=rsig)
lvl = input.int(5, 'Lookback Level for Divs', options=[1, 2, 3, 4, 5], group=rsig)
// pivot
ph = ta.pivothigh(sph, lb, rb)
pl = ta.pivotlow(spl, lb, rb)
hi0 = ta.valuewhen(ph, sph[rb], 0)
hi1 = ta.valuewhen(ph, sph[rb], 1)
hi2 = ta.valuewhen(ph, sph[rb], 2)
hi3 = ta.valuewhen(ph, sph[rb], 3)
hi4 = ta.valuewhen(ph, sph[rb], 4)
hi5 = ta.valuewhen(ph, sph[rb], 5)
lo0 = ta.valuewhen(pl, spl[rb], 0)
lo1 = ta.valuewhen(pl, spl[rb], 1)
lo2 = ta.valuewhen(pl, spl[rb], 2)
lo3 = ta.valuewhen(pl, spl[rb], 3)
lo4 = ta.valuewhen(pl, spl[rb], 4)
lo5 = ta.valuewhen(pl, spl[rb], 5)
lox0 = ta.valuewhen(pl, bar_index[rb], 0)
lox1 = ta.valuewhen(pl, bar_index[rb], 1)
lox2 = ta.valuewhen(pl, bar_index[rb], 2)
lox3 = ta.valuewhen(pl, bar_index[rb], 3)
lox4 = ta.valuewhen(pl, bar_index[rb], 4)
lox5 = ta.valuewhen(pl, bar_index[rb], 5)
hix0 = ta.valuewhen(ph, bar_index[rb], 0)
hix1 = ta.valuewhen(ph, bar_index[rb], 1)
hix2 = ta.valuewhen(ph, bar_index[rb], 2)
hix3 = ta.valuewhen(ph, bar_index[rb], 3)
hix4 = ta.valuewhen(ph, bar_index[rb], 4)
hix5 = ta.valuewhen(ph, bar_index[rb], 5)
rsi = ta.rsi(close, len)
rh0 = ta.valuewhen(ph, rsi[rb], 0)
rh1 = ta.valuewhen(ph, rsi[rb], 1)
rh2 = ta.valuewhen(ph, rsi[rb], 2)
rh3 = ta.valuewhen(ph, rsi[rb], 3)
rh4 = ta.valuewhen(ph, rsi[rb], 4)
rh5 = ta.valuewhen(ph, rsi[rb], 5)
rl0 = ta.valuewhen(pl, rsi[rb], 0)
rl1 = ta.valuewhen(pl, rsi[rb], 1)
rl2 = ta.valuewhen(pl, rsi[rb], 2)
rl3 = ta.valuewhen(pl, rsi[rb], 3)
rl4 = ta.valuewhen(pl, rsi[rb], 4)
rl5 = ta.valuewhen(pl, rsi[rb], 5)
// bull & bear divergence logic
bull_div_1= lo0<lo1
and rl1<rl0
bull_div_2= lo0<lo1 and lo0<lo2
and rl2<rl0 and rl2<rl1 and lvl>=2
bull_div_3= lo0<lo1 and lo0<lo2 and lo0<lo3
and rl3<rl0 and rl3<rl1 and rl3<rl2 and lvl>=3
bull_div_4= lo0<lo1 and lo0<lo2 and lo0<lo3 and lo0<lo4
and rl4<rl0 and rl4<rl1 and rl4<rl2 and rl4<rl3 and lvl>=4
bull_div_5= lo0<lo1 and lo0<lo2 and lo0<lo3 and lo0<lo4 and lo0<lo5
and rl5<rl0 and rl5<rl1 and rl5<rl2 and rl5<rl3 and rl5<rl4 and lvl>=5
bear_div_1= hi0>hi1
and rh1>rh0
bear_div_2= hi0>hi1 and hi0>hi2
and rh2>rh0 and rh2>rh1 and lvl>=2
bear_div_3= hi0>hi1 and hi0>hi2 and hi0>hi3
and rh3>rh0 and rh3>rh1 and rh3>rh2 and lvl>=3
bear_div_4= hi0>hi1 and hi0>hi2 and hi0>hi3 and hi0>hi4
and rh4>rh0 and rh4>rh1 and rh4>rh2 and rh4>rh3 and lvl>=4
bear_div_5= hi0>hi1 and hi0>hi2 and hi0>hi3 and hi0>hi4 and hi0>hi5
and rh5>rh0 and rh5>rh1 and rh5>rh2 and rh5>rh3 and rh5>rh4 and lvl>=5
new_bull1= bull_div_1 and not bull_div_1[1]
new_bull2= bull_div_2 and not bull_div_2[1]
new_bull3= bull_div_3 and not bull_div_3[1]
new_bull4= bull_div_4 and not bull_div_4[1]
new_bull5= bull_div_5 and not bull_div_5[1]
new_bear1= bear_div_1 and not bear_div_1[1]
new_bear2= bear_div_2 and not bear_div_2[1]
new_bear3= bear_div_3 and not bear_div_3[1]
new_bear4= bear_div_4 and not bear_div_4[1]
new_bear5= bear_div_5 and not bear_div_5[1]
recall(x) =>
ta.barssince(not na(x))
// bull divergence line plot
rbull1 = line(na)
rbull1 := new_bull1 and not new_bull2 and not new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox1, rl1, color=#ff9800, width=2) : na
rbull2 = line(na)
rbull2 := new_bull2 and not new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox2, rl2, color=#ff9800, width=2) : na
rbull3 = line(na)
rbull3 := new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox3, rl3, color=#ff9800, width=2) : na
rbull4 = line(na)
rbull4 := new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox4, rl4, color=#ff9800, width=2) : na
rbull5 = line(na)
rbull5 := new_bull5 ? line.new(lox0, rl0, lox5, rl5, color=#ff9800, width=2) : na
xbull21 = ta.valuewhen(recall(rbull2) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull31 = ta.valuewhen(recall(rbull3) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull41 = ta.valuewhen(recall(rbull4) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull51 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull32 = ta.valuewhen(recall(rbull3) == 0, bar_index, 0) - ta.valuewhen(recall(rbull2) == 0, bar_index, 0)
xbull42 = ta.valuewhen(recall(rbull4) == 0, bar_index, 0) - ta.valuewhen(recall(rbull2) == 0, bar_index, 0)
xbull52 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull2) == 0, bar_index, 0)
xbull43 = ta.valuewhen(recall(rbull4) == 0, bar_index, 0) - ta.valuewhen(recall(rbull3) == 0, bar_index, 0)
xbull53 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull3) == 0, bar_index, 0)
xbull54 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull4) == 0, bar_index, 0)
if new_bull2 and lo2 == ta.valuewhen(new_bull1, lo1, 0) and xbull21 >= 0
line.delete(rbull1[xbull21])
if new_bull3 and lo3 == ta.valuewhen(new_bull1, lo1, 0) and xbull31 >= 0
line.delete(rbull1[xbull31])
if new_bull4 and lo4 == ta.valuewhen(new_bull1, lo1, 0) and xbull41 >= 0
line.delete(rbull1[xbull41])
if new_bull5 and lo5 == ta.valuewhen(new_bull1, lo1, 0) and xbull51 >= 0
line.delete(rbull1[xbull51])
if new_bull3 and lo3 == ta.valuewhen(new_bull2, lo2, 0) and xbull32 >= 0
line.delete(rbull2[xbull32])
if new_bull4 and lo4 == ta.valuewhen(new_bull2, lo2, 0) and xbull42 >= 0
line.delete(rbull2[xbull42])
if new_bull5 and lo5 == ta.valuewhen(new_bull2, lo2, 0) and xbull52 >= 0
line.delete(rbull2[xbull52])
if new_bull4 and lo4 == ta.valuewhen(new_bull3, lo3, 0) and xbull43 >= 0
line.delete(rbull3[xbull43])
if new_bull5 and lo5 == ta.valuewhen(new_bull3, lo3, 0) and xbull53 >= 0
line.delete(rbull3[xbull53])
if new_bull5 and lo5 == ta.valuewhen(new_bull4, lo4, 0) and xbull54 >= 0
line.delete(rbull4[xbull54])
// bear divergence line plot
rbear1 = line(na)
rbear1 := new_bear1 and not new_bear2 and not new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix1, rh1, color=#ff9800, width=2) : na
rbear2 = line(na)
rbear2 := new_bear2 and not new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix2, rh2, color=#ff9800, width=2) : na
rbear3 = line(na)
rbear3 := new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix3, rh3, color=#ff9800, width=2) : na
rbear4 = line(na)
rbear4 := new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix4, rh4, color=#ff9800, width=2) : na
rbear5 = line(na)
rbear5 := new_bear5 ? line.new(hix0, rh0, hix5, rh5, color=#ff9800, width=2) : na
xbear21 = ta.valuewhen(recall(rbear2) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear31 = ta.valuewhen(recall(rbear3) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear41 = ta.valuewhen(recall(rbear4) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear51 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear32 = ta.valuewhen(recall(rbear3) == 0, bar_index, 0) - ta.valuewhen(recall(rbear2) == 0, bar_index, 0)
xbear42 = ta.valuewhen(recall(rbear4) == 0, bar_index, 0) - ta.valuewhen(recall(rbear2) == 0, bar_index, 0)
xbear52 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear2) == 0, bar_index, 0)
xbear43 = ta.valuewhen(recall(rbear4) == 0, bar_index, 0) - ta.valuewhen(recall(rbear3) == 0, bar_index, 0)
xbear53 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear3) == 0, bar_index, 0)
xbear54 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear4) == 0, bar_index, 0)
if new_bear2 and hi2 == ta.valuewhen(new_bear1, hi1, 0) and xbear21 >= 0
line.delete(rbear1[xbear21])
if new_bear3 and hi3 == ta.valuewhen(new_bear1, hi1, 0) and xbear31 >= 0
line.delete(rbear1[xbear31])
if new_bear4 and hi4 == ta.valuewhen(new_bear1, hi1, 0) and xbear41 >= 0
line.delete(rbear1[xbear41])
if new_bear5 and hi5 == ta.valuewhen(new_bear1, hi1, 0) and xbear51 >= 0
line.delete(rbear1[xbear51])
if new_bear3 and hi3 == ta.valuewhen(new_bear2, hi2, 0) and xbear32 >= 0
line.delete(rbear2[xbear32])
if new_bear4 and hi4 == ta.valuewhen(new_bear2, hi2, 0) and xbear42 >= 0
line.delete(rbear2[xbear42])
if new_bear5 and hi5 == ta.valuewhen(new_bear2, hi2, 0) and xbear52 >= 0
line.delete(rbear2[xbear52])
if new_bear4 and hi4 == ta.valuewhen(new_bear3, hi3, 0) and xbear43 >= 0
line.delete(rbear3[xbear43])
if new_bear5 and hi5 == ta.valuewhen(new_bear3, hi3, 0) and xbear53 >= 0
line.delete(rbear3[xbear53])
if new_bear5 and hi5 == ta.valuewhen(new_bear4, hi4, 0) and xbear54 >= 0
line.delete(rbear4[xbear54])
plotshape(title='bull_div_1', series=new_bull1 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_2', series=new_bull2 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_3', series=new_bull3 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_4', series=new_bull4 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_5', series=new_bull5 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_1', series=new_bear1 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_2', series=new_bear2 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_3', series=new_bear3 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_4', series=new_bear4 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_5', series=new_bear5 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
// rsi candle (with wick)
// rsi configuration
rsrc = close
ad = true
// rsi function
pine_rsi(rsrc, len) =>
u = math.max(rsrc - rsrc[1], 0)
d = math.max(rsrc[1] - rsrc, 0)
rs = ta.rma(u, len) / ta.rma(d, len)
res = 100 - 100 / (1 + rs)
res
pine_rma(rsrc, length) =>
b = 1 / length
sum = 0.0
sum := na(sum[1]) ? ta.sma(rsrc, length) : b * rsrc + (1 - b) * nz(sum[1])
u = math.max(rsrc - rsrc[1], 0)
d = math.max(rsrc[1] - rsrc, 0)
b = 1 / len
ruh = b * math.max(high - close[1], 0) + (1 - b) * ta.rma(u, len)[1]
rdh = (1 - b) * ta.rma(d, len)[1]
rul = (1 - b) * ta.rma(u, len)[1]
rdl = b * math.max(close[1] - low, 0) + (1 - b) * ta.rma(d, len)[1]
function(rsi, len) =>
f = -math.pow(math.abs(math.abs(rsi - 50) - 50), 1 + math.pow(len / 14, 0.618) - 1) / math.pow(50, math.pow(len / 14, 0.618) - 1) + 50
rsiadvanced = if rsi > 50
f + 50
else
-f + 50
rsiadvanced
rsiha = 100 - 100 / (1 + ruh / rdh)
rsila = 100 - 100 / (1 + rul / rdl)
rsia = ta.rsi(rsrc, len)
rsih = if ad
function(rsiha, len)
else
rsiha
rsil = if ad
function(rsila, len)
else
rsila
// rsi bought & sold zone
plot_bands = true
reb = hline(plot_bands ? 70 : na, 'Extreme Bought', color.new(#b2b5be, 50), linewidth=4, linestyle=hline.style_solid)
rmb = hline(plot_bands ? 50 : na, 'Middle Line', color.new(#fbc02d, 80), linewidth=4, linestyle=hline.style_solid)
res = hline(plot_bands ? 30 : na, 'Extreme Sold', color.new(#b2b5be, 50), linewidth=4, linestyle=hline.style_solid)
// candle
plotcandle(rsi[1], rsih, rsil, rsi, 'RSI_Candle', color=ta.change(rsi) > 0 ? #ffffff : #000000, wickcolor=#000000, bordercolor=#2a2e39)
plot(rsi, 'RSI_Line', color= ta.change(rsi) > 0 ? color.black : color.black, display=display.none, linewidth=2)
// linear regression
// input
lrg = 'Linear Regression'
linreg = input(true, 'Linear Regression On / Off')
periodTrend = input.int(100, 'Trend Period', minval=4, group=lrg)
deviationsAmnt = input.float(2, 'Deviation', minval=0.1, step=0.1, group=lrg)
estimatorType = input.string('Unbiased', 'Estimator', options=['Biased', 'Unbiased'], group=lrg)
var extendType = input.string('Right', 'Extend', options=['Right', 'Segment'], group=lrg) == 'Right' ? extend.right : extend.none
// drawline configuration
drawLine(X1, Y1, X2, Y2, ExtendType, Color, LineStyle) =>
var line Line = na
Line := linreg ? line.new(X1, Y1, X2, Y2, xloc.bar_index, ExtendType, Color, LineStyle, width=2) : na
line.delete(Line[1])
rsdcr2(PeriodMinusOne, Deviations, Estimate) =>
var period = PeriodMinusOne + 1
var devDenominator = Estimate == 'Unbiased' ? PeriodMinusOne : period
Ex = 0.0
Ex2 = 0.0
Exy = 0.0
Ey = 0.0
for i = 0 to PeriodMinusOne by 1
closeI = nz(rsi[i])
Ex := Ex + i
Ex2 := Ex2 + i * i
Exy := Exy + closeI * i
Ey := Ey + closeI
Ey
ExEx = Ex * Ex
slope = Ex2 == ExEx ? 0.0 : (period * Exy - Ex * Ey) / (period * Ex2 - ExEx)
linearRegression = (Ey - slope * Ex) / period
intercept = linearRegression + bar_index * slope
deviation = 0.0
for i = 0 to PeriodMinusOne by 1
deviation := deviation + math.pow(nz(rsi[i]) - (intercept - bar_index[i] * slope), 2.0)
deviation
deviation := Deviations * math.sqrt(deviation / devDenominator)
correlate = ta.correlation(rsi, bar_index, period)
r2 = math.pow(correlate, 2.0)
[linearRegression, slope, deviation, correlate, r2]
periodMinusOne = periodTrend - 1
[linReg, slope, deviation, correlate, r2] = rsdcr2(periodMinusOne, deviationsAmnt, estimatorType)
endPointBar = bar_index - periodTrend + 1
endPointY = linReg + slope * periodMinusOne
// drawline plot
drawLine(endPointBar, endPointY + deviation, bar_index, linReg + deviation, extendType, #e91e63, line.style_solid)
drawLine(endPointBar, endPointY, bar_index, linReg, extendType, #e91e63, line.style_dotted)
drawLine(endPointBar, endPointY - deviation, bar_index, linReg - deviation, extendType, #e91e63, line.style_solid) |
G_EMA's | https://www.tradingview.com/script/Kkfc5vvq-G-EMA-s/ | SHNVH_ASTA | https://www.tradingview.com/u/SHNVH_ASTA/ | 3 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Amit Lulla
//@version=5
indicator("EMA's", overlay=true)
Length1 = input.int(title="EMA1", defval=5, options=[5,13,26,50,100,200], inline="EMA1")
bool1 = input.bool(true, "EMA1", inline="EMA1")
Length2 = input.int(title="EMA2", defval=13, options=[5,13,26,50,100,200], inline="EMA2")
bool2 = input.bool(true, "EMA2", inline="EMA2")
Length3 = input.int(title="EMA3", defval=26, options=[5,13,26,50,100,200], inline="EMA3")
bool3 = input.bool(true, "EMA3", inline="EMA3")
Length4 = input.int(title="EMA4", defval=50, options=[5,13,26,50,100,200], inline="EMA4")
bool4 = input.bool(true, "EMA4", inline="EMA4")
Length5 = input.int(title="EMA5", defval=100, options=[5,13,26,50,100,200], inline="EMA5")
bool5 = input.bool(true, "EMA5", inline="EMA5")
Length6 = input.int(title="EMA6", defval=200, options=[5,13,26,50,100,200], inline="EMA6")
bool6 = input.bool(true, "EMA6", inline="EMA6")
xPrice = close
xEMA1 = ta.ema(xPrice, Length1)
xEMA2 = ta.ema(xPrice, Length2)
xEMA3 = ta.ema(xPrice, Length3)
xEMA4 = ta.ema(xPrice, Length4)
xEMA5 = ta.ema(xPrice, Length5)
xEMA6 = ta.ema(xPrice, Length6)
plot(bool1? xEMA1: na, color=color.red, title="EMA 5")
plot(bool2? xEMA2: na, color=color.green, title="EMA 13")
plot(bool3? xEMA3: na, color=color.yellow, title="EMA 26")
plot(bool4? xEMA4: na, color=color.purple, linewidth=2, title="EMA 50")
plot(bool5? xEMA5: na, color=color.orange, linewidth=2, title="EMA 100")
plot(bool6? xEMA6: na, color=color.blue, linewidth=3, title="EMA 200")
|
50HCL by Pankaj | https://www.tradingview.com/script/3FnvQBbh-50HCL-by-Pankaj/ | Bull_Bros | https://www.tradingview.com/u/Bull_Bros/ | 28 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © cool.panku01
//@version=5
indicator("50HCL", overlay=true)
H1= ta.ema(high, 50)
C1= ta.ema(close, 50)
L1= ta.ema(low, 50)
plot(H1, title="50H",color=color.green, linewidth= 2)
plot(C1, title="50C", color=color.blue, linewidth=2)
plot(L1,title="50L" , color=color.red, linewidth=2)
|
MAIndicator | https://www.tradingview.com/script/KOOorovx-MAIndicator/ | alphagxmarkets | https://www.tradingview.com/u/alphagxmarkets/ | 31 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © alphagxmarkets
//@version=5
indicator(title='MAIndicator', overlay=true)
shortMA = input.int(30, "Short EMA", minval = 1)
longMA = input.int(54, "Long EMA", minval = 1)
shortEMA = ta.ema(close,shortMA)
longEMA = ta.ema(close,longMA)
plot(shortEMA, "short EMA", color = color.green, linewidth = 3)
plot(longEMA, "long EMA", color = color.red, linewidth = 3)
plotBuy = ta.crossover(shortEMA, longEMA)
plotSell = ta.crossunder(shortEMA, longEMA)
plotshape(plotSell, title="Sell", text="Sell", location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.red, textcolor=color.white)
plotshape(plotBuy, title="Buy", text="Buy", location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.green, textcolor=color.white) |
PnL and Buy & Hold Tracker | https://www.tradingview.com/script/9Vm2Zvp9-PnL-and-Buy-Hold-Tracker/ | Fedra_Algotrading | https://www.tradingview.com/u/Fedra_Algotrading/ | 171 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Fedra_Algotrading
//@version=5
indicator('PnL Tracker', 'PnL Tracker 2.5', overlay = true, format=format.price, precision=2, max_labels_count=500)
/////////Source and lenght of the MAs
MAsource = input.source(close, title= "MAs Source", group='MA Settings')
emaLength = input.int(title='Fast MA Length', defval=20, group='MA Settings')
emaLength2 = input.int(title='Slow MA Length', defval=100, step=10, group='MA Settings')
///////Set variables
var totalPnl = 0.0 //This variable will store the cumulative PnL
var hold = 0.0 // This variable will store the price of the firs BUY signal
var tradecloseprice = 0.0// this variable will store the opening price of a trade
var pnlPos = 0
var pnlNeg = 0
var totalTrades = 0
winratio = pnlPos/pnlNeg
byh = (((close-hold)/hold)*100)// Buy & Hold calculation
//////////Set MA type
string i_maType = input.string("SMA", "Fast MA type", options = ["SMA","EMA", "RMA", "WMA","HMA", "CHANGE","CMO","COG","DEV","HIGHEST","LOWEST","MEDIAN","MOM","RANGE","STDEV","VARIANCE"], group='MA Settings to determine downtrend (BUY & SELL)')
float ma = switch i_maType
"SMA" => ta.sma(MAsource, emaLength)
"EMA" => ta.ema(MAsource, emaLength)
"RMA" => ta.rma(MAsource, emaLength)
"HMA" => ta.hma(MAsource, emaLength)
"CHANGE" => ta.change(MAsource, emaLength)
"CMO" => ta.cmo(MAsource, emaLength)
"COG" => ta.cog(MAsource, emaLength)
"DEV" => ta.dev(MAsource, emaLength)
"HIGHEST" => ta.highest(MAsource, emaLength)
"LOWEST" => ta.lowest(MAsource, emaLength)
"MEDIAN" => ta.median(MAsource, emaLength)
"MOM" => ta.mom(MAsource, emaLength)
"RANGE" => ta.range(MAsource, emaLength)
"STDEV" => ta.stdev(MAsource, emaLength)
"VARIANCE" => ta.variance(MAsource, emaLength)
// Default used when the three first cases do not match.
=> ta.wma(MAsource, emaLength)
string i_maType2 = input.string("SMA", "Slow MA type", options = ["SMA","EMA","RMA", "WMA","HMA", "CHANGE", "CMO","COG","DEV","HIGHEST","LOWEST","MEDIAN", "MOM","RANGE","STDEV","VARIANCE"], group='MA Settings to determine downtrend (BUY & SELL)')
float ma2 = switch i_maType2
"SMA" => ta.sma(MAsource, emaLength2)
"EMA" => ta.ema(MAsource, emaLength2)
"RMA" => ta.rma(MAsource, emaLength2)
"HMA" => ta.hma(MAsource, emaLength2)
"CHANGE" => ta.change(MAsource, emaLength2)
"CMO" => ta.cmo(MAsource, emaLength2)
"COG" => ta.cog(MAsource, emaLength2)
"DEV" => ta.dev(MAsource, emaLength2)
"HIGHEST" => ta.highest(MAsource, emaLength2)
"LOWEST" => ta.lowest(MAsource, emaLength2)
"MEDIAN" => ta.median(MAsource, emaLength2)
"MOM" => ta.mom(MAsource, emaLength2)
"RANGE" => ta.range(MAsource, emaLength2)
"STDEV" => ta.stdev(MAsource, emaLength2)
"VARIANCE" => ta.variance(MAsource, emaLength2)
// Default used when the three first cases do not match.
=> ta.wma(MAsource, emaLength2)
///Set BUY crossover
EMAbuy = ta.crossover(ma,ma2)
///Set SELL crossover
EMAsell = ta.crossunder(ma,ma2)
////Plot the MAs
line1 = plot(ma, linewidth=2, color=color.new(color.yellow, 0))
line2 = plot(ma2, linewidth=2, color=color.new(color.blue, 0))
fill(line1, line2, color = ma > ma2 ? color.green : color.red, transp=85)
///Set variables to track satus of an operation
var S_sell = false
var S_buy = false
///////Set BUY and SELL conditions (crossover + operation open/closed)
buyalert = not S_sell and EMAbuy
sellalert = not S_buy and EMAsell
////Track the unrealized PnL
if close > 0 and not S_buy
tplabel = label.new(x=bar_index[0], y=high[0]+high[0]*0.02, color=color.gray, textcolor=color.white, style=label.style_label_down, text='Unr.PnL: ' + str.tostring(((close-tradecloseprice)/tradecloseprice)*100)+'%')
tplabel
label.delete(tplabel[1])
////Plot Buy Label with the opening price, store the opening price in a variable and change the trade position to open
if buyalert
buylabel = label.new(x=bar_index, y=low[0] - low[0]*0.02, color=color.blue, textcolor=color.white, style=label.style_label_up, text='BUY :' + str.tostring(close))
buylabel
tradecloseprice := close
S_sell := true
S_buy := false
//////////Store the price of the first trade
if totalPnl == 0.0
hold := close
////Plot Buy Label with the PnL of a trade, and change the trade position to flat
if sellalert and tradecloseprice != 0.0
sell_label = label.new(x=bar_index[0], y=high[0] + high[0] * 0.02, color=color.green, textcolor=color.white, style=label.style_label_down, text='PnL: ' + str.tostring(((close-tradecloseprice)/tradecloseprice)*100)+'%')
sell_label
S_sell := false
S_buy := true
pnl = (((close-tradecloseprice)/tradecloseprice)*100)
totalTrades := totalTrades +1//Adding to the total closed trades counter
if pnl >= tradecloseprice
pnlPos := pnlPos +1//Adding to the positive trades counter
else
pnlNeg := pnlNeg +1//Adding to the negative trades counter
//Change the color of the closing label to green if is a win or red if is a loose
if pnl > tradecloseprice
label.set_color(sell_label, color= color.green)
else
label.set_color(sell_label, color= color.red)
totalPnl := totalPnl + pnl ///Add the PnL of the last trade to the cumulative PnL
var pnlTable = table.new(position = position.top_right, columns = 4, rows = 2, border_color = color.white, border_width = 1) ///Define the table
table.cell(table_id = pnlTable, column = 0, row = 0, bgcolor = color.gray, text_color = color.white, text = "Closed Trades")
table.cell(table_id = pnlTable, column = 1, row = 0, bgcolor = color.green, text_color = color.white, text = "Profit Factor")
table.cell(table_id = pnlTable, column = 2, row = 0, bgcolor = color.gray, text_color = color.white, text = "Cumulative PnL")
table.cell(table_id = pnlTable, column = 3, row = 0, bgcolor = color.gray, text_color = color.white, text = "Buy & Hold")
table.cell(table_id = pnlTable, column = 0, row = 1, bgcolor = color.gray, text = str.tostring(totalTrades))
table.cell(table_id = pnlTable, column = 1, row = 1, bgcolor = color.gray, text_color = color.yellow, text = str.tostring(winratio))
table.cell(table_id = pnlTable, column = 2, row = 1, bgcolor = color.gray, text = str.tostring(totalPnl)+'%')
table.cell(table_id = pnlTable, column = 3, row = 1, bgcolor = color.gray, text_color = color.yellow, text = str.tostring(byh)+'%')
///Change the PnL cell color to green if its positive or red if its negative
if totalPnl > 0
table.cell_set_bgcolor(pnlTable, column = 2, row = 1, bgcolor = color.green)
else
table.cell_set_bgcolor(pnlTable, column = 2, row = 1, bgcolor = color.red)
if winratio > 1
table.cell_set_bgcolor(pnlTable, column = 1, row = 1, bgcolor = color.green)
else
table.cell_set_bgcolor(pnlTable, column = 1, row = 1, bgcolor = color.red)
|
Cycles | https://www.tradingview.com/script/9P8HFYc3-Cycles/ | csmottola71 | https://www.tradingview.com/u/csmottola71/ | 123 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © csmottola71
//@version=4
study("Cycles")
cycle=input(title="Cycle Days", type=input.integer, step=1, defval=55)
l = lowest(low,cycle)
lSince = barssince(l < l[1])
h = highest(high,cycle)
hSince = barssince(h > h[1])
linea=0-(hSince-lSince)
bgCol = linea > linea[1] ? color.green : linea < linea[1] ? color.yellow : color.white
bgcolor(color.new(bgCol,65))
//plot(lSince, color=color.red)
//plot(hSince, color=color.blue)
plot(linea, color= linea > 0 ? color.blue : color.red)
|
[Nekonyam] Auto Select Currency Binance Open Interest | https://www.tradingview.com/script/3WK5lR8J-Nekonyam-Auto-Select-Currency-Binance-Open-Interest/ | Nekonyam | https://www.tradingview.com/u/Nekonyam/ | 219 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Nekonyam
//@version=5
indicator(title='Binance Open Interest Auto Select Currency[Nekonyam]', shorttitle='Open Interest',format = format.volume)
//Input settings.
chart_type = input.string(title="Chart Type", defval="Candle", options=["Candle","Line","Histogram"])
coin = input.string(title="Tether/Coin Margin's OI", defval="Tether", options=["Tether","Coin"])
isOverride = input(defval=false, title='Enable override symbol')
overrideSymbol = input.string(title='Override symbol', defval="BTC")
notshow = input(defval=false, title='Do not display messages when something happens',tooltip="For example, a message that you had set up a Coin margin OI and couldn't find it, so changed it to a Tether margin OI. Or, the message when no OI is found will no longer be displayed.")
line_color = input.color(color.blue, "Line color")
Histogram_up_color = input.color(color.new(#26A69A,0), "Histogram up color")
Histogram_down_color = input.color(color.new(#EF5350,0), "Histogram down color")
candle_up_color = input.color(color.new(#26A69A,0), "Candle up color")
candle_down_color = input.color(color.new(#EF5350,0), "Candle down color")
candle_wickcolor = input.color(color.gray, "Candle wick color")
candle_bordercolor = input.color(color.gray, "Candle border color")
show_title=input.bool(defval=true,title="Show title")
title_position = input.string(title='Title position', defval=position.bottom_left, options=[position.bottom_center, position.bottom_left, position.bottom_right, position.middle_center, position.middle_left, position.middle_right, position.top_center, position.top_left, position.top_right])
title_size = input.string(title='Title Size', defval=size.normal, options=[size.auto, size.tiny, size.small, size.normal, size.large, size.huge])
title_bakcol = input.color(color.white, "Title Background Color")
title_txtcol = input.color(color.black, "Title Text Color")
//Input open intarest.
o_c_open = request.security("BINANCE:"+overrideSymbol+"PERP_OI", timeframe.period, open,ignore_invalid_symbol=true)
o_c_high = request.security("BINANCE:"+overrideSymbol+"PERP_OI", timeframe.period, high,ignore_invalid_symbol=true)
o_c_low = request.security("BINANCE:"+overrideSymbol+"PERP_OI", timeframe.period, low,ignore_invalid_symbol=true)
o_c_close = request.security("BINANCE:"+overrideSymbol+"PERP_OI", timeframe.period, close,ignore_invalid_symbol=true)
o_t_open = request.security("BINANCE:"+overrideSymbol+"USDTPERP_OI", timeframe.period, open,ignore_invalid_symbol=true)
o_t_high = request.security("BINANCE:"+overrideSymbol+"USDTPERP_OI", timeframe.period, high,ignore_invalid_symbol=true)
o_t_low = request.security("BINANCE:"+overrideSymbol+"USDTPERP_OI", timeframe.period, low,ignore_invalid_symbol=true)
o_t_close = request.security("BINANCE:"+overrideSymbol+"USDTPERP_OI", timeframe.period, close,ignore_invalid_symbol=true)
c_open = request.security("BINANCE:"+syminfo.basecurrency+"PERP_OI", timeframe.period, open,ignore_invalid_symbol=true)
c_high = request.security("BINANCE:"+syminfo.basecurrency+"PERP_OI", timeframe.period, high,ignore_invalid_symbol=true)
c_low = request.security("BINANCE:"+syminfo.basecurrency+"PERP_OI", timeframe.period, low,ignore_invalid_symbol=true)
c_close = request.security("BINANCE:"+syminfo.basecurrency+"PERP_OI", timeframe.period, close,ignore_invalid_symbol=true)
t_open =request.security("BINANCE:"+syminfo.basecurrency+"USDTPERP_OI", timeframe.period, open,ignore_invalid_symbol=true)
t_high =request.security("BINANCE:"+syminfo.basecurrency+"USDTPERP_OI", timeframe.period, high,ignore_invalid_symbol=true)
t_low =request.security("BINANCE:"+syminfo.basecurrency+"USDTPERP_OI", timeframe.period, low,ignore_invalid_symbol=true)
t_close =request.security("BINANCE:"+syminfo.basecurrency+"USDTPERP_OI", timeframe.period, close,ignore_invalid_symbol=true)
s_open=0.0
s_high=0.0
s_low=0.0
s_close=0.0
isError=0
//Assign to variable for chart display.
if isOverride==true
if coin=="Coin"
s_open:=o_c_open
s_high:=o_c_high
s_low:=o_c_low
s_close:=o_c_close
//Error detection.
if na(s_open)
isError:=1
else
s_open:=o_t_open
s_high:=o_t_high
s_low:=o_t_low
s_close:=o_t_close
if na(s_open)
isError:=2
else
if coin=="Coin"
s_open:=c_open
s_high:=c_high
s_low:=c_low
s_close:=c_close
if na(s_open)
isError:=3
else
s_open:=t_open
s_high:=t_high
s_low:=t_low
s_close:=t_close
if na(s_open)
isError:=4
if syminfo.basecurrency=="" and na(s_open)
if not(isError==1 or isError==2)
isError:=5
//Identify the type of error and change the message.
errorMessageOne=""
overrideSymbolShowText=overrideSymbol
oiName=isOverride==true?(str.upper(overrideSymbolShowText)+" / "):(syminfo.basecurrency+" / ")
//When both OI's of the overridden symbol are not provided.
if (isError==1 or isError==2) and na(o_c_open)==true and na(o_t_open)==true
if str.length(overrideSymbol)>7
overrideSymbolShowText:=str.substring(overrideSymbol,0,8)+"..."
if overrideSymbolShowText==""
errorMessageOne:="The override symbol is blank."
oiName:=""
else
errorMessageOne:=" / This overridden\nsymbol's OI not found."
//When a coin margin override is used and only tether margin is provided.
if isError==1 and na(o_t_open)==false
errorMessageOne:="/ Coin OI not found.\nChanged to Tether OI."
coin:="Tether"
s_open:=o_t_open
s_high:=o_t_high
s_low:=o_t_low
s_close:=o_t_close
//When a tether margin override is used and only coin margin is provided.
if isError==2 and na(o_c_open)==false
errorMessageOne:="/ Tether OI not found.\nChanged to Coin OI."
coin:="Coin"
s_open:=o_c_open
s_high:=o_c_high
s_low:=o_c_low
s_close:=o_c_close
//When no override is used and OI for both margins is not provided.
if (isError==3 or isError==4) and na(c_open)==true and na(t_open)==true
errorMessageOne:=" / This symbol's\nOI not found."
//When no override is used and only tether margin is provided.
if isError==3 and na(t_open)==false
errorMessageOne:="/ Coin OI not found.\nChanged to Tether OI."
coin:="Tether"
s_open:=t_open
s_high:=t_high
s_low:=t_low
s_close:=t_close
//When no override is used and only coin margin is provided
if isError==4 and na(c_open)==false
errorMessageOne:="/ Tether OI not found.\nChanged to Coin OI."
coin:="Coin"
s_open:=c_open
s_high:=c_high
s_low:=c_low
s_close:=c_close
//When a symbol that is not supported at all is displayed on the main chart.
if isError==5
oiName:=""
errorMessageOne:="This symbol's OI\nis not available."
//Symbol and margin type display, error indication.
var table1 = table.new(position=title_position, columns=1, rows=4, bgcolor=title_bakcol, frame_color=color.black, frame_width=1, border_color=color.black, border_width=1)
if (barstate.islast and show_title) or (barstate.islast and isError>0)
if isError==0
table.cell(table_id=table1, column=0, row=0, text=oiName+coin, text_color=title_txtcol, text_size=title_size)
if isError>0
table.cell(table_id=table1, column=0, row=0, text=notshow==true?oiName+coin:oiName+coin+errorMessageOne, text_color=color.new(color.black,0), text_size=title_size)
//Adjusting Coin Margin Volume
if coin == "Coin"
Mult = 0
if syminfo.basecurrency == "BTC" or syminfo.basecurrency == "XBT"
Mult := 100
else
Mult := 10
s_open *=Mult
s_high *=Mult
s_low *=Mult
s_close *=Mult
//Plots
plotcandle(chart_type=="Candle" ? s_open : na, chart_type=="Candle"? s_high : na, chart_type=="Candle"? s_low : na, chart_type=="Candle"? s_close : na, color=s_open > s_close ? candle_down_color : candle_up_color, wickcolor=candle_wickcolor, bordercolor=candle_bordercolor)
plot(chart_type=="Line" ? s_close : na, title='Line Chart',color=line_color)
plot(chart_type=="Histogram" and s_close-s_close[1]>0? s_close-s_close[1] : na, title='Line Chart',color=Histogram_up_color,style = plot.style_columns)
plot(chart_type=="Histogram" and s_close-s_close[1]<0? s_close-s_close[1] : na, title='Line Chart',color=Histogram_down_color,style = plot.style_columns)
|
MACD Support Resistance | https://www.tradingview.com/script/fCy98tQH-MACD-Support-Resistance/ | venkatachari_n | https://www.tradingview.com/u/venkatachari_n/ | 61 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © VenkatNarayanan
//@version=5
indicator('MACD Support Resistance', overlay=true)
haTicker = ticker.heikinashi(syminfo.tickerid)
haClose = request.security(haTicker, timeframe.period, close)
haOpen = request.security(haTicker, timeframe.period, open)
haHigh = request.security(haTicker, timeframe.period, high)
haLow = request.security(haTicker, timeframe.period, low)
//MACD
fast_length = input(title="Fast Length", defval=12, group="MACD")
slow_length = input(title="Slow Length", defval=26, group="MACD")
src = haClose
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9, group="MACD")
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"], group="MACD")
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"], group="MACD")
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
//SMMA
smmalen = input.int(7, minval=1, title="SMMA Length", group="SMMA")
smmasrc = input(close, title="SMMA Source", group="SMMA")
smma = 0.0
_sma = ta.sma(smmasrc, smmalen)
smma := na(smma[1]) ? _sma : (smma[1] * (smmalen - 1) + smmasrc) / smmalen
plot(smma, title="SMMA", color=color.blue, linewidth=1)
//LSMA
lsmalength = input(title="LSMA Length", defval=25, group="LSMA")
lsmaoffset = input(title="LSMA Offset", defval=0, group="LSMA")
lsmasrc = input(close, title="LSMA Source", group="LSMA")
lsma = ta.linreg(lsmasrc, lsmalength, lsmaoffset)
plot(lsma, title="LSMA", color=color.yellow, linewidth=1)
//Calculation Resistance and Support using MACD Cross
lookback = input(title='Candle Lookback', defval=11, group="Support & Resistance")
var previoushigh = float(na)
var previouslow = float(na)
lookbackhigh = ta.highest(haHigh, lookback)
if ta.crossunder(macd,signal)
previoushigh := lookbackhigh
lookbacklow = ta.lowest(low, lookback)
if ta.crossunder(signal,macd)
previouslow := lookbacklow
lookbackavg = math.avg(previoushigh, previouslow)
plot(previoushigh, title="Resistance", color=color.red, linewidth=2)
plot(previouslow, title="Support", color=color.green, linewidth=2)
plot(lookbackavg, title='Average Resistance and Support', color=color.new(color.orange, 0), linewidth=2)
|
Interest Rates | USA / EU / UK | https://www.tradingview.com/script/NUbpGm4t/ | Realmix_mit_Soda | https://www.tradingview.com/u/Realmix_mit_Soda/ | 28 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Realmix_mit_Soda
//@version=5
indicator('Interest Rates', shorttitle='IR')
var inSym1 = input.symbol('ECONOMICS:USINTR', title='US Interest Rates')
var inSym2 = input.symbol('ECONOMICS:EUINTR', title='EU Interest Rates')
var inSym3 = input.symbol('ECONOMICS:GBINTR', title='UK Interest Rates')
var inLen = input.int(1, title='MA(Length)', minval=1, maxval=400)
inSrc = input(close, title='Source')
sym1 = request.security(inSym1, '', inSrc)
sym2 = request.security(inSym2, '', inSrc)
sym3 = request.security(inSym3, '', inSrc)
symMa1 = ta.sma(sym1, inLen)
symMa2 = ta.sma(sym2, inLen)
symMa3 = ta.sma(sym3, inLen)
plot(symMa1, 'US Interest Rates', color=color.new(color.red, 0))
plot(symMa2, 'EU Interest Rates', color=color.new(color.blue, 0))
plot(symMa3, 'UK Interest Rates', color=color.new(color.white, 0))
|
Stock Cumulative Percent Change | https://www.tradingview.com/script/E3jZikbH-Stock-Cumulative-Percent-Change/ | aaronmefford | https://www.tradingview.com/u/aaronmefford/ | 15 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SlinginTrades modified from @ connorwinemil
//@version=5
indicator("Stock Cumulative Percent Change", timeframe='', timeframe_gaps=false, overlay=false)
tf = timeframe.period
//tf = input.timeframe('', "TimeFrame", options=['','1','5','15','30','60','120','D','W','M'])
ma_period = input.int(5,"MA Period")
openTime = input.session("0930-0935", "Open time")
closeTime = input.session("1600-2400", "Close time")
premarketTime = input.session("0000-0930", "PreMarket time")
// Returns non 'na' value when in session.
trigger = not na(time(timeframe.period, openTime))
trigger2 = not na(time(timeframe.period, closeTime))
trigger3 = not na(time(timeframe.period, premarketTime))
// Detect when reset time is hit.
reset = (trigger and not trigger[1]) or (trigger2) or trigger3
stock1 = input.symbol(defval="AAPL", title="Symbol 1")
stock2 = input.symbol(defval="MSFT", title="Symbol 2")
stock3 = input.symbol(defval="AMZN", title="Symbol 3")
stock4 = input.symbol(defval="TSLA", title="Symbol 4")
stock5 = input.symbol(defval="GOOGL", title="Symbol 5")
stock6 = input.symbol(defval="NVDA", title="Symbol 6")
stock7 = input.symbol(defval="MSFT", title="Symbol 7")
stock1_pctchange = ((request.security(stock1, tf, close)/request.security(stock1, tf, close[1]))-1)*100
stock2_pctchange = ((request.security(stock2, tf, close)/request.security(stock2, tf, close[1]))-1)*100
stock3_pctchange = ((request.security(stock3, tf, close)/request.security(stock3, tf, close[1]))-1)*100
stock4_pctchange = ((request.security(stock4, tf, close)/request.security(stock4, tf, close[1]))-1)*100
stock5_pctchange = ((request.security(stock5, tf, close)/request.security(stock5, tf, close[1]))-1)*100
stock6_pctchange = ((request.security(stock6, tf, close)/request.security(stock6, tf, close[1]))-1)*100
stock7_pctchange = ((request.security(stock7, tf, close)/request.security(stock7, tf, close[1]))-1)*100
cum = 0.0
val = math.avg(2 * stock1_pctchange,stock2_pctchange,stock3_pctchange,stock4_pctchange,stock5_pctchange,stock6_pctchange,stock7_pctchange)
cum := reset ? 0 : cum[1] + val
ma = ta.sma(cum,ma_period)
plot(cum, color=cum>0 ? cum > cum[1]? color.green: color.yellow:cum< cum[1]?color.red:color.yellow, style=plot.style_columns)
plot(ma,color=ma > 0? color.green:color.red)
alertcondition(ta.crossover(ma,0),title="Momentum Shift Up", message="Momentum Over 0")
alertcondition(ta.crossunder(ma,0),title="Momentum Shift Down", message="Momentum Under 0")
|
SnakeBand | https://www.tradingview.com/script/aCiWB5cq/ | mizarkim | https://www.tradingview.com/u/mizarkim/ | 107 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
//
//
// © mizarkim
//
//
// Introduce indicators: https://tradingview.com/u/mizarkim/
//
//
//@version=5
indicator(title="SnakeBand", shorttitle="SnakeBand", overlay=true)
upperBand = (ta.highest(52)-ta.lowest(52)) * 0.786 + ta.highest(52)
lowerBand = (ta.lowest(26)-ta.highest(26)) * 0.786 + ta.lowest(26)
p1 = plot(upperBand, offset = 25 , color=#c2185b, linewidth=1, title="Upper Band")
p2 = plot(lowerBand, offset = 25 , color=#59ac59, linewidth=1, title="Lower Band")
|
volume oscillator nest | https://www.tradingview.com/script/l1D0ivRj-volume-oscillator-nest/ | pratikpatel322 | https://www.tradingview.com/u/pratikpatel322/ | 3 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © pratikpatel322
//@version=4
study("volume oscillator nest")
voc = ema(volume,5)-ema(volume,21)
plot(series=voc, style=plot.style_histogram)
|
[_ParkF]RSI (+ichimoku cloud) | https://www.tradingview.com/script/9u7BHNxe/ | ParkF | https://www.tradingview.com/u/ParkF/ | 560 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ParkF
//@version=5
indicator('[_ParkF]RSI (+Ichimoku Cloud)', overlay=false, max_bars_back=1500)
// rsi divergence
// input
rsig = 'RSI'
rb = input(2, 'How many Right Bars for Pivots', group=rsig)
lb = input(15, 'How many Left Bars for Pivots', group=rsig)
sph = input(close, 'Pivot source for Bear Divs', group=rsig)
spl = input(close, 'Pivots Source for Bull Divs', group=rsig)
len = input.int(14, ' RSI Length', minval=1, group=rsig)
lvl = input.int(5, 'Lookback Level for Divs', options=[1, 2, 3, 4, 5], group=rsig)
// pivot
ph = ta.pivothigh(sph, lb, rb)
pl = ta.pivotlow(spl, lb, rb)
hi0 = ta.valuewhen(ph, sph[rb], 0)
hi1 = ta.valuewhen(ph, sph[rb], 1)
hi2 = ta.valuewhen(ph, sph[rb], 2)
hi3 = ta.valuewhen(ph, sph[rb], 3)
hi4 = ta.valuewhen(ph, sph[rb], 4)
hi5 = ta.valuewhen(ph, sph[rb], 5)
lo0 = ta.valuewhen(pl, spl[rb], 0)
lo1 = ta.valuewhen(pl, spl[rb], 1)
lo2 = ta.valuewhen(pl, spl[rb], 2)
lo3 = ta.valuewhen(pl, spl[rb], 3)
lo4 = ta.valuewhen(pl, spl[rb], 4)
lo5 = ta.valuewhen(pl, spl[rb], 5)
lox0 = ta.valuewhen(pl, bar_index[rb], 0)
lox1 = ta.valuewhen(pl, bar_index[rb], 1)
lox2 = ta.valuewhen(pl, bar_index[rb], 2)
lox3 = ta.valuewhen(pl, bar_index[rb], 3)
lox4 = ta.valuewhen(pl, bar_index[rb], 4)
lox5 = ta.valuewhen(pl, bar_index[rb], 5)
hix0 = ta.valuewhen(ph, bar_index[rb], 0)
hix1 = ta.valuewhen(ph, bar_index[rb], 1)
hix2 = ta.valuewhen(ph, bar_index[rb], 2)
hix3 = ta.valuewhen(ph, bar_index[rb], 3)
hix4 = ta.valuewhen(ph, bar_index[rb], 4)
hix5 = ta.valuewhen(ph, bar_index[rb], 5)
rsi = ta.rsi(close, len)
rh0 = ta.valuewhen(ph, rsi[rb], 0)
rh1 = ta.valuewhen(ph, rsi[rb], 1)
rh2 = ta.valuewhen(ph, rsi[rb], 2)
rh3 = ta.valuewhen(ph, rsi[rb], 3)
rh4 = ta.valuewhen(ph, rsi[rb], 4)
rh5 = ta.valuewhen(ph, rsi[rb], 5)
rl0 = ta.valuewhen(pl, rsi[rb], 0)
rl1 = ta.valuewhen(pl, rsi[rb], 1)
rl2 = ta.valuewhen(pl, rsi[rb], 2)
rl3 = ta.valuewhen(pl, rsi[rb], 3)
rl4 = ta.valuewhen(pl, rsi[rb], 4)
rl5 = ta.valuewhen(pl, rsi[rb], 5)
// bull & bear divergence logic
bull_div_1= lo0<lo1
and rl1<rl0
bull_div_2= lo0<lo1 and lo0<lo2
and rl2<rl0 and rl2<rl1 and lvl>=2
bull_div_3= lo0<lo1 and lo0<lo2 and lo0<lo3
and rl3<rl0 and rl3<rl1 and rl3<rl2 and lvl>=3
bull_div_4= lo0<lo1 and lo0<lo2 and lo0<lo3 and lo0<lo4
and rl4<rl0 and rl4<rl1 and rl4<rl2 and rl4<rl3 and lvl>=4
bull_div_5= lo0<lo1 and lo0<lo2 and lo0<lo3 and lo0<lo4 and lo0<lo5
and rl5<rl0 and rl5<rl1 and rl5<rl2 and rl5<rl3 and rl5<rl4 and lvl>=5
bear_div_1= hi0>hi1
and rh1>rh0
bear_div_2= hi0>hi1 and hi0>hi2
and rh2>rh0 and rh2>rh1 and lvl>=2
bear_div_3= hi0>hi1 and hi0>hi2 and hi0>hi3
and rh3>rh0 and rh3>rh1 and rh3>rh2 and lvl>=3
bear_div_4= hi0>hi1 and hi0>hi2 and hi0>hi3 and hi0>hi4
and rh4>rh0 and rh4>rh1 and rh4>rh2 and rh4>rh3 and lvl>=4
bear_div_5= hi0>hi1 and hi0>hi2 and hi0>hi3 and hi0>hi4 and hi0>hi5
and rh5>rh0 and rh5>rh1 and rh5>rh2 and rh5>rh3 and rh5>rh4 and lvl>=5
new_bull1= bull_div_1 and not bull_div_1[1]
new_bull2= bull_div_2 and not bull_div_2[1]
new_bull3= bull_div_3 and not bull_div_3[1]
new_bull4= bull_div_4 and not bull_div_4[1]
new_bull5= bull_div_5 and not bull_div_5[1]
new_bear1= bear_div_1 and not bear_div_1[1]
new_bear2= bear_div_2 and not bear_div_2[1]
new_bear3= bear_div_3 and not bear_div_3[1]
new_bear4= bear_div_4 and not bear_div_4[1]
new_bear5= bear_div_5 and not bear_div_5[1]
recall(x) =>
ta.barssince(not na(x))
// bull divergence line plot
rbull1 = line(na)
rbull1 := new_bull1 and not new_bull2 and not new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox1, rl1, color=#ff9800, width=2) : na
rbull2 = line(na)
rbull2 := new_bull2 and not new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox2, rl2, color=#ff9800, width=2) : na
rbull3 = line(na)
rbull3 := new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox3, rl3, color=#ff9800, width=2) : na
rbull4 = line(na)
rbull4 := new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox4, rl4, color=#ff9800, width=2) : na
rbull5 = line(na)
rbull5 := new_bull5 ? line.new(lox0, rl0, lox5, rl5, color=#ff9800, width=2) : na
xbull21 = ta.valuewhen(recall(rbull2) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull31 = ta.valuewhen(recall(rbull3) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull41 = ta.valuewhen(recall(rbull4) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull51 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull32 = ta.valuewhen(recall(rbull3) == 0, bar_index, 0) - ta.valuewhen(recall(rbull2) == 0, bar_index, 0)
xbull42 = ta.valuewhen(recall(rbull4) == 0, bar_index, 0) - ta.valuewhen(recall(rbull2) == 0, bar_index, 0)
xbull52 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull2) == 0, bar_index, 0)
xbull43 = ta.valuewhen(recall(rbull4) == 0, bar_index, 0) - ta.valuewhen(recall(rbull3) == 0, bar_index, 0)
xbull53 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull3) == 0, bar_index, 0)
xbull54 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull4) == 0, bar_index, 0)
if new_bull2 and lo2 == ta.valuewhen(new_bull1, lo1, 0) and xbull21 >= 0
line.delete(rbull1[xbull21])
if new_bull3 and lo3 == ta.valuewhen(new_bull1, lo1, 0) and xbull31 >= 0
line.delete(rbull1[xbull31])
if new_bull4 and lo4 == ta.valuewhen(new_bull1, lo1, 0) and xbull41 >= 0
line.delete(rbull1[xbull41])
if new_bull5 and lo5 == ta.valuewhen(new_bull1, lo1, 0) and xbull51 >= 0
line.delete(rbull1[xbull51])
if new_bull3 and lo3 == ta.valuewhen(new_bull2, lo2, 0) and xbull32 >= 0
line.delete(rbull2[xbull32])
if new_bull4 and lo4 == ta.valuewhen(new_bull2, lo2, 0) and xbull42 >= 0
line.delete(rbull2[xbull42])
if new_bull5 and lo5 == ta.valuewhen(new_bull2, lo2, 0) and xbull52 >= 0
line.delete(rbull2[xbull52])
if new_bull4 and lo4 == ta.valuewhen(new_bull3, lo3, 0) and xbull43 >= 0
line.delete(rbull3[xbull43])
if new_bull5 and lo5 == ta.valuewhen(new_bull3, lo3, 0) and xbull53 >= 0
line.delete(rbull3[xbull53])
if new_bull5 and lo5 == ta.valuewhen(new_bull4, lo4, 0) and xbull54 >= 0
line.delete(rbull4[xbull54])
// bear divergence line plot
rbear1 = line(na)
rbear1 := new_bear1 and not new_bear2 and not new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix1, rh1, color=#ff9800, width=2) : na
rbear2 = line(na)
rbear2 := new_bear2 and not new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix2, rh2, color=#ff9800, width=2) : na
rbear3 = line(na)
rbear3 := new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix3, rh3, color=#ff9800, width=2) : na
rbear4 = line(na)
rbear4 := new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix4, rh4, color=#ff9800, width=2) : na
rbear5 = line(na)
rbear5 := new_bear5 ? line.new(hix0, rh0, hix5, rh5, color=#ff9800, width=2) : na
xbear21 = ta.valuewhen(recall(rbear2) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear31 = ta.valuewhen(recall(rbear3) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear41 = ta.valuewhen(recall(rbear4) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear51 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear32 = ta.valuewhen(recall(rbear3) == 0, bar_index, 0) - ta.valuewhen(recall(rbear2) == 0, bar_index, 0)
xbear42 = ta.valuewhen(recall(rbear4) == 0, bar_index, 0) - ta.valuewhen(recall(rbear2) == 0, bar_index, 0)
xbear52 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear2) == 0, bar_index, 0)
xbear43 = ta.valuewhen(recall(rbear4) == 0, bar_index, 0) - ta.valuewhen(recall(rbear3) == 0, bar_index, 0)
xbear53 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear3) == 0, bar_index, 0)
xbear54 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear4) == 0, bar_index, 0)
if new_bear2 and hi2 == ta.valuewhen(new_bear1, hi1, 0) and xbear21 >= 0
line.delete(rbear1[xbear21])
if new_bear3 and hi3 == ta.valuewhen(new_bear1, hi1, 0) and xbear31 >= 0
line.delete(rbear1[xbear31])
if new_bear4 and hi4 == ta.valuewhen(new_bear1, hi1, 0) and xbear41 >= 0
line.delete(rbear1[xbear41])
if new_bear5 and hi5 == ta.valuewhen(new_bear1, hi1, 0) and xbear51 >= 0
line.delete(rbear1[xbear51])
if new_bear3 and hi3 == ta.valuewhen(new_bear2, hi2, 0) and xbear32 >= 0
line.delete(rbear2[xbear32])
if new_bear4 and hi4 == ta.valuewhen(new_bear2, hi2, 0) and xbear42 >= 0
line.delete(rbear2[xbear42])
if new_bear5 and hi5 == ta.valuewhen(new_bear2, hi2, 0) and xbear52 >= 0
line.delete(rbear2[xbear52])
if new_bear4 and hi4 == ta.valuewhen(new_bear3, hi3, 0) and xbear43 >= 0
line.delete(rbear3[xbear43])
if new_bear5 and hi5 == ta.valuewhen(new_bear3, hi3, 0) and xbear53 >= 0
line.delete(rbear3[xbear53])
if new_bear5 and hi5 == ta.valuewhen(new_bear4, hi4, 0) and xbear54 >= 0
line.delete(rbear4[xbear54])
plotshape(title='bull_div_1', series=new_bull1 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_2', series=new_bull2 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_3', series=new_bull3 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_4', series=new_bull4 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_5', series=new_bull5 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_1', series=new_bear1 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_2', series=new_bear2 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_3', series=new_bear3 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_4', series=new_bear4 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_5', series=new_bear5 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
// rsi candle (with wick)
// rsi configuration
rsrc = close
ad = true
// rsi function
pine_rsi(rsrc, len) =>
u = math.max(rsrc - rsrc[1], 0)
d = math.max(rsrc[1] - rsrc, 0)
rs = ta.rma(u, len) / ta.rma(d, len)
res = 100 - 100 / (1 + rs)
res
pine_rma(rsrc, length) =>
b = 1 / length
sum = 0.0
sum := na(sum[1]) ? ta.sma(rsrc, length) : b * rsrc + (1 - b) * nz(sum[1])
u = math.max(rsrc - rsrc[1], 0)
d = math.max(rsrc[1] - rsrc, 0)
b = 1 / len
ruh = b * math.max(high - close[1], 0) + (1 - b) * ta.rma(u, len)[1]
rdh = (1 - b) * ta.rma(d, len)[1]
rul = (1 - b) * ta.rma(u, len)[1]
rdl = b * math.max(close[1] - low, 0) + (1 - b) * ta.rma(d, len)[1]
function(rsi, len) =>
f = -math.pow(math.abs(math.abs(rsi - 50) - 50), 1 + math.pow(len / 14, 0.618) - 1) / math.pow(50, math.pow(len / 14, 0.618) - 1) + 50
rsiadvanced = if rsi > 50
f + 50
else
-f + 50
rsiadvanced
rsiha = 100 - 100 / (1 + ruh / rdh)
rsila = 100 - 100 / (1 + rul / rdl)
rsia = ta.rsi(rsrc, len)
rsih = if ad
function(rsiha, len)
else
rsiha
rsil = if ad
function(rsila, len)
else
rsila
// rsi bought & sold zone
plot_bands = true
reb = hline(plot_bands ? 70 : na, 'Extreme Bought', color.new(#b2b5be, 50), linewidth=4, linestyle=hline.style_solid)
rmb = hline(plot_bands ? 50 : na, 'Middle Line', color.new(#fbc02d, 80), linewidth=4, linestyle=hline.style_solid)
res = hline(plot_bands ? 30 : na, 'Extreme Sold', color.new(#b2b5be, 50), linewidth=4, linestyle=hline.style_solid)
// candle
plotcandle(rsi[1], rsih, rsil, rsi, 'RSI_Candle', color=ta.change(rsi) > 0 ? #ffffff : #000000, wickcolor=#000000, bordercolor=#2a2e39)
plot(rsi, 'RSI_Line', color= ta.change(rsi) > 0 ? color.black : color.black, display=display.none, linewidth=2)
// linear regression
// input
lrg = 'Linear Regression'
linreg = input(true, 'Linear Regression On / Off')
periodTrend = input.int(100, 'Trend Period', minval=4, group=lrg)
deviationsAmnt = input.float(2, 'Deviation', minval=0.1, step=0.1, group=lrg)
estimatorType = input.string('Unbiased', 'Estimator', options=['Biased', 'Unbiased'], group=lrg)
var extendType = input.string('Right', 'Extend', options=['Right', 'Segment'], group=lrg) == 'Right' ? extend.right : extend.none
// drawline configuration
drawLine(X1, Y1, X2, Y2, ExtendType, Color, LineStyle) =>
var line Line = na
Line := linreg ? line.new(X1, Y1, X2, Y2, xloc.bar_index, ExtendType, Color, LineStyle, width=2) : na
line.delete(Line[1])
rsdcr2(PeriodMinusOne, Deviations, Estimate) =>
var period = PeriodMinusOne + 1
var devDenominator = Estimate == 'Unbiased' ? PeriodMinusOne : period
Ex = 0.0
Ex2 = 0.0
Exy = 0.0
Ey = 0.0
for i = 0 to PeriodMinusOne by 1
closeI = nz(rsi[i])
Ex := Ex + i
Ex2 := Ex2 + i * i
Exy := Exy + closeI * i
Ey := Ey + closeI
Ey
ExEx = Ex * Ex
slope = Ex2 == ExEx ? 0.0 : (period * Exy - Ex * Ey) / (period * Ex2 - ExEx)
linearRegression = (Ey - slope * Ex) / period
intercept = linearRegression + bar_index * slope
deviation = 0.0
for i = 0 to PeriodMinusOne by 1
deviation := deviation + math.pow(nz(rsi[i]) - (intercept - bar_index[i] * slope), 2.0)
deviation
deviation := Deviations * math.sqrt(deviation / devDenominator)
correlate = ta.correlation(rsi, bar_index, period)
r2 = math.pow(correlate, 2.0)
[linearRegression, slope, deviation, correlate, r2]
periodMinusOne = periodTrend - 1
[linReg, slope, deviation, correlate, r2] = rsdcr2(periodMinusOne, deviationsAmnt, estimatorType)
endPointBar = bar_index - periodTrend + 1
endPointY = linReg + slope * periodMinusOne
// drawline plot
drawLine(endPointBar, endPointY + deviation, bar_index, linReg + deviation, extendType, #e91e63, line.style_solid)
drawLine(endPointBar, endPointY, bar_index, linReg, extendType, #e91e63, line.style_dotted)
drawLine(endPointBar, endPointY - deviation, bar_index, linReg - deviation, extendType, #e91e63, line.style_solid)
// ichimoku
// input
ichig = 'Ichimoku'
conversionPeriods = input.int(9, minval=1, title='Conversion Line Periods', group=ichig)
basePeriods = input.int(26, minval=1, title='Base Line Periods', group=ichig)
laggingSpan2Periods = input.int(52, minval=1, title='Lagging Span 2 Periods', group=ichig)
displacement = input.int(26, minval=1, title='Displacement', group=ichig)
// calc
donchian(len) => math.avg(ta.lowest(rsil, len), ta.highest(rsih, len))
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = math.avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)
// plot
p1 = plot(leadLine1, offset = displacement- 1, color=color.new(#4caf50, 100), title="LeadLine A", linewidth=3)
p2 = plot(leadLine2, offset = displacement - 1, color=color.new(#f23645, 100), title="LeadLine B", linewidth=3)
fill(p1, p2, color = leadLine1 > leadLine2 ? color.new(#4caf50, 70) : color.new(#f23645, 70), title='Ichimoku Cloud') |
Triple Supertrend | https://www.tradingview.com/script/BR2Io0S9-Triple-Supertrend/ | venkatachari_n | https://www.tradingview.com/u/venkatachari_n/ | 76 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © venkatachari_n
//@version=5
indicator("Triple Supertrend", overlay=true, timeframe="", timeframe_gaps=true)
atrPeriod1 = input(10, "ATR Length")
factor1 = input.float(1.0, "Factor", step = 0.01)
[supertrend1, direction1] = ta.supertrend(factor1, atrPeriod1)
bodyMiddle1 = plot((open + close) / 2, display=display.none)
upTrend1 = plot(direction1 < 0 ? supertrend1 : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend1 = plot(direction1 < 0? na : supertrend1, "Down Trend", color = color.red, style=plot.style_linebr)
//fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
//fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
atrPeriod2 = input(11, "ATR Length")
factor2 = input.float(2.0, "Factor", step = 0.01)
[supertrend2, direction2] = ta.supertrend(factor2, atrPeriod2)
bodyMiddle2 = plot((open + close) / 2, display=display.none)
upTrend2 = plot(direction2 < 0 ? supertrend2 : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend2 = plot(direction2 < 0? na : supertrend2, "Down Trend", color = color.red, style=plot.style_linebr)
atrPeriod3 = input(12, "ATR Length")
factor3 = input.float(3.0, "Factor", step = 0.01)
[supertrend3, direction3] = ta.supertrend(factor3, atrPeriod3)
bodyMiddle3 = plot((open + close) / 2, display=display.none)
upTrend3 = plot(direction3 < 0 ? supertrend3 : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend3 = plot(direction3 < 0? na : supertrend3, "Down Trend", color = color.red, style=plot.style_linebr)
|
Pivot Points Standard Higher Timeframe | https://www.tradingview.com/script/YyrXRzSl-Pivot-Points-Standard-Higher-Timeframe/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 139 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RozaniGhani-RG
//@version=5
indicator('Pivot Points Standard Higher Timeframe', shorttitle='PPS_HTF', overlay=true)
// 0. Inputs
// 1. Formulas
// 2. Variable
// 3. Switches
// 4. Constructs
// ————————————————————————————————————————————————————————————————————————————— 0. Inputs {
T0 = 'Small font size recommended for mobile app or multiple layout'
higher_TF = input.timeframe( 'M', 'Timeframe')
i_b_label = input.bool( true, 'Label', inline = '0')
i_b_price = input.bool( true, 'Price', inline = '0')
i_b_percent = input.bool( true, 'Percent', inline = '0', tooltip = 'Tick to show')
i_c_R1 = input.color( color.red, 'R1', inline = '1')
i_c_PV = input.color( color.blue, 'PV', inline = '1')
i_c_S1 = input.color(color.green, 'S1', inline = '1', tooltip = 'Color for labels and lines')
i_s_extend = input.string('right', 'Extend line for last pivot', options = ['none', 'right'])
i_s_font = input.string('normal', 'Font size', options = ['tiny', 'small', 'normal', 'large', 'huge'], tooltip = T0)
// }
// ————————————————————————————————————————————————————————————————————————————— 1. Formulas {
ohlc() => [open[1], high[1], low[1], close[1]]
[pO, pH, pL, pC] = request.security(syminfo.tickerid, higher_TF, ohlc(), lookahead=barmerge.lookahead_on)
PV_lvl = math.avg(pH, pL, pC)
R1_lvl = PV_lvl * 2 - pL
S1_lvl = PV_lvl * 2 - pH
R1_pct = (R1_lvl - PV_lvl) / PV_lvl
S1_pct = (S1_lvl - PV_lvl) / PV_lvl
// }
// ————————————————————————————————————————————————————————————————————————————— 2. Variables {
var line R1_line = na, var line PV_line = na, var line S1_line = na
// }
// ————————————————————————————————————————————————————————————————————————————— 3. Switches {
[str_R1, str_PV, str_S1] = switch i_b_price
true => [str.tostring(R1_lvl, '\n#.#'), str.tostring(PV_lvl, '\n#.#'), '\n- ' + str.tostring(S1_lvl, '#.#')]
[pct_R1, pct_S1] = switch i_b_percent
true => [str.tostring(R1_pct, '\n#.#% ▲'),'\n' + str.tostring(S1_pct, '#.#%') + ' ▼']
// }
// ————————————————————————————————————————————————————————————————————————————— 4. Constructs {
if PV_lvl[1] != PV_lvl
// Each line except for last pivot
line.set_x2(R1_line, bar_index), line.set_extend(R1_line, extend.none)
line.set_x2(PV_line, bar_index), line.set_extend(PV_line, extend.none)
line.set_x2(S1_line, bar_index), line.set_extend(S1_line, extend.none)
// Line for Last Pivot with extend right
R1_line := line.new(bar_index, R1_lvl, bar_index, R1_lvl, color = i_c_R1, extend = i_s_extend == 'right' ? extend.right : extend.none)
PV_line := line.new(bar_index, PV_lvl, bar_index, PV_lvl, color = i_c_PV, extend = i_s_extend == 'right' ? extend.right : extend.none)
S1_line := line.new(bar_index, S1_lvl, bar_index, S1_lvl, color = i_c_S1, extend = i_s_extend == 'right' ? extend.right : extend.none)
// Label for all pivot
if i_b_label
label.new(bar_index, R1_lvl, 'R1' + str_R1 + pct_R1, color = i_c_R1, style=label.style_label_right, size = i_s_font)
label.new(bar_index, PV_lvl, 'PV' + str_PV, color = i_c_PV, style=label.style_label_right, size = i_s_font)
label.new(bar_index, S1_lvl, 'S1' + str_S1 + pct_S1, color = i_c_S1, style=label.style_label_right, size = i_s_font)
if not na(PV_line) and line.get_x2(PV_line) != bar_index
line.set_x2(R1_line, bar_index)
line.set_x2(PV_line, bar_index)
line.set_x2(S1_line, bar_index)
// } |
EMAs SAR Indicator | https://www.tradingview.com/script/z1iUpfXm-EMAs-SAR-Indicator/ | Coinekid | https://www.tradingview.com/u/Coinekid/ | 7 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinekid
//@version=5
indicator("EMAs SAR Indicator", overlay=true)
// REF
// Sonic R VuTien
///// Var
var tradeCount = 0
// -------- INPUT ----------
useSAR = input.bool(false, "Use SAR")
// TP1_Ratio = input(title="Sell Postion Size % @ TP1", type=input.float, defval=50, step=1, group="TP & SL", tooltip="Example: 50 closing 50% of the position once TP1 is reached")/100
// ------- Util functions ----------
// distance = 1 -> k and pivot is the same. abs(k-pivot) = 0
distanceRatio(k, pivot) =>
math.abs(pivot - math.abs(pivot-k))/pivot*100.0
distance(k, pivot) =>
math.abs(pivot-k)
getPipSize() =>
if syminfo.ticker == "XAUUSD"
syminfo.mintick * 100
else
syminfo.mintick * (syminfo.type == "forex" ? 10 : 1)
getPip(x,y) => math.abs(x - y) / getPipSize()
curProfitPip() =>
if strategy.position_size > 0
(high - strategy.position_avg_price) / getPipSize()
else if strategy.position_size < 0
(strategy.position_avg_price - low) / getPipSize()
else
0
getCurrentStage(tp1, tp2) =>
var stage = 0
entry = strategy.position_avg_price
if strategy.position_size == 0
stage := 0
if stage == 0 and strategy.position_size != 0
stage := 1
if stage == 1 and curProfitPip() >= getPip(entry, tp1)
stage := 2
if stage == 2 and curProfitPip() >= getPip(entry, tp2)
stage := 3
stage
calcSLPrice(offsetPip) =>
if strategy.position_size > 0
strategy.position_avg_price - offsetPip * getPipSize()
else if strategy.position_size < 0
strategy.position_avg_price + offsetPip * getPipSize()
else
na
calcTPPrice(offsetPip) =>
calcSLPrice(-offsetPip)
///////////// ----------------------------------
///////////// RSI
rsiLength = input.int(14, title="RSI Period Length")
rsiOverSold = 30
rsiOverBought = 70
rsiNeutral = 50
rsi = ta.rsi(close, rsiLength)
// plot(rsi, style=plot.style_line, linewidth=1 , color=color.orange)
//
ema200 = ta.ema(close, 200)
/// SAR
sar = ta.sar(0.02, 0.02, 0.2)
plot(useSAR ? sar:na , style=plot.style_cross, linewidth=1 , color=sar < low? color.green: color.red)
///// Volume
// volMALength = input(title="Volume MA Length", defval=20)
// highVol = volume >= ta.sma(volume, volMALength)
//Sonic R
HiLoLen = input.int(34, minval=2,title="EMA channel")
EMA = input.int(defval=89, title="EMA Signal")
pacC = ta.ema(close,HiLoLen)
pacL = ta.ema(low,HiLoLen)
pacH = ta.ema(high,HiLoLen)
DODGERBLUE = #1E90FFFF
// Plot the Price Action Channel (PAC) base on EMA high,low and close
L=plot(pacL, color=color.new(DODGERBLUE, transp=40), linewidth=1, title="High PAC EMA")
H=plot(pacH, color=color.new(DODGERBLUE, transp=40), linewidth=1, title="Low PAC EMA")
C=plot(pacC, color=color.blue, linewidth=2, title="Close PAC EMA")
fill(L,H, color=color.new(color.aqua, 95), title="Fill HiLo PAC")
//Moving Average
signalMA = ta.ema(close,EMA)
ema610= ta.ema(close, 610)
plot(ema610,title="EMA 610",color=color.white,linewidth=4,style=plot.style_line)
plot(ema200,title="EMA 200",color=color.orange,linewidth=3,style=plot.style_line)
plot(signalMA,title="EMA Signal",color=color.red, linewidth=3,style=plot.style_line)
|
TBM VWAP Bands Style Setup | https://www.tradingview.com/script/Vi5AsXmX-TBM-VWAP-Bands-Style-Setup/ | Mynicknameislion | https://www.tradingview.com/u/Mynicknameislion/ | 75 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator(title='VWAP', overlay=true)
getVWAP(x) =>
float p = na
float vol = na
float sn = na
float lastv = na
float laststd = na
newSession = ta.change(request.security(syminfo.tickerid, x, time, lookahead=barmerge.lookahead_on)) ? 1 : 0
p := newSession ? hlc3 * volume : nz(p[1]) + hlc3 * volume
vol := newSession ? volume : nz(vol[1]) + volume
v = p / vol
sn := newSession ? 0 : nz(sn[1]) + volume * (hlc3 - nz(v[1])) * (hlc3 - v)
std = math.sqrt(sn / vol)
lastv := newSession == 1 ? v[1] : lastv[1]
laststd := newSession == 1 ? std[1] : laststd[1]
[v, std, lastv, laststd]
// Inputs
period = input.string('1D', title='Time segmented VWAP Period', options=['1D', 'Custom'])
custom_period = input('10D', title='Time segmented VWAP Custom Period')
period_out = period == 'Custom' ? custom_period : period
b1_t = input.float(1.0, title='Band 1 multiplier', step=0.1)
b2_t = input.float(2.0, title='Band 2 multiplier', step=0.1)
b3_t = input.float(3.0, title='Band 3 multiplier', step=0.1)
b4_t = input.float(1.5, title='Band 4 multiplier', step=0.1)
// Calcs
[vwap_t, std_t, vwap_prev, std_t_prev] = getVWAP(period_out)
// Plots
//VWAPs
plot(vwap_t, title='VWAP', color=color.rgb(235, 204, 28), linewidth=1)
//BANDs
// Time Segmented VWAP
plot(vwap_t + b1_t * std_t, title='ST DEV 1', color=color.rgb(118, 21, 156), linewidth=1)
plot(vwap_t - b1_t * std_t, title='ST DEV 1', color=color.rgb(118, 21, 156), linewidth=1)
plot(vwap_t + b2_t * std_t, title='ST DEV 2', color=color.rgb(0, 134, 161), linewidth=1)
plot(vwap_t - b2_t * std_t, title='ST DEV 2', color=color.rgb(0, 134, 161), linewidth=1)
plot(vwap_t + b3_t * std_t, title='ST DEV 3', color=color.rgb(232, 27, 1), linewidth=1)
plot(vwap_t - b3_t * std_t, title='ST DEV 3', color=color.rgb(232, 27, 1), linewidth=1)
plot(vwap_t + b4_t * std_t, title='ST DEV 4', color=color.new(color.rgb(216, 113, 1), 70), linewidth=1)
plot(vwap_t - b4_t * std_t, title='ST DEV 4', color=color.new(color.rgb(216, 113, 1), 70), linewidth=1)
|
Bitcoin Best Value Corridor | https://www.tradingview.com/script/VBS3HFma-Bitcoin-Best-Value-Corridor/ | LJBunyan | https://www.tradingview.com/u/LJBunyan/ | 217 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LJBunyan
//@version=5
indicator(title = "Bitcoin Best Value Corridor", shorttitle = "BBVC", overlay = true)
// Days X-Axis Value
start = time == timestamp(2010,7,19,0,0) // First BLX Bitcoin Date
days = request.security(syminfo.tickerid, "D", ta.barssince(start))
offset = 561 // days between 2009/1/1 and "start" 561 - 579
d = days + offset
//Logarithmic Equations
// Center logarithmic trendline
a1 = input(-18, 'Regression Middle')
b1 = input(5.9466, 'Regression Gradient')
e1 = a1 + (b1 * math.log10(d))
y1 = 2 * math.pow(10, e1)
// Bottom logarithmic trendline
a2 = input(-18.18, 'Regression Lower')
b2 = input(5.9466, 'Regression Gradient')
e2 = a2 + (b2 * math.log10(d))
y2 = 2 * math.pow(10, e2)
// Peak logarithmic trendline
a3 = input(-17.82, 'Regression Higher')
b3 = input(5.9466, 'Regression Gradient')
e3 = a3 + (b3 * math.log10(d))
y3 = 2 * math.pow(10, e3)
// Plot
// Plotting each trendline
Fair = plot(y1, color = color.green, title = "Middle")
Lower = plot(y2, color = color.lime, title = "Lower")
Higher = plot(y3, color = color.lime, title = "Higher")
// Shading between each trendline
fill = input(true, "Plot Line Fill?")
fill(Higher, Fair, color = (color.new(color.green, 90)))
fill(Fair, Lower, color = (color.new(color.green, 90)))
//Label
// Orange label for center logarithmic trendline. Format.mintick gives two decimal places
labeltext = str.tostring(y1, format = format.mintick)
ourlabel = label.new(
x = bar_index,
y = y1,
text = labeltext,
color = color.new(color.green, 50),
textcolor = color.white,
style = label.style_label_left,
size = size.normal)
// Plots label for current bar only
label.delete(ourlabel[1])
// Green label for bottom logarithmic trendline. Format.mintick gives two decimal places
labeltext2 = str.tostring(y2, format = format.mintick)
ourlabel2 = label.new(
x = bar_index,
y = y2,
text = labeltext2,
color = color.new(color.lime, 50),
textcolor = color.white,
style = label.style_label_up,
size = size.normal)
// Plots label for current bar only
label.delete(ourlabel2[1])
// Red label for peak logarithmic trendline. Format.mintick gives two decimal places
labeltext3 = str.tostring(y3, format = format.mintick)
ourlabel3 = label.new(
x = bar_index,
y = y3,
text = labeltext3,
color = color.new(color.lime, 50),
textcolor = color.white,
style = label.style_label_down,
size = size.normal)
// Plots label for current bar only
label.delete(ourlabel3[1]) |
Lev Umanov Sin Equation | https://www.tradingview.com/script/kbkHFOu3-Lev-Umanov-Sin-Equation/ | LJBunyan | https://www.tradingview.com/u/LJBunyan/ | 63 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LJBunyan
//@version=5
indicator(title = "Lev Umanov Sin Equation", shorttitle = "LUSE", overlay = true)
// This indicator has been coded from the calculations made by Lev Umanov
// Days X-Axis Value
start = time == timestamp(2010,7,19,0,0) // First BLX Bitcoin Date
days = request.security(syminfo.tickerid, "D", ta.barssince(start))
offset = 561 // days between 2009/1/1 and "start" 561 - 579
d = days + offset
// Logarithmic Growth Curve
// Center logarithmic trendline
a1 = input(-16, 'Regression"a1"')
b1 = input(5.526, 'Regression"b1"')
e1 = a1 + (b1 * math.log10(d))
y1 = 2 * math.pow(10, e1)
// Sin Equation
m1 = math.sqrt(math.sqrt(d))
m2 = (2.983 * m1) - 0.57
m3 = math.sin(m2)
m4 = math.abs(m3) - 1
m5 = math.pow(m4, 2)
m6 = (2 * m5)-1
// Raised Equation
m7 = math.pow(10, math.pow(0.9998, d) * m6)
m8 = y1 * m7
// Not yet working
m9 = (2 * math.pow(math.abs(math.sin(((2.983 * math.sqrt(math.sqrt(d)))-0.57))-1), 2) - 1)
// Plot
plot(m8) |
Quasimodo Pattern by EmreKb | https://www.tradingview.com/script/SQRSlcup/ | EmreKb | https://www.tradingview.com/u/EmreKb/ | 2,291 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EmreKb
//@version=5
indicator("Quasimodo Pattern", "QML", overlay=true, max_bars_back=5000, max_labels_count=500, max_lines_count=500)
zigzag_len = input.int(13, "ZigZag Length")
var float[] high_points_arr = array.new_float(5)
var int[] high_index_arr = array.new_int(5)
var float[] low_points_arr = array.new_float(5)
var int[] low_index_arr = array.new_int(5)
to_up = high >= ta.highest(zigzag_len)
to_down = low <= ta.lowest(zigzag_len)
trend = 1
trend := nz(trend[1], 1)
trend := trend == 1 and to_down ? -1 : trend == -1 and to_up ? 1 : trend
last_trend_up_since = ta.barssince(to_up[1])
low_val = ta.lowest(nz(last_trend_up_since > 0 ? last_trend_up_since : 1, 1))
low_index = bar_index - ta.barssince(low_val == low)
last_trend_down_since = ta.barssince(to_down[1])
high_val = ta.highest(nz(last_trend_down_since > 0 ? last_trend_down_since : 1, 1))
high_index = bar_index - ta.barssince(high_val == high)
if ta.change(trend) != 0
if trend == 1
array.push(low_points_arr, low_val)
array.push(low_index_arr, low_index)
if trend == -1
array.push(high_points_arr, high_val)
array.push(high_index_arr, high_index)
f_get_high(ind) =>
[array.get(high_points_arr, array.size(high_points_arr) - 1 - ind), array.get(high_index_arr, array.size(high_index_arr) - 1 - ind)]
f_get_low(ind) =>
[array.get(low_points_arr, array.size(low_points_arr) - 1 - ind), array.get(low_index_arr, array.size(low_index_arr) - 1 - ind)]
[h0, h0i] = f_get_high(0)
[l0, l0i] = f_get_low(0)
[h1, h1i] = f_get_high(1)
[l1, l1i] = f_get_low(1)
[h2, h2i] = f_get_high(2)
[l2, l2i] = f_get_low(2)
bu_cond = trend == -1 and h2 > h1 and l1 > l0 and h0 > h1 and close > l1
be_cond = trend == 1 and l2 < l1 and h1 < h0 and l0 < l1 and close < h1
if bu_cond and not bu_cond[1]
line.new(h2i, h2, l1i, l1, color=color.green, width=2)
line.new(l1i, l1, h1i, h1, color=color.green, width=2)
line.new(h1i, h1, l0i, l0, color=color.green, width=2)
line.new(l0i, l0, h0i, h0, color=color.green, width=2)
line.new(l1i, l1, bar_index, l1, color=color.green, width=2)
label.new(bar_index, l1, "QM!", style=label.style_label_up, textcolor=color.white, color=color.green, size=size.tiny)
alert("Bullish QM!", alert.freq_once_per_bar)
if be_cond and not be_cond[1]
line.new(l2i, l2, h1i, h1, color=color.red, width=2)
line.new(h1i, h1, l1i, l1, color=color.red, width=2)
line.new(l1i, l1, h0i, h0, color=color.red, width=2)
line.new(h0i, h0, l0i, l0, color=color.red, width=2)
line.new(h1i, h1, bar_index, h1, color=color.red, width=2)
label.new(bar_index, h1, "QM!", style=label.style_label_down, textcolor=color.white, color=color.red, size=size.tiny)
alert("Bearish QM!", alert.freq_once_per_bar)
banner = input.bool(true, "Banner")
var table t = table.new(position.middle_right, 1, 1)
if banner
table.cell(t, 0, 0, "Telegram @tradindicator | alert for Binance Futures", bgcolor = color.yellow) |
Beta Calculator | https://www.tradingview.com/script/ZPED0KMh-Beta-Calculator/ | elio27 | https://www.tradingview.com/u/elio27/ | 117 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © elio27
//@version=5
indicator(title="Beta Calculator", shorttitle="β calc", overlay=true)
sym = input.symbol(title="Symbol", defval="ETHUSDT", confirm=true)
market = input.symbol(title="Reference", defval="BTCUSDT", confirm=true)
lookback = input.int(title="Lookback candles", defval=60, confirm=true)
symPrice = request.security(sym, timeframe.period, close)
symReturn = (symPrice - symPrice[1]) / symPrice[1]
symReturnAverage = ta.sma(symReturn, lookback - 1)
marketPrice = request.security(market, timeframe.period, close)
marketReturn = (marketPrice - marketPrice[1]) / marketPrice[1]
marketReturnSquared = marketReturn * marketReturn
marketReturnAverage = ta.sma(marketReturn, lookback - 1)
sRmR = symReturn * marketReturn
marketReturnVariance = ta.sma(marketReturnSquared, lookback - 1) - marketReturnAverage*marketReturnAverage
covariance = ta.sma(sRmR, lookback - 1) - marketReturnAverage * symReturnAverage
beta = covariance / marketReturnVariance
tbl = table.new(position.middle_right, 1, 2)
table.cell(tbl, 0, 0, "Beta", bgcolor = #548C8C)
table.cell(tbl, 0, 1, str.tostring(beta), bgcolor=#82D9D9)
|
Psychological Levels | https://www.tradingview.com/script/z2pK3rND-Psychological-Levels/ | barnabygraham | https://www.tradingview.com/u/barnabygraham/ | 112 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © barnabygraham
//@version=5
indicator("Psychological Levels",overlay=true,max_lines_count=500)
lines = input.string('Some',title='How Many Lines?', options=['Few','Some','More','Lots'])
var level = 0.
if close > 0.01 and close < 0.1
level := 0.01
if close > 0.05
level := level * 2
if close > 0.1 and close < 1
level := 0.1
if close > 0.5
level := level * 2
if close > 1 and close < 10
level := 1
if close > 5
level := level * 2
if close > 10 and close < 100
level := 10
if close > 50
level := level * 2
if close > 100 and close < 1000
level := 100
if close > 500
level := level * 2
if close > 1000 and close < 10000
level := 1000
if close > 5000
level := level * 2
if close > 10000 and close < 100000
level := 10000
if close > 50000
level := level * 2
if close > 100000 and close < 1000000
level := 100000
if close > 500000
level := level * 2
if close > 1000000 and close < 10000000
level := 1000000
if close > 5000000
level := level * 2
levelMultiplier = lines == 'Few' ? 1 : lines == 'Some' ? 0.5 : lines == 'More' ? 0.2 : lines == 'Lots' ? 0.1 : na
l1 = level*levelMultiplier
l2 = level*2*levelMultiplier
l3 = level*3*levelMultiplier
l4 = level*4*levelMultiplier
l5 = level*5*levelMultiplier
l6 = level*6*levelMultiplier
l7 = level*7*levelMultiplier
l8 = level*8*levelMultiplier
l9 = level*9*levelMultiplier
l10 = level*10*levelMultiplier
l11 = level*11*levelMultiplier
l12 = level*12*levelMultiplier
l13 = level*13*levelMultiplier
l14 = level*14*levelMultiplier
l15 = level*15*levelMultiplier
l16 = level*16*levelMultiplier
l17 = level*17*levelMultiplier
l18 = level*18*levelMultiplier
l19 = level*19*levelMultiplier
l20 = level*20*levelMultiplier
l21 = level*21*levelMultiplier
l22 = level*22*levelMultiplier
l23 = level*23*levelMultiplier
l24 = level*24*levelMultiplier
l25 = level*25*levelMultiplier
l26 = level*26*levelMultiplier
l27 = level*27*levelMultiplier
l28 = level*28*levelMultiplier
l29 = level*29*levelMultiplier
l30 = level*30*levelMultiplier
l31 = level*31*levelMultiplier
l32 = level*32*levelMultiplier
l33 = level*33*levelMultiplier
l34 = level*34*levelMultiplier
l35 = level*35*levelMultiplier
l36 = level*36*levelMultiplier
l37 = level*37*levelMultiplier
l38 = level*38*levelMultiplier
l39 = level*39*levelMultiplier
l40 = level*40*levelMultiplier
l41 = level*41*levelMultiplier
l42 = level*42*levelMultiplier
l43 = level*43*levelMultiplier
l44 = level*44*levelMultiplier
l45 = level*45*levelMultiplier
l46 = level*46*levelMultiplier
l47 = level*47*levelMultiplier
l48 = level*48*levelMultiplier
l49 = level*49*levelMultiplier
l50 = level*50*levelMultiplier
l51 = level*51*levelMultiplier
l52 = level*52*levelMultiplier
l53 = level*53*levelMultiplier
l54 = level*54*levelMultiplier
l55 = level*55*levelMultiplier
l56 = level*56*levelMultiplier
l57 = level*57*levelMultiplier
l58 = level*58*levelMultiplier
l59 = level*59*levelMultiplier
l60 = level*60*levelMultiplier
l61 = level*61*levelMultiplier
l62 = level*62*levelMultiplier
l63 = level*63*levelMultiplier
plot(level)
plot(level+l1)
plot(level+l2)
plot(level+l3)
plot(level+l4)
plot(level+l5)
plot(level+l6)
plot(level+l7)
plot(level+l8)
plot(level+l9)
plot(level+l10)
plot(levelMultiplier<1?level+l11:na)
plot(levelMultiplier<1?level+l12:na)
plot(levelMultiplier<1?level+l13:na)
plot(levelMultiplier<1?level+l14:na)
plot(levelMultiplier<1?level+l15:na)
plot(levelMultiplier<1?level+l16:na)
plot(levelMultiplier<1?level+l17:na)
plot(levelMultiplier<1?level+l18:na)
plot(levelMultiplier<1?level+l19:na)
plot(levelMultiplier<1?level+l20:na)
plot(levelMultiplier<0.5?level+l21:na)
plot(levelMultiplier<0.5?level+l22:na)
plot(levelMultiplier<0.5?level+l23:na)
plot(levelMultiplier<0.5?level+l24:na)
plot(levelMultiplier<0.5?level+l25:na)
plot(levelMultiplier<0.5?level+l26:na)
plot(levelMultiplier<0.5?level+l27:na)
plot(levelMultiplier<0.5?level+l28:na)
plot(levelMultiplier<0.5?level+l29:na)
plot(levelMultiplier<0.5?level+l30:na)
plot(levelMultiplier<0.5?level+l31:na)
plot(levelMultiplier<0.5?level+l32:na)
plot(levelMultiplier<0.5?level+l33:na)
plot(levelMultiplier<0.5?level+l34:na)
plot(levelMultiplier<0.5?level+l35:na)
plot(levelMultiplier<0.5?level+l36:na)
plot(levelMultiplier<0.5?level+l37:na)
plot(levelMultiplier<0.5?level+l38:na)
plot(levelMultiplier<0.5?level+l39:na)
plot(levelMultiplier<0.5?level+l40:na)
plot(levelMultiplier<0.5?level+l41:na)
plot(levelMultiplier<0.5?level+l42:na)
plot(levelMultiplier<0.5?level+l43:na)
plot(levelMultiplier<0.5?level+l44:na)
plot(levelMultiplier<0.5?level+l45:na)
plot(levelMultiplier<0.2?level+l46:na)
plot(levelMultiplier<0.2?level+l47:na)
plot(levelMultiplier<0.2?level+l48:na)
plot(levelMultiplier<0.2?level+l49:na)
plot(levelMultiplier<0.2?level+l50:na)
plot(levelMultiplier<0.2?level+l51:na)
plot(levelMultiplier<0.2?level+l52:na)
plot(levelMultiplier<0.2?level+l53:na)
plot(levelMultiplier<0.2?level+l54:na)
plot(levelMultiplier<0.2?level+l55:na)
plot(levelMultiplier<0.2?level+l56:na)
plot(levelMultiplier<0.2?level+l57:na)
plot(levelMultiplier<0.2?level+l58:na)
plot(levelMultiplier<0.2?level+l59:na)
plot(levelMultiplier<0.2?level+l60:na)
plot(levelMultiplier<0.2?level+l61:na)
plot(levelMultiplier<0.2?level+l62:na)
plot(levelMultiplier<0.2?level+l63:na)
|
Invisible Friend | https://www.tradingview.com/script/wI5e2xaT-Invisible-Friend/ | processingclouds | https://www.tradingview.com/u/processingclouds/ | 28 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © processingclouds
// Looking into a question from user Alex100, i realized many people do want
// some kind of values displayed on chart when they hover the mouse over
// different bars.
// As pinescript does not have any feature like pop up box, the only way is to
// plot a line and than see indicator values at top left. So when mouse is moved
// around the value displayed changes. As we just need the value, we do not want
// to clutter the chart with another line.
// So the solution is very simple, and requires a bit of creativity.
// We create an invisible line, in any color we like :)
// This indicator is a tutorial on how to display indicator values without the
// line showing up and also this can be implemented as displaying data for each
// bar on mouse hover.
//@version=5
indicator("Invisible Friend", "High Low Average", overlay=true)
plot(math.avg(high,low), "A", color.new(color.black,100), 0)
|
ATR Gain | https://www.tradingview.com/script/kZ2msOgR-ATR-Gain/ | carlpwilliams2 | https://www.tradingview.com/u/carlpwilliams2/ | 19 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © carlpwilliams2
//@version=5
indicator("ATR Gain")
gainUpperLimit = input.float(15, title="Gain Upper Limit", group="Limits")
gainLowerLimit = input.float(-15, title="Gain Lower Limit", group="Limits")
atr = ta.atr(14)
atrMA = ta.ema(atr,30)
atrGain = ((atr-atrMA)/atr)*100
upper = plot(gainUpperLimit, title="Gain Upper line", color=color.new(color.gray,60))
zero = plot(0,title="Zero Line", color=color.gray)
lower = plot(gainLowerLimit, title="Gain lower line", color=color.new(color.gray,60))
fill(upper,lower,color.new(color.gray,80))
plot(atrGain, title="Volume Gain", color= color.blue, linewidth=2) |
Singular and Cumulative Volume Delta (SVD+CVD) | https://www.tradingview.com/script/QGuYW4xI-Singular-and-Cumulative-Volume-Delta-SVD-CVD/ | JollyWizard | https://www.tradingview.com/u/JollyWizard/ | 574 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Singular Volume Delta and Cumulative Volume Delta.
//
// Options for MA/SMA smoothing.
// Cumulative vs Singular visual scale control.
// Sustain level to show where current delta must land to for cumulative delta to stay flat.
// Initial levels to show how current buy/sell/delta cumulations compare to values at start of current cumulation.
//@version=5
indicator("Singular and Cumulative Volume Delta (SVD+CVD)", shorttitle="SVD+CVD")
// <Variable Setup>
// Toggle Parts
var RenderDelta_Singular = input.bool(true, "Delta (Singular)", group="Show", inline="Delta")
var RenderDelta_Cumulative = input.bool(true, "Delta (Cumulative)", group="Show", inline="Delta")
var RenderBuySell_Singular = input.bool(true, "Buy/Sell (Singular)", group="Show", inline="Buy/Sell")
var RenderBuySell_Cumulative = input.bool(true, "Buy/Sell (Cumulative)", group="Show", inline="Buy/Sell")
var RenderCumulationLine = input.bool(true, "Cumulation Line", group="Show", inline="Cumulation Line", tooltip="Show where the cumulation window ends.")
var RenderSustainLevels = input.bool(true, "Sustain Level (Singular)", group="Show", inline="Sustain Level", tooltip="Show the singular delta value that would keep the current cumulative delta the same for the next bar.")
var RenderSustainLevelsHistory = input.bool(false, "Sustain Level History", group="Show", inline="Sustain History", tooltip="Show the history of the sustain level. Off for current candle only.")
var RenderInitialLevels = input.bool(true, "Inital Levels (Cumulative)", group="Show", inline="Initial Levels", tooltip="Show the initial cumulation levels from the current cumulation window.")
var RenderInitialLevelsHistory = input.bool(false, "Initial Levels History", group="Show", inline="Initial History", tooltip="Show the history of the initial levels. Off for current candle only.")
// Math Parameters
string cumulation_type = input.string("SUM", "Cumulation Type", group="Parameters", options = ["SUM", "EMA", "SMA"], tooltip="Formula to use to calculation cumulation.")
var cumulation_length = input.int(14, "Cumulation Length", group="Parameters", minval=1, tooltip="Number of periods to include in cumulation.")
var scale_factor = input.float(1.0, "Scale Factor", group="Parameters", tooltip="Scale the cumulation sizes. Sets the visual ratio between singular and cumulative data.", minval=0, step=.125)
var normalize_MAs = input.bool(true, "Normalize MAs", group="Parameters", tooltip="Unshrink the results of MA calculations. Multiplies the output average by the cumulation length.")
var cumulation_line_after_last = input.bool(true, "Cumulation Line After Last Input", group="Cumulation Line", tooltip=" True: Line appears AFTER the last cumulation input (@ last dropped value).\n\n False: Line appears OVER the last value (@ next value to drop).")
// Color Setup
// Pallete
bull_color = input.color(color.green, "Bull Bar Color", group="Colors")
bear_color = input.color(color.red, "Bear Bar Color", group="Colors")
weak_color = input.color(color.gray, "Weak Bar Color", group="Colors")
// Transparency Levels
Transparency_1 = input.int(65, "Cumulative", group="Transparency", minval=0, maxval=100, inline="Transparency Levels")
Transparency_2 = input.int(25, "Singular", group="Transparency", minval=0, maxval=100, inline="Transparency Levels")
// Default all colors to Transparency_1
bull_color := color.new(bull_color, Transparency_1)
bear_color := color.new(bear_color, Transparency_1)
weak_color := color.new(weak_color, Transparency_1)
// <essential calculations>
bullCandle = (open < close)
price_spread = (high - low)
// Establish lengths.
upper_wick_length = bullCandle ? (high-close) : (high-open)
lower_wick_length = bullCandle ? (open-low) : (close-low)
body_length = price_spread - (upper_wick_length + lower_wick_length)
// Convert lengths to Percents
upper_wick_percent = (upper_wick_length / price_spread)
lower_wick_percent = (lower_wick_length / price_spread)
body_percent = (body_length / price_spread)
// Convert percentage lengths into assignment groups.
var effective_wick_divisor = 2
wicks_percent = (upper_wick_percent + lower_wick_percent)
effective_wick_portion = (wicks_percent / effective_wick_divisor)
dominant_candle_portion = (body_percent + effective_wick_portion)
// Assign to volumes.
volume_buy = volume * ( bullCandle ? dominant_candle_portion : effective_wick_portion)
volume_sell = volume * (not bullCandle ? dominant_candle_portion : effective_wick_portion)
volume_delta = (volume_buy - volume_sell)
// Give name to direction calculation
volume_isBullish = (volume_delta > 0)
volume_isBearish = (volume_delta < 0)
// <Cumulations>
// Main cumulation Calculations
// Pre-calculating all values ends up being more coherent and forward thinking than complex `switch` calculations.
volume_buy_cumulative_sum = math.sum(volume_buy, cumulation_length)
volume_buy_cumulative_ema = ta.ema(volume_buy, cumulation_length)
volume_buy_cumulative_sma = ta.sma(volume_buy, cumulation_length)
volume_sell_cumulative_sum = math.sum(volume_sell, cumulation_length)
volume_sell_cumulative_ema = ta.ema(volume_sell, cumulation_length)
volume_sell_cumulative_sma = ta.sma(volume_sell, cumulation_length)
volume_delta_cumulative_sum = volume_buy_cumulative_sum - volume_sell_cumulative_sum
volume_delta_cumulative_sma = volume_buy_cumulative_sma - volume_sell_cumulative_sma
volume_delta_cumulative_ema = volume_buy_cumulative_ema - volume_sell_cumulative_ema
// Assign to plot variables / default data history.
volume_buy_cumulative = switch cumulation_type
"SUM" => volume_buy_cumulative_sum
"EMA" => volume_buy_cumulative_ema
"SMA" => volume_buy_cumulative_sma
volume_sell_cumulative = switch cumulation_type
"SUM" => volume_sell_cumulative_sum
"EMA" => volume_sell_cumulative_ema
"SMA" => volume_sell_cumulative_sma
// Normalize MAs if applicable.
// Only applies to plot values. Singular sized MA values are retained in their variables for other potential uses..
// @TODO Create separate series variables for normalized results and then switch at plot rendering.
is_MA_cumulation = switch cumulation_type
"EMA" => true
"SMA" => true
=> false
normalize_multiplier = (is_MA_cumulation and normalize_MAs) ? cumulation_length : 1
volume_buy_cumulative := volume_buy_cumulative * normalize_multiplier
volume_sell_cumulative := volume_sell_cumulative * normalize_multiplier
// For cumulative scale, do the buy and sell levels. Rest are derived from these anyway.
volume_buy_cumulative := volume_buy_cumulative * scale_factor
volume_sell_cumulative := volume_sell_cumulative * scale_factor
// This is calculated here, rather than switched from previous inputs, so the scaling is included.
volume_delta_cumulative = (volume_buy_cumulative - volume_sell_cumulative)
// Give name to direction calculation
volume_cumulative_isBullish = (volume_delta_cumulative > 0)
volume_cumulative_isBearish = (volume_delta_cumulative < 0)
// <plot: Buy/Sell Levels>
// Use alt transparency for buysell data.
buysell_data_transparency = Transparency_2
plot( not RenderBuySell_Singular ? na : volume_buy, "Buy Volume", style=plot.style_histogram, color=color.new(bull_color, buysell_data_transparency))
plot( not RenderBuySell_Singular ? na : -volume_sell, "Sell Volume", style=plot.style_histogram, color=color.new(bear_color, buysell_data_transparency))
plot( not RenderBuySell_Cumulative ? na : volume_buy_cumulative, "Buy Volume (Cumulative)", style=plot.style_stepline, color=color.new(bull_color, buysell_data_transparency))
plot( not RenderBuySell_Cumulative ? na : -volume_sell_cumulative, "Sell Volume (Cumulative)", style=plot.style_stepline, color=color.new(bear_color, buysell_data_transparency))
// <plot: Delta Singular>
volume_delta_color = volume_isBullish ? bull_color : volume_isBearish ? bear_color : weak_color
volume_delta_color := color.new(volume_delta_color, Transparency_2)
plot( not RenderDelta_Singular ? na : volume_delta, "Volume Delta", style=plot.style_columns, linewidth=4, color=volume_delta_color)
// <plot: Delta Cumulative (CVD)>
volume_delta_cumulative_color = (volume_cumulative_isBullish) ? (bull_color) : (volume_cumulative_isBearish) ? (bear_color) : (weak_color)
plot( not RenderDelta_Cumulative ? na : volume_delta_cumulative, "Cumulative Volume Delta", color=volume_delta_cumulative_color, style=plot.style_columns)
// -------------------------------------------------------------------------------------
// <plot: Center Line>
hline(0, "Zero Line", linestyle=hline.style_dotted, color=color.gray)
// -------------------------------------------------------------------------------------
// <plot: Cumulation Line>
// This line shows where the cumulation window ends. The values at this mark are dropped from the cumulation, and will be used for Sustain and Initial Levels.
var cumulation_line_bull = line.new(na,na,na,na, style=line.style_dotted, color=color.new(weak_color, Transparency_2))
cumulation_last_bar_index = bar_index - cumulation_length + (cumulation_line_after_last ? 0 : 1)
line.set_xy1(cumulation_line_bull, cumulation_last_bar_index, volume_buy_cumulative[cumulation_length])
line.set_xy2(cumulation_line_bull, cumulation_last_bar_index, -volume_sell_cumulative[cumulation_length])
// <Cumulation Sustain and Initial Levels>
// # Sustain Levels:
// The last element of the cumulation period gets dropped on each bar progression.
// This affects the update calculation in predictable ways, setting a break even level for the current candle.
// By previewing the change, we can establish if the market is on track to maintain, increase, or reverse the cumulation.
// The break even point is the sustain levels.
// # Initial Levels:
// The cumulation levels at the beginning of the cumulation window, compared to the current, indicate:
// * Relative changes in total number of buyers / sellers.
// * Change in cumulative delta direction and strength.
// * Growth and contraction of overal market volume.
// <calculate: Sustain Level>
// Collect the value to be dropped.
cumulation_last_drop_delta = volume_delta[cumulation_length]
// The SUM replenishment is just the values removed. That's how sums work.
cumulation_sustain_delta_sum = cumulation_last_drop_delta
// The SMA replenishment is the same as for SUM.
// b/c If you remove a value from an average's input pool,
// Then you need to put the same value back or the calculation changes.
cumulation_sustain_delta_sma = cumulation_last_drop_delta
// For EMA:
// There is an intuitive solution to this, but the algebra verifies:
// Let k = (smoothing/(1+cumulation_length)
// Then:
// ema_this = ema_last(1-k) + value_this(k)
// 1 = (ema_this)/(ema_last) = (1-k) + (value_this)(k)/(ema_last)
// 1 - (1-k) = (value_this)(k)/(ema_last)
// (k)(ema_last) = (value_this)(k)
// ema_last = value_this
//
// Essentially, the making the current output equal to the last output allows us to cancel out the smoothing
// Making the target variable equal as well.
float cumulation_sustain_delta_ema = volume_delta_cumulative_ema[1]
cumulation_sustain_delta = switch cumulation_type
"SUM" => cumulation_sustain_delta_sum
"SMA" => cumulation_sustain_delta_sma
"EMA" => cumulation_sustain_delta_ema
// <calculate: Initial Levels>
// Collect the values to be dropped.
cumulation_next_drop_delta_cumulative = volume_delta_cumulative[cumulation_length - 1]
cumulation_next_drop_buy_cumulative = volume_buy_cumulative[cumulation_length - 1]
cumulation_next_drop_sell_cumulative = volume_sell_cumulative[cumulation_length - 1]
// The initial levels are just history levels.
cumulation_initial_delta_cumulative = cumulation_next_drop_delta_cumulative
cumulation_initial_buy_cumulative = cumulation_next_drop_buy_cumulative
cumulation_initial_sell_cumulative = cumulation_next_drop_sell_cumulative
// <plot: sustain levels>
sustain_level_show_last = (RenderSustainLevelsHistory) ? (na) : (1)
plot( not RenderSustainLevels ? na : cumulation_sustain_delta, "Delta Sustain", style=plot.style_columns, color=weak_color, offset=0, show_last=sustain_level_show_last)
// <plot: initial levels>
initial_level_show_last = (RenderInitialLevelsHistory) ? (na) : (2)
plot( not RenderInitialLevels ? na : cumulation_initial_delta_cumulative, "Delta Cumulative Sustain", style=plot.style_stepline, color=weak_color, offset=0, show_last=initial_level_show_last)
plot( not RenderInitialLevels ? na : cumulation_initial_buy_cumulative, "Buy Cumulative Sustain", style=plot.style_stepline, color=weak_color, offset=0, show_last=initial_level_show_last)
plot( not RenderInitialLevels ? na : -cumulation_initial_sell_cumulative, "Sell Cumulative Sustain", style=plot.style_stepline, color=weak_color, offset=0, show_last=initial_level_show_last) |
Swing Failure Pattern by EmreKb | https://www.tradingview.com/script/JqWpj57x/ | EmreKb | https://www.tradingview.com/u/EmreKb/ | 2,067 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EmreKb
//@version=5
indicator("Swing Failure Pattern", "SFP", overlay=true, max_bars_back=4900)
lookback = 4899
is_opposite = input.bool(false, "Candle should be opposite direction", group="settings")
plen = input.int(21, "Pivot Lenght", 1, 99, group="settings")
textcolor = input.color(color.orange, "Text Color", group="display")
position = input.string(position.top_right, "Table Position", [position.top_right, position.top_left, position.bottom_right, position.bottom_left], group="table")
textcolortbl = input.color(color.orange, "Table Text Color", group="table")
ph = ta.pivothigh(plen, 0)
pl = ta.pivotlow(plen, 0)
f_get_candle(_index) =>
[open[_index], high[_index], low[_index], close[_index], bar_index[_index]]
f_is_candle_up(_open, _close) =>
_open < _close
f_sfp() =>
[so, sh, sl, sc, si] = f_get_candle(0)
// High SFP
hc1 = ph
maxp = high[1]
hc2 = false
hx = 0
hy = 0.0
for i=1 to lookback
[co, ch, cl, cc, ci] = f_get_candle(i)
if ch >= sh
break
if ch < sh and ch > math.max(so, sc) and ph[bar_index - ci] and ch > maxp
hc2 := true
hx := bar_index[i]
hy := ch
if ch > maxp
maxp := ch
hcs = hc1 and hc2
// Low SFP
lc1 = pl
minp = low[1]
lc2 = false
lx = 0
ly = 0.0
for i=2 to lookback
[co, ch, cl, cc, ci] = f_get_candle(i)
if cl < sl
break
if sl < cl and math.min(so, sc) > cl and pl[bar_index - ci] and cl < minp
lc2 := true
lx := bar_index[i]
ly := cl
if cl < minp
minp := cl
lcs = lc1 and lc2
[hcs, hx, hy, lcs, lx, ly]
f_control(_tf) =>
[_hsfp, _hx, _hy, _lsfp, _lx, _ly] = request.security(syminfo.tickerid, _tf, f_sfp())
_hsfp or _lsfp or _hsfp[1] or _lsfp[1]
f_multitimeframe() =>
tbl = table.new(position, 1, 1)
txt = ""
if f_control("5")
txt := txt + "5m SFP Detected\n"
if f_control("15")
txt := txt + "15m SFP Detected\n"
if f_control("30")
txt := txt + "30m SFP Detected\n"
if f_control("60")
txt := txt + "1h SFP Detected\n"
if f_control("120")
txt := txt + "2h SFP Detected\n"
if f_control("240")
txt := txt + "4h SFP Detected\n"
table.cell(tbl, 0, 0, txt, text_color=textcolortbl, text_size=size.small)
[hsfp, hx, hy, lsfp, lx, ly] = f_sfp()
hsfp := is_opposite ? hsfp and open > close : hsfp
lsfp := is_opposite ? lsfp and open < close : lsfp
if hsfp
line.new(hx, hy, bar_index + 1, hy, color=color.red)
alert("High SFP Detected!", alert.freq_once_per_bar)
plotshape(hsfp?high:na, "High SFP", style=shape.triangledown, location=location.abovebar, color=color.red, text="SFP", textcolor=color.red, size=size.tiny)
if lsfp
line.new(lx, ly, bar_index + 1, ly, color=color.green)
alert("Low SFP Detected!", alert.freq_once_per_bar)
plotshape(lsfp?low:na, "Low SFP", style=shape.triangleup, location=location.belowbar, color=color.green, text="SFP", textcolor=color.green, size=size.tiny)
f_multitimeframe() |
STD-Stepped VIDYA w/ Quantile Bands [Loxx] | https://www.tradingview.com/script/TLyNonqT-STD-Stepped-VIDYA-w-Quantile-Bands-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 75 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator('STD-Stepped VIDYA w/ Quantile Bands [Loxx]',
shorttitle = "STDDVIDYAQB [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps=true)
import loxx/loxxexpandedsourcetypes/3
greencolor = #2DD204
redcolor = #D2042D
SM02 = 'Slope'
SM03 = 'Middle Crossover'
SM04 = 'Levels Crossover'
_filt(src, len, filter)=>
price = src
filtdev = filter * ta.stdev(src, len)
price := math.abs(price - price[1]) < filtdev ? price[1] : price
price
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Basic Settings")
srcin = input.string("Close", "Source", group= "Basic Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input(9, 'Period', group= "Basic Settings")
histPer = input(30, 'Hist Period', group= "Basic Settings")
filterop = input.string("Both", "Filter Options", options = ["Price", "VIDYA", "Both"], group= "Filter Settings")
filter = input.float(0, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(1, "Filter Period", minval = 0, group= "Filter Settings")
FlPeriod = input.int(25, "Levels Period", group = "Levels Settings")
FlUp = input.float(80 , "Up Level", group = "Levels Settings")
FlDn = input.float(20 , "Down Level", group = "Levels Settings")
sigtype = input.string(SM03, "Signal type", options = [SM02, SM03, SM04], group = "Signal Settings")
colorbars = input.bool(false, "Color bars?", group = "UI Options")
showsignals = input.bool(false, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
price = filterop == "Both" or filterop == "Price" and filter > 0 ? _filt(src, filterperiod, filter) : src
k = ta.stdev(price, per) / ta.stdev(price, histPer)
sc = 2 / (per + 1)
vidya = 0.0
vidya := nz(k * sc * price + (1 - k * sc) * vidya[1], 0)
out = filterop == "Both" or filterop == "VIDYA" and filter > 0 ? _filt(vidya, filterperiod, filter) : vidya
sig = out[1]
flhi = ta.percentile_linear_interpolation(out, FlPeriod, FlUp)
mid = ta.percentile_linear_interpolation(out, FlPeriod, (FlUp+FlDn)/2.0)
fllo = ta.percentile_linear_interpolation(out, FlPeriod, FlDn)
state = 0.
if sigtype == SM02
if (out<sig)
state :=-1
if (out>sig)
state := 1
else if sigtype == SM03
if (out<mid)
state :=-1
if (out>mid)
state := 1
else if sigtype == SM04
if (out<fllo)
state :=-1
if (out>flhi)
state := 1
colorfish = state == -1 ? redcolor : state == 1 ? greencolor : color.gray
plot(out, color= colorfish, title="Fisher", linewidth = 3)
plot(flhi, "High Level", color = color.gray)
plot(fllo, "Low Level" ,color = color.gray)
plot(mid, "Middle", color = color.white)
barcolor(colorbars ? colorfish : na)
goLong = sigtype == SM02 ? ta.crossover(out, sig) : sigtype == SM03 ? ta.crossover(out, mid) : ta.crossover(out, flhi)
goShort = sigtype == SM02 ? ta.crossunder(out, sig) : sigtype == SM03 ? ta.crossunder(out, mid) : ta.crossunder(out, fllo)
plotshape(goLong and showsignals, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(goShort and showsignals, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="STD-Stepped VIDYA w/ Quantile Bands [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="STD-Stepped VIDYA w/ Quantile Bands [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
DSS of Advanced Kaufman AMA [Loxx] | https://www.tradingview.com/script/gDFILs6m-DSS-of-Advanced-Kaufman-AMA-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 105 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("DSS of Advanced Kaufman AMA [Loxx]", shorttitle='DSSAKAMA [Loxx]', timeframe="", overlay = false, timeframe_gaps=true)
greencolor = #2DD204
redcolor = #D2042D
_jfract(count)=>
window = math.ceil(count/2)
_hl1 = (ta.highest(high[window], window) - ta.lowest(low[window], window)) / window
_hl2 = (ta.highest(high, window) - ta.lowest(low, window)) / window
_hl = (ta.highest(high, count) - ta.lowest(low, count)) / count
_d = (math.log(_hl1 + _hl2) - math.log(_hl)) / math.log(2)
dim = _d < 1 ? 1 : _d > 2 ? 2 : _d
_kama(src, len, fast, slow, jcount, power, efratiocalc) =>
fastend = (2.0 /(fast + 1))
slowend = (2.0 /(slow + 1))
mom = math.abs(ta.change(src, len))
vola = math.sum(math.abs(ta.change(src)), len)
efratio = efratiocalc == "Regular" ? (vola != 0 ? mom / vola : 0) : math.min(2.0-_jfract(jcount), 1.0)
alpha = math.pow(efratio * (fastend - slowend) + slowend, power)
kama = 0.0
kama := alpha * src + (1 - alpha) * nz(kama[1], src)
kama
blsrc = input.source(close, "Source", group = "Kaufman AMA Settings")
period = input.int(10, "Period", minval = 0, group = "Kaufman AMA Settings")
kama_fastend = input.float(2, "Kaufman AMA Fast-end Period", minval = 0.0, group = "Kaufman AMA Settings")
kama_slowend = input.float(30, "Kaufman AMA Slow-end Period", minval = 0.0, group = "Kaufman AMA Settings")
efratiocalc = input.string("Fractal Dimension Adaptive", "Efficiency Ratio Type", options = ["Regular", "Fractal Dimension Adaptive"], group = "Kaufman AMA Settings")
jcount = input.int(defval=2, title="Fractal Dimension Count ", group = "Kaufman AMA Settings")
SmoothPower = input.int(2, "Kaufman Power Smooth", group = "Kaufman AMA Settings")
stochLen = input.int(30, "Stoch Smooth Period", group = "Stochastic Settings")
smEMA = input.int(9, "Intermediate Smooth Period", group = "Stochastic Settings")
sigEMA = input.int(5, "Signal Smooth Period", group = "Stochastic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
kamaC = _kama(blsrc, period, kama_fastend, kama_slowend, jcount, SmoothPower, efratiocalc)
kamaHi = ta.highest(kamaC, stochLen)
kamaLo = ta.lowest(kamaC, stochLen)
st1 = ta.stoch(kamaC, kamaHi, kamaLo, stochLen)
emaout = ta.ema(st1, smEMA)
firsthi = ta.highest(emaout, stochLen)
firstlo = ta.lowest(emaout, stochLen)
out = ta.stoch(emaout, firsthi, firstlo, stochLen)
outer = ta.ema(out, smEMA)
signal = ta.ema(outer, sigEMA)
plot(signal, color = color.white, linewidth = 1)
plot(50, color=color.new(color.gray, 30), linewidth=1, style=plot.style_circles, title = "Zero line")
plot(outer, color = outer > signal ? greencolor : redcolor, linewidth = 2)
barcolor(colorbars ? outer > signal ? greencolor : redcolor : na)
|
Turk Pivot Candle Order Blocks | https://www.tradingview.com/script/12Bb1iW3-Turk-Pivot-Candle-Order-Blocks/ | turk_shariq | https://www.tradingview.com/u/turk_shariq/ | 310 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © turk_shariq
//@version=5
indicator("Turk Pivot Candle Order Blocks", shorttitle="TURK - OB", overlay=true, max_bars_back=500, max_boxes_count=250)
//Titles
inputGroupTitle = "=== Pivots ==="
plotGroupTitle = "=== Plots ==="
//Inputs
leftLenH = input.int(title="Pivot High", defval=10, minval=1, inline="Pivot High", group=inputGroupTitle)
rightLenH = input.int(title="/", defval=10, minval=1, inline="Pivot High", group=inputGroupTitle)
leftLenL = input.int(title="Pivot Low", defval=10, minval=1, inline="Pivot Low", group=inputGroupTitle)
rightLenL = input.int(title="/", defval=10, minval=1, inline="Pivot Low", group=inputGroupTitle)
boxLength = input.int(30, title="Box Size", tooltip="Amount of candles long", group=plotGroupTitle)
bullBoxColor = input.color(color.new(#00E600,90), title="Bullish Box Color", group=plotGroupTitle, inline="1")
bearBoxColor = input.color(color.new(#FF0000,90), title="Bearish Box Color", group=plotGroupTitle, inline="1")
ph = ta.pivothigh(leftLenH, rightLenH)
pl = ta.pivotlow(leftLenL, rightLenL)
//Variables
var leftBull = bar_index
var rightBull = bar_index
var topBull = close
var bottomBull = close
var leftBear = bar_index
var rightBear = bar_index
var topBear = close
var bottomBear = close
//Bear Box Calc
if ph
leftBear := bar_index-leftLenH
rightBear := bar_index-(leftLenH-boxLength)
topBear := close>open ? close[leftLenH] : open[leftLenH]
bottomBear := close>open ? open[leftLenH] : close[leftLenH]
//Bull Box Calc
if pl
leftBull := bar_index-leftLenL
rightBull := bar_index-(leftLenL-boxLength)
topBull := close>open ? close[leftLenL] : open[leftLenL]
bottomBull := close>open ? open[leftLenL] : close[leftLenL]
if pl
bull = box.new(left=leftBull, right=rightBull, top=topBull, bottom=bottomBull, bgcolor=color.new(bullBoxColor,80), border_color=bullBoxColor)
if ph
bear = box.new(left=leftBear, right=rightBear, top=topBear, bottom=bottomBear, bgcolor=color.new(bearBoxColor,80), border_color=bearBoxColor) |
Bermaui Variety Averages Bands [Loxx] | https://www.tradingview.com/script/FWca57vK-Bermaui-Variety-Averages-Bands-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 187 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Bermaui Variety Averages Bands [Loxx]",
shorttitle='BVAB [Loxx]',
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
darkGreenColor = #1B7E02
darkRedColor = #93021F
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(50, "Period", group = "Basic Settings")
type = input.string("Simple Moving Average - SMA", "Double Smoothing MA Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre filt", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Basic Settings")
mult = input.float(2.1, "Bollinger Band Multtiplier", group = "Basic Settings")
showLongs = input.bool(true, "Show Longs?", group = "Signal Options")
showShorts = input.bool(true, "Show Shorts?", group = "Signal Options")
showCLongs = input.bool(false, "Show Continuation Longs?", group = "Signal Options")
showCShorts = input.bool(false, "Show Continuation Shorts?", group = "Signal Options")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
colorbg = input.bool(false, "Show background color?", group = "UI Options")
frama_FC = input.int(defval=1, title="* Fractal Adjusted (FRAMA) Only - FC", group = "Moving Average Inputs")
frama_SC = input.int(defval=200, title="* Fractal Adjusted (FRAMA) Only - SC", group = "Moving Average Inputs")
instantaneous_alpha = input.float(defval=0.07, minval = 0, title="* Instantaneous Trendline (INSTANT) Only - Alpha", group = "Moving Average Inputs")
_laguerre_alpha = input.float(title="* Laguerre filt (LF) Only - Alpha", minval=0, maxval=1, step=0.1, defval=0.7, group = "Moving Average Inputs")
lsma_offset = input.int(defval=0, title="* Least Squares Moving Average (LSMA) Only - Offset", group = "Moving Average Inputs")
_pwma_pwr = input.int(2, "* Parabolic Weighted Moving Average (PWMA) Only - Power", minval=0, group = "Moving Average Inputs")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "ADXvma - Average Directional Volatility Moving Average"
[t, s, b] = loxxmas.adxvma(src, len)
sig := s
trig := t
special := b
else if type == "Ahrens Moving Average"
[t, s, b] = loxxmas.ahrma(src, len)
sig := s
trig := t
special := b
else if type == "Alexander Moving Average - ALXMA"
[t, s, b] = loxxmas.alxma(src, len)
sig := s
trig := t
special := b
else if type == "Double Exponential Moving Average - DEMA"
[t, s, b] = loxxmas.dema(src, len)
sig := s
trig := t
special := b
else if type == "Double Smoothed Exponential Moving Average - DSEMA"
[t, s, b] = loxxmas.dsema(src, len)
sig := s
trig := t
special := b
else if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
else if type == "Fractal Adaptive Moving Average - FRAMA"
[t, s, b] = loxxmas.frama(src, len, frama_FC, frama_SC)
sig := s
trig := t
special := b
else if type == "Hull Moving Average - HMA"
[t, s, b] = loxxmas.hma(src, len)
sig := s
trig := t
special := b
else if type == "IE/2 - Early T3 by Tim Tilson"
[t, s, b] = loxxmas.ie2(src, len)
sig := s
trig := t
special := b
else if type == "Integral of Linear Regression Slope - ILRS"
[t, s, b] = loxxmas.ilrs(src, len)
sig := s
trig := t
special := b
else if type == "Instantaneous Trendline"
[t, s, b] = loxxmas.instant(src, instantaneous_alpha)
sig := s
trig := t
special := b
else if type == "Laguerre filt"
[t, s, b] = loxxmas.laguerre(src, _laguerre_alpha)
sig := s
trig := t
special := b
else if type == "Leader Exponential Moving Average"
[t, s, b] = loxxmas.leader(src, len)
sig := s
trig := t
special := b
else if type == "Linear Regression Value - LSMA (Least Squares Moving Average)"
[t, s, b] = loxxmas.lsma(src, len, lsma_offset)
sig := s
trig := t
special := b
else if type == "Linear Weighted Moving Average - LWMA"
[t, s, b] = loxxmas.lwma(src, len)
sig := s
trig := t
special := b
else if type == "McGinley Dynamic"
[t, s, b] = loxxmas.mcginley(src, len)
sig := s
trig := t
special := b
else if type == "McNicholl EMA"
[t, s, b] = loxxmas.mcNicholl(src, len)
sig := s
trig := t
special := b
else if type == "Non-Lag Moving Average"
[t, s, b] = loxxmas.nonlagma(src, len)
sig := s
trig := t
special := b
else if type == "Parabolic Weighted Moving Average"
[t, s, b] = loxxmas.pwma(src, len, _pwma_pwr)
sig := s
trig := t
special := b
else if type == "Recursive Moving Trendline"
[t, s, b] = loxxmas.rmta(src, len)
sig := s
trig := t
special := b
else if type == "Simple Moving Average - SMA"
[t, s, b] = loxxmas.sma(src, len)
sig := s
trig := t
special := b
else if type == "Sine Weighted Moving Average"
[t, s, b] = loxxmas.swma(src, len)
sig := s
trig := t
special := b
else if type == "Smoothed Moving Average - SMMA"
[t, s, b] = loxxmas.smma(src, len)
sig := s
trig := t
special := b
else if type == "Smoother"
[t, s, b] = loxxmas.smoother(src, len)
sig := s
trig := t
special := b
else if type == "Super Smoother"
[t, s, b] = loxxmas.super(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Butterworth"
[t, s, b] = loxxmas.threepolebuttfilt(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Smoother"
[t, s, b] = loxxmas.threepolesss(src, len)
sig := s
trig := t
special := b
else if type == "Triangular Moving Average - TMA"
[t, s, b] = loxxmas.tma(src, len)
sig := s
trig := t
special := b
else if type == "Triple Exponential Moving Average - TEMA"
[t, s, b] = loxxmas.tema(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers Butterworth"
[t, s, b] = loxxmas.twopolebutter(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers smoother"
[t, s, b] = loxxmas.twopoless(src, len)
sig := s
trig := t
special := b
else if type == "Volume Weighted EMA - VEMA"
[t, s, b] = loxxmas.vwema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average"
[t, s, b] = loxxmas.zlagdema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag Moving Average"
[t, s, b] = loxxmas.zlagma(src, len)
sig := s
trig := t
special := b
else if type == "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"
[t, s, b] = loxxmas.zlagtema(src, len)
sig := s
trig := t
special := b
trig
basis = variant(type, src, per)
dev = ta.stdev(src, per)
hihi = ta.highest(dev, per)
lolo = ta.lowest(dev, per)
mod = (hihi - dev) / (hihi - lolo) * mult
uplvl = basis + (mod * dev)
dnlvl = basis - (mod * dev)
plot(basis, "Basis", color=color.white, linewidth = 4)
plot(uplvl, "Upper Band", color=greencolor, linewidth = 2)
plot(dnlvl, "Lower Band", color=redcolor, linewidth = 2)
colorout = src > uplvl ? greencolor : src < dnlvl ? redcolor : color.gray
barcolor(colorbars ? colorout: na)
goLong_pre = ta.crossover(src, uplvl)
goShort_pre = ta.crossunder(src, dnlvl)
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch
goLong = contSwitch == 1 and ta.change(contSwitch)
goShort = contSwitch == -1 and ta.change(contSwitch)
contLong = contSwitch == 1 and goLong_pre and not goLong and not goShort
contShort = contSwitch == -1 and goShort_pre and not goShort and not goLong
plotshape(showLongs and goLong, title = "Long", color = greencolor, textcolor = greencolor, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showShorts and goShort, title = "Short", color = redcolor, textcolor = redcolor, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
plotshape(showCLongs and contLong, title = "Continuation Long", color = color.yellow, textcolor = color.yellow, text = "CL", style = shape.circle, location = location.belowbar, size = size.tiny)
plotshape(showCShorts and contShort, title = "Continuation Short", color = color.fuchsia, textcolor = color.fuchsia, text = "CS", style = shape.circle, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="Bermaui Variety Averages Bands [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Bermaui Variety Averages Bands [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(contLong, title="Continuation Long", message="Bermaui Variety Averages Bands [Loxx]: Continuation Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(contShort, title="Continuation Short", message="Bermaui Variety Averages Bands [Loxx]: Continuation Short\nSymbol: {{ticker}}\nPrice: {{close}}")
bgcolor(colorbg ? goLong or goShort or contLong or contShort ? color.new(color.yellow, 90) : na : na)
|
Whisker Reversal Oscillator [SpiritualHealer117] | https://www.tradingview.com/script/yF9N4TN0-Whisker-Reversal-Oscillator-SpiritualHealer117/ | spiritualhealer117 | https://www.tradingview.com/u/spiritualhealer117/ | 40 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © spiritualhealer117
//@version=5
indicator("whiskers",overlay=false)
len=input(14,"Length")
top_var=array.new<float>(len,0)
bot_var=array.new<float>(len,0)
body_var=array.new<float>(len,0)
for i = 0 to len-1
top = close[i] > open[i]? close[i]:open[i]
bottom = open[i] < close[i]? open[i]:close[i]
top_whisker = high[i]-top
bottom_whisker = bottom-low[i]
body = top-bottom
array.insert(top_var,i,top_whisker)
array.insert(bot_var,i,bottom_whisker)
array.insert(body_var,i,body)
avg_top = array.avg(top_var)
avg_bot = array.avg(bot_var)
avg_bod = array.avg(body_var)
botscillator = (avg_bot-avg_bod)/avg_bod
topscillator = (avg_top-avg_bod)/avg_bod
tl=plot(topscillator, color=color.yellow)
bl=plot(botscillator, color=color.blue)
fill(tl, bl, color=topscillator>botscillator?color.new(color.yellow,55):color.new(color.blue,55))
hline(-0.5)
hline(0)
hline(-1)
|
[GTH] Earnings | https://www.tradingview.com/script/xXzAMq5A-GTH-Earnings/ | gehteha | https://www.tradingview.com/u/gehteha/ | 49 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gehteha
//@version=5
indicator(title="[GTH] Earnings", scale=scale.right)
r1 = request.earnings(syminfo.tickerid, earnings.actual, ignore_invalid_symbol=true)
r2 = request.earnings(syminfo.tickerid, earnings.estimate, ignore_invalid_symbol=true)
col_p = input.color(title="Postive Surprise", defval=color.green)
col_n = input.color(title="Negative Surprise", defval=color.red)
col_p_l = input.color(title="Postive Shade", defval=color.rgb(0, 182, 6, 88))
col_n_l = input.color(title="Negative Shade", defval=color.rgb(255, 73, 73, 79))
h_off = input.int(title="Horizontal Label Offset", defval=0)
col = r1 > r2 ? col_p : col_n
p1 = plot(r1, title="Actual Earnings", color=r1>0 ? col_p : col_n, linewidth=3, style = plot.style_stepline)
p2 = plot(r2, title="Estimated Earnings",color= r2<r1 ? col_p : col_n, linewidth=1, style = plot.style_stepline, display=display.none)
fill(p1, p2, color=r1>r2 ? col_p_l : col_n_l)
float diff = r1-r1[1]
perc = r1 != r1[1] ? (r1/r1[1])-1 : na
bool plot_perc = r1 != r1[1] ? true : false
string form=str.replace(str.tostring(str.format("{0,number,percent}", math.abs(perc))), ",","",0)
if plot_perc
label.new(bar_index + h_off , r1, form, color = diff>0 ? col_p : col_n, style = diff>0 ? label.style_label_down : label.style_label_up, textcolor=color.white)
|
SST-V2 | https://www.tradingview.com/script/TNR9gz81-SST-V2/ | toyikata04 | https://www.tradingview.com/u/toyikata04/ | 110 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © toyikata04
//@version=4
study(title="SST-V2", overlay = true)
a = input(2, title = "sensitivity")
c = input(1, title = "ATR Period")
h = input(false, title = "Base On Heikin Ashi Candles")
xATR = atr(c)
nLoss = a * xATR
src = h ? security(heikinashi(syminfo.tickerid), timeframe.period, close, lookahead = false) : close
//INPUT
xATRTS = 0.0
xATRTS:= iff(src > nz(xATRTS[1], 0) and src[1] > nz(xATRTS[1], 0), max(nz(xATRTS[1]), src - nLoss),
iff(src < nz(xATRTS[1], 0) and src[1] < nz(xATRTS[1], 0), min(nz(xATRTS[1]), src + nLoss),
iff(src > nz(xATRTS[1], 0), src - nLoss, src + nLoss)))
pos = 0
pos := iff(src[1] < nz(xATRTS[1], 0) and src > nz(xATRTS[1], 0), 1,
iff(src[1] > nz(xATRTS[1], 0) and src < nz(xATRTS[1], 0), -1, nz(pos[1], 0)))
xcolor = pos == -1 ? color.red: pos == 1 ? color.green : color.blue
ema = ema(src,1)
above = crossover(ema, xATRTS)
below = crossover(xATRTS, ema)
BL = src > xATRTS and above
SS = src < xATRTS and below
barBL = src > xATRTS
barSS = src < xATRTS
plotshape(BL, title = "LONG", text = 'LONG', style = shape.labelup, location = location.belowbar, color= color.blue, textcolor = color.white, transp = 0, size = size.tiny)
plotshape(SS, title = "SHORT", text = 'SHORT', style = shape.labeldown, location = location.abovebar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny)
barcolor(barBL ? color.rgb(255, 255, 255) : na)
barcolor(barSS ? color.rgb(3, 3, 3) : na)
//EMA
EMA1 = input(200, minval=1)
EMA2 = input(34, minval=1)
xPrice = close
xEMA2 = ema(xPrice, EMA1)
xEMA1 = ema(xPrice, EMA2)
plot(xEMA2, color=#9c27b0, title="EMA")
plot(xEMA1, color=#250dff, title="EMA")
|
Magic EMA Ultra [Jay Jani] | https://www.tradingview.com/script/aSIWCsNL-Magic-EMA-Ultra-Jay-Jani/ | jayjani0007 | https://www.tradingview.com/u/jayjani0007/ | 16 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jayjani0007
//@version=4
study(title="Warrior Thunderbolt Indicator", shorttitle="WTI", overlay=true)
showpivot = input(defval = true, title="Show Pivot Points")
showEMA9 = input(title="Show EMA9", type=input.bool, defval=true)
showEMA20 = input(title="Show EMA20", type=input.bool, defval=true)
showEMA50 = input(title="Show EMA50", type=input.bool, defval=true)
showEMA100 = input(title="Show EMA100", type=input.bool, defval=true)
showEMA200 = input(title="Show EMA200", type=input.bool, defval=true)
showVWAP = input(title="Show VWAP", type=input.bool, defval=true)
showBB = input(title="Show BB", type=input.bool, defval=true)
prevDH = input(true, title="Show previous Day high?")
prevDL = input(true, title="show previous Day low?")
EMA9_Len = input(9, minval=1, title="EMA9_Length")
EMA9_src = input(close, title="EMA9_Source")
//EMA9_offset = input(title="EMA9_Offset", type=input.integer, defval=0, minval=-500, maxval=500)
EMA9_out = ema(EMA9_src, EMA9_Len)
plot(showEMA9 ? EMA9_out:na, title="EMA9", color=color.yellow, offset=0)
EMA20_Len = input(20, minval=1, title="EMA20_Length")
EMA20_src = input(close, title="EMA20_Source")
//EMA20_offset = input(title="EMA20_Offset", type=input.integer, defval=0, minval=-500, maxval=500)
EMA20_out = ema(EMA20_src, EMA20_Len)
plot(showEMA20 ? EMA20_out:na, title="EMA20", color=color.blue, offset=0)
EMA50_Len = input(50, minval=1, title="EMA50_Length")
EMA50_src = input(close, title="EMA50_Source")
//EMA50_offset = input(title="EMA50_Offset", type=input.integer, defval=0, minval=-500, maxval=500)
EMA50_out = ema(EMA50_src, EMA50_Len)
plot(showEMA50 ? EMA50_out:na, title="EMA50", color=color.green, offset=0)
EMA100_Len = input(100, minval=1, title="EMA100_Length")
EMA100_src = input(close, title="EMA100_Source")
//EMA100_offset = input(title="EMA100_Offset", type=input.integer, defval=0, minval=-500, maxval=500)
EMA100_out = ema(EMA100_src, EMA100_Len)
plot(showEMA100 ? EMA100_out:na, title="EMA100", color=color.red, offset=0)
EMA200_Len = input(200, minval=1, title="EMA200_Length")
EMA200_src = input(close, title="EMA200_Source")
//EMA200_offset = input(title="EMA200_Offset", type=input.integer, defval=0, minval=-500, maxval=500)
EMA200_out = ema(EMA20_src, EMA200_Len)
plot(showEMA200 ? EMA200_out:na, title="EMA200", color=color.lime, offset=0)
// Get user input
vwaplength= input(title="VWAP Length", type=input.integer, defval=1)
cvwap = ema(vwap,vwaplength)
plotvwap = plot(showVWAP ? cvwap : na,title="VWAP",color=color.orange, transp=0, linewidth=2)
length = input(20, minval=1)
src = input(close, title="BB_Source")
mult = input(2.0, minval=0.001, maxval=50, title="BB_StdDev")
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
plot(showBB ? basis : na, "Basis", color=#872323, offset = offset)
p1 = plot(showBB ? upper : na, "Upper", color=color.teal, offset = offset)
p2 = plot(showBB ? lower: na, "Lower", color=color.teal, offset = offset)
fill(p1, p2, title = "Background", color=#198787, transp=95)
//previous day
prevDayHigh = security(syminfo.tickerid, 'D', high[1], lookahead=true)
prevDayLow = security(syminfo.tickerid, 'D', low[1], lookahead=true)
//previous day Plots
plot( prevDH and prevDayHigh ? prevDayHigh : na, title="Prev Day High", style=plot.style_stepline, linewidth=2, color=color.red, transp=0)
plot( prevDL and prevDayLow ? prevDayLow : na, title="Prev Day Low", style=plot.style_stepline, linewidth=2, color=color.green, transp=0)
// colours for the chart
col0 = #6666ff
col1 = #ebdc87
col2 = #ffa36c
col3 = #d54062
colD = #799351
res = input(title="Resolution", type=input.resolution, defval="D")
h = security(syminfo.tickerid, res, high[1], barmerge.gaps_off, barmerge.lookahead_on)
l = security(syminfo.tickerid, res, low[1], barmerge.gaps_off, barmerge.lookahead_on)
c = security(syminfo.tickerid, res, close[1], barmerge.gaps_off, barmerge.lookahead_on)
// Pivot Range Calculations: Fibonac0
pivot = (h + l + c) / 3.0
plotF = input(defval=false, title="Plot 0.236", type=input.bool)
supp0 = (pivot - (0.236 * (h - l)))
supp1 = (pivot - (0.382 * (h - l)))
supp2 = (pivot - (0.618 * (h - l)))
supp3 = (pivot - (1 * (h - l)))
res0 = (pivot + (0.236 * (h - l)))
res1 = (pivot + (0.382 * (h - l)))
res2 = (pivot + (0.618 * (h - l)))
res3 = (pivot + (1 * (h - l)))
plot(showpivot ? pivot : na, title="D Pivot", style=plot.style_stepline, color=color.black, linewidth=2)
plot(plotF ? supp0 : na, title="0.236", style=plot.style_stepline, color=color.orange , linewidth=1)
plot(showpivot ? supp1 : na, title="S1", style=plot.style_stepline, color=color.orange, linewidth=1)
plot(showpivot ? supp2 : na , title="S2", style=plot.style_stepline, color=color.orange, linewidth=1)
plot(showpivot ? supp3 : na, title="S3", style=plot.style_stepline, color=color.orange, linewidth=1)
plot(plotF ? res0 : na, title="0.236", style=plot.style_stepline, color=color.orange, linewidth=1)
plot(showpivot ? res1 : na, title="R1", style=plot.style_stepline, color=color.orange, linewidth=1)
plot(showpivot ? res2 : na, title="R2", style=plot.style_stepline, color=color.orange, linewidth=1)
plot(showpivot ? res3 : na, title="R3", style=plot.style_stepline, color=color.orange, linewidth=1) |
EPS Surprise (Working) | https://www.tradingview.com/script/Os5ukEZt-EPS-Surprise-Working/ | jerrylui | https://www.tradingview.com/u/jerrylui/ | 29 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jerrylui
//@version=5
indicator("EPS Surprise")
earning = request.earnings(syminfo.tickerid, earnings.actual)
estimate = request.earnings(syminfo.tickerid, earnings.estimate)
p1 = plot(earning, "Actual", color=color.white, linewidth=1)
p2 = plot(estimate, "Estimate", color=color.gray, linewidth=1)
fill(p1, p2, color=(earning>=estimate)?color.green:color.red, title="Fill Color") |
Gold Silver Spread | https://www.tradingview.com/script/OcAUu6Yl-Gold-Silver-Spread/ | ktgnaidu | https://www.tradingview.com/u/ktgnaidu/ | 2 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © bensonsuntw
// updation inspired by Morty
//@version=4
study("Gold Silver Spread")
s1 = input(title="pair1",type=input.symbol,defval="MCX:SILVERM1!")
s2 = input(title="pair2",type=input.symbol,defval="MCX:GOLDM1!")
f() => [open,high,low,close]
[o1,h1,l1,c1]=security(s1,timeframe.period,f())
[o2,h2,l2,c2]=security(s2,timeframe.period,f())
plotcandle(o1-o2, h1-h2, l1-l2, c1-c2,color = o1-o2 < c1-c2 ? color.green : color.red, wickcolor=color.black)
|
On Balance Volume Deviation | https://www.tradingview.com/script/4vysQCTV-On-Balance-Volume-Deviation/ | bkeevil | https://www.tradingview.com/u/bkeevil/ | 82 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © bkeevil
// Adapted from the OBV indicator code provided by TradingView
// Purpose: To be a leading indicator of a large price change based on the premise that a large spike in volume will lead to a future change in price.
// Description: Displays a histogram of the deviation of the On Balance Volume (OBV) indicator
// This is overlayed on an SMA area chart of this deviation.
// Useage: When the histogram bars are higher than the area plot, then there is about to be a jump in price. Seems to work better on shorter timeframes.
// Reference: https://www.investopedia.com/terms/o/onbalancevolume.asp
// @version=5
indicator(title="On Balance Volume Deviation", shorttitle="OBV-DEV", overlay=false, precision=0, format=format.inherit, timeframe="", timeframe_gaps=true)
COLOR_DEV = color.new(color.purple,0)
COLOR_SMA = color.new(color.blue,80)
devLengthInput = input.int(defval=4, title="Deviation Length", minval=1, tooltip="Number of periods for SMA to calculate OBV deviation")
smaLengthInput = input.int(defval=8, title="Smoothing Length", minval=1, tooltip="Number of periods for SMA to smooth deviation histogram")
// cumVol is not used in obv calculations, only to detect the presence of volume data
var cumVol = 0.0
cumVol += nz(volume) // nz replaces NaN numbers with zeros
if barstate.islast and cumVol == 0
runtime.error("No volume is provided by the data vendor.")
// if close > previousDayClose, add todays volume to the accumulator.
// if close < previousDayClose, subtract todays volume from the accumulator.
obv = ta.cum(math.sign(ta.change(close)) * volume)
dev = ta.dev(obv, devLengthInput)
sma = ta.sma(dev, smaLengthInput)
plot(sma, "Histogram SMA", color=COLOR_SMA, style=plot.style_area)
plot(dev, "OBV Deviation", color=COLOR_DEV, style=plot.style_histogram)
|
Candle Stick Update | https://www.tradingview.com/script/ARW1j0ZI-Candle-Stick-Update/ | samiulgg | https://www.tradingview.com/u/samiulgg/ | 91 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © samiulgg
//@version=5
indicator(title="Candlestick Style Update", shorttitle="Candlestick Style Update", overlay=true, max_bars_back = 5000)
// Candlestick Style Input
activeBarUpdate = input.bool(true, "Active Candle Style?", group="Candlestick Style", tooltip="Please hide default candle chart (by clicking eye icon) to update this one.")
pline = input.bool(true, 'Show Price Line', tooltip="Please active 'Indicator and financials value labels' from Chart settings -> Scales Tab.", group="Candlestick Style")
barUpdate = input.string("Normal Candles", title="Candlestick Style", options=["Normal Candles", "Heiken Ashi Default", "Heiken Ashi Modified"], group="Candlestick Style")
// Candlestick Color Input
activeBody = input.bool(true, "", inline="Color Candle Body", group="Candlestick Color: Body")
colorBodyUp = input.color(#3179F5, "Up Color", inline="Color Candle Body", group="Candlestick Color: Body")
colorBodyDown = input.color(#787B86, "Down Color", inline="Color Candle Body", group="Candlestick Color: Body")
activeBorder = input.bool(true, "", inline="Color Candle Border", group="Candlestick Color: Border")
colorBorderUp = input.color(#3179F5, "Up Color", inline="Color Candle Border", group="Candlestick Color: Border")
colorBorderDown = input.color(#787B86, "Down Color", inline="Color Candle Border", group="Candlestick Color: Border")
activeWick = input.bool(true, "", inline="Color Candle Wick", group="Candlestick Color: Wick")
colorWickUp = input.color(#5D606B, "Up Color", inline="Color Candle Wick", group="Candlestick Color: Wick")
colorWickDown = input.color(#5D606B, "Down Color", inline="Color Candle Wick", group="Candlestick Color: Wick")
// Variables
// Normal Candles
open_Normal = request.security(ticker.new(syminfo.prefix, syminfo.ticker, session.regular), timeframe.period, open)
high_Normal = request.security(ticker.new(syminfo.prefix, syminfo.ticker, session.regular), timeframe.period, high)
low_Normal = request.security(ticker.new(syminfo.prefix, syminfo.ticker, session.regular), timeframe.period, low)
close_Normal = request.security(ticker.new(syminfo.prefix, syminfo.ticker, session.regular), timeframe.period, close)
// Heiken Ashi Default
open_HA1 = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
high_HA1 = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
low_HA1 = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
close_HA1 = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
// Heiken Ashi Modified
var open_HA2 = open
close_HA2 = 0.0
if not na(open_HA2[1])
open_HA2 := (open_HA2[1] + close_HA2[1]) / 2
open_HA2
high_HA2 = open > close ? open : close
low_HA2 = open < close ? open : close
close_HA2 := (open_HA2 + high_HA2 + low_HA2 + close) / 4
// Declaration
open_plot = barUpdate == "Heiken Ashi Default" ? open_HA1 : barUpdate == "Heiken Ashi Modified" ? open_HA2 : open_Normal
high_plot = barUpdate == "Heiken Ashi Default" ? high_HA1 : barUpdate == "Heiken Ashi Modified" ? high_HA2 : high_Normal
low_plot = barUpdate == "Heiken Ashi Default" ? low_HA1 : barUpdate == "Heiken Ashi Modified" ? low_HA2 : low_Normal
close_plot = barUpdate == "Heiken Ashi Default" ? close_HA1 : barUpdate == "Heiken Ashi Modified" ? close_HA2 : close_Normal
// Condition
body_col = open_plot > close_plot ? colorBodyDown : colorBodyUp
wick_col = open_plot > close_plot ? colorWickDown : colorWickUp
border_col = open_plot > close_plot ? colorBorderDown : colorBorderUp
// Plot
plotcandle(open_plot, high_plot, low_plot, close_plot, "Candle Colors", color=activeBarUpdate ? activeBody ? body_col : na : na, bordercolor=activeBarUpdate ? activeBorder ? border_col : na : na, wickcolor=activeBarUpdate ? activeWick ? wick_col : na : na)
plot(close_Normal, "Price Line", color = pline ? body_col : na, trackprice = pline ? true : false, style = plot.style_cross) |
Price-Filtered Ocean Natural Moving Average (NMA) [Loxx] | https://www.tradingview.com/script/K42uwKtB-Price-Filtered-Ocean-Natural-Moving-Average-NMA-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 45 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Price-Filtered Ocean Natural Moving Average (NMA) [Loxx]",
shorttitle="PFONMA [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/3
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Basic Settings")
srcin = input.string("Close", "Source", group= "Basic Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
type = input.string("Triple Exponential Moving Average - TEMA", "Price Filter Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Basic Settings")
namper = input.int(40, "NMA Period", minval=1, group = "Basic Settings")
maper = input.int(10, "Price Filter Period", minval=1, group = "Basic Settings")
colorbars = input.bool(false, "Color bars?", group = "UI Options")
frama_FC = input.int(defval=1, title="* Fractal Adjusted (FRAMA) Only - FC", group = "Moving Average Inputs")
frama_SC = input.int(defval=200, title="* Fractal Adjusted (FRAMA) Only - SC", group = "Moving Average Inputs")
instantaneous_alpha = input.float(defval=0.07, minval = 0, title="* Instantaneous Trendline (INSTANT) Only - Alpha", group = "Moving Average Inputs")
_laguerre_alpha = input.float(title="* Laguerre Filter (LF) Only - Alpha", minval=0, maxval=1, step=0.1, defval=0.7, group = "Moving Average Inputs")
lsma_offset = input.int(defval=0, title="* Least Squares Moving Average (LSMA) Only - Offset", group = "Moving Average Inputs")
_pwma_pwr = input.int(2, "* Parabolic Weighted Moving Average (PWMA) Only - Power", minval=0, group = "Moving Average Inputs")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "ADXvma - Average Directional Volatility Moving Average"
[t, s, b] = loxxmas.adxvma(src, len)
sig := s
trig := t
special := b
else if type == "Ahrens Moving Average"
[t, s, b] = loxxmas.ahrma(src, len)
sig := s
trig := t
special := b
else if type == "Alexander Moving Average - ALXMA"
[t, s, b] = loxxmas.alxma(src, len)
sig := s
trig := t
special := b
else if type == "Double Exponential Moving Average - DEMA"
[t, s, b] = loxxmas.dema(src, len)
sig := s
trig := t
special := b
else if type == "Double Smoothed Exponential Moving Average - DSEMA"
[t, s, b] = loxxmas.dsema(src, len)
sig := s
trig := t
special := b
else if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
else if type == "Fractal Adaptive Moving Average - FRAMA"
[t, s, b] = loxxmas.frama(src, len, frama_FC, frama_SC)
sig := s
trig := t
special := b
else if type == "Hull Moving Average - HMA"
[t, s, b] = loxxmas.hma(src, len)
sig := s
trig := t
special := b
else if type == "IE/2 - Early T3 by Tim Tilson"
[t, s, b] = loxxmas.ie2(src, len)
sig := s
trig := t
special := b
else if type == "Integral of Linear Regression Slope - ILRS"
[t, s, b] = loxxmas.ilrs(src, len)
sig := s
trig := t
special := b
else if type == "Instantaneous Trendline"
[t, s, b] = loxxmas.instant(src, instantaneous_alpha)
sig := s
trig := t
special := b
else if type == "Laguerre Filter"
[t, s, b] = loxxmas.laguerre(src, _laguerre_alpha)
sig := s
trig := t
special := b
else if type == "Leader Exponential Moving Average"
[t, s, b] = loxxmas.leader(src, len)
sig := s
trig := t
special := b
else if type == "Linear Regression Value - LSMA (Least Squares Moving Average)"
[t, s, b] = loxxmas.lsma(src, len, lsma_offset)
sig := s
trig := t
special := b
else if type == "Linear Weighted Moving Average - LWMA"
[t, s, b] = loxxmas.lwma(src, len)
sig := s
trig := t
special := b
else if type == "McGinley Dynamic"
[t, s, b] = loxxmas.mcginley(src, len)
sig := s
trig := t
special := b
else if type == "McNicholl EMA"
[t, s, b] = loxxmas.mcNicholl(src, len)
sig := s
trig := t
special := b
else if type == "Non-Lag Moving Average"
[t, s, b] = loxxmas.nonlagma(src, len)
sig := s
trig := t
special := b
else if type == "Parabolic Weighted Moving Average"
[t, s, b] = loxxmas.pwma(src, len, _pwma_pwr)
sig := s
trig := t
special := b
else if type == "Recursive Moving Trendline"
[t, s, b] = loxxmas.rmta(src, len)
sig := s
trig := t
special := b
else if type == "Simple Moving Average - SMA"
[t, s, b] = loxxmas.sma(src, len)
sig := s
trig := t
special := b
else if type == "Sine Weighted Moving Average"
[t, s, b] = loxxmas.swma(src, len)
sig := s
trig := t
special := b
else if type == "Smoothed Moving Average - SMMA"
[t, s, b] = loxxmas.smma(src, len)
sig := s
trig := t
special := b
else if type == "Smoother"
[t, s, b] = loxxmas.smoother(src, len)
sig := s
trig := t
special := b
else if type == "Super Smoother"
[t, s, b] = loxxmas.super(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Butterworth"
[t, s, b] = loxxmas.threepolebuttfilt(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Smoother"
[t, s, b] = loxxmas.threepolesss(src, len)
sig := s
trig := t
special := b
else if type == "Triangular Moving Average - TMA"
[t, s, b] = loxxmas.tma(src, len)
sig := s
trig := t
special := b
else if type == "Triple Exponential Moving Average - TEMA"
[t, s, b] = loxxmas.tema(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers Butterworth"
[t, s, b] = loxxmas.twopolebutter(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers smoother"
[t, s, b] = loxxmas.twopoless(src, len)
sig := s
trig := t
special := b
else if type == "Volume Weighted EMA - VEMA"
[t, s, b] = loxxmas.vwema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average"
[t, s, b] = loxxmas.zlagdema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag Moving Average"
[t, s, b] = loxxmas.zlagma(src, len)
sig := s
trig := t
special := b
else if type == "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"
[t, s, b] = loxxmas.zlagtema(src, len)
sig := s
trig := t
special := b
trig
maout = variant(type, src, maper)
mom = maout - nz(maout[1])
momRatio = 0., sumMomen = 0., ratio = 0.
for k = 0 to namper - 1
sumMomen += math.abs(nz(mom[k]))
momRatio += nz(mom[k]) * (math.sqrt(k + 1) - math.sqrt(k))
ratio := sumMomen != 0 ? math.abs(momRatio)/sumMomen : ratio
nma = 0.
nma := nz(nma[1]) + ratio * (src - nz(nma[1]))
colorout = nma > nma[1] ? greencolor : nma < nma[1] ? redcolor : color.gray
plot(nma, "NMA", color=colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
goLong = ta.crossover(nma, nma[1])
goShort = ta.crossunder(nma, nma[1])
alertcondition(goLong, title="Long", message="Ocean Natural Moving Average (NMA) [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Ocean Natural Moving Average (NMA) [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Option Calculator [elio27] | https://www.tradingview.com/script/EtOTdfpa-Option-Calculator-elio27/ | elio27 | https://www.tradingview.com/u/elio27/ | 146 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © elio27
//@version=5
indicator("Option Calculator [elio27]", shorttitle="Option Calc [elio27]", overlay=true)
// --- Inputs ---
type = input.string(defval="Call", options=["Call", "Put"], title="Option Type", confirm=true)
K = input.float(defval=0, title="Strike Price", confirm=true)
premium = input.float(defval=0, title="Premium", confirm=true)
qty = input.int(defval=1, title="Quantity", confirm=true)
labels = input.bool(defval=true, title="Show Labels")
offset = input.int(defval=15, title="Offset")
profitColor = input.color(defval=color.green, title="Positive Color")
lossColor = input.color(defval=color.red, title="Negative Color")
// --- Calculations ---
isExercised = false
isProfitable = false
breakEven = K
ret = 0.0
if type == "Call"
isExercised := close >= K // A call option is exercised when the price of the asset is superior to the strike price
breakEven += premium // The Break Even point of a call is where the benefit of buying under the current price equals the premium paid
isProfitable := close > breakEven // A call option is profitable, or "In The Money" when the price is above the Break Even point
ret += math.max(close - K, 0) * qty // The return of a call is the Maximum of S-K and 0
else
isExercised := close <= K // A put option is exercised when the price of the asset is inferior to the strike price
breakEven -= premium // The Break Even point of a put is where the benefit of seling above the current price equals the premium paid
isProfitable := close < breakEven // A put option is profitable, or "In The Money" when the price is under the Break Even point
ret += math.max(K - close, 0) * qty // The return of a put is the Maximum of K-S and 0
netReturn = ret - qty * premium // The net return of an option is its return minus the premium
// --- Outputs ---
line.new(bar_index, K, bar_index+offset, K, color = isExercised ? profitColor : lossColor, width=2)
plot(K, title="Strike Price", color = isExercised ? profitColor : lossColor, linewidth=2)
plot(breakEven, title="Break Even point", color=color.white, offset=offset, linewidth=2)
if barstate.islast and labels
label.new(bar_index + offset, breakEven, "Break Even point", color=color.white)
label.new(bar_index + offset, K, "Exercise price", color = isExercised ? profitColor : lossColor)
tbl = table.new(position.bottom_right, 2, 4, bgcolor = color.gray, frame_width = 2, frame_color = color.black)
table.cell(tbl, 0, 0, "State")
table.cell(tbl, 1, 0, isExercised ? "In The Money" : close==breakEven ? "At The Money" : "Out The Money", bgcolor = isExercised ? profitColor : lossColor)
table.cell(tbl, 0, 1, "Profitable")
table.cell(tbl, 1, 1, isProfitable ? "Yes" : "No", bgcolor = isProfitable ? profitColor : lossColor)
table.cell(tbl, 0, 2, "Return")
table.cell(tbl, 1, 2, str.tostring(ret), bgcolor = isExercised ? profitColor : lossColor)
table.cell(tbl, 0, 3, "Net Return")
table.cell(tbl, 1, 3, str.tostring(netReturn), bgcolor = isProfitable ? profitColor : lossColor)
|
Annual Returns % Comparison [By MUQWISHI] | https://www.tradingview.com/script/2VEC0XzU-Annual-Returns-Comparison-By-MUQWISHI/ | MUQWISHI | https://www.tradingview.com/u/MUQWISHI/ | 192 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MUQWISHI
//@version=5
indicator("Annual Returns %", overlay = true)
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | INPUTS |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
sTime = input.int(1999, "Start Year")
eTime = input.int(2025, "End Year" )
// Symbol
s01Opt = input.string("Chart Symbol", title = "Symbol 1 ", options =["Chart Symbol" , "Custom"], inline="s01")
s01Col = input.color(color.orange, title = "", inline="s01")
s01 = input.symbol("AMEX:SPY", title = "", inline="s01", tooltip = "Only Vaild When Choosing 'Custom'")
s02Opt = input.string("Custom", title = "Symbol 2 ", options =["Chart Symbol" , "Custom"], inline="s02")
s02Col = input.color(color.blue, title = "", inline="s02")
s02 = input.symbol("NASDAQ:QQQ", title = "", inline="s02", tooltip = "Only Vaild When Choosing 'Custom'")
// Adjustment
adjst = input.bool(true, title = "Adjust Data for Dividends?")
// Plot Location
in_plot_pos = input.string(title="Plot Location", defval= "Bottom Center",
options =["Top Right" , "Middle Right" , "Bottom Right" ,
"Top Center", "Middle Center", "Bottom Center",
"Top Left" , "Middle Left" , "Bottom Left" ], group= "Plot Setting")
// Bar Size
barHigh = input.float(0.3, "Bar Height", minval = 0.2, step= 0.01, group = "Plot Setting")
barWdth = input.float(1.5, "Bar Width" , minval = 1, step= 0.01, group = "Plot Setting")
// Plot Color
pltCol = input.color(#696969, title="Background", group = "Plot Setting")
borCol = input.color(color.silver, title="Border", group = "Plot Setting")
txtCol = input.color(color.white, title="Text", group = "Plot Setting")
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | CALCULATION |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// Calculation
yearFun(x) =>
timestamp(x, 01, 01, 0 ,0)
changeFun() =>
chngPer = float(na)
change = ta.change(close)/close[1] * 100
tim = int(na)
if time >= yearFun(sTime) and yearFun(eTime) >= time //and not na(time[1])
chngPer := change
tim := time
[chngPer, tim]
// Importing Data
adjut(s) =>
adjst ? '={"adjustment":"dividends", "symbol":"' + s + '"}' : s
ss01 = s01Opt == "Custom" ? s01 : syminfo.ticker
ss02 = s02Opt == "Custom" ? s02 : syminfo.ticker
[chg01, tim01] = request.security(adjut(ss01), "12M", changeFun())
[chg02, tim02] = request.security(adjut(ss02), "12M", changeFun())
// Get Symbol Name
sym_short(s) =>
str.substring(s, str.pos(s, ":") + 1)
// Set Up an array
arryFun(chg, tim) =>
var sym_arr = array.new_float(0)
var tim_arr = array.new_int(0)
if not na(chg) and array.size(tim_arr) == 0
array.push(sym_arr, nz(chg))
array.push(tim_arr, nz(year(tim)))
else if not na(chg) and tim != tim[1]// array.get(tim_arr, 0)
array.push(sym_arr, nz(chg))
array.push(tim_arr, nz(year(tim)))
[sym_arr, tim_arr]
// OutPut Array
[sym01_arr, tim01_arr] = arryFun(chg01, tim01)
[sym02_arr, tim02_arr] = arryFun(chg02, tim02)
// Packing Arrays' Elements
notMatch(tim1, tim2, sym2) =>
for i = 0 to array.size(tim1) - 1
if not array.includes(tim2, array.get(tim1, i))
array.insert(tim2, i, array.get(tim1, i))
array.insert(sym2, i, 0)
if barstate.islast
if array.size(tim02_arr) == 0 and array.size(tim01_arr) == 0
runtime.error("No Available Data. Enter Valid Date Range")
else
if array.size(tim02_arr) == 0 and array.size(tim01_arr) > 0
array.push(tim02_arr, array.get(tim01_arr, 0))
array.push(sym02_arr, 0)
if array.size(tim01_arr) == 0 and array.size(tim02_arr) > 0
array.push(tim01_arr, array.get(tim02_arr, 0))
array.push(sym01_arr, 0)
notMatch(tim01_arr, tim02_arr, sym02_arr)
notMatch(tim02_arr, tim01_arr, sym01_arr)
if array.size(tim01_arr) > 40
array.shift(tim01_arr), array.shift(sym01_arr)
array.shift(tim02_arr), array.shift(sym02_arr)
// Find the Maximum Number for Plot scale
coeff01 = math.max(math.abs(array.min(sym01_arr)), math.abs(array.max(sym01_arr)))
coeff02 = math.max(math.abs(array.min(sym02_arr)), math.abs(array.max(sym02_arr)))
scalCoef = 30/math.max(coeff01, coeff02)
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | TABLE |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// Get Table Position
table_pos(p) =>
switch p
"Top Right" => position.top_right
"Middle Right" => position.middle_right
"Bottom Right" => position.bottom_right
"Top Center" => position.top_center
"Middle Center" => position.middle_center
"Bottom Center" => position.bottom_center
"Top Left" => position.top_left
"Middle Left" => position.middle_left
=> position.bottom_left
var plt = table.new(position.bottom_left, 1 , 1)
// Find Number of Columns
mxArr = math.max(array.size(sym01_arr), array.size(sym02_arr))
numCol = mxArr * 3 + 2 < 17 ? 17 : mxArr * 3 + 2
// Set Up Plot Table
plt := table.new(table_pos(in_plot_pos), numCol, 68, bgcolor = color.new(pltCol, 50),
frame_width = 1, frame_color = borCol,
border_width = 0, border_color = color.new(txtCol, 100))
// Plot Cell
pltCell (x, y, w, h, col, tt) =>
table.cell(plt, x, y, width = w, height = h, bgcolor = col)
table.cell_set_tooltip(plt, x, y, tt)
// Plot Columns
pltCol (x, y, k, col) =>
pltCell(x, y > 0 ? 33 - k : y < 0 ? 35 - k : 33, barWdth, barHigh,
color.new(col, 0), str.tostring(y, "#.##")+"%")
pltCell(x, y > 0 ? 35 + k : y < 0 ? 33 + k : 33, barWdth, barHigh,
color.new(col, 100), "")
// Label Y-Axis Increments
yInc(y, val) =>
table.cell(plt, 0, y-1, text = str.tostring(val, "#") + "%",
text_color = txtCol, text_size = size.small, width = 2, height = 0.2)
table.merge_cells(plt, 0, y-1, 0, y+2)
// Plot Title
pltTtl(x, xf, txt, txtCol) =>
table.cell(plt, x, 0, width = barWdth, height = 2,
bgcolor = color.new(color.black, 100),
text_halign = text.align_center, text_valign = text.align_top,
text = txt, text_color = txtCol, text_size = size.small)
table.merge_cells(plt, x, 0, xf, 0)
if barstate.islast
if mxArr > 0
// Reset Table.
for i = 0 to numCol - 1
for j = 0 to 67
pltCell(i, j, 0.001, 0.001, color.new(txtCol, 100), "")
w= 0
for i = 2 to mxArr * 3 + 1 by 3
//Plot Columns
if math.round(scalCoef * array.get(sym01_arr, w)) == 0
pltCol(i, array.get(sym01_arr, w), 0, color.new(s01Col, 0))
else
for k = 0 to math.round(scalCoef * array.get(sym01_arr, w))
pltCol(i, array.get(sym01_arr, w), k, s01Col)
if math.round(scalCoef * array.get(sym02_arr, w)) == 0
pltCol( i+1, array.get(sym02_arr, w), 0, s02Col)
else
for h = 0 to math.round(scalCoef * array.get(sym02_arr, w))
pltCol( i+1, array.get(sym02_arr, w), h, s02Col)
// X-Axis Increments
table.cell(plt, i, 67, width = barWdth, text_color = txtCol,
text = str.tostring(array.get(tim01_arr, w)), text_size = size.small)
table.merge_cells(plt, i, 67, i+1, 67)
w := w + 1
// Plot Highlighted Color Between Interval
for i = 1 to mxArr * 3 + 1 by 3
for j = 0 to 67
pltCell(i, j, 0.3, 0.001, color.new(pltCol, 94), "")
// Draw X Axis Line (X==0)
for i = 2 to mxArr * 3
pltCell(i, 34, 0.4, 0.005, borCol, "")
// Y-Axis Increments
table.cell(plt, 0, 1, width = barWdth, height = 1)
yInc( 1, math.ceil( 30/scalCoef))
yInc(16, math.round(15/scalCoef))
yInc(33, 0/scalCoef)
yInc(50, math.round(-15/scalCoef))
yInc(64, math.floor(-30/scalCoef))
// Title
pltTtl( 1, 10, "Annual Returns %", txtCol)
pltTtl(11, 13, sym_short(ss01), s01Col)
pltTtl(14, 16, sym_short(ss02), s02Col)
|
Smoother Momentum MACD w/ DSL [Loxx] | https://www.tradingview.com/script/zns9rq44-Smoother-Momentum-MACD-w-DSL-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 120 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Smoother Momentum MACD w/ DSL [Loxx]",
shorttitle='SMMACDDSL [Loxx]',
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
darkGreenColor = #1B7E02
darkRedColor = #93021F
SM02 = 'Slope'
SM03 = 'Levels Crosses'
SM04 = 'Middle Crosses'
_smmom(float src, float per)=>
alphareg = 2.0 / (1.0 + per)
alphadbl = 2.0 / (1.0 + math.sqrt(per))
ema = src, ema21 = src, ema22 = src
if bar_index > 0
ema := nz(ema[1]) + alphareg * (src - nz(ema[1]))
ema21 := nz(ema21[1]) + alphadbl * (src - nz(ema21[1]))
ema22 := nz(ema22[1]) + alphadbl * (ema21 - nz(ema22[1]))
out = (ema22 - ema)
out
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("HAB Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
fastper = input.int(12, "Fast Period", group = "Basic Settings")
slowper = input.int(50, "Slow Period", group = "Basic Settings")
sigper = input.int(9, "Signal Period", group = "Signal/DSL Settings")
sigmatype = input.string("Exponential Moving Average - EMA", "Signal/DSL Smoothing", options = ["Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA"], group = "Signal/DSL Settings")
sigtype = input.string(SM03, "Signal type", options = [SM02, SM03, SM04], group = "Signal/DSL Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
trig
val = _smmom(src, slowper) - _smmom(src, fastper)
sig = val[1]
levelu = 0., leveld = 0., mid = 0.
levelu := (val > sig) ? variant(sigmatype, val, sigper) : nz(levelu[1])
leveld := (val < sig) ? variant(sigmatype, val, sigper) : nz(leveld[1])
state = 0.
if sigtype == SM02
if (val < sig)
state :=-1
if (val > sig)
state := 1
else if sigtype == SM03
if (val < leveld)
state :=-1
if (val > levelu)
state := 1
else if sigtype == SM04
if (val < mid)
state :=-1
if (val > mid)
state := 1
colorout = state == 1 ? greencolor : state == -1 ? redcolor : color.silver
plot(val, "Smoother Momentum MACD", color = colorout, linewidth = 3)
plot(levelu, "Level Up", color = darkGreenColor)
plot(leveld, "Level Down", color = darkRedColor)
plot(mid, "Middle", color = bar_index % 2 ? color.gray : na)
barcolor(colorbars ? colorout : na)
goLong = sigtype == SM02 ? ta.crossover(val, sig) : sigtype == SM03 ? ta.crossover(val, levelu) : ta.crossover(val, mid)
goShort = sigtype == SM02 ? ta.crossunder(val, sig) : sigtype == SM03 ? ta.crossunder(val, leveld) : ta.crossunder(val, mid)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Smoother Momentum MACD w/ DSL [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Smoother Momentum MACD w/ DSL [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Stairstep | https://www.tradingview.com/script/f3Ipzlcn-Stairstep/ | jmosullivan | https://www.tradingview.com/u/jmosullivan/ | 36 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jmosullivan
// @version=5
// Created By jmosullivan
// Stairstep
indicator(title='Stairstep', shorttitle="SS", overlay=true)
min_candles = input.int(5, 'Minimum Consecutive Candles', 3, 10, 1, tooltip="The minimum number of consecutive candles that represent a stairstep pattern.")
txtsize = input.string(defval=size.small, title="Text Size", options=[size.tiny, size.small, size.normal])
txtlen = input.string(defval="Words", title="Label Text", options=["Words", "Abbreviations"], tooltip="Show full words (Stairstep, Inside Bar) on the label, or abbreviations (SS, IB)")
show_numbers = input.bool(defval=true, title="Show # of Stairsteps")
clr_lbl_ss = input.color(color.rgb(232, 24, 170), 'Label', inline="1")
clr_txt_ss = input.color(color.white, 'Text', inline="1")
clr_txt_ib = input.color(color.yellow, 'IB Text', 'Colors of the label/text when stairstepping', inline="1")
clr_lbl_br = input.color(color.rgb(1, 95, 35), 'Break Label', inline="2")
clr_txt_br = input.color(color.rgb(96, 245, 0), 'Text', 'Colors of the label/text when stairstep breaks', inline="2")
// Apparently you can't assign high, low, open, close to a variable and then still access their history index.
// This function allows me to get around that...
getHistoryValue(direction, index) =>
ret = direction == 'Up' ? low[index] : high[index]
ret
isLastCandleGoingInDirection(direction, index) =>
movingInDirection = (direction == 'Up' and getHistoryValue(direction, index+1) <= getHistoryValue(direction, index)) or (direction == 'Down' and getHistoryValue(direction, index+1) >= getHistoryValue(direction, index))
movingInDirection
getStairstep(direction, length) =>
breaking = isLastCandleGoingInDirection(direction, 0) ? false : true
steps = 1
curr = false
i = steps
while isLastCandleGoingInDirection(direction, i) and i < 40
i := i + 1
steps := steps + 1
trending = steps >= length - 1
ret = trending ? breaking ? -1 : steps + 1 : 0
ret
// Should be used as an expression to request.security
get_inside_bar_count() =>
ib_count = 0
i = 0
maxLoops = 10
while i <= maxLoops
if (high[i+1] > high[i] and low[i+1] < low[i])
ib_count := ib_count + 1
i := i + 1
else
i := maxLoops + 1
ib_count
drawLabel(direction, len) =>
if (barstate.islast)
ss = getStairstep(direction, len)
ss_break = ss == -1
yloc = ss_break ? direction == 'Down' ? high[1] : low[1] : close
// is_ib = high <= high[1] and low >= low[1]
ib_count = get_inside_bar_count()
txt_ss = txtlen == "Words" ? "Stairstep" : "SS"
txt_ib = txtlen == "Words" ? "x Inside Bar" : "xIB"
txt_dn = txtlen == "Words" ? "Down" : "▼"
txt_up = txtlen == "Words" ? "Up" : "▲"
txt = txt_ss + ' ' + (direction == "Up" ? txt_up : txt_dn) + (ss_break ? ' Break' : '')
if (show_numbers and ss_break == false)
txt := str.tostring(ss) + " " + txt
if (ib_count > 0)
txt := txt + ', ' + str.tostring(ib_count) + txt_ib
clr = ss == -1 ? clr_lbl_br : clr_lbl_ss
txt_clr = ss == -1 ? clr_txt_br : ib_count > 0 ? clr_txt_ib : clr_txt_ss
l = label.new(x=bar_index[0]+1, y=yloc, text=txt, style=label.style_label_left, color=clr, textcolor=txt_clr, size=txtsize)
// Delete older labels (only have the latest one on the last candle)
label.delete(l[1])
// Delete the current one if there's no stairstep and no break
if (ss == 0)
label.delete(l[0])
drawLabel('Down', min_candles)
drawLabel('Up', min_candles) |
Mark Minervini | https://www.tradingview.com/script/pAciakH6/ | Fred6724 | https://www.tradingview.com/u/Fred6724/ | 1,006 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Fred6724
//@version=5
indicator('Mark Minervini', overlay=true)
// Input
bema5 = input(false, title='EMA 5', group='INDICATOR BASED ON PRICES', inline = '0')
cema5 = input(color.purple, title='Color', group='INDICATOR BASED ON PRICES', inline = '0')
bsma10 = input(false, title='SMA 10', group='INDICATOR BASED ON PRICES', inline = '0')
csma10 = input(color.red, title='Color', group='INDICATOR BASED ON PRICES', inline = '0')
bema10 = input(true, title='EMA 10', group='INDICATOR BASED ON PRICES', inline = '1')
cema10 = input(color.orange, title='Color', group='INDICATOR BASED ON PRICES', inline = '1')
bema20 = input(true, title='EMA 20', group='INDICATOR BASED ON PRICES', inline = '1')
cema20 = input(color.aqua, title='Color', group='INDICATOR BASED ON PRICES', inline = '1')
bsma50 = input(true, title='SMA 50', group='INDICATOR BASED ON PRICES', inline = '2')
csma50 = input(color.rgb(44, 138, 216), title='Color', group='INDICATOR BASED ON PRICES', inline = '2')
bsma150 = input(true, title='SMA 150', group='INDICATOR BASED ON PRICES', inline = '2')
csma150 = input(color.lime, title='Color', group='INDICATOR BASED ON PRICES', inline = '2')
bsma200 = input(true, title='SMA 200', group='INDICATOR BASED ON PRICES', inline = '3')
csma200 = input(color.red, title='Color', group='INDICATOR BASED ON PRICES', inline = '3')
aire = input(true, title='Marks Trend Template on 150-200SMA', group='INDICATOR BASED ON PRICES')
colorMM = input(color.rgb(0,230,118,80), title='Trend Template Color', group='INDICATOR BASED ON PRICES')
b52 = input(false, title='Display 52We Highs & Lows', group='INDICATOR BASED ON PRICES')
extend = input(true, title='Daily Extended Detector', group='ASSISTANCE WITH PRICE READING')
colorExtended = input(color.rgb(255,82,82,50), title='Extended Color', group='ASSISTANCE WITH PRICE READING')
iDay = input(false, title='Inside Days Detector', group='ASSISTANCE WITH PRICE READING')
colorIDay = input(color.white, title='Inside Day Color', group='ASSISTANCE WITH PRICE READING')
WtClose = input(false, title='Weekly Tight Closes Detector', group='ASSISTANCE WITH PRICE READING')
colorTightCloses = input(color.aqua, title='Color of Tight Closes Boxes', group='ASSISTANCE WITH PRICE READING')
// SMA/EMA Calculation
ema5 = ta.ema(close,5)
ema10 = ta.ema(close,10)
sma10 = ta.sma(close,10)
ema102 = ta.ema(close,10) // invisible ema10 used to display the extended area otherwise it disappears when we deactivate the first ema10
ema20 = ta.ema(close,20)
sma50 = ta.sma(close,50)
sma150 = ta.sma(close,150)
sma1502 = ta.sma(close,150) // invisible sma150 used to display the Mark Minervini Trend Template
sma200 = ta.sma(close,200)
// Ploting SMA/EMA
pema5 = plot(bema5 ? ema5:na, color=cema5)
pema10 = plot(bema10 ? ema10:na, color=cema10)
psma = plot(bsma10 ? sma10:na, color=csma10)
pema20 = plot(bema20 ? ema20:na, color=cema20)
psma50 = plot(bsma50 ? sma50:na, color=csma50)
psma150 = plot(bsma150 ? sma150:na, color=csma150)
psma200 = plot(bsma200 ? sma200:na, color=csma200)
// Mark's Trend Template Criteria = Qualifier only.
// From 'Trade Like a Stock Market Wizard'
// Trend Template
// 1. The current stock price is above both the 150-day (30-week) and the 200-day
// (40-week) moving average price lines.
// 2. The 150-day moving average is above the 200-day moving average.
// 3. The 200-day moving average line is trending up for at least 1 month (preferably
// 4–5 months minimum in most cases).
// 4. The 50-day (10-week) moving average is above both the 150-day and 200-day
// moving averages.
// 5. The current stock price is trading above the 50-day moving average.
// 6. The current stock price is at least 30 percent above its 52-week low. (Many of
// the best selections will be 100 percent, 300 percent, or greater above their
// 52-week low before they emerge from a solid consolidation period and mount
// a large scale advance.)
// 7. The current stock price is within at least 25 percent of its 52-week high (the
// closer to a new high the better).
// 8. The relative strength ranking (as reported in Investor’s Business Daily) is no
// less than 70, and preferably in the 80s or 90s, which will generally be the case
// with the better selections
//Cond 50>150>200
condTrade = (sma50>sma150 and sma150>sma200) and close>sma50 // SMA 50 > SMA 150 > SMA 200 & Close > MM50
condTrade2 = (sma200>sma200[10] and sma200[10]>sma200[20] and sma200[20]>sma200[30]) // Rising 200 SMA
srcWe = request.security(syminfo.tickerid, 'W', close)
highWe = request.security(syminfo.tickerid, 'W', high)
lowWe = request.security(syminfo.tickerid, 'W', low)
sma50Da = request.security(syminfo.tickerid, 'D', sma50)
sma150Da = request.security(syminfo.tickerid, 'D', sma150)
sma200Da = request.security(syminfo.tickerid, 'D', sma200)
// Calculation of 52-week high and 52-week low
highestWe52 = request.security(syminfo.tickerid, 'W', ta.highest(high,52)) // 52-week high
lowestWe52 = request.security(syminfo.tickerid, 'W', ta.lowest(low,52)) // 52-week low
condTrade4 = (highestWe52)*75 <= close*100 // The current stock price is within at least 25 percent of its 52-week high (the closer to a new high the better).
limitWe52 = (highestWe52)*75/100 // Calculation of the 25% threshold
condTrade3 = lowestWe52*130 <= close*100 // The current stock price is at least 30 percent above its 52-week low.
ph52=plot(b52 ? highestWe52:na)
pl52=plot(b52 ? lowestWe52:na)
plimit52=plot(b52 ? limitWe52:na, color=color.lime, style=plot.style_stepline)
condTot = condTrade and condTrade2 and condTrade3 and condTrade4
lime=color.new(color.lime,100)
psma1502 = plot((aire and condTot) and timeframe.isdaily ? sma1502:na, color=lime)
fill(psma1502,psma200, color=colorMM)
//Extended to EMA10
// Daily Close/High
DClose = request.security(syminfo.tickerid, 'D', close)
DHigh = request.security(syminfo.tickerid, 'D', high)
// Daily EMA10
DEma10 = request.security(syminfo.tickerid, 'D', ta.ema(DClose, 10))
DEma102 = request.security(syminfo.tickerid, 'D', ta.ema(DClose, 10))
// Previous condition with fix %
//condExtended = extend and ((DHigh*100/DEma10)-100>extendp)
// Test f(ATR) to make it auto-adaptable
atrDa = request.security(syminfo.tickerid, 'D', ta.atr(14))
// If the high of the candle minus the price of ema10 is above 2,1 time the Da atr (In these cases, I prefere to use multiple of 3 -> See Nicolas Tesla)
condExtended = extend and (DHigh-DEma10)>(2.1*atrDa)
orange = color.new(color.orange,100)
pema102 = plot(condExtended and timeframe.isdaily ? DEma102:na, color=orange) // Plotting another Da EMA10 only when condition is meet seems to be the only way to colorise the way I want...
sma3 = ta.sma(close,1)
blue = color.new(color.blue, 100)
psma3 = plot(sma3, color=blue)
fill(psma3,pema102, color=colorExtended)
// Weekly Tight Closes Detector
tfWeekly = timeframe.isweekly
if(tfWeekly)
// Open
WkO2 = open[2]
//Closes
WkC = close
WkC1 = close[1]
WkC2 = close[2]
// Highs
WkH = high
WkH1 = high[1]
WkH2 = high[2]
// Lows
WkL = low
WkL1 = low[1]
WkL2 = low[2]
// WEMA
Wema10 = ta.ema(close,10)
Wema20 = ta.ema(close,20)
// ATR Weekly (Used to have an auto-adaptive tight closes detector. Formula = Averages High-Low of the 14 previous bars. (Volatility measurement)
atr = ta.atr(14)
// Conditions (I like to have 3 tiny candle with tight closes so I add High and Low cond as well)
condTightClose = WkC < WkC1+(WkC1*atr/(close*2)) and WkC > WkC1-(WkC1*atr/(close*2)) and WkC1 < WkC2+(WkC2*atr/(close*2)) and WkC1 > WkC2-(WkC2*atr/(close*2)) and WkC < WkC2+(WkC2*atr/(close*2)) and WkC > WkC2-(WkC2*atr/(close*2))
condTightHigh = WkH < WkH1+(WkH1*atr/(close*2)) and WkH > WkH1-(WkH1*atr/(close*2)) and WkH1 < WkH2+(WkH2*atr/(close*2)) and WkH1 > WkH2-(WkH2*atr/(close*2))
condTightLow = WkL < WkL1+(WkL1*atr/(close*2)) and WkL > WkL1-(WkL1*atr/(close*2)) and WkL1 < WkL2+(WkL2*atr/(close*2)) and WkL1 > WkL2-(WkL2*atr/(close*2))
//condNotLowerLows = WkL2 > WkL1 and WkL1 > WkL
// I would like the script not to show me 3 tight candles when the first candle of the three is nearly full and big
// For that I wrote that the total size of the weekly wick of the candle must be 2 times bigger than the body
// But I noticed somtimes very small candle with little or no wick are still valide so added an exception ! (Yes it is far-fetched)
condFirstCandle = false
// For positive bars
if(WkC2 >= WkO2)
condFirstCandle := WkH2 - WkC2 + WkO2 - WkL2 > 2*(WkC2 - WkO2) or (WkH2-WkL2<WkH1-WkL1)
// For negative bars
if(WkC2 < WkO2)
condFirstCandle := WkH2 - WkO2 + WkC2 - WkL2 > 2*(WkO2 - WkC2) or (WkH2-WkL2<WkH1-WkL1)
// All condition together
condTot3WTight = condTightClose and (condTightHigh or condTightLow) and condFirstCandle //and not condNotLowerLows
//Plot Boxes Arround Weekly Tight Closes
highestW = ta.highest(WkH,3)
lowestW = ta.lowest (WkL,3)
if(condTot3WTight and WtClose)
box.new(bar_index[2], highestW, bar_index, lowestW, border_color = color.new(colorTightCloses,20), border_width = 1, border_style=line.style_dotted, bgcolor = color.new(colorTightCloses,85))
// Inside Bars Detector (All Timeframes)
condInside = iDay ? high[1] > high and low[1] < low:na
condBold = condInside and condInside[1] // Means two inside days in a row
if(iDay and condInside)
// I use boxes to colorize both up and down lines (Boxes with 100% transparency frames (Yes I cheat...! Always.))
b = box.new(bar_index[1], high[1], bar_index, low[1], border_color = color.new(colorIDay,100), border_width = 2, border_style=line.style_dotted, bgcolor = color.new(colorIDay,90))
l1 = line.new(bar_index[1], high[1], bar_index, high[1], color=colorIDay, style = line.style_dotted, extend = extend.none, width = condBold ? 2:1)
l2 = line.new(bar_index[1], low[1], bar_index, low[1], color=colorIDay, style = line.style_dotted, extend = extend.none, width = condBold ? 2:1)
//------------------ Markerd Highs and Lows ---------------------//
// Price Peak/Valley Points
// Highlights exact price at high or low points over a 19-period interval.
// For example, on a Daily chart, a High Price point is marked on the date
// where there has been no higher price the 9 days prior to that date and
// the 9 days following that date.
// Inputs
i_displayHL = input(true, title="Display H/L Points", group="High/Low Price Points")
i_colorHL = input(color.rgb(255,255,255,0), title='Labels Color', group="High/Low Price Points")
i_displayPc = input(false, title="%Change", group='High/Low Price Points')
i_colorPctP = input(color.rgb(0, 0, 255), title='Positive % Color', group="High/Low Price Points", inline = "z")
i_colorPctN = input(color.rgb(222,50,174,0), title='Negative %', group="High/Low Price Points", inline = "z")
i_pivot = input(9, title="Length for peak/valey points", group="High/Low Price Points")
// Definr arrays to store pivot values
var pivotHighValues = array.new_float(0)
var pivotLowValues = array.new_float(0)
if(i_displayHL and not tfWeekly)
// Use the function ta.pivothigh/low()
pivotHigh = ta.pivothigh(high, i_pivot, i_pivot)
pivotLow = ta.pivotlow (low, i_pivot, i_pivot)
// High Price Point
if(pivotHigh)
array.unshift(pivotHighValues, high[i_pivot])
textHigh9 = i_displayPc ? str.tostring(high[i_pivot], '0.00')+'\n':str.tostring(high[i_pivot], '0.00')
highestHigh = label.new(bar_index-i_pivot, array.get(pivotHighValues, 0), xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, text=textHigh9, textcolor=i_colorHL)
// Low Price Point
if(pivotLow)
array.unshift(pivotLowValues, low[i_pivot]) //low[i_pivot]
textLow9 = "\n" + str.tostring(low[i_pivot], '0.00')
lowestLow = label.new(bar_index-i_pivot, array.get(pivotLowValues, 0), xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_center, text=textLow9, textcolor=i_colorHL, color=color.rgb(0,0,0,100))
// Percentage Variation
float pHigh = na
float pLow = na
if array.size(pivotHighValues) > 0
pHigh := array.get(pivotHighValues, 0)
if array.size(pivotLowValues) > 0
pLow := array.get(pivotLowValues, 0)
prcVarHigh = (pHigh - pLow)/pLow * 100
prcVarLow = (pLow/pHigh - 1) * 100 // Formula to calculate percentage decline
prcVarHighText = prcVarHigh>=0 ? '+'+str.tostring(prcVarHigh, '0.0') + '%':str.tostring(prcVarHigh, '0.0') + '%'
prcVarLowText = prcVarLow>=0 ? '+'+str.tostring(prcVarLow , '0.0') + '%':str.tostring(prcVarLow, '0.0') + '%'
colorPctUp = prcVarHigh>=0 ? i_colorPctP:i_colorPctN
colorPctDn = prcVarLow >=0 ? i_colorPctP:i_colorPctN
// High Price Point Percent Variation
if(pivotHigh and i_displayPc)
pctPivotHigh = na(prcVarHigh)==true ? na:label.new(bar_index-i_pivot, array.get(pivotHighValues, 0), xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, text=prcVarHighText, textcolor=colorPctUp)
if(pivotLow and i_displayPc)
pctPivotLow = na(prcVarLow)==true ? na:label.new(bar_index-i_pivot, array.get(pivotLowValues, 0), xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_center, text="\n\n\n" + prcVarLowText, textcolor=colorPctDn, color=color.rgb(0,0,0,100)) |
Economic Calendar (Import from Spreadsheet) | https://www.tradingview.com/script/E0KaEY2L-Economic-Calendar-Import-from-Spreadsheet/ | DojiEmoji | https://www.tradingview.com/u/DojiEmoji/ | 575 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DojiEmoji
//@version=5
indicator("Economic Calendar [DojiEmoji]", overlay=true, max_lines_count=500, max_labels_count=500)
// Obtain source data:
// ie. Step 1: By obtaining from: https://www.fxstreet.com/economic-calendar
// Step 2: Using external tools (ie Excel, Python, etc.) to create a line of text that resembles
// calendar events.
//
// This script uses the following standardized format:
//
// Format = <timezone>;<date1>;<date2>; ... etc, up to the last event on <date_n>
// Where: 'date' is expressed as: YYYY,MM,DD,hh,mm,ss
//
// -----------------------
// Settings:
// -----------------------
// {
var bool show_table = input.bool(true, title="Show table displaying legend for colors")
var string str_table_position = input.string(position.bottom_right, options=[position.bottom_right, position.top_right, position.bottom_left], title="Location of table")
var color bgcolor_table = input.color(color.new(color.black,90), title="Background", inline="ln1")
var string font_size = input.string(size.small, inline="ln1", title="Font size", options=[size.tiny, size.small, size.normal, size.large, size.huge])
var string GROUP_CAT1 = "--------------- Category 1 ---------------"
var string name_cat1 = input.string("Fed", title="", inline="ln1", group=GROUP_CAT1)
var bool show_cat_1 = input.bool(true, title="Show category:", inline="ln1", group=GROUP_CAT1)
var color linecolor_cat1 = input.color(color.new(color.red,50), title="", inline="ln2", group=GROUP_CAT1)
var string str_input_1 = input.text_area(title="Source Data, Category 1:", group=GROUP_CAT1,
tooltip="Pasted From external tools (ie. Spreadsheet). A template has been provided in the blog post associated with this script).",
defval="GMT;2023,1,4,19,0,0;2023,1,10,14,0,0;2023,2,1,19,0,0;2023,2,1,19,0,0;2023,2,1,19,30,0;2023,2,7,17,40,0;2023,2,22,19,0,0;2023,3,7,15,0,0;2023,3,8,15,0,0;2023,3,22,18,0,0;2023,3,22,18,0,0;2023,3,22,18,0,0;2023,3,22,18,30,0;2023,4,12,18,0,0;2023,5,3,18,0,0;2023,5,3,18,0,0;2023,5,3,18,30,0;2023,5,19,15,0,0;2023,5,24,18,0,0;2023,6,14,18,0,0;2023,6,14,18,0,0;2023,6,14,18,0,0;2023,6,14,18,30,0;2023,6,21,14,0,0;2023,6,22,14,0,0;2023,6,28,13,30,0;2023,6,29,6,30,0;2023,7,5,18,0,0;2023,7,26,18,0,0;2023,7,26,18,0,0;2023,7,26,18,30,0;2023,8,16,18,0,0;2023,9,20,18,0,0;2023,9,20,18,0,0;2023,9,20,18,0,0;2023,9,20,18,30,0;2023,10,11,18,0,0;")
var int linewidth_cat1 = input.int(2, title="Width", minval=1, maxval=5, inline="ln2", group=GROUP_CAT1)
var string GROUP_CAT2 = "--------------- Category 2 ---------------"
var string name_cat2 = input.string("PMI", title="", inline="ln1", group=GROUP_CAT2)
var bool show_cat_2 = input.bool(true, title="Show category:", inline="ln1", group=GROUP_CAT2)
var color linecolor_cat2 = input.color(color.new(color.blue,50), title="", inline="ln2", group=GROUP_CAT2)
var string str_input_2 = input.text_area(title="Source Data, Category 2:", group=GROUP_CAT2,
tooltip="Pasted From external tools (ie. Spreadsheet). A template has been provided in the blog post associated with this script).",
defval="GMT;2023,1,4,15,0,0;2023,1,6,15,0,0;2023,2,1,15,0,0;2023,2,3,15,0,0;2023,3,1,15,0,0;2023,3,3,15,0,0;2023,4,3,14,0,0;2023,4,5,14,0,0;2023,5,1,14,0,0;2023,5,3,14,0,0;2023,6,1,14,0,0;2023,6,5,14,0,0;2023,7,3,14,0,0;2023,7,6,14,0,0;2023,7,24,13,45,0;2023,7,24,13,45,0;2023,8,1,14,0,0;2023,8,3,14,0,0;2023,8,23,13,45,0;2023,8,23,13,45,0;2023,9,1,14,0,0;2023,9,4,14,0,0;2023,9,22,13,45,0;2023,9,22,13,45,0;2023,10,2,14,0,0;2023,10,4,14,0,0;2023,10,24,13,45,0;2023,10,24,13,45,0;")
var int linewidth_cat2 = input.int(2, title="Width", minval=1, maxval=5, inline="ln2", group=GROUP_CAT2)
var string GROUP_CAT3 = "--------------- Category 3 ---------------"
var string name_cat3 = input.string("Retail Sales", title="", inline="ln1", group=GROUP_CAT3)
var bool show_cat_3 = input.bool(true, title="Show category:", inline="ln1", group=GROUP_CAT3)
var color linecolor_cat3 = input.color(color.new(color.orange,50), title="", inline="ln2", group=GROUP_CAT3)
var string str_input_3 = input.text_area(title="Source Data, Category 3:", group=GROUP_CAT3,
tooltip="Pasted From external tools (ie. Spreadsheet). A template has been provided in the blog post associated with this script).",
defval="GMT;2023,1,18,13,30,0;2023,1,18,13,30,0;2023,2,15,13,30,0;2023,2,15,13,30,0;2023,3,15,12,30,0;2023,3,15,12,30,0;2023,4,14,12,30,0;2023,4,14,12,30,0;2023,5,16,12,30,0;2023,5,16,12,30,0;2023,6,15,12,30,0;2023,6,15,12,30,0;2023,7,18,12,30,0;2023,7,18,12,30,0;2023,8,15,12,30,0;2023,8,15,12,30,0;2023,9,14,12,30,0;2023,9,14,12,30,0;2023,10,17,12,30,0;2023,10,17,12,30,0;")
var int linewidth_cat3 = input.int(2, title="Width", minval=1, maxval=5, inline="ln2", group=GROUP_CAT3)
var string GROUP_CAT4 = "--------------- Category 4 ---------------"
var string name_cat4 = input.string("CPI", title="", inline="ln1", group=GROUP_CAT4)
var bool show_cat_4 = input.bool(true, title="Show category:", inline="ln1", group=GROUP_CAT4)
var color linecolor_cat4 = input.color(color.new(color.green,50), title="", inline="ln2", group=GROUP_CAT4)
var string str_input_4 = input.text_area(title="Source Data, Category 4:", group=GROUP_CAT4,
tooltip="Pasted From external tools (ie. Spreadsheet). A template has been provided in the blog post associated with this script).",
defval="GMT;2023,1,12,13,30,0;2023,1,12,13,30,0;2023,2,14,13,30,0;2023,2,14,13,30,0;2023,3,14,12,30,0;2023,3,14,12,30,0;2023,4,12,12,30,0;2023,4,12,12,30,0;2023,5,10,12,30,0;2023,5,10,12,30,0;2023,6,13,12,30,0;2023,6,13,12,30,0;2023,7,12,12,30,0;2023,7,12,12,30,0;2023,7,12,12,30,0;2023,7,12,12,30,0;2023,8,10,12,30,0;2023,8,10,12,30,0;2023,8,10,12,30,0;2023,8,10,12,30,0;2023,9,13,12,30,0;2023,9,13,12,30,0;2023,9,13,12,30,0;2023,9,13,12,30,0;2023,10,12,12,30,0;2023,10,12,12,30,0;2023,10,12,12,30,0;2023,10,12,12,30,0;")
var int linewidth_cat4 = input.int(2, title="Width", minval=1, maxval=5, inline="ln2", group=GROUP_CAT4)
var string GROUP_CAT5 = "--------------- Category 5 ---------------"
var string name_cat5 = input.string("Others", title="", inline="ln1", group=GROUP_CAT5)
var bool show_cat_5 = input.bool(true, title="Show category:", inline="ln1", group=GROUP_CAT5)
var color linecolor_cat5 = input.color(color.new(color.teal,50), title="", inline="ln2", group=GROUP_CAT5)
var string str_input_5 = input.text_area(title="Source Data, Category 5:", group=GROUP_CAT5,
tooltip="Pasted From external tools (ie. Spreadsheet). A template has been provided in the blog post associated with this script).",
defval="GMT;2023,1,5,13,15,0;2023,1,6,13,30,0;2023,1,12,13,30,0;2023,1,13,15,0,0;2023,1,26,13,30,0;2023,1,26,13,30,0;2023,1,26,13,30,0;2023,2,1,13,15,0;2023,2,3,13,30,0;2023,2,8,2,0,0;2023,2,10,15,0,0;2023,2,23,13,30,0;2023,2,27,13,30,0;2023,2,27,13,30,0;2023,3,8,13,15,0;2023,3,10,13,30,0;2023,3,13,13,0,0;2023,3,17,14,0,0;2023,3,22,18,0,0;2023,3,22,18,0,0;2023,3,22,18,0,0;2023,3,22,18,0,0;2023,3,24,12,30,0;2023,3,24,12,30,0;2023,3,30,12,30,0;2023,4,5,12,15,0;2023,4,7,12,30,0;2023,4,14,14,0,0;2023,4,26,12,30,0;2023,4,26,12,30,0;2023,4,27,12,30,0;2023,5,3,12,15,0;2023,5,5,12,30,0;2023,5,12,14,0,0;2023,5,25,12,30,0;2023,5,26,12,30,0;2023,5,26,12,30,0;2023,6,1,12,15,0;2023,6,2,12,30,0;2023,6,14,18,0,0;2023,6,14,18,0,0;2023,6,14,18,0,0;2023,6,14,18,0,0;2023,6,16,14,0,0;2023,6,28,20,30,0;2023,6,29,12,30,0;2023,6,30,12,30,0;2023,6,30,12,30,0;2023,7,6,12,15,0;2023,7,7,12,30,0;2023,7,7,12,30,0;2023,7,7,12,30,0;2023,7,13,12,30,0;2023,7,14,14,0,0;2023,7,27,12,30,0;2023,7,28,12,30,0;2023,7,28,12,30,0;2023,8,2,12,15,0;2023,8,4,12,30,0;2023,8,4,12,30,0;2023,8,4,12,30,0;2023,8,11,12,30,0;2023,8,11,14,0,0;2023,8,24,12,30,0;2023,8,31,12,30,0;2023,8,31,12,30,0;2023,9,1,12,30,0;2023,9,1,12,30,0;2023,9,1,12,30,0;2023,9,6,12,15,0;2023,9,14,12,30,0;2023,9,15,14,0,0;2023,9,20,18,0,0;2023,9,20,18,0,0;2023,9,20,18,0,0;2023,9,20,18,0,0;2023,9,20,18,0,0;2023,9,28,12,30,0;2023,9,29,12,30,0;2023,9,29,12,30,0;2023,10,4,12,15,0;2023,10,6,12,30,0;2023,10,6,12,30,0;2023,10,6,12,30,0;2023,10,11,12,30,0;2023,10,13,14,0,0;2023,10,26,12,30,0;2023,10,27,12,30,0;2023,10,27,12,30,0;")
var int linewidth_cat5 = input.int(2, title="Width", minval=1, maxval=5, inline="ln2", group=GROUP_CAT5)
// }
// @function : _adjust
// To adjust for potential timing differences.
// Original Unix time might cause lines to offset when chart is viewed on other timeframes (ie 12hour).
//
// Thanks to @jdehorty for pointing this out and letting me use his logic for converting.
// https://www.tradingview.com/script/HLYDwa0N-Economic-Calendar-Events-FOMC-CPI-and-more/
_adjust(int t) =>
switch
timeframe.isdaily and timeframe.multiplier > 1 => t - timeframe.multiplier*86400000 // -n days
timeframe.isweekly => t - timeframe.multiplier*604800000 // -n week(s)
timeframe.ismonthly => t - timeframe.multiplier*2592000000 // -n month(s)
timeframe.isminutes and timeframe.multiplier > 60 => t - timeframe.multiplier*60000 // -n minutes
=> t
// @function : get_timestamps
// @returns array of int : Date of Events in Unix time, sorted.
get_timestamps(string str_input) =>
string[] tokens = str.split(str_input,";")
string timezone = array.get(tokens, 0)
int[] return_arr_time = array.new_int()
for i=1 to array.size(tokens)-1 // start from i=1; First element is reserved for 'timezone'
string[] subtokens = str.split(array.get(tokens,i), ",")
if array.size(subtokens) > 0
// Parse
int yyyy = int(str.tonumber(array.get(subtokens, 0)))
int mmm = int(str.tonumber(array.get(subtokens, 1)))
int dd = int(str.tonumber(array.get(subtokens, 2)))
int hh = int(str.tonumber(array.get(subtokens, 3)))
int mm = int(str.tonumber(array.get(subtokens, 4)))
int ss = int(str.tonumber(array.get(subtokens, 5)))
// Store
array.push(return_arr_time, _adjust(timestamp(timezone, yyyy, mmm, dd, hh, mm, ss)))
array.sort(return_arr_time, order.ascending)
return_arr_time
var tbl = table.new(str_table_position, 1, 5, frame_color=na, frame_width=0, border_width=0, border_color=na)
put_table(string text_size=size.small, color bgcolor) =>
table.cell(tbl, 0, 0, name_cat1, text_halign = text.align_left, text_color=linecolor_cat1, bgcolor = bgcolor, text_size = text_size)
table.cell(tbl, 0, 1, name_cat2, text_halign = text.align_left, text_color=linecolor_cat2, bgcolor = bgcolor, text_size = text_size)
table.cell(tbl, 0, 2, name_cat3, text_halign = text.align_left, text_color=linecolor_cat3, bgcolor = bgcolor, text_size = text_size)
table.cell(tbl, 0, 3, name_cat4, text_halign = text.align_left, text_color=linecolor_cat4, bgcolor = bgcolor, text_size = text_size)
table.cell(tbl, 0, 4, name_cat5, text_halign = text.align_left, text_color=linecolor_cat5, bgcolor = bgcolor, text_size = text_size)
// MAIN:
// {
var bool is_done = false
var string[] name_cat = array.from(name_cat1, name_cat2, name_cat3, name_cat4, name_cat5)
var bool[] show_cat = array.from(show_cat_1, show_cat_2, show_cat_3, show_cat_4, show_cat_5)
var string[] str_input = array.from(str_input_1, str_input_2, str_input_3, str_input_4, str_input_5)
var color[] linecolor = array.from(linecolor_cat1, linecolor_cat2, linecolor_cat3, linecolor_cat4, linecolor_cat5)
var int[] linewidth = array.from(linewidth_cat1, linewidth_cat2, linewidth_cat3, linewidth_cat4, linewidth_cat5)
if barstate.islast and not is_done
for i=0 to array.size(name_cat)-1
string _input = array.get(str_input, i)
_input := str.replace_all(_input, " ", "")
if array.get(show_cat, i) and _input != ""
if _input == ""
runtime.error(message = "Source data is empty: " + array.get(name_cat,i ))
_timestamps = get_timestamps(_input)
// Assert -> int[] timestamps sorted by chronological order
// Due to PineScript limitations - max. 500 lines on chart
// We should only show the most recent
max_lines = 100 // 100 lines for each category (total = 5 categories)
_n = array.size(_timestamps)
_lncol = array.get(linecolor, i)
_lnwidth = array.get(linewidth, i)
for j=math.max(0, _n - max_lines) to _n-1
t = array.get(_timestamps, j)
line.new(t, close, t, close*1.0001, xloc.bar_time, extend.both, _lncol, width=_lnwidth)
if show_table
put_table(font_size, bgcolor_table)
is_done := true
// }
|
Multi Type RSI [Misu] | https://www.tradingview.com/script/eB7fKKbR-Multi-Type-RSI-Misu/ | Fontiramisu | https://www.tradingview.com/u/Fontiramisu/ | 433 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
//@version=5
indicator(title="Multi Type RSI [Misu]", shorttitle="Multi RSI [Misu]", format=format.price, precision=2)
ma(source, length, type) =>
switch type
"SMMA (RMA)" => ta.rma(source, length)
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
lenRsi = input.int(14, minval=1, title="Lenght RSI", group="RSI Settings")
rsiMaTypeInput = input.string("EMA", title="RSI MA Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="RSI Settings")
lenFastMA = input.int(3, minval=1, title="Fast Lenght MA", group="RSI Settings")
lenSlowMA = input.int(5, minval=1, title="Slow Lenght MA", group="RSI Settings")
maTypeInput = input.string("EMA", title="Smoothing MA Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="RSI Settings")
lenLowerBand = input.float(25, minval=1, title="Lower Band", group="RSI Settings")
lenUpperBand = input.float(75, minval=1, title="Upper Band", group="RSI Settings")
signalType = input.string("Cross 2 Mas", options=["Cross 2 Mas", "Cross Ma/Bands"], title="Signal Type", group="RSI Settings")
up = ma(math.max(ta.change(rsiSourceInput), 0), lenRsi, rsiMaTypeInput)
down = ma(-math.min(ta.change(rsiSourceInput), 0), lenRsi, rsiMaTypeInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
// ---
rsiMaF = ma(rsi,lenFastMA, maTypeInput)
rsiMaS = ma(rsi,lenSlowMA, maTypeInput)
// ---
// Plot Rsi.
plot_0 = plot(rsiMaF, "RSI Slow", color=color.green, linewidth=1)
plot_1 = plot(rsiMaS, "RSI Fast", color=color.red, linewidth=1)
// Draw Bands.
rsiUpperBand = hline(lenUpperBand, "RSI Dmi Upper Band", color=#787B86)
hline(50, "RSI Dmi Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(lenLowerBand, "RSI Dmi Lower Band", color=#787B86)
// Define Cross params & Draw circles.
crossSell = signalType == "Cross 2 Mas" ? ta.crossunder(rsiMaF, rsiMaS) and rsiMaF > lenUpperBand : ta.crossunder(rsiMaF, lenUpperBand)
crossBuy = signalType == "Cross 2 Mas" ? ta.crossover(rsiMaF, rsiMaS) and rsiMaF < lenLowerBand : ta.crossover(rsiMaF, lenLowerBand)
alertcondition(crossSell, "Sell Signal", "Sell Signal")
alertcondition(crossBuy, "Buy Signal", "Buy Signal")
plot(crossSell ? rsiMaF: na, 'RSI Red Dots'
, color = color.red
, style = plot.style_circles
, linewidth = 4)
plot(crossBuy ? rsiMaF: na, 'RSI Green Dots'
, color = color.green
, style = plot.style_circles
, linewidth = 4)
// Fill Over.
rsiClamp = plot(math.max(lenLowerBand, math.min(lenUpperBand, rsiMaF)), title = "RSI Clamped (Not Used)", color = #00000000, editable = false)
fill(plot_0, rsiClamp, title = "Over Fill", color = rsi < 50 ? color.new(color.green, 50) : color.new(color.red, 50))
// Fill.
colorFill = rsiMaF > lenUpperBand ? color.new(color.red, 100) : rsiMaF < lenLowerBand ? color.new(color.green, 100) : rsiMaF < rsiMaS ? color.new(color.red, 90) : color.new(color.green, 90)
fill(plot_1, plot_0, colorFill)
|
TheATR: Fisher Oscillator. | https://www.tradingview.com/script/gDOOduFI-TheATR-Fisher-Oscillator/ | thealgorithmictrader | https://www.tradingview.com/u/thealgorithmictrader/ | 236 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thealgorithmictrader
//@version=5
indicator("TheATR: Fisher Oscillator.")
//User has to agree to have the indi loading on the chart.
//{
var user_consensus = input.string(defval="", title="By typing 'agree' you acknowledge the understanding about the fact 'TheATR: Fisher Oscillator.' doesn't aim and/or intend to provide any financial advice, as of its nature of being an educational tool.\n © TheATR", confirm = true, group="consensus")
var valid = false
if user_consensus == "agree"
valid := true
else
runtime.error("Type 'agree' first in order to show the algo!")
valid := false
//Fisher Oscillator Settings
//{
g_fish = "Fisher Indicator"
i_addf_fish_sign = input.bool(true, "",group=g_fish,inline="fish0")
i_addf_fish_signt = input.string("Classic Lines Crosses", "| Signals : Type",["0-Line Crosses", "Classic Lines Crosses"],group=g_fish,inline="fish0")
i_addf_fish_src = input.source(hl2, "Src",group=g_fish,inline="addf3")
i_addf_fish_l = input.int(13, "Len",group=g_fish,inline="addf3",minval=2)
i_addf_fish_alerts = input.bool(true, "Alerts",group=g_fish,inline="fishal")
g_fish_sty = "Fisher Indicator Style"
i_bull_col = input.color(color.blue, "Colors: Bull", group=g_fish_sty, inline = "sty0")
i_bear_col = input.color(color.purple, "Bear", group=g_fish_sty, inline = "sty0")
//}
//Fisher Oscillator Calculations
//{
fish_h = ta.highest(i_addf_fish_src, i_addf_fish_l)
fish_l = ta.lowest(i_addf_fish_src, i_addf_fish_l)
fish_rounding(input) =>
input > 0.99 ? 0.999 : input < -0.99 ? -0.999 : input
value = 0.0
var fisher_v = 0.0
fisher_v:=fish_rounding(0.66 * ((hl2 - fish_l) / math.max(fish_h - fish_l, 0.001) - 0.5) + 0.67 * nz(fisher_v[1]))
var fisher_vf = 0.0
fisher_vf:= 0.5 * math.log((1 + fisher_v) / math.max(1 - fisher_v, 0.001)) + 0.5 * nz(fisher_vf[1])
fisher_vfp = fisher_vf[1]
//}
//Fisher Oscillator Plots & Signals
//{
//FO Plots
hline(0.0, "Fisher Oscillator", color.gray)
plot(valid?fisher_vf:na, "Fisher V1", fisher_vf>fisher_vfp?i_bull_col:i_bear_col,2,style=plot.style_stepline)
plot(valid?fisher_vfp:na, "Fisher V1", color.gray, 2)
//FO Signals
fish_bull = i_addf_fish_signt== "Classic Lines Crosses"?ta.crossover(fisher_vf,fisher_vfp):ta.crossover(fisher_vf,0.0)
fish_bear = i_addf_fish_signt== "Classic Lines Crosses"?ta.crossunder(fisher_vf,fisher_vfp):ta.crossunder(fisher_vf,0.0)
var long_sign = array.new_label()
var short_sign = array.new_label()
//FO Signals Plots
plotshape(i_addf_fish_sign and fish_bull and valid, "Fisher Long Signals", shape.circle,location.bottom,i_bull_col,text="Long",textcolor=i_bull_col)
plotshape(i_addf_fish_sign and fish_bear and valid, "Fisher Short Signals", shape.circle,location.top,i_bear_col,text="Short",textcolor=i_bear_col)
//FO Alets
if i_addf_fish_sign and fish_bull and valid
alert("Fisher Long Alert")
if i_addf_fish_sign and fish_bear and valid
alert("Fisher Short Alert")
//}
|
Economic Calendar Events Nick | https://www.tradingview.com/script/0gy7IXMy-Economic-Calendar-Events-Nick/ | musiclife2008 | https://www.tradingview.com/u/musiclife2008/ | 49 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jdehorty
// @version=5
indicator('Economic Calendar Events', overlay=true, scale=scale.none, max_lines_count=500, max_labels_count = 500)
import jdehorty/EconomicCalendar/1 as calendar
// ==================
// ==== Settings ====
// ==================
use = input(true, "only Abbreviation")
show_fomc_meetings = input.bool(defval = true, title = "📅 FOMC", inline = "FOMC", group="⚙️ Settings", tooltip="The FOMC meets eight times a year to determine the course of monetary policy. The FOMC's decisions are announced in a press release at 2:15 p.m. ET on the day of the meeting. The press release is followed by a press conference at 2:30 p.m. ET. The FOMC's decisions are based on a review of economic and financial developments and its assessment of the likely effects of these developments on the economic outlook.")
c_fomcMeeting = input.color(color.new(color.red, 50), title = "Color", group="⚙️ Settings", inline = "FOMC")
t_fomcMeeting = "FOMC Meeting"
show_fomc_minutes = input.bool(defval = true, title = "📅 FOMC Minutes", inline = "FOMCMinutes", group="⚙️ Settings", tooltip="The FOMC minutes are released three weeks after each FOMC meeting. The minutes provide a detailed account of the FOMC's discussion of economic and financial developments and its assessment of the likely effects of these developments on the economic outlook.")
c_fomcMinutes = input.color(color.new(color.orange, 50), title = "Color", group="⚙️ Settings", inline = "FOMCMinutes")
t_fomcMinutes = "FOMC Minutes"
show_ppi = input.bool(defval = true, title = "📅 Producer Price Index (PPI)", inline = "PPI", group="⚙️ Settings", tooltip="The Producer Price Index (PPI) measures changes in the price level of goods and services sold by domestic producers. The PPI is a weighted average of prices of a basket of goods and services, such as transportation, food, and medical care. The PPI is a leading indicator of CPI.")
c_ppi = input.color(color.new(color.yellow, 50), title = "Color", group="⚙️ Settings", inline = "PPI")
t_ppi = use? 'PPI' : 'Producer Price Index'
show_cpi = input.bool(defval = true, title = "📅 Consumer Price Index (CPI)", inline = "CPI", group="⚙️ Settings", tooltip="The Consumer Price Index (CPI) measures changes in the price level of goods and services purchased by households. The CPI is a weighted average of prices of a basket of consumer goods and services, such as transportation, food, and medical care. The CPI-U is the most widely used measure of inflation. The CPI-U is based on a sample of about 87,000 households and measures the change in the cost of a fixed market basket of goods and services purchased by urban consumers.")
c_cpi = input.color(color.new(color.lime, 50), title = "Color", group="⚙️ Settings", inline = "CPI")
t_cpi = use ? 'CPI' : 'Consumer Price Index'
show_csi = input.bool(defval = true, title = "📅 Consumer Sentiment Index (CSI)", inline = "CSI", group="⚙️ Settings", tooltip="The University of Michigan's Consumer Sentiment Index (CSI) is a measure of consumer attitudes about the economy. The CSI is based on a monthly survey of 500 U.S. households. The index is based on consumers' assessment of present and future economic conditions. The CSI is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.")
c_csi = input.color(color.new(color.aqua, 50), title = "Color", group="⚙️ Settings", inline = "CSI")
t_csi = use ? 'CSI' : 'Consumer Sentiment Index'
show_cci = input.bool(defval = true, title = "📅 Consumer Confidence Index (CCI)", inline = "CCI", group="⚙️ Settings", tooltip="The Conference Board's Consumer Confidence Index (CCI) is a measure of consumer attitudes about the economy. The CCI is based on a monthly survey of 5,000 U.S. households. The index is based on consumers' assessment of present and future economic conditions. The CCI is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.")
c_cci = input.color(color.new(color.fuchsia, 50), title = "Color", group="⚙️ Settings", inline = "CCI")
t_cci = use ? 'CCI' : 'Consumer Confidence Index'
show_nfp = input.bool(defval = true, title = "📅 Non-Farm Payroll (NFP)", inline = "NFP", group="⚙️ Settings", tooltip="The Non-Farm Payroll (NFP) is a measure of the change in the number of employed persons, excluding farm workers and government employees. The NFP is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.")
c_nfp = input.color(color.new(color.silver, 50), title = "Color", group="⚙️ Settings", inline = "NFP")
t_nfp = use ? 'NFP' : 'Non-Farm Payroll'
// show_legend = input.bool(true, "Show Legend", group="⚙️ Settings", inline = "Legend", tooltip="Show the color legend for the economic calendar events.")
// =======================
// ==== Dates & Times ====
// =======================
getUnixTime(_eventArr, _index) =>
switch
timeframe.isdaily and timeframe.multiplier > 1 => array.get(_eventArr, _index) - timeframe.multiplier*86400000 // -n days
timeframe.isweekly => array.get(_eventArr, _index) - timeframe.multiplier*604800000 // -n week(s)
timeframe.ismonthly => array.get(_eventArr, _index) - timeframe.multiplier*2592000000 // -n month(s)
timeframe.isminutes and timeframe.multiplier > 60 => array.get(_eventArr, _index) - timeframe.multiplier*60000 // -n minutes
=> array.get(_eventArr, _index)
// Note: An offset of -n units is needed to realign events with the timeframe in which they occurred
if show_fomc_meetings
fomcMeetingsArr = calendar.fomcMeetings()
for i = 0 to array.size(fomcMeetingsArr) - 1
unixTime = getUnixTime(fomcMeetingsArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_fomcMeeting, width=2, xloc=xloc.bar_time)
label.new(unixTime,y = 0, yloc=yloc.price, xloc=xloc.bar_time, textcolor=c_fomcMeeting, text=t_fomcMeeting, color=color.new(color.blue, 100))
if show_fomc_minutes
fomcMinutesArr = calendar.fomcMinutes()
for i = 0 to array.size(fomcMinutesArr) - 1
unixTime = getUnixTime(fomcMinutesArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_fomcMinutes, width=2, xloc=xloc.bar_time)
label.new(unixTime,y = 0, yloc=yloc.price, xloc=xloc.bar_time, textcolor=c_fomcMinutes, text=t_fomcMinutes, color=color.new(color.blue, 100))
if show_ppi
ppiArr = calendar.ppiReleases()
for i = 0 to array.size(ppiArr) - 1
unixTime = getUnixTime(ppiArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_ppi, width=2, xloc=xloc.bar_time)
label.new(unixTime,y = 0, yloc=yloc.price, xloc=xloc.bar_time, textcolor=c_ppi, text=t_ppi, color=color.new(color.blue, 100))
if show_cpi
cpiArr = calendar.cpiReleases()
for i = 0 to array.size(cpiArr) - 1
unixTime = getUnixTime(cpiArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_cpi, width=2, xloc=xloc.bar_time)
label.new(unixTime,y = 0, yloc=yloc.price, xloc=xloc.bar_time, textcolor=c_cpi, text=t_cpi, color=color.new(color.blue, 100))
if show_csi
csiArr = calendar.csiReleases()
for i = 0 to array.size(csiArr) - 1
unixTime = getUnixTime(csiArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_csi, width=2, xloc=xloc.bar_time)
label.new(unixTime,y = 0, yloc=yloc.price, xloc=xloc.bar_time, textcolor=c_csi, text=t_csi, color=color.new(color.blue, 100))
if show_cci
cciArr = calendar.cciReleases()
for i = 0 to array.size(cciArr) - 1
unixTime = getUnixTime(cciArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_cci, width=2, xloc=xloc.bar_time)
label.new(unixTime,y = 0, yloc=yloc.price, xloc=xloc.bar_time, textcolor=c_cci, text=t_cci, color=color.new(color.blue, 100))
if show_nfp
nfpArr = calendar.nfpReleases()
for i = 0 to array.size(nfpArr) - 1
unixTime = getUnixTime(nfpArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_nfp, width=2, xloc=xloc.bar_time)
label.new(unixTime,y = 0, yloc=yloc.price, xloc=xloc.bar_time, textcolor=c_nfp, text=t_nfp, color=color.new(color.blue, 100))
// // ================
// // ==== Legend ====
// // ================
// if show_legend
// var tbl = table.new(position.top_right, columns=1, rows=8, frame_color=#151715, frame_width=1, border_width=2, border_color=color.new(color.black, 100))
// units = timeframe.isminutes ? "m" : ""
// if barstate.islast
// table.cell(tbl, 0, 0, syminfo.ticker + ' | ' + str.tostring(timeframe.period) + units, text_halign=text.align_center, text_color=color.gray, text_size=size.normal)
// table.cell(tbl, 0, 1, 'FOMC Meeting', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_fomcMeeting, 10), text_size=size.small)
// table.cell(tbl, 0, 2, 'FOMC Minutes', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_fomcMinutes, 10), text_size=size.small)
// table.cell(tbl, 0, 3, 'Producer Price Index (PPI)', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_ppi, 10), text_size=size.small)
// table.cell(tbl, 0, 4, 'Consumer Price Index (CPI)', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_cpi, 10), text_size=size.small)
// table.cell(tbl, 0, 5, 'Consumer Sentiment Index (CSI)', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_csi, 10), text_size=size.small)
// table.cell(tbl, 0, 6, 'Consumer Confidence Index (CCI)', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_cci, 10), text_size=size.small)
// table.cell(tbl, 0, 7, 'Non-Farm Payrolls (NFP)', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_nfp, 10), text_size=size.small) |
VolumeLib | https://www.tradingview.com/script/cjqwPTFt-volumelib/ | Hamster-Coder | https://www.tradingview.com/u/Hamster-Coder/ | 2 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Hamster-Coder
//@version=5
// @description Contains types and methods related to VOLUME
library("VolumeLib", overlay = true)
// @function TODO: add function description here
// @param x TODO: add parameter x description here
// @returns TODO: add what function returns
export volumePrice() =>
volume / (high - low)
// volume_price = volumePrice()
export averageVolumePrice(simple int length) =>
vp = volumePrice()
ta.sma(vp, length)
export volumePower(series float volume_price, series float average_volume_price) =>
volume_price / average_volume_price - 1
export volumePower(simple int length) =>
// avg = ta.sma(volume_price, length) // averageVolumePrice(length)
avg = averageVolumePrice(length)
price = volumePrice()
volumePower(price, avg)
|
VWAP Market Session Anchored | https://www.tradingview.com/script/zNkHo9a3-VWAP-Market-Session-Anchored/ | DeltaSeek | https://www.tradingview.com/u/DeltaSeek/ | 195 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=5
indicator("VWAP Market Session Anchored", "VWAP Market Session Anchored", true)
// CONSTANTS
// COLORS
color RED_L = #E74C3C, color RED_M = #B03A2E, color RED_D = #78281F
color ORA_L = #F0B27A, color ORA_M = #E67E22, color ORA_D = #AF601A
color YEL_L = #F7DC6F, color YEL_M = #F1C40F, color YEL_D = #B7950B
color GRE_L = #2ECC71, color GRE_M = #239B56, color GRE_D = #186A3B
color BLU_L = #85C1E9, color BLU_M = #3498DB, color BLU_D = #2874A6
color PUR_L = #8E44AD, color PUR_M = #6C3483, color PUR_D = #4A235A
color GRA_L = #BDC3C7, color GRA_M = #909497, color GRA_D = #626567
color WHI = #FFFFFF, color BLA = #000000, color CLE = #00000000
// INPUTS
float source = input.source (hlc3, "Source ", tooltip="", inline="", group="Volume Weighted Average Price")
int offset = input.int (0, "Offset ", tooltip="", inline="", group="Volume Weighted Average Price")
bool bands = input.bool (false, "Band Multiplier", tooltip="", inline="0", group="Volume Weighted Average Price")
float multiplier = input.float (1, "", tooltip="", inline="0", group="Volume Weighted Average Price")
bool sydney = input.bool (true, "Sydney ", tooltip="", inline="0", group="Session")
color sydneyColor = input.color (GRE_M, "", tooltip="", inline="0", group="Session")
bool tokyo = input.bool (true, "Tokyo ", tooltip="", inline="1", group="Session")
color tokyoColor = input.color (ORA_M, "", tooltip="", inline="1", group="Session")
bool london = input.bool (true, "London ", tooltip="", inline="0", group="Session")
color londonColor = input.color (BLU_M, "", tooltip="", inline="0", group="Session")
bool newYork = input.bool (true, "New York ", tooltip="", inline="1", group="Session")
color newYorkColor= input.color (RED_M, "", tooltip="", inline="1", group="Session")
bool custom = input.bool (false, "Custom ", tooltip="", inline="2", group="Session")
color customColor = input.color (PUR_M, "", tooltip="", inline="2", group="Session")
int customStart = input.int (8, "UTC", 0, 23, 1, tooltip="", inline="2", group="Session")
int customEnd = input.int (13, "-", 0, 23, 1, tooltip="", inline="2", group="Session")
// CALCULATIONS
utcTime = hour(time(timeframe.period, '0000-2400', 'UTC'), 'UTC')
sydneySession = utcTime >= 22 or utcTime <= 5
tokyoSession = utcTime >= 0 and utcTime <= 8
londonSession = utcTime >= 7 and utcTime <= 15
newYorkSession = utcTime >= 13 and utcTime <= 21
customSession = utcTime >= customStart and utcTime <= customEnd
[sydneyVwap , sydneyUpper , sydneyLower ] = ta.vwap(source, sydneySession [0] and not sydneySession [1], multiplier)
[tokyoVwap , tokyoUpper , tokyoLower ] = ta.vwap(source, tokyoSession [0] and not tokyoSession [1], multiplier)
[londonVwap , londonUpper , londonLower ] = ta.vwap(source, londonSession [0] and not londonSession [1], multiplier)
[newYorkVwap, newYorkUpper, newYorkLower] = ta.vwap(source, newYorkSession[0] and not newYorkSession[1], multiplier)
[customVwap , customUpper , customLower ] = ta.vwap(source, customSession [0] and not customSession [1], multiplier)
// PLOTS
plotSydneyUpper = plot(sydney and bands and sydneySession ? sydneyUpper : na, "Sydney Session VWAP Upper Band", sydneyColor, 1, plot.style_linebr, false, 0, offset)
plotSydneyVwap = plot(sydney and sydneySession ? sydneyVwap : na, "Sydney Session VWAP", sydneyColor, 1, plot.style_linebr, false, 0, offset)
plotSydneyLower = plot(sydney and bands and sydneySession ? sydneyLower : na, "Sydney Session VWAP Lower Band", sydneyColor, 1, plot.style_linebr, false, 0, offset)
fill(plotSydneyUpper, plotSydneyLower, color.new(sydneyColor, 95))
plotTokyoUpper = plot(tokyo and bands and tokyoSession ? tokyoUpper : na, "Tokyo Session VWAP Upper Band", tokyoColor, 1, plot.style_linebr, false, 0, offset)
plotTokyoVwap = plot(tokyo and tokyoSession ? tokyoVwap : na, "Tokyo Session VWAP", tokyoColor, 1, plot.style_linebr, false, 0, offset)
plotTokyoLower = plot(tokyo and bands and tokyoSession ? tokyoLower : na, "Tokyo Session VWAP Lower Band", tokyoColor, 1, plot.style_linebr, false, 0, offset)
fill(plotTokyoUpper, plotTokyoLower, color.new(tokyoColor, 95))
plotLondonUpper = plot(london and bands and londonSession ? londonUpper : na, "London Session VWAP Upper Band", londonColor, 1, plot.style_linebr, false, 0, offset)
plotLondonVwap = plot(london and londonSession ? londonVwap : na, "London Session VWAP", londonColor, 1, plot.style_linebr, false, 0, offset)
plotLondonLower = plot(london and bands and londonSession ? londonLower : na, "London Session VWAP Lower Band", londonColor, 1, plot.style_linebr, false, 0, offset)
fill(plotLondonUpper, plotLondonLower, color.new(londonColor, 95))
plotNewYorkUpper= plot(newYork and bands and newYorkSession ? newYorkUpper : na, "New York Session VWAP Upper Band", newYorkColor, 1, plot.style_linebr, false, 0, offset)
plotNewYorkVwap = plot(newYork and newYorkSession ? newYorkVwap : na, "New York Session VWAP", newYorkColor, 1, plot.style_linebr, false, 0, offset)
plotNewYorkLower= plot(newYork and bands and newYorkSession ? newYorkLower : na, "New York Session VWAP Lower Band", newYorkColor, 1, plot.style_linebr, false, 0, offset)
fill(plotNewYorkUpper, plotNewYorkLower, color.new(newYorkColor, 95))
plotcustomUpper = plot(custom and bands and customSession ? customUpper : na, "Custom Session VWAP Upper Band", customColor, 1, plot.style_linebr, false, 0, offset)
plotcustomVwap = plot(custom and customSession ? customVwap : na, "Custom Session VWAP", customColor, 1, plot.style_linebr, false, 0, offset)
plotcustomLower = plot(custom and bands and customSession ? customLower : na, "Custom Session VWAP Lower Band", customColor, 1, plot.style_linebr, false, 0, offset)
fill(plotcustomUpper, plotcustomLower, color.new(customColor, 95)) |
buy sell pressure | https://www.tradingview.com/script/jISVn1uy-buy-sell-pressure/ | Tradernawab | https://www.tradingview.com/u/Tradernawab/ | 73 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//trader nawab
//@version=5
indicator("buy sell pressure","buy sell pressure")
number1=(close-low[1])
number2=(high[1]-close)
len1=input.int(defval=15,title="length1",minval=1,maxval=200,step=1)
len2=input.int(defval=15,title="length2",minval=1,maxval=200,step=1)
len3=input.int(defval=50,title="length3",minval=1,maxval=200,step=1)
ema1=ta.ema(number1,len1)
ema2=ta.ema(number2,len2)
p1=plot(ema1,color=color.green)
p2=plot(ema2,color=#FF5733)
p3=plot(0,linewidth=1,color=color.blue)
|
Synapse Level Index | https://www.tradingview.com/script/I9Jsu0C9-Synapse-Level-Index/ | LvNThL | https://www.tradingview.com/u/LvNThL/ | 69 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
// © LvNThL \\
// \\ Description //
//
// Synapse Level Index Indicator
//
// This indicator simply allows the user to set their desired "Lookback Period",
// and "Lookahead Period" in the Bars Back and Bars Ahead, Pivot Settings. Once
// selected, the indicator tracks the highest high from X Bars Ahead, and the
// lowest low, from Y Bars Back. Then, the indicator calculates the Mean Value.
// Then, the indicator proceeds to draw the High to Low range by Eighths. Then,
// the indicator proceeds to draw the High to Low range by Sixteenths. Bravo.
// Fear and Greed increase at these levels psychologically. Volatility Ensues.
// The lowest percentage label is the change in value percentage from the lowest low,
// the middle percentage label is the entire change in value percentage from
// either the highest point to lowest point, or lowest to highest point, the top
// percentage label is the change in value percentage from the highest high.
//
// Enjoy
//
// Mr. Storm [LvNThL]
indicator("Synapse Level Index", shorttitle = "SLI", overlay = true, max_bars_back = 500, max_lines_count = 500, max_labels_count = 500)
var line line_1 = na
var line line_2 = na
var line line_3 = na
var line line_4 = na
var line line_5 = na
var line line_6 = na
var line line_7 = na
var line line_8 = na
var line line_9 = na
var line line_10 = na
var label lbl_1 = na
var label lbl_2 = na
var label lbl_3 = na
var label lbl_4 = na
var label lbl_5 = na
var label lbl_6 = na
var label lbl_7 = na
//SLI FUNCTION
int highperiod = input.int(248, title = "Bars Ahead", minval = 2, maxval = 248, step = 2, group = "SLI Settings", tooltip = string("Minimum Value: 2, Maximum Value: 248"))
int lowperiod = input.int(248, title = "Bars Back", minval = 2, maxval = 248, step = 2, group = "SLI Settings", tooltip = string("Minimum Value: 2, Maximum Value: 248"))
float change_in_value_1 = ta.highest(high, highperiod)
float change_in_value_2 = ta.lowest(low, lowperiod)
int change1 = -ta.highestbars(high, highperiod)
int change2 = -ta.lowestbars(low, lowperiod)
var color meancolor = na
// MEAN
float change_in_value_3 = (change_in_value_1 + change_in_value_2)/2
//FOURTHS
change_in_value_4 = (change_in_value_3 + change_in_value_1)/2
change_in_value_5 = (change_in_value_3 + change_in_value_2)/2
//EIGHTHS
change_in_value_6 = (change_in_value_1 + change_in_value_4)/2
change_in_value_7 = (change_in_value_4 + change_in_value_3)/2
change_in_value_8 = (change_in_value_3 + change_in_value_5)/2
change_in_value_9 = (change_in_value_5 + change_in_value_2)/2
if close >= change_in_value_3
meancolor := color.rgb(0,255,0,0)
else
meancolor := color.rgb(255,0,0,0)
bool slioverlay = input.bool(true, "SLI Indicator Active", group = "SLI Switches")
bool zigzag = input.bool(true, "ZigZag Active", group = "SLI Switches")
bool extendright = input.bool(false, "Extend Right", group = "SLI Switches")
bool extendleft = input.bool(false, "Extend Left", group = "SLI Switches")
bool extendboth = input.bool(false, "Extend Both", group = "SLI Switches")
bool lightmode = input.bool(false, "Light Mode", group = "SLI Switches")
string extension = extendright ? extend.right : extendleft ? extend.left : extendboth ? extend.both : extend.none
if barstate.islast and zigzag == true or barstate.islast and slioverlay == true
//ZIGZAG LINE
line_10 := zigzag ? line.new(bar_index[change2], change_in_value_2,bar_index[change1], change_in_value_1, color = lightmode ? color.black : color.silver, style = line.style_dashed, width = 1, extend = extend.none) : na
line.delete(line_10[1])
if barstate.islast and slioverlay == true
//TOP LINE
line_1 := line.new(bar_index[24], change_in_value_1, bar_index + 1, change_in_value_1, color = color.rgb(255,0,0,0), style = line.style_dotted, width = 1, extend = extension)
line.delete(line_1[1])
lbl_2 := label.new(bar_index + 1, change_in_value_1, close < change_in_value_1 ? string("▽ ") + str.tostring((close / change_in_value_1)-1, "#.##%") : close >= change_in_value_1 ? string("△ ") + str.tostring((change_in_value_1 / close)-1, "#.##%") : string("Unknown"), style = label.style_label_left, color = color.rgb(0,0,0,100), textcolor = lightmode ? color.black : color.silver, size = size.small)
label.delete(lbl_2[1])
//REMAINING TOP HALF LINES
line_6 := line.new(bar_index[24], change_in_value_6, bar_index + 1, change_in_value_6, color = lightmode ? color.black : color.silver, style = line.style_dotted, width = 1, extend = extension)
line.delete(line_6[1])
line_4 := line.new(bar_index[24], change_in_value_4, bar_index + 1, change_in_value_4, color = lightmode ? color.black : color.silver, style = line.style_dotted, width = 1, extend = extension)
line.delete(line_4[1])
line_7 := line.new(bar_index[24], change_in_value_7, bar_index + 1, change_in_value_7, color = lightmode ? color.black : color.silver, style = line.style_dotted, width = 1, extend = extension)
line.delete(line_7[1])
//MEAN LINE
line_3 := line.new(bar_index[24], change_in_value_3, bar_index + 1, change_in_value_3, color = meancolor, style = line.style_dashed, width = 1, extend = extension)
line.delete(line_3[1])
lbl_1 := label.new(bar_index + 1, change_in_value_3, change1 < change2 ? string("△ ") + str.tostring((change_in_value_1 / change_in_value_2)-1, "#.##%") : change1 >= change2 ? string("▽ ") + str.tostring((change_in_value_2 / change_in_value_1)-1, "#.##%") : string("Unknown"), style = label.style_label_left, color = color.rgb(0,0,0,100), textcolor = lightmode ? color.black : color.silver, size = size.small)
label.delete(lbl_1[1])
//BOTTOM LINE
line_2 := line.new(bar_index[24], change_in_value_2, bar_index + 1, change_in_value_2, color = color.rgb(0,255,0,0), style = line.style_dotted, width = 1, extend = extension)
line.delete(line_2[1])
lbl_3 := label.new(bar_index + 1, change_in_value_2, close < change_in_value_2 ? string("▽ ") + str.tostring((close / change_in_value_2)-1, "#.##%") : close >= change_in_value_2 ? string("△ ") + str.tostring((close / change_in_value_2)-1, "#.##%") : string("Unknown"), style = label.style_label_left, color = color.rgb(0,0,0,100), textcolor = lightmode ? color.black : color.silver, size = size.small)
label.delete(lbl_3[1])
//REMAINGIN BOTTOM HALF LINES
line_8 := line.new(bar_index[24], change_in_value_8, bar_index + 1, change_in_value_8, color = lightmode ? color.black : color.silver, style = line.style_dotted, width = 1, extend = extension)
line.delete(line_8[1])
line_5 := line.new(bar_index[24], change_in_value_5, bar_index + 1, change_in_value_5, color = lightmode ? color.black : color.silver, style = line.style_dotted, width = 1, extend = extension)
line.delete(line_5[1])
line_9 := line.new(bar_index[24], change_in_value_9, bar_index + 1, change_in_value_9, color = lightmode ? color.black : color.silver, style = line.style_dotted, width = 1, extend = extension)
line.delete(line_9[1])
//TOP HALF LINE FILL
linefill.new(line1 = line_1, line2 = line_6, color = color.rgb(255,0,0,95))
linefill.new(line1 = line_6, line2 = line_4, color = color.rgb(255,0,0,96))
linefill.new(line1 = line_4, line2 = line_7, color = color.rgb(255,0,0,97))
linefill.new(line1 = line_7, line2 = line_3, color = color.rgb(255,0,0,98))
//BOTTOM HALF LINE FILL
linefill.new(line1 = line_2, line2 = line_9, color = color.rgb(0,255,0,95))
linefill.new(line1 = line_9, line2 = line_5, color = color.rgb(0,255,0,96))
linefill.new(line1 = line_5, line2 = line_8, color = color.rgb(0,255,0,97))
linefill.new(line1 = line_8, line2 = line_3, color = color.rgb(0,255,0,98))
|
Extreme Volume Support Resistance Levels | https://www.tradingview.com/script/uxcUbZ0Y-extreme-volume-support-resistance-levels/ | tarasenko_ | https://www.tradingview.com/u/tarasenko_/ | 284 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tarasenko_
//@version=5
indicator("Extreme Volume Support Resistance Levels", shorttitle = "EVSR Levels", overlay = 1)
// Inputs
use_mtf = input(false, "Use MTF?", tooltip = "MTF - Multi Timeframe - option for using data from different timeframes on your current timeframe.", group = "MTF")
dtf = input.string('3', "Timeframe", options = ['1', '3', '5', '15', '30', '45', '60', '240', '480', '1440'], group = "MTF")
use_custom_tf = input(false, "Use custom timeframe?", group = "MTF")
custom_tf = input(3, "Custom Timeframe", tooltip = "Enter timeframe in minutes: 60 - 1H, 240 - 4H and etc.", group = "MTF")
p = input.int(400, "Lookback", maxval = 2000, minval = 100, group = "Main Settings")
vp = input(200, "Volume Threshold Period", group = "Main Settings")
vm = input.float(3, "Volume Threshold Multiplier", group = "Main Settings")
boxes_to_show = input(2, "Number of zones to show", group = "Main Settings")
show_db = input(true, "Show TF Dashboard?", tooltip = "Shows chosen MTF and your current timeframe, so you could see what timeframes you are using at the moment.", group = "Dashboard")
db_board_thickness = input(2, "DB Board Thickness", group = "Dashboard")
db_frame_width = input.int(1, "DB Frame Width", group = "Dashboard")
box_extend_type = input.string("Both", "Zones' Extend", options = ["Both", "Right", "Left"], group = "Extra")
box_extend = box_extend_type == "Both" ? extend.both : box_extend_type == "Right" ? extend.right : extend.left
box_filling = input(true, "Use color filling of zones?", group = "Extra")
// Functions
// Drawing zones
draw_sr_zones(o, h, l, c) =>
upper_box = box.new(bar_index - 1, h, bar_index, c > o ? c : o, close > h ? #00ff0050 : #ff000050, 2, line.style_solid, box_extend, xloc.bar_index, box_filling ? (close > h ? #00ff0020 : #ff000020) : na)
lower_box = box.new(bar_index - 1, c > o ? o : c, bar_index, l, close > l ? #00ff0050 : #ff000050, 2, line.style_solid, box_extend, xloc.bar_index, box_filling ? (close > l ? #00ff0020 : #ff000020) : na)
// Necessary global variables
tf = use_mtf ? (use_custom_tf ? str.tostring(custom_tf) : dtf) : timeframe.period // Timeframe
O = request.security(syminfo.tickerid, tf, open[1]) // MTF previous open
H = request.security(syminfo.tickerid, tf, high[1]) // MTF previous high
L = request.security(syminfo.tickerid, tf, low[1]) // MTF previous low
C = request.security(syminfo.tickerid, tf, close[1]) // MTF previous close
// Calculations
v = request.security(syminfo.tickerid, tf, volume[1]) // Requesting MTF volume
vl = request.security(syminfo.tickerid, tf, ta.ema(v, vp)) // Requesting MTF smoothed volume
vt = request.security(syminfo.tickerid, tf, vl * vm) // Requesting MTF "lifted" smoothed volume
// Plottings
if ta.crossover(v, vt)
box_array = box.all // Array of all plotted boxes. Veru useful deleting boxes themselves
while array.size(box_array) > 0 and array.size(box_array) >= 2 * boxes_to_show // Cleaning already existing boxes in order to give space for new boxes
box.delete(array.shift(box_array)) // Cleaning first line in box array = 1st lastest drawn zone
box.delete(array.shift(box_array)) // Cleaning second line in box array = 2nd lastest drawn zone
draw_sr_zones(O, H, L, C) // Calling main function to draw the zones
if show_db // Enabling/Disabling TF Dashboard, next group of lines is just customization
table db = table.new(position.top_right, 2, 3, color.rgb(30, 32, 38, 50), color.rgb(0, 0, 0), db_frame_width, color.rgb(0, 0, 0), db_board_thickness)
table.cell(db, 0, 0, "MTF", text_color = color.white, bgcolor = color.black, tooltip = "MTF that you've chosen.")
table.cell(db, 1, 0, str.tostring(tf), text_color = color.white, text_font_family = font.family_monospace)
table.cell(db, 0, 1, "Current\ntimeframe", text_color = color.white, bgcolor = color.black, tooltip = "Your current timeframe.")
table.cell(db, 1, 1, timeframe.period, text_color = color.white, text_font_family = font.family_monospace)
table.cell(db, 0, 2, "Zones found", text_color = color.white, bgcolor = color.black, tooltip = "Number of S/R zones, found by algorithm. If it equals 0, then there is no zones, try playing with other settings.")
table.cell(db, 1, 2, str.tostring(array.size(box.all)), text_color = color.white, text_font_family = font.family_monospace, bgcolor = array.size(box.all) == 0 ? #ff000050 : color.rgb(30, 32, 38, 50))
|
Dap's Oscillator- Short Term Momentum and Trend. | https://www.tradingview.com/script/bwZZxO7h-Dap-s-Oscillator-Short-Term-Momentum-and-Trend/ | CheatCode1 | https://www.tradingview.com/u/CheatCode1/ | 203 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CheatCode1
//@version=5
indicator("Dap's Oscillator", "Moving Average Momentum Indicator", overlay = false)
Lf = input.int(3, 'Look Forward Length', 1, 100, group = 'Pivot Value')
Lb = input.int(55, 'Look Back Length', 1, 500, group = 'Pivot Value')
//Simple and Exponential Moving average Variables
//SMA
sma1 = ta.sma(close, 5)
sma2 = ta.sma(close, 10)
sma3 = ta.sma(close, 15)
sma4 = ta.sma(close, 20)
sma5 = ta.sma(close, 25)
sma6 = ta.sma(close, 30)
sma7 = ta.sma(close, 35)
sma8 = ta.sma(close, 40)
sma9 = ta.sma(close, 45)
sma10 = ta.sma(close, 50)
sma11 = ta.sma(close, 55)
sma12 = ta.sma(close, 60)
sma13 = ta.sma(close, 65)
sma14 = ta.sma(close, 70)
sma15 = ta.sma(close, 75)
sma16 = ta.sma(close, 100)
sma17 = ta.sma(close, 120)
sma18 = ta.sma(close, 150)
sma19 = ta.sma(close, 200)
sma20 = ta.sma(close, 250)
//EMA
ema1 = ta.ema(close, 5)
ema2 = ta.ema(close, 10)
ema3 = ta.ema(close, 15)
ema4 = ta.ema(close, 20)
ema5 = ta.ema(close, 25)
ema6 = ta.ema(close, 30)
ema7 = ta.ema(close, 35)
ema8 = ta.ema(close, 40)
ema9 = ta.ema(close, 45)
ema10 = ta.ema(close, 50)
ema11 = ta.ema(close, 55)
ema12 = ta.ema(close, 60)
ema13 = ta.ema(close, 65)
ema14 = ta.ema(close, 70)
ema15 = ta.ema(close, 75)
ema16 = ta.ema(close, 100)
ema17 = ta.ema(close, 120)
ema18 = ta.ema(close, 150)
ema19 = ta.ema(close, 200)
ema20 = ta.ema(close, 250)
//Moving average differences
ma5 = (sma1 - ema1)
ma10 = (sma2 - ema2)
ma15 = (sma3 - ema3)
ma20 = (sma4 - ema4)
ma25 = (sma5 - ema5)
ma30 = (sma6 - ema6)
ma35 = (sma7 - ema7)
ma40 = (sma8 - ema8)
ma45 = (sma9 - ema9)
ma50 = (sma10 - ema10)
ma55 = (sma11 - ema11)
ma60 = (sma12 - ema12)
ma65 = (sma13 - ema13)
ma70 = (sma14 - ema14)
ma75 = (sma15 - ema15)
ma100 = (sma16 - ema16)
ma120 = (sma17 - ema17)
ma150 = (sma18 - ema18)
ma200 = (sma19 - ema19)
ma250 = (sma20 - ema20)
ReferenceMA = ma50*-1
//Average of Moving Average differences + DAP Equation Variables
AvgDiff1 = (ma5 + ma10 + ma15 + ma20 + ma25 + ma30 + ma35 + ma40 + ma45 + ma50 + ma55 + ma60 + ma65 + ma70 + ma75 + ma100 + ma120 + ma150 + ma200 + ma250)/20
AvgDiff = AvgDiff1/100*-1
AvgDiff2 = AvgDiff1 * AvgDiff1
AvgDiff_sqrt = math.sqrt(hl2/AvgDiff)
//Standard Deviation Differences
stdev5 = ta.stdev(ma5, 5)
stdev10 = ta.stdev(ma10, 10)
stdev15 = ta.stdev(ma15, 15)
stdev20 = ta.stdev(ma20, 20)
stdev25 = ta.stdev(ma25, 25)
stdev30 = ta.stdev(ma30, 30)
stdev35 = ta.stdev(ma35, 35)
stdev40 = ta.stdev(ma40, 40)
stdev45 = ta.stdev(ma45, 45)
stdev50 = ta.stdev(ma50, 50)
stdev55 = ta.stdev(ma55, 55)
stdev60 = ta.stdev(ma60, 60)
stdev65 = ta.stdev(ma65, 65)
stdev70 = ta.stdev(ma70, 70)
stdev75 = ta.stdev(ma75, 75)
stdev100 = ta.stdev(ma100, 100)
stdev120 = ta.stdev(ma120, 120)
stdev150 = ta.stdev(ma150, 150)
stdev200 = ta.stdev(ma200, 200)
stdev250 = ta.stdev(ma250, 250)
AVGstdev = (stdev5 + stdev10 + stdev15 + stdev20 + stdev25 + stdev30 + stdev35 + stdev40 + stdev45 + stdev50 + stdev55 + stdev60 + stdev65 + stdev70 + stdev75 + stdev100 + stdev120 + stdev150 + stdev200 + stdev250)/20
//DAP'S OSCILLATOR //DAP'S OSCILLATOR //DAP'S OSCILLATOR //DAP'S OSCILLATOR //DAP'S OSCILLATOR //DAP'S OSCILLATOR //DAP'S OSCILLATOR //DAP'S OSCILLATOR //DAP'S OSCILLATOR //DAP'S OSCILLATOR
docp = AVGstdev - (AvgDiff*2)
docn = AvgDiff -(AVGstdev*2)
//Length's
len1 = input.int(3, 'DAP\'s Oscillator', 0, 100, group = 'Osillator Length')
len3 = input.int(250, 'RC Average Length', 1, 500, group = 'RC MOVING AVERAGE')
len4 = int(175)
//Variable Libraries
//Positive +
AVGdocp5_A = (docp[4] + docp[3] + docp[2] +docp[1] + docn)/5
AVGdocp5_B = (docp[5] + docp[6] + docp[7] + docp[8] + docp[9])/5
AVGdocp5_C = (docp[14] + docp[13] + docp[12] + docp[11] + docp[10])/5
AVGdocp5_D = (docp[15] + docp[16] + docp[17] +docp[18] + docp[19])/5
AVGdocp5_E = (docp[24] + docp[23] + docp[22] + docp[21] + docp[20])/5
AVGdocp5_F = (docp[25] + docp[26] + docp[27] + docp[28] + docp[29])/5
AVGdocp5_G = (docp[34] + docp[33] + docp[32] + docp[31] + docp[30])/5
AVGdocp5_H = (docp[35] + docp[36] + docp[37] + docp[38] + docp[39])/5
AVGdocp5_I = (docp[44] + docp[43] + docp[42] + docp[41] + docp[40])/5
AVGdocp5_J = (docp[45] + docp[46] + docp[47] + docp[48] + docp[49])/5
AVGdocp5_K = (docp[54] + docp[53] + docp[52] + docp[51] + docp[50])/5
AVGdocp5_L = (docp[55] + docp[56] + docp[57] + docp[58] + docp[59])/5
AVGdocp5_M = (docp[64] + docp[63] + docp[62] + docp[61] + docp[60])/5
AVGdocp5_N = (docp[65] + docp[66] + docp[67] + docp[68] + docp[69])/5
AVGdocp5_O = (docp[74] + docp[73] + docp[72] + docp[71] + docp[70])/5
AVGdocp5_P = (docp[75] + docp[76] + docp[77] + docp[78] + docp[79])/5
AVGdocp5_Q = (docp[84] + docp[83] + docp[82] + docp[81] + docp[80])/5
AVGdocp5_R = (docp[85] + docp[86] + docp[87] + docp[88] + docp[89])/5
AVGdocp5_S = (docp[94] + docp[93] + docp[92] + docp[91] + docp[90])/5
AVGdocp5_T = (docp[95] + docp[96] + docp[97] + docp[98] + docp[99])/5
AVGdocp5_AB = math.avg (AVGdocp5_A, AVGdocp5_B)
AVGdocp5_ABC = math.avg (AVGdocp5_A, AVGdocp5_B, AVGdocp5_C)
AVGdocp5_ABCD = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D)
AVGdocp5_ABCDE = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E)
AVGdocp5_ABCDEF = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F)
AVGdocp5_ABCDEFG = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G)
AVGdocp5_ABCDEFGH = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G , AVGdocp5_H)
AVGdocp5_ABCDEFGHI = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G , AVGdocp5_H , AVGdocp5_I)
AVGdocp5_ABCDEFGHIJ = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G , AVGdocp5_H , AVGdocp5_I , AVGdocp5_J)
AVGdocp5_ABCDEFGHIJK = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G , AVGdocp5_H , AVGdocp5_I , AVGdocp5_J , AVGdocp5_K)
AVGdocp5_ABCDEFGHIJKL = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G , AVGdocp5_H , AVGdocp5_I , AVGdocp5_J , AVGdocp5_K , AVGdocp5_L)
AVGdocp5_ABCDEFGHIJKLM = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G , AVGdocp5_H , AVGdocp5_I , AVGdocp5_J , AVGdocp5_K , AVGdocp5_L , AVGdocp5_M)
AVGdocp5_ABCDEFGHIJKLMN = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G , AVGdocp5_H , AVGdocp5_I , AVGdocp5_J , AVGdocp5_K , AVGdocp5_L , AVGdocp5_M , AVGdocp5_N)
AVGdocp5_ABCDEFGHIJKLMNO = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G , AVGdocp5_H , AVGdocp5_I , AVGdocp5_J , AVGdocp5_K , AVGdocp5_L , AVGdocp5_M , AVGdocp5_N , AVGdocp5_O)
AVGdocp5_ABCDEFGHIJKLMNOP = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G , AVGdocp5_H , AVGdocp5_I , AVGdocp5_J , AVGdocp5_K , AVGdocp5_L , AVGdocp5_M , AVGdocp5_N , AVGdocp5_O , AVGdocp5_P)
AVGdocp5_ABCDEFGHIJKLMNOPQ = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G , AVGdocp5_H , AVGdocp5_I , AVGdocp5_J , AVGdocp5_K , AVGdocp5_L , AVGdocp5_M , AVGdocp5_N , AVGdocp5_O , AVGdocp5_P , AVGdocp5_Q)
AVGdocp5_ABCDEFGHIJKLMNOPQR = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G , AVGdocp5_H , AVGdocp5_I , AVGdocp5_J , AVGdocp5_K , AVGdocp5_L , AVGdocp5_M , AVGdocp5_N , AVGdocp5_O , AVGdocp5_P , AVGdocp5_Q , AVGdocp5_R)
AVGdocp5_ABCDEFGHIJKLMNOPQRS = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G , AVGdocp5_H , AVGdocp5_I , AVGdocp5_J , AVGdocp5_K , AVGdocp5_L , AVGdocp5_M , AVGdocp5_N , AVGdocp5_O , AVGdocp5_P , AVGdocp5_Q , AVGdocp5_R , AVGdocp5_S)
AVGdocp5_ABCDEFGHIJKLMNOPQRST = math.avg (AVGdocp5_A , AVGdocp5_B , AVGdocp5_C , AVGdocp5_D , AVGdocp5_E , AVGdocp5_F , AVGdocp5_G , AVGdocp5_H , AVGdocp5_I , AVGdocp5_J , AVGdocp5_K , AVGdocp5_L , AVGdocp5_M , AVGdocp5_N , AVGdocp5_O , AVGdocp5_P , AVGdocp5_Q , AVGdocp5_R , AVGdocp5_S , AVGdocp5_T)
//Negative -
AVGdocn5_A = (docn[4] + docn[3] + docn[2] +docn[1] + docn)/5
AVGdocn5_B = (docn[5] + docn[6] + docn[7] + docn[8] + docn[9])/5
AVGdocn5_C = (docn[14] + docn[13] + docn[12] + docn[11] + docn[10])/5
AVGdocn5_D = (docn[15] + docn[16] + docn[17] +docn[18] + docn[19])/5
AVGdocn5_E = (docn[24] + docn[23] + docn[22] + docn[21] + docn[20])/5
AVGdocn5_F = (docn[25] + docn[26] + docn[27] + docn[28] + docn[29])/5
AVGdocn5_G = (docn[34] + docn[33] + docn[32] + docn[31] + docn[30])/5
AVGdocn5_H = (docn[35] + docn[36] + docn[37] + docn[38] + docn[39])/5
AVGdocn5_I = (docn[44] + docn[43] + docn[42] + docn[41] + docn[40])/5
AVGdocn5_J = (docn[45] + docn[46] + docn[47] + docn[48] + docn[49])/5
AVGdocn5_K = (docn[54] + docn[53] + docn[52] + docn[51] + docn[50])/5
AVGdocn5_L = (docn[55] + docn[56] + docn[57] + docn[58] + docn[59])/5
AVGdocn5_M = (docn[64] + docn[63] + docn[62] + docn[61] + docn[60])/5
AVGdocn5_N = (docn[65] + docn[66] + docn[67] + docn[68] + docn[69])/5
AVGdocn5_O = (docn[74] + docn[73] + docn[72] + docn[71] + docn[70])/5
AVGdocn5_P = (docn[75] + docn[76] + docn[77] + docn[78] + docn[79])/5
AVGdocn5_Q = (docn[84] + docn[83] + docn[82] + docn[81] + docn[80])/5
AVGdocn5_R = (docn[85] + docn[86] + docn[87] + docn[88] + docn[89])/5
AVGdocn5_S = (docn[94] + docn[93] + docn[92] + docn[91] + docn[90])/5
AVGdocn5_T = (docn[95] + docn[96] + docn[97] + docn[98] + docn[99])/5
AVGdocn5_AB = math.avg (AVGdocn5_A, AVGdocn5_B)
AVGdocn5_ABC = math.avg (AVGdocn5_A, AVGdocn5_B, AVGdocn5_C)
AVGdocn5_ABCD = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D)
AVGdocn5_ABCDE = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E)
AVGdocn5_ABCDEF = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F)
AVGdocn5_ABCDEFG = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G)
AVGdocn5_ABCDEFGH = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G , AVGdocn5_H)
AVGdocn5_ABCDEFGHI = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G , AVGdocn5_H , AVGdocn5_I)
AVGdocn5_ABCDEFGHIJ = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G , AVGdocn5_H , AVGdocn5_I , AVGdocn5_J)
AVGdocn5_ABCDEFGHIJK = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G , AVGdocn5_H , AVGdocn5_I , AVGdocn5_J , AVGdocn5_K)
AVGdocn5_ABCDEFGHIJKL = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G , AVGdocn5_H , AVGdocn5_I , AVGdocn5_J , AVGdocn5_K , AVGdocn5_L)
AVGdocn5_ABCDEFGHIJKLM = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G , AVGdocn5_H , AVGdocn5_I , AVGdocn5_J , AVGdocn5_K , AVGdocn5_L , AVGdocn5_M)
AVGdocn5_ABCDEFGHIJKLMN = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G , AVGdocn5_H , AVGdocn5_I , AVGdocn5_J , AVGdocn5_K , AVGdocn5_L , AVGdocn5_M , AVGdocn5_N)
AVGdocn5_ABCDEFGHIJKLMNO = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G , AVGdocn5_H , AVGdocn5_I , AVGdocn5_J , AVGdocn5_K , AVGdocn5_L , AVGdocn5_M , AVGdocn5_N , AVGdocn5_O)
AVGdocn5_ABCDEFGHIJKLMNOP = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G , AVGdocn5_H , AVGdocn5_I , AVGdocn5_J , AVGdocn5_K , AVGdocn5_L , AVGdocn5_M , AVGdocn5_N , AVGdocn5_O , AVGdocn5_P)
AVGdocn5_ABCDEFGHIJKLMNOPQ = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G , AVGdocn5_H , AVGdocn5_I , AVGdocn5_J , AVGdocn5_K , AVGdocn5_L , AVGdocn5_M , AVGdocn5_N , AVGdocn5_O , AVGdocn5_P , AVGdocn5_Q)
AVGdocn5_ABCDEFGHIJKLMNOPQR = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G , AVGdocn5_H , AVGdocn5_I , AVGdocn5_J , AVGdocn5_K , AVGdocn5_L , AVGdocn5_M , AVGdocn5_N , AVGdocn5_O , AVGdocn5_P , AVGdocn5_Q , AVGdocn5_R)
AVGdocn5_ABCDEFGHIJKLMNOPQRS = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G , AVGdocn5_H , AVGdocn5_I , AVGdocn5_J , AVGdocn5_K , AVGdocn5_L , AVGdocn5_M , AVGdocn5_N , AVGdocn5_O , AVGdocn5_P , AVGdocn5_Q , AVGdocn5_R , AVGdocn5_S)
AVGdocn5_ABCDEFGHIJKLMNOPQRST = math.avg (AVGdocn5_A , AVGdocn5_B , AVGdocn5_C , AVGdocn5_D , AVGdocn5_E , AVGdocn5_F , AVGdocn5_G , AVGdocn5_H , AVGdocn5_I , AVGdocn5_J , AVGdocn5_K , AVGdocn5_L , AVGdocn5_M , AVGdocn5_N , AVGdocn5_O , AVGdocn5_P , AVGdocn5_Q , AVGdocn5_R , AVGdocn5_S , AVGdocn5_T)
//Array Series
// Positive +
doc_p = array.new_float(100, len1),
array.insert(doc_p, 0 , docn),
array.insert(doc_p, 1 , (docp[1] + docn)/2),
array.insert(doc_p, 2 , (docp[2] + docp[1] + docn)/3),
array.insert(doc_p, 3 , (docp[3] + docp[2] + docp[1] + docn)/4),
array.insert(doc_p, 4 , AVGdocp5_A),
array.insert(doc_p, 5 , (AVGdocp5_A + docp[5])/2),
array.insert(doc_p, 6 , (AVGdocp5_A + docp[6] + docp[5])/3),
array.insert(doc_p, 7 , (AVGdocp5_A + docp[7] + docp[6] + docp[5])/4),
array.insert(doc_p, 8 , (AVGdocp5_A + docp[8] + docp[7] + docp[6] + docp[5])/5),
array.insert(doc_p, 9 , (AVGdocp5_AB)),
array.insert(doc_p, 10 , (AVGdocp5_AB + docp[10] )/2),
array.insert(doc_p, 11 , (AVGdocp5_AB + docp[11] + docp[10] )/3),
array.insert(doc_p, 12 , (AVGdocp5_AB + docp[12] + docp[11] + docp[10] )/4),
array.insert(doc_p, 13 , (AVGdocp5_AB + docp[13] + docp[12] + docp[11] + docp[10] )/5),
array.insert(doc_p, 14 , (AVGdocp5_ABC)),
array.insert(doc_p, 15 , (AVGdocp5_ABC + docp[15] )/2),
array.insert(doc_p, 16 , (AVGdocp5_ABC + docp[16] + docp[15])/3),
array.insert(doc_p, 17 , (AVGdocp5_ABC + docp[17] + docp[16] + docp[15])/4),
array.insert(doc_p, 18 , (AVGdocp5_ABC + docp[18] + docp[17] + docp[16] + docp[15])/7),
array.insert(doc_p, 19 , (AVGdocp5_ABCD)),
array.insert(doc_p, 20 , (AVGdocp5_ABCD + docp[20]) /2),
array.insert(doc_p, 21 , (AVGdocp5_ABCD + docp[21] + docp[20])/3),
array.insert(doc_p, 22 , (AVGdocp5_ABCD + docp[22] + docp[21] + docp[20] )/4),
array.insert(doc_p, 23 , (AVGdocp5_ABCD + docp[23] + docp[22] + docp[21] + docp[20] )/5),
array.insert(doc_p, 24 , (AVGdocp5_ABCDE)),
array.insert(doc_p, 25 , (AVGdocp5_ABCDE + docp[25] )/2),
array.insert(doc_p, 26 , (AVGdocp5_ABCDE + docp[26] + docp[25])/3),
array.insert(doc_p, 27 , (AVGdocp5_ABCDE + docp[27] + docp[26] + docp[25] )/4),
array.insert(doc_p, 28 , (AVGdocp5_ABCDE + docp[28] + docp[27] + docp[26] + docp[25] )/5),
array.insert(doc_p, 29 , (AVGdocp5_ABCDEF)),
array.insert(doc_p, 30 , (AVGdocp5_ABCDEF + docp[30] )/2),
array.insert(doc_p, 31 , (AVGdocp5_ABCDEF + docp[31] + docp[30] )/3),
array.insert(doc_p, 32 , (AVGdocp5_ABCDEF + docp[32] + docp[31] + docp[30] )/4),
array.insert(doc_p, 33 , (AVGdocp5_ABCDEF + docp[33] + docp[32] + docp[31] + docp[30] )/5),
array.insert(doc_p, 34 , (AVGdocp5_ABCDEFG)),
array.insert(doc_p, 35 , (AVGdocp5_ABCDEFG + docp[35] )/2),
array.insert(doc_p, 36 , (AVGdocp5_ABCDEFG + docp[36] + docp[35] )/3),
array.insert(doc_p, 37 , (AVGdocp5_ABCDEFG + docp[37] + docp[36] + docp[35] )/4),
array.insert(doc_p, 38 , (AVGdocp5_ABCDEFG + docp[38] + docp[37] + docp[36] + docp[35] )/5),
array.insert(doc_p, 39 , (AVGdocp5_ABCDEFGH )),
array.insert(doc_p, 40 , (AVGdocp5_ABCDEFGH + docp[40] )/2),
array.insert(doc_p, 41 , (AVGdocp5_ABCDEFGH + docp[41] + docp[40])/3),
array.insert(doc_p, 42 , (AVGdocp5_ABCDEFGH + docp[42] + docp[41] + docp[40])/4),
array.insert(doc_p, 43 , (AVGdocp5_ABCDEFGH + docp[43] + docp[42] + docp[41] + docp[40])/5),
array.insert(doc_p, 44 , (AVGdocp5_ABCDEFGHI)),
array.insert(doc_p, 45 , (AVGdocp5_ABCDEFGHI + docp[45] )/2),
array.insert(doc_p, 46 , (AVGdocp5_ABCDEFGHI + docp[46] + docp[45] )/3),
array.insert(doc_p, 47 , (AVGdocp5_ABCDEFGHI + docp[47] + docp[46] + docp[45] )/4),
array.insert(doc_p, 48 , (AVGdocp5_ABCDEFGHI + docp[48] + docp[47] + docp[46] + docp[45] )/5),
array.insert(doc_p, 49 , (AVGdocp5_ABCDEFGHIJ)),
array.insert(doc_p, 50 , (AVGdocp5_ABCDEFGHIJ + docp[50])/2),
array.insert(doc_p, 51 , (AVGdocp5_ABCDEFGHIJ + docp[51] + docp[50] )/3),
array.insert(doc_p, 52 , (AVGdocp5_ABCDEFGHIJ + docp[52] + docp[51] + docp[50] )/4),
array.insert(doc_p, 53 , (AVGdocp5_ABCDEFGHIJ + docp[53] + docp[52] + docp[51] + docp[50] )/5),
array.insert(doc_p, 54 , (AVGdocp5_ABCDEFGHIJK)),
array.insert(doc_p, 55 , (AVGdocp5_ABCDEFGHIJK + docp[55] )/2),
array.insert(doc_p, 56 , (AVGdocp5_ABCDEFGHIJK + docp[56] + docp[55] )/3),
array.insert(doc_p, 57 , (AVGdocp5_ABCDEFGHIJK + docp[57] + docp[56] + docp[55] )/4),
array.insert(doc_p, 58 , (AVGdocp5_ABCDEFGHIJK + docp[58] + docp[57] + docp[56] + docp[55] )/5),
array.insert(doc_p, 59 , (AVGdocp5_ABCDEFGHIJKL)),
array.insert(doc_p, 60 , (AVGdocp5_ABCDEFGHIJKL + docp[60] )/2),
array.insert(doc_p, 61 , (AVGdocp5_ABCDEFGHIJKL + docp[61] + docp[60] )/3),
array.insert(doc_p, 62 , (AVGdocp5_ABCDEFGHIJKL + docp[62] + docp[61] + docp[60] )/4),
array.insert(doc_p, 63 , (AVGdocp5_ABCDEFGHIJKL + docp[63] + docp[62] + docp[61] + docp[60] )/5),
array.insert(doc_p, 64 , (AVGdocp5_ABCDEFGHIJKLM)),
array.insert(doc_p, 65 , (AVGdocp5_ABCDEFGHIJKLM + docp[65] )/2),
array.insert(doc_p, 66 , (AVGdocp5_ABCDEFGHIJKLM + docp[66] + docp[65] )/3),
array.insert(doc_p, 67 , (AVGdocp5_ABCDEFGHIJKLM + docp[67] + docp[66] + docp[65] )/4),
array.insert(doc_p, 68 , (AVGdocp5_ABCDEFGHIJKLM + docp[68] + docp[67] + docp[66] + docp[65] )/5),
array.insert(doc_p, 69 , (AVGdocp5_ABCDEFGHIJKLMN)),
array.insert(doc_p, 70 , (AVGdocp5_ABCDEFGHIJKLMN + docp[70] )/2),
array.insert(doc_p, 71 , (AVGdocp5_ABCDEFGHIJKLMN + docp[71] + docp[70] )/3),
array.insert(doc_p, 72 , (AVGdocp5_ABCDEFGHIJKLMN + docp[72] + docp[71] + docp[70] )/4),
array.insert(doc_p, 73 , (AVGdocp5_ABCDEFGHIJKLMN + docp[73] + docp[72] + docp[71] + docp[70] )/5),
array.insert(doc_p, 74 , (AVGdocp5_ABCDEFGHIJKLMNO)),
array.insert(doc_p, 75 , (AVGdocp5_ABCDEFGHIJKLMN + docp[75] )/2),
array.insert(doc_p, 76 , (AVGdocp5_ABCDEFGHIJKLMN + docp[76] + docp[75] )/3),
array.insert(doc_p, 77 , (AVGdocp5_ABCDEFGHIJKLMN + docp[77] + docp[76] + docp[75] )/4),
array.insert(doc_p, 78 , (AVGdocp5_ABCDEFGHIJKLMN + docp[78] + docp[77] + docp[76] + docp[75] )/5),
array.insert(doc_p, 79 , (AVGdocp5_ABCDEFGHIJKLMNOP)),
array.insert(doc_p, 80 , (AVGdocp5_ABCDEFGHIJKLMNOP + docp[80])/2),
array.insert(doc_p, 81 , (AVGdocp5_ABCDEFGHIJKLMNOP + docp[81] + docp[80])/3),
array.insert(doc_p, 82 , (AVGdocp5_ABCDEFGHIJKLMNOP + docp[82] + docp[81] + docp[80])/4),
array.insert(doc_p, 83 , (AVGdocp5_ABCDEFGHIJKLMNOP + docp[83] + docp[82] + docp[81] + docp[80] )/5),
array.insert(doc_p, 84 , (AVGdocp5_ABCDEFGHIJKLMNOPQ)),
array.insert(doc_p, 85 , (AVGdocp5_ABCDEFGHIJKLMNOPQ + docp[85] )/2),
array.insert(doc_p, 86 , (AVGdocp5_ABCDEFGHIJKLMNOPQ + docp[86] + docp[85] )/3),
array.insert(doc_p, 87 , (AVGdocp5_ABCDEFGHIJKLMNOPQ + docp[87] + docp[86] + docp[85] )/4),
array.insert(doc_p, 88 , (AVGdocp5_ABCDEFGHIJKLMNOPQ + docp[88] + docp[87] + docp[86] + docp[85] )/5),
array.insert(doc_p, 89 , (AVGdocp5_ABCDEFGHIJKLMNOPQR)),
array.insert(doc_p, 90 , (AVGdocp5_ABCDEFGHIJKLMNOPQR + docp[90] )/2),
array.insert(doc_p, 91 , (AVGdocp5_ABCDEFGHIJKLMNOPQR + docp[91] + docp[90] )/3),
array.insert(doc_p, 92 , (AVGdocp5_ABCDEFGHIJKLMNOPQR + docp[92] + docp[91] + docp[90])/4),
array.insert(doc_p, 93 , (AVGdocp5_ABCDEFGHIJKLMNOPQR + docp[93] + docp[92] + docp[91] + docp[90])/5),
array.insert(doc_p, 94 , (AVGdocp5_ABCDEFGHIJKLMNOPQRS)),
array.insert(doc_p, 95 , (AVGdocp5_ABCDEFGHIJKLMNOPQRS + docp[95] )/2),
array.insert(doc_p, 96 , (AVGdocp5_ABCDEFGHIJKLMNOPQRS + docp[96] + docp[95] )/3),
array.insert(doc_p, 97 , (AVGdocp5_ABCDEFGHIJKLMNOPQRS + docp[97] + docp[96] + docp[95] )/4),
array.insert(doc_p, 98 , (AVGdocp5_ABCDEFGHIJKLMNOPQRS + docp[98] + docp[97] + docp[96] + docp[95] )/5),
array.insert(doc_p, 99 , (AVGdocp5_ABCDEFGHIJKLMNOPQRST))
// Negative -
doc_n = array.new_float(100, len1),
array.insert(doc_n, 0 , docn),
array.insert(doc_n, 1 , (docn[1] + docn)/2),
array.insert(doc_n, 2 , (docn[2] + docn[1] + docn)/3),
array.insert(doc_n, 3 , (docn[3] + docn[2] + docn[1] + docn)/4),
array.insert(doc_n, 4 , AVGdocn5_A),
array.insert(doc_n, 5 , (AVGdocn5_A + docn[5])/2),
array.insert(doc_n, 6 , (AVGdocn5_A + docn[6] + docn[5])/3),
array.insert(doc_n, 7 , (AVGdocn5_A + docn[7] + docn[6] + docn[5])/4),
array.insert(doc_n, 8 , (AVGdocn5_A + docn[8] + docn[7] + docn[6] + docn[5])/5),
array.insert(doc_n, 9 , (AVGdocn5_AB)),
array.insert(doc_n, 10 , (AVGdocn5_AB + docn[10] )/2),
array.insert(doc_n, 11 , (AVGdocn5_AB + docn[11] + docn[10] )/3),
array.insert(doc_n, 12 , (AVGdocn5_AB + docn[12] + docn[11] + docn[10] )/4),
array.insert(doc_n, 13 , (AVGdocn5_AB + docn[13] + docn[12] + docn[11] + docn[10] )/5),
array.insert(doc_n, 14 , (AVGdocn5_ABC)),
array.insert(doc_n, 15 , (AVGdocn5_ABC + docn[15] )/2),
array.insert(doc_n, 16 , (AVGdocn5_ABC + docn[16] + docn[15])/3),
array.insert(doc_n, 17 , (AVGdocn5_ABC + docn[17] + docn[16] + docn[15])/4),
array.insert(doc_n, 18 , (AVGdocn5_ABC + docn[18] + docn[17] + docn[16] + docn[15])/7),
array.insert(doc_n, 19 , (AVGdocn5_ABCD)),
array.insert(doc_n, 20 , (AVGdocn5_ABCD + docn[20]) /2),
array.insert(doc_n, 21 , (AVGdocn5_ABCD + docn[21] + docn[20])/3),
array.insert(doc_n, 22 , (AVGdocn5_ABCD + docn[22] + docn[21] + docn[20] )/4),
array.insert(doc_n, 23 , (AVGdocn5_ABCD + docn[23] + docn[22] + docn[21] + docn[20] )/5),
array.insert(doc_n, 24 , (AVGdocn5_ABCDE)),
array.insert(doc_n, 25 , (AVGdocn5_ABCDE + docn[25] )/2),
array.insert(doc_n, 26 , (AVGdocn5_ABCDE + docn[26] + docn[25])/3),
array.insert(doc_n, 27 , (AVGdocn5_ABCDE + docn[27] + docn[26] + docn[25] )/4),
array.insert(doc_n, 28 , (AVGdocn5_ABCDE + docn[28] + docn[27] + docn[26] + docn[25] )/5),
array.insert(doc_n, 29 , (AVGdocn5_ABCDEF)),
array.insert(doc_n, 30 , (AVGdocn5_ABCDEF + docn[30] )/2),
array.insert(doc_n, 31 , (AVGdocn5_ABCDEF + docn[31] + docn[30] )/3),
array.insert(doc_n, 32 , (AVGdocn5_ABCDEF + docn[32] + docn[31] + docn[30] )/4),
array.insert(doc_n, 33 , (AVGdocn5_ABCDEF + docn[33] + docn[32] + docn[31] + docn[30] )/5),
array.insert(doc_n, 34 , (AVGdocn5_ABCDEFG)),
array.insert(doc_n, 35 , (AVGdocn5_ABCDEFG + docn[35] )/2),
array.insert(doc_n, 36 , (AVGdocn5_ABCDEFG + docn[36] + docn[35] )/3),
array.insert(doc_n, 37 , (AVGdocn5_ABCDEFG + docn[37] + docn[36] + docn[35] )/4),
array.insert(doc_n, 38 , (AVGdocn5_ABCDEFG + docn[38] + docn[37] + docn[36] + docn[35] )/5),
array.insert(doc_n, 39 , (AVGdocn5_ABCDEFGH )),
array.insert(doc_n, 40 , (AVGdocn5_ABCDEFGH + docn[40] )/2),
array.insert(doc_n, 41 , (AVGdocn5_ABCDEFGH + docn[41] + docn[40])/3),
array.insert(doc_n, 42 , (AVGdocn5_ABCDEFGH + docn[42] + docn[41] + docn[40])/4),
array.insert(doc_n, 43 , (AVGdocn5_ABCDEFGH + docn[43] + docn[42] + docn[41] + docn[40])/5),
array.insert(doc_n, 44 , (AVGdocn5_ABCDEFGHI)),
array.insert(doc_n, 45 , (AVGdocn5_ABCDEFGHI + docn[45] )/2),
array.insert(doc_n, 46 , (AVGdocn5_ABCDEFGHI + docn[46] + docn[45] )/3),
array.insert(doc_n, 47 , (AVGdocn5_ABCDEFGHI + docn[47] + docn[46] + docn[45] )/4),
array.insert(doc_n, 48 , (AVGdocn5_ABCDEFGHI + docn[48] + docn[47] + docn[46] + docn[45] )/5),
array.insert(doc_n, 49 , (AVGdocn5_ABCDEFGHIJ)),
array.insert(doc_n, 50 , (AVGdocn5_ABCDEFGHIJ + docn[50])/2),
array.insert(doc_n, 51 , (AVGdocn5_ABCDEFGHIJ + docn[51] + docn[50] )/3),
array.insert(doc_n, 52 , (AVGdocn5_ABCDEFGHIJ + docn[52] + docn[51] + docn[50] )/4),
array.insert(doc_n, 53 , (AVGdocn5_ABCDEFGHIJ + docn[53] + docn[52] + docn[51] + docn[50] )/5),
array.insert(doc_n, 54 , (AVGdocn5_ABCDEFGHIJK)),
array.insert(doc_n, 55 , (AVGdocn5_ABCDEFGHIJK + docn[55] )/2),
array.insert(doc_n, 56 , (AVGdocn5_ABCDEFGHIJK + docn[56] + docn[55] )/3),
array.insert(doc_n, 57 , (AVGdocn5_ABCDEFGHIJK + docn[57] + docn[56] + docn[55] )/4),
array.insert(doc_n, 58 , (AVGdocn5_ABCDEFGHIJK + docn[58] + docn[57] + docn[56] + docn[55] )/5),
array.insert(doc_n, 59 , (AVGdocn5_ABCDEFGHIJKL)),
array.insert(doc_n, 60 , (AVGdocn5_ABCDEFGHIJKL + docn[60] )/2),
array.insert(doc_n, 61 , (AVGdocn5_ABCDEFGHIJKL + docn[61] + docn[60] )/3),
array.insert(doc_n, 62 , (AVGdocn5_ABCDEFGHIJKL + docn[62] + docn[61] + docn[60] )/4),
array.insert(doc_n, 63 , (AVGdocn5_ABCDEFGHIJKL + docn[63] + docn[62] + docn[61] + docn[60] )/5),
array.insert(doc_n, 64 , (AVGdocn5_ABCDEFGHIJKLM)),
array.insert(doc_n, 65 , (AVGdocn5_ABCDEFGHIJKLM + docn[65] )/2),
array.insert(doc_n, 66 , (AVGdocn5_ABCDEFGHIJKLM + docn[66] + docn[65] )/3),
array.insert(doc_n, 67 , (AVGdocn5_ABCDEFGHIJKLM + docn[67] + docn[66] + docn[65] )/4),
array.insert(doc_n, 68 , (AVGdocn5_ABCDEFGHIJKLM + docn[68] + docn[67] + docn[66] + docn[65] )/5),
array.insert(doc_n, 69 , (AVGdocn5_ABCDEFGHIJKLMN)),
array.insert(doc_n, 70 , (AVGdocn5_ABCDEFGHIJKLMN + docn[70] )/2),
array.insert(doc_n, 71 , (AVGdocn5_ABCDEFGHIJKLMN + docn[71] + docn[70] )/3),
array.insert(doc_n, 72 , (AVGdocn5_ABCDEFGHIJKLMN + docn[72] + docn[71] + docn[70] )/4),
array.insert(doc_n, 73 , (AVGdocn5_ABCDEFGHIJKLMN + docn[73] + docn[72] + docn[71] + docn[70] )/5),
array.insert(doc_n, 74 , (AVGdocn5_ABCDEFGHIJKLMNO)),
array.insert(doc_n, 75 , (AVGdocn5_ABCDEFGHIJKLMN + docn[75] )/2),
array.insert(doc_n, 76 , (AVGdocn5_ABCDEFGHIJKLMN + docn[76] + docn[75] )/3),
array.insert(doc_n, 77 , (AVGdocn5_ABCDEFGHIJKLMN + docn[77] + docn[76] + docn[75] )/4),
array.insert(doc_n, 78 , (AVGdocn5_ABCDEFGHIJKLMN + docn[78] + docn[77] + docn[76] + docn[75] )/5),
array.insert(doc_n, 79 , (AVGdocn5_ABCDEFGHIJKLMNOP)),
array.insert(doc_n, 80 , (AVGdocn5_ABCDEFGHIJKLMNOP + docn[80])/2),
array.insert(doc_n, 81 , (AVGdocn5_ABCDEFGHIJKLMNOP + docn[81] + docn[80])/3),
array.insert(doc_n, 82 , (AVGdocn5_ABCDEFGHIJKLMNOP + docn[82] + docn[81] + docn[80])/4),
array.insert(doc_n, 83 , (AVGdocn5_ABCDEFGHIJKLMNOP + docn[83] + docn[82] + docn[81] + docn[80] )/5),
array.insert(doc_n, 84 , (AVGdocn5_ABCDEFGHIJKLMNOPQ)),
array.insert(doc_n, 85 , (AVGdocn5_ABCDEFGHIJKLMNOPQ + docn[85] )/2),
array.insert(doc_n, 86 , (AVGdocn5_ABCDEFGHIJKLMNOPQ + docn[86] + docn[85] )/3),
array.insert(doc_n, 87 , (AVGdocn5_ABCDEFGHIJKLMNOPQ + docn[87] + docn[86] + docn[85] )/4),
array.insert(doc_n, 88 , (AVGdocn5_ABCDEFGHIJKLMNOPQ + docn[88] + docn[87] + docn[86] + docn[85] )/5),
array.insert(doc_n, 89 , (AVGdocn5_ABCDEFGHIJKLMNOPQR)),
array.insert(doc_n, 90 , (AVGdocn5_ABCDEFGHIJKLMNOPQR + docn[90] )/2),
array.insert(doc_n, 91 , (AVGdocn5_ABCDEFGHIJKLMNOPQR + docn[91] + docn[90] )/3),
array.insert(doc_n, 92 , (AVGdocn5_ABCDEFGHIJKLMNOPQR + docn[92] + docn[91] + docn[90])/4),
array.insert(doc_n, 93 , (AVGdocn5_ABCDEFGHIJKLMNOPQR + docn[93] + docn[92] + docn[91] + docn[90])/5),
array.insert(doc_n, 94 , (AVGdocn5_ABCDEFGHIJKLMNOPQRS)),
array.insert(doc_n, 95 , (AVGdocn5_ABCDEFGHIJKLMNOPQRS + docn[95] )/2),
array.insert(doc_n, 96 , (AVGdocn5_ABCDEFGHIJKLMNOPQRS + docn[96] + docn[95] )/3),
array.insert(doc_n, 97 , (AVGdocn5_ABCDEFGHIJKLMNOPQRS + docn[97] + docn[96] + docn[95] )/4),
array.insert(doc_n, 98 , (AVGdocn5_ABCDEFGHIJKLMNOPQRS + docn[98] + docn[97] + docn[96] + docn[95] )/5),
array.insert(doc_n, 99 , (AVGdocn5_ABCDEFGHIJKLMNOPQRST)),
//Variable Declerations
docAVG_ = math.avg(array.avg(doc_n), array.avg(doc_p))
doc_nV = array.get(doc_n, len1)
doc_pV = array.get(doc_p, len1)
coV_sig2_array = ta.variance(docAVG_, len1) - (array.covariance(doc_p, doc_n, len1) - docAVG_)
e = ta.sma(close - (close-coV_sig2_array), len3)
m = ta.mom(close, len3)
a = ta.alma((close-(close-coV_sig2_array)), len4, 0, 6)
//Plot Functions
plot(a, 'alma', color.red, 1, plot.style_line, display = display.none)
plot(e, 'The RC Average', color.yellow , 1, plot.style_linebr)
plot(m, 'Momentum', m >= e and m >= a and m >= coV_sig2_array ? color.green:(m<= e and m <= a and m <= coV_sig2_array ? color.red:color.teal) , 3, plot.style_linebr )
plot(coV_sig2_array, 'DAP\'s Oscillator', color.aqua , 6)
|
Commission-aware Trade Labels | https://www.tradingview.com/script/LXKGbXnK-Commission-aware-Trade-Labels/ | bunulu | https://www.tradingview.com/u/bunulu/ | 24 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Andrei Bunulu
// @version=5
library("tradelabels", overlay=true)
labelSize(size) =>
switch size
"tiny" => size.tiny
"small" => size.small
"normal" => size.normal
"large" => size.large
"huge" => size.huge
=>
size.auto
// @type Order
// @field entry_price Entry price
// @field stop_loss_price Stop loss price
// @field stop_loss_percent Stop loss percent, default 2%
// @field take_profit_price Take profit price
// @field take_profit_percent Take profit percent, default 6%
// @field entry_amount Entry amount, default 5000$
// @field shares Shares
// @field commission Commission, default 0.04%
export type Order
float entry_price = na
float stop_loss_price = na
float stop_loss_percent = 2.0 // 2%
float take_profit_price = na
float take_profit_percent = 6.0 // 6%
float entry_amount = 5000.00
float shares = na
float commission = 0.04 // 0.04%
float risk_reward_ratio = 0.00 // 3.00
// @method entry_price
// @param this Order object
// @return entry_price
export method entry_price(Order this) =>
entry_price = na(this.entry_price) ? close : this.entry_price
entry_price
// @method stop_loss_price
// @param this Order object
// @return stop_loss_price
export method stop_loss_price(Order this) =>
if not this.stop_loss_price and not this.stop_loss_percent
runtime.error("No stop loss price/percent set")
entry_price = this.entry_price()
stop_loss_price = na(this.stop_loss_price) ? entry_price * (1 - this.stop_loss_percent) : this.stop_loss_price
stop_loss_price
// @method take_profit_price
// @param this Order object
// @return take_profit_price
export method take_profit_price(Order this) =>
if not this.take_profit_price and not this.take_profit_percent and not this.risk_reward_ratio == 0.00
runtime.error("No take profit price/percent set")
entry_price = this.entry_price()
stop_loss_price = this.stop_loss_price()
take_profit_price = this.take_profit_price
take_profit_percent = this.take_profit_percent
risk_reward_ratio = this.risk_reward_ratio == 0.00 ? na : this.risk_reward_ratio
if na(take_profit_price) and not na(take_profit_percent)
take_profit_price := entry_price * (1 + take_profit_percent)
if not na(risk_reward_ratio) and not na(stop_loss_price)
take_profit_price := entry_price + (entry_price - stop_loss_price) * risk_reward_ratio
take_profit_price
// @method is_long
// @param this Order object
// @return entry_price
export method is_long(Order this) =>
entry_price = this.entry_price()
take_profit_price = this.take_profit_price()
is_long = entry_price < take_profit_price
is_long
// @method is_short
// @param this Order object
// @return entry_price
export method is_short(Order this) =>
entry_price = this.entry_price()
take_profit_price = this.take_profit_price()
is_short = entry_price > take_profit_price
is_short
// @method percent_to_target
// @param this Order object
// @param target Target price
// @return percent
export method percent_to_target(Order this, float target) =>
entry_price = this.entry_price()
percent = math.abs((target - entry_price) / entry_price) * 100
percent
// @method risk_reward
// @param this Order object
// @return risk_reward_ratio
export method risk_reward(Order this) =>
entry_price = this.entry_price()
take_profit_price = this.take_profit_price()
stop_loss_price = this.stop_loss_price()
risk_reward_ratio = this.risk_reward_ratio == 0.00 ? na : this.risk_reward_ratio
if (not na(take_profit_price) and not na(stop_loss_price)) and
((this.is_long() and take_profit_price > entry_price and stop_loss_price < entry_price) or
(this.is_short() and take_profit_price < entry_price and stop_loss_price > entry_price))
// Calculate risk/reward
risk = entry_price - stop_loss_price
reward = take_profit_price - entry_price
risk_reward = reward / risk
risk_reward_ratio := math.round(risk_reward, 2)
risk_reward_ratio
// @method shares
// @param this Order object
// @return shares
export method shares(Order this) =>
entry_price = this.entry_price()
shares = na(this.shares) ? this.entry_amount / entry_price : this.shares
shares
// @method position_size
// @param this Order object
// @return position_size
export method position_size(Order this) =>
entry_price = this.entry_price()
shares = this.shares()
position_size = shares * entry_price
position_size
// @method commission_cost
// @param this Order object
// @return commission_cost
export method commission_cost(Order this, float target_price) =>
entry_price = this.entry_price()
shares = this.shares()
// Calculate commission for entry and exit transactions
commission_cost = ((this.commission / 100) * (entry_price * shares)) + ((this.commission / 100) * (target_price * shares))
commission_cost
// @method net_result
// @param this Order object
// @param target_price The target price to calculate net result for (either take_profit_price or stop_loss_price)
// @return net_result
export method net_result(Order this, float target_price) =>
entry_price = this.entry_price()
shares = this.shares()
gross_result = this.is_long() ? (target_price - entry_price) * shares : (entry_price - target_price) * shares
commission_cost = this.commission_cost(target_price)
// Calculate net result
net_result = gross_result - commission_cost
net_result
// @method create_take_profit_label
// @param this Order object
// @param simulate Is this a simulated label, default false
// @param prefix Label prefix
// @param size Label size, default small
// @param offset_x Label offset, default 5
// @param bg_color Label background color
// @param text_color Label text color
// @return void
export method create_take_profit_label(
Order this,
bool simulate = false,
string prefix = "✓",
string size = "small",
simple int offset_x = 5,
color bg_color = na,
color text_color = #003e1f) =>
var label take_profit_label = na
if barstate.islast
entry_price = this.entry_price()
target_price = this.take_profit_price()
stop_loss_price = this.stop_loss_price()
percent_to_target_price = this.percent_to_target(target_price)
// Calculate shares
shares = this.shares()
// Calculate position size
position_size = this.position_size()
// Calculate profit
net_amount = this.net_result(target_price)
// Calculate risk/reward
risk_reward_ratio = this.risk_reward()
// Label variables
var string type = entry_price < target_price ? "long" : "short"
var string rr_text = na(risk_reward_ratio) ? "" : "R/R: " + str.tostring(risk_reward_ratio, "##.##")
var string commission_cost = "\nCommission: " + str.tostring(this.commission_cost(target_price), "##.##") + "$"
var string stop_loss_text = na(risk_reward_ratio) ? "" : "\nStop loss: " + str.tostring(stop_loss_price)
var string amount = simulate ? "" : str.format("{0,number,currency}", net_amount) + " - "
// Draw the label
take_profit_label := label.new(
last_bar_index + offset_x,
target_price,
text=prefix + " " + str.tostring(target_price)
+ " - " + str.tostring(percent_to_target_price, "##.##") + "% - "
+ amount
+ rr_text,
tooltip = "Entry price: " + str.tostring(entry_price)
+ "\nTarget price: " + str.tostring(target_price)
+ "\nEntry amount: " + str.tostring(position_size) + "$"
+ stop_loss_text
+ commission_cost
+ "\nShares: " + str.tostring(shares, "##.####"))
label.set_style(take_profit_label, style=type == "long" ? label.style_label_lower_left : label.style_label_upper_left)
label.set_textcolor(take_profit_label, textcolor = text_color)
label.set_color(take_profit_label, bg_color)
label.set_size(take_profit_label, labelSize(size))
label.delete(take_profit_label[1])
// @method create_stop_loss_label
// @param this Order object
// @param simulate Is this a simulated label, default false
// @param prefix Label prefix
// @param size Label size, default small
// @param offset_x Label offset, default 5
// @param bg_color Label background color
// @param text_color Label text color
// @return void
export method create_stop_loss_label(
Order this,
bool simulate = false,
string prefix = "✘",
string size = "small",
simple int offset_x = 5,
color bg_color = na,
color text_color = #c9032b) =>
var label stop_loss_label = na
if barstate.islast
entry_price = this.entry_price()
stop_loss_price = this.stop_loss_price()
// Calculate shares
shares = this.shares()
// Calculate position size
position_size = this.position_size()
// Calculate profit
percent_to_stop_loss = this.percent_to_target(stop_loss_price)
stop_amount = this.net_result(stop_loss_price)
// Draw the label
if simulate
stop_loss_label := label.new(last_bar_index + offset_x, stop_loss_price, text=prefix + " " + str.tostring(stop_loss_price) + " - " + str.tostring(percent_to_stop_loss, "##.##") + "%")
else
stop_loss_label := label.new(last_bar_index + offset_x, stop_loss_price, text=prefix + " " + str.tostring(stop_loss_price) + " - " + str.tostring(percent_to_stop_loss, "##.##") + "% - " + str.format("{0,number,currency}", stop_amount))
label.set_style(stop_loss_label, style=entry_price > stop_loss_price ? label.style_label_upper_left : label.style_label_lower_left)
label.set_textcolor(stop_loss_label, textcolor = text_color)
label.set_color(stop_loss_label, bg_color)
label.set_size(stop_loss_label, labelSize(size))
label.delete(stop_loss_label[1])
// @method create_entry_label
// @param this Order object
// @param simulate Is this a simulated label, default false
// @param prefix Label prefix
// @param size Label size, default small
// @param offset_x Label offset, default 5
// @param bg_color Label background color
// @param text_color Label text color
// @return void
export method create_entry_label(
Order this,
bool simulate = false,
string prefix = "⌞",
string size = "small",
simple int offset_x = 5,
color bg_color = na,
color text_color = #49416D) =>
var label entry_label = na
if barstate.islast
entry_price = this.entry_price()
// Calculate shares
shares = this.shares()
// Calculate position size
position_size = this.position_size()
// Draw the label
if simulate
entry_label := label.new(last_bar_index + offset_x, entry_price, text=prefix + " " + str.tostring(entry_price))
else
entry_label := label.new(last_bar_index + offset_x, entry_price, text=prefix + " " + str.tostring(entry_price) + " - " + str.format("{0,number,currency}", position_size) + " - " + "Shares: " + str.tostring(shares, "##.####"))
label.set_style(entry_label, style=label.style_label_lower_left)
label.set_textcolor(entry_label, textcolor = text_color)
label.set_color(entry_label, bg_color)
label.set_size(entry_label, labelSize(size))
label.delete(entry_label[1])
export method create_line(Order this, float target_price, color line_color, int offset_x = 10, string line_style = line.style_dotted, int line_width = 1, bool draw_entry_line = true) =>
var line entry_line = na
var line line = na
if barstate.islast
if draw_entry_line
entry_price = this.entry_price()
entry_line := line.new(x1=bar_index, x2=last_bar_index + offset_x, y1=entry_price, y2=entry_price, width=line_width, color=line_color, style=line_style)
line.delete(entry_line[1])
line := line.new(x1=bar_index, x2=last_bar_index + offset_x, y1=target_price, y2=target_price, width=line_width, color=line_color, style=line_style)
line.delete(line[1])
// Example
// ------------------------------------------------
entry_order = Order.new()
entry_order.create_entry_label(simulate=true)
entry_order.create_line(target_price=entry_order.entry_price(), line_color=#49416D, draw_entry_line = false, line_style = line.style_solid)
take_profit_order = Order.new(take_profit_price=25000, stop_loss_price=29000)
take_profit_order.create_take_profit_label(size="normal")
take_profit_order.create_line(target_price=take_profit_order.take_profit_price(), line_color=#003e1f)
take_profit_order2 = Order.new(stop_loss_price=25600, risk_reward_ratio=3.00)
take_profit_order2.create_take_profit_label(size="normal")
take_profit_order2.create_line(target_price=take_profit_order2.take_profit_price(), line_color=#003e1f)
stop_loss_order = Order.new(stop_loss_price=29000)
stop_loss_order.create_stop_loss_label()
stop_loss_order.create_line(target_price=stop_loss_order.stop_loss_price(), line_color=#c9032b, draw_entry_line = false)
|
TextLib | https://www.tradingview.com/script/iHCVxoEP-textlib/ | Hamster-Coder | https://www.tradingview.com/u/Hamster-Coder/ | 0 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Hamster-Coder
//@version=5
// @description TODO: Library with text / string functions
library("TextLib", overlay = true)
// @function TODO: add function description here
// @param x TODO: add parameter x description here
// @returns TODO: add what function returns
// export concat(string value1, string value2, string separator = "\n") =>
// string result = ""
// if (str.length(value1) == 0 and str.length(value2) == 0)
// result := result
// else if (str.length(value1) == 0)
// result := value2
// else if (str.length(value2) == 0)
// result := value1
// else
// result := value1 + separator + value2
// result
export type textFormatOptions
string currency_format = "0.00"
string percent_format = "0.00"
string basecurrency_format = "0.00"
export concat(string[] values, string separator) =>
string result = ""
for [index, value] in values
if (str.length(result) == 0 and str.length(value) == 0)
result := result
else if (str.length(result) == 0)
result := value
else if (str.length(value) == 0)
result := result
else
result := result + separator + value
//string result = array.join(values, separator)
result
export concat(string value1, string value2, string separator) =>
values = array.from(value1, value2)
concat(values, separator)
export concat(string value1, string value2, string value3, string separator) =>
values = array.from(value1, value2, value3)
concat(values, separator)
export concat(string value1, string value2, string value3, string value4, string separator) =>
values = array.from(value1, value2, value3, value4)
concat(values, separator)
export concat(string value1, string value2, string value3, string value4, string value5, string separator) =>
values = array.from(value1, value2, value3, value4, value5)
concat(values, separator)
export concatLine(string[] values) =>
concat(values, "\n")
export concatLine(string value1, string value2) =>
values = array.from(value1, value2)
concatLine(values)
export concatLine(string value1, string value2, string value3) =>
values = array.from(value1, value2, value3)
concatLine(values)
export concatLine(string value1, string value2, string value3, string value4) =>
values = array.from(value1, value2, value3, value4)
concatLine(values)
export concatLine(string value1, string value2, string value3, string value4, string value5) =>
values = array.from(value1, value2, value3, value4, value5)
concatLine(values)
|
TradersPost WebhookMessage Library - Automatically Build JSON | https://www.tradingview.com/script/Dfo3ErmN-TradersPost-WebhookMessage-Library-Automatically-Build-JSON/ | TradersPostInc | https://www.tradingview.com/u/TradersPostInc/ | 12 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradersPostInc (https://traderspost.io). Visit TradersPost to automate your TradingView strategies and indicators.
//@version=5
// @description The webhook message library provides several functions for building JSON payloads
// used as instructions to manage automated orders and positions with TradersPost.io. See:
// https://docs.traderspost.io/docs/learn/webhooks
library("WebhookMessage", overlay = false)
// Example: Go long, 1 contract, with a 0.75% trailing stop
// import TradersPostInc/WebhookMessage/1 as wm
// cnst = wm.CONSTANTS.new()
// msg = wm.webhookMessage.new(
// ticker = syminfo.ticker,
// action = cnst.ACTION_BUY,
// sentiment = cnst.SENTIMENT_BULLISH,
// quantity = 1,
// stopLoss = wm.stopLossMessage.new(type = cnst.STOP_LOSS_TYPE_TRAILING_STOP, trailPercent = 0.75).buildStopLossJson()
// ).buildWebhookJson()
// alert(msg, freq = alert.freq_once_per_bar_close)
// @type Constants for payload values.
// @field <string> ACTION_BUY buy - Exit bearish position and optionally open bullish position. Used in webhookMessage.action.
// @field <string> ACTION_SELL sell - Exit bullish position and optionally open bearish position. Used in webhookMessage.action.
// @field <string> ACTION_EXIT exit - Exit open position without entering a new position on the other side. Used in webhookMessage.action.
// @field <string> ACTION_CANCEL cancel - Cancel open orders. Used in webhookMessage.action.
// @field <string> ACTION_ADD add - Add to existing open position. Used in webhookMessage.action.
// @field <string> SENTIMENT_BULLISH bullish - Open position after trade is executed should be bullish or flat. Used in webhookMessage.sentiment.
// @field <string> SENTIMENT_BEARISH bearish - Open position after trade is executed should be bearish or flat. Used in webhookMessage.sentiment.
// @field <string> SENTIMENT_FLAT flat - No position should be open after trade is executed. Used in webhookMessage.sentiment.
// @field <string> Stop loss type of market stop. Used in stopLossMessage.type.
// @field <string> Stop loss type of limit stop. Used in stopLossMessage.type.
// @field <string> Stop loss type of trailing stop. Used in stopLossMessage.type.
export type CONSTANTS
ACTION_BUY = "buy"
ACTION_SELL = "sell"
ACTION_EXIT = "exit"
ACTION_CANCEL = "cancel"
ACTION_ADD = "add"
SENTIMENT_BULLISH = "bullish"
SENTIMENT_BEARISH = "bearish"
SENTIMENT_LONG = "long"
SENTIMENT_SHORT = "short"
SENTIMENT_FLAT = "flat"
STOP_LOSS_TYPE_STOP = "stop"
STOP_LOSS_TYPE_STOP_LIMIT = "stop_limit"
STOP_LOSS_TYPE_TRAILING_STOP = "trailing_stop"
cnst = CONSTANTS.new()
// @type Final webhook message. See: https://docs.traderspost.io/docs/learn/webhooks#what-is-a-webhook
// @field <string> ticker The ticker symbol name. Example: SPY.
// @field <string> action The signal action. Supported values are buy, sell, exit, cancel or add.
// @field <string> sentiment bullish, bearish, or flat.
// @field <float> price The price of the buy or sell action. If you omit this value, the current market price will be used when the trade is executed.
// @field <int> quantity The quantity to enter. If you omit this value, the quantity will be dynamically calculated or defaulted to 1.
// @field <takeProfitMessage> takeProfit. See takeProfitMessage.
// @field <stopLossMessage> stopLoss. See stopLossMessage.
export type webhookMessage
string ticker
string action
string sentiment
float price
int quantity
string takeProfit = ""
string stopLoss = ""
// @type Take profit message. See: https://docs.traderspost.io/docs/learn/webhooks#signal-take-profit
// @field <string> limitPrice Absolute limit price calculated on the webhook sender side.
// @field <float> percent Relative percentage take profit to calculate relative to entry price. The entry price for market orders is estimated based on the mid point between the bid and ask on the most recent quote.
// @field <float> amount Relative dollar amount take profit to calculate relative to entry price. The entry price for market orders is estimated based on the mid point between the bid and ask on the most recent quote.
export type takeProfitMessage
float limitPrice
float percent
float amount
// @type Stop loss message. See: https://docs.traderspost.io/docs/learn/webhooks#signal-stop-loss
// @field <string> type Type of stop loss. If a value is provided, it overrides the stop loss type configured in strategy subscription settings. Allowed values are: stop, stop_limit, trailing_stop.
// @field <float> percent Relative percentage stop loss to calculate relative to entry price.
// @field <float> amount Relative dollar amount stop loss to calculate relative to entry price.
// @field <float> stopPrice Absolute stop price calculated on the webhook sender side.
// @field <float> limitPrice Absolute limit price calculated on the webhook sender side. type must be set to stop_limit to use this field.
// @field <float> trailPrice A dollar value away from the highest water mark. If you set this to 2.00 for a sell trailing stop, the stop price is always hwm - 2.00. type must be set to trailing_stop to use this field.
// @field <float> trailPercent A percent value away from the highest water mark. If you set this to 1.0 for a sell trailing stop, the stop price is always hwm * 0.99. type must be set to trailing_stop to use this field.
export type stopLossMessage
string type
float percent
float amount
float stopPrice
float limitPrice
float trailPrice
float trailPercent
// @function Builds the final JSON payload from a webhookMessage type.
// @param <webhookMessage> msg A prepared webhookMessage.
// @returns <string> A JSON Payload.
export method buildWebhookJson(webhookMessage msg) =>
json = "{"
json += '"library": "WebhookMessage"'
json += ',"timestamp": "' + str.tostring(time) + '"'
//ticker
json += ',"ticker": "' + (msg.ticker == "" ? syminfo.ticker : msg.ticker) + '"'
// action
json += ',"action": "' + msg.action + '"'
// sentiment
if (msg.sentiment == cnst.SENTIMENT_BULLISH or msg.sentiment == cnst.SENTIMENT_BEARISH or msg.sentiment == cnst.SENTIMENT_LONG or msg.sentiment == cnst.SENTIMENT_SHORT or msg.sentiment == cnst.SENTIMENT_FLAT)
json += ',"sentiment": "' + msg.sentiment + '"'
// price
json += msg.price > 0 ? ',"price": ' + str.tostring(msg.price) : ""
// quantity
json += msg.quantity > 0 ? ',"quantity": ' + str.tostring(msg.quantity) : ""
// takeProfit
if (msg.takeProfit != "")
json += ',"takeProfit":' + msg.takeProfit
// stopLoss
if (msg.stopLoss != "")
json += ',"stopLoss":' + msg.stopLoss
json += "}"
json
// @function Builds the takeProfit JSON message to be used in a webhook message.
// @param <takeProfitMessage> msg
// @returns <string> A JSON takeProfit payload.
export method buildTakeProfitJson(takeProfitMessage msg) =>
json = '{'
json += na(msg.limitPrice) ? "" : '"limitPrice": ' + str.tostring(msg.limitPrice)
json += na(msg.percent) ? "" : '"percent": ' + str.tostring(msg.percent)
json += na(msg.amount) ? "" : '"amount": ' + str.tostring(msg.amount)
json += "}"
json
// @function Builds the stopLoss JSON message to be used in a webhook message.
// @param <stopLossMessage> msg
// @returns <string> A JSON stopLoss payload.
export method buildStopLossJson(stopLossMessage msg) =>
//overload type message if not configured properly
if (not na(msg.limitPrice) and msg.type != cnst.STOP_LOSS_TYPE_STOP_LIMIT)
msg.type := cnst.STOP_LOSS_TYPE_STOP_LIMIT
if (not na(msg.trailPrice) or not na(msg.trailPercent) and msg.type != cnst.STOP_LOSS_TYPE_TRAILING_STOP)
msg.type := cnst.STOP_LOSS_TYPE_TRAILING_STOP
json = '{'
messages = array.new_string(0)
if (na(msg.type) == false)
array.push(messages, '"type": "' + msg.type + '"')
if (na(msg.percent) == false)
array.push(messages, '"percent": ' + str.tostring(msg.percent))
if (na(msg.amount) == false)
array.push(messages, '"amount": ' + str.tostring(msg.amount))
if (na(msg.stopPrice) == false)
array.push(messages, '"stopPrice": ' + str.tostring(msg.stopPrice))
if (na(msg.limitPrice) == false)
array.push(messages, '"limitPrice": ' + str.tostring(msg.limitPrice))
if (na(msg.trailPrice) == false)
array.push(messages, '"trailPrice": ' + str.tostring(msg.trailPrice))
if (na(msg.trailPercent) == false)
array.push(messages, '"trailPercent": ' + str.tostring(msg.trailPercent))
json += array.join(messages, ",")
json += "}"
json
//plot nothing to pass publishing rules
plot(0) |
Utils | https://www.tradingview.com/script/NguFQ9iG-Utils/ | andre_007 | https://www.tradingview.com/u/andre_007/ | 47 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=5
// @Author andre_007
// @description Utility functions. Mathematics, colors, and auxiliary algorithms.
library("Utils")
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region valueColorSpectrum: Theme for a Oscillator with levels of colors. Levels from 0 to 100/0 to -100.
// @type # Object to associate a color with a value, taking into account the previous value and its levels.
// ## Stores a color theme, which is used according to the position of the value within the levels.
// @field (float) currentValue Current value.
// @field (float) previousValue Previous value.
// @field (float) level1 Level 1. Default is 10.
// @field (float) level2 Level 2. Default is 30.
// @field (float) level3 Level 3. Default is 50.
// @field (float) level4 Level 4. Default is 70.
// @field (float) level5 Level 5. Default is 90.
// @field (color) currentColorValue Color associeted with current value. This value must be calculated with setCurrentColorValue method.
// @field (color) colorLevel_Lv1 Color associeted with value when below Level 1.
// @field (color) colorLevel_Lv1_Lv2 Color associeted with value when between Level 1 and 2.
// @field (color) colorLevel_Lv2_Lv3 Color associeted with value when between Level 2 and 3.
// @field (color) colorLevel_Lv3_Lv4 Color associeted with value when between Level 3 and 4.
// @field (color) colorLevel_Lv4_Lv5 Color associeted with value when between Level 4 and 5.
// @field (color) colorLevel_Lv5 Color associeted with value when above Level 5.
// @field (int) theme Theme (predefined colors). 1='Spectrum Blue-Green-Red'; 2='Monokai'; 3='User defined'
export type valueColorSpectrum
// Values
float currentValue
float previousValue
// Levels
float level1 = 10
float level2 = 30
float level3 = 50
float level4 = 70
float level5 = 90
// Colors. Default colors from theme 'Spectrum Blue-Green-Red'
color currentColorValue
color colorLevel_Lv1 = #0000FF
color colorLevel_Lv1_Lv2 = #01b5cc
color colorLevel_Lv2_Lv3 = #3af13c
color colorLevel_Lv3_Lv4 = #ffeb3b
color colorLevel_Lv4_Lv5 = #ff6d00
color colorLevel_Lv5 = #ff0000
int theme = 1 // Spectrum Blue-Green-Red
// @function Set theme for levels (predefined colors).
//
// #### Usage
// ___
// ```
// #region Theme for Histogram above 0
// var string GRP_THEME_HISTOGRAM_ABOVE = 'Theme for Histogram above 0'
// var int themeHistoP = input.int(defval=0, title='Theme',
// options=[0, 1, 2, 3, 4, 5, 6], inline='1', group='Theme for Histogram above 0', tooltip=THEME_TOOLTIP_HISTOGRAM)
// var colorHistogramUp_1 = input(color.new(#0064bb, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_2 = input(color.new(#007ce9, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_3 = input(color.new(#1893ff, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_4 = input(color.new(#46a9ff, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_5 = input(color.new(#75beff, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_6 = input(color.new(#91c9fa, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// // #endregion
//
// vcHistogram = UTIL.valueColorSpectrum.new()
// vcHistogram.currentValue := histogram
// vcHistogram.previousValue := histogram[1]
//
// UTIL.setCustomLevels(vcHistogram, 5, 10, 15, 20, 25)
//
// UTIL.setTheme(vcHistogram, themeHistoP)
// ```
// ___
// @param vc (valueColorSpectrum) Object to associate a color with a value, taking into account the previous value and its levels.
// @param theme (int) Theme (predefined colors).
// 10 to 15 → Spectrum Blue-Green-Red
// 20 to 21 → Monokai
// 30 to 31 → Spectrum White-Green-Red
// 40 to 41 → Green-Purple
// 50 to 51 → Blue-Red
// 60 to 61 → Blue-Yellow
// 70 to 71 → Green-Red
// 80 to 81 → Green
// 90 to 91 → Purple
// 100 to 107 → Blue
// 120 to 123 → Blue-Aqua
// 130 to 133 → Blue-Green
// 140 to 153 → Red
// 160 to 161 → Red-Yellow
// 170 to 171 → Red-White
// 180 to 185 → White-Black
// 190 to 200 → Spectrum Blue-Red
//
// @returns (void)
export setTheme(valueColorSpectrum vc, simple int theme) =>
vc.theme := theme
switch theme
// Spectrum Blue-Green-Red
10 =>
vc.colorLevel_Lv1 := #0000FF
vc.colorLevel_Lv1_Lv2 := #01b5cc
vc.colorLevel_Lv2_Lv3 := #3af13c
vc.colorLevel_Lv3_Lv4 := #ffeb3b
vc.colorLevel_Lv4_Lv5 := #ff6d00
vc.colorLevel_Lv5 := #ff0000
11 =>
vc.colorLevel_Lv1 := #ff0000
vc.colorLevel_Lv1_Lv2 := #ff6d00
vc.colorLevel_Lv2_Lv3 := #ffeb3b
vc.colorLevel_Lv3_Lv4 := #3af13c
vc.colorLevel_Lv4_Lv5 := #01b5cc
vc.colorLevel_Lv5 := #0000FF
12 =>
vc.colorLevel_Lv1 := #0028ff
vc.colorLevel_Lv1_Lv2 := #24fffe
vc.colorLevel_Lv2_Lv3 := #00ff00
vc.colorLevel_Lv3_Lv4 := #ffff00
vc.colorLevel_Lv4_Lv5 := #ff7f00
vc.colorLevel_Lv5 := #ff0000
13 =>
vc.colorLevel_Lv1 := #ff0000
vc.colorLevel_Lv1_Lv2 := #ff7f00
vc.colorLevel_Lv2_Lv3 := #ffff00
vc.colorLevel_Lv3_Lv4 := #00ff00
vc.colorLevel_Lv4_Lv5 := #24fffe
vc.colorLevel_Lv5 := #0028ff
14 =>
vc.colorLevel_Lv1 := #0036ff
vc.colorLevel_Lv1_Lv2 := #00bcd4
vc.colorLevel_Lv2_Lv3 := #1aa814
vc.colorLevel_Lv3_Lv4 := #f57f17
vc.colorLevel_Lv4_Lv5 := #dc1e5f
vc.colorLevel_Lv5 := #b800d8
15 =>
vc.colorLevel_Lv1 := #b800d8
vc.colorLevel_Lv1_Lv2 := #dc1e5f
vc.colorLevel_Lv2_Lv3 := #f57f17
vc.colorLevel_Lv3_Lv4 := #1aa814
vc.colorLevel_Lv4_Lv5 := #00bcd4
vc.colorLevel_Lv5 := #0036ff
// Monokai
20 =>
vc.colorLevel_Lv1 := #a6e22e
vc.colorLevel_Lv1_Lv2 := #00fff0
vc.colorLevel_Lv2_Lv3 := #8080ff
vc.colorLevel_Lv3_Lv4 := #e0e0e0
vc.colorLevel_Lv4_Lv5 := #f3ff6c
vc.colorLevel_Lv5 := #f54081
21 =>
vc.colorLevel_Lv1 := #f54081
vc.colorLevel_Lv1_Lv2 := #f3ff6c
vc.colorLevel_Lv2_Lv3 := #e0e0e0
vc.colorLevel_Lv3_Lv4 := #8080ff
vc.colorLevel_Lv4_Lv5 := #00fff0
vc.colorLevel_Lv5 := #a6e22e
// Spectrum White-Green-Red
30 =>
vc.colorLevel_Lv1 := #ffffff
vc.colorLevel_Lv1_Lv2 := #24fffe
vc.colorLevel_Lv2_Lv3 := #00ff00
vc.colorLevel_Lv3_Lv4 := #ffff00
vc.colorLevel_Lv4_Lv5 := #ff7f00
vc.colorLevel_Lv5 := #ff0000
31 =>
vc.colorLevel_Lv1 := #ff0000
vc.colorLevel_Lv1_Lv2 := #ff7f00
vc.colorLevel_Lv2_Lv3 := #ffff00
vc.colorLevel_Lv3_Lv4 := #00ff00
vc.colorLevel_Lv4_Lv5 := #24fffe
vc.colorLevel_Lv5 := #ffffff
// Green-Purple
40 =>
vc.colorLevel_Lv1 := #228B22
vc.colorLevel_Lv1_Lv2 := #3ACF3A
vc.colorLevel_Lv2_Lv3 := #6AE76A
vc.colorLevel_Lv3_Lv4 := #ca82f7
vc.colorLevel_Lv4_Lv5 := #b44df5
vc.colorLevel_Lv5 := #880ED4
41 =>
vc.colorLevel_Lv1 := #880ED4
vc.colorLevel_Lv1_Lv2 := #b44df5
vc.colorLevel_Lv2_Lv3 := #ca82f7
vc.colorLevel_Lv3_Lv4 := #6AE76A
vc.colorLevel_Lv4_Lv5 := #3ACF3A
vc.colorLevel_Lv5 := #228B22
// Blue-Red
50 =>
vc.colorLevel_Lv1 := #120ef6
vc.colorLevel_Lv1_Lv2 := #5086e1
vc.colorLevel_Lv2_Lv3 := #8ba8c9
vc.colorLevel_Lv3_Lv4 := #ddafae
vc.colorLevel_Lv4_Lv5 := #c97479
vc.colorLevel_Lv5 := #be1642
51 =>
vc.colorLevel_Lv1 := #be1642
vc.colorLevel_Lv1_Lv2 := #c97479
vc.colorLevel_Lv2_Lv3 := #ddafae
vc.colorLevel_Lv3_Lv4 := #8ba8c9
vc.colorLevel_Lv4_Lv5 := #5086e1
vc.colorLevel_Lv5 := #120ef6
// Blue-Yellow
60 =>
vc.colorLevel_Lv1 := #267af7
vc.colorLevel_Lv1_Lv2 := #6e9de6
vc.colorLevel_Lv2_Lv3 := #b1c6d8
vc.colorLevel_Lv3_Lv4 := #f7eca9
vc.colorLevel_Lv4_Lv5 := #f7e16b
vc.colorLevel_Lv5 := #f7d126
61 =>
vc.colorLevel_Lv1 := #f7d126
vc.colorLevel_Lv1_Lv2 := #f7e16b
vc.colorLevel_Lv2_Lv3 := #f7eca9
vc.colorLevel_Lv3_Lv4 := #b1c6d8
vc.colorLevel_Lv4_Lv5 := #6e9de6
vc.colorLevel_Lv5 := #267af7
// Green-Red
70 =>
vc.colorLevel_Lv1 := color.rgb(0, 255, 0)
vc.colorLevel_Lv1_Lv2 := color.rgb(51, 204, 0)
vc.colorLevel_Lv2_Lv3 := color.rgb(102, 153, 0)
vc.colorLevel_Lv3_Lv4 := color.rgb(153, 102, 0)
vc.colorLevel_Lv4_Lv5 := color.rgb(204, 51, 0)
vc.colorLevel_Lv5 := color.rgb(255, 0, 0)
71 =>
vc.colorLevel_Lv1 := color.rgb(255, 0, 0)
vc.colorLevel_Lv1_Lv2 := color.rgb(204, 51, 0)
vc.colorLevel_Lv2_Lv3 := color.rgb(153, 102, 0)
vc.colorLevel_Lv3_Lv4 := color.rgb(102, 153, 0)
vc.colorLevel_Lv4_Lv5 := color.rgb(51, 204, 0)
vc.colorLevel_Lv5 := color.rgb(0, 255, 0)
// Green
80 =>
vc.colorLevel_Lv1 := #228B22
vc.colorLevel_Lv1_Lv2 := #2BB02B
vc.colorLevel_Lv2_Lv3 := #3ACF3A
vc.colorLevel_Lv3_Lv4 := #5FD85F
vc.colorLevel_Lv4_Lv5 := #84E184
vc.colorLevel_Lv5 := #96f196
81 =>
vc.colorLevel_Lv1 := #96f196
vc.colorLevel_Lv1_Lv2 := #84E184
vc.colorLevel_Lv2_Lv3 := #5FD85F
vc.colorLevel_Lv3_Lv4 := #3ACF3A
vc.colorLevel_Lv4_Lv5 := #2BB02B
vc.colorLevel_Lv5 := #228B22
// Purple
90 =>
vc.colorLevel_Lv1 := #6C0BA9
vc.colorLevel_Lv1_Lv2 := #880ED4
vc.colorLevel_Lv2_Lv3 := #A020F0
vc.colorLevel_Lv3_Lv4 := #B24BF3
vc.colorLevel_Lv4_Lv5 := #cd90f3
vc.colorLevel_Lv5 := #d9b0f2
91 =>
vc.colorLevel_Lv1 := #d9b0f2
vc.colorLevel_Lv1_Lv2 := #cd90f3
vc.colorLevel_Lv2_Lv3 := #B24BF3
vc.colorLevel_Lv3_Lv4 := #A020F0
vc.colorLevel_Lv4_Lv5 := #880ED4
vc.colorLevel_Lv5 := #6C0BA9
// Blue
100 =>
vc.colorLevel_Lv1 := #0064bb
vc.colorLevel_Lv1_Lv2 := #007ce9
vc.colorLevel_Lv2_Lv3 := #1893ff
vc.colorLevel_Lv3_Lv4 := #46a9ff
vc.colorLevel_Lv4_Lv5 := #75beff
vc.colorLevel_Lv5 := #91c9fa
101 =>
vc.colorLevel_Lv1 := #91c9fa
vc.colorLevel_Lv1_Lv2 := #75beff
vc.colorLevel_Lv2_Lv3 := #46a9ff
vc.colorLevel_Lv3_Lv4 := #1893ff
vc.colorLevel_Lv4_Lv5 := #007ce9
vc.colorLevel_Lv5 := #0064bb
102 =>
vc.colorLevel_Lv1 := #1c3bfb
vc.colorLevel_Lv1_Lv2 := #2855fc
vc.colorLevel_Lv2_Lv3 := #346ffd
vc.colorLevel_Lv3_Lv4 := #4078fe
vc.colorLevel_Lv4_Lv5 := #5b9bf9
vc.colorLevel_Lv5 := #72b6fc
103 =>
vc.colorLevel_Lv1 := #72b6fc
vc.colorLevel_Lv1_Lv2 := #5b9bf9
vc.colorLevel_Lv2_Lv3 := #4078fe
vc.colorLevel_Lv3_Lv4 := #346ffd
vc.colorLevel_Lv4_Lv5 := #2855fc
vc.colorLevel_Lv5 := #1c3bfb
104 =>
vc.colorLevel_Lv1 := color.rgb(0, 0, 255)
vc.colorLevel_Lv1_Lv2 := color.rgb(30, 30, 255)
vc.colorLevel_Lv2_Lv3 := color.rgb(60, 60, 255)
vc.colorLevel_Lv3_Lv4 := color.rgb(90, 90, 255)
vc.colorLevel_Lv4_Lv5 := color.rgb(120, 120, 255)
vc.colorLevel_Lv5 := color.rgb(150, 150, 255)
105 =>
vc.colorLevel_Lv1 := color.rgb(150, 150, 255)
vc.colorLevel_Lv1_Lv2 := color.rgb(120, 120, 255)
vc.colorLevel_Lv2_Lv3 := color.rgb(90, 90, 255)
vc.colorLevel_Lv3_Lv4 := color.rgb(60, 60, 255)
vc.colorLevel_Lv4_Lv5 := color.rgb(30, 30, 255)
vc.colorLevel_Lv5 := color.rgb(0, 0, 255)
106 =>
vc.colorLevel_Lv1 := color.rgb(0, 0, 255)
vc.colorLevel_Lv1_Lv2 := color.rgb(51, 51, 255)
vc.colorLevel_Lv2_Lv3 := color.rgb(102, 102, 255)
vc.colorLevel_Lv3_Lv4 := color.rgb(153, 153, 255)
vc.colorLevel_Lv4_Lv5 := color.rgb(204, 204, 255)
vc.colorLevel_Lv5 := color.rgb(255, 255, 255)
107 =>
vc.colorLevel_Lv1 := color.rgb(255, 255, 255)
vc.colorLevel_Lv1_Lv2 := color.rgb(204, 204, 255)
vc.colorLevel_Lv2_Lv3 := color.rgb(153, 153, 255)
vc.colorLevel_Lv3_Lv4 := color.rgb(102, 102, 255)
vc.colorLevel_Lv4_Lv5 := color.rgb(51, 51, 255)
vc.colorLevel_Lv5 := color.rgb(0, 0, 255)
// Blue-Aqua
120 =>
vc.colorLevel_Lv1 := color.rgb(0, 0, 255)
vc.colorLevel_Lv1_Lv2 := color.rgb(12, 51, 255)
vc.colorLevel_Lv2_Lv3 := color.rgb(25, 102, 255)
vc.colorLevel_Lv3_Lv4 := color.rgb(38, 153, 255)
vc.colorLevel_Lv4_Lv5 := color.rgb(51, 204, 255)
vc.colorLevel_Lv5 := color.rgb(64, 255, 255)
121 =>
vc.colorLevel_Lv1 := color.rgb(64, 255, 255)
vc.colorLevel_Lv1_Lv2 := color.rgb(51, 204, 255)
vc.colorLevel_Lv2_Lv3 := color.rgb(38, 153, 255)
vc.colorLevel_Lv3_Lv4 := color.rgb(25, 102, 255)
vc.colorLevel_Lv4_Lv5 := color.rgb(12, 51, 255)
vc.colorLevel_Lv5 := color.rgb(0, 0, 255)
122 =>
vc.colorLevel_Lv1 := color.rgb(28, 59, 251)
vc.colorLevel_Lv1_Lv2 := color.rgb(40, 85, 252)
vc.colorLevel_Lv2_Lv3 := color.rgb(52, 111, 253)
vc.colorLevel_Lv3_Lv4 := color.rgb(58, 166, 250)
vc.colorLevel_Lv4_Lv5 := color.rgb(58, 198, 250)
vc.colorLevel_Lv5 := color.rgb(58, 231, 250)
123 =>
vc.colorLevel_Lv1 := color.rgb(58, 231, 250)
vc.colorLevel_Lv1_Lv2 := color.rgb(58, 198, 250)
vc.colorLevel_Lv2_Lv3 := color.rgb(58, 166, 250)
vc.colorLevel_Lv3_Lv4 := color.rgb(52, 111, 253)
vc.colorLevel_Lv4_Lv5 := color.rgb(40, 85, 252)
vc.colorLevel_Lv5 := color.rgb(28, 59, 251)
// Blue-Green
130 =>
vc.colorLevel_Lv1 := color.rgb(0, 255, 0)
vc.colorLevel_Lv1_Lv2 := color.rgb(0, 206, 209)
vc.colorLevel_Lv2_Lv3 := color.rgb(0, 191, 255)
vc.colorLevel_Lv3_Lv4 := color.rgb(30, 144, 255)
vc.colorLevel_Lv4_Lv5 := color.rgb(30, 89, 255)
vc.colorLevel_Lv5 := color.rgb(0, 0, 225)
131 =>
vc.colorLevel_Lv1 := color.rgb(0, 0, 225)
vc.colorLevel_Lv1_Lv2 := color.rgb(30, 89, 255)
vc.colorLevel_Lv2_Lv3 := color.rgb(30, 144, 255)
vc.colorLevel_Lv3_Lv4 := color.rgb(0, 191, 255)
vc.colorLevel_Lv4_Lv5 := color.rgb(0, 206, 209)
vc.colorLevel_Lv5 := color.rgb(0, 255, 0)
132 =>
vc.colorLevel_Lv1 := color.rgb(0, 255, 0)
vc.colorLevel_Lv1_Lv2 := color.rgb(127, 255, 212)
vc.colorLevel_Lv2_Lv3 := color.rgb(175, 238, 238)
vc.colorLevel_Lv3_Lv4 := color.rgb(0, 191, 255)
vc.colorLevel_Lv4_Lv5 := color.rgb(30, 144, 255)
vc.colorLevel_Lv5 := color.rgb(0, 55, 225)
133 =>
vc.colorLevel_Lv1 := color.rgb(0, 55, 225)
vc.colorLevel_Lv1_Lv2 := color.rgb(30, 144, 255)
vc.colorLevel_Lv2_Lv3 := color.rgb(0, 191, 255)
vc.colorLevel_Lv3_Lv4 := color.rgb(175, 238, 238)
vc.colorLevel_Lv4_Lv5 := color.rgb(127, 255, 212)
vc.colorLevel_Lv5 := color.rgb(0, 255, 0)
134 =>
vc.colorLevel_Lv1 := color.rgb(0, 186, 8)
vc.colorLevel_Lv1_Lv2 := color.rgb(124, 226, 132)
vc.colorLevel_Lv2_Lv3 := color.rgb(124, 222, 222)
vc.colorLevel_Lv3_Lv4 := color.rgb(0, 191, 255)
vc.colorLevel_Lv4_Lv5 := color.rgb(30, 144, 255)
vc.colorLevel_Lv5 := color.rgb(41, 98, 255)
135 =>
vc.colorLevel_Lv1 := color.rgb(41, 98, 255)
vc.colorLevel_Lv1_Lv2 := color.rgb(30, 144, 255)
vc.colorLevel_Lv2_Lv3 := color.rgb(0, 191, 255)
vc.colorLevel_Lv3_Lv4 := color.rgb(124, 222, 222)
vc.colorLevel_Lv4_Lv5 := color.rgb(124, 226, 132)
vc.colorLevel_Lv5 := color.rgb(0, 186, 8)
136 =>
vc.colorLevel_Lv1 := #00ba08
vc.colorLevel_Lv1_Lv2 := #14e024
vc.colorLevel_Lv2_Lv3 := #7dff5b
vc.colorLevel_Lv3_Lv4 := #00bcd4
vc.colorLevel_Lv4_Lv5 := #2962ff
vc.colorLevel_Lv5 := #0044ff
137 =>
vc.colorLevel_Lv1 := #0044ff
vc.colorLevel_Lv1_Lv2 := #2962ff
vc.colorLevel_Lv2_Lv3 := #00bcd4
vc.colorLevel_Lv3_Lv4 := #7dff5b
vc.colorLevel_Lv4_Lv5 := #14e024
vc.colorLevel_Lv5 := #00ba08
// Red
140 =>
vc.colorLevel_Lv1 := #8e1031
vc.colorLevel_Lv1_Lv2 := #be1642
vc.colorLevel_Lv2_Lv3 := #e62356
vc.colorLevel_Lv3_Lv4 := #eb527a
vc.colorLevel_Lv4_Lv5 := #f1829f
vc.colorLevel_Lv5 := #f395ae
141 =>
vc.colorLevel_Lv1 := #f395ae
vc.colorLevel_Lv1_Lv2 := #f1829f
vc.colorLevel_Lv2_Lv3 := #eb527a
vc.colorLevel_Lv3_Lv4 := #e62356
vc.colorLevel_Lv4_Lv5 := #be1642
vc.colorLevel_Lv5 := #8e1031
142 =>
vc.colorLevel_Lv1 := color.rgb(255, 0, 0)
vc.colorLevel_Lv1_Lv2 := color.rgb(255, 30, 30)
vc.colorLevel_Lv2_Lv3 := color.rgb(255, 60, 60)
vc.colorLevel_Lv3_Lv4 := color.rgb(255, 90, 90)
vc.colorLevel_Lv4_Lv5 := color.rgb(255, 120, 120)
vc.colorLevel_Lv5 := color.rgb(255, 150, 150)
143 =>
vc.colorLevel_Lv1 := color.rgb(255, 150, 150)
vc.colorLevel_Lv1_Lv2 := color.rgb(255, 120, 120)
vc.colorLevel_Lv2_Lv3 := color.rgb(255, 90, 90)
vc.colorLevel_Lv3_Lv4 := color.rgb(255, 60, 60)
vc.colorLevel_Lv4_Lv5 := color.rgb(255, 30, 30)
vc.colorLevel_Lv5 := color.rgb(255, 0, 0)
144 =>
vc.colorLevel_Lv1 := color.rgb(255, 0, 0)
vc.colorLevel_Lv1_Lv2 := color.rgb(255, 50, 50)
vc.colorLevel_Lv2_Lv3 := color.rgb(255, 100, 100)
vc.colorLevel_Lv3_Lv4 := color.rgb(255, 150, 150)
vc.colorLevel_Lv4_Lv5 := color.rgb(255, 180, 180)
vc.colorLevel_Lv5 := color.rgb(255, 200, 200)
145 =>
vc.colorLevel_Lv1 := color.rgb(255, 200, 200)
vc.colorLevel_Lv1_Lv2 := color.rgb(255, 180, 180)
vc.colorLevel_Lv2_Lv3 := color.rgb(255, 150, 150)
vc.colorLevel_Lv3_Lv4 := color.rgb(255, 100, 100)
vc.colorLevel_Lv4_Lv5 := color.rgb(255, 50, 50)
vc.colorLevel_Lv5 := color.rgb(255, 0, 0)
146 =>
vc.colorLevel_Lv1 := color.rgb(200, 0, 0)
vc.colorLevel_Lv1_Lv2 := color.rgb(218, 28, 28)
vc.colorLevel_Lv2_Lv3 := color.rgb(236, 56, 56)
vc.colorLevel_Lv3_Lv4 := color.rgb(244, 84, 84)
vc.colorLevel_Lv4_Lv5 := color.rgb(251, 107, 107)
vc.colorLevel_Lv5 := color.rgb(255, 130, 130)
147 =>
vc.colorLevel_Lv1 := color.rgb(255, 130, 130)
vc.colorLevel_Lv1_Lv2 := color.rgb(251, 107, 107)
vc.colorLevel_Lv2_Lv3 := color.rgb(244, 84, 84)
vc.colorLevel_Lv3_Lv4 := color.rgb(236, 56, 56)
vc.colorLevel_Lv4_Lv5 := color.rgb(218, 28, 28)
vc.colorLevel_Lv5 := color.rgb(200, 0, 0)
148 =>
vc.colorLevel_Lv1 := color.rgb(220, 20, 60)
vc.colorLevel_Lv1_Lv2 := color.rgb(230, 50, 80)
vc.colorLevel_Lv2_Lv3 := color.rgb(240, 80, 100)
vc.colorLevel_Lv3_Lv4 := color.rgb(250, 105, 130)
vc.colorLevel_Lv4_Lv5 := color.rgb(255, 105, 155)
vc.colorLevel_Lv5 := color.rgb(255, 105, 180)
149 =>
vc.colorLevel_Lv1 := color.rgb(255, 105, 180)
vc.colorLevel_Lv1_Lv2 := color.rgb(255, 105, 155)
vc.colorLevel_Lv2_Lv3 := color.rgb(250, 105, 130)
vc.colorLevel_Lv3_Lv4 := color.rgb(240, 80, 100)
vc.colorLevel_Lv4_Lv5 := color.rgb(230, 50, 80)
vc.colorLevel_Lv5 := color.rgb(220, 20, 60)
150 =>
vc.colorLevel_Lv1 := color.rgb(165, 0, 0)
vc.colorLevel_Lv1_Lv2 := color.rgb(200, 0, 0)
vc.colorLevel_Lv2_Lv3 := color.rgb(225, 30, 30)
vc.colorLevel_Lv3_Lv4 := color.rgb(240, 60, 60)
vc.colorLevel_Lv4_Lv5 := color.rgb(250, 70, 70)
vc.colorLevel_Lv5 := color.rgb(255, 80, 80)
151 =>
vc.colorLevel_Lv1 := color.rgb(255, 80, 80)
vc.colorLevel_Lv1_Lv2 := color.rgb(250, 70, 70)
vc.colorLevel_Lv2_Lv3 := color.rgb(240, 60, 60)
vc.colorLevel_Lv3_Lv4 := color.rgb(225, 30, 30)
vc.colorLevel_Lv4_Lv5 := color.rgb(200, 0, 0)
vc.colorLevel_Lv5 := color.rgb(165, 0, 0)
152 =>
vc.colorLevel_Lv1 := color.rgb(178, 34, 34)
vc.colorLevel_Lv1_Lv2 := color.rgb(200, 50, 50)
vc.colorLevel_Lv2_Lv3 := color.rgb(220, 75, 75)
vc.colorLevel_Lv3_Lv4 := color.rgb(240, 105, 105)
vc.colorLevel_Lv4_Lv5 := color.rgb(250, 130, 130)
vc.colorLevel_Lv5 := color.rgb(255, 160, 122)
153 =>
vc.colorLevel_Lv1 := color.rgb(255, 160, 122)
vc.colorLevel_Lv1_Lv2 := color.rgb(250, 130, 130)
vc.colorLevel_Lv2_Lv3 := color.rgb(240, 105, 105)
vc.colorLevel_Lv3_Lv4 := color.rgb(220, 75, 75)
vc.colorLevel_Lv4_Lv5 := color.rgb(200, 50, 50)
vc.colorLevel_Lv5 := color.rgb(178, 34, 34)
// Red-Yellow
160 =>
vc.colorLevel_Lv1 := color.rgb(255, 255, 102)
vc.colorLevel_Lv1_Lv2 := color.rgb(255, 204, 51)
vc.colorLevel_Lv2_Lv3 := color.rgb(255, 153, 0)
vc.colorLevel_Lv3_Lv4 := color.rgb(255, 102, 0)
vc.colorLevel_Lv4_Lv5 := color.rgb(255, 51, 0)
vc.colorLevel_Lv5 := color.rgb(204, 0, 0)
161 =>
vc.colorLevel_Lv1 := color.rgb(204, 0, 0)
vc.colorLevel_Lv1_Lv2 := color.rgb(255, 51, 0)
vc.colorLevel_Lv2_Lv3 := color.rgb(255, 102, 0)
vc.colorLevel_Lv3_Lv4 := color.rgb(255, 153, 0)
vc.colorLevel_Lv4_Lv5 := color.rgb(255, 204, 51)
vc.colorLevel_Lv5 := color.rgb(255, 255, 102)
162 =>
vc.colorLevel_Lv1 := color.rgb(182, 0, 0)
vc.colorLevel_Lv1_Lv2 := color.rgb(255, 0, 0)
vc.colorLevel_Lv2_Lv3 := color.rgb(242, 54, 69)
vc.colorLevel_Lv3_Lv4 := color.rgb(255, 90, 0)
vc.colorLevel_Lv4_Lv5 := color.rgb(255, 152, 0)
vc.colorLevel_Lv5 := color.rgb(255, 235, 59)
163 =>
vc.colorLevel_Lv1 := color.rgb(255, 235, 59)
vc.colorLevel_Lv1_Lv2 := color.rgb(255, 152, 0)
vc.colorLevel_Lv2_Lv3 := color.rgb(255, 90, 0)
vc.colorLevel_Lv3_Lv4 := color.rgb(242, 54, 69)
vc.colorLevel_Lv4_Lv5 := color.rgb(255, 0, 0)
vc.colorLevel_Lv5 := color.rgb(182, 0, 0)
164 =>
vc.colorLevel_Lv1 := #fbc02d
vc.colorLevel_Lv1_Lv2 := #ff9800
vc.colorLevel_Lv2_Lv3 := #e65100
vc.colorLevel_Lv3_Lv4 := #f23645
vc.colorLevel_Lv4_Lv5 := #ff0000
vc.colorLevel_Lv5 := #bf0000
165 =>
vc.colorLevel_Lv1 := #bf0000
vc.colorLevel_Lv1_Lv2 := #ff0000
vc.colorLevel_Lv2_Lv3 := #f23645
vc.colorLevel_Lv3_Lv4 := #e65100
vc.colorLevel_Lv4_Lv5 := #ff9800
vc.colorLevel_Lv5 := #fbc02d
// Red-White
170 =>
vc.colorLevel_Lv1 := color.rgb(255, 255, 255)
vc.colorLevel_Lv1_Lv2 := color.rgb(255, 153, 153)
vc.colorLevel_Lv2_Lv3 := color.rgb(255, 102, 102)
vc.colorLevel_Lv3_Lv4 := color.rgb(255, 51, 51)
vc.colorLevel_Lv4_Lv5 := color.rgb(204, 0, 0)
vc.colorLevel_Lv5 := color.rgb(153, 0, 0)
171 =>
vc.colorLevel_Lv1 := color.rgb(153, 0, 0)
vc.colorLevel_Lv1_Lv2 := color.rgb(204, 0, 0)
vc.colorLevel_Lv2_Lv3 := color.rgb(255, 51, 51)
vc.colorLevel_Lv3_Lv4 := color.rgb(255, 102, 102)
vc.colorLevel_Lv4_Lv5 := color.rgb(255, 153, 153)
vc.colorLevel_Lv5 := color.rgb(255, 255, 255)
// White-Black
180 =>
vc.colorLevel_Lv1 := color.rgb(255, 255, 255)
vc.colorLevel_Lv1_Lv2 := color.rgb(240, 240, 240)
vc.colorLevel_Lv2_Lv3 := color.rgb(221, 221, 221)
vc.colorLevel_Lv3_Lv4 := color.rgb(204, 204, 204)
vc.colorLevel_Lv4_Lv5 := color.rgb(187, 187, 187)
vc.colorLevel_Lv5 := color.rgb(170, 170, 170)
181 =>
vc.colorLevel_Lv1 := color.rgb(170, 170, 170)
vc.colorLevel_Lv1_Lv2 := color.rgb(187, 187, 187)
vc.colorLevel_Lv2_Lv3 := color.rgb(204, 204, 204)
vc.colorLevel_Lv3_Lv4 := color.rgb(221, 221, 221)
vc.colorLevel_Lv4_Lv5 := color.rgb(240, 240, 240)
vc.colorLevel_Lv5 := color.rgb(255, 255, 255)
182 =>
vc.colorLevel_Lv1 := color.rgb(255, 255, 255)
vc.colorLevel_Lv1_Lv2 := color.rgb(214, 214, 214)
vc.colorLevel_Lv2_Lv3 := color.rgb(153, 153, 153)
vc.colorLevel_Lv3_Lv4 := color.rgb(125, 125, 125)
vc.colorLevel_Lv4_Lv5 := color.rgb(100, 100, 100)
vc.colorLevel_Lv5 := color.rgb(75, 75, 75)
183 =>
vc.colorLevel_Lv1 := color.rgb(75, 75, 75)
vc.colorLevel_Lv1_Lv2 := color.rgb(100, 100, 100)
vc.colorLevel_Lv2_Lv3 := color.rgb(125, 125, 125)
vc.colorLevel_Lv3_Lv4 := color.rgb(153, 153, 153)
vc.colorLevel_Lv4_Lv5 := color.rgb(214, 214, 214)
vc.colorLevel_Lv5 := color.rgb(255, 255, 255)
184 =>
vc.colorLevel_Lv1 := color.rgb(30, 30, 30)
vc.colorLevel_Lv1_Lv2 := color.rgb(48, 48, 48)
vc.colorLevel_Lv2_Lv3 := color.rgb(68, 68, 68)
vc.colorLevel_Lv3_Lv4 := color.rgb(92, 92, 92)
vc.colorLevel_Lv4_Lv5 := color.rgb(115, 115, 115)
vc.colorLevel_Lv5 := color.rgb(128, 128, 128)
185 =>
vc.colorLevel_Lv1 := color.rgb(128, 128, 128)
vc.colorLevel_Lv1_Lv2 := color.rgb(115, 115, 115)
vc.colorLevel_Lv2_Lv3 := color.rgb(92, 92, 92)
vc.colorLevel_Lv3_Lv4 := color.rgb(68, 68, 68)
vc.colorLevel_Lv4_Lv5 := color.rgb(48, 48, 48)
vc.colorLevel_Lv5 := color.rgb(30, 30, 30)
// Spectrum Blue-Red
190 =>
vc.colorLevel_Lv1 := color.rgb(0, 0, 255)
vc.colorLevel_Lv1_Lv2 := color.rgb(51, 0, 204)
vc.colorLevel_Lv2_Lv3 := color.rgb(102, 0, 153)
vc.colorLevel_Lv3_Lv4 := color.rgb(153, 0, 102)
vc.colorLevel_Lv4_Lv5 := color.rgb(204, 0, 51)
vc.colorLevel_Lv5 := color.rgb(255, 0, 0)
191 =>
vc.colorLevel_Lv1 := color.rgb(255, 0, 0)
vc.colorLevel_Lv1_Lv2 := color.rgb(204, 0, 51)
vc.colorLevel_Lv2_Lv3 := color.rgb(153, 0, 102)
vc.colorLevel_Lv3_Lv4 := color.rgb(102, 0, 153)
vc.colorLevel_Lv4_Lv5 := color.rgb(51, 0, 204)
vc.colorLevel_Lv5 := color.rgb(0, 0, 255)
// @function Set theme for levels (customized colors).
//
// #### Usage
// ___
// ```
// #region Theme for Histogram above 0
// var string GRP_THEME_HISTOGRAM_ABOVE = 'Theme for Histogram above 0'
// var colorHistogramUp_1 = input(color.new(#0064bb, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_2 = input(color.new(#007ce9, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_3 = input(color.new(#1893ff, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_4 = input(color.new(#46a9ff, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_5 = input(color.new(#75beff, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_6 = input(color.new(#91c9fa, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// // #endregion
//
// vcHistogram = UTIL.valueColorSpectrum.new()
//
// vcHistogram.currentValue := histogram
// vcHistogram.previousValue := histogram[1]
//
// UTIL.setCustomLevels(vcHistogram, 5, 10, 15, 20, 25)
//
// UTIL.setTheme(vcHistogram, colorHistogramUp_1, colorHistogramUp_2, colorHistogramUp_3, colorHistogramUp_4, colorHistogramUp_5, colorHistogramUp_6)
// ```
// ___
// @param vc (valueColorSpectrum) Object to associate a color with a value, taking into account the previous value and its levels
// @param colorLevel_Lv1 (color) Color associeted with value when below Level 1.
// @param colorLevel_Lv1_Lv2 (color) Color associeted with value when between Level 1 and 2.
// @param colorLevel_Lv2_Lv3 (color) Color associeted with value when between Level 2 and 3.
// @param colorLevel_Lv3_Lv4 (color) Color associeted with value when between Level 3 and 4.
// @param colorLevel_Lv4_Lv5 (color) Color associeted with value when between Level 4 and 5.
// @param colorLevel_Lv5 (color) Color associeted with value when above Level 5.
// @returns (void)
export setTheme(valueColorSpectrum vc, simple color colorLevel_Lv1, simple color colorLevel_Lv1_Lv2,
simple color colorLevel_Lv2_Lv3, simple color colorLevel_Lv3_Lv4, simple color colorLevel_Lv4_Lv5,
simple color colorLevel_Lv5) =>
vc.theme := 0
vc.colorLevel_Lv1 := colorLevel_Lv1
vc.colorLevel_Lv1_Lv2 := colorLevel_Lv1_Lv2
vc.colorLevel_Lv2_Lv3 := colorLevel_Lv2_Lv3
vc.colorLevel_Lv3_Lv4 := colorLevel_Lv3_Lv4
vc.colorLevel_Lv4_Lv5 := colorLevel_Lv4_Lv5
vc.colorLevel_Lv5 := colorLevel_Lv5
// @function Set color to a current value, taking into account the previous value and its levels
//
// #### Usage
// ___
// ```
// vcHistogram = UTIL.valueColorSpectrum.new()
// vcHistogram.currentValue := histogram
// vcHistogram.previousValue := histogram[1]
// UTIL.setCustomLevels(vcHistogram, 5, 10, 15, 20, 25)
// if histogram >= 0
// UTIL.setTheme(vcHistogram, themeHistoP)
// if themeHistoP == 0
// UTIL.setTheme(vcHistogram, colorHistogramUp_1, colorHistogramUp_2, colorHistogramUp_3, colorHistogramUp_4, colorHistogramUp_5, colorHistogramUp_6)
// else
// UTIL.setTheme(vcHistogram, themeHistoN)
// if themeHistoN == 0
// UTIL.setTheme(vcHistogram, colorHistogramDown_1, colorHistogramDown_2, colorHistogramDown_3, colorHistogramDown_4, colorHistogramDown_5, colorHistogramDown_6)
// UTIL.setCurrentColorValue(vcHistogram)
// color colorHistogram = vcHistogram.currentColorValue
// ```
// ___
// @param vc (valueColorSpectrum) Object to associate a color with a value, taking into account the previous value and its levels
// @returns (void)
export setCurrentColorValue(valueColorSpectrum vc) =>
currentValue = math.abs(vc.currentValue)
previousValue = math.abs(vc.previousValue)
vc.currentColorValue := switch
(currentValue <= vc.level1) or (previousValue <= vc.level1) => vc.colorLevel_Lv1
(currentValue > vc.level1 and currentValue <= vc.level2) or (previousValue > vc.level1 and previousValue <= vc.level2) => color.from_gradient(currentValue, vc.level1, vc.level2, vc.colorLevel_Lv1, vc.colorLevel_Lv1_Lv2)
(currentValue > vc.level2 and currentValue <= vc.level3) or (previousValue > vc.level2 and previousValue <= vc.level3) => color.from_gradient(currentValue, vc.level2, vc.level3, vc.colorLevel_Lv1_Lv2, vc.colorLevel_Lv2_Lv3)
(currentValue > vc.level3 and currentValue <= vc.level4) or (previousValue > vc.level3 and previousValue <= vc.level4) => color.from_gradient(currentValue, vc.level3, vc.level4, vc.colorLevel_Lv2_Lv3, vc.colorLevel_Lv3_Lv4)
(currentValue > vc.level4 and currentValue <= vc.level5) or (previousValue > vc.level4 and previousValue <= vc.level5) => color.from_gradient(currentValue, vc.level4, vc.level5, vc.colorLevel_Lv3_Lv4, vc.colorLevel_Lv4_Lv5)
(currentValue > vc.level5) or (previousValue > vc.level5) => vc.colorLevel_Lv5
// @function Set boundaries for custom levels.
// @param vc (valueColorSpectrum) Object to associate a color with a value, taking into account the previous value and its levels
// @param level1 (float) Boundary for level 1
// @param level2 (float) Boundary for level 2
// @param level3 (float) Boundary for level 3
// @param level4 (float) Boundary for level 4
// @param level5 (float) Boundary for level 5
// @returns (void)
export setCustomLevels(valueColorSpectrum vc,
simple float level1 = 10,
simple float level2 = 30,
simple float level3 = 50,
simple float level4 = 70,
simple float level5 = 90) =>
vc.level1 := level1
vc.level2 := level2
vc.level3 := level3
vc.level4 := level4
vc.level5 := level5
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region valueColor: Simple theme for a Oscillator (2 colors)
// @type # Object to associate a color with a value, taking into account the previous value
// ## Stores a color theme, which is used according if value is greater or lesser than previous value
// @field (float) currentValue Current value.
// @field (float) previousValue Previous value.
// @field (color) currentColorValue Color associeted with current value. This value must be calculated with setCurrentColorValue method.
// @field (color) colorUp Color associeted with value when below Level 1.
// @field (color) colorDown Color associeted with value when between Level 1 and 2.
export type valueColor
// Values
float currentValue
float previousValue
// Colors
color currentColorValue
color colorUp = #2962ff
color colorDown = #ff1000
// @function Set color to a current value, taking into account the previous value.
// @param vc (valueColor) Object to associate a color with a value, taking into account the previous value
// @returns (void)
export setCurrentColorValue(valueColor vc, bool gradient) =>
vc.currentColorValue := if gradient
color.from_gradient( vc.currentValue > vc.previousValue ? vc.currentValue : vc.previousValue, 0, 100, vc.colorDown, vc.colorUp )
else
(vc.currentValue >= vc.previousValue) ? vc.colorUp : vc.colorDown
// @function Set color to a current value, taking into account the previous value.
// @param vc (valueColor) Object to associate a color with a value, taking into account the previous value.
// @param bottom_value (float) Bottom position value corresponding to bottom_color.
// @param top_value (float) Top position value corresponding to top_color.
// @returns (void)
export setCurrentColorValue(valueColor vc, bool gradient, float bottom_value, float top_value) =>
vc.currentColorValue := if gradient
color.from_gradient( vc.currentValue > vc.previousValue ? vc.currentValue : vc.previousValue, bottom_value, top_value, vc.colorDown, vc.colorUp )
else
(vc.currentValue >= vc.previousValue) ? vc.colorUp : vc.colorDown
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region Periodic Color
// @function Returns a periodic color. Useful for creating dotted lines for example.
// @param originalColor (color) Original color.
// @param density (float) Density of color. Expression used in modulo to obtain the integer remainder.
// If the remainder equals zero, the color appears, otherwise it remains hidden.
// @returns (color) Periodic color.
export getPeriodicColor(simple color originalColor, simple float density) =>
newColor = (bar_index % density == 0) ? originalColor : na
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region Math
// @function Round a value between .999 and -.999. Function used in Fisher Transform.
// @param value (float) Value to be rounded.
// @returns (float) Value rounded.
export round(float value) =>
value > .99 ? .999 : value < -.99 ? -.999 : value
// TODO: place this function in Volatility Indicators
// @function Get Dynamic Zones
// @param source (float) Source
// @param sampleLength (int) Sample Length
// @param pcntAbove (float) Calculates the top of the dynamic zone, considering that the maximum values are above x% of the sample
// @param pcntBelow (float) Calculates the bottom of the dynamic zone, considering that the minimum values are below x% of the sample
// @returns [float, float, float] A tuple with 3 series of values: (1) Upper Line of Dynamic Zone;
// (2) Lower Line of Dynamic Zone; (3) Center of Dynamic Zone (x = 50%)
export dinamicZone(float source, simple int sampleLength, simple float pcntAbove, simple float pcntBelow) =>
dZoneAbove = ta.percentile_nearest_rank(source, sampleLength, pcntAbove)
dZoneBelow = ta.percentile_nearest_rank(source, sampleLength, 100 - pcntBelow)
dZoneCenter = ta.percentile_nearest_rank(source, sampleLength, 100 - 50)
[dZoneAbove, dZoneBelow, dZoneCenter]
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// Sample code for using themes in a histogram
// // #region Theme for Histogram above 0
// var string GRP_THEME_HISTOGRAM_ABOVE = 'Theme for Histogram above 0'
// var int themeHistoP = input.int(defval=0, title='Theme',
// options=[0, 1, 2, 3, 4, 5, 6], inline='1', group='Theme for Histogram above 0', tooltip=THEME_TOOLTIP_HISTOGRAM)
// var colorHistogramUp_1 = input(color.new(#0064bb, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_2 = input(color.new(#007ce9, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_3 = input(color.new(#1893ff, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_4 = input(color.new(#46a9ff, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_5 = input(color.new(#75beff, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// var colorHistogramUp_6 = input(color.new(#91c9fa, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_ABOVE)
// // #endregion
// // #region Theme for Histogram below 0
// var string GRP_THEME_HISTOGRAM_BELOW = 'Theme for Histogram below 0'
// var int themeHistoN = input.int(defval=0, title='Theme',
// options=[0, 1, 2, 3, 4, 5, 6], inline='1', group='Theme for Histogram below 0')
// var colorHistogramDown_1 = input(color.new(#8e1031, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_BELOW)
// var colorHistogramDown_2 = input(color.new(#be1642, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_BELOW)
// var colorHistogramDown_3 = input(color.new(#e62356, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_BELOW)
// var colorHistogramDown_4 = input(color.new(#eb527a, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_BELOW)
// var colorHistogramDown_5 = input(color.new(#f1829f, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_BELOW)
// var colorHistogramDown_6 = input(color.new(#f395ae, 0), "", inline="2", group=GRP_THEME_HISTOGRAM_BELOW)
// // #endregion
// // ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// // #region Theme for Histogram
// vcHistogram = UTIL.valueColorSpectrum.new()
// vcHistogram.currentValue := histogram
// vcHistogram.previousValue := histogram[1]
// UTIL.setCustomLevels(vcHistogram, 5, 10, 15, 20, 25)
// if histogram >= 0
// UTIL.setTheme(vcHistogram, themeHistoP)
// if themeHistoP == 0
// UTIL.setTheme(vcHistogram, colorHistogramUp_1, colorHistogramUp_2, colorHistogramUp_3, colorHistogramUp_4, colorHistogramUp_5, colorHistogramUp_6)
// else
// UTIL.setTheme(vcHistogram, themeHistoN)
// if themeHistoN == 0
// UTIL.setTheme(vcHistogram, colorHistogramDown_1, colorHistogramDown_2, colorHistogramDown_3, colorHistogramDown_4, colorHistogramDown_5, colorHistogramDown_6)
// UTIL.setCurrentColorValue(vcHistogram)
// color colorHistogram = vcHistogram.currentColorValue
// // #endregion
// // ———————————————————————————————————————————————————————————————————————————————————————————————————————————— } |
AdxLib | https://www.tradingview.com/script/GoJqdYTb-adxlib/ | Hamster-Coder | https://www.tradingview.com/u/Hamster-Coder/ | 0 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Hamster-Coder
//@version=5
// @description TODO: add library description here
library("AdxLib", overlay = true)
dirmov(simple int length) =>
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
truerange = ta.rma(ta.tr, length)
plus = fixnan(100 * ta.rma(plusDM, length) / truerange)
minus = fixnan(100 * ta.rma(minusDM, length) / truerange)
[plus, minus]
export create(simple int di_length, simple int adx_length) =>
[plus, minus] = dirmov(di_length)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adx_length)
export create(simple int adx_length) =>
create(adx_length, adx_length) |
WIPTensor | https://www.tradingview.com/script/15n1qC2J-WIPTensor/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 26 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description A Tensor or 3 dimensional array structure and interface.
// ---
// Note: im just highjacking the name to use it as a 3d array on a project..
// there is no optimization attempts or tensor specific functionality within.
library("WIPTensor")
// reference:
// https://en.wikipedia.org/wiki/Tensor
//#region -> Types:
// @type Helper type for 3d structure.
// @field v Vector of the 3rd dimension.
export type Vector
array<float> v
// @type A Tensor is a three dimensional array were the 3rd dimension accounts for time.
// @field m Matrix that holds the vectors.
export type Tensor
matrix<Vector> m
//#endregion
//#region -> Translation:
// to_string () {
// @function Convert `Tensor` to a string format.
// @param this Tensor data.
// @returns string.
export method to_string (Tensor this) =>
string _str = ''
for _x = 0 to this.m.rows() - 1
for _y = 0 to this.m.columns() - 1
_str += str.format('\n({0}, {1}): {2}', _x, _y, str.tostring(this.m.get(_x, _y).v))
_str
// string inTensor = input.text_area('1,2;3,4|5,6;7,8')
// if barstate.islast
// _T = from(inTensor)
// label.new(bar_index, 0.0, _T.to_string())
// }
// to_vector () {
// @function Convert `Tensor` to a one dimension array.
// @param this Tensor data.
// @returns New array with flattened `Tensor` data.
export method to_vector (Tensor this) =>
array<float> _v = array.new<float>()
for _x = 0 to this.m.rows() - 1
for _y = 0 to this.m.columns() - 1
_v.concat(this.m.get(_x, _y).v)
_v
// }
//#endregion
//#region -> Constructor:
// new () {
// @function Create a new `Tensor` with provided shape.
// @param x Dimension `X` size.
// @param y Dimension `Y` size.
// @param z Dimension `Z` size.
// @param initial_value Value to fill the `Tensor`.
// @returns New `Tensor`.
export new (int x, int y, int z, float initial_value=na) =>
Tensor _T = Tensor.new(matrix.new<Vector>(x, y))
for _i = 0 to x-1
for _j = 0 to y-1
_T.m.set(_i, _j, Vector.new(array.new<float>(z, initial_value)))
_T
// @function Create a new `Tensor` with provided shape.
// @param shape Shape of dimensions size.
// @param initial_value Value to fill the `Tensor`.
// @returns New `Tensor`.
export new (array<int> shape, float initial_value=na) =>
new(array.get(shape, 0), array.get(shape, 1), array.get(shape, 2), initial_value)
// if barstate.islast
// _T = new(2, 2, 2, 1.1)
// label.new(bar_index, 0.0, str.tostring(_T.m.get(0,0).v.get(0)))
// }
// from () {
// @function Create a `Tensor` from provided string expression.
// @param expression String expression with `Tensor` data.
// @param sepx Default='|', Separator of the `X` dimension.
// @param sepy Default=';', Separator of the `Y` dimension.
// @param sepz Default=',', Separator of the `Z` dimension.
// @returns New `Tensor`.
export from (string expression, string sepx = '|', string sepy=';', string sepz=',') =>
array<string> _D1 = str.split(str.replace_all(expression, ' ', ''), sepx)
int _x = _D1.size()
if _x > 0
array<string> _D2 = str.split(_D1.get(0), sepy)
int _y = _D2.size()
if _y > 0
array<string> _D3 = str.split(_D2.get(0), sepz)
int _z = _D3.size()
if _z > 0
_T = new(_x, _y, _z)
for _xi = 0 to _x - 1
_D2 := str.split(_D1.get(_xi), sepy)
for _yi = 0 to _y - 1
_D3 := str.split(_D2.get(_yi), sepz)
_current_z = _T.m.get(_xi, _yi)
for _zi = 0 to _z - 1
_current_z.v.set(_zi, str.tonumber(_D3.get(_zi)))
_T
// string inTensor = input.text_area('1,2;3,4|5,6;7,8')
// int ix = input.int(0)
// int iy = input.int(0)
// int iz = input.int(0)
// if barstate.islast
// _T = from(inTensor)
// label.new(bar_index, 0.0, str.tostring(_T.m.get(ix,iy).v.get(iz)))
// @function Create a `Tensor` from provided array and shape.
// @param vector Data with flattened dimensions.
// @param x Shape of `X` dimension.
// @param y Shape of `Y` dimension.
// @param z Shape of `Z` dimension.
// @returns New `Tensor`.
export from (array<float> vector, int x, int y, int z) =>
Tensor _T = new(x, y, z)
int _c = 0
for _xi = 0 to x - 1
for _yi = 0 to y - 1
for _zi = 0 to z - 1
_T.m.get(_xi, _yi).v.set(_zi, vector.get(_c))
_c += 1
_T
// if barstate.islast
// _T = from(array.from(1.0,2,3,4,5,6,7,8,9,10,11,12), 2, 3, 2)
// label.new(bar_index, 0.0, to_string(_T))
// @function Create a `Tensor` from provided array and shape.
// @param vector Data with flattened dimensions.
// @param shape Shape of the dimensions.
// @returns New `Tensor`.
export from (array<float> vector, array<int> shape) =>
from(vector, array.get(shape, 0), array.get(shape, 1), array.get(shape, 2))
// }
//#endregion
//#region -> Properties:
// get () {
// @function Get the value at position.
// @param this `Tensor` data.
// @param x Position in `X` dimension.
// @param y Position in `Y` dimension.
// @param z Position in `Z` dimension.
// @returns Value at position.
export method get (Tensor this, int x, int y, int z) =>
this.m.get(x, y).v.get(z)
// @function Get the value at position.
// @param this `Tensor` data.
// @param position Coordinate position of value.
// @returns Value at position.
export method get (Tensor this, array<int> position) =>
this.get(array.get(position, 0), array.get(position, 1), array.get(position, 2))
// }
// set () {
// @function Set the value at position.
// @param this `Tensor` data.
// @param x Position in `X` dimension.
// @param y Position in `Y` dimension.
// @param z Position in `Z` dimension.
// @param value New Value.
export method set (Tensor this, int x, int y, int z, float value) =>
this.m.get(x, y).v.set(z, value)
// float new_value = input.float(1.123)
// if barstate.islast
// _T = from(array.from(1.0,2,3,4,5,6,7,8,9,10,11,12), 2, 3, 2)
// _T.set(1, 1, 1, new_value)
// label.new(bar_index, 0.0, to_string(_T))
// @function Set the value at position.
// @param this `Tensor` data.
// @param position Coordinate position of value.
// @param value New Value.
export method set (Tensor this, array<int> position, float value) =>
this.set(array.get(position, 0), array.get(position, 1), array.get(position, 2), value)
// }
// get_vector_xy () {
// @function Get the vector at position.
// @param this `Tensor` data.
// @param x Position in `X` dimension.
// @param y Position in `Y` dimension.
// @returns Vector at position.
export method get_vector_xy (Tensor this, int x, int y) =>
this.m.get(x, y).v
// @function Set the value at position.
// @param this `Tensor` data.
// @param position Coordinate position of value.
// @returns Vector at position.
export method get_vector_xy (Tensor this, array<int> position) =>
this.get_vector_xy(array.get(position, 0), array.get(position, 1))
// }
// set_vector_xy () {
// @function Set the vector at position.
// @param this `Tensor` data.
// @param x Position in `X` dimension.
// @param y Position in `Y` dimension.
// @param values New values vector.
export method set_vector_xy (Tensor this, int x, int y, array<float> values) =>
_oldv = this.m.get(x, y)
_oldv.v := values
// if barstate.islast
// _T = from(array.from(1.0,2,3,4,5,6,7,8,9,10,11,12), 2, 3, 2)
// _T.set_vector_xy(1, 1, array.from(33.3, 33.3))
// label.new(bar_index, 0.0, to_string(_T))
// @function Set the vector at position.
// @param this `Tensor` data.
// @param position Coordinate position of value.
// @param values New values vector.
export method set_vector_xy (Tensor this, array<int> position, array<float> values) =>
set_vector_xy(this, array.get(position, 0), array.get(position, 1), values)
// }
//#endregion
|
PhantomFlow RangeDetector | https://www.tradingview.com/script/WrkcNtP1-PhantomFlow-RangeDetector/ | PhantomFlow | https://www.tradingview.com/u/PhantomFlow/ | 79 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mxrshxl_trxde
//@version=5
indicator("PhantomFlow RangeDetector", "PhantomFlow RangeDetector", true, max_boxes_count = 500)
n = input.int(2, title='Min. bars for range')
coefZone = 4
// all_color = input.color(title='All colors', defval = color.rgb(0, 255, 234, 80), group="Visual Settings", inline = 'bg_ltf_color_liquidity')
color_up = input.color(title='Background UP', defval = color.rgb(255, 0, 0, 80), group="Visual Settings", inline = 'bg_ltf_color_liquidity')
color_down = input.color(title='Background DOWN', defval = color.rgb(0, 255, 0, 80), group="Visual Settings", inline = 'bg_ltf_color_liquidity')
// color_up_setup = input.color(title='Background UP Setup', defval = color.rgb(255, 0, 234, 80), group="Visual Settings", inline = 'bg_ltff_color_liquidity')
// color_down_setup = input.color(title='Background DOWN Setup', defval = color.rgb(0, 225, 255, 80), group="Visual Settings", inline = 'bg_ltff_color_liquidity')
type zone
int startBar
int endBar
float priceHigh
float priceLow
bool isChained
bool isDropZone
bool isActive
bool isBuildZone
string typeSort
box bx
bool isSetup
var array<zone> zones_all = array.new<zone>()
var array<zone> chain_zones_all = array.new<zone>()
var array<float> sized_zones = array.new<float>()
if (array.size(zones_all) != 0)
zone lastZone = array.last(zones_all)
if lastZone.priceLow > close or lastZone.priceHigh < close
if (lastZone.endBar - lastZone.startBar != 1 and lastZone.endBar - lastZone.startBar >= n and not lastZone.isDropZone)
lastZone.isChained := true
array.push(sized_zones, lastZone.priceHigh - lastZone.priceLow)
if (array.size(sized_zones) > 5)
array.shift(sized_zones)
else
if not na(lastZone.bx)
box.delete(lastZone.bx)
array.remove(zones_all, array.indexof(zones_all, lastZone))
if high[1] >= close and high[1] >= open and low[1] <= close and low[1] <= open
isContinous = true
if (array.size(zones_all) != 0)
zone lastZone = array.last(zones_all)
if not lastZone.isChained
if lastZone.priceHigh >= close and lastZone.priceHigh >= close[1] and lastZone.priceHigh >= open and lastZone.priceHigh >= open[1] and lastZone.priceLow <= close and lastZone.priceLow <= close[1] and lastZone.priceLow <= open and lastZone.priceLow <= open[1]
lastZone.endBar := bar_index
isContinous := false
if not na(lastZone.bx)
box.delete(lastZone.bx)
// lastZone.bx := box.new(lastZone.startBar, lastZone.priceHigh, lastZone.endBar, lastZone.priceLow, border_color = all_color, bgcolor = all_color)
else
if lastZone.endBar - lastZone.startBar == 1 or lastZone.endBar - lastZone.startBar < n
if not na(lastZone.bx)
box.delete(lastZone.bx)
array.remove(zones_all, array.indexof(zones_all, lastZone))
else
lastZone.isChained := true
array.push(sized_zones, lastZone.priceHigh - lastZone.priceLow)
if (array.size(sized_zones) > 5)
array.shift(sized_zones)
if lastZone.isChained and not lastZone.isBuildZone
lastZone.isDropZone := true
if not na(lastZone.bx)
box.delete(lastZone.bx)
if array.size(sized_zones) != 0 and isContinous
if (high[1] - low[1]) / array.avg(sized_zones) > coefZone
array.push(sized_zones, high[1] - low[1])
if (array.size(sized_zones) > 5)
array.shift(sized_zones)
isContinous := false
else
array.push(zones_all, zone.new(bar_index - 1, bar_index, high[1], low[1], false, false, false, false, na, na, false))
if array.size(sized_zones) == 0 and isContinous
array.push(zones_all, zone.new(bar_index - 1, bar_index, high[1], low[1], false, false, false, false, na, na, false))
if array.size(zones_all) != 0
zone lastZone = array.last(zones_all)
if not lastZone.isChained and array.size(zones_all) > 1
lastZone := array.get(zones_all, array.size(zones_all) - 2)
if lastZone.isChained and not lastZone.isBuildZone and not lastZone.isDropZone
if high > lastZone.priceHigh and close > lastZone.priceHigh
if lastZone.endBar - lastZone.startBar >= n
lastZone.isBuildZone := true
lastZone.isActive := true
lastZone.typeSort := 'long'
array.push(chain_zones_all, lastZone)
if not na(lastZone.bx)
box.delete(lastZone.bx)
lastZone.bx := box.new(lastZone.startBar, lastZone.priceHigh, lastZone.endBar, lastZone.priceLow, border_color = color_down, bgcolor = color_down)
else
lastZone.isDropZone := true
if not na(lastZone.bx)
box.delete(lastZone.bx)
if low < lastZone.priceLow and close < lastZone.priceLow
if lastZone.endBar - lastZone.startBar >= n
lastZone.isBuildZone := true
lastZone.isActive := true
lastZone.typeSort := 'short'
array.push(chain_zones_all, lastZone)
if not na(lastZone.bx)
box.delete(lastZone.bx)
lastZone.bx := box.new(lastZone.startBar, lastZone.priceHigh, lastZone.endBar, lastZone.priceLow, border_color = color_up, bgcolor = color_up)
else
lastZone.isDropZone := true
if not na(lastZone.bx)
box.delete(lastZone.bx)
// if array.size(zones_all) > 2
// zone lastZone = array.last(zones_all)
// zone prevZone = array.get(zones_all, array.size(zones_all) - 2)
// zone prevPrevZone = array.get(zones_all, array.size(zones_all) - 3)
// if lastZone.isBuildZone and prevZone.isBuildZone and prevPrevZone.isBuildZone
// if lastZone.typeSort == "short" and prevZone.typeSort == "short" and prevPrevZone.typeSort == "long"
// if prevPrevZone.priceHigh >= prevZone.priceLow and prevPrevZone.priceHigh < prevZone.priceHigh and lastZone.priceHigh >= prevZone.priceLow and lastZone.priceHigh < prevZone.priceHigh
// lastZone.isSetup := true
// if not na(lastZone.bx)
// box.delete(lastZone.bx)
// lastZone.bx := box.new(lastZone.startBar, lastZone.priceHigh, lastZone.endBar, lastZone.priceLow, border_color = color_up_setup, bgcolor = color_up_setup)
// if lastZone.typeSort == "long" and prevZone.typeSort == "long" and prevPrevZone.typeSort == "short"
// if prevPrevZone.priceLow <= prevZone.priceHigh and prevPrevZone.priceLow > prevZone.priceLow and lastZone.priceLow <= prevZone.priceHigh and lastZone.priceLow > prevZone.priceLow
// lastZone.isSetup := true
// if not na(lastZone.bx)
// box.delete(lastZone.bx)
// lastZone.bx := box.new(lastZone.startBar, lastZone.priceHigh, lastZone.endBar, lastZone.priceLow, border_color = color_down_setup, bgcolor = color_down_setup) |
Entry Assistant & News Alert | https://www.tradingview.com/script/sqzGGSP7-Entry-Assistant-News-Alert/ | ivanroyloewen | https://www.tradingview.com/u/ivanroyloewen/ | 22 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ivanroyloewen
//@version=5
indicator("Entry & News", overlay = true)
// Entry Assistant
//-------------------------------------------------------------------------------------------------------------------------------( General Inputs / Variables ) ---------------------------------------------
var direction = "Direction"
// are you planning to go Long ( displays data to assist entering Long positions)
var going_Long = input(title = "Long", defval = true, inline = direction, group = direction)
// are you planning to go Short ( displays data to assist entering Short positions)
var going_Short = input(title = "Short", defval = false, inline = direction, group = direction)
var show = "Show"
// display the stop loss line
var show_Stop = input(title = "Stop", defval = true, inline = show, group = show)
// display the BOC line
var show_BOC = input(title = "BOC", defval = true, inline = show, group = show)
// display the entry signal ( when current candle breaks previous candle )
var show_Entry_Signal = input(title = "Entry", defval = true, inline = show, group = show)
// only display the last three digits of the price ( on the price label )
var show_Only_Last_Three_Digits = input(title = "Three Digits Only", defval = true, inline = show, group = show)
//-------------------------------------------------------------------------------------------------------------------------------( Long Inputs ) ------------------------------------------------------------
var variables_Long = "Long Variables"
// how much price below the current candle do you want to Stop line placed
var pips_Below_Candle_Stop_Long = input.float(title = "Pips spacing below candle for stop loss", defval = 1.0, minval = 0, maxval = 1000, group = variables_Long)
// how much price above the Long BOC line until Long entry signal is displayed
var pips_Above_BOC_Entry_Long = input.float(title = "Pips spacing above BOC for entry signal", defval = 0.1, minval = 0, maxval = 1000, group = variables_Long)
// how many candles ahead on the x axis is the Long price label placed
var label_Distance_Long = input.int(title = "Label horizontal distance", defval = 20, minval = 0, maxval = 100, group = variables_Long)
// Long Colors
var colors_Long = "Long Colors"
// the color of the Long Stop line
var line_Color_Long = input.color(title = "Stop", defval = #5b9cf6, inline = colors_Long)
// the color of the Long BOC line
var line_BOC_Color_Long = input.color(title = "BOC", defval = #ac774f, inline = colors_Long)
// the color of the Long entry signal
var entry_Signal_Color_Long = input.color(title = "Entry", defval = color.green, inline = colors_Long)
// the color of the Long label
var label_Color_Long = input(title = "Label", defval = #3179f5, inline = colors_Long)
// the color of the Long label text
var labe_Text_Color_Long = input(title = "Text", defval = color.white, inline = colors_Long)
//-------------------------------------------------------------------------------------------------------------------------------( Short Inputs ) -----------------------------------------------------------
var variables_Short = "Short Variables"
// how much price above the current candle do you want to Stop line placed
var pips_Below_Candle_Stop_Short = input.float(title = "Pips spacing above candle for stop loss", defval = 1.0, minval = 0, maxval = 1000, group = variables_Short )
// how much price below the Short BOC line until Short entry signal is displayed
var pips_Above_BOC_Entry_Short = input.float(title = "Pips spacing below BOC for entry signal", defval = 0.1, minval = 0, maxval = 1000, group = variables_Short )
// how many candles ahead on the x axis is the Short price label placed
var label_Distance_Short = input.int(title = "Label horizontal distance", defval = 20, minval = 0, maxval = 100, group = variables_Short )
var colors_Short = "Short Colors"
// the color of the Short Stop line
var line_Color_Short = input.color(title = "Stop", defval = #5b9cf6, inline = colors_Short)
// the color of the Short BOC line
var line_BOC_Color_Short = input.color(title = "BOC", defval = #ac774f, inline = colors_Short)
// the color of the Short entry signal
var entry_Signal_Color_Short = input.color(title = "Entry", defval = color.green, inline = colors_Short)
// the color of the Short label
var label_Color_Short = input(title = "Label", defval = #3179f5, inline = colors_Short)
// the color of the Short label text
var label_Text_Color_Short = input(title = "Text", defval = color.white, inline = colors_Short)
//-------------------------------------------------------------------------------------------------------------------------------( Price Calculation ) -----------------------------------------------------------
var price_Digit_Count = str.length(str.tostring(syminfo.mintick))
// the time frame, calculated by the time between the current and previous candle
time_Frame = time - time[1]
// rounds numbers
Truncate(number, decimals) =>
factor = math.pow(10, decimals)
int(number * factor) / factor
// get the price value from the given inputs
pips_Price_Value_Stop_Long = syminfo.mintick * Truncate(pips_Below_Candle_Stop_Long, 1) * 10
pips_Price_Value_BOC_Long = syminfo.mintick * Truncate(pips_Above_BOC_Entry_Long, 1) * 10
// calculate the new line positions with the pips price value
price_Stop_Long = low - pips_Price_Value_Stop_Long
price_BOC_Entry_Long = high[1] + pips_Price_Value_BOC_Long
// the position where the Long label will be initially placed
long_Label_Point = chart.point.new(time = time, index = bar_index, price = price_Stop_Long)
long_Label_Text = str.tostring(price_Stop_Long)
// check if the current label text has less character than the instruments max digits price ( this means a "0" zero has been rounded off )
if str.length(long_Label_Text) < price_Digit_Count
// get the amount of zeros that have been rounded off
int amount_Of_Zeros_Rounded_Off = price_Digit_Count - str.length(long_Label_Text)
// add as many zeros back on that have been rounded off
for i = 1 to amount_Of_Zeros_Rounded_Off by 1
// add the zero back onto the label text
long_Label_Text += "0"
// get the price value from the given inputs
pips_Price_Value_Stop_Short = syminfo.mintick * Truncate(pips_Below_Candle_Stop_Short, 1) * 10
pips_Price_Value_BOC_Short = syminfo.mintick * Truncate(pips_Above_BOC_Entry_Short, 1) * 10
// calculate the new line positions with the pips price value
price_Stop_Short = high + pips_Price_Value_Stop_Short
price_BOC_Entry_Short = low[1] - pips_Price_Value_BOC_Short
// the position where the Short label will be initially placed
short_Label_Point = chart.point.new(time = time, index = bar_index, price = price_Stop_Short)
short_Label_Text = str.tostring(price_Stop_Short)
// check if the current label text has less character than the instruments max digits price ( this means a "0" zero has been rounded off )
if str.length(short_Label_Text) < price_Digit_Count
// get the amount of zeros that have been rounded off
int amount_Of_Zeros_Rounded_Off = price_Digit_Count - str.length(short_Label_Text)
// add as many zeros back on that have been rounded off
for i = 1 to amount_Of_Zeros_Rounded_Off by 1
// add the zero back onto the label text
short_Label_Text += "0"
//-------------------------------------------------------------------------------------------------------------------------------( Handle Long Data / Drawings ) --------------------------------------------
// if you are going Long
if going_Long
// draw the Long Stop line below the current candle
stop_Line_Long = line.new(bar_index[1], price_Stop_Long, bar_index, price_Stop_Long, xloc.bar_index, extend.right, line_Color_Long, line.style_solid, 2)
// delete the previous Long Stop line
line.delete(stop_Line_Long[1])
// if you are showing the Long BOC ( Break Of Candle ) line
if show_BOC
// draw the Long BOC line at the previous candles high
line_Long_BOC = line.new(bar_index[1], high[1], bar_index, high[1], xloc.bar_index, extend.right, line_BOC_Color_Long, line.style_solid, 2)
// delete the previous Long BOC line
line.delete(line_Long_BOC[1])
// set the default value to ERR ( error )
last_Three_Characters = "ERR"
// only show the last three digits of the stop loss price
if show_Only_Last_Three_Digits
// remove the decimal when only showing three digshow_Only
long_Label_Text := str.replace( long_Label_Text , target = ".", replacement = "")
// check for this condition to prevent compialation errors
if str.length(long_Label_Text) - 3 < 0 == false
// get the last 3 characters from the Long Stop line price
last_Three_Characters := str.substring(long_Label_Text, str.length(long_Label_Text) - 3)
// draw the Long label displaying the price of the Long line ( display only last 3 characters if specified )
label_Long = label.new(point = long_Label_Point, style = label.style_label_up, text = show_Only_Last_Three_Digits ? last_Three_Characters : long_Label_Text, color = label_Color_Long, textcolor = labe_Text_Color_Long, xloc = xloc.bar_time, size = size.huge)
// adjust the Long label x position based off of input
label_Long.set_x(time + label_Distance_Long * time_Frame)
// delete the previous Long label
label.delete(label_Long[1])
// draw a box when the current price has broken above the Long BOC line ( plus the additional pips from input)
BOC_Signal = box.new(bar_index[1], high , bar_index, price_BOC_Entry_Long, border_color = na, bgcolor = entry_Signal_Color_Long, extend = extend.right)
// delete the previous Long BOC signal box
box.delete(BOC_Signal[1])
// if show entry signal is false or the current candles high is not above the previous candles high
if show_Entry_Signal == false or high > price_BOC_Entry_Long == false
// delete the current Long BOC signal box
box.delete(BOC_Signal)
//-------------------------------------------------------------------------------------------------------------------------------( Handle Short Data / Drawings ) -------------------------------------------
// if you are going Short
if going_Short
// draw the Short Stop line above the current candle
stop_Line_Short = line.new(bar_index[1], price_Stop_Short, bar_index, price_Stop_Short, xloc.bar_index, extend.right, line_Color_Short, line.style_solid, 2)
// delete the previous Short Stop line
line.delete(stop_Line_Short[1])
// if you are showing the BOC ( Break Of Candle ) line
if show_BOC
// draw the Short BOC line at the previous candles low
line_Short_BOC = line.new(bar_index[1], low[1], bar_index, low[1], xloc.bar_index, extend.right, line_BOC_Color_Short, line.style_solid, 2)
// delete the previous Short BOC line
line.delete(line_Short_BOC[1])
// set the default value to ERR ( error )
last_Three_Characters = "ERR"
// only show the last three digits of the stop loss price
if show_Only_Last_Three_Digits
// remove the decimal when only showing three digshow_Only
short_Label_Text := str.replace( short_Label_Text , target = ".", replacement = "")
// check for this condition to prevent compialation errors
if str.length(short_Label_Text) - 3 < 0 == false// or str.length(short_Label_Text) - 3 < str.length(short_Label_Text) - 1
// get the last 3 characters from the Short Stop line price
last_Three_Characters := str.substring(short_Label_Text, str.length(short_Label_Text) - 3)
// draw the Short label displaying the price of the Short line ( display only last 3 characters if specified )
label_Short = label.new(point = short_Label_Point, style = label.style_label_down, text = show_Only_Last_Three_Digits ? last_Three_Characters : short_Label_Text, color = label_Color_Short, textcolor = label_Text_Color_Short, xloc = xloc.bar_time, size = size.huge)
// adjust the Short label x position based off of input
label_Short.set_x(time + label_Distance_Short * time_Frame)
// delete the previous Short label
label.delete(label_Short[1])
// draw a box when the current price has broken below the Short BOC line ( minus the additional pips from input)
BOC_Signal = box.new(bar_index[1], price_BOC_Entry_Short, bar_index, low, border_color = na, bgcolor = entry_Signal_Color_Short, extend = extend.right)
// delete the previous Short BOC signal box
box.delete(BOC_Signal[1])
// if show entry signal is false or the current candles low is not below the previous candles low
if show_Entry_Signal == false or low < price_BOC_Entry_Short == false
// delete the current Short BOC signal box
box.delete(BOC_Signal)
//------------------------------------------------------------------------------------------------------------------------------- ( Execute Functions) ----------------------------------------------------
// News Alert
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------( inputs )
var news = " News Alert"
// the offest of your personal timezone from Eastern Standard Time ( New York Time )
var time_Zone_Offset = input.int(defval = 0, title = "Timezone offset in hours from EST", maxval = 24, minval = -24, group = news)
// the inputs for the first news alert
var news_Time_1 = "News Time 1"
var news_Hour_1 = input.int(defval = 00, title = "Hour", group = news_Time_1, inline = news_Time_1, minval = 0, maxval = 24)
var news_Minute_1 = input.int(defval = 00, title = "Minute", group = news_Time_1, inline = news_Time_1, minval = 0, maxval = 45, step = 15)
var show_News_1 = input.bool(defval = false, title = "Show News 1", group = news_Time_1, inline = news_Time_1)
// the inputs for the second news alert
var news_Time_2 = "News Time 2"
var news_Hour_2 = input.int(defval = 00, title = "Hour", group = news_Time_2, inline = news_Time_2, minval = 0, maxval = 24)
var news_Minute_2 = input.int(defval = 00, title = "Minute", group = news_Time_2, inline = news_Time_2, minval = 0, maxval = 45, step = 15)
var show_News_2 = input.bool(defval = false, title = "Show News 2", group = news_Time_2, inline = news_Time_2)
// the inputs for the third news alert
var news_Time_3 = "News Time 3"
var news_Hour_3 = input.int(defval = 00, title = "Hour", group = news_Time_3, inline = news_Time_3, minval = 0, maxval = 24)
var news_Minute_3 = input.int(defval = 00, title = "Minute", group = news_Time_3, inline = news_Time_3, minval = 0, maxval = 45, step = 15)
var show_News_3 = input.bool(defval = false, title = "Show News 3", group = news_Time_3, inline = news_Time_3)
// the inputs for the warning period before and after the news release
var news_Warning = "News Warning Period"
var minutes_Warning_Before_News = input.int(defval = 10, title = "Minutes Before", group = news_Warning, inline = news_Warning, minval = 0, maxval = 65, step = 5)
var minutes_Warning_After_News = input.int(defval = 10, title = "Minutes After", group = news_Warning, inline = news_Warning, minval = 0, maxval = 65, step = 5)
// the inputs for the news line settings
var line_Settings = "News Line Settings"
var line_Color = input.color(defval = color.rgb(255, 255, 255), title = "Color", inline = line_Settings, group = line_Settings)
var line_Style = input.string(defval = "Dotted", title="Style", options=["Dotted", "Dashed", "Solid"], group = line_Settings, inline = line_Settings)
var line_Width = input.int(defval = 1, title = "Width", minval = 1, maxval = 10, inline = line_Settings, group = line_Settings)
// the inputs for the warning area surrounding the news release
var box_Settings = "News Area Settings"
var box_Background_Color = input.color(defval = color.rgb(0, 0, 255, 75), title = "Background Color", inline = box_Settings, group = box_Settings)
var box_Show = input.bool(defval = true, title = "Show Area", inline = box_Settings, group = box_Settings)
// set the line style using the string input
var line_Style_Selected = line.style_dotted
if line_Style == "Dotted"
line_Style_Selected := line.style_dotted
else if line_Style == "Dashed"
line_Style_Selected := line.style_dashed
else if line_Style == "Solid"
line_Style_Selected := line.style_solid
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------( time calculations )
// the current time of the current bar
current_Bar_Time = time
// News 1 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// get the time stamps for the first news warning, release, before and after
news_Time_Stamp_Release_1 = timestamp(year, month, dayofmonth, news_Hour_1 + time_Zone_Offset, news_Minute_1, 00)
news_Time_Stamp_Before_1 = timestamp(year, month, dayofmonth, news_Hour_1 + time_Zone_Offset, news_Minute_1 - minutes_Warning_Before_News, 00)
news_Time_Stamp_After_1 = timestamp(year, month, dayofmonth, news_Hour_1 + time_Zone_Offset, news_Minute_1 + minutes_Warning_After_News, 00)
// create bools to indicate where price is currently relatated to the first news warning, used for calculations
bool bar_Is_In_News_1 = current_Bar_Time >= news_Time_Stamp_Before_1 and current_Bar_Time <= news_Time_Stamp_After_1 and show_News_1
bool bar_Is_Before_News_1 = current_Bar_Time < news_Time_Stamp_Release_1 and current_Bar_Time >= news_Time_Stamp_Before_1
bool bar_Is_News_Release_1 = current_Bar_Time == news_Time_Stamp_Release_1
bool bar_Is_News_Ongoing_1 = current_Bar_Time > news_Time_Stamp_Release_1 and current_Bar_Time < news_Time_Stamp_After_1
bool bar_Is_Last_News_Candle_1 = current_Bar_Time == news_Time_Stamp_After_1
// draw the news warning objects if showing the first news warning
if show_News_1
// draw the news warning area
news_Box_1 = box.new(left = news_Time_Stamp_Before_1, top = (open * 2) + open, right = news_Time_Stamp_After_1, bottom = (open * -2) + open, xloc = xloc.bar_time, border_color = na, bgcolor = box_Background_Color)
box.delete(news_Box_1[1])
// delete the box if box show = false
if box_Show == false
box.delete(news_Box_1)
// draw the news release line
news_Line_1 = line.new(news_Time_Stamp_Release_1, -1, news_Time_Stamp_Release_1, 1, xloc.bar_time, extend.both, line_Color, line_Style_Selected, line_Width)
line.delete(news_Line_1[1])
// News 2 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// get the time stamps for the second news warning, release, before and after
news_Time_Stamp_Release_2 = timestamp(year, month, dayofmonth, news_Hour_2 + time_Zone_Offset, news_Minute_2, 00)
news_Time_Stamp_Before_2 = timestamp(year, month, dayofmonth, news_Hour_2 + time_Zone_Offset, news_Minute_2 - minutes_Warning_Before_News, 00)
news_Time_Stamp_After_2 = timestamp(year, month, dayofmonth, news_Hour_2 + time_Zone_Offset, news_Minute_2 + minutes_Warning_After_News, 00)
// create bools to indicate where price is currently relatated to the second news warning, used for calculations
bool bar_Is_In_News_2 = current_Bar_Time >= news_Time_Stamp_Before_2 and current_Bar_Time <= news_Time_Stamp_After_2 and show_News_2
bool bar_Is_Before_News_2 = current_Bar_Time < news_Time_Stamp_Release_2 and current_Bar_Time >= news_Time_Stamp_Before_2
bool bar_Is_News_Release_2 = current_Bar_Time == news_Time_Stamp_Release_2
bool bar_Is_News_Ongoing_2 = current_Bar_Time > news_Time_Stamp_Release_2 and current_Bar_Time < news_Time_Stamp_After_2
bool bar_Is_Last_News_Candle_2 = current_Bar_Time == news_Time_Stamp_After_2
// draw the news warning objects if showing the second news warning
if show_News_2
// draw the news warning area
news_Box_1 = box.new(left = news_Time_Stamp_Before_2, top = (open * 2) * open, right = news_Time_Stamp_After_2, bottom = (open * -2) + open, xloc = xloc.bar_time, border_color = na, bgcolor = box_Background_Color)
box.delete(news_Box_1[1])
// delete the box if box show = false
if box_Show == false
box.delete(news_Box_1)
// draw the news release line
news_Line_2 = line.new(news_Time_Stamp_Release_2, -1, news_Time_Stamp_Release_2, 1, xloc.bar_time, extend.both, line_Color, line_Style_Selected, line_Width)
line.delete(news_Line_2[1])
// News 3 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// get the time stamps for the third news warning, release, before and after
news_Time_Stamp_Release_3 = timestamp(year, month, dayofmonth, news_Hour_3 + time_Zone_Offset, news_Minute_3, 00)
news_Time_Stamp_Before_3 = timestamp(year, month, dayofmonth, news_Hour_3 + time_Zone_Offset, news_Minute_3 - minutes_Warning_Before_News, 00)
news_Time_Stamp_After_3 = timestamp(year, month, dayofmonth, news_Hour_3 + time_Zone_Offset, news_Minute_3 + minutes_Warning_After_News, 00)
// create bools to indicate where price is currently relatated to the third news warning, used for calculations
bool bar_Is_In_News_3 = current_Bar_Time >= news_Time_Stamp_Before_3 and current_Bar_Time <= news_Time_Stamp_After_3 and show_News_3
bool bar_Is_Before_News_3 = current_Bar_Time < news_Time_Stamp_Release_3 and current_Bar_Time >= news_Time_Stamp_Before_3
bool bar_Is_News_Release_3 = current_Bar_Time == news_Time_Stamp_Release_3
bool bar_Is_News_Ongoing_3 = current_Bar_Time > news_Time_Stamp_Release_3 and current_Bar_Time < news_Time_Stamp_After_3
bool bar_Is_Last_News_Candle_3 = current_Bar_Time == news_Time_Stamp_After_3
// draw the news warning objects if showing the third news warning
if show_News_3
// draw the news warning area
news_Box_1 = box.new(left = news_Time_Stamp_Before_3, top = (open * 2) * open, right = news_Time_Stamp_After_3, bottom = (open * -2) + open, xloc = xloc.bar_time, border_color = na, bgcolor = box_Background_Color)
// delete old boxes
box.delete(news_Box_1[1])
// delete the box if box show = false
if box_Show == false
box.delete(news_Box_1)
// draw the news release line
news_Line_3 = line.new(news_Time_Stamp_Release_3, -1, news_Time_Stamp_Release_3, 1, xloc.bar_time, extend.both, line_Color, line_Style_Selected, line_Width)
// delete old lines
line.delete(news_Line_3[1])
// All News ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// create bools to indicate where price is currently relatated to all the news warning, used for calculations
bool bar_Is_In_News = bar_Is_In_News_1 or bar_Is_In_News_2 or bar_Is_In_News_3
bool bar_Is_Before_News = bar_Is_Before_News_1 or bar_Is_Before_News_2 or bar_Is_Before_News_3
bool bar_Is_News_Release = bar_Is_News_Release_1 or bar_Is_News_Release_2 or bar_Is_News_Release_3
bool bar_Is_News_Ongoing = bar_Is_News_Ongoing_1 or bar_Is_News_Ongoing_2 or bar_Is_News_Ongoing_3
bool bar_Is_Last_News_Candle = bar_Is_Last_News_Candle_1 or bar_Is_Last_News_Candle_2 or bar_Is_Last_News_Candle_3
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------( News Table )
// create a table that will be used to display the news warning before, after and during the news release
news_Table = table.new(position = position.bottom_right, columns = 1, rows = 2, bgcolor = color.red, frame_color = color.white, frame_width = 2)
// if price is currently in a news warning area
if bar_Is_In_News == true
// indacate that there is currently active news
table.cell(table_id = news_Table, column = 0, row = 0, text = "Active News")
table.cell_set_text_size(news_Table, 0, 0, size.large)
table.cell_set_text_color(news_Table, 0, 0, color.white)
if bar_Is_News_Release
// indicate that it is the news release
table.cell(table_id = news_Table, column = 0, row = 1, text = "Release")
table.cell_set_text_size(news_Table, 0, 1, size.large)
table.cell_set_text_color(news_Table, 0, 1, color.white)
else if bar_Is_News_Ongoing
// indicate if news is ongoing ( after the news release )
table.cell(table_id = news_Table, column = 0, row = 1, text = "Ongoing")
table.cell_set_text_size(news_Table, 0, 1, size.large)
table.cell_set_text_color(news_Table, 0, 1, color.white)
else if bar_Is_Last_News_Candle
// indate if news is on the last candle before the warning ends
table.cell(table_id = news_Table, column = 0, row = 1, text = "Last Candle")
table.cell_set_text_size(news_Table, 0, 1, size.large)
table.cell_set_text_color(news_Table, 0, 1, color.white)
else if bar_Is_Before_News
// indicate if the news release is coming soon
table.cell(table_id = news_Table, column = 0, row = 1, text = "Incoming")
table.cell_set_text_size(news_Table, 0, 1, size.large)
table.cell_set_text_color(news_Table, 0, 1, color.white)
else
// indicate that price is currently not in a news warning
table.set_bgcolor(news_Table, bgcolor = color.green)
table.cell(table_id = news_Table, column = 0, row = 0, text = " Clear ")
table.cell_set_text_size(news_Table, 0, 0, size.normal)
table.cell_set_text_color(news_Table, 0, 0, color.white)
// delete old tables
table.delete(news_Table[1]) |
Consolidation indicator | https://www.tradingview.com/script/ab2xlRnX-Consolidation-indicator/ | cyatophilum | https://www.tradingview.com/u/cyatophilum/ | 120 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © cyatophilum
//@version=5
indicator("Consolidation indicator",overlay = true)
timeframe = input.timeframe('','timeframe')
smoothing_length = input.int(4,'price smoothing length',minval=1)
range_len = 14//input.int(14,'Avg range length')
NR_threshold = input.float(80,'% Threshold for Narrow Range')
consecutive_ranges = input.int(3,'Consecutive Narrow Ranges for Consolidation')
consolidation_candle_color = input.color(color.rgb(43, 255, 0),'Candle color')
var int cpt = 0
_priceRange = ta.sma(high - low,smoothing_length)
_averageRange = ta.rma(_priceRange, range_len)
offset = timeframe == timeframe.period ? 0 : 1
[priceRange, averageRange, HTFClose] = request.security(syminfo.tickerid, timeframe,
[
_priceRange[offset],
_averageRange[offset],
close[offset]
],
lookahead = barmerge.lookahead_on)
bool is_new_period = ta.change(HTFClose)
narrowRange = priceRange < NR_threshold * averageRange / 100
if is_new_period
if narrowRange
cpt := cpt + 1
else
cpt := 0
breakout = cpt[1] >= consecutive_ranges[1] and not narrowRange
transp = cpt == 0 ? 100 : 100 - cpt * 100 / consecutive_ranges
hma = ta.hma(close,range_len)
is_bullish = ta.rising(hma,1)
is_bearish = ta.falling(hma,1)
long = breakout and is_bullish
short = breakout and is_bearish
candlescolor = narrowRange ? color.new(consolidation_candle_color, transp) : chart.bg_color
wickcolor = narrowRange ? (consolidation_candle_color) : color.new(chart.fg_color,10)
bordercolor = narrowRange ? (consolidation_candle_color) : color.new(chart.fg_color,10)
plotcandle(open,high,low,close,'consolidation', candlescolor, wickcolor = wickcolor, bordercolor = bordercolor)
plot(narrowRange or breakout ? hma : na, 'direction line', is_bullish ? color.rgb(33, 150, 243) : color.red, 4, plot.style_linebr)
// plotchar(breakout ? close : na,'breakout','💥',location.belowbar,text='Breakout',textcolor = color.orange)
plotshape(long,'long breakout', shape.labelup, location.belowbar,color.rgb(0, 0, 0), text='Breakout💥', textcolor=color.lime)
plotshape(short,'short breakout', shape.labeldown, location.abovebar,color.rgb(0, 0, 0), text='Breakout💥', textcolor=color.red)
alertcondition(narrowRange and not narrowRange[1],'Consolidation Begins','')
alertcondition(long,'Long Breakout','')
alertcondition(short,'Short Breakout','')
|
Moving Average SAR | https://www.tradingview.com/script/2ysy4KuF/ | Seungdori_ | https://www.tradingview.com/u/Seungdori_/ | 34 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Seungdori_
//@version=5
indicator('Moving Average SAR', shorttitle='MA SAR', overlay = true)
//Inputs//
sensitiveness = 60 * input.int(10, minval=1, title='Sensitiveness')
len = input.int(20, minval=1, title='Length')
MA_type = input.string('RMA', 'MA Type ',options=['SMA', 'EMA', 'HMA', 'WMA', 'DEMA', 'RMA', 'Donchian', 'LSMA','SWMA', 'T3', 'VWAP', 'VWMA'])
src = close
trend_para = input.float(defval = 1, title= 'Trend Strength Parameter', step = 0.01)
AA = input.float(1, title= 'Band Width', step = 0.1)
show_signal = input.bool(defval= false, title = 'Show Signals')
//MA Settings//
/////////////////////
//Region : Function//
/////////////////////
bool bull = false
bool bear = false
FuncT3(_src, _length) =>
axe1 = ta.ema(_src, _length)
axe2 = ta.ema(axe1, _length)
axe3 = ta.ema(axe2, _length)
axe4 = ta.ema(axe3, _length)
axe5 = ta.ema(axe4, _length)
axe6 = ta.ema(axe5, _length)
ab = 0.7
ac1 = -ab * ab * ab
ac2 = 3 * ab * ab + 3 * ab * ab * ab
ac3 = -6 * ab * ab - 3 * ab - 3 * ab * ab * ab
ac4 = 1 + 3 * ab + ab * ab * ab + 3 * ab * ab
T3 = ac1 * axe6 + ac2 * axe5 + ac3 * axe4 + ac4 * axe3
T3
getMA(ma_type ,src, length) =>
maPrice = ta.ema(src, length)
ema = ta.ema(src, length)
sma = ta.sma(src, length)
if ma_type == 'SMA'
maPrice := ta.sma(src, length)
maPrice
if ma_type == 'EMA'
maPrice := ta.ema(src, length)
maPrice
if ma_type == 'HMA'
maPrice := ta.hma(src, length)
maPrice
if ma_type == 'WMA'
maPrice := ta.wma(src, length)
maPrice
if ma_type == 'VWMA'
maPrice := ta.vwma(src, length)
maPrice
if ma_type == 'VWAP'
maPrice := ta.vwap
maPrice
if ma_type == 'DEMA'
e1 = ta.ema(src, length)
e2 = ta.ema(e1, length)
maPrice := 2 * e1 - e2
maPrice
if ma_type == 'T3'
maPrice := FuncT3(src, length)
if ma_type == "SWMA"
maPrice := ta.swma(src)
if ma_type == "DEMA"
maPrice := 2 * ta.ema(src, length) - ta.ema(ta.ema(src, length), length)
if ma_type == "RMA"
maPrice := ta.rma(src, length)
if ma_type == "LSMA"
maPrice := ta.linreg(src, length, 0)
if ma_type == "Donchian"
maPrice := ((math.avg(ta.lowest(length), ta.highest(length))) + (math.avg(ta.lowest(length/2), ta.highest(length/2))))/2
maPrice
MA = getMA(MA_type, src, len)
//Main Logic//
interval_to_len = timeframe.multiplier * (timeframe.isdaily ? 1440 : timeframe.isweekly ? 1440 * 7 : timeframe.ismonthly ? 1440 * 30 : 1)
main_len = math.ceil(sensitiveness / interval_to_len)
_highest = math.min(ta.highest(high, main_len) ,close + ta.atr(46)*4)
_lowest = math.max(ta.lowest(low, main_len),close - ta.atr(46)*4)
SR = src
trend = math.sign(nz(src[1]) - nz(SR[1]))
atr = ta.rma(ta.atr(7), 14)
SR := nz(SR[1], SR) + trend * (math.abs(nz(MA, src) - nz(MA[1], MA))) * trend_para
SR := src < SR and trend > 0 ? _highest + atr*AA : src > SR and trend < 0 ? _lowest - atr*AA : SR
trend := math.sign(src - SR)
plot_SR = trend == 1 ? SR - atr*AA : SR + atr*AA
if trend>0 and close > plot_SR
bull := true
if trend<0 and close < plot_SR
bear := true
//////////////////
//Region : Plots//
//////////////////
SR_for_fill = plot(plot_SR, color=trend != trend[1] ? na : trend > 0 ? #65D25BFF : #FE6B69FF, title='Moving Average Stop and Reverse')
plot_SR_for_fill = plot(SR,color=color.aqua, display = display.none, editable = false)
fill(SR_for_fill, plot_SR_for_fill, color=trend != trend[1] ? na : trend > 0 ? color.new(#65D25BFF, 60) : color.new(#FE6B69FF, 60))
plotshape(show_signal and (bull and not bull[1]), title= 'Long', style = shape.labelup, location = location.belowbar, color=color.new(#65D25BFF, 20), size = size.tiny, text = 'Long', textcolor = color.white)
plotshape(show_signal and (bear and not bear[1]), title= 'Short', style = shape.labeldown, location = location.abovebar, color=color.new(#FE6B69FF, 20), size = size.tiny, text = 'Short', textcolor = color.white)
//////////////////
//Region : Alert//
//////////////////
alertcondition(bull and not bull[1], title = 'Long Signal')
alertcondition(bear and not bear[1], title = 'Short Signal')
|
Multimarket Direction indicator | https://www.tradingview.com/script/QDBvyqEv/ | quanvntaoiyeuquehuongvn | https://www.tradingview.com/u/quanvntaoiyeuquehuongvn/ | 31 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © quanvntaoiyeuquehuongvn
//@version=5
indicator("Multimarket Direction indicator", overlay=true)
ema21 = ta.ema(close, 20)
ema81 = ta.ema(close, 50)
macd1 = ta.ema(close, 7)
macd2 = ta.ema(close, 12)
ema200 = ta.ema(close, 200)
downtrend = ta.crossunder(ema21, ema81)
uptrend = ta.crossover(ema21, ema81)
highest_close = ta.highest(close, 200)
lowest_close = ta.lowest(close, 200)
sp = ta.rising(lowest_close, 2)
p1PlotID = plot(ema21, color=color.blue, linewidth=1, title="Ema 21")
p2PlotID = plot(ema81, color=color.orange, linewidth=1, title="Ema 81")
plot(ema200, color=color.green, linewidth=2, title="Ema 200")
fill(p1PlotID, p2PlotID, ema21 > ema81 ? color.new(color.green, 90) : color.new(color.red, 90))
plot (highest_close, color=color.new(color.red, 20), linewidth=5)
plot (lowest_close, color=color.new(color.green, 20), linewidth=5)
buySignal = uptrend and macd1 > macd2
plotshape(buySignal ? macd1 : na, "Buy", shape.triangleup, location = location.belowbar, color = color.green, size = size.small)
sellSignal = downtrend and macd1 < macd2
plotshape(sellSignal ? macd1 : na, "Sell", shape.triangledown, location = location.abovebar, color = color.red, size = size.small) |
Asset Rotation Aperture | https://www.tradingview.com/script/T3pXj1yt-Asset-Rotation-Aperture/ | ColeGarner | https://www.tradingview.com/u/ColeGarner/ | 20 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ColeGarner
//@version=5
indicator (title = 'Asset Rotation Aperture', shorttitle = 'Asset Rotation Aperture', format=format.percent, precision=3, scale=scale.right)
// v1.0
string D01 = 'Feature Switch A'
string res = '20'
//INPUTS
//res = // '20', 'Timeframe')
oscMode = D01 // 'Oscillator Mode', [D01, D02, D03])
oscLength = 3600 //(3600, 'Length', minval=2)
smoothing = 200// "Smoothing", minval = 1)
postFilter = true
OpacA = 100
OpacB = 12
Active_1 = input.bool (true, '', inline='1', group='Main')
Color_1 = input.color (#ffa600, '', inline='1', group='Main')
Desc_1 = input.string ('BITCOIN', '', inline='1', group='Main')
Symbol_1 = input.symbol ('BINANCE:BTCUSDT', '', inline='1', group='Main')
Active_2 = input.bool (true, '', inline='2', group='Main')
Color_2 = input.color (#05d5ff, '', inline='2', group='Main')
Desc_2 = input.string ('ETHEREUM', '', inline='2', group='Main')
Symbol_2 = input.symbol ('BINANCE:ETHUSDT', '', inline='2', group='Main')
Actv_3 = input.bool (true, '', inline='3', group='Main')
Colr_3 = input.color (#fff200, '', inline='3', group='Main')
Desc_3 = input.string ('BINANCE COIN', '', inline='3', group='Main')
Smbl_3 = input.symbol ('BINANCE:BNBUSDT', '', inline='3', group='Main')
Actv_4 = input.bool (true, '', inline='4', group='Main')
Colr_4 = input.color (#ffffff, '', inline='4', group='Main')
Desc_4 = input.string ('DOGE', '', inline='4', group='Main')
Smbl_4 = input.symbol ('BINANCE:DOGEUSDT', '', inline='4', group='Main')
Actv_5 = input.bool (true, '', inline='5', group='Main')
Colr_5 = input.color (#00ff08, '', inline='5', group='Main')
Desc_5 = input.string ('SOL', '', inline='5', group='Main')
Smbl_5 = input.symbol ('BINANCE:SOLUSDT', '', inline='5', group='Main')
Actv_6 = input.bool (true, '', inline='6', group='Main')
Colr_6 = input.color (#b1a5ff,'', inline='6', group='Main')
Desc_6 = input.string ('LINK', '', inline='6', group='Main')
Smbl_6 = input.symbol ('BINANCE:LINKUSDT', '', inline='6', group='Main')
Actv_7 = input.bool (true, '',inline='7', group='Main')
Colr_7 = input.color (#ff7474, '', inline='7', group='Main')
Desc_7 = input.string ('UNI','', inline='7',group='Main')
Smbl_7 = input.symbol ('BINANCE:UNIUSDT', '',inline='7',group='Main')
Actv_8 = input.bool (true, '', inline='8', group='Main')
Colr_8 = input.color (#00981e, '', inline='8',group='Main')
Desc_8 = input.string ('RUNE','', inline='8', group='Main')
Smbl_8 = input.symbol ('BINANCE:RUNEUSDT', '', inline='8', group='Main')
// PROCESS
mode_selector (src, len, sel, filt) =>
selector = switch sel
D01 => ta.cmo(ta.mfi(src, len), (len/2))
filt ? ta.vwma (selector, smoothing) : ta.ema (selector, 6)
// Symbols Oscilator
Asset_1 = Active_1 ? request.security( Symbol_1, res, mode_selector ( close, oscLength, oscMode, postFilter) ) : na
Asset_2 = Active_2 ? request.security( Symbol_2, res, mode_selector ( close, oscLength, oscMode, postFilter) ) : na
Asset_3 = Actv_3 ? request.security( Smbl_3 , res, mode_selector ( close, oscLength, oscMode, postFilter) ) : na
Asset_4 = Actv_4 ? request.security( Smbl_4 , res, mode_selector ( close, oscLength, oscMode, postFilter) ) : na
Asset_5 = Actv_5 ? request.security( Smbl_5 , res, mode_selector ( close, oscLength, oscMode, postFilter) ) : na
Asset_6 = Actv_6 ? request.security( Smbl_6 , res, mode_selector ( close, oscLength, oscMode, postFilter) ) : na
Asset_7 = Actv_7 ? request.security( Smbl_7 , res, mode_selector ( close, oscLength, oscMode, postFilter) ) : na
Asset_8 = Actv_8 ? request.security( Smbl_8 , res, mode_selector ( close, oscLength, oscMode, postFilter) ) : na
// PLOTS
zeroPlot = plot (0, editable=false, display=display.none)
Plot_1 = plot (Asset_1, '', color.new (Color_1, 100 - OpacA), 1)
Fill_1 = plot (Asset_1, '', color.new (Color_1, 100 - OpacB), 0, plot.style_area)
Plot_2 = plot (Asset_2, '', color.new (Color_2, 100 - OpacA), 1)
Fill_2 = plot (Asset_2, '', color.new (Color_2, 100 - OpacB), 0, plot.style_area)
Plot_3 = plot (Asset_3, '', color.new (Colr_3, 100 - OpacA), 1)
Fill_3 = plot (Asset_3, '', color.new (Colr_3, 100 - OpacB), 0, plot.style_area)
Plot_4 = plot (Asset_4, '', color.new (Colr_4, 100 - OpacA), 1)
Fill_4 = plot (Asset_4, '', color.new (Colr_4, 100 - OpacB), 0, plot.style_area)
Plot_5 = plot (Asset_5, '', color.new (Colr_5, 100 - OpacA), 1)
Fill_5 = plot (Asset_5, '', color.new (Colr_5, 100 - OpacB), 0, plot.style_area)
Plot_6 = plot (Asset_6, '', color.new (Colr_6, 100 - OpacA), 1)
Fill_6 = plot (Asset_6, '', color.new (Colr_6, 100 - OpacB), 0, plot.style_area)
Plot_7 = plot (Asset_7, '', color.new (Colr_7, 100 - OpacA), 1)
Fill_7 = plot (Asset_7, '', color.new (Colr_7, 100 - OpacB), 0, plot.style_area)
Plot_8 = plot (Asset_8, '', color.new (Colr_8, 100 - OpacA), 1)
Fill_8 = plot (Asset_8, '', color.new (Colr_8, 100 - OpacB), 0, plot.style_area)
// LABELS
var label Label_1 = Active_1 ? label.new(bar_index+8, Asset_1, Desc_1, xloc = xloc.bar_index, style=label.style_label_left, textcolor=color.black, color=Color_1, size=size.small) : na
var label Label_2 = Active_2 ? label.new(bar_index+8, Asset_2, Desc_2, xloc = xloc.bar_index, style=label.style_label_left, textcolor=color.black, color=Color_2, size=size.small) : na
var label Label_3 = Actv_3 ? label.new(bar_index+8, Asset_3, Desc_3, xloc = xloc.bar_index, style=label.style_label_left, textcolor=color.black, color=Colr_3, size=size.small) : na
var label Label_4 = Actv_4 ? label.new(bar_index+8, Asset_4, Desc_4, xloc = xloc.bar_index, style=label.style_label_left, textcolor=color.black, color=Colr_4, size=size.small) : na
var label Label_5 = Actv_5 ? label.new(bar_index+8, Asset_5, Desc_5, xloc = xloc.bar_index, style=label.style_label_left, textcolor=color.black, color=Colr_5, size=size.small) : na
var label Label_6 = Actv_6 ? label.new(bar_index+8, Asset_6, Desc_6, xloc = xloc.bar_index, style=label.style_label_left, textcolor=color.black, color=Colr_6, size=size.small) : na
var label Label_7 = Actv_7 ? label.new(bar_index+8, Asset_7, Desc_7, xloc = xloc.bar_index, style=label.style_label_left, textcolor=color.black, color=Colr_7, size=size.small) : na
var label Label_8 = Actv_8 ? label.new(bar_index+8, Asset_8, Desc_8, xloc = xloc.bar_index, style=label.style_label_left, textcolor=color.black, color=Colr_8, size=size.small) : na
label.set_xy(Label_1, bar_index+4, Asset_1)
label.set_xy(Label_2, bar_index+4, Asset_2)
label.set_xy(Label_3, bar_index+4, Asset_3)
label.set_xy(Label_4, bar_index+4, Asset_4)
label.set_xy(Label_5, bar_index+4, Asset_5)
label.set_xy(Label_6, bar_index+4, Asset_6)
label.set_xy(Label_7, bar_index+4, Asset_7)
label.set_xy(Label_8, bar_index+4, Asset_8) |
Cumulative Volume Price | https://www.tradingview.com/script/1xLJDMgP-Cumulative-Volume-Price/ | VanHe1sing | https://www.tradingview.com/u/VanHe1sing/ | 33 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © VanHe1sing
//@version=5
indicator("Cumulative Volume Price")
//Inputs
length = input.int(20, "Length")
length_ = input.int(2, "Length of Rise")
//Variables
var cumvol = 0.0
var cumprice = 0.0
cumvol += nz(volume)
cumprice += nz(close)
//Calculations
net = (cumprice * volume) / cumvol
net_ = ta.rising(ta.ema(close, length), length_) ? net : -net
plot(net_, style = plot.style_histogram, color = net_ > 0 ? color.green : color.red)
|
Cumulative New Highs - New Lows | https://www.tradingview.com/script/PFbkrnm5-Cumulative-New-Highs-New-Lows/ | F30G20 | https://www.tradingview.com/u/F30G20/ | 33 | study | 5 | MPL-2.0 | // This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © F30G20
//@version=5
indicator('Cumulative New Highs - New Lows', shorttitle='Cum. Hi-Lo', overlay=false, precision=0)
//Inputs
indexChoice = input.string(title='Index', defval='Total Stock Market', options=['Total Stock Market' , 'NYSE Composite' , 'Nasdaq Composite' , 'S&P 500', 'Nasdaq 100' , 'Russell 2000'])
maLength = input(20, title='Moving Average Length')
//Data & Calculation
indexData = indexChoice == 'Nasdaq 100' ? request.security('NADC', 'D', close) :
indexChoice == 'S&P 500' ? request.security('MADP', 'D', close) :
indexChoice == 'NYSE Composite' ? request.security('MAHN', 'D', close) - request.security('MALN', 'D', close) :
indexChoice == 'Nasdaq Composite' ? request.security('MAHQ', 'D', close) - request.security('MALQ', 'D', close) :
indexChoice == 'Russell 2000' ? request.security('MADC', 'D', close) : request.security('MAHX', 'D', close) - request.security('MALX', 'D', close)
cumulativeIndex = ta.cum(indexData)
lineColor = cumulativeIndex > cumulativeIndex[1] ? color.green : cumulativeIndex < cumulativeIndex[1] ? color.red : color.gray
movingAverage = ta.sma(cumulativeIndex, maLength)
//Plots
plot(cumulativeIndex, title='Cumulative Index Line', color=lineColor)
plot(movingAverage, title='Moving Average', color=color.rgb(33, 149, 243, 40))
|
ObjectHelpers | https://www.tradingview.com/script/erK33jZa-ObjectHelpers/ | FFriZz | https://www.tradingview.com/u/FFriZz/ | 5 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © FFriZz
frizlabz =
"\n
███████╗███████╗██████╗ ██╗███████╗███████╗
██╔════╝██╔════╝██╔══██╗██║╚══███╔╝╚══███╔╝
█████╗ █████╗ ██████╔╝██║ ███╔╝ ███╔╝
██╔══╝ ██╔══╝ ██╔══██╗██║ ███╔╝ ███╔╝
██║ ██║ ██║ ██║██║███████╗███████╗
'█████╗████╗ █╗████╗ █╗'╝╚═'███╗ ████╗ ████╗
'██╔═══█╔══█╗█║╚══█║ █║ █╔══█╗█╔══█╗╚══█║
'████╗ ████╔╝█║ █╔╝ █║ █████║████╔╝ █╔╝
'██╔═╝ █╔══█╗█║ █╔╝ █║ █╔══█║█╔══█╗ █╔╝
'██║ █║ █╗█║█╔╝ █║ █║ █║█║ █║█╔╝
'██║ █║ █║█║█████╗█████╗█║ █║████║ ████╗
'╚═╝ ╚╝ ╚╝╚╝╚════╝╚════╝╚╝ ╚╝╚═══╝ ╚═══╝
Line | Box | Label | Linefill
Maker | Setter | Getter
import FFriZz/ObjectHelpers/1 as obj
"
//@version=5
// @description Line | Box | Label | Linefill -- Maker, Setter, Getter Library
// TODO: add table functionality
library("ObjectHelpers")
import FFriZz/FrizLabz_Time_Utility_Methods/6 as Time
// import FFriZz/FrizBug/17 as p
// @function Get all of the location variables for `line`, `box`, `label` objects or the line objects from a `linefill`
//***
//## Overloaded
//***
//```
//method Get(line Line) => [int x1, float y1, int x2, float y2]
//```
//### Params
//- **Line** `line` - line object | `required`
//***
//```
//method Get(box Box) => [int left, float top, int right, float bottom]
//```
//### Params
//- **Box** `box` - box object | `required`
//***
//```
//method Get(label Label) => [int x, float y, string _text]
//```
//### Paramas
//- **Label** `label` - label object | `required`
//***
//```
//method Get(linefill Linefill) => [line line1, line line2]
//```
//### Params
//- **Linefill** `linefill` - linefill object | `required`
// @param line `line` - line object
// @returns [`int x1`,`float y1`,`int x2`,`float y2`]
export method Get(line Line) =>
x1 = Line.get_x1()
x2 = Line.get_x2()
y1 = Line.get_y1()
y2 = Line.get_y2()
[x1,y1,x2,y2]
// @function Gets the location paramaters of a Box
// @param Box `box` - box object
// @returns [`int left`,`float top`,`int right`,`float bottom`]
export method Get(box Box) =>
left = Box.get_left()
top = Box.get_top()
right = Box.get_right()
bottom = Box.get_bottom()
[left,top,right,bottom]
// @function Gets the `x`, `y`, `text` of a Label
// @param Label `label` - label object
// @returns [`int x`,`float y`,`string _text`]
export method Get(label Label) =>
txt = Label.get_text()
x = Label.get_x()
y = Label.get_y()
[x,y,txt]
// @function Gets `line 1`, `line 2` from a Linefill
// @param Linefill `linefill` - linefill object
// @returns [`line line1`,`line line2`]
export method Get(linefill Linefill) =>
line line1 = Linefill.get_line1()
line line2 = Linefill.get_line2()
[line1,line2]
// @function Set the `x1`, `x2` of a line
//***
//### Params
//- **Line** `line` - line object | `required`
//- **x1** `int` - value to set x1 | `required`
//- **x2** `int` - value to set x2 | `required`
// @param Line `line` - line object
// @param x1 `int` - value to set x1
// @param x2 `int` - value to set x2
// @returns `line`
export method Set_x(line Line, int x1, int x2) =>
if not na(Line)
Line.set_x1(x1)
Line.set_x2(x2)
Line
// @function Set `y1`, `y2` of a line
//***
//### Params
//- **Line** `line` - line object | `required`
//- **y1** `float` - value to set y1 | `required`
//- **y2** `float` - value to set y2 | `required`
// @param Line `line` - line object
// @param y1 `float` - value to set y1
// @param y2 `float` - value to set y2
// @returns `line`
export method Set_y(line Line, float y1, float y2) =>
if not na(Line)
Line.set_y1(y1)
Line.set_y2(y2)
Line
// @function Set all params for `line`, `box`, `label`, `linefill` objects with 1 function
//***
//## Overloaded
//***
//```
//method Set(line Line, int x1=na, float y1=na, int x2=na, float y2=na,string xloc=na,string extend=na,color color=na,string style=na,int width=na,bool update=na) => line
//```
//### Params
//- **Line** `line` - line object | `required`
//- **x1** `int` - value to set x1
//- **y1** `float` - value to set y1
//- **x2** `int` - value to set x2
//- **y2** `float` - value to set y2
//- **xloc** `int` - value to set xloc
//- **yloc** `int` - value to set yloc
//- **extend** `string` - value to set extend
//- **color** `color` - value to set color
//- **style** `string` - value to set style
//- **width** `int` - value to set width
//- **update** `bool` - if true will update line side of box to next bar ever new bar
//***
//```
//method Set(box Box,int left=na,float top=na,int right=na, float bottom=na,color bgcolor=na,color border_color=na,string border_style=na,int border_width=na,string extend=na,string txt=na,color text_color=na,string text_font_family=na,string text_halign=na,string text_valign=na,string text_wrap=na,bool update=false) => box
//```
//### Params
//- **Box** `box` - box object
//- **left** `int` - value to set left
//- **top** `float` - value to set top
//- **right** `int` - value to set right
//- **bottom** `float` - value to set bottom
//- **bgcolor** `color` - value to set bgcolor
//- **border_color** `color` - value to set border_color
//- **border_style** `string` - value to set border_style
//- **border_width** `int` - value to set border_width
//- **extend** `string` - value to set extend
//- **txt** `string` - value to set _text
//- **text_color** `color` - value to set text_color
//- **text_font_family** `string` - value to set text_font_family
//- **text_halign** `string` - value to set text_halign
//- **text_valign** `string` - value to set text_valign
//- **text_wrap** `string` - value to set text_wrap
//- **update** `bool` - if true will update right side of box to next bar ever new bar
//***
//```
//method Set(label Label,int x=na,float y=na, string txt=na,string xloc=na,color color=na,color textcolor=na,string size=na,string style=na,string textalign=na,string tooltip=na,string text_font_family=na,bool update=false) => label
//```
//### Paramas
//- **Label** `label` - label object
//- **x** `int` - value to set x
//- **y** `float` - value to set y
//- **txt** `string` - value to set text add`"+++"` to the _text striing to have the current label text concatenated to the location of the "+++")
//- **textcolor** `color` - value to set textcolor
//- **size** `string` - value to set size
//- **style** `string` - value to set style (use "flip" ,as the style to have label flip to top or bottom of bar depending on if open > close and vice versa)
//- **text_font_family** `string` - value to set text_font_family
//- **textalign** `string` - value to set textalign
//- **tooltip** `string` - value to set tooltip
//- **update** `bool` - if true will update label to next bar ever new bar
//***
//```
//method Set(linefill Linefill=na,line line1=na,line line2=na,color color=na) => linefill
//```
//### Params
//- **linefill** `linefill` - linefill object
//- **line1** `line` - line object
//- **line2** `line` - line object
//- **color** `color` - color
// @param Line `line` - line object | `required`
// @param x1 `int` - value to set x1
// @param y1 `float` - value to set y1
// @param x2 `int` - value to set x2
// @param y2 `float` - value to set y2
// @param xloc `int` - value to set xloc
// @param yloc `int` - value to set yloc
// @param extend `string` - value to set extend
// @param color `color` - value to set color
// @param style `string` - value to set style
// @param width `int` - value to set width
// @param update `bool` - if true will move x2 to next bar ever new bar
// @returns `line`
export method
Set(
line Line,
int x1=na,
float y1=na,
int x2=na,
float y2=na,
string xloc=na,
string extend=na,
color color=na,
string style=na,
int width=na,
bool update=na
) =>
if not na(Line)
M = 1000000
get_x1 = Line.get_x1()
get_x2 = Line.get_x2()
int _x1 = na(x1) ? get_x1 : x1
int _x2 = na(x2) ? get_x2 : x2
if not na(xloc)
if xloc == xloc.bar_time or xloc == xloc.bar_index
na
else
runtime.error("Set xloc to either xloc.bar_time or xloc.bar_index for Line.set()")
if xloc == xloc.bar_time
Line.set_xloc(_x1 > M ?
_x1:
Time.index_to_time(_x1),
_x2 > M ?
_x2:
Time.index_to_time(_x2),
xloc)
if xloc == xloc.bar_index
Line.set_xloc(_x1 > M ?
Time.time_to_index(_x1):
_x1,
_x2 > M ?
Time.time_to_index(_x2):
_x2,
xloc)
else if update and na(x2)
if _x2 > M
Line.set_x2(_x2+Time.bar_time())
if _x2 < M
Line.set_x2(_x2+1)
else if not na(x2)
Line.set_x2(x2)
else if (_x1 < M and get_x1 > M) and not na(get_x1) and not na(_x1)
runtime.error("Change x1 param to time based input or use xloc param")
else if (_x2 < M and get_x2 > M) and not na(get_x2) and not na(_x2)
runtime.error("Change x2 param to time based input or use xloc param")
else if (_x1 > M and get_x1 < M) and not na(get_x1) and not na(_x1)
runtime.error("Change x1 param to bar_index based input or use xloc param")
else if (_x2 > M and get_x2 < M) and not na(get_x2) and not na(_x2)
runtime.error("Change x2 param to bar_index based input or use xloc param")
if x1 and na(xloc)
Line.set_x1(x1)
if y1
Line.set_y1(y1)
if y2
Line.set_y2(y2)
if not na(extend)
Line.set_extend(extend)
if not na(color)
Line.set_color(color)
if not na(style)
Line.set_style(style)
if not na(width)
Line.set_width(width)
Line
// @function Set all params of a box with 1 function
// @param Box `box` - box object | `required`
// @param left `int` - value to set left
// @param top `float` - value to set top
// @param right `int` - value to set right
// @param bottom `float` - value to set bottom
// @param bgcolor `color` - value to set bgcolor
// @param border_color `color` - value to set border_color
// @param border_style `string` - value to set border_style
// @param border_width `int` - value to set border_width
// @param extend `string` - value to set extend
// @param txt `string` - value to set _text
// @param text_color `color` - value to set text_color
// @param text_font_family `string` - value to set text_font_family
// @param text_halign `string` - value to set text_halign
// @param text_valign `string` - value to set text_valign
// @param text_wrap `string` - value to set text_wrap
// @param update `bool` - if true will update right side of box to next bar every new bar
// @returns `box`
export method
Set(
box Box,
int left=na,
float top=na,
int right=na,
float bottom=na,
color bgcolor=na,
color border_color=na,
string border_style=na,
int border_width=na,
string extend=na,
string txt=na,
color text_color=na,
string text_font_family=na,
string text_halign=na,
string text_valign=na,
string text_wrap=na,
bool update=false
) =>
if not na(Box)
M = 1000000
get_right = Box.get_right()
get_left = Box.get_left()
int _left = na(left) ? get_left : left
int _right = na(right) ? get_right : right
if (_left < M and get_left > M) and not na(get_left) and not na(_left)
runtime.error("Change left param to time based input")
else if (_right < M and get_right > M) and not na(get_right) and not na(_right)
runtime.error("Change right param to time based input")
else if (_left > M and get_left < M) and not na(get_left) and not na(_left)
runtime.error("Change left param to bar_index based input")
else if (_right > M and get_right < M) and not na(get_right) and not na(_right)
runtime.error("Change right param to bar_index based input")
else
if update and na(right)
if get_right > M
Box.set_right(_right+Time.bar_time())
else
Box.set_right(_right+1)
if not na(right)
Box.set_right(right)
if _left
Box.set_left(_left)
if top
Box.set_top(top)
if bottom
Box.set_bottom(bottom)
if not na(bgcolor)
Box.set_bgcolor(bgcolor)
if not na(border_color)
Box.set_border_color(border_color)
if not na(border_style)
Box.set_border_style(border_style)
if border_width
Box.set_border_width(border_width)
if not na(txt)
Box.set_text(txt)
if not na(extend)
Box.set_extend(extend)
if not na(text_color)
Box.set_text_color(text_color)
if not na(text_halign)
Box.set_text_halign(text_halign)
if not na(text_valign)
Box.set_text_valign(text_valign)
if not na(text_font_family)
Box.set_text_font_family(text_font_family)
if not na(text_wrap)
Box.set_text_wrap(text_wrap)
Box
// @function Set all params of a label with 1 function
// @param Label `label` | `required`
// @param x `int` - value to set x
// @param y `float` - value to set y
// @param txt `string` - value to set text add`"+++"` to the _text striing to have the current label text concatenated to the location of the "+++")
// @param textcolor `color` - value to set textcolor
// @param size `string` - value to set size
// @param style `string` - value to set style (use "flip" ,as the style to have label flip to top or bottom of bar depending on if open > close and vice versa)
// @param text_font_family `string` - value to set text_font_family
// @param textalign `string` - value to set textalign
// @param tooltip `string` - value to set tooltip
// @param update `bool` - if true will move label ahead 1 bar every new bar
// @returns `label`
export method
Set(
label Label,
int x=na,
float y=na,
string txt=na,
string xloc=na,
color color=na,
color textcolor=na,
string size=na,
string style=na,
string textalign=na,
string tooltip=na,
string text_font_family=na,
bool update=false
) =>
if not na(Label)
M = 1000000
[get_x, get_y, get_text] = Label.Get()
_x = na(x) ? get_x : x
Txt = if not na(txt)
if str.contains(txt, "+++")
str.replace_all(txt, "+++", get_text)
else
txt
else
na
if not na(xloc)
if xloc == xloc.bar_time or xloc == xloc.bar_index
na
else
runtime.error("Set xloc to either xloc.bar_time or xloc.bar_index for Label.set()")
if xloc == xloc.bar_time
Label.set_xloc(_x > M ?
_x:
Time.index_to_time(_x),
xloc)
if xloc == xloc.bar_index
Label.set_xloc(_x > M ?
Time.time_to_index(x):
_x,
xloc)
else if _x < M and get_x > M
runtime.error("Change x param to time based input or set xloc param")
else if _x > M and get_x < M
runtime.error("Change x param to bar_index based input or set xloc param")
else if na(xloc)
if update and na(x)
if _x > M
Label.set_x(_x+1)
else
Label.set_x(_x+Time.bar_time())
if not na(x)
Label.set_x(x)
if y
Label.set_y(y)
if not na(txt)
Label.set_text(Txt)
if not na(color)
Label.set_color(color)
if not na(textcolor)
Label.set_textcolor(textcolor)
if not na(size)
Label.set_size(size)
if style == "flip" and close > open
Label.set_style(label.style_label_down), Label.set_yloc(yloc.abovebar)
else if style == "flip" and close < open
Label.set_style(label.style_label_up), Label.set_yloc(yloc.belowbar)
if not na(style) and style != "flip"
Label.set_style(style), Label.set_yloc(yloc.price)
if not na(textalign)
Label.set_textalign(textalign)
if not na(tooltip)
Label.set_tooltip(tooltip)
if not na(text_font_family)
Label.set_text_font_family(text_font_family)
Label
// @function change the 1 or 2 of the lines in a linefill object
// @param linefill `linefill` - linefill object | `required`
// @param line1 `line` - line object
// @param line2 `line` - line object
// @param color `color` - color
// @returns `linefill`
export method Set(linefill Linefill=na, line line1=na, line line2=na, color color=na) =>
if not na(Linefill)
_linefill = Linefill
line _line1 = Linefill.get_line1()
line _line2 = Linefill.get_line2()
color _color = na(color) ? #0000ff4b : color
if not na(line1) and not na(line2)
_linefill := linefill.new(line1,line2,color)
else if na(line1)
_linefill := linefill.new(_line1,line2,color)
else if na(line2)
_linefill := linefill.new(line1,_line2,color)
if not na(color)
linefill.set_color(_linefill,_color)
Linefill.delete()
_linefill
// @function Similar to `line.new()` but optimized for convenience
//***
//### Params
//- **x1** `int` - value to set
//- **y1** `float` - value to set
//- **x2** `int` - value to set
//- **y2** `float` - value to set
//- **extend** `string` - extend value to set line
//- **color** `color` - color to set line
//- **style** `string` - style to set line
//- **width** `int` - width to set line
// @param x1 `int` - value to set
// @param y1 `float` - value to set
// @param x2 `int` - value to set
// @param y2 `float` - value to set
// @param extend `string` - extend value to set line
// @param color `color` - color to set line
// @param style `string` - style to set line
// @param width `int` - width to set line
// @returns `line`
export method
Line(
int x1 = na,
float y1 = na,
int x2 = na,
float y2 = na,
string extend = extend.none,
color color = chart.fg_color,
string style = line.style_solid,
int width = 1
) =>
xloc = na(x1) ? xloc.bar_index : x1>1000000 ? xloc.bar_time : xloc.bar_index
var Line = line.new(
xloc = xloc,
x1 = x1,
y1 = y1,
x2 = x2,
y2 = y2,
extend = extend,
color = color,
style = style,
width = width)
// @function similar to `box.new()` but optimized for convenience
//***
//### Params
//- **left** `int` - value to set
//- **top** `float` - value to set
//- **right** `int` - value to set
//- **bottom** `float` - value to set
//- **extend** `string` - extend value to set box
//- **border_color** `color` - color to set border
//- **bgcolor** `color` - color to set background
//- **text_color** `color` - color to set text
//- **border_width** `int` - width to set border
//- **border_style** `string` - style to set border
//- **txt** `string` - text to set
//- **text_halign** `string` - horizontal alignment to set text
//- **text_valign** `string` - vertical alignment to set text
//- **text_size** `string` - size to set text
//- **text_wrap** `string` - wrap to set text
// @param left `int` - value to set
// @param top `float` - value to set
// @param right `int` - value to set
// @param bottom `float` - value to set
// @param extend `string` - extend value to set box
// @param border_color `color` - color to set border
// @param bgcolor `color` - color to set background
// @param text_color `color` - color to set text
// @param border_width `int` - width to set border
// @param border_style `string` - style to set border
// @param txt `string` - text to set
// @param text_halign `string` - horizontal alignment to set text
// @param text_valign `string` - vertical alignment to set text
// @param text_size `string` - size to set text
// @param text_wrap `string` - wrap to set text
// @returns `box`
export method
Box(
int left = na,
float top = na,
int right = na,
float bottom = na,
string extend = extend.none,
color border_color = chart.fg_color,
color bgcolor = na,
color text_color = chart.bg_color,
int border_width = 1,
string border_style = line.style_solid,
string txt = na,
string text_halign = text.align_center,
string text_valign = text.align_center,
string text_size = size.normal,
string text_wrap = text.wrap_none
) =>
xloc = na(left) ? xloc.bar_index : left>1000000 ? xloc.bar_time : xloc.bar_index
var Box = box.new(
xloc = xloc,
left = left,
top = top,
right = right,
bottom = bottom,
border_color = border_color,
border_width = border_width,
border_style = border_style,
extend = extend,
bgcolor = bgcolor,
text = txt,
text_size = text_size,
text_color = text_color,
text_halign = text_halign,
text_valign = text_valign,
text_wrap = text_wrap)
// @function Similar to `label.new()` but optimized for convenience
//***
//### Params
//- **txt** `string` - string to set
//- **x** `int` - value to set
//- **y** `float` - value to set
//- **yloc** `string` - y location to set
//- **color** `color` - label color to set
//- **textcolor** `color` - text color to set
//- **style** `string` - style to set
//- **size** `string` - size to set
//- **textalign** `string` - text alignment to set
//- **text_font_family** `string` - font family to set
//- **tooltip** `string` - tooltip to set
// @param txt `string` - string to set
// @param x `int` - value to set
// @param y `float` - value to set
// @param yloc `string` - y location to set
// @param color `color` - label color to set
// @param textcolor `color` - text color to set
// @param style `string` - style to set
// @param size `string` - size to set
// @param textalign `string` - text alignment to set
// @param text_font_family `string` - font family to set
// @param tooltip `string` - tooltip to set
// @returns `label`
export method
Label(
string txt = '',
int x = na,
float y = na,
string yloc = yloc.price,
color color = chart.fg_color,
color textcolor = chart.bg_color,
string style = label.style_label_down,
string size = size.normal,
string textalign = text.align_center,
string text_font_family = font.family_default,
string tooltip = na
) =>
xloc = na(x) ? xloc.bar_index : x>1000000 ? xloc.bar_time : xloc.bar_index
var Label = label.new(
xloc = xloc,
x = x,
y = y,
text = txt,
yloc = yloc,
color = color,
style = style,
textcolor = textcolor,
size = size,
textalign = textalign,
tooltip = tooltip,
text_font_family = text_font_family)
// if barstate.islast
// var LINE = Line(time[100],low*0.95,time,low*0.95)
// .print("BEFORE set()", pos="1")
// .Set(bar_index-30,x2=bar_index,color=color.rgb(82, 114, 255),width=6,xloc=xloc.bar_index,update=true)
// .print("AFTER set()",pos="2")
// // var BOX = Box(time[30],high,time[10],low)
// // .print("BEFORE set()", pos="4")
// // .set(top=high,bottom=low,txt="hello world",bgcolor=#000000,border_color=color.red,border_style=line.style_dashed,update=true)
// // .print("AFTER set()",pos="5")
// var LABEL = Label("Pine",time[30],high*1.05)
// .print("BEFORE set()", pos="7")
// .Set(x=bar_index,txt="+++script",xloc=xloc.bar_index,textcolor=#00ff00,color=#000000,size=size.large,style=label.style_label_left,update=true)
// .print("AFTER set()",pos="8")
// TODO: figure this out
// case1(_x1, _x2, M) => _x1 > M and _x2 < M
// case2(_x1, _x2, M) => _x1 < M and _x2 > M
// case3(_x1, _x2, M) => _x1 > M and _x2 > M
// case4(_x1, _x2, M) => _x1 < M and _x2 < M
// convertTime(_x1, _x2, get_x1, get_x2, M) =>
// int newX1 = na, int newX2 = na, string xloc = na
// if case1(_x1, _x2, M)
// newX2 := Time.time_to_index(_x2)
// xloc := xloc.bar_index
// else if case2(_x1, _x2, M)
// newX2 := Time.index_to_time(_x2)
// xloc := xloc.bar_time
// else if case3(_x1, _x2, M)
// newX1 := Time.time_to_index(_x1)
// xloc := xloc.bar_index
// else if case4(_x1, _x2, M)
// newX1 := Time.index_to_time(_x1)
// xloc := xloc.bar_time
// [newX1, newX2, xloc] |
TradeTracker | https://www.tradingview.com/script/4o5WNuRl-TradeTracker/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 45 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
// @description Simple Library for tracking trades
library("TradeTracker", overlay = true)
// @type Has the constituents to track trades generated by any method.
// @field direction Trade direction. Positive values for long and negative values for short trades
// @field initialEntry Initial entry price. This value will not change even if the entry is changed in the lifecycle of the trade
// @field entry Updated entry price. Allows variations to initial calculated entry. Useful in cases of trailing entry.
// @field initialStop Initial stop. Similar to initial entry, this is the first calculated stop for the lifecycle of trade.
// @field stop Trailing Stop. If there is no trailing, the value will be same as that of initial trade
// @field targets array of target values.
// @field startBar bar index of starting bar. Set by default when object is created. No need to alter this after that.
// @field endBar bar index of last bar in trade. Set by tracker on each execution
// @field startTime time of the start bar. Set by default when object is created. No need to alter this after that.
// @field endTime time of the ending bar. Updated by tracking method.
// @field status Integer parameter to track the status of the trade
// @field retest Boolean parameter to notify if there was retest of the entry price
export type Trade
int id
int direction
float initialEntry
float entry
float initialStop
float stop
array<float> targets
int startBar = bar_index
int endBar = bar_index
int startTime = time
int endTime = time
int status = 0
bool retest = false
// @function tracks trade when called on every bar
// @param this Trade object
// @returns current Trade object
export method track(Trade this)=>
if(this.status != -1 and this.status != this.targets.size()+1)
stopValue = this.direction > 0? low : high
targetValue = this.direction > 0? high : low
stopped = stopValue * this.direction <= this.stop * this.direction
newStatus = this.status
if (targetValue >= this.entry)
newStatus +=1
for target in this.targets
if(targetValue*this.direction >= target * this.direction)
newStatus+=1
this.retest := this.status >= 1 and (stopValue * this.direction <= this.entry * this.direction) ? true : this.retest
this.status := stopped? -1 : math.max(this.status, newStatus)
this.endBar := bar_index
this.endTime := time
this
|
MathEasingFunctions | https://www.tradingview.com/script/o3oYFWcE-MathEasingFunctions/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 31 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description A collection of Easing functions.
//
// Easing functions are commonly used for smoothing actions over time, They are used to smooth out the sharp edges
// of a function and make it more pleasing to the eye, like for example the motion of a object through time.
// Easing functions can be used in a variety of applications, including animation, video games, and scientific
// simulations. They are a powerful tool for creating realistic visual effects and can help to make your work more
// engaging and enjoyable to the eye.
// ---
// Includes functions for ease in, ease out, and, ease in and out, for the following constructs:
// sine, quadratic, cubic, quartic, quintic, exponential, elastic, circle, back, bounce.
// ---
// Reference:
// https://easings.net/#
// https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/easing-functions
library("MathEasingFunctions")
//#region 0: Variables:
//#region 0.0: Numeric Constants:
float __C1 = 1.70158
float __C2 = __C1 * 1.525
float __C3 = __C1 + 1.0
float __C4 = (2.0 * math.pi) / 3.0
float __C5 = (2.0 * math.pi) / 4.5
float __N1 = 7.5625
float __D1 = 2.75
//#endregion 0.0
//#region 0.1: List of effect names:
string __E0 = 'ease-in'
string __E1 = 'ease-out'
string __E2 = 'ease-in-out'
string __EN = str.format('[{0}, {1}, {2}]', __E0, __E1, __E2)
//#endregion 0.1
//#region 0.2: List of formula names:
string __F0 = 'sine'
string __F1 = 'quadratic'
string __F2 = 'cubic'
string __F3 = 'quartic'
string __F4 = 'quintic'
string __F5 = 'exponential'
string __F6 = 'circle'
string __F7 = 'back'
string __F8 = 'elastic'
string __F9 = 'bounce'
string __FN = str.format('[{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}]', __F0, __F1, __F2, __F3, __F4, __F5, __F6, __F7, __F8, __F9)
//#endregion 0.2
//#region 0.3: Linear value for testing:
bool restrict = input.bool(false, 'Restric testing value:')
float v = (restrict ? -50 + (bar_index % 100) : -50 + bar_index) * 0.01
if v > 1.5
v := float(na)
plot(bar_index%3==0?v:na, 'value', style = plot.style_linebr)
//#endregion 0.3
//#endregion 0
//#region 1: Functions:
//#region 1.0: Sine:
//#region 1.0.0: Ease in:
// @function Sinusoidal function, the position over elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_sine_unbound (float v) =>
1.0 - math.cos((v * math.pi) / 2.0)
// @function Sinusoidal function, the position over elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_sine (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_sine_unbound(v)
// plot(ease_in_sine(v))
//#endregion 1.0.0
//#region 1.0.1: Ease out:
// @function Sinusoidal function, the position over elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_sine_unbound (float v) =>
math.sin((v * math.pi) / 2.0)
// @function Sinusoidal function, the position over elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_sine (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_out_sine_unbound(v)
// plot(ease_out_sine(v))
//#endregion 1.0.1
//#region 1.0.2: Ease in out:
// @function Sinusoidal function, the position over elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_sine_unbound (float v) =>
-(math.cos(math.pi * v) - 1.0) * 0.5
// @function Sinusoidal function, the position over elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_sine (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_out_sine_unbound(v)
// plot(ease_in_out_sine(v))
//#endregion 1.0.2
//#endregion 1.0
//#region 1.1: Quadratic:
//#region 1.1.0: Ease in:
// @function Quadratic function, the position equals the square of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_quad_unbound (float v) =>
math.pow(v, 2)
// @function Quadratic function, the position equals the square of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_quad (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_quad_unbound(v)
// plot(ease_in_quad_unbound(v), "Unbound", #00aaff)
// plot(ease_in_quad(v), "Bound", #0011ff)
//#endregion 1.1.0
//#region 1.1.1: Ease out:
// @function Quadratic function, the position equals the square of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_quad_unbound (float v) =>
1.0 - math.pow(1.0 - v, 2)
// @function Quadratic function, the position equals the square of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_quad (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_out_quad_unbound(v)
// plot(ease_out_quad_unbound(v), "Unbound", #00aaff)
// plot(ease_out_quad(v), "Bound", #0011ff)
//#endregion 1.1.1
//#region 1.1.2: Ease in out:
// @function Quadratic function, the position equals the square of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_quad_unbound (float v) =>
if v < 0.5
2.0 * math.pow(v, 2)
else
1.0 - math.pow(-2.0 * v + 2.0, 2) * 0.5
// @function Quadratic function, the position equals the square of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_quad (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_out_quad_unbound(v)
// plot(ease_in_out_quad_unbound(v), "Unbound", #00aaff)
// plot(ease_in_out_quad(v), "Bound", #0011ff)
//#endregion 1.1.2
//#endregion 1.1
//#region 1.2: Cubic:
//#region 1.2.0: Ease in:
// @function Cubic function, the position equals the cube of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_cubic_unbound (float v) =>
math.pow(v, 3)
// @function Cubic function, the position equals the cube of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_cubic (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_cubic_unbound(v)
// plot(ease_in_cubic_unbound(v), "Unbound", #00aaff)
// plot(ease_in_cubic(v), "Bound", #0011ff)
//#endregion 1.2.0
//#region 1.2.1: Ease out:
// @function Cubic function, the position equals the cube of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_cubic_unbound (float v) =>
1.0 - math.pow(1.0 - v, 3)
// @function Cubic function, the position equals the cube of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_cubic (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_out_cubic_unbound(v)
// plot(ease_out_cubic_unbound(v), "Unbound", #00aaff)
// plot(ease_out_cubic(v), "Bound", #0011ff)
//#endregion 1.2.1
//#region 1.2.2: Ease in out:
// @function Cubic function, the position equals the cube of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_cubic_unbound (float v) =>
v < 0.5 ? 4.0 * math.pow(v, 3) : 1.0 - math.pow(-2.0 * v + 2.0, 3) / 2
// @function Cubic function, the position equals the cube of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_cubic (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_out_cubic_unbound(v)
// plot(ease_in_out_cubic_unbound(v), "Unbound", #00aaff)
// plot(ease_in_out_cubic(v), "Bound", #0011ff)
//#endregion 1.2.2
//#endregion 1.2
//#region 1.3: Quartic:
//#region 1.3.0: Ease in:
// @function Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_quart_unbound (float v) =>
math.pow(v, 4)
// @function Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_quart (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_quart_unbound(v)
// plot(ease_in_quart_unbound(v), "Unbound", #00aaff)
// plot(ease_in_quart(v), "Bound", #0011ff)
//#endregion 1.3.0
//#region 1.3.1: Ease out:
// @function Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_quart_unbound (float v) =>
1.0 - math.pow(1.0 - v, 4)
// @function Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_quart (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_out_quart_unbound(v)
// plot(ease_out_quart_unbound(v), "Unbound", #00aaff)
// plot(ease_out_quart(v), "Bound", #0011ff)
//#endregion 1.3.1
//#region 1.3.2: Ease in out:
// @function Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_quart_unbound (float v) =>
if v < 0.5
8.0 * math.pow(v, 4)
else
1.0 - math.pow(-2.0 * v + 2.0, 4) * 0.5
// @function Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_quart (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_out_quart_unbound(v)
// plot(ease_in_out_quart_unbound(v), "Unbound", #00aaff)
// plot(ease_in_out_quart(v), "Bound", #0011ff)
//#endregion 1.3.2
//#endregion 1.3
//#region 1.4: Quintic:
//#region 1.4.0: Ease in:
// @function Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_quint_unbound (float v) =>
math.pow(v, 5)
// @function Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_quint (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_quint_unbound(v)
// plot(ease_in_quint_unbound(v), "Unbound", #00aaff)
// plot(ease_in_quint(v), "Bound", #0011ff)
//#endregion 1.4.0
//#region 1.4.1: Ease out:
// @function Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_quint_unbound (float v) =>
1.0 - math.pow(1.0 - v, 5)
// @function Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_quint (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_out_quint_unbound(v)
// plot(ease_out_quint_unbound(v), "Unbound", #00aaff)
// plot(ease_out_quint(v), "Bound", #0011ff)
//#endregion 1.4.1
//#region 1.4.2: Ease in out:
// @function Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_quint_unbound (float v) =>
v < 0.5 ? 16.0 * math.pow(v, 5) : 1 - math.pow(-2.0 * v + 2.0, 5) / 2.0
// @function Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_quint (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_out_quint_unbound(v)
// plot(ease_in_out_quint_unbound(v), "Unbound", #00aaff)
// plot(ease_in_out_quint(v), "Bound", #0011ff)
//#endregion 1.4.2
//#endregion 1.4
//#region 1.5: Exponential:
//#region 1.5.0: Ease in:
// @function Exponential function, the position equals the exponential formula of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_expo_unbound (float v) =>
if v == 0.0
0.0
else
math.pow(2.0, 10.0 * v - 10.0)
// @function Exponential function, the position equals the exponential formula of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_expo (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_expo_unbound(v)
// plot(ease_in_expo_unbound(v), "Unbound", #00aaff)
// plot(ease_in_expo(v), "Bound", #0011ff)
//#endregion 1.5.0
//#region 1.5.1: Ease out:
// @function Exponential function, the position equals the exponential formula of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_expo_unbound (float v) =>
if v == 1.0
1.0
else
1.0 - math.pow(2.0, -10 * v)
// @function Exponential function, the position equals the exponential formula of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_expo (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_out_expo_unbound(v)
// plot(ease_out_expo_unbound(v), "Unbound", #00aaff)
// plot(ease_out_expo(v), "Bound", #0011ff)
//#endregion 1.5.1
//#region 1.5.2: Ease in out:
// @function Exponential function, the position equals the exponential formula of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_expo_unbound (float v) =>
switch
v == 0.0 => 0.0
v == 1.0 => 1.0
v < 0.5 => math.pow(2.0, 20.0 * v - 10.0) * 0.5
=> (2.0 - math.pow(2.0, -20 * v + 10.0)) * 0.5
// @function Exponential function, the position equals the exponential formula of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_expo (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_out_expo_unbound(v)
// plot(ease_in_out_expo_unbound(v), "Unbound", #00aaff)
// plot(ease_in_out_expo(v), "Bound", #0011ff)
//#endregion 1.5.2
//#endregion 1.5
//#region 1.6: Circle:
//#region 1.6.0: Ease in:
// @function Circular function, the position equals the circular formula of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_circ_unbound (float v) =>
1.0 - math.sqrt(1.0 - math.pow(v, 2))
// @function Circular function, the position equals the circular formula of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_circ (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_circ_unbound(v)
// plot(ease_in_circ_unbound(v), "Unbound", #00aaff)
// plot(ease_in_circ(v), "Bound", #0011ff)
//#endregion 1.6.0
//#region 1.6.1: Ease out:
// @function Circular function, the position equals the circular formula of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_circ_unbound (float v) =>
math.sqrt(1.0 - math.pow(v - 1.0, 2))
// @function Circular function, the position equals the circular formula of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_circ (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_out_circ_unbound(v)
// plot(ease_out_circ_unbound(v), "Unbound", #00aaff)
// plot(ease_out_circ(v), "Bound", #0011ff)
//#endregion 1.6.1
//#region 1.6.2: Ease in out:
// @function Circular function, the position equals the circular formula of elapsed time (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_circ_unbound (float v) =>
if v < 0.5
(1.0 - math.sqrt(1.0 - math.pow(2.0 * v, 2))) * 0.5
else
(math.sqrt(1.0 - math.pow(-2.0 * v + 2.0, 2)) + 1.0) * 0.5
// @function Circular function, the position equals the circular formula of elapsed time (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_circ (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_out_circ_unbound(v)
// plot(ease_in_out_circ_unbound(v), "Unbound", #00aaff)
// plot(ease_in_out_circ(v), "Bound", #0011ff)
//#endregion 1.6.2
//#endregion 1.6
//#region 1.7: Back:
//#region 1.7.0: Ease in:
// @function Back function, the position retreats a bit before resuming (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_back_unbound (float v) =>
__C2 * math.pow(v, 3) - __C1 * math.pow(v, 2)
// @function Back function, the position retreats a bit before resuming (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_back (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_back_unbound(v)
// plot(ease_in_back_unbound(v), "Unbound", #00aaff)
// plot(ease_in_back(v), "Bound", #0011ff)
//#endregion 1.7.0
//#region 1.7.1: Ease out:
// @function Back function, the position retreats a bit before resuming (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_back_unbound (float v) =>
1.0 + __C2 * math.pow(v - 1.0, 3) + __C1 * math.pow(v - 1.0, 2)
// @function Back function, the position retreats a bit before resuming (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_back (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_out_back_unbound(v)
// plot(ease_out_back_unbound(v), "Unbound", #00aaff)
// plot(ease_out_back(v), "Bound", #0011ff)
//#endregion 1.7.1
//#region 1.7.2: Ease in out:
// @function Back function, the position retreats a bit before resuming (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_back_unbound (float v) =>
if v < 0.5
(math.pow(2.0 * v, 2) * ((__C2 + 1.0) * 2.0 * v - __C2)) * 0.5
else
(math.pow(2.0 * v - 2.0, 2) * ((__C2 + 1.0) * (v * 2.0 - 2.0) + __C2) + 2.0) * 0.5
// @function Back function, the position retreats a bit before resuming (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_back (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_out_back_unbound(v)
// plot(ease_in_out_back_unbound(v), "Unbound", #00aaff)
// plot(ease_in_out_back(v), "Bound", #0011ff)
//#endregion 1.7.2
//#endregion 1.7
//#region 1.8: Elastic:
//#region 1.8.0: Ease in:
// @function Elastic function, the position oscilates back and forth like a spring (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_elastic_unbound (float v) =>
switch
v == 0.0 => 0.0
v == 1.0 => 1.0
=> -math.pow(2.0, 10.0 * v - 10.0) * math.sin((v * 10.0 - 10.75) * __C4)
// @function Elastic function, the position oscilates back and forth like a spring (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_elastic (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_elastic_unbound(v)
// plot(ease_in_elastic_unbound(v), "Unbound", #00aaff)
// plot(ease_in_elastic(v), "Bound", #0011ff)
//#endregion 1.8.0
//#region 1.8.1: Ease out:
// @function Elastic function, the position oscilates back and forth like a spring (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_elastic_unbound (float v) =>
switch
v == 0.0 => 0.0
v == 1.0 => 1.0
=> math.pow(2.0, -10.0 * v) * math.sin((v * 10.0 - 0.75) * __C4) + 1.0
// @function Elastic function, the position oscilates back and forth like a spring (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_elastic (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_out_elastic_unbound(v)
// plot(ease_out_elastic_unbound(v), "Unbound", #00aaff)
// plot(ease_out_elastic(v), "Bound", #0011ff)
//#endregion 1.8.1
//#region 1.8.2: Ease in out:
// @function Elastic function, the position oscilates back and forth like a spring (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_elastic_unbound (float v) =>
switch
v == 0.0 => 0.0
v == 1.0 => 1.0
v < 0.5 => -(math.pow(2.0, 20.0 * v - 10.0) * math.sin((20.0 * v - 11.125) * __C5)) * 0.5
=> (math.pow(2.0, -20.0 * v + 10.0) * math.sin((20.0 * v - 11.125) * __C5)) * 0.5 + 1
// @function Elastic function, the position oscilates back and forth like a spring (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_elastic (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_out_elastic_unbound(v)
// plot(ease_in_out_elastic_unbound(v), "Unbound", #00aaff)
// plot(ease_in_out_elastic(v), "Bound", #0011ff)
//#endregion 1.8.2
//#endregion 1.8
//#region 1.9: Bounce:
//#region 1.9.0: Ease in:
// @function Bounce function, the position bonces from the boundery (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_bounce_unbound (float v) =>
float _vi = 1.0 - v
switch
_vi < (1.0 / __D1) => 1.0 - (__N1 * math.pow(_vi, 2))
_vi < (2.0 / __D1) => float _v = _vi - (1.500 / __D1) , 1.0 - (__N1 * _v * _v + 0.750000)
_vi < (2.5 / __D1) => float _v = _vi - (2.250 / __D1) , 1.0 - (__N1 * _v * _v + 0.937500)
=> float _v = _vi - (2.625 / __D1) , 1.0 - (__N1 * _v * _v + 0.984375)
// @function Bounce function, the position bonces from the boundery (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_bounce (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_bounce_unbound(v)
// plot(ease_in_bounce_unbound(v), "Unbound", #00aaff)
// plot(ease_in_bounce(v), "Bound", #0011ff)
//#endregion 1.9.0
//#region 1.9.1: Ease out:
// @function Bounce function, the position bonces from the boundery (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_bounce_unbound (float v) =>
switch
v < (1.0 / __D1) => __N1 * math.pow(v, 2)
v < (2.0 / __D1) => float _v = v - (1.500 / __D1) , __N1 * _v * _v + 0.75
v < (2.5 / __D1) => float _v = v - (2.250 / __D1) , __N1 * _v * _v + 0.9375
=> float _v = v - (2.625 / __D1) , __N1 * _v * _v + 0.984375
// @function Bounce function, the position bonces from the boundery (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_out_bounce (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_out_bounce_unbound(v)
// plot(ease_out_bounce_unbound(v), "Unbound", #00aaff)
// plot(ease_out_bounce(v), "Bound", #0011ff)
//#endregion 1.9.1
//#region 1.9.2: Ease in out:
// @function Bounce function, the position bonces from the boundery (unbound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_bounce_unbound (float v) =>
if v < 0.5
(1.0 - ease_out_bounce_unbound(1.0 - 2.0 * v)) * 0.5
else
(1.0 + ease_out_bounce_unbound(2.0 * v - 1.0)) * 0.5
// @function Bounce function, the position bonces from the boundery (bound).
// @param v `float` Elapsed time.
// @returns Ratio of change.
export ease_in_out_bounce (float v) =>
switch
v <= 0.0 => 0.0
v >= 1.0 => 1.0
=> ease_in_out_bounce_unbound(v)
// plot(ease_in_out_bounce_unbound(v), "Unbound", #00aaff)
// plot(ease_in_out_bounce(v), "Bound", #0011ff)
//#endregion 1.9.2
//#endregion 1.9
//#endregion 1
//#region 2: Selection:
//#region 2.0: select ():
export select (float v, string formula='sine', string effect = 'ease-in', bool bounded=true) =>
switch formula
__F0 =>
switch effect
__E0 =>
switch bounded
true => ease_in_sine(v)
false => ease_in_sine_unbound(v)
__E1 =>
switch bounded
true => ease_out_sine(v)
false => ease_out_sine_unbound(v)
__E2 =>
switch bounded
true => ease_in_out_sine(v)
false => ease_in_out_sine_unbound(v)
=> runtime.error(str.format('Used string is not compatible `{0}`, please use one of either: {1}.', effect, __EN)), float(na)
__F1 =>
switch effect
__E0 =>
switch bounded
true => ease_in_quad(v)
false => ease_in_quad_unbound(v)
__E1 =>
switch bounded
true => ease_out_quad(v)
false => ease_out_quad_unbound(v)
__E2 =>
switch bounded
true => ease_in_out_quad(v)
false => ease_in_out_quad_unbound(v)
=> runtime.error(str.format('Used string is not compatible `{0}`, please use one of either: {1}.', effect, __EN)), float(na)
__F2 =>
switch effect
__E0 =>
switch bounded
true => ease_in_cubic(v)
false => ease_in_cubic_unbound(v)
__E1 =>
switch bounded
true => ease_out_cubic(v)
false => ease_out_cubic_unbound(v)
__E2 =>
switch bounded
true => ease_in_out_cubic(v)
false => ease_in_out_cubic_unbound(v)
=> runtime.error(str.format('Used string is not compatible `{0}`, please use one of either: {1}.', effect, __EN)), float(na)
__F3 =>
switch effect
__E0 =>
switch bounded
true => ease_in_quart(v)
false => ease_in_quart_unbound(v)
__E1 =>
switch bounded
true => ease_out_quart(v)
false => ease_out_quart_unbound(v)
__E2 =>
switch bounded
true => ease_in_out_quart(v)
false => ease_in_out_quart_unbound(v)
=> runtime.error(str.format('Used string is not compatible `{0}`, please use one of either: {1}.', effect, __EN)), float(na)
__F4 =>
switch effect
__E0 =>
switch bounded
true => ease_in_quint(v)
false => ease_in_quint_unbound(v)
__E1 =>
switch bounded
true => ease_out_quint(v)
false => ease_out_quint_unbound(v)
__E2 =>
switch bounded
true => ease_in_out_quint(v)
false => ease_in_out_quint_unbound(v)
=> runtime.error(str.format('Used string is not compatible `{0}`, please use one of either: {1}.', effect, __EN)), float(na)
__F5 =>
switch effect
__E0 =>
switch bounded
true => ease_in_expo(v)
false => ease_in_expo_unbound(v)
__E1 =>
switch bounded
true => ease_out_expo(v)
false => ease_out_expo_unbound(v)
__E2 =>
switch bounded
true => ease_in_out_expo(v)
false => ease_in_out_expo_unbound(v)
=> runtime.error(str.format('Used string is not compatible `{0}`, please use one of either: {1}.', effect, __EN)), float(na)
__F6 =>
switch effect
__E0 =>
switch bounded
true => ease_in_circ(v)
false => ease_in_circ_unbound(v)
__E1 =>
switch bounded
true => ease_out_circ(v)
false => ease_out_circ_unbound(v)
__E2 =>
switch bounded
true => ease_in_out_circ(v)
false => ease_in_out_circ_unbound(v)
=> runtime.error(str.format('Used string is not compatible `{0}`, please use one of either: {1}.', effect, __EN)), float(na)
__F7 =>
switch effect
__E0 =>
switch bounded
true => ease_in_back(v)
false => ease_in_back_unbound(v)
__E1 =>
switch bounded
true => ease_out_back(v)
false => ease_out_back_unbound(v)
__E2 =>
switch bounded
true => ease_in_out_back(v)
false => ease_in_out_back_unbound(v)
=> runtime.error(str.format('Used string is not compatible `{0}`, please use one of either: {1}.', effect, __EN)), float(na)
__F8 =>
switch effect
__E0 =>
switch bounded
true => ease_in_elastic(v)
false => ease_in_elastic_unbound(v)
__E1 =>
switch bounded
true => ease_out_elastic(v)
false => ease_out_elastic_unbound(v)
__E2 =>
switch bounded
true => ease_in_out_elastic(v)
false => ease_in_out_elastic_unbound(v)
=> runtime.error(str.format('Used string is not compatible `{0}`, please use one of either: {1}.', effect, __EN)), float(na)
__F9 =>
switch effect
__E0 =>
switch bounded
true => ease_in_bounce(v)
false => ease_in_bounce_unbound(v)
__E1 =>
switch bounded
true => ease_out_bounce(v)
false => ease_out_bounce_unbound(v)
__E2 =>
switch bounded
true => ease_in_out_bounce(v)
false => ease_in_out_bounce_unbound(v)
=> runtime.error(str.format('Used string is not compatible `{0}`, please use one of either: {1}.', effect, __EN)), float(na)
=> runtime.error(str.format('Used string is not compatible `{0}`, please use one of either: {1}.', formula, __FN)), float(na)
f_ = input.string(__F0, 'Formula:', options=[__F0, __F1, __F2, __F3, __F4, __F5, __F6, __F7, __F8, __F9])
e_ = input.string(__E0, 'Effect:', options=[__E0, __E1, __E2])
b_ = input.bool(true, 'Respect boundary:')
plot(select(v, f_, e_, b_), 'Easing Function:', #00eeff)
//#endregion 2.0
//#endregion 2 |
Detrended Price Rate of Change | https://www.tradingview.com/script/ATbKNtaB-Detrended-Price-Rate-of-Change/ | OmegaTools | https://www.tradingview.com/u/OmegaTools/ | 36 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OmegaTools
//@version=5
indicator("Detrended Price Rate of Change", "DPROC")
lnt = input(21, "Length")
smth = input(3, "Smoothing factor")
heik = input.bool(false, "Candle mode")
heiklnt = input(10, "Candle sensitivity")
mid = ta.sma(close, lnt*3)
roc = (close - close[lnt])
dp = close - mid
dproc = ta.sma(math.avg(dp, roc), smth)
dpsma = ta.sma(dproc, heiklnt)
[middle, upper, lower] = ta.bb(dproc, 200, 1)
[middle2, upper2, lower2] = ta.bb(dproc, 200, 2)
p1 = plot(heik == false ? dproc : na, "DPROC", color = color.purple)
plotcandle(heik == true ? dpsma : na, dproc, heik == true ? dpsma : na, dproc, "DPROC Candle", dproc > dpsma ? #2962ff : #e91e63)
hline(0, color = color.new(color.gray, 50), linestyle = hline.style_dotted)
p2 = plot(upper, color = color.new(#e91e63, 50))
p3 = plot(upper2, color = color.new(#e91e63, 0))
p4 = plot(lower, color = color.new(#2962ff, 50))
p5 = plot(lower2, color = color.new(#2962ff, 0))
p12 = plot(0, "", color.gray, display = display.none, editable = false)
fill(p1, p2, dproc > upper ? color.new(#e91e63, 90) : na)
fill(p1, p3, dproc > upper2 ? color.new(#e91e63, 90) : na)
fill(p1, p4, dproc < lower ? color.new(#2962ff, 90) : na)
fill(p1, p5, dproc < lower2 ? color.new(#2962ff, 90) : na)
fill(p1, p12, dproc > lower and dproc < upper ? color.new(color.gray, 95) : na) |
ReversalChartPatternLibrary | https://www.tradingview.com/script/b2cONadQ-ReversalChartPatternLibrary/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 62 | library | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Trendoscope Pty Ltd
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
// @description User Defined Types and Methods for reversal chart patterns - Double Top, Double Bottom, Triple Top, Triple Bottom, Cup and Handle, Inverted Cup and Handle, Head and Shoulders, Inverse Head and Shoulders
library("ReversalChartPatternLibrary", overlay = true)
import HeWhoMustNotBeNamed/DrawingTypes/2 as dr
import HeWhoMustNotBeNamed/DrawingMethods/2
import HeWhoMustNotBeNamed/ZigzagTypes/5 as zg
import HeWhoMustNotBeNamed/ZigzagMethods/6
import HeWhoMustNotBeNamed/TradeTracker/1 as t
// @type Type which holds the drawing objects for Reversal Chart Pattern Types
// @field patternLines array of Line objects representing pattern
// @field entry Entry price Line
// @field stop Stop price Line
// @field target Target price Line
export type ReversalChartPatternDrawing
array<dr.Line> patternLines
dr.Line entry
array<dr.Line> targets
dr.Line stop
dr.Label patternLabel
// @type Trade properties of ReversalChartPattern
// @field riskAdjustment Risk Adjustment for calculation of stop
// @field useFixedTarget Boolean flag saying use fixed target type wherever possible. If fixed target type is not possible, then risk reward/fib ratios are used for calculation of targets
// @field variableTargetType Integer value which defines whether to use fib based targets or risk reward based targets. 1 - Risk Reward, 2 - Fib Ratios
// @field variableTargetRatios Risk reward or Fib Ratios to be used for calculation of targets when fixed target is not possible or not enabled
// @field entryPivotForWm which Pivot should be considered as entry point for WM patterns. 0 refers to the latest breakout pivot where as 5 refers to initial pivot of the pattern
export type ReversalChartTradeProperties
float riskAdjustment = 13.0
bool useFixedTarget = true
int variableTargetType = 2
array<float> variableTargetRatios
int entryPivotForWm = 0
// @type Reversal Chart Pattern master type which holds the pattern components, drawings and trade details
// @field pivots Array of Zigzag Pivots forming the pattern
// @field patternType Defines the main type of pattern 1 - Double Tap, 1 - Triple Tap, 3 - Cup and Handle, 4 - Head and Shoulders, 5- W/M Patterns, 6 - Full Trend, 7 - Half Trend
// @field patternColor Color in which the pattern will be drawn on chart
// @field ReversalChartTradeProperties object contains the properties needed for setting entry, stop and targets
// @field drawing ReversalChartPatternDrawing object which holds the drawing components
// @field trade TradeTracker.Trade object holding trade components
export type ReversalChartPattern
array<zg.Pivot> pivots
int patternType = 0
color patternColor = color.blue
ReversalChartTradeProperties properties
ReversalChartPatternDrawing drawing
t.Trade trade
// @function Deletes the drawing components of ReversalChartPatternDrawing object
// @param this ReversalChartPatternDrawing object
// @returns current ReversalChartPatternDrawing object
export method delete(ReversalChartPatternDrawing this)=>
for ln in this.patternLines
ln.delete()
this.entry.delete()
for ln in this.targets
ln.delete()
this.stop.delete()
this.patternLabel.delete()
this
// @function Deletes the drawing components of ReversalChartPattern object. In turn calls the delete of ReversalChartPatternDrawing
// @param this ReversalChartPattern object
// @returns current ReversalChartPattern object
export method delete(ReversalChartPattern this)=>
this.drawing.delete()
this
// @function Array push with limited number of items in the array. Old items are deleted when new one comes and exceeds the limit
// @param this array<ReversalChartPattern> object
// @param obj ReversalChartPattern object which need to be pushed to the array
// @param limit max items on the array. Default is 10
// @param deleteOld If set to true, also deletes the drawing objects. If not, the drawing objects are kept but the pattern object is removed from array. Default is false.
// @returns current ReversalChartPattern object
export method lpush(array<ReversalChartPattern> this, ReversalChartPattern obj, int limit =10, bool deleteOld = false)=>
this.push(obj)
while(this.size() > limit)
removed = this.shift()
if(deleteOld)
removed.delete()
this
// @function Draws the components of ReversalChartPatternDrawing
// @param this ReversalChartPatternDrawing object
// @returns current ReversalChartPatternDrawing object
export method draw(ReversalChartPatternDrawing this)=>
for ln in this.patternLines
ln.draw()
this.entry.draw()
for ln in this.targets
ln.draw()
this.stop.draw()
this.patternLabel.draw()
this
// @function Draws the components of ReversalChartPatternDrawing within the ReversalChartPattern object.
// @param this ReversalChartPattern object
// @returns current ReversalChartPattern object
export method draw(ReversalChartPattern this)=>
this.drawing.draw()
this
method checkExistingPatterns(zg.Zigzag zigzag, array<ReversalChartPattern> patterns, int offset=0)=>
existingPattern = false
for pattern in patterns
matchingPattern = true
if(pattern.pivots.size() <= zigzag.zigzagPivots.size()+offset)
for [index, pivot] in pattern.pivots
if(index > 0) and (zigzag.zigzagPivots.get(index+offset).point.bar != pattern.pivots.get(index).point.bar)
matchingPattern := false
break
else
false
if(matchingPattern)
existingPattern := true
break
existingPattern
method scanWMPatterns(zg.Zigzag zigzag, array<ReversalChartPattern> patterns, int offset = 0)=>
isPattern = false
if(zigzag.zigzagPivots.size()>=5+offset)
existingPattern = zigzag.checkExistingPatterns(patterns, offset)
if(not existingPattern)
dPivot = zigzag.zigzagPivots.get(offset)
cPivot = zigzag.zigzagPivots.get(offset+1)
bPivot = zigzag.zigzagPivots.get(offset+2)
aPivot = zigzag.zigzagPivots.get(offset+3)
xPivot = zigzag.zigzagPivots.get(offset+4)
r1 = dPivot.ratio
r2 = cPivot.ratio
r3 = bPivot.ratio
r4 = aPivot.ratio
r5 = xPivot.ratio
isPattern := r4 > 1 and r3 < 1 and r2 < 1 and r1 > 1 and (dPivot.point.price*dPivot.dir > xPivot.point.price*dPivot.dir)
isPattern
method fullTrendPattern(zg.Zigzag zigzag, array<ReversalChartPattern> patterns, int offset = 0)=>
isPattern = false
if(zigzag.zigzagPivots.size()>=5+offset)
existingPattern = zigzag.checkExistingPatterns(patterns, offset)
if(not existingPattern)
dPivot = zigzag.zigzagPivots.get(offset)
cPivot = zigzag.zigzagPivots.get(offset+1)
bPivot = zigzag.zigzagPivots.get(offset+2)
aPivot = zigzag.zigzagPivots.get(offset+3)
xPivot = zigzag.zigzagPivots.get(offset+4)
r1 = dPivot.ratio
r2 = cPivot.ratio
r3 = bPivot.ratio
r4 = aPivot.ratio
r5 = xPivot.ratio
isPattern := r5 > 1 and r4 < 1 and r3 > 1 and r2 < 1 and r1 > 1
isPattern
method halfTrendPattern(zg.Zigzag zigzag, array<ReversalChartPattern> patterns, int offset = 0)=>
isPattern = false
if(zigzag.zigzagPivots.size()>=6+offset)
existingPattern = zigzag.checkExistingPatterns(patterns, offset)
if(not existingPattern)
dPivot = zigzag.zigzagPivots.get(offset)
cPivot = zigzag.zigzagPivots.get(offset+1)
bPivot = zigzag.zigzagPivots.get(offset+2)
aPivot = zigzag.zigzagPivots.get(offset+3)
xPivot = zigzag.zigzagPivots.get(offset+4)
oPivot = zigzag.zigzagPivots.get(offset+5)
direction = math.sign(dPivot.dir)
r1 = dPivot.ratio
r2 = cPivot.ratio
r3 = bPivot.ratio
r4 = aPivot.ratio
r5 = xPivot.ratio
isPattern := r5 > 1 and r4 < 1 and r3 < 1 and
(r2 < 1 or cPivot.point.price*direction >=oPivot.point.price*direction) and
(r1 > 1 and dPivot.point.price >= xPivot.point.price)
isPattern
// @function Scans zigzag for ReversalChartPattern occurences
// @param zigzag ZigzagTypes.Zigzag object having array of zigzag pivots and other information on each pivots
// @param patterns Existing patterns array. Used for validating duplicates
// @param errorPercent Error threshold for considering ratios. Default is 13
// @param shoulderStart Starting range of shoulder ratio. Used for identifying shoulders, handles and necklines
// @param shoulderEnd Ending range of shoulder ratio. Used for identifying shoulders, handles and necklines
// @param allowedPatterns array of int containing allowed pattern types
// @param offset Offset of zigzag to consider only confirmed pivots
// @returns int pattern type
export method scan(zg.Zigzag zigzag, array<ReversalChartPattern> patterns, float errorPercent = 13.0, float shoulderStart = 0.1, float shoulderEnd = 0.5, array<int> allowedPatterns = na, int offset = 0)=>
patternType = 0
allowedPatternsLocal = na(allowedPatterns)? array.from(1,2,3,4,5,6,7) : allowedPatterns
if(zigzag.zigzagPivots.size()>=4)
existingPattern = zigzag.checkExistingPatterns(patterns, offset)
if(not existingPattern)
cPivot = zigzag.zigzagPivots.get(offset)
bPivot = zigzag.zigzagPivots.get(offset+1)
aPivot = zigzag.zigzagPivots.get(offset+2)
xPivot = zigzag.zigzagPivots.get(offset+3)
r1 = cPivot.ratio
r2 = bPivot.ratio
r3 = aPivot.ratio
r4 = xPivot.ratio
min = (1-errorPercent/100)
max = (1+errorPercent/100)
r1IsTap = (r1 >= min and r1 <= max) and r1 > nz(array.max(cPivot.indicatorRatios))
r2IsTap = (r2 >= min and r2 <= max) and r2 > nz(array.max(bPivot.indicatorRatios))
r3IsTap = (r3 >= min and r3 <= max) and r3 > nz(array.max(aPivot.indicatorRatios))
r4IsTap = (r4 >= min and r4 <= max) and r4 > nz(array.max(xPivot.indicatorRatios))
r1IsShoulder = (r1 <= shoulderEnd) and (r1 >=shoulderStart)
r2IsShoulder = (r2 <= shoulderEnd) and (r2 >= shoulderStart)
r4IsShoulder = (r4 <= shoulderEnd) and (r4 >= shoulderStart)
r3IsHead = (r3 >= 1/shoulderEnd) and (r3 <= 1/shoulderStart)
isWm = allowedPatternsLocal.includes(5) and zigzag.scanWMPatterns(patterns, offset)
isFullTrend = allowedPatternsLocal.includes(6) and zigzag.fullTrendPattern(patterns, offset)
isHalfTrend = allowedPatternsLocal.includes(7) and zigzag.halfTrendPattern(patterns, offset)
headAndShoulder = r1IsShoulder and r2IsTap and r3IsHead and r4IsShoulder and allowedPatternsLocal.includes(4)
tripleTap = r1IsTap and r2IsTap and r3IsTap and r4IsShoulder and allowedPatternsLocal.includes(2)
cupAndHandle = not headAndShoulder and r1IsShoulder and r2IsTap and allowedPatternsLocal.includes(3)
doubleTap = not tripleTap and r1IsTap and r2IsShoulder and allowedPatternsLocal.includes(1)
patternType := doubleTap? 1 : tripleTap? 2 : cupAndHandle? 3 : headAndShoulder? 4 : isWm? 5 : isFullTrend? 6 : isHalfTrend? 7 : 0
patternType
// @function Create Pattern from ZigzagTypes.Zigzag object
// @param zigzag ZigzagTypes.Zigzag object having array of zigzag pivots and other information on each pivots
// @param patternType Type of pattern being created. 1 - Double Tap, 2 - Triple Tap, 3 - Cup and Handle, 4 - Head and Shoulders
// @param patternColor Color in which the patterns are drawn
// @param riskAdjustment Used for calculating stops
// @returns ReversalChartPattern object created
export method createPattern(zg.Zigzag zigzag, int patternType = 1, color patternColor = color.blue, ReversalChartTradeProperties properties = na, int offset=0)=>
patternPivots = zigzag.zigzagPivots.slice(offset, (patternType >= 5? 5 : (patternType %2 == 1 ? 4 : 6)+offset))
tProperties = na(properties)?ReversalChartTradeProperties.new():properties
tProperties.variableTargetRatios := na(tProperties.variableTargetRatios)? array.from(1.0) : tProperties.variableTargetRatios
ReversalChartPattern.new(patternPivots, patternType, patternColor, tProperties)
// @function get pattern name of ReversalChartPattern object
// @param this ReversalChartPattern object
// @returns string name of the pattern
export method getName(ReversalChartPattern this)=>
this.patternType == 1? (this.trade.direction > 0? 'Double Bottom' : 'Double Top') :
this.patternType == 2? (this.trade.direction > 0? 'Triple Bottom' : 'Triple Top') :
this.patternType == 3? (this.trade.direction > 0? 'Cup and Handle' : 'Inverted Cup and Handle') :
this.patternType == 4? (this.trade.direction > 0? 'Inverse Head and Shoulders' : 'Head and Shoulders'):
this.patternType == 5? (this.trade.direction > 0? 'W Pattern' : 'M Pattern'):
this.patternType == 6? (this.trade.direction > 0? 'Full Uptrend' : 'Full Downtrend'):
this.patternType == 7? (this.trade.direction > 0? 'Half Uptrend' : 'Half Downtrend'): 'None'
// @function get consolidated description of ReversalChartPattern object
// @param this ReversalChartPattern object
// @returns string consolidated description
export method getDescription(ReversalChartPattern this)=>
risk = math.abs(this.trade.entry - this.trade.stop)
reward = not na(this.trade.targets) ? this.trade.targets.size() != 0? math.abs(this.trade.entry - this.trade.targets.first()) : na : na
riskReward = not na(this.trade.targets) ? this.trade.targets.size() != 0 ? reward/risk : na : na
entryLabel = not na(this.trade) ? not na(this.trade.entry) ? 'Entry : '+str.tostring(this.trade.entry, format.mintick)+'\n' : '' : ''
stopLabel = not na(this.trade) ? not na(this.trade.stop) ? 'Stop : '+str.tostring(this.trade.stop, format.mintick)+'\n' : '' : ''
targetLabel = not na(this.trade) ? not na(this.trade.targets)? this.trade.targets.size()!=0? 'Targets :'+str.tostring(this.trade.targets.first(), format.mintick)+'\n':
'': '' : ''
rrLabel = not na(riskReward)? 'Estimated RR : '+str.tostring(riskReward, '#.##') : ''
'Pattern :'+this.getName()+'\n'+entryLabel+stopLabel+targetLabel+rrLabel
// @function initializes the ReversalChartPattern object and creates sub object types
// @param this ReversalChartPattern object
// @returns ReversalChartPattern current object
export method init(ReversalChartPattern this)=>
entryPrice = this.pivots.get(this.patternType < 5 ? 1 : this.properties.entryPivotForWm).point.price
direction = int(math.sign(this.pivots.last().dir))
patternSize = this.patternType == 5? math.max(math.abs(this.pivots.get(0).point.price - this.pivots.get(1).point.price), math.abs(this.pivots.get(0).point.price - this.pivots.get(3).point.price)):
math.max(math.abs(this.pivots.get(0).point.price - this.pivots.get(1).point.price), math.abs(this.pivots.get(2).point.price - this.pivots.get(1).point.price))
stop = this.pivots.get(this.patternType >= 5? 3 : 0).point.price - direction*this.properties.riskAdjustment*(entryPrice - this.pivots.first().point.price)/100
array<float> targetPrices = array.new<float>()
if(this.properties.useFixedTarget and this.patternType <= 2) or na(this.properties.variableTargetRatios)? true : this.properties.variableTargetRatios.size() == 0
targetPrices.push(this.pivots.last().point.price)
else
for ratio in this.properties.variableTargetRatios
targetPrice = entryPrice + direction*ratio* (this.properties.variableTargetType == 2 ? patternSize : math.abs(entryPrice-stop))
targetPrices.push(targetPrice)
this.trade := t.Trade.new(0, direction, entryPrice, entryPrice, stop, stop, targetPrices)
dr.LineProperties properties = dr.LineProperties.new()
this.drawing := ReversalChartPatternDrawing.new()
properties.color := this.patternColor
this.drawing.patternLines := array.new<dr.Line>()
for i = 0 to this.pivots.size()-2
this.drawing.patternLines.push(this.pivots.get(i).point.createLine(this.pivots.get(i+1).point, properties))
startBar = this.pivots.get(this.patternType >= 5? 2: 1).point.bar
endBar = 2*this.pivots.first().point.bar-this.pivots.get(this.patternType < 5 ? 1: 0).point.bar
dr.Point entryPointStart = dr.Point.new(entryPrice, startBar)
dr.Point entryPointEnd = dr.Point.new(entryPrice, endBar)
dr.LineProperties entryLineProp = properties.copy()
entryLineProp.style := line.style_dotted
entryLineProp.color := color.blue
this.drawing.entry := entryPointStart.createLine(entryPointEnd, entryLineProp)
dr.Point stopPointStart = dr.Point.new(stop, startBar)
dr.Point stopPointEnd = dr.Point.new(stop, endBar)
dr.LineProperties stopLineProp = entryLineProp.copy()
stopLineProp.color := color.red
this.drawing.stop := stopPointStart.createLine(stopPointEnd, stopLineProp)
dr.LineProperties targetLineProp = entryLineProp.copy()
targetLineProp.color := color.green
this.drawing.targets := array.new<dr.Line>()
for target in this.trade.targets
dr.Point targetPointStart = dr.Point.new(target, startBar)
dr.Point targetPointEnd = dr.Point.new(target, endBar)
this.drawing.targets.push(targetPointStart.createLine(targetPointEnd, targetLineProp))
dr.LabelProperties lblProperties = dr.LabelProperties.new()
lblProperties.color := this.patternColor
lblProperties.textcolor := this.patternColor
lblProperties.style := direction > 0 ? label.style_arrowup : label.style_arrowdown
lblProperties.yloc := direction > 0? yloc.belowbar : yloc.abovebar
this.drawing.patternLabel := this.pivots.get(this.patternType >= 5? 3 : 0).point.createLabel(this.getName(), this.getDescription(), lblProperties)
this |
Oscillator overlay | https://www.tradingview.com/script/YNsZyPiH-Oscillator-overlay/ | mickes | https://www.tradingview.com/u/mickes/ | 37 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mickes
//@version=5
indicator("Oscillator overlay", overlay = true)
_atrFactor = input.float(2, "ATR factor", tooltip = "Determines the limits for where the oscillator is shown", group = "General")
_changeBackground = input.bool(true, "Change background", group = "General")
_showLastValue = input.bool(true, "Show last value", group = "General")
_showPivots = input.bool(true, "Show", group = "Pivots")
_showPivotsOscillatorValue = input.bool(true, "Show oscillator value", group = "Pivots")
_pivotLength = input.int(10, "Length", group = "Pivots")
_oscillatorType = input.string("MFI", "Oscillator", ["MFI", "RSI", "Stochastic"], group = "Osciillator")
_length = input.int(14, "Length", group = "Osciillator")
_oversold = input.float(20, "Oversold", group = "Osciillator")
_overbougth = input.float(80, "Overbougth", group = "Osciillator")
type Oscillator
float Value
type Drawing
float Oversold
float Overbought
float Minimum
float Maximum
float Value
float Price
var _lightTheme = color.r(chart.bg_color) == 255
var _oscillator = Oscillator.new()
switch _oscillatorType
"MFI" => _oscillator.Value := ta.mfi(hlc3, _length)
"RSI" => _oscillator.Value := ta.rsi(close, _length)
"Stochastic" => _oscillator.Value := ta.sma(ta.stoch(close, high, low, _length), 3)
oscillate() =>
atr = ta.atr(14)
drawing = Drawing.new(low, high, low, high, ohlc4)
if not na(atr)
drawing.Minimum := low - ((atr * _atrFactor))
drawing.Maximum := high + ((atr * _atrFactor))
area = drawing.Maximum - drawing.Minimum
drawing.Oversold := drawing.Minimum + (area * (_oversold / 100))
drawing.Overbought := drawing.Maximum - (area * (1 - (_overbougth / 100)))
drawing.Price := ((drawing.Maximum - drawing.Minimum) * (_oscillator.Value / 100)) + drawing.Minimum
drawing
background() =>
color background = na
if _changeBackground
if _oscillator.Value > _overbougth
background := color.new(color.red, 80)
else if _oscillator.Value < _oversold
background := color.new(color.green, 80)
background
showLastValue(drawing) =>
if barstate.islast
var l = label.new(bar_index, 0, color = color.new(color.purple, 30), style = label.style_label_lower_left, textcolor = color.white)
label.set_text(l, str.format("{0,number,#.##}", _oscillator.Value))
label.set_xy(l, bar_index, drawing.Price)
showPvots(drawing) =>
pivotHigh = ta.pivothigh(_oscillator.Value, _pivotLength, _pivotLength)
highPrice = drawing.Maximum[_pivotLength]
pivotLow = ta.pivotlow(_oscillator.Value, _pivotLength, _pivotLength)
lowPrice = drawing.Minimum[_pivotLength]
if _showPivots
if not na(pivotHigh)
labelColor = pivotHigh > _overbougth ? color.new(color.red, 30) : color.new(color.red, 70)
label.new(bar_index - _pivotLength, highPrice, str.format("{0}▼", _showPivotsOscillatorValue ? str.format("{0,number,#.##}\n", pivotHigh) : ""), color = labelColor, textcolor = color.white)
if not na(pivotLow)
labelColor = pivotLow < _oversold ? color.new(color.green, 30) : color.new(color.green, 70)
label.new(bar_index - _pivotLength, lowPrice, str.format("▲{0}", _showPivotsOscillatorValue ? str.format("\n{0,number,#.##}", pivotLow) : ""), color = labelColor, textcolor = color.white, style = label.style_label_up)
drawing = oscillate()
plot(_oscillator.Value, "Value (for alerts)", display = display.none)
price = plot(drawing.Price, "Price", color = _oscillator.Value > _overbougth ? color.red : _oscillator.Value < _oversold ? color.green : color.purple, display = display.pane)
extremeTransparency = 90
oversold = plot(drawing.Oversold, "Oversold", color = _lightTheme ? color.new(color.black, extremeTransparency) : color.new(color.white, extremeTransparency), display = display.pane)
overbougth = plot(drawing.Overbought, "Overbougth", color = _lightTheme ? color.new(color.black, extremeTransparency) : color.new(color.white, extremeTransparency), display = display.pane)
fill(oversold, overbougth, color.new(color.purple, 90), "Background")
limitTransparency = 60
min = plot(drawing.Minimum, "Minimum", color = _lightTheme ? color.new(color.black, limitTransparency) : color.new(color.white, limitTransparency), display = display.pane)
max = plot(drawing.Maximum, "Maximum", color = _lightTheme ? color.new(color.black, limitTransparency) : color.new(color.white, limitTransparency), display = display.pane)
fill(price, overbougth, _oscillator.Value > _overbougth ? color.new(color.red, 80) : na)
fill(price, oversold, _oscillator.Value < _oversold ? color.new(color.green, 80) : na)
showPvots(drawing)
if _showLastValue
showLastValue(drawing)
bgcolor(background()) |
OHLC Break | https://www.tradingview.com/script/uGrt9Ct3/ | minerlancer | https://www.tradingview.com/u/minerlancer/ | 21 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © minerlancer
//@version=5
indicator(title = 'OHLC Break' , overlay = true , max_boxes_count = 500 , max_labels_count = 500 , max_bars_back = 5000 , max_lines_count = 500)
max_tf = input.int(defval = 60 , title = 'Max TF Show' , inline = '0' , group = 'Input')
max_line = input.int(defval = 500 , title = 'Max Bars Back', inline = '0' , group = 'Input')
Timezone = 'America/New_York'
DOM = (timeframe.multiplier <= max_tf) and (timeframe.isintraday)
newDay = ta.change(dayofweek)
//-----------------
// Function
//-----------------
//Vertical Lines
vline(Start1, Color, linestyle, LineWidth) =>
line.new(x1 = Start1 , y1 = low - ta.tr , x2 = Start1 , y2 = high + ta.tr , xloc = xloc.bar_time , extend = extend.both , color = Color , style = linestyle , width = LineWidth)
// Session String to int
SeshStartHour(Session) =>
math.round(str.tonumber(str.substring(Session,0,2)))
SeshStartMins(Session) =>
math.round(str.tonumber(str.substring(Session,2,4)))
SeshEndHour(Session) =>
math.round(str.tonumber(str.substring(Session,5,7)))
SeshEndMins(Session) =>
math.round(str.tonumber(str.substring(Session,7,9)))
// BgInSession
BarInSession(sess) =>
time(timeframe.period, sess, Timezone) != 0
//-----------------
// End Function
//-----------------
//---Input OHLC
show_OHLC = input.bool(defval = false , title = 'Show OHLC Break ' , inline = '0' , group = 'OHLC Break')
candle_box = input.bool(defval = true , title = 'Change color Candel OHLC', inline = '0' , group = 'OHLC Break')
col_candle_box = input.color(defval = color.white , title = '' , inline = '0' , group = 'OHLC Break')
show_line = input.bool(defval = false , title = 'Show Line no Break ', inline = '1' , group = 'OHLC Break')
show_lab = input.bool(defval = false , title = 'Show Label' , inline = '1' , group = 'OHLC Break' , tooltip = 'Shows a Label on candles that respect the minimum of broken levels')
show_box = input.bool(defval = false , title = 'Show Box on the candle that broke at least', inline = '3' , group = 'OHLC Break')
max_line_break = input.int(defval = 5 , title = '' , inline = '3' , group = 'OHLC Break' , tooltip = 'Choose the minimum of broken levels')
style_box = input.string(defval = '⎯⎯⎯' , title = '' , options = ['⎯⎯⎯' ,'----' , '····'] , inline = '4' , group = 'OHLC Break')
choise_style_box = style_box == '····' ? line.style_dotted : style_box == '----' ? line.style_dashed : line.style_solid
color_box = input.color(defval = color.maroon , title = '' , inline = '4' , group = 'OHLC Break')
size_box = input.int(defval = 1 , title = 'Size' , inline = '4' , group = 'OHLC Break')
max_Box = input.int(defval = 5 , title = 'Tot. Box' , inline = '4' , group = 'OHLC Break' , tooltip = 'Max Box Show')
show_lv = show_line ? color.black : na
linebx = choise_style_box
colobx = color_box
var line[] _lowLiqLines = array.new_line()
var line[] _highLiqLines = array.new_line()
var box[] boxArray = array.new_box()
//Function to Calculate Line Length
_controlLine(_lines, __high, __low) =>
if array.size(_lines) > 0
var bool isLineDashed = false
var int count = 0
var bool changeCandle = na
for i = array.size(_lines) - 1 to 0 by 1
_line = array.get(_lines, i)
_lineLow = line.get_y1(_line)
_lineHigh = line.get_y2(_line)
_lineRight = line.get_x2(_line)
if na or (bar_index == _lineRight and not((__high > _lineLow and __low < _lineLow) or (__high > _lineHigh and __low < _lineHigh)))
line.set_x2(_line, bar_index + 1)
line.set_extend(_line, extend.right)
if _lineRight > bar_index[5] and _lineRight < bar_index[0]
line.set_color(_line, color.red)
line.set_style(_line, line.style_dashed)
if _lineRight < bar_index
line.delete(_line)
var bool isPreviousBarRight = false
for j = bar_index[0] - 1 to bar_index[1] + 1 by 1
prevBarIndex = j
if prevBarIndex == _lineRight
isPreviousBarRight := true
break
// Increase count if line is dashed
if isPreviousBarRight and _lineRight < bar_index
isLineDashed := true
count += 1
// Add the label only once after the loop completes
if count >= max_line_break
changeCandle := true
if show_lab
a = label.new(x = bar_index[1] , y = high[1] , text = str.tostring(count), color = color.rgb(255, 255, 255, 78), textcolor = color.black, style = label.style_label_down)
if show_box
bx = box.new(left = bar_index[1] , top = high[1] , right = bar_index , bottom = low[1] , border_color = colobx , border_width = size_box , border_style = linebx , extend = extend.right , bgcolor = na )
if array.size(boxArray) >= max_Box
box.delete(array.shift(boxArray))
array.push(boxArray, bx)
else
changeCandle := false
if barstate.isconfirmed and isLineDashed
count := 0
changeCandle
//Pivot Low Line Plotting
var bool changeCandle_1 = na
var bool changeCandle_2 = na
if show_OHLC
_lowPVT = line.new(x1 = bar_index - 1 , y1 = low[1] , x2 = bar_index , y2 = low[1] , extend = extend.none , color = show_lv, style = line.style_solid)
if array.size(_lowLiqLines) >= max_line
line.delete(array.shift(_lowLiqLines))
array.push(_lowLiqLines, _lowPVT)
//Pivot High Line Plotting
_highPVT = line.new(x1 = bar_index - 1 , y1 = high[1] , x2 = bar_index , y2 = high[1] , extend = extend.none , color = show_lv, style = line.style_solid)
if array.size(_highLiqLines) >= max_line
line.delete(array.shift(_highLiqLines))
array.push(_highLiqLines, _highPVT)
changeCandle_1 := _controlLine(_lowLiqLines, high, low)
changeCandle_2 := _controlLine(_highLiqLines, high, low)
barcolor(candle_box and changeCandle_1 ? col_candle_box : na , offset = -1)
barcolor(candle_box and changeCandle_2 ? col_candle_box : na , offset = -1)
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
// Session
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
show_BR_Sess = input.bool(defval = false , title = 'Session' , inline = 'Show' , group = 'Session')
Show_OND = input.bool(defval = true , title = 'Show Only Today' , inline = 'Show' , group = 'Session')
show_Sess_1 = input.bool(defval = false , title = '' , inline = '1' , group = 'Session')
Sess_1 = input.session(defval = '0200-0500' , title = '' , inline = '1' , group = 'Session')
col_Sess_1 = input.color(defval = color.blue , title = '' , inline = '1' , group = 'Session')
show_Sess_2 = input.bool(defval = false , title = '' , inline = '2' , group = 'Session')
Sess_2 = input.session(defval = '0830-1100' , title = '' , inline = '2' , group = 'Session')
col_Sess_2 = input.color(defval = color.red , title = '' , inline = '2' , group = 'Session')
show_Sess_3 = input.bool(defval = false , title = '' , inline = '3' , group = 'Session')
Sess_3 = input.session(defval = '0900-1200' , title = '' , inline = '3' , group = 'Session')
col_Sess_3 = input.color(defval = color.yellow , title = '' , inline = '3' , group = 'Session')
show_Sess_4 = input.bool(defval = false , title = '' , inline = '4' , group = 'Session')
Sess_4 = input.session(defval = '1330-1600' , title = '' , inline = '4' , group = 'Session')
col_Sess_4 = input.color(defval = color.purple , title = '' , inline = '4' , group = 'Session')
// Time Periods
Sess_Start_Time_1 = timestamp(Timezone, year, month, dayofmonth, SeshStartHour(Sess_1), SeshStartMins(Sess_1), 00)
Sess_End_Time_1 = timestamp(Timezone, year, month, dayofmonth, SeshEndHour(Sess_1), SeshEndMins(Sess_1), 00)
//
Sess_Start_Time_2 = timestamp(Timezone, year, month, dayofmonth, SeshStartHour(Sess_2), SeshStartMins(Sess_2), 00)
Sess_End_Time_2 = timestamp(Timezone, year, month, dayofmonth, SeshEndHour(Sess_2), SeshEndMins(Sess_2), 00)
//
Sess_Start_Time_3 = timestamp(Timezone, year, month, dayofmonth, SeshStartHour(Sess_3), SeshStartMins(Sess_3), 00)
Sess_End_Time_3 = timestamp(Timezone, year, month, dayofmonth, SeshEndHour(Sess_3), SeshEndMins(Sess_3), 00)
//
Sess_Start_Time_4 = timestamp(Timezone, year, month, dayofmonth, SeshStartHour(Sess_4), SeshStartMins(Sess_4), 00)
Sess_End_Time_4 = timestamp(Timezone, year, month, dayofmonth, SeshEndHour(Sess_4), SeshEndMins(Sess_4), 00)
// Creating Variables
var Sess_Start_Vline_1 = line.new(x1 = na , y1 = na , x2 = na , xloc = xloc.bar_time , y2 = close , color = color.rgb(255,255,255,100) , width = 1)
var Sess_End_Vline_1 = line.new(x1 = na , y1 = na , x2 = na , xloc = xloc.bar_time , y2 = close , color = color.rgb(255,255,255,100) , width = 1)
var Sess_Fill_1 = linefill.new(Sess_Start_Vline_1, Sess_End_Vline_1, color.new(#787b86, 90))
//
var Sess_Start_Vline_2 = line.new(x1 = na , y1 = na , x2 = na , xloc = xloc.bar_time , y2 = close , color = color.rgb(255,255,255,100) , width = 1)
var Sess_End_Vline_2 = line.new(x1 = na , y1 = na , x2 = na , xloc = xloc.bar_time , y2 = close , color = color.rgb(255,255,255,100) , width = 1)
var Sess_Fill_2 = linefill.new(Sess_Start_Vline_2, Sess_End_Vline_2, color.new(#787b86, 90))
//
var Sess_Start_Vline_3 = line.new(x1 = na , y1 = na , x2 = na , xloc = xloc.bar_time , y2 = close , color = color.rgb(255,255,255,100) , width = 1)
var Sess_End_Vline_3 = line.new(x1 = na , y1 = na , x2 = na , xloc = xloc.bar_time , y2 = close , color = color.rgb(255,255,255,100) , width = 1)
var Sess_Fill_3 = linefill.new(Sess_Start_Vline_3, Sess_End_Vline_3, color.new(#787b86, 90))
//
var Sess_Start_Vline_4 = line.new(x1 = na , y1 = na , x2 = na , xloc = xloc.bar_time , y2 = close , color = color.rgb(255,255,255,100) , width = 1)
var Sess_End_Vline_4 = line.new(x1 = na , y1 = na , x2 = na , xloc = xloc.bar_time , y2 = close , color = color.rgb(255,255,255,100) , width = 1)
var Sess_Fill_4 = linefill.new(Sess_Start_Vline_4, Sess_End_Vline_4, color.new(#787b86, 90))
// When a New Day Starts, Start Drawing all lines
if Show_OND and newDay and dayofweek != dayofweek.sunday
if (show_BR_Sess and show_Sess_1 and DOM)
Sess_Start_Vline_1 := vline(Sess_Start_Time_1 , color.rgb(255,255,255,100) , line.style_solid , 1)
Sess_End_Vline_1 := vline(Sess_End_Time_1 , color.rgb(255,255,255,100) , line.style_solid , 1)
Sess_Fill_1 := linefill.new(Sess_Start_Vline_1, Sess_End_Vline_1, color.new(col_Sess_1, 90))
line.delete(Sess_Start_Vline_1[1])
line.delete(Sess_End_Vline_1[1])
linefill.delete(Sess_Fill_1[1])
if (show_BR_Sess and show_Sess_2 and DOM)
Sess_Start_Vline_2 := vline(Sess_Start_Time_2 , color.rgb(255,255,255,100) , line.style_solid , 1)
Sess_End_Vline_2 := vline(Sess_End_Time_2 , color.rgb(255,255,255,100) , line.style_solid , 1)
Sess_Fill_2 := linefill.new(Sess_Start_Vline_2, Sess_End_Vline_2, color.new(col_Sess_2, 90))
line.delete(Sess_Start_Vline_2[1])
line.delete(Sess_End_Vline_2[1])
linefill.delete(Sess_Fill_2[1])
if (show_BR_Sess and show_Sess_3 and DOM)
Sess_Start_Vline_3 := vline(Sess_Start_Time_3 , color.rgb(255,255,255,100) , line.style_solid , 1)
Sess_End_Vline_3 := vline(Sess_End_Time_3 , color.rgb(255,255,255,100) , line.style_solid , 1)
Sess_Fill_3 := linefill.new(Sess_Start_Vline_3, Sess_End_Vline_3, color.new(col_Sess_3, 90))
line.delete(Sess_Start_Vline_3[1])
line.delete(Sess_End_Vline_3[1])
linefill.delete(Sess_Fill_3[1])
if (show_BR_Sess and show_Sess_4 and DOM)
Sess_Start_Vline_4 := vline(Sess_Start_Time_4 , color.rgb(255,255,255,100) , line.style_solid , 1)
Sess_End_Vline_4 := vline(Sess_End_Time_4 , color.rgb(255,255,255,100) , line.style_solid , 1)
Sess_Fill_4 := linefill.new(Sess_Start_Vline_4, Sess_End_Vline_4, color.new(col_Sess_4, 90))
line.delete(Sess_Start_Vline_4[1])
line.delete(Sess_End_Vline_4[1])
linefill.delete(Sess_Fill_4[1])
chartColour1 = not Show_OND and DOM and show_BR_Sess and show_Sess_1 and BarInSession(Sess_1) ? color.new(col_Sess_1 , 90) : na
bgcolor(color = chartColour1 , title = 'Session 1' , transp = 95 )
chartColour2 = not Show_OND and DOM and show_BR_Sess and show_Sess_2 and BarInSession(Sess_2) ? color.new(col_Sess_2 , 90) : na
bgcolor(color = chartColour2 , title = 'Session 2' , transp = 95)
chartColour3 = not Show_OND and DOM and show_BR_Sess and show_Sess_3 and BarInSession(Sess_3) ? color.new(col_Sess_3 , 90) : na
bgcolor(color = chartColour3 , title = 'Session 3' , transp = 95)
chartColour4 = not Show_OND and DOM and show_BR_Sess and show_Sess_4 and BarInSession(Sess_4) ? color.new(col_Sess_4 , 90) : na
bgcolor(color = chartColour4 , title = 'Session 3' , transp = 95) |
Trend Channels [Cryptoverse] | https://www.tradingview.com/script/MqI8ewj1/ | HasanGocmen | https://www.tradingview.com/u/HasanGocmen/ | 96 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HasanGocmen
//@version=5
indicator("Trend Channels [Cryptoverse]", overlay = true, max_labels_count = 500, max_lines_count = 500, max_bars_back = 10)
period = input.int(defval = 6, title="Pivot Period", minval = 1, maxval = 50, group = "GENERAL SETUP")
topSource = input.string(title="Top Pivot Source", defval = 'close', group = "GENERAL SETUP", options = ['close', 'high'])
bottomSource = input.string(title="Bottom Pivot Source", defval = 'close', group = "GENERAL SETUP", options = ['close', 'low'])
// Trend Lines Setups
showTL = input.bool(true, "Show All Trend Lines", group = "TREND LINES SETUP")
hideOL = input.bool(false, "Hide Old Trend Lines", group = "TREND LINES SETUP")
hideML = input.bool(false, "Hide Middle Trend Lines", group = "TREND LINES SETUP")
hideTTSL = input.bool(false, "Hide 0.236 Lines", group = "TREND LINES SETUP", inline="hidelines")
hideSESL = input.bool(false, "Hide 0.786 Lines", group = "TREND LINES SETUP", inline="hidelines")
hlpr_l_f = input.string(title="Helper Line Format", defval="$", options=["%", "$"], group = "TREND LINES SETUP")
ut_clr = input.color(color.rgb(113, 165, 42), "Up Trend Color", group = "TREND LINES SETUP", inline = "trendcolor")
dt_clr = input.color(color.rgb(246, 12, 122), "Down Trend Color", group = "TREND LINES SETUP", inline = "trendcolor")
mt_clr = input.color(color.rgb(255, 152, 0), "0.5 Trend Color", group = "TREND LINES SETUP", inline = "centercolor")
tts_t_clr = input.color(color.rgb(0,188,212), "0.236 Trend Color", group = "TREND LINES SETUP", inline = "helpercolor")
ses_t_clr = input.color(color.rgb(0,188,212), "0.786 Trend Color", group = "TREND LINES SETUP", inline = "helpercolor")
t_c_w = input.int(defval = 1, title="Trend Channel Width", minval = 1, maxval = 4, group = "TREND LINES SETUP")
t_c_s = input.string("solid (─)", title="Trend Channel Style", options=["solid (─)", "dotted (┈)", "dashed (╌)"], group = "TREND LINES SETUP")
tPT = topSource == 'close' ? close : high
bPT = bottomSource == 'close' ? close : low
float src1 = math.max(tPT, tPT)
float src2 = math.min(bPT, bPT)
float ph = ta.pivothigh(src1, period, period)
float pl = ta.pivotlow(src2, period, period)
plotshape(ph, style = shape.triangledown, color = color.red, textcolor = color.red, location = location.abovebar, offset = -period)
plotshape(pl, style = shape.triangleup, color = color.lime, textcolor = color.lime, location = location.belowbar, offset = -period)
var pvtH = array.new_float(0)
var pvtL = array.new_float(0)
var pvtHI = array.new_int(0)
var pvtLI = array.new_int(0)
var line t_h_l = na
var line t_l_l = na
var line t_c_l = na
var line t_tts_l = na
var line t_ses_l = na
var line b_l_l = na
var line b_h_l = na
var line b_c_l = na
var line b_tts_l = na
var line b_ses_l = na
t_l_s = t_c_s == "dotted (┈)" ? line.style_dotted : t_c_s == "dashed (╌)" ? line.style_dashed : line.style_solid
add_to_array(arr, indexArr, val)=>
array.push(arr, val)
array.push(indexArr, bar_index - period)
c_e_p(price, process, percent)=>
result = 0.0
if(process == "plus")
result := price + (price / 100) * percent
else
result := price - (price / 100) * percent
u_d_l(line, type)=>
l_x_i = line.get_x1(line)
l_x_p = line.get_y1(line)
l_y_i = line.get_x2(line)
l_y_p = line.get_y2(line)
l_b_c = l_y_i - l_x_i
l_d_p = type == "top" ? l_x_p - l_y_p : l_y_p - l_x_p
l_u_p = l_d_p / l_b_c
d_l_f_p = (bar_index - period) - l_x_i
c_l_p_p = 0.0
if(type == "top")
c_l_p_p := l_x_p - (l_u_p * d_l_f_p)
else
c_l_p_p := l_x_p + (l_u_p * d_l_f_p)
c_l_p_p
d_t_h_l(pHI, pHP, lHP)=>
new_l_b_c = (bar_index - period) - pHI
new_l_d_p = pHP - lHP
new_l_u_p = new_l_d_p / new_l_b_c
lowest = 100000.0
t_lowest = 100000.0
l_i = 0
if(topSource == 'close')
for y = 0 to new_l_b_c
if(close[period + new_l_b_c - y] - (new_l_u_p * (new_l_b_c - y)) < t_lowest)
lowest := close[period + new_l_b_c - y]
t_lowest := close[period + new_l_b_c - y] - (new_l_u_p * (new_l_b_c - y))
l_i := bar_index - (period + new_l_b_c - y)
else
for y = 0 to new_l_b_c
if(low[period + new_l_b_c - y] - (new_l_u_p * (new_l_b_c - y)) < t_lowest)
lowest := low[period + new_l_b_c - y]
t_lowest := low[period + new_l_b_c - y] - (new_l_u_p * (new_l_b_c - y))
l_i := bar_index - (period + new_l_b_c - y)
d_l_b_c = l_i - pHI
c_l_l_p = pHP - (new_l_u_p * d_l_b_c)
pLP = 0.0
lLP = 0.0
pCP = 0.0
lCP = 0.0
pTTSP = 0.0
lTTSP = 0.0
pSESP = 0.0
lSESP = 0.0
if(hlpr_l_f == '%')
l_perc = (lowest - c_l_l_p) * 100 / c_l_l_p
pLP := pHP * ((100 - math.abs(l_perc)) / 100)
lLP := lHP * ((100 - math.abs(l_perc)) / 100)
c_perc = ((lowest - c_l_l_p) * 100 / c_l_l_p) / 2
pCP := pHP * ((100 - math.abs(c_perc)) / 100)
lCP := lHP * ((100 - math.abs(c_perc)) / 100)
else
pLP := pHP + (lowest - c_l_l_p)
lLP := lHP + (lowest - c_l_l_p)
pCP := pHP - ((pHP - pLP) * 0.5)
lCP := lHP - ((lHP - lLP) * 0.5)
pTTSP := pHP - ((pHP - pLP) * 0.236)
lTTSP := lHP - ((lHP - lLP) * 0.236)
pSESP := pHP - ((pHP - pLP) * 0.786)
lSESP := lHP - ((lHP - lLP) * 0.786)
[pLP, lLP, pCP, lCP, pTTSP, lTTSP, pSESP, lSESP]
d_b_h_l(pLI, pLP, lLP)=>
new_l_b_c = (bar_index - period) - pLI
new_l_d_p = lLP - pLP
new_l_u_p = new_l_d_p / new_l_b_c
highest = 0.0
t_highest = 0.0
h_i = 0
if(bottomSource == 'close')
for y = 0 to new_l_b_c
if(close[period + new_l_b_c - y] + (new_l_u_p * (new_l_b_c - y)) > t_highest)
highest := close[period + new_l_b_c - y]
t_highest := close[period + new_l_b_c - y] + (new_l_u_p * (new_l_b_c - y))
h_i := bar_index - (period + new_l_b_c - y)
else
for y = 0 to new_l_b_c
if(high[period + new_l_b_c - y] + (new_l_u_p * (new_l_b_c - y)) > t_highest)
highest := high[period + new_l_b_c - y]
t_highest := high[period + new_l_b_c - y] + (new_l_u_p * (new_l_b_c - y))
h_i := bar_index - (period + new_l_b_c - y)
d_l_b_c = h_i - pLI
c_h_l_p = pLP + (new_l_u_p * d_l_b_c)
pHP = 0.0
lHP = 0.0
pCP = 0.0
lCP = 0.0
pTTSP = 0.0
lTTSP = 0.0
pSESP = 0.0
lSESP = 0.0
if(hlpr_l_f == '%')
l_perc = (highest - c_h_l_p) * 100 / c_h_l_p
pHP := pLP * ((100 + math.abs(l_perc)) / 100)
lHP := lLP * ((100 + math.abs(l_perc)) / 100)
c_perc = ((highest - c_h_l_p) * 100 / c_h_l_p) / 2
pCP := pLP * ((100 - math.abs(c_perc)) / 100)
lCP := lLP * ((100 - math.abs(c_perc)) / 100)
else
pHP := pLP + (highest - c_h_l_p)
lHP := lLP + (highest - c_h_l_p)
pCP := pLP + ((pHP - pLP) * 0.5)
lCP := lLP + ((lHP - lLP) * 0.5)
pTTSP := pLP + ((pHP - pLP) * 0.236)
lTTSP := lLP + ((lHP - lLP) * 0.236)
pSESP := pLP + ((pHP - pLP) * 0.786)
lSESP := lLP + ((lHP - lLP) * 0.786)
[pHP, lHP, pCP, lCP, pTTSP, lTTSP, pSESP, lSESP]
if(ph)
if(array.size(pvtH) > 0 and showTL)
pPH = array.get(pvtH, array.size(pvtH) - 1)
prev_pvtHI = array.get(pvtHI, array.size(pvtHI) - 1)
two_pPH = array.size(pvtH) > 1 ? array.get(pvtH, array.size(pvtH) - 2) : 0
two_prev_pvtHI = array.size(pvtHI) > 1 ? array.get(pvtHI, array.size(pvtHI) - 2) : 0
three_pPH = array.size(pvtH) > 2 ? array.get(pvtH, array.size(pvtH) - 3) : 0
c_HLPP = u_d_l(t_h_l, "top")
c_LLPP = u_d_l(t_l_l, "top")
c_CLPP = u_d_l(t_c_l, "top")
c_TTSLPP = u_d_l(t_tts_l, "top")
c_SESLPP = u_d_l(t_ses_l, "top")
a_LTP = line.get_y1(t_h_l)
if(two_pPH >= three_pPH and pPH < two_pPH and ph * 1.001 < pPH)
line.set_xy2(t_h_l, bar_index - period, c_HLPP)
line.set_xy2(t_l_l, bar_index - period, c_LLPP)
line.set_xy2(t_c_l, bar_index - period, c_CLPP)
line.set_xy2(t_tts_l, bar_index - period, c_TTSLPP)
line.set_xy2(t_ses_l, bar_index - period, c_SESLPP)
if(na(c_HLPP) or c_e_p(c_HLPP, "plus", 0.35) < ph or c_e_p(c_LLPP, "minus", 0.35) > ph)
line.set_color(t_h_l, color.new(dt_clr, 50))
line.set_color(t_l_l, color.new(dt_clr, 50))
line.set_color(t_c_l, color.new(mt_clr, 75))
line.set_color(t_tts_l, color.new(tts_t_clr, 75))
line.set_color(t_ses_l, color.new(ses_t_clr, 75))
line.set_extend(t_h_l, extend.none)
line.set_extend(t_l_l, extend.none)
line.set_extend(t_c_l, extend.none)
line.set_extend(t_tts_l, extend.none)
line.set_extend(t_ses_l, extend.none)
if(hideOL)
line.delete(t_h_l)
line.delete(t_l_l)
line.delete(t_c_l)
line.delete(t_tts_l)
line.delete(t_ses_l)
t_h_l := line.new(two_prev_pvtHI, two_pPH, bar_index - period, ph, extend = extend.right, width = t_c_w, color= dt_clr, style = t_l_s)
[pLP, lLP, pCP, lCP, pTTSP, lTTSP, pSESP, lSESP] = d_t_h_l(two_prev_pvtHI, two_pPH, ph)
t_l_l := line.new(two_prev_pvtHI, pLP, bar_index - period, lLP, extend = extend.right, width = 1, color= dt_clr, style = t_l_s)
if not hideML
t_c_l := line.new(two_prev_pvtHI, pCP, bar_index - period, lCP, extend = extend.right, width = t_c_w, color = color.new(mt_clr, 50), style = t_l_s)
if not hideTTSL
t_tts_l := line.new(two_prev_pvtHI, pTTSP, bar_index - period, lTTSP, extend = extend.right, width = t_c_w, color = color.new(tts_t_clr, 75), style = t_l_s)
if not hideSESL
t_ses_l := line.new(two_prev_pvtHI, pSESP, bar_index - period, lSESP, extend = extend.right, width = t_c_w, color = color.new(ses_t_clr, 75), style = t_l_s)
else
if(a_LTP > ph)
line.set_xy2(t_h_l, bar_index - period, c_HLPP)
line.set_xy2(t_l_l, bar_index - period, c_LLPP)
line.set_xy2(t_c_l, bar_index - period, c_CLPP)
add_to_array(pvtH, pvtHI, ph)
if(pl)
if(array.size(pvtL) > 0 and showTL)
pPL = array.get(pvtL, array.size(pvtL) - 1)
prev_pvtLI = array.get(pvtLI, array.size(pvtLI) - 1)
two_pPL = array.size(pvtL) > 1 ? array.get(pvtL, array.size(pvtL) - 2) : 0
two_prev_pvtLI = array.size(pvtLI) > 1 ? array.get(pvtLI, array.size(pvtLI) - 2) : 0
three_pPL = array.size(pvtL) > 2 ? array.get(pvtL, array.size(pvtL) - 3) : 0
c_LLPP = u_d_l(b_l_l, "bottom")
c_HLPP = u_d_l(b_h_l, "bottom")
c_CLPP = u_d_l(b_c_l, "bottom")
c_TTSLPP = u_d_l(b_tts_l, "bottom")
c_SESLPP = u_d_l(b_ses_l, "bottom")
a_LBP = line.get_y1(b_l_l)
if(two_pPL <= three_pPL and pPL > two_pPL and pl * 0.999 > pPL)
line.set_xy2(b_l_l, bar_index - period, c_LLPP)
line.set_xy2(b_h_l, bar_index - period, c_HLPP)
line.set_xy2(b_c_l, bar_index - period, c_CLPP)
line.set_xy2(b_tts_l, bar_index - period, c_TTSLPP)
line.set_xy2(b_ses_l, bar_index - period, c_SESLPP)
if(na(c_LLPP) or c_e_p(c_LLPP, "minus", 0.35) > pl or c_e_p(c_HLPP, "plus", 0.35) < pl)
line.set_color(b_h_l, color.new(ut_clr, 50))
line.set_color(b_l_l, color.new(ut_clr, 50))
line.set_color(b_c_l, color.new(ut_clr, 75))
line.set_color(b_tts_l, color.new(tts_t_clr, 90))
line.set_color(b_ses_l, color.new(ses_t_clr, 90))
line.set_extend(b_h_l, extend.none)
line.set_extend(b_l_l, extend.none)
line.set_extend(b_c_l, extend.none)
line.set_extend(b_tts_l, extend.none)
line.set_extend(b_ses_l, extend.none)
if(hideOL)
line.delete(b_h_l)
line.delete(b_l_l)
line.delete(b_c_l)
line.delete(b_tts_l)
line.delete(b_ses_l)
b_l_l := line.new(two_prev_pvtLI, two_pPL, bar_index - period, pl, extend = extend.right, width = t_c_w, color= ut_clr, style = t_l_s)
[pHP, lHP, pCP, lCP, pTTSP, lTTSP, pSESP, lSESP] = d_b_h_l(two_prev_pvtLI, two_pPL, pl)
b_h_l := line.new(two_prev_pvtLI, pHP, bar_index - period, lHP, extend = extend.right, width = t_c_w, color= ut_clr, style = t_l_s)
if not hideML
b_c_l := line.new(two_prev_pvtLI, pCP, bar_index - period, lCP, extend = extend.right, width = t_c_w, color= color.new(mt_clr, 50), style = t_l_s)
if not hideTTSL
b_tts_l := line.new(two_prev_pvtLI, pTTSP, bar_index - period, lTTSP, extend = extend.right, width = t_c_w, color = color.new(tts_t_clr, 50), style = t_l_s)
if not hideSESL
b_ses_l := line.new(two_prev_pvtLI, pSESP, bar_index - period, lSESP, extend = extend.right, width = t_c_w, color = color.new(ses_t_clr, 50), style = t_l_s)
else
if(a_LBP < pl)
line.set_xy2(b_l_l, bar_index - period, c_LLPP)
line.set_xy2(b_h_l, bar_index - period, c_HLPP)
line.set_xy2(b_c_l, bar_index - period, c_CLPP)
add_to_array(pvtL, pvtLI, pl)
|
Pivot Support & Resistance [DeltaAlgo] | https://www.tradingview.com/script/aw0DmHzG-Pivot-Support-Resistance-DeltaAlgo/ | GeorgeWashington1 | https://www.tradingview.com/u/GeorgeWashington1/ | 85 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DeltaAlgo
//@version=5
indicator("Pivot Support & Resistance [DeltaAlgo]", overlay = true, max_lines_count = 500)
// ----------------- }}
// --- user inputs - }}
// ----------------- }}
period = input.int(10, "Pivot Period", 3, 100, 1, "", "", "pivot s&r settings")
maxLine = input.int(3, "Maximum Lines", 1, 100, 1, "if set at 3 there will be 6 total, 3 support & 3 resistance", "", "pivot s&r settings")
resCol = input.color(#ff5252, "S & R", "", "colors", "pivot s&r settings")
supCol = input.color(#4caf50, "", "", "colors", "pivot s&r settings")
lineWidth = input.int(2, "", 0, 5, 1, "Resistance Line Colors\n\nSupport Line Colors\n\nLine Width", "colors", "pivot s&r settings")
// ------------------------------- }}
// ----- pivot s&Resistance ------ }}
// ------------------------------- }}
pivotHigh = ta.pivothigh(period, period)
pivotLow = ta.pivotlow(period, period)
var resLine = array.new_line()
var supLine = array.new_line()
hh = not na(pivotHigh)
ll = not na(pivotLow)
// -------- Resistance Lines ---- }}
if hh
newHighLine = line.new(bar_index[period], high[period], bar_index, high[period], color = resCol, width = lineWidth)
array.push(resLine, newHighLine)
if array.size(resLine) > maxLine
line.delete(array.get(resLine, 0))
array.remove(resLine, 0)
for i = array.size(resLine) - 1 to 0
if array.size(resLine) - 1 > 0
line.set_x2(array.get(resLine, i), bar_index)
highPrice = line.get_y1(array.get(resLine, i))
if close > highPrice
line.delete(array.get(resLine, i))
array.remove(resLine, i)
// -------- Support Lines --- }}
if ll
newLowLine = line.new(bar_index[period], low[period], bar_index, low[period], color = supCol, width = lineWidth)
array.push(supLine, newLowLine)
if array.size(supLine) > maxLine
line.delete(array.get(supLine, 0))
array.remove(supLine, 0)
for i = array.size(supLine) - 1 to 0
if array.size(supLine) - 1 > 0
line.set_x2(array.get(supLine, i), bar_index)
lowPrice = line.get_y1(array.get(supLine, i))
if close < lowPrice
line.delete(array.get(supLine, i))
array.remove(supLine, i)
// ----------------------------------------- }}
// ------ End Of Script -------------------- }}
// ----------------------------------------- }}
|
News Alert | https://www.tradingview.com/script/iZiUM697-News-Alert/ | ivanroyloewen | https://www.tradingview.com/u/ivanroyloewen/ | 35 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ivanroyloewen
//@version=5
indicator("News Alert", overlay = true)
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------( inputs )
// the offest of your personal timezone from Eastern Standard Time ( New York Time )
var time_Zone_Offset = input.int(defval = 0, title = "Timezone offset in hours from EST", maxval = 24, minval = -24)
// the inputs for the first news alert
var news_Time_1 = "News Time 1"
var news_Hour_1 = input.int(defval = 00, title = "Hour", group = news_Time_1, inline = news_Time_1, minval = 0, maxval = 24)
var news_Minute_1 = input.int(defval = 00, title = "Minute", group = news_Time_1, inline = news_Time_1, minval = 0, maxval = 45, step = 15)
var show_News_1 = input.bool(defval = false, title = "Show News 1", group = news_Time_1, inline = news_Time_1)
// the inputs for the second news alert
var news_Time_2 = "News Time 2"
var news_Hour_2 = input.int(defval = 00, title = "Hour", group = news_Time_2, inline = news_Time_2, minval = 0, maxval = 24)
var news_Minute_2 = input.int(defval = 00, title = "Minute", group = news_Time_2, inline = news_Time_2, minval = 0, maxval = 45, step = 15)
var show_News_2 = input.bool(defval = false, title = "Show News 2", group = news_Time_2, inline = news_Time_2)
// the inputs for the third news alert
var news_Time_3 = "News Time 3"
var news_Hour_3 = input.int(defval = 00, title = "Hour", group = news_Time_3, inline = news_Time_3, minval = 0, maxval = 24)
var news_Minute_3 = input.int(defval = 00, title = "Minute", group = news_Time_3, inline = news_Time_3, minval = 0, maxval = 45, step = 15)
var show_News_3 = input.bool(defval = false, title = "Show News 3", group = news_Time_3, inline = news_Time_3)
// the inputs for the warning period before and after the news release
var news_Warning = "News Warning Period"
var minutes_Warning_Before_News = input.int(defval = 10, title = "Minutes Before", group = news_Warning, inline = news_Warning, minval = 0, maxval = 65, step = 5)
var minutes_Warning_After_News = input.int(defval = 10, title = "Minutes After", group = news_Warning, inline = news_Warning, minval = 0, maxval = 65, step = 5)
// the inputs for the news line settings
var line_Settings = "News Line Settings"
var line_Color = input.color(defval = color.rgb(255, 255, 255), title = "Color", inline = line_Settings, group = line_Settings)
var line_Style = input.string(defval = "Dotted", title="Style", options=["Dotted", "Dashed", "Solid"], group = line_Settings, inline = line_Settings)
var line_Width = input.int(defval = 1, title = "Width", minval = 1, maxval = 10, inline = line_Settings, group = line_Settings)
// the inputs for the warning area surrounding the news release
var box_Settings = "News Area Settings"
var box_Background_Color = input.color(defval = color.rgb(0, 0, 255, 75), title = "Background Color", inline = box_Settings, group = box_Settings)
var box_Show = input.bool(defval = true, title = "Show Area", inline = box_Settings, group = box_Settings)
// set the line style using the string input
var line_Style_Selected = line.style_dotted
if line_Style == "Dotted"
line_Style_Selected := line.style_dotted
else if line_Style == "Dashed"
line_Style_Selected := line.style_dashed
else if line_Style == "Solid"
line_Style_Selected := line.style_solid
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------( time calculations )
// the current time of the current bar
current_Bar_Time = time
// News 1 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// get the time stamps for the first news warning, release, before and after
news_Time_Stamp_Release_1 = timestamp(year, month, dayofmonth, news_Hour_1 + time_Zone_Offset, news_Minute_1, 00)
news_Time_Stamp_Before_1 = timestamp(year, month, dayofmonth, news_Hour_1 + time_Zone_Offset, news_Minute_1 - minutes_Warning_Before_News, 00)
news_Time_Stamp_After_1 = timestamp(year, month, dayofmonth, news_Hour_1 + time_Zone_Offset, news_Minute_1 + minutes_Warning_After_News, 00)
// create bools to indicate where price is currently relatated to the first news warning, used for calculations
bool bar_Is_In_News_1 = current_Bar_Time >= news_Time_Stamp_Before_1 and current_Bar_Time <= news_Time_Stamp_After_1 and show_News_1
bool bar_Is_Before_News_1 = current_Bar_Time < news_Time_Stamp_Release_1 and current_Bar_Time >= news_Time_Stamp_Before_1
bool bar_Is_News_Release_1 = current_Bar_Time == news_Time_Stamp_Release_1
bool bar_Is_News_Ongoing_1 = current_Bar_Time > news_Time_Stamp_Release_1 and current_Bar_Time < news_Time_Stamp_After_1
bool bar_Is_Last_News_Candle_1 = current_Bar_Time == news_Time_Stamp_After_1
// draw the news warning objects if showing the first news warning
if show_News_1
// draw the news warning area
news_Box_1 = box.new(left = news_Time_Stamp_Before_1, top = (open * 2) + open, right = news_Time_Stamp_After_1, bottom = (open * -2) + open, xloc = xloc.bar_time, border_color = na, bgcolor = box_Background_Color)
box.delete(news_Box_1[1])
if box_Show == false
box.delete(news_Box_1)
// draw the news release line
news_Line_1 = line.new(news_Time_Stamp_Release_1, -1, news_Time_Stamp_Release_1, 1, xloc.bar_time, extend.both, line_Color, line_Style_Selected, line_Width)
line.delete(news_Line_1[1])
// News 2 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// get the time stamps for the second news warning, release, before and after
news_Time_Stamp_Release_2 = timestamp(year, month, dayofmonth, news_Hour_2 + time_Zone_Offset, news_Minute_2, 00)
news_Time_Stamp_Before_2 = timestamp(year, month, dayofmonth, news_Hour_2 + time_Zone_Offset, news_Minute_2 - minutes_Warning_Before_News, 00)
news_Time_Stamp_After_2 = timestamp(year, month, dayofmonth, news_Hour_2 + time_Zone_Offset, news_Minute_2 + minutes_Warning_After_News, 00)
// create bools to indicate where price is currently relatated to the second news warning, used for calculations
bool bar_Is_In_News_2 = current_Bar_Time >= news_Time_Stamp_Before_2 and current_Bar_Time <= news_Time_Stamp_After_2 and show_News_2
bool bar_Is_Before_News_2 = current_Bar_Time < news_Time_Stamp_Release_2 and current_Bar_Time >= news_Time_Stamp_Before_2
bool bar_Is_News_Release_2 = current_Bar_Time == news_Time_Stamp_Release_2
bool bar_Is_News_Ongoing_2 = current_Bar_Time > news_Time_Stamp_Release_2 and current_Bar_Time < news_Time_Stamp_After_2
bool bar_Is_Last_News_Candle_2 = current_Bar_Time == news_Time_Stamp_After_2
// draw the news warning objects if showing the second news warning
if show_News_2
// draw the news warning area
news_Box_1 = box.new(left = news_Time_Stamp_Before_2, top = (open * 2) * open, right = news_Time_Stamp_After_2, bottom = (open * -2) + open, xloc = xloc.bar_time, border_color = na, bgcolor = box_Background_Color)
box.delete(news_Box_1[1])
// draw the news release line
news_Line_2 = line.new(news_Time_Stamp_Release_2, -1, news_Time_Stamp_Release_2, 1, xloc.bar_time, extend.both, line_Color, line_Style_Selected, line_Width)
line.delete(news_Line_2[1])
// News 3 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// get the time stamps for the third news warning, release, before and after
news_Time_Stamp_Release_3 = timestamp(year, month, dayofmonth, news_Hour_3 + time_Zone_Offset, news_Minute_3, 00)
news_Time_Stamp_Before_3 = timestamp(year, month, dayofmonth, news_Hour_3 + time_Zone_Offset, news_Minute_3 - minutes_Warning_Before_News, 00)
news_Time_Stamp_After_3 = timestamp(year, month, dayofmonth, news_Hour_3 + time_Zone_Offset, news_Minute_3 + minutes_Warning_After_News, 00)
// create bools to indicate where price is currently relatated to the third news warning, used for calculations
bool bar_Is_In_News_3 = current_Bar_Time >= news_Time_Stamp_Before_3 and current_Bar_Time <= news_Time_Stamp_After_3 and show_News_3
bool bar_Is_Before_News_3 = current_Bar_Time < news_Time_Stamp_Release_3 and current_Bar_Time >= news_Time_Stamp_Before_3
bool bar_Is_News_Release_3 = current_Bar_Time == news_Time_Stamp_Release_3
bool bar_Is_News_Ongoing_3 = current_Bar_Time > news_Time_Stamp_Release_3 and current_Bar_Time < news_Time_Stamp_After_3
bool bar_Is_Last_News_Candle_3 = current_Bar_Time == news_Time_Stamp_After_3
// draw the news warning objects if showing the third news warning
if show_News_3
// draw the news warning area
news_Box_1 = box.new(left = news_Time_Stamp_Before_3, top = (open * 2) * open, right = news_Time_Stamp_After_3, bottom = (open * -2) + open, xloc = xloc.bar_time, border_color = na, bgcolor = box_Background_Color)
// delete old boxes
box.delete(news_Box_1[1])
// draw the news release line
news_Line_3 = line.new(news_Time_Stamp_Release_3, -1, news_Time_Stamp_Release_3, 1, xloc.bar_time, extend.both, line_Color, line_Style_Selected, line_Width)
// delete old lines
line.delete(news_Line_3[1])
// All News ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// create bools to indicate where price is currently relatated to all the news warning, used for calculations
bool bar_Is_In_News = bar_Is_In_News_1 or bar_Is_In_News_2 or bar_Is_In_News_3
bool bar_Is_Before_News = bar_Is_Before_News_1 or bar_Is_Before_News_2 or bar_Is_Before_News_3
bool bar_Is_News_Release = bar_Is_News_Release_1 or bar_Is_News_Release_2 or bar_Is_News_Release_3
bool bar_Is_News_Ongoing = bar_Is_News_Ongoing_1 or bar_Is_News_Ongoing_2 or bar_Is_News_Ongoing_3
bool bar_Is_Last_News_Candle = bar_Is_Last_News_Candle_1 or bar_Is_Last_News_Candle_2 or bar_Is_Last_News_Candle_3
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------( News Table )
// create a table that will be used to display the news warning before, after and during the news release
news_Table = table.new(position = position.bottom_right, columns = 1, rows = 2, bgcolor = color.red, frame_color = color.white, frame_width = 2)
// if price is currently in a news warning area
if bar_Is_In_News == true
// indacate that there is currently active news
table.cell(table_id = news_Table, column = 0, row = 0, text = "Active News")
table.cell_set_text_size(news_Table, 0, 0, size.large)
table.cell_set_text_color(news_Table, 0, 0, color.white)
if bar_Is_News_Release
// indicate that it is the news release
table.cell(table_id = news_Table, column = 0, row = 1, text = "Release")
table.cell_set_text_size(news_Table, 0, 1, size.large)
table.cell_set_text_color(news_Table, 0, 1, color.white)
else if bar_Is_News_Ongoing
// indicate if news is ongoing ( after the news release )
table.cell(table_id = news_Table, column = 0, row = 1, text = "Ongoing")
table.cell_set_text_size(news_Table, 0, 1, size.large)
table.cell_set_text_color(news_Table, 0, 1, color.white)
else if bar_Is_Last_News_Candle
// indate if news is on the last candle before the warning ends
table.cell(table_id = news_Table, column = 0, row = 1, text = "Last Candle")
table.cell_set_text_size(news_Table, 0, 1, size.large)
table.cell_set_text_color(news_Table, 0, 1, color.white)
else if bar_Is_Before_News
// indicate if the news release is coming soon
table.cell(table_id = news_Table, column = 0, row = 1, text = "Incoming")
table.cell_set_text_size(news_Table, 0, 1, size.large)
table.cell_set_text_color(news_Table, 0, 1, color.white)
else
// indicate that price is currently not in a news warning
table.set_bgcolor(news_Table, bgcolor = color.green)
table.cell(table_id = news_Table, column = 0, row = 0, text = " Clear ")
table.cell_set_text_size(news_Table, 0, 0, size.normal)
table.cell_set_text_color(news_Table, 0, 0, color.white)
// delete old tables
table.delete(news_Table[1]) |
NormInvTargetSeeker | https://www.tradingview.com/script/efJapO2M-NormInvTargetSeeker/ | RickSimpson | https://www.tradingview.com/u/RickSimpson/ | 126 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// @ RickSimpson
//@version=5
indicator('NormInvTargetSeeker', overlay = true, max_bars_back = 500, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500)
// ◀─── User paramaters ───►
i_labels = input.bool(true, 'Inverse Normalized Performance Labels', group = 'Inverse Normalized Performance')
i_out_css = input.color(color.new(#07A896, 0), 'Outperformance', group = 'Inverse Normalized Performance', inline = 'Norminv css')
i_und_css = input.color(color.new(#E81E1E, 0), 'Underperformance', group = 'Inverse Normalized Performance', inline = 'Norminv css')
i_multitimeframe_filter = input.bool(false, 'Harmonized Multi-Timeframe Analysis', group = 'Inverse Normalized Performance', tooltip = 'When enabled, this feature analyzes signals across all timeframes to ensure consistency and reliability before presenting a valid signal. This approach aims to enhance the robustness of trend indications.')
i_bands = input.bool(false, 'Display Statistical Range Bands', group = 'Inverse Normalized Performance', tooltip = 'Enable to show bands representing statistical price range deviations. Useful for identifying volatility and market extremes.')
i_sr = input.bool(true, 'Support & Resistance Line', group = 'Inverse Normalized Performance', tooltip = 'Toggle to display or hide the Outperformance/Underperformance Lines on the chart. These lines can provide insights into potential support or resistance zones.')
i_sr_lb = input.bool(true, 'Line Price Levels', group = 'Inverse Normalized Performance', tooltip = 'Toggle to display or hide the price level next to the Outperformance/Underperformance Lines. This provides an exact price level for the support or resistance.')
i_layout = input.string('Wick', 'Line Type', options = ['Wick', 'Average', 'Full Range'], group = 'Inverse Normalized Performance', tooltip = 'Select the style of the Outperformance/Underperformance Lines. "Wick" uses candle wicks, "Average" displays an average range, and "Full Range" displays both Zone and Average.')
i_max_line = input.int(10, 'Maximum Line Displayed', minval = 1, maxval = 500, group = 'Inverse Normalized Performance')
i_inv_css = input.bool(true, 'Enable Deviation Line Color Switch', group = 'Inverse Normalized Performance', tooltip = 'Switch the line color to differentiate between periods of underperformance and outperformance. Helps in quick visual identification of performance trends.')
i_use_body = input.bool(false, 'Use Candle Body', group = 'Inverse Normalized Performance', tooltip = 'Toggle to decide whether to use the candle body or the wick for determining Outperformance/Underperformance Lines.')
i_line_width = input.int(1, 'Line Thickness', minval = 1, maxval = 3, group = 'Inverse Normalized Performance', inline = 'Norminv line style')
i_line_style = input.string('⎯⎯⎯', 'Line Style', options = ['⎯⎯⎯', '----', '····'], group = 'Inverse Normalized Performance', inline = 'Norminv line style')
i_extend = input.bool(true, 'Extend Lines', group = 'Inverse Normalized Performance')
// ◀─── Utility Variables ───►
// Initialize last_condition and determine price range based on user preference: candle body or full wick
var float last_condition = 0
int bullcandle = 0
int bearcandle = 0
float max = i_use_body ? math.max(open, close) : high
float min = i_use_body ? math.min(open, close) : low
// ◀─── Utility Functions ───►
// Function to map string descriptors to line styles
get_line_style(style) =>
out = switch style
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted
// Function to create lines based on layout preference
createline(value, iswick, isaverage, displaysignal) =>
if i_sr and displaysignal
if (i_layout == 'Wick' and iswick) or (i_layout == 'Average' and isaverage) or (i_layout == 'Full Range')
line.new(bar_index, value, bar_index, value)
else
na
else
na
// Function to create labels
createlabel(value, isaverage, color, labelprefix) =>
if i_sr_lb and i_sr
label.new(bar_index, value, text = labelprefix + ' - ' + str.tostring(math.round_to_mintick(value)), textcolor = color, style = label.style_none)
else
na
// ◀─── Inverse Normalized Performance ───►
// Coefficients for the erf function
cof_0 = -1.3026537197817094
cof_1 = 6.4196979235649026e-1
cof_2 = 1.9476473204185836e-2
cof_3 = -9.561514786808631e-3
cof_4 = -9.46595344482036e-4
cof_5 = 3.66839497852761e-4
cof_6 = 4.2523324806907e-5
cof_7 = -2.0278578112534e-5
cof_8 = -1.624290004647e-6
cof_9 = 1.303655835580e-6
cof_10 = 1.5626441722e-8
cof_11 = -8.5238095915e-8
cof_12 = 6.529054439e-9
cof_13 = 5.059343495e-9
cof_14 = -9.91364156e-10
cof_15 = -2.27365122e-10
cof_16 = 9.6467911e-11
cof_17 = 2.394038e-12
cof_18 = -6.886027e-12
cof_19 = 8.94487e-13
cof_20 = 3.13092e-13
cof_21 = -1.12708e-13
cof_22 = 3.81e-16
cof_23 = 7.106e-15
cof_24 = -1.523e-15
cof_25 = -9.4e-17
cof_26 = 1.21e-16
cof_27 = -2.8e-17
p_erf = 0.3275911
// Coefficients for the erfcinv function
c1 = -0.70711
c2 = 2.30753
c3 = 0.27061
c4 = 0.99229
c5 = 0.04481
constant_erfcinv = 1.12837916709551257
_erf(x) =>
t = 1.0 / (1.0 + p_erf * math.abs(x))
y = 0.0
y := y + cof_0 * math.pow(t, 1)
y := y + cof_1 * math.pow(t, 2)
y := y + cof_2 * math.pow(t, 3)
y := y + cof_3 * math.pow(t, 4)
y := y + cof_4 * math.pow(t, 5)
y := y + cof_5 * math.pow(t, 6)
y := y + cof_6 * math.pow(t, 7)
y := y + cof_7 * math.pow(t, 8)
y := y + cof_8 * math.pow(t, 9)
y := y + cof_9 * math.pow(t, 10)
y := y + cof_10 * math.pow(t, 11)
y := y + cof_11 * math.pow(t, 12)
y := y + cof_12 * math.pow(t, 13)
y := y + cof_13 * math.pow(t, 14)
y := y + cof_14 * math.pow(t, 15)
y := y + cof_15 * math.pow(t, 16)
y := y + cof_16 * math.pow(t, 17)
y := y + cof_17 * math.pow(t, 18)
y := y + cof_18 * math.pow(t, 19)
y := y + cof_19 * math.pow(t, 20)
y := y + cof_20 * math.pow(t, 21)
y := y + cof_21 * math.pow(t, 22)
y := y + cof_22 * math.pow(t, 23)
y := y + cof_23 * math.pow(t, 24)
y := y + cof_24 * math.pow(t, 25)
y := y + cof_25 * math.pow(t, 26)
y := y + cof_26 * math.pow(t, 27)
y := y + cof_27 * math.pow(t, 28)
if x < 0.0
-y
else
y
// Complementary error function
erfc(float x) =>
1 - _erf(x)
// Inverse complementary error function with improved error handling
erfcinv(float probability) =>
if (probability <= 0 or probability >= 2)
na
else
float pp = (probability < 1) ? probability : 2 - probability
float t = math.sqrt(-2 * math.log(pp / 2))
float x = c1 * ((c2 + t * c3) / (1 + t * (c4 + t * c5)) - t)
// First iteration
float err1 = (1 - _erf(x)) - pp
x := x + err1 / (constant_erfcinv * math.exp(-x * x) - x * err1)
// Second iteration
float err2 = (1 - _erf(x)) - pp
x := x + err2 / (constant_erfcinv * math.exp(-x * x) - x * err2)
(probability < 1) ? x : -x
// Computes the inverse of the standard normal cumulative Underperformance function with specified mean and stdev
norminv(float number, float mean, float stdev) =>
-1.41421356237309505 * stdev * erfcinv(2 * number) + mean
// Adjust values based on the timeframe
var float mean_value = 0
var float stddev_value = 0
var float alpha_value = 0
var int value_for_hma = 0
var float z_threshold_bullish = 0
var float z_threshold_bearish = 0
// Get the current timeframe
current_timeframe = timeframe.period
// Increment values for each higher timeframe
increment_value = 0.5
increment_stddev = 0.1
increment_alpha = 0.01
increment_hma = 1
increment_z_threshold = 0.1
// Set base values for the smallest timeframe (1 minute)
base_mean_value = 65.5
base_stddev_value = 2.5
base_alpha_value = 0.5
base_hma_value = 2
base_z_threshold = 1.5
// Calculate increments based on timeframe
timeframe_multiplier = switch current_timeframe
'1' => 0
'3' => 1
'5' => 2
'15' => 3
'30' => 4
'60' => 5
'120' => 6
'240' => 7
'D' => 8
'W' => 9
'M' => 10
// Apply increments to base values
mean_value := base_mean_value + increment_value * timeframe_multiplier
stddev_value := base_stddev_value + increment_stddev * timeframe_multiplier
alpha_value := base_alpha_value + increment_alpha * timeframe_multiplier
value_for_hma := base_hma_value + increment_hma * timeframe_multiplier
z_threshold_bullish := base_z_threshold - increment_z_threshold * timeframe_multiplier
z_threshold_bearish := -base_z_threshold + increment_z_threshold * timeframe_multiplier
// Calculate norminv values
float bullish_norm_inv = norminv(alpha_value / 2, mean_value, stddev_value)
float bearish_norm_inv = norminv(1 - alpha_value / 2, mean_value, stddev_value)
// Use the adjusted values in the calculation
outperformance = ta.hma(bullish_norm_inv, value_for_hma) >= z_threshold_bullish and close > open
underperformance = ta.hma(bearish_norm_inv, value_for_hma) >= z_threshold_bearish and close < open
// Determine whether we should display an label
should_plot_out = outperformance and (na(last_condition) or last_condition != 1)
should_plot_und = underperformance and (na(last_condition) or last_condition != -1)
// Update the last condition
if should_plot_out
last_condition := 1
else if should_plot_und
last_condition := -1
// Define the timeframes statically
string tf_m1 = '1'
string tf_m3 = '3'
string tf_m5 = '5'
string tf_m15 = '15'
string tf_m30 = '30'
string tf_h1 = '60'
string tf_h2 = '120'
string tf_h4 = '240'
string tf_d = 'D'
string tf_w = 'W'
string tf_m = 'M'
// Function to retrieve the outperformance and underperformance signals for a given timeframe
get_signal_from_timeframe(tf) =>
[plot_out, plot_und] = request.security(syminfo.tickerid, tf, [should_plot_out, should_plot_und])
[plot_out, plot_und]
// Retrieve signals for each timeframe
[plot_out_m1, plot_und_m1] = get_signal_from_timeframe('1')
[plot_out_m3, plot_und_m3] = get_signal_from_timeframe('3')
[plot_out_m5, plot_und_m5] = get_signal_from_timeframe('5')
[plot_out_m15, plot_und_m15] = get_signal_from_timeframe('15')
[plot_out_m30, plot_und_m30] = get_signal_from_timeframe('30')
[plot_out_h1, plot_und_h1] = get_signal_from_timeframe('60')
[plot_out_h2, plot_und_h2] = get_signal_from_timeframe('120')
[plot_out_h4, plot_und_h4] = get_signal_from_timeframe('240')
[plot_out_d, plot_und_d] = get_signal_from_timeframe('D')
[plot_out_w, plot_und_w] = get_signal_from_timeframe('W')
[plot_out_m, plot_und_m] = get_signal_from_timeframe('M')
// Function to check if signals are concordant across all timeframes
is_signal_concordant() =>
concordant = true
if i_multitimeframe_filter
concordant := concordant and plot_out_m1 or plot_und_m1
concordant := concordant and plot_out_m3 or plot_und_m3
concordant := concordant and plot_out_m5 or plot_und_m5
concordant := concordant and plot_out_m15 or plot_und_m15
concordant := concordant and plot_out_m30 or plot_und_m30
concordant := concordant and plot_out_h1 or plot_und_h1
concordant := concordant and plot_out_h2 or plot_und_h2
concordant := concordant and plot_out_h4 or plot_und_h4
concordant := concordant and plot_out_d or plot_und_d
concordant := concordant and plot_out_w or plot_und_w
concordant := concordant and plot_out_m or plot_und_m
concordant
// Apply the concordant signal logic
concordant_signal = is_signal_concordant()
// Check which signal to display based on user's choice
bool display_out_signal = i_multitimeframe_filter ? concordant_signal and should_plot_out : should_plot_out
bool display_und_signal = i_multitimeframe_filter ? concordant_signal and should_plot_und : should_plot_und
// Plot shapes based on inverse normalized performance
plotshape(i_labels and display_out_signal, style = shape.circle, location = location.belowbar, color = color.new(i_out_css, 0), size = size.tiny, title = 'Outperformance')
plotshape(i_labels and display_und_signal, style = shape.circle, location = location.abovebar, color = color.new(i_und_css, 0), size = size.tiny, title = 'Underperformance')
// Alert conditions based on the filtering
alertcondition(display_out_signal, title = 'Outperformance Alert', message = 'Outperformance detected!')
alertcondition(display_und_signal, title = 'Underperformance Alert', message = 'Underperformance detected!')
// ◀─── Support & Resistance Line ───►
// Initialize variables for handling support and resistance zones, including their lines, labels, tested conditions, and associated colors
var int numberofline = i_max_line
var float upperphzone = 0
var float upperplzone = 0
var float uppermdzone = 0
var float lowerphzone = 0
var float lowerplzone = 0
var float lowermdzone = 0
var line upperphzoneline = na
var line upperplzoneline = na
var line uppermdzoneline = na
var line lowerphzoneline = na
var line lowerplzoneline = na
var line lowermdzoneline = na
var label labelph = na
var label labelphmd = na
var label labelpl = na
var label labelplmd = na
var bool upperzonetested = false
var bool lowerzonetested = false
var color upperzonecolor = i_und_css
var color lowerzonecolor = i_out_css
var line[] upperphzonearr = array.new_line(0, na)
var line[] upperplzonearr = array.new_line(0, na)
var line[] uppermdzonearr = array.new_line(0, na)
var line[] lowerphzonearr = array.new_line(0, na)
var line[] lowerplzonearr = array.new_line(0, na)
var line[] lowermdzonearr = array.new_line(0, na)
var bool[] upperzonetestedarr = array.new_bool(0, false)
var bool[] lowerzonetestedarr = array.new_bool(0, false)
var label[] labelpharr = array.new_label(0, na)
var label[] labelphmdarr = array.new_label(0, na)
var label[] labelplarr = array.new_label(0, na)
var label[] labelplmdarr = array.new_label(0, na)
// Resistance line calculations and styling
if i_sr and display_und_signal
// Define the high and low of the resistance zone and calculate the midpoint
upperphzone := max
upperplzone := min
uppermdzone := math.avg(upperphzone, upperplzone)
// Creating lines and labels for resistance zones
upperphzoneline := createline(upperphzone, true, false, display_und_signal)
upperplzoneline := createline(upperplzone, false, false, display_und_signal)
uppermdzoneline := createline(uppermdzone, false, true, display_und_signal)
// Create a label for the price level at the resistance zone high or midpoint based on user preference
if i_layout == 'Wick' or i_layout == 'Full Range'
labelph := createlabel(upperphzone, upperphzone, upperzonecolor, 'Underperformance')
else if i_layout == 'Average'
labelphmd := createlabel(uppermdzone, uppermdzone, upperzonecolor, 'Underperformance')
// Remove old lines and labels if they exceed the user-defined maximum number
if array.size(upperphzonearr) > numberofline
line.delete(array.shift(upperphzonearr))
line.delete(array.shift(upperplzonearr))
line.delete(array.shift(uppermdzonearr))
array.shift(upperzonetestedarr)
label.delete(array.shift(labelpharr))
label.delete(array.shift(labelphmdarr))
// Store the newly created lines and labels in their respective arrays
array.push(upperphzonearr, upperphzoneline)
array.push(upperplzonearr, upperplzoneline)
array.push(uppermdzonearr, uppermdzoneline)
array.push(upperzonetestedarr, i_extend ? true : false)
array.push(labelpharr, labelph)
array.push(labelphmdarr, labelphmd)
// If there are any resistance zone lines, update their style and check for crossings
if array.size(upperplzonearr) > 0 or array.size(uppermdzonearr) > 0
for i = 0 to array.size(upperplzonearr) - 1 by 1
// Retrieve each line and label from the arrays
line tempupperline = array.get(upperphzonearr, i)
line templowerline = array.get(upperplzonearr, i)
line tempmiddleline = array.get(uppermdzonearr, i)
label linepricelabel = array.get(labelpharr, i)
label mdlinepricelabel = array.get(labelphmdarr, i)
bool tested = array.get(upperzonetestedarr, i)
// Set the style and width for the lines based on user preferences
line.set_style(tempupperline, get_line_style(i_line_style))
line.set_style(templowerline, get_line_style(i_line_style))
line.set_style(tempmiddleline, get_line_style(i_line_style))
line.set_width(tempupperline, i_line_width)
line.set_width(templowerline, i_line_width)
line.set_width(tempmiddleline, i_line_width)
// Set the color for the lines and label based on user preference
line.set_color(tempupperline, i_inv_css ? lowerzonecolor : upperzonecolor)
line.set_color(templowerline, i_inv_css ? lowerzonecolor : upperzonecolor)
line.set_color(tempmiddleline, i_inv_css ? lowerzonecolor : upperzonecolor)
label.set_textcolor(linepricelabel, i_inv_css ? lowerzonecolor : upperzonecolor)
label.set_textcolor(mdlinepricelabel, i_inv_css ? lowerzonecolor : upperzonecolor)
// Update the label text with the price level
if i_layout == 'Wick' or i_layout == 'Full Range'
label.set_text(linepricelabel, ' Underperformance - ' + str.tostring(math.round_to_mintick(line.get_y1(tempupperline))))
label.set_size(linepricelabel, size.small)
label.set_x(linepricelabel, bar_index)
else if i_layout == 'Average'
label.set_text(mdlinepricelabel, ' Underperformance - ' + str.tostring(math.round_to_mintick(line.get_y1(tempmiddleline))))
label.set_size(mdlinepricelabel, size.small)
label.set_x(mdlinepricelabel, bar_index)
// Check if the current price has crossed the resistance line and update the tested status
crossed = high > line.get_y1(tempupperline)
if crossed and not tested
array.set(upperzonetestedarr, i, true)
label.delete(linepricelabel)
label.delete(mdlinepricelabel)
// Extend the lines to the current bar if necessary based on user settings
else if i_extend ? tested : not tested
line.set_x2(tempupperline, bar_index)
array.set(upperphzonearr, i, tempupperline)
line.set_x2(templowerline, bar_index)
array.set(upperplzonearr, i, templowerline)
line.set_x2(tempmiddleline, bar_index)
array.set(uppermdzonearr, i, tempmiddleline)
// Support line calculations and styling
if i_sr and display_out_signal
// Calculate the high, low, and average (middle) of the support zones
lowerphzone := max
lowerplzone := min
lowermdzone := math.avg(lowerphzone, lowerplzone)
// Creating lines and labels for support zones
lowerphzoneline := createline(lowerphzone, false, false, display_out_signal)
lowerplzoneline := createline(lowerplzone, true, false, display_out_signal)
lowermdzoneline := createline(lowermdzone, false, true, display_out_signal)
// Create a label for the price level at the support zone low or midpoint based on user preference
if i_layout == 'Wick' or i_layout == 'Full Range'
labelpl := createlabel(lowerplzone, lowerplzone, lowerzonecolor, 'Outperformance')
else if i_layout == 'Average'
labelplmd := createlabel(lowermdzone, lowermdzone, upperzonecolor, 'Outperformance')
// Remove old lines and labels if they exceed the user-defined maximum number
if array.size(lowerphzonearr) > numberofline
line.delete(array.shift(lowerphzonearr))
line.delete(array.shift(lowerplzonearr))
line.delete(array.shift(lowermdzonearr))
array.shift(lowerzonetestedarr)
label.delete(array.shift(labelplarr))
label.delete(array.shift(labelplmdarr))
// Store the newly created lines and labels in their respective arrays
array.push(lowerphzonearr, lowerphzoneline)
array.push(lowerplzonearr, lowerplzoneline)
array.push(lowermdzonearr, lowermdzoneline)
array.push(lowerzonetestedarr, i_extend ? true : false)
array.push(labelplarr, labelpl)
array.push(labelplmdarr, labelplmd)
// If there are any support zone lines, update their style and check for crossings
if array.size(lowerplzonearr) > 0
for i = 0 to array.size(lowerplzonearr) - 1 by 1
// Retrieve each line and label from the arrays
line tempupperline = array.get(lowerphzonearr, i)
line templowerline = array.get(lowerplzonearr, i)
line tempmiddleline = array.get(lowermdzonearr, i)
label linepricelabel = array.get(labelplarr, i)
label mdlinepricelabel = array.get(labelplmdarr, i)
bool tested = array.get(lowerzonetestedarr, i)
// Set the style and width for the lines based on user preferences
line.set_style(tempupperline, get_line_style(i_line_style))
line.set_style(templowerline, get_line_style(i_line_style))
line.set_style(tempmiddleline, get_line_style(i_line_style))
line.set_width(tempupperline, i_line_width)
line.set_width(templowerline, i_line_width)
line.set_width(tempmiddleline, i_line_width)
// Set the color for the lines and label based on user preference
line.set_color(tempupperline, i_inv_css ? upperzonecolor : lowerzonecolor)
line.set_color(templowerline, i_inv_css ? upperzonecolor : lowerzonecolor)
line.set_color(tempmiddleline, i_inv_css ? upperzonecolor : lowerzonecolor)
label.set_textcolor(linepricelabel, i_inv_css ? upperzonecolor : lowerzonecolor)
label.set_textcolor(mdlinepricelabel, i_inv_css ? upperzonecolor : lowerzonecolor)
// Update the label text with the price level
if i_layout == 'Wick' or i_layout == 'Full Range'
label.set_text(linepricelabel, ' Outperformance - ' + str.tostring(math.round_to_mintick(line.get_y1(templowerline))))
label.set_size(linepricelabel, size.small)
label.set_x(linepricelabel, bar_index)
else if i_layout == 'Average'
label.set_text(mdlinepricelabel, ' Outperformance - ' + str.tostring(math.round_to_mintick(line.get_y1(tempmiddleline))))
label.set_size(mdlinepricelabel, size.small)
label.set_x(mdlinepricelabel, bar_index)
// Check if the current price has crossed the support line and update the tested status
crossed = low < line.get_y1(templowerline)
if crossed and not tested
array.set(lowerzonetestedarr, i, true)
label.delete(linepricelabel)
label.delete(mdlinepricelabel)
// Extend the lines to the current bar if necessary based on user settings
else if i_extend ? tested : not tested
line.set_x2(tempupperline, bar_index)
array.set(lowerphzonearr, i, tempupperline)
line.set_x2(templowerline, bar_index)
array.set(lowerplzonearr, i, templowerline)
line.set_x2(tempmiddleline, bar_index)
array.set(lowermdzonearr, i, tempmiddleline)
// ◀─── Deviation Bands ───►
// Function to calculate the inverse normal distribution based on the dynamic alpha value
norminv_dynamic(alpha_value) =>
local_mean_value = ta.hma(close, value_for_hma)
local_stddev_value = ta.stdev(close, value_for_hma)
local_bullish_norm_inv = norminv(alpha_value / 2, local_mean_value, local_stddev_value)
local_bearish_norm_inv = norminv(1 - alpha_value / 2, local_mean_value, local_stddev_value)
[local_bullish_norm_inv, local_bearish_norm_inv]
// Retrieve the inverse normal values for the current dynamic alpha
[local_bullish_inv, local_bearish_inv] = norminv_dynamic(alpha_value)
// Calculate the dynamic deviation bands based on the local inverse normal values
upper_band_value = local_bullish_inv
lower_band_value = local_bearish_inv
middle_band_value = math.avg(upper_band_value, lower_band_value)
// Plotting the dynamic deviation bands
upper_band = plot(i_bands ? upper_band_value : na, color = i_und_css, title = 'Upper Band')
middle_band = plot(i_bands ? middle_band_value : na, color = chart.fg_color, title = 'Middle Band')
lower_band = plot(i_bands ? lower_band_value : na, color = i_out_css, title = 'Lower Band')
// Fill the space between the upper and lower bands with a shade
fill(upper_band, lower_band, color = color.rgb(173, 216, 230, 90), title = 'Band Shade')
// Alert conditions for crossing the bands
alertcondition(ta.crossover(high, upper_band_value), title = 'Price Crossed Above Upper Band', message = 'The price has closed above the upper deviation band, indicating potential overbought conditions.')
alertcondition(ta.crossunder(low, lower_band_value), title = 'Price Crossed Below Lower Band', message = 'The price has closed below the lower deviation band, indicating potential oversold conditions.')
alertcondition(ta.crossover(close, middle_band_value) or ta.crossunder(close, middle_band_value), title = 'Price Crossed Middle Band', message = 'The price has crossed the middle deviation band, suggesting a possible change in the price trend.')
// Conditions for touching the bands
alertcondition(high >= upper_band_value, title = 'Price Touched Upper Band', message = 'The price has reached or exceeded the upper deviation band, which may signal upper resistance.')
alertcondition(low <= lower_band_value, title = 'Price Touched Lower Band', message = 'The price has reached or dropped below the lower deviation band, which may indicate lower support.')
alertcondition(close == middle_band_value, title = 'Price Touched Middle Band', message = 'The price has touched the middle deviation band, potentially signaling a pause or hesitation in the trend.') |
Volume Sentiment | https://www.tradingview.com/script/3iTbmLpp-Volume-Sentiment/ | grnghost | https://www.tradingview.com/u/grnghost/ | 38 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © grnghost
//@version=5
indicator("Volume Senitment", "V Sent", overlay = false, precision = 1)
group1 = "Volume Thrust"
vlookback = input.int(9, "Volume Sum Period =", minval = 1, group = group1)
ma_len = input.int(13, "Moving Average Length =", minval = 2, group = group1)
group2 = "Strong Volume"
vma_len = input.int(18,"Volume MA Length", 2, group = group2)
thresh = input.float(45, "Strong Volume Threshold (% over MA)", minval = 1, step = 0.5, group = group2)
group3 = "Display"
cbmo = input.bool(false, "Color by Momentum", group = group3)
show_ma = input.bool(false, "Show Moving Average", group = group3)
show_str = input.bool(true, "Show Strong Volume Signal", group = group3)
show_sig = input.bool(false, "Show Trade Signals", group = group3)
up_bar = close > hl2 // close > open
dn_bar = close < hl2 //close < open
u_vol = up_bar ? volume : 0
d_vol = dn_bar ? volume : 0
up_vol = math.sum(u_vol,vlookback)
dn_vol = math.sum(d_vol,vlookback)
thrust = 100*(up_vol - dn_vol)/(up_vol + dn_vol)
thrust_ln = ta.sma(thrust,2)
thrust_ma = ta.sma(thrust, ma_len)
//Stong Volume
vma = ta.sma(volume, vma_len)
strong = volume > (1 + (thresh/100))*vma
str_col = strong and close < open ? color.new(color.red,30) : strong and close > open ? color.new(color.green,30) : na
var plot_col = color.blue
if cbmo == true
plot_col := ta.change(thrust,2) < 0 and thrust < 0 ? color.new(color.red,30) : thrust < 0 ? #FFCDD2 : ta.change(thrust,2) > 0 and thrust > 0 ? color.new(color.green,30) : thrust > 0 ? #B2DFDB : na
else
plot_col := thrust < 0 ? color.new(color.red,30) : color.new(color.green,30)
long = ta.crossover(thrust, 0)
short = ta.crossunder(thrust, 0)
plot(math.abs(thrust), "Thrust", color = plot_col, style = plot.style_columns) //strong ? str_col :
plot(ta.sma(math.abs(thrust), ma_len), "Moving Average", color = show_ma ? color.yellow : na)
hline(70, "High Line", color = color.gray, linestyle = hline.style_dashed)
hline(30, "Mid Line", color = color.gray, linestyle = hline.style_dashed)
hline(0, "Zero Line", color = color.gray, linestyle = hline.style_solid)
plotshape(show_str ? strong : na, "Strong Volume Signal", style = shape.triangleup, location = location.top, color = color.orange, display = display.pane)
plotshape(show_sig ? long : na , "Bull Volume", style = shape.triangleup, location = location.bottom, color = color.yellow, display = display.pane)
plotshape(show_sig ? short : na, "Bear Volume", style = shape.triangledown, location = location.bottom, color = color.yellow, display = display.pane)
alertcondition(strong != strong[1]? strong : na, "Strong Volumen Alert", "Increased activity, take action.")
|
Trend Gaussian Channels [DeltaAlgo] | https://www.tradingview.com/script/ILM8RM4T-Trend-Gaussian-Channels-DeltaAlgo/ | GeorgeWashington1 | https://www.tradingview.com/u/GeorgeWashington1/ | 95 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DeltaAlgo
//@version=5
indicator("Trend Gaussian Channels [DeltaAlgo]", "Trend Gaussian Channels [DeltaAlgo]", true)
// user inputs
length = input.int(25, "Length", 2, 999, 1, inline = "tgc", group = "trend gaussian channel settings")
mult = input.float(1, "", 1, 5, 0.01, "Top & Bottom Band Multiplier", "tgc", "trend gaussian channel settings")
barcol = input.bool(true, "Bar Colors", "Toggle On/Off Candle Colors", group = "candle color settings")
signal = input.bool(true, "Trend Shift Signals", "Toggle On/Off Trend Signals When Trend Shifts", group = "candle color settings")
// gaussian channel
guassianBasis(float source, int length, float mult) =>
basis = ta.ema(ta.hma(ta.sma(source, length), length * 2), length /2)
topBand = basis + (ta.atr(105) * (mult * 1.005))
lowBand = basis - (ta.atr(105) / (mult / 1.005))
[basis, topBand, lowBand]
[base, upper, lower] = guassianBasis(close, length, mult)
upward = base < high
dnward = base > low
basePlot = plot(base, "Base", upward ? color.new(#00cf4b, 15) : color.new(#ff5252, 15), 2)
upperPlot = plot(upper, "Upper", upward ? color.new(#00cf4b, 20) : color.new(#ff5252, 20), 2)
lowerPlot = plot(lower, "Lower", upward ? color.new(#00cf4b, 20) : color.new(#ff5252, 20), 2)
fill(upperPlot, lowerPlot, upward ? color.new(#00cf4b, 80) : color.new(#ff0000, 80), "Channel Fill")
// barcolor
uptrend = color.from_gradient(ta.rsi(close, 15), 25, 76, #67248f, #00cf4b)
ranging = color.from_gradient(ta.rsi(close, 15), 30, 75, #63726f, #67248f)
dntrend = color.from_gradient(ta.rsi(close, 15), 8, 82, #ff0000, #67248f)
barcolor(barcol ? high > upper ? uptrend : high < upper and high > lower ? ranging : dntrend : na)
// signals
upSignalCondition = high > upper and ta.crossover(low, upper)
dnSignalCondition = low < lower and ta.crossunder(high, lower)
plotshape(signal and upSignalCondition, "Bullish Signal", shape.labelup, location.belowbar, color.new(#00cf4b, 35), size = size.small)
plotshape(signal and dnSignalCondition, "Bearish Signal", shape.labeldown, location.abovebar, color.new(#ff0000, 35), size = size.small)
|
typeandcast | https://www.tradingview.com/script/BaG63HpS-typeandcast/ | moebius1977 | https://www.tradingview.com/u/moebius1977/ | 0 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © moebius1977
//@version=5
// @description Contains the following methods:
// _type() - Returns the type of the variable in the forms "int", "array<int>", "matrix<linefill>"
// _type_item() - Returns the type of the variable or of the element (for array/matrix).
// _type_struct() - Returns the type of the structure only (i.e. "array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// tona() - Casts na to the type of the parent object. (e.g. `intVariable.tona()` returns `int(na)`
// cast() - Casts int to float if sampleVar is float. Does nothing otherwise. (May be used to cast const int literals to float in the overloaded functions based on the tyoe of other arguments, e.g. if overloaded function adds a row filled with `1` to a float or int matrix.)
library("typeandcast")
// ====== ======== ====== ======== ====== ======= =======
// ---- _type() / _type_item() / _type_struct() ----- {
//----------- _type () -----------{
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(int _temp)=> na(_temp) ? 'int' : 'int'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(float _temp)=> na(_temp) ? 'float' : 'float'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(bool _temp)=> na(_temp) ? 'bool' : 'bool'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(string _temp)=> na(_temp) ? 'string' : 'string'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(color _temp)=> na(_temp) ? 'color' : 'color'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(line _temp)=> na(_temp) ? 'line' : 'line'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(label _temp)=> na(_temp) ? 'label' : 'label'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(box _temp)=> na(_temp) ? 'box' : 'box'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(table _temp)=> na(_temp) ? 'table' : 'table'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(linefill _temp)=> na(_temp) ? 'linefill' : 'linefill'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(int [] _temp)=> na(_temp) ? 'array<int>' : 'array<int>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(float [] _temp)=> na(_temp) ? 'array<float>' : 'array<float>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(bool [] _temp)=> na(_temp) ? 'array<bool>' : 'array<bool>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(string [] _temp)=> na(_temp) ? 'array<string>' : 'array<string>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(color [] _temp)=> na(_temp) ? 'array<color>' : 'array<color>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(line [] _temp)=> na(_temp) ? 'array<line>' : 'array<line>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(label [] _temp)=> na(_temp) ? 'array<label>' : 'array<label>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(box [] _temp)=> na(_temp) ? 'array<box>' : 'array<box>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(table [] _temp)=> na(_temp) ? 'array<table>' : 'array<table>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(linefill [] _temp)=> na(_temp) ? 'array<linefill>' : 'array<linefill>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(matrix <int> _temp)=> na(_temp) ? 'matrix<int>' : 'matrix<int>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(matrix <float> _temp)=> na(_temp) ? 'matrix<float>' : 'matrix<float>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(matrix <bool> _temp)=> na(_temp) ? 'matrix<bool>' : 'matrix<bool>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(matrix <string> _temp)=> na(_temp) ? 'matrix<string>' : 'matrix<string>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(matrix <color> _temp)=> na(_temp) ? 'matrix<color>' : 'matrix<color>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(matrix <line> _temp)=> na(_temp) ? 'matrix<line>' : 'matrix<line>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(matrix <label> _temp)=> na(_temp) ? 'matrix<label>' : 'matrix<label>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(matrix <box> _temp)=> na(_temp) ? 'matrix<box>' : 'matrix<box>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(matrix <table> _temp)=> na(_temp) ? 'matrix<table>' : 'matrix<table>'
// @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type() // returns "array<int>"
// ```
export method _type(matrix <linefill>_temp)=> na(_temp) ? 'matrix<linefill>' : 'matrix<linefill>'
// END OF _type }
//----------- _type_item () -----------{
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(int _temp)=> na(_temp) ? 'int' : 'int'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(float _temp)=> na(_temp) ? 'float' : 'float'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(bool _temp)=> na(_temp) ? 'bool' : 'bool'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(string _temp)=> na(_temp) ? 'string' : 'string'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(color _temp)=> na(_temp) ? 'color' : 'color'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(line _temp)=> na(_temp) ? 'line' : 'line'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(label _temp)=> na(_temp) ? 'label' : 'label'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(box _temp)=> na(_temp) ? 'box' : 'box'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(table _temp)=> na(_temp) ? 'table' : 'table'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(linefill _temp)=> na(_temp) ? 'linefill' : 'linefill'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(int [] _temp)=> na(_temp) ? 'int' : 'int'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(float [] _temp)=> na(_temp) ? 'float' : 'float'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(bool [] _temp)=> na(_temp) ? 'bool' : 'bool'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(string [] _temp)=> na(_temp) ? 'string' : 'string'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(color [] _temp)=> na(_temp) ? 'color' : 'color'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(line [] _temp)=> na(_temp) ? 'line' : 'line'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(label [] _temp)=> na(_temp) ? 'label' : 'label'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(box [] _temp)=> na(_temp) ? 'box' : 'box'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(table [] _temp)=> na(_temp) ? 'table' : 'table'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(linefill [] _temp)=> na(_temp) ? 'linefill' : 'linefill'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(matrix <int> _temp)=> na(_temp) ? 'int' : 'int'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(matrix <float> _temp)=> na(_temp) ? 'float' : 'float'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(matrix <bool> _temp)=> na(_temp) ? 'bool' : 'bool'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(matrix <string> _temp)=> na(_temp) ? 'string' : 'string'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(matrix <color> _temp)=> na(_temp) ? 'color' : 'color'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(matrix <line> _temp)=> na(_temp) ? 'line' : 'line'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(matrix <label> _temp)=> na(_temp) ? 'label' : 'label'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(matrix <box> _temp)=> na(_temp) ? 'box' : 'box'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(matrix <table> _temp)=> na(_temp) ? 'table' : 'table'
// @function Returns type of the variable or of the element (for array/matrix).
// ```
// int n = 0
// n._type_item() // returns "int"
// arr = array.new<int>()
// arr._type_item() // returns "int"
// ```
export method _type_item(matrix <linefill>_temp)=> na(_temp) ? 'linefill' : 'linefill'
// END OF _type_item }
//----------- _type_struct () -----------{
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(int _temp)=> na(_temp) ? 'simple' : 'simple'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(float _temp)=> na(_temp) ? 'simple' : 'simple'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(bool _temp)=> na(_temp) ? 'simple' : 'simple'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(string _temp)=> na(_temp) ? 'simple' : 'simple'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(color _temp)=> na(_temp) ? 'simple' : 'simple'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(line _temp)=> na(_temp) ? 'simple' : 'simple'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(label _temp)=> na(_temp) ? 'simple' : 'simple'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(box _temp)=> na(_temp) ? 'simple' : 'simple'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(table _temp)=> na(_temp) ? 'simple' : 'simple'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(linefill _temp)=> na(_temp) ? 'simple' : 'simple'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(int [] _temp)=> na(_temp) ? 'array' : 'array'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(float [] _temp)=> na(_temp) ? 'array' : 'array'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(bool [] _temp)=> na(_temp) ? 'array' : 'array'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(string [] _temp)=> na(_temp) ? 'array' : 'array'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(color [] _temp)=> na(_temp) ? 'array' : 'array'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(line [] _temp)=> na(_temp) ? 'array' : 'array'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(label [] _temp)=> na(_temp) ? 'array' : 'array'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(box [] _temp)=> na(_temp) ? 'array' : 'array'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(table [] _temp)=> na(_temp) ? 'array' : 'array'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(linefill [] _temp)=> na(_temp) ? 'array' : 'array'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(matrix <int> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(matrix <float> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(matrix <bool> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(matrix <string> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(matrix <color> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(matrix <line> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(matrix <label> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(matrix <box> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(matrix <table> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// ```
// int n = 0
// n._type_struct() // returns "simple"
// arr = array.new<int>()
// arr._type_struct() // returns "array"
// ```
export method _type_struct(matrix <linefill>_temp)=> na(_temp) ? 'matrix' : 'matrix'
// END OF _type_struct }
// END OF _type }
// ====== ======== ====== ======== ====== ======= =======
// ====== ======== ====== ======== ====== =======
// --------------- tona() -------------- {
// @function Returns na of the same type.
//```
// int n = 0
// n.tona() // returns int(na)
//```
export method tona(int _temp)=> na(_temp) ? int (na) : int (na)
// @function Returns na value of the same type. (e.g. `intVariable.tona()` returns `int(na)`
//```
// int n = 0
// n.tona() // returns int(na)
//```
export method tona(float _temp)=> na(_temp) ? float (na) : float (na)
// @function Returns na value of the same type. (e.g. `intVariable.tona()` returns `int(na)`
//```
// int n = 0
// n.tona() // returns int(na)
//```
export method tona(bool _temp)=> na(_temp) ? bool (na) : bool (na)
// @function Returns na value of the same type. (e.g. `intVariable.tona()` returns `int(na)`
//```
// int n = 0
// n.tona() // returns int(na)
//```
export method tona(string _temp)=> na(_temp) ? string (na) : string (na)
// @function Returns na value of the same type. (e.g. `intVariable.tona()` returns `int(na)`
//```
// int n = 0
// n.tona() // returns int(na)
//```
export method tona(color _temp)=> na(_temp) ? color (na) : color (na)
// @function Returns na value of the same type. (e.g. `intVariable.tona()` returns `int(na)`
//```
// int n = 0
// n.tona() // returns int(na)
//```
export method tona(line _temp)=> na(_temp) ? line (na) : line (na)
// @function Returns na value of the same type. (e.g. `intVariable.tona()` returns `int(na)`
//```
// int n = 0
// n.tona() // returns int(na)
//```
export method tona(label _temp)=> na(_temp) ? label (na) : label (na)
// @function Returns na value of the same type. (e.g. `intVariable.tona()` returns `int(na)`
//```
// int n = 0
// n.tona() // returns int(na)
//```
export method tona(box _temp)=> na(_temp) ? box (na) : box (na)
// @function Returns na value of the same type. (e.g. `intVariable.tona()` returns `int(na)`
//```
// int n = 0
// n.tona() // returns int(na)
//```
export method tona(table _temp)=> na(_temp) ? table (na) : table (na)
// somehow does not work for linefill.....
//export method tona(linefill _temp)=> na(_temp) ? linefill (na) : linefill (na)
// @function Returns na value of the same type. (e.g. `intVariable.tona()` returns `int(na)`
//```
// int n = 0
// n.tona() // returns int(na)
//```
_n(linefill i)=> [i, linefill (na)] // thanks to ©kaigouthro
export method tona(linefill _temp)=> [_tmp, _na] = _n(_temp), _na
// @function Returns na value of the same type as the elements of the parent array. E.g. `arrayFloat.tona()` returns `float(na)`.
//```
// int n = 0
// n.tona() // returns int(na)
//```
export method tona(int [] _temp)=> na(_temp) ? int (na) : int (na)
// @function Returns na value of the same type as the elements of the parent array. E.g. `arrayFloat.tona()` returns `float(na)`.
export method tona(float [] _temp)=> na(_temp) ? float (na) : float (na)
// @function Returns na value of the same type as the elements of the parent array. E.g. `arrayFloat.tona()` returns `float(na)`.
export method tona(bool [] _temp)=> na(_temp) ? bool (na) : bool (na)
// @function Returns na value of the same type as the elements of the parent array. E.g. `arrayFloat.tona()` returns `float(na)`.
export method tona(string [] _temp)=> na(_temp) ? string (na) : string (na)
// @function Returns na value of the same type as the elements of the parent array. E.g. `arrayFloat.tona()` returns `float(na)`.
export method tona(color [] _temp)=> na(_temp) ? color (na) : color (na)
// @function Returns na value of the same type as the elements of the parent array. E.g. `arrayFloat.tona()` returns `float(na)`.
export method tona(line [] _temp)=> na(_temp) ? line (na) : line (na)
// @function Returns na value of the same type as the elements of the parent array. E.g. `arrayFloat.tona()` returns `float(na)`.
export method tona(label [] _temp)=> na(_temp) ? label (na) : label (na)
// @function Returns na value of the same type as the elements of the parent array. E.g. `arrayFloat.tona()` returns `float(na)`.
export method tona(box [] _temp)=> na(_temp) ? box (na) : box (na)
// @function Returns na value of the same type as the elements of the parent array. E.g. `arrayFloat.tona()` returns `float(na)`.
export method tona(table [] _temp)=> na(_temp) ? table (na) : table (na)
// @function Returns na value of the same type as the elements of the parent array. E.g. `arrayFloat.tona()` returns `float(na)`.
_n(linefill[] i)=> [i, linefill (na)] // thanks to ©kaigouthro
export method tona(linefill[] _temp)=> [_tmp, _na] = _n(_temp), _na
// @function Returns na value of the same type as the elements of the parent matrix. E.g. `matrixFloat.tona()` returns `float(na)`.
export method tona(matrix<int > _temp)=> na(_temp) ? int (na) : int (na)
// @function Returns na value of the same type as the elements of the parent matrix. E.g. `matrixFloat.tona()` returns `float(na)`.
export method tona(matrix<float > _temp)=> na(_temp) ? float (na) : float (na)
// @function Returns na value of the same type as the elements of the parent matrix. E.g. `matrixFloat.tona()` returns `float(na)`.
export method tona(matrix<bool > _temp)=> na(_temp) ? bool (na) : bool (na)
// @function Returns na value of the same type as the elements of the parent matrix. E.g. `matrixFloat.tona()` returns `float(na)`.
export method tona(matrix<string> _temp)=> na(_temp) ? string (na) : string (na)
// @function Returns na value of the same type as the elements of the parent matrix. E.g. `matrixFloat.tona()` returns `float(na)`.
export method tona(matrix<color > _temp)=> na(_temp) ? color (na) : color (na)
// @function Returns na value of the same type as the elements of the parent matrix. E.g. `matrixFloat.tona()` returns `float(na)`.
export method tona(matrix<line > _temp)=> na(_temp) ? line (na) : line (na)
// @function Returns na value of the same type as the elements of the parent matrix. E.g. `matrixFloat.tona()` returns `float(na)`.
export method tona(matrix<label > _temp)=> na(_temp) ? label (na) : label (na)
// @function Returns na value of the same type as the elements of the parent matrix. E.g. `matrixFloat.tona()` returns `float(na)`.
export method tona(matrix<box > _temp)=> na(_temp) ? box (na) : box (na)
// @function Returns na value of the same type as the elements of the parent matrix. E.g. `matrixFloat.tona()` returns `float(na)`.
export method tona(matrix<table > _temp)=> na(_temp) ? table (na) : table (na)
// @function Returns na value of the same type as the elements of the parent matrix. E.g. `matrixFloat.tona()` returns `float(na)`.
_n(matrix<linefill> i)=> [i, linefill (na)] // thanks to ©kaigouthro
export method tona(matrix<linefill> _temp)=> [_tmp, _na] = _n(_temp), _na
// END OF tona() }
// ====== ======== ====== ======== ====== =======
// ====== ======== ====== ======== ====== =======
// --------------- cast(int, sampleVar) -------------- {
// @function Casts int to float if sampleVar is float. Does nothing otherwise. (May be used to cast const int literals to float in the overloaded functions based on the tyoe of other arguments, e.g. if overloaded function adds a row filled with `1` to a float or int matrix.)
export method cast(int v, int sampleVar) => na(sampleVar) ? v : v
export method cast(int v, array<int> sampleVar) => na(sampleVar) ? v : v
export method cast(int v, matrix<int> sampleVar) => na(sampleVar) ? v : v
export method cast(int v, float sampleVar) => na(sampleVar) ? float(v) : float(v)
export method cast(int v, array<float> sampleVar) => na(sampleVar) ? float(v) : float(v)
export method cast(int v, matrix<float> sampleVar) => na(sampleVar) ? float(v) : float(v)
export method cast(float v, int sampleVar) => na(sampleVar) ? v : v
export method cast(float v, array<int> sampleVar) => na(sampleVar) ? v : v
export method cast(float v, matrix<int> sampleVar) => na(sampleVar) ? v : v
export method cast(float v, float sampleVar) => na(sampleVar) ? v : v
export method cast(float v, array<float> sampleVar) => na(sampleVar) ? v : v
export method cast(float v, matrix<float> sampleVar) => na(sampleVar) ? v : v
// END OF cast() }
// ====== ======== ====== ======== ====== =======
// ++++++++++++++ ++++++++++++++ ---- ++++++++++++++ ++++++++++++++
// || || || || || || || DEMO || || || || || || || {
int intN = 2
arrayString = array.new<string>()
arrayLine = array.new<line>()
matrixFloat = matrix.new<color>()
linefill[] arrayLinefill = na
matrix<linefill> matrixLinefill = na
if barstate.islastconfirmedhistory
s = str.format("
intN._type() = {0} \n
intN.tona()._type() ={1} \n
arrayString._type() = {2} \n
arrayLine._type_item() = {3} \n
matrixFloat._type_struct() = {4} \n
matrixFloat.tona()._type() = {5} \n
arrayLinefill.tona()._type() = {6}\n
matrixLinefill.tona()._type() = {7}
"
, intN._type()
, intN.tona()._type()
, arrayString._type()
, arrayLine._type_item()
, matrixFloat._type_struct()
, matrixFloat.tona()._type()
, arrayLinefill.tona()._type()
, matrixLinefill.tona()._type()
)
lbl = label.new(bar_index, high, s, color = color.rgb(206, 255, 199), text_font_family = font.family_monospace, textcolor = color.rgb(64, 64, 64))
// END OF DEMO }
// ++++++++++++++ ++++++++++++++ ---- ++++++++++++++ ++++++++++++++
// CONDENSED CODE (without descriptions, easier for bulk editing)
// // ====== ======== ====== ======== ====== ======= =======
// // ---- _type() / _type_item() / _type_struct() ----- {
// //----------- _type () -----------{
// // @function Returns type of variable in the forms "int", "array<int>", "matrix\<linefill\>"
// // ```
// // int n = 0
// // n._type_item() // returns "int"
// // arr = array.new<int>()
// // arr._type() // returns "array<int>"
// // ```
// export method _type(int _temp)=> na(_temp) ? 'int' : 'int'
// export method _type(float _temp)=> na(_temp) ? 'float' : 'float'
// export method _type(bool _temp)=> na(_temp) ? 'bool' : 'bool'
// export method _type(string _temp)=> na(_temp) ? 'string' : 'string'
// export method _type(color _temp)=> na(_temp) ? 'color' : 'color'
// export method _type(line _temp)=> na(_temp) ? 'line' : 'line'
// export method _type(label _temp)=> na(_temp) ? 'label' : 'label'
// export method _type(box _temp)=> na(_temp) ? 'box' : 'box'
// export method _type(table _temp)=> na(_temp) ? 'table' : 'table'
// export method _type(linefill _temp)=> na(_temp) ? 'linefill' : 'linefill'
// export method _type(int [] _temp)=> na(_temp) ? 'array<int>' : 'array<int>'
// export method _type(float [] _temp)=> na(_temp) ? 'array<float>' : 'array<float>'
// export method _type(bool [] _temp)=> na(_temp) ? 'array<bool>' : 'array<bool>'
// export method _type(string [] _temp)=> na(_temp) ? 'array<string>' : 'array<string>'
// export method _type(color [] _temp)=> na(_temp) ? 'array<color>' : 'array<color>'
// export method _type(line [] _temp)=> na(_temp) ? 'array<line>' : 'array<line>'
// export method _type(label [] _temp)=> na(_temp) ? 'array<label>' : 'array<label>'
// export method _type(box [] _temp)=> na(_temp) ? 'array<box>' : 'array<box>'
// export method _type(table [] _temp)=> na(_temp) ? 'array<table>' : 'array<table>'
// export method _type(linefill [] _temp)=> na(_temp) ? 'array<linefill>' : 'array<linefill>'
// export method _type(matrix <int> _temp)=> na(_temp) ? 'matrix<int>' : 'matrix<int>'
// export method _type(matrix <float> _temp)=> na(_temp) ? 'matrix<float>' : 'matrix<float>'
// export method _type(matrix <bool> _temp)=> na(_temp) ? 'matrix<bool>' : 'matrix<bool>'
// export method _type(matrix <string> _temp)=> na(_temp) ? 'matrix<string>' : 'matrix<string>'
// export method _type(matrix <color> _temp)=> na(_temp) ? 'matrix<color>' : 'matrix<color>'
// export method _type(matrix <line> _temp)=> na(_temp) ? 'matrix<line>' : 'matrix<line>'
// export method _type(matrix <label> _temp)=> na(_temp) ? 'matrix<label>' : 'matrix<label>'
// export method _type(matrix <box> _temp)=> na(_temp) ? 'matrix<box>' : 'matrix<box>'
// export method _type(matrix <table> _temp)=> na(_temp) ? 'matrix<table>' : 'matrix<table>'
// export method _type(matrix <linefill>_temp)=> na(_temp) ? 'matrix<linefill>' : 'matrix<linefill>'
// // END OF _type }
// //----------- _type_item () -----------{
// // @function Returns type of variable or the element for array/matrix.
// // ```
// // int n = 0
// // n._type_item() // returns "int"
// // arr = array.new<int>()
// // arr._type_item() // returns "int"
// // ```
// export method _type_item(int _temp)=> na(_temp) ? 'int' : 'int'
// export method _type_item(float _temp)=> na(_temp) ? 'float' : 'float'
// export method _type_item(bool _temp)=> na(_temp) ? 'bool' : 'bool'
// export method _type_item(string _temp)=> na(_temp) ? 'string' : 'string'
// export method _type_item(color _temp)=> na(_temp) ? 'color' : 'color'
// export method _type_item(line _temp)=> na(_temp) ? 'line' : 'line'
// export method _type_item(label _temp)=> na(_temp) ? 'label' : 'label'
// export method _type_item(box _temp)=> na(_temp) ? 'box' : 'box'
// export method _type_item(table _temp)=> na(_temp) ? 'table' : 'table'
// export method _type_item(linefill _temp)=> na(_temp) ? 'linefill' : 'linefill'
// export method _type_item(int [] _temp)=> na(_temp) ? 'int' : 'int'
// export method _type_item(float [] _temp)=> na(_temp) ? 'float' : 'float'
// export method _type_item(bool [] _temp)=> na(_temp) ? 'bool' : 'bool'
// export method _type_item(string [] _temp)=> na(_temp) ? 'string' : 'string'
// export method _type_item(color [] _temp)=> na(_temp) ? 'color' : 'color'
// export method _type_item(line [] _temp)=> na(_temp) ? 'line' : 'line'
// export method _type_item(label [] _temp)=> na(_temp) ? 'label' : 'label'
// export method _type_item(box [] _temp)=> na(_temp) ? 'box' : 'box'
// export method _type_item(table [] _temp)=> na(_temp) ? 'table' : 'table'
// export method _type_item(linefill [] _temp)=> na(_temp) ? 'linefill' : 'linefill'
// export method _type_item(matrix <int> _temp)=> na(_temp) ? 'int' : 'int'
// export method _type_item(matrix <float> _temp)=> na(_temp) ? 'float' : 'float'
// export method _type_item(matrix <bool> _temp)=> na(_temp) ? 'bool' : 'bool'
// export method _type_item(matrix <string> _temp)=> na(_temp) ? 'string' : 'string'
// export method _type_item(matrix <color> _temp)=> na(_temp) ? 'color' : 'color'
// export method _type_item(matrix <line> _temp)=> na(_temp) ? 'line' : 'line'
// export method _type_item(matrix <label> _temp)=> na(_temp) ? 'label' : 'label'
// export method _type_item(matrix <box> _temp)=> na(_temp) ? 'box' : 'box'
// export method _type_item(matrix <table> _temp)=> na(_temp) ? 'table' : 'table'
// export method _type_item(matrix <linefill>_temp)=> na(_temp) ? 'linefill' : 'linefill'
// // END OF _type_item }
// //----------- _type_struct () -----------{
// // @function Returns type of the structure only ("array" or "matrix"), for simple types (like e.g. `int`) returns "simple"
// // ```
// // int n = 0
// // n._type_struct() // returns "simple"
// // arr = array.new<int>()
// // arr._type_struct() // returns "array"
// // ```
// export method _type_struct(int _temp)=> na(_temp) ? 'simple' : 'simple'
// export method _type_struct(float _temp)=> na(_temp) ? 'simple' : 'simple'
// export method _type_struct(bool _temp)=> na(_temp) ? 'simple' : 'simple'
// export method _type_struct(string _temp)=> na(_temp) ? 'simple' : 'simple'
// export method _type_struct(color _temp)=> na(_temp) ? 'simple' : 'simple'
// export method _type_struct(line _temp)=> na(_temp) ? 'simple' : 'simple'
// export method _type_struct(label _temp)=> na(_temp) ? 'simple' : 'simple'
// export method _type_struct(box _temp)=> na(_temp) ? 'simple' : 'simple'
// export method _type_struct(table _temp)=> na(_temp) ? 'simple' : 'simple'
// export method _type_struct(linefill _temp)=> na(_temp) ? 'simple' : 'simple'
// export method _type_struct(int [] _temp)=> na(_temp) ? 'array' : 'array'
// export method _type_struct(float [] _temp)=> na(_temp) ? 'array' : 'array'
// export method _type_struct(bool [] _temp)=> na(_temp) ? 'array' : 'array'
// export method _type_struct(string [] _temp)=> na(_temp) ? 'array' : 'array'
// export method _type_struct(color [] _temp)=> na(_temp) ? 'array' : 'array'
// export method _type_struct(line [] _temp)=> na(_temp) ? 'array' : 'array'
// export method _type_struct(label [] _temp)=> na(_temp) ? 'array' : 'array'
// export method _type_struct(box [] _temp)=> na(_temp) ? 'array' : 'array'
// export method _type_struct(table [] _temp)=> na(_temp) ? 'array' : 'array'
// export method _type_struct(linefill [] _temp)=> na(_temp) ? 'array' : 'array'
// export method _type_struct(matrix <int> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// export method _type_struct(matrix <float> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// export method _type_struct(matrix <bool> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// export method _type_struct(matrix <string> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// export method _type_struct(matrix <color> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// export method _type_struct(matrix <line> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// export method _type_struct(matrix <label> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// export method _type_struct(matrix <box> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// export method _type_struct(matrix <table> _temp)=> na(_temp) ? 'matrix' : 'matrix'
// export method _type_struct(matrix <linefill>_temp)=> na(_temp) ? 'matrix' : 'matrix'
// // END OF _type_struct }
// // END OF _type }
// // ====== ======== ====== ======== ====== ======= =======
// // ====== ======== ====== ======== ====== =======
// // --------------- tona() -------------- {
// // @function Returns na of the same type.
// //```
// // int n = 0
// // n.tona() // returns int(na)
// //```
// export method tona(int _temp)=> na(_temp) ? int (na) : int (na)
// export method tona(float _temp)=> na(_temp) ? float (na) : float (na)
// export method tona(bool _temp)=> na(_temp) ? bool (na) : bool (na)
// export method tona(string _temp)=> na(_temp) ? string (na) : string (na)
// export method tona(color _temp)=> na(_temp) ? color (na) : color (na)
// export method tona(line _temp)=> na(_temp) ? line (na) : line (na)
// export method tona(label _temp)=> na(_temp) ? label (na) : label (na)
// export method tona(box _temp)=> na(_temp) ? box (na) : box (na)
// export method tona(table _temp)=> na(_temp) ? table (na) : table (na)
// // export method tona(linefill _temp)=> na(_temp) ? linefill (na) : linefill (na)
// export method tona(int [] _temp)=> na(_temp) ? int (na) : int (na)
// export method tona(float [] _temp)=> na(_temp) ? float (na) : float (na)
// export method tona(bool [] _temp)=> na(_temp) ? bool (na) : bool (na)
// export method tona(string [] _temp)=> na(_temp) ? string (na) : string (na)
// export method tona(color [] _temp)=> na(_temp) ? color (na) : color (na)
// export method tona(line [] _temp)=> na(_temp) ? line (na) : line (na)
// export method tona(label [] _temp)=> na(_temp) ? label (na) : label (na)
// export method tona(box [] _temp)=> na(_temp) ? box (na) : box (na)
// export method tona(table [] _temp)=> na(_temp) ? table (na) : table (na)
// _n(linefill[] i)=> [i, linefill (na)] // thanks to ©kaigouthro
// method tona(linefill[] _temp)=> [_tmp, _na] = _n(_temp), _na
// export method tona(matrix<int > _temp)=> na(_temp) ? int (na) : int (na)
// export method tona(matrix<float > _temp)=> na(_temp) ? float (na) : float (na)
// export method tona(matrix<bool > _temp)=> na(_temp) ? bool (na) : bool (na)
// export method tona(matrix<string> _temp)=> na(_temp) ? string (na) : string (na)
// export method tona(matrix<color > _temp)=> na(_temp) ? color (na) : color (na)
// export method tona(matrix<line > _temp)=> na(_temp) ? line (na) : line (na)
// export method tona(matrix<label > _temp)=> na(_temp) ? label (na) : label (na)
// export method tona(matrix<box > _temp)=> na(_temp) ? box (na) : box (na)
// export method tona(matrix<table > _temp)=> na(_temp) ? table (na) : table (na)
// _n(matrix<linefill> i)=> [i, linefill (na)] // thanks to ©kaigouthro
// method tona(matrix<linefill> _temp)=> [_tmp, _na] = _n(_temp), _na
// // END OF tona() }
// // ====== ======== ====== ======== ====== =======
|
MA Slope [EMA Magic] | https://www.tradingview.com/script/lhTNgJJp-MA-Slope-EMA-Magic/ | KiomarsRakei | https://www.tradingview.com/u/KiomarsRakei/ | 34 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KiomarsRakei
//@version=5
indicator("MA Slope [EMA Magic]",format=format.percent, precision = 3)
ma(source, length, type) =>
type == "SMA" ? ta.sma(source, length) :
type == "EMA" ? ta.ema(source, length) :
type == "WMA" ? ta.wma(source, length) :
type == "VWMA" ? ta.vwma(source, length) :
na
//
tf_i = input.timeframe(defval = "",title = "Indicator Timeframe")
ma_type = input.string("EMA" ,title="MA", group="Calculations",inline="1", options=["SMA", "EMA", "WMA", "VWMA"])
ma_source = input(close,title="", group="Calculations",inline="1")
ma_length = input.int(67,title="", group="Calculations", minval=1,inline="1")
ma = ma(ma_source, ma_length, ma_type)
matf=request.security(symbol=syminfo.tickerid,timeframe=tf_i,expression=ma,gaps = barmerge.gaps_on)
atr_i = input.int(defval= 7,title="ATR",options=[3,7,14],group= "Calculations",tooltip= "Better not to change")
atr = ta.atr(atr_i)
atrtf=request.security(symbol=syminfo.tickerid,timeframe=tf_i,expression=atr,gaps = barmerge.gaps_on)
change_i= input.bool(defval=false,title="Sudden Change",group="Signal",inline="1")
change_i2=input.float(defval=0.099,title="Value",group = "Signal",inline="1")
breakout_i= input.bool(defval=false,title="Slope Breakout",group="Signal",inline="2")
band_i= input.float(defval= 0.075,title= "Limit",group= "Signal",inline= "2",minval= 0.001, maxval=0.999 )
//
diff = ma-ma[3]
maslope= diff/atr
maslopetf= request.security(symbol = syminfo.tickerid,timeframe=tf_i,expression = maslope)
plot(maslopetf,title="MA Slope",color=color.red)
upline= hline(band_i,title="Upper Band",linestyle = hline.style_solid)
hline(0.0,editable = false)
downline=hline(band_i * -1,title="Lower Band",linestyle= hline.style_solid)
sudden = maslopetf > maslopetf[1] + change_i2 or maslopetf < maslopetf[1] - change_i2
suddenchange = sudden and change_i
alertcondition(suddenchange,title="Sudden Change")
bgcolor(suddenchange==true ? color.rgb(230, 36, 36, 70) : na ,title="Sudden Change")
crossmatfup= ta.crossover(maslopetf,band_i)
crossmatfdown= ta.crossunder(maslopetf,band_i * -1)
if breakout_i == false
crossmatfup:= false
crossmatfdown :=false
for i=1 to 9
if crossmatfup[i] == true
crossmatfup := false
for i=1 to 9
if crossmatfdown[i] == true
crossmatfdown := false
anycross= crossmatfup or crossmatfdown
alertcondition(anycross,title="Slope Breakout")
bgcolor(crossmatfup == true or crossmatfdown == true ? color.rgb(240, 13, 164, 70) : na,title= "Slope Breakout") |
WebhookJsonMsg | https://www.tradingview.com/script/7j9udc1j-WebhookJsonMsg/ | IncSilence | https://www.tradingview.com/u/IncSilence/ | 24 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © GlassCat
//@version=5
// @description This webhook json message library provides convenient functions for building JSON messages
// Used to manage automatic transaction orders and positions
library("WebhookJsonMsg", overlay = true)
// @type Define some constant values
// @field <string> OPEN_LONG open_long. Used in WebhookMessage.orderSide.
// @field <string> OPEN_SHORT open_short. Used in WebhookMessage.orderSide.
// @field <string> CLOSE_LONG close_long. Used in WebhookMessage.orderSide.
// @field <string> CLOSE_SHORT close_short. Used in WebhookMessage.orderSide.
// @field <string> LIMIT limit. Used in WebhookMessage.orderType.
// @field <string> MARKET market. Used in WebhookMessage.orderType.
// @field <string> U_MARGIN U-Margin. Used in WebhookMessage.symbolType.
// @field <string> C_MARGIN C-Margin. Used in WebhookMessage.symbolType.
// @field <string> SPOT SPOT. Used in WebhookMessage.symbolType.
export type Dict
OPEN_LONG = "open_long"
OPEN_SHORT = "open_short"
CLOSE_LONG = "close_long"
CLOSE_SHORT = "close_short"
LIMIT = "limit"
MARKET = "market"
U_MARGIN = "U-Margin"
C_MARGIN = "C-Margin"
SPOT = "Spot"
DictObj = Dict.new()
// @type Webhook message structure.
// @field <string> strategyId - your strategy id.
// @field <string> signalNo - Signal No, used to track current signals.
// @field <string> relatedSignalNo - Related Signal No, used to track previous signals, you can close specified order using this field.
// @field <string> symbol - symbol.
// @field <string> symbolType - symbol type.
// @field <string> orderSide - order side.
// @field <string> price - price for limit order type.
// @field <string> orderType - order type.
// @field <string> takeProfitPrice - take profit price.
// @field <string> stopLossPrice - stop loss price.
// @field <string> timestamp - Unix timestamp (millisecond).
// @field <string> accessKey - your strategy access key.
// @field <string> positionRatio - control position ratio.
export type WebhookMessage
string strategyId
string signalNo
string relatedSignalNo
string symbol
string symbolType
string orderSide
string price
string orderType
string takeProfitPrice
string stopLossPrice
string timestamp
string accessKey
string positionRatio
// @function Builds the final JSON payload from a WebhookMessage type.
// @param WebhookMessage msg A prepared WebhookMessage.
// @returns <string> A JSON Payload.
export method buildWebhookJson(WebhookMessage msg) =>
json = "{"
json += '"library": "GlassCat/WebhookMessage"'
json += ',"strategyId": "' + msg.strategyId + '"'
if (msg.signalNo != "")
json += ',"signalNo": "' + msg.signalNo + '"'
if (msg.relatedSignalNo != "")
json += ',"relatedSignalNo": "' + msg.relatedSignalNo + '"'
json += ',"symbol": "' + (msg.symbol == "" ? syminfo.basecurrency + syminfo.currency : msg.symbol) + '"'
json += ',"symbolType": "' + (msg.symbolType == "" ? DictObj.U_MARGIN : msg.symbolType) + '"'
json += ',"orderSide": "' + msg.orderSide + '"'
json += ',"accessKey": "' + msg.accessKey + '"'
if (msg.orderType != "")
json += ',"orderType": "' + msg.orderType + '"'
if (msg.orderType == DictObj.LIMIT)
json += ',"price": "' + msg.price + '"'
if (msg.timestamp != "")
json += ',"timestamp": "' + msg.timestamp + '"'
else
json += ',"timestamp": "' + str.tostring(timenow) + '"'
if (msg.takeProfitPrice != "")
json += ',"takeProfitPrice": "' + msg.takeProfitPrice + '"'
if (msg.stopLossPrice != "")
json += ',"stopLossPrice": "' + msg.stopLossPrice + '"'
if (msg.positionRatio != "")
json += ',"positionRatio": "' + msg.positionRatio + '"'
json += "}"
json
//plot nothing to pass publishing rules
plot(na) |
Mad_Standardparts | https://www.tradingview.com/script/VUZvDQYC-Mad-Standardparts/ | djmad | https://www.tradingview.com/u/djmad/ | 4 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © djmad
//@version=5
// @description TODO: add library description here
library("Mad_Standardparts")
// @function Round a floating point value to a specified number of decimal places.
// @description This function takes a floating point value and rounds it to a specified number of decimal places.
// @param _value The floating point value to be rounded.
// @param _decimals The number of decimal places to round to. Must be a non-negative integer. OVERLOAD bring in a preselector format as string
// @returns The rounded value, as a string.
export round_to_Str(float _value, int _decimals) =>
result = str.tostring(math.round(_value * math.pow(10, _decimals)) / math.pow(10, _decimals))
export round_to_Str(float _value, string _decimals_s) =>
result = str.tostring(_value, _decimals_s)
export method removeDeleteAll(array<line> ln) =>
int size = ln.size()
for i = size > 0 ? size - 1 : na to 0
ln.pop().delete()
export method removeDeleteAll(array<linefill> ln) =>
int size = ln.size()
for i = size > 0 ? size - 1 : na to 0
ln.pop().delete()
export method removeDeleteAll(array<label> ln) =>
int size = ln.size()
for i = size > 0 ? size - 1 : na to 0
ln.pop().delete()
export method removeDeleteAll(array<box> ln) =>
int size = ln.size()
for i = size > 0 ? size - 1 : na to 0
ln.pop().delete()
// @function Delete all drawings on the chart.
// @description This function deletes all drawings on the chart, including lines, boxes, fills and labels.
// @returns None.
export clear_all() =>
line.all.removeDeleteAll()
label.all.removeDeleteAll()
linefill.all.removeDeleteAll()
box.all.removeDeleteAll()
// @function Create a string of spaces to shift text over by a specified amount.
// @description This function takes an integer value and returns a string consisting of that many spaces, which can be used to shift text over in a PineScript chart.
// @param _value The number of spaces to create in the output string.
// @returns A string consisting of the specified number of spaces.
export shifting(int _value) =>
var string output = ""
output := ""
for i = 0 to _value by 1
output := output + " "
// @function Convert a linear value to a logarithmic value.
// @description This function takes a linear value and converts it to a logarithmic value, using the formula specified in the code.
// @param value The linear value to be converted to a logarithmic value.
// @returns The corresponding logarithmic value, as a floating point number.
export fromLog(float _value) =>
float logical_offset = 4
float coord_offset = 0.0001
float exponent = math.abs(_value)
float product = math.pow(10, exponent - logical_offset) - coord_offset
float result = exponent < 1e-8 ? 0 : _value < 0 ? - product : product
// @function Convert a logarithmic value to a linear value.
// @description This function takes a logarithmic value and converts it to a linear value, using the formula specified in the code.
// @param value The logarithmic value to be converted to a linear value.
// @returns The corresponding linear value, as a floating point number.
export toLog(float _value) =>
float logical_offset = 4
float coord_offset = 0.0001
float exponent = math.abs(_value)
float product = math.log10(exponent + coord_offset) + logical_offset
float result = exponent < 1e-8 ? 0 : _value < 0 ? - product : product
// @function Calculate the time per bar on the chart.
// @description This function calculates the time per bar on the chart based on the first 100 bars. Usefull when we have exchanges with timegaps
// @returns The time per bar, as an integer value.
export f_getbartime() =>
var int firstbartime = 0, var int lastbartime = 0
var bool locked1 = false
var bool locked2 = false
var bool locked3 = false
var int counter = 0
var int difftime = 0
var int timeperbar = na
if locked1 == false
firstbartime := time
counter := 0
locked1 := true
if counter == 100 and locked2 == false
lastbartime := time
locked2 := true
if locked3 == false and locked2 == true
difftime := lastbartime - firstbartime
timeperbar := difftime / counter
locked3 := true
if locked3 != true
counter += 1
timeperbar
///// Fibonacci Box {
// @types for defining a fill group with corresponding color
export type type_fill
int partner_A = na
int partner_B = na
color fill_color = na
// @types for defining a fibonacci box
export type type_Fibonacci_box
float bottom_price = na
float top_price = na
int StartBar = na
int StopBar = na
array<float> levels = na
array<float> prices = na
array<type_fill> fills = na
bool ChartisLog = na
bool fibreverse = na
color fiblinecolor = na
color fibtextcolor = na
string fibtextsize = size.auto
int decimals_price = 2
int decimals_percent = 2
int transp = na
bool drawlines = true
bool drawlabels = true
bool drawfills = true
// @function fibonacci calc.
// @description This function block uses the levels and paramters set into the type_fibonacci_box(levels) and fills the corresponding array of prices.
// @returns returns a type_Fibonacci_box with the filled data
export f_fib_calc(type_Fibonacci_box _Fibonacci_box) =>
var type_Fibonacci_box _get_RW = _Fibonacci_box
float Diff = _get_RW.top_price-_get_RW.bottom_price
if not _get_RW.fibreverse
for i = 0 to array.size(_get_RW.levels) -1
if _get_RW.ChartisLog
array.set(_get_RW.prices, i, fromLog( toLog(_get_RW.bottom_price) + (toLog(_get_RW.top_price)-toLog(_get_RW.bottom_price)) * array.get(_get_RW.levels,i) ))
else
array.set(_get_RW.prices, i, (_get_RW.bottom_price) + (Diff) * (array.get(_get_RW.levels,i)))
_get_RW
else
for i =-(array.size(_get_RW.levels) -1) to 0
if _get_RW.ChartisLog
array.set(_get_RW.prices, -i, fromLog( toLog(_get_RW.bottom_price) + (toLog(_get_RW.top_price)-toLog(_get_RW.bottom_price)) * array.get(_get_RW.levels,-i) ))
else
array.set(_get_RW.prices, -i, (_get_RW.bottom_price) + (Diff) * (array.get(_get_RW.levels,-i)))
_get_RW
_get_RW
// @function fibonacci draw.
// @description This function block uses the levels, prices and paramters set into the type_fibonacci_box(levels) and draws the fib on the chart
// @returns returns lines labels and fills on the chart, no data returns
export f_fib_draw(type_Fibonacci_box _Fibonacci_box) =>
var line [] line_array = array.new_line(array.size(_Fibonacci_box.levels), line.new(x1 = na, y1 = na, x2 = na, y2 = na))
var linefill [] linefill_array = array.new_linefill(0, linefill.new(line1 = na, line2 = na, color = na))
var label [] label_array = array.new_label(0, label.new(x = na, y = na))
line line_1 = na
linefill fill_1 = na
label label1 = na
label label2 = na
line_array.removeDeleteAll()
label_array.removeDeleteAll()
linefill_array.removeDeleteAll()
for i = 0 to array.size(_Fibonacci_box.levels)-1
line_array.push(line.new(x1= _Fibonacci_box.StartBar, y1= array.get(_Fibonacci_box.prices,i),
x2 = _Fibonacci_box.StopBar,
y2 = array.get(_Fibonacci_box.prices,i),
xloc=xloc.bar_index,
style=line.style_solid,
extend=extend.none,
color=_Fibonacci_box.drawlines?_Fibonacci_box.fiblinecolor:color.new(color.black,100)))
if _Fibonacci_box.drawlabels
label_array.push(label.new(x=_Fibonacci_box.StopBar+20, y= array.get(_Fibonacci_box.prices,i),
text = ' ' + str.tostring(_Fibonacci_box.fibreverse?(1-array.get(_Fibonacci_box.levels,i)):array.get(_Fibonacci_box.levels,i)) + ' (' + str.tostring(round_to_Str(array.get(_Fibonacci_box.prices,i),_Fibonacci_box.decimals_price)) + ') ' +
str.tostring(round_to_Str(array.get(_Fibonacci_box.prices,i)/close*100-100,_Fibonacci_box.decimals_percent)) + '% = ' + str.tostring(round_to_Str(array.get(_Fibonacci_box.prices,i)-close,_Fibonacci_box.decimals_price)),
xloc=xloc.bar_index,
yloc=yloc.price,
color=_Fibonacci_box.fibtextcolor,
style=label.style_none,
textcolor=_Fibonacci_box.fibtextcolor,
size=_Fibonacci_box.fibtextsize,
textalign=text.align_left))
if i == 8 and _Fibonacci_box.drawlabels
label_array.push(label.new(x=_Fibonacci_box.StopBar+20, y= array.get(_Fibonacci_box.prices,i),
text = 'Range-Up = ' + str.tostring(round_to_Str(array.get(_Fibonacci_box.prices,0)/array.get(_Fibonacci_box.prices,8)*100-100,_Fibonacci_box.decimals_percent)) + '% / ' +
str.tostring(round_to_Str(array.get(_Fibonacci_box.prices,0)-array.get(_Fibonacci_box.prices,8),_Fibonacci_box.decimals_price)) +
'\nRange-Down = ' + str.tostring(round_to_Str(array.get(_Fibonacci_box.prices,8)/array.get(_Fibonacci_box.prices,0)*100-100,_Fibonacci_box.decimals_percent)) + '%\n',
xloc=xloc.bar_index,
yloc=yloc.price,
color=_Fibonacci_box.fibtextcolor,
style=label.style_none,
textcolor=_Fibonacci_box.fibtextcolor,
size=_Fibonacci_box.fibtextsize,
textalign=text.align_left))
if _Fibonacci_box.drawfills
for i_F = 0 to array.size(_Fibonacci_box.fills) - 1
var type_fill _get_RO = na
_get_RO := array.get(_Fibonacci_box.fills,i_F)
for i_LA = 0 to (array.size(_Fibonacci_box.prices) - 1)
if _get_RO.partner_A == i_LA and _get_RO.partner_B <= array.size(_Fibonacci_box.prices) and _get_RO.partner_B >= 0
linefill_array.push(linefill.new(line1 = array.get(line_array,i_LA), line2 = array.get(line_array,_get_RO.partner_B),color = _get_RO.fill_color))
///// Fibonacci Box }
//demo implementation {
var type_Fibonacci_box Fibonacci_box = type_Fibonacci_box.new()
Fibonacci_box.levels := array.new<float>(0,na)
//
Fibonacci_box.bottom_price := ta.lowest(500)
Fibonacci_box.top_price := ta.highest(500)
Fibonacci_box.StartBar := bar_index -500
Fibonacci_box.StopBar := bar_index
//
Fibonacci_box.fibreverse := input.bool(false,'Reverse Fib',group='Global', inline='11a')
Fibonacci_box.ChartisLog := input.bool(false,'Logarithmic',group='Global',inline='11a')
Fibonacci_box.decimals_price := input.int(2,'Price decimals',group='decimals trimming',inline='1')
Fibonacci_box.decimals_percent := input.int(2,'Percent decimals',group='decimals trimming',inline='1')
//
Fibonacci_box.fibtextcolor := input.color(color.rgb(128, 128, 128),'Text color',group='Global',inline='1a')
Fibonacci_box.fibtextsize := input.string(size.small,'size', options = [size.tiny,size.small,size.normal,size.large],group='Global',inline='1a')
Fibonacci_box.fiblinecolor := input.color(color.rgb(126, 126, 126),'Linecolor',inline='1a')
Fibonacci_box.transp := input.int(60,'Transparency fillings',group='Fillings')
Fibonacci_box.drawlines := true
Fibonacci_box.drawfills := true
Fibonacci_box.drawlabels := true
//
array.push(Fibonacci_box.levels, input.float(1.0 ,'Level 0',group='Fiblevels 01',step=0.001))
array.push(Fibonacci_box.levels, input.float(0.786 ,'Level 1',group='Fiblevels 01',step=0.001,inline='1a'))
array.push(Fibonacci_box.levels, input.float(0.65 ,'Level 2',group='Fiblevels 23',step=0.001))
array.push(Fibonacci_box.levels, input.float(0.618 ,'Level 3',group='Fiblevels 23',step=0.001,inline='1b'))
array.push(Fibonacci_box.levels, input.float(0.5 ,'Level 4',group='Fiblevels 4',step=0.001))
array.push(Fibonacci_box.levels, input.float(0.382 ,'Level 5',group='Fiblevels 56',step=0.001 ))
array.push(Fibonacci_box.levels, input.float(0.35 ,'Level 6',group='Fiblevels 56',step=0.001,inline='1c'))
array.push(Fibonacci_box.levels, input.float(0.236 ,'Level 7',group='Fiblevels 78',step=0.001 ))
array.push(Fibonacci_box.levels, input.float(0.0 ,'Level 8',group='Fiblevels 78',step=0.001,inline='1d'))
//
Fibonacci_box.prices := array.new<float>(array.size(Fibonacci_box.levels),0)
Fibonacci_box.fills := array.new<type_fill>(0, type_fill.new(partner_A = na, partner_B = na, fill_color = na))
//
_1A = input(0, "partner1_A", group="Fill 1")
_1B = input(1, "partner1_B", group="Fill 1")
_1C = color.new(input.color(color.rgb(175, 76, 76, 0),'Fill-Color 0-1',group="Fill 1",inline='1a'),Fibonacci_box.transp)
_2A = input(2, "partner2_A", group="Fill 2")
_2B = input(3, "partner2_B", group="Fill 2")
_2C = color.new(input.color(color.rgb(175, 172, 76, 0),'Fill-Color 2-3',group="Fill 2",inline='1b'),Fibonacci_box.transp)
_3A = input(5, "partner3_A", group="Fill 3")
_3B = input(6, "partner3_B", group="Fill 3")
_3C = color.new(input.color(color.rgb(175, 172, 76, 0),'Fill-Color 5-6',group="Fill 3",inline='1c'),Fibonacci_box.transp)
_4A = input(7, "partner4_A", group="Fill 4")
_4B = input(8, "partner4_B", group="Fill 4")
_4C = color.new(input.color(color.rgb(76, 175, 79, 0),'Fill-Color 7-8',group="Fill 4",inline='1d'),Fibonacci_box.transp)
//
array.push(Fibonacci_box.fills,(type_fill.new(partner_A = _1A, partner_B = _1B, fill_color = _1C)))
array.push(Fibonacci_box.fills,(type_fill.new(partner_A = _2A, partner_B = _2B, fill_color = _2C)))
array.push(Fibonacci_box.fills,(type_fill.new(partner_A = _3A, partner_B = _3B, fill_color = _3C)))
array.push(Fibonacci_box.fills,(type_fill.new(partner_A = _4A, partner_B = _4B, fill_color = _4C)))
Fibonacci_box := f_fib_calc(Fibonacci_box)
f_fib_draw(Fibonacci_box)
// } |
Mizar_Library | https://www.tradingview.com/script/UICSx5Kq-Mizar-Library/ | Mizar_trading | https://www.tradingview.com/u/Mizar_trading/ | 10 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Mizar Library to send JSON commands to DCA bots
// version 1.0 - May 2023
// Intellectual property © Mizar.com
// Mizar public library
//@version=5
// @description Provides general functions to use Mizar DCA bot system
library("Mizar_Library", overlay = true)
// ************************************
// ** BOT functions ***
// ************************************
// @type Bot_params
export type bot_params
string bot_id = "#nil"
string api_key = "#nil"
string action = "open"
string tp_perc = "#nil"
string base_asset = "#nil"
string quote_asset = "USDT"
string direction = "#nil"
// @function DCA_bot_msg
// @param _cmd ::: the user-defined type [UDT] with all the info for the bot command
// @param - bot_id ::: the BOT ID number from your Mizar bot
// @param - api_key ::: your private (do not share!) API key from your Mizar account
// @param - action ::: the command to perform: "open" [standard] or "close"
// @param - tp_perc ::: the target price in percentage (1% = "0.01")
// @param - base_asset ::: the coin you want to buy (e.g. "BTC")
// @param - quote_asset ::: the coin with which you want to pay (e.g. "USDT" [standard])
// @param - direction ::: the direction of the position: "long" or "short"
// @returns A string with the complete JSON command for a Mizar DCA bot.
export DCA_bot_msg(bot_params _cmd) =>
string _msg = '{ "bot_id": "' + _cmd.bot_id + '", "api_key": "' + _cmd.api_key + '", "base_asset": "' + _cmd.base_asset + '", "quote_asset": "' + _cmd.quote_asset + '", "action": "' + _cmd.action + "-position"
if _cmd.tp_perc != "#nil"
_msg += '", "take_profit_pct": "' + _cmd.tp_perc
if _cmd.direction != "#nil"
_msg += '", "side": "' + _cmd.direction
_msg += '" }'
// ************************************
// ** Support functions ***
// ************************************
// @function rounding_to_ticks
// @param value ::: the calculated price as float type, which should be rounded to the next real price
// @param ticks ::: the smallest possible price (you get via request in your script)
// @param rounding_type ::: 0 = closest real price, 1 = closest real price above, 2 = closest real price below
// @returns A float with the rounded value to the next tick.
export rounding_to_ticks(float value, float ticks, int rounding_type) =>
float fun_return = na
int factor = na
float sym_in_ticks = math.round(value/ticks, 0)
if sym_in_ticks * ticks > value
factor := 0
else
factor := 1
if rounding_type != 1 and rounding_type != 2 // Standard rounding to closest CEX tick
fun_return := sym_in_ticks * ticks
if rounding_type == 1 // Rounding to the next CEX tick above the calculated price
fun_return := (sym_in_ticks + factor) * ticks
if rounding_type == 2 // Rounding to the next CEX tick below the calculated price
fun_return := (sym_in_ticks - 1 + factor) * ticks
fun_return |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.