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
|
---|---|---|---|---|---|---|---|---|
Fair Value Gap (FVG) Underlay | https://www.tradingview.com/script/ScDbozSU-Fair-Value-Gap-FVG-Underlay/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 65 | 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/
// © LeafAlgo
//@version=5
indicator("Fair Value Gap (FVG)", overlay=false)
// Calculation Inputs
bodyToWickRatioThreshold = input(0.7, "Body-to-Wick Ratio Threshold")
lookbackPeriod = input(20, "Lookback Period")
// Calculate Body-to-Wick Ratio
bodySize = math.abs(open - close)
wickSize = high - low
bodyToWickRatio = bodySize / wickSize
// Determine Fair Value Gap (FVG)
isBearishFVG = ta.change(close, 1) < 0 and bodyToWickRatio >= bodyToWickRatioThreshold
isBullishFVG = ta.change(close, 1) > 0 and bodyToWickRatio >= bodyToWickRatioThreshold
// Calculate FVG Percentage
fvgPercentage = bodyToWickRatio * 100
// Plot Fair Value Gap (FVG) as Columns
plot(isBearishFVG ? fvgPercentage : na, "Bearish FVG", color=color.fuchsia, style=plot.style_columns, linewidth=4)
plot(isBullishFVG ? fvgPercentage : na, "Bullish FVG", color=color.lime, style=plot.style_columns, linewidth=4)
// Background Color
bgcolor(isBearishFVG ? color.new(color.fuchsia, 80) : isBullishFVG ? color.new(color.lime, 80) : na)
// Bar Color
barcolor(isBearishFVG ? color.fuchsia : isBullishFVG ? color.lime : na) |
Distributions | https://www.tradingview.com/script/7o9yP1i6-Distributions/ | miivanov | https://www.tradingview.com/u/miivanov/ | 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/
// © miivanov
//@version=5
// @description Price distribution calculation helpers
library("Distributions")
import miivanov/Colors/2
// helper to get OHLC series values
getOhlc() => [open, high, low, close]
// @function Returns price distribution zones based on HLC and for some period
// @param h high price
// @param l low price
// @param c close price
// @param window period to calculate distributions
// @returns tuple of 5 price zones in descent order, from highest to lowest
export getZones(series float h, series float l, series float c, simple int window) =>
avghlc = (h + l + c) / 3
avg = ta.sma(avghlc, window)
top = ta.highest(h, window)
bottom = ta.lowest(l, window)
zHighest = avg[1] + top[1] - bottom[1]
zHigh = 2 * avg[1] - bottom[1]
zLow = 2 * avg[1] - top[1]
zLowest = avg[1] + bottom[1] - top[1]
zMiddle = (zHighest + zLow) / 2
[zHighest, zHigh, zMiddle, zLow, zLowest]
// @function Plots table of price distribution zones
// @param zHighest highest prices distribution zone
// @param zHigh upper-middle prices distribution zone
// @param zMiddle middle zone of prices distribution
// @param zLow lower-middle distribution zone
// @param zLowest lowest distribuion zone
export plotZonesTable(series float zHighest, series float zHigh, series float zMiddle, series float zLow, series float zLowest, simple int window) =>
var colors = Colors.getColorsRange(color.green, color.red, 6)
int resetCounter = 0
int lowestPricesPct = 0
int lowPricesPct = 0
int lowerMidPricesPct = 0
int upperMidPricesPct = 0
int highPricesPct = 0
int higherPricesPct = 0
switch
close >= zHighest => higherPricesPct += 1
close < zHighest and close >= zHigh => highPricesPct += 1
close < zHigh and close >= zMiddle => upperMidPricesPct += 1
close < zMiddle and close >= zLow => lowerMidPricesPct += 1
close < zLow and close >= zLowest => lowPricesPct += 1
close < zLowest => lowestPricesPct += 1
var test = 0
if (resetCounter < window)
test := higherPricesPct + highPricesPct + upperMidPricesPct + lowerMidPricesPct + lowPricesPct + lowestPricesPct
else
resetCounter := 0
lowestPricesPct := 0
lowPricesPct := 0
lowerMidPricesPct := 0
upperMidPricesPct := 0
highPricesPct := 0
higherPricesPct := 0
resetCounter := 0
resetCounter += 1
var distTable = table.new(position = position.top_right, columns = 6, rows = 3, bgcolor = color.yellow, border_color = color.black, border_width = 2)
string tableTitle = str.format("Prices distributed by zones for last {0} of {1} days", resetCounter, window)
table.cell(table_id = distTable, column = 0, row = 0, text = tableTitle, text_halign = text.align_center)
table.merge_cells(table_id = distTable, start_column = 0, start_row = 0, end_column = 5, end_row = 0)
table.cell(table_id = distTable, column = 5, row = 1, text = "Highest")
table.cell(table_id = distTable, column = 4, row = 1, text = "High")
table.cell(table_id = distTable, column = 3, row = 1, text = "Upper mid.")
table.cell(table_id = distTable, column = 2, row = 1, text = "Lower mid.")
table.cell(table_id = distTable, column = 1, row = 1, text = "Low")
table.cell(table_id = distTable, column = 0, row = 1, text = "Lowest")
table.cell(table_id = distTable, column = 5, row = 2, bgcolor = array.get(colors, 0), text = str.tostring(math.round((higherPricesPct / test) * 100, 2)) + '%')
table.cell(table_id = distTable, column = 4, row = 2, bgcolor = array.get(colors, 1), text = str.tostring(math.round((highPricesPct / test) * 100, 2)) + '%')
table.cell(table_id = distTable, column = 3, row = 2, bgcolor = array.get(colors, 2), text = str.tostring(math.round((upperMidPricesPct / test) * 100, 2)) + '%')
table.cell(table_id = distTable, column = 2, row = 2, bgcolor = array.get(colors, 3), text = str.tostring(math.round((lowerMidPricesPct / test) * 100, 2)) + '%')
table.cell(table_id = distTable, column = 1, row = 2, bgcolor = array.get(colors, 4), text = str.tostring(math.round((lowPricesPct / test) * 100, 2)) + '%')
table.cell(table_id = distTable, column = 0, row = 2, bgcolor = array.get(colors, 5), text = str.tostring(math.round((lowestPricesPct / test) * 100, 2)) + '%') |
HTF FVG D/W/M 25%/50%/75% [MK] | https://www.tradingview.com/script/ed6MESu8-HTF-FVG-D-W-M-25-50-75-MK/ | malk1903 | https://www.tradingview.com/u/malk1903/ | 163 | 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/
// © malk1903
//@version=5
indicator("HTF FVG D/W/M [MK]", overlay=true, max_boxes_count = 500)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// MTF FVG (price overlay)
tfinput2 = input.timeframe(defval="Daily", title=' Timeframe ', options=["Daily", "Weekly", "Monthly"], group = 'General Settings', inline='1')
upcol1 = input.color(color.new(color.yellow,80), 'Box/Border/Text - UP', inline='appup', group = 'General Settings')
upbordercol = input.color(color.rgb(76, 175, 79, 100), '', inline='appup', group = 'General Settings')
uptextcol = input.color(color.new(color.yellow,0), '', inline='appup', group = 'General Settings')
downcol1 = input.color(color.new(color.yellow,80), 'Box/Border/Text - DOWN', inline='appdown', group = 'General Settings')
downbordercol = input.color(color.rgb(255, 82, 82, 100), '', inline='appdown', group = 'General Settings')
downtextcol = input.color(color.new(color.yellow, 0), '', inline='appdown', group = 'General Settings')
showboxtext = input.bool(defval=true, title="Text", inline='appdown2', group = 'General Settings')
showboxes = input.bool(true, 'Show Boxes', inline='appdown2', group = 'General Settings')
extendtilfilled = input.bool(true, '', group = 'General Settings', inline='fill')
filledtype = input.string('Full Fill', 'Fill Condition ', options=['Touch', 'Full Fill', 'Half Fill'], group = 'General Settings', inline='fill')
hidefilled = input.bool(false, 'Hide Filled Levels', group = 'General Settings', inline='fill2')
lookbackm = input.bool(true, '', inline='lb', group = 'General Settings')
daysBack = input.float(30, 'Lookback (D) ', group = 'General Settings',inline='lb')
maxBoxes = input.int(defval=4, title="Maximum Boxes", minval=0, maxval=499, step=1, group = 'General Settings',inline='lc')
conditiontype = 'None'
nmbars = 3500
linestylem = input.string(defval='Dotted', title="25/50/75% Style", options=['Dotted', 'Solid', 'Dashed'], inline='he', group='General Settings')
lineCol = input.color(color.new(color.silver,0), title='', inline='he', group='General Settings')
wdth = input.int(defval=1, title="Width", minval=0, maxval=4, step=1, group = 'General Settings',inline='he')
nbars = 4
//convert timeframe inputs
tfinput = ''
if tfinput2 == "Daily"
tfinput := "D"
if tfinput2 == "Weekly"
tfinput := "W"
if tfinput2 == "Monthly"
tfinput := "M"
// Requesting HTF data
[o, h, l, c] = request.security(syminfo.tickerid, tfinput, [open, high, low, close])
[o1, h1, l1, c1] = request.security(syminfo.tickerid, tfinput, [open[1], high[1], low[1], close[1]])
[o2, h2, l2, c2] = request.security(syminfo.tickerid, tfinput, [open[2], high[2], low[2], close[2]])
t = request.security(syminfo.tickerid, tfinput, time)
bool new = ta.change(time(tfinput))
clear = color.rgb(0,0,0,100)
color upcol = showboxes ? upcol1 : clear
color downcol = showboxes ? downcol1 : clear
MSPD = 24 * 60 * 60 * 1000
lastBarDate = timestamp(year(timenow), month(timenow), dayofmonth(timenow), hour(timenow), minute(timenow), second(timenow))
thisBarDate = timestamp(year, month, dayofmonth, hour, minute, second)
daysLeft = math.abs(math.floor((lastBarDate - thisBarDate) / MSPD))
inRange = lookbackm ? (daysLeft < daysBack) : true
// Timeframe labels
timeframelabel(tfinput) =>
switch tfinput
'' => timeframe.period + (timeframe.isminutes ? 'm' : na)
'1' => '1m'
'2' => '2m'
'3' => '3m'
'4' => '4m'
'5' => '5m'
'10' => '10m'
'15' => '15m'
'30' => '30m'
'60' => '1 Hr'
'120' => '2 Hr'
'240' => '4 Hr'
'480' => '8 Hr'
'720' => '12 Hr'
=> tfinput
// Box Text
var string imbboxtext = na, var string gapboxtext = na, var string wickboxtext = na
if showboxtext //and textType == 'Labels + Timeframe'
imbboxtext := str.tostring(timeframelabel(tfinput) + ' ' + str.tostring("FVG"))
// Line style and text label appearance
lineStyle(x) =>
switch x
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
// Conditions for Imbalances, Gaps and Wicks
var bool condition = na, var bool condition2 = na, var bool condition3 = na, var bool condition4 = na, var bool condition5 = na, var bool condition6 = na
if conditiontype == 'None'
condition := true
condition2 := true
condition3 := true
condition4 := true
condition5 := true
condition6 := true
// Drawing Boxes and Lines
var boxes = array.new_box(), var topLines = array.new_line(), var middleLines = array.new_line(), var bottomLines = array.new_line()
if (l > h2) and condition and inRange and new //and fvg1hr
imbboxUP = box.new(t[2], l, time, h2, bgcolor = upcol, border_color=upbordercol,border_width = 1, text=imbboxtext, text_size = size.small, text_halign = text.align_right, text_valign = text.align_center, text_color = uptextcol,xloc = xloc.bar_time)
topLine = line.new(t[2], (((l + h2)/2) + l)/2, time, (((l + h2)/2) + l)/2, color=lineCol, style=lineStyle(linestylem), xloc = xloc.bar_time, width=wdth)
bottomLine = line.new(t[2], (((l + h2)/2) + h2)/2, time, (((l + h2)/2) + h2)/2, color=lineCol, style=lineStyle(linestylem), xloc = xloc.bar_time, width=wdth)
middleLine = line.new(t[2], (l + h2)/2, last_bar_time, (l + h2)/2, color=lineCol, style=lineStyle(linestylem), xloc = xloc.bar_time, width=wdth)
array.push(topLines, topLine)
array.push(middleLines, middleLine)
array.push(bottomLines, bottomLine)
array.push(boxes, imbboxUP)
if (h < l2) and condition2 and inRange and new //and fvg1hr
imbboxDOWN = box.new(t[2], h, time, l2, bgcolor = downcol, border_color=downbordercol,border_width = 1, text=imbboxtext, text_size = size.small, text_halign = text.align_right, text_valign = text.align_center, text_color = downtextcol, xloc = xloc.bar_time)
topLine = line.new(t[2], (((l2 + h)/2) + l2)/2, time, (((l2 + h)/2) + l2)/2, color=lineCol, style=lineStyle(linestylem), xloc = xloc.bar_time, width=wdth)
bottomLine = line.new(t[2], (((l2 + h)/2) + h)/2, time, (((l2 + h)/2) + h)/2, color=lineCol, style=lineStyle(linestylem), xloc = xloc.bar_time, width=wdth)
middleLine = line.new(t[2], (h+l2)/2, last_bar_time, (h+l2)/2, color=lineCol, style=lineStyle(linestylem), xloc = xloc.bar_time, width=wdth)
array.push(topLines, topLine)
array.push(middleLines, middleLine)
array.push(bottomLines, bottomLine)
array.push(boxes, imbboxDOWN)
// Looping over the arrays and updating objects
size = array.size(boxes)
if size > 0
for i = 0 to size - 1
j = size - 1 - i
box = array.get(boxes, j)
topLine = array.get(topLines, j)
middleLine = array.get(middleLines, j)
bottomLine = array.get(bottomLines, j)
level = box.get_bottom(box)
level2 = box.get_top(box)
level3 = (level2+level)/2
// Defining fill conditions for zones and lines
var bool filled = na
unifill = (high > level and low < level) or (high > level2 and low < level2)
if filledtype == 'Touch'
filled := (high > level and low < level) or (high > level2 and low < level2)
if filledtype == 'Half Fill'
filled := (high > level3 and low < level3)
if filledtype == 'Full Fill'
for imbboxUP in boxes
filled := (high > level2 and low < level2)
for imbboxDOWN in boxes
filled := (high > level and low < level)
if hidefilled and filled
line.delete(topLine)
line.delete(middleLine)
line.delete(bottomLine)
box.delete(box)
array.remove(boxes, j)
array.remove(topLines, j)
array.remove(middleLines, j)
array.remove(bottomLines, j)
continue
if filled and extendtilfilled
array.remove(boxes, j)
array.remove(topLines, j)
array.remove(middleLines, j)
array.remove(bottomLines, j)
continue
box.set_right(box, last_bar_time)
line.set_x2(topLine, last_bar_time)
line.set_x2(middleLine, last_bar_time)
line.set_x2(bottomLine, last_bar_time)
if not filled and not extendtilfilled
array.remove(boxes, j)
array.remove(topLines, j)
array.remove(middleLines, j)
array.remove(bottomLines, j)
continue
box.set_right(box, time+nbars)
line.set_x2(topLine, time+nbars)
line.set_x2(middleLine, time+nbars)
line.set_x2(bottomLine, time+nbars)
continue
box.set_right(box, time)
line.set_x2(topLine, time)
line.set_x2(middleLine, time)
line.set_x2(bottomLine, time)
// Deleting if the array is too big
if array.size(boxes) >= maxBoxes
int i = 0
while array.size(boxes) >= maxBoxes
box = array.get(boxes, i)
topLine = array.get(topLines, i)
middleLine = array.get(middleLines, i)
bottomLine = array.get(bottomLines, i)
line.delete(topLine)
line.delete(middleLine)
line.delete(bottomLine)
box.delete(box)
array.remove(boxes, i)
array.remove(topLines, i)
array.remove(middleLines, i)
array.remove(bottomLines, i)
i += 1
|
HighLowBox 1+3TF | https://www.tradingview.com/script/GH01d5cr/ | nazomobile | https://www.tradingview.com/u/nazomobile/ | 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/
// © nazo
//@version=5
indicator(title="HighLowBox HTF+RSI",shorttitle="HLBox+RSI",overlay=true, max_boxes_count=500,max_labels_count=500, max_lines_count=500)
//
idChart = syminfo.tickerid
tfChart = timeframe.period
// t00,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15
t00="Chart", t01="1", t02="3", t03="5", t04="15", t05="30",t06="60",t07="120", t08="180",t09="240",
t10="D", t11='W',t12="M",t13="3M", t14="6M",t15="Y"
th1="higher1", th2="higher2", th3="higher3", th4="higher4"
tl1="lower1", tl2="lower2", tl3="lower3", tl4="lower4"
f_gt(x,y) => x>y?x:y
f_lt(x,y) => x<y?x:y
f_tfMultiplier(tf) =>
x=
str.endswith(tf,"M")? str.length(tf)==1?"1":str.replace(tf,"M",""):
str.endswith(tf,"W")? str.length(tf)==1?"1":str.replace(tf,"W",""):
str.endswith(tf,"D")? str.length(tf)==1?"1":str.replace(tf,"D",""):
str.endswith(tf,"S")? str.length(tf)==1?"1":str.replace(tf,"S",""):
tf
str.tonumber(x)
f_time_ddHHmm (_t)=>
_s=1000
_m=60*_s
_h=60*_m
_d=24*_h
_sec = _t
_day = int(_sec/_d)
_mod = _sec%_d
_hour= int(_mod/_h)
_mod:= _mod%_h
_min = int(_mod/_m)
(_day>0?str.tostring(_day,"00")+"d":"")+str.tostring(_hour,"00")+"h"+str.tostring(_min,"00")+"m"
f_tfUp (tf) =>
m = f_tfMultiplier(tf)
x= str.endswith(tf,"M")? m<3?"3M": m<6?"6M": m<12?"12M":na:
str.endswith(tf,"W")? "M":
str.endswith(tf,"D")? "W":
str.endswith(tf,"S")? "1":
m<15?"15": m<60?"60": m<240?"240": m>=240?"D":na
f_tfDn (tf) =>
m = f_tfMultiplier(tf)
x= str.endswith(tf,"M")? m>6?"6M": m>3?"3M":"W":
str.endswith(tf,"W")? "D":
str.endswith(tf,"D")? "240":
str.endswith(tf,"S")? na:
m>240?"240": m>60?"60": m>15?"15": m>5?"5": m>3?"3":"1"
string tfHigher1 = f_tfUp(tfChart)
string tfHigher2 = f_tfUp(tfHigher1)
string tfHigher3 = f_tfUp(tfHigher2)
string tfHigher4 = f_tfUp(tfHigher3)
string tfLower1 = f_tfDn(tfChart)
string tfLower2 = f_tfDn(tfLower1)
string tfLower3 = f_tfDn(tfLower2)
string tfLower4 = f_tfDn(tfLower3)
f_opt2tf(opt) => opt==t00?tfChart:
opt==th1?tfHigher1: opt==th2?tfHigher2: opt==th3?tfHigher3: opt==th4?tfHigher4:
opt==tl1?tfLower1: opt==tl2?tfLower2: opt==tl3?tfLower3: opt==tl4?tfLower4:
opt
b_tfgt(tfa,tfb) => timeframe.in_seconds(tfa)>timeframe.in_seconds(tfb)
b_tflt(tfa,tfb) => timeframe.in_seconds(tfa)<timeframe.in_seconds(tfb)
b_tfgtCur(tf) => timeframe.in_seconds(tf)>timeframe.in_seconds(tfChart)
b_tfltCur(tf) => timeframe.in_seconds(tf)<timeframe.in_seconds(tfChart)
f_getMtfLowerAvg(tf,x) => na(tf)?na:array.avg(request.security_lower_tf(idChart,tf,x))
f_getMtfLowerMax(tf,x) => na(tf)?na:array.avg(request.security_lower_tf(idChart,tf,x))
f_getMtf(tf,x) => na(tf)?na: tf==tfChart?x:
b_tfgtCur(tf)?request.security(idChart,tf,x, gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_off):na
f_bb (center,std,sigma) => center + std*sigma
f_bbsetup(center,std) => [
f_bb(center,std,4),
f_bb(center,std,3),
f_bb(center,std,2),
f_bb(center,std,1),
f_bb(center,std,-1),
f_bb(center,std,-2),
f_bb(center,std,-3),
f_bb(center,std,-4)
]
f_bb3sigma1side (val, center, std) => center<val?f_bb(center,std,3):f_bb(center,std,-3)
f_madev(val, ma) => (val - ma) / ma * 100
s_madev(val, ma) => str.tostring(val-ma,"0.000")+"("+str.tostring(math.round(f_madev(val,ma),2))+"%)"
f_fibo(a,z) =>
diff = z-a
[z-diff*3.618,z-diff*2.618,z-diff*1.618,
a+diff*0.236,a+diff*0.382,a+diff*0.5,a+diff*0.618,a+diff*0.786,
a+diff*1.618,a+diff*2.618,a+diff*3.618]
f_fibo_range(a,z,x) =>
diff = z-a
_rti=-1
_rbi=-1
listfibo = array.from(z-diff*3.618,z-diff*2.618,z-diff*1.618,a,a+diff*0.236,a+diff*0.382,a+diff*0.5,a+diff*0.618,a+diff*0.786,z,a+diff*1.618,a+diff*2.618,a+diff*3.618)
s_listfibo = array.from("3.618fromT","2.618fromT","1.618fromT","____Bottom","0.236fromB","0.382fromB","____Center","0.382fromT","0.236fromT","_______Top","1.618fromB","2.618fromB","3.618fromB")
for i = 0 to array.size(listfibo)-1
if x<array.get(listfibo,i)
_rti:=i
break
for i = array.size(listfibo)-1 to 0
if x>array.get(listfibo,i)
_rbi:=i
break
[_rti==-1?na:array.get(listfibo,_rti),_rti==-1?na:array.get(s_listfibo,_rti),
_rbi==-1?na:array.get(listfibo,_rbi),_rbi==-1?na:array.get(s_listfibo,_rbi)]
f_fibo_level(a,z,x) =>
diff = z-a
level = x<=a+diff*0.5? x>a+diff*0.382?"ML": x>a+diff*0.236?"L": x>a?"L-": "BB":
x<a+diff*0.618?"MH": x<a+diff*0.786?"H": x<z?"H+": "BT"
f_fl_va(_fl) =>
switch _fl
"ML" => text.align_center
"L" => text.align_bottom
"L-" => text.align_bottom
"BB" => text.align_bottom
"MH" => text.align_center
"H" => text.align_top
"H+" => text.align_top
"BT" => text.align_top
f_fl_c(_fl) =>
switch _fl
"ML" => color.new(color.orange,20)
"L" => color.new(color.red,60)
"L-" => color.new(color.red,40)
"BB" => color.new(color.red,20)
"MH" => color.new(color.yellow,20)
"H" => color.new(color.blue,60)
"H+" => color.new(color.blue,40)
"BT" => color.new(color.blue,20)
l00="solid",l01="dashed",l02="dotted"
f_linestyle (x) => x==l00?line.style_solid: x==l01?line.style_dashed: x==l02?line.style_dotted:na
s00="auto",s01="huge",s02="large",s03="normal",s04="small",s05="tiny"
f_textsize (x) => x==s00?size.auto: x==s01?size.huge: x==s02?size.large: x==s03?size.normal: x==s04?size.small: x==s05?size.tiny:na
f_renew_high(_last_renew,_high,_high_time,_m_high,_m_return_high,_m_low,_m_return_low) =>
_i_renew =0
_a_high = matrix.row(_m_high,0)
_a_high_time = matrix.row(_m_high,1)
_a_return_high = matrix.row(_m_return_high,0)
_a_return_high_time = matrix.row(_m_return_high,1)
_a_low = matrix.row(_m_low,0)
_a_low_time = matrix.row(_m_low,1)
_a_return_low = matrix.row(_m_return_low,0)
_a_return_low_time = matrix.row(_m_return_low,1)
if array.size(_a_return_high)>0
if array.last(_a_return_high)<_high
while(array.size(_a_return_high)>0)
if array.last(_a_return_high)<_high
array.pop(_a_return_high)
array.pop(_a_return_high_time)
else
break
array.push(_a_return_high,_high)
array.push(_a_return_high_time,_high_time)
if array.last(_a_high)<array.last(_a_return_high)
_i_renew:=1
if _i_renew==_last_renew
array.pop(_a_high)
array.pop(_a_high_time)
array.push(_a_high,array.last(_a_return_high))
array.push(_a_high_time,array.last(_a_return_high_time))
array.push(_a_low,array.last(_a_return_low))
array.push(_a_low_time,array.last(_a_return_low_time))
o_m_high = matrix.new<float>(2,array.size(_a_high),na)//0: price, 1:time
matrix.add_row(o_m_high,0,_a_high)
matrix.add_row(o_m_high,1,_a_high_time)
o_m_return_high = matrix.new<float>(2,array.size(_a_return_high),na)//0: price, 1:time
matrix.add_row(o_m_return_high,0,_a_return_high)
matrix.add_row(o_m_return_high,1,_a_return_high_time)
o_m_low = matrix.new<float>(2,array.size(_a_low),na)//0: price, 1:time
matrix.add_row(o_m_low,0,_a_low)
matrix.add_row(o_m_low,1,_a_low_time)
o_m_return_low = matrix.new<float>(2,array.size(_a_return_low),na)//0: price, 1:time
matrix.add_row(o_m_return_low,0,_a_return_low)
matrix.add_row(o_m_return_low,1,_a_return_low_time)
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]
f_renew_low(_last_renew,_low,_low_time,_m_low,_m_return_low,_m_high,_m_return_high) =>
_i_renew =0
_a_high = matrix.row(_m_high,0)
_a_high_time = matrix.row(_m_high,1)
_a_return_high = matrix.row(_m_return_high,0)
_a_return_high_time = matrix.row(_m_return_high,1)
_a_low = matrix.row(_m_low,0)
_a_low_time = matrix.row(_m_low,1)
_a_return_low = matrix.row(_m_return_low,0)
_a_return_low_time = matrix.row(_m_return_low,1)
if array.size(_a_return_low)>0
if array.last(_a_return_low)>_low
while(array.size(_a_return_low)>0)
if array.last(_a_return_low)>_low
array.pop(_a_return_low)
array.pop(_a_return_low_time)
else
break
array.push(_a_return_low,_low)
array.push(_a_return_low_time,_low_time)
if array.last(_a_low)>array.last(_a_return_low)
_i_renew:=-1
if _i_renew==_last_renew
array.pop(_a_low)
array.pop(_a_low_time)
array.push(_a_low,array.last(_a_return_low))
array.push(_a_low_time,array.last(_a_return_low_time))
array.push(_a_high,array.last(_a_return_high))
array.push(_a_high_time,array.last(_a_return_high_time))
o_m_high = matrix.new<float>(2,array.size(_a_high),na)//0: price, 1:time
matrix.add_row(o_m_high,0,_a_high)
matrix.add_row(o_m_high,1,_a_high_time)
o_m_return_high = matrix.new<float>(2,array.size(_a_return_high),na)//0: price, 1:time
matrix.add_row(o_m_return_high,0,_a_return_high)
matrix.add_row(o_m_return_high,1,_a_return_high_time)
o_m_low = matrix.new<float>(2,array.size(_a_low),na)//0: price, 1:time
matrix.add_row(o_m_low,0,_a_low)
matrix.add_row(o_m_low,1,_a_low_time)
o_m_return_low = matrix.new<float>(2,array.size(_a_return_low),na)//0: price, 1:time
matrix.add_row(o_m_return_low,0,_a_return_low)
matrix.add_row(o_m_return_low,1,_a_return_low_time)
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]
//RSI span string
//rsi01,rsi02,rsi03,rsi04,rsi05,rsi06,rsi07,rsi08,rsi09,rsi10,rsi11,rsi12,rsi13,rsi14,rsi15,rsi16,rsi17,rsi18,rsi19,rsi20,rsi21,rsi22,rsi23,rsi24,rsi25,rsi26,rsi27,rsi28,rsi29,rsi30
rsi01="①",rsi02="②",rsi03="③",rsi04="④",rsi05="⑤",rsi06="⑥",rsi07="⑦",rsi08="⑧",rsi09="⑨",rsi10="⑩",
rsi11="⑪",rsi12="⑫",rsi13="⑬",rsi14="⑭",rsi15="⑮",rsi16="⑯",rsi17="⑰",rsi18="⑱",rsi19="⑲",rsi20="⑳",
rsi21="㉑",rsi22="㉒",rsi23="㉓",rsi24="⑭",rsi25="㉕",rsi26="㉖",rsi27="㉗",rsi28="㉘",rsi29="㉙",rsi30="㉚"
f_rsi_span2label(_i) => _i==1?rsi01: _i==2?rsi02: _i==3?rsi03: _i==4?rsi04: _i==5?rsi05: _i==6?rsi06: _i==7?rsi07: _i==8?rsi08: _i==9?rsi09: _i==10?rsi10:
_i==11?rsi11: _i==12?rsi12: _i==13?rsi13: _i==14?rsi14: _i==15?rsi15: _i==16?rsi16: _i==17?rsi17: _i==18?rsi18: _i==19?rsi19: _i==20?rsi20:
_i==21?rsi21: _i==22?rsi22: _i==23?rsi23: _i==24?rsi14: _i==25?rsi25: _i==26?rsi26: _i==27?rsi27: _i==28?rsi28: _i==29?rsi29: _i==30?rsi30:na
rsi00="▼", rsi99="▲"
f_rsi_direc(_isup)=>_isup?rsi99:rsi00
//
// colors
//
colorLabelText=color.new(color.white,60)
colorBoxT=color.new(color.white,5)
colorBoxU=color.new(#aaffaa,5)
colorBoxD=color.new(#ffaaaa,5)
colorRSIi=color.new(color.white,5)
colorRSIt1=color.new(color.yellow,5)
colorRSIt2=color.new(color.orange,5)
colorRSIt3=color.new(color.red,5)
colorRSIb1=color.new(color.aqua,5)
colorRSIb2=color.new(color.blue,5)
colorRSIb3=color.new(color.green,5)
//settings
show0 = input.bool(defval=true,title="show current TF")
transBox = input.int(defval=40,minval=0,maxval=99,title="border transpar",inline="tfC")
cBoxU = input.color(defval=colorBoxU,title="newHigh",inline="tfC")
cBoxD = input.color(defval=colorBoxD,title="newLow",inline="tfC")
cBoxU:=color.new(cBoxU,transBox)
cBoxD:=color.new(cBoxD,transBox)
widthBox = input.int(defval=1,minval=1,maxval=4,title="width",inline="tfC")
_styleBox = input.string(defval=l01,options=[l00,l01,l02],title="box style",inline="tfC")
styleBox = f_linestyle(_styleBox)
b_fillBox = input.bool(defval=true,title="fill box",inline="tfCf")
transFill = input.int(defval=90,minval=0,maxval=99,title="fill transpar",inline="tfCf")
cBoxUf = input.color(defval=colorBoxU,title="newHigh",inline="tfCf")
cBoxDf = input.color(defval=colorBoxD,title="newLow",inline="tfCf")
cBoxUf:=b_fillBox?color.new(cBoxUf,transFill):na
cBoxDf:=b_fillBox?color.new(cBoxDf,transFill):na
b_fibo = input.bool(defval=true,title="show fibonacci scale",inline="tfCF")
b_info = input.bool(defval=true,title="range info",inline="tfCi")
_infoSize = input.string(defval=s04,options=[s01,s02,s03,s04,s05],title="info size",inline="tfCi")
infoSize = f_textsize(_infoSize)
_cBoxT = input.color(defval=colorBoxT,title="info color",inline="tfCi")
transInfo = input.int(defval=30,minval=0,maxval=99,title="text transpar",inline="tfCi")
cBoxT = color.new(_cBoxT,transInfo)
show1 = input.bool(defval=true,title="show TF1")
_tf1 = input.timeframe(defval=th1, title="", inline="tfH1",
options=[th1,th2,th3,th4,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15])
tf1 = f_opt2tf(_tf1)
transBox1 = input.int(defval=50,minval=0,maxval=99,title="border transpar",inline="tfH1")
cBoxU1 = input.color(defval=colorBoxU,title="newHigh",inline="tfH1")
cBoxD1 = input.color(defval=colorBoxD,title="newLow",inline="tfH1")
cBoxU1:=color.new(cBoxU1,transBox1)
cBoxD1:=color.new(cBoxD1,transBox1)
widthBox1 = input.int(defval=2,minval=1,maxval=4,title="width",inline="tfH1")
_styleBox1 = input.string(defval=l00,options=[l00,l01,l02],title="box style",inline="tfH1")
styleBox1 = f_linestyle(_styleBox1)
b_fibo1 = input.bool(defval=true,title="show fibonacci level",inline="tfH1")
b_info1 = input.bool(defval=true,title="range info",inline="tfH1i")
_infoSize1 = input.string(defval=s04,options=[s01,s02,s03,s04,s05],title="info size",inline="tfH1i")
infoSize1 = f_textsize(_infoSize1)
_cBoxT1 = input.color(defval=colorBoxT,title="info color",inline="tfH1i")
transInfo1 = input.int(defval=30,minval=0,maxval=99,title="text transpar",inline="tfH1i")
cBoxT1 = color.new(_cBoxT1,transInfo1)
show2 = input.bool(defval=true,title="show TF2")
_tf2 = input.timeframe(defval=th2, title="", inline="tfH2",
options=[th1,th2,th3,th4,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15])
tf2 = f_opt2tf(_tf2)
transBox2 = input.int(defval=60,minval=0,maxval=99,title="border transpar",inline="tfH2")
cBoxU2 = input.color(defval=colorBoxU,title="newHigh",inline="tfH2")
cBoxD2 = input.color(defval=colorBoxD,title="newLow",inline="tfH2")
cBoxU2:=color.new(cBoxU2,transBox2)
cBoxD2:=color.new(cBoxD2,transBox2)
widthBox2 = input.int(defval=3,minval=1,maxval=4,title="width",inline="tfH2")
_styleBox2 = input.string(defval=l01,options=[l00,l01,l02],title="box style",inline="tfH2")
styleBox2 = f_linestyle(_styleBox2)
b_fibo2 = input.bool(defval=true,title="show fibonacci level",inline="tfH2")
b_info2 = input.bool(defval=true,title="range info",inline="tfH2i")
_infoSize2 = input.string(defval=s04,options=[s01,s02,s03,s04,s05],title="info size",inline="tfH2i")
infoSize2 = f_textsize(_infoSize2)
_cBoxT2 = input.color(defval=colorBoxT,title="info color",inline="tfH2i")
transInfo2 = input.int(defval=30,minval=0,maxval=99,title="text transpar",inline="tfH2i")
cBoxT2 = color.new(_cBoxT2,transInfo2)
show3 = input.bool(defval=true,title="show TF3")
_tf3 = input.timeframe(defval=th3, title="", inline="tfH3",
options=[th1,th2,th3,th4,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15])
tf3 = f_opt2tf(_tf3)
transBox3 = input.int(defval=70,minval=0,maxval=99,title="border transpar",inline="tfH3")
cBoxU3 = input.color(defval=colorBoxU,title="newHigh",inline="tfH3")
cBoxD3 = input.color(defval=colorBoxD,title="newLow",inline="tfH3")
cBoxU3:=color.new(cBoxU3,transBox3)
cBoxD3:=color.new(cBoxD3,transBox3)
widthBox3 = input.int(defval=4,minval=1,maxval=4,title="width",inline="tfH3")
_styleBox3 = input.string(defval=l00,options=[l00,l01,l02],title="box style",inline="tfH3")
styleBox3 = f_linestyle(_styleBox3)
b_fibo3 = input.bool(defval=true,title="show fibonacci level",inline="tfH3")
b_info3 = input.bool(defval=true,title="range info",inline="tfH3i")
_infoSize3 = input.string(defval=s04,options=[s01,s02,s03,s04,s05],title="info size",inline="tfH3i")
infoSize3 = f_textsize(_infoSize3)
_cBoxT3 = input.color(defval=colorBoxT,title="info color",inline="tfH3i")
transInfo3 = input.int(defval=30,minval=0,maxval=99,title="text transpar",inline="tfH3i")
cBoxT3 = color.new(_cBoxT3,transInfo3)
show4 = input.bool(defval=false,title="show TF4")
_tf4 = input.timeframe(defval=th4, title="", inline="tfH4",
options=[th1,th2,th3,th4,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15])
tf4 = f_opt2tf(_tf4)
transBox4 = input.int(defval=80,minval=0,maxval=99,title="border transpar",inline="tfH4")
cBoxU4 = input.color(defval=colorBoxU,title="newHigh",inline="tfH4")
cBoxD4 = input.color(defval=colorBoxD,title="newLow",inline="tfH4")
cBoxU4:=color.new(cBoxU4,transBox4)
cBoxD4:=color.new(cBoxD4,transBox4)
widthBox4 = input.int(defval=4,minval=1,maxval=4,title="width",inline="tfH4")
_styleBox4 = input.string(defval=l02,options=[l00,l01,l02],title="box style",inline="tfH4")
styleBox4 = f_linestyle(_styleBox4)
b_fibo4 = input.bool(defval=true,title="show fibonacci level",inline="tfH4")
b_info4 = input.bool(defval=true,title="range info",inline="tfH4i")
_infoSize4 = input.string(defval=s04,options=[s01,s02,s03,s04,s05],title="info size",inline="tfH4i")
infoSize4 = f_textsize(_infoSize4)
_cBoxT4 = input.color(defval=colorBoxT,title="info color",inline="tfH4i")
transInfo4 = input.int(defval=30,minval=0,maxval=99,title="text transpar",inline="tfH4i")
cBoxT4 = color.new(_cBoxT4,transInfo4)
showMinimap = input.bool(defval=false,title="show minimap(experimental)",inline="tfM")
minimapHist = input.int(defval=32,minval=10,maxval=99,title="minimap hist",inline="tfM")
srcRSI = input.source(defval=hlc3,title="RSI src",group="RSI")
spanRSI_1 = input.int(defval=9,minval=1,maxval=30,title="span1", inline="RSIspan", group="RSI")
spanRSI_2 = input.int(defval=14,minval=1,maxval=30,title="span2", inline="RSIspan", group="RSI")
_cRSIi = input.color(defval=colorRSIi,title="only span1>=70 or only span1<=30",inline="top",group="RSI >= 70")
_cRSIt1 = input.color(defval=colorRSIt1,title="both>=70 and span1>span2",inline="top",group="RSI >= 70")
_cRSIt2 = input.color(defval=colorRSIt2,title="both>=70 and span1<span2",inline="top",group="RSI >= 70")
_cRSIt3 = input.color(defval=colorRSIt3,title="span1<70",inline="top",group="RSI >= 70")
_cRSIb1 = input.color(defval=colorRSIb1,title="both<=30 and span1<span2",inline="top",group="RSI <= 30")
_cRSIb2 = input.color(defval=colorRSIb2,title="both<=30 and span1>span2",inline="top",group="RSI <= 30")
_cRSIb3 = input.color(defval=colorRSIb3,title="span1>30",inline="top",group="RSI <= 30")
showRSI = input.bool(defval=true,title="use RSI in current TF",inline="tf",group="RSI")
transRSI = input.int(defval=80,minval=0,maxval=99,title="border transpar",inline="tf",group="RSI")
cRSIi=color.new(_cRSIi,transRSI)
cRSIt1=color.new(_cRSIt1,transRSI)
cRSIt2=color.new(_cRSIt2,transRSI)
cRSIt3=color.new(_cRSIt3,transRSI)
cRSIb1=color.new(_cRSIb1,transRSI)
cRSIb2=color.new(_cRSIb2,transRSI)
cRSIb3=color.new(_cRSIb3,transRSI)
showRSI1 = input.bool(defval=true,title="use RSI in Higher TF1",inline="tf1",group="RSI")
transRSI1 = input.int(defval=70,minval=0,maxval=99,title="border transpar",inline="tf1",group="RSI")
cRSI1i=color.new(_cRSIi,transRSI1)
cRSI1t1=color.new(_cRSIt1,transRSI1)
cRSI1t2=color.new(_cRSIt2,transRSI1)
cRSI1t3=color.new(_cRSIt3,transRSI1)
cRSI1b1=color.new(_cRSIb1,transRSI1)
cRSI1b2=color.new(_cRSIb2,transRSI1)
cRSI1b3=color.new(_cRSIb3,transRSI1)
showRSI2 = input.bool(defval=true,title="use RSI in Higher TF2",inline="tf2",group="RSI")
transRSI2 = input.int(defval=60,minval=0,maxval=99,title="border transpar",inline="tf2",group="RSI")
cRSI2i=color.new(_cRSIi,transRSI2)
cRSI2t1=color.new(_cRSIt1,transRSI2)
cRSI2t2=color.new(_cRSIt2,transRSI2)
cRSI2t3=color.new(_cRSIt3,transRSI2)
cRSI2b1=color.new(_cRSIb1,transRSI2)
cRSI2b2=color.new(_cRSIb2,transRSI2)
cRSI2b3=color.new(_cRSIb3,transRSI2)
showRSI3 = input.bool(defval=true,title="use RSI in Higher TF3",inline="tf3",group="RSI")
transRSI3 = input.int(defval=50,minval=0,maxval=99,title="border transpar",inline="tf3",group="RSI")
cRSI3i=color.new(_cRSIi,transRSI3)
cRSI3t1=color.new(_cRSIt1,transRSI3)
cRSI3t2=color.new(_cRSIt2,transRSI3)
cRSI3t3=color.new(_cRSIt3,transRSI3)
cRSI3b1=color.new(_cRSIb1,transRSI3)
cRSI3b2=color.new(_cRSIb2,transRSI3)
cRSI3b3=color.new(_cRSIb3,transRSI3)
showRSI4 = input.bool(defval=true,title="use RSI in Higher TF4",inline="tf4",group="RSI")
transRSI4 = input.int(defval=40,minval=0,maxval=99,title="border transpar",inline="tf4",group="RSI")
cRSI4i=color.new(_cRSIi,transRSI4)
cRSI4t1=color.new(_cRSIt1,transRSI4)
cRSI4t2=color.new(_cRSIt2,transRSI4)
cRSI4t3=color.new(_cRSIt3,transRSI4)
cRSI4b1=color.new(_cRSIb1,transRSI4)
cRSI4b2=color.new(_cRSIb2,transRSI4)
cRSI4b3=color.new(_cRSIb3,transRSI4)
//
//high low box
//
var a_hist_top = array.new_float(0,na)
var a_hist_bottom = array.new_float(0,na)
var a_hist_time = array.new_int(0,na)
var a_hist_tf = array.new_string(0,na)
var a_hist_close = array.new_float(0,na)
var a_hist_cbox = array.new_color(0,na)
var m_high = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_high = matrix.new<float>(2,1,time)//0: price, 1:time
var m_low = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_low = matrix.new<float>(2,1,time)//0: price, 1:time
b_isLastUp=close[1]>open[1]?true:false
b_isUp=close>open?true:false
b_peak=b_isLastUp and not b_isUp
b_bottom=not b_isLastUp and b_isUp
i_renew=0
var i_last_renew=0
if b_peak or b_bottom
if b_peak
_high=close[1]>=open?close[1]:open
_high_time=close[1]>=open?time_close[1]:time_close
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_high(i_last_renew,_high,_high_time,m_high,m_return_high,m_low,m_return_low)
i_renew:=_i_renew
m_high:= o_m_high
m_return_high:=o_m_return_high
m_low:= o_m_low
m_return_low:= o_m_return_low
else if b_bottom
_low=close[1]<=open?close[1]:open
_low_time=close[1]<=open?time_close[1]:time_close
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_low(i_last_renew,_low,_low_time,m_low,m_return_low,m_high,m_return_high)
i_renew:=_i_renew
m_high:= o_m_high
m_return_high:= o_m_return_high
m_low:= o_m_low
m_return_low:= o_m_return_low
else
na
else
na
//
i_last_renew:=i_renew
var mybox=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na)
var myfibo23=line.new(na,na,na,na,xloc=xloc.bar_time)
var myfibo38=line.new(na,na,na,na,xloc=xloc.bar_time)
var myfibo50=line.new(na,na,na,na,xloc=xloc.bar_time)
var myfibo61=line.new(na,na,na,na,xloc=xloc.bar_time)
var myfibo78=line.new(na,na,na,na,xloc=xloc.bar_time)
var myfibo161=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none)
var myfibo261=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none)
var myfibo361=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none)
var myfibom161=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none)
var myfibom261=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none)
var myfibom361=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none)
var i_breakT=0
var i_breakf161=0
var i_breakf261=0
var i_breakB=0
var i_breakfm161=0
var i_breakfm261=0
top= matrix.get(m_high,0,matrix.columns(m_high)-1)
top_time= matrix.get(m_high,1,matrix.columns(m_high)-1)
bottom= matrix.get(m_low,0,matrix.columns(m_low)-1)
bottom_time= matrix.get(m_low,1,matrix.columns(m_low)-1)
c_box_bg=bottom_time<top_time?cBoxUf:cBoxDf
c_box=bottom_time<top_time?cBoxU:cBoxD
_h = array.from(int(top_time),int(bottom_time))
_v = array.from(top,bottom)
_t = array.max(_v)
_b = array.min(_v)
_l = array.min(_h)
[fm361,fm261,fm161,f23,f38,f50,f61,f78,f161,f261,f361] = f_fibo(_b,_t)
if show0 and i_renew!=0
mybox:=box.new(_l,na,na,na,xloc=xloc.bar_time,border_width=widthBox,text_halign=text.align_center,text_size=infoSize,
border_color=c_box,text_color=cBoxT,bgcolor=c_box_bg,border_style=styleBox)
array.push(a_hist_time,_l)
array.push(a_hist_tf,tfChart)
array.push(a_hist_top,_t)
array.push(a_hist_bottom,_b)
array.push(a_hist_close,close)
array.push(a_hist_cbox,c_box)
if b_fibo
myfibo23:=line.new(_l,f23,na,f23,xloc.bar_time,extend.none,c_box,line.style_dashed,1)
myfibo38:=line.new(_l,f38,na,f38,xloc.bar_time,extend.none,c_box,line.style_dashed,1)
myfibo50:=line.new(_l,f50,na,f50,xloc.bar_time,extend.none,c_box,line.style_solid,1)
myfibo61:=line.new(_l,f61,na,f61,xloc.bar_time,extend.none,c_box,line.style_dashed,1)
myfibo78:=line.new(_l,f78,na,f78,xloc.bar_time,extend.none,c_box,line.style_dashed,1)
myfibo161:=label.new(na,f161,"___1.618:"+str.tostring(f161,"#.0000")+"___",xloc.bar_time,yloc.price,c_box_bg,label.style_none,c_box,infoSize)
myfibo261:=label.new(na,f261,"___2.618:"+str.tostring(f261,"#.0000")+"___",xloc.bar_time,yloc.price,c_box_bg,label.style_none,c_box,infoSize)
myfibo361:=label.new(na,f361,"___3.618:"+str.tostring(f361,"#.0000")+"___",xloc.bar_time,yloc.price,c_box_bg,label.style_none,c_box,infoSize)
myfibom161:=label.new(na,fm161,"___1.618:"+str.tostring(fm161,"#.0000")+"___",xloc.bar_time,yloc.price,c_box_bg,label.style_none,c_box,infoSize)
myfibom261:=label.new(na,fm261,"___2.618:"+str.tostring(fm261,"#.0000")+"___",xloc.bar_time,yloc.price,c_box_bg,label.style_none,c_box,infoSize)
myfibom361:=label.new(na,fm361,"___3.618:"+str.tostring(fm361,"#.0000")+"___",xloc.bar_time,yloc.price,c_box_bg,label.style_none,c_box,infoSize)
else
label.delete(myfibo161),label.delete(myfibo261),label.delete(myfibo361)
label.delete(myfibom161),label.delete(myfibom261),label.delete(myfibo361)
i_breakT:=0
i_breakB:=0
i_breakf161:=0
i_breakf261:=0
i_breakfm161:=0
i_breakfm261:=0
i_breakT+=high>_t?1:0
i_breakB+=low<_t?1:0
i_breakf161:=high>f161?1:0
i_breakf261:=high>f261?1:0
i_breakfm161:=low<fm161?1:0
i_breakfm261:=low<fm261?1:0
if show0
box.set_right(mybox,time_close)
box.set_bottom(mybox,_b)
box.set_top(mybox,_t)
box.set_text(mybox,
b_info?
"TF="+tfChart+":"+f_time_ddHHmm(box.get_right(mybox)-box.get_left(mybox))+":"+
str.tostring(math.abs(box.get_top(mybox)-box.get_bottom(mybox))):na)
if array.lastindexof(a_hist_tf,tfChart)!=-1
array.set(a_hist_top,array.lastindexof(a_hist_tf,tfChart),_t)
array.set(a_hist_bottom,array.lastindexof(a_hist_tf,tfChart),_b)
array.set(a_hist_close,array.lastindexof(a_hist_tf,tfChart),close)
line.set_x2(myfibo23,time_close)
line.set_x2(myfibo38,time_close)
line.set_x2(myfibo50,time_close)
line.set_x2(myfibo61,time_close)
line.set_x2(myfibo78,time_close)
if i_breakT>0
label.set_xy(myfibo161,(_l+time_close)/2,f161)
if i_breakf161>0
label.set_xy(myfibo261,(_l+time_close)/2,f261)
if i_breakf261>0
label.set_xy(myfibo361,(_l+time_close)/2,f361)
if i_breakB>0
label.set_xy(myfibom161,(_l+time_close)/2,fm161)
if i_breakfm161>0
label.set_xy(myfibom261,(_l+time_close)/2,fm261)
if i_breakfm261>0
label.set_xy(myfibom361,(_l+time_close)/2,fm361)
//box H1
close1=f_getMtf(tf1,close)
open1=f_getMtf(tf1,open)
time1=f_getMtf(tf1,time)
time_close1=f_getMtf(tf1,time_close)
var m_high1 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_high1 = matrix.new<float>(2,1,time)//0: price, 1:time
var m_low1 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_low1 = matrix.new<float>(2,1,time)//0: price, 1:time
b_isLastUp1=close1[1]>open1[1]?true:false
b_isUp1=close1>open1?true:false
b_peak1=b_isLastUp1 and not b_isUp1
b_bottom1=not b_isLastUp1 and b_isUp1
i_renew1=0
var i_last_renew1=0//laststate
if b_peak1 or b_bottom1
if b_peak1
_high=close1[1]>=open1?close1[1]:open1
_high_time=close1[1]>=open1?time_close1[1]:time_close1
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_high(i_last_renew1,_high,_high_time,m_high1,m_return_high1,m_low1,m_return_low1)
i_renew1:=_i_renew
m_high1:= o_m_high
m_return_high1:=o_m_return_high
m_low1:= o_m_low
m_return_low1:= o_m_return_low
else if b_bottom1
_low=close1[1]<=open1?close1[1]:open1
_low_time=close1[1]<=open1?time_close1[1]:time_close1
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_low(i_last_renew1,_low,_low_time,m_low1,m_return_low1,m_high1,m_return_high1)
i_renew1:=_i_renew
m_high1:= o_m_high
m_return_high1:= o_m_return_high
m_low1:= o_m_low
m_return_low1:= o_m_return_low
else
na
else
na
//
i_last_renew1:=i_renew1
var mybox1=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na)
top1= matrix.get(m_high1,0,matrix.columns(m_high1)-1)
top_time1= matrix.get(m_high1,1,matrix.columns(m_high1)-1)
bottom1= matrix.get(m_low1,0,matrix.columns(m_low1)-1)
bottom_time1= matrix.get(m_low1,1,matrix.columns(m_low1)-1)
c_box1=bottom_time1<top_time1?cBoxU1:cBoxD1
va1=bottom_time1<top_time1?text.align_top:text.align_bottom
_h1 = array.from(int(top_time1),int(bottom_time1))
_v1 = array.from(top1,bottom1)
_t1 = array.max(_v1)
_b1 = array.min(_v1)
_l1 = array.min(_h1)
if show1 and i_renew1!=0
mybox1:=box.new(_l1,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_width=widthBox1,border_style=styleBox1,
text_halign=text.align_right,text_valign=va1,text_size=infoSize1,border_color=c_box1,text_color=cBoxT1)
array.push(a_hist_time,_l1)
array.push(a_hist_tf,tf1)
array.push(a_hist_top,_t1)
array.push(a_hist_bottom,_b1)
array.push(a_hist_close,close)
array.push(a_hist_cbox,c_box)
if show1
box.set_right(mybox1,time_close1)
box.set_bottom(mybox1,_b1)
box.set_top(mybox1,_t1)
box.set_text(mybox1,b_info1?"TF➊="+tf1+"\n"+
f_time_ddHHmm(box.get_right(mybox1)-box.get_left(mybox1))+"\n"+
str.tostring(math.abs(box.get_top(mybox1)-box.get_bottom(mybox1))):na)
if array.lastindexof(a_hist_tf,tf1)!=-1
array.set(a_hist_top,array.lastindexof(a_hist_tf,tf1),_t1)
array.set(a_hist_bottom,array.lastindexof(a_hist_tf,tf1),_b1)
array.set(a_hist_close,array.lastindexof(a_hist_tf,tf1),close1)
//box H2
close2=f_getMtf(tf2,close)
open2=f_getMtf(tf2,open)
time2=f_getMtf(tf2,time)
time_close2=f_getMtf(tf2,time_close)
var m_high2 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_high2 = matrix.new<float>(2,1,time)//0: price, 1:time
var m_low2 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_low2 = matrix.new<float>(2,1,time)//0: price, 1:time
b_isLastUp2=close2[1]>open2[1]?true:false
b_isUp2=close2>open2?true:false
b_peak2=b_isLastUp2 and not b_isUp2
b_bottom2=not b_isLastUp2 and b_isUp2
i_renew2=0
var i_last_renew2=0//laststate
if b_peak2 or b_bottom2
if b_peak2
_high=close2[1]>=open2?close2[1]:open2
_high_time=close2[1]>=open2?time_close2[1]:time_close2
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_high(i_last_renew2,_high,_high_time,m_high2,m_return_high2,m_low2,m_return_low2)
i_renew2:=_i_renew
m_high2:= o_m_high
m_return_high2:=o_m_return_high
m_low2:= o_m_low
m_return_low2:= o_m_return_low
else if b_bottom2
_low=close2[1]<=open2?close2[1]:open2
_low_time=close2[1]<=open2?time_close2[1]:time_close2
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_low(i_last_renew2,_low,_low_time,m_low2,m_return_low2,m_high2,m_return_high2)
i_renew2:=_i_renew
m_high2:= o_m_high
m_return_high2:= o_m_return_high
m_low2:= o_m_low
m_return_low2:= o_m_return_low
else
na
else
na
//
i_last_renew2:=i_renew2
var mybox2=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na)
top2= matrix.get(m_high2,0,matrix.columns(m_high2)-1)
top_time2= matrix.get(m_high2,1,matrix.columns(m_high2)-1)
bottom2= matrix.get(m_low2,0,matrix.columns(m_low2)-1)
bottom_time2= matrix.get(m_low2,1,matrix.columns(m_low2)-1)
c_box2=bottom_time2<top_time2?cBoxU2:cBoxD2
va2=bottom_time2<top_time2?text.align_top:text.align_bottom
_h2 = array.from(int(top_time2),int(bottom_time2))
_v2 = array.from(top2,bottom2)
_t2 = array.max(_v2)
_b2 = array.min(_v2)
_l2 = array.min(_h2)
if show2 and i_renew2!=0
mybox2:=box.new(_l2,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_width=widthBox2,border_style=styleBox2,
text_halign=text.align_right,text_valign=va2,text_size=infoSize2,border_color=c_box2,text_color=cBoxT2)
array.push(a_hist_time,_l2)
array.push(a_hist_tf,tf2)
array.push(a_hist_top,_t2)
array.push(a_hist_bottom,_b2)
array.push(a_hist_close,close)
array.push(a_hist_cbox,c_box)
if show2
box.set_right(mybox2,time_close2)
box.set_bottom(mybox2,_b2)
box.set_top(mybox2,_t2)
box.set_text(mybox2,b_info2?"TF➋="+tf2+"\n"+
f_time_ddHHmm(box.get_right(mybox2)-box.get_left(mybox2))+"\n"+
str.tostring(math.abs(box.get_top(mybox2)-box.get_bottom(mybox2))):na)
if array.lastindexof(a_hist_tf,tf2)!=-1
array.set(a_hist_top,array.lastindexof(a_hist_tf,tf2),_t2)
array.set(a_hist_bottom,array.lastindexof(a_hist_tf,tf2),_b2)
array.set(a_hist_close,array.lastindexof(a_hist_tf,tf2),close2)
//box H3
close3=f_getMtf(tf3,close)
open3=f_getMtf(tf3,open)
time3=f_getMtf(tf3,time)
time_close3=f_getMtf(tf3,time_close)
var m_high3 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_high3 = matrix.new<float>(2,1,time)//0: price, 1:time
var m_low3 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_low3 = matrix.new<float>(2,1,time)//0: price, 1:time
b_isLastUp3=close3[1]>open3[1]?true:false
b_isUp3=close3>open3?true:false
b_peak3=b_isLastUp3 and not b_isUp3
b_bottom3=not b_isLastUp3 and b_isUp3
i_renew3=0
var i_last_renew3=0
if b_peak3 or b_bottom3
if b_peak3
_high=close3[1]>=open3?close3[1]:open3
_high_time=close3[1]>=open3?time_close3[1]:time_close3
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_high(i_last_renew3,_high,_high_time,m_high3,m_return_high3,m_low3,m_return_low3)
i_renew3:=_i_renew
m_high3:= o_m_high
m_return_high3:=o_m_return_high
m_low3:= o_m_low
m_return_low3:= o_m_return_low
else if b_bottom3
_low=close3[1]<=open3?close3[1]:open3
_low_time=close3[1]<=open3?time_close3[1]:time_close3
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_low(i_last_renew3,_low,_low_time,m_low3,m_return_low3,m_high3,m_return_high3)
i_renew3:=_i_renew
m_high3:= o_m_high
m_return_high3:= o_m_return_high
m_low3:= o_m_low
m_return_low3:= o_m_return_low
else
na
else
na
//
i_last_renew3:=i_renew3
var mybox3=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na)
top3= matrix.get(m_high3,0,matrix.columns(m_high3)-1)
top_time3= matrix.get(m_high3,1,matrix.columns(m_high3)-1)
bottom3= matrix.get(m_low3,0,matrix.columns(m_low3)-1)
bottom_time3= matrix.get(m_low3,1,matrix.columns(m_low3)-1)
c_box3=bottom_time3<top_time3?cBoxU3:cBoxD3
va3=bottom_time3<top_time3?text.align_top:text.align_bottom
_h3 = array.from(int(top_time3),int(bottom_time3))
_v3 = array.from(top3,bottom3)
_t3 = array.max(_v3)
_b3 = array.min(_v3)
_l3 = array.min(_h3)
if show3 and i_renew3!=0
mybox3:=box.new(_l3,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_width=widthBox3,border_style=styleBox3,
text_halign=text.align_right,text_valign=va3,text_size=infoSize3,border_color=c_box3,text_color=cBoxT3)
array.push(a_hist_time,_l3)
array.push(a_hist_tf,tf3)
array.push(a_hist_top,_t3)
array.push(a_hist_bottom,_b3)
array.push(a_hist_close,close)
array.push(a_hist_cbox,c_box)
if show3
box.set_right(mybox3,time_close3)
box.set_bottom(mybox3,_b3)
box.set_top(mybox3,_t3)
box.set_text(mybox3,b_info3?"TF➌="+tf3+"\n"+
f_time_ddHHmm(box.get_right(mybox3)-box.get_left(mybox3))+"\n"+
str.tostring(math.abs(box.get_top(mybox3)-box.get_bottom(mybox3))):na)
if array.lastindexof(a_hist_tf,tf3)!=-1
array.set(a_hist_top,array.lastindexof(a_hist_tf,tf3),_t3)
array.set(a_hist_bottom,array.lastindexof(a_hist_tf,tf3),_b3)
array.set(a_hist_close,array.lastindexof(a_hist_tf,tf3),close3)
//box H4
close4=f_getMtf(tf4,close)
open4=f_getMtf(tf4,open)
time4=f_getMtf(tf4,time)
time_close4=f_getMtf(tf4,time_close)
var m_high4 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_high4 = matrix.new<float>(2,1,time)//0: price, 1:time
var m_low4 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_low4 = matrix.new<float>(2,1,time)//0: price, 1:time
b_isLastUp4=close4[1]>open4[1]?true:false
b_isUp4=close4>open4?true:false
b_peak4=b_isLastUp4 and not b_isUp4
b_bottom4=not b_isLastUp4 and b_isUp4
i_renew4=0
var i_last_renew4=0
if b_peak4 or b_bottom4
if b_peak4
_high=close4[1]>=open4?close4[1]:open4
_high_time=close4[1]>=open4?time_close4[1]:time_close4
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_high(i_last_renew4,_high,_high_time,m_high4,m_return_high4,m_low4,m_return_low4)
i_renew4:=_i_renew
m_high4:= o_m_high
m_return_high4:=o_m_return_high
m_low4:= o_m_low
m_return_low4:= o_m_return_low
else if b_bottom4
_low=close4[1]<=open4?close4[1]:open4
_low_time=close4[1]<=open4?time_close4[1]:time_close4
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_low(i_last_renew4,_low,_low_time,m_low4,m_return_low4,m_high4,m_return_high4)
i_renew4:=_i_renew
m_high4:= o_m_high
m_return_high4:= o_m_return_high
m_low4:= o_m_low
m_return_low4:= o_m_return_low
else
na
else
na
//
i_last_renew4:=i_renew4
var mybox4=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na)
top4= matrix.get(m_high4,0,matrix.columns(m_high4)-1)
top_time4= matrix.get(m_high4,1,matrix.columns(m_high4)-1)
bottom4= matrix.get(m_low4,0,matrix.columns(m_low4)-1)
bottom_time4= matrix.get(m_low4,1,matrix.columns(m_low4)-1)
c_box4=bottom_time4<top_time4?cBoxU4:cBoxD4
va4=bottom_time4<top_time4?text.align_top:text.align_bottom
_h4 = array.from(int(top_time4),int(bottom_time4))
_v4 = array.from(top4,bottom4)
_t4 = array.max(_v4)
_b4 = array.min(_v4)
_l4 = array.min(_h4)
if show4 and i_renew4!=0
mybox4:=box.new(_l4,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_width=widthBox4,border_style=styleBox4,
text_halign=text.align_right,text_valign=va4,text_size=infoSize4,border_color=c_box4,text_color=cBoxT4)
array.push(a_hist_time,_l4)
array.push(a_hist_tf,tf4)
array.push(a_hist_top,_t4)
array.push(a_hist_bottom,_b4)
array.push(a_hist_close,close)
array.push(a_hist_cbox,c_box)
if show4
box.set_right(mybox4,time_close4)
box.set_bottom(mybox4,_b4)
box.set_top(mybox4,_t4)
box.set_text(mybox4,b_info4?"TF➍="+tf4+"\n"+
f_time_ddHHmm(box.get_right(mybox4)-box.get_left(mybox4))+"\n"+
str.tostring(math.abs(box.get_top(mybox4)-box.get_bottom(mybox4))):na)
if array.lastindexof(a_hist_tf,tf4)!=-1
array.set(a_hist_top,array.lastindexof(a_hist_tf,tf4),_t4)
array.set(a_hist_bottom,array.lastindexof(a_hist_tf,tf4),_b4)
array.set(a_hist_close,array.lastindexof(a_hist_tf,tf4),close4)
//
//fibonacci levels of higher boxes
//
var l_mybox1_rt=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize1,text.align_left)
var l_mybox1_rb=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize1,text.align_left)
var l_mybox2_rt=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize2,text.align_left)
var l_mybox2_rb=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize2,text.align_left)
var l_mybox3_rt=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize3,text.align_left)
var l_mybox3_rb=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize3,text.align_left)
var l_mybox4_rt=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize3,text.align_left)
var l_mybox4_rb=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize3,text.align_left)
if show1 and b_fibo1
[_top,_tops,_bottom,_bottoms] = f_fibo_range(box.get_bottom(mybox1),box.get_top(mybox1),close)
label.set_xy(l_mybox1_rt,box.get_right(mybox1),_top)
label.set_textcolor(l_mybox1_rt,c_box1)
label.set_text(l_mybox1_rt,"_____"+_tops+":"+str.tostring(_top,"#.0000")+"@➊"+tf1)
label.set_xy(l_mybox1_rb,box.get_right(mybox1),_bottom)
label.set_textcolor(l_mybox1_rb,c_box1)
label.set_text(l_mybox1_rb,"_____"+_bottoms+":"+str.tostring(_bottom,"#.0000")+"@➊"+tf1)
if show2 and b_fibo2
[_top,_tops,_bottom,_bottoms] = f_fibo_range(box.get_bottom(mybox2),box.get_top(mybox2),close)
label.set_xy(l_mybox2_rt,box.get_right(mybox2),_top)
label.set_textcolor(l_mybox2_rt,c_box2)
label.set_text(l_mybox2_rt,"_____"+_tops+":"+str.tostring(_top,"#.0000")+"@➋"+tf2)
label.set_xy(l_mybox2_rb,box.get_right(mybox2),_bottom)
label.set_textcolor(l_mybox2_rb,c_box2)
label.set_text(l_mybox2_rb,"_____"+_bottoms+":"+str.tostring(_bottom,"#.0000")+"@➋"+tf2)
if show3 and b_fibo3
[_top,_tops,_bottom,_bottoms] = f_fibo_range(box.get_bottom(mybox3),box.get_top(mybox3),close)
label.set_xy(l_mybox3_rt,box.get_right(mybox3),_top)
label.set_textcolor(l_mybox3_rt,c_box3)
label.set_text(l_mybox3_rt,"_____"+_tops+":"+str.tostring(_top,"#.0000")+"@➌"+tf3)
label.set_xy(l_mybox3_rb,box.get_right(mybox3),_bottom)
label.set_textcolor(l_mybox3_rb,c_box3)
label.set_text(l_mybox3_rb,"_____"+_bottoms+":"+str.tostring(_bottom,"#.0000")+"@➌"+tf3)
if show4 and b_fibo4
[_top,_tops,_bottom,_bottoms] = f_fibo_range(box.get_bottom(mybox4),box.get_top(mybox4),close)
label.set_xy(l_mybox4_rt,box.get_right(mybox4),_top)
label.set_textcolor(l_mybox4_rt,c_box4)
label.set_text(l_mybox4_rt,"_____"+_tops+":"+str.tostring(_top,"#.0000")+"@➍"+tf4)
label.set_xy(l_mybox4_rb,box.get_right(mybox4),_bottom)
label.set_textcolor(l_mybox4_rb,c_box4)
label.set_text(l_mybox4_rb,"_____"+_bottoms+":"+str.tostring(_bottom,"#.0000")+"@➍"+tf4)
var max=minimapHist
a_hist_top_mm=array.new_float(0,na)
a_hist_bottom_mm=array.new_float(0,na)
a_hist_time_mm=array.new_int(0,na)
a_hist_tf_mm=array.new_string(0,na)
a_hist_close_mm=array.new_float(0,na)
a_hist_cbox_mm=array.new_color(0,na)
a_hist_top_mm :=array.size(a_hist_top)>max?array.slice(a_hist_top,array.size(a_hist_top)-max,array.size(a_hist_top)-1):a_hist_top
a_hist_bottom_mm :=array.size(a_hist_bottom)>max?array.slice(a_hist_bottom,array.size(a_hist_bottom)-max,array.size(a_hist_bottom)-1):a_hist_bottom
a_hist_time_mm :=array.size(a_hist_time)>max?array.slice(a_hist_time,array.size(a_hist_time)-max,array.size(a_hist_time)-1):a_hist_time
a_hist_tf_mm :=array.size(a_hist_tf)>max?array.slice(a_hist_tf,array.size(a_hist_tf)-max,array.size(a_hist_tf)-1):a_hist_tf
a_hist_close_mm :=array.size(a_hist_close)>max?array.slice(a_hist_close,array.size(a_hist_close)-max,array.size(a_hist_close)-1):a_hist_close
a_hist_cbox_mm :=array.size(a_hist_cbox)>max?array.slice(a_hist_cbox,array.size(a_hist_cbox)-max,array.size(a_hist_cbox)-1):a_hist_cbox
hist_top = array.max(a_hist_top_mm)
hist_bottom = array.min(a_hist_bottom_mm)
f_cellpos(_top,_bottom,_rt,_rb) =>
_p0 = 10
_p100 = 50
_diff = _top-_bottom
_rtdiff = _top-_rt
_rbdiff = _top-_rb
_topp = int(10 - (_p0-_p100)*_rtdiff/_diff)
_bottomp =int(10 - (_p0-_p100)*_rbdiff/_diff)
[_topp,_bottomp]
if showMinimap
minimap = table.new(position.bottom_left,100,100,color.new(color.white,90),frame_color=color.white,frame_width=1,border_color=na,border_width=1)
if array.size(a_hist_time_mm)>0
table.cell(minimap,0,0,text="minimap from "+f_time_ddHHmm(array.last(a_hist_time_mm)-array.get(a_hist_time_mm,0))+" ago",text_color=color.white,text_size=size.small,text_halign=text.align_left)
table.merge_cells(minimap,0,0,10,0)
table.cell(minimap,0,1,text=str.tostring(hist_top),text_color=color.white,text_size=size.small,text_halign=text.align_left)
table.merge_cells(minimap,0,1,10,1)
table.cell(minimap,0,99,text=str.tostring(hist_bottom),text_color=color.white,text_size=size.small,text_halign=text.align_left)
table.merge_cells(minimap,0,99,10,99)
if array.size(a_hist_top_mm)>0
for i = 0 to array.size(a_hist_top_mm)-1
[_top,_bottom]=f_cellpos(hist_top,hist_bottom,array.get(a_hist_top_mm,i),array.get(a_hist_bottom_mm,i))
if array.get(a_hist_tf_mm,i) == tfChart
_fl = f_fibo_level(array.get(a_hist_bottom_mm,i),array.get(a_hist_top_mm,i),array.get(a_hist_close_mm,i))
table.cell(minimap,i,_top,_fl,text_color=f_fl_c(_fl),bgcolor=array.get(a_hist_cbox_mm,i),text_size=size.tiny,text_valign=f_fl_va(_fl))
table.merge_cells(minimap,i,_top,i,_bottom)
else
table.cell(minimap,i,_top-1,"▼",text_color=array.get(a_hist_cbox_mm,i),text_size=size.tiny,bgcolor=na)
table.cell(minimap,i,_top,array.get(a_hist_tf_mm,i),text_color=color.white,bgcolor=array.get(a_hist_cbox_mm,i),text_size=size.tiny)
table.merge_cells(minimap,i,_top,i,_bottom)
table.cell(minimap,i,_bottom+1,"▲",text_color=array.get(a_hist_cbox_mm,i),text_size=size.tiny,bgcolor=na)
na
//*****
//end of high low box
//*****
//
//RSI
//
var int RSIt =70
var int RSIb =30
s_RSI_1= show0 and showRSI?ta.rsi(srcRSI,spanRSI_1):na
s_RSI_2= show0 and showRSI?ta.rsi(srcRSI,spanRSI_2):na
b_RSI_70 = s_RSI_1>=RSIt or s_RSI_2>=RSIt
b_RSI_30 = s_RSI_1<=RSIb or s_RSI_2<=RSIb
cRSI=
s_RSI_1==s_RSI_1[1] and s_RSI_2==s_RSI_2[1]?na:
b_RSI_70? s_RSI_1>s_RSI_2? s_RSI_2<RSIt?cRSIi: cRSIt1: s_RSI_1<RSIt?cRSIt3: cRSIt2:
b_RSI_30? s_RSI_1<s_RSI_2? s_RSI_2>RSIb?cRSIi: cRSIb1: s_RSI_1>RSIb?cRSIb3: cRSIb2:na
RSIy=b_RSI_70? box.get_top(mybox): b_RSI_30?box.get_bottom(mybox):na
plotshape(RSIy,"SIG_RSI",shape.circle,location=location.absolute,color=cRSI,text=na,textcolor=na,size=size.normal)
//➊➋➌➍➎➏➐➑➒➓❶❷❸❹❺❻❼❽❾❿
//H1
s_RSI1_1= show1 and showRSI1?f_getMtf(tf1,ta.rsi(srcRSI,spanRSI_1)):na
s_RSI1_2= show1 and showRSI1?f_getMtf(tf1,ta.rsi(srcRSI,spanRSI_2)):na
b_RSI1_70 = s_RSI1_1>=RSIt or s_RSI1_2>=RSIt
b_RSI1_30 = s_RSI1_1<=RSIb or s_RSI1_2<=RSIb
cRSI1=
s_RSI1_1==s_RSI1_1[1] and s_RSI1_2==s_RSI1_2[1]?na:
b_RSI1_70? s_RSI1_1>s_RSI1_2? s_RSI1_2<RSIt?cRSI1i: cRSI1t1: s_RSI1_1<RSIt?cRSI1t3: cRSI1t2:
b_RSI1_30? s_RSI1_1<s_RSI1_2? s_RSI1_2>RSIb?cRSI1i: cRSI1b1: s_RSI1_1>RSIb?cRSI1b3: cRSI1b2:na
RSI1y=b_RSI1_70? box.get_top(mybox1): b_RSI1_30?box.get_bottom(mybox1):na
plotchar(RSI1y,"SIG_RSI1",char="➊",location=location.absolute,color=cRSI1,textcolor=na,size=size.small)
//H2
s_RSI2_1= show2 and showRSI2?f_getMtf(tf2,ta.rsi(srcRSI,spanRSI_1)):na
s_RSI2_2= show2 and showRSI2?f_getMtf(tf2,ta.rsi(srcRSI,spanRSI_2)):na
b_RSI2_70 = s_RSI2_1>=RSIt or s_RSI2_2>=RSIt
b_RSI2_30 = s_RSI2_1<=RSIb or s_RSI2_2<=RSIb
cRSI2=
s_RSI2_1==s_RSI2_1[1] and s_RSI2_2==s_RSI2_2[1]?na:
b_RSI2_70? s_RSI2_1>s_RSI2_2? s_RSI2_2<RSIt?cRSI2i: cRSI2t1: s_RSI2_1<RSIt?cRSI2t3: cRSI2t2:
b_RSI2_30? s_RSI2_1<s_RSI2_2? s_RSI2_2>RSIb?cRSI2i: cRSI2b1: s_RSI2_1>RSIb?cRSI2b3: cRSI2b2:na
RSI2y=b_RSI2_70? box.get_top(mybox2): b_RSI2_30?box.get_bottom(mybox2):na
plotchar(RSI2y,"SIG_RSI2",char="➋",location=location.absolute,color=cRSI2,textcolor=na,size=size.small)
//H3
s_RSI3_1= show3 and showRSI3?f_getMtf(tf3,ta.rsi(srcRSI,spanRSI_1)):na
s_RSI3_2= show3 and showRSI3?f_getMtf(tf3,ta.rsi(srcRSI,spanRSI_2)):na
b_RSI3_70 = s_RSI3_1>=RSIt or s_RSI3_2>=RSIt
b_RSI3_30 = s_RSI3_1<=RSIb or s_RSI3_2<=RSIb
cRSI3=
s_RSI3_1==s_RSI3_1[1] and s_RSI3_2==s_RSI3_2[1]?na:
b_RSI3_70? s_RSI3_1>s_RSI3_2? s_RSI3_2<RSIt?cRSI3i: cRSI3t1: s_RSI3_1<RSIt?cRSI3t3: cRSI3t2:
b_RSI3_30? s_RSI3_1<s_RSI3_2? s_RSI3_2>RSIb?cRSI3i: cRSI3b1: s_RSI3_1>RSIb?cRSI3b3: cRSI3b2:na
RSI3y=b_RSI3_70? box.get_top(mybox3): b_RSI3_30?box.get_bottom(mybox3):na
plotchar(RSI3y,"SIG_RSI3",char="➌",location=location.absolute,color=cRSI3,textcolor=na,size=size.small)
//H4
s_RSI4_1= show4 and showRSI4?f_getMtf(tf4,ta.rsi(srcRSI,spanRSI_1)):na
s_RSI4_2= show4 and showRSI4?f_getMtf(tf4,ta.rsi(srcRSI,spanRSI_2)):na
b_RSI4_70 = s_RSI4_1>=RSIt or s_RSI4_2>=RSIt
b_RSI4_30 = s_RSI4_1<=RSIb or s_RSI4_2<=RSIb
cRSI4=
s_RSI4_1==s_RSI4_1[1] and s_RSI4_2==s_RSI4_2[1]?na:
b_RSI4_70? s_RSI4_1>s_RSI4_2? s_RSI4_2<RSIt?cRSI4i: cRSI4t1: s_RSI4_1<RSIt?cRSI4t3: cRSI4t2:
b_RSI4_30? s_RSI4_1<s_RSI4_2? s_RSI4_2>RSIb?cRSI4i: cRSI4b1: s_RSI4_1>RSIb?cRSI4b3: cRSI4b2:na
RSI4y=b_RSI4_70? box.get_top(mybox4): b_RSI4_30?box.get_bottom(mybox4):na
plotchar(RSI4y,"SIG_RSI4",char="➍",location=location.absolute,color=cRSI4,textcolor=na,size=size.small)
|
Events | https://www.tradingview.com/script/Xg7dgEIE-Events/ | sherwoodherben2 | https://www.tradingview.com/u/sherwoodherben2/ | 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/
// © sherwoodherben2
//@version=5
// original credit to:
// © jdehorty
// @description This library is a data provider for important Dates and Times from the Economic Calendar.
// Updates and additions by Sherwood
// [1/11/23] (published as revision 2.0)]
// added CPI calendar for 2023
// [1/11/23] (published as revision 5.0)]
// added PPI calendar for 2023
// [1/15/23] (published as revision 11.0)
// added ECI for 2022/23
library(title='Events')
// @function Returns the list of dates supported by this library as a string array.
// @returns
// array<string> : Names of events supported by this library
export events () =>
var array<string> events = array.from(
"FOMC Meetings", // Federal Open Market Committee
"FOMC Minutes", // FOMC Meeting Minutes
"PPI", // Producer Price Index
"CPI", // Consumer Price Index
"CSI", // Consumer Sentiment Index
"CCI", // Consumer Confidence Index
"NFP", // Non-Farm Payrolls
"ECI" // Employment Cost Index
)
// @function Gets the FOMC Meeting Dates. The FOMC meets eight times a year to determine the course of monetary policy. The FOMC announces its decision on the federal funds rate at the conclusion of each meeting and also issues a statement that provides information on the economic outlook and the Committee's assessment of the risks to the outlook.
// @returns
// array<int> : FOMC Meeting Dates as timestamps
export fomcMeetings() =>
array.from(
timestamp("26 Jan 2022 14:00:00 EST"), // 2022
timestamp("16 March 2022 14:00:00 EDT"),
timestamp("4 May 2022 14:00:00 EDT"),
timestamp("15 June 2022 14:00:00 EDT"),
timestamp("27 July 2022 14:00:00 EDT"),
timestamp("21 Sept 2022 14:00:00 EDT"),
timestamp("2 Nov 2022 14:00:00 EDT"),
timestamp("14 Dec 2022 14:00:00 EST"),
timestamp("1 Feb 2023 14:00:00 EST"), // 2023
timestamp("22 March 2023 14:00:00 EDT"),
timestamp("3 May 2023 14:00:00 EDT"),
timestamp("14 June 2023 14:00:00 EDT"),
timestamp("26 July 2023 14:00:00 EDT"),
timestamp("20 Sept 2023 14:00:00 EDT"),
timestamp("1 Nov 2023 14:00:00 EDT"),
timestamp("13 Dec 2023 14:00:00 EST")
)
// @function Gets the FOMC Meeting Minutes Dates. The FOMC Minutes are released three weeks after each FOMC meeting. The Minutes provide information on the Committee's deliberations and decisions at the meeting.
// @returns
// array<int> : FOMC Meeting Minutes Dates as timestamps
export fomcMinutes() =>
array.from(
timestamp("16 Feb 2022 14:00:00 EST"), // 2022
timestamp("6 April 2022 14:00:00 EDT"),
timestamp("25 May 2022 14:00:00 EDT"),
timestamp("6 July 2022 14:00:00 EDT"),
timestamp("17 Aug 2022 14:00:00 EDT"),
timestamp("12 Oct 2022 14:00:00 EDT"),
timestamp("23 Nov 2022 14:00:00 EST"),
timestamp("4 Jan 2023 14:00:00 EST"), // 2023
timestamp("22 Feb 2023 14:00:00 EST"),
timestamp("12 April 2023 14:00:00 EDT"),
timestamp("24 May 2023 14:00:00 EDT"),
timestamp("5 July 2023 14:00:00 EDT"),
timestamp("16 Aug 2023 14:00:00 EDT"),
timestamp("11 Oct 2023 14:00:00 EDT"),
timestamp("22 Nov 2023 14:00:00 EST"),
timestamp("3 Jan 2024 14:00:00 EST")
)
// @function Gets the Producer Price Index (PPI) Dates. The Producer Price Index (PPI) measures the average change over time in the selling prices received by domestic producers for their output. The PPI is a leading indicator of CPI, and CPI is a leading indicator of inflation.
// @returns
// array<int> : PPI Dates as timestamps
export ppiReleases() =>
array.from(
timestamp("9 Nov 2021 8:30:00 EST"), // 2021
timestamp("14 Dec 2021 8:30:00 EST"),
timestamp("13 Jan 2022 8:30:00 EST"), // 2022
timestamp("15 Feb 2022 8:30:00 EST"),
timestamp("15 Mar 2022 8:30:00 EST"),
timestamp("13 Apr 2022 8:30:00 EDT"),
timestamp("12 May 2022 8:30:00 EDT"),
timestamp("14 Jun 2022 8:30:00 EDT"),
timestamp("14 Jul 2022 8:30:00 EDT"),
timestamp("11 Aug 2022 8:30:00 EDT"),
timestamp("14 Sep 2022 8:30:00 EDT"),
timestamp("12 Oct 2022 8:30:00 EDT"),
timestamp("15 Nov 2022 8:30:00 EST"),
timestamp("9 Dec 2022 8:30:00 EST"),
timestamp("18 Jan 2023 8:30:00 EST"), // 2023
timestamp("16 Feb 2023 8:30:00 EST"),
timestamp("15 Mar 2023 8:30:00 EST"),
timestamp("13 Apr 2023 8:30:00 EDT"),
timestamp("11 May 2023 8:30:00 EDT"),
timestamp("14 Jun 2023 8:30:00 EDT"),
timestamp("13 Jul 2023 8:30:00 EDT"),
timestamp("11 Aug 2023 8:30:00 EDT"),
timestamp("14 Sep 2023 8:30:00 EDT"),
timestamp("11 Oct 2023 8:30:00 EDT"),
timestamp("15 Nov 2023 8:30:00 EST"),
timestamp("9 Dec 2023 8:30:00 EST")
)
// @function Gets the Consumer Price Index (CPI) Rekease Dates. The Consumer Price Index (CPI) measures changes in the price level of a market basket of consumer goods and services purchased by households. The CPI is a leading indicator of inflation.
// @returns
// array<int> : CPI Dates as timestamps
export cpiReleases() =>
array.from(
timestamp("12 Jan 2022 08:30:00 EST"), // 2022
timestamp("10 Feb 2022 08:30:00 EST"),
timestamp("10 March 2022 08:30:00 EST"),
timestamp("12 April 2022 08:30:00 EDT"),
timestamp("11 May 2022 08:30:00 EDT"),
timestamp("10 June 2022 08:30:00 EDT"),
timestamp("13 July 2022 08:30:00 EDT"),
timestamp("10 Aug 2022 08:30:00 EDT"),
timestamp("13 Sept 2022 08:30:00 EDT"),
timestamp("13 Oct 2022 08:30:00 EDT"),
timestamp("10 Nov 2022 08:30:00 EST"),
timestamp("13 Dec 2022 08:30:00 EST"),
timestamp("12 Jan 2023 08:30:00 EST"), // 2022
timestamp("14 Feb 2023 08:30:00 EST"),
timestamp("14 March 2023 08:30:00 EST"),
timestamp("12 April 2023 08:30:00 EDT"),
timestamp("10 May 2023 08:30:00 EDT"),
timestamp("12 June 2023 08:30:00 EDT"),
timestamp("12 July 2023 08:30:00 EDT"),
timestamp("10 Aug 2023 08:30:00 EDT"),
timestamp("13 Sept 2023 08:30:00 EDT"),
timestamp("12 Oct 2023 08:30:00 EDT"),
timestamp("14 Nov 2023 08:30:00 EST"),
timestamp("11 Dec 2023 08:30:00 EST")
)
// @function Gets the CSI release dates. The Consumer Sentiment Index (CSI) is a survey of consumer attitudes about the economy and their personal finances. The CSI is a leading indicator of consumer spending.
// @returns
// array<int> : CSI Dates as timestamps
export csiReleases() =>
array.from(
timestamp("14 Jan 2022 10:00:00 EST"), // 2022
timestamp("28 Jan 2022 10:00:00 EST"),
timestamp("11 Feb 2022 10:00:00 EST"),
timestamp("25 Feb 2022 10:00:00 EST"),
timestamp("18 March 2022 10:00:00 EDT"),
timestamp("1 April 2022 10:00:00 EDT"),
timestamp("15 April 2022 10:00:00 EDT"),
timestamp("29 April 2022 10:00:00 EDT"),
timestamp("13 May 2022 10:00:00 EDT"),
timestamp("27 May 2022 10:00:00 EDT"),
timestamp("17 June 2022 10:00:00 EDT"),
timestamp("1 July 2022 10:00:00 EDT"),
timestamp("15 July 2022 10:00:00 EDT"),
timestamp("29 July 2022 10:00:00 EDT"),
timestamp("12 Aug 2022 10:00:00 EDT"),
timestamp("26 Aug 2022 10:00:00 EDT"),
timestamp("16 Sept 2022 10:00:00 EDT"),
timestamp("30 Sept 2022 10:00:00 EDT"),
timestamp("14 Oct 2022 10:00:00 EDT"),
timestamp("28 Oct 2022 10:00:00 EDT"),
timestamp("11 Nov 2022 10:00:00 EST"),
timestamp("23 Nov 2022 10:00:00 EST"),
timestamp("9 Dec 2022 10:00:00 EST"),
timestamp("23 Dec 2022 10:00:00 EST"),
timestamp("13 Jan 2023 10:00:00 EST"), // 2023
timestamp("27 Jan 2023 10:00:00 EST"),
timestamp("10 Feb 2023 10:00:00 EST"),
timestamp("24 Feb 2023 10:00:00 EST"),
timestamp("17 March 2023 10:00:00 EDT"),
timestamp("31 March 2023 10:00:00 EDT"),
timestamp("14 April 2023 10:00:00 EDT"),
timestamp("28 April 2023 10:00:00 EDT"),
timestamp("12 May 2023 10:00:00 EDT"),
timestamp("26 May 2023 10:00:00 EDT"),
timestamp("16 June 2023 10:00:00 EDT"),
timestamp("30 June 2023 10:00:00 EDT"),
timestamp("14 July 2023 10:00:00 EDT"),
timestamp("28 July 2023 10:00:00 EDT"),
timestamp("11 Aug 2023 10:00:00 EDT"),
timestamp("25 Aug 2023 10:00:00 EDT"),
timestamp("15 Sept 2023 10:00:00 EDT"),
timestamp("29 Sept 2023 10:00:00 EDT"),
timestamp("13 Oct 2023 10:00:00 EDT"),
timestamp("27 Oct 2023 10:00:00 EDT"),
timestamp("10 Nov 2023 10:00:00 EST"),
timestamp("22 Nov 2023 10:00:00 EST"),
timestamp("8 Dec 2023 10:00:00 EST"),
timestamp("22 Dec 2023 10:00:00 EST")
)
// @function Gets the CCI release dates. The Conference Board's Consumer Confidence Index (CCI) is a survey of consumer attitudes about the economy and their personal finances. The CCI is a leading indicator of consumer spending.
// @returns
// array<int> : CCI Dates as timestamps
export cciReleases() =>
array.from(
timestamp("25 Jan 2022 10:00:00 EST"), // 2022
timestamp("22 Feb 2022 10:00:00 EST"),
timestamp("29 March 2022 10:00:00 EDT"),
timestamp("26 April 2022 10:00:00 EDT"),
timestamp("31 May 2022 10:00:00 EDT"),
timestamp("28 June 2022 10:00:00 EDT"),
timestamp("26 July 2022 10:00:00 EDT"),
timestamp("30 Aug 2022 10:00:00 EDT"),
timestamp("27 Sept 2022 10:00:00 EDT"),
timestamp("25 Oct 2022 10:00:00 EDT"),
timestamp("29 Nov 2022 10:00:00 EST"),
timestamp("27 Dec 2022 10:00:00 EST"),
timestamp("31 Jan 2023 10:00:00 EST"), // 2023
timestamp("28 Feb 2023 10:00:00 EST"),
timestamp("28 March 2023 10:00:00 EDT"),
timestamp("25 April 2023 10:00:00 EDT"),
timestamp("30 May 2023 10:00:00 EDT"),
timestamp("27 June 2023 10:00:00 EDT"),
timestamp("25 July 2023 10:00:00 EDT"),
timestamp("29 Aug 2023 10:00:00 EDT"),
timestamp("26 Sept 2023 10:00:00 EDT"),
timestamp("31 Oct 2023 10:00:00 EDT"),
timestamp("28 Nov 2023 10:00:00 EST"),
timestamp("26 Dec 2023 10:00:00 EST")
)
// @function Gets the NFP release dates. Nonfarm payrolls is an employment report released monthly by the Bureau of Labor Statistics (BLS) that measures the change in the number of employed people in the United States.
// @returns
// array<int> : NFP Dates as timestamps
export nfpReleases() =>
array.from(
timestamp("7 Jan 2022 8:30:00 EST"), // 2022
timestamp("4 Feb 2022 8:30:00 EST"),
timestamp("4 March 2022 8:30:00 EST"),
timestamp("1 April 2022 8:30:00 EDT"),
timestamp("6 May 2022 8:30:00 EDT"),
timestamp("3 June 2022 8:30:00 EDT"),
timestamp("8 July 2022 8:30:00 EDT"),
timestamp("5 Aug 2022 8:30:00 EDT"),
timestamp("2 Sept 2022 8:30:00 EDT"),
timestamp("7 Oct 2022 8:30:00 EDT"),
timestamp("4 Nov 2022 8:30:00 EDT"),
timestamp("2 Dec 2022 8:30:00 EST"),
timestamp("6 Jan 2023 8:30:00 EST"), // 2023
timestamp("3 Feb 2023 8:30:00 EST"),
timestamp("3 March 2023 8:30:00 EST"),
timestamp("7 April 2023 8:30:00 EDT"),
timestamp("5 May 2023 8:30:00 EDT"),
timestamp("2 June 2023 8:30:00 EDT"),
timestamp("7 July 2023 8:30:00 EDT"),
timestamp("4 Aug 2023 8:30:00 EDT"),
timestamp("1 Sept 2023 8:30:00 EDT"),
timestamp("6 Oct 2023 8:30:00 EDT"),
timestamp("3 Nov 2023 8:30:00 EDT"),
timestamp("1 Dec 2023 8:30:00 EST")
)
// @function Gets the ECI The Employment Cost Index (ECI) is a measure of the change in the cost of labor,
export eciReleases() =>
array.from(
timestamp("31 Jan 2022 8:30:00 EST"), // 2022
timestamp("29 Apr 2022 8:30:00 EST"),
timestamp("29 Jul 2022 8:30:00 EST"),
timestamp("31 oct 2022 8:30:00 EST"),
timestamp("31 Jan 2023 8:30:00 EST"), // 2023
timestamp("28 Apr 2023 8:30:00 EST"),
timestamp("28 Jul 2023 8:30:00 EST"),
timestamp("31 oct 2023 8:30:00 EST")
)
|
Liquidation_lines | https://www.tradingview.com/script/PfATAp8v-Liquidation-lines/ | djmad | https://www.tradingview.com/u/djmad/ | 64 | 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
// my_current_verion=158.0
//@version=5
library("Liquidationline",overlay = true)
/////////////////////////////////
// this libary helps you drawing standard liquidationlines
/////////////////////////////////
export type Liquidationline
int creationtime = na
int stoptime = na
float price = na
float leverage = na
float maintainance = na
bool line_active = na
color line_color = na
int line_thickness = na
string line_style = na
string line_direction = na
bool line_finished = na
bool text_active = na
string text_size = na
color text_color = na
export f_getbartime() =>
// this function delivers the time per bar in unixtime
var int _timeperbar = na
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
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
export f_calculateLeverage(float _leverage, float _maintainance, float _value, string _direction) =>
//f_calculateLeverage - calculates the leverage based on inputs _leverage, _maintainance, _value, and _direction
maintainance_f = (100 - _maintainance)/10000
if _direction == "short"
(_leverage * _value)/(_leverage - 1 + (maintainance_f * _leverage))
else if _direction == "long"
(_leverage * _value)/(_leverage + 1 - (maintainance_f * _leverage))
export f_liqline_update(Liquidationline [] _Liqui_Line, bool _killonlowhigh, int _minlength = -1, float _timeperbar = 0.00000000001) =>
//This code updates the properties of Liquidationline objects stored in the _Liqui_Line array.
//The properties being updated include stoptime, line_finished, and price.
//The code first checks the line direction of each object and then updates the values accordingly.
// If the line direction is "long" and the line has not been finished and the low is less than the leverage
//value calculated using f_calculateLeverage or if the close is less than the leverage value, then the line is
//marked as finished and the stoptime is set to the current time. If the line direction is "short" and the
//line has not been finished and the high is greater than the leverage value calculated using f_calculateLeverage
//or if the close is greater than the leverage value, then the line is marked as finished and the stoptime is set to the current time.
var string getA_line_direction = na
var float getA_price = na
var float getA_leverage = na
var float getA_maintainance = na
var bool getA_line_finished = na
if array.size(_Liqui_Line) > 0
for i = array.size(_Liqui_Line)-1 to 0
getA = array.get(_Liqui_Line, i)
//capturing double gets
getA_line_direction := getA.line_direction
getA_price := getA.price
getA_leverage := getA.leverage
getA_maintainance := getA.maintainance
getA_line_finished := getA.line_finished
if getA_line_direction == "long" //checking if line is liquidated
if getA.line_finished == false and
(_killonlowhigh ?
(low < f_calculateLeverage(getA_leverage, getA_maintainance, getA_price, getA_line_direction)):
(close < f_calculateLeverage(getA_leverage, getA_maintainance, getA_price, getA_line_direction)))
getA.line_finished := true
getA.stoptime := time
array.set(_Liqui_Line, i, getA)
else if getA.line_finished == false //no: prolong the line one more bar
getA.stoptime := time
array.set(_Liqui_Line, i, getA)
if getA_line_direction == "short" //checking if line is liquidated
if getA.line_finished == false and
(_killonlowhigh ?
(high > f_calculateLeverage(getA_leverage, getA_maintainance, getA_price, getA_line_direction)):
(close > f_calculateLeverage(getA_leverage, getA_maintainance, getA_price, getA_line_direction)))
getA.line_finished := true
getA.stoptime := time
array.set(_Liqui_Line, i, getA)
else if getA.line_finished == false //no: prolong the line one more bar
getA.stoptime := time
array.set(_Liqui_Line, i, getA)
//Check if killed line is to short for drawing, when yes remove it from the array
//this does repaint, but it will give bigger relevant history
if _minlength != -1 //dont waste time on gets if not relevant
if getA_line_finished == true and
((getA.stoptime - getA.creationtime) / _timeperbar) <= _minlength
array.remove(_Liqui_Line, i)
_Liqui_Line
export f_liqline_draw(Liquidationline [] _Liqui_Line, bool _priceorliq) =>
//The function f_drawfield takes an array of Liquidationline objects as input and uses the elements
//in the array to draw lines on a chart. The line properties such as color, style, and thickness are
//taken from the Liquidationline object and the line start and end points are calculated based on the
//creationtime, stoptime, price, leverage, and maintainance values in the Liquidationline object.
//The f_calculateLeverage function is called to help in calculating the line endpoints.
var string getA_line_direction = na
var float getA_price = na
var float getA_leverage = na
var float getA_maintainance = na
if (barstate.isrealtime or barstate.islast) and array.size(_Liqui_Line) > 0
if array.size(_Liqui_Line) > 0
for i = 0 to array.size(_Liqui_Line)-1
getA = array.get(_Liqui_Line, i)
getA_line_direction := getA.line_direction
getA_price := getA.price
getA_leverage := getA.leverage
getA_maintainance := getA.maintainance
line.new(
x1 = getA.creationtime ,
y1 = _priceorliq ? getA_price : f_calculateLeverage(getA_leverage, getA_maintainance, getA_price, getA_line_direction) ,
x2 = getA.stoptime ,
y2 = _priceorliq ? getA_price : f_calculateLeverage(getA_leverage, getA_maintainance, getA_price, getA_line_direction) ,
xloc = xloc.bar_time ,
extend = extend.none ,
color = getA.line_color ,
style = getA.line_style ,
width = getA.line_thickness
)
export f_liqline_add(Liquidationline [] _Liqui_Line, Liquidationline linetoadd, int _limit = 250) =>
//This code is defining a function f_liqline_add which takes in parameters dir (direction), col (color), thickness, and
//_Liqui_Line (an array of Liquidationline). The function creates a new instance of Liquidationline class with properties
//such as creation time, stop time, price, leverage, and line color, thickness, style, direction.
//The new instance is then added to the beginning of the _Liqui_Line array.
//If the size of the _Liqui_Line array is greater than the limit, the last element of the array is popped.
//limit sets the maximum lines in the array, no linedelete as they will pop on maximum themself
array.unshift(_Liqui_Line, linetoadd)
if array.size(_Liqui_Line) > _limit
array.pop(_Liqui_Line)
_Liqui_Line
////////////////// Indicator implementation sample
////////////////// Indicator implementation sample
////////////////// Indicator implementation sample
float maintainance = input.float(50, "Exchange margin maintainance %", minval=0, maxval=100 ,group='leverage',step = 1)
float f_leverage = input.float(25, "leverage", minval=0, maxval=100 ,group='leverage',step = 1)
bool priceorliq = input.bool(false, "Position or Liq", group='leverage')
col_long = input(color.rgb(76, 175, 79, 50))
col_short = input(color.rgb(255, 82, 82, 50))
int thinkness = input.int(1,"Thickness of lines", minval = -1)
bool killonlowhigh = input.bool(true, "Kill on LOW/HIGH", tooltip = "how is a relevant liquidation handled, by high/low or by the close value")
int maximumlines = input.int(25,"Maximum ammount of lines", tooltip = "if u convert this script to a indicator set max_line_count to 500 and this variable here to 250")
int minimumlength = input.int(10,"Minimum Length of liquidated lines", minval = -1, tooltip = "set this parameter to disable the small line cleanup, as longer the minimum length as more historic lines will remain")
float factor = input.float(1.03,"minimum shrink/raise of the close for new line draw",step = 0.01, minval = 1.0, group='Indicator settings')
string mtf_lvl = input.timeframe("", title="Custom TF",group='Indicator settings')
bool Show_L1 = input.bool(false, "Show L1 Bollingers",group='Indicator settings')
bool Show_L2 = input.bool(true, "Show L2 Bollingers",group='Indicator settings')
bool Show_L3 = input.bool(true, "Show L3 Bollingers",group='Indicator settings')
var bool LOCK = false
var float lastprice = na
var Liquidationline[] Liqui_Line_L = array.new <Liquidationline>()
var Liquidationline[] Liqui_Line_S = array.new <Liquidationline>()
var float timeperbar = 0.0000001
set_l = Liquidationline.new(
creationtime= time,
stoptime = time,
price= close,
leverage= f_leverage,
maintainance= maintainance,
line_active= true,
line_color= color.rgb(33, 191, 67),
line_thickness= 1,
line_style= line.style_solid,
line_direction= "long",
line_finished= false,
text_active= true,
text_size= size.normal,
text_color= color.white
)
set_s = Liquidationline.new(
creationtime= time,
stoptime = time,
price= close,
leverage= f_leverage,
maintainance= maintainance,
line_active= true,
line_color= color.rgb(191, 33, 33),
line_thickness= 1,
line_style= line.style_solid,
line_direction= "short",
line_finished= false,
text_active= true,
text_size= size.normal,
text_color= color.white
)
//run the timeperbar only as long till relevant data is aviable ( 100 bars to get the value, incl. 100 bars reserve)
if bar_index < 200
timeperbar := f_getbartime()
//this blocks recurring repositions at the same privelevel
if close > lastprice * factor or close < lastprice / factor
LOCK := false
[a1,b1,c1] = request.security(syminfo.tickerid,mtf_lvl,ta.bb(close,20,1), barmerge.gaps_off, barmerge.lookahead_off)
[a2,b2,c2] = request.security(syminfo.tickerid,mtf_lvl,ta.bb(close,20,2), barmerge.gaps_off, barmerge.lookahead_off)
[a3,b3,c3] = request.security(syminfo.tickerid,mtf_lvl,ta.bb(close,20,3), barmerge.gaps_off, barmerge.lookahead_off)
//using bollingerbands to create some signals, you can enter here whatever you want signal like rsi, macdcross,....
if ((Show_L1? ta.crossunder(close,c1) or ta.crossover(close,a1) :false) or
(Show_L2? ta.crossunder(close,c2) or ta.crossover(close,a2) :false) or
(Show_L3? ta.crossunder(close,c3) or ta.crossover(close,a3) :false)) and LOCK == false
LOCK := true
lastprice := close
f_liqline_add(_Liqui_Line = Liqui_Line_L, linetoadd = set_l,_limit = maximumlines)
f_liqline_add(_Liqui_Line = Liqui_Line_S, linetoadd = set_s,_limit = maximumlines)
//drawing
f_liqline_draw(_Liqui_Line = Liqui_Line_L, _priceorliq = priceorliq)
f_liqline_draw(_Liqui_Line = Liqui_Line_S, _priceorliq = priceorliq)
//prolonging lines, liquidations and cleaning up the short lines smaller minimumlength
f_liqline_update(_Liqui_Line = Liqui_Line_L, _killonlowhigh = killonlowhigh, _minlength = minimumlength, _timeperbar = timeperbar)
f_liqline_update(_Liqui_Line = Liqui_Line_S, _killonlowhigh = killonlowhigh, _minlength = minimumlength, _timeperbar = timeperbar)
|
Position | https://www.tradingview.com/script/dthThnxt-Position/ | Electrified | https://www.tradingview.com/u/Electrified/ | 52 | 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/
// © Electrified
//@version=5
// @description Allows for simulating trades within an indicator.
library("Position", overlay = true)
//////////////////////////////////////////////////
// @type Represents a single trade.
// @field size Size of the trade in units.
// @field price Price of the trade in currency.
// @field value Total value of the trade in currency units.
// @field time Timestamp of the trade.
export type Trade
float size
float price
float value
int time
//////////////////////////////////////////////////
// @type Represents a single position.
// @field size The size of the position.
// @field price Average price of the position in currency.
// @field value Total value of the position in currency units.
// @field start Timestamp of the first trade that opened the position.
// @field net Realized gains and losses of the position in currency units.
// @field history Array of trades that make up the position.
export type Position
float size
float price
float value
int start
float net
Trade[] history
//////////////////////////////////////////////////
// @type The state of a position in one direction
// @field size The size of the position
// @field change The change in size
// @field holding Indicates whether a position is currently being held
// @field increased Indicates whether the position has increased
// @field decreased Indicates whether the position has decreased
export type DirectionState
float size
float change
bool holding
bool increased
bool decreased
//////////////////////////////////////////////////
// @type The bi-directional state of a position
// @field holding Indicates whether a position is currently being held
// @field long The state of the long position
// @field short The state of the short position
export type State
float size
float change
bool holding
DirectionState long
DirectionState short
float price
newDirState(series float size) =>
change = ta.change(math.abs(size))
DirectionState.new(size, change, size != 0, change > 0, change < 0)
validate(float size, float price, int time) =>
if na(size)
runtime.error("size cannot be NA")
if na(price)
runtime.error("price cannot be NA")
if na(time)
runtime.error("time cannot be NA")
//////////////////////////////////////////////////
// @function Creates a new trade object.
// @param size The size of the trade (number of shares or contracts).
// @param price The price at which the trade took place.
// @param timestamp The timestamp of the trade. Defaults to the current time.
// @returns A new trade object.
export newTrade(float size, float price = close, int timestamp = time) =>
validate(size, price, time)
Trade.new(size, price, size * price, timestamp)
//////////////////////////////////////////////////
// @function Starts a new position.
// @param size The size of the position (number of shares or contracts).
// @param price The price at which the position was started.
// @param timestamp The timestamp of the start of the position. Defaults to the current time.
// @returns A new position object.
export start(float size, float price = close, int timestamp = time) =>
validate(size, price, time)
history = array.new<Trade>(1, newTrade(size, price, timestamp))
Position.new(size, price, size * price, timestamp, 0, history)
//////////////////////////////////////////////////
// @function Starts a new (blank) position with no trades.
// @returns A new position object.
export start() =>
Position.new(0, na, 0, na, 0, array.new<Trade>())
//////////////////////////////////////////////////
// @function Returns the current state of the position.
// @param posSize the current size of the position.
export state(float posSize) =>
size = nz(posSize)
change = ta.change(size)
sizeLong = math.min(size, 0)
sizeShort = math.max(size, 0)
long = newDirState(sizeLong)
short = newDirState(sizeShort)
State.new(size, change, size != 0, long, short)
//////////////////////////////////////////////////
// @function Returns the current state of the position.
// @param pos The position to read the size from.
export method state(Position pos) =>
size = na(pos) ? na : pos.size
state(size)
//////////////////////////////////////////////////
// @function Modifies an existing position.
// @param pos The position to be modified.
// @param size The size of the trade (number of shares or contracts).
// @param price The price at which the trade took place.
// @param timestamp The timestamp of the trade. Defaults to the current time.
// @returns The result of the trade. (The state of the position.)
export method trade(Position pos, float size, float price = close, int timestamp = time) =>
if na(pos)
runtime.error("cannot modify an NA position")
validate(size, price, time)
trade = newTrade(size, price, timestamp)
array.push(pos.history, trade)
newSize = pos.size + size
// Determine if we are increasing or decresing our position as increasing affects the position price and decreasing affects the net.
[shrink, flip, longChange, shortChange] = if pos.size > 0 and size < 0
s = math.min(pos.size, -size)
f = math.min(newSize, 0)
[s, f, s, f]
else if pos.size < 0 and size > 0
s = math.max(pos.size, -size)
f = math.max(newSize, 0)
[s, f, f, s]
else // Expand only?
long = size > 0 ? size : 0
short = size < 0 ? size : 0
[0, 0, long, short]
if shrink != 0
pos.net += shrink * (price - pos.price)
// Full exit?
if newSize == 0
pos.size := 0
pos.price := na
pos.value := 0
// Typical increase or decrease?
else if flip == 0
pos.size += size
pos.value += trade.value
if shrink == 0
pos.price := pos.value / pos.size
// Flipped from long to short or vice versa?
else
pos.size := flip
pos.price := price
pos.value := flip * price
State.new(newSize, size, newSize != 0,
DirectionState.new(newSize > 0 ? newSize : 0, longChange, newSize > 0, longChange > 0, longChange < 0),
DirectionState.new(newSize < 0 ? newSize : 0, shortChange, newSize < 0, shortChange < 0, shortChange > 0),
trade.price)
//////////////////////////////////////////////////
// @function Closes a position by trading the entire position size at a given price and timestamp.
// @param pos The position being closed.
// @param price The price at which the position is being closed.
// @param timestamp The timestamp of the trade, defaults to the current time.
// @returns The updated position after the trade.
export method exit(Position pos, float price = close, int timestamp = time) =>
if na(pos)
runtime.error("cannot modify an NA position")
if na(price)
runtime.error("price cannot be NA")
if na(time)
runtime.error("time cannot be NA")
trade(pos, -pos.size, price, timestamp)
//////////////////////////////////////////////////
// @function Calculates the unrealized gain or loss for a given position and price.
// @param pos The position for which to calculate unrealized gain/loss.
// @param price The current market price.
// @returns The calculated unrealized gain or loss.
export method unrealized(Position pos, float price = close) =>
if na(pos)
0.0
else if na(price)
runtime.error("price cannot be NA")
0.0
else
pos.size == 0 ? 0.0 : pos.size * (price - pos.price)
//////////////////////////////////////////////////
// @function Returns the number of shares held by a position.
// @param pos The position for which to read the size. A value of NA will return zero.
export method size(Position pos) =>
na(pos) ? 0.0 : pos.size
//////////////////////////////////////////////////
// @function Returns true if the position has shares.
// @param pos The position for which to read the size. A value of NA will return false.
export method isActive(Position pos) =>
na(pos) ? false : nz(pos.size) != 0
//////////////////////////////////////////////////
// @function Creates a lablel if a trade was made.
// @param pos The position.
// @param ts The state of the position or result of the trade to generate a label from.
// @returns The label that was generated or na if none.
export addLabel(Position pos, State ts, string details = na) =>
label lbl = na
if na(pos) or na(ts)
lbl
else
if ts.change > 0
s = array.new_string()
s.push(str.format("+{0,number}", ts.change))
if ts.short.change != 0
s.push(ts.short.size==0 ? "S:0" : str.format("S:{0, number}", -ts.short.size))
if ts.long.change != 0
s.push(str.format("\:{0, number}", ts.long.size))
lbl := label.new(time, low, s.join("\n"), xloc.bar_time, yloc.price, #006600, label.style_label_up, color.white)
else if ts.change < 0
s = array.new_string()
s.push(str.format("{0,number}", ts.change))
if ts.long.change != 0
s.push(str.format("L:{0, number}", ts.long.size))
if ts.short.change != 0
s.push(ts.short.size==0 ? "S:0" : str.format("S:{0, number}", -ts.short.size))
lbl := label.new(time, high, s.join("\n"), xloc.bar_time, yloc.price, #660000, label.style_label_down, color.white)
tooltip = array.new_string()
tooltip.push(str.format(ts.change > 0 ? "+{0,number} @ {1,number,currency}" : "{0,number} @ {1,number,currency}", ts.change, ts.price))
if ts.price != pos.price
tooltip.push(str.format("Average: {0,number,currency}", pos.price))
if pos.net != 0
tooltip.push(str.format("Realized: {0,number,currency}", pos.net))
if not na(details)
tooltip.push(str.format("\n{0}", details))
label.set_tooltip(lbl, tooltip.join("\n"))
lbl
//////////////////////////////////////////////////
//// Demo ////////////////////////////////////////
//////////////////////////////////////////////////
var pos = start()
posState = state(pos)
tradeSize = posState.holding ? 2 : 1
fast = ta.wma(hlc3, 100)
slow = ta.wma(hlc3, 150)
longSignal = ta.crossover(fast, slow)
shortSignal = ta.crossunder(fast, slow)
plot(pos.size(), "Size", display = display.status_line)
State ts = na
if longSignal
ts := pos.trade(+tradeSize)
else if shortSignal
ts := pos.trade(-tradeSize)
addLabel(pos, ts) |
Webby % Off 52 Week | https://www.tradingview.com/script/i03UcrD5-Webby-Off-52-Week/ | Amphibiantrading | https://www.tradingview.com/u/Amphibiantrading/ | 209 | 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/
// © Amphibiantrading
//@version=5
indicator("Webby % Off 52 Week", shorttitle = '% Off High')
//input
lineCol = input.color(color.blue, '% Off Line Color')
z1Col = input.color(color.green, 'Zone 1 (0-8%) Background Color')
z2Col = input.color(color.yellow, 'Zone 2 (8-15%) Background Color')
z3Col = input.color(color.red, 'Zone 3 (16-25%) Background Color')
off = input.bool(true, 'Cut off at 25%', tooltip = 'If selected anything more than 25% off the high will be drawn at 25% to keep the scaling and plot in the zones')
//caluclations
yearhigh = ta.highest(high, 251)
distAway = ((close-yearhigh) / yearhigh) * 100
if distAway < -25 and off
distAway := -25
//plots
plot(distAway, '% Off High', lineCol)
//hlines for fill zones
z1Top = hline(0, 'Z1', color.new(color.green,100))
z1Btm = hline(-8.0, 'Z1', color.new(color.green,100))
z2Top = hline(-8.1, 'Z2', color.new(color.yellow,100))
z2Btm = hline(-15.0, 'Z2', color.new(color.yellow,100))
z3Top = hline(-15.1, 'Z3', color.new(color.red,100))
z3Btm = hline(-25.0, 'Z3', color.new(color.red,100))
//fill the zones
fill(z1Top, z1Btm, z1Col)
fill(z2Top, z2Btm, z2Col)
fill(z3Top, z3Btm, z3Col)
|
Bar Dependent Moving Average | https://www.tradingview.com/script/DH7fVWZn-Bar-Dependent-Moving-Average/ | UnknownUnicorn56349756 | https://www.tradingview.com/u/UnknownUnicorn56349756/ | 8 | 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/
// © Mahan_Mahmoudi
//@version=5
indicator("BDMA 2.0",max_bars_back = 5000,format=format.price,overlay=true)
// Security BDMA Counter Locks
yearly = request.security(syminfo.tickerid,"1M",close)
monthly = request.security(syminfo.tickerid,"1W",close)
daily = request.security(syminfo.tickerid,"1D",close)
hourly = request.security(syminfo.tickerid,"60",close)
custom = input.int(200,title=" Custom BDMA Period",minval=2)
var int yearlycounter = 0
var int monthlycounter = 0
var int dailycounter = 0
var int hourlycounter = 0
var int fibcounter = 4182
var int fib4182 = 0
var bool yearlylock = false
var bool monthlylock= false
if yearly[1]<yearly or yearly[1]>yearly and monthlylock == false
yearlycounter := yearlycounter + 1
if yearlycounter > 4999
monthlylock := true
yearlycounter := 5000
if monthly[1]<monthly or monthly[1]>monthly and monthlylock == true
monthlycounter := monthlycounter + 1
if monthlycounter > 4999
monthlycounter := 4999
if yearlycounter < 4182 and monthlylock == false
yearlycounter := 4182
if monthlycounter < 4182 and monthlylock == true
monthlycounter := 4182
if yearlycounter < fibcounter
fib4182 := fibcounter
fibmov1 = monthlylock ? ta.sma(yearly,fibcounter/1) :ta.sma(monthly,fibcounter/1)
fibmov2 = monthlylock ? ta.sma(yearly,fibcounter/2) :ta.sma(monthly,fibcounter/2)
fibmov3 = monthlylock ? ta.sma(yearly,fibcounter/3) :ta.sma(monthly,fibcounter/3)
fibmov5 = monthlylock ? ta.sma(yearly,fibcounter/5) :ta.sma(monthly,fibcounter/5)
fibmov8 = monthlylock ? ta.sma(yearly,fibcounter/8) :ta.sma(monthly,fibcounter/8)
fibmov13 = monthlylock ? ta.sma(yearly,fibcounter/13) :ta.sma(monthly,fibcounter/13)
fibmov21 = monthlylock ? ta.sma(yearly,fibcounter/21) :ta.sma(monthly,fibcounter/21)
fibmov34 = monthlylock ? ta.sma(yearly,fibcounter/34) :ta.sma(monthly,fibcounter/34)
fibmov55 = monthlylock ? ta.sma(yearly,fibcounter/55) :ta.sma(monthly,fibcounter/55)
fibmov89 = monthlylock ? ta.sma(yearly,fibcounter/89) :ta.sma(monthly,fibcounter/89)
fibmov144 = monthlylock ? ta.sma(yearly,fibcounter/144) :ta.sma(monthly,fibcounter/144)
fibmov233 = monthlylock ? ta.sma(yearly,fibcounter/233) :ta.sma(monthly,fibcounter/233)
fibmov377 = monthlylock ? ta.sma(yearly,fibcounter/377) :ta.sma(monthly,fibcounter/377)
fibmov610 = monthlylock ? ta.sma(yearly,fibcounter/610) :ta.sma(monthly,fibcounter/610)
fibmov987 = monthlylock ? ta.sma(yearly,fibcounter/987) :ta.sma(monthly,fibcounter/987)
fibmov1597 = monthlylock ? ta.sma(yearly,fibcounter/1597) :ta.sma(monthly,fibcounter/1597)
fibmov2584 = monthlylock ? ta.sma(yearly,fibcounter/2584) :ta.sma(monthly,fibcounter/2584)
fibmov4181 = monthlylock ? ta.sma(yearly,fibcounter/4181) :ta.sma(monthly,fibcounter/4181)
fma = (fibmov1 + fibmov2 + fibmov3 + fibmov5 + fibmov8 + fibmov13 + fibmov21 + fibmov34 + fibmov55 + fibmov89 + fibmov144 + fibmov233 + fibmov377 + fibmov610 + fibmov987 + fibmov1597 + fibmov2584 + fibmov4181) / 18
plot(fibmov2,title="Relative Fibonacci 4182 2",color=color.yellow, linewidth= 3, style = plot.style_line)
plot(fibmov3,title="Relative Fibonacci 4182 3",color=color.green , linewidth= 2, style = plot.style_line)
plot(fibmov5,title="Relative Fibonacci 4182 5",color=color.black , linewidth= 2 , style = plot.style_line)
plot(fibmov8,title="Relative Fibonacci 4182 8",color=color.red , linewidth= 2 , style = plot.style_line)
plot(fibmov13,title="Relative Fibonacci 4182 13",color=color.navy , linewidth= 2 , style = plot.style_line)
plot(fibmov21,title="Relative Fibonacci 4182 21",color=color.gray , linewidth= 1 , style = plot.style_line)
plot(fibmov34,title="Relative Fibonacci 4182 34",color=color.fuchsia , linewidth= 1 , style = plot.style_line)
plot(fibmov55,title="Relative Fibonacci 4182 55",color=color.maroon , linewidth= 1 , style = plot.style_line)
plot(fibmov89,title="Relative Fibonacci 4182 89",color=color.lime , linewidth= 1 , style = plot.style_line)
plot(fibmov144,title="Relative Fibonacci 4182 144",color=color.aqua , linewidth= 1 , style = plot.style_line)
plot(fibmov233,title="Relative Fibonacci 4182 233",color=color.blue , linewidth= 1 , style = plot.style_line)
plot(fibmov377,title="Relative Fibonacci 4182 377",color=color.silver , linewidth= 1 , style = plot.style_line)
plot(fma,title="Fibonacci Moving Average",color=color.white,linewidth=4)
plot(monthlylock ? ta.sma(yearly,monthlycounter/custom) :ta.sma(monthly,yearlycounter/custom),title=" Custom BDMA Average",color=color.rgb(0, 255, 251))
|
FrizLabz_Time_Utility_Methods | https://www.tradingview.com/script/uqHMnQ7l-FrizLabz-Time-Utility-Methods/ | FFriZz | https://www.tradingview.com/u/FFriZz/ | 14 | 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
//@version=5
library("FrizLabz_Time_Utility_Methods")
// @description [FrizLabz] Time & Utility - Methods some simple methods for time to bar_index conversion and vice versa
// also a Line Label Box function
// @function UTC helper function this adds the + to the positive utc times, add "UTC" to the string
// and can be used in the timezone arg of for format_time()
// @param utc (int) +/- utc offset
// @returns string string to be added to the timezone paramater for utc timezone usage
export UTC_helper(int utc=-6) =>
//TODO : Exapand on this and make it cover all timezone options
out = ''
if utc >= 0
out := 'UTC+'+str.tostring(utc)
if utc <= 0
out := 'UTC'+str.tostring(utc)
out
// @function from a time to index
// @param bar_amount (int) default - 1)
// @returns int bar_time
export method bar_time(int bar_amount = 1)=>
bar_time = (time_close - time) * bar_amount
bar_time
// @function from time to bar_index
// @param _time (int)
// @returns int time_to_index bar_index that corresponds to time provided
export method time_to_index(int _time) =>
switch
_time < 1000000 => runtime.error("_time is not Unix time\nFor index to time use method index_to_time()")
time_diff_index = (time-_time)/bar_time()
time_to_index = bar_index - time_diff_index
time_to_index
// @function from a time quanity to bar quanity for use with [historical ref].
// @param _time (int)
// @returns int bars_back yeilds the amount of bars from current bar to reach _time provided
export method time_to_bars_back(int _time) =>
timediff = time - _time
bars_back = timediff/bar_time()
bars_back
// @function from bars_back to time
// @param _time (int)
// @returns int using same logic as [historical ref.] this will return the
// time of the bar = to the bar that corresponds to [x] bars_back
export method bars_back_to_time(int bars_back) => time - bar_time(bars_back)
// @function bar_index to UNIX time
// @param index (int)
// @returns int time time in unix that corrresponds to the bar_index
export method index_to_time(int index) =>
switch
index > 1000000 => runtime.error("index = Unix time [detected]\nFor time to index use method time_to_index()")
index_diff = bar_index - index
time_of_index = index_diff.bars_back_to_time()
time_of_index
// @function method to use with a time or bar_index variable that will detect if it is an index or unix time
// and convert it to a printable string
// @param time_or_index (int) required) time in unix or bar_index
// @param timezone (int) required) utc offset to be appled to output
// @param format (string) default - "yyyy-MM-dd'T'HH:mm:ssZ") the format for the time, provided string is default
// one from str.format_time()
// @returns string time formatted string
export method to_utc(int time_or_index,int timezone=-6,string format = na) =>
_format = na(format) ? "yyyy-MM-dd'T'HH:mm:ssZ" : format
check = time_or_index
if time_or_index < 1000000
check := time_or_index.index_to_time()
out = str.format_time(check,format,UTC_helper(timezone))
|
Standardized MACD Heikin-Ashi Transformed | https://www.tradingview.com/script/g5qN1YDp-Standardized-MACD-Heikin-Ashi-Transformed/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 1,105 | 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/
// © QuantiLuxe
//@version=5
indicator("Standardized MACD Heikin-Ashi Transformed", "[Ʌ] - 𝗦𝘁. 𝗠𝗔𝗖𝗗 𝗛-𝗔", false)
type bar
float o = na
float h = na
float l = na
float c = na
method src(bar b, simple string src) =>
float x = switch src
'open' => b.o
'high' => b.h
'low' => b.l
'close' => b.c
'oc2' => math.avg(b.o, b.c )
'hl2' => math.avg(b.h, b.l )
'hlc3' => math.avg(b.h, b.l, b.c )
'ohlc4' => math.avg(b.o, b.h, b.l, b.c)
'hlcc4' => math.avg(b.h, b.l, b.c, b.c)
x
method ha(bar b, simple bool p = true) =>
var bar x = bar.new( )
x.c := b .src('ohlc4')
x := bar.new(
na(x.o[1]) ?
b.src('oc2') : nz(x.src('oc2')[1]),
math.max(b.h, math.max(x.o, x.c)) ,
math.min(b.l, math.min(x.o, x.c)) ,
x.c )
p ? x : b
f_macd(src, fast, slow) =>
(ta.ema(src, fast) - ta.ema(src, slow)) / (ta.ema(high - low, slow)) * 100
var string gm = "MACD Settings", var string gu = "UI Options"
src = input.source(close , "Source" , group = gm)
fast = input.int (12 , "Fast Length" , group = gm)
slow = input.int (26 , "Slow Length" , group = gm)
sigb = input.bool (true , "Signal" , inline = '1', group = gm)
sigs = input.string('close' , "Source" , ['open', 'high', 'low', 'close', 'hl2', 'hlc3', 'ohlc4', 'hlcc4'], inline = '1', group = gm)
sigl = input.int (9 , "Length" , inline = '1', group = gm)
mode = input.string('Hybrid', "Display Mode" , ['Hybrid', 'MACD', 'Histogram'], group = gu)
revs = input.bool (true , "" , inline = '0', group = gu)
revt = input.int (100 , "Reversion Threshold", [100, 150], inline = '0', group = gu)
colb = input.string('None' , "Bar Coloring" , ['None', 'MidLine', 'Candles', 'Sig Cross', 'Extremities', 'Reversions'], group = gu)
hol = input.bool (true , "Hollow Candles" , group = gu)
float macd = f_macd (src , fast, slow )
bar hm = bar.new(
macd[1] ,
math.max(macd, macd[1]) ,
math.min(macd, macd[1]) ,
macd ).ha()
float sig = ta .ema(hm.src(sigs), sigl)
float hist = macd - sig
var color colup = #00bcd4
var color coldn = #fc1f1f
var color colsig = chart.fg_color
color h_col = hist > 0 ?
(hist > hist[1] ? #8ac3f5a1 : #74a5cfa1) :
(hist > hist[1] ? #ffa7b6a1 : #d88b98a1)
color haColor = switch
hm.c > hm.o => colup
hm.c < hm.o => coldn
hline(0, "Mid Line", chart.fg_color, hline.style_solid)
min = hline(mode != 'Histogram' ? -200 : -100, display = display.none)
ll = hline(mode != 'Histogram' ? -150 : -75 , display = display.none)
hl = hline(mode != 'Histogram' ? -100 : -50 , display = display.none)
max = hline(mode != 'Histogram' ? 200 : 100 , display = display.none)
hh = hline(mode != 'Histogram' ? 150 : 75 , display = display.none)
lh = hline(mode != 'Histogram' ? 100 : 50 , display = display.none)
fill(lh, hh , #fc1f1f1c)
fill(hh, max, #fc1f1f38)
fill(ll, hl , #00bbd41a)
fill(ll, min, #00bbd436)
plot(mode != 'Histogram' and sigb ? sig : na, "𝗦𝗶𝗴𝗻𝗮𝗹", colsig )
plot(mode != 'MACD' ? hist : na, "𝗛" , h_col , 1, plot.style_columns)
plotcandle(mode != 'Histogram' ? hm.o : na,
mode != 'Histogram' ? hm.h : na,
mode != 'Histogram' ? hm.l : na,
mode != 'Histogram' ? hm.c : na,
"𝗠𝗔𝗖𝗗", hol ? hm.c > hm.o ? na : haColor : haColor, haColor, bordercolor = haColor)
plotshape(mode != 'Histogram' ? revs ? hm.h > revt and hm.c < hm.o and not (hm.c[1] < hm.o[1]) ? hm.h + 40 : na : na : na, "OB", shape.triangledown, location.absolute, coldn, size = size.tiny)
plotshape(mode != 'Histogram' ? revs ? hm.l < -revt and hm.c > hm.o and not (hm.c[1] > hm.o[1]) ? hm.l - 40 : na : na : na, "OS", shape.triangleup , location.absolute, colup, size = size.tiny)
color col = switch colb
'None' => na
'MidLine' => macd > 0 ? colup : coldn
'Candles' => hm.c > hm.o ? colup : coldn
'Sig Cross' => sig > hm.c ? coldn : colup
'Extremities' => macd > revt ? coldn : macd < -revt ? colup : #b3b3b3c2
'Reversions' => macd > revt and macd < macd[1] and not (macd[1] < macd[2]) ? coldn : macd < -revt and macd > macd[1] and not (macd[1] > macd[2]) ? colup : #b3b3b3c2
barcolor(col)
//Source Construction For Indicator\Strategy Exports
plot(hm.o , "open" , editable = false, display = display.none)
plot(hm.h , "high" , editable = false, display = display.none)
plot(hm.l , "low" , editable = false, display = display.none)
plot(hm.c , "close", editable = false, display = display.none)
plot(hm.src('hl2' ), "hl2" , editable = false, display = display.none)
plot(hm.src('hlc3' ), "hlc3" , editable = false, display = display.none)
plot(hm.src('ohlc4'), "ohlc4", editable = false, display = display.none)
plot(hm.src('hlcc4'), "hlcc4", editable = false, display = display.none) |
Webby's RS Line | https://www.tradingview.com/script/4qgg7f1C-Webby-s-RS-Line/ | Amphibiantrading | https://www.tradingview.com/u/Amphibiantrading/ | 216 | 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/
// © Amphibiantrading
//@version=5
indicator(title = 'Webby\'s RS Line')
// inputs
index = input.symbol(title='Index to Compare', defval='SPX')
upColor = input.color(color.blue, 'RS Line Above 21 Color')
downColor = input.color(color.red, 'RS Line Below 21 Color')
emaWidth = input.int(title='EMA\'s Line Width', defval=1, minval=1, maxval=5)
//calculations
spx = request.security(index, timeframe.period, low)
rs = (low / spx) * 100
ema = ta.ema(rs,21)
dist = ((rs - ema) / rs) * 100
ema1 = ta.ema(dist, 3)
ema2 = ta.ema(dist, 13)
//colors
histCol = dist > 0 ? upColor : downColor
ema1Col = ema1 > ema1[1] ? color.lime : color.maroon
ema2Col = ema2 > ema2[1] ? color.green : color.red
//plots
plot(dist, 'Distance', color = histCol, style = plot.style_histogram, linewidth = 2)
plot(ema1, color = ema1Col, linewidth = emaWidth)
plot(ema2, color = ema2Col, linewidth = emaWidth)
|
RSI Divergence Screener by zdmre | https://www.tradingview.com/script/ob1uM5ZM-RSI-Divergence-Screener-by-zdmre/ | zdmre | https://www.tradingview.com/u/zdmre/ | 128 | 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/
// © zdmre
//@version=5
indicator("RSI Divergence Screener by zdmre", overlay=false, max_bars_back = 500)
//Divergence
inputgroup = "Divergence"
srcDIV = close
timeframe = timeframe.period
shdiv = input.bool(defval = true, title = "Show Divergences", group=inputgroup)
shdate = input.bool(defval = false, title = "Show Dates", group=inputgroup)
colorwg_data = input.string('Red/Green', 'Line Color ',
options=['Red/Green', 'White', 'Yellow', 'Blue'],
group = inputgroup, inline='0')
lwidth_data = input.int(2,'Line Width ',
group = inputgroup, minval=0,maxval=4)
//Table Position
in_table_pos = input.string(title="Position ", defval= "Top Right",
options =["Top Right", "Middle Right", "Bottom Right",
"Top Center", "Middle Center", "Bottom Center",
"Top Left", "Middle Left", "Bottom Left"],
group= "Table Styling", inline= "1")
//Table Size
in_table_size = input.string(title="Size ", defval="Small",
options=["Auto", "Huge", "Large", "Normal", "Small", "Tiny"],
group= "Table Styling" , inline= "2")
// Color
column_title_bgcol = input.color(color.gray , title="Title Color ", group = "Table Styling" , inline="3")
cell_bgcol = input.color(#aaaaaa , title="Cell Color ", group = "Table Styling" , inline="4")
cell_txtcol = input.color(color.black , title="Text Color ", group = "Table Styling" , inline="5")
bull_color = input.color(color.green, title = "Gradient Colors ", group = "Table Styling", inline = "6")
bear_color = input.color(color.red, title = "", group = "Table Styling", inline = "6")
//Sorting
table_sort_by = input.string(title="Sort by ", defval="None",
options =["None", "Symbol"],
group = "Table Sorting", inline="7")
table_sort_dir = input.string(title="Direction ", defval="Ascending",
options =["Ascending", "Descending"],
group = "Table Sorting", inline="8")
//RSI
len_data = 14
up_data = ta.rma(math.max(ta.change(close), 0), len_data)
down_data = ta.rma(-math.min(ta.change(close), 0), len_data)
rsi_data = down_data == 0 ? 100 : up_data == 0 ? 0 : 100 - 100 / (1 + up_data / down_data)
plot(rsi_data, 'RSI', color=color.new(#7E57C2, 0))
//Chart Vis
lengthdiv_data = 21
lengthright_data = 0
lengthwg_data = lengthright_data
length2wg_data = lengthright_data
upwg_data = ta.pivothigh(rsi_data, lengthdiv_data, lengthright_data)
dnwg_data = ta.pivotlow(rsi_data, lengthdiv_data, lengthright_data)
upchart_data = ta.pivothigh(close, lengthdiv_data, lengthright_data)
dnchart_data = ta.pivotlow(close, lengthdiv_data, lengthright_data)
astart_data = 1
aend_data = 0
bstart_data = 1
bend_data = 0
nw_data = bar_index
a1_data = ta.valuewhen(not na(upwg_data), nw_data, astart_data)
b1_data = ta.valuewhen(not na(dnwg_data), nw_data, bstart_data)
a2_data = ta.valuewhen(not na(upwg_data), nw_data, aend_data)
b2_data = ta.valuewhen(not na(dnwg_data), nw_data, bend_data)
ach1_data = ta.valuewhen(not na(upchart_data), nw_data, astart_data)
bch1_data = ta.valuewhen(not na(dnchart_data), nw_data, bstart_data)
ach2_data = ta.valuewhen(not na(upchart_data), nw_data, aend_data)
bch2_data = ta.valuewhen(not na(dnchart_data), nw_data, bend_data)
//Colors Div
color1 = color.red
color2 = color.green
if colorwg_data == 'White'
color1 := color.white
color2 := color.white
color2
if colorwg_data == 'Yellow'
color1 := color.yellow
color2 := color.yellow
color2
if colorwg_data == 'Blue'
color1 := color.blue
color2 := color.blue
color2
if colorwg_data == 'Red/Green'
color1 := color.red
color2 := color.green
color2
//Divergence
div1_data = upwg_data[nw_data - a2_data] < upwg_data[nw_data - a1_data] and upchart_data[nw_data - ach2_data] > upchart_data[nw_data - ach1_data] and upchart_data > high[nw_data - ach1_data]
div2_data = dnwg_data[nw_data - b2_data] > dnwg_data[nw_data - b1_data] and dnchart_data[nw_data - bch2_data] < dnchart_data[nw_data - bch1_data] and dnchart_data < low[nw_data - bch1_data]
//Label
if div1_data and shdiv
line.new(nw_data[nw_data - a1_data + lengthwg_data], upwg_data[nw_data - a1_data], nw_data[nw_data - a2_data + lengthwg_data], upwg_data[nw_data - a2_data], extend=extend.none,color=color1, width=lwidth_data,style=line.style_dotted)
label1 = label.new(nw_data[nw_data - a2_data + lengthwg_data], 70 , text="Divergence\n|", style=label.style_label_down, color=color.new(color.red,100))
label.set_size(label1, size.small)
label.set_textcolor(label1, color.red)
if div2_data and shdiv
line.new(nw_data[nw_data - b1_data + length2wg_data], dnwg_data[nw_data - b1_data], nw_data[nw_data - b2_data + length2wg_data], dnwg_data[nw_data - b2_data], extend=extend.none, color=color2, width=lwidth_data, style=line.style_dotted)
label2 = label.new(nw_data[nw_data - b2_data + length2wg_data], 30, text="|\nDivergence", style=label.style_label_up, color=color.new(color.green,100))
label.set_size(label2, size.small)
label.set_textcolor(label2, color.green)
if div1_data and shdate
label1 = label.new(nw_data[nw_data - a2_data + lengthwg_data], 80 , text = str.format("{0,date, y\nMMM-d\n}", time[nw_data - a2_data + lengthwg_data]), style=label.style_label_down, color=color.new(color.red,100))
label.set_size(label1, size.small)
label.set_textcolor(label1, color.red)
if div2_data and shdate
label2 = label.new(nw_data[nw_data - b2_data + length2wg_data], 20 , text = str.format("{0,date, \ny\nMMM-d}", time[nw_data - b2_data + length2wg_data]), style=label.style_label_up, color=color.new(color.green,100))
label.set_size(label2, size.small)
label.set_textcolor(label2, color.green)
//SYMBOLs
u01 = input.bool(true, title = "", group = 'Symbols', inline = 's01')
u02 = input.bool(true, title = "", group = 'Symbols', inline = 's02')
u03 = input.bool(true, title = "", group = 'Symbols', inline = 's03')
u04 = input.bool(true, title = "", group = 'Symbols', inline = 's04')
u05 = input.bool(true, title = "", group = 'Symbols', inline = 's05')
u06 = input.bool(true, title = "", group = 'Symbols', inline = 's06')
u07 = input.bool(true, title = "", group = 'Symbols', inline = 's07')
u08 = input.bool(true, title = "", group = 'Symbols', inline = 's08')
u09 = input.bool(true, title = "", group = 'Symbols', inline = 's09')
u10 = input.bool(true, title = "", group = 'Symbols', inline = 's10')
u11 = input.bool(false, title = "", group = 'Symbols', inline = 's11')
u12 = input.bool(false, title = "", group = 'Symbols', inline = 's12')
u13 = input.bool(false, title = "", group = 'Symbols', inline = 's13')
u14 = input.bool(false, title = "", group = 'Symbols', inline = 's14')
u15 = input.bool(false, title = "", group = 'Symbols', inline = 's15')
u16 = input.bool(false, title = "", group = 'Symbols', inline = 's16')
u17 = input.bool(false, title = "", group = 'Symbols', inline = 's17')
u18 = input.bool(false, title = "", group = 'Symbols', inline = 's18')
u19 = input.bool(false, title = "", group = 'Symbols', inline = 's19')
u20 = input.bool(false, title = "", group = 'Symbols', inline = 's20')
// Symbols
s01 = input.symbol('BTCUSDT', group = 'Symbols', inline = 's01')
s02 = input.symbol('ETHUSDT', group = 'Symbols', inline = 's02')
s03 = input.symbol('BNBUSDT', group = 'Symbols', inline = 's03')
s04 = input.symbol('XRPUSDT', group = 'Symbols', inline = 's04')
s05 = input.symbol('ADAUSDT', group = 'Symbols', inline = 's05')
s06 = input.symbol('DOGEUSDT', group = 'Symbols', inline = 's06')
s07 = input.symbol('LTCUSDT', group = 'Symbols', inline = 's07')
s08 = input.symbol('SOLUSDT', group = 'Symbols', inline = 's08')
s09 = input.symbol('TRXUSDT', group = 'Symbols', inline = 's09')
s10 = input.symbol('DOTUSDT', group = 'Symbols', inline = 's10')
s11 = input.symbol('MATICUSDT', group = 'Symbols', inline = 's11')
s12 = input.symbol('BCHUSDT', group = 'Symbols', inline = 's12')
s13 = input.symbol('TONUSDT', group = 'Symbols', inline = 's13')
s14 = input.symbol('AVAXUSDT', group = 'Symbols', inline = 's14')
s15 = input.symbol('SHIBUSDT', group = 'Symbols', inline = 's15')
s16 = input.symbol('LINKUSDT', group = 'Symbols', inline = 's16')
s17 = input.symbol('ATOMUSDT', group = 'Symbols', inline = 's17')
s18 = input.symbol('UNIUSDT', group = 'Symbols', inline = 's18')
s19 = input.symbol('XMRUSDT', group = 'Symbols', inline = 's19')
s20 = input.symbol('XLMUSDT', group = 'Symbols', inline = 's20')
//Calc
f_strLeftOf(_str, _of) =>
string[] _chars = str.split(_str, '')
int _len = array.size(_chars)
int _ofPos = array.indexof(_chars, _of)
string[] _substr = array.new_string(0)
if _ofPos > 0 and _ofPos <= _len - 1
_substr := array.slice(_chars, 0, _ofPos)
_substr
string _return = array.join(_substr, '')
_return
// Get only symbol
only_symbol(s) =>
array.get(str.split(s, ":"), 1)
// 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
// Get Table Size
table_size(s) =>
switch s
"Auto" => size.auto
"Huge" => size.huge
"Large" => size.large
"Normal" => size.normal
"Small" => size.small
=> size.tiny
screener_func(flag) =>
out_screener_func = array.new_string(5, string(na))
if flag
src = srcDIV
len = 14
up = ta.rma(math.max(ta.change(src), 0), len)
down = ta.rma(-math.min(ta.change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
lengthdiv = 21
lengthright = 0
lengthwg = lengthright
length2wg = lengthright
upwg = ta.pivothigh(rsi, lengthdiv, lengthright)
dnwg = ta.pivotlow(rsi, lengthdiv, lengthright)
upchart = ta.pivothigh(close, lengthdiv, lengthright)
dnchart = ta.pivotlow(close, lengthdiv, lengthright)
astart = 1
aend = 0
bstart = 1
bend = 0
nw = bar_index
a1 = ta.valuewhen(not na(upwg), nw, astart)
b1 = ta.valuewhen(not na(dnwg), nw, bstart)
a2 = ta.valuewhen(not na(upwg), nw, aend)
b2 = ta.valuewhen(not na(dnwg), nw, bend)
ach1 = ta.valuewhen(not na(upchart), nw, astart)
bch1 = ta.valuewhen(not na(dnchart), nw, bstart)
ach2 = ta.valuewhen(not na(upchart), nw, aend)
bch2 = ta.valuewhen(not na(dnchart), nw, bend)
//Div
div1 = upwg[nw - a2] < upwg[nw - a1] and upchart[nw - ach2] > upchart[nw - ach1] and upchart > high[nw - ach1]
div2 = dnwg[nw - b2] > dnwg[nw - b1] and dnchart[nw - bch2] < dnchart[nw - bch1] and dnchart < low[nw - bch1]
t_div = 0
t_div_ = 0
t_div := bar_index == 0 ? time : div1[1] == true ? time : t_div[1]
days_div_bear = math.round((timenow - t_div) / 86400000)
t_div_ := bar_index == 0 ? time : div2[1] == true ? time : t_div_[1]
days_div_bull = math.round((timenow - t_div_) / 86400000)
array.set(out_screener_func, 0, str.tostring(rsi, "#"))
array.set(out_screener_func, 1, str.tostring(days_div_bull))
array.set(out_screener_func, 2, str.tostring(days_div_bear))
out_screener_func
//IMPORT
s01_data = request.security(s01, timeframe, screener_func(u01))
s02_data = request.security(s02, timeframe, screener_func(u02))
s03_data = request.security(s03, timeframe, screener_func(u03))
s04_data = request.security(s04, timeframe, screener_func(u04))
s05_data = request.security(s05, timeframe, screener_func(u05))
s06_data = request.security(s06, timeframe, screener_func(u06))
s07_data = request.security(s07, timeframe, screener_func(u07))
s08_data = request.security(s08, timeframe, screener_func(u08))
s09_data = request.security(s09, timeframe, screener_func(u09))
s10_data = request.security(s10, timeframe, screener_func(u10))
s11_data = request.security(s11, timeframe, screener_func(u11))
s12_data = request.security(s12, timeframe, screener_func(u12))
s13_data = request.security(s13, timeframe, screener_func(u13))
s14_data = request.security(s14, timeframe, screener_func(u14))
s15_data = request.security(s15, timeframe, screener_func(u15))
s16_data = request.security(s16, timeframe, screener_func(u16))
s17_data = request.security(s17, timeframe, screener_func(u17))
s18_data = request.security(s18, timeframe, screener_func(u18))
s19_data = request.security(s19, timeframe, screener_func(u19))
s20_data = request.security(s20, timeframe, screener_func(u20))
//OUTPUTs
// Set Table
var tbl = table.new(table_pos(in_table_pos), 5, 22, frame_color = #151715,
frame_width=1, border_width=1, border_color=color.new(color.white, 100))
// Set Up Screener Matrix
screener_mtx = matrix.new<string>(20, 4, na)
// Fill Up Matrix Cells
mtx(mtxName, row, symbol, s_data)=>
if not na(array.get(s_data, 0))
matrix.set(mtxName, row, 0, symbol ) //Symbol
matrix.set(mtxName, row, 1, array.get(s_data, 0)) //Rsi
matrix.set(mtxName, row, 2, array.get(s_data, 1)) //Bull
matrix.set(mtxName, row, 3, array.get(s_data, 2)) //Bear
if barstate.islast
mtx(screener_mtx, 0, only_symbol(s01), s01_data)
mtx(screener_mtx, 1, only_symbol(s02), s02_data)
mtx(screener_mtx, 2, only_symbol(s03), s03_data)
mtx(screener_mtx, 3, only_symbol(s04), s04_data)
mtx(screener_mtx, 4, only_symbol(s05), s05_data)
mtx(screener_mtx, 5, only_symbol(s06), s06_data)
mtx(screener_mtx, 6, only_symbol(s07), s07_data)
mtx(screener_mtx, 7, only_symbol(s08), s08_data)
mtx(screener_mtx, 8, only_symbol(s09), s09_data)
mtx(screener_mtx, 9, only_symbol(s10), s10_data)
mtx(screener_mtx, 10, only_symbol(s11), s11_data)
mtx(screener_mtx, 11, only_symbol(s12), s12_data)
mtx(screener_mtx, 12, only_symbol(s13), s13_data)
mtx(screener_mtx, 13, only_symbol(s14), s14_data)
mtx(screener_mtx, 14, only_symbol(s15), s15_data)
mtx(screener_mtx, 15, only_symbol(s16), s16_data)
mtx(screener_mtx, 16, only_symbol(s17), s17_data)
mtx(screener_mtx, 17, only_symbol(s18), s18_data)
mtx(screener_mtx, 18, only_symbol(s19), s19_data)
mtx(screener_mtx, 19, only_symbol(s20), s20_data)
if table_sort_by != "None"
matrix.sort(screener_mtx, table_sort_by == "Symbol" ? 0 : na, table_sort_dir == "Ascending" ? order.ascending : order.descending)
//Remove NaN rows
q= 0
while q <= matrix.rows(screener_mtx) - 1 and matrix.rows(screener_mtx) > 1
if na(matrix.get(screener_mtx, q, 0))
matrix.remove_row(screener_mtx, q)
q := q
else
q := q + 1
// Fill up Table
table.cell(tbl, 0, 0, 'Symbol', bgcolor = column_title_bgcol,
text_color = cell_txtcol, text_size = table_size(in_table_size))
table.cell(tbl, 1, 0, 'RSI', bgcolor = column_title_bgcol,
text_color = cell_txtcol, text_size = table_size(in_table_size))
table.cell(tbl, 2, 0, 'Bullish-Days Ago', bgcolor = color.green,
text_color = cell_txtcol, text_size = table_size(in_table_size))
table.cell(tbl, 3, 0, 'Bearish-Days Ago', bgcolor = color.red,
text_color = cell_txtcol, text_size = table_size(in_table_size))
// Output
max_row = 1
for i = 0 to matrix.rows(screener_mtx) - 1
if not na(matrix.get(screener_mtx, i, 1))
// Symbol
table.cell(tbl, 0, i + 2, matrix.get(screener_mtx, i, 0),
text_halign = text.align_center, bgcolor = column_title_bgcol,
text_color = cell_txtcol, text_size = table_size(in_table_size))
// Rsi
rsi_value = str.tonumber(matrix.get(screener_mtx, i, 1))
rsi_col = color.from_gradient(rsi_value, 30, 70, bull_color, bear_color)
table.cell(tbl, 1, i + 2, matrix.get(screener_mtx, i, 1),
text_halign = text.align_center, bgcolor = rsi_col,
text_color = cell_txtcol, text_size = table_size(in_table_size))
// Bull
bull_value = str.tonumber(matrix.get(screener_mtx, i, 2))
bull_col = color.from_gradient(bull_value, 0, 100, bull_color, color.white)
table.cell(tbl, 2, i + 2, matrix.get(screener_mtx, i, 2),
text_halign = text.align_center, bgcolor = bull_col,
text_color = cell_txtcol, text_size = table_size(in_table_size))
// Bear
bear_value = str.tonumber(matrix.get(screener_mtx, i, 3))
bear_col = color.from_gradient(bear_value, 0, 100, bear_color, color.white)
table.cell(tbl, 3, i + 2, matrix.get(screener_mtx, i, 3),
text_halign = text.align_center, bgcolor = bear_col,//cell_bgcol,
text_color = cell_txtcol, text_size = table_size(in_table_size))
max_row := max_row + 1
//Bands
band1 = hline(70, "Upper Band", color=#787B86)
bandm = hline(50, "Middle Band", color=color.new(#787B86, 50))
band0 = hline(30, "Lower Band", color=#787B86)
fill(band1, band0, color=color.rgb(126, 87, 194, 90), title="Background") |
Kalman Filtered ROC & Stochastic with MA Smoothing | https://www.tradingview.com/script/OZaJv4Sz-Kalman-Filtered-ROC-Stochastic-with-MA-Smoothing/ | profitprotrading | https://www.tradingview.com/u/profitprotrading/ | 452 | 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/
// © profitprotrading
//@version=5
indicator("Kalman Smoothed ROC & Stochastic", shorttitle = "SROCST")
//MA Smoothing
ma_type = input.string(title='MA Type', defval='TEMA', options=['EMA', 'DEMA', 'TEMA', 'WMA', 'VWMA', 'SMA', 'SMMA', 'HMA', 'LSMA', 'PEMA'], group = "Moving Average Smoothing")
lsma_offset = input.int(defval=0, title='*(LSMA) Only - Offset Value', minval=0, group = "Moving Average Smoothing")
smoothlen = input(12, "Smoothing Length")
//MA Smoothing indicator credit to: © traderharikrishna https://www.tradingview.com/v/X72V8xjH/
ma(type, src, len) =>
float result = 0
if type == 'SMA' // Simple
result := ta.sma(src, len)
result
if type == 'EMA' // Exponential
result := ta.ema(src, len)
result
if type == 'DEMA' // Double Exponential
e = ta.ema(src, len)
result := 2 * e - ta.ema(e, len)
result
if type == 'TEMA' // Triple Exponential
e = ta.ema(src, len)
result := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len)
result
if type == 'WMA' // Weighted
result := ta.wma(src, len)
result
if type == 'VWMA' // Volume Weighted
result := ta.vwma(src, len)
result
if type == 'SMMA' // Smoothed
w = ta.wma(src, len)
result := na(w[1]) ? ta.sma(src, len) : (w[1] * (len - 1) + src) / len
result
if type == 'HMA' // Hull
result := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len)))
result
if type == 'LSMA' // Least Squares
result := ta.linreg(src, len, lsma_offset)
result
if type == 'PEMA'
// Copyright (c) 2010-present, Bruno Pio
// Copyright (c) 2019-present, Alex Orekhov (everget)
// Pentuple Exponential Moving Average script may be freely distributed under the MIT license.
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
ema4 = ta.ema(ema3, len)
ema5 = ta.ema(ema4, len)
ema6 = ta.ema(ema5, len)
ema7 = ta.ema(ema6, len)
ema8 = ta.ema(ema7, len)
pema = 8 * ema1 - 28 * ema2 + 56 * ema3 - 70 * ema4 + 56 * ema5 - 28 * ema6 + 8 * ema7 - ema8
result := pema
result
result
//
//Kalman Filter with credit to © Loxx https://www.tradingview.com/v/OxYmisSS/
src = input(close, "Kalman Source", group = "Kalman Filter")
Sharpness = input.float(25.0, "Sharpness", group = "Kalman Filter")
K = input.float(1.0, "Filter Period", group = "Kalman Filter")
velocity = 0.0
kfilt = 0.0
Distance = src - nz(kfilt[1], src)
Error = nz(kfilt[1], src) + Distance * math.sqrt(Sharpness*K/ 100)
velocity := nz(velocity[1], 0) + Distance*K / 100
kfilt := Error + velocity
//ROC
length = input.int(9, "ROC Length", minval=1, group = "Rate of Change")
roc = 100 * (kfilt - kfilt[length])/kfilt[length]
//Stochastic
periodK = input.int(14, title="%K Length", minval=1, group = "Stochastic")
smoothK = input.int(1, title="%K Smoothing", minval=1, group = "Stochastic")
periodD = input.int(3, title="%D Smoothing", minval=1, group = "Stochastic")
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)
//ROC + Stochastic
blend = (roc + d)/2
blend := ma(ma_type, blend, smoothlen)
//Plotting
bcol = blend > blend[1] ? color.rgb(255, 255, 255) : color.rgb(17, 0, 208)
blendx = plot(blend, "Blended ROC & Stochastic", linewidth = 2, color = bcol)
plotshape(ta.crossover(blend,blend[1]) and barstate.isconfirmed ? blend : na, style = shape.labelup, text = "B", textcolor = color.white, location = location.absolute, size = size.tiny, color = color.rgb(0, 135, 14), offset = -1)
plotshape(ta.crossunder(blend,blend[1]) and barstate.isconfirmed ? blend : na, style = shape.labeldown, text = "S", textcolor = color.white, location = location.absolute, size = size.tiny, color = color.rgb(37, 0, 224), offset = -1)
//OB/OS
obtop = plot(60, display = display.none)
obb = plot(50, display = display.none)
osb = plot(0, display = display.none)
ostop = plot(10, display = display.none)
mid = plot(30, "Midline", display = display.none)
fill(blendx, mid, blend > blend[1] ? blend : 30, blend > blend[1] ? 30 : blend, blend > blend[1] ? color.rgb(169, 162, 255, 60) : #00000000, blend > blend[1] ? #00000000 : color.rgb(17, 0, 208,60))
hline(60, color = color.rgb(255, 0, 0))
hline(50, color = color.rgb(255, 0, 0))
hline(0, color = color.rgb(0, 222, 7))
hline(10, color = color.rgb(0, 222, 7)) |
ALMA Smoothed Gaussian Moving Average | https://www.tradingview.com/script/9kZxqmzH-ALMA-Smoothed-Gaussian-Moving-Average/ | profitprotrading | https://www.tradingview.com/u/profitprotrading/ | 460 | 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/
// © profitprotrading
//@version=5
indicator("ALMA Smoothed Gaussian Moving Average", shorttitle = "ASGMA", overlay=true)
//ALMA Smoothing
src = input(close, title='Source', group = "ALMA Smoothing")
smooth = input.int(1, title='Smoothing', minval=1, group = "ALMA Smoothing")
length1 = input.int(25, title='Lookback', minval=1, group = "ALMA Smoothing")
offset = 0.85
sigma1 = 7
pchange = ta.change(src, smooth) / src * 100
avpchange = ta.alma(pchange, length1, offset, sigma1)
//RSI
rsi = ta.rsi(close, 14)
rsiL = rsi > rsi[1]
rsiS = rsi < rsi[1]
//Chande Momentum
length11 = 9
src1 = close
momm = ta.change(src1)
f1(m) => m >= 0.0 ? m : 0.0
f2(m) => m >= 0.0 ? 0.0 : -m
m1 = f1(momm)
m2 = f2(momm)
sm1 = math.sum(m1, length11)
sm2 = math.sum(m2, length11)
percent(nom, div) => 100 * nom / div
chandeMO = percent(sm1-sm2, sm1+sm2)
cL = chandeMO > chandeMO[1]
cS = chandeMO < chandeMO[1]
//GAMA credit to author: © LeafAlgo https://www.tradingview.com/v/th7NZUPM/
length = input.int(14, minval=1, title="Length", group = "Gaussian Adaptive Moving Average")
adaptive = input.bool(true, title="Adaptive Parameters", group = "Gaussian Adaptive Moving Average")
volatilityPeriod = input.int(20, minval=1, title="Volatility Period", group = "Gaussian Adaptive Moving Average")
// Calculate Gaussian Moving Average
gma = 0.0
sumOfWeights = 0.0
sigma = adaptive ? ta.stdev(close, volatilityPeriod) : input.float(1.0, minval=0.1, title="Standard Deviation", group = "Gaussian Adaptive Moving Average")
for i = 0 to length - 1
weight = math.exp(-math.pow(((i - (length - 1)) / (2 * sigma)), 2) / 2)
value = ta.highest(avpchange, i + 1) + ta.lowest(avpchange, i + 1)
gma := gma + (value * weight)
sumOfWeights := sumOfWeights + weight
gma := (gma / sumOfWeights) / 2
gma:= ta.ema(gma, 7)
gmaColor = avpchange >= gma ? color.rgb(0, 161, 5) : color.rgb(215, 0, 0)
// Color bars based on signals until the next signal occurs
var int currentSignal = 0
currentSignal := avpchange >= gma ? 1 : -1//le_final ? -1 : currentSignal
var color barColor = na
if currentSignal == 1
barColor := color.rgb(0, 186, 6)
else if currentSignal == -1
barColor := color.rgb(176, 0, 0)
barcolor(barColor)
plotcandle(open, high, low, close, "Bar Color", barColor, barColor, bordercolor = barColor)
//Plotting
ema = ta.ema(close, 7)
plot(ema, color=gmaColor, linewidth=3, title="Gaussian Moving Average")
plotshape(ta.crossover(avpchange,gma) and barstate.isconfirmed, "Buy Signal", text = "B", textcolor = color.white, style = shape.labelup, location = location.belowbar, color = color.rgb(0, 161, 5), offset = -1)
plotshape(ta.crossunder(avpchange,gma) and barstate.isconfirmed, "Sell Signal", text = "S", textcolor = color.white, style = shape.labeldown, location = location.abovebar, color = color.rgb(215, 0, 0), offset = -1)
bgcolor(ta.crossover(avpchange,gma) and barstate.isconfirmed and rsiL and cL ? color.rgb(0, 162, 5, 85): na, offset = -1)
bgcolor(ta.crossunder(avpchange,gma) and barstate.isconfirmed and rsiS and cS ? color.rgb(207, 0, 0, 85): na, offset = -1)
barcolor(gmaColor)
alertcondition(ta.crossover(avpchange,gma) and barstate.isconfirmed, title="Buy Signal", message="Go Long! {{exchange}}:{{ticker}}")
alertcondition(ta.crossunder(avpchange,gma) and barstate.isconfirmed, title="Sell Signal", message="Go Short! {{exchange}}:{{ticker}}") |
Discrete Fourier Transformed Money Flow Index | https://www.tradingview.com/script/Ski1QqnX-Discrete-Fourier-Transformed-Money-Flow-Index/ | profitprotrading | https://www.tradingview.com/u/profitprotrading/ | 119 | 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/
// © profitprotrading
//@version=5
indicator(title="Fourier Transformed Money Flow Index", shorttitle="FMFI", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
//Fourier Settings (Credit to author: wbburgin - May 26 2023 https://www.tradingview.com/v/gThgCf69/)
//Inputs
N = input.int(3,"Fourier Period", group = "Fourier Transform")
xval = input.source(hlc3,"Fourier Source", group = "Fourier Transform")
//Discrete Fourier Transform
DFT(x, y, Nx, _dir) =>
float _arg = 0.0
float _cos = 0.0
float _sin = 0.0
float xArr_i = 0.0
float yArr_i = 0.0
xArr = array.new_float(array.size(x))
yArr = array.new_float(array.size(y))
for i = 0 to Nx - 1 by 1
xArr_i := 0.0
yArr_i := 0.0
kx = float(i) / float(Nx)
_arg := -_dir * 2 * math.pi * kx
for k = 0 to Nx - 1 by 1
_cos := math.cos(k * _arg)
_sin := math.sin(k * _arg)
xArr_i += array.get(x, k) * _cos - array.get(y, k) * _sin
yArr_i += array.get(x, k) * _sin + array.get(y, k) * _cos
yArr_i
array.set(xArr, i, xArr_i)
array.set(yArr, i, yArr_i)
if _dir == 1
for i = 0 to Nx - 1 by 1
array.set(x, i, array.get(xArr, i) / float(Nx))
array.set(y, i, array.get(yArr, i) / float(Nx))
else
for i = 0 to Nx - 1 by 1
array.set(x, i, array.get(xArr, i))
array.set(y, i, array.get(yArr, i))
//
x = array.new_float(N, 0.0)
y = array.new_float(N, 0.0)
for i = 0 to N - 1
array.set(x, i, xval[i])
array.set(y, i, 0.0)
DFT(x, y, N, 1)
mag = array.new_float(N, 0.0)
for i = 0 to N - 1
mag_i = math.sqrt(math.pow(array.get(x, i), 2) + math.pow(array.get(y, i), 2))
array.set(mag, i, mag_i)
ft = array.get(mag,0)
//Money Flow Index
length = input.int(title="Length", defval=14, minval=1, maxval=2000, group = "MFI")
smooth = input.int(7, "Smoothing", group = "MFI")
src = input(hlc3, "Source", group = "MFI")
ori = input.bool(true, "Plot original MFI?")
mf = ta.mfi(ft, length)
mf := ta.ema(mf, smooth)
short = (ta.crossunder(mf,mf[1]))
//Plotting
plot(mf, "MF", color=mf > mf[1] ? #ffffff: color.rgb(128, 35, 95), linewidth = 4)
plotchar(ta.crossover(mf,mf[1]) ? mf : na, char = "⊙", location = location.absolute, size = size.tiny, color = #ffffff, offset = -1)
plotchar(ta.crossunder(mf,mf[1]) ? mf : na, char = "⦿", location = location.absolute, size = size.tiny, color = color.rgb(246, 93, 192), offset = -1)
plotshape((ta.crossunder(mf,mf[1]) and mf > 80), style = shape.triangledown, color = color.rgb(201, 8, 8), location = location.top, size = size.tiny, offset = -1)
plotshape((ta.crossover(mf,mf[1]) and mf < 20), style = shape.triangleup, color = color.rgb(0, 171, 11), location = location.bottom, size = size.tiny, offset = -1)
mfx = plot(ori ? ta.mfi(src,length): na, color = color.rgb(0, 208, 255, 65))
ob = plot(80, display = display.none)
ob1 = plot(100, display = display.none)
ob2 = plot(65, display = display.none)
os = plot(20, display = display.none)
os1 = plot(0, display = display.none)
os2 = plot(35, display = display.none)
fill(ob, ob1, color = color.rgb(234, 0, 0, 75))
fill(os, os1, color = color.rgb(0, 193, 6, 75))
fill(ob2, ob, color =color.rgb(234, 0, 0, 85))
fill(os, os2, color =color.rgb(0, 193, 6, 85))
//Alert Conditions
alertcondition(ta.crossover(mf,mf[1]), title="Buy", message="{{exchange}}:{{ticker}}")
alertcondition(ta.crossunder(mf,mf[1]), title="Sell", message="{{exchange}}:{{ticker}}")
alertcondition((ta.crossover(mf,mf[1]) and mf < 20), title="Firm Buy", message="{{exchange}}:{{ticker}}")
alertcondition((ta.crossunder(mf,mf[1]) and mf > 80), title="Firm Sell", message="{{exchange}}:{{ticker}}") |
Volume Forks [Trendoscope] | https://www.tradingview.com/script/qAMnMxZI-Volume-Forks-Trendoscope/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 547 | study | 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
indicator("Volume Forks [Trendoscope]", "VF [Trendoscope]", overlay = true, max_lines_count=500, max_bars_back = 3000)
import HeWhoMustNotBeNamed/DrawingTypes/2 as dr
import HeWhoMustNotBeNamed/DrawingMethods/2
import HeWhoMustNotBeNamed/ZigzagTypes/5 as zg
import HeWhoMustNotBeNamed/ZigzagMethods/6
import HeWhoMustNotBeNamed/PitchforkTypes/2 as p
import HeWhoMustNotBeNamed/PitchforkMethods/2
import HeWhoMustNotBeNamed/utils/1 as ut
theme = input.string('Dark', title='Theme', options=['Light', 'Dark'], group='Generic Settings',
tooltip='Chart theme settings. Line and label colors are generted based on the theme settings. If dark theme is selected, '+
'lighter colors are used and if light theme is selected, darker colors are used.')
zigzagLength = input.int(13, step=5, minval=3, title='Length', group='Zigzag', tooltip='Zigzag length for level 0 zigzag')
depth = input.int(50, "Depth", step=25, maxval=500, group='Zigzag', tooltip='Zigzag depth refers to max number of pivots to show on chart')
useRealTimeBars = input.bool(true, 'Use Real Time Bars', group='Zigzag', tooltip = 'If enabled real time bars are used for calculation. Otherwise, only confirmed bars are used')
typeTooltip = 'Handle Type' +
'\nandrews - Pivot A' +
'\nschiff - X of Pivot A and y from median of Pivot A and B' +
'\nmschiff - X and Y are median of Pivot A and Pivot B' +
'\n\nNeck Type' +
'\nmedian - median of Pivot B and Pivot C' +
'\ninside - Pivot C'
pitchforkType = input.string("andrews", "Type", ["andrews", "schiff", "mschiff"], group="Pitchfork", inline="t")
neckType = input.string('inside', '', ['median', 'inside'], group="Pitchfork", inline="t", tooltip=typeTooltip)
handle = pitchforkType=='andrews'?'regular': pitchforkType
inside = neckType == 'inside'
ratioFrom = input.float(0.25, 'Ratio', minval=0.0, maxval=0.5, group='Pitchfork', inline='r')
ratioTo = input.float(1, '', minval=0.5, maxval=1.618, group='Pitchfork', inline='r', tooltip='Range of ratio for which drawing pitchfork is allowed')
numberOfForks = input.int(100, 'Forks', group = 'Pitchfork', inline='f', minval=10, maxval = 200, step=25, tooltip = 'Number of volume forks')
usePercentile = input.bool(false, 'Percentile', group='Pitchfork', tooltip = 'Use percentile of volume to determine the length of forks instead of percentage')
useConfirmedPivot = input.bool(true, 'Use Confirmed Pivots', group="Pitchfork", tooltip="If set to true, uses last confirmed pivot and ignores the current moving pivot")
extend = false
fill = false
offset = useRealTimeBars? 0 : 1
indicators = matrix.new<float>()
indicatorNames = array.new<string>()
themeColors = ut.getColors(theme)
var zg.Zigzag zigzag = zg.Zigzag.new(zigzagLength, depth, offset)
zigzag.calculate(array.from(high, low), indicators, indicatorNames)
startIndex = useConfirmedPivot? 1:0
method get_price(dr.Line this, int bar)=>
stepPerBar = (this.end.price - this.start.price)/(this.end.bar - this.start.bar)
distance = bar - this.start.bar
this.start.price + distance*stepPerBar
array<p.Fork> forks = array.new<p.Fork>()
for i=0 to numberOfForks-1
forks.push(p.Fork.new(i/(numberOfForks-1)))
p.PitchforkProperties properties = p.PitchforkProperties.new(forks, handle, inside)
if(barstate.islast)
var array<p.Pitchfork> pitchforks = array.new<p.Pitchfork>()
pitchforks.clear()
mlzigzag = zigzag
while(mlzigzag.zigzagPivots.size() >= 3+startIndex)
lineColor = themeColors.pop()
themeColors.unshift(lineColor)
p3 = mlzigzag.zigzagPivots.get(startIndex)
p3Point = p3.point
p2Point = mlzigzag.zigzagPivots.get(startIndex+1).point
p1Point = mlzigzag.zigzagPivots.get(startIndex+2).point
if (p3.ratio >= ratioFrom and p3.ratio <= ratioTo and p3Point.bar - p1Point.bar <500)
dr.LineProperties lProperties = dr.LineProperties.new(color=lineColor)
p.PitchforkDrawingProperties dProperties = p.PitchforkDrawingProperties.new(extend, fill, commonColor=color.new(lineColor, 70))
p.Pitchfork pitchFork = p.Pitchfork.new(p1Point, p2Point, p3Point, properties, dProperties, lProperties)
drawing = pitchFork.createDrawing()
array<float> forkVolumes = array.new<float>(drawing.forkLines.size(), 0.0)
for bar=p1Point.bar to p3Point.bar
bOpen = open[bar_index-bar]
bClose = close[bar_index-bar]
bHigh = high[bar_index-bar]
bLow = low[bar_index-bar]
bVol = volume[bar_index-bar]
for [index, forkLine] in drawing.forkLines
linePrice = forkLine.get_price(bar)
vMultiplier = linePrice >= math.min(bOpen, bClose) and linePrice <= math.max(bOpen, bClose)? 2 :
linePrice >= bLow and linePrice <= bHigh? 1 : 0
forkVolumes.set(index, forkVolumes.get(index)+bVol*vMultiplier)
for [index, forkLine] in drawing.forkLines
vPercent = usePercentile? forkVolumes.percentrank(index)/100 : forkVolumes.get(index)/forkVolumes.max()
forkLine.end.bar := forkLine.start.bar + int(vPercent*(forkLine.end.bar - forkLine.start.bar))
forkLine.end.price := forkLine.start.price + vPercent*(forkLine.end.price - forkLine.start.price)
drawing.draw()
pitchforks.push(pitchFork)
mlzigzag := mlzigzag.nextlevel() |
Savitzky-Golay Filtered Chande Momentum Oscillator | https://www.tradingview.com/script/ZQ4fiJfH-Savitzky-Golay-Filtered-Chande-Momentum-Oscillator/ | profitprotrading | https://www.tradingview.com/u/profitprotrading/ | 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/
// © profitprotrading
//@version=5
indicator(title="Savitzky-Golay Filtered Chande Momentum Oscillator", shorttitle="SGCMO", format=format.price, precision=0)
src1 = input(close, "Source")
//Savitzky-Golay Filtering credit to © anieri
sgfilter5(x) =>
(x[4] * -3 + x[3] * 12 + x[2] * 17 + x[1] * 12 + x[0] * -3) / 35
sgfilter7(x) =>
(x[6] * -2 + x[5] * 3 + x[4] * 6 + x[3] * 7 + x[2] * 6 + x[1] * 3 + x[0] * -2) / 21
sgfilter9(x) =>
(x[8] * -21 + x[7] * 14 + x[6] * 39 + x[5] * 54 + x[4] * 59 + x[3] * 54 + x[2] * 39 + x[1] * 14 + x[0] * -21) / 231
sgfilter15(x) =>
(x[14] * -78 + x[13] * -13 + x[12] * 42 + x[11] * 87 + x[10] * 122 + x[9] * 147 + x[8] * 162 + x[7] * 167 + x[6] * 162 + x[5] * 147 + x[4] * 122 + x[3] * 87 + x[2] * 42 + x[1] * -13 + x[0] * -78) / 1105
sgfilter25(x) =>
(x[24] * -253 + x[23] * -138 + x[22] * -33 + x[21] * 62 + x[20] * 147 + x[19] * 222 + x[18] * 287 + x[17] * 343 + x[16] * 387 + x[15] * 422 + x[14] * 447 + x[13] * 462 + x[12] * 467 + x[11] * 462 + x[10] * 447 + x[9] * 422 + x[8] * 387 + x[7] * 343 + x[6] * 287 + x[5] * 222 + x[4] * 147 + x[3] * 62 + x[2] * -33 + x[1] * -138 + x[0] * -253) / 5175
//
//Chande Momentum Oscillator
length = input.int(9, minval=1, title = "Oscillator Length")
smooth = input(8, "Oscillator Smoothing")
momm = ta.change(sgfilter5(src1))
f1(m) => m >= 0.0 ? m : 0.0
f2(m) => m >= 0.0 ? 0.0 : -m
m1 = f1(momm)
m2 = f2(momm)
sm1 = math.sum(m1, length)
sm2 = math.sum(m2, length)
percent(nom, div) => 100 * nom / div
chandeMO = percent(sm1-sm2, sm1+sm2)
chandeMO:= ta.ema(chandeMO, smooth)
//Plots
ob = plot(80, display = display.none)
ob1 = plot(50, display = display.none)
ob2 = plot(35, display = display.none)
os = plot(-80, display = display.none)
os1 = plot(-50, display = display.none)
os2 = plot(-35, display = display.none)
fill(ob, ob1, color = color.rgb(21, 0, 255, 92))
fill(os, os1, color = color.rgb(0, 208, 255, 92))
fill(ob2, ob, color =color.rgb(21, 0, 255, 95))
fill(os, os2, color =color.rgb(0, 208, 255, 95))
col = chandeMO > chandeMO[1]? color.white: color.rgb(255, 64, 0)
col2 = chandeMO > chandeMO[1] and chandeMO < -50? color.rgb(0, 215, 14, 75): na
col3 = chandeMO < chandeMO[1] and chandeMO > 50? color.rgb(215, 0, 0, 75): na
plot(chandeMO, "Chande MO", color= col, linewidth = 3)
bgcolor(col2, offset = -1)
bgcolor(col3, offset = -1) |
Price Exhaustion Indicator | https://www.tradingview.com/script/P4MrhRbk-Price-Exhaustion-Indicator/ | profitprotrading | https://www.tradingview.com/u/profitprotrading/ | 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/
// © profitprotrading
//@version=5
indicator(title='Price Exhaustion Indicator', shorttitle='PE', overlay=false)
//Input parameters
fastLength = input.int(12, minval=1, title='Fast Length')
slowLength = input.int(26, minval=1, title='Slow Length')
signalSmoothing = input.int(9, minval=1, title='Signal Smoothing')
atrLength = input.int(14, minval=1, title='ATR Length')
stochLength = input.int(14, minval=1, title='Stochastic Length')
smoothK = input.int(3, minval=1, title='Stochastic %K Smoothing')
//MACD
[macdLine, signalLine, _] = ta.macd(close, fastLength, slowLength, signalSmoothing)
// ATR
atrValue = ta.atr(atrLength)
//Stochastic Oscillator
stochK = ta.sma(ta.stoch(close, high, low, stochLength), smoothK)
// Calculate price exhaustion
exhaustion = macdLine / atrValue * stochK
//Colors
color = color.from_gradient(exhaustion, -20, 40, color.purple, color.white)
color2 = color.from_gradient(exhaustion, 40, 100, color.white, color.purple)
//Plotting
ex1 = plot(exhaustion, title='Trend Exhaustion', color= exhaustion < 40? color: color2, linewidth=2)
plotchar(ta.crossunder(exhaustion, 100), char = "🞄", location = location.top, color = color.rgb(198, 0, 0), size = size.tiny)
plotchar(ta.crossunder(exhaustion, -20), char = "🞄", location = location.bottom, color = color.rgb(0, 186, 6), size = size.tiny)
top = plot(100, color = color.gray, display = display.none)
bottom = plot(-20, color = color.gray, display = display.none)
mid = plot(40, title='Exhaustion Threshold', color=color.red, display = display.none)
fill(mid,bottom, top_value = 40, bottom_value = -20, top_color = color.rgb(0, 0, 0, 100), bottom_color = color.rgb(0, 255, 8, 78))
fill(mid,top, top_value = 100, bottom_value = 40, top_color = color.rgb(255, 0, 0, 78), bottom_color = color.rgb(0, 0, 0, 100))
fill(ex1, top, 200, 100, top_color = color.new(#960091, 0), bottom_color = color.new(#960091, 100), title = "Overbought Gradient Fill")
fill(ex1, bottom, -20, -70, top_color = color.new(#960091, 100), bottom_color = color.new(#960091, 0), title = "Oversold Gradient Fill") |
RSI Chart Levels | https://www.tradingview.com/script/rYbWnFri-RSI-Chart-Levels/ | RSI_Trading_Concepts | https://www.tradingview.com/u/RSI_Trading_Concepts/ | 547 | 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/
// © Waldo307
//@version=5
indicator("RSI Chart Levels", overlay=true, max_bars_back = 100,max_labels_count = 15,max_lines_count = 15)
////INPUTs
inputgroup = "**********INPUTs**********"
shtline = input.bool(defval = true, title = "Show Trend Lines", group=inputgroup)
////RSI
rsigroup = "**********RSI**********"
len = input.int(14, minval=1, title='RSI Length', group = rsigroup)
src = input(close, 'RSI Source', group = rsigroup)
up = ta.rma(math.max(ta.change(src), 0), len)
down = ta.rma(-math.min(ta.change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
////TRENDLINEs
trendgroup = "**********TREND LINE**********"
length = input(10, title='Zigzag Length')
r = rsi[length]
l = rsi[14]
ph = ta.pivothigh(rsi,length,length)
pl = ta.pivotlow(rsi,length,length)
valH = ta.valuewhen(ph,r,0)
valL = ta.valuewhen(pl,r,0)
valpH = ta.valuewhen(ph,r,1)
valpL = ta.valuewhen(pl,r,1)
d = math.abs(r)
n = bar_index
label lbl = na
HIH = valH > valpH ? "Higher High" : na
HIL = valH < valpH ? "Lower High" : na
LOL = valL < valpL ? "Lower Low" : na
LOH = valL > valpL ? "Higher Low" : na
if ph and valH > valpH and shtline
lbl := label.new(n[length],close[length],HIH,color=#ff1100 ,
style=label.style_label_down,textcolor=color.white,size=size.tiny)
label.delete(lbl[2])
linehh = line.new(n[length],close[length], bar_index,close[length], extend=extend.right, color=color.red)
line.delete(linehh[2])
else if ph and valH < valpH and shtline
lbl := label.new(n[length],close[length],HIL,color=#e79700 ,
style=label.style_label_down,textcolor=color.white,size=size.tiny)
label.delete(lbl[2])
linehl = line.new(n[length],close[length], bar_index, close[length], extend=extend.right, color=color.orange)
line.delete(linehl[2])
else if pl and valL < valpL and shtline
lbl := label.new(n[length],close[length],LOL,color=#009c0c ,
style=label.style_label_up,textcolor=color.white,size=size.tiny)
label.delete(lbl[2])
linell = line.new(n[length],close[length], bar_index, close[length], extend=extend.right, color=color.green)
line.delete(linell[2])
else if pl and valL > valpL and shtline
lbl := label.new(n[length],close[length],LOH,color= #0073ee ,
style=label.style_label_up,textcolor=color.white,size=size.tiny)
label.delete(lbl[2])
linelh = line.new(n[length],close[length], bar_index, close[length], extend=extend.right, color=color.blue)
line.delete(linelh[2])
label.delete(lbl[200])
|
TTM Waves ABC ATR AO MOM SQZ | https://www.tradingview.com/script/CYdGEITF/ | PenguinCryptic | https://www.tradingview.com/u/PenguinCryptic/ | 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/
//All code picked from many indicators, if you recognize your code, pls comment so people can see your awesome work! I only edited and added them all together. Hope this indicator helps as many people as it can.
//@version=5
indicator("TTM Waves ABC ATR AO MOM SQZ")
showA = input.bool(true,"Show TTM Wave A")
showB = input.bool(false,"Show TTM Wave B")
showC = input.bool(false,"Show TTM Wave C")
// C
float ttmwcmacd = na
float ttmwcf = na
if showC
[Cmacd,_,CSlowHist] = ta.macd(close,8,377,377)
ttmwcmacd := Cmacd
[_,_,CFastHist] = ta.macd(close,8,233,233)
ttmwcf := CFastHist
plot(ttmwcmacd,style=plot.style_histogram,title="TTM wave C Macd",color=#296a22,linewidth=3)
plot(ttmwcf,style=plot.style_histogram,title="TTM wave C Fast",color=#f3701c,linewidth=3)
// B
float ttmwbs = na
float ttmwbf = na
if showB
[_,_,BSlowHist] = ta.macd(close,8,144,144)
ttmwbs := BSlowHist
[_,_,BFastHist] = ta.macd(close,8,89,89)
ttmwbf := BFastHist
plot(ttmwbs,style=plot.style_histogram,title="TTM wave B Slow",color=#296a22,linewidth=3)
plot(ttmwbf,style=plot.style_histogram,title="TTM wave B Fast",color=#f3701c,linewidth=3)
// A
float ttmwas = na
float ttmwaf = na
if showA
[_,_,ASlowHist] = ta.macd(close,8,55,55)
ttmwas := ASlowHist
[_,_,AFastHist] = ta.macd(close,8,34,34)
ttmwaf := AFastHist
plot(ttmwas,style=plot.style_histogram,title="TTM wave A Slow",color=#296a22,linewidth=3)
plot(ttmwaf,style=plot.style_histogram,title="TTM wave A Fast",color=#f3701c,linewidth=3)
atr_length = input.int(14, title = "ATR Length", minval = 0, group = "ATR Indicator Settings")
atr1_multiplier = input.float(1.5, title = "ATR Multiplier #1", minval = 0, group = "ATR Multiplier Settings")
show_atr2 = input.bool(false, title = "Show 2nd ATR line?", group = "ATR Multiplier Settings")
atr2_multiplier = input.float(3, title = "ATR Multiplier #2", minval = 0, group = "ATR Multiplier Settings")
//==============================================================================
//==============================================================================
// ATR #1 and ATR #2 Calculation
//==============================================================================
// Calculate basic ATR value with given smoothing parameters
atr = ta.rma(ta.tr, atr_length)
// Multiply atr by the given atr1 multiplier to get atr1
atr1 = atr * atr1_multiplier
// Multiply atr by the given atr2 multiplier to get atr2
atr2 = atr * atr2_multiplier
//==============================================================================
//==============================================================================
// Plot ATR #1 and ATR #2
//==============================================================================
atr1_color = show_atr2 ? color.red : color.new(#000000, 0)
atr1_plot = plot(atr1, title = "ATR #1", color = atr1_color)
atr2_plot = plot(show_atr2 ? atr2 : na, title = "ATR #2", color = color.green)
length = input.int(20, "TTM Squeeze Length")
//BOLLINGER BANDS
BB_mult = input.float(2.0, "Bollinger Band STD Multiplier")
BB_basis = ta.sma(close, length)
dev = BB_mult * ta.stdev(close, length)
BB_upper = BB_basis + dev
BB_lower = BB_basis - dev
//KELTNER CHANNELS
KC_mult_high = input.float(1.0, "Keltner Channel #1")
KC_mult_mid = input.float(1.5, "Keltner Channel #2")
KC_mult_low = input.float(2.0, "Keltner Channel #3")
KC_basis = ta.sma(close, length)
devKC = ta.sma(ta.tr, length)
KC_upper_high = KC_basis + devKC * KC_mult_high
KC_lower_high = KC_basis - devKC * KC_mult_high
KC_upper_mid = KC_basis + devKC * KC_mult_mid
KC_lower_mid = KC_basis - devKC * KC_mult_mid
KC_upper_low = KC_basis + devKC * KC_mult_low
KC_lower_low = KC_basis - devKC * KC_mult_low
//SQUEEZE CONDITIONS
NoSqz = BB_lower < KC_lower_low or BB_upper > KC_upper_low //NO SQUEEZE: GREEN
LowSqz = BB_lower >= KC_lower_low or BB_upper <= KC_upper_low //LOW COMPRESSION: BLACK
MidSqz = BB_lower >= KC_lower_mid or BB_upper <= KC_upper_mid //MID COMPRESSION: RED
HighSqz = BB_lower >= KC_lower_high or BB_upper <= KC_upper_high //HIGH COMPRESSION: ORANGE
//MOMENTUM OSCILLATOR
mom = ta.linreg(close - math.avg(math.avg(ta.highest(high, length), ta.lowest(low, length)), ta.sma(close, length)), length, 0)
//MOMENTUM HISTOGRAM COLOR
iff_1 = mom > nz(mom[1]) ? color.new(color.aqua, 0) : color.new(#2962ff, 0)
iff_2 = mom < nz(mom[1]) ? color.new(color.red, 0) : color.new(color.yellow, 0)
mom_color = mom > 0 ? iff_1 : iff_2
//SQUEEZE DOTS COLOR
sq_color = HighSqz ? color.new(color.orange, 0) : MidSqz ? color.new(color.red, 0) : LowSqz ? color.new(color.black, 0) : color.new(color.green, 0)
//ALERTS
Detect_Sqz_Start = input.bool(true, "Alert Price Action Squeeze")
Detect_Sqz_Fire = input.bool(true, "Alert Squeeze Firing")
if Detect_Sqz_Start and NoSqz[1] and not NoSqz
alert("Squeeze Started")
else if Detect_Sqz_Fire and NoSqz and not NoSqz[1]
alert("Squeeze Fired")
//PLOTS
plot(mom, title='MOM', color=mom_color, style=plot.style_columns, linewidth=2)
plot(0, title='SQZ', color=sq_color, style=plot.style_circles, linewidth=3)
//@version=5
ao = ta.sma(hl2,5) - ta.sma(hl2,34)
diff = ao - ao[1]
aoColor = ao >= 0 ? (ao[1] < ao ? #26A69A : #B2DFDB) : (ao[1] < ao ? #FFCDD2 : #EF5350)
plot(ao, title="AO", style=plot.style_columns, color=aoColor, transp=0)
|
Ultimate Heiken-Ashi | https://www.tradingview.com/script/e554riHW-Ultimate-Heiken-Ashi/ | TradersForecast | https://www.tradingview.com/u/TradersForecast/ | 48 | 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/
// © TradersForecast, used code from 'allanster'
//@version=5
indicator(title = "Ultimate Heiken-Ashi", shorttitle = "uHA", overlay = true) //, scale=scale.none)
// Custom source function for toggling traditional Candle sources or Heikin-Ashi sources on a traditional Candles chart.
// Thanks to PineCoders for rounding method: https://www.pinecoders.com/faq_and_code/#how-can-i-round-to-ticks
// Thanks to @LucF and @RicardoSantos for their advice and enlightenment as always.
hknAsh = input.bool(true, title = "Heikin Ashi (else regular bars)?")
HAfact = input.float(1.0, title="Heikin Ashi factor")
lineOnly = input.bool(false, title = "Line (instead of bars)?")
existingBars = input.bool(false, title = "Use existing bars as is (else force normal bars)?")
useModif4HA = input.bool(false, title="Use modified calculation?")
twiceHA = input.bool(false, title="Do HA 2nd time?")
useModif4HA2 = input.bool(false, title="Use modified calculation (2nd time)?")
upClr = input.color(color.green, "Up bar color") //#0010FF90 #0040FF50 //#00BFFF50 //#26a69a50
dnClr = input.color(color.maroon, "Down bar color") //#FFC70090 #FFA50050
lineClr = input.color(color.green, "Line color")
// functions
// isHA() =>
// is_ha = na(open[1]) ? false : (round(open/syminfo.mintick)*syminfo.mintick == round(((nz(open[1]) + nz(close[1])) / 2) / syminfo.mintick) * syminfo.mintick ? true : false)
mkHA0(o_, h_, l_, c_, useModif) =>
cl = math.round(((o_ + h_ + l_ + c_)/4) / syminfo.mintick) * syminfo.mintick // needs to be before /op/
op = float(na)
if useModif == true
op := na(o_[1]) ? (o_ + HAfact*c_)/(1+HAfact) : (nz(op[1]) + HAfact*nz(cl[1]))/(1+HAfact)
else
op := na(o_[1]) ? (o_ + HAfact*c_)/(1+HAfact) : (nz(o_[1]) + HAfact*nz(c_[1]))/(1+HAfact)
op := math.round(op / syminfo.mintick) * syminfo.mintick
hi = math.round(math.max(h_, op, cl) / syminfo.mintick) * syminfo.mintick
lo = math.round(math.min(l_, op, cl) / syminfo.mintick) * syminfo.mintick
[op, hi, lo, cl]
mkHA(o_, h_, l_, c_, useModif_, twice, useModif2) =>
[op, hi, lo, cl] = mkHA0(o_, h_, l_, c_, useModif_)
if twice
[op2, hi2, lo2, cl2] = mkHA0(op, hi, lo, cl, useModif2)
op := op2
hi := hi2
lo := lo2
cl := cl2
[op, hi, lo, cl]
t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
ono = request.security(t, timeframe.period, open, gaps=barmerge.gaps_on) // Official Normal Open
onh = request.security(t, timeframe.period, high, gaps=barmerge.gaps_on)
onl = request.security(t, timeframe.period, low, gaps=barmerge.gaps_on)
onc = request.security(t, timeframe.period, close, gaps=barmerge.gaps_on)
open_ = existingBars ? open : ono
high_ = existingBars ? high : onh
low_ = existingBars ? low :onl
close_ = existingBars ? close : onc
[O, H, L, C] = mkHA(open_, high_, low_, close_, useModif4HA, twiceHA, useModif4HA2)
if not hknAsh
O := open_
H := high_
L := low_
C := close_
upBar = C > O
upBarOpen = upBar ? O : na
upBarHigh = upBar ? H : na
upBarLow = upBar ? L : na
upBarClose = upBar ? C : na
dnBarOpen = upBar ? na : O
dnBarHigh = upBar ? na : H
dnBarLow = upBar ? na : L
dnBarClose = upBar ? na : C
lineClose = lineOnly ? C : na
if lineOnly
upBarOpen := na
upBarHigh := na
upBarLow := na
upBarClose := na
dnBarOpen := na
dnBarHigh := na
dnBarLow := na
dnBarClose := na
plotcandle(upBarOpen, upBarHigh, upBarLow, upBarClose, title = "Up candle", color = upClr, wickcolor = upClr, bordercolor = upClr) // plot up bars
plotcandle(dnBarOpen, dnBarHigh, dnBarLow, dnBarClose, title = "Down candle", color = dnClr, wickcolor = dnClr, bordercolor = dnClr) // plot dn bars
plot(lineClose, title='Line plot', color = lineClr)
|
Volume-Blended Candlesticks [QuantVue] | https://www.tradingview.com/script/jz2XG4WJ-Volume-Blended-Candlesticks-QuantVue/ | QuantVue | https://www.tradingview.com/u/QuantVue/ | 147 | 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/
// © QuantVue
//@version=5
indicator('Volume-Blended Candlesticks [QuantVue]', overlay = true)
/////////////
// inputs //
sensitivity = input.string('Normal', 'Sensitivity Level', options = ['Normal', 'More', 'Less'], tooltip = 'More sensitive will require a smaller volume threshold to change candle opacity resulting in more extreme candles. Less sensitive will require a larger volume threshold resulting in more neutral candles.')
maLen = input.int(50, 'Volume MA length')
colPrev = input.bool(false, 'Color based on Previous Close', inline = '1')
upCol = input.color(color.lime, 'Up Bar Color', inline = '2')
downCol = input.color(color.red, 'Down Bar Color', inline = '2')
showPP = input.bool(true, 'Show Pocket Pivots', inline = '3')
ppCol = input.color(color.fuchsia, '', inline = '3')
shapeLoc = input.string('Below Bar', '', options = ['Below Bar', 'Above Bar','Bottom', 'Top'], inline = '3', tooltip = 'Plots a diamond at selected location signifying a pocket pivot volume signature')
showTable = input.bool(true, 'Show Volume Info', inline = '4')
yPos = input.string('Bottom', ' ', options = ['Top', 'Middle', 'Bottom'], inline = '4')
xPos = input.string('Right', ' ', options = ['Right','Center', 'Left'], inline = '4')
textColor = input.color(color.rgb(255, 255, 255), 'Text Color', inline = '5')
bgColor = input.color(color.new(color.rgb(192, 195, 206),70), 'Background Color', inline = '5')
/////////////
// switch //
ppLoc = switch shapeLoc
'Below Bar' => location.belowbar
'Above Bar' => location.abovebar
'Top' => location.top
'Bottom' => location.bottom
senseLevel = switch sensitivity
'Normal' => 75
'More' => 25
'Less' => 125
////////////////
// variables //
var table volInfo = table.new(str.lower(yPos) + '_' + str.lower(xPos), 4, 2, color.new(color.white,100),
border_color = color.new(color.white,100), border_width = 2)
var float h10 = 0
float volSec = na
vols = array.new<float>()
projVol = float(volume)
///////////////////
// calculations //
avgVol = ta.sma(volume, maLen)
up = colPrev ? close >= close[1] : close >= open
down = colPrev ? close < close[1] : close < open
avgDollarVol = avgVol * close
upVol = close > close[1] ? volume : 0
dnVol = close < close[1] ? volume : 0
sumUp = math.sum(upVol, maLen)
sumDn = math.sum(dnVol, maLen)
upDnVolRatio = sumUp / sumDn
////////////////////
// pocket pivots //
for i = 0 to 10
if close[i] < close[i + 1]
array.push(vols, volume[i])
h10 := array.max(vols)
pocketpivot = close > close[1] and volume > h10
///////////////////////
// projected volume //
timePassed = timenow - time
timeLeft = time_close - timenow
if timeLeft > 0
volSec := (volume / timePassed)
projVol := (volume + (volSec * timeLeft))
runRate = nz(projVol / avgVol * 100) - 100
volPerChng = nz((volume / avgVol * 100) - 100)
/////////////////
// bar colors //
barUpCol = color.from_gradient(runRate, senseLevel*-1, senseLevel, color.new(upCol,99), upCol)
barDownCol = color.from_gradient(runRate, senseLevel*-1, senseLevel, color.new(downCol,99), downCol)
////////////
// plots //
plotshape(showPP and pocketpivot, 'PP', shape.diamond, ppLoc, ppCol, display = display.pane)
barcolor(up ? barUpCol : down ? barDownCol : na)
if barstate.islast and showTable
table.cell(volInfo, 0, 0, 'Volume: ' + str.tostring(volume,format.volume) + ', ' +
(runRate > 0 ? '+' + str.tostring(runRate, '#') + '%' : str.tostring(runRate, '#') + '%'),
bgcolor = bgColor, text_color = textColor)
table.cell(volInfo, 1, 0, 'Avg. Vol: ' + str.tostring(avgVol, format.volume),
bgcolor =bgColor, text_color = textColor)
table.cell(volInfo, 2, 0, 'Avg: $ Vol: ' + str.tostring(avgDollarVol, format.volume),
bgcolor =bgColor, text_color = textColor)
table.cell(volInfo, 3, 0, 'U/D Ratio: ' + str.tostring(upDnVolRatio, '#.##'), bgcolor = bgColor,
text_color = textColor)
/////////////
// alerts //
alertcondition(runRate > 100, 'Heavy Volume', '{{ticker}} Projected Above Average Volume') |
Sub-Super Script and Roman numerals Library | https://www.tradingview.com/script/WAmLr7TA-Sub-Super-Script-and-Roman-numerals-Library/ | 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
//@version=5
// ███████╗███████╗███████ ██ ███████ ███████╗
// ██╔════▒██╔════▒██╔══██╗██░╚════██░╚════██░
// █████╗ ░█████╗ ░██████╔╝██░ ███╔═╝ ███╔═╝
// ██╔══╝ ░██╔══╝ ░██╔══██╗██░██╔══╝ ██╔══╝
// ██░░ ░██░░ ░██░░ ██░██░███████╗███████╗
// ╚═╝░ ░╚═╝░ ░╚═╝░ ╚═╝╚═╝╚══════╝╚══════╝ Labz
// @description Library to transform numbers into Roman numerals / Super-Sub script / check if value is alpha or number
library("Sub_Super_Script_and_RomanNumerals_Library")
import FFriZz/FrizBug/9 as p
// @function check to see if value is a number
// @param input (string/float/int) value to check
// @returns (na) if value is NOT a number and input (string/float/int) if value is a number
export method isnumber(string input) =>
numbers = '0123456789.,'
out = ''
if str.contains(input,' ')
out := na
else
s_num = str.split(input,'')
for i in s_num
if str.contains(numbers,i)
out := input
else
out := na
break
out
export method isnumber(float input) =>
n = str.tostring(input).isnumber()
out = 0.
if not na(n)
out := str.tonumber(n)
out
export method isnumber(int input) =>
n = str.tostring(input).isnumber()
out = 0.
if not na(n)
out := str.tonumber(n)
out
// @function check a string if it is alpha(doesnt contain numbers)
// @param string string - string to check if alpha
// @returns (string) if string input does NOT contain numbers, return (na) if input string contains numbers
export method isalpha(string input) =>
out = ''
num = isnumber(input)
if na(num)
out := input
else
out := na
out
export method isalpha(float input) =>
string = str.tostring(input)
out = string.isalpha()
export method isalpha(int input) =>
string = str.tostring(input)
out = string.isalpha()
// @function convert a string's numbers from normal print to super-script [0⁰1¹2²3³4⁴5⁵6⁶7⁷8⁸9⁹]
// @param num (string/int/float) input value to transform
// @returns string of input with numbers converted to super-script
export method super(string num) =>
supers = array.from('⁰','¹','²','³','⁴','⁵','⁶','⁷','⁸','⁹')
out = str.tostring(num)
for i = 0 to 9
out := str.replace_all(out,str.tostring(i),supers.get(i))
out
export method super(float num) =>
out = str.tostring(num).super()
export method super(int num) =>
out = str.tostring(num).super()
// @function convert a string's numbers from normal print to sub-script [0₀1₁2₂3₃4₄5₅6₆7₇8₈9₉]
// @param num (string/int/float) input value to transform
// @returns string of input with numbers converted to sub-script
export method sub(string num) =>
subs = array.from('₀','₁','₂','₃','₄','₅','₆','₇','₈','₉')
out = str.tostring(num)
for i = 0 to 9
out := str.replace_all(out,str.tostring(i),subs.get(i))
out
export method sub(float num) =>
out = sub(str.tostring(num))
export method sub(int num) =>
out = sub(str.tostring(num))
// @function convert a string of numbers, float, or int
// @param num (string) input number to transform
// @param trunc (bool | false) true to truncate float value, false to show roman numerals with decimals (XX.VI)
// @returns string of roman numerals representing the input (num)
export method roman(string num,bool trunc = false) =>
numbers = array.from( 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000, 4000, 5000, 9000, 10000, 40000, 50000, 90000, 100000)
roman = array.from("I", "IV", "V", "IX", "X", "XL","L","XC", "C", "CD", "D", "CM", "M", 'Mↁ', 'ↁ', 'Mↂ', 'ↂ', 'ↂↇ', 'ↇ', 'ↂↈ', 'ↈ')
build = ''
build_d = ''
if na(num.isalpha())
a_split = str.split(str.replace_all(num,',',''),'.')
for i = 0 to a_split.size()-1
if trunc and i
break
else if i
build_d += '.'
number = str.tonumber(a_split.get(i))
n = 20
while n >= 0
div = number / numbers.get(n)
number %= numbers.get(n)
while div >= 1
switch i
0 => build += roman.get(n)
1 => build_d += roman.get(n)
div -= 1
n -= 1
build+build_d
// USAGE
// Str = str.split(str.tostring(close),'.')
// if Str.size() == 1
// Str.push('00')
// CLOSE = str.tostring(close)
// p.print(roman(str.tostring(close)),'Close price - ROMAN NUMERAL',tick = true,pos='8')
// p.print('\nSUPER = '+Str.get(0)+'.'+super(Str.get(1))+'\n SUB ='+Str.get(0)+'.'+sub(Str.get(1)),'SUPER/SUB script',tick = true,pos = '1')
// p.print('\nfloat = '+CLOSE.isnumber()+'\nalpha ='+CLOSE.isalpha(),'Close price - isnumber/isalpha',tick = true,pos = '7')
|
Liquidity Peaks | https://www.tradingview.com/script/9XASmUKy-Liquidity-Peaks/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 379 | 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/
// © QuantiLuxe
//@version=5
indicator("Liquidity Peaks", "{Ʌ} - 𝐋𝐢𝐪. 𝐏𝐞𝐚𝐤𝐬", true)
// up or down candle
red_candle = (close < open)
green_candle = (close > open)
//inputs
lookback = input.int(55,"Lookback",tooltip = "More lookback = more reacting zone, less lookback = less reacting zone",group = "Inputs")
src = input.string("Open","Source",["Body","Full","Open","Close"],group = "Inputs")
col = input.color(#bbd9fb,"Liquidity Color",group = "Color")
col_2 = input.color(color.gray,"Liquidity Formed Color",group = "Color")
col_3 = input.color(#e65100,"Liquidity Swipe",group = "Color")
extd = input.bool(false,"Display Origin Point",group = "UI Options")
mult = input.int(2,"Multiplier",tooltip = "Add weight to the future bar",group = "Inputs",minval = 1)
adjustment = input.bool(true,"Adjust Liquidity Grab",group = "UI Options")
text_c = input.color(color.rgb(238, 255, 0),title = "Volume Text Color",group = "Color")
//variables
vol = close > open ? volume : -volume
var data = array.new<float>(lookback)
var current_index = 0
var float max_vol = 0
index = 0
// main calculation
current_index += 1
array.push(data,vol)
if current_index == lookback + 1
array.clear(data)
current_index := 0
max_vol := 0
if current_index == lookback
max_vol := array.max(data)
index := array.indexof(data,array.max(data))
draw_swipe(left,top,right,bottom) =>
var box bx = na
bx_col = color.new(col_3,0)
bx := box.new(left,top,right,bottom,border_color = color.new(bx_col,100),bgcolor = color.new(bx_col,50))
draw_box(left,top,right,bottom) =>
var box bx = na
bx_col = color.new(col_2,80)
bx := box.new(left,top,right,bottom,border_color = color.new(bx_col,100),bgcolor = color.new(bx_col,90))
draw_volume(left,top,right,bottom) =>
var box bx = na
bx_col = color.new(col,50)
bx := box.new(left,top,right,bottom,bgcolor = color.new(bx_col,66),border_color = color.new(color.yellow,100),text = str.tostring(math.round(max_vol)) + " K",text_halign = text.align_right,text_color = text_c,text_size = size.auto)
var float top = na
var float bottom = na
if current_index == lookback
top := switch src
"Open" => red_candle[lookback] ? high[current_index] : open[current_index]
"Body" => red_candle[lookback] ? open[current_index] : close[current_index]
"Close" => red_candle[lookback] ? close[current_index] : high[current_index]
"Full" => high[current_index]
bottom := switch src
"Open" => red_candle[lookback] ? open[current_index] : low[current_index]
"Body" => red_candle[lookback] ? close[current_index] : open[current_index]
"Close" => red_candle[lookback] ? low[current_index] : close[current_index]
"Full" => low[current_index]
if current_index == lookback
if adjustment
top := switch src
"Open" => red_candle[lookback] ? high[current_index] + math.abs(open[current_index]-high[current_index]) : low[current_index]
"Close" => red_candle[lookback] ? low[current_index] : high[current_index] + math.abs(close[current_index] - high[current_index])
"Body" => red_candle[lookback] ? open[current_index] : close[current_index]
"Full" => high[current_index]
bottom := switch src
"Open" => red_candle[lookback] ? high[current_index] : low[current_index] - math.abs(open[current_index]-low[current_index])
"Close" => red_candle[lookback] ? low[current_index] - math.abs(close[current_index] - low[current_index]) : high[current_index]
"Body" => red_candle[lookback] ? close[current_index] : open[current_index]
"Full" => low[current_index]
num = lookback * mult
back = extd == true ? current_index : 0
if adjustment == false
draw_box( bar_index - back - 1, high[current_index + 1],bar_index + num, low[current_index + 1])
draw_volume(bar_index - back , top ,bar_index + num, bottom)
if ta.crossover(high, top)
swipe_bottom = red_candle ? low : close
swipe_top = red_candle ? close : high
draw_swipe(bar_index,swipe_top,bar_index + current_index * mult,swipe_bottom)
if ta.crossunder(low, bottom)
swipe_bottom = red_candle ? low : close
swipe_top = red_candle ? close : high
draw_swipe(bar_index,swipe_top,bar_index + current_index * mult,swipe_bottom)
if adjustment == true
top_b = high[current_index]
bottom_b = low[current_index]
draw_box( bar_index - back, top_b, bar_index + num,bottom_b)
draw_volume(bar_index - back, top , bar_index + num, bottom)
if ta.crossover(high, top_b)
swipe_bottom = red_candle ? low : close
swipe_top = red_candle ? close : high
draw_swipe(bar_index,swipe_top,bar_index + current_index * mult,swipe_bottom)
if ta.crossunder(low, bottom_b)
swipe_bottom = red_candle ? low : close
swipe_top = red_candle ? close : high
draw_swipe(bar_index,swipe_top,bar_index + current_index * mult,swipe_bottom) |
Filtered Momentum Indicator (FMI) | https://www.tradingview.com/script/0xPEyxeK-Filtered-Momentum-Indicator-FMI/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 107 | 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/
// © LeafAlgo
//@version=5
indicator("Filtered Momentum Indicator (FMI)", overlay=false)
// Calculation Inputs
momentumPeriod = input(14, "Momentum Period")
bollingerPeriod = input(20, "Bollinger Bands Period")
deviations = input(2.0, "Bollinger Bands Deviations")
signalMultiplier = input(2.0, 'Signal Comparison Multiplier', tooltip = 'To generate bull/bear signals, the F- or F+ must be greater than or equal to [this multiplier] times the value of the opposite line')
signalThreshold = input(3.0, 'Signal Value Threshold', tooltip = 'F+ or F- must be above this threshold to generate a bull/bear signal.')
// Calculate Momentum
momentum = (close / close[momentumPeriod]) * 100
// Calculate Bollinger Bands
basis = ta.sma(momentum, bollingerPeriod)
deviation = ta.stdev(momentum, bollingerPeriod)
upperBand = basis + (deviations * deviation)
lowerBand = basis - (deviations * deviation)
// Calculate Filtered Momentum
filteredPlus = upperBand - momentum
filteredMinus = momentum - lowerBand
// Colors
fmiColor = filteredMinus >= signalMultiplier*filteredPlus and filteredMinus >= signalThreshold ? color.lime : filteredPlus >= signalMultiplier*filteredMinus and filteredPlus >= signalThreshold ? color.fuchsia : color.yellow
bgcolor(color.new(fmiColor, 80))
barcolor(fmiColor)
// Plotting
plot(filteredPlus, color=color.aqua, linewidth=4, title="F+")
plot(filteredMinus, color=color.yellow, linewidth=4, title="F-")
hline(0, linewidth=2)
|
adaptive_mfi | https://www.tradingview.com/script/jemVx7Zm-adaptive-mfi/ | palitoj_endthen | https://www.tradingview.com/u/palitoj_endthen/ | 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/
// © palitoj_endthen
//@version=5
indicator(title = 'Adaptive Money Flow Index', shorttitle = 'adaptive_mfi', overlay = false)
// input
hp_period = input.int(defval = 48, title = 'High-Pass Period', group = 'Value', tooltip = 'Determines the High-Pass Period e.g. 48, 89, 125, etc')
src = input.source(defval = ohlc4, title = 'Source', group = 'Options', tooltip = 'Determines the source of input data use to compute dominant cycle, default to ohlc4')
color_type = input.string(defval = 'Solid', title = 'Color Scheme', group = 'Options', options = ['Solid', 'Normalized'], tooltip = 'Determines the color scheme of adaptive money flow index')
// check cumulative volume (tradingview)
vol = volume
cum_vol = 0.0
cum_vol += nz(vol)
if barstate.islast and cum_vol == 0
runtime.error('No volume is provided by the data vendor')
// dominant cycle: determined an applied adaptive input length with dominant cycle - Ehlers
// variable
avg_length = 3
m = 0.00
n = 0.00
x = 0.00
y = 0.09
alpha1 = 0.00
hp = 0.00
a1 = 0.00
b1 = 0.00
c1 = 0.00
c2 = 0.00
c3 = 0.00
filt = 0.00
sx = 0.00
sy = 0.00
sxx = 0.00
syy = 0.00
sxy = 0.00
max_pwr = 0.00
dominant_cycle = 0.00
// array
var corr = array.new_float(50)
var cosine_part = array.new_float(50)
var sine_part = array.new_float(50)
var sq_sum = array.new_float(50)
var r1 = array.new_float(50)
var r2 = array.new_float(50)
var pwr = array.new_float(50)
// high-pass filter cyclic components whose periods are shorter than 48 bars
pi = 2*math.asin(1)
alpha1 := (math.cos(.707*360/hp_period)+math.sin(.707*360/hp_period)-1)/math.cos(.707*360/hp_period)
hp := (1-alpha1/2)*(1-alpha1/2)*(src-2*src[1]+src[2])+2*(1-alpha1)*nz(hp[1])-(1-alpha1)*(1-alpha1)*nz(hp[2])
// smoothed with super smoother filter
a1 := math.exp(-1.414*pi/10)
b1 := 2*a1*math.cos(1.414*180/10)
c2 := b1
c3 := -a1*a1
c1 := 1-c2-c3
filt := c1*(hp+hp[1])/2+c2*nz(filt[1])+c3*nz(filt[2])
// pearson correlation for each value of lag
for lag = 0 to 48
// set the averaging length as m
m := avg_length
if avg_length == 0
m := lag
// initialize correlation sums
sx := 0.00
sy := 0.00
sxx := 0.00
syy := 0.00
sxy := 0.00
// advance samples of both data streams and sum pearson components
for count = 0 to m-1
x := filt[count]
y := filt[lag+count]
sx := sx+x
sy := sy+y
sxx := sxx+x*x
sxy := sxy+x*y
syy := syy+y*y
// compute correlation for each value of lag
if (m*sxx-sx*sx)*(m*syy-sy*sy) > 0
array.set(corr, lag, ((m*sxy-sx*sy)/math.sqrt((m*sxx-sx*sx)*(m*syy-sy*sy))))
for period = 10 to 48
array.set(cosine_part, period, 0)
array.set(sine_part, period, 0)
for n2 = 3 to 48
array.set(cosine_part, period, nz(array.get(cosine_part, period))+nz(array.get(corr, n2))*math.cos(360*n2/period))
array.set(sine_part, period, nz(array.get(sine_part, period))+nz(array.get(corr, n2))*math.sin(360*n2/period))
array.set(sq_sum, period, nz(array.get(cosine_part, period))*nz(array.get(cosine_part, period))+nz(array.get(sine_part, period))*nz(array.get(sine_part, period)))
for period2 = 10 to 48
array.set(r2, period2, nz(array.get(r1, period2)))
array.set(r1, period2, .2*nz(array.get(sq_sum, period2))*nz(array.get(sq_sum, period2))+.8*nz(array.get(r2, period2)))
// find maximum power level for normalization
max_pwr := .991*max_pwr
for period3 = 10 to 48
if nz(array.get(r1, period3)) > max_pwr
max_pwr := nz(array.get(r1, period3))
for period4 = 3 to 48
array.set(pwr, period4, nz(array.get(r1, period4))/max_pwr)
// compute the dominant cycle using the cg of the spectrum
spx = 0.00
sp = 0.00
for period5 = 10 to 48
if nz(array.get(pwr, period5)) >= .5
spx := spx+period5*nz(array.get(pwr, period5))
sp := sp+nz(array.get(pwr, period5))
if sp != 0
dominant_cycle := spx/sp
if dominant_cycle < 10
dominant_cycle := 10
if dominant_cycle > 48
dominant_cycle := 48
// money flow index
// variable
typical_price = hlc3
p_rmfi = 0.00
n_rmfi = 0.00
mfr = 0.00
mfi = 0.00
smfi = 0.00
// raw money flow index
raw_mfi = typical_price*vol
// adaptive money flow index
dc = int(dominant_cycle)
for i = 0 to dc-1
// positive money flow
if typical_price[i] > typical_price[i+1]
p_rmfi += raw_mfi[i]
// negative money flow
if typical_price[i] < typical_price[i+1]
n_rmfi += raw_mfi[i]
// money flow ratio
mfr := p_rmfi/n_rmfi
// money flow index
mfi := 100 - (100/(1+mfr))
// smoothed with super-smoother
smfi := c1*(mfi+mfi[1])/2+c2*nz(smfi[1])+c3*nz(smfi[2])
// visualize
// color scheme 2 - Normalized
high_smfi = ta.highest(smfi, dc)
low_smfi = ta.lowest(smfi, dc)
norm_smfi = (smfi-low_smfi)/(high_smfi-low_smfi)
col(x) =>
if x > .5
color.rgb(255*(2-2*x), 255, 0)
else if x < .5
color.rgb(255, 2*255*x, 0)
// color scheme
color_fin = color_type == 'Solid' ? color.maroon : col(norm_smfi)
// plot
hline_ = hline(50, color = color.new(color.blue, 50))
plot(smfi, color = color_fin, linewidth = 2)
// create alert
alert_ = norm_smfi > .5
alertcondition((not alert_[1] and alert_), title = 'Entry', message = 'Buy/Long entry detected')
alertcondition((alert_ and not alert_[1]), title = 'Close', message = 'Sell/Short entry detected')
// // strategy test
// percent_sl = input.float(defval = 3, title = 'Stop Loss', group = 'Value', tooltip = 'Determines the stop-loss percentage')
// long_condition = ta.crossover(smfi, 50)
// short_condition = ta.crossunder(smfi, 50)
// long_sl = 0.00
// long_sl := long_condition ? src*(1-percent_sl/100) : nz(long_sl[1])
// if long_condition
// strategy.entry(id = 'long', direction = strategy.long)
// if not long_condition
// strategy.exit(id = 'exit-long', from_entry = 'long', stop = long_sl)
|
Binary Option Strategy Tester with Martingale-Basic V.2 | https://www.tradingview.com/script/7iRLKHim-Binary-Option-Strategy-Tester-with-Martingale-Basic-V-2/ | tanayroy | https://www.tradingview.com/u/tanayroy/ | 144 | 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/
// © tanayroy
//@version=5
//The strategy tester works well with Binary option traded in IQ Option or other similar Platform.
indicator("Binary Option Strategy Tester with Martingale-Basic V.2[tanayroy]", shorttitle="BOST V.2",overlay = true)
gp = 'Strategy Information'
i_trade_call_put = input.string('BOTH', title='Trade Call/Put', options=['BOTH', 'CALL', 'PUT'], group=gp)
//input on martingale level
i_martingale_level = input.int(2, title='Martingale Level', minval=1, maxval=5, group=gp)
i_martingle_trade = input.string('SAME', title='Type of Trade', options=['SAME', 'OPPOSITE', 'FOLLOW CANDLE COLOR',
'OPPOSITE CANDLE COLOR'], group=gp)
//trading time
i_trading_session = input.session('0100-1000',title='Trading Session', group=gp)
i_use_session = input.bool(true, 'Use Specific Session', group=gp)
initial_investment=input.float(10.0,title="Initial Investment Per Option",minval=1.0,group=gp)
profit_percentage=input.int(80,title='Profit Percentage Offered',group=gp)
//check if in session
InSession() =>
time(timeframe.period, i_trading_session) != 0
var in_sess=false
in_sess := i_use_session ? InSession() : true
long_allowed = i_trade_call_put == 'BOTH' or i_trade_call_put == 'CALL'
short_allowed = i_trade_call_put == 'BOTH' or i_trade_call_put == 'PUT'
//check martingale way
martingale_way(call, put, type, length) =>
out = false
if call and type == 'NA'
out := close > open[length]
out
else if put and type == 'NA'
out := open[length] > close
out
else if type == 'SAME' and call
out := close > open[length]
out
else if type == 'SAME' and put
out := open[length] > close
out
else if type == 'OPPOSITE' and call
out := open[length] > close
out
else if type == 'OPPOSITE' and put
out := close > open[length]
out
else if type == 'FOLLOW CANDLE COLOR'
out := close[1] > open[1] ? close > open[length] : open[length] > close
out
else if type == 'OPPOSITE CANDLE COLOR'
out := close[1] > open[1] ? close < open[length] : open[length] < close
out
out
//variable for strategy testing
var can_buy_call = false
var can_buy_put = false
var in_martingale = false
var in_trade = false
var buy_condition = false
var sell_condition = false
var int count_call = 0
var int count_put = 0
var bool cl1win = na
var bool cl2win = na
var bool cl3win = na
var bool cl4win = na
var bool cl5win = na
var bool closs = na
var int count_cl1win = 0
var int count_cl2win = 0
var int count_cl3win = 0
var int count_cl4win = 0
var int count_cl5win = 0
var int count_closs = 0
var bool pl1win = na
var bool pl2win = na
var bool pl3win = na
var bool pl4win = na
var bool pl5win = na
var bool ploss = na
var int count_pl1win = 0
var int count_pl2win = 0
var int count_pl3win = 0
var int count_pl4win = 0
var int count_pl5win = 0
var int count_ploss = 0
var bool in_profit = false
var bool in_loss = false
var int max_loss = 0
var int consecutive_loss = 0
var int max_profit = 0
var int consecutive_profit = 0
//*****************************************************************************//
//*****************************************************************************//
//********************************PASTE YOUR STRATEGY***************************//
//*****************************************************************************//
//*****************************************************************************//
//Start From Here
//strategy Vdub Binary Options SniperVX v1 by vdubus
len = 8
src = close
out = ta.sma(src, len)
last8h = ta.highest(close, 13)
lastl8 = ta.lowest(close, 13)
bearish = ta.cross(close,out) == 1 and close[1] > close
bullish = ta.cross(close,out) == 1 and close[1] < close
channel2=false
src0 = close, len0 = 13//input(13, minval=1, title="Trend Change EMA")
ema0 = ta.ema(src0, len0)
//--Modified vyacheslav.shindin-------------------------------------------------// Signal 1
//Configured ema signal output
slow = 8
fast = 5
vh1 = ta.ema(ta.highest(math.avg(low, close), fast), 5)
vl1 = ta.ema(ta.lowest(math.avg(high, close), slow), 8)
//
e_ema1 = ta.ema(close, 1)
e_ema2 = ta.ema(e_ema1, 1)
e_ema3 = ta.ema(e_ema2, 1)
tema = 1 * (e_ema1 - e_ema2) + e_ema3
//
e_e1 = ta.ema(close, 8)
e_e2 = ta.ema(e_e1, 5)
dema = 2 * e_e1 - e_e2
signal = tema > dema ? math.max(vh1, vl1) : math.min(vh1, vl1)
//strategy for buying call
is_call=tema > dema and signal > low and (signal-signal[1] > signal[1]-signal[2])
//strategy fo selling call
is_put=tema < dema and signal < high and (signal[1]-signal > signal[2]-signal[1])
//PASTE END HERE
// is_call and is_put variable is required. assign buy logic in is_call and sell logic in is_put
//****************************YOUR STRATEGY END HERE*************************************//
//****************************KEEP THE REST CODE INTACT*************************************//
if is_call and long_allowed and in_sess
can_buy_call := true
can_buy_put := false
if is_put and short_allowed and in_sess
can_buy_call := false
can_buy_put := true
if can_buy_call and not can_buy_call[1] and not in_trade
buy_condition := true
in_trade := true
count_call += 1
else if buy_condition[1]
buy_condition := false
if can_buy_put and not can_buy_put[1] and not in_trade
sell_condition := true
in_trade := true
count_put += 1
else if sell_condition[1]
sell_condition := false
call_profit = martingale_way(true, false, 'NA', 0)
mart_call_profit = martingale_way(true, false, i_martingle_trade, 0)
put_profit = martingale_way(false, true, 'NA', 0)
mart_put_profit = martingale_way(false, true, i_martingle_trade, 0)
if i_martingale_level == 1
if buy_condition[1] and not buy_condition and in_trade and call_profit
and not sell_condition[1] and not sell_condition
count_cl1win += 1
in_trade := false
cl1win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[1] and not buy_condition and not sell_condition[1]
and not sell_condition and in_trade and not call_profit
count_closs += 1
in_trade := false
closs := true
in_profit := false
in_loss := true
buy_condition := false
sell_condition := false
can_buy_call := false
can_buy_put := false
else if i_martingale_level == 2
if buy_condition[1] and not buy_condition and in_trade and call_profit
and not sell_condition[1] and not sell_condition
count_cl1win += 1
in_trade := false
cl1win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[2] and not buy_condition[1] and not buy_condition and in_trade and mart_call_profit
and not sell_condition[1] and not sell_condition[2] and not sell_condition
count_cl2win += 1
in_trade := false
cl2win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[2] and not buy_condition[1] and not buy_condition and not sell_condition[1]
and not sell_condition[2] and not sell_condition and in_trade and not mart_call_profit
count_closs += 1
in_trade := false
closs := true
in_loss := true
in_profit := false
buy_condition := false
sell_condition := false
can_buy_call := false
can_buy_put := false
else if i_martingale_level == 3
if buy_condition[1] and not buy_condition and in_trade and call_profit and not sell_condition[1]
and not sell_condition
count_cl1win += 1
in_trade := false
cl1win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[2] and not buy_condition[1] and not buy_condition and in_trade
and mart_call_profit and not sell_condition[1]
and not sell_condition[2] and not sell_condition
count_cl2win += 1
in_trade := false
cl2win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[3] and not buy_condition[2] and not buy_condition[1] and not buy_condition
and in_trade and mart_call_profit and not sell_condition[1]
and not sell_condition[2] and not sell_condition[3] and not sell_condition
count_cl3win += 1
in_trade := false
cl3win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[3] and not buy_condition[2] and not buy_condition[1] and not buy_condition
and not sell_condition[1] and not sell_condition[2] and not sell_condition[3] and not sell_condition
and in_trade and not mart_call_profit
count_closs += 1
in_trade := false
closs := true
in_loss := true
in_profit := false
buy_condition := false
sell_condition := false
can_buy_call := false
can_buy_put := false
else if i_martingale_level == 4
if buy_condition[1] and not buy_condition and in_trade and call_profit and not sell_condition[1]
and not sell_condition
count_cl1win += 1
in_trade := false
cl1win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[2] and not buy_condition[1] and not buy_condition and in_trade and mart_call_profit
and not sell_condition[1]
and not sell_condition[2] and not sell_condition
count_cl2win += 1
in_trade := false
cl2win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[3] and not buy_condition[2] and not buy_condition[1] and not buy_condition
and in_trade and mart_call_profit and not sell_condition[1]
and not sell_condition[2] and not sell_condition[3] and not sell_condition
count_cl3win += 1
in_trade := false
cl3win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[4] and not buy_condition[3] and not buy_condition[2] and not buy_condition[1]
and not buy_condition and in_trade and mart_call_profit and not sell_condition[1]
and not sell_condition[2] and not sell_condition[3] and not sell_condition[4] and not sell_condition
count_cl4win += 1
in_trade := false
cl4win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[4] and not buy_condition[3] and not buy_condition[2] and not buy_condition[1]
and not buy_condition and not sell_condition[1] and not sell_condition[2] and not sell_condition[3]
and not sell_condition[4] and not sell_condition and in_trade and not mart_call_profit
count_closs += 1
in_trade := false
closs := true
in_loss := true
in_profit := false
buy_condition := false
sell_condition := false
can_buy_call := false
can_buy_put := false
if i_martingale_level == 5
if buy_condition[1] and not buy_condition and in_trade and call_profit and not sell_condition[1]
and not sell_condition
count_cl1win += 1
in_trade := false
cl1win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[2] and not buy_condition[1] and not buy_condition and in_trade and mart_call_profit
and not sell_condition[1]
and not sell_condition[2] and not sell_condition
count_cl2win += 1
in_trade := false
cl2win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[3] and not buy_condition[2] and not buy_condition[1] and not buy_condition and in_trade
and mart_call_profit and not sell_condition[1]
and not sell_condition[2] and not sell_condition[3] and not sell_condition
count_cl3win += 1
in_trade := false
cl3win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[4] and not buy_condition[3] and not buy_condition[2] and not buy_condition[1]
and not buy_condition and in_trade and mart_call_profit and not sell_condition[1]
and not sell_condition[2] and not sell_condition[3] and not sell_condition[4] and not sell_condition
count_cl4win += 1
in_trade := false
cl4win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[5] and not buy_condition[4] and not buy_condition[3] and not buy_condition[2]
and not buy_condition[1] and not buy_condition and not sell_condition[1] and not sell_condition[2]
and not sell_condition[3] and not sell_condition[4] and not sell_condition[5] and not sell_condition
and in_trade and mart_call_profit
count_cl5win += 1
in_trade := false
cl5win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if buy_condition[5] and not buy_condition[4] and not buy_condition[3] and not buy_condition[2]
and not buy_condition[1] and not buy_condition and not sell_condition[1] and not sell_condition[2]
and not sell_condition[3] and not sell_condition[4] and not sell_condition[5] and not sell_condition
and in_trade and not mart_call_profit
count_closs += 1
in_trade := false
closs := true
in_loss := true
in_profit := false
buy_condition := false
sell_condition := false
can_buy_call := false
can_buy_put := false
calculate_martingale_amount(previous_investment, win_ratio)=>
mart = (int(previous_investment) / win_ratio) + int(previous_investment)
if mart - math.floor(mart) >= 0.5
math.ceil(mart)
else
math.floor(mart)
if cl1win[1]
cl1win := false
if cl2win[1]
cl2win := false
if cl3win[1]
cl3win := false
if cl4win[1]
cl4win := false
if cl5win[1]
cl5win := false
if closs[1]
closs := false
if i_martingale_level == 1
if sell_condition[1] and not sell_condition and in_trade and
put_profit and not buy_condition[1] and not buy_condition
count_pl1win += 1
in_trade := false
pl1win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[1] and not sell_condition and not buy_condition[1]
and not buy_condition and in_trade and not put_profit
count_ploss += 1
in_trade := false
ploss := true
buy_condition := false
sell_condition := false
in_loss := true
in_profit := false
can_buy_call := false
can_buy_put := false
else if i_martingale_level == 2
if sell_condition[1] and not sell_condition and in_trade and put_profit and not buy_condition[1]
and not buy_condition
count_pl1win += 1
in_trade := false
pl1win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[2] and not sell_condition[1] and not sell_condition and in_trade and mart_put_profit
and not buy_condition[1]
and not buy_condition[2] and not buy_condition
count_pl2win += 1
in_trade := false
pl2win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[2] and not sell_condition[1] and not sell_condition and not buy_condition[1]
and not buy_condition[2] and not buy_condition and in_trade and not mart_put_profit
count_ploss += 1
in_trade := false
ploss := true
buy_condition := false
sell_condition := false
in_loss := true
in_profit := false
can_buy_call := false
can_buy_put := false
else if i_martingale_level == 3
if sell_condition[1] and not sell_condition and in_trade and put_profit and not buy_condition[1]
and not buy_condition
count_pl1win += 1
in_trade := false
pl1win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[2] and not sell_condition[1] and not sell_condition and in_trade
and mart_put_profit and not buy_condition[1]
and not buy_condition[2] and not buy_condition
count_pl2win += 1
in_trade := false
pl2win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[3] and not sell_condition[2] and not sell_condition[1] and not sell_condition
and in_trade and mart_put_profit and not buy_condition[1]
and not buy_condition[2] and not buy_condition[3] and not buy_condition
count_pl3win += 1
in_trade := false
pl3win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[3] and not sell_condition[2] and not sell_condition[1] and not sell_condition
and not buy_condition[1] and not buy_condition[2] and not buy_condition[3] and not buy_condition
and in_trade and not mart_put_profit
count_ploss += 1
in_trade := false
ploss := true
buy_condition := false
sell_condition := false
in_loss := true
in_profit := false
can_buy_call := false
can_buy_put := false
else if i_martingale_level == 4
if sell_condition[1] and not sell_condition and in_trade and put_profit and not buy_condition[1]
and not buy_condition
count_pl1win += 1
in_trade := false
pl1win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[2] and not sell_condition[1] and not sell_condition and in_trade and mart_put_profit
and not buy_condition[1]
and not buy_condition[2] and not buy_condition
count_pl2win += 1
in_trade := false
pl2win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[3] and not sell_condition[2] and not sell_condition[1] and not sell_condition and in_trade
and mart_put_profit and not buy_condition[1]
and not buy_condition[2] and not buy_condition[3] and not buy_condition
count_pl3win += 1
in_trade := false
pl3win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[4] and not sell_condition[3] and not sell_condition[2] and not sell_condition[1]
and not sell_condition
and in_trade and mart_put_profit and not buy_condition[1]
and not buy_condition[2] and not buy_condition[3] and not buy_condition[4] and not buy_condition
count_pl4win += 1
in_trade := false
pl4win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[4] and not sell_condition[3] and not sell_condition[2] and not sell_condition[1]
and not sell_condition and not buy_condition[1] and not buy_condition[2] and not buy_condition[3]
and not buy_condition[4] and not buy_condition and in_trade and not mart_put_profit
count_ploss += 1
in_trade := false
ploss := true
buy_condition := false
sell_condition := false
in_loss := true
in_profit := false
can_buy_call := false
can_buy_put := false
else if i_martingale_level == 5
if sell_condition[1] and not sell_condition and in_trade and put_profit and not buy_condition[1]
and not buy_condition
count_pl1win += 1
in_trade := false
pl1win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[2] and not sell_condition[1] and not sell_condition and in_trade and mart_put_profit
and not buy_condition[1]
and not buy_condition[2] and not buy_condition
count_pl2win += 1
in_trade := false
pl2win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[3] and not sell_condition[2] and not sell_condition[1] and not sell_condition and in_trade
and mart_put_profit and not buy_condition[1]
and not buy_condition[2] and not buy_condition[3] and not buy_condition
count_pl3win += 1
in_trade := false
pl3win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[4] and not sell_condition[3] and not sell_condition[2] and not sell_condition[1]
and not sell_condition and in_trade and mart_put_profit and not buy_condition[1]
and not buy_condition[2] and not buy_condition[3] and not buy_condition[4] and not buy_condition
count_pl4win += 1
in_trade := false
pl4win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[5] and not sell_condition[4] and not sell_condition[3] and not sell_condition[2]
and not sell_condition[1] and not sell_condition and in_trade and mart_put_profit and not buy_condition[1]
and not buy_condition[2] and not buy_condition[3] and not buy_condition[4] and not buy_condition[5]
and not buy_condition
count_pl5win += 1
in_trade := false
pl5win := true
buy_condition := false
sell_condition := false
in_profit := true
in_loss := false
can_buy_call := false
can_buy_put := false
else if sell_condition[5] and not sell_condition[4] and not sell_condition[3] and not sell_condition[2]
and not sell_condition[1] and not sell_condition and not buy_condition[1] and not buy_condition[2]
and not buy_condition[3] and not buy_condition[4] and not buy_condition[5] and not buy_condition
and in_trade and not mart_put_profit
count_ploss += 1
in_trade := false
ploss := true
buy_condition := false
sell_condition := false
in_loss := true
in_profit := false
can_buy_call := false
can_buy_put := false
if in_profit
max_profit += 1
max_loss := 0
in_profit := false
in_loss := false
if in_loss
max_loss += 1
max_profit := 0
in_loss := false
in_profit := false
if max_profit > consecutive_profit
consecutive_profit := max_profit
if max_loss > consecutive_loss
consecutive_loss := max_loss
if pl1win[1]
pl1win := false
if pl2win[1]
pl2win := false
if pl3win[1]
pl3win := false
if pl4win[1]
pl4win := false
if pl5win[1]
pl5win := false
if ploss[1]
ploss := false
var label lx=na
plotshape(buy_condition,title="Call",style = shape.triangleup,location = location.belowbar,
color=color.new(color.teal, 0))
plotshape(sell_condition,title="Put",style = shape.triangledown,location = location.abovebar,
color=color.new(color.maroon, 0))
plotchar(cl1win ,title="Call Level 1 Char", char='1', location=location.abovebar)
plotchar(cl2win ,title="Call Level 2 Char", char='2', location=location.abovebar,offset=0)
plotchar(cl3win ,title="Call Level 3 Char", char='3', location=location.abovebar,offset=0)
plotchar(cl4win ,title="Call Level 4 Char", char='4', location=location.abovebar,offset=0)
plotchar(cl5win ,title="Call Level 5 Char", char='5', location=location.abovebar,offset=0)
plotchar(closs ,title="Call Loss Char", char='L', location=location.abovebar,color = color.new(color.red,0))
plotchar(pl1win ,title="Put Level 1 Char", char='1', location=location.belowbar)
plotchar(pl2win ,title="Put Level 2 Char", char='2', location=location.belowbar,offset=0)
plotchar(pl3win ,title="Put Level 3 Char", char='3', location=location.belowbar,offset=0)
plotchar(pl4win ,title="Put Level 4 Char", char='4', location=location.belowbar,offset=0)
plotchar(pl5win ,title="Put Level 5 Char", char='5', location=location.belowbar,offset=0)
plotchar(ploss ,title="Put Loss L", char='L', location=location.belowbar,color = color.new(color.red,0))
var table _table = table.new(position.top_right, 3, 9, border_color=color.black, border_width=2)
var table _table2 = table.new(position.bottom_left, 3, 8, border_color=color.black, border_width=2)
var table _table3 = table.new(position.bottom_right, 3, 5, border_color=color.black, border_width=2)
alertcondition(condition=is_call,
title= " BOST Buy",
message='Buy alert triggered'
)
alertcondition(condition=is_put,title="BOST Sell",
message='Sell alert triggered'
)
if barstate.islast
table.cell(_table, 0, 0, 'Number of bar Tested', text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 1, 0, str.tostring(bar_index), text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 2, 0, '100%', text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 0, 1, 'Number of Call', text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 1, 1, str.tostring(count_call), text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 2, 1, str.tostring(count_call / bar_index * 100, '#.##'),
text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 0, 2, 'Level 1 Win', text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 1, 2, str.tostring(count_cl1win), text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 2, 2, str.tostring(count_cl1win / count_call * 100, '#.##'), text_color=color.white,
bgcolor=#1848CC)
table.cell(_table, 0, 3, 'Level 2 Win', text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 1, 3, str.tostring(count_cl2win), text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 2, 3, str.tostring(count_cl2win / count_call * 100, '#.##'), text_color=color.white,
bgcolor=#1848CC)
table.cell(_table, 0, 4, 'Level 3 Win', text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 1, 4, str.tostring(count_cl3win), text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 2, 4, str.tostring(count_cl3win / count_call * 100, '#.##'), text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 0, 5, 'Level 4 Win', text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 1, 5, str.tostring(count_cl4win), text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 2, 5, str.tostring(count_cl4win / count_call * 100, '#.##'), text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 0, 6, 'Level 5 Win', text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 1, 6, str.tostring(count_cl5win), text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 2, 6, str.tostring(count_cl5win / count_call * 100, '#.##'), text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 0, 7, 'Total Call Profit', text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 1, 7, str.tostring(count_cl1win + count_cl2win + count_cl3win + count_cl4win + count_cl5win), text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 2, 7, str.tostring((count_cl1win + count_cl2win + count_cl3win + count_cl4win + count_cl5win) / count_call * 100, '#.##'), text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 0, 8, 'Loss', text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 1, 8, str.tostring(count_closs), text_color=color.white, bgcolor=#1848CC)
table.cell(_table, 2, 8, str.tostring(count_closs / count_call * 100, '#.##'), text_color=color.white, bgcolor=#1848CC)
table.cell(_table2, 0, 0, 'Number of Put', text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 1, 0, str.tostring(count_put), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 2, 0, str.tostring(count_put / bar_index * 100, '#.##'), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 0, 1, 'Level 1 Win', text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 1, 1, str.tostring(count_pl1win), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 2, 1, str.tostring(count_pl1win / count_put * 100, '#.##'), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 0, 2, 'Level 2 Win', text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 1, 2, str.tostring(count_pl2win), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 2, 2, str.tostring(count_pl2win / count_put * 100, '#.##'), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 0, 3, 'Level 3 Win', text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 1, 3, str.tostring(count_pl3win), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 2, 3, str.tostring(count_pl3win / count_put * 100, '#.##'), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 0, 4, 'Level 4 Win', text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 1, 4, str.tostring(count_pl4win), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 2, 4, str.tostring(count_pl4win / count_put * 100, '#.##'), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 0, 5, 'Level 5 Win', text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 1, 5, str.tostring(count_pl5win), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 2, 5, str.tostring(count_pl5win / count_put * 100, '#.##'), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 0, 6, 'Total Put Profit', text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 1, 6, str.tostring(count_pl1win + count_pl2win + count_pl3win + count_pl4win + count_pl5win), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 2, 6, str.tostring((count_pl1win + count_pl2win + count_pl3win + count_pl4win + count_pl5win) / count_put * 100, '#.##'), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 0, 7, 'Loss', text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 1, 7, str.tostring(count_ploss), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table2, 2, 7, str.tostring(count_ploss / count_put * 100, '#.##'), text_color=color.white, bgcolor=#ff4a68)
table.cell(_table3, 0, 0, 'Profit in a row', text_color=color.white, bgcolor=#056b60)
table.cell(_table3, 1, 0, str.tostring(consecutive_profit), text_color=color.white, bgcolor=#056b60)
table.cell(_table3, 2, 0, str.tostring(consecutive_profit / (count_call + count_put) * 100, '#.##'), text_color=color.white, bgcolor=#056b60)
table.cell(_table3, 0, 1, 'Loss in a row', text_color=color.white, bgcolor=#c71c69)
table.cell(_table3, 1, 1, str.tostring(consecutive_loss), text_color=color.white, bgcolor=#c71c69)
table.cell(_table3, 2, 1, str.tostring(consecutive_loss / (count_call + count_put) * 100, '#.##'), text_color=color.white, bgcolor=#c71c69)
tp=(((count_pl1win + count_pl2win + count_pl3win + count_pl4win + count_pl5win)+
(count_cl1win + count_cl2win + count_cl3win + count_cl4win + count_cl5win))*initial_investment)*(profit_percentage/100)
table.cell(_table3, 0, 2, 'Total Profit', text_color=color.white, bgcolor=#c71c69)
table.cell(_table3, 1, 2, '$'+str.tostring(tp,'#.##'), text_color=color.white, bgcolor=#c71c69)
table.cell(_table3, 2, 2, '-', text_color=color.white, bgcolor=#c71c69)
amt2=calculate_martingale_amount(initial_investment, (profit_percentage/100))
amt3=calculate_martingale_amount(amt2, (profit_percentage/100))+1
amt4=calculate_martingale_amount(amt3, (profit_percentage/100))+1
amt5=calculate_martingale_amount(amt4, (profit_percentage/100))+1
tl=0.0
if i_martingale_level==1
tl:=(count_ploss+count_closs)*initial_investment
else if i_martingale_level==2
tl:=(count_ploss+count_closs)*(initial_investment+amt2)
else if i_martingale_level==3
tl:=(count_ploss+count_closs)*(initial_investment+amt2+amt3)
else if i_martingale_level==4
tl:=(count_ploss+count_closs)*(initial_investment+amt2+amt3+amt4)
else if i_martingale_level==5
tl:=(count_ploss+count_closs)*(initial_investment+amt2+amt3+amt4+amt5)
table.cell(_table3, 0, 3, 'Total Loss', text_color=color.white, bgcolor=#c71c69)
table.cell(_table3, 1, 3, '$'+str.tostring(tl*1,'#.##'), text_color=color.white, bgcolor=#c71c69)
table.cell(_table3, 2, 3, str.tostring(initial_investment)+', '+str.tostring(amt2)
+', '+str.tostring(amt3)+',\n'+str.tostring(amt4)+', '+str.tostring(amt5), text_color=color.white, bgcolor=#c71c69)
np=tp-tl
table.cell(_table3, 0, 4, 'Net PL', text_color=color.white, bgcolor=#c71c69)
table.cell(_table3, 1, 4, '$'+str.tostring(np), text_color=color.white, bgcolor=#c71c69)
table.cell(_table3, 2, 4, '-', text_color=color.white, bgcolor=#c71c69)
|
Webby's RSI 2.0 | https://www.tradingview.com/script/atuLQ8ZN-Webby-s-RSI-2-0/ | Amphibiantrading | https://www.tradingview.com/u/Amphibiantrading/ | 233 | 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/
// © Amphibiantrading
//@version=5
indicator("Webby RSI 2.0")
//constants
EMA21 = ta.ema(close,21)
SMA10 = ta.sma(close,10)
//inputs
atrLen = input.int(50, 'Atr Length')
osLevel = input.int(3, 'Stretched Level')
posCol = input.color(color.green, 'Above 21 Color')
negCol = input.color(color.red, 'Below 21 Color')
maCol = input.color(color.orange, 'Moving Average Extension Color')
//atr
atr = ta.atr(50)
// vs 21 & 10
lowV21 = low - EMA21
highV21 = EMA21 - high
highV10 = high - SMA10
//calculations
rsiPos = lowV21 / atr
rsiNeg = highV21 / atr
smaPos = highV10 / atr
//plots
plot(rsiPos > 0 ? rsiPos : na, 'ATR > 21', posCol, 2, plot.style_histogram)
plot(rsiNeg > 0 ? rsiNeg : na, 'ATR < 21', negCol, 2, plot.style_histogram)
hline(osLevel, 'Extended Level', color.red, hline.style_solid, 2)
plot(smaPos > 0 ? smaPos : na, 'SMA Extension', maCol, 2, plot.style_linebr)
|
@tk · fractal rsi levels | https://www.tradingview.com/script/NPkqgXL6-tk-fractal-rsi-levels/ | gabrielrtakeda | https://www.tradingview.com/u/gabrielrtakeda/ | 57 | 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/
// © gabrielrtakeda
//@version=5
indicator(title="@tk · fractal rsi levels", overlay=true)
//
// <import_statements>
//
import gabrielrtakeda/tk/1 as tk
//
// <constant_declarations>
//
MINUTE = 60
HOUR = 60 * MINUTE
DAY = 24 * HOUR
WEEK = 7 * DAY
MONTH = 4 * WEEK
TRANSPARENT = color.rgb(0, 0, 0, 100)
string FRACTAL_RSI_LEVEL_COLOR_HINT = 'This color will be applied for all fractal RSI Levels. The data that will differ from each other is the line\'s label with timeframe `period` on each one.'
string LABELS_SHOW_PRICE_SCALE_HINT = 'Enable this option to see labels on price scale.'
string LABELS_SHOW_PRICE_RAY_HINT = 'Enable this option to see fractal RSI levels prices on fractal rays respectively.'
string FRACTAL_RAY_VISIBILITY_RULE_HINT = 'When you choose the `15m` option, the fractal ray will be visible only when the current timeframe was less than or equals to 15 minutes. Condition: `if tf != CURRENT_TIMEFRAME and tf <= CHOSEN_OPTION`.'
DEFAULT_TABLE_SIZE = size.small
//
// <inputs>
//
string GROUP_GENERAL = 'General'
string textSizeInput = input.string(title='Text Size', defval=DEFAULT_TABLE_SIZE, options=[size.tiny, size.small, size.normal, size.large], group=GROUP_GENERAL)
string GROUP_RSI_LEVELS = 'RSI Levels · Settings'
int preOversoldLevelInput = input.int(33, 'Pre-oversold Level', minval=1, maxval=49, group=GROUP_RSI_LEVELS)
int preOverboughtLevelInput = input.int(67, 'Pre-overbought Level', minval=51, maxval=100, group=GROUP_RSI_LEVELS)
bool showPreOverLevelsInput = input.bool(true, 'Show "Pre-over" Levels.', tooltip='pre-oversold / pre-overbought', group=GROUP_RSI_LEVELS)
string GROUP_FRACTAL_SETTINGS = 'Fractal Rays · Settings'
int fractalRsiLengthInput = input.int(14, 'Length', minval=1, group=GROUP_FRACTAL_SETTINGS)
float fractalRsiSourceInput = input.source(close, 'Source', group=GROUP_FRACTAL_SETTINGS)
string GROUP_FRACTAL_RAYS = 'Fractal Rays · Style'
color fractalRsiRayColorInput = input.color(color.rgb(187, 74, 207), 'Ray Color', tooltip=FRACTAL_RSI_LEVEL_COLOR_HINT, group=GROUP_FRACTAL_RAYS)
string fractalRsiRayStyleInput = input.string(line.style_dotted, 'Ray Style', options=[line.style_solid, line.style_dashed, line.style_dotted], group=GROUP_FRACTAL_RAYS)
int fractalRsiRayLengthInput = input.int(15, 'Ray Length', group=GROUP_FRACTAL_RAYS)
string GROUP_FRACTAL_OVERSOLD = 'Fractal Rays · Oversold'
int fractalRsiOversoldLvlInput = input.int(30, 'Oversold Level', minval=1, group=GROUP_FRACTAL_OVERSOLD)
string fractalRsiOversoldPrefixInput = input.string(title='Oversold Prefix', defval='🚀', group=GROUP_FRACTAL_OVERSOLD)
string fractalRsiOversoldSuffixInput = input.string(title='Oversold Suffix', defval='', group=GROUP_FRACTAL_OVERSOLD)
string GROUP_FRACTAL_OVERBOUGHT = 'Fractal Rays · Overbought'
int fractalRsiOverboughtLvlInput = input.int(70, 'Overbought Level', minval=1, group=GROUP_FRACTAL_OVERBOUGHT)
string fractalRsiOverboughtPrefixInput = input.string(title='Overbought Prefix', defval='🐻', group=GROUP_FRACTAL_OVERBOUGHT)
string fractalRsiOverboughtSuffixInput = input.string(title='Overbought Suffix', defval='', group=GROUP_FRACTAL_OVERBOUGHT)
string GROUP_FRACTAL_VISIBILITY_RULES = 'Fractal Rays · Visiblity Rules'
string fractalRayVisRuleInput_1m = input.string('15m', '· for `1m` fractal', options=['hidden', '1m', '5m', '15m', '1h', '4h', '12h', 'D', 'W'], tooltip=FRACTAL_RAY_VISIBILITY_RULE_HINT, group=GROUP_FRACTAL_VISIBILITY_RULES)
string fractalRayVisRuleInput_5m = input.string('1h', '· for `5m` fractal', options=['hidden', '1m', '5m', '15m', '1h', '4h', '12h', 'D', 'W'], tooltip=FRACTAL_RAY_VISIBILITY_RULE_HINT, group=GROUP_FRACTAL_VISIBILITY_RULES)
string fractalRayVisRuleInput_15m = input.string('4h', '· for `15m` fractal', options=['hidden', '1m', '5m', '15m', '1h', '4h', '12h', 'D', 'W'], tooltip=FRACTAL_RAY_VISIBILITY_RULE_HINT, group=GROUP_FRACTAL_VISIBILITY_RULES)
string fractalRayVisRuleInput_1h = input.string('D', '· for `1h` fractal', options=['hidden', '1m', '5m', '15m', '1h', '4h', '12h', 'D', 'W'], tooltip=FRACTAL_RAY_VISIBILITY_RULE_HINT, group=GROUP_FRACTAL_VISIBILITY_RULES)
string fractalRayVisRuleInput_4h = input.string('W', '· for `4h` fractal', options=['hidden', '1m', '5m', '15m', '1h', '4h', '12h', 'D', 'W'], tooltip=FRACTAL_RAY_VISIBILITY_RULE_HINT, group=GROUP_FRACTAL_VISIBILITY_RULES)
string fractalRayVisRuleInput_12h = input.string('W', '· for `12h` fractal', options=['hidden', '1m', '5m', '15m', '1h', '4h', '12h', 'D', 'W'], tooltip=FRACTAL_RAY_VISIBILITY_RULE_HINT, group=GROUP_FRACTAL_VISIBILITY_RULES)
string fractalRayVisRuleInput_1D = input.string('W', '· for `1D` fractal', options=['hidden', '1m', '5m', '15m', '1h', '4h', '12h', 'D', 'W'], tooltip=FRACTAL_RAY_VISIBILITY_RULE_HINT, group=GROUP_FRACTAL_VISIBILITY_RULES)
string fractalRayVisRuleInput_1W = input.string('W', '· for `1W` fractal', options=['hidden', '1m', '5m', '15m', '1h', '4h', '12h', 'D', 'W'], tooltip=FRACTAL_RAY_VISIBILITY_RULE_HINT, group=GROUP_FRACTAL_VISIBILITY_RULES)
string GROUP_LABELS = 'Labels'
bool showLabelsPriceScaleInput = input.bool(false, 'Show Labels on Price Scale.', tooltip=LABELS_SHOW_PRICE_SCALE_HINT, group=GROUP_LABELS)
bool showPriceRayInput = input.bool(false, 'Show Price on Fractal Rays.', tooltip=LABELS_SHOW_PRICE_RAY_HINT, group=GROUP_LABELS)
//
// <function_declarations>
//
// @function Converts the fractal rays timeframe visibility rule label to timestamp int.
// @param string visibilityRule Fractal ray visibility rule label.
// @returns int Fractal ray visibility rule timestamp.
fn_fractalVisibilityRule(string visibilityRule) =>
int ms = 1
if visibilityRule == 'hidden'
ms := 1
else if visibilityRule == '1m'
ms := 1 * MINUTE
else if visibilityRule == '5m'
ms := 5 * MINUTE
else if visibilityRule == '15m'
ms := 15 * MINUTE
else if visibilityRule == '1h'
ms := 1 * HOUR
else if visibilityRule == '4h'
ms := 4 * HOUR
else if visibilityRule == '12h'
ms := 12 * HOUR
else if visibilityRule == 'D'
ms := 1 * DAY
else if visibilityRule == 'W'
ms := 1 * WEEK
ms
// @function Requests fractal data based on `period` for a given expression.
// @param string period Timeframe period for the desired fractal.
// @param mixed expression Security expression that will be applied for calculation.
// @returns mixed A result determined by expression.
fn_requestFractal(string period, expression) =>
request.security(syminfo.tickerid, period, expression, gaps=barmerge.gaps_off)
// @function Plots ray after chart bars for the current time.
// @param float y Value in price scale for ray's vertical positioning.
// @param string label Text that will be displayed as label.
// @param color color The color of both, ray and text.
// @param int length The length of the ray in bars count. (default: 12)
// @returns void This function only plots the elements into the chart
fn_plotRay(float y, string label, color color, int length=12) =>
lb = label.new(x=bar_index + length, y=y, text=label, color=color.rgb(0, 0, 0, 100), textcolor=color, style=label.style_label_left, size=textSizeInput)
ln = line.new(x1=bar_index, y1=y, x2=label.get_x(lb) + 1, y2=y, style=fractalRsiRayStyleInput, color=color)
label.delete(lb[1])
line.delete(ln[1])
// @function Plots RSI Levels ray after chart bars for the current time.
// @param simple string period Timeframe period.
// @param simple int level Relative Strength Index level.
// @param color color The color of both, ray and label text.
// @returns void This function only plots the elements into the chart
fn_plotRsiLevelRay(simple string period, simple int level, color color) =>
fractalRsiUpLvl = fn_requestFractal(period, tk.rsiUp())
fractalRsiDownLvl = fn_requestFractal(period, tk.rsiDown())
hasFractalRsiLevel = not na(fractalRsiUpLvl) and not na(fractalRsiDownLvl)
rsiLevel = tk.rsiLevel(level, fractalRsiSourceInput, fractalRsiLengthInput, fractalRsiUpLvl, fractalRsiDownLvl)
prefix = level < 50 ? fractalRsiOversoldPrefixInput : fractalRsiOverboughtPrefixInput
suffix = level < 50 ? fractalRsiOversoldSuffixInput : fractalRsiOverboughtSuffixInput
priceLabel = showPriceRayInput ? str.format(' · {0,number,' + str.tostring(syminfo.mintick) + '}', rsiLevel) : ''
fn_plotRay(hasFractalRsiLevel ? rsiLevel : na, prefix + ' ' + tk.labelizeTimeFrame(period) + priceLabel + ' ' + suffix , color, length=fractalRsiRayLengthInput)
//
// <calculations>
//
tf = timeframe.in_seconds()
// upperband
LVL_80 = tk.rsiLevel(80)
LVL_78 = tk.rsiLevel(78)
LVL_76 = tk.rsiLevel(76)
LVL_74 = tk.rsiLevel(74)
LVL_72 = tk.rsiLevel(72)
LVL_70 = tk.rsiLevel(70)
PRE_OVERBOUGHT_LVL = tk.rsiLevel(preOverboughtLevelInput)
// lowerband
PRE_OVERSOLD_LVL = tk.rsiLevel(preOversoldLevelInput)
LVL_30 = tk.rsiLevel(30)
LVL_28 = tk.rsiLevel(28)
LVL_26 = tk.rsiLevel(26)
LVL_24 = tk.rsiLevel(24)
LVL_22 = tk.rsiLevel(22)
LVL_20 = tk.rsiLevel(20)
//
// <strategy_calls>
//
//
// <visuals>
//
// options
labelDisplay = showLabelsPriceScaleInput ? display.all : display.pane
// upperband
PLOT_80 = plot(LVL_80, title="Level 80", color=color.new(color.purple, 65), linewidth=2, display=labelDisplay)
PLOT_78 = plot(LVL_78, title="Level 78", color=color.new(color.purple, 75), linewidth=1, display=labelDisplay)
PLOT_76 = plot(LVL_76, title="Level 76", color=color.new(color.purple, 75), linewidth=1, display=labelDisplay)
PLOT_74 = plot(LVL_74, title="Level 74", color=color.new(color.purple, 75), linewidth=1, display=labelDisplay)
PLOT_72 = plot(LVL_72, title="Level 72", color=color.new(color.purple, 75), linewidth=1, display=labelDisplay)
PLOT_70 = plot(LVL_70, title="Level 70 · Overbought", color=color.new(color.purple, 20), linewidth=1, display=labelDisplay)
fill(PLOT_80, PLOT_70, title="Upperband Background", color=color.new(color.purple, 93))
// lowerband
PLOT_30 = plot(LVL_30, title="Level 30 · Oversold", color=color.new(color.purple, 20), linewidth=1, display=labelDisplay)
PLOT_28 = plot(LVL_28, title="Level 28", color=color.new(color.purple, 75), linewidth=1, display=labelDisplay)
PLOT_26 = plot(LVL_26, title="Level 26", color=color.new(color.purple, 75), linewidth=1, display=labelDisplay)
PLOT_24 = plot(LVL_24, title="Level 24", color=color.new(color.purple, 75), linewidth=1, display=labelDisplay)
PLOT_22 = plot(LVL_22, title="Level 22", color=color.new(color.purple, 75), linewidth=1, display=labelDisplay)
PLOT_20 = plot(LVL_20, title="Level 20", color=color.new(color.purple, 65), linewidth=2, display=labelDisplay)
fill(PLOT_30, PLOT_20, title="Lowerband Background", color=color.new(color.purple, 93))
// 'pre-over'
PRE_OVERBOUGHT_PLOT = plot(showPreOverLevelsInput ? PRE_OVERBOUGHT_LVL : na, title="Pre-overbought Level", color=color.new(color.white, 95), linewidth=1, display=display.pane)
PRE_OVERSOLD_PLOT = plot(showPreOverLevelsInput ? PRE_OVERSOLD_LVL : na, title="Pre-oversold Level", color=color.new(color.white, 95), linewidth=1, display=display.pane)
fill(PRE_OVERBOUGHT_PLOT, PLOT_70, title="Pre-overbought Background", color=color.new(color.white, 98))
fill(PRE_OVERSOLD_PLOT, PLOT_30, title="Pre-oversold Background", color=color.new(color.white, 98))
//
// fractal rsi levels
//
bool visibilityRule_1m = tf != 1 * MINUTE and tf <= fn_fractalVisibilityRule(fractalRayVisRuleInput_1m)
fn_plotRsiLevelRay('1', fractalRsiOversoldLvlInput, visibilityRule_1m ? fractalRsiRayColorInput : TRANSPARENT)
fn_plotRsiLevelRay('1', fractalRsiOverboughtLvlInput, visibilityRule_1m ? fractalRsiRayColorInput : TRANSPARENT)
bool visibilityRule_5m = tf != 5 * MINUTE and tf <= fn_fractalVisibilityRule(fractalRayVisRuleInput_5m)
fn_plotRsiLevelRay('5', fractalRsiOversoldLvlInput, visibilityRule_5m ? fractalRsiRayColorInput : TRANSPARENT)
fn_plotRsiLevelRay('5', fractalRsiOverboughtLvlInput, visibilityRule_5m ? fractalRsiRayColorInput : TRANSPARENT)
bool visibilityRule_15m = tf != 15 * MINUTE and tf <= fn_fractalVisibilityRule(fractalRayVisRuleInput_15m)
fn_plotRsiLevelRay('15', fractalRsiOversoldLvlInput, visibilityRule_15m ? fractalRsiRayColorInput : TRANSPARENT)
fn_plotRsiLevelRay('15', fractalRsiOverboughtLvlInput, visibilityRule_15m ? fractalRsiRayColorInput : TRANSPARENT)
bool visibilityRule_1h = tf != 1 * HOUR and tf <= fn_fractalVisibilityRule(fractalRayVisRuleInput_1h)
fn_plotRsiLevelRay('60', fractalRsiOversoldLvlInput, visibilityRule_1h ? fractalRsiRayColorInput : TRANSPARENT)
fn_plotRsiLevelRay('60', fractalRsiOverboughtLvlInput, visibilityRule_1h ? fractalRsiRayColorInput : TRANSPARENT)
bool visibilityRule_4h = tf != 4 * HOUR and tf <= fn_fractalVisibilityRule(fractalRayVisRuleInput_4h)
fn_plotRsiLevelRay('240', fractalRsiOversoldLvlInput, visibilityRule_4h ? fractalRsiRayColorInput : TRANSPARENT)
fn_plotRsiLevelRay('240', fractalRsiOverboughtLvlInput, visibilityRule_4h ? fractalRsiRayColorInput : TRANSPARENT)
bool visibilityRule_12h = tf != 12 * HOUR and tf <= fn_fractalVisibilityRule(fractalRayVisRuleInput_12h)
fn_plotRsiLevelRay('720', fractalRsiOversoldLvlInput, visibilityRule_12h ? fractalRsiRayColorInput : TRANSPARENT)
fn_plotRsiLevelRay('720', fractalRsiOverboughtLvlInput, visibilityRule_12h ? fractalRsiRayColorInput : TRANSPARENT)
bool visibilityRule_1D = tf != 1 * DAY and tf <= fn_fractalVisibilityRule(fractalRayVisRuleInput_1D)
fn_plotRsiLevelRay('D', fractalRsiOversoldLvlInput, visibilityRule_1D ? fractalRsiRayColorInput : TRANSPARENT)
fn_plotRsiLevelRay('D', fractalRsiOverboughtLvlInput, visibilityRule_1D ? fractalRsiRayColorInput : TRANSPARENT)
bool visibilityRule_1W = tf != 1 * WEEK and tf <= fn_fractalVisibilityRule(fractalRayVisRuleInput_1W)
fn_plotRsiLevelRay('W', fractalRsiOversoldLvlInput, visibilityRule_1W ? fractalRsiRayColorInput : TRANSPARENT)
fn_plotRsiLevelRay('W', fractalRsiOverboughtLvlInput, visibilityRule_1W ? fractalRsiRayColorInput : TRANSPARENT)
//
// HUD
//
// hudInstance = tk.hudInit()
// if tk.isHudReady()
// tk.hud(hudInstance, array.from('debug', str.tostring(fn_fractalVisibilityRule(fractalRayVisRuleInput_1m))))
//
// <alerts>
//
|
AIR Vortex ADX | https://www.tradingview.com/script/joeg05SX-AIR-Vortex-ADX/ | alphaXiom | https://www.tradingview.com/u/alphaXiom/ | 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/
// ╭━━╮╱╱╱╱╱╱╭╮╱╱╱╭━┳╮
// ┃╭╮┣━┳━╮╭┳┫╰┳━╮┃━┫╰╮
// ┃╭╮┃┻┫╋╰┫╭┫╋┃╋╰╋━┃┃┃
// ╰━━┻━┻━━┻╯╰━┻━━┻━┻┻╯ @ Woody_Bearbash
//@version=5
indicator('AIR ADX of Vortex', 'AIR Vortex ADX')
var M1 = 'Urban'
var M2 = 'Night'
var M3 = 'Earth'
var M4 = 'Classic'
var M5 = 'Wood'
var M6 = 'Pop'
var M7 = 'Mono'
length = input.int(34, minval=2, maxval=499, title='Length', group = 'Vortex', inline='1')
threshold = input.float(0.2, minval=0, maxval=1.0, step=0.025, title='Threshold', group = 'Vortex', inline='1')
smoothingMode = input.string('Super Smoother', 'Smoothing', options=['Hann Window', 'Super Smoother', 'Wilders', 'None'], group='Vortex', inline='4')
smoothing = input.int(9, minval=2, title='Length', group = 'Vortex', inline='4')
var string GRP_RF = '══════ Range mix ══════'
atrActive = input.bool(true, 'ATR,', inline='42', group=GRP_RF)
atrMult = input.float(1.0, 'Mult', step=0.1, inline='42', group=GRP_RF)
atr_move = input.string('Super Smoother', 'MA', options=['Hann Window', 'Super Smoother', 'Wilders', 'None'], group=GRP_RF, inline='42')
pipActive = input.bool(true, 'IR,', inline='43', group=GRP_RF)
pipMult = input.float(0.25, 'Mult', step=0.05, inline='43', group=GRP_RF)
spacer_chop = input.int(17, '%', inline='43', group=GRP_RF, tooltip = 'IR (Interpercentile range) is to AIR (Average IR) what TR (True range) is to ATR (Average TR)')
airActive = input.bool(false, 'AIR,', inline='44', group=GRP_RF)
airMult = input.float(0.3, 'Mult', step=0.1, inline='44', group=GRP_RF)
air_move = input.string('Hann Window', 'MA', options=['Hann Window', 'Super Smoother', 'Wilders', 'None'], group=GRP_RF, inline='44')
percent_rng = input.int(26, '%', inline='44', group=GRP_RF)
var string GRP_RSI = '══════ Trendless RSI filter ══════'
rsi_threshold = input.int(6, 'RSI centre-cancel theshold', minval = 0, inline = 'r', group = GRP_RSI)
rsi_len = input.int(14, 'Length', inline = 'r', group = GRP_RSI, tooltip = 'RSI centres around 50, hence a threshold value of 6 cancels ranging RSI between 44 & 56')
var string GRP_UI = '══════ UI ══════'
the_m = input.string(M4, "Theme", options = [M1, M2, M3, M4, M5, M6, M7], inline= 'ez', group=GRP_UI)
switch_col = input.bool(defval = true, title = 'Bar coloring', inline = 'ez', group=GRP_UI)
i_bullColor_t = input.color(#fbc02d, 'Up', inline='COLOR', group=GRP_UI)
gr1 = input.color(#eae4a0, '', inline='COLOR', group=GRP_UI)
i_bearColor_t = input.color(#3179f5, 'Down', inline='COLOR', group=GRP_UI)
rd1 = input.color(#99c1f1, '', inline='COLOR', group=GRP_UI)
i_bullColor_a = input.color(#fbc02d, "Up", inline='COLORa', group=GRP_UI)
gr2 = input.color(#fff9c4, "", inline='COLORa', group=GRP_UI)
i_bearColor_a = input.color(#ba4bcd, "Down", inline='COLORa', group=GRP_UI)
rd2 = input.color(#d8a7f7, "", inline='COLORa', group=GRP_UI)
i_bullColor_m = input.color(#388e3c, 'Up', inline='COLORb', group=GRP_UI)
gr3 = input.color(#96df99, '', inline='COLORb', group=GRP_UI)
i_bearColor_m = input.color(#3179f5, 'Down', inline='COLORb', group=GRP_UI)
rd3 = input.color(#99c1f1, '', inline='COLORb', group=GRP_UI)
i_bullColor_c = input.color(#57d132, "Up", inline='COLORc', group=GRP_UI)
gr4 = input.color(#b6f1b8, "", inline='COLORc', group=GRP_UI)
i_bearColor_c = input.color(#e42626, "Down", inline='COLORc', group=GRP_UI)
rd4 = input.color(#f581a8, "", inline='COLORc', group=GRP_UI)
i_bullColor_s = input.color(#379832, 'Up', inline='COLORs', group=GRP_UI)
gr5 = input.color(#aadba4, '', inline='COLORs', group=GRP_UI)
i_bearColor_s = input.color(#ffa726, 'Down', inline='COLORs', group=GRP_UI)
rd5 = input.color(#eacfa0, '', inline='COLORs', group=GRP_UI)
i_bullColor_p = input.color(#8da23d, "Up", inline='COLORcp', group=GRP_UI)
gr6 = input.color(#e4ffc4, "", inline='COLORcp', group=GRP_UI)
i_bearColor_p = input.color(#7d35b2, "Down", inline='COLORcp', group=GRP_UI)
rd6 = input.color(#b9aef7, "", inline='COLORcp', group=GRP_UI)
i_bullColor_o = input.color(#9598a1, "Up", inline='COLORcpn', group=GRP_UI)
gr7 = input.color(#e5edf6, "", inline='COLORcpn', group=GRP_UI)
i_bearColor_o = input.color(#3179f5, "Down", inline='COLORcpn', group=GRP_UI)
rd7 = input.color(#99c1f1, "", inline='COLORcpn', group=GRP_UI)
up_ = the_m == M1 ? i_bullColor_t : the_m == M2 ? i_bullColor_a : the_m == M3 ? i_bullColor_m : the_m == M4 ? i_bullColor_c : the_m == M5 ? i_bullColor_s : the_m == M6 ? i_bullColor_p : the_m == M7 ? i_bullColor_o : na
dn_ = the_m == M1 ? i_bearColor_t : the_m == M2 ? i_bearColor_a : the_m == M3 ? i_bearColor_m : the_m == M4 ? i_bearColor_c : the_m == M5 ? i_bearColor_s : the_m == M6 ? i_bearColor_p : the_m == M7 ? i_bearColor_o : na
gr = the_m == M1 ? gr1 : the_m == M2 ? gr2 : the_m == M3 ? gr3 : the_m == M4 ? gr4 : the_m == M5 ? gr5 : the_m == M6 ? gr6 : the_m == M7 ? gr7 : na
rd = the_m == M1 ? rd1 : the_m == M2 ? rd2 : the_m == M3 ? rd3 : the_m == M4 ? rd4 : the_m == M5 ? rd5 : the_m == M6 ? rd6 : the_m == M7 ? rd7 : na
bk_grd = input.color(#b5a1e2, 'Threshold color, fade', inline = 'q', group = GRP_UI)
fader = input.int(72, '', inline = 'q', group = GRP_UI)
isThreshCol = input.bool(true, 'ADX fill', inline='i', group=GRP_UI)
// ===========================================================================================================
// Functions
// ===========================================================================================================
// Hann Window Smoothing – Credits to @cheatcountry
doHannWindow(float _series, float _hannWindowLength) =>
sum = 0.0, coef = 0.0
for i = 1 to _hannWindowLength
cosine = 1 - math.cos(2 * math.pi * i / (_hannWindowLength + 1))
sum := sum + (cosine * nz(_series[i - 1]))
coef := coef + cosine
h = coef != 0 ? sum / coef : 0
// Super Smoother Function
ss(Series, Period) => // Super Smoother Function
var PI = 2.0 * math.asin(1.0)
var SQRT2 = math.sqrt(2.0)
lambda = PI * SQRT2 / Period
a1 = math.exp(-lambda)
coeff2 = 2.0 * a1 * math.cos(lambda)
coeff3 = -math.pow(a1, 2.0)
coeff1 = 1.0 - coeff2 - coeff3
filt1 = 0.0
filt1 := coeff1 * (Series + nz(Series[1])) * 0.5 + coeff2 * nz(filt1[1]) + coeff3 * nz(filt1[2])
filt1
wilders(src, period)=>
wild =0.
wild := nz(wild[1]) + (src -nz(wild[1]))/period
wild
doSmoothing(float _input, int length) =>
switch smoothingMode
'Hann Window' => doHannWindow(_input, length)
'Super Smoother' => ss(_input, length)
'Wilders' => wilders(_input, length)
=> _input
atr_ma(float _input, int length) =>
switch atr_move
'Hann Window' => doHannWindow(_input, length)
'Super Smoother' => ss(_input, length)
=> _input
air_ma(float _input, int length) =>
switch air_move
'Hann Window' => doHannWindow(_input, length)
'Super Smoother' => ss(_input, length)
'Wilders' => wilders(_input, length)
=> _input
// ===========================================================================================================
// Calculations
// ===========================================================================================================
[_close, _low, _high] = request.security(symbol = syminfo.tickerid, timeframe = '', expression = [close[1], low[1], high[1]], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
atr(atrLength) =>
float tr = math.max(math.max(_high - _low, math.abs(_high - _close[1])), math.abs(_low - _close[1]))
atr_ma(tr, atrLength)
ipr_array(len, dnny, uppy) =>
float[] hiArray = array.new_float(0)
float[] loArray = array.new_float(0)
float[] cmArray = array.new_float(0)
for i = 0 to len - 1
array.push(hiArray, high[i]) // tested with '_close', '_low', etc. bof
array.push(loArray, low[i])
array.push(cmArray, hlcc4[i])
hlArray = array.concat(hiArray, loArray)
hlcmArray = array.concat(hlArray, cmArray)
q1 = array.percentile_linear_interpolation(hlcmArray, dnny)
q3 = array.percentile_linear_interpolation(hlcmArray, uppy)
iqr = (q3 - q1) / 2
atrFactor = atrActive ? atrMult * atr(smoothing) : 0
pipFactor = pipActive ? pipMult * ipr_array(smoothing, spacer_chop, 100 - spacer_chop) : 0
airFactor = airActive ? airMult * air_ma(ipr_array(smoothing, percent_rng, 100 - percent_rng), smoothing) : 0
blender = nz(atrFactor) + nz(pipFactor) + nz(airFactor)
vortex(int period) =>
tr = blender
VMP = math.sum(math.abs(high - low[1]), period)
VMM = math.sum(math.abs(low - high[1]), period)
Sum_TR = math.sum(tr, period)
plus = VMP / Sum_TR
minus = VMM / Sum_TR
DI_Dif = math.abs(plus - minus) * 10
DI_Sum = (plus + minus) * 10
Vortex = 100 * doSmoothing(DI_Dif / DI_Sum, period)
[Vortex, plus, minus]
[vortex, vortexPlus, vortexMinus] = vortex(length)
normalize(float _src, int _min, int _max) =>
var float _historicMin = 1.0
var float _historicMax = -1.0
_historicMin := math.min(nz(_src, _historicMin), _historicMin)
_historicMax := math.max(nz(_src, _historicMax), _historicMax)
_min + (_max - _min) * (_src - _historicMin) / math.max(_historicMax - _historicMin, 1)
max = 1
min = 0
vortex := normalize(vortex, min, max)
vortexPlus := normalize(vortexPlus, min, max)
vortexMinus := normalize(vortexMinus, min, max)
// RSI filter
rsi_threshold_up = 50 + rsi_threshold
rsi_threshold_dn = 50 - rsi_threshold
rsi_cond = ta.rsi(close, rsi_len) > rsi_threshold_up or ta.rsi(close, rsi_len) < rsi_threshold_dn
// ===========================================================================================================
// Colors & plots
// ===========================================================================================================
vortexPlot = plot(vortex, color=color.new(bk_grd, fader), linewidth = 1, style=plot.style_cross, title='Vortex')
flat = plot(0, display = display.none)
above_thr_up = vortex > threshold and vortexPlus > vortexMinus
above_thr_dn = vortex > threshold and vortexPlus < vortexMinus
thresher_col = above_thr_up ? gr : above_thr_dn ? rd : na
agreg = above_thr_up ? vortexPlus - vortexMinus : above_thr_dn ? vortexMinus - vortexPlus : na
absolute = plot(agreg, color=thresher_col, style = plot.style_linebr, title='absolute DX')
fill(flat, absolute, color=isThreshCol and vortex > threshold ? color.new(thresher_col, 65) : color.new(bk_grd, 80))
// Bar coloring conditions
buy = vortexPlus > vortexMinus and vortexPlus > vortex and above_thr_up and rsi_cond
sell = vortexMinus > vortexPlus and vortexMinus > vortex and above_thr_dn and rsi_cond
self_cancel = vortexPlus < threshold and vortexMinus < threshold
ob = not self_cancel and not buy and not sell and vortexPlus > vortexMinus and rsi_cond
os = not self_cancel and not buy and not sell and vortexMinus > vortexPlus and rsi_cond
baring = self_cancel ? color.new(bk_grd, 75) : buy ? gr : sell ? rd : ob ? up_ : os ? dn_ : color.new(bk_grd, 75)
barcolor(switch_col ? baring : na)
baring_histo = self_cancel ? color.new(bk_grd, 100) : buy ? gr : sell ? rd : ob ? color.new(up_, 35) : os ? color.new(dn_, 35) : color.new(bk_grd, 100)
vortexPlot_hist = plot(vortex, color=baring_histo, linewidth = 1, style=plot.style_histogram, title='Vortex')
// ===========================================================================================================
// Signals & alerts
// ===========================================================================================================
var trend_noch = 0
if buy
trend_noch := 1
trend_noch
if sell
trend_noch := -1
trend_noch
up_trig = trend_noch[1] == -1 and trend_noch == 1
dn_trig = trend_noch[1] == 1 and trend_noch == -1
alertcondition(up_trig, "AIR Vortex ADX Up 🟢", "AIR Vortex ADX Up 🟢")
alertcondition(dn_trig, "AIR Vortex ADX Down 🔴", "AIR Vortex ADX Down 🔴")
plotshape(up_trig, title='Trend up', style=shape.triangleup, location=location.top, color=gr, size = size.tiny)
plotshape(dn_trig, title='Trend down', style=shape.triangledown, location=location.top, color=rd, size = size.tiny)
// ( __)( ( \( \
// ) _) / / ) D (
// (____)\_)__)(____/
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
|
Sector Momentum | https://www.tradingview.com/script/fb1mmWfP-Sector-Momentum/ | kuantumk | https://www.tradingview.com/u/kuantumk/ | 121 | 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/
// @kuantumk
//@version=5
indicator(title="MACD of Number of Stocks Above 20SMA of a Sector", shorttitle="Sector Momentum")
// Getting inputs
sector = input.string(title="Sector", defval="XLK", options=["XLB", "XLC", "XLE", "XLF", "XLI", "XLK", "XLP", "XLRE", "XLU", "XLV", "XLY"])
ticker = switch sector
"XLB" => "SBTW"
"XLC" => "SLTW"
"XLE" => "SETW"
"XLF" => "SFTW"
"XLI" => "SITW"
"XLK" => "SKTW"
"XLP" => "SPTW"
"XLRE" => "SSTW"
"XLU" => "SUTW"
"XLV" => "SVTW"
"XLY" => "SYTW"
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = request.security(ticker, "D", close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
// Plot colors
col_macd = input(#2962FF, "MACD Line ", group="Color Settings", inline="MACD")
col_signal = input(#FF6D00, "Signal Line ", group="Color Settings", inline="Signal")
col_grow_above = input(#26A69A, "Above Grow", group="Histogram", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")
// Calculating
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
hline(0, "Zero Line", color=color.new(#787B86, 50))
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
//plot(macd, title="MACD", color=col_macd)
//plot(signal, title="Signal", color=col_signal)
table t = table.new(position.top_right, 1, 11, bgcolor=color.black)
table.cell(t, 0, 0, sector, text_color=color.white, text_size = size.large) |
On Balance Volume Heikin-Ashi Transformed | https://www.tradingview.com/script/cB91XnCF-On-Balance-Volume-Heikin-Ashi-Transformed/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 194 | 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/
// © QuantiLuxe
//@version=5
indicator("On Balance Volume Heikin-Ashi", "[Ʌ] - 𝘖𝘉𝘝 𝘏-𝘈", true, scale = scale.none)
type bar
float o = open
float h = high
float l = low
float c = close
float v = volume
method src(bar b, simple string src) =>
float x = switch src
'oc2' => math.avg(b.o, b.c )
'hl2' => math.avg(b.h, b.l )
'hlc3' => math.avg(b.h, b.l, b.c )
'ohlc4' => math.avg(b.o, b.h, b.l, b.c)
'hlcc4' => math.avg(b.h, b.l, b.c, b.c)
x
method ha(bar b, simple bool p = true) =>
var bar x = bar.new( )
x.c := b .src('ohlc4')
x := bar.new(
na(x.o[1]) ?
b.src('oc2') : nz(x.src('oc2')[1]),
math.max(b.h, math.max(x.o, x.c)) ,
math.min(b.l, math.min(x.o, x.c)) ,
x.c )
p ? x : b
f_obv(float src) =>
bar b = bar .new ( )
float dir = math.sign(b.c - b.o)
ta.cum(dir == 1 ?
+ b.v * src :
dir == -1 ?
- b.v * src :
0 )
var string go = "OBV", var string ge = "EMAs"
norm = input.bool(false, "Normalize |", inline = '3', group = go)
len = input.int (21 , "Period" , inline = '3', group = go)
ma1 = input.bool(true , "EMA |" , inline = '1', group = ge)
len1 = input.int (20 , "Length" , inline = '1', group = ge)
ma2 = input.bool(false, "EMA |" , inline = '2', group = ge)
len2 = input.int (50 , "Length" , inline = '2', group = ge)
float calc = norm ?
f_obv(ohlc4) - ta.ema(f_obv(ohlc4), len) :
f_obv(ohlc4)
bar obv = bar.new(
calc[1] ,
math.max(calc, calc[1]),
math.min(calc, calc[1]),
calc ).ha()
var color colup = #fff2cc
var color coldn = #6fa8dc
var color colema1 = #FFD6E8
var color colema2 = #9a9adf
color haColor = switch
obv.c > obv.o => colup
obv.c < obv.o => coldn
plotcandle(obv.o, obv.h, obv.l, obv.c,
" 𝘖𝘉𝘝", haColor, haColor, bordercolor = haColor)
hline(norm ? 0 : na , "Zero Line", #ffffff80, hline.style_solid)
plot (ma1 ? ta.ema(obv.c, len1) : na, " 𝘌𝘔𝘈 1" , colema1)
plot (ma2 ? ta.ema(obv.c, len2) : na, " 𝘌𝘔𝘈 2" , colema2)
//Source Construction For Indicator\Strategy Exports
plot(obv.o , "open" , editable = false, display = display.none)
plot(obv.h , "high" , editable = false, display = display.none)
plot(obv.l , "low" , editable = false, display = display.none)
plot(obv.c , "close", editable = false, display = display.none)
plot(obv.src('hl2' ), "hl2" , editable = false, display = display.none)
plot(obv.src('hlc3' ), "hlc3" , editable = false, display = display.none)
plot(obv.src('ohlc4'), "ohlc4", editable = false, display = display.none)
plot(obv.src('hlcc4'), "hlcc4", editable = false, display = display.none) |
Z-Score Heikin-Ashi Transformed | https://www.tradingview.com/script/MFW8vsmU-Z-Score-Heikin-Ashi-Transformed/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 550 | 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/
// © QuantiLuxe
//@version=5
indicator("Z-Score Heikin Ashi Transformed", "[Ʌ] - 𝘡 𝘏-𝘈", false)
type bar
float o = open
float h = high
float l = low
float c = close
method src(bar b, simple string src) =>
float x = switch src
'oc2' => math.avg(b.o, b.c )
'hl2' => math.avg(b.h, b.l )
'hlc3' => math.avg(b.h, b.l, b.c )
'ohlc4' => math.avg(b.o, b.h, b.l, b.c)
'hlcc4' => math.avg(b.h, b.l, b.c, b.c)
x
method ha(bar b, simple bool p = true) =>
var bar x = bar.new( )
x.c := b .src('ohlc4')
x := bar.new(
na(x.o[1]) ?
b.src('oc2') : nz(x.src('oc2')[1]),
math.max(b.h, math.max(x.o, x.c)) ,
math.min(b.l, math.min(x.o, x.c)) ,
x.c )
p ? x : b
f_z(float src, simple int len) =>
(src - ta.sma(src, len)) / ta.stdev(src, len)
method z(bar b, simple int len) =>
bar x = bar.new(
f_z(b.o, len),
f_z(b.h, len),
f_z(b.l, len),
f_z(b.c, len))
x
var string gz = "Z-Score", var string ge = "EMAs"
len = input.int (21 , "Z Period" , group = gz)
revs = input.bool(true , "Reversions" , inline = '0', group = gz)
revt = input.int (2 , "Threshold" , [1, 2, 3], inline = '0', group = gz)
hol = input.bool(true , "Hollow Candles", group = gz)
ma1 = input.bool(true , "EMA |" , inline = '1', group = ge)
len1 = input.int (20 , "Length" , inline = '1', group = ge)
ma2 = input.bool(false, "EMA |" , inline = '2', group = ge)
len2 = input.int (50 , "Length" , inline = '2', group = ge)
bar score = bar.new().ha().z(len)
var color colup = #fff2cc
var color coldn = #6fa8dc
var color colema1 = #FFD6E8
var color colema2 = #9a9adf
color haColor = switch
score.c > score.o => colup
score.c < score.o => coldn
plotcandle(score.o, score.h, score.l, score.c, "𝘚𝘤𝘰𝘳𝘦",
hol ? score.c < score.o ? haColor : na : haColor, haColor, bordercolor = haColor)
plot(ma1 ? ta.ema(score.c, len1) : na, "𝘌𝘔𝘈 1", colema1)
plot(ma2 ? ta.ema(score.c, len2) : na, "𝘌𝘔𝘈 2", colema2)
hline(0, "Mid Line", chart.fg_color, hline.style_solid)
min = hline(-4, display = display.none)
ll = hline(-3, display = display.none)
hl = hline(-2, display = display.none)
max = hline(4 , display = display.none)
hh = hline(3 , display = display.none)
lh = hline(2 , display = display.none)
fill(lh, hh , color = #9a9adf2a)
fill(hh, max, color = #9a9adf4d)
fill(ll, hl , color = #ffd6e83b)
fill(ll, min, color = #ffd6e85e)
plotshape(revs ? score.h > revt and score.h < score.h[1] and not (score.h[1] < score.h[2]) ? score.h + 0.75 : na : na, "OB", shape.triangledown, location.absolute, colema1, size = size.tiny)
plotshape(revs ? score.l < -revt and score.l > score.l[1] and not (score.l[1] > score.l[2]) ? score.l - 0.75 : na : na, "OS", shape.triangleup , location.absolute, colema2, size = size.tiny)
//Source Construction For Indicator\Strategy Exports
plot(score.o , "open" , editable = false, display = display.none)
plot(score.h , "high" , editable = false, display = display.none)
plot(score.l , "low" , editable = false, display = display.none)
plot(score.c , "close", editable = false, display = display.none)
plot(score.src('hl2' ), "hl2" , editable = false, display = display.none)
plot(score.src('hlc3' ), "hlc3" , editable = false, display = display.none)
plot(score.src('ohlc4'), "ohlc4", editable = false, display = display.none)
plot(score.src('hlcc4'), "hlcc4", editable = false, display = display.none) |
CVD+ - Multi Symbol Cumulative Volume Delta | https://www.tradingview.com/script/9CYWSMSj-CVD-Multi-Symbol-Cumulative-Volume-Delta/ | In_Finito_ | https://www.tradingview.com/u/In_Finito_/ | 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/
// © TradingView
//Edit by InFinito
//Added features:
// - Option to manually select a symbol from which to calculate the LTF CVD
// - Option to normalize the selected symbol's CVD to the chart's symbol's CVD (Useful when you want to compare futures and spot on the same pane)
// - Label that displays the selected symbol's name and exchange
// - Changed presets to plot the CVD as the predetermined option
//@version=5
indicator("CVD - Multi Symbol Cumulative Volume Delta", "CVD Candles", format = format.volume)
// CVD - Cumulative Volume Delta Candles
// v7, 2023.03.25
// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
import PineCoders/Time/4 as PCtime
import PineCoders/lower_tf/4 as PCltf
import TradingView/ta/4 as TVta
//#region ———————————————————— Constants and Inputs
// ————— Constants
int MS_IN_MIN = 60 * 1000
int MS_IN_HOUR = MS_IN_MIN * 60
int MS_IN_DAY = MS_IN_HOUR * 24
// Default colors
color GRAY = #808080ff
color LIME = #00FF00ff
color MAROON = #800000ff
color ORANGE = #FF8000ff
color PINK = #FF0080ff
color TEAL = #008080ff
color BG_DIV = color.new(ORANGE, 90)
color BG_RESETS = color.new(GRAY, 90)
// Reset conditions
string RST1 = "None"
string RST2 = "On a stepped higher timeframe"
string RST3 = "On a fixed higher timeframe..."
string RST4 = "At a fixed time..."
string RST5 = "At the beginning of the regular session"
string RST6 = "At the first visible chart bar"
string RST7 = "On trend changes..."
// Trends
string TR01 = "Supertrend"
string TR02 = "Aroon"
string TR03 = "Parabolic SAR"
// Volume Delta calculation mode
string VD01 = "Volume Delta"
string VD02 = "Volume Delta Percent"
// Realtime calculation modes
string RT1 = "Intrabars (same as on historical bars)"
string RT2 = "Chart updates"
// Intrabar precisions
string LTF1 = "Covering most chart bars (least precise)"
string LTF2 = "Covering some chart bars (less precise)"
string LTF3 = "Covering less chart bars (more precise)"
string LTF4 = "Covering few chart bars (very precise)"
string LTF5 = "Covering the least chart bars (most precise)"
string LTF6 = "~12 intrabars per chart bar"
string LTF7 = "~24 intrabars per chart bar"
string LTF8 = "~50 intrabars per chart bar"
string LTF9 = "~100 intrabars per chart bar"
string LTF10 = "~250 intrabars per chart bar"
// Tooltips
string TT_RST = "This is where you specify how you want the cumulative volume delta to reset.
If you select one of the last three choices, you must also specify the relevant additional information below."
string TT_RST_HTF = "This value only matters when '" + RST3 +"' is selected."
string TT_RST_TIME = "Hour: 0-23\nMinute: 0-59\nThese values only matter when '" + RST4 +"' is selected.
A reset will occur when the time is greater or equal to the bar's open time, and less than its close time."
string TT_RST_TREND = "These values only matter when '" + RST7 +"' is selected.\n
For Supertrend, the first value is the length of ATR, the second is the factor. For Aroon, the first value is the lookback length."
string TT_TOTVOL = "Total volume can only be displayed when '" + VD01 +"' is selected as the Volume Delta Calculation mode.\n\n
The 'Bodies' value is the transparency of the total volume candle bodies. Zero is opaque, 100 is transparent."
string TT_LINE = "This plots a line at the `close` values of the CVD candles. You can use it instead of the CVD candles."
string TT_LTF = "Your selection here controls how many intrabars will be analyzed for each chart bar.
The more intrabars you analyze, the more precise the calculations will be,
but the less chart bars will be covered by the indicator's calculations because a maximum of 100K intrabars can be analyzed.\n\n
The first five choices determine the lower timeframe used for intrabars using how much chart coverage you want.
The last five choices allow you to select approximately how many intrabars you want analyzed per chart bar."
string TT_MA = "This plots the running average of CVD from its last reset. The 'Length' period only applies when CVD does not reset, i.e., the reset is 'None'."
// ————— Inputs
string MS = 'Symbol Selection'
bool moasw =input.bool(false, 'Manual Symbol', inline = '1', group = MS)
string manticker =input.symbol(title='', defval='BINANCE:BTCUSDT', inline = '1', group = MS)
bool swNormal =input.bool(false, 'Normalize', inline = '1', group = MS, tooltip =
'When selecting a futures symbol, different symbol, or the same symbol with very different volume, normalizing it will make it easier to compare to the baseline')
ticker = moasw ? manticker : syminfo.tickerid
int labelx =input.int(50, 'Label bars to the right position', 15, 500, 25, inline = '2', group = MS)
// string symName =input.string('', 'On-chart symbol name', tooltip = 'Ex. Binance Futures', inline = '2', group = MS)
string resetInput = input.string(RST2, "CVD Resets", inline = "00", options = [RST1, RST2, RST5, RST6, RST3, RST4, RST7], tooltip = TT_RST)
string fixedTfInput = input.timeframe("D", " Fixed higher timeframe:", tooltip = TT_RST_HTF)
int hourInput = input.int(9, " Fixed time: Hour", inline = "01", minval = 0, maxval = 23)
int minuteInput = input.int(30, "Minute", inline = "01", minval = 0, maxval = 59, tooltip = TT_RST_TIME)
string trendInput = input.string(TR01, " Trend: ", inline = "02", options = [TR02, TR03, TR01])
int trendPeriodInput = input.int(14, " Length", inline = "02", minval = 2)
float trendValue2Input = input.float(3.0, "", inline = "02", minval = 0.25, step = 0.25, tooltip = TT_RST_TREND)
string ltfModeInput = input.string(LTF3, "Intrabar precision", inline = "03", options = [LTF1, LTF2, LTF3, LTF4, LTF5, LTF6, LTF7, LTF8, LTF9, LTF10], tooltip = TT_LTF)
string vdCalcModeInput = input.string(VD01, "Volume Delta Calculation", inline = "04", options = [VD01, VD02])
string GRP1 = "Visuals"
bool showCandlesInput = input.bool(false, "CVD candles", inline = "11", group = GRP1)
color upColorInput = input.color(LIME, " 🡑", inline = "11", group = GRP1)
color dnColorInput = input.color(PINK, "🡓", inline = "11", group = GRP1)
bool colorDivBodiesInput = input.bool(false, "Color CVD bodies on divergences ", inline = "12", group = GRP1)
color upDivColorInput = input.color(TEAL, "🡑", inline = "12", group = GRP1)
color dnDivColorInput = input.color(MAROON, "🡓", inline = "12", group = GRP1)
bool showTotVolInput = input.bool(false, "Total volume candle borders", inline = "13", group = GRP1)
color upTotVolColorInput = input.color(TEAL, "🡑", inline = "13", group = GRP1)
color dnTotVolColorInput = input.color(MAROON, "🡓", inline = "13", group = GRP1)
int totVolBodyTranspInput = input.int(80, "bodies", inline = "13", group = GRP1, minval = 0, maxval = 100, tooltip = TT_TOTVOL)
bool showLineInput = input.bool(true, "CVD line", inline = "14", group = GRP1)
color lineUpColorInput = input.color(LIME, " 🡑", inline = "14", group = GRP1)
color lineDnColorInput = input.color(PINK, "🡓", inline = "14", group = GRP1, tooltip = TT_LINE)
bool showMaInput = input.bool(false, "CVD MA", inline = "15", group = GRP1)
color maUpColorInput = input.color(TEAL, " 🡑", inline = "15", group = GRP1)
color maDnColorInput = input.color(MAROON, "🡓", inline = "15", group = GRP1)
int maPeriodInput = input.int(20, " Length", inline = "15", group = GRP1, minval = 2, tooltip = TT_MA)
bool bgDivInput = input.bool(false, "Color background on divergences ", inline = "16", group = GRP1)
color bgDivColorInput = input.color(BG_DIV, "", inline = "16", group = GRP1)
bool bgResetInput = input.bool(true, "Color background on resets ", inline = "17", group = GRP1)
color bgResetColorInput = input.color(BG_RESETS, "", inline = "17", group = GRP1)
bool showZeroLineInput = input.bool(true, "Zero line", inline = "18", group = GRP1)
bool showInfoBoxInput = input.bool(false, "Show information box ", group = GRP1)
string infoBoxSizeInput = input.string("small", "Size ", inline = "19", group = GRP1, options = ["tiny", "small", "normal", "large", "huge", "auto"])
string infoBoxYPosInput = input.string("bottom", "↕", inline = "19", group = GRP1, options = ["top", "middle", "bottom"])
string infoBoxXPosInput = input.string("left", "↔", inline = "19", group = GRP1, options = ["left", "center", "right"])
color infoBoxColorInput = input.color(color.gray, "", inline = "19", group = GRP1)
color infoBoxTxtColorInput = input.color(color.white, "T", inline = "19", group = GRP1)
//#endregion
//#region ———————————————————— Functions
// @function Determines if the volume for an intrabar is up or down.
// @returns ([float, float]) A tuple of two values, one of which contains the bar's volume. `upVol` is the volume of up bars. `dnVol` is the volume of down bars.
// Note that when this function is called with `request.security_lower_tf()` a tuple of float[] arrays will be returned by `request.security_lower_tf()`.
upDnIntrabarVolumes() =>
float upVol = 0.0
float dnVol = 0.0
switch
// Bar polarity can be determined.
close > open => upVol += volume
close < open => dnVol -= volume
// If not, use price movement since last bar.
close > nz(close[1]) => upVol += volume
close < nz(close[1]) => dnVol -= volume
// If not, use previously known polarity.
nz(upVol[1]) > 0 => upVol += volume
nz(dnVol[1]) < 0 => dnVol -= volume
[upVol, dnVol]
// @function Selects a HTF from the chart's TF.
// @returns (simple string) A timeframe string.
htfStep() =>
int tfInMs = timeframe.in_seconds() * 1000
string result =
switch
tfInMs <= MS_IN_MIN => "60"
tfInMs < MS_IN_HOUR * 3 => "D"
tfInMs <= MS_IN_HOUR * 12 => "W"
tfInMs < MS_IN_DAY * 7 => "M"
=> "12M"
// @function Determines when a bar opens at a given time.
// @param hours (series int) "Hour" part of the time we are looking for.
// @param minutes (series int) "Minute" part of the time we are looking for.
// @returns (series bool) `true` when the bar opens at `hours`:`minutes`, false otherwise.
timeReset(int hours, int minutes) =>
int openTime = timestamp(year, month, dayofmonth, hours, minutes, 0)
bool timeInBar = time <= openTime and time_close > openTime
bool result = timeframe.isintraday and not timeInBar[1] and timeInBar
//#endregion
//#region ———————————————————— Calculations
// Lower timeframe (LTF) used to mine intrabars.
var string ltfString = PCltf.ltf(ltfModeInput, LTF1, LTF2, LTF3, LTF4, LTF5, LTF6, LTF7, LTF8, LTF9, LTF10)
// Get two arrays, one each for up and dn volumes.
[upVolumes, dnVolumes] = request.security_lower_tf(ticker, ltfString, upDnIntrabarVolumes())
// Calculate the maximum volumes, total volume, and volume delta, and assign the result to the `barDelta` variable.
float totalUpVolume = nz(upVolumes.sum())
float totalDnVolume = nz(dnVolumes.sum())
float maxUpVolume = nz(upVolumes.max())
float maxDnVolume = nz(dnVolumes.min())
float totalVolume = totalUpVolume - totalDnVolume
float delta = totalUpVolume + totalDnVolume
float deltaPct = delta / totalVolume
// Track cumulative volume.
var float cvd = 0.0
[reset, trendIsUp, resetDescription] =
switch resetInput
RST1 => [false, na, "No resets"]
RST2 => [timeframe.change(htfStep()), na, "Resets every " + htfStep()]
RST3 => [timeframe.change(fixedTfInput), na, "Resets every " + fixedTfInput]
RST4 => [timeReset(hourInput, minuteInput), na, str.format("Resets at {0,number,00}:{1,number,00}", hourInput, minuteInput)]
RST5 => [session.isfirstbar_regular, na, "Resets at the beginning of the session"]
RST6 => [time == chart.left_visible_bar_time, na, "Resets at the beginning of visible bars"]
RST7 =>
switch trendInput
TR01 =>
[_, direction] = ta.supertrend(trendValue2Input, trendPeriodInput)
[ta.change(direction, 1) != 0, direction == -1, "Resets on Supertrend changes"]
TR02 =>
[up, dn] = TVta.aroon(trendPeriodInput)
[ta.cross(up, dn), ta.crossover(up, dn), "Resets on Aroon changes"]
TR03 =>
float psar = ta.sar(0.02, 0.02, 0.2)
[ta.cross(psar, close), ta.crossunder(psar, close), "Resets on PSAR changes"]
=> [na, na, na]
if reset
cvd := 0
// Build OHLC values for CVD candles.
bool useVdPct = vdCalcModeInput == VD02
float barDelta = useVdPct ? deltaPct : delta
float cvdO = cvd
float cvdC = cvdO + barDelta
float cvdH = useVdPct ? math.max(cvdO, cvdC) : cvdO + maxUpVolume
float cvdL = useVdPct ? math.min(cvdO, cvdC) : cvdO + maxDnVolume
cvd += barDelta
if swNormal
cvdO := cvdO/ohlc4
cvdC := cvdC/ohlc4
cvdH := cvdH/ohlc4
cvdL := cvdL/ohlc4
cvd := cvd
else
cvdO := cvdO
cvdC := cvdC
cvdH := cvdH
cvdL := cvdL
cvd := cvd
// MA of CVD
var float ma = cvd
var cvdValues = array.new<float>()
if resetInput == RST1
ma := ta.sma(cvdC, maPeriodInput)
else
if reset
cvdValues.clear()
cvdValues.push(cvd)
else
cvdValues.push(cvd)
ma := cvdValues.avg()
// Total volume level relative to CVD.
float totalVolumeLevel = cvdO + (totalVolume * math.sign(barDelta))
// ———— Intrabar stats
[intrabars, chartBarsCovered, avgIntrabars] = PCltf.ltfStats(upVolumes)
int chartBars = bar_index + 1
// Detect errors.
if resetInput == RST3 and timeframe.in_seconds(fixedTfInput) <= timeframe.in_seconds()
runtime.error("The higher timeframe for resets must be greater than the chart's timeframe.")
else if resetInput == RST4 and not timeframe.isintraday
runtime.error("Resets at a fixed time work on intraday charts only.")
else if ta.cum(totalVolume) == 0 and barstate.islast
runtime.error("No volume is provided by the data vendor.")
else if ta.cum(intrabars) == 0 and barstate.islast
runtime.error("No intrabar information exists at the '" + ltfString + "' timeframe.")
// Detect divergences between volume delta and the bar's polarity.
bool divergence = delta != 0 and math.sign(delta) != math.sign(close - open)
//#endregion
//#region ———————————————————— Visuals
color candleColor = delta > 0 ? colorDivBodiesInput and divergence ? upDivColorInput : upColorInput : colorDivBodiesInput and divergence ? dnDivColorInput : dnColorInput
color totVolCandleColor = delta > 0 ? upTotVolColorInput : dnTotVolColorInput
// Display key values in indicator values and Data Window.
displayLocation = display.data_window
plot(delta, "Volume delta for the bar", candleColor, display = displayLocation)
plot(totalUpVolume, "Up volume for the bar", upColorInput, display = displayLocation)
plot(totalDnVolume, "Dn volume for the bar", dnColorInput, display = displayLocation)
plot(totalVolume, "Total volume", display = displayLocation)
plot(na, "═════════════════", display = displayLocation)
plot(cvdO, "CVD before this bar", display = displayLocation)
plot(cvdC, "CVD after this bar", display = displayLocation)
plot(maxUpVolume, "Max intrabar up volume", upColorInput, display = displayLocation)
plot(maxDnVolume, "Max intrabar dn volume", dnColorInput, display = displayLocation)
plot(intrabars, "Intrabars in this bar", display = displayLocation)
plot(avgIntrabars, "Average intrabars", display = displayLocation)
plot(chartBarsCovered, "Chart bars covered", display = displayLocation)
plot(bar_index + 1, "Chart bars", display = displayLocation)
plot(na, "═════════════════", display = displayLocation)
// Total volume boxes.
[totalVolO, totalVolH, totalVolL, totalVolC] = if showTotVolInput and not useVdPct
[cvdO, math.max(cvdO, totalVolumeLevel), math.min(cvdO, totalVolumeLevel), totalVolumeLevel]
else
[na, na, na, na]
plotcandle(totalVolO, totalVolH, totalVolL, totalVolC, "CVD", color = color.new(totVolCandleColor, totVolBodyTranspInput), wickcolor = totVolCandleColor, bordercolor = totVolCandleColor)
// CVD candles.
plotcandle(showCandlesInput ? cvdO : na, cvdH, cvdL, cvdC, "CVD", color = candleColor, wickcolor = candleColor, bordercolor = candleColor)
// CVD line.
plot(showLineInput ? cvdC : na, "CVD line", cvdC > 0 ? lineUpColorInput : lineDnColorInput)
/////CVD LINE TICKER NAME LABEL
var label cvdtickername = na
if barstate.islast
label.delete(cvdtickername)
cvdtickername := label.new(bar_index+labelx, cvdC, str.tostring(ticker), color= cvdC > 0 ? lineUpColorInput : lineDnColorInput, size=size.normal)
// CVD MA.
plot(showMaInput ? ma : na, "CVD MA", reset ? na : ma > 0 ? maUpColorInput : maDnColorInput)
// Zero line.
hline(showZeroLineInput ? 0 : na, "Zero", GRAY, hline.style_dotted)
// Up/Dn arrow used when resets occur on trend changes.
plotchar(reset and not na(trendIsUp) ? trendIsUp : na, "Up trend", "▲", location.top, upColorInput)
plotchar(reset and not na(trendIsUp) ? not trendIsUp : na, "Dn trend", "▼", location.top, dnColorInput)
// Background on resets and divergences.
bgcolor(bgResetInput and reset ? bgResetColorInput : bgDivInput and divergence ? bgDivColorInput : na)
// Display information box only once on the last historical bar, instead of on all realtime updates, as when `barstate.islast` is used.
if showInfoBoxInput and barstate.islastconfirmedhistory
var table infoBox = table.new(infoBoxYPosInput + "_" + infoBoxXPosInput, 1, 1)
color infoBoxBgColor = infoBoxColorInput
string txt = str.format("{0}\nUses intrabars at {1}\nAvg intrabars per chart bar: {2,number,#.##}\nChart bars covered: {3} / {4} ({5,number,percent})",
resetDescription, PCtime.formattedNoOfPeriods(timeframe.in_seconds(ltfString) * 1000),
avgIntrabars, chartBarsCovered, bar_index + 1, chartBarsCovered / (bar_index + 1))
if avgIntrabars < 5
txt += "\nThis quantity of intrabars is dangerously small.\nResults will not be as reliable with so few."
infoBoxBgColor := color.red
table.cell(infoBox, 0, 0, txt, text_color = infoBoxTxtColorInput, text_size = infoBoxSizeInput, bgcolor = infoBoxBgColor)
//#endregion
|
Simple Grid Lines Visualizer | https://www.tradingview.com/script/MmExl1YV-Simple-Grid-Lines-Visualizer/ | lecjacks | https://www.tradingview.com/u/lecjacks/ | 110 | 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/
// © lecjacks
//@version=5
indicator("Grid Lines Visualizer", overlay=true)
// Input prices
top_price = input.float(31400., "Top Price")
bottom_price = input.float(24200., "Bottom Price")
use = input.string(title="Use", options=["Num Grid", "Profit per Grid"], defval="Num Grid", inline = "03", tooltip="How grid lines are computed.\nNum grid: Explicit.\nProfit per Grid: First grid is computed from bottom up as\n- Start: bottom price\n- End: bottom price * (1 + percent profit).\nHow many number of these grids may enter the range is computed and then rounded to bottom integer.")
num_grids = input.int(30, "Number of Grids", minval = 2, inline="01", tooltip="Grid SPACES or (Number of Grid LINES - 1)")
profit_per_grid = input.float(0.6, "% Profit per Grid", minval = 0.0000001, inline = "02", tooltip="Minimum profit received buying at one grid line, selling on next one.")
externalLineColour = input.color(color.new(color.orange, 40), title="Top/Bottom Lines Colour")
internalLineColour = input.color(color.new(color.blue, 40), title="Internal Line Colour")
// Compute the price increment between each gridline
var float grid_range = top_price - bottom_price
var float price_increment = 0.0
if use == "Num Grid"
price_increment := grid_range / (num_grids)
else if use == "Profit per Grid"
price_increment := math.min(bottom_price * profit_per_grid / 100, grid_range)
num_grids := int(grid_range / price_increment)
price_increment := grid_range / (num_grids - 1)
// Draw horizontal lines for top and bottom channels
line.new(x1=bar_index[1], y1=bottom_price, x2=bar_index, y2=bottom_price, style = line.style_solid, color = externalLineColour, extend = extend.both)
line.new(x1=bar_index[1], y1=top_price, x2=bar_index, y2=top_price, style = line.style_solid, color = externalLineColour, extend = extend.both)
for i = 1 to num_grids-1
price = bottom_price + i * price_increment
line.new(x1=bar_index[1], y1=price, x2=bar_index, y2=price, style = line.style_solid, color = internalLineColour, extend = extend.both) |
Predictive Ranges [LuxAlgo] | https://www.tradingview.com/script/lIdNGLiV-Predictive-Ranges-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 4,194 | 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/
// © LuxAlgo
//@version=5
indicator("Predictive Ranges [LuxAlgo]", "LuxAlgo - Predictive Ranges", overlay = true)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input.int(200, 'Length', minval = 2)
mult = input.float(6., 'Factor', minval = 0, step = .5)
tf = input.timeframe('', 'Timeframe')
src = input(close, 'Source')
//-----------------------------------------------------------------------------}
//Function
//-----------------------------------------------------------------------------{
pred_ranges(length, mult)=>
var avg = src
var hold_atr = 0.
atr = nz(ta.atr(length)) * mult
avg := src - avg > atr ? avg + atr :
avg - src > atr ? avg - atr :
avg
hold_atr := avg != avg[1] ? atr / 2 : hold_atr
[avg + hold_atr * 2, avg + hold_atr, avg, avg - hold_atr, avg - hold_atr * 2]
//-----------------------------------------------------------------------------}
//Calculation
//-----------------------------------------------------------------------------{
[prR2
, prR1
, avg
, prS1
, prS2] = request.security(syminfo.tickerid, tf, pred_ranges(length, mult))
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot_pru2 = plot(prR2, 'PR Upper 2', avg != avg[1] ? na : #f23645)
plot_pru1 = plot(prR1, 'PR Upper 1', avg != avg[1] ? na : #f23645)
plot_pravg = plot(avg , 'PR Average', avg != avg[1] ? na : #5b9cf6)
plot_prl1 = plot(prS1, 'PR Lower 1', avg != avg[1] ? na : #089981)
plot_prl2 = plot(prS2, 'PR Lower 2', avg != avg[1] ? na : #089981)
//Fills
fill(plot_pru2, plot_pru1, avg != avg[1] ? na : color.new(#f23645, 95))
fill(plot_prl1, plot_prl2, avg != avg[1] ? na : color.new(#089981, 95))
//-----------------------------------------------------------------------------} |
Volume Orderbook (Expo) | https://www.tradingview.com/script/CVsC5pw9-Volume-Orderbook-Expo/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 2,758 | 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/
// © Zeiierman
//@version=5
indicator("Volume Orderbook (Expo)",overlay=true,max_boxes_count=500,max_lines_count=500)
//~~}
// ~~ Inputs {
src = input.source(close,"Source")
rows = input.int(10,"Rows",0,20,inline="rows")
mult = input.float(.5,"Width",.1,2,step=.05,inline="rows")
poc = input.bool(false,"POC",inline="rows")
tbl = input.bool(false,"Table",inline="table")
left = input.int(5,"Left",0,50,5,inline="table")
tbli = input.bool(false,"Grid",inline="table")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Variables & Array's {
b = bar_index
var step = 0.0
type Table
array<box> boxes
array<line> lines
array<label> lab
var levels = array.new<float>()
var volumes = array.new<float>()
var vols = array.new<float>(rows*2+1)
var tab = Table.new(array.new<box>(rows*2+2),array.new<line>(rows*2+1),array.new<label>(rows*2+1))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Code {
//Save first candle size
if barstate.isfirst
step := (high-low)*mult
//Stores each candle volume in levels
if levels.size()<=0
levels.push(src+step)
levels.push(src-step)
volumes.push(volume)
else
found = false
for i=0 to levels.size()-2
lvl1 = levels.get(i)
lvl2 = levels.get(i+1)
if src<lvl1 and src>lvl2
volumes.set(i,volumes.get(i)+volume)
found := true
break
if not found
if src>levels.get(0)
lvl = levels.get(0)
while src>lvl
levels.unshift(lvl+step)
volumes.unshift(0)
lvl := lvl+step
levels.unshift(lvl+step)
volumes.unshift(volume)
else if src<levels.get(levels.size()-1)
lvl = levels.get(levels.size()-1)
while src<lvl
levels.push(lvl-step)
volumes.push(0)
lvl := lvl-step
levels.push(lvl-step)
volumes.push(volume)
//Plots the orderbook
if barstate.islast
for i=0 to levels.size()-2
if src<levels.get(i) and src>levels.get(i+1)
for x=0 to (rows*2)
vols.set(x,volumes.get(math.max(0,i-rows+x)))
vol = vols.copy()
vols.sort()
for x=0 to (rows*2)
tab.boxes.get(x).delete()
col = x<rows?color.red:x>rows?color.lime:color.gray
colgrade = color.from_gradient(vols.indexof(vol.get(x)),0,vols.size(),color.new(col,80),color.new(col,40))
tab.boxes.set(x,box.new((b+left+rows*2)-vols.indexof(vol.get(x)),levels.get(math.max(0,i-rows+x)),
(b+left+rows*2)+vols.indexof(vol.get(x)),levels.get(math.max(1,i-rows+x+1)),
colgrade,bgcolor=colgrade,border_style=line.style_dotted,
text=str.tostring(vol.get(x),format.volume),text_color=chart.fg_color,
extend=poc and vols.indexof(vol.get(x))==rows*2?extend.left:extend.none))
if tbli
tab.lines.get(x).delete()
tab.lines.set(x,line.new(b+left,levels.get(i-rows+x),b+left+rows*2+vols.size()-1,levels.get(i-rows+x),
color=color.gray))
if tbl
tab.boxes.get(rows*2+1).delete()
tab.boxes.set(rows*2+1,box.new(b+left,box.get_top(tab.boxes.get(0)),
b+left+rows*2+vols.size()-1,box.get_bottom(tab.boxes.get(rows*2)),
color.gray,border_width=2,bgcolor=color(na)))
break
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} |
Open Interest RSI | https://www.tradingview.com/script/Ont5Ci34/ | Demech | https://www.tradingview.com/u/Demech/ | 136 | study | 5 | MPL-2.0 | // This code is licensed under the Mozilla Public License 2.0
// © Demech
//@version=5
indicator(title = "Open Interest RSI", shorttitle = "OI RSI", format = format.volume, overlay = false)
// These two lines create user inputs that allow the user to override the default symbol
bool overwriteSymbolInput = input.bool(false, "Override symbol", inline = "Override symbol")
string tickerInput = input.symbol("", "", inline = "Override symbol")
// This checks if the user has chosen to override the default symbol. If they have, it uses the inputted symbol. If not, it uses the default.
string symbolOnly = syminfo.ticker(tickerInput)
string userSymbol = overwriteSymbolInput ? symbolOnly : syminfo.prefix + ":" + syminfo.ticker
// This creates the symbol for the open interest data and determines the timeframe for the data
string openInterestTicker = str.format("{0}_OI", userSymbol)
string timeframe = syminfo.type == "futures" and timeframe.isintraday ? "1D" : timeframe.period
// This line requests the open, high, low, and close of the open interest data
[oiOpen, oiHigh, oiLow, oiClose, oiColorCond] = request.security(openInterestTicker, timeframe, [open, high, low, close, close > close[1]], ignore_invalid_symbol = true)
// This checks if there's any missing open interest data, and if so, returns an error message
if barstate.islastconfirmedhistory and na(oiClose)
runtime.error(str.format("No Open Interest data found for the `{0}` symbol.", userSymbol))
// These lines set the periods for the RSI and VWMA, then calculate the RSI and VWMA of the open interest data
oirsiPeriod = input(14, title="OI RSI Period")
oivwmaPeriode = input(14, title="OI VWMA Period")
oiRSI = ta.rsi(oiClose, oirsiPeriod)
oivwma = ta.vwma(oiRSI, oivwmaPeriode)
// Calculate Normal RSI
rsiPeriod = input(14, title = "RSI Period" )
rsi = ta.rsi(close, rsiPeriod)
vwmaPeriode = input(14, title="VWMA Period")
vwma = ta.vwma(rsi, vwmaPeriode)
// These two lines plot the Open Interest RSI and VWMA
plot(oiRSI, title="Open Interest RSI", color=color.rgb(0, 0, 0))
plot(oivwma, title="Open Interest RSI", color=color.orange)
// These two lines plot the RSI and VWMA
plot(rsi, title="Open Interest RSI", color=color.blue)
plot(vwma, title="Open Interest RSI", color=color.purple)
// Signal Logik
oib = (oiRSI > 70 and rsi < 30) or (oiRSI < 30 and rsi < 30)
ois = (oiRSI < 30 and rsi > 70) or (oiRSI > 70 and rsi > 70)
// Signals
bgcolor(oib ? color.new(color.green, 50) : na)
bgcolor(ois ? color.new(color.red, 50) : na)
// These lines create horizontal lines at various levels on the chart
u1 = hline(70, "Upper Level", color=color.red, linestyle= hline.style_solid)
u2 = hline(80, "Upper Level", color=color.red, linestyle= hline.style_solid)
l1 = hline(30, "Lower Level", color=color.green, linestyle= hline.style_solid)
l2 = hline(20, "Lower Level", color=color.green, linestyle= hline.style_solid)
m1 = hline(53, "upper Middl Level", color=color.gray, linestyle= hline.style_solid)
m2 = hline(47, "Lower Middl Level", color=color.gray, linestyle= hline.style_solid)
// These lines fill the areas between the horizontal lines with different colors
fill(u1, u2, color = color.new(color.red, 80))
fill(l1, l2, color = color.new(color.green, 80))
fill(m1, m2, color = color.new(color.gray, 80))
// Alerts
combined_alert = oib or ois
alertcondition(combined_alert, title='Combined Alert', message='A signal has triggered!')
alertcondition(oib, title='buy', message='Long Signal')
alertcondition(ois, title='sell', message='Short Signal') |
Mark Minervini's Trend Template | https://www.tradingview.com/script/22JWROvE-Mark-Minervini-s-Trend-Template/ | OmkarBanne | https://www.tradingview.com/u/OmkarBanne/ | 103 | 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/
// © omkar_banne
//@version=5
indicator("Mark Minervini's Trend Template", overlay = true)
position = input.string(position.top_right, 'Table \nPosition\n', options= [position.top_left, position.top_right, position.bottom_left, position.bottom_right], group='--------------Table Properties--------------', inline = "1")
textcolor = input(color.white, "Text Color", group='--------------Table Properties--------------', inline = "1")
textsize = input.string(size.normal, 'Text Size', options=[size.auto, size.small, size.normal, size.large], group='--------------Table Properties--------------', inline = "2")
panelbgcolor = input(color.gray, "Background Color", group='--------------Table Properties--------------', inline = "2")
//Moving Averages
type = input.string(defval='EMA', options=['EMA', 'SMA'] , title='Moving Average Type', tooltip='EMA / SMA?.', group = '--------------Moving Average Settings--------------')
// Table
var table1 = table.new(position, 3, 15, frame_color=color.rgb(49, 71, 131), border_width = 1, frame_width = 2, border_color = color.black)
table.merge_cells(table1,0,0,2,0)
table.cell(table1, 0, 0, 'Mark Minervini Template', bgcolor = color.rgb(88, 247, 114), text_size=textsize, text_color=color.black)
ma50 = ta.ema(close, 50)
ma150 = ta.ema(close, 150)
ma200 = ta.ema(close, 200)
ma200_22 = ma200[22]
if type == 'EMA'
ma50 := ta.ema(close, 50)
ma150 := ta.ema(close, 150)
ma200 := ta.ema(close, 200)
if type == 'SMA'
ma50 := ta.sma(close, 50)
ma150 := ta.sma(close, 150)
ma200 := ta.sma(close, 200)
bgcolor = panelbgcolor
// CMP > 50MA
close_greaterthan_50ma = close > ma50
close_greaterthan_50ma_color = color.gray
if not close_greaterthan_50ma
close_greaterthan_50ma_color := color.red
if na(ma50)
close_greaterthan_50ma_color := color.gray
isDaily = ta.change(time("D")) == 0
if timeframe.isdaily
per50 = (1-(ma50/close))*100
table.cell(table1, 0, 1, (close_greaterthan_50ma ? '✓' : 'x'), bgcolor = close_greaterthan_50ma_color, text_size=textsize, text_color=textcolor)
table.cell(table1, 1, 1, str.tostring("CMP > 50MA"), bgcolor = color.rgb(6, 192, 224), text_size=textsize, text_color=color.black)
table.cell(table1, 2, 1, str.tostring(ma50,'#.#') + " (" + str.tostring(per50,'#.#') + " %" + ")", bgcolor = panelbgcolor, text_size=textsize, text_color=textcolor, tooltip = "50 MA and % Distance from 50 MA")
// CMP > 150MA
close_greaterthan_150ma = close > ma150
close_greaterthan_150ma_color = color.gray
if not close_greaterthan_150ma
close_greaterthan_150ma_color := color.red
if na(ma150)
close_greaterthan_150ma_color := color.gray
if timeframe.isdaily
per150 = (1-(ma150/close))*100
table.cell(table1, 0, 2, (close_greaterthan_150ma ? '✓' : 'x'), bgcolor = close_greaterthan_150ma_color, text_size=textsize, text_color=textcolor)
table.cell(table1, 1, 2, str.tostring("CMP > 150MA"), bgcolor = color.rgb(6, 192, 224), text_size=textsize, text_color=color.black)
table.cell(table1, 2, 2, str.tostring(ma150,'#.#') + " (" + str.tostring(per150,'#.#') + " %" + ")", bgcolor = panelbgcolor, text_size=textsize, text_color=textcolor, tooltip = "150 MA and % Distance from 150 MA")
// CMP > 200MA
close_greaterthan_200ma = close > ma200
close_greaterthan_200ma_color = color.gray
if not close_greaterthan_200ma
close_greaterthan_200ma_color := color.red
if na(ma200)
close_greaterthan_200ma_color := color.gray
if timeframe.isdaily
per200 = (1-(ma200/close))*100
table.cell(table1, 0, 3, (close_greaterthan_200ma ? '✓' : 'x'), bgcolor = close_greaterthan_200ma_color, text_size=textsize, text_color=textcolor)
table.cell(table1, 1, 3, str.tostring("CMP > 200MA"), bgcolor = color.rgb(6, 192, 224), text_size=textsize, text_color=color.black)
table.cell(table1, 2, 3, str.tostring(ma200,'#.#') + " (" + str.tostring(per200,'#.#') + " %" + ")", bgcolor = panelbgcolor, text_size=textsize, text_color=textcolor, tooltip = "200 MA and % Distance from 200 MA")
// 50MA > 150MA
ma50_greaterthan_150ma = ma50 > ma150
ma50_greaterthan_150ma_color = color.gray
if not ma50_greaterthan_150ma
ma50_greaterthan_150ma_color := color.red
if na(ma50) or na(ma150)
ma50_greaterthan_150ma_color := color.gray
if timeframe.isdaily
per50_150 = (1-(ma50/ma150))*100
table.cell(table1, 0, 4, (ma50_greaterthan_150ma ? '✓' : 'x'), bgcolor = ma50_greaterthan_150ma_color, text_size=textsize, text_color=textcolor)
table.cell(table1, 1, 4, str.tostring("50 MA > 150 MA"), bgcolor = color.rgb(6, 192, 224), text_size=textsize, text_color=color.black)
table.cell(table1, 2, 4, str.tostring(per50_150,'#.#') + " %", bgcolor = panelbgcolor, text_size=textsize, text_color=textcolor, tooltip = "Distance between 50 & 150 MA")
// 50MA > 200MA
ma50_greaterthan_200ma = ma50 > ma200
ma50_greaterthan_200ma_color = color.gray
if not ma50_greaterthan_200ma
ma50_greaterthan_200ma_color := color.red
if na(ma50) or na(ma200)
ma50_greaterthan_200ma_color := color.gray
if timeframe.isdaily
per50_200 = (1-(ma50/ma200))*100
table.cell(table1, 0, 5, (ma50_greaterthan_200ma ? '✓' : 'x'), bgcolor = ma50_greaterthan_200ma_color, text_size=textsize, text_color=textcolor)
table.cell(table1, 1, 5, str.tostring("50 MA > 200 MA"), bgcolor = color.rgb(6, 192, 224), text_size=textsize, text_color=color.black)
table.cell(table1, 2, 5, str.tostring(per50_200,'#.#') + " %", bgcolor = panelbgcolor, text_size=textsize, text_color=textcolor, tooltip = "Distance between 50 & 200 MA")
// 150MA > 200MA
ma150_greaterthan_200ma = ma50 > ma200
ma150_greaterthan_200ma_color = color.gray
if not ma150_greaterthan_200ma
ma150_greaterthan_200ma_color := color.red
if na(ma150) or na(ma200)
ma150_greaterthan_200ma_color := color.gray
if timeframe.isdaily
per150_200 = (1-(ma150/ma200))*100
table.cell(table1, 0, 6, (ma150_greaterthan_200ma ? '✓' : 'x'), bgcolor = ma150_greaterthan_200ma_color, text_size=textsize, text_color=textcolor)
table.cell(table1, 1, 6, str.tostring("150 MA > 200 MA"), bgcolor = color.rgb(6, 192, 224), text_size=textsize, text_color=color.black)
table.cell(table1, 2, 6, str.tostring(per150_200,'#.#') + " %", bgcolor = panelbgcolor, text_size=textsize, text_color=textcolor, tooltip = "Distance between 150 & 200 MA")
//200MA trending up
ma200_uptrend = ma200 > ma200_22
ma200_uptrend_color = color.gray
if not ma200_uptrend
ma200_uptrend_color := color.red
if na(ma200) or na(ma200_22)
ma200_uptrend_color := color.gray
if timeframe.isdaily
per200_22 = (1-(ma200/close))*100
table.cell(table1, 0, 7, (ma200_uptrend ? '✓' : 'x'), bgcolor = ma200_uptrend_color, text_size=textsize, text_color=textcolor)
table.cell(table1, 1, 7, str.tostring("200 MA trending up?"), bgcolor = color.rgb(6, 192, 224), text_size=textsize, text_color=color.black)
table.cell(table1, 2, 7, str.tostring(per200_22,'#.#') + " %", bgcolor = panelbgcolor, text_size=textsize, text_color=textcolor, tooltip = "Distance from 200 MA")
// 52-week High
price_52wh = request.security(syminfo.tickerid,"1D", ta.highest(high,252), lookahead=barmerge.lookahead_off, gaps = barmerge.gaps_off)
get_all_time_high() =>
hi = 0.0
hi := bar_index == 0 ? high : high > hi[1] ? high : hi[1]
[hi]
[ath] = request.security(syminfo.tickerid, 'D', get_all_time_high())
if high > ath
ath := high
if bar_index <= 252
price_52wh := ath
per_52wh = (1-(price_52wh/close))*100
bgcolor52wh = color.red
per52 = 0
if (per_52wh>-25)
per52 := 1
bgcolor52wh := color.gray
table.cell(table1, 0, 8, (per52 ? '✓' : 'x'), bgcolor = bgcolor52wh, text_size=textsize, text_color=textcolor)
table.cell(table1, 1, 8, str.tostring("Within 25% of 52-week High"), bgcolor = color.rgb(6, 192, 224), text_size=textsize, text_color=color.black)
table.cell(table1, 2, 8, str.tostring(price_52wh,'#.#') + " (" + str.tostring(per_52wh,'#.#') + " %" + ")", bgcolor = panelbgcolor, text_size=textsize, text_color=textcolor, tooltip = "52-week High and % Distance from 52-week High")
// 52-week Low
price_52wl = request.security(syminfo.tickerid,"1D", ta.lowest(low,252), lookahead=barmerge.lookahead_off, gaps = barmerge.gaps_off)
get_all_time_low() =>
lo = 0.0
lo := bar_index == 0 ? low : low < lo[1] ? low : lo[1]
[lo]
[atl] = request.security(syminfo.tickerid, 'D', get_all_time_low())
if low < atl
atl := low
if bar_index <= 252
price_52wl := atl
per_52wl = ((close/price_52wl)-1)*100
bgcolor52wl = color.gray
per52l = 1
if (per_52wl<25)
per52l := 0
bgcolor52wl := color.red
table.cell(table1, 0, 9, (per52l ? '✓' : 'x'), bgcolor = bgcolor52wl, text_size=textsize, text_color=textcolor)
table.cell(table1, 1, 9, str.tostring(">25% up from 52-week Low"), bgcolor = color.rgb(6, 192, 224), text_size=textsize, text_color=color.black)
table.cell(table1, 2, 9, str.tostring(price_52wl,'#.#') + " (" + str.tostring(per_52wl,'#.#') + " %" + ")", bgcolor = panelbgcolor, text_size=textsize, text_color=textcolor, tooltip = "52-week Low and % Distance from 52-week Low")
// Does it fulfil Mark Minervini's Criteria?
bgcolor_criteria = color.red
textcolor_satisfy = color.white
fulfil = 0
if close_greaterthan_50ma==1 and close_greaterthan_150ma==1 and close_greaterthan_200ma==1 and ma50_greaterthan_150ma==1 and ma50_greaterthan_200ma==1 and ma150_greaterthan_200ma==1 and ma200_uptrend==1 and per52==1 and per52l==1
fulfil :=1
bgcolor_criteria := color.rgb(88, 247, 114)
textcolor_satisfy := color.black
if timeframe.isdaily
table.merge_cells(table1,0,10,1,10)
table.cell(table1, 0, 10, str.tostring("Does it satisfy Minervini's criteria?"), bgcolor = bgcolor_criteria, text_size=textsize, text_color=textcolor_satisfy)
table.cell(table1, 2, 10, (fulfil ? '✓✓✓' : 'X'), bgcolor = bgcolor_criteria, text_size=textsize, text_color=textcolor_satisfy)
|
Upgraded Watermark | https://www.tradingview.com/script/r9iTBjn1-Upgraded-Watermark/ | Amphibiantrading | https://www.tradingview.com/u/Amphibiantrading/ | 232 | 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/
// © Amphibiantrading
//@version=5
indicator("Upgraded Watermark", shorttitle = 'WM', overlay = true)
yPos = input.string("Middle", "Watermark Location", options = ["Top", "Middle", "Bottom"], inline = '1')
xPos = input.string("Center", " ", options = ["Right","Center", "Left"], inline = '1')
txtCol = input.color(color.rgb(164, 167, 180,30), 'Text Color', inline = '2')
txtSize = input.string('Huge', 'Text Size', options = ['Huge', 'Large', 'Normal', 'Small'], inline = '2')
symTime = input.bool(true, 'Symbol & Time Frame')
compName = input.bool(true, 'Company Name')
indSec = input.bool(true, 'Industry & Sector')
mCap = input.bool(false, 'Show Market Cap')
//switch
sizer = switch txtSize
'Huge' => size.huge
'Large' => size.large
'Normal' => size.normal
'Small' => size.small
//rounding method for marketcap
method rounder(float this) =>
if this >= 1000000000000
market = math.round(math.abs(this / 1000000000000),2)
else if this >= 1000000000
market = math.round(math.abs(this / 1000000000),2)
else
market = math.round(math.abs(this / 1000000),2)
//ticker info
sector = syminfo.sector
ind = syminfo.industry
tick = syminfo.ticker
tf = timeframe.period
name = syminfo.description
tso = syminfo.shares_outstanding_total
tf := timeframe.period == 'D' ? '1D' : timeframe.period == 'W' ? '1W' : timeframe.period == '60' ? '1H' :
timeframe.period == '120' ? '2H' : timeframe.period == '180' ? '3H' : timeframe.period == '240' ? '4H' : tf
//market cap info
marketcap = tso * close
marCap = marketcap > 1000000000000 ? 'T' : marketcap > 1000000000 ? 'B' : 'M'
//plot
var table sec = table.new(str.lower(yPos) + '_' + str.lower(xPos), 1,3, color.new(color.white,100), color.new(color.white,100), 1, color.new(color.white,100), 1)
if barstate.islast
if symTime
sec.cell(0,0,tick + ', ' + tf, text_color = txtCol, text_size = sizer)
if compName
sec.cell(0,1, mCap ? name + ' (' + str.tostring(nz(marketcap.rounder())) + marCap + ')' : name, text_color = txtCol, text_size = sizer)
if indSec
sec.cell(0,2, not na(sector) ? sector + ', ' + ind : '', text_color = txtCol, text_size = sizer)
|
Bitcoin Economics Adaptive Multiple | https://www.tradingview.com/script/yKWVgxS7-Bitcoin-Economics-Adaptive-Multiple/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 181 | 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/
// © QuantiLuxe
//@version=5
indicator("Bitcoin Economics Adaptive Multiple", "{Ʌ} - 𝔹𝔼𝔸𝕄", false)
upper = input.float(0.96, "Upper Threshold", step = 0.01)
lower = input.float(0.07, "Upper Threshold", step = 0.01)
var int count = 0
count += 1
beam = math.log(close / ta.sma(close, math.min(count, 1400))) / 2.5
max = hline(1.2, display = display.none)
hh = hline(upper, display = display.none)
min = hline(-0.25, display = display.none)
ll = hline(lower, display = display.none)
fill(hh, max, color = #bb00104d)
fill(ll, min, color = #00b35144)
plot(beam, "𝔹𝔼𝔸𝕄", color.from_gradient(beam, lower, upper, #00FF7F, #FF3D51), 2) |
ATR Visualizer | https://www.tradingview.com/script/pSQ8jMGO-ATR-Visualizer/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 64 | 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/
// © peacefulLizard50262
//@version=5
indicator("Range", overlay = true)
length = input.int(10, "Length", 1)
candle_1 = input.string("Bear/Bull Range", "Style", ["Bear/Bull Range", "Bearish Range", "Bullish Range","Average Range", "Cumulative Average Range"])
candle_2 = input.string("Disabled", "Style", ["Disabled", "Bear/Bull Range", "Bearish Range", "Bullish Range","Average Range", "Cumulative Average Range"])
bullish_color = input.color(color.green, "Color", inline = "color")
even_color = input.color(color.gray, "", inline = "color")
bearish_color = input.color(color.red, "", inline = "color")
ema(source)=>
var float ema = 0.0
var int count = 0
if source != 0
count := nz(count[1]) + 1
ema := (1.0 - 2.0 / (count + 1.0)) * nz(ema[1]) + 2.0 / (count + 1.0) * source
ema
bullish_average_body(length)=>
var float ema = 0.0
if close > open
ema := (1.0 - 2.0 / (length + 1.0)) * nz(ema[1]) + 2.0 / (length + 1.0) * math.abs(close - open)
ema
bullish_average_top_wick(length)=>
var float ema = 0.0
wick = close > open ? math.abs(high - close) : math.abs(high - open)
if wick != 0 and close > open
ema := (1.0 - 2.0 / (length + 1.0)) * nz(ema[1]) + 2.0 / (length + 1.0) * wick
ema
bullish_average_bottom_wick(length)=>
var float ema = 0.0
wick = close > open ? math.abs(open - low) : math.abs(close - low)
if wick != 0 and close > open
ema := (1.0 - 2.0 / (length + 1.0)) * nz(ema[1]) + 2.0 / (length + 1.0) * wick
ema
bearish_average_body(length)=>
var float ema = 0.0
if close < open
ema := (1.0 - 2.0 / (length + 1.0)) * nz(ema[1]) + 2.0 / (length + 1.0) * math.abs(open - close)
ema
bearish_average_top_wick(length)=>
var float ema = 0.0
wick = close > open ? math.abs(high - close) : math.abs(high - open)
if wick != 0 and close < open
ema := (1.0 - 2.0 / (length + 1.0)) * nz(ema[1]) + 2.0 / (length + 1.0) * wick
ema
bearish_average_bottom_wick(length)=>
var float ema = 0.0
wick = close > open ? math.abs(open - low) : math.abs(close - low)
if wick != 0 and close < open
ema := (1.0 - 2.0 / (length + 1.0)) * nz(ema[1]) + 2.0 / (length + 1.0) * wick
ema
windowed_top_wick(length)=>
ta.rma(close > open ? math.abs(high - close) : math.abs(high - open), length)
windowed_bottom_wick(length)=>
ta.rma(close > open ? math.abs(open - low) : math.abs(close - low), length)
windowed_bear_bull_ratio(length = 10)=>
bull_count = 0
bear_count = 0
for i = 0 to length - 1
if open[i] < close[i]
bull_count += 1
if open[i] > close[i]
bear_count += 1
log_bear_bull_ratio = math.log(bull_count / bear_count)
bear_bull_ratio()=>
var bull_count = 0
var bear_count = 0
if open < close
bull_count += 1
if open > close
bear_count += 1
log_bear_bull_ratio = math.log(bull_count / bear_count)
average_body = ema(math.abs(open - close))
average_top_wick = ema(open < close ? high - close : high - open)
average_bottom_wick = ema(open < close ? open - low : close - low)
bear_bull_ratio = bear_bull_ratio()
bear_bull_ratio_status = bear_bull_ratio >= 0
center = 0
average_open = bear_bull_ratio_status ? center - average_body / 2 : center + average_body / 2
average_close = bear_bull_ratio_status ? center + average_body / 2 : center - average_body / 2
average_high = bear_bull_ratio_status ? average_close + average_top_wick : average_open + average_top_wick
average_low = bear_bull_ratio_status ? average_open - average_bottom_wick : average_close - average_bottom_wick
top_value = bear_bull_ratio_status ? average_close : average_open
bottom_value = bear_bull_ratio_status ? average_open : average_close
average_color = bear_bull_ratio > 0 ? bullish_color : bear_bull_ratio < 0 ? bearish_color : even_color
windowed_body = ta.ema(ta.tr, length)
windowed_top_wick = windowed_top_wick(length)
windowed_bottom_wick = windowed_bottom_wick(length)
windowed_bear_bull_ratio = windowed_bear_bull_ratio(length)
windowed_condition = windowed_bear_bull_ratio >= 0
windowed_color = windowed_bear_bull_ratio > 0 ? bullish_color : windowed_bear_bull_ratio < 0 ? bearish_color : even_color
windowed_open = windowed_condition ? center - windowed_body / 2 : center + windowed_body / 2
windowed_close = windowed_condition ? center + windowed_body / 2 : center - windowed_body / 2
windowed_high = windowed_condition ? windowed_close + windowed_top_wick : windowed_open + windowed_top_wick
windowed_low = windowed_condition ? windowed_open - windowed_bottom_wick : windowed_close - windowed_bottom_wick
windowed_top_value = windowed_condition ? average_close : average_open
windowed_bottom_value = windowed_condition ? average_open : average_close
bullish_average_body = bullish_average_body(length)
bullish_average_top_wick = bullish_average_top_wick(length)
bullish_average_bottom_wick = bullish_average_bottom_wick(length)
bullish_close = center + bullish_average_body / 2
bullish_open = center - bullish_average_body / 2
bullish_high = bullish_close + bullish_average_top_wick
bullish_low = bullish_open - bullish_average_bottom_wick
bearish_average_body = bearish_average_body(length)
bearish_average_top_wick = bearish_average_top_wick(length)
bearish_average_bottom_wick = bearish_average_bottom_wick(length)
bearish_open = center + bearish_average_body / 2
bearish_close = center - bearish_average_body / 2
bearish_high = bearish_open + bearish_average_top_wick
bearish_low = bearish_close - bearish_average_bottom_wick
candle_state = close > open
current_color = candle_state ? bullish_color : bearish_color
current_body = math.abs(close - open)
current_top_wick = candle_state ? math.abs(high - close) : math.abs(high - open)
current_bottom_wick = candle_state ? math.abs(open - low) : math.abs(close - low)
current_open = candle_state ? center - current_body / 2 : center + current_body / 2
current_close = candle_state ? center + current_body / 2 : center - current_body / 2
current_high = candle_state ? current_close + current_top_wick : current_open + current_top_wick
current_low = candle_state ? current_open - current_bottom_wick : current_close - current_bottom_wick
current_top = candle_state ? current_close : current_open
current_bottom = candle_state ? current_open : current_close
oc2 = math.avg(open, close)
type candle
box body
line top_wick
line bottom_wick
method delete(candle id)=>
box.delete(id.body)
line.delete(id.top_wick)
line.delete(id.bottom_wick)
type position
int x1 = na
int x2 = na
int x3 = na
type values
float t = na
float b = na
float h = na
float l = na
color c = na
bullish_values = values.new(
bullish_close[1] + oc2
, bullish_open[1] + oc2
, bullish_high[1] + oc2
, bullish_low[1] + oc2
, bullish_color
)
bearish_values = values.new(
bearish_open[1] + oc2
, bearish_close[1] + oc2
, bearish_high[1] + oc2
, bearish_low[1] + oc2
, bearish_color
)
windowed_values = values.new(
windowed_top_value[1] + oc2
, windowed_bottom_value[1] + oc2
, windowed_high[1] + oc2
, windowed_low[1] + oc2
, windowed_color
)
average_values = values.new(
top_value[1] + oc2
, bottom_value[1] + oc2
, average_high[1] + oc2
, average_low[1] + oc2
, average_color
)
bear_bull_values()=>
switch close > open
true => bullish_values
false => bearish_values
first_position = position.new(
bar_index + 1
, bar_index + 3
, bar_index + 2
)
second_position = position.new(
bar_index + 4
, bar_index + 6
, bar_index + 5
)
candle_values(string style)=>
values out = switch style
"Disabled" => values.new()
"Bear/Bull Range" => bear_bull_values()
"Bearish Range" => bearish_values
"Bullish Range" => bullish_values
"Average Range" => windowed_values
"Cumulative Average Range" => average_values
out
candle_1_values = candle_values(candle_1)
candle_2_values = candle_values(candle_2)
first_candle = candle.new(box.new(first_position.x1, candle_1_values.t, first_position.x2, candle_1_values.b, candle_1_values.c, bgcolor = candle_1_values.c)
, line.new(first_position.x3, candle_1_values.t, first_position.x3, candle_1_values.h, color = candle_1_values.c)
, line.new(first_position.x3, candle_1_values.b, first_position.x3, candle_1_values.l, color = candle_1_values.c)
)
second_candle = candle.new(box.new(second_position.x1, candle_2_values.t, second_position.x2, candle_2_values.b, candle_2_values.c, bgcolor = candle_2_values.c)
, line.new(second_position.x3, candle_2_values.t, second_position.x3, candle_2_values.h, color = candle_2_values.c)
, line.new(second_position.x3, candle_2_values.b, second_position.x3, candle_2_values.l, color = candle_2_values.c)
)
if barstate.isconfirmed
first_candle.delete()
second_candle.delete()
|
Days Higher Than Current Price | https://www.tradingview.com/script/ujSBTygF-Days-Higher-Than-Current-Price/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 200 | 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/
// © QuantiLuxe
//@version=5
indicator("Days Higher Than Current Price", "{Ʌ} - 𝒟𝒶𝓎𝓈 𝐻𝒾𝑔𝒽𝑒𝓇", true)
f_h() =>
var price = array.new<float>(na)
array.unshift(price, close)
int count = 0
for i = 1 to array.size(price) < 500 ? array.size(price) : 500
if na(close[1])
break
if array.get(price, i - 1) > close
count += 1
count
val = f_h()
col = switch
val <= 200 => color.from_gradient(val, 0, 200, #00abe4, #00FF7F)
val > 200 and val <= 400 => color.from_gradient(val, 201, 400, #00FF7F, #FFA500)
val > 400 => color.from_gradient(val, 400, 500, #FFA500, #FF0000)
f_col(j) =>
cell_col = switch
j <= 7 => color.from_gradient(j, 0, 7, #FF0000, #FFA500)
j > 7 and j <= 15 => color.from_gradient(j, 7, 15, #FFA500, #00FF7F)
j > 15 => color.from_gradient(j, 15, 19, #00FF7F, #00abe4)
plotcandle(open, high, low, close, "", col, col, false, na, col)
var table Main = table.new(position.middle_right, 2, 20)
if barstate.islast
table.cell(Main, 0, 0, "500", text_color = chart.fg_color, text_size = size.small), table.cell(Main, 0, 3, "400", text_color = chart.fg_color, text_size = size.small)
table.cell(Main, 0, 7, "300", text_color = chart.fg_color, text_size = size.small), table.cell(Main, 0, 11, "200", text_color = chart.fg_color, text_size = size.small)
table.cell(Main, 0, 15, "100", text_color = chart.fg_color, text_size = size.small), table.cell(Main, 0, 19, "0", text_color = chart.fg_color, text_size = size.small)
for j = 0 to 19
table.cell(Main, 1, j, "", bgcolor = f_col(j), height = 4)
|
Recursive Micro Zigzag | https://www.tradingview.com/script/WCQ3CFl6-Recursive-Micro-Zigzag/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 183 | study | 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
indicator("Recursive Micro Zigzag", overlay = true, max_lines_count=500)
import HeWhoMustNotBeNamed/Drawing/3 as dr
ltf = input.timeframe('1', 'Lower timeframe')
levelToDisplay = input.int(4, 'Level to Display')
backtestBars = input.int(5000, 'Backtest Bars', minval=500, maxval=20000, step=500)
type Pivot
dr.Point point
int dir
int level = 0
type Zigzag
array<Pivot> zigzagPivots
array<Pivot> newPivots
array<dr.Line> zigzagLines
bool removeLast = false
Pivot removedPivot
Pivot tempBullishPivot
Pivot tempBearishPivot
method addnewpivot(Zigzag this, Pivot pivot)=>
dir = math.sign(pivot.dir)
if(this.zigzagPivots.size() >=1)
lastPivot = this.zigzagPivots.get(0)
lastValue = lastPivot.point.price
if(math.sign(lastPivot.dir) == math.sign(dir))
runtime.error('Direction mismatch')
if(this.zigzagPivots.size() >=2)
llastPivot = this.zigzagPivots.get(1)
value = pivot.point.price
llastValue = llastPivot.point.price
newDir = dir * value > dir * llastValue ? dir * 2 : dir
pivot.dir := int(newDir)
this.zigzagPivots.unshift(pivot)
this.newPivots.push(pivot)
this
method resetFlags(Zigzag this)=>
this.removeLast := false
this.removedPivot := na
this.newPivots.clear()
method removeLast(Zigzag this)=>
this.removedPivot := this.zigzagPivots.shift()
this.removeLast := true
method addNew(Zigzag this, Pivot pivot)=>
if(this.zigzagPivots.size() == 0)
this.zigzagPivots.unshift(pivot)
false
else
lastPivot = this.zigzagPivots.first()
if(math.sign(lastPivot.dir) == math.sign(pivot.dir) and pivot.point.price*pivot.dir > lastPivot.point.price*pivot.dir)
this.removeLast()
if(pivot.point.price*pivot.dir > lastPivot.point.price*pivot.dir)
this.addnewpivot(pivot)
true
method addNextLevelPivot(Zigzag nextLevel, Pivot pivot)=>
lPivot = Pivot.copy(pivot)
dir = lPivot.dir
newDir = math.sign(dir)
value = lPivot.point.price
lPivot.level := lPivot.level+1
if(nextLevel.zigzagPivots.size() > 0)
lastPivot = nextLevel.zigzagPivots.first()
lastDir = math.sign(lastPivot.dir)
lastValue = lastPivot.point.price
if(math.abs(dir) == 2)
if(lastDir == newDir)
if(dir*lastValue < dir*value)
nextLevel.removeLast()
else
tempPivot = newDir >0 ? nextLevel.tempBearishPivot : nextLevel.tempBullishPivot
if(not na(tempPivot))
nextLevel.addnewpivot(tempPivot)
else
tempFirstPivot = newDir >0 ? nextLevel.tempBullishPivot : nextLevel.tempBearishPivot
tempSecondPivot = newDir >0 ? nextLevel.tempBearishPivot : nextLevel.tempBullishPivot
if(not na(tempFirstPivot) and not na(tempSecondPivot))
tempVal = tempFirstPivot.point.price
val = lPivot.point.price
if(newDir*tempVal > newDir*val)
nextLevel.addnewpivot(tempFirstPivot)
nextLevel.addnewpivot(tempSecondPivot)
nextLevel.addnewpivot(lPivot)
nextLevel.tempBullishPivot := na
nextLevel.tempBearishPivot := na
true
else
tempPivot = newDir > 0? nextLevel.tempBullishPivot : nextLevel.tempBearishPivot
if(not na(tempPivot))
tempDir = tempPivot.dir
tempVal = tempPivot.point.price
val = lPivot.point.price
if(val*dir > tempVal*dir)
if(newDir > 0)
nextLevel.tempBullishPivot := lPivot
else
nextLevel.tempBearishPivot := lPivot
false
else
if(newDir > 0)
nextLevel.tempBullishPivot := lPivot
else
nextLevel.tempBearishPivot := lPivot
true
else if(math.abs(dir) == 2)
nextLevel.addnewpivot(lPivot)
true
method getColor(Pivot this)=>
this.dir == 2? color.green :
this.dir == 1? color.orange :
this.dir == -1? color.lime :
this.dir == -2 ? color.red : color.blue
method draw(Zigzag this, bool highlight = false)=>
if(this.removeLast and this.zigzagLines.size() > 0)
this.zigzagLines.shift().delete()
for [index, newPivot] in this.newPivots
if(this.zigzagPivots.size() > this.newPivots.size()-index)
dr.LineProperties properties = dr.LineProperties.new(color = newPivot.getColor(), style = highlight? line.style_solid : line.style_dotted, width = highlight? 2 : 0)
this.zigzagLines.unshift(this.zigzagPivots.get(this.newPivots.size()-index).point.createLine(newPivot.point, properties).draw())
[lh, ll, lv] = request.security_lower_tf(syminfo.tickerid, ltf, [high, low, volume], true)
if(bar_index >= (last_bar_index - backtestBars))
hIndices = array.sort_indices(lh, order.descending)
highestIndex = array.size(hIndices) >= 5? array.get(hIndices, 0) : 0
lIndices = array.sort_indices(ll, order.ascending)
lowestIndex = array.size(lIndices) >= 5? array.get(lIndices, 0) : 0
var array<Zigzag> zigzagMatrix = array.from(Zigzag.new(array.new<Pivot>(), array.new<Pivot>(), array.new<dr.Line>()))
if not na(highestIndex) and not na(lowestIndex)
Pivot pHigh = Pivot.new(dr.Point.new(high, bar_index, time), 1)
Pivot pLow = Pivot.new(dr.Point.new(low, bar_index, time), -1)
currentZigzag = zigzagMatrix.first()
currentZigzag.addNew(highestIndex<lowestIndex?pHigh:pLow)
currentZigzag.addNew(highestIndex<lowestIndex?pLow:pHigh)
level = 0
while(currentZigzag.zigzagPivots.size() > 0 and currentZigzag.newPivots.size() > 0 and level <= levelToDisplay)
level := level+1
if(zigzagMatrix.size()<=level)
zigzagMatrix.push(Zigzag.new(array.new<Pivot>(), array.new<Pivot>(), array.new<dr.Line>()))
nextZigzag = zigzagMatrix.get(level)
if(currentZigzag.removeLast and nextZigzag.zigzagPivots.size() > 0?
(currentZigzag.removedPivot.point.price == nextZigzag.zigzagPivots.first().point.price and
currentZigzag.removedPivot.point.bar == nextZigzag.zigzagPivots.first().point.bar) : false )
nextZigzag.removeLast()
for [index, newPivot] in currentZigzag.newPivots
nextZigzag.addNextLevelPivot(newPivot)
if(levelToDisplay == level-1)
currentZigzag.draw(levelToDisplay == level-1)
currentZigzag.resetFlags()
currentZigzag := nextZigzag
|
Rough Average | https://www.tradingview.com/script/bO3SyHtK-Rough-Average/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 181 | 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/
// © QuantiLuxe
//@version=5
indicator("Rough Average", "{Ʌ} - Rough Avg.", false)
len = input.int(14, "Length", group = "Rough AVG")
upper = input.int(80, "Upper Level", group = "Rough AVG")
lower = input.int(20, "Lower Level", group = "Rough AVG")
colbar = input.string("None", "Bar Coloring", ["None", "Trend", "Extremities", "Reversions"], group = "UI Options")
revshow = input.bool(true, "Show Reversal Signals", group = "UI Options")
f_checkp() =>
p = close
count = 0
while p > 1
p /= 10
count += 1
math.pow(10, count)
f_profile(len) =>
l = len
integral = 0.0
f_x = math.abs(ta.rsi(close, len))
for x = low / f_checkp() to high / f_checkp()
integral := integral + f_x
l * integral
spacing_profile = f_profile(len)
ra = ta.rsi(ta.ema(spacing_profile, len), len)
col_up = #3179f5
col_dn = #ab47bc
d = plot(ra, "RA", ra > 50 ? color.from_gradient(ra, 40, upper, #00000000, col_up) : color.from_gradient(ra, lower, 60, col_dn, #00000000))
hline(50, "Mid Line", #ffffff80, hline.style_dotted)
u = plot(upper, "Upper Line", #ffffff80, display = display.pane)
l = plot(lower, "Lower Line", #ffffff80, display = display.pane)
fill(d, u, 95, upper, col_dn, #aa47bc00)
fill(d, l, lower, 5, #3179f500, col_up)
plotshape(revshow ? ra > upper and ra < ra[1] and not (ra[1] < ra[2]) ? 110 : na : na, "OB", shape.triangledown, location.absolute, col_up, size = size.tiny)
plotshape(revshow ? ra < lower and ra > ra[1] and not (ra[1] > ra[2]) ? -10 : na : na, "OS", shape.triangleup, location.absolute, col_dn, size = size.tiny)
color col = switch colbar
"None" => na
"Trend" => ra > 50 ? col_up : col_dn
"Extremities" => ra > upper ? col_up : ra < lower ? col_dn : #b3b3b3c2
"Reversions" => ra > upper and ra < ra[1] and not (ra[1] < ra[2]) ? col_up : ra < lower and ra > ra[1] and not (ra[1] > ra[2]) ? col_dn : #b3b3b3c2
barcolor(col) |
Liquidity Sentiment Profile [LuxAlgo] | https://www.tradingview.com/script/asr7nOb2-Liquidity-Sentiment-Profile-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,932 | 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/
// © LuxAlgo
//@version=5
indicator("Liquidity Sentiment Profile [LuxAlgo]", "LuxAlgo - Liquidity Sentiment Profile", true, max_bars_back = 5000, max_boxes_count = 500, max_lines_count = 500)
//------------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------{
rpGR = 'Rainbow Profiles'
tfTP = 'The indicator resolution is set by the input of the Anchor Period. If the Anchor Period is set to AUTO (the default value), then the increased resolution is determined by the following algorithm:\n\n' +
' - for intraday resolutions up to 4 Hour, DAY (1D) is used\n - for intraday resolutions equal to 4 Hour, WEEK (1W) is used\n - for daily resolutions MONTH is used (1M)\n - for weekly resolution, 3-MONTH (3M) is used\n - for monthly resolution, 12-MONTH (12M) is used\n\n' +
'Note : Difference between Session and Day\n - Day will take into account extended hours (if present on the chart), whereas\n - Session will assume only regular trading hours. Session is default value for AUTO Anchor Period'
tfIN = input.string('Auto', 'Anchor Period', options=['Auto', 'Session', 'Day', 'Week', 'Month', 'Quarter', 'Year'], group = rpGR, tooltip = tfTP)
tfOT = tfIN == 'Session' or tfIN == 'Day' ? 'D' : tfIN == 'Week' ? 'W' : tfIN == 'Month' ? 'M' : tfIN == 'Quarter' ? '3M' : tfIN == 'Year' ? '12M' : timeframe.isintraday and timeframe.period != '240' ? 'D' : timeframe.period == '240' ? 'W' : timeframe.isdaily ? 'M' : timeframe.isweekly ? '3M' : '12M'
vpGR = 'Liquidity Profile Settings'
vpTP = 'displays total trading activity (common interest, both buying and selling trading activity) over a specified time period at specific price levels\n\n' +
' - high traded node rows : high trading activity price levels - usually represents consolidation levels (value areas)\n' +
' - average traded node rows : average trading activity price levels\n' +
' - low traded node rows : low trading activity price levels - usually represents supply & demand levels or liquidity levels\n\n' +
'row lengths, indicates the amount of the traded activity at specific price levels'
vpSH = input.bool(true, 'Liquidity Profile', group = vpGR, tooltip = vpTP)
vpHVC = input.color(color.new(#ff9800, 81), 'High Traded Nodes', inline='VP1', group = vpGR)
vpHVT = input.int(73, 'Threshold %' , minval = 50, maxval = 99 , step = 1,inline='VP1', group = vpGR, tooltip = 'option range [50-99]') / 100
vpAVC = input.color(color.new(#787b86, 81), 'Average Traded Nodes', group = vpGR)
vpLVC = input.color(color.new(#2962ff, 81), 'Low Traded Nodes', inline='VP2', group = vpGR)
vpLVT = input.int(21, 'Threshold %' , minval = 10, maxval = 40 , step = 1,inline='VP2', group = vpGR, tooltip = 'option range [10-40]') / 100
spGR = 'Sentiment Profile Settings'
spTP = 'displays the sentiment, the dominat party over a specified time period at the specific price levels\n\n' +
' - bullish node rows : buying trading activity is higher\n' +
' - barish node rows : selling trading activity is higher\n\n' +
'row lengths, indicates the strength of the buyers/sellers at the specific price levels'
spSH = input.bool(true, 'Sentiment Profile', group = spGR, tooltip = spTP)
spBLC = input.color(color.new(#26a69a, 81), 'Bullish Nodes', inline='SP', group = spGR)
spBRC = input.color(color.new(#ef5350, 81), 'Bearish Nodes', inline='SP', group = spGR)
othGR = 'Other Settings'
pcTP = 'displays the changes of the price levels with the highest traded activity'
rpPC = input.bool(false, 'Level of Significance', inline='PoC', group = othGR, tooltip = pcTP)
rpPCC = input.color(color.new(#ff0000, 0), '', inline='PoC', group = othGR)
rpPCW = input.int(2, '', inline='PoC', group = othGR)
rpPL = input.bool(false, 'Profile Price Levels', inline = 'BBe', group = othGR)
rpPLC = input.color(color.new(#00bcd4, 0), '', inline = 'BBe', group = othGR)
rpLS = input.string('Small', "", options=['Tiny', 'Small', 'Normal'], inline = 'BBe', group = othGR)
rpNR = input.int(25, 'Number of Rows' , minval = 10, maxval = 100 ,step = 5, group = othGR, tooltip = 'option range [10-100]')
rpW = input.int(50, 'Profile Width %', minval = 10, maxval = 50, group = othGR, tooltip = 'option range [10-50]') / 100
rpBG = input.bool(true, 'Profile Range Background Fill', inline = 'BG', group = othGR)
rpBGC = input.color(color.new(#00bcd4, 95), '', inline = 'BG', group = othGR)
//-----------------------------------------------------------------------------}
// User Defined Types
//-----------------------------------------------------------------------------{
// @type bar properties with their values
//
// @field o (float) open price of the bar
// @field h (float) high price of the bar
// @field l (float) low price of the bar
// @field c (float) close price of the bar
// @field v (float) volume of the bar
// @field i (int) index of the bar
type bar
float o = open
float h = high
float l = low
float c = close
float v = volume
int i = bar_index
//-----------------------------------------------------------------------------}
// Variables
//-----------------------------------------------------------------------------{
bar b = bar.new()
rpVST = array.new_float(rpNR + 1, 0.)
rpVSB = array.new_float(rpNR + 1, 0.)
rpVSD = array.new_float(rpNR + 1, 0.)
aRP = array.new_box()
aPC = array.new_line()
lRP = array.new_label()
var dRP = array.new_box()
var dPC = array.new_line()
var x1 = 0
var x2 = 0
var float pir = na, var float eki = na
//-----------------------------------------------------------------------------}
// Functions/methods
//-----------------------------------------------------------------------------{
// @function calculates htf highest and lowest price value
//
// @param _tf (strings) timeframe value
// @param _tfi (strings) session specific timeframe value
//
// @returns [float, float] highest and lowest price value
f_htfHL(_tf, _tfi) =>
var h = 0., var l = 0.
var hx = 0., var lx = 0.
chg = _tf == 'D' and _tfi == 'Day' ? dayofweek != dayofweek[1] : ta.change(time(_tf))
if chg
hx := h
h := b.h
lx := l
l := b.l
else
h := math.max(b.h, h)
l := math.min(b.l, l)
[hx, lx]
// @function creates new label object and updates existing label objects
//
// @param details in Pine Script™ language reference manual
//
// @returns none, updated visual objects (labels)
f_drawLabelX(_x, _y, _text, _style, _textcolor, _size, _tooltip) =>
var lb = label.new(_x, _y, _text, xloc.bar_index, yloc.price, color(na), _style, _textcolor, _size, text.align_left, _tooltip)
lb.set_xy(_x, _y)
lb.set_text(_text)
lb.set_tooltip(_tooltip)
lb.set_textcolor(_textcolor)
//-----------------------------------------------------------------------------}
// Calculations
//-----------------------------------------------------------------------------{
bull = b.c > b.o
nzV = nz(b.v)
rpS = switch rpLS
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
if tfOT == 'D' and tfIN == 'Day' ? dayofweek != dayofweek[1] : ta.change(time(tfOT))
x1 := x2
x2 := b.i
rpLN = x2 - x1
[pHST, pLST] = f_htfHL(tfOT, tfIN)
pSTP = (pHST - pLST) / rpNR
vRPI = last_bar_index - b.i <= (math.round(500 / (spSH ? rpNR * 2 : rpNR)) - 1) * rpLN
proceed = tfOT == 'D' and tfIN == 'Day' ? dayofweek != dayofweek[1] : ta.change(time(tfOT))
if proceed and nzV and timeframe.period != tfOT and not timeframe.isseconds and pSTP > 0 and b.i > rpLN
if dRP.size() > 0
for i = 0 to dRP.size() - 1
box.delete(dRP.shift())
for bI = rpLN to 1 //1 to rpLN
l = 0
for pLL = pLST to pHST by pSTP
if b.h[bI] >= pLL and b.l[bI] < pLL + pSTP
rpVST.set(l, rpVST.get(l) + nzV[bI] * ((b.h[bI] - b.l[bI]) == 0 ? 1 : pSTP / (b.h[bI] - b.l[bI])) )
if bull[bI] and spSH
rpVSB.set(l, rpVSB.get(l) + nzV[bI] * ((b.h[bI] - b.l[bI]) == 0 ? 1 : pSTP / (b.h[bI] - b.l[bI])) )
l += 1
if rpPC and vRPI
if bI == rpLN
aPC.push(line.new(b.i[bI] - 1, eki, b.i[bI], pLST + (rpVST.indexof(rpVST.max()) + .50) * pSTP, color = rpPCC, width = rpPCW))
pir := pLST + (rpVST.indexof(rpVST.max()) + .50) * pSTP
else
aPC.push(line.new(b.i[bI] - 1, pir, b.i[bI], pLST + (rpVST.indexof(rpVST.max()) + .50) * pSTP, color = rpPCC, width = rpPCW))
pir := pLST + (rpVST.indexof(rpVST.max()) + .50) * pSTP
eki := pLST + (rpVST.indexof(rpVST.max()) + .50) * pSTP
for l = 0 to rpNR - 1
bbp = 2 * rpVSB.get(l) - rpVST.get(l)
rpVSD.set(l, rpVSD.get(l) + bbp * (bbp > 0 ? 1 : -1) )
if rpBG
aRP.push(box.new(b.i - rpLN, pLST, b.i, pHST, rpBGC, 1, line.style_dotted, bgcolor = rpBGC ))
if rpPL and vRPI
lRP.push(label.new(b.i - rpLN / 2, pHST, str.tostring(pHST, format.mintick), xloc.bar_index, yloc.price, color(na), label.style_label_down, rpPLC, rpS, text.align_left, 'Profile High - ' + str.tostring(pHST, format.mintick) + '\n %' + str.tostring((pHST - pLST) / pLST * 100, '#.##') + ' higher than the Profile Low\n\n# bars : ' + str.tostring(rpLN) ))
lRP.push(label.new(b.i - rpLN / 2, pLST, str.tostring(pLST, format.mintick), xloc.bar_index, yloc.price, color(na), label.style_label_up , rpPLC, rpS, text.align_left, 'Profile Low - ' + str.tostring(pLST, format.mintick) + '\n %' + str.tostring((pHST - pLST) / pHST * 100, '#.##') + ' lower than the Profile High\n\n# bars : ' + str.tostring(rpLN) ))
for l = 0 to rpNR - 1
if vpSH
sBI = b.i - rpLN / 2
eBI = sBI + int( rpVST.get(l) / rpVST.max() * rpLN * rpW)
llC = rpVST.get(l) / rpVST.max() > vpHVT ? vpHVC : rpVST.get(l) / rpVST.max() < vpLVT ? vpLVC : vpAVC
aRP.push(box.new(sBI, pLST + (l + 0.) * pSTP, eBI, pLST + (l + 1.) * pSTP, llC, bgcolor = llC))
if spSH
bbp = 2 * rpVSB.get(l) - rpVST.get(l)
sBI = b.i - rpLN / 2
eBI = sBI - int( rpVSD.get(l) / rpVSD.max() * rpLN * rpW)
aRP.push(box.new(sBI, pLST + (l + 0.) * pSTP, eBI, pLST + (l + 1.) * pSTP, bbp > 0 ? spBLC : spBRC, bgcolor = bbp > 0 ? spBLC : spBRC ))
rpLN := barstate.islast ? last_bar_index - x2 : 1
pHST := ta.highest(high, rpLN > 0 ? rpLN : 1)
pLST := ta.lowest (low , rpLN > 0 ? rpLN : 1)
pSTP := (pHST - pLST) / rpNR
if barstate.islast and nzV and timeframe.period != tfOT and not timeframe.isseconds and rpLN > 0 and pSTP > 0
if dRP.size() > 0
for i = 0 to dRP.size() - 1
box.delete(dRP.shift())
if dPC.size() > 0
for i = 0 to dPC.size() - 1
line.delete(dPC.shift())
for bI = rpLN to 0
l = 0
for pLL = pLST to pHST by pSTP
if b.h[bI] >= pLL and b.l[bI] < pLL + pSTP
rpVST.set(l, rpVST.get(l) + nzV[bI] * ((b.h[bI] - b.l[bI]) == 0 ? 1 : pSTP / (b.h[bI] - b.l[bI])) )
if bull[bI] and spSH
rpVSB.set(l, rpVSB.get(l) + nzV[bI] * ((b.h[bI] - b.l[bI]) == 0 ? 1 : pSTP / (b.h[bI] - b.l[bI])) )
l += 1
if rpPC
if bI == rpLN
dPC.push(line.new(b.i[bI] - 1, eki, b.i[bI], pLST + (rpVST.indexof(rpVST.max()) + .50) * pSTP, color = rpPCC, width = rpPCW))
pir := pLST + (rpVST.indexof(rpVST.max()) + .50) * pSTP
else
dPC.push(line.new(b.i[bI] - 1, pir, b.i[bI], pLST + (rpVST.indexof(rpVST.max()) + .50) * pSTP, color = rpPCC, width = rpPCW))
pir := pLST + (rpVST.indexof(rpVST.max()) + .50) * pSTP
for l = 0 to rpNR - 1
bbp = 2 * rpVSB.get(l) - rpVST.get(l)
rpVSD.set(l, rpVSD.get(l) + bbp * (bbp > 0 ? 1 : -1) )
if rpBG
dRP.push(box.new(b.i - rpLN, pLST, b.i, pHST, rpBGC, bgcolor = rpBGC ))
if rpPL
f_drawLabelX(b.i - rpLN / 2, pHST, str.tostring(pHST, format.mintick), label.style_label_down, rpPLC, rpS, 'Profile High - ' + str.tostring(pHST, format.mintick) + '\n %' + str.tostring((pHST - pLST) / pLST * 100, '#.##') + ' higher than the Profile Low\n\nNumber of bars : ' + str.tostring(rpLN))
f_drawLabelX(b.i - rpLN / 2, pLST, str.tostring(pLST, format.mintick), label.style_label_up , rpPLC, rpS, 'Profile Low - ' + str.tostring(pLST, format.mintick) + '\n %' + str.tostring((pHST - pLST) / pHST * 100, '#.##') + ' lower than the Profile High\n\nNumber of bars : ' + str.tostring(rpLN))
for l = 0 to rpNR - 1
if vpSH
sBI = b.i - rpLN / 2
eBI = sBI + int( rpVST.get(l) / rpVST.max() * rpLN * rpW)
llC = rpVST.get(l) / rpVST.max() > vpHVT ? vpHVC : rpVST.get(l) / rpVST.max() < vpLVT ? vpLVC : vpAVC
dRP.push(box.new(sBI, pLST + (l + 0.) * pSTP, eBI, pLST + (l + 1.) * pSTP, llC, bgcolor = llC ))
if spSH
bbp = 2 * rpVSB.get(l) - rpVST.get(l)
sBI = b.i - rpLN / 2
eBI = sBI - int( rpVSD.get(l) / rpVSD.max() * rpLN * rpW)
dRP.push(box.new(sBI, pLST + (l + 0.) * pSTP, eBI, pLST + (l + 1.) * pSTP, bbp > 0 ? spBLC : spBRC, bgcolor = bbp > 0 ? spBLC : spBRC ))
//-----------------------------------------------------------------------------} |
REVE Cohorts - Range Extension Volume Expansion Cohorts | https://www.tradingview.com/script/b4igiL2c-REVE-Cohorts-Range-Extension-Volume-Expansion-Cohorts/ | eykpunter | https://www.tradingview.com/u/eykpunter/ | 60 | 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/
// © eykpunter
//@version=5
indicator("Range Extension Volume Expansion Cohorts", shorttitle="REVE Cohorts", max_labels_count = 100)
pertttext="Script uses timeframe to set lookback - month and week: 14, day: 21, 4hour and 3hour:28, 1hour and 45min: 35, 15min: 42, 5min and 3min: 49, 1min: 56"
perwish=input.bool(true, "script sets lookback (overrides user)", tooltip=pertttext)
perfeedback=input.bool(false, "show feedback label about lookback")
evaltttext="e.g. when set to 10 the Range Candles will show confirms or falters toward direction of slope of 10 period Moving Average"
eval=input.int(10,"Look back (when script setting is off)",1,tooltip=evaltttext, group="DIRECTION AND RANGE")
//input colors for price direction
ttup="uptrend marker line, range candle border in uptrend, candle body in confirm uptrend, transparent in falter downtrend candles"
ttdn="downtrend marker line, range candle border in downtrend, candle body in confirm downtrend, transparent in falter uptrend candles"
cup=input.color(color.blue, "price direction up", group="DIRECTION AND RANGE", tooltip = ttup)
cdn=input.color(color.red, "price direction down", group="DIRECTION AND RANGE", tooltip = ttdn)
cfup=color.new(cup,40)
cfdn=color.new(cdn,40)
volwish=input.bool(true, "show volume cohorts", group = "VOLUME")
//input colors for cohorts in volume patches
cv1=input.color(color.green, "cohort 0 - 80 percent: low volume", group = "VOLUME")
cv2=input.color(color.blue, "cohort 80 - 120 percent: normal volume", group = "VOLUME")
cv3=input.color(color.rgb(230,80,0), "cohort 120 - 200 percent: high volume", group = "VOLUME")
cv4=input.color(color.maroon, "cohort above 200 percent: extreme volume", group = "VOLUME")
sigu=input.color(color.aqua, "signal pressure up", group="SIGNALS")
sigd=input.color(color.fuchsia, "signal pressure down", group="SIGNALS")
inv=color.new(color.yellow,100)//invisible color
//calculate periods by script if perwish == true
setper= 14 //initialize setper
tf=timeframe.period
setper:= tf=="M"? 14: tf=="W"? 14: tf=="D"? 21: tf=="240"? 28: tf=="180"? 28: tf=="120"? 35: tf=="60"? 35: tf=="45"? 35: tf=="30"? 42: tf=="15"? 42: tf=="5"? 49: tf=="3"? 49: tf=="1"? 56: 10
eval:= perwish? setper : eval
//Calculate price DIRECTION
cl=math.avg(close,eval)
pr=cl[eval]
op=math.avg(open,eval)
up=cl>pr and cl>op
dn=cl<pr and cl<op
fa= not up and not dn //price falters
fup= close >= open and fa //up bar is a falter bar (true in down trend)
fdn= open > close and fa //down bar is a falter bar (true in up trend)
ut=up or fdn //up trend i.e. direction of sma[eval] goes up
dt=dn or fup //down trend i.e. direction of sma[eval] goes down
//calculate VOLUME values
novol=na(volume) //check if volume is present in period
yesvol=not novol //volume is present
curvol=yesvol? volume:0 //current volume, set to zero if no volume present
//Setting lookback by using bar_index results in an integer value that works in ta.median from the first candle in the data onwards.
m180=bar_index<4?1: bar_index<10?4 :bar_index<20?10 :bar_index<60?20 :bar_index<180?60: 180
m60=bar_index<4?1: bar_index<10?4 :bar_index<20?10 :bar_index<60?20 :60
m20=bar_index<4?1: bar_index<10?4 :bar_index<20?10 :20 //
norvol= (ta.median(curvol[1],m180) + ta.median(curvol[1],m60) + ta.median(curvol[1],m20))/3 //normal volume, i.e. average of medians 20,60 and 180 used as 100 %
pervol=yesvol? curvol/norvol*100: 0 //current volume as percent of normal volume
//VOLUME cohorts
modvol=pervol==0? 0: pervol<=80? 1: pervol<=120? 2: pervol<=200? 3: pervol>200? 4: 0 //assign Volume percents to cohorts
//volume cohorts booleans
v0=modvol==0 //no volume present
v1=modvol==1 //low volume 0- 80 percent
v2=modvol==2 //normal volume 80-120 percent
v3=modvol==3 //high volume 120-200 percent
v4=modvol==4 //extreme volume above 200 percent
//calculate RANGE values
noran=high==low and close==close[1] //check if a range is present
yesran=not noran //range is present
curran=yesran? ta.tr:0 //current true range, set to zero if no range present
norran=ta.median(curran[1],m60) //normal range, median 50, used as 100 %
perran=yesran? curran/norran*100 :0 //current range as percent of normal range
//RANGE cohorts
modran=perran==0? 1: perran<=120? 1: perran>120? 2: 1 //assign range percents to cohorts
//range cohorsts booleans
r1=modran==1 //small range 0-120 percent
r2=modran==2 //wide range above 120 percent
//levels for RANGE candles
vshow = volwish and not v0 //condition to show volume, if no volume no space assigned
zero=0
u1=vshow?1: 0
u2=vshow?2: 0
u3=vshow?3: 1
u4=vshow?4: 2
u5=vshow?5: 3
d1=vshow?-1: 0
d2=vshow?-2: 0
d3=vshow?-3: -1
d4=vshow?-4: -2
d5=vshow?-5: -3
border=ut and vshow? u5: dt and vshow? d5: ut? u5: d5
plot(border, "trend marker", color=ut?cdn:cup, style = plot.style_stepline) //provides a marker for trend change
//level plottings
pz=plot(zero, "zero", inv)
pu1=plot(u1, "up level 1", inv)
pu2=plot(u2, "up level 2", inv)
pu3=plot(u3, "up level 3", inv)
pu4=plot(u4, "up level 4", inv)
pub=plot(u5, "uptrend marker", color=ut[1] and not dt?cup:inv, linewidth=2)
pd1=plot(d1, "down level 1", inv)
pd2=plot(d2, "down level 2", inv)
pd3=plot(d3, "down level 3", inv)
pd4=plot(d4, "down level 4", inv)
pdb=plot(d5, "downtrend marker", color=dt[1] and not ut? cdn: inv, linewidth =2)
//logic for RANGE candles
up1=up and r1
up2=up and r2
fdn1=fdn and r1
fdn2=fdn and r2
dn1=dn and r1
dn2=dn and r2
fup1=fup and r1
fup2=fup and r2
//setting and plotting RANGE candles
hcbo=up1?u4: up2?u5: fdn1?u4: fdn2?u4: dn1?d3: dn2?d3: fup1?d3: d2 //high candle border open value
hcbh=up1?u4: up2?u5: fdn1?u4: fdn2?u4: dn1?d3: dn2?d3: fup1?d3: d2 //high candle border high value
lcbl=up1?u3: up2?u3: fdn1?u3: fdn2?u2: dn1?d4: dn2?d5: fup1?d4: d4 //low candle border low value
lcbc=up1?u3: up2?u3: fdn1?u3: fdn2?u2: dn1?d4: dn2?d5: fup1?d4: d4 //low candle border close value
plotcandle(hcbo,hcbh,lcbl,lcbc, color=up?cup: dn?cdn: fup?cfup: cfdn, wickcolor=vshow?color.black:inv, bordercolor=ut?cup:cdn)
//fillS for VOLUME patches
tran=v1?50: v2?50: v3?20: 20 //transparancy lower in high volume
cv1f=color.new(cv1, tran)
cv2f=color.new(cv2, tran)
cv3f=color.new(cv3, tran)
cv4f=color.new(cv4, tran)
fill(pu1,pz, title="volume cohort colors", color=dt? v1?cv1f: v2?cv2f: v3?cv3f: cv4f: na) //in down trend patches above histogram
fill(pz ,pd1, title="volume cohort colors", color=ut? v1?cv1f: v2?cv2f: v3?cv3f: cv4f: na) //below histogram
//VOLUME histogram all heights one, width varies, wide in high volume
vh=vshow? ut? 1: -1: na
plot(vh, "low volume histogram", color=v1?cv1: inv, linewidth=2, style=plot.style_histogram)
plot(vh, "normal volume histogram", color=v2?cv2: inv, linewidth=2, style=plot.style_histogram)
plot(vh, "high volume histogram", color=v3?cv3: inv, linewidth=6, style=plot.style_histogram)
plot(vh, "extreme volume histogram", color=v4?cv4: inv, linewidth=6, style=plot.style_histogram)
//SIGNALS
//Logic for SIGNALS
//uptrendside
presup=v4 and up2? true: v3 and up2? true: false //pressure up while uptrend
presdn4=v4 and fdn2? true: false //pressure down while uptrend
presfup=v4 and up1? true: v4 and fdn1? true: v3 and fdn2? true: false //unresolved pressure while uptrend
presut=presup or presup[1] or presdn4 or presdn4[1] or presfup or presfup[1]
//downtrendside
presdn=v4 and dn2? true: v3 and dn2? true: false //pressure down while downtrend
presup4=v4 and fup2? true: false //pressure up while downtrend
presfdn=v4 and dn1? true: v4 and fup1? true: v3 and fup2? true: false //unresolved pressure while downtrend
presdt=presdn or presdn[1] or presup4 or presup4[1] or presfdn or presfdn[1]
//SIGNAL labels
var label lbupu = na
var label lbdnu = na
var label lbpru = na
var label lbprd = na
var label lbupd = na
var label lbdnd = na
lbupu:=presup?label.new(bar_index, d2, color=sigu, style=label.style_triangleup, size=size.auto):na
lbupu:=presup?label.new(bar_index, d3, color=sigu, style=label.style_triangleup, size=size.auto):na
lbdnu:=presdn4?label.new(bar_index, d3, color=sigu, style=label.style_square, size=size.auto):na
lbdnu:=presdn4?label.new(bar_index, d4, color=sigd, style=label.style_triangledown, size=size.auto):na
lbupd:=presup4?label.new(bar_index, u4,color=sigu, style=label.style_triangleup, size=size.auto):na
lbupd:=presup4?label.new(bar_index, u3,color=sigd, style=label.style_square, size=size.auto):na
lbdnd:=presdn?label.new(bar_index, u2,color=sigd, style=label.style_triangledown, size=size.auto):na
lbdnd:=presdn?label.new(bar_index, u3,color=sigd, style=label.style_triangledown, size=size.auto):na
lbprd:=presfdn?label.new(bar_index, u3,color=sigd, style=label.style_square, size=size.auto):na
lbpru:=presfup?label.new(bar_index, d3,color=sigu, style=label.style_square, size=size.auto):na
//feedback table
var table userorscript = table.new(position=position.bottom_left, columns=1, rows=1)
feedbacktext=perwish? "script lookback " +str.tostring(eval) : "user lookback " +str.tostring(eval)
if perfeedback == true
table.cell(userorscript, row=0, column=0, text=feedbacktext, bgcolor=color.silver)
else if perfeedback == false
table.clear(userorscript, 0, 0, 0, 0) |
Advanced Exponential Smoothing Indicator (AESI) [AstrideUnicorn] | https://www.tradingview.com/script/EVXi9xaZ-Advanced-Exponential-Smoothing-Indicator-AESI-AstrideUnicorn/ | AstrideUnicorn | https://www.tradingview.com/u/AstrideUnicorn/ | 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/
// © AstrideUnicorn
//@version=5
indicator(title='Advanced Exponential Smoothing Indicator (AESI)', shorttitle='AESI', overlay=true)
// Input parameters
length = input.int(14, minval=1, title='Length')
alpha = input.float(0.5, minval=0, maxval=1, title='Alpha')
cloud_mode = input.bool(true, title='Cloud Mode')
// Calculate Exponential Moving Average (EMA)
ema = ta.ema(close, length)
// Calculate the total price-ema difference
sad = math.sum(close - ema, length)
// Calculate the Smoothing Factor
smoothing_factor = alpha * (sad / length)
// Calculate AESI
aesi =ema + smoothing_factor
// Plotting AESI
plot(aesi, color = not cloud_mode? color.new(color.green, 0): color.new(color.green, 100) , title='AESI')
// Plot AESI Cloud
cloud_color = aesi > ema ? color.green : color.red
cloud_color := cloud_mode ? cloud_color : color.new(color.black,100)
c1 = plot(ema, color = cloud_color)
c2 = plot(aesi, color = cloud_color)
fill(c1,c2, color = cloud_color)
|
Volume Suite - By Leviathan (CVD, Volume Delta, Relative Volume) | https://www.tradingview.com/script/YNMTwt1n-Volume-Suite-By-Leviathan-CVD-Volume-Delta-Relative-Volume/ | LeviathanCapital | https://www.tradingview.com/u/LeviathanCapital/ | 2,035 | 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/
// © LeviathanCapital
//@version=5
indicator("Volume Suite - By Leviathan", overlay = false, format = format.volume)
g1 = 'General'
g2 = 'Large Change Thresholds'
g3 = 'Volume-Price Imbalances'
g5 = 'Additional Settings'
g4 = 'Display Settings'
// General
disp = input.string('Relative Volume', 'Display', options = ['Relative Volume', 'CRVOL (Cumulative Relative Volume)', 'Volume', 'Buy/Sell Volume', 'Volume Delta', 'CVD (Cumulative Volume Delta)'])
upcol = input.color(#d1d4dc, 'Primary Colors ▲', inline = 'udcol')
downcol = input.color(#9598a1f6, '▼', inline = 'udcol')
// Large Change Thresholds
show_mult1 = input.bool(true, '', inline = 'mult1', group = g2)
mult = input.float(1.5, '>', inline = 'mult1', group = g2, step = 0.1)
upcol_mult1 = input.color(#c8e6c9, ' ▲', inline = 'mult1', group = g2)
downcol_mult1 = input.color(#faa1a4, '▼', inline = 'mult1', group = g2)
show_mult2 = input.bool(true, '', inline = 'mult2', group = g2)
mult2 = input.float(2.5, '>', inline = 'mult2', group = g2, step = 0.1)
upcol_mult2 = input.color(#a5d6a7, ' ▲', inline = 'mult2', group = g2)
downcol_mult2 = input.color(#f77c80, '▼', inline = 'mult2', group = g2)
show_mult3 = input.bool(true, '', inline = 'mult3', group = g2)
mult3 = input.float(3.5, '>', inline = 'mult3', group = g2, step = 0.1)
upcol_mult3 = input.color(#66bb6a, ' ▲', inline = 'mult3', group = g2)
downcol_mult3 = input.color(#f7525f, '▼', inline = 'mult3', group = g2)
// Imbalances
show_imb1 = input.bool(false, 'High Volume + Small Price Change', group = g3, inline = 'imb1')
imb1_col = input.color(color.orange, '', group = g3, inline = 'imb1')
vimb1 = input.float(1, 'V >', group = g3, inline = 'imb11', step = 0.1)
pimb1 = input.float(0, 'P <', group = g3, inline = 'imb11', step = 0.1)
show_imb2 = input.bool(false, 'Low Volume + Large Price Change', group = g3, inline = 'imb2')
imb2_col = input.color(color.blue, '', group = g3, inline = 'imb2')
vimb2 = input.float(0, 'V <', group = g3, inline = 'imb22', step = 0.1)
pimb2 = input.float(1, 'P >', group = g3, inline = 'imb22', step = 0.1)
// Additional settings
color_candles = input.bool(false, 'Color Candles', group = g5)
gradient = input.bool(false, 'Gradient Coloring', inline = 'g', group = g5)
gr1 = input.color(#f7525f, '', inline = 'g', group = g5)
gr2 = input.color(#ffe0b2, '', inline = 'g', group = g5)
tf = input.timeframe('1', 'LTF Timeframe', group = g5)
threshtype = input.string('Z-SCORE', 'Threshold Calculation Type', options = ['SMA', 'RELATIVE', 'Z-SCORE'], group = g5)
zlen = input.int(50, 'Z Length', group = g5)
smalen = input.int(300, 'SMA Length', group = g5)
rellen = input.int(20, 'Relative Length', group = g5)
// Display
rv_disp = input.string('Columns', 'Relative Volume', options = ['Columns', 'Histogram', 'Line'], group = g4)
crv_disp = input.string('Candles', 'Cumulative Relative Volume', options = ['Candles', 'Line'], group = g4)
bsv_disp = input.string('Columns', 'Buy/Sell Volume', options = ['Columns', 'Histogram', 'Line'], group = g4)
vd_disp = input.string('Columns', 'Volume Delta', options = ['Columns', 'Histogram', 'Line'], group = g4)
cvd_disp = input.string('Candles', 'CVD', options = ['Candles', 'Line'], group = g4)
disp_type(x) =>
switch x
'Columns' => plot.style_columns
'Histogram' => plot.style_histogram
'Line' => plot.style_line
// SMA Function
f_mult1(src) =>
ta.sma(src, smalen) * (mult + 1)
f_mult2(src) =>
ta.sma(src, smalen) * (mult2 + 1)
f_mult3(src) =>
ta.sma(src, smalen) * (mult3 + 1)
// Relative function
f_relative(src) =>
src / ta.sma(src, rellen)
// Z-Score function
f_zscore(src) =>
mean = ta.sma(src, zlen)
std = ta.stdev(src, zlen)
z_score = (src - mean) / std
// Volume calculations
vol = volume
vol_sma = f_mult1(vol)
vol_sma2 = f_mult2(vol)
vol_sma3 = f_mult3(vol)
// Relative Volume and Cumulative Relative Volume calculations
rvol = f_relative(volume)
rvol_sma = f_mult1(rvol)
rvol_sma2 = f_mult2(rvol)
rvol_sma3 = f_mult3(rvol)
obv = ta.cum(close > open ? rvol : -rvol)
// Volume Delta, CVD, Buy/Sell Volume Calculations
[buy_volume, sell_volume] = request.security_lower_tf(syminfo.tickerid, tf, [close>open ? volume : 0, close<open ? volume : 0])
buy_vol = array.sum(buy_volume)
sell_vol = array.sum(sell_volume)
delta_vol = buy_vol-sell_vol
cum_delta_vol = ta.cum(delta_vol)
delta_abs = math.abs(delta_vol)
rposdelta = f_relative(delta_vol>0 ? delta_vol : 0)
rnegdelta = f_relative(delta_vol<0 ? delta_vol : 0)
vdp_sma = f_mult1(delta_vol>0 ? delta_vol : 0) * 2
vdp_sma2 = f_mult2(delta_vol>0 ? delta_vol : 0) * 3
vdp_sma3 = f_mult3(delta_vol>0 ? delta_vol : 0) * 7
vdn_sma = f_mult1(delta_vol<0 ? delta_vol : 0) * 2
vdn_sma2 = f_mult2(delta_vol<0 ? delta_vol : 0) * 3
vdn_sma3 = f_mult3(delta_vol<0 ? delta_vol : 0) * 7
bvl_sma = f_mult1(buy_vol)
bvl2_sma = f_mult2(buy_vol)
bvl3_sma = f_mult3(buy_vol)
svl_sma = f_mult1(sell_vol)
svl2_sma = f_mult2(sell_vol)
svl3_sma = f_mult3(sell_vol)
// Coloring
V_COL = close > open ? upcol : downcol
VD_COL = delta_vol > 0 ? upcol : downcol
CRV_COL = close>open ? upcol : downcol
BV_COL = upcol
SV_COL = downcol
color bar_col = color.rgb(0,0,0,100)
//
if threshtype=='SMA'
if disp=='Volume'
if show_mult1 and vol >= vol_sma
V_COL := close>open ? upcol_mult1 : downcol_mult1
bar_col := V_COL
if show_mult2 and vol >= vol_sma2
V_COL := close>open ? upcol_mult2 : downcol_mult2
bar_col := V_COL
if show_mult3 and vol >= vol_sma3
V_COL := close>open ? upcol_mult3 : downcol_mult3
bar_col := V_COL
if disp=='CRVOL (Cumulative Relative Volume)' or disp=='Relative Volume'
if show_mult1 and rvol >= rvol_sma
CRV_COL := close>open ? upcol_mult1 : downcol_mult1
bar_col := CRV_COL
if show_mult2 and rvol >= rvol_sma2
CRV_COL := close>open ? upcol_mult2 : downcol_mult2
bar_col := CRV_COL
if show_mult3 and rvol >= rvol_sma3
CRV_COL := close>open ? upcol_mult3 : downcol_mult3
bar_col := CRV_COL
if disp=='Volume Delta' or disp=='CVD (Cumulative Volume Delta)'
if show_mult1 and delta_vol>0 and delta_vol>vdp_sma
VD_COL := upcol_mult1
bar_col := VD_COL
if show_mult2 and delta_vol>0 and delta_vol>vdp_sma2
VD_COL := upcol_mult2
bar_col := VD_COL
if show_mult3 and delta_vol>0 and delta_vol>vdp_sma3
VD_COL := upcol_mult3
bar_col := VD_COL
if show_mult1 and delta_vol<0 and delta_vol<vdn_sma
VD_COL := downcol_mult1
bar_col := VD_COL
if show_mult2 and delta_vol<0 and delta_vol<vdn_sma2
VD_COL := downcol_mult2
bar_col := VD_COL
if show_mult3 and delta_vol<0 and delta_vol<vdn_sma3
VD_COL := downcol_mult3
bar_col := VD_COL
if disp=='Buy/Sell Volume'
if show_mult1 and buy_vol>bvl_sma
BV_COL := upcol_mult1
bar_col := BV_COL
if show_mult2 and buy_vol>bvl2_sma
BV_COL := upcol_mult2
bar_col := BV_COL
if show_mult3 and buy_vol>bvl3_sma
BV_COL := upcol_mult3
bar_col := BV_COL
if show_mult1 and sell_vol>svl_sma
SV_COL := downcol_mult1
bar_col := SV_COL
if show_mult2 and sell_vol>svl2_sma
SV_COL := downcol_mult2
bar_col := SV_COL
if show_mult3 and sell_vol>svl3_sma
SV_COL := downcol_mult3
bar_col := SV_COL
if threshtype=='RELATIVE'
if disp=='Volume'
if show_mult1 and f_relative(vol)>mult
V_COL := close>open ? upcol_mult1 : downcol_mult1
bar_col := V_COL
if show_mult2 and f_relative(vol)>mult2
V_COL := close>open ? upcol_mult2 : downcol_mult2
bar_col := V_COL
if show_mult3 and f_relative(vol)>mult3
V_COL := close>open ? upcol_mult3 : downcol_mult3
bar_col := V_COL
if disp=='CRVOL (Cumulative Relative Volume)' or disp=='Relative Volume'
if show_mult1 and rvol >= mult//rvol_sma
CRV_COL := close>open ? upcol_mult1 : downcol_mult1
bar_col := CRV_COL
if show_mult2 and rvol >= mult2//rvol_sma2
CRV_COL := close>open ? upcol_mult2 : downcol_mult2
bar_col := CRV_COL
if show_mult3 and rvol >= mult3//rvol_sma3
CRV_COL := close>open ? upcol_mult3 : downcol_mult3
bar_col := CRV_COL
if disp=='Volume Delta' or disp=='CVD (Cumulative Volume Delta)'
if show_mult1 and delta_vol>0 and rposdelta > mult * 1.5
VD_COL := upcol_mult1
bar_col := VD_COL
if show_mult2 and delta_vol>0 and rposdelta > mult2 * 1.5
VD_COL := upcol_mult2
bar_col := VD_COL
if show_mult3 and delta_vol>0 and rposdelta > mult3 * 1.5
VD_COL := upcol_mult3
bar_col := VD_COL
if show_mult1 and delta_vol<0 and -rnegdelta < -mult * 1.5
VD_COL := downcol_mult1
bar_col := VD_COL
if show_mult2 and delta_vol<0 and -rnegdelta < -mult2 * 1.5
VD_COL := downcol_mult2
bar_col := VD_COL
if show_mult3 and delta_vol<0 and -rnegdelta < -mult3 * 1.5
VD_COL := downcol_mult3
bar_col := VD_COL
if disp=='Buy/Sell Volume'
if show_mult1 and f_relative(buy_vol)>mult
BV_COL := upcol_mult1
bar_col := BV_COL
if show_mult2 and f_relative(buy_vol)>mult2
BV_COL := upcol_mult2
bar_col := BV_COL
if show_mult3 and f_relative(buy_vol)>mult3
BV_COL := upcol_mult3
bar_col := BV_COL
if show_mult1 and f_relative(sell_vol)>=mult
SV_COL := downcol_mult1
bar_col := SV_COL
if show_mult2 and f_relative(sell_vol)>=mult2
SV_COL := downcol_mult2
bar_col := SV_COL
if show_mult3 and f_relative(sell_vol)>=mult3
SV_COL := downcol_mult3
bar_col := SV_COL
if threshtype=='Z-SCORE'
if disp=='Volume'
if show_mult1 and f_zscore(vol) >= mult
V_COL := close>open ? upcol_mult1 : downcol_mult1
bar_col := V_COL
if show_mult2 and f_zscore(vol) >= mult2
V_COL := close>open ? upcol_mult2 : downcol_mult2
bar_col := V_COL
if show_mult3 and f_zscore(vol) >= mult3
V_COL := close>open ? upcol_mult3 : downcol_mult3
bar_col := V_COL
if disp=='CRVOL (Cumulative Relative Volume)' or disp=='Relative Volume'
if show_mult1 and f_zscore(rvol) >= mult
CRV_COL := close>open ? upcol_mult1 : downcol_mult1
bar_col := CRV_COL
if show_mult2 and f_zscore(rvol) >= mult2
CRV_COL := close>open ? upcol_mult2 : downcol_mult2
bar_col := CRV_COL
if show_mult3 and f_zscore(rvol) >= mult3
CRV_COL := close>open ? upcol_mult3 : downcol_mult3
bar_col := CRV_COL
if disp=='Volume Delta' or disp=='CVD (Cumulative Volume Delta)'
if show_mult1 and delta_vol>0 and f_zscore(rposdelta) >= mult
VD_COL := upcol_mult1
bar_col := VD_COL
if show_mult2 and delta_vol>0 and f_zscore(rposdelta) >= mult2
VD_COL := upcol_mult2
bar_col := VD_COL
if show_mult3 and delta_vol>0 and f_zscore(rposdelta) >= mult3
VD_COL := upcol_mult3
bar_col := VD_COL
if show_mult1 and delta_vol<0 and f_zscore(rnegdelta) >= mult
VD_COL := downcol_mult1
bar_col := VD_COL
if show_mult2 and delta_vol<0 and f_zscore(rnegdelta) >= mult2
VD_COL := downcol_mult2
bar_col := VD_COL
if show_mult3 and delta_vol<0 and f_zscore(rnegdelta) >= mult3
VD_COL := downcol_mult3
bar_col := VD_COL
if disp=='Buy/Sell Volume'
if show_mult1 and f_zscore(buy_vol)>=mult
BV_COL := upcol_mult1
bar_col := BV_COL
if show_mult2 and f_zscore(buy_vol)>=mult2
BV_COL := upcol_mult2
bar_col := BV_COL
if show_mult3 and f_zscore(buy_vol)>=mult3
BV_COL := upcol_mult3
bar_col := BV_COL
if show_mult1 and f_zscore(sell_vol)>=mult
SV_COL := downcol_mult1
bar_col := SV_COL
if show_mult2 and f_zscore(sell_vol)>=mult2
SV_COL := downcol_mult2
bar_col := SV_COL
if show_mult3 and f_zscore(sell_vol)>=mult3
SV_COL := downcol_mult3
bar_col := SV_COL
switch_src(disp) =>
switch disp
'Volume' => vol
'Relative Volume' => rvol
'CRVOL (Cumulative Relative Volume)' => rvol
'Volume Delta' => math.abs(delta_vol)
'CVD (Cumulative Volume Delta)' => math.abs(delta_vol)
'Buy/Sell Volume' => math.abs(delta_vol)
if show_imb1 and f_zscore(switch_src(disp)) > vimb1 and f_zscore(high-low) < pimb1
V_COL := imb1_col
CRV_COL := imb1_col
VD_COL := imb1_col
BV_COL := buy_vol>sell_vol ? imb1_col : na
SV_COL := sell_vol>buy_vol ? imb1_col : na
bar_col := imb1_col
if show_imb2 and f_zscore(switch_src(disp)) < vimb2 and f_zscore(high-low) > pimb2
V_COL := imb2_col
CRV_COL := imb2_col
VD_COL := imb2_col
BV_COL := buy_vol<sell_vol ? imb2_col : na
SV_COL := sell_vol<buy_vol ? imb2_col : na
bar_col := imb2_col
if gradient
glen = 50
V_COL := color.from_gradient(vol, 0, ta.highest(vol, glen), gr2, gr1)
CRV_COL := color.from_gradient(rvol, 0, ta.highest(rvol, glen), gr2, gr1)
VD_COL := color.from_gradient(delta_vol, ta.lowest(delta_vol, glen), ta.highest(delta_vol, glen), gr2, gr1)
BV_COL := color.from_gradient(buy_vol, 0, ta.highest(buy_vol, glen), gr2, gr1)
SV_COL := color.from_gradient(sell_vol, 0, ta.highest(sell_vol, glen), gr2, gr1)
// Plotting
o_ = disp=='CRVOL (Cumulative Relative Volume)' ? obv[1] : cum_delta_vol[1]
h_ = disp=='CRVOL (Cumulative Relative Volume)' ? obv : cum_delta_vol
l_ = disp=='CRVOL (Cumulative Relative Volume)' ? obv : cum_delta_vol
c_ = disp=='CRVOL (Cumulative Relative Volume)' ? obv : cum_delta_vol
// Plotting CRV
crv_cond = disp=='CRVOL (Cumulative Relative Volume)' and crv_disp=='Candles'
plotcandle(crv_cond ? o_ : na, crv_cond ? h_ : na, crv_cond ? l_ : na, crv_cond ? c_ : na, color = CRV_COL, wickcolor = CRV_COL, bordercolor = CRV_COL, title = 'CRVOL')
plot(disp=='CRVOL (Cumulative Relative Volume)' and crv_disp=='Line' ? obv : na, color = CRV_COL, title = 'CRVOL')
// Plotting CVD
cvd_cond = disp=='CVD (Cumulative Volume Delta)' and cvd_disp=='Candles'
plotcandle(cvd_cond ? o_ : na, cvd_cond ? h_ : na, cvd_cond ? l_ : na, cvd_cond ? c_ : na, color = VD_COL, wickcolor = VD_COL, bordercolor = VD_COL, title = 'CVD')
plot(disp=='CVD (Cumulative Volume Delta)' and cvd_disp=='Line' ? cum_delta_vol : na, color = VD_COL, title = 'CVD')
// Plotting Relative Volume
plot(disp=='Relative Volume' ? rvol : na, style = disp_type(rv_disp), color = CRV_COL, title = 'RVOL')
// Plotting Regular Volume
plot(disp=='Volume' ? volume : na, style=plot.style_columns, color = V_COL, title = 'VOL')
// Plotting Buy/Sell Volume
plot(disp=='Buy/Sell Volume' ? buy_vol : na, style = disp_type(bsv_disp), color = BV_COL, title = 'Buy Volume')
plot(disp=='Buy/Sell Volume' ? -sell_vol : na, style = disp_type(bsv_disp), color = SV_COL, title = 'Sell Volume')
// Plotting Volume Delta
plot(disp=='Volume Delta' ? delta_vol : na, style = disp_type(vd_disp), color = VD_COL, title = 'Volume Delta')
// Coloring candles
barcolor(color_candles and bar_col != color.rgb(0,0,0,100) ? bar_col : na)
|
ATR Delta | https://www.tradingview.com/script/ru7qK5hy-ATR-Delta/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 72 | 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/
// © LeafAlgo
//@version=5
indicator("ATR Delta", overlay=false)
// Calculation Inputs
length = input(20, "ATR Length")
// Calculate ATR
atr = ta.atr(length)
// Calculate ATR Delta
atrDelta = atr - ta.atr(length)[1]
// Signal Line
signalLength = input(14, "Signal Line Length")
signalLine = ta.ema(atrDelta, signalLength)
// Coloration
deltaColor = signalLine > 0 and atrDelta > 0 and atrDelta > signalLine ? color.green : signalLine < 0 and atrDelta < 0 and atrDelta < signalLine ? color.red : color.gray
signalColor = signalLine > 0 ? color.lime : color.fuchsia
// Plotting
plot(atrDelta, color = deltaColor, linewidth=2, title="ATR Delta", style = plot.style_columns)
plot(signalLine, color=signalColor, linewidth=4, title="Signal Line")
hline(0, linewidth = 3)
// Bar Color
barcolor(deltaColor)
bgcolor(color.new(signalColor, 80))
|
Bank Nifty Scalping | https://www.tradingview.com/script/r04L7ZK5-Bank-Nifty-Scalping/ | DanSib | https://www.tradingview.com/u/DanSib/ | 250 | 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/
// © DanSib
//@version=5
indicator(title="Bank Nifty Scalping", shorttitle = "DS", overlay=true)
//===== MULTI EMA 20,50,100,200 =====
showmema = input(true, title="Show Multi EMA 20/50/100/200", group = "EMA")
plot((showmema ? ta.ema(close, 20) : na), "EMA 20", style=plot.style_line, color=color.gray , linewidth=1)
plot((showmema ? ta.ema(close, 50) : na), "EMA 50", style=plot.style_line, color=color.maroon , linewidth=1, display=display.none)
plot((showmema ? ta.ema(close, 100) : na), "EMA 100", style=plot.style_line, color=color.blue, linewidth=1, display=display.none)
plot((showmema ? ta.ema(close, 200) : na), "EMA 200", style=plot.style_line, color=color.black, linewidth=2)
//===== 9 EMA 5 Minutes =====
showema = input(true, title="Show 9 EMA 5 Mins", group = "EMA")
out = request.security(syminfo.tickerid, "5" , ta.ema(close, 9))
plot(showema ? out : na, "9 EMA", color=color.orange , offset = 0)
//===== VWAP =====
showVWAP = input.bool(title = "Show VWAP", defval=true, group = "VWAP")
VWAPSource = input.source(title="VWAP Source", defval=hl2, group = "VWAP")
VWAPrice = ta.vwap(VWAPSource)
plot(showVWAP ? VWAPrice : na, color= color.teal, title="VWAP", linewidth = 2)
//===== Super Trend 1 =====
showST = input(true, "Show SuperTrend Indicator 1", group = "Super Trend 1")
Period=input(title="ATR Period", defval=10)
Multiplier=input(title="ATR Multiplier", defval=2)
//Super Trend ATR
Up=hl2-(Multiplier*ta.atr(Period))
Dn=hl2+(Multiplier*ta.atr(Period))
var TUp = close
TUp:=close[1]>TUp[1]? math.max(Up,TUp[1]) : Up
var TDown = close
TDown:=close[1]<TDown[1]? math.min(Dn,TDown[1]) : Dn
var Trend = -1
Trend := close > TDown[1] ? 1: close< TUp[1]? -1: nz(Trend[1],1)
Tsl1 = Trend==1? TUp: TDown
Tsl2 = Trend==1? TDown: TUp
linecolor = Trend == 1 ? color.green : color.red
plot(showST ?Tsl1 : na, color = linecolor, style = plot.style_line , linewidth = 2,title = "SuperTrend 1")
//===== Super Trend 2 =====
showST2 = input(false, "Show SuperTrend Indicator 2", group = "Super Trend 2")
Period2=input(title="ATR Period", defval=10)
Multiplier2=input(title="ATR Multiplier", defval=3)
//Super Trend ATR
Up2=hl2-(Multiplier2*ta.atr(Period2))
Dn2=hl2+(Multiplier2*ta.atr(Period2))
var TUp2 = close
TUp2:=close[1]>TUp2[1]? math.max(Up2,TUp2[1]) : Up2
var TDown2 = close
TDown2:=close[1]<TDown2[1]? math.min(Dn2,TDown2[1]) : Dn2
var Trend2 = -1
Trend2 := close > TDown2[1] ? 1: close< TUp2[1]? -1: nz(Trend2[1],1)
Tsl12 = Trend2==1? TUp2: TDown2
Tsl22 = Trend2==1? TDown2: TUp2
linecolor2 = Trend2 == 1 ? color.green : color.red
plot(showST2 ?Tsl12 : na, color = linecolor2, style = plot.style_line , linewidth = 1,title = "SuperTrend 2")
//===== VWMA =====
showVWMA = input(true, "Show VWMA", group = "VWMA")
len = input.int(20, "Length", minval=1)
vsrc = input(close, "Source")
ma = ta.vwma(vsrc, len)
offset = input.int(0, "Offset", minval = -500, maxval = 500)
plot(showVWMA ? ma : na, title="VWMA", color=#2962FF, offset = offset)
//===== Camarilla Pivot =====
showcam = input.bool(true, title="Show Camarilla R3/R4/S3/S4", group = "Camarilla")
tc2 = input.string(title = "Camarilla Pivot Resolution", defval="D", options =["D","W","M"],group = "Camarilla")
//Get previous day/week bar and avoiding realtime calculation by taking the previous to current bar
[sopen,shigh,slow,sclose] = request.security(syminfo.tickerid, tc2, [open[1],high[1],low[1],close[1]], barmerge.gaps_off, barmerge.lookahead_on)
r = shigh-slow
//Calculate pivots
center=(sclose)
h1=sclose + r*(1.1/12)
h2=sclose + r*(1.1/6)
h3=sclose + r*(1.1/4)
h4=sclose + r*(1.1/2)
h5=(shigh/slow)*sclose
l1=sclose - r*(1.1/12)
l2=sclose - r*(1.1/6)
l3=sclose - r*(1.1/4)
l4=sclose - r*(1.1/2)
l5=sclose - (h5-sclose)
//Colors (<ternary conditional operator> expression prevents continuous lines on history)
c4=sopen != sopen[1] ? na : color.fuchsia
c3=sopen != sopen[1] ? na : color.fuchsia
//Plotting Camarilla
plot((showcam ? h4 : na), title="Camarilla R4",color=c4,style=plot.style_circles, linewidth=2)
plot((showcam ? h3 : na), title="Camarilla R3",color=c3, style=plot.style_circles, linewidth=2)
plot((showcam ? l3 : na), title="Camarilla S3",color=c3, style=plot.style_circles, linewidth=2)
plot((showcam ? l4 : na), title="Camarilla S4",color=c4, style=plot.style_circles, linewidth=2)
//===== CPR - Cenral Pivot Range =====
pivot = (high + low + close) /3 //Central Povit
BC = (high + low) / 2 //Below Central povit
TC = (pivot - BC) + pivot //Top Central povot
//3 support levels
S1 = (pivot * 2) - high
S2 = pivot - (high - low)
S3 = low - 2 * (high - pivot)
//3 resistance levels
R1 = (pivot * 2) - low
R2 = pivot + (high - low)
R3 = high + 2 * (pivot-low)
CPRPlot = input.bool(title = "Show CPR", defval=true, group = "CPR")
DayS1R1 = input.bool(title = "Show Daiy S1/R1", defval=true, group = "CPR")
DayS2R2 = input.bool(title = "Show Daiy S2/R2", defval=false, group = "CPR")
DayS3R3 = input.bool(title = "Show Daiy S3/R3", defval=false, group = "CPR")
// Getting daywise CPR/Level 1, 2 & 3
[DayPivot, DayBC, DayTC, DayS1, DayS2, DayS3, DayR1, DayR2, DayR3]=request.security(syminfo.tickerid, "D", [pivot[1],BC[1],TC[1],S1[1],S2[1],S3[1],R1[1],R2[1],R3[1]], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks daywse for CPR
CPColour = DayPivot != DayPivot[1] ? na : color.black
BCColour = DayBC != DayBC[1] ? na : color.blue
TCColour = DayTC != DayTC[1] ? na : color.blue
//Plotting daywise CPR
plot(CPRPlot ? DayPivot : na, title = "CPR_CP" , color = CPColour, style=plot.style_circles, linewidth =2)
plot(CPRPlot ? DayBC : na , title = "CPR_BC" , color = BCColour, style = plot.style_line, linewidth =1)
plot(CPRPlot ? DayTC : na , title = "CPR_TC" , color = TCColour, style = plot.style_line, linewidth =1)
//Adding linebreaks for daywise Support levels
DayS1Color =DayS1 != DayS1[1] ? na : color.green
DayS2Color =DayS2 != DayS2[1] ? na : color.green
DayS3Color =DayS3 != DayS3[1] ? na : color.green
//Plotting daywise Support levels
plot(DayS1R1 ? DayS1 : na, title = "CPR-S1" , color = DayS1Color, style = plot.style_line, linewidth =1)
plot(DayS2R2 ? DayS2 : na, title = "CPR-S2" , color = DayS2Color, style = plot.style_line, linewidth =1)
plot(DayS3R3 ? DayS3 : na, title = "CPR-S3" , color = DayS3Color, style = plot.style_line, linewidth =1)
//Adding linebreaks for daywise Support levels
DayR1Color =DayR1 != DayR1[1] ? na : color.red
DayR2Color =DayR2 != DayR2[1] ? na : color.red
DayR3Color =DayR3 != DayR3[1] ? na : color.red
//Plotting daywise Resistance levels
plot(DayS1R1 ? DayR1 : na, title = "CPR-R1" , color = DayR1Color, style = plot.style_line, linewidth =1)
plot(DayS2R2 ? DayR2 : na, title = "CPR-R2" , color = DayR2Color, style = plot.style_line, linewidth =1)
plot(DayS3R3 ? DayR3 : na, title = "CPR-R3" , color = DayR3Color, style = plot.style_line, linewidth =1)
//===== Previous day High/Low =====
PH = high
PL= low
showPDHL = input.bool(true, title="Show PDH/PDL", group = "CPR")
[PDH,PDL] = request.security(syminfo.tickerid, 'D', [PH[1],PL[1]], lookahead=barmerge.lookahead_on)
//PDH = request.security(syminfo.tickerid, 'D', PH[1], lookahead=barmerge.lookahead_on)
//PDL = request.security(syminfo.tickerid, 'D', PL[1], lookahead=barmerge.lookahead_on)
plot(showPDHL ? PDH : na, title = "PDH", color=color.green, style=plot.style_circles, linewidth = 2, trackprice = true)
plot(showPDHL ? PDL : na, title = "PDL", color=color.red, style=plot.style_circles, linewidth = 2, trackprice = true)
//===== Fibonacci Pivot Points =====
showFibPiv = input(false, "Show Fibonacci Pivot Points", group = "Fib Pivot Points")
fpt = input.string(title = "Fibonacci Pivot Resolution", defval="D", options =["D","W","M"],group = "Fib Pivot Points")
//Get previous day/week bar and avoiding realtime calculation by taking the previous to current bar
[fopen,fhigh,flow,fclose] = request.security(syminfo.tickerid, fpt, [open[1],high[1],low[1],close[1]], barmerge.gaps_off, barmerge.lookahead_on)
fr = fhigh-flow
fp = (fhigh+flow+fclose)/3
fib_L1 = input(title="Insert Fib Level 1", defval=0.382)
fib_L2 = input(title="Insert Fib Level 2", defval=0.618)
fib_L3 = input(title="Insert Fib Level 3", defval=1.000)
//Calculate Fib pivots
fR1 = fp+(fr*fib_L1)
fS1 = fp-(fr*fib_L1)
fR2 = fp+(fr*fib_L2)
fS2 = fp-(fr*fib_L2)
fR3 = fp+(fr*fib_L3)
fS3 = fp-(fr*fib_L3)
//Colors (<ternary conditional operator> expression prevents continuous lines on history)
fc1=fopen != fopen[1] ? na : color.red
fc2=fopen != fopen[1] ? na : color.green
//Plotting Fibonacci Pivot Points
plot(showFibPiv ? fS1 : na, color=fc1, title="Fib-S1", style = plot.style_line, linewidth = 1)
plot(showFibPiv ? fS2 : na, color=fc1, title="Fib-S2", style = plot.style_line, linewidth = 1)
plot(showFibPiv ? fS3 : na, color=fc1, title="Fib-S3", style = plot.style_line, linewidth = 1)
plot(showFibPiv ? fR1 : na, color=fc2, title="Fib-R1", style = plot.style_line, linewidth = 1)
plot(showFibPiv ? fR2 : na, color=fc2, title="Fib-R2", style = plot.style_line, linewidth = 1)
plot(showFibPiv ? fR3 : na, color=fc2, title="Fib-R3", style = plot.style_line, linewidth = 1)
//===== Elder Impulse =====
showEI = input(true, title="Show Elder Impulse", group = "Elder Impulse")
source = close
// MACD Options
macd_length_fast = input.int(defval=12, minval=1, title="MACD Fast Length")
macd_length_slow = input.int(defval=26, minval=1, title="MACD Slow Length")
macd_length_signal = input.int(defval=9, minval=1, title="MACD Signal Length")
// Calculate MACD
macd_ma_fast = ta.ema(source, macd_length_fast)
macd_ma_slow = ta.ema(source, macd_length_slow)
macd = macd_ma_fast - macd_ma_slow
macd_signal = ta.ema(macd, macd_length_signal)
macd_histogram = macd - macd_signal
// EMA Option
ema_length = input.int(defval=13, minval=1, title="EMA Length")
// Calculate EMA
ema = ta.ema(source, ema_length)
// Calculate Elder Impulse
elder_bulls = (ema[0] > ema[1]) and (macd_histogram[0] > macd_histogram[1])
elder_bears = (ema[0] < ema[1]) and (macd_histogram[0] < macd_histogram[1])
elder_color = elder_bulls
? color.green // If Bulls Control Trend and Momentum
: elder_bears
? color.red // If Bears Control Trend and Mementum
: color.blue // If Neither Bulls or Bears Control the Market
barcolor(showEI ? elder_color : na, title = "Elder Impulse Bar Color")
// ====== Volume ======
ShowHighVolume = input(true, 'Show Strong Volume', group = "Strong Volume")
Averageval1 = input.int(title='Average Volume BankNifty: (in K)', defval=40, minval=1,group = "Strong Volume")
Averageval2 = input.int(title='Average Volume Nifty: (in K)', defval=100, minval=1,group = "Strong Volume")
Averageval = syminfo.ticker == 'BANKNIFTY1!' ? Averageval1 * 1000 : syminfo.ticker == 'NIFTY1!' ? Averageval2 * 1000 : ta.sma(volume, 20)
varstrong = volume >= Averageval
plotshape(ShowHighVolume ? varstrong : na,"Volume Shape", style=shape.square, location=location.bottom, color=color.blue)
//===== Inside Bar =====
showIB = input(false, "Show Inside Bar", group = "Inside Bar")
isInside() =>
bodyStatus = (close >= open) ? 1 : -1
isInsidePattern = high < high[1] and low > low[1]
isInsidePattern ? bodyStatus : 0
// When is bullish
plotshape(showIB ? isInside() == 1 : na, style=shape.triangleup,
location=location.abovebar, color=color.green)
// When is bearish
plotshape(showIB ? isInside() == -1 : na, style=shape.triangledown,
location=location.belowbar, color=color.red)
isInsideBarMade = isInside() == 1 or isInside() == -1
alertcondition(showIB ? isInsideBarMade : na, title='Inside Bar', message='Inside Bar formed') |
Momentum Oscillator, Divergences & Signals [TrendAlpha] | https://www.tradingview.com/script/2qwDo2Q6-Momentum-Oscillator-Divergences-Signals-TrendAlpha/ | TrendAlpha | https://www.tradingview.com/u/TrendAlpha/ | 100 | 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/
// © TrendAlpha
//@version=5
indicator("Momentum Oscillator, Real Time Divergences & Signals [TrendAlpha]", "Momentum Oscillator, Divergences & Signals [TrendAlpha]")
length = input(7, "Length")
src = input(close, "Source")
show_lines = input(true, "Show Lines")
colcor = input(false, "Hide Price/Oscillator")
up = ta.highest(src, length)
dn = ta.lowest(src, length)
osc = ta.mom(ta.sma(ta.sma(src, length), length), length)
phosc = ta.crossunder(ta.change(osc), 0)
plosc = ta.crossover(ta.change(osc), 0)
bear = osc > 0 and phosc and ta.valuewhen(phosc, osc, 0) < ta.valuewhen(phosc, osc, 1) and ta.valuewhen(phosc, up, 0) > ta.valuewhen(phosc, up, 1)
bull = osc < 0 and plosc and ta.valuewhen(plosc, osc, 0) > ta.valuewhen(plosc, osc, 1) and ta.valuewhen(plosc, dn, 0) < ta.valuewhen(plosc, dn, 1)
simple_css = osc > osc[1] and osc > 0 ? color.new(color.green, 0) : osc < osc[1] and osc > 0 ? color.new(color.lime, 0) : osc < osc[1] and osc < 0 ? color.new(color.red, 0) : osc > osc[1] and osc < 0 ? color.new(color.maroon, 0) : na
plot(osc, "Osc", colcor ? color.new(color.black, 0) : simple_css, 3, plot.style_histogram)
plotshape(bull ? osc : na, "Bullish Circle", shape.circle, location.absolute, color.new(color.green, 0), size = size.tiny)
plotshape(bear ? osc : na, "Bearish Circle", shape.circle, location.absolute, color.new(color.red, 0), size = size.tiny)
plotshape(bull ? osc : na, "Bullish Label", shape.labelup, location.absolute, color.new(color.green, 0), text = "Buy", textcolor = color.white, size = size.tiny)
plotshape(bear ? osc : na, "Bearish Label", shape.labeldown, location.absolute, color.new(color.red, 0), text = "Sell", textcolor = color.white, size = size.tiny)
n = bar_index
bull_x1 = ta.valuewhen(plosc, n, 1)
bull_y1 = ta.valuewhen(plosc, osc, 1)
bear_x1 = ta.valuewhen(phosc, n, 1)
bear_y1 = ta.valuewhen(phosc, osc, 1)
var line bull_line = na
var line bear_line = na
if show_lines
if bull
bull_line := line.new(x1 = bull_x1, y1 = bull_y1, x2 = n, y2 = osc, color = color.new(color.green, 0), width = 1)
line.delete(bear_line)
else if bear
bear_line := line.new(x1 = bear_x1, y1 = bear_y1, x2 = n, y2 = osc, color = color.new(color.red, 0), width = 1)
line.delete(bull_line)
alertcondition(bull, title = "Bullish Divergence", message = "Bullish Divergence")
alertcondition(bear, title = "Bearish Divergence", message = "Bearish Divergence") |
IKH Cloud V1.0 (nextSignals) | https://www.tradingview.com/script/hjJw9cqN-IKH-Cloud-V1-0-nextSignals/ | justatradebro | https://www.tradingview.com/u/justatradebro/ | 150 | 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/
// © justatradebro
//@version=5
indicator("IKH Cloud V1.0 (nextSignals)", shorttitle='KumoDoc', overlay=true)
ima_color = input.color(color.orange, title = 'IMA Color')
trail_color_up = input.color(color.rgb(76, 175, 79, 70), title = 'Trail Up')
trail_color_down = input.color(color.rgb(255, 82, 82, 70), title = 'Trail Down')
candle_color_up = input.color(color.green, title = 'Candle Up')
candle_color_down = input.color(color.red, title = 'Candle Down')
// IMA Calculation
length = 5 // Length parameter for IMA calculation
ph = 0.0
pl = 0.0
alpha = 2.5 / (length + 1)
ima = 0.0
ima := alpha * ohlc4[1] + (1 - alpha) * nz(ima[1])
p1 = plot(ima, color=ima_color, linewidth=2, title="Instantaneous Moving Average")
lowest_low = ta.lowest(low[1], 5)
highest_high = ta.highest(high[1], 5)
avg_low = ta.sma(low[1], 5)
avg_high = ta.sma(high[1], 5)
// Trailing stop
a = 0.0
b = 0.0
z = 0.0
c = 0.0
l = 0.0
s = 0.0
trail = 0.0
if bar_index > 1 and nz(a[1]) == 1
b := math.max(lowest_low, nz(b[1]))
z := avg_high < nz(b[1]) and close < low[1] ? 1 : nz(z[1])
a := avg_high < nz(b[1]) and close < low[1] ? 0 : nz(a[1])
c := avg_high < nz(b[1]) and close < low[1] ? highest_high : nz(c[1])
else if nz(a[1]) == 0
c := math.min(highest_high, nz(c[1]))
z := avg_low > nz(c[1]) and close > high[1] ? 0 : nz(z[1])
a := avg_low > nz(c[1]) and close > high[1] ? 1 : nz(a[1])
b := avg_low > nz(c[1]) and close > high[1] ? lowest_low : nz(b[1])
else
b := nz(b[1])
z := nz(z[1])
a := nz(a[1])
c := nz(c[1])
if z == 0
l := nz(z[1]) != 0 ? nz(s[1]) : math.max(nz(b[1]), nz(l[1]))
s := 0
else if nz(z[1]) != 1
s := nz(l[1])
l := 0
else if z == 1
s := math.min(c, nz(s[1]))
l := nz(l[1])
else
l := nz(l[1])
s := nz(s[1])
if l > 0
trail := l
else
trail := s
trail_color_cond = ima < trail ? trail_color_down : trail_color_up
candle_color_cond = ohlc4 < trail ? candle_color_down : candle_color_up
p2 = plot(trail, color=trail_color_cond, title = "Trail")
plotcandle(open,high,low,close, color=candle_color_cond, wickcolor=candle_color_cond, bordercolor = candle_color_cond)
fill(plot1=p1, plot2=p2, color=trail_color_cond) |
K's Pivot Points | https://www.tradingview.com/script/d9w7Cwct-K-s-Pivot-Points/ | Sofien-Kaabar | https://www.tradingview.com/u/Sofien-Kaabar/ | 347 | 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/
// © Sofien-Kaabar
//@version=5
indicator("Smoothed Pivot Points", overlay = true)
lookback_piv = input(defval = 24, title = 'Pivot Lookback')
// Pivot points
// Adjusted highs
adjusted_high = ta.highest(high, lookback_piv)
// Adjusted lows
adjusted_low = ta.lowest(low, lookback_piv)
// Adjusted close
adjusted_close = ta.sma(close, lookback_piv)
// Pivot point
pivot_point = (adjusted_high + adjusted_low + adjusted_close) / 3
first_support = (ta.lowest(pivot_point, 12) * 2) - adjusted_high
first_resistance = (ta.highest(pivot_point, 12) * 2) - adjusted_low
found_support = close > first_support and close[1] < first_support[1]
found_resistance = close < first_resistance and close[1] > first_resistance[1]
plot(first_support, color = color.green)
plot(first_resistance, color = color.red)
plotshape(found_support, style = shape.triangleup, color = color.green, location = location.belowbar, size = size.small)
plotshape(found_resistance, style = shape.triangledown, color = color.red, location = location.abovebar, size = size.small)
|
RSI + ADX + MACD | https://www.tradingview.com/script/wkgtj1Bi/ | Dvd_Trading | https://www.tradingview.com/u/Dvd_Trading/ | 43 | 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/
// © Dvd_Trading
//@version=5
indicator(title='RSI + ADX ')
// Getting inputs
MACDmultiplier = input.float(title='MACD Hight multiplier', minval=0.0000000000001, maxval=999999999999, defval=0.1)
fast_length = input(title='Fast Length', defval=12)
slow_length = input(title='Slow Length', defval=26)
src = input(close, title='Source')
signal_length = input.int(title='Signal Smoothing', minval=1, maxval=50, defval=9)
sma_source = input(title='Simple MA(Oscillator)', defval=false)
sma_signal = input(title='Simple MA(Signal Line)', defval=false)
RSILength = input.int(14, minval=1, title='RSI Length')
// Plot colors
col_grow_above = #26A69A
col_grow_below = #FFCDD2
col_fall_above = #B2DFDB
col_fall_below = #EF5350
col_macd = color.green //#0094ff
col_signal = color.red //#ff6a00
// Calculating MACD
sma_1 = ta.sma(src, fast_length)
ema_1 = ta.ema(src, fast_length)
fast_ma = sma_source ? sma_1 : ema_1
sma_2 = ta.sma(src, slow_length)
ema_2 = ta.ema(src, slow_length)
slow_ma = sma_source ? sma_2 : ema_2
macd = fast_ma - slow_ma
sma_3 = ta.sma(macd, signal_length)
ema_3 = ta.ema(macd, signal_length)
signal = sma_signal ? sma_3 : ema_3
hist = macd - signal
// RSI
up = ta.rma(math.max(ta.change(src), 0), RSILength)
down = ta.rma(-math.min(ta.change(src), 0), RSILength)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
// Awesome Oscillator
ao = (ta.sma(hl2, 5) - ta.sma(hl2, 34)) * MACDmultiplier
// Directional Movement Index (DMI)
DMI_len = input.int(14, minval=1, title='DI Length')
DMI_lensig = input.int(14, title='ADX Smoothing', minval=1, maxval=50)
DMI_up = ta.change(high)
DMI_down = -ta.change(low)
plusDM = na(DMI_up) ? na : DMI_up > DMI_down and DMI_up > 0 ? DMI_up : 0
minusDM = na(DMI_down) ? na : DMI_down > DMI_up and DMI_down > 0 ? DMI_down : 0
trur = ta.rma(ta.tr, DMI_len)
plus = fixnan(100 * ta.rma(plusDM, DMI_len) / trur)
minus = fixnan(100 * ta.rma(minusDM, DMI_len) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), DMI_lensig)
// plot MACD
plot(hist * MACDmultiplier, title='Histogram', style=plot.style_columns, color=hist >= 0 ? hist[1] < hist ? col_grow_above : col_fall_above : hist[1] < hist ? col_grow_below : col_fall_below, transp=0)
plot(macd * MACDmultiplier, title='MACD', color=color.new(col_macd, 0))
plot(signal * MACDmultiplier, title='Signal', color=color.new(col_signal, 0))
// plot RSI
plot(rsi, color=color.new(color.purple, 0))
band1 = hline(70)
band0 = hline(30)
fill(band1, band0, color=color.new(color.fuchsia, 90))
hline(50, title='center', linestyle=hline.style_solid)
// plot AO
plot(ao, color=ta.change(ao) <= 0 ? color.red : color.green, style=plot.style_histogram)
// plot DMI
plot(plus, color=color.new(color.blue, 0), title='+DI')
plot(minus, color=color.new(color.orange, 0), title='-DI')
plot(adx, color=color.new(color.red, 0), title='ADX')
hline(25, title='25%', color=color.black, linestyle=hline.style_solid)
|
Liquidity Sweeps and Raids | https://www.tradingview.com/script/tKxs1WM0-Liquidity-Sweeps-and-Raids/ | Cancamurria | https://www.tradingview.com/u/Cancamurria/ | 239 | 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/
// © pmk07 - who is absolute Stud. Made MTF
// © Cancamurria
// @version=5
indicator(title ="Canca`s Sweeps`n`Raids", overlay=true,max_bars_back=4999, max_lines_count = 500, max_labels_count = 500)
var index = if (3 % 2 != 0)
math.ceil(float(3) / 2) - 1
else
math.round(float(3) / 2) - 1
history = input.int(999, "History", minval=10, maxval=4999, group='General')
sweepType = input.string(defval='Wick Only', title="Type", options=['Regular', 'Wick Only'], group='General')
enable_clear = input.bool(true, "Delete broken", group='General')
s_style = input.string(defval='Dotted', title="Style", options=['Solid', 'Dotted', 'Dashed'], group='Lines')
lineStyle = s_style == 'Dotted' ? line.style_dotted : s_style == 'Dashed' ? line.style_dashed : line.style_solid
lineWidth = input.int(1, "Width", group='Lines')
BullColor = input.color(defval=#2195f3, title='Bullish', group='Lines')
BearColor = input.color(defval=#ff0000, title='Bearish', group='Lines')
enable_label = input.bool(true, title= "Labels", group='Labels')
LabelColor = input.color(defval=color.gray, title='Color', group='Labels')
LabelSize = input.string(defval=size.small, title="Size", options=[size.huge, size.large, size.small, size.tiny, size.auto, size.normal], group='Labels')
type sweep
float lvl = na // y1 and y2
int start = na // time
int stop = na // time
int tf = na // TF in minutes
type plot
line line = na
label label = na
bool isbull = na // true = bull and false = bear
int tf = na
var plot[] lines = array.new <plot>()
tf1 = input.bool(true, "1", group='Timeframe')
tf2 = input.bool(true, "3", group='Timeframe')
tf3 = input.bool(true, "5", group='Timeframe')
tf4 = input.bool(false, "15", group='Timeframe')
tf5 = input.bool(false, "30", group='Timeframe')
tf6 = input.bool(false, "45", group='Timeframe')
tf7 = input.bool(true, "60", group='Timeframe')
tf8 = input.bool(false, "120", group='Timeframe')
tf9 = input.bool(false, "180", group='Timeframe')
tf10 = input.bool(false, "240", group='Timeframe')
tf11 = input.bool(true, "D", group='Timeframe')
tf12 = input.bool(false, "W", group='Timeframe')
find_lines(string sweepType, int t) =>
sweep bearishSweep = na
sweep bullishSweep = na
float thresholdSwingLow = na
float thresholdSwingHigh = na
for index = 1 to history by 1
if high[index] >= thresholdSwingHigh or na(thresholdSwingHigh)
thresholdSwingHigh := high[index]
if high[index] >= high or thresholdSwingHigh >= high
break
if high[index + 1] <= high[index] and high[index - 1] <= high[index] and high >= high[index] and open <= high[index] and high[index] >= thresholdSwingHigh
if sweepType == 'Regular' or (sweepType == 'Wick Only' and close < high[index])
bearishSweep := sweep.new(high[index], time - t * 60000 * index, time + t * 60000, t)
for index = 1 to history by 1
if low[index] <= thresholdSwingLow or na(thresholdSwingLow)
thresholdSwingLow := low[index]
if low[index] <= low or thresholdSwingLow <= low
break
if low[index + 1] >= low[index] and low[index - 1] >= low[index] and low <= low[index] and open >= low[index] and low[index] <= thresholdSwingLow
if sweepType == 'Regular' or (sweepType == 'Wick Only' and close > low[index])
bullishSweep := sweep.new(low[index], time - t * 60000 * index, time + t * 60000, t)
[bearishSweep, bullishSweep]
remove_lastline(plot[] lines)=>
sz = array.size(lines)
if sz >= 100
temp = array.get(lines, 0)
line.delete(temp.line)
if enable_label
label.delete(temp.label)
array.remove(lines, 0)
get_txt(tf)=>
string out = na
if tf != timeframe.multiplier
out := switch tf
1 => "1"
3 => "3"
5 => "5"
15 => "15"
30 => "30"
45 => "45"
60 => "60"
120 => "120"
180 => "180"
240 => "240"
1440 => "D"
10080 => "W"
=> "XXX"
out
create_lines(sweep bearishSweep, sweep bullishSweep, int tf) =>
currentTF = timeframe.multiplier
if not na(bearishSweep) and tf >= currentTF
remove_lastline(lines)
label temp_label = na
if enable_label
temp_label := label.new(bearishSweep.stop, bearishSweep.lvl, get_txt(bearishSweep.tf), xloc.bar_time, yloc.price, na, label.style_none, LabelColor, LabelSize)
temp_line = line.new(bearishSweep.start, bearishSweep.lvl, bearishSweep.stop, bearishSweep.lvl, xloc=xloc.bar_time, color=BearColor, style=lineStyle, width=lineWidth)
array.push(lines, plot.new(temp_line, temp_label, false, bearishSweep.tf))
if not na(bullishSweep) and tf >= currentTF
remove_lastline(lines)
label temp_label = na
if enable_label
temp_label := label.new(bullishSweep.stop, bullishSweep.lvl, get_txt(bullishSweep.tf), xloc.bar_time, yloc.price, na, label.style_none, LabelColor, LabelSize)
temp_line = line.new(bullishSweep.start, bullishSweep.lvl, bullishSweep.stop, bullishSweep.lvl, xloc=xloc.bar_time, color=BullColor, style=lineStyle, width=lineWidth)
array.push(lines, plot.new(temp_line, temp_label, true, bullishSweep.tf))
control_lines(plot[] lines)=>
sz = array.size(lines)
id = array.new_int()
if sz > 0
for index = sz - 1 to 0 by 1
temp = array.get(lines, index)
tf = temp.tf
if timeframe.change(get_txt(tf))
line = temp.line
lineLvl = line.get_y1(line)
isbull = temp.isbull
if (isbull == true and high < lineLvl) or ( isbull == false and low > lineLvl)
if enable_label
label.delete(temp.label)
line.delete(line)
array.set(lines, index, na)
array.push(id, index)
if array.size(id) > 0
array.sort(id, order.ascending)
for index = array.size(id) - 1 to 0 by 1
array.remove(lines, array.get(id, index))
[bearishSweep1, bullishSweep1] = request.security(syminfo.tickerid, "1", find_lines(sweepType, 1), barmerge.gaps_off, barmerge.lookahead_off)
[bearishSweep2, bullishSweep2] = request.security(syminfo.tickerid, "3", find_lines(sweepType, 3), barmerge.gaps_off, barmerge.lookahead_off)
[bearishSweep3, bullishSweep3] = request.security(syminfo.tickerid, "5", find_lines(sweepType, 5), barmerge.gaps_off, barmerge.lookahead_off)
[bearishSweep4, bullishSweep4] = request.security(syminfo.tickerid, "15", find_lines(sweepType, 15), barmerge.gaps_off, barmerge.lookahead_off)
[bearishSweep5, bullishSweep5] = request.security(syminfo.tickerid, "30", find_lines(sweepType, 30), barmerge.gaps_off, barmerge.lookahead_off)
[bearishSweep6, bullishSweep6] = request.security(syminfo.tickerid, "45", find_lines(sweepType, 45), barmerge.gaps_off, barmerge.lookahead_off)
[bearishSweep7, bullishSweep7] = request.security(syminfo.tickerid, "60", find_lines(sweepType, 60), barmerge.gaps_off, barmerge.lookahead_off)
[bearishSweep8, bullishSweep8] = request.security(syminfo.tickerid, "120", find_lines(sweepType, 120), barmerge.gaps_off, barmerge.lookahead_off)
[bearishSweep9, bullishSweep9] = request.security(syminfo.tickerid, "180", find_lines(sweepType, 180), barmerge.gaps_off, barmerge.lookahead_off)
[bearishSweep10, bullishSweep10] = request.security(syminfo.tickerid, "240", find_lines(sweepType, 240), barmerge.gaps_off, barmerge.lookahead_off)
[bearishSweep11, bullishSweep11] = request.security(syminfo.tickerid, "D", find_lines(sweepType, 1440), barmerge.gaps_off, barmerge.lookahead_off)
[bearishSweep12, bullishSweep12] = request.security(syminfo.tickerid, "W", find_lines(sweepType, 10080), barmerge.gaps_off, barmerge.lookahead_off)
currentTF = timeframe.multiplier
if tf1 and currentTF <= 1
create_lines(bearishSweep1, bullishSweep1, 1)
if tf2 and currentTF <= 3
create_lines(bearishSweep2, bullishSweep2, 3)
if tf3 and currentTF <= 5
create_lines(bearishSweep3, bullishSweep3, 5)
if tf4 and currentTF <= 15
create_lines(bearishSweep4, bullishSweep4, 15)
if tf5 and currentTF <= 30
create_lines(bearishSweep5, bullishSweep5, 30)
if tf6 and currentTF <= 45
create_lines(bearishSweep6, bullishSweep6, 45)
if tf7 and currentTF <= 60
create_lines(bearishSweep7, bullishSweep7, 60)
if tf8 and currentTF <= 120
create_lines(bearishSweep8, bullishSweep8, 120)
if tf9 and currentTF <= 180
create_lines(bearishSweep9, bullishSweep9, 180)
if tf10 and currentTF <= 240
create_lines(bearishSweep10, bullishSweep10, 240)
if tf11 and currentTF <= 1440
create_lines(bearishSweep11, bullishSweep11, 1440)
if tf12 and currentTF <= 10080
create_lines(bearishSweep12, bullishSweep12, 10080)
if enable_clear
control_lines(lines)
// Define alert conditions for each timeframe
SweepAlert1 = (na(bearishSweep1) ? false : true) or (na(bullishSweep1) ? false : true)
SweepAlert2 = (na(bearishSweep2) ? false : true) or (na(bullishSweep2) ? false : true)
SweepAlert3 = (na(bearishSweep3) ? false : true) or (na(bullishSweep3) ? false : true)
SweepAlert4 = (na(bearishSweep4) ? false : true) or (na(bullishSweep4) ? false : true)
SweepAlert5 = (na(bearishSweep5) ? false : true) or (na(bullishSweep5) ? false : true)
SweepAlert6 = (na(bearishSweep6) ? false : true) or (na(bullishSweep6) ? false : true)
SweepAlert7 = (na(bearishSweep7) ? false : true) or (na(bullishSweep7) ? false : true)
SweepAlert8 = (na(bearishSweep8) ? false : true) or (na(bullishSweep8) ? false : true)
SweepAlert9 = (na(bearishSweep9) ? false : true) or (na(bullishSweep9) ? false : true)
SweepAlert10 = (na(bearishSweep10) ? false : true) or (na(bullishSweep10) ? false : true)
SweepAlert11 = (na(bearishSweep11) ? false : true) or (na(bullishSweep11) ? false : true)
SweepAlert12 = (na(bearishSweep12) ? false : true) or (na(bullishSweep12) ? false : true)
SweepAlert13 = (na(bearishSweep1) ? false : true) or (na(bullishSweep1) ? false : true) or (na(bearishSweep2) ? false : true) or (na(bullishSweep2) ? false : true) or (na(bearishSweep3) ? false : true) or (na(bullishSweep3) ? false : true) or (na(bearishSweep4) ? false : true) or (na(bullishSweep4) ? false : true) or (na(bearishSweep5) ? false : true) or (na(bullishSweep5) ? false : true) or (na(bearishSweep6) ? false : true) or (na(bullishSweep6) ? false : true) or (na(bearishSweep7) ? false : true) or (na(bullishSweep7) ? false : true) or (na(bearishSweep8) ? false : true) or (na(bullishSweep8) ? false : true) or (na(bearishSweep9) ? false : true) or (na(bullishSweep9) ? false : true) or (na(bearishSweep10) ? false : true) or (na(bullishSweep10) ? false : true) or (na(bearishSweep11) ? false : true) or (na(bullishSweep11) ? false : true) or (na(bearishSweep12) ? false : true) or (na(bullishSweep12) ? false : true)
alertcondition(SweepAlert13, title="All timeframes", message="Sweep has occurred!")
alertcondition(SweepAlert1, title="1", message="1 minute sweep has occurred!")
alertcondition(SweepAlert2, title="3", message="3 minutes sweep has occurred!")
alertcondition(SweepAlert3, title="5", message="5 minutes sweep has occurred!")
alertcondition(SweepAlert4, title="15", message="15 minutes sweep has occurred!")
alertcondition(SweepAlert5, title="30", message="30 minutes sweep has occurred!")
alertcondition(SweepAlert6, title="45", message="45 minutes sweep has occurred!")
alertcondition(SweepAlert7, title="60", message="Hourly sweep has occurred!")
alertcondition(SweepAlert8, title="2H", message="2H sweep has occurred!")
alertcondition(SweepAlert9, title="3H", message="3H sweep has occurred!")
alertcondition(SweepAlert10, title="4H", message="4H sweep has occurred!")
alertcondition(SweepAlert11, title="D", message="Daily sweep has occurred!")
alertcondition(SweepAlert12, title="W", message="Weekly sweep has occurred!")
|
Moving Average - TREND POWER v1.1- (AS) | https://www.tradingview.com/script/JwFFFF8I/ | Adam-Szafranski | https://www.tradingview.com/u/Adam-Szafranski/ | 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/
// © Adam-Szafranski
//@version=5
indicator("Moving Average - TREND POWER v1.1- (AS)",shorttitle = 'TR_POW - (AS)',overlay = false)
///////////////////TOOLTIPS{
TT_0X = 'MAIN IDEA: \n This is Trend Indicator that rises/falls if moving avg is below/above price and resets when there is a cross (cross of what will be defined later).If you have trouble with grasping how it works either look into "STRATEGY LOGIC" part of the code or in case you dont know pine script select SIMPLE preset and define values of MA1(how SIMPLE works described in PRESETS tooltip)\n!!!!!!-defval settings for MA1 and MA2 are not optimalized for now'
//TT_0Y = 'CROSS TYPES LIST: \n-1 means that its cross of MA1 \n-2 means its cross of MA2 \n-3 is a cross of MA1 and MA2 \n-H - cross with high \n-L - cross with low \n"So for example 1L is cross of MA1 with low or 2H is cross of MA2 with high \n-1HL-cross of MA1 with high or low 12HL cross of MA1 with high or MA1 with low or MA2 with high or MA2 with low \nLIST: \n -1L MA1+low \n -1H MA1+high\n -2L MA2+low\n -1H MA2+high\n -1L MA1+low\n -1L MA1+low'
TT_01 = 'SOURCE: \nSource of MA1 and MA2 \nOVERLAY: \n(off by def) - if you want to see MA1/2 on chart turn ON and change overlay to true in the code'
TT_02 = 'TRESHOLDS: \nvalue od upper/lower treshold/Use TSHs? \nIF blw upper and above lower - consolidation'
TT_03 = 'MA1: \nLength/type/Offset(only if LSMA) \n faster MAs for short trends and slower/bigger periods for larger trends'
TT_04 = 'MA2(ALMA):\nLength/offset/sigma \n Use setting in which MA2>MA1 in Downtrend and MA2<MA1 in uptrend'
TT_05 = 'CROSS TYPE: \nchoose type of cross to plot on chart(Overlay=true) or to use in counting crosses \nPlot cross on chart? '
TT_06 = 'LOOKBACK: \nSet lookback for counting choosen cross type above /npPLOT number of crosses on chart (Overlay=false)'
TT_07 = 'PRESETS: \n-SIMPLE-most basic version using only MA1 and CROSS_1_ULT type(all crosses of MA1(low,high,close,ohlc4 etc...)) \n-ABSOLUTE-shows only positive values if trend(UP/DN), uses CROSS_123_ULT type(all crosses)\n-CUSTOM-pick this to define your own conditions below (take look into stratey code if more help needed)\nSOURCE: \nabv/blw to calculate value \n-HL-MA<high for UPtrend and MA>low for DNtren \n-OHLC4- MA > or < from OHLC4'
TT_08 = '(this part only if PRESET choosen above is CUST\nCHOOSE MA: \nChoosing which MA to use (if PRESET=CUST). \nMA1 - only use MA1 - grows if ma1 below defined source and falls if above \nMA2 - only use MA2 - smae as MA1 but MA2 instead \nBOTH - Use MA1 and MA2 - grows if MA1 or MA2 below, grows faster if MA1 and MA2 below, growws fastest if MA1 and MA2 blelow and MA2<MA1 \nCRS:\nWhat Conditions of cross to use for going back to 0\n>/< - 0 if uptrend and cross with high (and the other way around)\nALL - 0 if cross with high or low\nULT - 0 if any cross'
/////TOOLTIPS}
///////////////////FUNCTIONS{
ma(type, src, len,off) =>
e = ta.ema(src,len)
switch type
'SMA' => ta.sma(src, len)
'EMA' => ta.ema(src, len)
'2MA' => 2 * e - ta.ema(e, len)
'3MA' => 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len)
'WMA' => ta.wma(src, len)
'LSM' => ta.linreg(src,len,off)
'HMA' => ta.hma(src,len)
'RMA' => ta.rma(src,len)
///////////////////FUNCTIONS}
///////////////////INPUTS{
var G_STRT = '---Starting settings---'
STARTINFO = input.bool (true ,group = G_STRT,inline = 'X',title ='HOW TO USE AND SET - READ ME!',tooltip=TT_0X)
//LISTSINFO = input.bool (true ,group = G_STRT,inline = 'Y',title ='TYPE OF CROSS AND COND - LIST',tooltip=TT_0Y)
INPSOURCE = input.source (ohlc4 ,group = G_STRT,inline = '1',title ='SOURCE/OVERLAY->')
P_OVERLAY = input.bool (false ,group = G_STRT,inline = '1',title ='',tooltip = TT_01)
TSHOLD_UP = input.float (0.5 ,group = G_STRT,inline = '2',title ='TSHL-UP/DN/USE?->')
TSHOLD_DN = input.float (-0.5 ,group = G_STRT,inline = '2',title ='')
P_TSHOLDS = input.bool (false ,group = G_STRT,inline = '2',title ='',tooltip = TT_02)
var G_MOVA = 'Moving avgs settings'
INPMA1LEN = input.int (120 ,group = G_MOVA,inline = '3',title ='MA1-LEN/TYP/OFF')
INPMA1TYP = input.string ('LSM' ,group = G_MOVA,inline = '3',title ='', options = ['EMA','HMA','2MA','3MA','WMA','SMA','LSM','RMA'])
INPLSMAOF = input (36 ,group = G_MOVA,inline = '3',title ='',tooltip = TT_03)
INPMA2LEN = input.int (120 ,group = G_MOVA,inline = '4',title ='MA2-LEN/OFF/SIG')
INPMA2OFF = input.float (1.5 ,group = G_MOVA,inline = '4',title ='')
INPMA2SIG = input.int (1 ,group = G_MOVA,inline = '4',title ='',tooltip = TT_04)
var G_CROS = 'Crosses settings'
P_CRS_SIG = input.string ('NONE' ,group = G_CROS,inline = '5',title ='CROSS TO PLOT/COUNT',options = ['NONE','1L','1H','1HL','2L','2H','2HL','12L','12H','12HL','3','123HL','1-ULT','2-ULT','123-ULT'])
P_CRSHAPE = input.bool (false ,group = G_CROS,inline = '5',title ='PLOT?',tooltip = TT_05)
INPLOOKBC = input.int (25 ,group = G_CROS,inline = '6',title ='CROSS COUNT LOOKBC')
P_CRSNUMB = input.bool (false ,group = G_CROS,inline = '6',title ='PLOT?',tooltip = TT_06)
var G_COND = 'Define Conditions for calculation'
PRESETS = input.string ('CUST' ,group = G_COND,inline = '7',title ='PRESETS/SOURCE',options = ['CUST','SIMPLE','ABSOLUTE'])
S_SRC_CD = input.string ('H/L' ,group = G_COND,inline = '7',title ='/',options = ['H/L','OHLC'],tooltip = TT_07)
S_USE_MA = input.string ('MA1' ,group = G_COND,inline = '8',title ='IF CUST - MA/CRS',options = ['MA1','MA2','BOTH'])
S_CRS_CD = input.string ('>/<' ,group = G_COND,inline = '8',title ='/',options = ['>/<','ALL','ULT'],tooltip = TT_08)
///////////////////INPUTS}
///////////////////CROSSES{
MA1 = ma (INPMA1TYP, INPSOURCE, INPMA1LEN, INPLSMAOF)
MA2 = ta.alma (INPSOURCE, INPMA2LEN, INPMA2OFF, INPMA2SIG)
CROSS_1_L = ta.cross(MA1,low) ,CROSS_1_H = ta.cross(MA1,high) ,CROSS_3_M = ta.cross(MA1,MA2)
CROSS_2_L = ta.cross(MA2,low) ,CROSS_2_H = ta.cross(MA2,high)
CROSS_12_L = CROSS_1_L or CROSS_2_L ,CROSS_12_H = CROSS_1_H or CROSS_2_H
CROSS_1_HL = CROSS_1_L or CROSS_1_H ,CROSS_2_HL = CROSS_2_L or CROSS_2_H
CROSS_12_HL = CROSS_1_L or CROSS_2_L or CROSS_1_H or CROSS_2_H
CROSS_123_HL = CROSS_1_L or CROSS_2_L or CROSS_1_H or CROSS_2_H or CROSS_3_M
CROSS_1_ULT = ta.cross(MA1,close) or ta.cross(MA1,ohlc4) or ta.cross(MA1,hl2) or ta.cross(MA1,high) or ta.cross(MA1,low) or ta.cross(MA1,open)
CROSS_2_ULT = ta.cross(MA2,close) or ta.cross(MA2,ohlc4) or ta.cross(MA2,hl2) or ta.cross(MA2,high) or ta.cross(MA2,low) or ta.cross(MA2,open)
CROSS_123_ULT =
ta.cross(MA1,close) or
ta.cross(MA1,ohlc4) or ta.cross(MA1,hl2) or
ta.cross(MA1,high) or ta.cross(MA1,low) or
ta.cross(MA1,open) or ta.cross(MA2,close) or
ta.cross(MA2,ohlc4) or ta.cross(MA2,hl2) or
ta.cross(MA2,high) or ta.cross(MA2,low) or
ta.cross(MA2,open) or ta.cross(MA1,MA2)
CROSStoCOUNT =
P_CRS_SIG=='1L' ?CROSS_1_L :P_CRS_SIG=='1H' ?CROSS_1_H :P_CRS_SIG=='1HL' ?CROSS_1_HL :
P_CRS_SIG=='2L' ?CROSS_2_L :P_CRS_SIG=='2H' ?CROSS_2_H :P_CRS_SIG=='2HL' ?CROSS_2_HL :
P_CRS_SIG=='12L' ?CROSS_12_L :P_CRS_SIG=='12H' ?CROSS_12_H :P_CRS_SIG=='12HL' ?CROSS_12_HL :
P_CRS_SIG=='3' ?CROSS_3_M :P_CRS_SIG=='123HL' ?CROSS_123_HL :P_CRS_SIG=='1-ULT' ?CROSS_1_ULT :
P_CRS_SIG=='2-ULT' ?CROSS_2_ULT :P_CRS_SIG=='123-ULT' ?CROSS_123_ULT :na
CROSScount = 0
for i = 0 to (INPLOOKBC-1)
if CROSStoCOUNT[i]
CROSScount+= 1
///////////////////CROSSES}
///////////////////CONDITIONS{
COND_UP_1 = S_SRC_CD=='H/L'?MA1<high:MA1<ohlc4 ,COND_UP_2 = S_SRC_CD=='H/L'?MA2<high:MA2<ohlc4 ,COND_UP_3 = MA2<MA1
COND_DN_1 = S_SRC_CD=='H/L'?MA1>low :MA1>ohlc4 ,COND_DN_2 = S_SRC_CD=='H/L'?MA2>low :MA2>ohlc4 ,COND_DN_3 = MA2>MA1
COND_UP_1and2 = COND_UP_1 and COND_UP_2 ,COND_UP_1or2 = COND_UP_1 or COND_UP_2
COND_DN_1and2 = COND_DN_1 and COND_DN_2 ,COND_DN_1or2 = COND_DN_1 or COND_DN_2
COND_UP_1and2and3 = COND_UP_1 and COND_UP_2 and COND_UP_3
COND_DN_1and2and3 = COND_DN_1 and COND_DN_2 and COND_DN_3
///////////////////CONDITIONS}
///////////////////INDICATOR LOGIC{
var TREND_POINTS_C = 0.0
var TREND_POINTS_S = 0.0
var TREND_POINTS_A = 0.0
if PRESETS == 'CUST'
if S_USE_MA=='MA1'
if COND_UP_1
TREND_POINTS_C+=0.02
if COND_DN_1
TREND_POINTS_C-=0.02
if S_USE_MA=='MA2'
if COND_UP_2
TREND_POINTS_C+=0.02
if COND_DN_2
TREND_POINTS_C-=0.02
if S_USE_MA=='BOTH'
if COND_UP_1and2and3 //123
TREND_POINTS_C+=0.04
else if COND_UP_1and2
TREND_POINTS_C+=0.03 //12
else if COND_UP_1or2
TREND_POINTS_C+=0.02 //1
if COND_DN_1and2and3
TREND_POINTS_C-=0.04 //3
else if COND_DN_1and2 //12
TREND_POINTS_C-=0.03
else if COND_DN_1or2 //1
TREND_POINTS_C-=0.02
if S_CRS_CD == '>/<'
if S_USE_MA=='MA1'
if TREND_POINTS_C>0 and CROSS_1_H
TREND_POINTS_C := 0
if TREND_POINTS_C<0 and CROSS_1_L
TREND_POINTS_C := 0
if S_USE_MA=='MA2'
if TREND_POINTS_C>0 and CROSS_2_H
TREND_POINTS_C := 0
if TREND_POINTS_C<0 and CROSS_2_L
TREND_POINTS_C := 0
if S_USE_MA=='BOTH'
if TREND_POINTS_C>0 and CROSS_12_H
TREND_POINTS_C := 0
if TREND_POINTS_C<0 and CROSS_12_L
TREND_POINTS_C := 0
if S_CRS_CD == 'ALL'
if S_USE_MA=='MA1'
if CROSS_1_HL
TREND_POINTS_C := 0
if S_USE_MA=='MA2'
if CROSS_2_HL
TREND_POINTS_C := 0
if S_USE_MA=='BOTH'
if CROSS_123_HL
TREND_POINTS_C := 0
if S_CRS_CD == 'ULT'
if S_USE_MA=='MA1'
if CROSS_1_ULT
TREND_POINTS_C := 0
if S_USE_MA=='MA2'
if CROSS_2_ULT
TREND_POINTS_C := 0
if S_USE_MA=='BOTH'
if CROSS_123_ULT
TREND_POINTS_C := 0
if PRESETS == 'SIMPLE'
if COND_UP_1
TREND_POINTS_S+=0.02
if COND_DN_1
TREND_POINTS_S-=0.02
if CROSS_1_ULT
TREND_POINTS_S:=0
if PRESETS == 'ABSOLUTE'
if COND_DN_1and2and3 or COND_UP_1and2and3
TREND_POINTS_A += 0.02
if CROSS_123_ULT
TREND_POINTS_A :=0
VALUE = PRESETS == 'ABSOLUTE'?TREND_POINTS_A:PRESETS == 'SIMPLE'?TREND_POINTS_S:PRESETS == 'CUST'?TREND_POINTS_C:na
///////////////////INDICATOR LOGIC}
///////////////////PLOTS{
TREND_VALUE_COLOR =
PRESETS == 'ABSOLUTE' ?color.rgb(0, 116, 211):
PRESETS == 'SIMPLE' ?color.rgb(216, 194 , 0):
PRESETS == 'CUST' ?color.rgb(220, 35, 112):na
TREND_P = plot (not P_OVERLAY?VALUE:na ,'TREND_PLOT_V' ,TREND_VALUE_COLOR)
ZERO1_P = hline (not P_OVERLAY?0:na ,'ZERO1_PLOT' ,color.rgb(123, 128, 146) ,linestyle = hline.style_dashed )
ZERO2_P = plot (not P_OVERLAY?0:na ,'ZERO2_PLOT' ,color.rgb(33, 149 , 243,100) ,display = display.none)
CROSS_P = plot (P_CRSNUMB and not P_OVERLAY?CROSScount:na ,'CROSS',color.yellow,1,plot.style_columns)
TSHUP_P = hline (P_TSHOLDS and not P_OVERLAY?TSHOLD_UP :na ,'TSHUP',color.gray,hline.style_dashed)
TSHDN_P = hline (P_TSHOLDS and not P_OVERLAY?TSHOLD_DN :na ,'TSHSN',color.gray,hline.style_dashed)
MA1_P = plot (P_OVERLAY and S_USE_MA!='MA2'?MA1:na,'MA1',color.rgb(46, 92, 231))
MA2_P = plot (P_OVERLAY and S_USE_MA!='MA1'?MA2:na,'MA2',color.rgb(255, 26, 106))
fill (ZERO2_P,TREND_P ,P_OVERLAY?na:(VALUE>=0?#00ff0040:VALUE<0?#e9377e3f:color.blue))
fill (MA1_P,MA2_P ,P_OVERLAY?(COND_UP_1and2and3?#00ff0040:COND_DN_1and2and3?#e9377e3f:na):na)
plotshape(P_CRS_SIG == '1L' and P_CRSHAPE and P_OVERLAY?CROSS_1_L :na,'',shape.cross,location.abovebar,color.rgb(213, 40, 144, 58),size=size.small)
plotshape(P_CRS_SIG == '1H' and P_CRSHAPE and P_OVERLAY?CROSS_1_H :na,'',shape.cross,location.abovebar,color.rgb(40, 213, 75 , 58),size=size.small)
plotshape(P_CRS_SIG == '1HL' and P_CRSHAPE and P_OVERLAY?CROSS_1_HL :na,'',shape.cross,location.abovebar,color.rgb(35, 170, 233, 58),size=size.small)
plotshape(P_CRS_SIG == '2L' and P_CRSHAPE and P_OVERLAY?CROSS_2_L :na,'',shape.cross,location.abovebar,color.rgb(213, 40, 144, 58),size=size.small)
plotshape(P_CRS_SIG == '2H' and P_CRSHAPE and P_OVERLAY?CROSS_2_H :na,'',shape.cross,location.abovebar,color.rgb(40, 213, 75 , 58),size=size.small)
plotshape(P_CRS_SIG == '2HL' and P_CRSHAPE and P_OVERLAY?CROSS_2_HL :na,'',shape.cross,location.abovebar,color.rgb(35, 170, 233, 58),size=size.small)
plotshape(P_CRS_SIG == '12L' and P_CRSHAPE and P_OVERLAY?CROSS_12_L :na,'',shape.cross,location.abovebar,color.rgb(213, 40, 144, 58),size=size.small)
plotshape(P_CRS_SIG == '12H' and P_CRSHAPE and P_OVERLAY?CROSS_12_H :na,'',shape.cross,location.abovebar,color.rgb(40, 213, 75 , 58),size=size.small)
plotshape(P_CRS_SIG == '12HL' and P_CRSHAPE and P_OVERLAY?CROSS_12_HL :na,'',shape.cross,location.abovebar,color.rgb(35, 170, 233, 58),size=size.small)
plotshape(P_CRS_SIG == '3' and P_CRSHAPE and P_OVERLAY?CROSS_3_M :na,'',shape.cross,location.abovebar,color.rgb(35, 170, 233, 58),size=size.small)
plotshape(P_CRS_SIG == '123HL' and P_CRSHAPE and P_OVERLAY?CROSS_123_HL :na,'',shape.cross,location.abovebar,color.rgb(35, 170, 233, 58),size=size.small)
plotshape(P_CRS_SIG == '1-ULT' and P_CRSHAPE and P_OVERLAY?CROSS_1_ULT :na,'',shape.cross,location.abovebar,color.rgb(35, 170, 233, 58),size=size.small)
plotshape(P_CRS_SIG == '2-ULT' and P_CRSHAPE and P_OVERLAY?CROSS_2_ULT :na,'',shape.cross,location.abovebar,color.rgb(35, 170, 233, 58),size=size.small)
plotshape(P_CRS_SIG == '123-ULT' and P_CRSHAPE and P_OVERLAY?CROSS_123_ULT :na,'',shape.cross,location.abovebar,color.rgb(35, 170, 233, 58),size=size.small)
///////////////////PLOTS}
|
Open interest flow / quantifytools | https://www.tradingview.com/script/68wuwSZ3-Open-interest-flow-quantifytools/ | quantifytools | https://www.tradingview.com/u/quantifytools/ | 569 | 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/
// © quantifytools
//@version=5
indicator("Open interest flow / quantifytools")
// Inputs
//OI inputs
groupSource = "Open interest source"
i_oiSymbol = input.symbol("BTCUSDT.P_OI", "Open interest source", group=groupSource, inline="src")
i_autoOiCrypto = input.bool(false, "Auto-select source (crypto)", tooltip="Automatically chooses OI source for CRYPTO/USDT pairs when enabled. OI is fetched from Binance.")
groupSettings = "Open interest settings"
i_xtrSensitivity = input.int(3, "Flow burst sensitivity", minval=1, maxval=5, tooltip="Controls criteria set for bursts. 1 = OI value at 0.80 + 10% increase = OI burst. 5 = OI value at 1.2 + 50% increase = OI burst. 1 step in sensitivity = 0.10 increase in OI value/10% increase in required change.", group=groupSettings)
i_rBasisLength = input.int(10, "Length for relative OI/price calculations", tooltip="Controls length of moving average used in relative OI/price calculations. Greater length = more lag, less noise. Shorter length = less lag, more noise. Recommended to keep at default value (10).", group=groupSettings)
//Visual inputs
groupCol = "Visuals"
i_candleColor = input.string("None", "Colorize candles", options=["None", "Flows", "Extremes"], group=groupCol, tooltip="Colorizes candles based on either all flow states occuring or flow states during bursts")
i_flowInfoBool = input.bool(false, "Flow guidelines", group=groupCol, tooltip="Enables guidelines/reminders for OI flow interpretation")
i_staticColor = input.bool(false, "Static color", group=groupCol, tooltip="Enables static color instead of gradient. Better visibility for chart color.")
i_showPriceLine = input.bool(false, "Show price line", group=groupCol, tooltip="Enables relative price line alongside relative OI.")
//Color inputs
i_buyInflowCol = input.color(color.green, "Buy inflows", group=groupCol, inline="bin")
i_sellInflowCol = input.color(color.red, "Sell inflows", group=groupCol, inline="sin")
i_buyOutflowCol = input.color(color.teal, "Buy outflows", group=groupCol, inline="bout")
i_sellOutflowCol = input.color(color.maroon, "Sell outflows", group=groupCol, inline="sout")
i_buyInflowColExt = input.color(color.rgb(7, 255, 230) , "Extreme", group=groupCol, inline="bin")
i_sellInflowColExt = input.color(color.rgb(255, 125, 12), "Extreme", group=groupCol, inline="sin")
i_buyOutflowColExt = input.color(color.green, "Extreme", group=groupCol, inline="bout")
i_sellOutflowColExt = input.color(color.red, "Extreme", group=groupCol, inline="sout")
i_upperLine = input.color(color.new(color.gray, 90), "Upper band", group=groupCol, inline="bandu")
i_upperLine2 = input.color(color.new(color.red, 90), "Extreme", group=groupCol, inline="bandu")
i_lowerLine2 = input.color(color.new(color.red, 90), "Lower band", group=groupCol, inline="bandd")
i_lowerLine = input.color(color.new(color.gray, 90), "Extreme", group=groupCol, inline="bandd")
// Relative OI
//Relative price (OI/price relative to its moving average)
sma = ta.sma(close, i_rBasisLength)
smaSpread = ((close / sma) - 1) * 100
//Requested OI symbol
reqOiSymbol = i_autoOiCrypto and str.contains(syminfo.ticker, "USDT.P") ? "BINANCE:" + syminfo.ticker + "_OI" :
i_autoOiCrypto and str.contains(syminfo.ticker, "USDT.P") == false and str.contains(syminfo.ticker, "USDT") ? "BINANCE:" + syminfo.ticker + ".P_OI": i_oiSymbol
//Fetching relative OI
oiSpread = request.security(reqOiSymbol, timeframe.period, smaSpread)
//Function for forming relative values (used for price and OI)
relativeValue(source) =>
//Initializing arrays
var pivotHighs = array.new_float()
var pivotLows = array.new_float()
//Array size limit
sizeLimit = 20
//Keeping array sizes fixed
if array.size(pivotHighs) > sizeLimit
array.remove(pivotHighs, 0)
if array.size(pivotLows) > sizeLimit
array.remove(pivotLows, 0)
//Defining pivot. Consider pivot valid only when spread is above/below 0.
ph = source > 0 ? ta.pivothigh(source, 5, 5) : na
pl = source < 0 ? ta.pivotlow(source, 5, 5) : na
//Populating arrays
if ph
array.push(pivotHighs, ph)
if pl
array.push(pivotLows, pl)
//Forming average values from arrays
avgPh = array.avg(pivotHighs)
avgPl = array.avg(pivotLows)
[avgPh, avgPl]
//Average OI spread turning points
[smaPhOi, smaPlOi] = relativeValue(oiSpread)
//Calculating relative OI
relativeOi = oiSpread > 0 ? oiSpread / smaPhOi : 0 - (oiSpread / smaPlOi)
// Relative price
//Average price spread turning points
[smaPhPrice, smaPlPrice] = relativeValue(smaSpread)
//Calculating relative price
relativePrice = smaSpread > 0 ? smaSpread / smaPhPrice : 0 - (smaSpread / smaPlPrice)
//OI flow burst criteria, gain and position
oiXtremeGain = i_xtrSensitivity == 1 ? 1.1 : i_xtrSensitivity == 2 ? 1.2 : i_xtrSensitivity == 3 ? 1.3 :
i_xtrSensitivity == 4 ? 1.4 : 1.5
oiXtremePos = i_xtrSensitivity == 1 ? 0.80 : i_xtrSensitivity == 2 ? 0.9 : i_xtrSensitivity == 3 ? 1 :
i_xtrSensitivity == 4 ? 1.1 : 1.2
//OI burst up scenarios
oiBurstUp = relativeOi > relativeOi[1] * oiXtremeGain and relativeOi > oiXtremePos
oiBurstDown = relativeOi < relativeOi[1] * oiXtremeGain and relativeOi < 0 - oiXtremePos
// Plots
//Inflow/outflow colors. Gradient by default, static if selected
bullInflowCol = i_staticColor ? i_buyInflowCol : color.from_gradient(relativeOi, 0, 1, color.new(i_buyInflowCol, 70), color.new(i_buyInflowCol, 1))
bullOutflowCol = i_staticColor ? i_buyOutflowCol : color.from_gradient(math.abs(relativeOi), 0, 1, color.new(i_buyOutflowCol, 70), color.new(i_buyOutflowCol, 1))
bearInflowCol = i_staticColor ? i_sellInflowCol : color.from_gradient(math.abs(relativeOi), 0, 1, color.new(i_sellInflowCol, 70), color.new(i_sellInflowCol, 1))
bearOutflowCol = i_staticColor ? i_sellOutflowCol : color.from_gradient(math.abs(relativeOi), 0, 1, color.new(i_sellOutflowCol, 70), color.new(i_sellOutflowCol, 1))
//Choose appropriate color corresponding to a OI/price scenario
oiFlowCol = relativePrice > 0 and relativeOi < 0 ? bearOutflowCol : relativePrice > 0 and relativeOi > 0 ? bullInflowCol :
relativePrice < 0 and relativeOi < 0 ? bullOutflowCol : bearInflowCol //relativePrice < 0 and relativeOi > 0 ? : color.white
//Plot extremes
pUpper1 = plot(1, "+1", color=color.new(color.gray, 100), display=display.data_window)
pLower1 = plot(-1, "-1", color=color.new(color.gray, 100), display=display.data_window)
pUpper2 = plot(2, "+2", color=color.new(color.gray, 100), display=display.data_window)
pLower2 = plot(-2, "-2", color=color.new(color.gray, 100), display=display.data_window)
pUpper3 = plot(3, "+3", color=color.new(color.gray, 100), display=display.data_window)
pLower3 = plot(-3, "-3", color=color.new(color.gray, 100), display=display.data_window)
//Fill extremes
fill(pUpper1, pUpper2, title = "+1 to +2 fill", color=i_upperLine)
fill(pLower1, pLower2, title = "-1 to -2 fill", color=i_lowerLine)
fill(pUpper2, pUpper3, title = "+2 to +3 fill", color=i_upperLine2)
fill(pLower2, pLower3, title = "-3 to -3 fill", color=i_lowerLine2)
//OI burst color
oiBurstCol = oiFlowCol == bearOutflowCol ? i_sellOutflowColExt : oiFlowCol == bearInflowCol ? i_sellInflowColExt :
oiFlowCol == bullInflowCol ? i_buyInflowColExt : i_buyOutflowColExt
//Plot shapes for OI bursts
plotshape(oiBurstUp ? relativeOi : na, style=shape.circle, text="", color=oiBurstCol, location=location.absolute, size=size.tiny)
plotshape(oiBurstDown ? relativeOi : na, style=shape.circle, text="", color=oiBurstCol, location=location.absolute, size=size.tiny)
//Candle color for either all flow states or only during extremes
barcolor(i_candleColor == "Flows" ? oiFlowCol : i_candleColor == "Extremes" and (oiBurstUp or oiBurstDown) ? oiFlowCol : na)
//Plot relative OI and relative price if enabled
plot(relativeOi, "Relative OI", color=oiFlowCol, style=plot.style_columns)
plot(i_showPriceLine ? relativePrice : na, "Relative price", color=color.white)
// Alerts
//Conditions for abnormal flows
abnormalBuyInflow = relativeOi > 1 and oiFlowCol == bullInflowCol
abnormalSellInflow = relativeOi > 1 and oiFlowCol == bearInflowCol
abnormalBuyOutflow = relativeOi < -1 and oiFlowCol == bullOutflowCol
abnormalSellOutflow = relativeOi < -1 and oiFlowCol == bearOutflowCol
//Conditions for bursts
abnormalBuyBurstUp = oiBurstUp and oiBurstCol == i_buyInflowColExt
abnormalSellBurstUp = oiBurstUp and oiBurstCol == i_sellInflowColExt
abnormalBuyBurstDown = oiBurstDown and oiBurstCol == i_buyOutflowColExt
abnormalSellBurstDown = oiBurstDown and oiBurstCol == i_sellOutflowColExt
//Grouped conditions
anyAbnormalInflows = abnormalBuyInflow or abnormalSellInflow
anyAbnormalOutflows = abnormalBuyOutflow or abnormalSellOutflow
anyAbnormalBurstUp = abnormalBuyBurstUp or abnormalSellBurstUp
anyAbnormalBurstDown = abnormalBuyBurstDown or abnormalSellBurstDown
//Alert conditions
alertcondition(abnormalBuyInflow and barstate.isconfirmed, "Abnormal long inflows", "Abnormal long inflows detected.")
alertcondition(abnormalSellInflow and barstate.isconfirmed, "Abnormal short inflows", "Abnormal short inflows detected.")
alertcondition(abnormalBuyOutflow and barstate.isconfirmed, "Abnormal long outflows", "Abnormal long outflows detected.")
alertcondition(abnormalSellOutflow and barstate.isconfirmed, "Abnormal short outflows", "Abnormal short outflows detected.")
alertcondition(abnormalBuyBurstUp and barstate.isconfirmed, "Aggressive longs", "Aggressive long inflows detected.")
alertcondition(abnormalSellBurstUp and barstate.isconfirmed, "Aggressive shorts", "Aggressive short inflows detected.")
alertcondition(abnormalBuyBurstDown and barstate.isconfirmed, "Liquidated longs", "Liquidated long outflows detected.")
alertcondition(abnormalSellBurstDown and barstate.isconfirmed, "Liquidated shorts", "Liquidated short outflows detected.")
alertcondition(anyAbnormalInflows and barstate.isconfirmed, "Abnormal long/short inflows", "Abnormal long/short inflows detected.")
alertcondition(anyAbnormalOutflows and barstate.isconfirmed, "Abnormal long/short outflows", "Abnormal long/short outflows detected.")
alertcondition(anyAbnormalBurstUp and barstate.isconfirmed, "Aggressive longs/shorts", "Aggressive long/short inflows detected.")
alertcondition(anyAbnormalBurstDown and barstate.isconfirmed, "Liquidated longs/shorts", "Liquidated long/short outflows detected.")
// Table
//Initializing table
var flowTable = table.new(position = position.top_right, columns = 50, rows = 50, bgcolor = color.new(color.black, 100), border_width = 3, border_color=color.new(color.white, 100))
//Populate flow guidelines if user has enabled setting
if i_flowInfoBool
table.cell(table_id = flowTable, column = 0, row = 0, text = "● Buy OI inflow", text_color=i_buyInflowCol, text_halign = text.align_left, text_size=size.small)
table.cell(table_id = flowTable, column = 1, row = 0, text = "● Buy OI outflow", text_color=i_buyOutflowCol, text_halign = text.align_left, text_size=size.small)
table.cell(table_id = flowTable, column = 2, row = 0, text = "● Sell OI inflow", text_color=i_sellInflowCol, text_halign = text.align_left, text_size=size.small)
table.cell(table_id = flowTable, column = 3, row = 0, text = "● Sell OI outflow", text_color=i_sellOutflowCol, text_halign = text.align_left, text_size=size.small)
//Populate OI source
table.cell(table_id = flowTable, column = 4, row = 0, text = "OI: " + str.tostring(reqOiSymbol), text_color=color.gray, text_halign = text.align_left, text_size=size.small)
|
Plot background depending on Index EMA 10 and EMA 20 | https://www.tradingview.com/script/vIIOvCL8-Plot-background-depending-on-Index-EMA-10-and-EMA-20/ | MrMoneyMaker81 | https://www.tradingview.com/u/MrMoneyMaker81/ | 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/
// © MrMoneyMaker81
//@version=5
indicator(title="Index MA", overlay=true)
//Get the prefix of the stock.
stock_prefix = syminfo.prefix
//Check which index should be used for the indicator. Uncheck below line if you need to debug. If no match is found indicator will use IXIC as reference.
//label.new(bar_index, high, syminfo.prefix) //For debug to get the prifix of the ticker, add en else if with "prefix" below.
index_ticker = if(stock_prefix == "OMXSTO")
"OMXSPI"
else if(stock_prefix == "OSL_DLY")
"OBX"
else if(stock_prefix == "NGM")
"OMXSPI"
else if(stock_prefix == "OMXHEX")
"OMXHPI"
else if(stock_prefix == "OMXCOP")
"OMXCPI"
else
"IXIC"
//Calculated the EMA10 and EMA20 for the index.
index = request.security(index_ticker, timeframe.period, close)
indexSMA10=ta.ema(index, 10)
indexSMA10_old=indexSMA10[1]
indexSMA20=ta.ema(index, 20)
indexSMA20_old=indexSMA20[1]
//Plot Index EMA10 and EMA20 but it's transparent as defalut.
plot(indexSMA10, color=color.new(color.white,100), title = "IndexSMA10")
plot(indexSMA20, color=color.new(color.white,100), title = "IndexSMA20")
//Plot the different backgrounds. Description is in the title of each plot.
bgcolor((indexSMA10 < indexSMA10_old and indexSMA20 < indexSMA20_old and indexSMA10 < indexSMA20) and timeframe.period =='D' ? color.new(color.red,50) : na, title = "MA10 < MA20 & MA10/MA20 down")
bgcolor((indexSMA10 > indexSMA10_old and indexSMA20 > indexSMA20_old and indexSMA10 > indexSMA20) and timeframe.period =='D' ? color.new(color.green,50) : na, title = "MA10 > MA20 & MA10/MA20 up")
bgcolor((indexSMA10 < indexSMA10_old and indexSMA20 < indexSMA20_old and indexSMA10 > indexSMA20) and timeframe.period =='D' ? color.new(color.orange,70) : na, title = "MA10 > MA20 & MA10/MA20 down")
bgcolor((indexSMA10 > indexSMA10_old and indexSMA20 > indexSMA20_old and indexSMA10 < indexSMA20) and timeframe.period =='D' ? color.new(color.green,70) : na, title = "MA10 < MA20 & MA10/MA20 up")
bgcolor((indexSMA10 < indexSMA10_old and indexSMA20 > indexSMA20_old and indexSMA10 > indexSMA20) and timeframe.period =='D' ? color.new(color.orange,50) : na, title = "MA10 > MA20 & MA10 down MA20 up")
bgcolor((indexSMA10 > indexSMA10_old and indexSMA20 < indexSMA20_old and indexSMA10 < indexSMA20) and timeframe.period =='D' ? color.new(#00ff0a,50) : na, title = "MA10 < MA20 & MA10 up MA20 down") |
FalconRed 5 EMA Indicator (Powerofstocks) | https://www.tradingview.com/script/Izq4mHhD-FalconRed-5-EMA-Indicator-Powerofstocks/ | falcon_red | https://www.tradingview.com/u/falcon_red/ | 127 | 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/
// © falcon_red
//@version=5
indicator("FR_POS_5EMA_Indicator_V2", overlay=true)
shortRR=input.float(3, minval=1, title="Sell Risk:Reward Ratio")
buyRR=input.float(2, minval=1, title="Buy Risk:Reward Ratio")
showBUY=input(false, "Show Buy")
showSELL=input(true, "Show Sell")
draw_line(y,col,sty)=>line.new(x1=time-(10*60*1000),y1=y,x2=time+(60*60*1000),y2=y, color=col,xloc= xloc.bar_time, style=sty)
draw_label(y)=>
display_text =str.format(" ({0})", math.round_to_mintick(y))
label.new(x = time+(60*60*1000), y=y, text=display_text, textcolor=color.new(color.white,50), color=#00000000, xloc=xloc.bar_time)
ema15 = ta.ema(close, 15 )
ema5 = ta.ema(close, 5 )
sl= 0.0
tar = 0.0
type AlertCandle
float o
float h
float l
float c
float v
var alertSellCandle = AlertCandle.new()
var alertBuyCandle = AlertCandle.new()
plot(ema5, color=color.green, title="5 EMA", linewidth=2)
plot(ema15, color=color.rgb(11, 74, 13), title="15 EMA", linewidth=2)
if low > ema5 or (not na(alertSellCandle) and alertSellCandle.l < low)
alertSellCandle := AlertCandle.new(o=open, h=high, l=low, c=close, v=volume)
if high < ema15 or (not na(alertBuyCandle) and alertBuyCandle.h > high)
alertBuyCandle := AlertCandle.new(o=open, h=high, l=low, c=close, v=volume)
plotshape(showSELL and low<alertSellCandle.l and not(barstate.isfirst), title="Sell Label", text="SELL",color=color.new(#ff000d, 0), location=location.abovebar, style=shape.labeldown, size=size.tiny, textcolor=color.white)
if showSELL and low<alertSellCandle.l and not(barstate.isfirst)
sl := high>alertSellCandle.h?high:alertSellCandle.h
tar := alertSellCandle.l-(shortRR*(sl-alertSellCandle.l))
draw_line(sl,color.red,line.style_solid)
draw_label(sl)
draw_line(tar,color.green,line.style_solid)
draw_label(tar)
draw_line(alertSellCandle.l,color.rgb(0, 82, 246),line.style_solid)
alertSellCandle := AlertCandle.new()
plotshape(showBUY and high>alertBuyCandle.h and not(barstate.isfirst), title="Buy Label", text="BUY",color=color.new(#2fec55, 0), location=location.belowbar, style=shape.labelup, size=size.tiny, textcolor=color.white)
if showBUY and high>alertBuyCandle.h and not(barstate.isfirst)
sl := low<alertBuyCandle.l?low:alertBuyCandle.l
tar := alertBuyCandle.h+(buyRR*(alertBuyCandle.h-sl))
draw_line(sl,color.red,line.style_solid)
draw_label(sl)
draw_line(tar,color.green,line.style_solid)
draw_label(tar)
draw_line(alertBuyCandle.h,color.rgb(0, 82, 246),line.style_solid)
alertBuyCandle := AlertCandle.new()
|
ICT TGIF_V2 [MK] | https://www.tradingview.com/script/fTeOEdm9-ICT-TGIF-V2-MK/ | malk1903 | https://www.tradingview.com/u/malk1903/ | 242 | 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
//malk1903
//-------------------------------------------------------------------------------------------
indicator(title='ICT TGIF_V2 [MK]', shorttitle='ICT TGIF_V2 [MK]', overlay=true, precision=8, max_boxes_count = 500, max_lines_count = 500)
tZone = input.string("GMT-4", "Timezone", options=["GMT+0", "GMT+1", "GMT+2", "GMT+3","GMT+4","GMT+5","GMT+6","GMT+7","GMT+8","GMT+9","GMT+10","GMT+11","GMT+12","GMT-1", "GMT-2", "GMT-3","GMT-4","GMT-5","GMT-6","GMT-7","GMT-8","GMT-9","GMT-10","GMT-11","GMT-12"], inline="0", group="TGIF-------------------------------------------------------")
i_maxtf_tgif = input.int (60, "Max Timeframe", 1, 240, inline="0", group="TGIF-------------------------------------------------------")
HL_clr = input.color(color.new(color.red, 0), title="Week High/Low Line", group="TGIF Levels-------------------------------------------------------", inline = "1")
wkHL = input(true, title='', group="TGIF Levels-------------------------------------------------------", inline = "1")
HLStyle = input.string ("Solid", "", options=["Solid", "Dotted", "Dashed"], group="TGIF Levels-------------------------------------------------------", inline = "1")
colorlevels = input.color(color.new(color.aqua, 100), title="20-30% Border", group="TGIF Levels-------------------------------------------------------", inline = "2")
fillcolor = input.color(color.new(color.aqua, 30), title="Box", group="TGIF Levels-------------------------------------------------------", inline = "2")
lineWidth = input(title='Width', defval=1, group="TGIF Levels-------------------------------------------------------", inline = "2")
txt_col = input.color(title='Text', defval=color.new(color.silver,50), group="TGIF Levels-------------------------------------------------------", inline = "3")
txt_tgif = input.bool(title='', defval=true, group="TGIF Levels-------------------------------------------------------", inline = "3")
wkOPN_clr = input.color(color.new(color.white, 0), title="Week Open Line", group="TGIF Levels-------------------------------------------------------", inline = "4")
wkOPN = input.bool(title='', defval=true, group="TGIF Levels-------------------------------------------------------", inline = "4")
WkStyle = input.string ("Dashed", "", options=["Solid", "Dotted", "Dashed"], group="TGIF Levels-------------------------------------------------------", inline = "4")
linewidths = input.int(defval=1, title="Line Widths", group="TGIF Levels-------------------------------------------------------", inline = "6")
//linestyles
_WkStyle = WkStyle == "Solid" ? line.style_solid : WkStyle == "Dotted" ? line.style_dotted : line.style_dashed
_HLStyle = HLStyle == "Solid" ? line.style_solid : HLStyle == "Dotted" ? line.style_dotted : line.style_dashed
//var
pc_20 = 0.0
pc_30 = 0.0
pc_70 = 0.0
pc_80 = 0.0
Fri_PM = input.session(defval="0830-1600", title="Friday hours to show 20-30% levels")//input.session(title='Display Period', defval='1300-1600:6', inline="2", group="Friday Only-------------------------------------------------------", tooltip="20-30% box will only be shown during this session period, default is to only show during friday PM session")
Wk_sess = '1800-1700'
//Friday New Bar
is_newbar(sess) =>
t = time('D', sess, tZone)
na(t[1]) and not na(t) or t[1] < t
//Weekly New Bar
is_newbar2(sess) =>
t = time('W', sess, tZone)
na(t[1]) and not na(t) or t[1] < t
is_session(sess) =>
not na(time('D', sess, tZone))
is_session2(sess) =>
not na(time('W', sess, tZone))
//Friday PM Only
Fri_Newbar = is_newbar(Fri_PM)
Fri_Session = is_session(Fri_PM)
//New Week
WeekNewbar = is_newbar2(Wk_sess)
WeekSession = is_session2(Wk_sess)
///max tf
disp_tgif = timeframe.isintraday and timeframe.multiplier <= i_maxtf_tgif
///////new weekbox high low and level boxes
if WeekSession and disp_tgif
float WkLow = na
WkLow := if WeekSession
if WeekNewbar
low
else
math.min(WkLow[1], low)
else
WkLow[1]
float WkHigh = na
WkHigh := if WeekSession
if WeekNewbar
high
else
math.max(WkHigh[1], high)
else
WkHigh[1]
///////////////////////////////////////////
float WkOpen = na
WkOpen := if WeekSession
if WeekNewbar
open
else
WkOpen[1]
/////////////////////////////////////////
int WkStart = na
WkStart := if WeekSession
if WeekNewbar
time
else
math.min(WkStart[1], time)
else
na
int WkEnd = na
WkEnd := if WeekSession
if WeekNewbar
time_close
else
math.max(WkEnd[1], time_close)
else
na
pc_20 := (WkHigh - WkLow) * 0.8 + WkLow
pc_30 := (WkHigh - WkLow) * 0.7 + WkLow
pc_80 := (WkHigh - WkLow) * 0.2 + WkLow
pc_70 := (WkHigh - WkLow) * 0.3 + WkLow
weeklyhigh = if WeekNewbar
weeklyhigh = wkHL ? line.new(WkStart, WkHigh, WkEnd, WkHigh, xloc = xloc.bar_time, style = _HLStyle, width = linewidths, color = HL_clr) : na
weeklyopen = if WeekNewbar
weeklyopen = wkOPN ? line.new(WkStart, WkOpen, WkEnd, WkOpen, xloc = xloc.bar_time, style = _WkStyle, width = linewidths, color = wkOPN_clr) : na
weeklylow = if WeekNewbar
weeklylow = wkHL ? line.new(WkStart, WkLow, WkEnd, WkLow, xloc = xloc.bar_time, style = _HLStyle, width = linewidths, color = HL_clr) : na
twenty30Box = if WeekNewbar
twenty30Box = box.new(WkStart, pc_20, WkEnd, pc_30, xloc = xloc.bar_time, bgcolor = color.new(color.black,100), border_width = lineWidth, border_color = color.new(color.black,100), text = txt_tgif ? "TGIF" : na, text_halign = text.align_right, text_size=size.normal, text_color = color.new(color.black,100))
eighty70Box = if WeekNewbar
eighty70Box = box.new(WkStart, pc_70, WkEnd, pc_80, xloc = xloc.bar_time, bgcolor = color.new(color.black,100), border_width = lineWidth, border_color = color.new(color.black,100), text = txt_tgif ? "TGIF" : na, text_halign = text.align_right, text_size=size.normal, text_color = color.new(color.black,100))
if not WeekNewbar
line.set_x2(weeklyopen[1], WkEnd)
line.set_y1(weeklyopen[1], WkOpen)
line.set_y2(weeklyopen[1], WkOpen)
line.set_x2(weeklylow[1], WkEnd)
line.set_y1(weeklylow[1], WkLow)
line.set_y2(weeklylow[1], WkLow)
line.set_x2(weeklyhigh[1], WkEnd)
line.set_y1(weeklyhigh[1], WkHigh)
line.set_y2(weeklyhigh[1], WkHigh)
box.set_right(twenty30Box[1], WkEnd)
box.set_top(twenty30Box[1], pc_20)
box.set_bottom(twenty30Box[1], pc_30)
box.set_right(eighty70Box[1], WkEnd)
box.set_top(eighty70Box[1], pc_70)
box.set_bottom(eighty70Box[1], pc_80)
//has the friday PM session started, is so set 20-30% boxes left to session start time
if Fri_Session and disp_tgif
int Fri_Start = na
Fri_Start := if Fri_Session
if Fri_Newbar
time
else
math.min(Fri_Start[1], time)
else
na
if not Fri_Newbar
box.set_left(twenty30Box[1], Fri_Start)
box.set_left(eighty70Box[1], Fri_Start)
is_new_week = timeframe.change("W")
var weekly_high_price = high
var weekly_low_price = low
var weekly_high_time = time
var weekly_low_time = time
//var label weekly_high_label = label.new(na, na, "Weekly\nHigh", xloc=xloc.bar_time, yloc=yloc.abovebar, color=color.green, textcolor=color.white) //used for testing week level
//var label weekly_low_label = label.new(na, na, "Weekly\nLow", xloc=xloc.bar_time, yloc=yloc.belowbar, color=color.red, textcolor=color.white, style=label.style_label_up) //used for testing
timeAllowed = Fri_PM//friday high/low must be within these hours
isWithinTime = time(timeframe.period, timeAllowed + ":6", tZone)
if (is_new_week) //finds high of week
weekly_high_price := high
weekly_low_price := low
weekly_high_time := time
weekly_low_time := time
else
if (high > weekly_high_price) //updates high of week if breaks higher
weekly_high_price := high
weekly_high_time := time
if (low < weekly_low_price)
weekly_low_price := low
weekly_low_time := time
//detects if high of week was on a friday, and is so, sets the 20-30% level to visible
fri_up = false
if dayofweek(weekly_high_time, tZone) == 6
fri_up := true
if isWithinTime and fri_up//= time(timeframe.period, timeAllowed + ":1234567")///current bar within time..not weekly_high_time
box.set_text_color(twenty30Box, txt_col)
box.set_bgcolor(twenty30Box, fillcolor)
box.set_border_color(twenty30Box, colorlevels)
//detects if low of week was on a friday, and is so, sets the 70-80% level to visible
fri_dn = false
if dayofweek(weekly_low_time, tZone) == 6
fri_dn := true
if isWithinTime and fri_dn//= time(timeframe.period, timeAllowed + ":1234567")///current bar within time..not weekly_high_time
box.set_text_color(eighty70Box, txt_col)
box.set_bgcolor(eighty70Box, fillcolor)
box.set_border_color(eighty70Box, colorlevels)
|
TimeLy Moving Average - TMA | https://www.tradingview.com/script/eKFGImOU/ | only_fibonacci | https://www.tradingview.com/u/only_fibonacci/ | 281 | 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/
// © only_fibonacci
//@version=5
indicator(title = "TimeLy Moving Average", shorttitle = "TMA", overlay= true, max_bars_back = 5000)
temporal = input.string(defval = "Daily", title = "Time", options = ["Hourly","Daily","Weekly","Monthly"])
movingAverageType = input.string(defval = "SMA", title = "MA Type", options = ["SMA","WMA"])
source = input.source(defval = close, title = "Source")
tempo = switch temporal
"Hourly" => timeframe.isintraday and timeframe.multiplier <= 60 ? hour : na
"Daily" => timeframe.isminutes or (timeframe.isseconds and timeframe.multiplier >= 6) ? dayofmonth : na
"Weekly" => timeframe.isminutes or timeframe.isdaily ? weekofyear : na
"Monthly"=> (timeframe.isminutes and timeframe.multiplier >= 10) or timeframe.isdaily ? month : na
timeLy1 = ta.valuewhen(tempo != tempo[1] ,bar_index,0)
timeLy2 = ta.valuewhen(tempo != tempo[1] ,bar_index,1)
period = bar_index - timeLy1 > 0 ? bar_index - timeLy1 : 1
ma = switch movingAverageType
"SMA" => ta.sma(source,period)
"WMA" => ta.wma(source,period)
plot(not na(ma) and not timeframe.isweekly and not timeframe.ismonthly ? ma : na, title = "TMA", color = color.black)
if bar_index == timeLy1
label.new(timeLy1 - 1,ma[1],text = temporal + " Average\n" + str.tostring(math.round_to_mintick(ma[1])),color = color.gray, textcolor = color.white, style = label.style_label_lower_left)
var lastLabel = label.new(last_bar_index,close)
if bar_index == last_bar_index and not timeframe.isweekly and not timeframe.ismonthly
lastLabel := label.new(last_bar_index,ma,text = temporal + " Average\n" + str.tostring(math.round_to_mintick(ma)),color = color.gray, textcolor = color.white, style = label.style_label_lower_left)
label.delete(lastLabel[1])
|
Bitcoin Limited Growth Model | https://www.tradingview.com/script/94QSUrau-Bitcoin-Limited-Growth-Model/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 179 | 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/
// © QuantiLuxe
//@version=5
indicator("Bitcoin Limited Growth Model", "{Ʌ} - LGS-S2F", true)
var a_step = 0.17, var b_step = 0.02, var c_step = 22.7
a = input.float(24.16, "Coefficient A", step = a_step)
b = input.float(0.397, "Coefficient B", step = b_step)
c = input.float(81.0, "Coefficient C", step = c_step)
stdev_len = input.int(200, "Stdev Length")
calc_mode = input.string("Normal", "Sigma Calculation Method", ["Normal", "Stdev"])
stock = request.security("GLASSNODE:BTC_SUPPLY", "D", close)
blocks = request.security("GLASSNODE:BTC_BLOCKS", "D", close)
f_stdev(src_,len) =>
length = len
pi = length / 1000
src = src_ * float(1 + pi)
mult = 3
basis = ta.vwma(src, length)
dev = mult * ta.stdev(src, length)
basis - (0.236 * dev)
f_lg(a, b, c) =>
1 / stock * ((c * math.pow(10, 12)) * math.exp((a * math.pow(3.64568 * math.pow(10, 6), b)) * (-math.pow(2, -4.7619 * math.pow(10, -6) * b * blocks) * math.pow(stock, -b))))
base = f_lg(a, b, c)
lh = f_lg(a + a_step, b + b_step, c + c_step)
hh = f_lg(a + a_step, b + 2 * b_step, c + c_step)
llh = f_lg(a, b, c + c_step)
hhl = f_lg(a, b, c - c_step)
hl = f_lg(a - a_step, b - b_step, c - c_step)
ll = f_lg(a - a_step, b - 2 * b_step, c - c_step)
switch calc_mode
"Stdev" =>
lh := f_stdev(lh, stdev_len)
hh := f_stdev(hh, stdev_len)
llh := f_stdev(llh, stdev_len)
hhl := f_stdev(hhl, stdev_len)
hl := f_stdev(hl, stdev_len)
ll := f_stdev(ll, stdev_len)
p_b = plot(base, "", #ffffff80)
p_lh = plot(lh, "", #bb001081)
p_hh = plot(hh, "", #bb001081)
p_llh = plot(llh, "", #bb001081)
p_hhl = plot(hhl, "", #00b35169)
p_hl = plot(hl, "", #00b35169)
p_ll = plot(ll, "", #00b35169)
fill(p_ll, p_hl, #40ff4027)
fill(p_hl, p_hhl, #80ff8042)
fill(p_hhl, p_b, #c0ffc02f)
fill(p_b, p_llh, #ffc0c031)
fill(p_llh, p_lh, #ff5f5f3d)
fill(p_lh, p_hh, #ff40402d)
|
Flat Tops & Botttoms | https://www.tradingview.com/script/p8bEfFLX-Flat-Tops-Botttoms/ | aryanarora33 | https://www.tradingview.com/u/aryanarora33/ | 23 | 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/
// © aryanarora33
//@version=5
indicator("AR#C1 Flat Tops & Botttoms", shorttitle = "AR#C1 FT&B", overlay = true, max_bars_back = 500, max_labels_count = 500, max_lines_count = 500)
showFlatTops = input.bool(true, 'Show Flat Tops', group = 'Inputs')
showFlatBottoms = input.bool(true, 'Show Flat Bottoms', group = 'Inputs')
enableAlerts = input(true, title="Enable Alerts", group = 'Inputs')
flat_top = (high == open and showFlatTops) ? true : false
flat_bottom = (low == open and showFlatBottoms) ? true : false
label_below_bar = low - (ta.atr(10) * 0.6)
label_above_bar = high + (ta.atr(10) * 0.6)
plotshape(flat_top, text = '.', style=shape.triangledown, location=location.abovebar, color=color.new(color.orange, 0), textcolor=color.new(color.black, 0), size=size.tiny)
plotshape(flat_bottom, text = '.', style=shape.triangleup, location=location.belowbar, color=color.new(color.orange, 0), textcolor=color.new(color.black, 0), size=size.tiny)
alertcondition(flat_top and enableAlerts, "Flat Top Detected", "Flat Top")
alertcondition(flat_bottom and enableAlerts, "Flat Bottom Detected", "Flat Bottom") |
Divergence Screener [Mr_Zed] | https://www.tradingview.com/script/HT7u5Rbj-Divergence-Screener-Mr-Zed/ | Indicator_Wizard | https://www.tradingview.com/u/Indicator_Wizard/ | 48 | 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/
// © MR_zed
//@version=5
indicator(title="Divergence Screener [Mr_Zed]", overlay = true,format=format.price)
indiSet = input(false, "═════════ DS Settings ════════")
len = input.int(title="RSI Period", minval=1, defval=14)
src = input(title="RSI Source", defval=close)
lbR = input(title="Pivot Lookback Right", defval=5)
lbL = input(title="Pivot Lookback Left", defval=5)
rangeUpper = input(title="Max of Lookback Range", defval=60)
rangeLower = input(title="Min of Lookback Range", defval=5)
screenList = input(false, "═════════ Screener ════════")
asset_01 = input.symbol("",title="Asset 01",inline = "asset_01")
asset_01_tf = input.timeframe('',title="TimeFrame",inline = "asset_01")
asset_02 = input.symbol("",title="Asset 02",inline = "asset_02")
asset_02_tf = input.timeframe('',title="TimeFrame",inline = "asset_02")
asset_03 = input.symbol("",title="Asset 03",inline = "asset_03")
asset_03_tf = input.timeframe('',title="TimeFrame",inline = "asset_03")
asset_04 = input.symbol("",title="Asset 04",inline = "asset_04")
asset_04_tf = input.timeframe('',title="TimeFrame",inline = "asset_04")
asset_05 = input.symbol("",title="Asset 05",inline = "asset_05")
asset_05_tf = input.timeframe('',title="TimeFrame",inline = "asset_05")
asset_06 = input.symbol("",title="Asset 06",inline = "asset_06")
asset_06_tf = input.timeframe('',title="TimeFrame",inline = "asset_06")
asset_07 = input.symbol("",title="Asset 07",inline = "asset_07")
asset_07_tf = input.timeframe('',title="TimeFrame",inline = "asset_07")
asset_08 = input.symbol("",title="Asset 08",inline = "asset_08")
asset_08_tf = input.timeframe('',title="TimeFrame",inline = "asset_08")
asset_09 = input.symbol("",title="Asset 09",inline = "asset_09")
asset_09_tf = input.timeframe('',title="TimeFrame",inline = "asset_09")
asset_10 = input.symbol("",title="Asset 10",inline = "asset_10")
asset_10_tf = input.timeframe('',title="TimeFrame",inline = "asset_10")
asset_11 = input.symbol("",title="Asset 11",inline = "asset_11")
asset_11_tf = input.timeframe('',title="TimeFrame",inline = "asset_11")
asset_12 = input.symbol("",title="Asset 12",inline = "asset_12")
asset_12_tf = input.timeframe('',title="TimeFrame",inline = "asset_12")
asset_13 = input.symbol("",title="Asset 13",inline = "asset_13")
asset_13_tf = input.timeframe('',title="TimeFrame",inline = "asset_13")
asset_14 = input.symbol("",title="Asset 14",inline = "asset_14")
asset_14_tf = input.timeframe('',title="TimeFrame",inline = "asset_14")
asset_15 = input.symbol("",title="Asset 15",inline = "asset_15")
asset_15_tf = input.timeframe('',title="TimeFrame",inline = "asset_15")
asset_16 = input.symbol("",title="Asset 16",inline = "asset_16")
asset_16_tf = input.timeframe('',title="TimeFrame",inline = "asset_16")
asset_17 = input.symbol("",title="Asset 17",inline = "asset_17")
asset_17_tf = input.timeframe('',title="TimeFrame",inline = "asset_17")
asset_18 = input.symbol("",title="Asset 18",inline = "asset_18")
asset_18_tf = input.timeframe('',title="TimeFrame",inline = "asset_18")
asset_19 = input.symbol("",title="Asset 19",inline = "asset_19")
asset_19_tf = input.timeframe('',title="TimeFrame",inline = "asset_19")
asset_20 = input.symbol("",title="Asset 20",inline = "asset_20")
asset_20_tf = input.timeframe('',title="TimeFrame",inline = "asset_20")
asset_21 = input.symbol("",title="Asset 21",inline = "asset_21")
asset_21_tf = input.timeframe('',title="TimeFrame",inline = "asset_21")
asset_22 = input.symbol("",title="Asset 22",inline = "asset_22")
asset_22_tf = input.timeframe('',title="TimeFrame",inline = "asset_22")
asset_23 = input.symbol("",title="Asset 23",inline = "asset_23")
asset_23_tf = input.timeframe('',title="TimeFrame",inline = "asset_23")
asset_24 = input.symbol("",title="Asset 24",inline = "asset_24")
asset_24_tf = input.timeframe('',title="TimeFrame",inline = "asset_24")
asset_25 = input.symbol("",title="Asset 25",inline = "asset_25")
asset_25_tf = input.timeframe('',title="TimeFrame",inline = "asset_25")
asset_26 = input.symbol("",title="Asset 26",inline = "asset_26")
asset_26_tf = input.timeframe('',title="TimeFrame",inline = "asset_26")
asset_27 = input.symbol("",title="Asset 27",inline = "asset_27")
asset_27_tf = input.timeframe('',title="TimeFrame",inline = "asset_27")
asset_28 = input.symbol("",title="Asset 28",inline = "asset_28")
asset_28_tf = input.timeframe('',title="TimeFrame",inline = "asset_28")
asset_29 = input.symbol("",title="Asset 29",inline = "asset_29")
asset_29_tf = input.timeframe('',title="TimeFrame",inline = "asset_29")
asset_30 = input.symbol("",title="Asset 30",inline = "asset_30")
asset_30_tf = input.timeframe('',title="TimeFrame",inline = "asset_30")
asset_31 = input.symbol("",title="Asset 31",inline = "asset_31")
asset_31_tf = input.timeframe('',title="TimeFrame",inline = "asset_31")
asset_32 = input.symbol("",title="Asset 32",inline = "asset_32")
asset_32_tf = input.timeframe('',title="TimeFrame",inline = "asset_32")
asset_33 = input.symbol("",title="Asset 33",inline = "asset_33")
asset_33_tf = input.timeframe('',title="TimeFrame",inline = "asset_33")
asset_34 = input.symbol("",title="Asset 34",inline = "asset_34")
asset_34_tf = input.timeframe('',title="TimeFrame",inline = "asset_34")
asset_35 = input.symbol("",title="Asset 35",inline = "asset_35")
asset_35_tf = input.timeframe('',title="TimeFrame",inline = "asset_35")
asset_36 = input.symbol("",title="Asset 36",inline = "asset_36")
asset_36_tf = input.timeframe('',title="TimeFrame",inline = "asset_36")
asset_37 = input.symbol("",title="Asset 37",inline = "asset_37")
asset_37_tf = input.timeframe('',title="TimeFrame",inline = "asset_37")
asset_38 = input.symbol("",title="Asset 38",inline = "asset_38")
asset_38_tf = input.timeframe('',title="TimeFrame",inline = "asset_38")
asset_39 = input.symbol("",title="Asset 39",inline = "asset_39")
asset_39_tf = input.timeframe('',title="TimeFrame",inline = "asset_39")
asset_40 = input.symbol("",title="Asset 40",inline = "asset_40")
asset_40_tf = input.timeframe('',title="TimeFrame",inline = "asset_40")
DivergenceIndicator() =>
osc = ta.rsi(src, len)
plFound = na(ta.pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(osc, lbL, lbR)) ? false : true
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
bars = ta.barssince(plFound[1] == true)
isInRange = rangeLower <= bars and bars <= rangeUpper
oscHL = osc[lbR] > ta.valuewhen(plFound, osc[lbR], 1) and isInRange//_inRange(plFound[1])
priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bullCond = priceLL and oscHL and plFound //and barstate.isconfirmed
//-------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High
bars_2 = ta.barssince(phFound[1] == true)
isInRange_2 = rangeLower <= bars_2 and bars_2 <= rangeUpper
oscLH = osc[lbR] < ta.valuewhen(phFound, osc[lbR], 1) and isInRange_2
priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
bearCond = priceHH and oscLH and phFound //and barstate.isconfirmed
status = 0
if bullCond and barstate.isconfirmed
status := 2
else if bearCond and barstate.isconfirmed
status := 4
else if bullCond
status := 1
else if bearCond
status := 3
status
//************************************************************************************************************
// Screener Logic
//************************************************************************************************************
checkStatus(value,ticker,tf) =>
if value == 2
alert("Bullish Divergence\n on " + ticker + "\n Timeframe: "+tf,alert.freq_once_per_bar)
else if value == 4
alert("Bearish Divergence\n on " + ticker + "\n Timeframe: "+tf,alert.freq_once_per_bar)
0
asset_01_status = asset_01 == '' ? 0 : request.security(asset_01, asset_01_tf, DivergenceIndicator(),gaps = barmerge.gaps_off,lookahead=barmerge.lookahead_on)
xx = asset_01 == '' ? 0 : checkStatus(asset_01_status,asset_01,asset_01_tf)
asset_02_status = asset_02 == '' ? 0 : request.security(asset_02, asset_02_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_02 == '' ? 0 : checkStatus(asset_02_status, asset_02, asset_02_tf)
asset_03_status = asset_03 == '' ? 0 : request.security(asset_03, asset_03_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_03 == '' ? 0 : checkStatus(asset_03_status, asset_03, asset_03_tf)
asset_04_status = asset_04 == '' ? 0 : request.security(asset_04, asset_04_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_04 == '' ? 0 : checkStatus(asset_04_status, asset_04, asset_04_tf)
asset_05_status = asset_05 == '' ? 0 : request.security(asset_05, asset_05_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_05 == '' ? 0 : checkStatus(asset_05_status, asset_05, asset_05_tf)
asset_06_status = asset_06 == '' ? 0 : request.security(asset_06, asset_06_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_06 == '' ? 0 : checkStatus(asset_06_status, asset_06, asset_06_tf)
asset_07_status = asset_07 == '' ? 0 : request.security(asset_07, asset_07_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_07 == '' ? 0 : checkStatus(asset_07_status, asset_07, asset_07_tf)
asset_08_status = asset_08 == '' ? 0 : request.security(asset_08, asset_08_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_08 == '' ? 0 : checkStatus(asset_08_status, asset_08, asset_08_tf)
asset_09_status = asset_09 == '' ? 0 : request.security(asset_09, asset_09_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_09 == '' ? 0 : checkStatus(asset_09_status, asset_09, asset_09_tf)
asset_10_status = asset_10 == '' ? 0 : request.security(asset_10, asset_10_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_10 == '' ? 0 : checkStatus(asset_10_status, asset_10, asset_10_tf)
asset_11_status = asset_11 == '' ? 0 : request.security(asset_11, asset_11_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_11 == '' ? 0 : checkStatus(asset_11_status, asset_11, asset_11_tf)
asset_12_status = asset_12 == '' ? 0 : request.security(asset_12, asset_12_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_12 == '' ? 0 : checkStatus(asset_12_status, asset_12, asset_12_tf)
asset_13_status = asset_13 == '' ? 0 : request.security(asset_13, asset_13_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_13 == '' ? 0 : checkStatus(asset_13_status, asset_13, asset_13_tf)
asset_14_status = asset_14 == '' ? 0 : request.security(asset_14, asset_14_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_14 == '' ? 0 : checkStatus(asset_14_status, asset_14, asset_14_tf)
asset_15_status = asset_15 == '' ? 0 : request.security(asset_15, asset_15_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_15 == '' ? 0 : checkStatus(asset_15_status, asset_15, asset_15_tf)
asset_16_status = asset_16 == '' ? 0 : request.security(asset_16, asset_16_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_16 == '' ? 0 : checkStatus(asset_16_status, asset_16, asset_16_tf)
asset_17_status = asset_17 == '' ? 0 : request.security(asset_17, asset_17_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_17 == '' ? 0 : checkStatus(asset_17_status, asset_17, asset_17_tf)
asset_18_status = asset_18 == '' ? 0 : request.security(asset_18, asset_18_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_18 == '' ? 0 : checkStatus(asset_18_status, asset_18, asset_18_tf)
asset_19_status = asset_19 == '' ? 0 : request.security(asset_19, asset_19_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_19 == '' ? 0 : checkStatus(asset_19_status, asset_19, asset_19_tf)
asset_20_status = asset_20 == '' ? 0 : request.security(asset_20, asset_20_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_20 == '' ? 0 : checkStatus(asset_20_status, asset_20, asset_20_tf)
asset_21_status = asset_21 == '' ? 0 : request.security(asset_21, asset_21_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_21 == '' ? 0 : checkStatus(asset_21_status, asset_21, asset_21_tf)
asset_22_status = asset_22 == '' ? 0 : request.security(asset_22, asset_22_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_22 == '' ? 0 : checkStatus(asset_22_status, asset_22, asset_22_tf)
asset_23_status = asset_23 == '' ? 0 : request.security(asset_23, asset_23_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_23 == '' ? 0 : checkStatus(asset_23_status, asset_23, asset_23_tf)
asset_24_status = asset_24 == '' ? 0 : request.security(asset_24, asset_24_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_24 == '' ? 0 : checkStatus(asset_24_status, asset_24, asset_24_tf)
asset_25_status = asset_25 == '' ? 0 : request.security(asset_25, asset_25_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_25 == '' ? 0 : checkStatus(asset_25_status, asset_25, asset_25_tf)
asset_26_status = asset_26 == '' ? 0 : request.security(asset_26, asset_26_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_26 == '' ? 0 : checkStatus(asset_26_status, asset_26, asset_26_tf)
asset_27_status = asset_27 == '' ? 0 : request.security(asset_27, asset_27_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_27 == '' ? 0 : checkStatus(asset_27_status, asset_27, asset_27_tf)
asset_28_status = asset_28 == '' ? 0 : request.security(asset_28, asset_28_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_28 == '' ? 0 : checkStatus(asset_28_status, asset_28, asset_28_tf)
asset_29_status = asset_29 == '' ? 0 : request.security(asset_29, asset_29_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_29 == '' ? 0 : checkStatus(asset_29_status, asset_29, asset_29_tf)
asset_30_status = asset_30 == '' ? 0 : request.security(asset_30, asset_30_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_30 == '' ? 0 : checkStatus(asset_30_status, asset_30, asset_30_tf)
asset_31_status = asset_31 == '' ? 0 : request.security(asset_31, asset_31_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_31 == '' ? 0 : checkStatus(asset_31_status, asset_31, asset_31_tf)
asset_32_status = asset_32 == '' ? 0 : request.security(asset_32, asset_32_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_32 == '' ? 0 : checkStatus(asset_32_status, asset_32, asset_32_tf)
asset_33_status = asset_33 == '' ? 0 : request.security(asset_33, asset_33_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_33 == '' ? 0 : checkStatus(asset_33_status, asset_33, asset_33_tf)
asset_34_status = asset_34 == '' ? 0 : request.security(asset_34, asset_34_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_34 == '' ? 0 : checkStatus(asset_34_status, asset_34, asset_34_tf)
asset_35_status = asset_35 == '' ? 0 : request.security(asset_35, asset_35_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_35 == '' ? 0 : checkStatus(asset_35_status, asset_35, asset_35_tf)
asset_36_status = asset_36 == '' ? 0 : request.security(asset_36, asset_36_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_36 == '' ? 0 : checkStatus(asset_36_status, asset_36, asset_36_tf)
asset_37_status = asset_37 == '' ? 0 : request.security(asset_37, asset_37_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_37 == '' ? 0 : checkStatus(asset_37_status, asset_37, asset_37_tf)
asset_38_status = asset_38 == '' ? 0 : request.security(asset_38, asset_38_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_38 == '' ? 0 : checkStatus(asset_38_status, asset_38, asset_38_tf)
asset_39_status = asset_39 == '' ? 0 : request.security(asset_39, asset_39_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_39 == '' ? 0 : checkStatus(asset_39_status, asset_39, asset_39_tf)
asset_40_status = asset_40 == '' ? 0 : request.security(asset_40, asset_40_tf, DivergenceIndicator(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
xx := asset_40 == '' ? 0 : checkStatus(asset_40_status, asset_40, asset_40_tf)
//bullish div
bullish_div = ""
bullish_div := asset_01 != '' and asset_01_status == 1 ? bullish_div + asset_01 + " (Bullish) Timframe["+asset_01_tf+"]\n" : bullish_div
bullish_div := asset_02 != '' and asset_02_status == 1 ? bullish_div + asset_02 + " (Bullish) Timframe["+asset_02_tf+"]\n" : bullish_div
bullish_div := asset_03 != '' and asset_03_status == 1 ? bullish_div + asset_03 + " (Bullish) Timframe["+asset_03_tf+"]\n" : bullish_div
bullish_div := asset_04 != '' and asset_04_status == 1 ? bullish_div + asset_04 + " (Bullish) Timframe["+asset_04_tf+"]\n" : bullish_div
bullish_div := asset_05 != '' and asset_05_status == 1 ? bullish_div + asset_05 + " (Bullish) Timframe["+asset_05_tf+"]\n" : bullish_div
bullish_div := asset_06 != '' and asset_06_status == 1 ? bullish_div + asset_06 + " (Bullish) Timframe["+asset_06_tf+"]\n" : bullish_div
bullish_div := asset_07 != '' and asset_07_status == 1 ? bullish_div + asset_07 + " (Bullish) Timframe["+asset_07_tf+"]\n" : bullish_div
bullish_div := asset_08 != '' and asset_08_status == 1 ? bullish_div + asset_08 + " (Bullish) Timframe["+asset_08_tf+"]\n" : bullish_div
bullish_div := asset_09 != '' and asset_09_status == 1 ? bullish_div + asset_09 + " (Bullish) Timframe["+asset_09_tf+"]\n" : bullish_div
bullish_div := asset_10 != '' and asset_10_status == 1 ? bullish_div + asset_10 + " (Bullish) Timframe["+asset_10_tf+"]\n" : bullish_div
bullish_div := asset_11 != '' and asset_11_status == 1 ? bullish_div + asset_11 + " (Bullish) Timframe["+asset_11_tf+"]\n" : bullish_div
bullish_div := asset_12 != '' and asset_12_status == 1 ? bullish_div + asset_12 + " (Bullish) Timframe["+asset_12_tf+"]\n" : bullish_div
bullish_div := asset_13 != '' and asset_13_status == 1 ? bullish_div + asset_13 + " (Bullish) Timframe["+asset_13_tf+"]\n" : bullish_div
bullish_div := asset_14 != '' and asset_14_status == 1 ? bullish_div + asset_14 + " (Bullish) Timframe["+asset_14_tf+"]\n" : bullish_div
bullish_div := asset_15 != '' and asset_15_status == 1 ? bullish_div + asset_15 + " (Bullish) Timframe["+asset_15_tf+"]\n" : bullish_div
bullish_div := asset_16 != '' and asset_16_status == 1 ? bullish_div + asset_16 + " (Bullish) Timframe["+asset_16_tf+"]\n" : bullish_div
bullish_div := asset_17 != '' and asset_17_status == 1 ? bullish_div + asset_17 + " (Bullish) Timframe["+asset_17_tf+"]\n" : bullish_div
bullish_div := asset_18 != '' and asset_18_status == 1 ? bullish_div + asset_18 + " (Bullish) Timframe["+asset_18_tf+"]\n" : bullish_div
bullish_div := asset_19 != '' and asset_19_status == 1 ? bullish_div + asset_19 + " (Bullish) Timframe["+asset_19_tf+"]\n" : bullish_div
bullish_div := asset_20 != '' and asset_20_status == 1 ? bullish_div + asset_20 + " (Bullish) Timframe["+asset_20_tf+"]\n" : bullish_div
bullish_div := asset_21 != '' and asset_21_status == 1 ? bullish_div + asset_21 + " (Bullish) Timframe["+asset_21_tf+"]\n" : bullish_div
bullish_div := asset_22 != '' and asset_22_status == 1 ? bullish_div + asset_22 + " (Bullish) Timframe["+asset_22_tf+"]\n" : bullish_div
bullish_div := asset_23 != '' and asset_23_status == 1 ? bullish_div + asset_23 + " (Bullish) Timframe["+asset_23_tf+"]\n" : bullish_div
bullish_div := asset_24 != '' and asset_24_status == 1 ? bullish_div + asset_24 + " (Bullish) Timframe["+asset_24_tf+"]\n" : bullish_div
bullish_div := asset_25 != '' and asset_25_status == 1 ? bullish_div + asset_25 + " (Bullish) Timframe["+asset_25_tf+"]\n" : bullish_div
bullish_div := asset_26 != '' and asset_26_status == 1 ? bullish_div + asset_26 + " (Bullish) Timframe["+asset_26_tf+"]\n" : bullish_div
bullish_div := asset_27 != '' and asset_27_status == 1 ? bullish_div + asset_27 + " (Bullish) Timframe["+asset_27_tf+"]\n" : bullish_div
bullish_div := asset_28 != '' and asset_28_status == 1 ? bullish_div + asset_28 + " (Bullish) Timframe["+asset_28_tf+"]\n" : bullish_div
bullish_div := asset_29 != '' and asset_29_status == 1 ? bullish_div + asset_29 + " (Bullish) Timframe["+asset_29_tf+"]\n" : bullish_div
bullish_div := asset_30 != '' and asset_30_status == 1 ? bullish_div + asset_30 + " (Bullish) Timframe["+asset_30_tf+"]\n" : bullish_div
bullish_div := asset_31 != '' and asset_31_status == 1 ? bullish_div + asset_31 + " (Bullish) Timframe["+asset_31_tf+"]\n" : bullish_div
bullish_div := asset_32 != '' and asset_32_status == 1 ? bullish_div + asset_32 + " (Bullish) Timframe["+asset_32_tf+"]\n" : bullish_div
bullish_div := asset_33 != '' and asset_33_status == 1 ? bullish_div + asset_33 + " (Bullish) Timframe["+asset_33_tf+"]\n" : bullish_div
bullish_div := asset_34 != '' and asset_34_status == 1 ? bullish_div + asset_34 + " (Bullish) Timframe["+asset_34_tf+"]\n" : bullish_div
bullish_div := asset_35 != '' and asset_35_status == 1 ? bullish_div + asset_35 + " (Bullish) Timframe["+asset_35_tf+"]\n" : bullish_div
bullish_div := asset_36 != '' and asset_36_status == 1 ? bullish_div + asset_36 + " (Bullish) Timframe["+asset_36_tf+"]\n" : bullish_div
bullish_div := asset_37 != '' and asset_37_status == 1 ? bullish_div + asset_37 + " (Bullish) Timframe["+asset_37_tf+"]\n" : bullish_div
bullish_div := asset_38 != '' and asset_38_status == 1 ? bullish_div + asset_38 + " (Bullish) Timframe["+asset_38_tf+"]\n" : bullish_div
bullish_div := asset_39 != '' and asset_39_status == 1 ? bullish_div + asset_39 + " (Bullish) Timframe["+asset_39_tf+"]\n" : bullish_div
bullish_div := asset_40 != '' and asset_40_status == 1 ? bullish_div + asset_40 + " (Bullish) Timframe["+asset_40_tf+"]\n" : bullish_div
//bullish div
bearish_div = ""
bearish_div := asset_01 != '' and asset_01_status == 3 ? bearish_div + asset_01 + " (Bearish) Timframe["+asset_01_tf+"]\n" : bearish_div
bearish_div := asset_02 != '' and asset_02_status == 3 ? bearish_div + asset_02 + " (Bearish) Timframe["+asset_02_tf+"]\n" : bearish_div
bearish_div := asset_03 != '' and asset_03_status == 3 ? bearish_div + asset_03 + " (Bearish) Timframe["+asset_03_tf+"]\n" : bearish_div
bearish_div := asset_04 != '' and asset_04_status == 3 ? bearish_div + asset_04 + " (Bearish) Timframe["+asset_04_tf+"]\n" : bearish_div
bearish_div := asset_05 != '' and asset_05_status == 3 ? bearish_div + asset_05 + " (Bearish) Timframe["+asset_05_tf+"]\n" : bearish_div
bearish_div := asset_06 != '' and asset_06_status == 3 ? bearish_div + asset_06 + " (Bearish) Timframe["+asset_06_tf+"]\n" : bearish_div
bearish_div := asset_07 != '' and asset_07_status == 3 ? bearish_div + asset_07 + " (Bearish) Timframe["+asset_07_tf+"]\n" : bearish_div
bearish_div := asset_08 != '' and asset_08_status == 3 ? bearish_div + asset_08 + " (Bearish) Timframe["+asset_08_tf+"]\n" : bearish_div
bearish_div := asset_09 != '' and asset_09_status == 3 ? bearish_div + asset_09 + " (Bearish) Timframe["+asset_09_tf+"]\n" : bearish_div
bearish_div := asset_10 != '' and asset_10_status == 3 ? bearish_div + asset_10 + " (Bearish) Timframe["+asset_10_tf+"]\n" : bearish_div
bearish_div := asset_11 != '' and asset_11_status == 3 ? bearish_div + asset_11 + " (Bearish) Timframe["+asset_11_tf+"]\n" : bearish_div
bearish_div := asset_12 != '' and asset_12_status == 3 ? bearish_div + asset_12 + " (Bearish) Timframe["+asset_12_tf+"]\n" : bearish_div
bearish_div := asset_13 != '' and asset_13_status == 3 ? bearish_div + asset_13 + " (Bearish) Timframe["+asset_13_tf+"]\n" : bearish_div
bearish_div := asset_14 != '' and asset_14_status == 3 ? bearish_div + asset_14 + " (Bearish) Timframe["+asset_14_tf+"]\n" : bearish_div
bearish_div := asset_15 != '' and asset_15_status == 3 ? bearish_div + asset_15 + " (Bearish) Timframe["+asset_15_tf+"]\n" : bearish_div
bearish_div := asset_16 != '' and asset_16_status == 3 ? bearish_div + asset_16 + " (Bearish) Timframe["+asset_16_tf+"]\n" : bearish_div
bearish_div := asset_17 != '' and asset_17_status == 3 ? bearish_div + asset_17 + " (Bearish) Timframe["+asset_17_tf+"]\n" : bearish_div
bearish_div := asset_18 != '' and asset_18_status == 3 ? bearish_div + asset_18 + " (Bearish) Timframe["+asset_18_tf+"]\n" : bearish_div
bearish_div := asset_19 != '' and asset_19_status == 3 ? bearish_div + asset_19 + " (Bearish) Timframe["+asset_19_tf+"]\n" : bearish_div
bearish_div := asset_20 != '' and asset_20_status == 3 ? bearish_div + asset_20 + " (Bearish) Timframe["+asset_20_tf+"]\n" : bearish_div
bearish_div := asset_21 != '' and asset_21_status == 3 ? bearish_div + asset_21 + " (Bearish) Timframe["+asset_21_tf+"]\n" : bearish_div
bearish_div := asset_22 != '' and asset_22_status == 3 ? bearish_div + asset_22 + " (Bearish) Timframe["+asset_22_tf+"]\n" : bearish_div
bearish_div := asset_23 != '' and asset_23_status == 3 ? bearish_div + asset_23 + " (Bearish) Timframe["+asset_23_tf+"]\n" : bearish_div
bearish_div := asset_24 != '' and asset_24_status == 3 ? bearish_div + asset_24 + " (Bearish) Timframe["+asset_24_tf+"]\n" : bearish_div
bearish_div := asset_25 != '' and asset_25_status == 3 ? bearish_div + asset_25 + " (Bearish) Timframe["+asset_25_tf+"]\n" : bearish_div
bearish_div := asset_26 != '' and asset_26_status == 3 ? bearish_div + asset_26 + " (Bearish) Timframe["+asset_26_tf+"]\n" : bearish_div
bearish_div := asset_27 != '' and asset_27_status == 3 ? bearish_div + asset_27 + " (Bearish) Timframe["+asset_27_tf+"]\n" : bearish_div
bearish_div := asset_28 != '' and asset_28_status == 3 ? bearish_div + asset_28 + " (Bearish) Timframe["+asset_28_tf+"]\n" : bearish_div
bearish_div := asset_29 != '' and asset_29_status == 3 ? bearish_div + asset_29 + " (Bearish) Timframe["+asset_29_tf+"]\n" : bearish_div
bearish_div := asset_30 != '' and asset_30_status == 3 ? bearish_div + asset_30 + " (Bearish) Timframe["+asset_30_tf+"]\n" : bearish_div
bearish_div := asset_31 != '' and asset_31_status == 3 ? bearish_div + asset_31 + " (Bearish) Timframe["+asset_31_tf+"]\n" : bearish_div
bearish_div := asset_32 != '' and asset_32_status == 3 ? bearish_div + asset_32 + " (Bearish) Timframe["+asset_32_tf+"]\n" : bearish_div
bearish_div := asset_33 != '' and asset_33_status == 3 ? bearish_div + asset_33 + " (Bearish) Timframe["+asset_33_tf+"]\n" : bearish_div
bearish_div := asset_34 != '' and asset_34_status == 3 ? bearish_div + asset_34 + " (Bearish) Timframe["+asset_34_tf+"]\n" : bearish_div
bearish_div := asset_35 != '' and asset_35_status == 3 ? bearish_div + asset_35 + " (Bearish) Timframe["+asset_35_tf+"]\n" : bearish_div
bearish_div := asset_36 != '' and asset_36_status == 3 ? bearish_div + asset_36 + " (Bearish) Timframe["+asset_36_tf+"]\n" : bearish_div
bearish_div := asset_37 != '' and asset_37_status == 3 ? bearish_div + asset_37 + " (Bearish) Timframe["+asset_37_tf+"]\n" : bearish_div
bearish_div := asset_38 != '' and asset_38_status == 3 ? bearish_div + asset_38 + " (Bearish) Timframe["+asset_38_tf+"]\n" : bearish_div
bearish_div := asset_39 != '' and asset_39_status == 3 ? bearish_div + asset_39 + " (Bearish) Timframe["+asset_39_tf+"]\n" : bearish_div
bearish_div := asset_40 != '' and asset_40_status == 3 ? bearish_div + asset_40 + " (Bearish) Timframe["+asset_40_tf+"]\n" : bearish_div
//--------------
// Prep Label Value
//--------------
var assetcount = asset_01=='' and asset_02=='' and asset_03=='' and asset_04=='' and asset_05=='' and asset_06=='' and asset_07=='' and asset_08=='' and asset_09=='' and asset_10=='' and asset_11=='' and asset_12=='' and asset_13=='' and asset_14=='' and asset_15=='' and asset_16=='' and asset_17=='' and asset_18=='' and asset_19=='' and asset_20=='' and asset_21=='' and asset_22=='' and asset_23=='' and asset_24=='' and asset_25=='' and asset_26=='' and asset_27=='' and asset_28=='' and asset_29=='' and asset_30=='' and asset_31=='' and asset_32=='' and asset_33=='' and asset_34=='' and asset_35=='' and asset_36=='' and asset_37=='' and asset_38=='' and asset_39=='' and asset_40=='' ? 0 : 1
var brl = "\n-----------------------\n"
title = "Divergence Screener [Mr_Zed]"+brl
checklist = assetcount==0 ? "No Asset Defined\nPlease update parameter " : ""
obList = ""
osList = ""
if(assetcount>0)
if(bullish_div != "")
obList := "\nBullish List: "+brl+bullish_div
if(bearish_div != "")
osList := "\nBearish List: "+brl+bearish_div
if(obList=="" and osList == "")
checklist := "Nothing Interesting"
//--------------
// Draw Label
//--------------
label _lbl = label.new(time, close, xloc=xloc.bar_time,
text = title + checklist + osList + obList,
color = color.black,
style = label.style_label_left,
textcolor = color.white,
size = size.normal,
textalign = text.align_left)
label.set_x(_lbl, label.get_x(_lbl) + math.round(ta.change(time)*10))
label.delete(_lbl[1])
|
Price Delta Heatmap | https://www.tradingview.com/script/8dRYYSPd-Price-Delta-Heatmap/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 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/
// © LeafAlgo
//@version=5
indicator("Price Delta Heatmap", overlay=false)
// Calculate price delta
priceDelta = close - close[1]
// Define color ranges for heatmap
delta1 = input.float(100.0, 'Highest Positive Delta Threshold')
delta2 = input.float(50.0, 'Third Positive Delta Threshold')
delta3 = input.float(20.0, 'Second Positive Delta Threshold')
delta4 = input.float(10.0, 'Lowest Positive Delta Threshold')
delta5 = 0
delta6 = input.float(-10.0, 'Lowest Negative Delta Threshold')
delta7 = input.float(-20.0, 'Second Negative Delta Threshold')
delta8 = input.float(-50.0, 'Third Negative Delta Threshold')
delta9 = input.float(-100.0, 'Lowest Negative Delta Threshold')
// Set bar and background colors based on price delta ranges
barcolor(priceDelta >= delta1 ? color.lime :
priceDelta >= delta2 ? color.green :
priceDelta >= delta3 ? color.olive :
priceDelta >= delta4 ? color.yellow :
priceDelta >= delta5 ? color.white :
priceDelta >= delta6 ? color.yellow :
priceDelta >= delta7 ? color.orange :
priceDelta >= delta8 ? color.red :
color.maroon)
bgcolor(priceDelta >= delta1 ? color.new(color.lime, 70) :
priceDelta >= delta2 ? color.new(color.green, 70) :
priceDelta >= delta3 ? color.new(color.olive, 70) :
priceDelta >= delta4 ? color.new(color.yellow, 70) :
priceDelta >= delta5 ? color.new(color.white, 70) :
priceDelta >= delta6 ? color.new(color.yellow, 70) :
priceDelta >= delta7 ? color.new(color.orange, 70) :
priceDelta >= delta8 ? color.new(color.red, 70) :
color.new(color.maroon, 70))
// Plotting
deltaColor = priceDelta >= delta3 ? color.lime : priceDelta <= delta7 ? color.fuchsia : color.aqua
plotshape(priceDelta >= delta3, 'Positive Delta Signal', style = shape.triangleup, size=size.small, color=color.lime, location=location.bottom)
plotshape(priceDelta <= delta7, 'Negative Delta Signal', style = shape.triangledown, size=size.small, color=color.fuchsia, location=location.bottom)
plot(priceDelta, color=deltaColor, linewidth=4, title="Price Delta")
hline(delta1)
hline(delta2)
hline(delta3)
hline(delta4)
hline(delta5, linewidth=2)
hline(delta6)
hline(delta7)
hline(delta8)
hline(delta9)
|
ICT Killzones + Pivots [TFO] | https://www.tradingview.com/script/nW5oGfdO-ICT-Killzones-Pivots-TFO/ | tradeforopp | https://www.tradingview.com/u/tradeforopp/ | 8,333 | 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/
// © tradeforopp
//@version=5
indicator("ICT Killzones & Pivots [TFO]", "ICT Killzones & Pivots [TFO]", true, max_labels_count = 500, max_lines_count = 500, max_boxes_count = 500)
// ---------------------------------------- Inputs --------------------------------------------------
var g_SETTINGS = "Settings"
max_days = input.int(3, "Session Drawing Limit", 1, tooltip = "Only this many drawings will be kept on the chart, for each selected drawing type (killzone boxes, pivot lines, open lines, etc.)", group = g_SETTINGS)
tf_limit = input.timeframe("30", "Timeframe Limit", tooltip = "Drawings will not appear on timeframes greater than or equal to this", group = g_SETTINGS)
gmt_tz = input.string('GMT-4', "Timezone", options = ['GMT-12','GMT-11','GMT-10','GMT-9','GMT-8','GMT-7','GMT-6','GMT-5','GMT-4','GMT-3','GMT-2','GMT-1','GMT+0','GMT+1','GMT+2','GMT+3','GMT+4','GMT+5','GMT+6','GMT+7','GMT+8','GMT+9','GMT+10','GMT+11','GMT+12','GMT+13','GMT+14'], tooltip = "Note GMT is not adjusted to reflect Daylight Saving Time changes", group = g_SETTINGS)
lb_size = input.string('Normal', "Label Size", options = ['Auto', 'Tiny', 'Small', 'Normal', 'Large', 'Huge'], group = g_SETTINGS)
lb_color = input.color(color.black, "Label Text Color", group = g_SETTINGS)
use_cutoff = input.bool(true, "Drawing Cutoff Time", inline = "CO", tooltip = "When enabled, all highs and lows will stop extending after this time", group = g_SETTINGS)
cutoff = input.session("1200-1201", "", inline = "CO", group = g_SETTINGS)
var g_KZ = "Killzones"
show_kz = input.bool(true, "Show Killzone Boxes", inline = "KZ", group = g_KZ)
show_kz_text = input.bool(true, "Display Text", inline = "KZ", group = g_KZ)
box_transparency = input.int(70, "Box Transparency", 0, 100, group = g_KZ)
text_transparency = input.int(50, "Text Transparency", 0, 100, group = g_KZ)
use_asia = input.bool(true, "", inline = "ASIA", group = g_KZ)
asia_text = input.string("Asia", "", inline = "ASIA", group = g_KZ)
asia = input.session("2000-0000", "", inline = "ASIA", group = g_KZ)
as_color = input.color(color.blue, "", inline = "ASIA", group = g_KZ)
use_london = input.bool(true, "", inline = "LONDON", group = g_KZ)
london_text = input.string("London", "", inline = "LONDON", group = g_KZ)
london = input.session("0200-0500", "", inline = "LONDON", group = g_KZ)
lo_color = input.color(color.red, "", inline = "LONDON", group = g_KZ)
use_nyam = input.bool(true, "", inline = "NYAM", group = g_KZ)
nyam_text = input.string("NY AM", "", inline = "NYAM", group = g_KZ)
nyam = input.session("0930-1100", "", inline = "NYAM", group = g_KZ)
na_color = input.color(#089981, "", inline = "NYAM", group = g_KZ)
use_nylu = input.bool(true, "", inline = "NYLU", group = g_KZ)
nylu_text = input.string("NY Lunch", "", inline = "NYLU", group = g_KZ)
nylu = input.session("1200-1300", "", inline = "NYLU", group = g_KZ)
nl_color = input.color(color.yellow, "", inline = "NYLU", group = g_KZ)
use_nypm = input.bool(true, "", inline = "NYPM", group = g_KZ)
nypm_text = input.string("NY PM", "", inline = "NYPM", group = g_KZ)
nypm = input.session("1330-1600", "", inline = "NYPM", group = g_KZ)
np_color = input.color(color.purple, "", inline = "NYPM", group = g_KZ)
var g_LABELS = "Killzone Pivots"
show_pivots = input.bool(true, "Show Pivots", inline = "PV", group = g_LABELS)
show_labels = input.bool(true, "Show Labels", inline = "PV", group = g_LABELS)
ash_str = input.string("AS.H", "Session 1 Labels", inline = "L_AS", group = g_LABELS)
asl_str = input.string("AS.L", "", inline = "L_AS", group = g_LABELS)
as_alert = input.bool(false, "Alerts", inline = "L_AS", group = g_LABELS)
loh_str = input.string("LO.H", "Session 2 Labels", inline = "L_LO", group = g_LABELS)
lol_str = input.string("LO.L", "", inline = "L_LO", group = g_LABELS)
lo_alert = input.bool(false, "Alerts", inline = "L_LO", group = g_LABELS)
nah_str = input.string("NYAM.H", "Session 3 Labels", inline = "L_NA", group = g_LABELS)
nal_str = input.string("NYAM.L", "", inline = "L_NA", group = g_LABELS)
na_alert = input.bool(false, "Alerts", inline = "L_NA", group = g_LABELS)
nlh_str = input.string("NYL.H", "Session 4 Labels", inline = "L_NL", group = g_LABELS)
nll_str = input.string("NYL.L", "", inline = "L_NL", group = g_LABELS)
nl_alert = input.bool(false, "Alerts", inline = "L_NL", group = g_LABELS)
nph_str = input.string("NYPM.H", "Session 5 Labels", inline = "L_NP", group = g_LABELS)
npl_str = input.string("NYPM.L", "", inline = "L_NP", group = g_LABELS)
np_alert = input.bool(false, "Alerts", inline = "L_NP", group = g_LABELS)
s_style = input.string(defval = 'Solid', title = "Style", options = ['Solid', 'Dotted', 'Dashed'], inline = "L_0", group = g_LABELS)
s_width = input.int(1, "", inline = "L_0", group = g_LABELS)
var g_DWM = "DWM Open"
dow_labels = input.bool(true, "Day of Week Labels", inline = "DOW", group = g_DWM)
dow_yloc = input.string('Bottom', "", options = ['Top', 'Bottom'], inline = "DOW", group = g_DWM)
dow_xloc = input.string('Midnight', "", options = ['Midnight', 'Midday'], inline = "DOW", group = g_DWM)
dow_color = input.color(color.black, "", inline = "DOW", group = g_DWM)
show_d_open = input.bool(false, "", inline = "DO", group = g_DWM)
d_open_str = input.string("D.OPEN", "", inline = "DO", group = g_DWM)
ds = input.bool(false, "Separators", inline = "DO", tooltip = "Mark where a new day begins. Unlimited will override the drawing limit", group = g_DWM)
ds_unlimited = input.bool(true, "Unlimited", inline = "DO", group = g_DWM)
d_color = input.color(color.blue, "", inline = "DO", group = g_DWM)
show_w_open = input.bool(false, "", inline = "WO", group = g_DWM)
w_open_str = input.string("W.OPEN", "", inline = "WO", group = g_DWM)
ws = input.bool(false, "Separators", inline = "WO", tooltip = "Mark where a new week begins. Unlimited will override the drawing limit", group = g_DWM)
ws_unlimited = input.bool(true, "Unlimited", inline = "WO", group = g_DWM)
w_color = input.color(#089981, "", inline = "WO", group = g_DWM)
show_m_open = input.bool(false, "", inline = "MO", group = g_DWM)
m_open_str = input.string("M.OPEN", "", inline = "MO", group = g_DWM)
ms = input.bool(false, "Separators", inline = "MO", tooltip = "Mark where a new month begins. Unlimited will override the drawing limit", group = g_DWM)
ms_unlimited = input.bool(true, "Unlimited", inline = "MO", group = g_DWM)
m_color = input.color(color.red, "", inline = "MO", group = g_DWM)
dwm_style = input.string(defval = 'Solid', title = "Style", options = ['Solid', 'Dotted', 'Dashed'], inline = "D0", group = g_DWM)
dwm_width = input.int(1, "", inline = "D0", group = g_DWM)
var g_OPEN = "Opening Price"
use_h1 = input.bool(true, "", inline = "H1", group = g_OPEN)
h1_text = input.string("True Day Open", "", inline = "H1", group = g_OPEN)
h1 = input.session("0000-0001", "", inline = "H1", group = g_OPEN)
h1_color = input.color(color.black, "", inline = "H1", group = g_OPEN)
use_h2 = input.bool(false, "", inline = "H2", group = g_OPEN)
h2_text = input.string("06:00", "", inline = "H2", group = g_OPEN)
h2 = input.session("0600-0601", "", inline = "H2", group = g_OPEN)
h2_color = input.color(color.black, "", inline = "H2", group = g_OPEN)
use_h3 = input.bool(false, "", inline = "H3", group = g_OPEN)
h3_text = input.string("10:00", "", inline = "H3", group = g_OPEN)
h3 = input.session("1000-1001", "", inline = "H3", group = g_OPEN)
h3_color = input.color(color.black, "", inline = "H3", group = g_OPEN)
use_h4 = input.bool(false, "", inline = "H4", group = g_OPEN)
h4_text = input.string("14:00", "", inline = "H4", group = g_OPEN)
h4 = input.session("1400-1401", "", inline = "H4", group = g_OPEN)
h4_color = input.color(color.black, "", inline = "H4", group = g_OPEN)
h_style = input.string(defval = 'Dotted', title = "Style", options = ['Solid', 'Dotted', 'Dashed'], inline = "H0", group = g_OPEN)
h_width = input.int(1, "", inline = "H0", group = g_OPEN)
var g_VERTICAL = "Timestamps"
use_v1 = input.bool(false, "", inline = "V1", group = g_VERTICAL)
v1 = input.session("0000-0001", "", inline = "V1", group = g_VERTICAL)
v1_color = input.color(color.black, "", inline = "V1", group = g_VERTICAL)
use_v2 = input.bool(false, "", inline = "V2", group = g_VERTICAL)
v2 = input.session("0800-0801", "", inline = "V2", group = g_VERTICAL)
v2_color = input.color(color.black, "", inline = "V2", group = g_VERTICAL)
use_v3 = input.bool(false, "", inline = "V3", group = g_VERTICAL)
v3 = input.session("1000-1001", "", inline = "V3", group = g_VERTICAL)
v3_color = input.color(color.black, "", inline = "V3", group = g_VERTICAL)
use_v4 = input.bool(true, "", inline = "V4", group = g_VERTICAL)
v4 = input.session("1200-1201", "", inline = "V4", group = g_VERTICAL)
v4_color = input.color(color.black, "", inline = "V4", group = g_VERTICAL)
v_style = input.string(defval = 'Dotted', title = "Style", options = ['Solid', 'Dotted', 'Dashed'], inline = "V0", group = g_VERTICAL)
v_width = input.int(1, "", inline = "V0", group = g_VERTICAL)
// ---------------------------------------- Inputs --------------------------------------------------
// ---------------------------------------- Variables & Constants --------------------------------------------------
t_as = not na(time("", asia, gmt_tz))
t_lo = not na(time("", london, gmt_tz))
t_na = not na(time("", nyam, gmt_tz))
t_nl = not na(time("", nylu, gmt_tz))
t_np = not na(time("", nypm, gmt_tz))
t_co = not na(time("", cutoff, gmt_tz))
t_h1 = not na(time("", h1, gmt_tz))
t_h2 = not na(time("", h2, gmt_tz))
t_h3 = not na(time("", h3, gmt_tz))
t_h4 = not na(time("", h4, gmt_tz))
t_v1 = not na(time("", v1, gmt_tz))
t_v2 = not na(time("", v2, gmt_tz))
t_v3 = not na(time("", v3, gmt_tz))
t_v4 = not na(time("", v4, gmt_tz))
var as_hi_line = array.new_line()
var as_lo_line = array.new_line()
var lo_hi_line = array.new_line()
var lo_lo_line = array.new_line()
var na_hi_line = array.new_line()
var na_lo_line = array.new_line()
var nl_hi_line = array.new_line()
var nl_lo_line = array.new_line()
var np_hi_line = array.new_line()
var np_lo_line = array.new_line()
var d_sep_line = array.new_line()
var w_sep_line = array.new_line()
var m_sep_line = array.new_line()
var d_line = array.new_line()
var w_line = array.new_line()
var m_line = array.new_line()
var h1_line = array.new_line()
var h2_line = array.new_line()
var h3_line = array.new_line()
var h4_line = array.new_line()
var v1_line = array.new_line()
var v2_line = array.new_line()
var v3_line = array.new_line()
var v4_line = array.new_line()
var d_label = array.new_label()
var w_label = array.new_label()
var m_label = array.new_label()
var h1_label = array.new_label()
var h2_label = array.new_label()
var h3_label = array.new_label()
var h4_label = array.new_label()
var as_hi_label = array.new_label()
var as_lo_label = array.new_label()
var lo_hi_label = array.new_label()
var lo_lo_label = array.new_label()
var na_hi_label = array.new_label()
var na_lo_label = array.new_label()
var nl_hi_label = array.new_label()
var nl_lo_label = array.new_label()
var np_hi_label = array.new_label()
var np_lo_label = array.new_label()
var as_box = array.new_box()
var lo_box = array.new_box()
var na_box = array.new_box()
var nl_box = array.new_box()
var np_box = array.new_box()
transparent = #ffffff00
d_o = request.security(syminfo.tickerid, "D", open, barmerge.gaps_off, barmerge.lookahead_on)
w_o = request.security(syminfo.tickerid, "W", open, barmerge.gaps_off, barmerge.lookahead_on)
m_o = request.security(syminfo.tickerid, "M", open, barmerge.gaps_off, barmerge.lookahead_on)
// ---------------------------------------- Variables & Constants --------------------------------------------------
// ---------------------------------------- Functions --------------------------------------------------
get_label_size(_size) =>
result = switch _size
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Large' => size.large
'Huge' => size.huge
'Auto' => size.auto
result
get_line_type(_style) =>
result = switch _style
'Solid' => line.style_solid
'Dotted' => line.style_dotted
'Dashed' => line.style_dashed
result
get_box_color(_color, _transparency) =>
result = color.new(_color, _transparency)
adjust(_hline, _lline, _hlabel, _llabel, _ulabel, _box) =>
_hline.set_x2(bar_index)
_lline.set_x2(bar_index)
_box.set_right(bar_index)
_top = show_kz ? _box.get_top() : _hline.get_y1()
_bot = show_kz ? _box.get_bottom() : _lline.get_y1()
if high > _top
_hline.set_xy1(bar_index, high)
_hline.set_y2(high)
_box.set_top(high)
_hlabel.set_x(bar_index)
_hlabel.set_y(high)
if low < _bot
_lline.set_xy1(bar_index, low)
_lline.set_y2(low)
_box.set_bottom(low)
_llabel.set_x(bar_index)
_llabel.set_y(low)
check_high(_line) =>
result = false
broke = false
_line.set_x2(bar_index)
if high > _line.get_y1()
result := true
broke := true
else if (use_cutoff ? t_co : false)
result := true
[result, broke]
check_low(_line) =>
result = false
broke = false
_line.set_x2(bar_index)
if low < _line.get_y1()
result := true
broke := true
else if (use_cutoff ? t_co : false)
result := true
[result, broke]
check_open(_line, _label) =>
result = false
_line.set_x2(bar_index)
_label.set_x(bar_index)
if (use_cutoff ? t_co : false)
result := true
result
check_array(_arr) =>
if _arr.size() > max_days
_arr.pop().delete()
// ---------------------------------------- Functions --------------------------------------------------
// ---------------------------------------- Core Logic --------------------------------------------------
s_style := get_line_type(s_style)
dwm_style := get_line_type(dwm_style)
h_style := get_line_type(h_style)
v_style := get_line_type(v_style)
lb_size := get_label_size(lb_size)
var color as_box_color = get_box_color(as_color, box_transparency)
var color lo_box_color = get_box_color(lo_color, box_transparency)
var color na_box_color = get_box_color(na_color, box_transparency)
var color nl_box_color = get_box_color(nl_color, box_transparency)
var color np_box_color = get_box_color(np_color, box_transparency)
var color as_text_color = get_box_color(as_color, text_transparency)
var color lo_text_color = get_box_color(lo_color, text_transparency)
var color na_text_color = get_box_color(na_color, text_transparency)
var color nl_text_color = get_box_color(nl_color, text_transparency)
var color np_text_color = get_box_color(np_color, text_transparency)
var h1_co = false
var h2_co = false
var h3_co = false
var h4_co = false
var as_stop_hi = false
var as_stop_lo = false
var lo_stop_hi = false
var lo_stop_lo = false
var na_stop_hi = false
var na_stop_lo = false
var nl_stop_hi = false
var nl_stop_lo = false
var np_stop_hi = false
var np_stop_lo = false
as_broke_hi = false
as_broke_lo = false
lo_broke_hi = false
lo_broke_lo = false
na_broke_hi = false
na_broke_lo = false
nl_broke_hi = false
nl_broke_lo = false
np_broke_hi = false
np_broke_lo = false
// day_str = switch dayofweek
// if dayofweek != dayofweek[1]
// label.new(time, high, str.tostring(dayofweek))
if timeframe.in_seconds("") <= timeframe.in_seconds(tf_limit)
// Asia
if use_asia
if t_as and not t_as[1]
as_stop_hi := false
as_stop_lo := false
if show_kz
as_box.unshift(box.new(bar_index, high, bar_index, low, border_color = as_box_color, bgcolor = as_box_color, text = show_kz_text ? asia_text : na, text_color = as_text_color))
if show_pivots
as_hi_line.unshift(line.new(bar_index, high, bar_index, high, style = s_style, color = as_color, width = s_width))
as_lo_line.unshift(line.new(bar_index, low, bar_index, low, style = s_style, color = as_color, width = s_width))
if show_labels
as_hi_label.unshift(label.new(bar_index, high, ash_str, color = transparent, textcolor = lb_color, style = label.style_label_down, size = lb_size))
as_lo_label.unshift(label.new(bar_index, low, asl_str, color = transparent, textcolor = lb_color, style = label.style_label_up, size = lb_size))
else if t_as
adjust(show_pivots ? as_hi_line.get(0) : na, show_pivots ? as_lo_line.get(0) : na, show_labels ? as_hi_label.get(0) : na, show_labels ? as_lo_label.get(0) : na, show_labels, show_kz ? as_box.get(0) : na)
else if not t_as and as_hi_line.size() > 0
if not as_stop_hi
[_r, _b] = check_high(as_hi_line.get(0))
if _r
as_stop_hi := true
if _b
as_broke_hi := true
if as_alert
alert("Broke " + str.tostring(ash_str), alert.freq_once_per_bar)
if not as_stop_lo
[_r, _b] = check_low(as_lo_line.get(0))
if _r
as_stop_lo := true
if _b
as_broke_lo := true
if as_alert
alert("Broke " + str.tostring(asl_str), alert.freq_once_per_bar)
// London
if use_london
if t_lo and not t_lo[1]
lo_stop_hi := false
lo_stop_lo := false
if show_kz
lo_box.unshift(box.new(bar_index, high, bar_index, low, border_color = lo_box_color, bgcolor = lo_box_color, text = show_kz_text ? london_text : na, text_color = lo_text_color))
if show_pivots
lo_hi_line.unshift(line.new(bar_index, high, bar_index, high, style = s_style, color = lo_color, width = s_width))
lo_lo_line.unshift(line.new(bar_index, low, bar_index, low, style = s_style, color = lo_color, width = s_width))
if show_labels
lo_hi_label.unshift(label.new(bar_index, high, loh_str, color = transparent, textcolor = lb_color, style = label.style_label_down, size = lb_size))
lo_lo_label.unshift(label.new(bar_index, low, lol_str, color = transparent, textcolor = lb_color, style = label.style_label_up, size = lb_size))
else if t_lo
adjust(show_pivots ? lo_hi_line.get(0) : na, show_pivots ? lo_lo_line.get(0) : na, show_labels ? lo_hi_label.get(0) : na, show_labels ? lo_lo_label.get(0) : na, show_labels, show_kz ? lo_box.get(0) : na)
else if not t_lo and lo_hi_line.size() > 0
if not lo_stop_hi
[_r, _b] = check_high(lo_hi_line.get(0))
if _r
lo_stop_hi := true
if _b
lo_broke_hi := true
if lo_alert
alert("Broke " + str.tostring(loh_str), alert.freq_once_per_bar)
if not lo_stop_lo
[_r, _b] = check_low(lo_lo_line.get(0))
if _r
lo_stop_lo := true
if _b
lo_broke_lo := true
if lo_alert
alert("Broke " + str.tostring(lol_str), alert.freq_once_per_bar)
// NY AM
if use_nyam
if t_na and not t_na[1]
na_stop_hi := false
na_stop_lo := false
if show_kz
na_box.unshift(box.new(bar_index, high, bar_index, low, border_color = na_box_color, bgcolor = na_box_color, text = show_kz_text ? nyam_text : na, text_color = na_text_color))
if show_pivots
na_hi_line.unshift(line.new(bar_index, high, bar_index, high, style = s_style, color = na_color, width = s_width))
na_lo_line.unshift(line.new(bar_index, low, bar_index, low, style = s_style, color = na_color, width = s_width))
if show_labels
na_hi_label.unshift(label.new(bar_index, high, nah_str, color = transparent, textcolor = lb_color, style = label.style_label_down, size = lb_size))
na_lo_label.unshift(label.new(bar_index, low, nal_str, color = transparent, textcolor = lb_color, style = label.style_label_up, size = lb_size))
else if t_na
adjust(show_pivots ? na_hi_line.get(0) : na, show_pivots ? na_lo_line.get(0) : na, show_labels ? na_hi_label.get(0) : na, show_labels ? na_lo_label.get(0) : na, show_labels, show_kz ? na_box.get(0) : na)
else if not t_na and na_hi_line.size() > 0
if not na_stop_hi
[_r, _b] = check_high(na_hi_line.get(0))
if _r
na_stop_hi := true
if _b
na_broke_hi := true
if na_alert
alert("Broke " + str.tostring(nah_str), alert.freq_once_per_bar)
if not na_stop_lo
[_r, _b] = check_low(na_lo_line.get(0))
if _r
na_stop_lo := true
if _b
na_broke_lo := true
if na_alert
alert("Broke " + str.tostring(nal_str), alert.freq_once_per_bar)
// NY Lunch
if use_nylu
if t_nl and not t_nl[1]
nl_stop_hi := false
nl_stop_lo := false
if show_kz
nl_box.unshift(box.new(bar_index, high, bar_index, low, border_color = nl_box_color, bgcolor = nl_box_color, text = show_kz_text ? nylu_text : na, text_color = nl_text_color))
if show_pivots
nl_hi_line.unshift(line.new(bar_index, high, bar_index, high, style = s_style, color = nl_color, width = s_width))
nl_lo_line.unshift(line.new(bar_index, low, bar_index, low, style = s_style, color = nl_color, width = s_width))
if show_labels
nl_hi_label.unshift(label.new(bar_index, high, nlh_str, color = transparent, textcolor = lb_color, style = label.style_label_down, size = lb_size))
nl_lo_label.unshift(label.new(bar_index, low, nll_str, color = transparent, textcolor = lb_color, style = label.style_label_up, size = lb_size))
else if t_nl
adjust(show_pivots ? nl_hi_line.get(0) : na, show_pivots ? nl_lo_line.get(0) : na, show_labels ? nl_hi_label.get(0) : na, show_labels ? nl_lo_label.get(0) : na, show_labels, show_kz ? nl_box.get(0) : na)
else if not t_nl and nl_hi_line.size() > 0
if not nl_stop_hi
[_r, _b] = check_high(nl_hi_line.get(0))
if _r
nl_stop_hi := true
if _b
nl_broke_hi := true
if nl_alert
alert("Broke " + str.tostring(nlh_str), alert.freq_once_per_bar)
if not nl_stop_lo
[_r, _b] = check_low(nl_lo_line.get(0))
if _r
nl_stop_lo := true
if _b
nl_broke_lo := true
if nl_alert
alert("Broke " + str.tostring(nll_str), alert.freq_once_per_bar)
// NY PM
if use_nypm
if t_np and not t_np[1]
np_stop_hi := false
np_stop_lo := false
if show_kz
np_box.unshift(box.new(bar_index, high, bar_index, low, border_color = np_box_color, bgcolor = np_box_color, text = show_kz_text ? nypm_text : na, text_color = np_text_color))
if show_pivots
np_hi_line.unshift(line.new(bar_index, high, bar_index, high, style = s_style, color = np_color, width = s_width))
np_lo_line.unshift(line.new(bar_index, low, bar_index, low, style = s_style, color = np_color, width = s_width))
if show_labels
np_hi_label.unshift(label.new(bar_index, high, nph_str, color = transparent, textcolor = lb_color, style = label.style_label_down, size = lb_size))
np_lo_label.unshift(label.new(bar_index, low, npl_str, color = transparent, textcolor = lb_color, style = label.style_label_up, size = lb_size))
else if t_np
adjust(show_pivots ? np_hi_line.get(0) : na, show_pivots ? np_lo_line.get(0) : na, show_labels ? np_hi_label.get(0) : na, show_labels ? np_lo_label.get(0) : na, show_labels, show_kz ? np_box.get(0) : na)
else if not t_np and np_hi_line.size() > 0
if not np_stop_hi
[_r, _b] = check_high(np_hi_line.get(0))
if _r
np_stop_hi := true
if _b
np_broke_hi := true
if np_alert
alert("Broke " + str.tostring(nph_str), alert.freq_once_per_bar)
if not np_stop_lo
[_r, _b] = check_low(np_lo_line.get(0))
if _r
np_stop_lo := true
if _b
np_broke_lo := true
if np_alert
alert("Broke " + str.tostring(npl_str), alert.freq_once_per_bar)
// Vertical Lines
if use_v1
if t_v1 and not t_v1[1]
v1_line.unshift(line.new(bar_index, high, bar_index, low, style = v_style, width = v_width, extend = extend.both, color = v1_color))
if use_v2
if t_v2 and not t_v2[1]
v2_line.unshift(line.new(bar_index, high, bar_index, low, style = v_style, width = v_width, extend = extend.both, color = v2_color))
if use_v3
if t_v3 and not t_v3[1]
v3_line.unshift(line.new(bar_index, high, bar_index, low, style = v_style, width = v_width, extend = extend.both, color = v3_color))
if use_v4
if t_v4 and not t_v4[1]
v4_line.unshift(line.new(bar_index, high, bar_index, low, style = v_style, width = v_width, extend = extend.both, color = v4_color))
// Horizontal Lines
if use_h1
if t_h1 and not t_h1[1]
h1_co := false
h1_line.unshift(line.new(bar_index, open, bar_index, open, style = h_style, width = h_width, color = h1_color))
h1_label.unshift(label.new(bar_index, open, h1_text, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if not t_h1 and h1_line.size() > 0
if not h1_co
if not check_open(h1_line.get(0), h1_label.get(0))
h1_label.get(0).set_x(bar_index)
else
h1_co := true
if use_h2
if t_h2 and not t_h2[1]
h2_co := false
h2_line.unshift(line.new(bar_index, open, bar_index, open, style = h_style, width = h_width, color = h2_color))
h2_label.unshift(label.new(bar_index, open, h2_text, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if not t_h2 and h2_line.size() > 0
if not h2_co
if not check_open(h2_line.get(0), h2_label.get(0))
h2_label.get(0).set_x(bar_index)
else
h2_co := true
if use_h3
if t_h3 and not t_h3[1]
h3_co := false
h3_line.unshift(line.new(bar_index, open, bar_index, open, style = h_style, width = h_width, color = h3_color))
h3_label.unshift(label.new(bar_index, open, h3_text, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if not t_h3 and h3_line.size() > 0
if not h3_co
if not check_open(h3_line.get(0), h3_label.get(0))
h3_label.get(0).set_x(bar_index)
else
h3_co := true
if use_h4
if t_h4 and not t_h4[1]
h4_co := false
h4_line.unshift(line.new(bar_index, open, bar_index, open, style = h_style, width = h_width, color = h4_color))
h4_label.unshift(label.new(bar_index, open, h4_text, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if not t_h4 and h4_line.size() > 0
if not h4_co
if not check_open(h4_line.get(0), h4_label.get(0))
h4_label.get(0).set_x(bar_index)
else
h4_co := true
// DWM - Separators
if ds
if d_o != d_o[1]
d_sep_line.unshift(line.new(bar_index, high, bar_index, low, style = dwm_style, width = dwm_width, extend = extend.both, color = d_color))
if ws
if w_o != w_o[1]
w_sep_line.unshift(line.new(bar_index, high, bar_index, low, style = dwm_style, width = dwm_width, extend = extend.both, color = w_color))
if ms
if m_o != m_o[1]
m_sep_line.unshift(line.new(bar_index, high, bar_index, low, style = dwm_style, width = dwm_width, extend = extend.both, color = m_color))
// DWM - Open Lines
if show_d_open
if d_o != d_o[1]
d_line.unshift(line.new(bar_index, d_o, bar_index, d_o, style = dwm_style, width = dwm_width, color = d_color))
d_label.unshift(label.new(bar_index, d_o, d_open_str, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if d_line.size() > 0
if not check_open(d_line.get(0), d_label.get(0))
d_label.get(0).set_x(bar_index)
if show_w_open
if w_o != w_o[1]
w_line.unshift(line.new(bar_index, w_o, bar_index, w_o, style = dwm_style, width = dwm_width, color = w_color))
w_label.unshift(label.new(bar_index, w_o, w_open_str, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if w_line.size() > 0
if not check_open(w_line.get(0), w_label.get(0))
w_label.get(0).set_x(bar_index)
if show_m_open
if m_o != m_o[1]
m_line.unshift(line.new(bar_index, m_o, bar_index, m_o, style = dwm_style, width = dwm_width, color = m_color))
m_label.unshift(label.new(bar_index, m_o, m_open_str, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if m_line.size() > 0
if not check_open(m_line.get(0), m_label.get(0))
m_label.get(0).set_x(bar_index)
new_dow_time = dow_xloc == 'Midday' ? time - timeframe.in_seconds("D") / 2 * 1000 : time
new_day = dayofweek(new_dow_time, gmt_tz) != dayofweek(new_dow_time, gmt_tz)[1]
dow_top = dow_yloc == 'Top'
monday = "MONDAY"
tuesday = "TUESDAY"
wednesday = "WEDNESDAY"
thursday = "THURSDAY"
friday = "FRIDAY"
plotchar(dow_labels and timeframe.isintraday and dayofweek(new_dow_time, gmt_tz) == 2 and new_day, location = dow_top ? location.top : location.bottom, char = "", textcolor = dow_color, text = monday)
plotchar(dow_labels and timeframe.isintraday and dayofweek(new_dow_time, gmt_tz) == 3 and new_day, location = dow_top ? location.top : location.bottom, char = "", textcolor = dow_color, text = tuesday)
plotchar(dow_labels and timeframe.isintraday and dayofweek(new_dow_time, gmt_tz) == 4 and new_day, location = dow_top ? location.top : location.bottom, char = "", textcolor = dow_color, text = wednesday)
plotchar(dow_labels and timeframe.isintraday and dayofweek(new_dow_time, gmt_tz) == 5 and new_day, location = dow_top ? location.top : location.bottom, char = "", textcolor = dow_color, text = thursday)
plotchar(dow_labels and timeframe.isintraday and dayofweek(new_dow_time, gmt_tz) == 6 and new_day, location = dow_top ? location.top : location.bottom, char = "", textcolor = dow_color, text = friday)
check_array(as_hi_line)
check_array(as_lo_line)
check_array(as_hi_label)
check_array(as_lo_label)
check_array(as_box)
check_array(lo_hi_line)
check_array(lo_lo_line)
check_array(lo_hi_label)
check_array(lo_lo_label)
check_array(lo_box)
check_array(na_hi_line)
check_array(na_lo_line)
check_array(na_hi_label)
check_array(na_lo_label)
check_array(na_box)
check_array(nl_hi_line)
check_array(nl_lo_line)
check_array(nl_hi_label)
check_array(nl_lo_label)
check_array(nl_box)
check_array(np_hi_line)
check_array(np_lo_line)
check_array(np_hi_label)
check_array(np_lo_label)
check_array(np_box)
check_array(v1_line)
check_array(v2_line)
check_array(v3_line)
check_array(v4_line)
check_array(h1_line)
check_array(h2_line)
check_array(h3_line)
check_array(h4_line)
check_array(h1_label)
check_array(h2_label)
check_array(h3_label)
check_array(h4_label)
if not ds_unlimited
check_array(d_sep_line)
check_array(d_line)
check_array(d_label)
if not ws_unlimited
check_array(w_sep_line)
check_array(w_line)
check_array(w_label)
if not ms_unlimited
check_array(m_sep_line)
check_array(m_line)
check_array(m_label)
// ---------------------------------------- Core Logic -------------------------------------------------- |
Banana RSI | https://www.tradingview.com/script/wXeAToLN-Banana-RSI/ | SamRecio | https://www.tradingview.com/u/SamRecio/ | 47 | 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/
// © SamRecio
//@version=5
indicator(title="Banana RSI", shorttitle="🍌 RSI", precision=2)
rsi_len = input.int(14, minval=1, title="RSI Length")
f_len = input.int(9,minval = 1, title = "Fast Reg. Length")
s_len = input.int(21,minval = 1, title = "Slow Reg. Length")
rsi = ta.rsi(close,rsi_len)
linreg1 = ta.linreg(rsi,s_len,0)
linreg2 = ta.linreg(rsi,f_len,0)
plot(rsi, title = "RSI", color= #40311c, editable = true)
plot(linreg1, title = "Slow Regression", color = #ffffcc)
plot(linreg2, title = "Fast Regression", color = #ffff00)
avg = ta.cum(rsi) / bar_index
high_avg = ta.cum(rsi>avg?rsi:0) / ta.cum(rsi>avg?1:0)
low_avg = ta.cum(rsi<avg?rsi:0) / ta.cum(rsi<avg?1:0)
dash = (bar_index/2 - math.floor(bar_index/2)) > 0 // is true every other bar to alternate coloring for avg lines
plot(high_avg, title = "High_Avg", color = dash?#C0C0C0:color.new(#C0C0C0, 100))
plot(avg, title = "Avg", color= dash?color.new(#C0C0C0, 100):color.new(#C0C0C0, 50))
plot(low_avg, title = "Low_Avg", color = dash?#C0C0C0:color.new(#C0C0C0, 100)) |
Moving Average Candles | https://www.tradingview.com/script/zSn3xkjX-Moving-Average-Candles/ | EsIstTurnt | https://www.tradingview.com/u/EsIstTurnt/ | 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/
// © EsIstTurnt
//@version=5
indicator("Moving Average Candles",overlay=true)
t_Body = input.int(95,"Body Transparency" ,0,100,5,group="Transparency")// \
t_Border= input.int(70,"Border Transparency" ,0,100,5,group="Transparency")// ----Candle Transparency Settings
t_Wick = input.int(100,"Wick Transparency" ,0,100,5,group="Transparency")// /
maType = input.string("ALMA","Average Type",["SMA","EMA","WMA","RMA","HMA","VWMA","ALMA","MED","LRC"],group="Inputs")// Averaging method selection
len1 = input.int(16 ,"Length #1",1,group="Inputs")// \
len2 = input.int(32 ,"Length #2",1,group="Inputs")// \
len3 = input.int(64 ,"Length #3",1,group="Inputs")// \____ Lengths to use for Moving Averages
len4 = input.int(96 ,"Length #4",1,group="Inputs")// /
len5 = input.int(128,"Length #5",1,group="Inputs")// /
len6 = input.int(160,"Length #6",1,group="Inputs")// /
useClose= input.bool(false,"Draw each candle from MA to close instead of sequential MA")//Alternative Candle plotting style because why not
o= input.float(1.0 ,"Offset",tooltip="Relevant only if maType == LRC or ALMA",group="Inputs")//Float offset value for ALMA/LRC
f= math.round(o)// Round it for use in LRC calculation
s= input.float(3.0 ,"Sigma" ,tooltip="Relevant only if maType == ALMA",group="Inputs")// Float sigma value for ALMA
maCandles(l1,l2,l3,l4,l5,l6,src=close,type)=>
[ma1,ma2,ma3,ma4,ma5,ma6] = switch type//
"SMA" => [ta.sma (src,l1) ,ta.sma (src,l2) ,ta.sma (src,l3) ,ta.sma (src,l4) ,ta.sma (src,l5) ,ta.sma (src,l6) ]// \
"EMA" => [ta.ema (src,l1) ,ta.ema (src,l2) ,ta.ema (src,l3) ,ta.ema (src,l4) ,ta.ema (src,l5) ,ta.ema (src,l6) ]// \
"WMA" => [ta.wma (src,l1) ,ta.wma (src,l2) ,ta.wma (src,l3) ,ta.wma (src,l4) ,ta.wma (src,l5) ,ta.wma (src,l6) ]// \
"RMA" => [ta.sma (src,l1) ,ta.sma (src,l2) ,ta.sma (src,l3) ,ta.sma (src,l4) ,ta.sma (src,l5) ,ta.sma (src,l6) ]// \
"HMA" => [ta.ema (src,l1) ,ta.ema (src,l2) ,ta.ema (src,l3) ,ta.ema (src,l4) ,ta.ema (src,l5) ,ta.ema (src,l6) ]// ---- Get the raw MA value for each length
"VWMA" => [ta.vwma (src,l1) ,ta.vwma (src,l2) ,ta.vwma (src,l3) ,ta.vwma (src,l4) ,ta.vwma (src,l5) ,ta.vwma (src,l6) ]// /
"ALMA" => [ta.alma (src,l1,o,s),ta.alma (src,l2,o,s),ta.alma (src,l3,o,s),ta.alma (src,l4,o,s),ta.alma (src,l5,o,s),ta.alma (src,l6,o,s)]// /
"MED" => [ta.median(src,l1) ,ta.median(src,l2) ,ta.median(src,l3) ,ta.median(src,l4) ,ta.median(src,l5) ,ta.median(src,l6) ]// /
"LRC" => [ta.linreg(src,l1,f) ,ta.linreg(src,l2,f) ,ta.linreg(src,l3,f) ,ta.linreg(src,l4,f) ,ta.linreg(src,l5,f) ,ta.linreg(src,l6,f) ]// /
ma1_=useClose?close:ma1// \
ma2_=useClose?close:ma2// \
ma3_=useClose?close:ma3// \____If bool "useClose" is true swap out the ma value with the close value
ma4_=useClose?close:ma4// /
ma5_=useClose?close:ma5// /
ma6_=useClose?close:ma6// /
[c1o,c1h,c1l,c1c]= request.security(syminfo.ticker,timeframe.period,[ma1,math.max(ma1,close),math.min(ma1,close),close])// \
[c2o,c2h,c2l,c2c]= request.security(syminfo.ticker,timeframe.period,[ma2,math.max(ma2,ma1_),math.min(ma2,ma1_),ma1_] )// \
[c3o,c3h,c3l,c3c]= request.security(syminfo.ticker,timeframe.period,[ma3,math.max(ma3,ma2_),math.min(ma3,ma2_),ma2_] )// \____Get "OHLC" data as a tuple via request.security using the values above rather than the standard open,high,low,close
[c4o,c4h,c4l,c4c]= request.security(syminfo.ticker,timeframe.period,[ma4,math.max(ma4,ma3_),math.min(ma4,ma3_),ma3_] )// /
[c5o,c5h,c5l,c5c]= request.security(syminfo.ticker,timeframe.period,[ma5,math.max(ma5,ma4_),math.min(ma5,ma4_),ma4_] )// /
[c6o,c6h,c6l,c6c]= request.security(syminfo.ticker,timeframe.period,[ma6,math.max(ma6,ma5_),math.min(ma6,ma5_),ma5_] )// /
[c1o,c1h,c1l,c1c,c2o,c2h,c2l,c2c,c3o,c3h,c3l,c3c,c4o,c4h,c4l,c4c,c5o,c5h,c5l,c5c,c6o,c6h,c6l,c6c]// Return All of the requested data as tuple
[c1o,c1h,c1l,c1c,c2o,c2h,c2l,c2c,c3o,c3h,c3l,c3c,c4o,c4h,c4l,c4c,c5o,c5h,c5l,c5c,c6o,c6h,c6l,c6c]=maCandles(len1,len2,len3,len4,len5,len6,close,maType) // Use "maCandles()" function defined above with user inputs to get the data for plotting
upCol=input.color(#acfb00)//Color if ma1,2,3,etc > ma2,3,4,etc
dnCol=input.color(#ff0000)//Color if ma1,2,3,etc < ma2,3,4,etc
color(o,c,t=85)=>o<c?color.new(upCol,t):color.new(dnCol,t)//Function for coloring
plotcandle(c1o,c1h,c1l,c1c,"MA1-->(Close) ",color=color(c1o,c1c,t_Body),bordercolor=color(c1o,c1c,t_Border),wickcolor=color(c1o,c1c,t_Wick),display = display.pane)// \
plotcandle(c2o,c2h,c2l,c2c,"MA2-->( MA1 or Close)",color=color(c2o,c2c,t_Body),bordercolor=color(c2o,c2c,t_Border),wickcolor=color(c2o,c2c,t_Wick),display = display.pane)// \
plotcandle(c3o,c3h,c3l,c3c,"MA3-->( MA2 or Close)",color=color(c3o,c3c,t_Body),bordercolor=color(c3o,c3c,t_Border),wickcolor=color(c3o,c3c,t_Wick),display = display.pane)// \____ Now plot each candle
plotcandle(c4o,c4h,c4l,c4c,"MA4-->( MA3 or Close)",color=color(c4o,c4c,t_Body),bordercolor=color(c4o,c4c,t_Border),wickcolor=color(c4o,c4c,t_Wick),display = display.pane)// /
plotcandle(c5o,c5h,c5l,c5c,"MA5-->( MA4 or Close)",color=color(c5o,c5c,t_Body),bordercolor=color(c5o,c5c,t_Border),wickcolor=color(c5o,c5c,t_Wick),display = display.pane)// /
plotcandle(c6o,c6h,c6l,c6c,"MA6-->( MA5 or Close)",color=color(c6o,c6c,t_Body),bordercolor=color(c6o,c6c,t_Border),wickcolor=color(c6o,c6c,t_Wick),display = display.pane)// / |
Yearly High & Low | https://www.tradingview.com/script/78yc1opY-Yearly-High-Low/ | SFR6 | https://www.tradingview.com/u/SFR6/ | 66 | 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/
// © Safxxr
//@version=5
indicator("Yearly High & Low", overlay=true)
var start_year = input.int(2017, "Starting Year")
var end_year = input.int(2022, "Ending Year")
var show_high = input.bool(true, "Show Highs")
var show_low = input.bool(true, "Show Lows")
var show_price = input.bool(true, "Show Price")
var high_color = input(color.new(color.lime, 0), "High Colour")
var low_color = input(color.new(color.red, 0), "Low Colour")
var label_font_color = input(color.rgb(255, 255, 255), "Label Colour") // New input for label font color
var current_high = float(0)
var current_low = float(0)
var hl = line.new(bar_index, current_high, bar_index + 1, current_high, extend=extend.right, color=high_color)
var ll = line.new(bar_index, current_low, bar_index + 1, current_low, extend=extend.right, color=low_color)
var y = year(time)
if start_year > year(time) or year(time) > end_year
line.delete(hl)
line.delete(ll)
var hlabel_array = array.new_label(na)
var llabel_array = array.new_label(na)
if high > line.get_y1(hl)
current_high := high
line.set_y1(hl, current_high)
line.set_y2(hl, current_high)
line.set_x1(hl, bar_index)
line.set_x2(hl, bar_index + 1)
if low < line.get_y1(ll)
current_low := low
line.set_y1(ll, current_low)
line.set_y2(ll, current_low)
line.set_x1(ll, bar_index)
line.set_x2(ll, bar_index + 1)
if year(time) > y
label_year = str.tostring(y)
label_high = show_price ? "$" + str.tostring(current_high) : ""
label_low = show_price ? "$" + str.tostring(current_low) : ""
high_label = label_year + " - " + label_high
low_label = label_year + " - " + label_low
hlabel = label.new(bar_index, y=current_high, text=high_label, style=label.style_none, textcolor=label_font_color) // Use label_font_color for font color
llabel = label.new(bar_index, y=current_low, text=low_label, style=label.style_none, textcolor=label_font_color) // Use label_font_color for font color
if start_year >= year(time) or year(time) > end_year
label.delete(hlabel)
label.delete(llabel)
else
array.push(hlabel_array, hlabel)
array.push(llabel_array, llabel)
y := year(time)
current_high := high
current_low := low
hl := line.new(bar_index, current_high, bar_index + 1, current_high, extend=extend.right, color=high_color)
ll := line.new(bar_index, current_low, bar_index + 1, current_low, extend=extend.right, color=low_color)
if not show_low
line.delete(ll)
if not show_high
line.delete(hl)
if barstate.islast
label_year = str.tostring(y)
label_high = show_price ? "$" + str.tostring(current_high) : ""
label_low = show_price ? "$" + str.tostring(current_low) : ""
high_label = label_year + " - " + label_high
low_label = label_year + " - " + label_low
hlabel = label.new(bar_index, y=current_high, text=high_label, style=label.style_none, textcolor=label_font_color) // Use label_font_color for font color
llabel = label.new(bar_index, y=current_low, text=low_label, style=label.style_none, textcolor=label_font_color) // Use label_font_color for font color
if start_year >= year(time) or year(time) > end_year
label.delete(hlabel)
label.delete(llabel)
else
array.push(hlabel_array, hlabel)
array.push(llabel_array, llabel)
if start_year > year(time) or year(time) > end_year
line.delete(hl)
for i in hlabel_array
if show_high
label.set_x(i, bar_index + 10)
else
label.delete(i)
for i in llabel_array
if show_low
label.set_x(i, bar_index + 10)
else
label.delete(i)
|
ATR Momentum [QuantVue] | https://www.tradingview.com/script/ycjeadf1-ATR-Momentum-QuantVue/ | QuantVue | https://www.tradingview.com/u/QuantVue/ | 77 | 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/
// © QuantVue
//@version=5
indicator("ATR Momentum [QuantVue]", overlay = false)
//inputs
atr1Len = input.int(5, 'Short ATR Length')
atr2Len = input.int(20, 'Long ATR Length')
atrMult = input.float(1.0, 'Multiplier', minval = .25, step = .25)
//ATR
shortATR = ta.atr(atr1Len)
longATR = ta.atr(atr2Len)
//condition
expanding = shortATR > (longATR * atrMult)
//styling
fillColor = color.new(color.white,100)
fillColor := expanding ? color.green : not expanding ? color.red : fillColor
//plots
shortPlot = plot(shortATR, 'Short ATR', color = color.black, display = display.pane)
longPlot = plot(longATR, 'Long ATR', color = color.black, display = display.pane)
fill(shortPlot, longPlot, fillColor)
//alerts
alertcondition(expanding, 'Increasing Momentum', '{{ticker}} has increasing momentum') |
Volume Z-Score [SuperJump] | https://www.tradingview.com/script/9jfqYg87-Volume-Z-Score-SuperJump/ | SuperJump | https://www.tradingview.com/u/SuperJump/ | 167 | 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/
// © SuperJump
//@version=4
study("Volume Z-Score [SuperJump]",max_bars_back=5000, format = format.volume)
len = input(1000, "Z-score Length")
isVolume = input(true, "Bar is Volume (false : Z-Score)")
alertZscore = input(3, "Alert Z-Score")
score1 = input(6.0, "1st Level - Highest trading volume")
score2 = input(4.5, "2nd Level - 2nd highest trading volume")
score3 = input(3, "3rd Level - 3rd highest trading volume")
score4 = input(1.5, "4th Level - 4th highest trading volume")
score5 = input(0, "5th Level - 5th highest trading volume")
volumeData = volume
avgVolume = sma(volumeData, len)
stdDevVolume = stdev(volumeData, len)
zScore = (volumeData - avgVolume) / stdDevVolume
colorPalette = array.new_color(6)
array.set(colorPalette, 0, color.red)
array.set(colorPalette, 1, color.orange)
array.set(colorPalette, 2, color.yellow)
array.set(colorPalette, 3, color.green)
array.set(colorPalette, 4, color.gray)
array.set(colorPalette, 5, color.navy)
zScoreColor = zScore >= score1 ? array.get(colorPalette,0) :
zScore >= score2 ? array.get(colorPalette,1) :
zScore >= score3 ? array.get(colorPalette,2) :
zScore >= score4 ? array.get(colorPalette,3) :
zScore >= score5 ? array.get(colorPalette,4) :
array.get(colorPalette,5)
plot(isVolume? volume :zScore, style=plot.style_columns, color=zScoreColor, title="Volume Z-Score")
alertcondition(zScore >= alertZscore, title="Volume Alert", message = "Volume Zscore Alert" ) |
QFL Screener [ ZCrypto ] | https://www.tradingview.com/script/39ARY3Ax-QFL-Screener-ZCrypto/ | TZack88 | https://www.tradingview.com/u/TZack88/ | 140 | 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/
// © TZack88
//@version=5
indicator("QFL Screener [ ZCrypto ]",shorttitle = "QFL Screener",overlay = true)
string table_name ='QFL Screener [ZCrypto]'
string table_Group = "Table"
string settings_Group = "Core Settings"
var float base = na
var float lowrange = na
bool buySignal = false
bool buySignal2 = false
int ra = 80
float savezone = 2.0
float signal = 0.0
float szone = 0.0
float rangeHigh = ta.highest(high, ra)
float rangeLow = ta.lowest(low, ra)
float stochValue = ta.sma(ta.stoch(close, high, low, 14), 3)
int CheckThreshold = input.int(8,group = settings_Group,inline = "1",
tooltip = "set the percentage threshold for checking the higher peak"
)
bool show_table = input.bool(true,title= "Show Table ❓",inline = "002",group = table_Group)
string position = input.string("Top Right",
options = ["Middle Right","Top Center","Top Right","Middle Left","Middle Center","Bottom Left","Bottom Center","Bottom Right"],
title = 'Position',
inline = "002",
group = table_Group
)
color textcolos = input.color(color.rgb(255, 186, 75),title = "Text Color",inline = "002",group = table_Group)
string freq = input.string("once per bar close",
options = ["freq all","once per bar","once per bar close"],
title = 'Alert frequency',
inline = "002",
group = "Alerts"
)
bool backtest = input.bool(false,"Activate Backtesting❓",group = "Testing",inline = "001")
int testvalue = input.int(100,group = "Testing",inline = "001",title = "Value")
// Arrays
array<string> names = array.new_string(0)
array<bool> USEbool = array.new_bool(0)
array<bool> qfl_arr = array.new_bool(0)
//----Alerts ----{
alert_freq() =>
switch freq
"freq all" => alert.freq_all
"once per bar" => alert.freq_once_per_bar
"once per bar close" => alert.freq_once_per_bar_close
//----Table ----{
table_position() =>
switch position
"Middle Right" => position.middle_right
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
var summary_table = table.new(table_position(), 15, 50, frame_color=color.rgb(241, 124, 8), frame_width=2,border_width = 2)
change_color(con)=>
con ? color.rgb(0, 149, 77) : color.rgb(152, 46, 46)
table_cell(table,_row,in1,in2,coloz)=>
text_color = show_table ? color.rgb(210, 210, 210) : color.black
table.cell(table, 0, _row, in1, text_color=text_color,bgcolor = color.rgb(120, 123, 134, 38))
table.cell(table, 1, _row, str.tostring(in2), text_color=text_color,bgcolor = change_color(coloz))
table_cell2(table,_row,in1,in2,coloz)=>
text_color = show_table ? color.rgb(210, 210, 210) : color.black
table.cell(table, 3, _row, in1, text_color=text_color,bgcolor = color.rgb(120, 123, 134, 38))
table.cell(table, 4, _row, str.tostring(in2), text_color=text_color,bgcolor = change_color(coloz))
//-- }
////////////
// SYMBOLS //
u01 = input.bool(true, title = "", group = 'Symbols', inline = 's01')
u02 = input.bool(true, title = "", group = 'Symbols', inline = 's02')
u03 = input.bool(true, title = "", group = 'Symbols', inline = 's03')
u04 = input.bool(true, title = "", group = 'Symbols', inline = 's04')
u05 = input.bool(true, title = "", group = 'Symbols', inline = 's05')
u06 = input.bool(true, title = "", group = 'Symbols', inline = 's06')
u07 = input.bool(true, title = "", group = 'Symbols', inline = 's07')
u08 = input.bool(true, title = "", group = 'Symbols', inline = 's08')
u09 = input.bool(true, title = "", group = 'Symbols', inline = 's09')
u10 = input.bool(true, title = "", group = 'Symbols', inline = 's10')
u11 = input.bool(true, title = "", group = 'Symbols', inline = 's11')
u12 = input.bool(true, title = "", group = 'Symbols', inline = 's12')
u13 = input.bool(true, title = "", group = 'Symbols', inline = 's13')
u14 = input.bool(true, title = "", group = 'Symbols', inline = 's14')
u15 = input.bool(true, title = "", group = 'Symbols', inline = 's15')
u16 = input.bool(true, title = "", group = 'Symbols', inline = 's16')
u17 = input.bool(true, title = "", group = 'Symbols', inline = 's17')
u18 = input.bool(true, title = "", group = 'Symbols', inline = 's18')
u19 = input.bool(true, title = "", group = 'Symbols', inline = 's19')
u20 = input.bool(true, title = "", group = 'Symbols', inline = 's20')
u21 = input.bool(true, title = "", group = 'Symbols', inline = 's21')
u22 = input.bool(true, title = "", group = 'Symbols', inline = 's22')
u23 = input.bool(true, title = "", group = 'Symbols', inline = 's23')
u24 = input.bool(true, title = "", group = 'Symbols', inline = 's24')
u25 = input.bool(true, title = "", group = 'Symbols', inline = 's25')
u26 = input.bool(true, title = "", group = 'Symbols', inline = 's26')
u27 = input.bool(true, title = "", group = 'Symbols', inline = 's27')
u28 = input.bool(true, title = "", group = 'Symbols', inline = 's28')
u29 = input.bool(true, title = "", group = 'Symbols', inline = 's29')
u30 = input.bool(true, title = "", group = 'Symbols', inline = 's30')
u31 = input.bool(true, title = "", group = 'Symbols', inline = 's31')
u32 = input.bool(true, title = "", group = 'Symbols', inline = 's32')
u33 = input.bool(true, title = "", group = 'Symbols', inline = 's33')
u34 = input.bool(true, title = "", group = 'Symbols', inline = 's34')
u35 = input.bool(true, title = "", group = 'Symbols', inline = 's35')
u36 = input.bool(true, title = "", group = 'Symbols', inline = 's36')
u37 = input.bool(true, title = "", group = 'Symbols', inline = 's37')
u38 = input.bool(true, title = "", group = 'Symbols', inline = 's38')
u39 = input.bool(true, title = "", group = 'Symbols', inline = 's39')
u40 = input.bool(true, title = "", group = 'Symbols', inline = 's40')
s01 = input.symbol('XRPUSDT', group = 'Symbols', inline = 's01',title = "Symbol 1")
s02 = input.symbol('BTCUSDT', group = 'Symbols', inline = 's02',title = "Symbol 2")
s03 = input.symbol('DOGEUSDT', group = 'Symbols', inline = 's03',title = "Symbol 3")
s04 = input.symbol('BNBUSDT', group = 'Symbols', inline = 's04',title = "Symbol 4")
s05 = input.symbol('ETHUSDT', group = 'Symbols', inline = 's05',title = "Symbol 5")
s06 = input.symbol('ADAUSDT', group = 'Symbols', inline = 's06',title = "Symbol 6")
s07 = input.symbol('XRPBTC', group = 'Symbols', inline = 's07',title = "Symbol 7")
s08 = input.symbol('DOGEBTC', group = 'Symbols', inline = 's08',title = "Symbol 8")
s09 = input.symbol('TRXUSDT', group = 'Symbols', inline = 's09',title = "Symbol 9")
s10 = input.symbol('BTCBUSD', group = 'Symbols', inline = 's10',title = "Symbol 10")
s11 = input.symbol('ETHBUSD', group = 'Symbols', inline = 's11',title = "Symbol 11")
s12 = input.symbol('BNBBUSD', group = 'Symbols', inline = 's12',title = "Symbol 12")
s13 = input.symbol('VETUSDT', group = 'Symbols', inline = 's13',title = "Symbol 13")
s14 = input.symbol('ETHBTC', group = 'Symbols', inline = 's14',title = "Symbol 14")
s15 = input.symbol('BNBBTC', group = 'Symbols', inline = 's15',title = "Symbol 15")
s16 = input.symbol('EOSUSDT', group = 'Symbols', inline = 's16',title = "Symbol 16")
s17 = input.symbol('XLMUSDT', group = 'Symbols', inline = 's17',title = "Symbol 17")
s18 = input.symbol('LTCUSDT', group = 'Symbols', inline = 's18',title = "Symbol 18")
s19 = input.symbol('XRPBUSD', group = 'Symbols', inline = 's19',title = "Symbol 19")
s20 = input.symbol('WINUSDT', group = 'Symbols', inline = 's20',title = "Symbol 20")
s21 = input.symbol('DOTUSDT', group = 'Symbols', inline = 's21',title = "Symbol 21")
s22 = input.symbol('BTTUSDT', group = 'Symbols', inline = 's22',title = "Symbol 22")
s23 = input.symbol('BCHUSDT', group = 'Symbols', inline = 's23',title = "Symbol 23")
s24 = input.symbol('ADABTC', group = 'Symbols', inline = 's24',title = "Symbol 24")
s25 = input.symbol('IOSTUSDT', group = 'Symbols', inline = 's25',title = "Symbol 25")
s26 = input.symbol('CHZUSDT', group = 'Symbols', inline = 's26',title = "Symbol 26")
s27 = input.symbol('LINKUSDT', group = 'Symbols', inline = 's27',title = "Symbol 27")
s28 = input.symbol('TRXBTC', group = 'Symbols', inline = 's28',title = "Symbol 28")
s29 = input.symbol('DOGEBUSD', group = 'Symbols', inline = 's29',title = "Symbol 29")
s30 = input.symbol('BTCEUR', group = 'Symbols', inline = 's30',title = "Symbol 30")
s31 = input.symbol('FILUSDT', group = 'Symbols', inline = 's31',title = "Symbol 31")
s32 = input.symbol('HOTUSDT', group = 'Symbols', inline = 's32',title = "Symbol 32")
s33 = input.symbol('SXPUSDT', group = 'Symbols', inline = 's33',title = "Symbol 33")
s34 = input.symbol('ADABUSD', group = 'Symbols', inline = 's34',title = "Symbol 34")
s35 = input.symbol('RVNUSDT', group = 'Symbols', inline = 's35',title = "Symbol 35")
s36 = input.symbol('ATOMUSDT', group = 'Symbols', inline = 's36',title = "Symbol 36")
s37 = input.symbol('XRPBNB', group = 'Symbols', inline = 's37',title = "Symbol 37")
s38 = input.symbol('LTCBTC', group = 'Symbols', inline = 's38',title = "Symbol 38")
s39 = input.symbol('IOSTBTC', group = 'Symbols', inline = 's39',title = "Symbol 39")
s40 = input.symbol('GRTUSDT', group = 'Symbols', inline = 's40',title = "Symbol 40")
get_data(pair) =>
[r_high,r_low,lows] = request.security(pair,timeframe.period, [rangeHigh,rangeLow,low])
check_for_qfl(pair) =>
[highz,lowz,lows] = get_data(pair)
rangez = math.abs(lowz - highz) /lowz * 100
if (lows == lowz) and rangez >= CheckThreshold
szone == math.abs((lows[1] - lows) /lows[1]) * 100
if szone >= savezone
false
else
true
// Security call
qfl01 = check_for_qfl(s01)
qfl02 = check_for_qfl(s02)
qfl03 = check_for_qfl(s03)
qfl04 = check_for_qfl(s04)
qfl05 = check_for_qfl(s05)
qfl06 = check_for_qfl(s06)
qfl07 = check_for_qfl(s07)
qfl08 = check_for_qfl(s08)
qfl09 = check_for_qfl(s09)
qfl10 = check_for_qfl(s10)
qfl11 = check_for_qfl(s11)
qfl12 = check_for_qfl(s12)
qfl13 = check_for_qfl(s13)
qfl14 = check_for_qfl(s14)
qfl15 = check_for_qfl(s15)
qfl16 = check_for_qfl(s16)
qfl17 = check_for_qfl(s17)
qfl18 = check_for_qfl(s18)
qfl19 = check_for_qfl(s19)
qfl20 = check_for_qfl(s20)
qfl21 = check_for_qfl(s21)
qfl22 = check_for_qfl(s22)
qfl23 = check_for_qfl(s23)
qfl24 = check_for_qfl(s24)
qfl25 = check_for_qfl(s25)
qfl26 = check_for_qfl(s26)
qfl27 = check_for_qfl(s27)
qfl28 = check_for_qfl(s28)
qfl29 = check_for_qfl(s29)
qfl30 = check_for_qfl(s30)
qfl31 = check_for_qfl(s31)
qfl32 = check_for_qfl(s32)
qfl33 = check_for_qfl(s33)
qfl34 = check_for_qfl(s34)
qfl35 = check_for_qfl(s35)
qfl36 = check_for_qfl(s36)
qfl37 = check_for_qfl(s37)
qfl38 = check_for_qfl(s38)
qfl39 = check_for_qfl(s39)
qfl40 = check_for_qfl(s40)
// Lets add symbols to array for table and alerts
array.push(names, syminfo.ticker(s01))
array.push(names, syminfo.ticker(s02))
array.push(names, syminfo.ticker(s03))
array.push(names, syminfo.ticker(s04))
array.push(names, syminfo.ticker(s05))
array.push(names, syminfo.ticker(s06))
array.push(names, syminfo.ticker(s07))
array.push(names, syminfo.ticker(s08))
array.push(names, syminfo.ticker(s09))
array.push(names, syminfo.ticker(s10))
array.push(names, syminfo.ticker(s11))
array.push(names, syminfo.ticker(s12))
array.push(names, syminfo.ticker(s13))
array.push(names, syminfo.ticker(s14))
array.push(names, syminfo.ticker(s15))
array.push(names, syminfo.ticker(s16))
array.push(names, syminfo.ticker(s17))
array.push(names, syminfo.ticker(s18))
array.push(names, syminfo.ticker(s19))
array.push(names, syminfo.ticker(s20))
array.push(names, syminfo.ticker(s21))
array.push(names, syminfo.ticker(s22))
array.push(names, syminfo.ticker(s23))
array.push(names, syminfo.ticker(s24))
array.push(names, syminfo.ticker(s25))
array.push(names, syminfo.ticker(s26))
array.push(names, syminfo.ticker(s27))
array.push(names, syminfo.ticker(s28))
array.push(names, syminfo.ticker(s29))
array.push(names, syminfo.ticker(s30))
array.push(names, syminfo.ticker(s31))
array.push(names, syminfo.ticker(s32))
array.push(names, syminfo.ticker(s33))
array.push(names, syminfo.ticker(s34))
array.push(names, syminfo.ticker(s35))
array.push(names, syminfo.ticker(s36))
array.push(names, syminfo.ticker(s37))
array.push(names, syminfo.ticker(s38))
array.push(names, syminfo.ticker(s39))
array.push(names, syminfo.ticker(s40))
// Lets add bools to array for table and alerts
array.push(USEbool, u01)
array.push(USEbool, u02)
array.push(USEbool, u03)
array.push(USEbool, u04)
array.push(USEbool, u05)
array.push(USEbool, u06)
array.push(USEbool, u07)
array.push(USEbool, u08)
array.push(USEbool, u09)
array.push(USEbool, u10)
array.push(USEbool, u11)
array.push(USEbool, u12)
array.push(USEbool, u13)
array.push(USEbool, u14)
array.push(USEbool, u15)
array.push(USEbool, u16)
array.push(USEbool, u17)
array.push(USEbool, u18)
array.push(USEbool, u19)
array.push(USEbool, u20)
array.push(USEbool, u21)
array.push(USEbool, u22)
array.push(USEbool, u23)
array.push(USEbool, u24)
array.push(USEbool, u25)
array.push(USEbool, u26)
array.push(USEbool, u27)
array.push(USEbool, u28)
array.push(USEbool, u29)
array.push(USEbool, u30)
array.push(USEbool, u31)
array.push(USEbool, u32)
array.push(USEbool, u33)
array.push(USEbool, u34)
array.push(USEbool, u35)
array.push(USEbool, u36)
array.push(USEbool, u37)
array.push(USEbool, u38)
array.push(USEbool, u39)
array.push(USEbool, u40)
// QFL signal to array for table and alerts
array.push(qfl_arr, qfl01)
array.push(qfl_arr, qfl02)
array.push(qfl_arr, qfl03)
array.push(qfl_arr, qfl04)
array.push(qfl_arr, qfl05)
array.push(qfl_arr, qfl06)
array.push(qfl_arr, qfl07)
array.push(qfl_arr, qfl08)
array.push(qfl_arr, qfl09)
array.push(qfl_arr, qfl10)
array.push(qfl_arr, qfl11)
array.push(qfl_arr, qfl12)
array.push(qfl_arr, qfl13)
array.push(qfl_arr, qfl14)
array.push(qfl_arr, qfl15)
array.push(qfl_arr, qfl16)
array.push(qfl_arr, qfl17)
array.push(qfl_arr, qfl18)
array.push(qfl_arr, qfl19)
array.push(qfl_arr, qfl20)
array.push(qfl_arr, qfl21)
array.push(qfl_arr, qfl22)
array.push(qfl_arr, qfl23)
array.push(qfl_arr, qfl24)
array.push(qfl_arr, qfl25)
array.push(qfl_arr, qfl26)
array.push(qfl_arr, qfl27)
array.push(qfl_arr, qfl28)
array.push(qfl_arr, qfl29)
array.push(qfl_arr, qfl30)
array.push(qfl_arr, qfl31)
array.push(qfl_arr, qfl32)
array.push(qfl_arr, qfl33)
array.push(qfl_arr, qfl34)
array.push(qfl_arr, qfl35)
array.push(qfl_arr, qfl36)
array.push(qfl_arr, qfl37)
array.push(qfl_arr, qfl38)
array.push(qfl_arr, qfl39)
array.push(qfl_arr, qfl40)
// plotshape(conditioin, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
if barstate.islast
if show_table
text_color = show_table ? color.rgb(210, 210, 210) : color.black
table.cell(summary_table, 0, 0, table_name, bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167), color.rgb(240, 141, 71)))
table.cell(summary_table, 1, 0, "", bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167), color.rgb(240, 141, 71)),text_halign = text.align_left)
table.cell(summary_table, 2, 0, "", bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167), color.rgb(240, 141, 71)),text_halign = text.align_left)
table.cell(summary_table, 3, 0, "", bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167), color.rgb(240, 141, 71)),text_halign = text.align_left)
table.cell(summary_table, 4, 0, "", bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167), color.rgb(240, 141, 71)),text_halign = text.align_left)
table.merge_cells(summary_table, 0, 0, 4, 0)
table.cell(summary_table, 0, 1, 'Symbol', bgcolor=color.rgb(120, 123, 134, 38),text_color = textcolos)
table.cell(summary_table, 1, 1, 'Status', bgcolor=color.rgb(120, 123, 134, 38),text_color = textcolos)
table.cell(summary_table, 3, 1, 'Symbol', bgcolor=color.rgb(120, 123, 134, 38),text_color = textcolos)
table.cell(summary_table, 4, 1, 'Status', bgcolor=color.rgb(120, 123, 134, 38),text_color = textcolos)
// first table
for i = 0 to 19
if array.get(USEbool, i)
table_cell(summary_table,(i+1)+ 1 , array.get(names, i),array.get(qfl_arr, i) ? "True" : "False",array.get(qfl_arr, i))
// 2nd table
for i = 20 to 39
if array.get(USEbool, i)
table_cell2(summary_table,(i-19) + 1 , array.get(names, i),array.get(qfl_arr, i) ? "True" : "False",array.get(qfl_arr, i))
// alert function
Alertz()=>
for i = 0 to 39
if array.get(qfl_arr, i)
conditioin = true
alert(message = array.get(names, i) +" Fired QFL Signal",freq = alert_freq())
conditioin
Alert = Alertz()
// plotting --
plot(backtest and Alert ? testvalue : 0,title = "QFL Signal",display = display.none)
plotshape(Alert, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small) |
RSI Momentum Trend | https://www.tradingview.com/script/g6Nyg5kS-RSI-Momentum-Trend/ | TZack88 | https://www.tradingview.com/u/TZack88/ | 798 | 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/
// © TZack88
//@version=5
indicator('RSI Momentum Trend', overlay=true)
// ** ---> Inputs ------------- {
var bool positive = false
var bool negative = false
string RSI_group = "RSI Settings"
string mom_group = "Momentum Vales"
string visual = "Visuals"
int Len2 = input(14,"RSI 1️⃣",inline = "rsi",group = RSI_group)
int pmom = input(65," Positive above",inline = "rsi1",group =RSI_group )
int nmom = input(32,"Negative below",inline = "rsi1",group =RSI_group )
bool showlabels = input(true,"Show Momentum ❓",inline = "001",group =visual )
color p = input(color.rgb(76, 175, 79, 62),"Positive",inline = "001",group =visual )
color n = input(color.rgb(255, 82, 82, 66),"Negative",inline = "001",group =visual )
bool filleshow = input(true,"Show highlighter ❓",inline = "002",group =visual )
color bull = input(color.rgb(76, 175, 79, 62),"Bull",inline = "002",group =visual )
color bear = input(color.rgb(255, 82, 82, 66),"Bear",inline = "002",group =visual )
rsi = ta.rsi(close, Len2)
//------------------- }
// ** ---> Momentums ------------- {
p_mom = rsi[1] < pmom and rsi > pmom and rsi > nmom and ta.change(ta.ema(close,5)) > 0
n_mom = rsi < nmom and ta.change(ta.ema(close,5)) < 0
if p_mom
positive:= true
negative:= false
if n_mom
positive:= false
negative:= true
// ** ---> Entry Conditions ------------- {
a = plot(filleshow ? ta.ema(high,5) : na,display = display.none,editable = false)
b = plot(filleshow ? ta.ema(low,10) : na,style = plot.style_stepline,color = color.red,display = display.none,editable = false)
// fill(a,b,color = color.from_gradient(rsi14,35,pmom,color.rgb(255, 82, 82, 66),color.rgb(76, 175, 79, 64)) )
fill(a,b,color = positive ? bull :bear ,editable = false)
//plotting
pcondition = positive and not positive[1]
ncondition2 = negative and not negative[1]
plotshape(showlabels ? pcondition: na , title="Positive Signal",style=shape.labelup, color=p, location= location.belowbar , size=size.tiny,text= "Positive",textcolor = color.white)
plotshape(showlabels ? ncondition2: na , title="Negative Signal",style=shape.labeldown, color=n, location= location.abovebar , size=size.tiny,text = "Negative",textcolor = color.white)
// Alerts //
alertcondition(pcondition,"Positive Trend")
alertcondition(ncondition2,"Negative Trend")
// |
VIX Monitor [Zero54] | https://www.tradingview.com/script/llghqvFu-VIX-Monitor-Zero54/ | zero54 | https://www.tradingview.com/u/zero54/ | 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/
//@version=5
indicator('VIX Monitor')
ticker = input.string("IN VIX","Monitor",["IN VIX","NIFTY FUT","BANK NIFTY FUT"])
symbol = ticker=="IN VIX"?"INDIAVIX":ticker=="NIFTY FUT"?"NSE:NIFTY1!":ticker=="BANK NIFTY FUT"?"NSE:BANKNIFTY1!":"INDIAVIX"
vix = request.security(symbol, timeframe.period, close)
ma = ta.ema(vix, input.int(20,"EMA Length"))
plot(ma, color=color.new(color.gray, 0),display = display.all - display.price_scale)
v = plot(vix, color=vix > vix[1] ? input.color(color.rgb(243, 194, 33),"Up Color") : input.color(color.rgb(228, 226, 226),"Down Color"), linewidth=2, title='Ticker') |
Moving Average-TREND POWER v2.0-(AS) | https://www.tradingview.com/script/Q2j2g5hb/ | Adam-Szafranski | https://www.tradingview.com/u/Adam-Szafranski/ | 216 | 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/
// © Adam-Szafranski
//@version=5
indicator("Moving Average-TREND POWER v2.0-(AS)",overlay = false)
TT_INFO1 = 'HELLO: \nThis indicator is a waaaay simpler version of my other script - Moving Average-TREND POWER v1.1-(AS). Keep this box always on. \nHOW DOES IT WORK: \nScript counts number of bars below or above selected Moving Average (u can se them by turning PLOT BARS on). Then multiplies number of bars by 0.01 and adds previous value. So in the uptrend indicator will be growing faster with every bar when price is above MA. When MA crosess price Value goes to zero so it shows when the market is ranging. If Cross happens when number of bars is higher than Upper treshold or lower then Lower Treshold indicator will go back to zero only if MA crosses with high in UPtrend and low in DNtrend. If cross happens inside THSs Value will be zero when MA crosses with any type of price source(close,high,low,ohlc4,hl etc.....).This helps to get more crosess in side trend and less resets during a visible trend \nHOW TO SET: \nJust select what type of MA you want to use and Length. Then based on your preference set values of THSs'
TT_INFO2 = 'ADDITIONAL INFORMATION: \n-Script was created and tested on EURUSD 5M. \n-For bigger trends choose slowerMAs and bigger periods and the other way around for short trends (FasterMAs/shorter periods) \n-Below script code you can find not used formulas for calculating indicator value(thanks chat GPT), If you know some pinescript I encourage you to try try them or maybe bulid better ones. Script uses most basic one. \n-Pls give me some feedback/ideas to improve and check out first version. Its way more complicated for no real reason but still worth to take a look'
ma(type, src, len) =>
switch type
'SMA' => ta.sma(src, len)
'EMA' => ta.ema(src, len)
'WMA' => ta.wma(src, len)
'HMA' => ta.hma(src,len)
'RMA' => ta.rma(src,len)
README_INFO = input.bool (true ,'!---!READ ME!---!' ,inline = '0',tooltip = TT_INFO1)
INP_MA1_LEN = input.int (120 ,'MA1_LEN/TYP' ,inline = '1')
INP_MA1_TYP = input.string ('WMA' ,'/' ,inline = '1', options = ['EMA','HMA','WMA','SMA','RMA'])
INP_TSH_UPP = input.float (50 ,'TSH ->UP/DN' ,inline = '2')
INP_TSH_DWN = input.float (-50 ,'/' ,inline = '2')
PLT_TSHOLDS = input.bool (false ,'/' ,inline = '3')
PLT_TRNDNUM = input.bool (false ,'PLOT->TSH/NUMofBARS?' ,inline = '3')
README_MORE = input.bool (false ,'ADDITIONAL INFORMATION' ,inline = '4',tooltip = TT_INFO2)
MA1 = ma(INP_MA1_TYP,close,INP_MA1_LEN)
UP = MA1<close
DN = MA1>close
CROSS_NO_TREND = ta.cross(MA1,close) or ta.cross(MA1,ohlc4) or ta.cross(MA1,hl2) or ta.cross(MA1,high) or ta.cross(MA1,low) or ta.cross(MA1,open) or ta.cross(MA1,hl2) or ta.cross(MA1,hlc3) or ta.cross(MA1,hlcc4)
CROSS_UP_TREND = ta.crossover(MA1[1],high[1]) and MA1>high
CROSS_DN_TREND = ta.crossunder(MA1[1],low[1]) and MA1<low
var TREND_NUM = 0.0
var IND_VALUE = 0.0
GROW_FACTOR = (0.01 * TREND_NUM)
if README_INFO
if UP
TREND_NUM+=1
IND_VALUE:=IND_VALUE+GROW_FACTOR
if DN
TREND_NUM-=1
IND_VALUE:=IND_VALUE+GROW_FACTOR
if TREND_NUM<INP_TSH_UPP and TREND_NUM>INP_TSH_DWN and CROSS_NO_TREND
TREND_NUM:=0
if TREND_NUM>INP_TSH_UPP and CROSS_UP_TREND
TREND_NUM:=0
if TREND_NUM<INP_TSH_DWN and CROSS_DN_TREND
TREND_NUM:=0
if TREND_NUM == 0
IND_VALUE:=0
TRND_P = plot(PLT_TRNDNUM?TREND_NUM:na,'TREND_NUMBERBAR',color.rgb(237, 216, 33))
GROW_P = plot(README_INFO?IND_VALUE:na,'INDICATOR_VALUE',color.orange)
ZERO_P = plot(0,'ZERO',color.gray)
TSHU_P = plot(PLT_TSHOLDS?INP_TSH_UPP:na,'UP',color.gray)
TSHD_P = plot(PLT_TSHOLDS?INP_TSH_DWN:na,'DN',color.gray)
fill(ZERO_P,GROW_P,IND_VALUE>0?color.rgb(85, 188, 88, 72):color.rgb(150, 21, 71, 64))
//plot(MA1)
//GROW_FACTOR = TREND_NUM > 0 ? (0.01 * TREND_NUM * math.sqrt(TREND_NUM))/100 : TREND_NUM < 0 ? (0.01 * TREND_NUM * math.sqrt(-TREND_NUM))/100 : 0
//GROW_FACTOR = (0.01 * TREND_NUM)
//GROW_FACTOR = TREND_NUM > 0 ? math.pow(TREND_NUM, 0.5) : TREND_NUM < 0 ? math.pow(-TREND_NUM, 0.5) : 0
//GROW_FACTOR = TREND_NUM > 0 ? (1 * TREND_NUM * math.sqrt(TREND_NUM))/100 : TREND_NUM < 0 ? (1 * TREND_NUM * math.sqrt(-TREND_NUM))/100 : 0
//GROW_FACTOR = TREND_NUM > 0 ? math.log(TREND_NUM + 1) / 100 : TREND_NUM < 0 ? -math.log(-TREND_NUM + 1) / 100 : 0
|
VWAP angle Trend | https://www.tradingview.com/script/MDxpv6sE-VWAP-angle-Trend/ | TZack88 | https://www.tradingview.com/u/TZack88/ | 107 | 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/
// © TZack88
//@version=5
indicator("VWAP angle",overlay = false)
string CORE = "➞ Main Core Settings 🔸"
float scr = input.source(hlc3,"Source",group = CORE)
int lookback = input.int(title='LookBack', defval=10,group = CORE)
int ATR = input.int(title='ATR Period', defval=14,group = CORE)
Vwap_angle(_src, _lookback) =>
math.todegrees(math.atan((_src[1] - _src[_lookback]) / ta.atr(ATR)))
ang = math.min(math.max(Vwap_angle(ta.vwap(scr), lookback), -100), 100)
Angplot = plot(ang,color = color.from_gradient(ang,-90,70,top_color = #70e1f5,bottom_color = #ffd194),linewidth = 2,title = "V-Angle")
lowBand = hline(-65,color=color.new(color.lime,85),title = "Low Band")
lowerband = hline(-80,color=color.new(color.lime,85),title = "Lower Band")
highband = hline(65,color=color.new(color.red,85),title = "High Band")
higherband = hline(80,color=color.new(color.red,85),title = "Higher Band")
lineplot = plot(65,display = display.none,editable = false)
fill(lowBand,lowerband,color= color.new(#1c4a10, 90))
fill(highband,higherband,color= color.new(#e3332d, 95))
fill(lowBand,highband,65,-65,top_color = color.new(#3F5EFB, 95), bottom_color = color.new(#FC466B, 95))
fill(Angplot, lineplot, -65, -90, top_color = color.new(color.green, 100), bottom_color = color.new(#2ef835, 0),title = "Oversold Fill")
fill(Angplot, lineplot, 100, 65, top_color = color.new(#f52d2d, 5), bottom_color = color.new(#ff5252, 100),title = "Overbought Fill")
// bgcolor(con ? color.new(color.red,85): na ) |
Crypto Aggregated Volume «NoaTrader» | https://www.tradingview.com/script/7q3A0uOy-Crypto-Aggregated-Volume-NoaTrader/ | NoaTrader | https://www.tradingview.com/u/NoaTrader/ | 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/
// © noafarin
//@version=5
indicator("Crypto Aggregated Spot Volume «NoaTrader»","AGG VOL",overlay = false,max_labels_count = 500)
var ma_len = input.int(1000,"Average Length")
var vol_mult = input.float(3,"Multiplier for Label") // 5 for 15m
var avg_method = input.string("SMA","Average Method",["SMA","EMA","HMA"])
var exclude_binance = input.bool(false,"Exclude Binance")
binance_usdt = exclude_binance ? 0 : nz(request.security("BINANCE:"+ syminfo.basecurrency+"USDT","",volume,ignore_invalid_symbol = true))
binance_busd = exclude_binance ? 0 : nz(request.security("BINANCE:"+ syminfo.basecurrency+"BUSD","",volume,ignore_invalid_symbol = true))
binance_fdusd = exclude_binance ? 0 : nz(request.security("BINANCE:"+ syminfo.basecurrency+"FDUSD","",volume,ignore_invalid_symbol = true))
binance_tusd = exclude_binance ? 0 : nz(request.security("BINANCE:"+ syminfo.basecurrency+"TUSD","",volume,ignore_invalid_symbol = true))
bitstamp = nz(request.security("BITSTAMP:"+ syminfo.ticker,"",volume,ignore_invalid_symbol = true))
coinbase = nz(request.security("COINBASE:"+ syminfo.ticker,"",volume,ignore_invalid_symbol = true))
huobi = nz(request.security("HUOBI:"+ syminfo.ticker,"",volume,ignore_invalid_symbol = true))
kraken = nz(request.security("KRAKEN:"+ syminfo.ticker,"",volume,ignore_invalid_symbol = true))
bitfinex = nz(request.security("BITFINEX:"+ syminfo.ticker,"",volume,ignore_invalid_symbol = true))
bybit = nz(request.security("BYBIT:"+ syminfo.ticker,"",volume,ignore_invalid_symbol = true))
okx = nz(request.security("OKX:"+ syminfo.ticker,"",volume,ignore_invalid_symbol = true))
kucoin = nz(request.security("KUCOIN:"+ syminfo.ticker,"",volume,ignore_invalid_symbol = true))
bithumb = nz(request.security("BITHUMB:"+ syminfo.ticker,"",volume,ignore_invalid_symbol = true))
agg_vol = binance_usdt + binance_tusd + binance_fdusd + binance_busd + bitstamp + coinbase + huobi + kraken + bitfinex + bybit + okx + kucoin + bithumb
vol_clr = color.from_gradient(agg_vol,ta.lowest(agg_vol,int(ma_len/20)),int(ta.highest(agg_vol,int(ma_len/20))*0.618),color.red,color.green)
plot(agg_vol,color=vol_clr,style=plot.style_columns)
vol_ma = avg_method == "SMA" ? ta.sma(agg_vol,ma_len) : avg_method == "EMA"? ta.ema(agg_vol,ma_len) : avg_method == "HMA"? ta.hma(agg_vol,ma_len) : 0
plot(vol_mult * vol_ma,"MA",chart.bg_color == color.white ? color.black : color.white)
if agg_vol > vol_mult * vol_ma
label.new(bar_index,agg_vol,str.tostring(int(agg_vol),format.volume),textcolor = color.white,size = size.tiny) |
HTF Candle Support & Resistance «NoaTrader» | https://www.tradingview.com/script/ODzjS0qZ-HTF-Candle-Support-Resistance-NoaTrader/ | NoaTrader | https://www.tradingview.com/u/NoaTrader/ | 62 | 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/
// © NoaTrader
//@version=5
indicator("Support & Resistance based on Higher Timeframe Candle «NoaTrader»","HTF CBSR",overlay = true,max_lines_count = 500)
var mh_array = array.new_line()
var ml_array = array.new_line()
var mc_array = array.new_line()
var timeframe_input = input.string("W","Source time frame",["12M","3M","M","W","D","240","60"],"M -> Month | W -> Week | D -> Day | 240 -> 4Hour | 60 -> 1Hour")
// var auto_timeframe = input.bool(false,"Set source time frame automatically based on chart timeframe ")
// var percent_difference_input = input.float(5,"Near candles show (%)")
var last_bar_offset_input = 10 //input.int(10,"Last candle SR offset")
// tf = auto_timeframe ? timeframe.isseconds ? "D" : timeframe.isminutes ? "W" : "M" : timeframe_input
[C_h,C_l,C_c] = request.security(syminfo.tickerid,timeframe_input,[high,low,close],barmerge.gaps_on)
is_candle = not na(C_h)
if is_candle
mh_array.push(line.new(bar_index,C_h,bar_index,C_h,color = color.rgb(255, 82, 82, 50)))
ml_array.push(line.new(bar_index,C_l,bar_index,C_l,color = color.rgb(76, 175, 79, 50)))
mc_array.push(line.new(bar_index,C_c,bar_index,C_c,color = color.rgb(76, 96, 175, 50)))
hl_diff_percent_abs(X) =>
h = (high - X) * 100 / X
l = (low - X) * 100 / X
math.abs(math.min(h,l))
last_bar_offset = bar_index == last_bar_index ? last_bar_offset_input : 0
percent_difference = ta.sma(math.abs(close-open)*100/open,100) * 5
for [i, h] in mh_array
if hl_diff_percent_abs(line.get_y1(h)) < percent_difference
line.set_x2(h,bar_index+last_bar_offset)
for [i, l] in ml_array
if hl_diff_percent_abs(line.get_y1(l)) < percent_difference
line.set_x2(l,bar_index+last_bar_offset)
for [i, c] in mc_array
if hl_diff_percent_abs(line.get_y1(c)) < percent_difference
line.set_x2(c,bar_index+last_bar_offset) |
RSI Trend Transform [wbburgin] | https://www.tradingview.com/script/BuXOOUQk-RSI-Trend-Transform-wbburgin/ | wbburgin | https://www.tradingview.com/u/wbburgin/ | 67 | 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/
// © wbburgin
//@version=5
indicator("RSI Trend Transform [wbburgin]",overlay=false)
import TradingView/ta/5
src = input.source(close,"RSI Source")
len = input.int(200,"RSI Length")
plotp = input.bool(true,"Price RSI",inline="P")
typp = input.string("Stochastic",options=["Stochastic","Regular"],title="",inline="P")
colp = input.color(color.yellow,title="",inline="P")
smoothp = input.int(7,"Smooth",inline="P")
plotv = input.bool(true,"Volume RSI",inline="V")
typv = input.string("Stochastic",options=["Stochastic","Regular"],title="",inline="V")
colv = input.color(color.red,title="",inline="V")
smoothv = input.int(7,"Smooth",inline="V")
plots = input.bool(false,"Combined RSI",inline="C")
cols = input.color(color.orange,title="",inline="C")
smooths = input.int(7,"Smooth",inline="C")
ub = input.int(80,"Upper Band")
lb = input.int(20,"Lower Band")
rsi_directional(src, length)=>
p_index = 0.
n_index = 0.
av_src = ta.sma(src,length)
for i=1 to length
if av_src > av_src[1]
p_index += av_src - av_src[1]
if av_src < av_src[1]
n_index += av_src[1] - av_src
rel = ta.rma(p_index / (p_index + n_index),length) * 100
pd = rsi_directional(src,len)
vd = rsi_directional(volume,len)
rsi_ = typp == "Stochastic" ? ta.stoch(pd,pd,pd,len) : pd
vol_ = typv == "Stochastic" ? ta.stoch(vd,vd,vd,len) : vd
sq = math.avg(rsi_,vol_)
rsis = ta.ema(rsi_,smoothp)
vols = ta.ema(vol_,smoothv)
sqs = ta.ema(sq,smooths)
pp=plot(plotp ? rsis : na,color=colp,title="Price RSI")
vp=plot(plotv ? vols : na,color=colv,title="Volume RSI")
sp=plot(plots ? sqs : na,color=cols,title="Combined RSI")
ubp = plot(ub,color=color.white)
lbp = plot(lb,color=color.white)
fill(ubp,lbp,color=color.new(color.purple,88)) |
Relative Trend Index (RTI) by Zeiierman | https://www.tradingview.com/script/VwmUNNwp-Relative-Trend-Index-RTI-by-Zeiierman/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 1,834 | 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/
// © Zeiierman
//@version=5
indicator('Relative Trend Index (RTI) by Zeiierman', shorttitle= "RTI", overlay=false, precision=0)
// Inputs {
trend_data_count = input.int(100, step=4, minval=10, title="Trend Length", inline = "RT", group="Relative Trend Index [RTI]", tooltip="This variable determines the number of data points used in the calculation. \n\nIn short: A high value returns the long-term trend and a low value returns the short-term trend. \n\nIf a user increases the 'Trend Length', the trend will take into account a larger number of data points. This makes the trends smoother and more resistant to sudden changes in the market, as they're based on a broader set of data. It also makes the trends slower to react to recent changes, as they're diluted by older data. \n\nOn the other hand, if a user decreases the 'Trend Length', the trend will take into account fewer data points. This could make the trends more responsive to recent market changes, as they're based on a narrower set of data. It also makes the trends more susceptible to noise and rapid fluctuations, as each new piece of data has a greater impact.")
trend_sensitivity_percentage = input.int(95, step=1,minval=50, maxval=98,title='Sensitivity ', inline = "RT1", group="Relative Trend Index [RTI]", tooltip="This variable determines the specific indices in the sorted trend arrays that are used for the upper and lower trend. It's used as a percentage of the 'Trend length'. \n\nIf a user increases the 'Sensitivity', the trend will be based on higher and lower positions in the sorted arrays, respectively. This makes the trend less sensitive. \n\nConversely, if a user decreases the 'Sensitivity', the trend will be based on positions closer to the middle of the sorted arrays. This makes the trend more sensitive.")
signal_length = input.int(20, step=1,minval=1, maxval=200,title='Signal Length', inline = "", group="Signal Line", tooltip="Set the Ma period.")
ob = input.float(80, step=1, minval=0, maxval=100, title="", inline = "obos", group="Overbought/Oversold", tooltip="")
os = input.float(20,step=1, minval=0, maxval=100,title="", inline = "obos", group="Overbought/Oversold", tooltip="Set the OB/OS levels.")
//~~~~~~~~~~~~~~~~~~~~~~~}
// Relative Trend Index Calculation {
upper_trend = close + ta.stdev(close, 2)
lower_trend = close - ta.stdev(close, 2)
upper_array = array.new<float>(0)
lower_array = array.new<float>(0)
for i = 0 to trend_data_count - 1
upper_array.push(upper_trend[i])
lower_array.push(lower_trend[i])
upper_array.sort()
lower_array.sort()
upper_index = math.round(trend_sensitivity_percentage / 100 * trend_data_count) - 1
lower_index = math.round((100 - trend_sensitivity_percentage) / 100 * trend_data_count) - 1
UpperTrend = upper_array.get(upper_index)
LowerTrend = lower_array.get(lower_index)
RelativeTrendIndex = ((close - LowerTrend) / (UpperTrend - LowerTrend))*100
//~~~~~~~~~~~~~~~~~~~~~~~}
// Plots {
MA_RelativeTrendIndex = ta.ema(RelativeTrendIndex,signal_length)
RT = plot(RelativeTrendIndex, 'Relative Trend Index (RTI)', color=color.new(color.teal, 0))
plot(MA_RelativeTrendIndex, 'Ma Relative Trend Index', color=color.new(#00bcd4, 0))
//~~~~~~~~~~~~~~~~~~~~~~~}
// Line plots {
mid = hline(50, 'Mid', color=#606060, linestyle=hline.style_dashed)
overbought = hline(ob, 'Overbought', color=#606060, linestyle=hline.style_dashed)
oversold = hline(os, 'Oversold', color=#606060, linestyle=hline.style_dashed)
//~~~~~~~~~~~~~~~~~~~~~~~}
// BG Fill {
fill(overbought, oversold, color=color.new(color.teal, 90), title='Background')
//~~~~~~~~~~~~~~~~~~~~~~~}
// Overbought/Oversold Gradient Fill {
midLinePlot = plot(50, color = na, editable = false, display = display.none)
fill(RT, midLinePlot, 100, ob, top_color = color.new(color.green, 0), bottom_color = color.new(color.green, 100), title = "Overbought Gradient Fill")
fill(RT, midLinePlot, os, 0, top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0), title = "Oversold Gradient Fill")
//~~~~~~~~~~~~~~~~~~~~~~~}
//Alerts {
RT_OB_Over = ta.crossover(RelativeTrendIndex,ob)
RT_OB_Under = ta.crossunder(RelativeTrendIndex,ob)
RT_OS_Over = ta.crossover(RelativeTrendIndex,os)
RT_OS_Under = ta.crossunder(RelativeTrendIndex,os)
RT_Mid_Over = ta.crossover(RelativeTrendIndex,50)
RT_Mid_Under = ta.crossunder(RelativeTrendIndex,50)
RT_MA_Over = ta.crossover(RelativeTrendIndex,MA_RelativeTrendIndex)
RT_MA_Under = ta.crossunder(RelativeTrendIndex,MA_RelativeTrendIndex)
alertcondition(RT_OB_Over, title = "RTI Crossover OB", message = "RTI Crossover OB")
alertcondition(RT_OB_Under, title = "RTI Crossunder OB", message = "RTI Crossunder OB")
alertcondition(RT_OS_Over, title = "RTI Crossover OS", message = "RTI Crossover OS")
alertcondition(RT_OS_Under, title = "RTI Crossunder OS", message = "RTI Crossunder OS")
alertcondition(RT_Mid_Over, title = "RTI Crossover 50", message = "RTI Crossover 50")
alertcondition(RT_Mid_Under,title = "RTI Crossunder 50", message = "RTI Crossunder 50")
alertcondition(RT_MA_Over, title = "RTI Crossover Ma", message = "RTI Crossover Ma")
alertcondition(RT_MA_Under, title = "RTI Crossunder Ma", message = "RTI Crossunder Ma")
//~~~~~~~~~~~~~~~~~~~~~~~} |
Range H/L Buy and Sell Signal | https://www.tradingview.com/script/lVFtWNQj-Range-H-L-Buy-and-Sell-Signal/ | theDOGEguy1 | https://www.tradingview.com/u/theDOGEguy1/ | 89 | 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/
// © theDOGEguy1
//@version=5
indicator("Range H/L Buy and Sell Signal", overlay=true)
// Customizable parameters
rangeStartHour = input(0, "Range Start Hour")
rangeStartMinute = input(0, "Range Start Minute")
rangeEndHour = input(8, "Range End Hour")
rangeEndMinute = input(00, "Range End Minute")
volatilityThreshold = input(0.5, "Volatility Threshold")
// Calculate range start and end timestamps
rangeStart = timestamp(year, month, dayofmonth, rangeStartHour, rangeStartMinute)
rangeEnd = timestamp(year, month, dayofmonth, rangeEndHour, rangeEndMinute)
// Calculate DR lines
High = ta.valuewhen(rangeStart <= time and time <= rangeEnd, ta.highest(high, 1), 0)
Low = ta.valuewhen(rangeStart <= time and time <= rangeEnd, ta.lowest(low, 1), 0)
// Calculate volatility
trueRange = ta.tr(true)
averageTrueRange = ta.sma(trueRange, 14)
// Generate buy and sell signals based on breakout conditions and volatility filter
buySignal = ta.crossover(close, High) and trueRange > volatilityThreshold * averageTrueRange
sellSignal = ta.crossunder(close, Low) and trueRange > volatilityThreshold * averageTrueRange
// Plot DR lines
plot(High, title="High", color=color.green)
plot(Low, title="Low", color=color.red)
// Plot buy and sell signals
plotshape(buySignal, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY")
plotshape(sellSignal, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")
|
Persistency - Days over MA | https://www.tradingview.com/script/SvrHAD8X-Persistency-Days-over-MA/ | kulturdesken | https://www.tradingview.com/u/kulturdesken/ | 8 | 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/
// © kulturdesken
//@version=4
study(title="Persistency - Days over MA", shorttitle="Over MA", overlay=false)
// Input parameters
lookback_period = input(125, "Lookback Period")
ma_period = input(65, "MA Period")
// Calculate the moving average
ma = sma(close, ma_period)
// Initialize the counter
over_ma_days = 0
// Loop through the past days
for i = 0 to lookback_period - 1
// Check if price is above the moving average
if close[i] > ma[i]
over_ma_days := over_ma_days + 1
// Plot the result
plot(over_ma_days, title="Over MA Days", color=color.gray, linewidth=1) |
RSI Fractal Energy with Signal Line | https://www.tradingview.com/script/cK1LmQcE-RSI-Fractal-Energy-with-Signal-Line/ | JohnCabernet | https://www.tradingview.com/u/JohnCabernet/ | 12 | 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/
// © Cookie1245
//@version=5
indicator("RSI Fractal Energy with Signal Line", overlay=false)
// RSI Inputs
rsiLength = input(14, title="RSI Length")
rsiSource = close
// Fractal Inputs
fractalLength = input(5, title="Fractal Length")
// Signal Line Inputs
signalPeriod = input(9, title="Signal Line Period")
// Calculate RSI
rsiValue = ta.rsi(rsiSource, rsiLength)
// Calculate Fractals
higherHigh = ta.highest(high, fractalLength)
lowerLow = ta.lowest(low, fractalLength)
// Calculate Fractal Energy
energy = math.abs(rsiValue - 50) * 2
// Calculate Signal Line
signalLine = ta.sma(energy, signalPeriod)
// Plotting
plot(energy, title="RSI Fractal Energy", color=color.blue, linewidth=2)
plot(signalLine, title="Signal Line", color=color.red, linewidth=1)
// Plot Overbought/Oversold Levels
hline(70, title="Overbought", color=color.red, linestyle=hline.style_dashed)
hline(30, title="Oversold", color=color.green, linestyle=hline.style_dashed)
|
Supply and Demand Daily [LuxAlgo] | https://www.tradingview.com/script/rc0kPSGU-Supply-and-Demand-Daily-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,852 | 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/
// © LuxAlgo
//@version=5
indicator("Supply and Demand Daily [LuxAlgo]", "LuxAlgo - Supply and Demand Daily", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_bars_back = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
per = input.float(10., 'Threshold %', minval = 0, maxval = 100)
div = input.int(50, 'Resolution' , minval = 2, maxval = 500)
tf = input.timeframe('', 'Intrabar TF')
//Colors
showSupply = input(true ,'Supply ', inline = 'supply', group = 'Style')
supplyCss = input(#2157f3, '' , inline = 'supply', group = 'Style')
supplyArea = input(true ,'Area' , inline = 'supply', group = 'Style')
supplyAvg = input(true ,'Average' , inline = 'supply', group = 'Style')
supplyWavg = input(true ,'Weighted' , inline = 'supply', group = 'Style')
showEqui = input(true ,'Equilibrium' , inline = 'equi' , group = 'Style')
equiCss = input(color.gray, '' , inline = 'equi' , group = 'Style')
equiAvg = input(true ,'Average' , inline = 'equi' , group = 'Style')
equiWavg = input(true ,'Weighted' , inline = 'equi' , group = 'Style')
showDemand = input(true ,'Demand ' , inline = 'demand', group = 'Style')
demandCss = input(#ff5d00, '' , inline = 'demand', group = 'Style')
demandArea = input(true ,'Area' , inline = 'demand', group = 'Style')
demandAvg = input(true ,'Average' , inline = 'demand', group = 'Style')
demandWavg = input(true ,'Weighted' , inline = 'demand', group = 'Style')
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type bin
float lvl
float prev
float sum
float prev_sum
float csum
float avg
bool isreached
type area
box bx
line avg
line wavg
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
n = bar_index
get_hlv()=> [high, low, volume]
method set_area(area id, x1, top, btm, avg, wavg, showArea, showAvg, showWavg)=>
if showArea
id.bx.set_lefttop(x1, top)
id.bx.set_rightbottom(n, btm)
if showAvg
id.avg.set_xy1(x1, avg)
id.avg.set_xy2(n, avg)
if showWavg
id.wavg.set_xy1(x1, wavg)
id.wavg.set_xy2(n, wavg)
//-----------------------------------------------------------------------------}
//Main variables
//-----------------------------------------------------------------------------{
var max = 0.
var min = 0.
var x1 = 0
var csum = 0.
var area supply_area = na
var area demand_area = na
//Intrabar data
[h, l, v] = request.security_lower_tf(syminfo.tickerid, tf, get_hlv())
//Accumulate
max := math.max(high[1], max)
min := math.min(low[1], min)
csum += volume[1]
//-----------------------------------------------------------------------------}
//Set zones
//-----------------------------------------------------------------------------{
var float supply_wavg = na
var float demand_wavg = na
if dayofmonth != dayofmonth[1]
r = (max - min) / div
supply = bin.new(max, max, 0, 0, 0, 0, false)
demand = bin.new(min, min, 0, 0, 0, 0, false)
//Loop trough intervals
for i = 0 to div-1
supply.lvl -= r
demand.lvl += r
//Loop trough bars
for j = 1 to (n - x1)-1
//Loop trough intrabars
for k = 0 to (v[j]).size()-1
//Accumulate if within upper internal
supply.sum += (h[j]).get(k) > supply.lvl and (h[j]).get(k) < supply.prev ? (v[j]).get(k) : 0
supply.avg += supply.lvl * (supply.sum - supply.prev_sum)
supply.csum += supply.sum - supply.prev_sum
supply.prev_sum := supply.sum
//Accumulate if within lower interval
demand.sum += (l[j]).get(k) < demand.lvl and (l[j]).get(k) > demand.prev ? (v[j]).get(k) : 0
demand.avg += demand.lvl * (demand.sum - demand.prev_sum)
demand.csum += demand.sum - demand.prev_sum
demand.prev_sum := demand.sum
//Test if supply accumulated volume exceed threshold and set box
if supply.sum / csum * 100 > per and not supply.isreached
avg = math.avg(max, supply.lvl)
supply_wavg := supply.avg / supply.csum
//Set Box/Level coordinates
if showSupply
supply_area := area.new(
box.new(na, na, na, na, na, bgcolor = color.new(supplyCss, 80))
, line.new(na, na, na, na, color = supplyCss)
, line.new(na, na, na, na, color = supplyCss, style = line.style_dashed))
supply_area.set_area(x1, max, supply.lvl, avg, supply_wavg, supplyArea, supplyAvg, supplyWavg)
supply.isreached := true
//Test if demand accumulated volume exceed threshold and set box
if demand.sum / csum * 100 > per and not demand.isreached and showDemand
avg = math.avg(min, demand.lvl)
demand_wavg := demand.avg / demand.csum
//Set Box/Level coordinates
if showDemand
demand_area := area.new(
box.new(na, na, na, na, na, bgcolor = color.new(demandCss, 80))
, line.new(na, na, na, na, color = demandCss)
, line.new(na, na, na, na, color = demandCss, style = line.style_dashed))
demand_area.set_area(x1, demand.lvl, min, avg, demand_wavg, demandArea, demandAvg, demandWavg)
demand.isreached := true
if supply.isreached and demand.isreached
break
supply.prev := supply.lvl
demand.prev := demand.lvl
max := high
min := low
csum := volume
x1 := n
if barstate.islast
if showSupply
supply_area.bx.set_right(n)
supply_area.avg.set_x2(n)
supply_area.wavg.set_x2(n)
if showDemand
demand_area.bx.set_right(n)
demand_area.avg.set_x2(n)
demand_area.wavg.set_x2(n)
//-----------------------------------------------------------------------------} |
TOP 4 STABLECOIN MARKET CAP | https://www.tradingview.com/script/WvhUoY06/ | Springtimestn | https://www.tradingview.com/u/Springtimestn/ | 9 | 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/
// © Springtimestn
//@version=5
indicator("TOP 4 STABLECOIN MARKET CAP", "TOP 4 stUSD MC", overlay=true)
toCompactString(value) =>
formatted_value = ""
if math.abs(value) >= 1000000000
formatted_value := str.tostring(math.round(value / 1000000000, 2)) + "B"
else if math.abs(value) >= 1000000
formatted_value := str.tostring(math.round(value / 1000000, 2)) + "M"
else
formatted_value := str.tostring(math.round(value, 2))
formatted_value
// USDT
sym_usdt = input.symbol("CRYPTOCAP:USDT", "USDT Market Cap", group = "TOKEN MARKET CAP")
sym_usdt_color = color.new(color.red, 0)
sym_usdt_mc = request.security(sym_usdt, timeframe.period, close)
sym_usdt_mc_past = ta.valuewhen(true, sym_usdt_mc, 1)
usdt_mc_change = sym_usdt_mc - sym_usdt_mc_past
// USDC
sym_usdc = input.symbol("CRYPTOCAP:USDC", "USDC Market Cap", group = "TOKEN MARKET CAP")
sym_usdc_color = color.new(color.blue, 0)
sym_usdc_mc = request.security(sym_usdc, timeframe.period, close)
sym_usdc_mc_past = ta.valuewhen(true, sym_usdc_mc, 1)
usdc_mc_change = sym_usdc_mc - sym_usdc_mc_past
// TUSD
sym_tusd = input.symbol("CRYPTOCAP:TUSD", "TUSD Market Cap", group = "TOKEN MARKET CAP")
sym_tusd_color = color.new(color.yellow, 0)
sym_tusd_mc = request.security(sym_tusd, timeframe.period, close)
sym_tusd_mc_past = ta.valuewhen(true, sym_tusd_mc, 1)
tusd_mc_change = sym_tusd_mc - sym_tusd_mc_past
// BUSD
sym_busd = input.symbol("GLASSNODE:BUSD_SUPPLY", "BUSD Market Cap", group = "TOKEN MARKET CAP")
sym_busd_color = color.new(color.lime, 0)
sym_busd_mc = request.security(sym_busd, timeframe.period, close)
sym_busd_mc_past = ta.valuewhen(true, sym_busd_mc, 1)
busd_mc_change = sym_busd_mc - sym_busd_mc_past
// stUSD
total_mc = sym_usdt_mc + sym_usdc_mc + sym_tusd_mc + sym_busd_mc
total_color = color.new(color.white, 0)
total_mc_past = sym_usdt_mc_past + sym_usdc_mc_past + sym_tusd_mc_past + sym_busd_mc_past
total_mc_change = total_mc - total_mc_past
usdt_scaling_factor = math.round(total_mc / sym_usdt_mc, 1)
usdc_scaling_factor = math.round(total_mc / sym_usdc_mc, 1)
tusd_scaling_factor = math.round(total_mc / sym_tusd_mc, 1)
busd_scaling_factor = math.round(total_mc / sym_busd_mc, 1)
usdt_move = input.float(0.0, "Move USDT Chart", minval=-0.1, maxval=0.1, step=0.01, group = "MOVE CHART STEP TO CLEAR CHART")
usdc_move = input.float(0.01, "Move USDC Chart", minval=-0.1, maxval=0.1, step=0.01, group = "MOVE CHART STEP TO CLEAR CHART")
tusd_move = input.float(0.02, "Move TUSD Chart", minval=-0.1, maxval=0.1, step=0.01, group = "MOVE CHART STEP TO CLEAR CHART")
busd_move = input.float(0.03, "Move BUSD Chart", minval=-0.1, maxval=0.1, step=0.01, group = "MOVE CHART STEP TO CLEAR CHART")
sym_usdt_mc_scaled = sym_usdt_mc * usdt_scaling_factor - total_mc * usdt_move
sym_usdc_mc_scaled = sym_usdc_mc * usdc_scaling_factor - total_mc * usdc_move
sym_tusd_mc_scaled = sym_tusd_mc * tusd_scaling_factor - total_mc * tusd_move
sym_busd_mc_scaled = sym_busd_mc * busd_scaling_factor - total_mc * busd_move
var label sym_usdt_label = na
var label sym_usdc_label = na
var label sym_tusd_label = na
var label sym_busd_label = na
var label total_label = na
if barstate.islast
if na(sym_usdt_label)
labelUsdt = "USDT: " + toCompactString(sym_usdt_mc) + " (" + toCompactString(usdt_mc_change) + ")"
sym_usdt_label := label.new(x=bar_index, y=sym_usdt_mc_scaled, text=labelUsdt, textcolor=total_color, textalign=text.align_center, size=size.small)
else
label.set_text(sym_usdt_label, "USDT: " + toCompactString(sym_usdt_mc) + " (" + toCompactString(usdt_mc_change) + ")")
label.set_y(sym_usdt_label, sym_usdt_mc_scaled)
if barstate.islast
if na(sym_usdc_label)
labelUsdc = "USDC: " + toCompactString(sym_usdc_mc) + " (" + toCompactString(usdc_mc_change) + ")"
sym_usdc_label := label.new(x=bar_index, y=sym_usdc_mc_scaled, text=labelUsdc, textcolor=total_color, textalign=text.align_left, size=size.small)
else
label.set_text(sym_usdc_label, "USDC: " + toCompactString(sym_usdc_mc) + " (" + toCompactString(usdc_mc_change) + ")")
label.set_y(sym_usdc_label, sym_usdc_mc_scaled)
if barstate.islast
if na(sym_tusd_label)
labelTusd = "TUSD: " + toCompactString(sym_tusd_mc) + " (" + toCompactString(tusd_mc_change) + ")"
sym_tusd_label := label.new(x=bar_index, y=sym_tusd_mc_scaled, text=labelTusd, textcolor=total_color, textalign=text.align_left, size=size.small)
else
label.set_text(sym_tusd_label, "TUSD: " + toCompactString(sym_tusd_mc) + " (" + toCompactString(tusd_mc_change) + ")")
label.set_y(sym_tusd_label, sym_tusd_mc_scaled)
if barstate.islast
if na(sym_busd_label)
labelBusd = "BUSD: " + toCompactString(sym_busd_mc) + " (" + toCompactString(busd_mc_change) + ")"
sym_busd_label := label.new(x=bar_index, y=sym_busd_mc_scaled, text=labelBusd, textcolor=total_color, textalign=text.align_left, size=size.small)
else
label.set_text(sym_busd_label, "BUSD: " + toCompactString(sym_busd_mc) + " (" + toCompactString(busd_mc_change) + ")")
label.set_y(sym_busd_label, sym_busd_mc_scaled)
if barstate.islast
if na(total_label)
labelTotal = "T.stUSD: " + toCompactString(total_mc) + " (" + toCompactString(total_mc_change) + ")"
total_label := label.new(x=bar_index, y=total_mc, text=labelTotal, textcolor=total_color, textalign=text.align_left, size=size.small)
else
label.set_text(total_label, "T.stUSD: " + toCompactString(total_mc) + " (" + toCompactString(total_mc_change) + ")")
label.set_y(total_label, total_mc)
plot(sym_usdt_mc_scaled, title="USDT", color=sym_usdt_color, display=display.pane)
plot(sym_usdc_mc_scaled, title="USDC", color=sym_usdc_color, display=display.pane)
plot(sym_tusd_mc_scaled, title="TUSD", color=sym_tusd_color, display=display.pane)
plot(sym_busd_mc_scaled, title="BUSD", color=sym_busd_color, display=display.pane)
plot(total_mc, title="TOP 4 STABLECOIN MARKET CAP", color=total_color,display=display.pane)
|
CommonTypesMath | https://www.tradingview.com/script/bEtqEGss-CommonTypesMath/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 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/
// © RicardoSantos
//@version=5
// @description Provides a common library source for common types of useful mathematical structures.
// Includes: `complex, Vector2, Vector3, Vector4, Quaternion, Segment2, Segment3, Pole, Plane, M32, M44`
library("CommonTypesMath")
//#region ~~~ Mathematical Structure Types interface:
// @type Representation of a Complex Number, a complex number `z` is a number in the form `z = x + yi`,
// were `x` and `y` are real numbers and i is the imaginary unit, with property `i2 = -1`.
// @field re Real part of the complex number.
// @field im Imaginary part of the complex number.
export type complex
float re
float im
// @type Representation of a two dimentional vector with components `(x:float,y:float)`.
// @field x Coordinate `x` of the vector.
// @field y Coordinate `y` of the vector.
export type Vector2
float x
float y
// @type Representation of a three dimentional vector with components `(x:float,y:float,z:float)`.
// @field x Coordinate `x` of the vector.
// @field y Coordinate `y` of the vector.
// @field z Coordinate `z` of the vector.
export type Vector3
float x
float y
float z
// @type Representation of a four dimentional vector with components `(x:float,y:float,z:float,w:float)`.
// @field x Coordinate `x` of the vector.
// @field y Coordinate `y` of the vector.
// @field z Coordinate `z` of the vector.
// @field w Coordinate `w` of the vector.
export type Vector4
float x
float y
float z
float w
// @type Representation of a four dimentional vector with components `(x:float,y:float,z:float,w:float)`.
// @field x Coordinate `x` of the vector.
// @field y Coordinate `y` of the vector.
// @field z Coordinate `z` of the vector.
// @field w Coordinate `w` of the vector, specifies the rotation component.
export type Quaternion
float x
float y
float z
float w
//@type Representation of a line in two dimentional space.
// @field origin Origin coordinates.
// @field target Target coordinates.
export type Segment2
Vector2 origin
Vector2 target
//@type Representation of a line in three dimentional space.
// @field origin Origin coordinates.
// @field target Target coordinates.
export type Segment3
Vector3 origin
Vector3 target
// @type Representation of polar coordinates `(radius:float,angle:float)`.
// @field radius Radius of the pole.
// @field angle Angle in radians of the pole.
export type Pole
float radius
float angle
// @type Representation of a 3D plane.
// @field normal Normal vector of the plane.
// @field distance Distance of the plane along its normal from the origin.
export type Plane
Vector3 normal
float distance
// @type Representation of a 3x2 matrix.
// @field m11 First element of the first row.
// @field m12 Second element of the first row.
// @field m21 First element of the second row.
// @field m22 Second element of the second row.
// @field m31 First element of the third row.
// @field m32 Second element of the third row.
export type M32
float m11
float m12
float m21
float m22
float m31
float m32
// @type Representation of a 4x4 matrix.
// @field m11 First element of the first row.
// @field m12 Second element of the first row.
// @field m13 Third element of the first row.
// @field m14 fourth element of the first row.
// @field m21 First element of the second row.
// @field m22 Second element of the second row.
// @field m23 Third element of the second row.
// @field m24 fourth element of the second row.
// @field m31 First element of the third row.
// @field m32 Second element of the third row.
// @field m33 Third element of the third row.
// @field m34 fourth element of the third row.
// @field m41 First element of the fourth row.
// @field m42 Second element of the fourth row.
// @field m43 Third element of the fourth row.
// @field m44 fourth element of the fourth row.
export type M44
// row 1
float m11
float m12
float m13
float m14
// row 2
float m21
float m22
float m23
float m24
// row 3
float m31
float m32
float m33
float m34
// row 4
float m41
float m42
float m43
float m44
//#endregion
|
Super Pivots | https://www.tradingview.com/script/mfqIEaOJ/ | ban-yen | https://www.tradingview.com/u/ban-yen/ | 2,066 | 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/
// © banyen
//@version=5
// v1.0.0 revision=84.0
// v1.1.0 revision=151.0(137.0)
// v1.1.1 revision=160.0
// v1.2.0 revision=198.0
indicator(title = "Super Pivots", shorttitle = "Super Pivots (v1.2.0)", overlay = true, max_lines_count = 500, max_labels_count = 500)
//--- input
// ラベルの位置
input_position_label = input.string("Left", "ラベルの位置", ["Left", "Right"], group = "Position")
input_position_leftlabel_float = input.bool(true, "ラベルを常にチャート内に表示(Leftのみ)", group = "Position")
// Number of Pivots Back
lookback_max = 15
lookback = input.int(1, "Number of Pivots Back", 1, lookback_max)
// 1分足
input_1m_hourly = input.bool(false, "(1時間)", inline = "1m", group = "1分足")
input_1m_4hourly = input.bool(false, "(4時間)", inline = "1m", group = "1分足")
input_1m_daily = input.bool(true, "日", inline = "1m", group = "1分足")
input_1m_weekly = input.bool(true, "週", inline = "1m", group = "1分足")
input_1m_monthly = input.bool(true, "月", inline = "1m", group = "1分足")
input_1m_yearly = input.bool(true, "年", inline = "1m", group = "1分足")
input_1m_market = input.bool(false, "(マーケット)", inline = "1m", group = "1分足")
// 5分足
input_5m_daily = input.bool(true, "日", inline = "5m", group = "5分足")
input_5m_weekly = input.bool(true, "週", inline = "5m", group = "5分足")
input_5m_monthly = input.bool(true, "月", inline = "5m", group = "5分足")
input_5m_yearly = input.bool(true, "年", inline = "5m", group = "5分足")
input_5m_market = input.bool(false, "(マーケット)", inline = "5m", group = "5分足")
// 15分足
input_15m_daily = input.bool(true, "日", inline = "15m", group = "15分足")
input_15m_weekly = input.bool(true, "週", inline = "15m", group = "15分足")
input_15m_monthly = input.bool(true, "月", inline = "15m", group = "15分足")
input_15m_yearly = input.bool(true, "年", inline = "15m", group = "15分足")
input_15m_market = input.bool(false, "(マーケット)", inline = "15m", group = "15分足")
// 1時間足
input_1h_daily = input.bool(false, "(日)", inline = "1h", group = "1時間足")
input_1h_weekly = input.bool(true, "週", inline = "1h", group = "1時間足")
input_1h_monthly = input.bool(true, "月", inline = "1h", group = "1時間足")
input_1h_yearly = input.bool(true, "年", inline = "1h", group = "1時間足")
// 4時間足
input_4h_daily = input.bool(false, "(日)", inline = "4h", group = "4時間足")
input_4h_weekly = input.bool(false, "(週)", inline = "4h", group = "4時間足")
input_4h_monthly = input.bool(true, "月", inline = "4h", group = "4時間足")
input_4h_yearly = input.bool(true, "年", inline = "4h", group = "4時間足")
// 日足
input_1d_daily = input.bool(false, "(日)", inline = "1d", group = "日足")
input_1d_weekly = input.bool(false, "(週)", inline = "1d", group = "日足")
input_1d_monthly = input.bool(false, "(月)", inline = "1d", group = "日足")
input_1d_yearly = input.bool(true, "年", inline = "1d", group = "日足")
// 週足
input_1w_daily = input.bool(false, "(日)", inline = "1w", group = "週足")
input_1w_weekly = input.bool(false, "(週)", inline = "1w", group = "週足")
input_1w_monthly = input.bool(false, "(月)", inline = "1w", group = "週足")
input_1w_yearly = input.bool(true, "年", inline = "1w", group = "週足")
// 月足
input_1M_daily = input.bool(false, "(日)", inline = "1M", group = "月足")
input_1M_weekly = input.bool(false, "(週)", inline = "1M", group = "月足")
input_1M_monthly = input.bool(false, "(月)", inline = "1M", group = "月足")
input_1M_yearly = input.bool(true, "年", inline = "1M", group = "月足")
// 色
input_color_hourly = input.color(color.orange, "1H", inline = "color", group = "Color(Line/Label)")
input_color_4hourly = input.color(color.orange, "4H", inline = "color", group = "Color(Line/Label)")
input_color_daily = input.color(color.orange, "1D", inline = "color", group = "Color(Line/Label)")
input_color_weekly = input.color(color.orange, "1W", inline = "color", group = "Color(Line/Label)")
input_color_monthly = input.color(color.orange, "1M", inline = "color", group = "Color(Line/Label)")
input_color_yearly = input.color(color.orange, "1Y", inline = "color", group = "Color(Line/Label)")
input_color_market = input.color(color.orange, "Market", inline = "color", group = "Color(Line/Label)")
// 可視性
input_visibility_p = input.bool(true, "P", inline = "visibility", group = "Visibility")
input_visibility_r1 = input.bool(true, "R1", inline = "visibility", group = "Visibility")
input_visibility_s1 = input.bool(true, "S1", inline = "visibility", group = "Visibility")
input_visibility_r2 = input.bool(true, "R2", inline = "visibility", group = "Visibility")
input_visibility_s2 = input.bool(true, "S2", inline = "visibility", group = "Visibility")
input_visibility_r3 = input.bool(true, "R3", inline = "visibility2", group = "Visibility")
input_visibility_s3 = input.bool(true, "S3", inline = "visibility2", group = "Visibility")
input_visibility_r4 = input.bool(true, "R4", inline = "visibility2", group = "Visibility")
input_visibility_s4 = input.bool(true, "S4", inline = "visibility2", group = "Visibility")
input_visibility_r5 = input.bool(true, "R5", inline = "visibility2", group = "Visibility")
input_visibility_s5 = input.bool(true, "S5", inline = "visibility2", group = "Visibility")
//--- Pivot計算
pivot_type = "Traditional"
get_pivots(float prev_high, float prev_low, float prev_close) =>
pp = (prev_high + prev_low + prev_close) / 3
r1 = pp * 2 - prev_low
s1 = pp * 2 - prev_high
r2 = pp + (prev_high - prev_low)
s2 = pp - (prev_high - prev_low)
r3 = pp * 2 + (prev_high - 2 * prev_low)
s3 = pp * 2 - (2 * prev_high - prev_low)
r4 = pp * 3 + (prev_high - 3 * prev_low)
s4 = pp * 3 - (3 * prev_high - prev_low)
r5 = pp * 4 + (prev_high - 4 * prev_low)
s5 = pp * 4 - (4 * prev_high - prev_low)
res_list = array.new_float()
array.push(res_list, pp)
array.push(res_list, r1)
array.push(res_list, s1)
array.push(res_list, r2)
array.push(res_list, s2)
array.push(res_list, r3)
array.push(res_list, s3)
array.push(res_list, r4)
array.push(res_list, s4)
array.push(res_list, r5)
array.push(res_list, s5)
res_list
// Hourly Pivot
is_hour_change = timeframe.change("60")
array_hourly_pivots = ta.pivot_point_levels(pivot_type, is_hour_change)
// 4Hourly Pivot
is_4hour_change = timeframe.change("240")
array_4hourly_pivots = ta.pivot_point_levels(pivot_type, is_4hour_change)
// Daily Pivot
is_day_change = timeframe.change("1D")
array_daily_pivots = ta.pivot_point_levels(pivot_type, is_day_change)
// Weekly Pivot
is_week_change = timeframe.change("1W")
array_weekly_pivots = ta.pivot_point_levels(pivot_type, is_week_change)
// Monthly Pivot
is_month_change = timeframe.change("1M")
array_monthly_pivots = ta.pivot_point_levels(pivot_type, is_month_change)
[prev_high_1M, prev_low_1M, prev_close_1M] = request.security(syminfo.tickerid, "1M", [high[1], low[1], close[1]], barmerge.gaps_off, barmerge.lookahead_on)
if timeframe.period == "1" or timeframe.period == "5" or timeframe.period == "15"
array.clear(array_monthly_pivots)
array_monthly_pivots := get_pivots(prev_high_1M, prev_low_1M, prev_close_1M)
// Yearly Pivot
is_year_change = timeframe.change("12M")
array_yearly_pivots = ta.pivot_point_levels(pivot_type, is_year_change)
[prev_high_12M, prev_low_12M, prev_close_12M] = request.security(syminfo.tickerid, "12M", [high[1], low[1], close[1]], barmerge.gaps_off, barmerge.lookahead_on)
if timeframe.period == "1" or timeframe.period == "5" or timeframe.period == "15"
array.clear(array_yearly_pivots)
array_yearly_pivots := get_pivots(prev_high_12M, prev_low_12M, prev_close_12M)
// Market Pivot
is_start_tokyo = timeframe.change("1D")
is_start_london = hour(time, "UTC+9") == 15 and minute(time, "UTC+9") == 0
is_start_newyork = hour(time, "UTC+9") == 21 and minute(time, "UTC+9") == 0
array_market_pivots = ta.pivot_point_levels(pivot_type, is_start_tokyo or is_start_london or is_start_newyork)
//--- Line and Label
var array_1m_hourly_lines = array.new_line(0)
var array_1m_4hourly_lines = array.new_line(0)
var array_1m_daily_lines = array.new_line(0)
var array_1m_weekly_lines = array.new_line(0)
var array_1m_monthly_lines = array.new_line(0)
var array_1m_yearly_lines = array.new_line(0)
var array_1m_market_lines = array.new_line(0)
var array_1m_hourly_labels = array.new_label(0)
var array_1m_4hourly_labels = array.new_label(0)
var array_1m_daily_labels = array.new_label(0)
var array_1m_weekly_labels = array.new_label(0)
var array_1m_monthly_labels = array.new_label(0)
var array_1m_yearly_labels = array.new_label(0)
var array_1m_market_labels = array.new_label(0)
var array_5m_daily_lines = array.new_line(0)
var array_5m_weekly_lines = array.new_line(0)
var array_5m_monthly_lines = array.new_line(0)
var array_5m_yearly_lines = array.new_line(0)
var array_5m_market_lines = array.new_line(0)
var array_5m_daily_labels = array.new_label(0)
var array_5m_weekly_labels = array.new_label(0)
var array_5m_monthly_labels = array.new_label(0)
var array_5m_yearly_labels = array.new_label(0)
var array_5m_market_labels = array.new_label(0)
var array_15m_daily_lines = array.new_line(0)
var array_15m_weekly_lines = array.new_line(0)
var array_15m_monthly_lines = array.new_line(0)
var array_15m_yearly_lines = array.new_line(0)
var array_15m_market_lines = array.new_line(0)
var array_15m_daily_labels = array.new_label(0)
var array_15m_weekly_labels = array.new_label(0)
var array_15m_monthly_labels = array.new_label(0)
var array_15m_yearly_labels = array.new_label(0)
var array_15m_market_labels = array.new_label(0)
var array_1h_daily_lines = array.new_line(0)
var array_1h_weekly_lines = array.new_line(0)
var array_1h_monthly_lines = array.new_line(0)
var array_1h_yearly_lines = array.new_line(0)
var array_1h_daily_labels = array.new_label(0)
var array_1h_weekly_labels = array.new_label(0)
var array_1h_monthly_labels = array.new_label(0)
var array_1h_yearly_labels = array.new_label(0)
var array_4h_daily_lines = array.new_line(0)
var array_4h_weekly_lines = array.new_line(0)
var array_4h_monthly_lines = array.new_line(0)
var array_4h_yearly_lines = array.new_line(0)
var array_4h_daily_labels = array.new_label(0)
var array_4h_weekly_labels = array.new_label(0)
var array_4h_monthly_labels = array.new_label(0)
var array_4h_yearly_labels = array.new_label(0)
var array_1d_daily_lines = array.new_line(0)
var array_1d_weekly_lines = array.new_line(0)
var array_1d_monthly_lines = array.new_line(0)
var array_1d_yearly_lines = array.new_line(0)
var array_1d_daily_labels = array.new_label(0)
var array_1d_weekly_labels = array.new_label(0)
var array_1d_monthly_labels = array.new_label(0)
var array_1d_yearly_labels = array.new_label(0)
var array_1w_daily_lines = array.new_line(0)
var array_1w_weekly_lines = array.new_line(0)
var array_1w_monthly_lines = array.new_line(0)
var array_1w_yearly_lines = array.new_line(0)
var array_1w_daily_labels = array.new_label(0)
var array_1w_weekly_labels = array.new_label(0)
var array_1w_monthly_labels = array.new_label(0)
var array_1w_yearly_labels = array.new_label(0)
var array_1M_daily_lines = array.new_line(0)
var array_1M_weekly_lines = array.new_line(0)
var array_1M_monthly_lines = array.new_line(0)
var array_1M_yearly_lines = array.new_line(0)
var array_1M_daily_labels = array.new_label(0)
var array_1M_weekly_labels = array.new_label(0)
var array_1M_monthly_labels = array.new_label(0)
var array_1M_yearly_labels = array.new_label(0)
// Delete Lines
func_delete_lines(array_lines) =>
if array.size(array_lines) > 0 and array.size(array_lines) == lookback * 11
for i = 0 to 10 by 1
line.delete(array.shift(array_lines))
// Delete Labels
func_delete_labels(array_labels) =>
if array.size(array_labels) > 0 and array.size(array_labels) == lookback * 11
for i = 0 to 10 by 1
label.delete(array.shift(array_labels))
// Array for Label
var array_label_str = array.new_string(0)
if array.size(array_label_str) == 0
array.push(array_label_str, "(P)")
array.push(array_label_str, "(R1)")
array.push(array_label_str, "(S1)")
array.push(array_label_str, "(R2)")
array.push(array_label_str, "(S2)")
array.push(array_label_str, "(R3)")
array.push(array_label_str, "(S3)")
array.push(array_label_str, "(R4)")
array.push(array_label_str, "(S4)")
array.push(array_label_str, "(R5)")
array.push(array_label_str, "(S5)")
func_check_level(index) =>
// 表示対象:true
res = switch index
0 => input_visibility_p
1 => input_visibility_r1
2 => input_visibility_s1
3 => input_visibility_r2
4 => input_visibility_s2
5 => input_visibility_r3
6 => input_visibility_s3
7 => input_visibility_r4
8 => input_visibility_s4
9 => input_visibility_r5
10 => input_visibility_s5
// ★計算量暫定対策
func_is_calc(pivot_timeframe) =>
bool res = false
if pivot_timeframe == "hourly"
res := switch timeframe.period
"1" => input_1m_hourly
else if pivot_timeframe == "4hourly"
res := switch timeframe.period
"1" => input_1m_4hourly
else if pivot_timeframe == "daily"
res := switch timeframe.period
"1" => input_1m_daily
"5" => input_5m_daily
"15" => input_15m_daily
"60" => input_1h_daily
"240" => input_4h_daily
"D" => input_1d_daily
"W" => input_1w_daily
"M" => input_1M_daily
else if pivot_timeframe == "weekly"
res := switch timeframe.period
"1" => input_1m_weekly
"5" => input_5m_weekly
"15" => input_15m_weekly
"60" => input_1h_weekly
"240" => input_4h_weekly
"D" => input_1d_weekly
"W" => input_1w_weekly
"M" => input_1M_weekly
else if pivot_timeframe == "monthly"
res := switch timeframe.period
"1" => input_1m_monthly
"5" => input_5m_monthly
"15" => input_15m_monthly
"60" => input_1h_monthly
"240" => input_4h_monthly
"D" => input_1d_monthly
"W" => input_1w_monthly
"M" => input_1M_monthly
else if pivot_timeframe == "yearly"
res := switch timeframe.period
"1" => input_1m_yearly
"5" => input_5m_yearly
"15" => input_15m_yearly
"60" => input_1h_yearly
"240" => input_4h_yearly
"D" => input_1d_yearly
"W" => input_1w_yearly
"M" => input_1M_yearly
else if pivot_timeframe == "market"
res := switch timeframe.period
"1" => input_1m_market
"5" => input_5m_market
"15" => input_15m_market
res
// Hourly Pivot
if is_hour_change and func_is_calc("hourly")
func_delete_lines(array_1m_hourly_lines)
func_delete_labels(array_1m_hourly_labels)
for [i, p] in array_hourly_pivots
if not func_check_level(i)
array.push(array_1m_hourly_lines, na)
array.push(array_1m_hourly_labels, na)
continue
// 1m
if input_1m_hourly and timeframe.period == "1"
l = line.new(time, array.get(array_hourly_pivots, i), time + timeframe.in_seconds("60") * 1000, array.get(array_hourly_pivots, i), xloc = xloc.bar_time, color = input_color_hourly)
array.push(array_1m_hourly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("60") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_hourly_pivots, i), "1H" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_hourly)
array.push(array_1m_hourly_labels, l2)
// 4Hourly Pivot
if is_4hour_change and func_is_calc("4hourly")
func_delete_lines(array_1m_4hourly_lines)
func_delete_labels(array_1m_4hourly_labels)
for [i, p] in array_4hourly_pivots
if not func_check_level(i)
array.push(array_1m_4hourly_lines, na)
array.push(array_1m_4hourly_labels, na)
continue
// 1m
if input_1m_4hourly and timeframe.period == "1"
l = line.new(time, array.get(array_4hourly_pivots, i), time + timeframe.in_seconds("240") * 1000, array.get(array_4hourly_pivots, i), xloc = xloc.bar_time, color = input_color_4hourly)
array.push(array_1m_4hourly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("240") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_4hourly_pivots, i), "4H" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_4hourly)
array.push(array_1m_4hourly_labels, l2)
// Daily Pivot
if is_day_change and func_is_calc("daily")
func_delete_lines(array_1m_daily_lines)
func_delete_lines(array_5m_daily_lines)
func_delete_lines(array_15m_daily_lines)
func_delete_lines(array_1h_daily_lines)
func_delete_lines(array_4h_daily_lines)
func_delete_lines(array_1d_daily_lines)
func_delete_lines(array_1w_daily_lines)
func_delete_lines(array_1M_daily_lines)
func_delete_labels(array_1m_daily_labels)
func_delete_labels(array_5m_daily_labels)
func_delete_labels(array_15m_daily_labels)
func_delete_labels(array_1h_daily_labels)
func_delete_labels(array_4h_daily_labels)
func_delete_labels(array_1d_daily_labels)
func_delete_labels(array_1w_daily_labels)
func_delete_labels(array_1M_daily_labels)
for [i, p] in array_daily_pivots
if not func_check_level(i)
array.push(array_1m_daily_lines, na)
array.push(array_5m_daily_lines, na)
array.push(array_15m_daily_lines, na)
array.push(array_1h_daily_lines, na)
array.push(array_4h_daily_lines, na)
array.push(array_1d_daily_lines, na)
array.push(array_1w_daily_lines, na)
array.push(array_1M_daily_lines, na)
array.push(array_1m_daily_labels, na)
array.push(array_5m_daily_labels, na)
array.push(array_15m_daily_labels, na)
array.push(array_1h_daily_labels, na)
array.push(array_4h_daily_labels, na)
array.push(array_1d_daily_labels, na)
array.push(array_1w_daily_labels, na)
array.push(array_1M_daily_labels, na)
continue
// 1m
if input_1m_daily and timeframe.period == "1"
l = line.new(time, array.get(array_daily_pivots, i), time + timeframe.in_seconds("1D") * 1000, array.get(array_daily_pivots, i), xloc = xloc.bar_time, color = input_color_daily)
array.push(array_1m_daily_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1D") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_daily_pivots, i), "D" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_daily)
array.push(array_1m_daily_labels, l2)
// 5m
if input_5m_daily and timeframe.period == "5"
l = line.new(time, array.get(array_daily_pivots, i), time + timeframe.in_seconds("1D") * 1000, array.get(array_daily_pivots, i), xloc = xloc.bar_time, color = input_color_daily)
array.push(array_5m_daily_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1D") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_daily_pivots, i), "D" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_daily)
array.push(array_5m_daily_labels, l2)
// 15m
if input_15m_daily and timeframe.period == "15"
l = line.new(time, array.get(array_daily_pivots, i), time + timeframe.in_seconds("1D") * 1000, array.get(array_daily_pivots, i), xloc = xloc.bar_time, color = input_color_daily)
array.push(array_15m_daily_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1D") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_daily_pivots, i), "D" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_daily)
array.push(array_15m_daily_labels, l2)
// 1h
if input_1h_daily and timeframe.period == "60"
l = line.new(time, array.get(array_daily_pivots, i), time + timeframe.in_seconds("1D") * 1000, array.get(array_daily_pivots, i), xloc = xloc.bar_time, color = input_color_daily)
array.push(array_1h_daily_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1D") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_daily_pivots, i), "D" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_daily)
array.push(array_1h_daily_labels, l2)
// 4h
if input_4h_daily and timeframe.period == "240"
l = line.new(time, array.get(array_daily_pivots, i), time + timeframe.in_seconds("1D") * 1000, array.get(array_daily_pivots, i), xloc = xloc.bar_time, color = input_color_daily)
array.push(array_4h_daily_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1D") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_daily_pivots, i), "D" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_daily)
array.push(array_4h_daily_labels, l2)
// 1d
if input_1d_daily and timeframe.period == "D"
l = line.new(time, array.get(array_daily_pivots, i), time + timeframe.in_seconds("1D") * 1000, array.get(array_daily_pivots, i), xloc = xloc.bar_time, color = input_color_daily)
array.push(array_1h_daily_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1D") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_daily_pivots, i), "D" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_daily)
array.push(array_1d_daily_labels, l2)
// 1w
if input_1w_daily and timeframe.period == "W"
l = line.new(time, array.get(array_daily_pivots, i), time + timeframe.in_seconds("1D") * 1000, array.get(array_daily_pivots, i), xloc = xloc.bar_time, color = input_color_daily)
array.push(array_1w_daily_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1D") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_daily_pivots, i), "D" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_daily)
array.push(array_1w_daily_labels, l2)
// 1M
if input_1M_daily and timeframe.period == "M"
l = line.new(time, array.get(array_daily_pivots, i), time + timeframe.in_seconds("1D") * 1000, array.get(array_daily_pivots, i), xloc = xloc.bar_time, color = input_color_daily)
array.push(array_1M_daily_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1D") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_daily_pivots, i), "D" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_daily)
array.push(array_1M_daily_labels, l2)
// Weekly Pivot
if is_week_change and func_is_calc("weekly")
func_delete_lines(array_1m_weekly_lines)
func_delete_lines(array_5m_weekly_lines)
func_delete_lines(array_15m_weekly_lines)
func_delete_lines(array_1h_weekly_lines)
func_delete_lines(array_4h_weekly_lines)
func_delete_lines(array_1d_weekly_lines)
func_delete_lines(array_1w_weekly_lines)
func_delete_lines(array_1M_weekly_lines)
func_delete_labels(array_1m_weekly_labels)
func_delete_labels(array_5m_weekly_labels)
func_delete_labels(array_15m_weekly_labels)
func_delete_labels(array_1h_weekly_labels)
func_delete_labels(array_4h_weekly_labels)
func_delete_labels(array_1d_weekly_labels)
func_delete_labels(array_1w_weekly_labels)
func_delete_labels(array_1M_weekly_labels)
for [i, p] in array_weekly_pivots
if not func_check_level(i)
array.push(array_1m_weekly_lines, na)
array.push(array_5m_weekly_lines, na)
array.push(array_15m_weekly_lines, na)
array.push(array_1h_weekly_lines, na)
array.push(array_4h_weekly_lines, na)
array.push(array_1d_weekly_lines, na)
array.push(array_1w_weekly_lines, na)
array.push(array_1M_weekly_lines, na)
array.push(array_1m_weekly_labels, na)
array.push(array_5m_weekly_labels, na)
array.push(array_15m_weekly_labels, na)
array.push(array_1h_weekly_labels, na)
array.push(array_4h_weekly_labels, na)
array.push(array_1d_weekly_labels, na)
array.push(array_1w_weekly_labels, na)
array.push(array_1M_weekly_labels, na)
continue
// 1m
if input_1m_weekly and timeframe.period == "1"
l = line.new(time, array.get(array_weekly_pivots, i), time + timeframe.in_seconds("1W") * 1000, array.get(array_weekly_pivots, i), xloc = xloc.bar_time, color = input_color_weekly)
array.push(array_1m_weekly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1W") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_weekly_pivots, i), "W" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_weekly)
array.push(array_1m_weekly_labels, l2)
// 5m
if input_5m_weekly and timeframe.period == "5"
l = line.new(time, array.get(array_weekly_pivots, i), time + timeframe.in_seconds("1W") * 1000, array.get(array_weekly_pivots, i), xloc = xloc.bar_time, color = input_color_weekly)
array.push(array_5m_weekly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1W") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_weekly_pivots, i), "W" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_weekly)
array.push(array_5m_weekly_labels, l2)
// 15m
if input_15m_weekly and timeframe.period == "15"
l = line.new(time, array.get(array_weekly_pivots, i), time + timeframe.in_seconds("1W") * 1000, array.get(array_weekly_pivots, i), xloc = xloc.bar_time, color = input_color_weekly)
array.push(array_15m_weekly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1W") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_weekly_pivots, i), "W" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_weekly)
array.push(array_15m_weekly_labels, l2)
// 1h
if input_1h_weekly and timeframe.period == "60"
l = line.new(time, array.get(array_weekly_pivots, i), time + timeframe.in_seconds("1W") * 1000, array.get(array_weekly_pivots, i), xloc = xloc.bar_time, color = input_color_weekly)
array.push(array_1h_weekly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1W") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_weekly_pivots, i), "W" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_weekly)
array.push(array_1h_weekly_labels, l2)
// 4h
if input_4h_weekly and timeframe.period == "240"
l = line.new(time, array.get(array_weekly_pivots, i), time + timeframe.in_seconds("1W") * 1000, array.get(array_weekly_pivots, i), xloc = xloc.bar_time, color = input_color_weekly)
array.push(array_4h_weekly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1W") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_weekly_pivots, i), "W" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_weekly)
array.push(array_4h_weekly_labels, l2)
// 1d
if input_1d_weekly and timeframe.period == "D"
l = line.new(time, array.get(array_weekly_pivots, i), time + timeframe.in_seconds("1W") * 1000, array.get(array_weekly_pivots, i), xloc = xloc.bar_time, color = input_color_weekly)
array.push(array_1h_weekly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1W") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_weekly_pivots, i), "W" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_weekly)
array.push(array_1d_weekly_labels, l2)
// 1w
if input_1w_weekly and timeframe.period == "W"
l = line.new(time, array.get(array_weekly_pivots, i), time + timeframe.in_seconds("1W") * 1000, array.get(array_weekly_pivots, i), xloc = xloc.bar_time, color = input_color_weekly)
array.push(array_1w_weekly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1W") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_weekly_pivots, i), "W" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_weekly)
array.push(array_1w_weekly_labels, l2)
// 1M
if input_1M_weekly and timeframe.period == "M"
l = line.new(time, array.get(array_weekly_pivots, i), time + timeframe.in_seconds("1W") * 1000, array.get(array_weekly_pivots, i), xloc = xloc.bar_time, color = input_color_weekly)
array.push(array_1M_weekly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + timeframe.in_seconds("1W") * 1000
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_weekly_pivots, i), "W" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_weekly)
array.push(array_1M_weekly_labels, l2)
// Monthly Pivot
if (is_month_change or bar_index == 0) and func_is_calc("monthly")
func_delete_lines(array_1m_monthly_lines)
func_delete_lines(array_5m_monthly_lines)
func_delete_lines(array_15m_monthly_lines)
func_delete_lines(array_1h_monthly_lines)
func_delete_lines(array_4h_monthly_lines)
func_delete_lines(array_1d_monthly_lines)
func_delete_lines(array_1w_monthly_lines)
func_delete_lines(array_1M_monthly_lines)
func_delete_labels(array_1m_monthly_labels)
func_delete_labels(array_5m_monthly_labels)
func_delete_labels(array_15m_monthly_labels)
func_delete_labels(array_1h_monthly_labels)
func_delete_labels(array_4h_monthly_labels)
func_delete_labels(array_1d_monthly_labels)
func_delete_labels(array_1w_monthly_labels)
func_delete_labels(array_1M_monthly_labels)
for [i, p] in array_monthly_pivots
if not func_check_level(i)
array.push(array_1m_monthly_lines, na)
array.push(array_5m_monthly_lines, na)
array.push(array_15m_monthly_lines, na)
array.push(array_1h_monthly_lines, na)
array.push(array_4h_monthly_lines, na)
array.push(array_1d_monthly_lines, na)
array.push(array_1w_monthly_lines, na)
array.push(array_1M_monthly_lines, na)
array.push(array_1m_monthly_labels, na)
array.push(array_5m_monthly_labels, na)
array.push(array_15m_monthly_labels, na)
array.push(array_1h_monthly_labels, na)
array.push(array_4h_monthly_labels, na)
array.push(array_1d_monthly_labels, na)
array.push(array_1w_monthly_labels, na)
array.push(array_1M_monthly_labels, na)
continue
// 1m
if input_1m_monthly and timeframe.period == "1"
l = line.new(time, array.get(array_monthly_pivots, i), time_close("1M"), array.get(array_monthly_pivots, i), xloc = xloc.bar_time, color = input_color_monthly)
array.push(array_1m_monthly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("1M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_monthly_pivots, i), "M" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_monthly)
array.push(array_1m_monthly_labels, l2)
// 5m
if input_5m_monthly and timeframe.period == "5"
l = line.new(time, array.get(array_monthly_pivots, i), time_close("1M"), array.get(array_monthly_pivots, i), xloc = xloc.bar_time, color = input_color_monthly)
array.push(array_5m_monthly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("1M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_monthly_pivots, i), "M" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_monthly)
array.push(array_5m_monthly_labels, l2)
// 15m
if input_15m_monthly and timeframe.period == "15"
l = line.new(time, array.get(array_monthly_pivots, i), time_close("1M"), array.get(array_monthly_pivots, i), xloc = xloc.bar_time, color = input_color_monthly)
array.push(array_15m_monthly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("1M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_monthly_pivots, i), "M" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_monthly)
array.push(array_15m_monthly_labels, l2)
// 1h
if input_1h_monthly and timeframe.period == "60"
l = line.new(time, array.get(array_monthly_pivots, i), time_close("1M"), array.get(array_monthly_pivots, i), xloc = xloc.bar_time, color = input_color_monthly)
array.push(array_1h_monthly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("1M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_monthly_pivots, i), "M" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_monthly)
array.push(array_1h_monthly_labels, l2)
// 4h
if input_4h_monthly and timeframe.period == "240"
l = line.new(time, array.get(array_monthly_pivots, i), time_close("1M"), array.get(array_monthly_pivots, i), xloc = xloc.bar_time, color = input_color_monthly)
array.push(array_4h_monthly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("1M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_monthly_pivots, i), "M" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_monthly)
array.push(array_4h_monthly_labels, l2)
// 1d
if input_1d_monthly and timeframe.period == "D"
l = line.new(time, array.get(array_monthly_pivots, i), time_close("1M"), array.get(array_monthly_pivots, i), xloc = xloc.bar_time, color = input_color_monthly)
array.push(array_1h_monthly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + time_close("1M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_monthly_pivots, i), "M" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_monthly)
array.push(array_1d_monthly_labels, l2)
// 1w
if input_1w_monthly and timeframe.period == "W"
l = line.new(time, array.get(array_monthly_pivots, i), time_close("1M"), array.get(array_monthly_pivots, i), xloc = xloc.bar_time, color = input_color_monthly)
array.push(array_1w_monthly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("1M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_monthly_pivots, i), "M" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_monthly)
array.push(array_1w_monthly_labels, l2)
// 1M
if input_1M_monthly and timeframe.period == "M"
l = line.new(time, array.get(array_monthly_pivots, i), time_close("1M"), array.get(array_monthly_pivots, i), xloc = xloc.bar_time, color = input_color_monthly)
array.push(array_1M_monthly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("1M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_monthly_pivots, i), "M" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_monthly)
array.push(array_1M_monthly_labels, l2)
// Yearly Pivot
if (is_year_change or bar_index == 0) and func_is_calc("yearly")
func_delete_lines(array_1m_yearly_lines)
func_delete_lines(array_5m_yearly_lines)
func_delete_lines(array_15m_yearly_lines)
func_delete_lines(array_1h_yearly_lines)
func_delete_lines(array_4h_yearly_lines)
func_delete_lines(array_1d_yearly_lines)
func_delete_lines(array_1w_yearly_lines)
func_delete_lines(array_1M_yearly_lines)
func_delete_labels(array_1m_yearly_labels)
func_delete_labels(array_5m_yearly_labels)
func_delete_labels(array_15m_yearly_labels)
func_delete_labels(array_1h_yearly_labels)
func_delete_labels(array_4h_yearly_labels)
func_delete_labels(array_1d_yearly_labels)
func_delete_labels(array_1w_yearly_labels)
func_delete_labels(array_1M_yearly_labels)
for [i, p] in array_yearly_pivots
if not func_check_level(i)
array.push(array_1m_yearly_lines, na)
array.push(array_5m_yearly_lines, na)
array.push(array_15m_yearly_lines, na)
array.push(array_1h_yearly_lines, na)
array.push(array_4h_yearly_lines, na)
array.push(array_1d_yearly_lines, na)
array.push(array_1w_yearly_lines, na)
array.push(array_1M_yearly_lines, na)
array.push(array_1m_yearly_labels, na)
array.push(array_5m_yearly_labels, na)
array.push(array_15m_yearly_labels, na)
array.push(array_1h_yearly_labels, na)
array.push(array_4h_yearly_labels, na)
array.push(array_1d_yearly_labels, na)
array.push(array_1w_yearly_labels, na)
array.push(array_1M_yearly_labels, na)
continue
// 1m
if input_1m_yearly and timeframe.period == "1"
l = line.new(time, array.get(array_yearly_pivots, i), time_close("12M"), array.get(array_yearly_pivots, i), xloc = xloc.bar_time, color = input_color_yearly)
array.push(array_1m_yearly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("12M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_yearly_pivots, i), "Y" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_yearly)
array.push(array_1m_yearly_labels, l2)
// 5m
if input_5m_yearly and timeframe.period == "5"
l = line.new(time, array.get(array_yearly_pivots, i), time_close("12M"), array.get(array_yearly_pivots, i), xloc = xloc.bar_time, color = input_color_yearly)
array.push(array_5m_yearly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("12M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_yearly_pivots, i), "Y" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_yearly)
array.push(array_5m_yearly_labels, l2)
// 15m
if input_15m_yearly and timeframe.period == "15"
l = line.new(time, array.get(array_yearly_pivots, i), time_close("12M"), array.get(array_yearly_pivots, i), xloc = xloc.bar_time, color = input_color_yearly)
array.push(array_15m_yearly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("12M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_yearly_pivots, i), "Y" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_yearly)
array.push(array_15m_yearly_labels, l2)
// 1h
if input_1h_yearly and timeframe.period == "60"
l = line.new(time, array.get(array_yearly_pivots, i), time_close("12M"), array.get(array_yearly_pivots, i), xloc = xloc.bar_time, color = input_color_yearly)
array.push(array_1h_yearly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("12M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_yearly_pivots, i), "Y" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_yearly)
array.push(array_1h_yearly_labels, l2)
// 4h
if input_4h_yearly and timeframe.period == "240"
l = line.new(time, array.get(array_yearly_pivots, i), time_close("12M"), array.get(array_yearly_pivots, i), xloc = xloc.bar_time, color = input_color_yearly)
array.push(array_4h_yearly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("12M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_yearly_pivots, i), "Y" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_yearly)
array.push(array_4h_yearly_labels, l2)
// 1d
if input_1d_yearly and timeframe.period == "D"
l = line.new(time, array.get(array_yearly_pivots, i), time_close("12M"), array.get(array_yearly_pivots, i), xloc = xloc.bar_time, color = input_color_yearly)
array.push(array_1h_yearly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("12M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_yearly_pivots, i), "Y" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_yearly)
array.push(array_1d_yearly_labels, l2)
// 1w
if input_1w_yearly and timeframe.period == "W"
l = line.new(time, array.get(array_yearly_pivots, i), time_close("12M"), array.get(array_yearly_pivots, i), xloc = xloc.bar_time, color = input_color_yearly)
array.push(array_1w_yearly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("12M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_yearly_pivots, i), "Y" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_yearly)
array.push(array_1w_yearly_labels, l2)
// 1M
if input_1M_yearly and timeframe.period == "M"
l = line.new(time, array.get(array_yearly_pivots, i), time_close("12M"), array.get(array_yearly_pivots, i), xloc = xloc.bar_time, color = input_color_yearly)
array.push(array_1M_yearly_lines, l)
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time_close("12M")
label_style := label.style_label_left
l2 = label.new(label_x, array.get(array_yearly_pivots, i), "Y" + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_yearly)
array.push(array_1M_yearly_labels, l2)
// Market Pivot
if (is_start_tokyo or is_start_london or is_start_newyork) and func_is_calc("market")
func_delete_lines(array_1m_market_lines)
func_delete_lines(array_5m_market_lines)
func_delete_lines(array_15m_market_lines)
func_delete_labels(array_1m_market_labels)
func_delete_labels(array_5m_market_labels)
func_delete_labels(array_15m_market_labels)
int x2_len = 0
string label_str = ""
if is_start_tokyo
x2_len := 9 * 60 * 60 * 1000
label_str := "MKT:T"
else if is_start_london
x2_len := 6 * 60 * 60 * 1000
label_str := "MKT:L"
else if is_start_newyork
x2_len := 9 * 60 * 60 * 1000
label_str := "MKT:N"
label_x = 0
label_style = ""
if input_position_label == "Left"
if input_position_leftlabel_float
label_x := chart.left_visible_bar_time < time ? time : chart.left_visible_bar_time
label_style := chart.left_visible_bar_time < time ? label.style_label_right : label.style_label_left
else
label_x := time
label_style := label.style_label_right
else
label_x := time + x2_len
label_style := label.style_label_left
for [i, p] in array_market_pivots
if not func_check_level(i)
array.push(array_1m_market_lines, na)
array.push(array_5m_market_lines, na)
array.push(array_15m_market_lines, na)
array.push(array_1m_market_labels, na)
array.push(array_5m_market_labels, na)
array.push(array_15m_market_labels, na)
continue
// 1m
if input_1m_market and timeframe.period == "1"
l = line.new(time, array.get(array_market_pivots, i), time + x2_len, array.get(array_market_pivots, i), xloc = xloc.bar_time, color = input_color_market)
array.push(array_1m_market_lines, l)
l2 = label.new(label_x, array.get(array_market_pivots, i), label_str + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_market)
array.push(array_1m_market_labels, l2)
// 5m
if input_5m_market and timeframe.period == "5"
l = line.new(time, array.get(array_market_pivots, i), time + x2_len, array.get(array_market_pivots, i), xloc = xloc.bar_time, color = input_color_market)
array.push(array_5m_market_lines, l)
l2 = label.new(label_x, array.get(array_market_pivots, i), label_str + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_market)
array.push(array_5m_market_labels, l2)
// 15m
if input_15m_market and timeframe.period == "15"
l = line.new(time, array.get(array_market_pivots, i), time + x2_len, array.get(array_market_pivots, i), xloc = xloc.bar_time, color = input_color_market)
array.push(array_15m_market_lines, l)
l2 = label.new(label_x, array.get(array_market_pivots, i), label_str + array.get(array_label_str, i), xloc = xloc.bar_time, color = chart.bg_color, style = label_style, textcolor = input_color_market)
array.push(array_15m_market_labels, l2)
|
Pullback Warning | https://www.tradingview.com/script/YgZKVl2C-Pullback-Warning/ | Amphibiantrading | https://www.tradingview.com/u/Amphibiantrading/ | 247 | 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/
// © Amphibiantrading
//@version=5
indicator("Pullback Warning", overlay = true)
//constants
EMA9 = ta.ema(close, 9)
EMA20 = ta.ema(close, 20)
SMA50 = ta.sma(close, 50)
//inputs
sensitivity = input.string('Normal', 'Sensitivity', options = ['Normal', 'More', 'Less'])
bgFill = input.bool(true, 'Highlight Backgrond', inline = '1')
bgCol = input.color(color.new(color.red,85), ' ', inline = '1')
showShape = input.bool(true, 'Show Symbol', inline = '2')
shapeLocation = input.string('Above Bar', ' ', options = ['Above Bar', 'Below Bar', 'Bottom', 'Top'], inline = '2')
//switches
senseNum = switch sensitivity
'Normal' => 6
'More' => 5
'Less' => 7
loc = switch shapeLocation
'Above Bar' => location.abovebar
'Below Bar' => location.belowbar
'Bottom' => location.bottom
'Top' => location.top
//calculations
distMa1 = math.round(((close / EMA9) -1 ) *100, 1)
distMas = math.round(((EMA9 / EMA20) - 1) * 100, 1)
dist50 = math.round(((close / SMA50) -1 ) *100, 1)
//condition
extended = distMa1 > distMas and dist50 >= senseNum
//plots
plotshape(extended and showShape ? 1 : 0, 'Extended', loc == location.abovebar or loc == location.top ? shape.triangledown : shape.triangleup,
loc, color.red, display = display.pane)
bgcolor(bgFill and extended ? bgCol : na) |
EFFR Range Visualizer | https://www.tradingview.com/script/fl2oe1Tn-EFFR-Range-Visualizer/ | CSC1 | https://www.tradingview.com/u/CSC1/ | 4 | 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/
// © CSC1
//@version=5
indicator("EFFR Range Visualizer",overlay = true)
target_upper = 100-(request.security("DFEDTARU","D",close))
target_lower = 100-(request.security("DFEDTARL","D",close))
plot(target_lower)
plot(target_upper) |
gZScore | https://www.tradingview.com/script/ihvXeV6C-gZScore/ | giancarlopagliaroli | https://www.tradingview.com/u/giancarlopagliaroli/ | 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/
// © giancarlopagliaroli
//@version=5
indicator(title="gZScore", shorttitle="gZScore", overlay=false, precision=2)
//252 days in one year
length = input(252, title="Length on timeframe daily")
source = input(close, title="Source")
color_score = input.color(color.white, "Z-Score")
color_average = input.color(color.white, "Average")
//Z-score is a standardized measure of displacement from the mean; z = (x – x̄) /s̄.
//Standardization allows the displacement to be compared between different sources, even if their values are significantly different.
//mean over last day
if timeframe.period == '5'
length := 1440/5
//mean over last week
if timeframe.period == '30'
length := (1440/30)*5
//mean over last month
if timeframe.period == '240'
length := (1440/240)*4
//mean over last year
if timeframe.period == 'D'
length := length
//mean over last 3 year
if timeframe.period == 'W'
length := 52 * 3
//mean over last 5 year
if timeframe.period == 'M'
length := 12 * 5
mean=ta.sma(source,length)
float deviation=ta.stdev(source,length)
float displacement=source-mean
float zscore=displacement/deviation
zmean=ta.sma(zscore,length)
//Plots
plot(zscore,color=color_score,title="Z-Score", linewidth = 2)
plot(zmean,title="Z-Score Average", color = color_average, linewidth = 1)
plot(0, title = 'ZScore 0' ) //mean
plot(1, color = color.yellow, title = 'ZScore 1')
plot(-1, color = color.yellow, title = 'ZScore -1')
plot(-2, color = color.orange, title = 'ZScore -2')
plot(2, color = color.orange, title = 'ZScore 2')
plot(-3, color = color.red, title = 'ZScore -3')
plot(3, color = color.red, title = 'ZScore 3')
plot(-5, color = color.red, linewidth = 2, title = 'ZScore -5')
plot(5, color = color.red, linewidth = 2, title = 'ZScore 5') |
Supply and Demand Based Pattern [RH] | https://www.tradingview.com/script/N1UG66qp-Supply-and-Demand-Based-Pattern-RH/ | HasanRifat | https://www.tradingview.com/u/HasanRifat/ | 515 | 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/
// © HasanRifat
//@version=5
indicator("Supply and Demand Based Pattern [RH]", overlay = true, max_lines_count = 500, max_boxes_count = 500)
// Tooltips
bodyHealthTip = "Our objective is to establish a stronger initial momentum by ensuring the presence of at least one candle with 60% health during the first rise/drop phase."
baseRetracementTip = "This input parameter ensures that the base retracement remains below 80%. By decreasing the value, we can effectively limit the extent of retracement, thus minimizing the potential for excessive pullbacks."
// User freedom
bodyHealthInput = input.int(defval = 60, title = "Candle Health %", minval = 1, maxval = 100, tooltip = bodyHealthTip)
baseRetracement = input.float(defval = 0.80, title = "Base Max Retracement", minval = 0.1, maxval = 1, tooltip = baseRetracementTip)
var float bullLow1 = na
var float bullLow2 = na
var float bullHigh = na
var int bullPass = 0
var int bullLineX1 = na
var float bearHigh1 = na
var float bearHigh2 = na
var float bearLow = na
var int bearPass = 0
var int bearLineX1 = na
bool bullPattern = na
bool bearPattern = na
var int activePattern = na
var int bullFinalLoopIndex = na
var int bullLeft = na
var int bullRight = na
var float bullTop = na
var float bullBottom = na
var int bearLeft = na
var int bearRight = na
var float bearTop = na
var float bearBottom = na
var bullHighArray = array.new_float()
var bullLow1Array = array.new_float()
var bullLow2Array = array.new_float()
var bullLineX1Array = array.new_int()
var bearLowArray = array.new_float()
var bearHigh1Array = array.new_float()
var bearHigh2Array = array.new_float()
var bearLineX1Array = array.new_int()
// Candle type for future calculations
bullCandle = close > open
bearCandle = close < open
// Body health calculation
a = high - low
b = close > open ? close - open : open - close
bodyHealth = ((a-b)/a)*100
bullHealthPass = 0
bearHealthPass = 0
// First hook for RBR
if bullCandle and close > high[1]
if bullPass[1] < 2
bullPass := 1
// Base initialization and first rise value gathering
if bullPass == 1 and bearCandle
for i = 1 to 10
if bullCandle[i]
array.push(bullLow1Array, open[i])
array.push(bullHighArray, high[i])
array.push(bullLineX1Array, bar_index[i])
if bodyHealth[i] < (100 - bodyHealthInput)
bullHealthPass := bullHealthPass + 1
if bearCandle[i]
break
bullLow1 := array.min(bullLow1Array)
bullLineX1 := array.min(bullLineX1Array)
if bullHealthPass > 0
if close > bullLow1
array.push(bullHighArray, high)
bullPass := 2
bullFinalLoopIndex := bar_index
bullLeft := bar_index - 1
bullRight := bar_index + 1
bullTop := high>high[1] ? high : high[1]
bullBottom := low
if close < bullLow1
bullPass := 0
if bullHealthPass < 0
bullPass := 0
if bullPass == 2 and bearCandle
if close < bullLow1
bullPass := 0
// RBR Pattern confirmation
if bullPass == 2 and bullCandle
bullHigh := array.max(bullHighArray)
if close < bullHigh
bullPass := 3
bullBottom := low[1]
if close > bullHigh
bullPass := 1
for i = 0 to (bar_index-bullFinalLoopIndex)
array.push(bullLow2Array, low[i])
bullLow2 := array.min(bullLow2Array)
if bullLow2 > bullLow1 + (bullHigh - bullLow1)*(1-baseRetracement)
bullPattern := true
activePattern := 1
box.new(bullLeft, bullTop, bar_index, bullBottom, bgcolor = color.new(color.green, 60), border_color = na)
line.new(bullLineX1, bullLow1, bar_index, bullLow1, color = color.green)
line.new(bar_index, bullLow1, bar_index, low, color = color.green, style = line.style_dashed)
if bullPass == 3 and bearCandle
bullPass := 0
if bullPass == 3 and bullCandle
if close > bullHigh
bullPass := 1
for i = 0 to (bar_index-bullFinalLoopIndex)
array.push(bullLow2Array, low[i])
bullLow2 := array.min(bullLow2Array)
if bullLow2 > bullLow1 + (bullHigh - bullLow1)*(1-baseRetracement)
bullPattern := true
activePattern := 1
box.new(bullLeft, bullTop, bar_index, bullBottom, bgcolor = color.new(color.green, 60), border_color = na)
line.new(bullLineX1, bullLow1, bar_index, bullLow1, color = color.green)
line.new(bar_index, bullLow1, bar_index, low, color = color.green, style = line.style_dashed)
if bullPass == 1
array.clear(bullHighArray)
array.clear(bullLow1Array)
array.clear(bullLow2Array)
array.clear(bullLineX1Array)
// First hook for DBD
if bearCandle and close < low[1]
if bearPass[1] < 2
bearPass := 1
//Base initialization and first drop value gathering
if bearPass == 1 and bullCandle
for i = 1 to 10
if bearCandle[i]
array.push(bearHigh1Array, open[i])
array.push(bearLowArray, low[i])
array.push(bearLineX1Array, bar_index[i])
if bodyHealth[i] < (100 - bodyHealthInput)
bullHealthPass := bullHealthPass + 1
if bullCandle[i]
break
bearHigh1 := array.max(bearHigh1Array)
bearLineX1 := array.min(bearLineX1Array)
if bullHealthPass > 0
if close < bearHigh1
array.push(bearLowArray, low)
bearPass := 2
bullFinalLoopIndex := bar_index
bearLeft := bar_index - 1
bearRight := bar_index + 1
bearTop := high
bearBottom := low < low[1] ? low : low[1]
if close > bearHigh1
bearPass := 0
if bullHealthPass < 0
bearPass := 0
if bearPass == 2 and bullCandle
if close > bearHigh1
bearPass := 0
// DBD Pattern confirmation
if bearPass == 2 and bearCandle
bearLow := array.min(bearLowArray)
if close > bearLow
bearPass := 3
bearTop := high[1]
if close < bearLow
bearPass := 1
for i = 0 to (bar_index-bullFinalLoopIndex)
array.push(bearHigh2Array, high[i])
bearHigh2 := array.max(bearHigh2Array)
if bearHigh2 < bearHigh1 - (bearHigh1 - bearLow)*(1-baseRetracement)
bearPattern := true
activePattern := -1
box.new(bearLeft, bearTop, bar_index, bearBottom, bgcolor = color.new(color.red, 60), border_color = na)
line.new(bearLineX1, bearHigh1, bar_index, bearHigh1, color = color.red)
line.new(bar_index, bearHigh1, bar_index, high, color = color.red, style = line.style_dashed)
if bearPass == 3 and bullCandle
bearPass := 0
if bearPass == 3 and bearCandle
if close < bearLow
bearPass := 1
for i = 0 to (bar_index-bullFinalLoopIndex)
array.push(bearHigh2Array, high[i])
bearHigh2 := array.max(bearHigh2Array)
if bearHigh2 < bearHigh1 - (bearHigh1 - bearLow)*(1-baseRetracement)
bearPattern := true
activePattern := -1
box.new(bearLeft, bearTop, bar_index, bearBottom, bgcolor = color.new(color.red, 60), border_color = na)
line.new(bearLineX1, bearHigh1, bar_index, bearHigh1, color = color.red)
line.new(bar_index, bearHigh1, bar_index, high, color = color.red, style = line.style_dashed)
if bearPass == 1
array.clear(bearLowArray)
array.clear(bearHigh1Array)
array.clear(bearHigh2Array)
array.clear(bearLineX1Array)
bullFirst = activePattern == 1 and activePattern[1] == -1
bearFirst = activePattern == -1 and activePattern[1] == 1
// Plotting
plotshape(bullFirst, title = "Bull Pattern", style = shape.labelup, color = color.green, location = location.belowbar, size = size.tiny, text = "RBR", textcolor = color.white)
plotshape(bearFirst, title = "Bear Pattern", style = shape.labeldown, color = color.red, location = location.abovebar, size = size.tiny, text = "DBD", textcolor = color.white)
// Alerts
alertcondition(bullPattern, title = "All Bullish(RBR) Pattern", message = "RBR")
alertcondition(bearPattern, title = "All Bearish(DBD) Pattern", message = "DBD")
alertcondition(bullFirst, title = "First Bullish(RBR) Pattern", message = "1st RBR")
alertcondition(bearFirst, title = "First Bearish(DBD) Pattern", message = "1st DBD")
|
[DisDev] D-I-Y Gridbot | https://www.tradingview.com/script/DNi9L4fk-DisDev-D-I-Y-Gridbot/ | DisDev | https://www.tradingview.com/u/DisDev/ | 445 | 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/
// © xxattaxx-DisDev
//@version=5
Indicator = '[DisDev] D-I-Y Gridbot'
indicator(Indicator, overlay=true)
//Create variables for tooltips for easier code readability
ttTrigger = 'Candle location to trigger the signal. "Wick" will use either high or low, depending on the signal direction. "Close" will use the close price. "MA" will use the MA/moving average.'
ttConfirm = 'Market direction to confirm thr candle trigger. "Reverse" will confirm the signal when the price crosses back over the trigger. "Breakout" will confirm when the price breaks out of the trigger.'
ttMAtype = 'Exponential Moving Average (EMA), Hull Moving Average (HMA), Simple Moving Average (SMA), Triple Exponential Moving Average (TEMA), Volume Weighted Moving Average (VWMA), Volume Weighted Average Price (VWAP)'
ttFill = 'Fill the area between the upper and lower gridlines. "MA" will fill between the MA and the gridlines. "Signal" will fill between the signal and the gridlines. "Source" will fill between the buy/sell source and the gridlines.'
ttZones = 'Number of Support/Resistance zones. 1: Only Top Grid is Support/Only Bottom Grid is Resistance. 2: Top two grids are Resistance/Bottom two grids are Support. 3:Top three grids are Resistance/Bottom three grids are Support'
ttMA = 'Filter prices based on MA. No Buys above the MA. No Sells below the MA.'
ttRepeat = 'If checked, signals will repeat on the same gridline as previous signals if next gridline is crossed before the signal is confirmed. If unchecked, signals will not repeat on the same gridline.'
//Inputs
Trigger = input.string ('Wick', 'Trigger ', group='Signals', inline='trigger',
options = ['Wick', 'Close', 'MA'], tooltip=ttTrigger)
Confirm = input.string ('Breakout', 'Confirmation', group='Signals', inline='confirm',
options = ['Reverse', 'Breakout'], tooltip=ttConfirm)
zones = input.int (3, 'S/R Zones ', minval=1, maxval=3,group='Signals', inline='zones', tooltip=ttZones)
smLen = input.int (50, '', minval=1, group='MA', inline='MA', tooltip='MA Length')
smType = input.string ('ema', '',
options = ['ema', 'hull', 'sma', 'tema', 'vwma', 'vwap'], group='MA', inline='MA', tooltip=ttMAtype)
TF = input.timeframe('', '', group='MA', inline='MA1', tooltip='MA Timeframe')
smUse = input.bool (true, 'MA Filter', group='MA', inline='MA2', tooltip=ttMA)
repeat = input.bool (false, 'Allow Repeat Signals', group='MA', inline='MA2', tooltip=ttRepeat)
colMA = input.color (color.new(color.orange, 70), 'MA ', group='Colors', inline='grids')
colResist = input.color (color.new(color.red, 10), ' Grids ', group='Colors', inline='grids')
colMid = input.color (color.new(color.yellow, 30), '', group='Colors', inline='grids')
colSupp = input.color (color.new(color.green, 10), '', group='Colors', inline='grids')
colUpperTop = input.color (color.new(#FF0000, 75), 'Fill ', group='Colors', inline='fill')
colLowerTop = input.color (color.new(#228B22, 75), '', group='Colors', inline='fill')
colUpperBot = color.new (colUpperTop, 98)
colLowerBot = color.new (colLowerTop, 98)
filltype = input.string ('MA', '', group='Colors', inline='fill',
options =['none', 'MA', 'Signal', 'Source'], tooltip=ttFill)
Price0_ = input.price (0.0, '(1 of 6)', group='Girdlines', inline='upper', confirm=true)
Price1_ = input.price (0.0, '(2 of 6)', group='Girdlines', inline='upper', confirm=true)
Price2_ = input.price (0.0, '(3 of 6)', group='Girdlines', inline='middle', confirm=true)
Price3_ = input.price (0.0, '(4 of 6)', group='Girdlines', inline='middle', confirm=true)
Price4_ = input.price (0.0, '(5 of 6)', group='Girdlines', inline='lower', confirm=true)
Price5_ = input.price (0.0, '(6 of 6)', group='Girdlines', inline='lower', confirm=true)
//Initialize Variables
var LastSignal=0, var LastSignal_Index=0, smSrc = close
// Moving Average / VWAP (note: smLen will have no effect on VWAP)
xMA = switch smType
'ema' => ta.ema(smSrc, smLen)
'hull' => ta.hma(smSrc, smLen)
'sma' => ta.sma(smSrc, smLen)
'tema' => ta.ema(ta.ema(ta.ema(smSrc, smLen), smLen), smLen)
'vwma' => ta.vwma(smSrc, smLen)
'vwap' => ta.vwap(smSrc)
=> ta.sma(smSrc, smLen)
MA = request.security(syminfo.tickerid, TF, barstate.isrealtime? xMA: xMA[1])
// BuySource and SellSource are dependent on candle trigger and confirmation. Wick: Use highs or lows for sell signals. Close: Use close for sell signals. MA: Use MA for sell signals.
BuySource = Trigger=='Wick'? low: Trigger == 'MA'? MA : close
SellSource = Trigger=='Wick'? high: Trigger == 'MA'? MA : close
//Create an array from all the input levels so they can be sorted
GridArray = array.from(Price0_,Price1_,Price2_,Price3_,Price4_,Price5_)
array.sort(GridArray)
LowerLimit = array.get(GridArray,0), UpperLimit = array.get(GridArray,5)
//Draw Gridlines from first bar onward. No need to redraw every bar.
LineArray = array.new_line(5)
if barstate.isfirst
for i = 0 to 5
lColor = i >= 6 - zones ? colResist : i < zones? colSupp : colMid
Y = array.get(GridArray,i)
lWidth = i == 0 or i == 5? 2 : 1
array.push(LineArray, line.new(time, Y, time+1, Y, xloc=xloc.bar_time, width=lWidth, color=lColor, extend=extend.both))
// Get the nearest index to buy and sell. If none are found, both indexes will be -1.
Get_BuySell_Index() =>
BuyIndex = -1, SellIndex = -1
for [index,array_value] in GridArray
if Confirm == 'Breakout'
BuyIndex :=BuySource <= array_value and BuySource[1] > array_value? index : BuyIndex
SellIndex :=SellSource >= array_value and SellSource[1] < array_value? index : SellIndex
else //if Confirm == 'Reverse'
BuyIndex :=BuySource >= array_value and BuySource[1] < array_value? index : BuyIndex
SellIndex :=SellSource <= array_value and SellSource[1] > array_value? index : SellIndex
[BuyIndex,SellIndex]
[BuyLine_Index,SellLine_Index]=Get_BuySell_Index()
// Set Buy or Sell if any crosses were found. If none were found, both indexes would be -1 (the initial value set in the function)
Buy = BuyLine_Index >= 0
Sell = SellLine_Index >= 0
// No repeat signals at same grid level
Buy := BuyLine_Index >= LastSignal_Index? false : Buy
Sell := SellLine_Index <= LastSignal_Index? false : Sell
// MA Filters. No buys if price is above MA, no sells if price is below MA
Buy := smUse and BuySource > MA? false : Buy
Sell := smUse and SellSource < MA? false : Sell
// Zones. Calculate the max buy and min sell for each zone. If price is above max buy, no buys. If price is below min sell, no sells.
MaxBuy = array.get(GridArray,5-zones), MinSell = array.get(GridArray,zones)
Buy := BuySource > MaxBuy? false : Buy
Sell := SellSource < MinSell? false : Sell
// Track the last signal. We can use this to prevent repeat signals at the same grid level, or will reset if next grid level is reached (repeat)
LastSignal := Buy?1:Sell?-1:LastSignal
LastSignal_Index := Buy? BuyLine_Index : Sell? SellLine_Index : LastSignal_Index
LastSignal_Index := repeat and BuyLine_Index >= 0? BuyLine_Index : repeat and SellLine_Index >= 0? SellLine_Index : LastSignal_Index
// Plots. The lines must be plotted to be able to use them in the gradient fill.
sigPrice = array.get(GridArray,LastSignal_Index)
sigLine = plot (sigPrice, "Signal Price", color=na, display= display.none)
topLine = plot (UpperLimit, "Upper Limit", color=na, display= display.none)
botLine = plot (LowerLimit, "Lower Limit", color=na, display= display.none)
bsLine = plot (BuySource, "Buy Source", color=na, display= display.none)
ssLine = plot (SellSource, "Sell Source", color=na, display= display.none)
maLine = plot (MA, "MA", color = colMA, linewidth = 3)
// Gradient fill types. MA: MA line, Source: Buy/Sell Source, Signal: Last Signal Price
fill (maLine, botLine, MA, LowerLimit, filltype=='MA'? colLowerBot:na, filltype=='MA'? colLowerTop: na)
fill (maLine, topLine, MA, UpperLimit, filltype=='MA'? colUpperBot:na, filltype=='MA'? colUpperTop: na)
fill (bsLine, botLine, BuySource, LowerLimit, filltype=='Source'? colLowerBot:na, filltype=='Source'? colLowerTop: na)
fill (ssLine, topLine, SellSource, UpperLimit, filltype=='Source'? colUpperBot:na, filltype=='Source'? colUpperTop: na)
fill (sigLine, botLine, sigPrice, LowerLimit, filltype=='Signal'? colLowerBot:na, filltype=='Signal'? colLowerTop: na)
fill (sigLine, topLine, sigPrice, UpperLimit, filltype=='Signal'? colUpperBot:na, filltype=='Signal'? colUpperTop: na)
// Plot Signals
plotchar (Buy, 'Buy', color=color.new(#32CD32, 0), size=size.tiny, location=location.belowbar, char='▲')
plotchar (Sell, 'Sell', color=color.new(#EE4B2B, 0), size=size.tiny, location=location.abovebar, char='▼')
// Alerts
alertcondition (condition=Buy, title='buy', message='buy')
alertcondition (condition=Sell, title='sell', message='sell')
// Version Info
version = input.string('v1.00', options=['v1.00'], inline='1', group=Indicator)
date = input.string('06/19/2023', options=['06/19/2023'], inline='1', group=Indicator) |
London candle range | https://www.tradingview.com/script/rGUadasF/ | pula78 | https://www.tradingview.com/u/pula78/ | 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/
// © pula78
//@version=5
indicator("London candle range", overlay = true)
t1 = time_close(timeframe.period, "0900-1000", "Europe/Warsaw")
barcolor(t1 ? color.purple : na)
range_bar_middle = 0.0
range_bar_upper_band = 0.0
range_bar_lower_band = 0.0
if t1
range_bar_middle := math.abs(high - low) / 2 + low
range_bar_upper_band := math.abs(high - low) / 2 + high
range_bar_lower_band := low - (math.abs(high - low) / 2)
line.new(bar_index, low, bar_index + 5, low)
line.new(bar_index, high, bar_index + 5, high)
line.new(bar_index, range_bar_middle, bar_index + 5, range_bar_middle)
line.new(bar_index, range_bar_upper_band, bar_index + 5, range_bar_upper_band)
line.new(bar_index, range_bar_lower_band, bar_index + 5, range_bar_lower_band)
|
QFL Drop % | https://www.tradingview.com/script/AsJwouqw-QFL-Drop/ | AHMEDABDELAZIZZIZO | https://www.tradingview.com/u/AHMEDABDELAZIZZIZO/ | 24 | 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/
// © AHMEDABDELAZIZZIZO
//@version=5
indicator("QFL Drop %",overlay = true)
left = input(10)
right = input(10)
p = ta.pivotlow(low,left,right)
v = ta.valuewhen(p,low[left],0)
textcolor = input.color(color.white)
var float [] lows = array.new_float()
var float chn = na
if v < v[1]
chn := (v[1] -v )/ v[1] * 100
if array.size(lows) < 4000
array.push(lows, chn)
else
array.shift(lows)
array.push(lows, chn)
mediandrop = array.avg(lows)
maxdrop = array.max(lows)
mindrop = array.min(lows)
tabl = table.new(position = position.top_right, columns = 4, rows = 4)
table.cell(table_id = tabl , column = 1 , row = 1, text = "Avg Drop %" , width = 15 , text_color = textcolor)
table.cell(table_id = tabl , column = 2 , row = 1, text = "Min Drop %", width = 15 , text_color =textcolor)
table.cell(table_id = tabl , column = 3 , row = 1, text = "Max Drop %", width = 15 , text_color = textcolor)
table.cell(table_id = tabl , column = 1 , row = 2 , text = str.tostring(mediandrop), width = 10 , text_color = textcolor)
table.cell(table_id = tabl , column = 2 , row = 2 , text = str.tostring(mindrop), width = 10 , text_color = textcolor)
table.cell(table_id = tabl , column = 3 , row = 2 , text = str.tostring(maxdrop), width = 10 , text_color = textcolor)
t = fixnan(ta.pivotlow(low,left,right))
plot(t, color=ta.change(t) ? na : #03f590b6, linewidth=3, offset=-(right), title="Support") |
Trendilo LSMA Band Example | https://www.tradingview.com/script/Xb4BQ8GS-Trendilo-LSMA-Band-Example/ | dudeowns | https://www.tradingview.com/u/dudeowns/ | 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/
// © dudeowns
//@version=5
indicator("Trendilo LSMA",overlay = true)
length = input(title="LSMAlen", defval=25)
offset2 = input(title="LSMA Offset", defval=0)
smooth = input(title = "LSMA Smoother", defval = 5)
src = ta.ema(hl2, smooth)
lsma = ta.linreg(src, length, offset2)
length2 = input(title = "HMAlen", defval = 50)
hma = ta.hma(src, length2)
combine = math.avg(lsma, hma)
signal = combine - combine[1]
colorr = signal > 0 ? color.rgb(0, 255, 10) : signal < 0 ? color.rgb(254, 24, 7) : color.yellow
plot(combine, color = colorr, linewidth = 2)
|
% Stocks Above MA | https://www.tradingview.com/script/lfaaPPVQ-Stocks-Above-MA/ | marquardt1195 | https://www.tradingview.com/u/marquardt1195/ | 14 | 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/
// © marquardt1195
//@version=4
study(title="% Stocks Above MA", shorttitle="Marquardt Above MA")
market = input(defval="Overall", type=input.string, title="Select Market", options=["Overall", "SP500", "DJI", "Nasdaq", "Nasdaq100", "Russel2000", "Russel3000"])
dma = input(defval="20", type=input.string, title="Select DMA", options=["200", "150", "100", "50", "20", "5"])
ticker = ("Overall" == market) ? ("200" == dma) ? "MMTH" : ("150" == dma) ? "MMOF" : ("100" == dma) ? "MMOH" : ("50" == dma) ? "MMFI" : ("5" == dma) ? "MMFD" : "MMTW" :
("SP500" == market) ? ("200" == dma) ? "S5TH" : ("150" == dma) ? "S5OF" : ("100" == dma) ? "S5OH" : ("50" == dma) ? "S5FI" : ("5" == dma) ? "S5FD" : "S5TW" :
("DJI" == market) ? ("200" == dma) ? "DITH" : ("150" == dma) ? "DIOF" : ("100" == dma) ? "DIOH" : ("50" == dma) ? "DIFI" : ("5" == dma) ? "DIFD" : "DITW" :
("Nasdaq" == market) ? ("200" == dma) ? "NCTH" : ("150" == dma) ? "NCOF" : ("100" == dma) ? "NCOH" : ("50" == dma) ? "NCFI" : ("5" == dma) ? "NCFD" : "NCTW" :
("Nasdaq100" == market) ? ("200" == dma) ? "NDTH" : ("150" == dma) ? "NDOF" : ("100" == dma) ? "NDOH" : ("50" == dma) ? "NDFI" : ("5" == dma) ? "NDFD" : "NDTW" :
("Russel2000" == market) ? ("200" == dma) ? "R2TH" : ("150" == dma) ? "R2OF" : ("100" == dma) ? "R2OH" : ("50" == dma) ? "R2FI" : ("5" == dma) ? "R2FD" : "R2TW" :
("Russel3000" == market) ? ("200" == dma) ? "R3TH" : ("150" == dma) ? "R3OF" : ("100" == dma) ? "R3OH" : ("50" == dma) ? "R3FI" : ("5" == dma) ? "R3FD" : "R3TW" :
na
percentage_above_ma = security(ticker, timeframe.period, close-50)
high = input(color.rgb(30, 107, 255), "Up")
low = input(color.red, "Down")
pam_line = plot(series = percentage_above_ma, style=plot.style_histogram, color=percentage_above_ma > 0 ? color.rgb(30,107,255) : color.rgb(255,30,32), linewidth = 4, title="Above MA")
|
Market Structure CHoCH/BOS (Fractal) [LuxAlgo] | https://www.tradingview.com/script/ZpHqSrBK-Market-Structure-CHoCH-BOS-Fractal-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,924 | 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/
// © LuxAlgo
//@version=5
indicator("Market Structure CHoCH/BOS (Fractal) [LuxAlgo]", "LuxAlgo - Market Structure (Fractal)", overlay = true, max_lines_count = 500, max_labels_count = 500)
//------------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------{
length = input.int(5, minval = 3)
//Colors
showBull = input(true, 'Bullish Structures', inline = 'bull', group = 'Style')
bullCss = input.color(#089981, '', inline = 'bull', group = 'Style')
showBear = input(true, 'Bearish Structures', inline = 'bear', group = 'Style')
bearCss = input.color(#f23645, '', inline = 'bear', group = 'Style')
showSupport = input(false, 'Support', inline = 's', group = 'Style')
supCss = input.color(#089981, '', inline = 's', group = 'Style')
showResistance = input(false, 'Resistance', inline = 'r', group = 'Style')
resCss = input.color(#f23645, '', inline = 'r', group = 'Style')
//Dashboard
showDash = input(false, 'Show Dashboard', group = 'Dashboard')
dashLoc = input.string('Top Right', 'Location', options = ['Top Right', 'Bottom Right', 'Bottom Left'], group = 'Dashboard')
textSize = input.string('Small', 'Size' , options = ['Tiny', 'Small', 'Normal'] , group = 'Dashboard')
//-----------------------------------------------------------------------------}
//Types
//-----------------------------------------------------------------------------{
type fractal
float value
int loc
bool iscrossed
//-----------------------------------------------------------------------------}
//Fractal Detection
//-----------------------------------------------------------------------------{
var p = int(length/2)
n = bar_index
dh = math.sum(math.sign(high - high[1]), p)
dl = math.sum(math.sign(low - low[1]), p)
bullf = dh == -p and dh[p] == p and high[p] == ta.highest(length)
bearf = dl == p and dl[p] == -p and low[p] == ta.lowest(length)
bullf_count = ta.cum(bullf ? 1 : 0)
bearf_count = ta.cum(bearf ? 1 : 0)
//-----------------------------------------------------------------------------}
//Bullish market structure
//-----------------------------------------------------------------------------{
var upper = fractal.new()
var line lower_lvl = na
var label ms_lbl = na
var bull_ms_count = 0
var broken_sup = false
var os = 0
if bullf
upper.value := high[p]
upper.loc := n-p
upper.iscrossed := false
if ta.crossover(close, upper.value) and not upper.iscrossed
line.new(upper.loc, upper.value, n, upper.value, color = showBull ? bullCss : na)
ms_lbl := label.new(int(math.avg(n, upper.loc)), upper.value, os == -1 ? 'ChoCH' : 'BOS'
, color = color(na)
, textcolor = showBull ? bullCss : na
, style = label.style_label_down
, size = size.tiny)
//Set support
k = 2
min = low[1]
for i = 2 to (n - upper.loc)-1
min := math.min(low[i], min)
k := low[i] == min ? i : k
if showSupport
lower_lvl := line.new(n-k, min, n, min, color = bullCss, style = line.style_dashed)
broken_sup := false
upper.iscrossed := true
bull_ms_count += 1
os := 1
else if showSupport and not broken_sup
lower_lvl.set_x2(n)
if close < lower_lvl.get_y2()
broken_sup := true
//-----------------------------------------------------------------------------}
//Bearish market structure
//-----------------------------------------------------------------------------{
var lower = fractal.new()
var line upper_lvl = na
var broken_res = false
var bear_ms_count = 0
if bearf
lower.value := low[p]
lower.loc := n-p
lower.iscrossed := false
if ta.crossunder(close, lower.value) and not lower.iscrossed
line.new(lower.loc, lower.value, n, lower.value, color = showBear ? bearCss : na)
label.new(int(math.avg(n, lower.loc)), lower.value, os == 1 ? 'ChoCH' : 'BOS'
, color = color(na)
, textcolor = showBear ? bearCss : na
, style = label.style_label_up
, size = size.tiny)
//Set resistance
k = 2
max = high[1]
for i = 2 to (n - lower.loc)-1
max := math.max(high[i], max)
k := high[i] == max ? i : k
if showResistance
upper_lvl := line.new(n-k, max, n, max, color = bearCss, style = line.style_dashed)
broken_res := false
lower.iscrossed := true
bear_ms_count += 1
os := -1
else if showResistance and not broken_res
upper_lvl.set_x2(n)
if close > upper_lvl.get_y2()
broken_res := true
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
var table_position = dashLoc == 'Bottom Left' ? position.bottom_left
: dashLoc == 'Top Right' ? position.top_right
: position.bottom_right
var table_size = textSize == 'Tiny' ? size.tiny
: textSize == 'Small' ? size.small
: size.normal
var tb = table.new(table_position, 2, 3
, bgcolor = #1e222d
, border_color = #373a46
, border_width = 1
, frame_color = #373a46
, frame_width = 1)
if showDash
if barstate.isfirst
tb.cell(0, 0, 'Structure To Fractal %', text_color = color.white, text_size = table_size)
tb.merge_cells(0,0,1,0)
tb.cell(0, 1, 'Bullish', text_color = #089981, text_size = table_size)
tb.cell(1, 1, 'Bearish', text_color = #f23645, text_size = table_size)
if barstate.islast
tb.cell(0, 2, str.tostring(bull_ms_count / bullf_count * 100, format.percent), text_color = #089981, text_size = table_size)
tb.cell(1, 2, str.tostring(bear_ms_count / bearf_count * 100, format.percent), text_color = #f23645, text_size = table_size)
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot(broken_res and not broken_res[1] ? low : na, 'Resistance Breakout', #089981, 2, plot.style_circles)
plot(broken_sup and not broken_sup[1] ? high : na, 'Support Breakout', #f23645, 2, plot.style_circles)
//-----------------------------------------------------------------------------} |
Dodge Trend [JacobMagleby] | https://www.tradingview.com/script/vwUt3cEJ-Dodge-Trend-JacobMagleby/ | JacobMagleby | https://www.tradingview.com/u/JacobMagleby/ | 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/
// © JacobMagleby
//@version=5
// { <DECLARATION STATEMENT>
indicator(title = "Dodge Trend [JacobMagleby]", shorttitle = "Dodge Trend [JacobMagleby] - Version 1.0.0", overlay = true, timeframe = "")
// } <DECLARATION STATEMENT>
// { <CONSTANT_DECLARATIONS>
INDICATOR_GROUP = "Indicator Settings"
COLOR_GROUP = "Color Settings"
COLOR_INLINE = "Color Inline"
// } <CONSTANTS>
// { <INPUTS>
lengthInput = input.int(
title = "Length",
defval = 20,
minval = 1,
group = INDICATOR_GROUP,
tooltip = "How Much Price Action To Take Into Consideration. Lower Values = More Reactive To Current Market Volatility.")
sizeInput = input.float(
title = "Size",
defval = 3.0,
minval = 0.1,
step = 0.1,
group = INDICATOR_GROUP,
tooltip = "How Wide The Gap Is From The Current Price To The Line When Flipping.")
sourceInput = input.source(
title = "Source",
defval = hl2,
group = INDICATOR_GROUP,
tooltip = "Source For The Dodge Line")
dodgeIntensity = input.float(
title = "Dodge Intensity",
defval = 95.0,
minval = 0.0,
maxval = 99,
step = 0.1,
group = INDICATOR_GROUP,
tooltip= "How Intense/Aggressive The Dodge Effect Is. Anything Above 96 Will Get Very Intense. 95 Is Recommended Default. 0 Will Yield Almost No Dodge Effect.")
upColorInput = input.color(
title = "",
defval = color.green,
group = COLOR_GROUP,
inline = COLOR_INLINE)
downColorInput = input.color(
title = "",
defval = color.red,
group = COLOR_GROUP,
inline = COLOR_INLINE)
// } <INPUTS>
// { <USER DEFINED TYPES>
type dodgeTrend
int length
float size
float source
color upColor
color downColor
float trueRangeAverage
float referenceTop
float referenceBottom
float lowestReferenceTop
float highestReferenceBottom
float activeTop
float activeBottom
float combinedValue
float direction
color currentColor
method updateDependencies(dodgeTrend self)=>
trueRangeAverage = ta.sma(ta.tr, lengthInput)
self.referenceTop := sourceInput + (trueRangeAverage * sizeInput)
self.referenceBottom := sourceInput - (trueRangeAverage * sizeInput)
if na(self.direction) and not na(self.referenceTop)
self.direction := 1
self.activeTop := na
self.activeBottom := self.referenceBottom
self.combinedValue := self.referenceBottom
self.highestReferenceBottom := self.referenceBottom
self.currentColor := self.upColor
self
method updateActives(dodgeTrend self)=>
self.lowestReferenceTop := ta.change(self.direction) ? self.referenceTop :
self.lowestReferenceTop
self.highestReferenceBottom := ta.change(self.direction) ? self.referenceBottom :
self.highestReferenceBottom
self.activeTop := self.direction == -1 and self.direction[1] == 1 ? self.referenceTop :
self.direction == 1 and self.direction[1] == -1 > 0 ? na :
self.activeTop
self.activeBottom := self.direction == 1 and self.direction[1] == -1 ? self.referenceBottom :
self.direction == -1 and self.direction[1] == 1 ? na :
self.activeBottom
rPrevB = self.referenceBottom[1]
rPrevBH = self.highestReferenceBottom
rPrevT = self.referenceTop[1]
rPrevTH = self.lowestReferenceTop
pullback = .60 * (100 - dodgeIntensity)
recover = .40 * (100 - dodgeIntensity)
if self.direction == 1
self.highestReferenceBottom := self.referenceBottom > self.highestReferenceBottom ? self.referenceBottom :
self.highestReferenceBottom
self.activeBottom := self.highestReferenceBottom > rPrevBH ? self.activeBottom + (self.highestReferenceBottom - rPrevBH) :
self.referenceBottom < rPrevB ? self.activeBottom - ((rPrevB - self.referenceBottom) / pullback) :
self.referenceBottom > rPrevB ? self.activeBottom + ((self.referenceBottom - rPrevB) / recover) :
self.activeBottom
self.combinedValue := self.activeBottom
self.direction := close < self.activeBottom ? -1 :
self.direction
self.currentColor := self.upColor
else
self.lowestReferenceTop := self.referenceTop < self.lowestReferenceTop ? self.referenceTop :
self.lowestReferenceTop
self.activeTop := self.lowestReferenceTop < rPrevTH ? self.activeTop - (rPrevTH - self.lowestReferenceTop) :
self.referenceTop > rPrevT ? self.activeTop + ((self.referenceTop - rPrevT) / pullback) :
self.referenceTop < rPrevT ? self.activeTop - ((rPrevT - self.referenceTop) / recover) :
self.activeTop
self.combinedValue := self.activeTop
self.direction := close > self.activeTop ? 1 :
self.direction
self.currentColor := self.downColor
self
method run(dodgeTrend self)=>
self.updateDependencies()
self.updateActives()
self
// } <USER DEFINED TYPES>
// { <CALCULATIONS>
var dodgeTrend = dodgeTrend.new(
length = lengthInput,
size = sizeInput,
source = sourceInput,
upColor = upColorInput,
downColor = downColorInput)
dodgeTrend.run()
// } <CALCULATIONS>
// { <VISUALS>
topBoundry = dodgeTrend.combinedValue + (ta.atr(1000) / 3)
botBoundry = dodgeTrend.combinedValue - (ta.atr(1000) / 3)
invisible = color.new(color.white, 100)
topBoundryPlot = plot(topBoundry, color = invisible, editable = false)
botBoundryPlot = plot(botBoundry, color = invisible, editable = false)
centerBoundryPlot = plot(dodgeTrend.combinedValue, "Dodge Trend", dodgeTrend.currentColor, 2)
fill(topBoundryPlot, centerBoundryPlot, topBoundry, dodgeTrend.combinedValue, invisible, color.new(dodgeTrend.currentColor, 75))
fill(centerBoundryPlot, botBoundryPlot, dodgeTrend.combinedValue, botBoundry, color.new(dodgeTrend.currentColor, 75), invisible)
// } <VISUALS>
// { <ALERTS>
alertcondition(
condition = dodgeTrend.direction == 1 and dodgeTrend.direction[1] == -1,
title = "Dodge Trend Flips Up")
alertcondition(
condition = dodgeTrend.direction == -1 and dodgeTrend.direction[1] == 1,
title = "Dodge Trend Flips Down")
// } <ALERTS>
|
Subsets and Splits