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
|
---|---|---|---|---|---|---|---|---|
Angled Volume Profile [Trendoscope] | https://www.tradingview.com/script/MgsLckWl-Angled-Volume-Profile-Trendoscope/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 587 | 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
import HeWhoMustNotBeNamed/LineWrapper/1 as LineWrapper
indicator("Angled Volume Profile [Trendoscope]", "AVP[Trendoscope]", overlay=true, max_lines_count = 500, max_bars_back = 5000)
startX = input.time(0, 'StartX', inline='Start', group='Coordinates', confirm=true)
startY = input.price(0, "StartY", inline='Start', group='Coordinates', confirm=true)
endY = input.price(0, "EndY", inline='End', group='Coordinates', confirm=true)
precision = input.int(1000, 'Step Multiplier', minval=10, step=100, group='Properties', tooltip='Multiplier for min tick to define step between profile lines')
lineColor = input.color(color.yellow, '', inline='l', group='Display')
lineTransparency = input.int(80, '', minval=0, maxval=100, step=5, inline='l', group='Display')
lineStyle = input.string(line.style_dotted, '', [line.style_dotted, line.style_dashed, line.style_solid], inline='l', group='Display', tooltip = 'Volume profile line color, transparency and style')
type VolumeProfileLine
LineWrapper.Line profileLine
float profileVolume = 0.0
method update(map<float, VolumeProfileLine> this, startXBar, endXBar, startXValue, endXValue, factor)=>
vLine = this.contains(startXValue)? this.get(startXValue) : VolumeProfileLine.new(
LineWrapper.Line.new(startXBar, startXValue, endXBar, endXValue, color=lineColor, style = lineStyle)
)
vLine.profileVolume += volume*factor
this.put(startXValue, vLine)
this
roundtoprecision(price, step)=>
multiplier = 1/step
int(price*multiplier)/(multiplier*1.0)
method add(array<polyline> this, array<chart.point> points)=>
this.push(polyline.new(points, false, false, xloc.bar_index, color.new(lineColor, lineTransparency), line_style=lineStyle))
points.clear()
method flush(array<polyline> this)=>
while this.size()!=0
this.pop().delete()
var startXBar = 0
var volumeProfiles = map.new<float, VolumeProfileLine>()
var label startLbl = label.new(startX, startY, "", xloc = xloc.bar_time, style = label.style_circle, size = size.tiny, color = color.maroon, tooltip='Starting Point - Time+Price. Move this to change starting point')
var label endLbl = label.new(last_bar_time, endY, "", xloc = xloc.bar_time, style = label.style_circle, size = size.tiny, color = color.maroon, tooltip = 'Ending Point - Only price can be changed. Ending bar is always the last bar')
var float diff = endY - startY
var float step = syminfo.mintick*precision
if(time == startX)
startXBar := bar_index
end = diff + close
vLine = LineWrapper.Line.new(startXBar, close, last_bar_index, end, color=lineColor, style = lineStyle)
volumeProfiles.put(close, VolumeProfileLine.new(vLine, 0.0))
if(time >= startX and not na(step))
endXBar = last_bar_index
factor = (high-low)/(high-low+math.abs(open-close))
startDiff = diff*(bar_index-startXBar)/(endXBar-startXBar)
endDiff = diff*(endXBar-bar_index)/(endXBar-startXBar)
for price = low to high by step
startXValue = roundtoprecision(price- startDiff, step)
endXValue = roundtoprecision(price + endDiff, step)
volumeProfiles.update(startXBar, endXBar, startXValue, endXValue, (price <=math.max(open, close) and price >= math.min(open, close) ? 2 : 1)*factor)
float maxVolume = na
var bool draw = true
if(barstate.islast and draw)
draw := false
for volumeProfile in volumeProfiles.values()
maxVolume := nz(math.max(volumeProfile.profileVolume, maxVolume), volumeProfile.profileVolume)
array<chart.point> profilePoints = array.new<chart.point>()
array<polyline> polyLineArrays = array.new<polyline>()
polyLineArrays.flush()
for volumeProfile in volumeProfiles.values()
percent = volumeProfile.profileVolume*100/maxVolume
newEndX = startXBar + math.floor((last_bar_index-startXBar)*percent/100)
newEndY = volumeProfile.profileLine.get_price(newEndX)
newStartY = volumeProfile.profileLine.get_y1()
if(percent != 0)
profilePoints.push(chart.point.from_index(startXBar, newStartY))
profilePoints.push(chart.point.from_index(newEndX, newEndY))
profilePoints.push(chart.point.from_index(startXBar, newStartY))
if(profilePoints.size() > 997)
polyLineArrays.add(profilePoints)
polyLineArrays.add(profilePoints) |
Ladder ATR | https://www.tradingview.com/script/0J8sQTz5-Ladder-ATR/ | jason5480 | https://www.tradingview.com/u/jason5480/ | 75 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jason5480
//@version=5
indicator(title = 'Ladder ATR',
shorttitle = 'LATR',
timeframe = '',
timeframe_gaps = true)
import HeWhoMustNotBeNamed/arraymethods/1
import HeWhoMustNotBeNamed/arrayutils/21 as pa
// INPUT ============================================================================================================
atrMaType = str.lower(input.string(defval = 'SMA', title = 'ATR Smooth Type/Len', options = ['SMA', 'EMA', 'RMA', 'WMA', 'HMA'], inline = 'ATR'))
atrLength = input.int(defval = 20, title = '', minval = 1, tooltip = 'The smoothing type and the length to be used for the ATR calculation.', inline = 'ATR')
// LOGIC ============================================================================================================
var positiveTrs = array.new<float>()
var negativeTrs = array.new<float>()
if(close > open)
positiveTrs.push(ta.tr(true), atrLength)
else
negativeTrs.push(ta.tr(true), atrLength)
float ladderPositiveAtr = pa.ma(positiveTrs, atrMaType, atrLength)
float ladderNegativeAtr = pa.ma(negativeTrs, atrMaType, atrLength)
// PLOT =============================================================================================================
var positiveColor = color.new(#26A69A, 0)
plot(series = ladderPositiveAtr, title = 'Positive ATR', color = positiveColor, linewidth = 1, style = plot.style_line, trackprice = true)
var negativeColor = color.new(#EF5350, 0)
plot(series = ladderNegativeAtr, title = 'Negative ATR', color = negativeColor, linewidth = 1, style = plot.style_line, trackprice = true) |
VWAP2D+ | https://www.tradingview.com/script/Bn6wz47K-VWAP2D/ | Electrified | https://www.tradingview.com/u/Electrified/ | 113 | 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/
// © Electrified
//@version=5
//@description=Tracks the VWAP for the latest/current and previous session.
indicator("VWAP2D+", overlay = true)
source = input.source(hlc3, "Source")
extended = input.bool(false, "Allow start from early extended session")
alertSource = input.bool(false, "Use open value instead of close for alerts") ? open : close
theme = color.rgb(174, 136, 60)
type VWAP
float sum
float volume
float value
getDailyVwapData(series float source, int maxDays, simple bool extended = false)=>
var days = array.new<VWAP>()
if extended ? session.isfirstbar : session.isfirstbar_regular
array.unshift(days, VWAP.new(0,0,0))
if array.size(days) > maxDays
array.pop(days)
size = array.size(days)
if size != 0
v0 = volume
s0 = source
sv = s0 * v0
for i = 0 to size-1
d = array.get(days, i)
v = d.volume + v0
s = d.sum + sv
x = VWAP.new(s, v, s/v)
array.set(days, i, x)
days
getVwapForDay(simple int day, simple int maxDays) =>
days = getDailyVwapData(source, maxDays, extended)
if array.size(days) > day
d = array.get(days, day)
d.value
else
float(na)
vwap0 = getVwapForDay(0, 2)
vwap1 = getVwapForDay(1, 2)
plot(vwap1, "Previous", theme, 1, plot.style_circles)
plot(vwap0, "Latest", theme, 2, plot.style_circles)
plot(vwap0, "Click Assist", color.new(theme, 100), 5, plot.style_linebr, display=display.pane)
// Alerts
alertcondition(ta.cross(alertSource, vwap0),
"Crossing Current", message="VWAP2D+, Crossed Current ({{ticker}} {{interval}})")
alertcondition(ta.cross(alertSource, vwap0),
"Crossing Previous", message="VWAP2D+, Crossed Previous ({{ticker}} {{interval}})")
alertcondition(alertSource < vwap0 and alertSource < vwap1,
"Fall Below Both", message="VWAP2D+, Fell Below ({{ticker}} {{interval}})")
alertcondition(alertSource > vwap0 and alertSource > vwap1,
"Rise Above Both", message="VWAP2D+, Rose Above ({{ticker}} {{interval}})")
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
MEASUREMENT = "Deviation Measurement"
days = input.int(50, "Days", group = MEASUREMENT, tooltip = "The number of days to measure.")
EXCEEDED = "Exceeded", FULL = "Full", HIDDEN = "Hidden"
mode = input.string(EXCEEDED,
"Display Mode",
[EXCEEDED, FULL, HIDDEN],
"Determines how the deviation is rendered\nExceeded: only show when exceeded\nFull: show the full range\nHidden: don't calculate and don't display",
group = MEASUREMENT)
type TimeOfDay
float[] data
[mean, standardDeviation] = if mode == HIDDEN
[0, 0]
else
var data = array.new<TimeOfDay>()
dayStart = time("D")
// Time of day in seconds
timeOfDay = (time - dayStart) / 1000
multiple = switch
timeframe.isminutes => 60 * timeframe.multiplier
timeframe.isseconds => timeframe.multiplier
=> timeOfDay
barOfDay = math.floor(timeOfDay / multiple)
while barOfDay >= data.size()
data.push(TimeOfDay.new(array.new_float()))
entries = data.size() == 0 ? array.new_float() : data.get(barOfDay).data
mean = entries.avg()
diff2sum = 0.0
for e in entries
diff2sum += e * e
variance = diff2sum / entries.size()
standardDeviation = math.sqrt(variance)
// Delay adding today's data
entries.push(math.abs(nz(source - vwap0)))
if entries.size() > days
entries.shift()
[mean, standardDeviation]
plus1 = mean + standardDeviation
avgPosValue = vwap0 + mean
avgNegValue = vwap0 - mean
stdDev1PosValue = vwap0 + plus1
stdDev1NegValue = vwap0 - plus1
avgPos = plot(avgPosValue, "+Average", color.orange, 1, display = display.none)
avgNeg = plot(avgNegValue, "-Average", color.orange, 1, display = display.none)
stdDev1Pos = plot(stdDev1PosValue, "+1 Standard Deviation", color.yellow, 1, display = display.none)
stdDev1Neg = plot(stdDev1NegValue, "-1 Standard Deviation", color.yellow, 1, display = display.none)
vwapHiColor = color.yellow
vwapLoColor = color.blue
hiPlot = plot(math.max(open, close), "High", na, 0, display = display.none)
loPlot = plot(math.min(open, close), "Low", na, 0, display = display.none)
fill(avgPos, hiPlot, avgPosValue, stdDev1PosValue,
color.new(vwapHiColor, 100), color.new(vwapHiColor, 65),
"VWAP High Exeeded", display = mode==EXCEEDED ? display.all : display.none)
fill(avgNeg, loPlot, avgNegValue, stdDev1NegValue,
color.new(vwapLoColor, 100), color.new(vwapLoColor, 65),
"VWAP Low Exeeded", display = mode==EXCEEDED ? display.all : display.none)
fill(avgPos, stdDev1Pos, avgPosValue, stdDev1PosValue,
color.new(vwapHiColor, 100), color.new(vwapHiColor, 65),
"VWAP High Range", display = mode==FULL ? display.all : display.none)
fill(avgNeg, stdDev1Neg, avgNegValue, stdDev1NegValue,
color.new(vwapLoColor, 100), color.new(vwapLoColor, 65),
"VWAP Low Range", display = mode==FULL ? display.all : display.none)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import Electrified/Volatility/7
import Electrified/Time/7
ATR = "Closing In Range (ATR)"
showAtrRange = input.bool(false, "Show", 'Shows the zone that "Closing In Range" will be triggered. Useful at anticipating VWAP touches.', group = ATR)
tr = Volatility.fromTrueRange(
input.int(500,
"Length",
tooltip = "The number of bars to measure the average true range.",
group = ATR),
input.float(3.5,
"TR Max Outlier",
tooltip = "The maximum outlier level to allow when calculating the average true range.",
group = ATR),
smoothing = input.int(100,
"Smoothing",
tooltip = "The number of bars to average in order to smooth out the result.",
group = ATR))
atr = tr.average
* input.float(0.5, "Multiple",
step = 0.1,
tooltip = "The multiple to apply the the ATR.",
group = ATR)
if input.bool(true,
"Adjust for intraday timeframe",
"Modifies the multiple based upon the timeframe.",
group = ATR)
var adjustment = math.pow(60 * 1000 / Time.bar(), 0.5)
atr *= adjustment
alertcondition(close > vwap0 - atr and close < vwap0 + atr,
"Closing In Range", message="VWAP2D+, Closing In Range ({{ticker}} {{interval}})")
hiAtr = plot(vwap0 + atr, "ATR High", theme, 1, display = display.none)
loAtr = plot(vwap0 - atr, "ATR Low", theme, 1, display = display.none)
fill(hiAtr, loAtr, color.new(theme, 50), display = showAtrRange ? display.all : display.none) |
Equilibrium | https://www.tradingview.com/script/4syrwJXn-Equilibrium/ | sudoMode | https://www.tradingview.com/u/sudoMode/ | 113 | 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/
// © sudoMode
//@version=5
//@release=0.0.7
indicator(title = 'Pressure Gauge', shorttitle = 'Equilibrium', overlay = false)
// --- user-input ---
// setting groups
group_1 = 'Gauge Settings'
group_2 = 'Oscillator Settings'
// gauge settings
show_gauge = input.bool(false, 'Show Gauge', inline = '1', group = group_1)
show_text = input.bool(false, 'Show Text', inline = '1', group = group_1)
sell_color = input.color(color.red, title = 'Sell Color', inline = '2', group = group_1)
buy_color = input.color(color.green, title = 'Buy Color', inline = '2', group = group_1)
alignment = input.string('Vertical', title = 'Alignment',
options = ['Vertical', 'Horizontal'], inline = '3', group = group_1)
lookback_1 = input.int(50, title = 'Lookback Period', minval = 10, maxval = 1000, step = 10,
inline = '3', group = group_1)
// oscillator settings
_sell_color = input.color(color.rgb(125, 10, 10), title = 'Sell Color', inline = '4', group = group_2)
_buy_color = input.color(color.rgb(50, 150, 200), title = 'Buy Color', inline = '4', group = group_2)
short_ma_length = input.int(3, title = 'Short MA Length', minval = 1, maxval = 10, inline = '5', group = group_2)
show_long_ma = input.bool(false, title = 'Show Long MA', inline = '6', group = group_2)
long_ma_length = input.int(10, title = 'Long MA Length', minval = 10, maxval = 30, inline = '7', group = group_2)
lookback_2 = input.int(30, title = 'Lookback Period', minval = 5, maxval = 100, inline = '8', group = group_2)
// --- globals ---
var white = color.white
var tiny = size.tiny
var scale = 25
// --- utils ---
// scale value between a range
scaler(_series, minimum = -1, maximum = 1) =>
_min = ta.min(_series)
_max = ta.max(_series)
_range = _max - _min
((_series - _min) / _range) * (maximum - minimum) + minimum
// position gauge based on alignment
position_map(alignment) =>
switch alignment
'Vertical' => position.middle_right
'Horizontal' => position.bottom_center
// create an empty table -> to be used as the gauge
init_gauge(alignment) =>
columns = alignment == 'Vertical' ? 1 : scale
rows = alignment == 'Horizontal' ? 1 : scale
position = position_map(alignment)
table.new(position = position, columns = columns, rows = rows)
// compute length distribution of red & green candles
candle_distribution(red, green) =>
total = red + green
dist_red = int((red / total) * scale)
dist_green = scale - dist_red
[dist_red, dist_green]
// generate cell color based on type
color_map(_type) =>
switch _type
'sell' => sell_color
'buy' => buy_color
// generate column & row index
coordinate_map(alignment, _type, index) =>
column = alignment == 'Vertical' ? 0 : (_type == 'sell' ? scale - index - 1 : index)
row = alignment == 'Horizontal' ? 0 : (_type == 'sell' ? index : scale - index - 1)
[column, row]
// popluate the gauge
// higher distribution => higher presssure => greater color intensity
// vertical alignment : sell => top to bottom | buy => bottom to top
// horizontal alignment : sell => right to left | buy => left to right
project_pressure(gauge, alignment, scale, index, dist, _type) =>
if index < dist
[column, row] = coordinate_map(alignment, _type, index)
percentage = str.tostring(math.round(dist * (100/scale))) + '%'
_color = color.new(color_map(_type), (100 - ((100 / scale) * index)))
_text = show_text and index + 2 == dist ? percentage : ''
width = _text == '' ? (alignment == 'Vertical' ? 2 : 4) : 0
height = _text == '' ? 4 : 0
table.cell(gauge, column = column, row = row, bgcolor = _color, text = _text, text_color = white,
text_size = tiny, width = width, height=height)
// indicate buy/sell pressure by populating the gauge
draw_pressure_gauge(red, green, alignment='Vertical') =>
gauge = init_gauge(alignment)
for i = 0 to math.max(red, green)
project_pressure(gauge, alignment, scale, i, red, 'sell')
project_pressure(gauge, alignment, scale, i, green, 'buy')
// compute total candle lengths for the given lookback period
compute_lengths(lookback) =>
red = 0
green = 0
for i = 0 to lookback
_range = (close[i] - open[i]) * volume[i]
if _range > 0
green += int(_range)
else
red += int(math.abs(_range))
[red, green]
// --- driver ---
// gauge
if show_gauge
// compute distribution
[red_gauge, green_gauge] = compute_lengths(lookback_1)
[dist_red_gauge, dist_green_gauge] = candle_distribution(red_gauge, green_gauge)
// draw gauge
draw_pressure_gauge(dist_red_gauge, dist_green_gauge, alignment)
// oscillator
// compute pressure
[red_oscillator, green_oscillator] = compute_lengths(lookback_2)
[dist_red_oscillator, dist_green_oscillator] = candle_distribution(red_oscillator, green_oscillator)
raw_pressure = dist_green_oscillator - dist_red_oscillator
scaled_pressure = raw_pressure < 0 ? scaler(raw_pressure, -1, 0) : scaler(raw_pressure, 0, 1)
short_pressure = ta.ema(scaled_pressure, short_ma_length)
long_pressure = ta.sma(scaled_pressure, long_ma_length)
// draw oscillator
_buy_color := color.from_gradient(short_pressure, 0, 1, color.new(_buy_color, 50), color.new(_buy_color, 0))
_sell_color := color.from_gradient(short_pressure, -1, 0, color.new(_sell_color, 0), color.new(_sell_color, 50))
short_color = short_pressure < 0 ? _sell_color : _buy_color
plot(short_pressure, style = plot.style_columns, color = short_color)
long_color = show_long_ma ? color.gray : na
plot(long_pressure, style = plot.style_line, color = long_color, linewidth = 2)
|
Bar Magnified Volume Profile/Fixed Range [ChartPrime] | https://www.tradingview.com/script/azaqVnio-Bar-Magnified-Volume-Profile-Fixed-Range-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 945 | 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/
// © ExoMaven
//@version=5
indicator(title = "Bar Magnified Volume Profile/Fixed Range [ChartPrime]", shorttitle = "Bar Magnified Volume Profile/Fixed Range [ChartPrime]", overlay = true, max_boxes_count = 100, max_bars_back = 5000)
//░█████╗░██╗░░██╗░█████╗░██████╗░████████╗ ██████╗░██████╗░██╗███╗░░░███╗███████╗
//██╔══██╗██║░░██║██╔══██╗██╔══██╗╚══██╔══╝ ██╔══██╗██╔══██╗██║████╗░████║██╔════╝
//██║░░╚═╝███████║███████║██████╔╝░░░██║░░░ ██████╔╝██████╔╝██║██╔████╔██║█████╗░░
//██║░░██╗██╔══██║██╔══██║██╔══██╗░░░██║░░░ ██╔═══╝░██╔══██╗██║██║╚██╔╝██║██╔══╝░░
//╚█████╔╝██║░░██║██║░░██║██║░░██║░░░██║░░░ ██║░░░░░██║░░██║██║██║░╚═╝░██║███████╗
//╚════╝░╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░ ╚═╝░░░░░╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝╚══════╝
//--------------------------------------------------------------------------------
//░█████╗░██████╗░███████╗░█████╗░████████╗███████╗██████╗░ ██████╗░██╗░░░██╗
//██╔══██╗██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝██╔══██╗ ██╔══██╗╚██╗░██╔╝
//██║░░╚═╝██████╔╝█████╗░░███████║░░░██║░░░█████╗░░██║░░██║ ██████╦╝░╚████╔╝░
//██║░░██╗██╔══██╗██╔══╝░░██╔══██║░░░██║░░░██╔══╝░░██║░░██║ ██╔══██╗░░╚██╔╝░░
//╚█████╔╝██║░░██║███████╗██║░░██║░░░██║░░░███████╗██████╔╝ ██████╦╝░░░██║░░░
//░╚════╝░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝░░░╚═╝░░░╚══════╝╚═════╝░ ╚═════╝░░░░╚═╝░░░
//███████╗██╗░░██╗░█████╗░███╗░░░███╗░█████╗░██╗░░░██╗███████╗███╗░░██╗
//██╔════╝╚██╗██╔╝██╔══██╗████╗░████║██╔══██╗██║░░░██║██╔════╝████╗░██║
//█████╗░░░╚███╔╝░██║░░██║██╔████╔██║███████║╚██╗░██╔╝█████╗░░██╔██╗██║
//██╔══╝░░░██╔██╗░██║░░██║██║╚██╔╝██║██╔══██║░╚████╔╝░██╔══╝░░██║╚████║
//███████╗██╔╝╚██╗╚█████╔╝██║░╚═╝░██║██║░░██║░░╚██╔╝░░███████╗██║░╚███║
//╚══════╝╚═╝░░╚═╝░╚════╝░╚═╝░░░░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░╚══════╝╚═╝░░╚══╝
//-------------------------------------------------------------------------------
// user input
lookback = input.int(title = "Lookback Period", defval = 100, maxval = 1000, group = "Main Configuration", tooltip = "Number of bars to search for highest high and highest low to create a price range")
segs = input.int(title = "Number Of Levels", defval = 100, maxval = 100, group = "Main Configuration", tooltip = "Number of volume grids/nodes for the volume profile")
n_skew = input.int(title = "Profile Length", defval = 25, minval = 10, maxval = 1000, group = "Main Configuration", tooltip = "Length of the volume profile. Higher = Wider, Lower = Skinnier")
n_shift = input.int(title = "Profile Offset", defval = 35, group = "Main Configuration", tooltip = "Offset the entire volume profile left or right. Higher = Right, Lower = Left")
high_volume_color = input.color(color.new(color.green, 10), "High Volume", inline = "Colors", group = "Cosmetic Settings")
low_volume_color = input.color(color.new(color.blue, 10), "Low Volume", inline = "Colors", group = "Cosmetic Settings")
activity_bull_color = input.color(color.new(color.orange, 10), "Above Point Of Interest", inline = "POI", group = "Cosmetic Settings")
activity_bear_color = input.color(color.new(color.orange, 10), "Below Point Of Interest", inline = "POI", group = "Cosmetic Settings")
// data
highest_high = ta.highest(high, lookback)
lowest_low = ta.lowest(low, lookback)
// lower timeframe data extraction
tf = timeframe.isdaily ? 1440 : timeframe.isweekly ? 1440 * 7 : timeframe.ismonthly ? 1440 * 30 : str.tonumber(timeframe.period)
req_tf = math.round(tf / 16) < 1 ? "30S" : str.tostring(math.round(tf / 16))
[h, l, v] = request.security_lower_tf(syminfo.tickerid, req_tf, [high, low, volume])
// arrays
var borders = array.new_float()
var boxes = array.new_box()
var box_vols = array.new_float()
var line activity_line = na
// initialize box arrays on first bar
if barstate.isfirst
for i = 0 to segs - 1
array.push(boxes, box.new(na, na, na, na, xloc = xloc.bar_time, border_color = na))
array.push(box_vols, 0)
activity_line := line.new(na, na, na, na, style = line.style_dashed, width = 2)
if barstate.islast
//define range and create grid
inc = (highest_high - lowest_low) / segs
for i = 0 to segs
if i == 0
array.clear(borders)
array.push(borders, highest_high - (inc * i))
//parse all lower timeframe bars and attribute volume to each grid
for b = 0 to array.size(boxes) > 0 ? array.size(boxes) - 1 : na
box_ = array.get(boxes, b)
box_vol = 0.0
t_border = array.get(borders, b)
b_border = array.get(borders, b + 1)
for q = 0 to lookback - 1
for e = 0 to array.size(h[q]) > 0 ? array.size(h[q]) - 1 : na
ltf_high = array.get(h[q], e)
ltf_low = array.get(l[q], e)
ltf_vol = array.get(v[q], e)
ltf_diff = ltf_high - ltf_low
if ltf_low <= t_border and ltf_high >= b_border
top_register = math.min(ltf_high, t_border)
bot_register = math.max(ltf_low, b_border)
register_diff = top_register - bot_register
register_vol = register_diff / ltf_diff
box_vol += nz(register_vol * ltf_vol)
array.set(box_vols, b, box_vol)
//update box objects with proper volume, color, and position
max_vol = array.max(box_vols)
min_vol = array.min(box_vols)
shift = (time - time[n_shift])
skew = (time - time[n_skew]) / max_vol
for b = 0 to array.size(boxes) > 0 ? array.size(boxes) - 1 : na
box_ = array.get(boxes, b)
box_vol = array.get(box_vols, b)
t_border = array.get(borders, b)
b_border = array.get(borders, b + 1)
box.set_lefttop(box_, (time + shift) - int(box_vol * skew), t_border)
box.set_rightbottom(box_, time + shift, b_border)
array.set(box_vols, b, box_vol)
box.set_bgcolor(box_, color.from_gradient(box_vol, min_vol, max_vol, low_volume_color, high_volume_color))
if box_vol == max_vol
mid = (t_border + b_border) / 2
line.set_xloc(activity_line, time, (time + shift) - int(box_vol * skew), xloc.bar_time)
line.set_y1(activity_line, mid)
line.set_y2(activity_line, mid)
line.set_color(activity_line, close > mid ? activity_bull_color : activity_bear_color) |
Gaps [Kioseff Trading] | https://www.tradingview.com/script/0JcOuXSQ-Gaps-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 408 | 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/
// © KioseffTrading
//@version=5
indicator("Gaps [Kioseff Trading]", overlay = true,
max_labels_count = 500 ,
max_boxes_count = 500 ,
max_lines_count = 500 ,
max_bars_back = 500
)
// ________________________________________________
// | |
// | --------------------------------- |
// | | K̲ i̲ o̲ s̲ e̲ f̲ f̲ T̲ r̲ a̲ d̲ i̲ n̲ g | |
// | | | |
// | | ƃ u ᴉ p ɐ ɹ ꓕ ⅎ ⅎ ǝ s o ᴉ ꓘ | |
// | -------------------------------- |
// | |
// |_______________________________________________|
// _______________________________________________________
//
// Inputs
// _______________________________________________________
perG = input.float (defval = 0, title = "Percentage Gap Size" ,
group = "Important Settings", step = 0.1, minval = 0 ,
tooltip = "How large, percentage wise, must a gap be to get marked?" ) /100
old = input.float (defval = 5, title = "Hide Gaps When Price Deviates by Percentage" ,
group = "Important Settings", minval = -1 ,
tooltip = "Configuring This Setting to “-1” Will Keep All Gaps on the Chart.
Configuring This Setting at or Above “0” Will Hide Gap Boxes if Price Moves the Percentage
Amount Away From the Box. The “Percentage Amount” Is the Number in Defined for This Setting.") / 100
dont = input.bool (defval = false , title = "No Partially Filled Gaps" , group = "Secondary Settings" )
lab = input.bool (defval = false , title = "Put Data in Label" , group = "Secondary Settings" )
del = input.bool (defval = false , title = "Delete Filled Gaps" , group = "Secondary Settings" )
vis = input.bool (defval = false , title = "Gaps Chart" , group = "Secondary Settings" )
rec = input.int (defval = 5 , title = "Recent Unfilled Gaps to Show (Table)" , group = "Secondary Settings", minval = 0 )
font = input.bool (defval = true , title = "Monospace Font", group = "Aesthetics" )
size = input.string(defval = "Auto" , group = "Aesthetics", title = "On Chart", options = ["Auto", "Tiny", "Small", "Normal", "Large", "Huge"] )
ssize = input.string(defval = "Normal" , group = "Aesthetics", title = "Table Size", options = ["Auto", "Tiny", "Small", "Normal", "Large", "Huge"] )
ori = input.string(defval = "Top Right" , group = "Aesthetics", title = "Table Orientation",
options = [
"Top Left", "Top Center", "Top Right",
"Middle Left", "Middle Center", "Middle Right",
"Bottom Left", "Bottom Center", "Bottom Right"
])
guc = input.color (defval = color.lime, group = "Aesthetics", title = "Gap Up Color" , inline = "0")
gdc = input.color (defval = color.red , group = "Aesthetics", title = "Gap Down Color", inline = "0")
gft = input.bool (defval = true, group = "Aesthetics", title = "Show Unfilled Gaps Table" )
gfs = input.bool (defval = true, group = "Aesthetics", title = "Show Gaps Statistics Table" )
// _______________________________________________________
//
// Prerequisite Calculations
// _______________________________________________________
var int [] tim = array.new_int(2), var int timFin = 0
if barstate.isfirst
tim.set(0,
math.round(timestamp(year, month, dayofmonth, hour, minute, second)))
if bar_index == 1
tim.set(1,
math.round(timestamp(year, month, dayofmonth, hour, minute, second)))
timFin := tim.get(1) - tim.get(0)
// _______________________________________________________
//
// Gaps
// _______________________________________________________
type statsDraw
float gCount
box boxGpU
box boxGpD
label labGpD
label labGpU
float price
int boxCount
float save
box gBox
color gCol
float gFloat
string dNp
bool gDn = high < low[1] and math.abs(low[1] / high - 1) > perG
bool gUp = low > high[1] and math.abs(low / high[1] - 1) > perG
var upMat = matrix.new<statsDraw>(6, 0), var dnMat = matrix.new<statsDraw>(6, 0)
var gMat = matrix.new<statsDraw>(5, 0), var int [] avgU = array.new_int(), var int [] avgD = array.new_int(),
var float [] finAvgU = array.new_float(), var float [] finAvgD = array.new_float()
sz = switch size
"Auto" => size.auto
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
if session.ismarket
if gUp
upMat.add_col(upMat.columns()), gMat.add_col(0)
for i = 0 to 3
dataG = switch i != -1
true and i == 0 => statsDraw.new(gFloat = gMat.columns() == 1 ? low : gMat.get(0, 1).gFloat + low - high[1])
true and i == 1 => statsDraw.new(gFloat = (low / high[1] - 1) * 100)
true and i == 2 => statsDraw.new(gCol = color.new(guc, 50))
=> statsDraw.new(dNp =
str.tostring(low - high[1], format.mintick) + "\n" +
str.tostring(year, "###") + "/" +
str.tostring(month, "###") + "/" +
str.tostring(dayofmonth, "###"))
gMat.set(i, 0, dataG)
for i = 0 to 5
dataU = switch i != -1
true and i == 0 => statsDraw.new(
boxGpU = box.new(
math.round(time),low, math.round(time) + timFin,high[1],
text = str.tostring((close / low - 1) * 100, format.percent) + " To Fill",
xloc = xloc.bar_time,
bgcolor = color.new(guc, 50),
border_color = guc,
text_color = color.white,
text_halign = text.align_right,
text_size = sz
))
true and i == 1 => statsDraw.new(
boxGpU = box.new(
na, na, na, na, xloc = xloc.bar_time, text_size = sz, text_color = color.white
))
true and i == 2 => statsDraw.new(
labGpU = label.new(
na, na, xloc = xloc.bar_time,
color = color.new(guc, 50),
textcolor = #ffffff,
style = label.style_label_left,
size = size == "Auto" ? size.small : sz
))
true and i == 3 => statsDraw.new(boxCount = 0)
true and i == 4 => statsDraw.new(price = 1e+13)
true and i == 5 => statsDraw.new(save = upMat.get(0, upMat.columns() - 1).boxGpU.get_top())
upMat.set(i, upMat.columns() - 1, dataU)
avgU.push(bar_index)
if gDn
gMat.add_col(0), dnMat.add_col(dnMat.columns())
for i = 0 to 3
dataG = switch i != -1
true and i == 0 => statsDraw.new(gFloat = gMat.columns() == 1 ? high : gMat.get(0, 1).gFloat + high - low[1])
true and i == 1 => statsDraw.new(gFloat = (high / low[1] - 1) * 100)
true and i == 2 => statsDraw.new(gCol = color.new(gdc, 50))
=> statsDraw.new(dNp =
str.tostring(high - low[1], format.mintick) + "\n" +
str.tostring(year, "###") + "/" +
str.tostring(month, "###") + "/" +
str.tostring(dayofmonth, "###"))
gMat.set(i, 0, dataG)
for i = 0 to 5
dataD = switch i != -1
true and i == 0 => statsDraw.new(
boxGpD = box.new(
math.round(time), low[1], math.round(time) + timFin, high, xloc = xloc.bar_time,
text = str.tostring((close / high - 1) * 100, format.percent) + " To Fill",
bgcolor = color.new(gdc, 50),
border_color = gdc,
text_color = color.white,
text_halign = text.align_right,
text_size = sz
))
true and i == 1 => statsDraw.new(
boxGpD = box.new(
na, na, na, na, xloc = xloc.bar_time, text_size = sz, text_color = color.white
))
true and i == 2 => statsDraw.new(
labGpD = label.new(
na, na, xloc = xloc.bar_time, color = color.new(gdc, 50),
textcolor = #ffffff,
style = label.style_label_left,
size = size == "Auto" ?
size.small : sz
))
true and i == 3 => statsDraw.new(boxCount = 0)
true and i == 4 => statsDraw.new(price = 0)
true and i == 5 => statsDraw.new(save = dnMat.get(0, dnMat.columns() - 1).boxGpD.get_bottom())
dnMat.set(i, dnMat.columns() - 1, dataD)
avgD.push(bar_index)
if upMat.columns() > 0
for n = 0 to upMat.columns() - 1
if low < upMat.get(0, n).boxGpU.get_bottom()
if upMat.get(3, n).boxCount != 1 and upMat.get(3, n).boxCount != 3
upMat.get(0, n).boxGpU.set_text(gDn ? "New Gap" : "Filled")
upMat.get(0, n).boxGpU.set_bgcolor(color.new(guc, 90))
upMat.get(0, n).boxGpU.set_border_color(color.new(guc, 90))
finAvgU.push(bar_index - array.get(avgU, n))
if not na(upMat.get(1, n).boxGpU.get_bottom())
upMat.get(1, n).boxGpU.set_bgcolor(na), upMat.get(1, n).boxGpU.set_border_color(na)
upMat.get(0, n).boxGpU.set_top(upMat.get(1, n).boxGpU.get_top())
switch del
false => upMat.set(3, n, statsDraw.new(boxCount = 1))
=> upMat.set(3, n, statsDraw.new(boxCount = 3))
if lab
upMat.get(2, n).labGpU.set_color(na), upMat.get(2, n).labGpU.set_textcolor(na)
if dont
upMat.get(0, n).boxGpU.set_top(upMat.get(5, n).save)
else if low < upMat.get(0, n).boxGpU.get_top() and low > upMat.get(0, n).boxGpU.get_bottom() and (upMat.get(3, n).boxCount == 0 or upMat.get(3, n).boxCount == 2)
if upMat.get (3, n) .boxCount == 0
upMat.set(3, n, statsDraw.new(boxCount = 2))
if dont == false
upMat.get(1, n).boxGpU.set_rightbottom(upMat.get(0, n).boxGpU.get_right(), upMat.get(0, n).boxGpU.get_bottom())
upMat.get(1, n).boxGpU.set_bgcolor(color.new(guc, 90))
upMat.get(1, n).boxGpU.set_border_color(guc), upMat.get(0, n).boxGpU.set_border_color(na)
upMat.get(1, n).boxGpU.set_lefttop(upMat.get(0, n).boxGpU.get_left(), upMat.get(0, n).boxGpU.get_top())
upMat.get(0, n).boxGpU.set_top(low)
if upMat.get(3, n).boxCount != 1 and upMat.get(3, n).boxCount != 3
upMat.set(4, n, statsDraw.new(price = math.min(low, upMat.get(4, n).price)))
upMat.get(0, n).boxGpU.set_right( math.round(time + timFin))
txt = switch upMat.get(3, n).boxCount == 0
true => str.tostring((upMat.get(0, n).boxGpU.get_bottom() / close - 1) * 100, format.percent) + " Decrease To Fill"
=> dont == false ? str.tostring((upMat.get(0, n).boxGpU.get_bottom() / close - 1) * 100, format.percent) + " To Fill \n(Partially Filled " +
str.tostring ((( upMat.get(4, n).price
- upMat.get(1, n).boxGpU.get_top ()) * 100)
/ (upMat.get(1, n).boxGpU.get_bottom()
- upMat.get(1, n).boxGpU.get_top ()),
format.percent) + ")"
: str.tostring((upMat.get(0, n).boxGpU.get_bottom() / close - 1) * 100, format.percent) + " Decrease To Fill"
[row, row1] = if dont == true and upMat.get(3, n).boxCount != 0
[1, 0]
else
[0, 1]
if lab == false
switch upMat.get(3, n).boxCount == 0
true => upMat.get(0, n).boxGpU.set_text(txt)
=> upMat.get(row, n).boxGpU.set_text(""), upMat.get(row1, n).boxGpU.set_text(txt)
else
upMat.get(0, n).boxGpU.set_text(""), upMat.get(2, n).labGpU.set_text(txt)
upMat.get(2, n).labGpU.set_xy(math.round(time) + timFin, math.avg(upMat.get(0, n).boxGpU.get_bottom(),
upMat.get(0, n).boxGpU.get_top()))
if dont == false
upMat.get(1, n).boxGpU.set_right(math.round(time) + timFin)
if del == true
for i = 0 to upMat.columns() - 1
if i < upMat.columns()
if upMat.get(3, i).boxCount == 3
upMat.get(0, i).boxGpU.delete(), upMat.get(1, i).boxGpU.delete(), upMat.get(2, i).labGpU.delete()
upMat.remove_col(i)
else
if upMat.columns() - 1 > 250
for i = 0 to upMat.columns() - 1
if upMat.get(3, i).boxCount == 1
upMat.get(0, i).boxGpU.delete(), upMat.get(1, i).boxGpU.delete(), upMat.get(2, i).labGpU.delete()
upMat.remove_col(i)
break
if old >= 0 and upMat.columns() > 0
for x = 0 to upMat.columns() - 1
if upMat.get(3, x).boxCount != 1 and upMat.get(3, x).boxCount != 3
if close >= upMat.get(0, x).boxGpU.get_top() * (1 + old)
for i = 0 to 1
upMat.get(i, x).boxGpU.set_bgcolor(na), upMat.get(i, x).boxGpU.set_border_color(na)
upMat.get(i, x).boxGpU.set_right(upMat.get(i, x).boxGpU.get_left())
else
for i = 0 to 1
upMat.get(i, x).boxGpU.set_bgcolor(color.new(guc, 50))
upMat.get(i, x).boxGpU.set_border_color(color.new(guc, 50))
if dnMat.columns() > 0
for n = 0 to dnMat.columns() - 1
if high > dnMat.get(0, n).boxGpD.get_top()
if dnMat.get(3, n).boxCount != 1 and dnMat.get(3, n).boxCount != 3
finAvgD.push(bar_index - avgD.get(n))
dnMat.get(0, n).boxGpD.set_text(gUp ? "New Gap" : "Filled")
dnMat.get(0, n).boxGpD.set_bgcolor(color.new (gdc, 90))
dnMat.get(0, n).boxGpD.set_border_color(color.new(gdc, 90))
if not na(dnMat.get(1, n).boxGpD.get_bottom())
dnMat.get(1, n).boxGpD.set_bgcolor(na), dnMat.get(1, n).boxGpD.set_border_color(na)
dnMat.get(0, n).boxGpD.set_bottom(dnMat.get(1, n).boxGpD.get_bottom())
switch del
false => dnMat.set(3, n, statsDraw.new(boxCount = 1))
=> dnMat.set(3, n, statsDraw.new(boxCount = 3))
if lab
dnMat.get(2, n).labGpD.set_color(na), dnMat.get(2, n).labGpD.set_textcolor(na)
if dont
dnMat.get(0, n).boxGpD.set_bottom(dnMat.get(5, n).save)
else if high < dnMat.get(0, n).boxGpD.get_top() and high > dnMat.get(0, n).boxGpD.get_bottom() and (dnMat.get(3, n).boxCount == 0 or dnMat.get(3, n).boxCount == 2)
if dnMat.get(3, n).boxCount == 0
dnMat.set(3, n, statsDraw.new(boxCount = 2))
if dont == false
dnMat.get(1, n).boxGpD.set_rightbottom(dnMat.get(0, n).boxGpD.get_right(), dnMat.get(0, n).boxGpD.get_bottom())
dnMat.get(1, n).boxGpD.set_bgcolor(color.new(gdc, 90))
dnMat.get(1, n).boxGpD.set_border_color(gdc), dnMat.get(0, n).boxGpD.set_border_color(na)
dnMat.get(1, n).boxGpD.set_lefttop(dnMat.get(0, n).boxGpD.get_left(), dnMat.get(0, n).boxGpD.get_top())
dnMat.get(0, n).boxGpD.set_bottom(high)
if dnMat.get(3, n).boxCount != 1 and dnMat.get(3, n).boxCount != 3
dnMat.set(5, n, statsDraw.new(price = math.max(high, dnMat.get(5, n).price)))
dnMat.get(0, n).boxGpD.set_right(math.round(time) + timFin)
txt = switch dnMat.get(3, n).boxCount == 0
true => str.tostring((dnMat.get(0, n).boxGpD.get_top() / close - 1) * 100, format.percent) + " Increase To Fill"
=> dont == false ? str.tostring((dnMat.get(0, n).boxGpD.get_top() / close - 1) * 100, format.percent) + " To Fill \n(Partially Filled " +
str.tostring(((dnMat.get(0, n).boxGpD.get_bottom() - dnMat.get(1, n).boxGpD.get_bottom()) * 100)
/ (dnMat.get(0, n).boxGpD.get_top() - dnMat.get(1, n).boxGpD.get_bottom()),
format.percent) + ")" :
str.tostring((dnMat.get(0, n).boxGpD.get_top() / close - 1) * 100, format.percent) + " Increase To Fill"
[row, row1] = if dont == true and dnMat.get(3, n).boxCount != 0
[1, 0]
else
[0, 1]
if lab == false
switch dnMat.get(3, n).boxCount == 0
true => dnMat.get(0, n).boxGpD.set_text(txt)
=> dnMat.get(row, n).boxGpD.set_text(""), dnMat.get(row1, n).boxGpD.set_text(txt)
else
dnMat.get(0, n).boxGpD.set_text("")
dnMat.get(2, n).labGpD.set_text(txt), dnMat.get(2, n).labGpD.set_xy(math.round(time) + timFin,
math.avg(dnMat.get(0, n).boxGpD.get_bottom(), dnMat.get(0, n).boxGpD.get_top()))
dnMat.get(1, n).boxGpD.set_right(math.round(time) + timFin)
if del == true
for i = 0 to dnMat.columns() - 1
if i < dnMat.columns()
if dnMat.get(3, i).boxCount == 3
dnMat.get(0, i).boxGpD.delete(), dnMat.get(1, i).boxGpD.delete(), dnMat.get(0, i).labGpD.delete()
dnMat.remove_col(i)
else
if dnMat.columns() > 250
for i = 0 to dnMat.columns() - 1
if dnMat.get(3, i).boxCount == 1
dnMat.get(0, i).boxGpD.delete(), dnMat.get(1, i).boxGpD.delete(), dnMat.get(0, i).labGpD.delete()
dnMat.remove_col(i)
break
if old >= 0 and dnMat.columns() > 0
for x = 0 to dnMat.columns() - 1
if dnMat.get(3, x).boxCount != 1 and dnMat.get(3, x).boxCount != 3
if close <= dnMat.get(0, x).boxGpD.get_bottom() * (1 - old)
for i = 0 to 1
dnMat.get(i, x).boxGpD.set_bgcolor(na), dnMat.get(i, x).boxGpD.set_border_color(na)
dnMat.get(i, x).boxGpD.set_right(dnMat.get(i, x).boxGpD.get_left())
else
for i = 0 to 1
dnMat.get(i, x).boxGpD.set_bgcolor(color.new(gdc, 50))
dnMat.get(i, x).boxGpD.set_border_color(color.new(gdc, 50))
if barstate.islast
if gMat.columns() > 0
xn = gMat
if vis == true
bo = box.all
for i = 0 to bo.size() - 1
bo.shift().delete()
for i = 0 to math.min(500, gMat.columns() - 2)
xn.set(4, i, statsDraw.new(gBox = box.new(bar_index[i + 1],
xn.get(0, i).gFloat > xn.get(0, i + 1).gFloat ? xn.get(0, i).gFloat : xn.get(0, i + 1).gFloat ,
bar_index[i],
xn.get(0, i).gFloat > xn.get(0, i + 1).gFloat ? xn.get(0, i + 1).gFloat : xn.get(0, i).gFloat,
bgcolor = xn.get(2, i).gCol,
border_color = color.white,
text = xn.get(3, i).dNp,
text_color = color.white,
text_size = sz
)))
calc = math.abs(close - xn.get(4, 0).gBox.get_top()), calc1 = math.abs(close - xn.get(4, 0).gBox.get_bottom())
for i = 0 to array.size(box.all) - 1
xn.get(4, i).gBox.set_top(xn.get(4, i) .gBox.get_top () + calc)
xn.get(4, i).gBox.set_bottom(xn.get(4, i).gBox.get_bottom() + calc1)
else
sli = array.new_float()
for i = 0 to gMat.columns() - 1
sli.push(xn.get(1, i).gFloat)
sli.sort(order.ascending)
dn = array.new_float(), up = array.new_float()
for x = 1 to sli.size() - 1
if sli.get(0) < 0
if sli.get(sli.size() - 1) > 0
if sli.get(x - 1) < 0 and sli.get(x) > 0
for n = 0 to x - 1
dn.push(sli.get(n))
for n = x to sli.size() - 1
up.push(sli.get(n))
break
else if sli.get(0) > 0
if x != sli.size() - 1
up.push(sli.get(x - 1))
else
if sli.size() > 1
up.push(sli.get(x))
up.push(sli.get(x - 1))
if sli.get(sli.size() - 1) < 0
if x != sli.size() - 1
dn.push(sli.get(x - 1))
else
if sli.size() > 1
up.push(sli.get(x))
up.push(sli.get(x - 1))
orit = switch ori
"Top Left" => position.top_left
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
var table stats = table.new(position.bottom_right, 10, 10, border_color = color.white, frame_color= color.white, border_width = 1, frame_width = 1)
var table upRight = table.new(orit, 10, 10, border_color = color.white, frame_color= color.white, border_width = 1, frame_width = 1)
if gfs
stats.cell(0, 0, "# of Gaps: " + str.tostring(sli.size()) , text_color = guc, bgcolor = color.new(#000000, 75))
stats.cell(0, 1, "Gaps Up: " + str.tostring(array.size(up)) , text_color = guc, bgcolor = color.new(#000000, 75))
stats.cell(0, 2, "Gaps Down: " + str.tostring(array.size(dn)) , text_color = guc, bgcolor = color.new(#000000, 75))
stats.cell(1, 1, "Cumulative Increase: " + str.tostring(array.sum(up), format.percent) , text_color = guc, bgcolor = color.new(#000000, 75))
stats.cell(2, 1, "Cumulative Decrease: " + str.tostring(array.sum(dn), format.percent) , text_color = guc, bgcolor = color.new(#000000, 75))
stats.cell(1, 2, "Avg. Increase: " + str.tostring(array.avg(up), format.percent) , text_color = guc, bgcolor = color.new(#000000, 75))
stats.cell(2, 2, "Avg. Decrease: " + str.tostring(array.avg(dn), format.percent) , text_color = guc, bgcolor = color.new(#000000, 75))
strUp = "", strDn = ""
if upMat.columns() > 0 and rec > 0
upCou = 0
for n = upMat.columns() - 1 to 0
if upCou == rec
upCou := 0, break
if upMat.get(3, n).boxCount != 1 and upMat.get(3, n).boxCount != 3
if not na(upMat.get(0, n).boxGpU.get_bottom())
strUp := strUp + str.tostring(upMat.get(0, n).boxGpU.get_bottom(), format.mintick) +
" - " + str.tostring(upMat.get(0, n).boxGpU.get_top (), format.mintick) +
" (Distance: " + str.tostring((close - upMat.get(0, n).boxGpU.get_bottom()) * -1, format.mintick) + ")" +
"\n"
upCou += 1
if dnMat.columns() > 0 and rec > 0
dnCou = 0
for n = dnMat.columns() - 1 to 0
if dnCou == rec
break
if dnMat.get(3, n).boxCount != 1 and dnMat.get(3, n).boxCount != 3
if not na(dnMat.get(0, n).boxGpD.get_bottom())
strDn := strDn + str.tostring(dnMat.get(0, n).boxGpD.get_bottom(), format.mintick) +
" - " + str.tostring(dnMat.get(0, n).boxGpD.get_top (), format.mintick) +
" (Distance: +" + str.tostring((close - dnMat.get(0, n).boxGpD.get_top()) * -1, format.mintick) + ")" +
"\n"
dnCou += 1
if gft
if rec > 0
sz2 = switch size
"Auto" => size.auto
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
if strUp != ""
upRight.cell(0, 0, old != -1/100 ? "Gaps " + str.tostring(old * 100, format.percent)
+ " Away From Price Are Not Shown \nThis Can Be Changed In The Settings"
: "All Gaps Shown\n This Can Be Changed In The Settings",
bgcolor = color.new(#000000, 75),
text_color = color.yellow,
text_size = size.small
)
upRight.cell(0, 1, "Unfilled Up Gaps", bgcolor = color.new(#000000, 75), text_color = guc, text_size = sz2)
upRight.cell(0, 2, strUp, bgcolor = color.new(#000000, 75), text_color = guc, text_size = sz2)
if strDn != ""
upRight.cell(0, 3, "Unfilled Down Gaps", bgcolor = color.new(#000000, 75), text_color = gdc, text_size = sz2)
upRight.cell(0, 4, strDn, bgcolor = color.new(#000000, 75), text_color = gdc, text_size = sz2)
if font
bo = box.all, ta = table.all
if gft
for i = 0 to 4
upRight .cell_set_text_font_family(0, i, font.family_monospace)
if gfs
for i = 0 to 2
for x = 0 to 2
stats.cell_set_text_font_family(i, x, font.family_monospace)
for i = 0 to bo.size() - 1
bo.get(i) .set_text_font_family(font.family_monospace)
if lab
l = label.all
for i = 0 to l.size() - 1
l.get(i) .set_text_font_family(font.family_monospace)
if del == false and gfs
for i = 1 to 2
strin = switch i != -1
true and i == 1 => "Avg. Bars to Fill Up Gap: " + str.tostring(math.round(finAvgU.avg()), "#")
=> "Avg. Bars to Fill Down Gap: " + str.tostring(math.round(finAvgD.avg()), "#")
table.cell(stats, i, 0, strin,
text_color = guc,
bgcolor = color.new(#000000, 75),
text_font_family = font ? font.family_monospace : font.family_default)
else
if gfs
stats.merge_cells(0, 0, 2, 0)
else
runtime.error("No Gaps Detected - Change Assets or Plot a Different Dataset")
|
Historical Volatility Scale [ChartPrime] | https://www.tradingview.com/script/tKw4WJVt-Historical-Volatility-Scale-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 236 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ExoMaven
//@version=5
indicator(title = "Historical Volatility Scale [ChartPrime]", shorttitle = "Historical Volatility Scale [V1]", overlay = true, scale = scale.none, max_lines_count = 100)
//░█████╗░██╗░░██╗░█████╗░██████╗░████████╗ ██████╗░██████╗░██╗███╗░░░███╗███████╗
//██╔══██╗██║░░██║██╔══██╗██╔══██╗╚══██╔══╝ ██╔══██╗██╔══██╗██║████╗░████║██╔════╝
//██║░░╚═╝███████║███████║██████╔╝░░░██║░░░ ██████╔╝██████╔╝██║██╔████╔██║█████╗░░
//██║░░██╗██╔══██║██╔══██║██╔══██╗░░░██║░░░ ██╔═══╝░██╔══██╗██║██║╚██╔╝██║██╔══╝░░
//╚█████╔╝██║░░██║██║░░██║██║░░██║░░░██║░░░ ██║░░░░░██║░░██║██║██║░╚═╝░██║███████╗
//╚════╝░╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░ ╚═╝░░░░░╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝╚══════╝
//--------------------------------------------------------------------------------
//░█████╗░██████╗░███████╗░█████╗░████████╗███████╗██████╗░ ██████╗░██╗░░░██╗
//██╔══██╗██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝██╔══██╗ ██╔══██╗╚██╗░██╔╝
//██║░░╚═╝██████╔╝█████╗░░███████║░░░██║░░░█████╗░░██║░░██║ ██████╦╝░╚████╔╝░
//██║░░██╗██╔══██╗██╔══╝░░██╔══██║░░░██║░░░██╔══╝░░██║░░██║ ██╔══██╗░░╚██╔╝░░
//╚█████╔╝██║░░██║███████╗██║░░██║░░░██║░░░███████╗██████╔╝ ██████╦╝░░░██║░░░
//░╚════╝░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝░░░╚═╝░░░╚══════╝╚═════╝░ ╚═════╝░░░░╚═╝░░░
//███████╗██╗░░██╗░█████╗░███╗░░░███╗░█████╗░██╗░░░██╗███████╗███╗░░██╗
//██╔════╝╚██╗██╔╝██╔══██╗████╗░████║██╔══██╗██║░░░██║██╔════╝████╗░██║
//█████╗░░░╚███╔╝░██║░░██║██╔████╔██║███████║╚██╗░██╔╝█████╗░░██╔██╗██║
//██╔══╝░░░██╔██╗░██║░░██║██║╚██╔╝██║██╔══██║░╚████╔╝░██╔══╝░░██║╚████║
//███████╗██╔╝╚██╗╚█████╔╝██║░╚═╝░██║██║░░██║░░╚██╔╝░░███████╗██║░╚███║
//╚══════╝╚═╝░░╚═╝░╚════╝░╚═╝░░░░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░╚══════╝╚═╝░░╚══╝
//-------------------------------------------------------------------------------
len = input.int(title = "Length", defval = 50)
vol = ta.stdev(close / close[1], len, true)
vol_percentile = ta.percentrank(vol, len)
scale_offset = 5
scale_width = 10
pin_offset = 5
pin_size = size.huge
inv = color.new(color.black, 100)
polar_size = size.huge
var scale = array.new_line()
var line mover = na
var label pin = na
var label heat = na
var label snooze = na
if barstate.isfirst
for i = 0 to 99
array.push(scale, line.new(1, i, 1, i + 1, width = scale_width))
pin := label.new(na, na, color = inv, size = pin_size, text = "◀", style = label.style_label_left)
heat := label.new(na, na, color = inv, size = polar_size, text = "🔥", style = label.style_label_down)
snooze := label.new(na, na, color = inv, size = polar_size, text = "😴", style = label.style_label_up)
if barstate.islast
for i = 0 to array.size(scale) - 1
branch = array.get(scale, i)
line.set_xloc(branch, bar_index + scale_offset, bar_index + scale_offset, xloc.bar_index)
line.set_color(branch, color.from_gradient(i, 0, 100, color.green, color.red))
label.set_xloc(pin, bar_index + pin_offset, xloc.bar_index)
label.set_y(pin, vol_percentile)
label.set_textcolor(pin, color.from_gradient(vol_percentile, 0, 100, color.green, color.red))
label.set_xloc(heat, bar_index + scale_offset, xloc.bar_index)
label.set_y(heat, 100)
label.set_xloc(snooze, bar_index + scale_offset, xloc.bar_index)
label.set_y(snooze, 0)
|
Candle Mania [starlord_xrp] | https://www.tradingview.com/script/dNPDmo0C-Candle-Mania-starlord-xrp/ | starlord_xrp | https://www.tradingview.com/u/starlord_xrp/ | 59 | 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/
// © starlord_xrp
//@version=5
indicator("Candle Mania [starlord_xrp]", overlay = true)
//fast volume weighted moving average that acts like a filter for uptrend or downtrend
ma = ta.vwma(close, 8)
//triggers
bool doji_star = false
show_doji_star = input.bool(true, "Show Doji Star")
bool doji_long_leg_bull = false
bool doji_long_leg_bear = false
show_doji_long_leg = input.bool(true, "Show Long-Legged Doji")
bool morning_star = false
show_morning_star = input.bool(true, "Show Morning Star")
bool evening_star = false
show_evening_star = input.bool(true, "Show Evening Star")
bool no_trades = false
show_no_trades = input.bool(false, "Show No-Trading")
bool three_black_crows = false
show_three_black_crows = input.bool(false, "Show Three Black Crows")
bool three_white_soldiers = false
show_three_white_soldiers = input.bool(false, "Show Three White Soldiers")
bool grave_stone = false
show_gravestone = input.bool(true, "Show Gravestone")
bool dragenfly = false
show_dragonfly = input.bool(false, "Show Dragonfly")
bool hanging_man = false
show_hanging_man = input.bool(true, "Shwo Hanging Man")
bool hammer = false
show_hammer = input.bool(true, "Show Hammer")
bool inverted_hammer = false
show_inverted_hammer = input.bool(true, "Show Inverted Hammer")
bool bull_engulfing = false
show_bull_engulfing = input.bool(false, "Show Bullish Engulfing")
bool bear_engulfing = false
show_bear_engulfing = input.bool(false, "Show Bearish Engulfing")
bool dark_cloud = false
show_dark_cloud = input.bool(false, "Show Dark Cloud")
bool piercing_patern = false
show_piercing_patern = input.bool(false, "Show Piercing Pattern")
bool shooting_star = false
show_shooting_star = input.bool(true, "Show Shooting Star")
bool bearish_harami = false
show_bearish_harami = input.bool(false, "Show Bearish Harami")
bool bullish_harami = false
show_bullish_harami = input.bool(false, "Show Bullish Harami")
bool ha_bear = false
bool ha_bull = false
show_ha = input.bool(false, "Show Heiken Ashi Direction Changes On Chart")
//this lets the close and open be within 0.01% of each other to be counted as the same for dojis
bool open_close_same = close>open-(open*0.0001) and close<open+(open*0.0001)
bool close_high_same = close>high-(high*0.0001) and close<high+(high*0.0001)
bool close_low_same = close > low-(low*0.0001) and close < low+(low*0.0001)
bool open_high_same = open>high-(high*0.0001) and open<high+(high*0.0001)
bool open_low_same = open>low-(low*0.0001) and open<low+(low*0.0001)
//rsi
show_rsi = input.bool(true, "===Show RSI===", group = "RSI")
length = input.int(14, "RSI Length", group = "RSI")
src = input.source(close, "RSI Source", group = "RSI")
float rsi = ta.rsi(src, length)
rsi_over_bought = input.int(70, "RSI Over-bought Level", group = "RSI")
rsi_over_sold = input.int(30, "RSI Over-sold Level", group = "RSI")
//money flow index
show_mfi = input.bool(false, "===Show MFI===", group = "MFI" )
length2 = input.int(14, "MFI Length", group = "MFI")
mfi_over_bought = input.int(80, "MFI Over-bought Level", group = "MFI")
mfi_over_sold = input.int(20, "MFI Over-sold Level", group = "MFI")
src2 = hlc3
mfi = ta.mfi(src2, length2)
//stochastic RSI
show_stoch = input.bool(false, "===Show Stochastic RSI===", group = "Stochastic RSI")
smoothK = input.int(3, "K", minval=1, group = "Stochastic RSI")
smoothD = input.int(3, "D", minval=1, group = "Stochastic RSI")
lengthRSI = input.int(14, "RSI Length", minval=1, group = "Stochastic RSI")
lengthStoch = input.int(14, "Stochastic Length", minval=1, group = "Stochastic RSI")
src3 = input.source(close, title="Stochastic RSI Source", group = "Stochastic RSI")
stoch_over_bought = input.int(80, "Stochastic Over-bought Level", group = "Stochastic RSI")
stoch_over_sold = input.int(20, "Stochastic Over-sold Level", group = "Stochastic RSI")
rsi1 = ta.rsi(src3, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
// easy bull to caululate if the previous candle was up
bool bullrun = false
if close[1]>open[1]
bullrun := true
//this just checks if the price did not move at all
if open == close and close==low and high==low and show_no_trades and barstate.isconfirmed
no_trades := true
//dogi star
if open_close_same and (close-low == high-close) and close != low and show_doji_star and barstate.isconfirmed
doji_star := true
//dogi long-legged
//bear
if open_close_same and (close-low < high-close) and low != open and high != open and close>ma and show_doji_long_leg and barstate.isconfirmed
doji_long_leg_bear := true
//bull
if open_close_same and (close-low > high-close) and high != open and low != open and close<ma and show_doji_long_leg and barstate.isconfirmed
doji_long_leg_bull := true
//gravestone doji
if open_close_same and (close==low or open==low) and high>open and high>close and close>ma and show_gravestone and barstate.isconfirmed
grave_stone := true
// dragonfly
if open_close_same and (close==high or open==high) and low<open and low<close and rsi<rsi_over_bought and show_dragonfly and barstate.isconfirmed
dragenfly := true
//hangman
if (close_high_same or open_high_same) and close>ma and show_hanging_man
if close>open and close-open < (open-low)/2 and barstate.isconfirmed
hanging_man := true
if close<open and open-close < (close-low)/2 and barstate.isconfirmed
hanging_man := true
//hammer
if (close_high_same or open_high_same) and close<ma and show_hammer
if close>open and close-open < (open-low)/2 and barstate.isconfirmed
hammer := true
if close<open and open-close < (close-low)/2 and barstate.isconfirmed
hammer := true
//bullish engulfing
if bullrun==false and close[1]>open and close>open[1] and close>open and show_bull_engulfing and barstate.isconfirmed
bull_engulfing := true
//bearish engulfing
if bullrun and close[1]<open and close<open[1] and close<open and show_bear_engulfing and barstate.isconfirmed
bear_engulfing := true
//dark cloud
if close[1]>ma and open>high[1] and close<(open[1]+close[1])/2 and show_dark_cloud and barstate.isconfirmed
dark_cloud := true
//piercing pattern
if close[1]<ma and open<low[1] and close>(open[1]+close[1])/2 and close<open[1] and show_piercing_patern and barstate.isconfirmed
piercing_patern := true
//evenging star
if close[2]>open[2] and open_close_same[1] and open[1]>close[2] and close<open and close<((open[2]+close[2])/2) and close[1]>ma and show_evening_star and barstate.isconfirmed
evening_star := true
//morning star
if close[2]<open[2] and open_close_same[1] and open[1]<close[2] and close>open and close>((open[2]+close[2])/2) and close[1]<ma and show_morning_star and barstate.isconfirmed
morning_star := true
//shooting star
if (close_low_same or open_low_same) and close>ma and show_shooting_star and close>ma
if close>open and close-open < (high-close)/2 and barstate.isconfirmed
shooting_star := true
if close<open and open-close < (high-open)/2 and barstate.isconfirmed
shooting_star := true
//inverted hammer
if (close_low_same or open_low_same) and close<ma and show_inverted_hammer and close<ma
if close>open and close-open < (high-close)/2 and barstate.isconfirmed
inverted_hammer := true
if close<open and open-close < (high-open)/2 and barstate.isconfirmed
inverted_hammer := true
//bearish harami
if bullrun and open<close[1] and open_close_same==false and close>open[1] and barstate.isconfirmed and close<open and close[1]>ma and show_bearish_harami and barstate.isconfirmed
bearish_harami := true
//bullish harami
if bullrun==false and open>close[1] and close<open[1] and close>open and open_close_same==false and close[1]<ma and show_bullish_harami and barstate.isconfirmed
bullish_harami := true
//three black crows
if close[2]<open[3] and close[2]<close[3] and open[1]>close[2] and close[1]<close[2] and open>close[1] and close<close[1] and show_three_black_crows and barstate.isconfirmed
three_black_crows := true
//three whise soldiers
if close[2]>open[3] and close[2]>close[3] and open[1]<close[2] and close[1]>close[2] and open<close[1] and close>close[1] and show_three_white_soldiers and barstate.isconfirmed
three_white_soldiers := true
//heiken ashi trend turns
if show_ha and request.security(ticker.heikinashi(syminfo.tickerid), "", close>open) and ta.change(request.security(ticker.heikinashi(syminfo.tickerid), "", close>open))
ha_bull := true
if show_ha and ta.change(request.security(ticker.heikinashi(syminfo.tickerid), "", close<open)) and request.security(ticker.heikinashi(syminfo.tickerid), "", close<open)
ha_bear := true
//plots
plotshape(doji_star and bullrun, "", shape.cross, location.abovebar, color.red, 0, "Doji Star", textcolor = color.red, size = size.tiny)
plotshape(doji_star and bullrun==false, "", shape.cross, location.belowbar, color.green, 0, "Doji Star", textcolor = color.green, size = size.tiny)
plotchar(morning_star, "", "⭐", location.belowbar, color.green, -1, "Morning Star", textcolor = color.green, size = size.tiny)
plotchar(evening_star, "", "⭐", location.abovebar, color.red, -1, "Evening Star", textcolor = color.red, size = size.tiny)
plotchar(doji_long_leg_bear, "", "🦵", location.abovebar, color.red, 0, "Long-Leg Doji", color.red, size = size.tiny)
plotchar(doji_long_leg_bull and bullrun==false, "", "🦵", location.belowbar, color.green, 0, "Long-Leg Doji", textcolor = color.green, size = size.tiny)
plotshape(no_trades, "no trades", shape.xcross, location.abovebar, color.gray, 0, "No Trades", textcolor = color.gray, size = size.tiny)
plotchar(grave_stone, "", "💀", location.abovebar, color.red, 0, "Gravestone", textcolor = color.red, size = size.tiny)
plotchar(dragenfly, "", "🐉", location.belowbar, offset = 0, text = "Dragonfly", textcolor = color.green, size = size.tiny)
plotchar(hammer, "", "🔨", location.belowbar, color.green, 0, "Hammer", textcolor = color.green, size = size.tiny)
plotchar(hanging_man, "", "ᡷ", location.abovebar, color.red, 0, "Hanging Man", textcolor = color.red, size = size.tiny)
plotchar(bull_engulfing, "", "🐮", location.belowbar, color.green, 0, "Bull Engulfing", textcolor = color.green, size = size.tiny)
plotchar(bear_engulfing, "", "🐻", location.abovebar, color.red, 0, "Bear Engulfing", textcolor = color.red, size = size.tiny)
plotchar(dark_cloud, "", "🌩", location.abovebar, color.gray, 0, "Dark Cloud", textcolor = color.red, size = size.tiny)
plotchar(piercing_patern, "", "⚡", location.belowbar, color.green, 0, "Piercing Pattern", textcolor = color.green, size = size.tiny)
plotchar(shooting_star, "","🌠", location.abovebar, color.red, 0, "Shooting Star", color.red, size = size.tiny)
plotchar(inverted_hammer, "", "🔨", location.belowbar, color.green, 0, "Inverted Hammer", textcolor = color.green, size = size.tiny)
plotchar(bearish_harami, "", "🔥", location.abovebar, color.red, 0, "Bearish Harami", textcolor = color.red, size = size.tiny)
plotchar(bullish_harami, "", "🔥", location.belowbar, color.green, 0, "Bullish Harami", textcolor = color.green, size = size.tiny)
plotchar(three_black_crows, "", "🐦", location.abovebar, color.red, 0, "", color.red, size = size.tiny)
plotchar(three_black_crows, "", "🐦", location.abovebar, color.red, -1, "Three Black Crows", color.red, size = size.tiny)
plotchar(three_black_crows, "", "🐦", location.abovebar, color.red, -2, "", color.red, size = size.tiny)
plotchar(three_white_soldiers, "", "💣", location.belowbar, color.green, 0, "", color.green, size = size.tiny)
plotchar(three_white_soldiers, "", "💣", location.belowbar, color.green, -1, "Three White Soldiers", color.green, size = size.tiny)
plotchar(three_white_soldiers, "", "💣", location.belowbar, color.green, -2, "", color.green, size = size.tiny)
plotchar(ha_bull, "", "⇧", location.belowbar, color.green, 0, "\n", color.green, size = size.tiny)
plotchar(ha_bear, "", "⇩", location.abovebar, color.red, 0, "\n", color.red, size = size.tiny)
//background rsi/msi/stoch switches
color background = na
//rsi
if rsi<rsi_over_sold and show_rsi
background := color.new(color.green, 80)
if rsi>rsi_over_bought and show_rsi
background := color.new(color.red, 80)
//mfi
if mfi<mfi_over_sold and show_mfi
background := color.new(color.green, 80)
if mfi>mfi_over_bought and show_mfi
background := color.new(color.red, 80)
//stoch
if k<stoch_over_sold and show_stoch
background := color.new(color.green, 80)
if k>stoch_over_bought and show_stoch
background := color.new(color.red, 80)
//set background
bgcolor(background) |
Economic Data Trading alerts - CPI, Interest rate, PPI, etc | https://www.tradingview.com/script/GnmFUUVu-Economic-Data-Trading-alerts-CPI-Interest-rate-PPI-etc/ | KareemFarid | https://www.tradingview.com/u/KareemFarid/ | 18 | 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/
// © KareemFarid
//@version=5
indicator("BETA - Economic Data Trading Strategy - CPI, Interest rate, PPI and more", shorttitle = "Economic Data Trading Strategy", overlay=true)
// Input for the location and economic data point to trade
location = input.string("US", "Location", options=["US", "EU", "JP"])
data_point = input.string("GDP", "Economic Data Point", options=["GDP", "CPI", "CCPI", "UR", "PMI", "PPI","RSMM", "IPMM", "IJC", "INTR"])
// Input for trade direction
trade_on_increase = input.string("Long", "Trade direction when the value increases", options=["Long", "Short", "None"])
trade_on_decrease = input.string("Short", "Trade direction when the value decreases", options=["Long", "Short", "None"])
// Input for multiple TP and SL levels
tp1 = input.float(1, "Take Profit Level 1 (%)") / 100
sl1 = input.float(0.5, "Stop Loss Level 1 (%)") / 100
// Request the economic data
economic_data = request.economic(location, data_point)
// Access the current and previous values
current_value = economic_data
previous_value = economic_data[1]
// Define the long and short conditions based on the current and previous values
value_increased = current_value > previous_value
value_decreased = current_value < previous_value
long_condition = (trade_on_increase == "Long" and value_increased) or (trade_on_decrease == "Long" and value_decreased)
short_condition = (trade_on_increase == "Short" and value_increased) or (trade_on_decrease == "Short" and value_decreased)
// Plot long and short entries on the chart
plotshape(long_condition, title="Long Entry", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
plotshape(short_condition, title="Short Entry", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)
alertcondition(long_condition, title="Long Entry Alert", message="Long Entry Signal")
alertcondition(short_condition, title="Short Entry Alert", message="Short Entry Signal")
|
[JL] Control Your Emotions Reminder | https://www.tradingview.com/script/USC9rsqK-JL-Control-Your-Emotions-Reminder/ | Jesse.Lau | https://www.tradingview.com/u/Jesse.Lau/ | 35 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Jesse.Lau
//@version=5
indicator('[JL] Control Your Emotions Reminder', overlay=true, max_bars_back = 4900)
text_= input.string('=====Control Your Emotions=====\n')
text1= input.string('Fear:Fear can cause you to exit trades prematurely or prevent you from entering potentially profitable trades.')
text2= input.string('Greed: Greed can lead to overtrading, holding onto positions for too long, or taking excessive risks.')
text3= input.string('Anxiety: Anxiety can result in impulsive decision-making, affecting your ability to analyze and execute trades effectively.')
text4= input.string('Frustration: Frustration can lead to revenge trading or making rash decisions to recover losses quickly.')
text5= input.string('Overconfidence: Overconfidence can result in excessive risk-taking or a failure to adhere to your trading plan.')
text6= input.string('Euphoria: Euphoria can cause you to ignore risks, leading to potential losses when market conditions change.')
text7= input.string('Regret: Regret can lead to emotional decision-making, such as chasing missed opportunities or holding onto losing positions.')
text8= input.string('Envy: Envy can prompt you to copy other traders without conducting your own analysis, leading to potentially poor decisions.')
text9= input.string('Impatience: Impatience can lead to hasty decision-making, entering trades too early, or exiting too soon.')
text10= input.string('Boredom: Boredom can result in overtrading, entering trades without sufficient analysis, or neglecting your trading plan.')
text_ := text_ + '\n☐ '+text1
text_ := text_ + '\n☐ '+text2
text_ := text_ + '\n☐ '+text3
text_ := text_ + '\n☐ '+text4
text_ := text_ + '\n☐ '+text5
text_ := text_ + '\n☐ '+text6
text_ := text_ + '\n☐ '+text7
text_ := text_ + '\n☐ '+text8
text_ := text_ + '\n☐ '+text9
text_ := text_ + '\n☐ '+text10
bars_right = input.int(10, "x bars right")
position = input.source(close, "Label position")
one_color = input.bool(false, "Label only in one color")
lab_color = input.color(#ffd010, "Label color")
text_color = input.color(color.black,"Text color")
t = timenow + math.round(ta.change(time)*bars_right)
var label lab = na, label.delete(lab), lab := label.new(t, position, text = text_, style=label.style_label_left, yloc=yloc.price, xloc=xloc.bar_time, textalign=text.align_left, color=lab_color, textcolor=text_color,size=size.large )
|
Trend Line | https://www.tradingview.com/script/LUKaSZlC-Trend-Line/ | HPotter | https://www.tradingview.com/u/HPotter/ | 380 | 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/
// © HPotter 15/03/2023
//@version=5
////////////////////////////////////////////////////////////
// The indicator draws a trend line indicating the trend at the current moment and show it is resistance or support.
////////////////////////////////////////////////////////////
indicator("Trend Line", shorttitle="TL", overlay = true)
Length = input.int(25 , title="Length",tooltip="Overall length of market analysis")
var Green = color.new(color.green, 0)
var Red = color.new(color.red, 0)
var Work = false
var line lineLevel = na
var label labelName = na
if barstate.islastconfirmedhistory or barstate.isrealtime
Work := true
Points = ta.sma(hl2[1], Length)
clr = close[1] > Points ? Green : Red
line.delete(lineLevel)
lineLevel := line.new(bar_index-Length*2, Points[Length*2-1], bar_index, Points[1], color = clr)
label.delete(labelName)
trendLineIs = close[1] > Points ? "Support" : "Resistance"
_x = time + math.round(ta.change(time) * 10)
labelName := label.new(x=_x, y= Points[1] , text= trendLineIs, color=color.new(#000000, 100), textcolor = clr, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price) |
Will my limit order be filled ? | https://www.tradingview.com/script/GXcFOSbU-Will-my-limit-order-be-filled/ | mks17 | https://www.tradingview.com/u/mks17/ | 14 | 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/
// © mks17
//@version=5
indicator("Will my order be filled ?")
limitMargin = input.float(0.2, "Margin % from last close", step=0.01) / 100
numberBars = input.int(5, "Number of Bars to have a fill")
sourceL = input.source(close, "Source for the Long fill")
sourceS = input.source(close, "Source for the Short fill")
checkEntryL(int j) =>
counter = 0
for i = 0 to j - 1
if sourceL[i] < close[j] * (1 - limitMargin)
counter := 1
break
counter
checkEntryS(int j) =>
counter = 0
for i = 0 to j - 1
if sourceS[i] > close[j] * (1 + limitMargin)
counter := 1
break
counter
resultL = 0, resultS = 0
for i = 1 to numberBars
checkL = checkEntryL(i)
resultL := resultL + checkL
checkS = checkEntryS(i)
resultS := resultS + checkS
PercFilledL = resultL * 100 / numberBars
PercFilledS = resultS * 100 / numberBars
f_fhma(float _src) =>
sum = 0.0, var counter = 0
sum := nz(sum[1])
if not(na(_src))
counter := nz(counter[1]) + 1
sum := nz(_src) + sum
fhma = sum / counter
fhma
avgL = f_fhma(PercFilledL)
avgS = f_fhma(PercFilledS)
// plot(PercFilledL, "Percentage of Long limit orders Filled")
// plot(PercFilledS, "Percentage of Short limit orders Filled")
plot(avgL, "Percentage of Long limit orders Filled", color=color.blue)
plot(avgS, "Percentage of Short limit orders Filled", color=color.red)
|
SPX Fair Value Bands WSHOSHO | https://www.tradingview.com/script/MxhYLsAW-SPX-Fair-Value-Bands-WSHOSHO/ | dharmatech | https://www.tradingview.com/u/dharmatech/ | 136 | 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/
// © dharmatech
//@version=5
indicator("SPX Fair Value Bands WSHOSHO", overlay = true)
wshosho = request.security("WSHOSHO", "D", close)
rrp = request.security("RRPONTSYD", "D", close)
tga = request.security("WTREGEN", "D", close)
nl = wshosho - rrp - tga
spx_fv = nl / 1000 / 1000 / 1000 - 1700
upper = spx_fv + 300
lower = spx_fv - 200
plot(series=upper, title = 'Upper Band', color = color.red)
plot(series=spx_fv, title = 'Fair Value', color = color.orange)
plot(series=lower, title = 'Lower Band', color = color.green)
|
Supertrend ANY INDICATOR (RSI, MFI, CCI, etc.) + Range Filter | https://www.tradingview.com/script/GRMqFdJQ-Supertrend-ANY-INDICATOR-RSI-MFI-CCI-etc-Range-Filter/ | wbburgin | https://www.tradingview.com/u/wbburgin/ | 929 | 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
import wbburgin/wbburgin_utils/1 as e
//@version=5
indicator("Supertrend ANY INDICATOR (RSI, MFI, CCI, etc.) + Range Filter",shorttitle="ST ANY INDICATOR [wbburgin]",overlay=false)
// This indicator will generate a supertrend of your chosen configuration on any of the following indicators:
// RSI
// MFI
// ACCUMULATION / DISTRIBUTION
// MOMENTUM
// ON BALANCE VOLUME
// CCI
// Stochastic
// If you find this indicator useful, please boost it and follow! I am open to suggestions for adding new indicators
// to this script, it's very simple to add new ones, just suggest them in the comments.
// INPUTS ______________________________________________________________________________________________________________
sel = input.string("RSI","Indicator for Supertrend",
options=["RSI","MFI","Accum/Dist","Momentum","OB Volume","CCI","Stochastic"],
group="Main Settings")
indicator_length = input.int(14, "Indicator Length (if applicable)",group="Main Settings",
tooltip = "Ignore if indicator does not have length inputs (i.e. Accum/Dist, OBV)")
atr_length = input.int(10, "Supertrend ATR Length",group="Main Settings")
atr_mult = input.float(3.0,"Supertrend ATR Mult",step=0.5,group="Main Settings")
use_range = input.bool(false,"Use Range Filter of Indicator",
tooltip = "Use a range filter of the indicator instead of the indicator itself for calculations (for smoothing)",
group="Range Filter")
sampling_period = input.int(50,"Range Filter Sampling Period (if applicable)",group="Range Filter")
range_mult = input.float(3,"Range Filter Multiple (if applicable)",group="Range Filter")
labels = input.bool(true,"Show Labels",group="Display")
highlighting = input.bool(true,"Display Highlighting",group="Display")
oversold = input.int(30,"Oversold Level (if applicable)",group="Display")
overbought = input.int(70,"Overbought Level (if applicable)",group="Display")
// CALCULATIONS ________________________________________________________________________________________________________
filt(source,sampling_period,range_mult) =>
e.rngfilt(source,e.smoothrng(source,sampling_period,range_mult))
rsi = switch
use_range == false => ta.rsi(close,indicator_length)
=> filt(ta.rsi(close,indicator_length),sampling_period,range_mult)
mfi = switch
use_range == false => ta.mfi(close,indicator_length)
=> filt(ta.mfi(close,indicator_length),sampling_period,range_mult)
accdist = switch
use_range == false => ta.accdist
=> filt(ta.accdist,sampling_period,range_mult)
mom = switch
use_range == false => ta.mom(close,indicator_length)
=> filt(ta.mom(close,indicator_length),sampling_period,range_mult)
obv = switch
use_range == false => ta.obv
=> filt(ta.obv,sampling_period,range_mult)
cci = switch
use_range == false => ta.cci(close,indicator_length)
=> filt(ta.cci(close,indicator_length),sampling_period,range_mult)
stoch = switch
use_range == false => ta.stoch(close,high,low,indicator_length)
=> filt(ta.stoch(close,high,low,indicator_length),sampling_period,range_mult)
indicator = switch
sel == "RSI" => rsi
sel == "MFI" => mfi
sel == "Accum/Dist" => accdist
sel == "Momentum" => mom
sel == "OB Volume" => obv
sel == "CCI" => cci
sel == "Stochastic" => stoch
not_bound = indicator==accdist or indicator==obv
[supertrend,dir] = e.supertrend_anysource(indicator,atr_mult,atr_length)
supertrend_up = dir == -1 ? supertrend : na
supertrend_dn = dir == 1 ? supertrend : na
supertrend_up_start = dir == -1 and dir[1] == 1 ? supertrend : na
supertrend_dn_start = dir == 1 and dir[1] == -1 ? supertrend : na
linecolor = dir == -1 ? color.green : color.red
fillcolor = dir == -1 ? color.new(color.green,88) : color.new(color.red,88)
sup = plot(supertrend_up,title="Up Supertrend",color=linecolor,style=plot.style_linebr,linewidth=2)
sdn = plot(supertrend_dn,title="Down Supertrend",color=linecolor,style=plot.style_linebr,linewidth=2)
mid=plot(indicator,color=color.white)
plotshape(supertrend_up_start,title="Supertrend Up Start",style=shape.circle,location=location.absolute,
color=color.green, size=size.tiny)
plotshape(supertrend_dn_start,title="Supertrend Down Start",style=shape.circle,location=location.absolute,
color=color.red, size=size.tiny)
plotshape(labels==false?na:supertrend_up_start,title="Supertrend Buy Label",style=shape.labelup,location=location.absolute,
color=color.green,textcolor=color.white,text = "Buy")
plotshape(labels==false?na:supertrend_dn_start,title="Supertrend Sell Label",style=shape.labeldown,location=location.absolute,
color=color.red,textcolor=color.white,text = "Sell")
fill(sup,mid,highlighting==true ? fillcolor : na)
fill(sdn,mid,highlighting==true ? fillcolor : na)
hiPlot=plot(not_bound ? na : oversold,title="Oversold Level",color=color.new(color.white,75),style=plot.style_circles)
loPlot=plot(not_bound ? na : overbought,title="Overbought Level",color=color.new(color.white,75),style=plot.style_circles)
fill(hiPlot,loPlot,color=highlighting==true ? color.new(color.purple,95):na)
alertcondition(supertrend_up_start,"Supertrend Any Indicator Buy")
alertcondition(supertrend_dn_start,"Supertrend Any Indicator Sell") |
Price Data Label | https://www.tradingview.com/script/dd2ZEP5s-Price-Data-Label/ | Amphibiantrading | https://www.tradingview.com/u/Amphibiantrading/ | 208 | 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("Price Data Label", overlay=true, max_labels_count = 500)
//constants
ISDAILY = timeframe.isdaily
ISWEEKLY = timeframe.isweekly
//inputs
var g1 = 'Daily Moving Averages'
ima1 = input.int(8, "Daily Moving Average 1", inline = "a1", group = g1)
ima2 = input.int(21, "Daily Moving Average 2",inline = "a2", group = g1)
ima3 = input.int(50, "Daily Moving Average 1",inline = "a3", group = g1)
ima4 = input.int(200, "Daily Moving Average 2",inline = "a4", group = g1)
maType1 = input.string("EMA", "", options = ["EMA", "SMA"],inline = "a1", group = g1)
maType2 = input.string("EMA", "", options = ["EMA", "SMA"],inline = "a2", group = g1)
maType3 = input.string("SMA", "", options = ["EMA", "SMA"],inline = "a3", group = g1)
maType4 = input.string("SMA", "", options = ["EMA", "SMA"],inline = "a4", group = g1)
var g2 = 'Weekly Moving Averages'
ima5 = input.int(10, 'Weekly Moving Average 1', inline = '2', group = g2)
ima6 = input.int(40, 'Weekly Moving Average 2', inline = '3', group = g2)
maType5 = input.string("SMA", "", options = ["EMA", "SMA"],inline = "2", group = g2)
maType6 = input.string("SMA", "", options = ["EMA", "SMA"],inline = "3", group = g2)
// create labels
var label dashboard = na
float volSec = na
projVol = float(volume)
//mas
ma1 = maType1 == "EMA" ? ta.ema(close, ima1) : maType1 == "SMA" ? ta.sma(close, ima1) : na
ma2 = maType2 == "EMA" ? ta.ema(close, ima2) : maType2 == "SMA" ? ta.sma(close, ima2) : na
ma3 = maType3 == "EMA" ? ta.ema(close, ima3) : maType3 == "SMA" ? ta.sma(close, ima3) : na
ma4 = maType4 == "EMA" ? ta.ema(close, ima4) : maType4 == "SMA" ? ta.sma(close, ima4) : na
ma5 = maType5 == "EMA" ? ta.ema(close, ima5) : maType3 == "SMA" ? ta.sma(close, ima5) : na
ma6 = maType6 == "EMA" ? ta.ema(close, ima6) : maType4 == "SMA" ? ta.sma(close, ima6) : na
nasVolAvg = request.security('TVOLQ', 'D', ta.sma(close,50))
spxVolAvg = request.security('TVOL', 'D', ta.sma(close,50))
nasVolAvgWk = request.security('TVOLQ', "W", ta.sma(close,10))
spxVolAvgWk = request.security('TVOL', 'W', ta.sma(close,10))
avgVol = syminfo.ticker == 'IXIC' ? nasVolAvg : syminfo.ticker == 'SPX' ? spxVolAvg : ta.sma(volume,50)
avgVolWk = syminfo.ticker == 'IXIC' ? nasVolAvgWk : syminfo.ticker == 'SPX' ? spxVolAvgWk : ta.sma(volume,10)
nasVol = request.security('TVOLQ', 'D', close)
spxVol = request.security('TVOL', 'D', close)
nasVolWk = request.security('TVOLQ', 'W', close)
spxVolWk = request.security('TVOL', 'W', close)
//projected volume
timePassed = timenow - time
timeLeft = time_close - timenow
if timeLeft > 0 and (syminfo.ticker != 'IXIC' or syminfo.ticker != 'SPX')
volSec := (volume / timePassed)
projVol := (volume + (volSec * timeLeft))
projVolPer = (projVol / avgVol * 100) - 100
projVolPerWk = (projVol / avgVolWk * 100) - 100
//calculations
distMa1 = ((close / ma1) -1 ) *100
distMa2 = ((close / ma2) -1 ) *100
distMa3 = ((close / ma3) -1 ) *100
distMa4 = ((close / ma4) -1 ) *100
distMa5 = ((close / ma5) -1 ) *100
distMa6 = ((close / ma6) -1 ) *100
dollarChng = ta.change(close,1)
perChng = dollarChng / close[1] * 100
closeRange = (close - low) / (high - low) *100
runRate = syminfo.ticker == 'IXIC' ? 100 * (nasVol / nasVolAvg) - 100 : syminfo.ticker == 'SPX' ? 100 * (spxVol / spxVolAvg) - 100 : projVolPer
runRateWk = syminfo.ticker == 'IXIC' ? 100 * (nasVolWk / nasVolAvgWk) - 100 : syminfo.ticker == 'SPX' ? 100 * (spxVolWk / spxVolAvgWk) - 100 : projVolPerWk
//titles
dateTitle = "Date: "
highTitle = "High: "
lowTitle = "Low: "
closeTitle = "Close: "
perChangeTitle = "% Chg: "
clsrngTitle = "DCR: "
clsrngTitleWk = 'WCR: '
volTitle = "Volume: "
volPercTitle = 'Vol %: '
maTitle1 = maType1 + str.tostring(ima1) + ": "
maTitle2 = maType2 + str.tostring(ima2) + ": "
maTitle3 = maType3 + str.tostring(ima3) + ": "
maTitle4 = maType4 + str.tostring(ima4) + ": "
maTitle5 = maType5 + str.tostring(ima5) + ": "
maTitle6 = maType6 + str.tostring(ima6) + ": "
nl = '\n'
// plot the labels
if ISDAILY and (barstate.isconfirmed or barstate.islast)
label(dashboard)
dashboard := label.new(bar_index, high ,color = color.new(color.white,100), tooltip = dateTitle + str.format_time(time, 'MM-dd-yy', 'UTC-7') + nl +
highTitle + str.tostring(high, "##.##") + nl +
lowTitle + str.tostring(low, "##.##") + nl +
closeTitle + str.tostring(close, "##.##") + ' (' + str.tostring(dollarChng, format.mintick) + ')' + nl +
perChangeTitle + str.tostring(perChng, "##.##") + nl +
clsrngTitle + str.tostring(closeRange, "#") + "%" + nl +
volTitle + (syminfo.ticker == 'IXIC' ? str.tostring(nasVol, "#,###,###,###") :
syminfo.ticker == 'SPX' ? str.tostring(spxVol, "#,###,###,###") : str.tostring(volume, "#,###,###,###")) + nl +
volPercTitle + str.tostring(runRate, "#") + '%' + nl +
maTitle1 + str.tostring(ma1, format.mintick) + ' (' + str.tostring(distMa1, "#.#") + "%" + ')' + nl +
maTitle2 + str.tostring(ma2, format.mintick) + ' (' + str.tostring(distMa2, "#.#") + "%" + ')' + nl +
maTitle3 + str.tostring(ma3, format.mintick) + ' (' + str.tostring(distMa3, "#.#") + "%" + ')' + nl +
maTitle4 + str.tostring(ma4, format.mintick) + ' (' + str.tostring(distMa4, "#.#") + "%" + ')'
)
if ISWEEKLY and (barstate.isconfirmed or barstate.islast)
label(dashboard)
dashboard := label.new(bar_index, high ,color = color.new(color.white,100), tooltip = dateTitle + str.format_time(time, 'MM-dd-yy', 'UTC-7') + nl +
highTitle + str.tostring(high, "##.##") + nl +
lowTitle + str.tostring(low, "##.##") + nl +
closeTitle + str.tostring(close, "##.##") + ' (' + str.tostring(dollarChng, format.mintick) + ')' + nl +
perChangeTitle + str.tostring(perChng, "##.##") + nl +
clsrngTitleWk + str.tostring(closeRange, "#") + "%" + nl +
volTitle + (syminfo.ticker == 'IXIC' ? str.tostring(nasVolWk, "#,###,###,###") :
syminfo.ticker == 'SPX' ? str.tostring(spxVolWk, "#,###,###,###") : str.tostring(volume, "#,###,###,###")) + nl +
volPercTitle + str.tostring(runRateWk, "#") + '%' + nl +
maTitle5 + str.tostring(ma5, format.mintick) + ' (' + str.tostring(distMa5, "#.#") + "%" + ')' + nl +
maTitle6 + str.tostring(ma6, format.mintick) + ' (' + str.tostring(distMa6, "#.#") + "%" + ')'
)
|
VOLD Indicator | https://www.tradingview.com/script/MJECvbeV-VOLD-Indicator/ | viewer405 | https://www.tradingview.com/u/viewer405/ | 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/
// © viewer405
//@version=5
indicator(title="VOLD Indicator", shorttitle="VOLD")
bullColor = #26a69a
bearColor = #ef5350
timeInterval = input.timeframe("", title="Time Interval")
style = input.string("line", title="Candle Style", options=["bars", "line", "candles", "ratio"], tooltip="NOTE: If selecting 'ratio', the Threshold Lines and Moving Averages will cause the histogram to appear very small. Consider disabling both options if selecting 'ratio'.")
default = input.string("USI:VOLD", title="Default Ticker", options=["USI:VOLD", "USI:VOLDQ", "USI:VOLDA"])
enableThresholds = input.bool(false, "Enable Threshold Lines")
enableMA = input.bool(false, "Enable Moving Averages")
ma1Length = input.int(10, "1st MA Length")
ma2Length = input.int(20, "2nd MA Length")
ma1Source = input.string("close", "1st MA Source", options=["open", "high", "low", "close", "hl2", "hlc3", "ohlc4"])
ma2Source = input.string("close", "2nd MA Source", options=["open", "high", "low", "close", "hl2", "hlc3", "ohlc4"])
ma1Type = input.string("ema", "1st MA Type", options=["ema", "sma"])
ma2Type = input.string("ema", "2nd MA Type", options=["ema", "sma"])
prefix = switch syminfo.prefix
"NYSE" => "USI:VOLD"
"NASDAQ" => "USI:VOLDQ"
"USI" => syminfo.ticker
=> ""
type = switch syminfo.type
"crypto" => "USI:VOLDQ" // Crypto is behaving like tech sector, use NASDAQ.
"economic" => ""
"fund" => ""
"cfd" => "" // (contract for difference)
"dr" => "" // (depository receipt)
"stock" => "USI:VOLDA"
"index" => ""
=> ""
index = switch syminfo.ticker
"ES" => "USI:VOLD"
"SPY" => "USI:VOLD"
"SPX" => "USI:VOLD"
"NQ" => "USI:VOLDQ"
"QQQ" => "USI:VOLDQ"
"TQQQ" => "USI:VOLDQ"
"NASDAQ" => "USI:VOLDQ"
"YM" => "USI:VOLD"
"DJI" => "USI:VOLD"
=> ""
ticker = prefix != "" ? prefix : (type != "" ? type : (index != "" ? index : default))
// As of 2022, TradingView has not yet resolved data issues when querying daily
// candlestick data for USI:VOLD. Use 390 minutes instead of the daily. It
// equates to 6 1/2 hours that the markets are open Monday to Friday.
if timeframe.isdaily and (style == "candles" or style == "ratio")
timeInterval := '390'
uO = request.security(str.replace(ticker, "USI:VOLD", "USI:UVOL"), timeInterval, open)
uH = request.security(str.replace(ticker, "USI:VOLD", "USI:UVOL"), timeInterval, high)
uL = request.security(str.replace(ticker, "USI:VOLD", "USI:UVOL"), timeInterval, low)
uC = request.security(str.replace(ticker, "USI:VOLD", "USI:UVOL"), timeInterval, close)
dO = request.security(str.replace(ticker, "USI:VOLD", "USI:DVOL"), timeInterval, open)
dH = request.security(str.replace(ticker, "USI:VOLD", "USI:DVOL"), timeInterval, high)
dL = request.security(str.replace(ticker, "USI:VOLD", "USI:DVOL"), timeInterval, low)
dC = request.security(str.replace(ticker, "USI:VOLD", "USI:DVOL"), timeInterval, close)
ratio = uC > dC ? math.round(uC / dC, 2) : -math.round(dC / uC, 2)
o = request.security(ticker, timeInterval, open)
h = request.security(ticker, timeInterval, high)
l = request.security(ticker, timeInterval, low)
c = request.security(ticker, timeInterval, close)
getMASourcePrice(source, o, h, l, c) =>
price = switch source
"open" => o
"high" => h
"low" => l
"close" => c
"hl2" => (h + l) / 2
"hlc3" => (h + l + c) / 3
"ohlc4" => (o + h + l + c) / 4
=> c
price
ma1Price = getMASourcePrice(ma1Source, o, h, l, c)
ma2Price = getMASourcePrice(ma2Source, o, h, l, c)
ma1 = ma1Type == "ema" ? ta.ema(ma1Price, ma1Length) : ta.sma(ma1Price, ma1Length)
ma2 = ma2Type == "ema" ? ta.ema(ma2Price, ma2Length) : ta.sma(ma2Price, ma2Length)
plot(ma1, "1st MA", display = enableMA ? display.all : display.none, color=color.fuchsia)
plot(ma2, "2nd MA", display = enableMA ? display.all : display.none, color=color.aqua)
if barstate.islast
table legend = table.new(position.top_right, 2, 4, bgcolor = color.gray, frame_width = 2)
table.cell(legend, 0, 0, ticker + " " + str.tostring(c))
table.cell(legend, 0, 1, "Ratio: " + str.tostring(ratio) + ":1")
isBar = style == "bars" ? true : false
isLine = style == "line" ? true : false
isRatio = style == "ratio" ? true : false
isCandle = style == "candles" ? true : false
plot(c, display=isLine ? display.all : display.none)
plot(ratio, style = plot.style_columns, display = isRatio ? display.all : display.none)
plotbar(open=o, high=h, low=l, close=c, color=c < o ? bearColor : bullColor, display=isBar ? display.all : display.none)
plotcandle(open=o, high=h, low=l, close=c, color=c < o ? bearColor : bullColor, bordercolor=na, display=isCandle ? display.all : display.none)
hline(0, "Middle Band", color=color.new(#787B86, 50), display = enableThresholds ? display.all : display.none)
hline(100000000, "Upper Band +100M", color=color.new(bullColor, 75), display = enableThresholds ? display.all : display.none)
hline(-100000000, "Lower Band -100M", color=color.new(bearColor, 75), display = enableThresholds ? display.all : display.none)
hline(300000000, "Upper Band +300M", color=color.new(bullColor, 50), display = enableThresholds ? display.all : display.none)
hline(-300000000, "Lower Band -300M", color=color.new(bearColor, 50), display = enableThresholds ? display.all : display.none)
hline(500000000, "Upper Band +500M", color=color.new(bullColor, 25), display = display.none)
hline(-500000000, "Lower Band -500M", color=color.new(bearColor, 25), display = display.none)
hline(1000000000, "Upper Band +1000M", color=color.new(bullColor, 0), display = display.none)
hline(-1000000000, "Lower Band -1000M", color=color.new(bearColor, 0), display = display.none) |
Previous Levels With Custom TimeZone | https://www.tradingview.com/script/1JZPGtam/ | LudoGH68 | https://www.tradingview.com/u/LudoGH68/ | 278 | 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/
// © LudoGH68
//@version=5
indicator("Previous Levels", overlay = true)
import LudoGH68/SessionAndTimeFct_public/1 as sat
import LudoGH68/Drawings_public/1 as d
getLineStyle(lineOption) =>
lineOption == "┈" ? line.style_dotted : lineOption == "╌" ? line.style_dashed : line.style_solid
// Select Timezone to get data
timeZone = input.string("GMT-5", title="Time Zone", options=["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"], group="Time Zone")
// Daily Open
isDailyOpenToShow = input(true, title='Display line', group="Daily Open")
isDailyOpenLabelToShow = input(true, title='Display label', group="Daily Open")
dailyOpenColor = input(color.lime, 'Color', group="Daily Open")
dailyOpenLineStyleOption = input.string("─", title="Style", group="Daily Open", options=["─", "┈", "╌"])
dailyOpenLineStyle = getLineStyle(dailyOpenLineStyleOption)
dailyOpenLineWidth = input.int(1, title="Width", group="Daily Open", minval=1, maxval=5)
// Daily High & Low
isDhlToShow = input(true, title='Display line', group="Daily High & Low")
isDhlLabelToShow = input(true, title='Display label', group="Daily High & Low")
dhlColor = input(color.lime, 'Color', group="Daily High & Low")
dhlLineStyleOption = input.string("─", title="Style", group="Daily High & Low", options=["─", "┈", "╌"])
dhlLineStyle = getLineStyle(dhlLineStyleOption)
dhlLineWidth = input.int(1, title="Width", group="Daily High & Low", minval=1, maxval=5)
// Previous Daily High & Low
isPdhlToShow = input(true, title='Display lines', group="Previous Daily High & Low")
isPdhlLabelToShow = input(true, title='Display labels', group="Previous Daily High & Low")
pdhlColor = input(color.orange, 'Color', group="Previous Daily High & Low")
pdhlLineStyleOption = input.string("╌", title="Style", group="Previous Daily High & Low", options=["─", "┈", "╌"])
pdhlLineStyle = getLineStyle(pdhlLineStyleOption)
pdhlLineWidth = input.int(1, title="Width", group="Previous Daily High & Low", minval=1, maxval=5)
// Previous Weekly High & Low
isPwhlToShow = input(true, title='Display lines', group="Previous Weekly High & Low")
isPwhlLabelToShow = input(true, title='Display labels', group="Previous Weekly High & Low")
pwhlColor = input(color.red, 'Color', group="Previous Weekly High & Low")
pwhlLineStyleOption = input.string("╌", title="Style", group="Previous Weekly High & Low", options=["─", "┈", "╌"])
pwhlLineStyle = getLineStyle(pwhlLineStyleOption)
pwhlLineWidth = input.int(1, title="Width", group="Previous Weekly High & Low", minval=1, maxval=5)
// Previous Monthly High & Low
isPmhlToShow = input(true, title='Display lines', group="Previous Monthly High & Low")
isPmhlLabelToShow = input(true, title='Display labels', group="Previous Monthly High & Low")
pmhlColor = input(color.green, 'Color', group="Previous Monthly High & Low")
pmhlLineStyleOption = input.string("╌", title="Style", group="Previous Monthly High & Low", options=["─", "┈", "╌"])
pmhlLineStyle = getLineStyle(pmhlLineStyleOption)
pmhlLineWidth = input.int(1, title="Width", group="Previous Monthly High & Low", minval=1, maxval=5)
// Price variable
var float pmh = 0.0
var float pml = 0.0
var float pwh = 0.0
var float pwl = 0.0
var float pdh = 0.0
var float pdl = 0.0
var float monthlyHigh = 0.0
var float monthlyLow = 0.0
var float weeklyHigh = 0.0
var float weeklyLow = 0.0
var float dailyHigh = 0.0
var float dailyLow = 0.0
var float dailyOpen = 0.0
// Index variable
var int pmhIndex = 0
var int pmlIndex = 0
var int pwhIndex = 0
var int pwlIndex = 0
var int pdhIndex = 0
var int pdlIndex = 0
var int monthlyHighIndex = 0
var int monthlyLowIndex = 0
var int weeklyHighIndex = 0
var int weeklyLowIndex = 0
var int dailyHighIndex = 0
var int dailyLowIndex = 0
var int dailyOpenIndex = 0
// Line variable
var line pmhLine = na
var line pmlLine = na
var line pwhLine = na
var line pwlLine = na
var line pdhLine = na
var line pdlLine = na
var line dailyHighLine = na
var line dailyLowLine = na
var line dailyOpenLine = na
// Label variable
var label pmhLabel = na
var label pmlLabel = na
var label pwhLabel = na
var label pwlLabel = na
var label pdhLabel = na
var label pdlLabel = na
var label dailyHighLabel = na
var label dailyLowLabel = na
var label dailyOpenLabel = na
// MONTHLY PROCESS
if(sat.is_new_month(timeZone) and sat.is_element_to_show_with_tf_up('m', 3) and sat.is_element_to_show_with_tf_down('M', 1))
// Remove previous PMH/PMH lines
d.delete_line(pmlLine, pmlLabel)
d.delete_line(pmhLine, pmhLabel)
// Update price and index data
pmh := monthlyHigh
pml := monthlyLow
pmhIndex := monthlyHighIndex
pmlIndex := monthlyLowIndex
monthlyHigh := high
monthlyLow := low
monthlyHighIndex := bar_index
monthlyLowIndex := bar_index
// Create new lines
pmhLine := isPmhlToShow ? line.new(pmhIndex, pmh, bar_index, pmh, xloc=xloc.bar_index, extend=extend.right, color=pmhlColor, style=pmhlLineStyle, width=pmhlLineWidth) : na
pmlLine := isPmhlToShow ? line.new(pmlIndex, pml, bar_index, pml, xloc=xloc.bar_index, extend=extend.right, color=pmhlColor, style=pmhlLineStyle, width=pmhlLineWidth) : na
pmhLabel := isPmhlToShow and isPmhlLabelToShow ? label.new(bar_index + 20, pmh, text="PMH", style=label.style_none, textcolor=pmhlColor) : na
pmlLabel := isPmhlToShow and isPmhlLabelToShow ? label.new(bar_index + 20, pml, text="PML", style=label.style_none, textcolor=pmhlColor) : na
else
// Update highest / lowest daily price if necessary
if(high > monthlyHigh)
monthlyHigh := high
monthlyHighIndex := bar_index
else if(low < monthlyLow)
monthlyLow := low
monthlyLowIndex := bar_index
// Update labels position
d.update_label_coordinates(pmhLabel, pmh)
d.update_label_coordinates(pmlLabel, pml)
// WEEKLY PROCESS
if(sat.is_new_week(timeZone) and sat.is_element_to_show_with_tf_up('m', 1) and sat.is_element_to_show_with_tf_down('W', 1))
// Remove previous PDH/PDH lines
d.delete_line(pwlLine, pwlLabel)
d.delete_line(pwhLine, pwhLabel)
// Update price and index data
pwh := weeklyHigh
pwl := weeklyLow
pwhIndex := weeklyHighIndex
pwlIndex := weeklyLowIndex
weeklyHigh := high
weeklyLow := low
weeklyHighIndex := bar_index
weeklyLowIndex := bar_index
// Create new lines
pwhLine := isPwhlToShow ? line.new(pwhIndex, pwh, bar_index, pwh, xloc=xloc.bar_index, extend=extend.right, color=pwhlColor, style=pwhlLineStyle, width=pwhlLineWidth) : na
pwlLine := isPwhlToShow ? line.new(pwlIndex, pwl, bar_index, pwl, xloc=xloc.bar_index, extend=extend.right, color=pwhlColor, style=pwhlLineStyle, width=pwhlLineWidth) : na
// Create labels
pwhLabel := isPwhlToShow and isPwhlLabelToShow ? label.new(bar_index + 20, pwh, text="PWH", style=label.style_none, textcolor=pwhlColor) : na
pwlLabel := isPwhlToShow and isPwhlLabelToShow ? label.new(bar_index + 20, pwl, text="PWL", style=label.style_none, textcolor=pwhlColor) : na
else
// Update highest / lowest daily price if necessary
if(high > weeklyHigh)
weeklyHigh := high
weeklyHighIndex := bar_index
else if(low < weeklyLow)
weeklyLow := low
weeklyLowIndex := bar_index
d.update_label_coordinates(pwhLabel, pwh)
d.update_label_coordinates(pwlLabel, pwl)
// DAILY PROCESS
if(sat.is_new_day(timeZone) and sat.is_element_to_show_with_tf_down('D', 1))
// Remove previous PDH/PDH lines
d.delete_line(pdlLine, pdlLabel)
d.delete_line(pdhLine, pdhLabel)
d.delete_line(dailyOpenLine, dailyOpenLabel)
d.delete_line(dailyHighLine, dailyHighLabel)
d.delete_line(dailyLowLine, dailyLowLabel)
// Update price and index data
pdh := dailyHigh
pdl := dailyLow
pdhIndex := dailyHighIndex
pdlIndex := dailyLowIndex
dailyHigh := high
dailyLow := low
dailyOpen := open
dailyHighIndex := bar_index
dailyLowIndex := bar_index
dailyOpenIndex := bar_index
// Create lines
pdhLine := isPdhlToShow ? line.new(pdhIndex, pdh, bar_index, pdh, xloc=xloc.bar_index, extend=extend.right, color=pdhlColor, style=pdhlLineStyle, width=pdhlLineWidth) : na
pdlLine := isPdhlToShow ? line.new(pdlIndex, pdl, bar_index, pdl, xloc=xloc.bar_index, extend=extend.right, color=pdhlColor, style=pdhlLineStyle, width=pdhlLineWidth) : na
dailyOpenLine := isDailyOpenToShow ? line.new(dailyOpenIndex, dailyOpen, bar_index + 1, dailyOpen, xloc=xloc.bar_index, extend=extend.right, color=dailyOpenColor, style=dailyOpenLineStyle, width=dailyOpenLineWidth) : na
dailyHighLine := isDhlToShow ? line.new(dailyHighIndex, dailyHigh, bar_index + 1, dailyHigh, xloc=xloc.bar_index, extend=extend.right, color=dhlColor, style=dhlLineStyle, width=dhlLineWidth) : na
dailyLowLine := isDhlToShow ? line.new(dailyLowIndex, dailyLow, bar_index + 1, dailyLow, xloc=xloc.bar_index, extend=extend.right, color=dhlColor, style=dhlLineStyle, width=dhlLineWidth) : na
// Create labels
pdhLabel := isPdhlToShow and isPdhlLabelToShow ? label.new(bar_index + 20, pdh, text="PDH", style=label.style_none, textcolor=pdhlColor) : na
pdlLabel := isPdhlToShow and isPdhlLabelToShow ? label.new(bar_index + 20, pdl, text="PDL", style=label.style_none, textcolor=pdhlColor) : na
dailyOpenLabel := isDailyOpenToShow and isDailyOpenLabelToShow ? label.new(bar_index + 20, dailyOpen, text="Daily open", style=label.style_none, textcolor=dailyOpenColor) : na
dailyHighLabel := isDhlToShow and isDhlLabelToShow ? label.new(bar_index + 20, dailyHigh, text="Daily high", style=label.style_none, textcolor=dhlColor) : na
dailyLowLabel := isDhlToShow and isDhlLabelToShow ? label.new(bar_index + 20, dailyLow, text="Daily low", style=label.style_none, textcolor=dhlColor) : na
else
// Update highest / lowest daily price if necessary
if(high > dailyHigh)
dailyHigh := high
dailyHighIndex := bar_index
else if(low < dailyLow)
dailyLow := low
dailyLowIndex := bar_index
// Update lines coordinates
d.update_line_coordinates(dailyHighLine, dailyHighLabel, dailyHighIndex, dailyHigh, bar_index + 1, dailyHigh)
d.update_line_coordinates(dailyLowLine, dailyLowLabel, dailyLowIndex, dailyLow, bar_index + 1, dailyLow)
// Update labels position
d.update_label_coordinates(pdhLabel, pdh)
d.update_label_coordinates(pdlLabel, pdl)
d.update_label_coordinates(dailyOpenLabel, dailyOpen)
plot(na)
|
XLY/XLP Ratio | https://www.tradingview.com/script/ulCnavTl/ | MasterOfDesaster | https://www.tradingview.com/u/MasterOfDesaster/ | 15 | 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/
// © MasterOfDesaster
//@version=4
study(title="XLY/XLP Ratio", overlay=false)
// Definieren Sie XLY und XLP Symbole
xly = "XLY"
xlp = "XLP"
// Abrufen der Kursdaten von TradingView
xly_price = security(xly, timeframe.period, close)
xlp_price = security(xlp, timeframe.period, close)
// Berechnen Sie das XLY/XLP-Verhältnis
ratio = xly_price / xlp_price
// Zeichnen Sie das Verhältnis-Chart
plot(ratio, title="XLY/XLP Ratio", color=color.green, linewidth=2)
|
Federal Funds Rate Projections [tedtalksmacro] | https://www.tradingview.com/script/cIna7eYl-Federal-Funds-Rate-Projections-tedtalksmacro/ | tedtalksmacro | https://www.tradingview.com/u/tedtalksmacro/ | 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/
// © tedtalksmacro
//@version=5
indicator("Federal Funds Rate Projections [tedtalksmacro]", overlay = false, format = format.percent)
// Calculate
currentfedfunds = (request.security("ZQ1!", "1", close) - 100) * -1
octoberfedfunds = (request.security("ZQV2023", "1", close) - 100) * -1
novemberfedfunds = (request.security("ZQX2023", "1", close) - 100) * -1
decemberfedfunds = (request.security("ZQZ2023", "1", close) - 100) * -1
jan24fedfunds = (request.security("ZQF2024", "1", close) - 100) * -1
feb24fedfunds = (request.security("ZQG2024", "1", close) - 100) * -1
march24fedfunds = (request.security("ZQH2024", "1", close) - 100) * -1
// plot projections
plot(currentfedfunds, style = plot.style_line, linewidth=2, color= color.new(color.black, 0), title = 'Current')
plot(octoberfedfunds, style = plot.style_line, linewidth=2, color= color.new(color.gray, 0), title = 'OCT 2023')
plot(novemberfedfunds, style = plot.style_line, linewidth=2, color= color.new(color.fuchsia, 0), title = 'NOV 2023')
plot(decemberfedfunds, style = plot.style_line, linewidth=2, color= color.new(color.lime, 0), title = 'DEC 2023')
plot(jan24fedfunds, style = plot.style_line, linewidth=2, color= color.new(color.teal, 0), title = 'JAN 2024')
plot(feb24fedfunds, style = plot.style_line, linewidth=2, color= color.new(color.olive, 0), title = 'FEB 2024')
plot(march24fedfunds, style = plot.style_line, linewidth=2, color= color.new(color.silver, 0), title = 'MAR 2024') |
Highest/Lowest value since X time ago, various indicators | https://www.tradingview.com/script/adA4h4Pm-Highest-Lowest-value-since-X-time-ago-various-indicators/ | Dean_Crypto | https://www.tradingview.com/u/Dean_Crypto/ | 51 | 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/
// © Dean_Crypto
//@version=5
// User input
indicator(title="v2 Highest/Lowest value since X time ago", shorttitle = "H/L-V X-Ago", overlay=false, max_labels_count = 500)
grp1 = "Sources | Length, (length only applies to (MA)"
grp2 = "Display Filter"
il1 = " 1"
il2 = " 2"
il3 = " 3"
il4 = " 4"
il5 = " 5"
il6 = " 6"
il7 = " 7"
il8 = " 8"
il9 = " 9"
il10 = "10"
maxbb = input.int( title = "count bars back limit", defval = 5000, minval = 1, maxval = 100000, tooltip = "also affects how long ago since 'x' occurrence happened. 24 bars on 1hr chart at most can show max 1D ago")
indicatorNameDistance = input.int(defval = 2, minval = 1, title = "indicator name distance")
labelFilterCount = input.int(defval = 1, minval = 0, title = "label higher than:", tooltip = "only show labels higher than x bars ago", group = grp2, inline = il1)
labelFilterTFOpt = input.string(defval = "hr", title = "", options = ["sec","min","hr","day","week","month","year"], group = grp2, inline = il1)
// displays the amount of sources you'd like to use. Note adjusting this will also align the hlines correctly
sourceChoices = input.int(defval = 5, minval = 1, maxval = 10, title = "dispaly sources", tooltip = "Adjusting this also corrects the hline display issue. Resize the indicator so the sources are aligned with the table")
hlSourceOpt1 = input.string(defval = "high", title = "source 1", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], group = grp1, inline = il1)
hlSourceOpt2 = input.string(defval = "low", title = "source 2", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], group = grp1, inline = il2)
hlSourceOpt3 = input.string(defval = "close", title = "source 3", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], group = grp1, inline = il3)
hlSourceOpt4 = input.string(defval = "volume", title = "source 4", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], group = grp1, inline = il4)
hlSourceOpt5 = input.string(defval = "volume (MA)", title = "source 5", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], group = grp1, inline = il5)
hlSourceOpt6 = input.string(defval = "range (MA)", title = "source 6", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], group = grp1, inline = il6)
hlSourceOpt7 = input.string(defval = "eom", title = "source 7", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], group = grp1, inline = il7)
hlSourceOpt8 = input.string(defval = "mfi (MA)", title = "source 8", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], group = grp1, inline = il8)
hlSourceOpt9 = input.string(defval = "obv", title = "source 9", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], group = grp1, inline = il9)
hlSourceOpt10 = input.string(defval = "rsi (MA)", title = "source 10", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], group = grp1, inline = il10)
// color red for the lowest value since x time ago
// color green for the highest value since x time ago
colorLowOpt = input.color(defval = color.rgb(255, 150, 150), title = "lowest since x time ago color")
colorHighOpt =input.color(defval = color.rgb(150, 255, 150), title = "highest since x time ago color")
// len only applies if a source with (MA) has been selected
sDataLen1 = input.int(defval = 20 , minval = 1, title = "", group = grp1, inline = il1)
sDataLen2 = input.int(defval = 20 , minval = 1, title = "", group = grp1, inline = il2)
sDataLen3 = input.int(defval = 10 , minval = 1, title = "", group = grp1, inline = il3)
sDataLen4 = input.int(defval = 20 , minval = 1, title = "", group = grp1, inline = il4)
sDataLen5 = input.int(defval = 20 , minval = 1, title = "", group = grp1, inline = il5)
sDataLen6 = input.int(defval = 20 , minval = 1, title = "", group = grp1, inline = il6)
sDataLen7 = input.int(defval = 20 , minval = 1, title = "", group = grp1, inline = il7)
sDataLen8 = input.int(defval = 20 , minval = 1, title = "", group = grp1, inline = il8)
sDataLen9 = input.int(defval = 20 , minval = 1, title = "", group = grp1, inline = il9)
sDataLen10 = input.int(defval = 20, minval = 1, title = "", group = grp1, inline = il10)
textSizeOption = input.string(title = "text size", defval = "large", options = ["auto", "huge", "large", "normal", "small", "tiny"])
aget(id, i) => array.get(id, i)
aget0(id) => array.get(id, 0)
aset(id, i, v) => array.set(id, i, v)
asize(id) => array.size(id)
apush(id, v) => array.push(id, v)
apop(id) => array.pop(id)
ashift(id) => array.shift(id)
unshift(id, v) => array.unshift(id, v)
bi = bar_index
lbi = last_bar_index
// without this line nothing works. Only begin loading data once the bar index reaches the amount of bars you're
plottable = bi + 1 > lbi - maxbb
//if data exists in array
canGet(id1, id2) => asize(id1) > 0 and asize(id2) > 0
addArrowsOpt = input.bool(defval = true, title = "add highest/lowest arrows")
onOffAlt(onOffOpt, value, valueAlt) => onOffOpt ? value : valueAlt
// retrieve the highest or lowest of the indicator's current value with the most time ago
labelHLCondition(sourceL, sourceH) =>
if canGet(sourceL, sourceH)
aget0(sourceL) > aget0(sourceH) ? aget0(sourceL) : aget0(sourceH)
// color red for the lowest value since, color green for the highest value since
labelColorCondition(sourceL, sourceH) =>
if canGet(sourceL, sourceH)
aget0(sourceL) > aget0(sourceH) ? color.rgb(255, 150, 150) : color.rgb(150, 255, 150)
// function for text sizes
size(sizeName) =>
switch sizeName
"auto" => size.auto
"huge" => size.huge
"large" => size.large
"normal" => size.normal
"small" => size.small
"tiny" => size.tiny
// user defined type to store the time values as it is repeated in a few functions
type timeKey
int s
int m
int h
int d
int w
int M
int Y
timeKey timeTrack = timeKey.new(1, 60, 3600, 86400, 604800, 2628000, 31540000)
// used to set the time type when using the filter option
labelFilterTF = switch labelFilterTFOpt
"sec" => timeTrack.s
"min" => timeTrack.m
"hr" => timeTrack.h
"day" => timeTrack.d
"week" => timeTrack.w
"month" => timeTrack.M
"year" => timeTrack.Y
//returns a string of the time taken since the last time the occurence happened
barTF(barsBack) =>
string forammtted = na
// convertToSec
min = timeTrack.m
hr = timeTrack.h
d = timeTrack.d
w = timeTrack.w
m = timeTrack.M
y = timeTrack.Y
totalSeconds = timeframe.in_seconds() * barsBack
string timeAgoText = na
if totalSeconds > 0 and totalSeconds < min
timeAgoText := str.format("{0, number, #s}", totalSeconds)
else if totalSeconds >= min and totalSeconds < hr
totalSeconds := math.round(totalSeconds, 1) / min
timeAgoText := str.format("{0, number, #.#m}", totalSeconds)
else if totalSeconds >= hr and totalSeconds < d
totalSeconds := math.round(totalSeconds, 1) / hr
timeAgoText := str.format("{0, number, #.#h}", totalSeconds)
else if totalSeconds >= d and totalSeconds < w
totalSeconds := math.round(totalSeconds, 1) / d
timeAgoText := str.format("{0, number, #.#d}", totalSeconds)
else if totalSeconds >= w and totalSeconds < m
totalSeconds := math.round(totalSeconds, 1) / w
timeAgoText := str.format("{0, number, #.#w}", totalSeconds)
else if totalSeconds >= m and totalSeconds < y
totalSeconds := math.round(totalSeconds, 1) / m
timeAgoText := str.format("{0, number, #.#M}", totalSeconds)
else if totalSeconds >= y
totalSeconds := math.round(totalSeconds, 1) / y
timeAgoText := str.format("{0, number, #.#Y}", totalSeconds)
timeAgoText
// display filter that will return true if the amount of bars is higher than the user input of time
displayFilter(barsBack) => (timeframe.in_seconds() * barsBack) > (labelFilterCount * labelFilterTF)
labelTextSize = size(textSizeOption)
// begin adding bars once the bar index reaches the first bar of maxbb (max bars back)
addData(id, source) =>
if plottable
if asize(id) > maxbb
ashift(id)
unshift(id, source)
// takes in an array and stores the count number of bars back until it reaches a higher value from the current value of the indicator
addHighCount(data, highs) =>
if plottable
sSize = asize(data)
cbar = aget(data, 0)
count = 1
hCount = 0
if sSize > 1
while cbar > aget(data, count) and count < sSize - 1
count := count + 1
hCount := hCount + 1
if count > sSize or cbar < aget(data, count)
break
if asize(highs) > maxbb
ashift(highs)
unshift(highs, hCount)
// takes in an array and stores the count number of bars back until it reaches a lower value from the current value of the indicator
addLowCount(data, lows) =>
if plottable
sSize = asize(data)
cbar = aget(data, 0)
count = 1
lCount = 0
if sSize > 1
while cbar < aget(data, count) and count < sSize - 1
count := count + 1
lCount := lCount + 1
if count > sSize or cbar > aget(data, count)
break
if asize(lows) > maxbb
ashift(lows)
unshift(lows, lCount)
tablePosition(OptionsName) =>
switch OptionsName
"middle right" => position.middle_right
"top left" => position.top_left
"top center" => position.top_center
"top right" => position.top_right
"middle left" => position.middle_left
"middle center" => position.middle_center
"middle right" => position.middle_right
"bottom left" => position.bottom_left
"bottom center" => position.bottom_center
"bottom right" => position.bottom_right
closePercentChange() => (nz(close[1], low) < close ? 1 : -1) * (high - low) / low * 100
closePercent = closePercentChange()
var float [] sourceData1 = array.new_float()
var float [] sourceData2 = array.new_float()
var float [] sourceData3 = array.new_float()
var float [] sourceData4 = array.new_float()
var float [] sourceData5 = array.new_float()
var float [] sourceData6 = array.new_float()
var float [] sourceData7 = array.new_float()
var float [] sourceData8 = array.new_float()
var float [] sourceData9 = array.new_float()
var float [] sourceData10 = array.new_float()
var float [] sourceLow1 = array.new_float()
var float [] sourceHigh1 = array.new_float()
var float [] sourceLow2 = array.new_float()
var float [] sourceHigh2 = array.new_float()
var float [] sourceLow3 = array.new_float()
var float [] sourceHigh3 = array.new_float()
var float [] sourceLow4 = array.new_float()
var float [] sourceHigh4 = array.new_float()
var float [] sourceLow5 = array.new_float()
var float [] sourceHigh5 = array.new_float()
var float [] sourceLow6 = array.new_float()
var float [] sourceHigh6 = array.new_float()
var float [] sourceLow7 = array.new_float()
var float [] sourceHigh7 = array.new_float()
var float [] sourceLow8 = array.new_float()
var float [] sourceHigh8 = array.new_float()
var float [] sourceLow9 = array.new_float()
var float [] sourceHigh9 = array.new_float()
var float [] sourceLow10 = array.new_float()
var float [] sourceHigh10 = array.new_float()
label [] sourceLBL1 = array.new_label()
label [] sourceLBL2 = array.new_label()
label [] sourceLBL3 = array.new_label()
label [] sourceLBL4 = array.new_label()
label [] sourceLBL5 = array.new_label()
label [] sourceLBL6 = array.new_label()
label [] sourceLBL7 = array.new_label()
label [] sourceLBL8 = array.new_label()
label [] sourceLBL9 = array.new_label()
label [] sourceLBL10 = array.new_label()
// switch function for source choices
sources(optionName, len) =>
switch optionName
"atr (MA)" => ta.atr(len)
"cci (MA)" => ta.cci(close, len)
"close percent" => closePercent
"close" => close
"cog (MA)" => ta.cog(close, len)
"dollar value" => volume * hlc3
"eom" => volume / closePercent
"gaps" => open - close[1]
"high" => high
"low" => low
"mfi (MA)" => ta.mfi(hlc3, len)
"obv" => ta.obv
"open" => open
"range (MA)" => math.round(((ta.highest(high, len) - ta.lowest(low, len)) / ta.highest(high, len) * 100), 1)
"rsi (MA)" => ta.rsi(close, len)
"rvi (MA)" => ta.ema((close - open) / (high - low) * volume, len)
"timeClose (MA)" => ta.sma(time_close, 10)
"volume (MA)" => ta.ema(volume, len)
"volume" => volume
//assigning each source to a switch option
source1 = sources(hlSourceOpt1, sDataLen1)
source2 = sources(hlSourceOpt2, sDataLen2)
source3 = sources(hlSourceOpt3, sDataLen3)
source4 = sources(hlSourceOpt4, sDataLen4)
source5 = sources(hlSourceOpt5, sDataLen5)
source6 = sources(hlSourceOpt6, sDataLen6)
source7 = sources(hlSourceOpt7, sDataLen7)
source8 = sources(hlSourceOpt8, sDataLen8)
source9 = sources(hlSourceOpt9, sDataLen9)
source10 = sources(hlSourceOpt10, sDataLen10)
//store each bar in sourceData from the selected source
addData(sourceData1, source1)
addData(sourceData2, source2)
addData(sourceData3, source3)
addData(sourceData4, source4)
addData(sourceData5, source5)
addData(sourceData6, source6)
addData(sourceData7, source7)
addData(sourceData8, source8)
addData(sourceData9, source9)
addData(sourceData10, source10)
// add the lowest value since bar count and the same for highest value since bar count
addLowCount( sourceData1 , sourceLow1 )
addHighCount(sourceData1 , sourceHigh1 )
addLowCount( sourceData2 , sourceLow2 )
addHighCount(sourceData2 , sourceHigh2 )
addLowCount( sourceData3 , sourceLow3 )
addHighCount(sourceData3 , sourceHigh3 )
addLowCount( sourceData4 , sourceLow4 )
addHighCount(sourceData4 , sourceHigh4 )
addLowCount( sourceData5 , sourceLow5 )
addHighCount(sourceData5 , sourceHigh5 )
addLowCount( sourceData6 , sourceLow6 )
addHighCount(sourceData6 , sourceHigh6 )
addLowCount( sourceData7 , sourceLow7 )
addHighCount(sourceData7 , sourceHigh7 )
addLowCount( sourceData8 , sourceLow8 )
addHighCount(sourceData8 , sourceHigh8 )
addLowCount( sourceData9 , sourceLow9 )
addHighCount(sourceData9 , sourceHigh9 )
addLowCount( sourceData10 , sourceLow10 )
addHighCount(sourceData10 , sourceHigh10 )
line1 = 9.5
line2 = 8.5
line3 = 7.5
line4 = 6.5
line5 = 5.5
line6 = 4.5
line7 = 3.5
line8 = 2.5
line9 = 1.5
line10 = 0.5
lineWidth = 10
// fill array with names of the source choices
string [] sourceChoiceNames = array.from(hlSourceOpt1, hlSourceOpt2, hlSourceOpt3, hlSourceOpt4, hlSourceOpt5, hlSourceOpt6, hlSourceOpt7, hlSourceOpt8, hlSourceOpt9, hlSourceOpt10)
//outline color for labels
outlineColor = color.rgb(0, 0, 0)
sourceLCC1 = labelColorCondition(sourceLow1, sourceHigh1)
sourceLCC2 = labelColorCondition(sourceLow2, sourceHigh2)
sourceLCC3 = labelColorCondition(sourceLow3, sourceHigh3)
sourceLCC4 = labelColorCondition(sourceLow4, sourceHigh4)
sourceLCC5 = labelColorCondition(sourceLow5, sourceHigh5)
sourceLCC6 = labelColorCondition(sourceLow6, sourceHigh6)
sourceLCC7 = labelColorCondition(sourceLow7, sourceHigh7)
sourceLCC8 = labelColorCondition(sourceLow8, sourceHigh8)
sourceLCC9 = labelColorCondition(sourceLow9, sourceHigh9)
sourceLCC10 = labelColorCondition(sourceLow10, sourceHigh10)
sourceLC1 = labelHLCondition(sourceLow1, sourceHigh1)
sourceLC2 = labelHLCondition(sourceLow2, sourceHigh2)
sourceLC3 = labelHLCondition(sourceLow3, sourceHigh3)
sourceLC4 = labelHLCondition(sourceLow4, sourceHigh4)
sourceLC5 = labelHLCondition(sourceLow5, sourceHigh5)
sourceLC6 = labelHLCondition(sourceLow6, sourceHigh6)
sourceLC7 = labelHLCondition(sourceLow7, sourceHigh7)
sourceLC8 = labelHLCondition(sourceLow8, sourceHigh8)
sourceLC9 = labelHLCondition(sourceLow9, sourceHigh9)
sourceLC10 = labelHLCondition(sourceLow10, sourceHigh10)
tfToStr1 = barTF(sourceLC1)
tfToStr2 = barTF(sourceLC2)
tfToStr3 = barTF(sourceLC3)
tfToStr4 = barTF(sourceLC4)
tfToStr5 = barTF(sourceLC5)
tfToStr6 = barTF(sourceLC6)
tfToStr7 = barTF(sourceLC7)
tfToStr8 = barTF(sourceLC8)
tfToStr9 = barTF(sourceLC9)
tfToStr10 = barTF(sourceLC10)
// only plot hlines based on amount of source choices selected
hline(10, linestyle = hline.style_solid, color = color.rgb(120, 123, 134, 50))
hline(sourceChoices >= 1 ? 9 : na , linestyle = hline.style_solid, color = color.rgb(120, 123, 134, 50))
hline(sourceChoices >= 2 ? 8 : na , linestyle = hline.style_solid, color = color.rgb(120, 123, 134, 50))
hline(sourceChoices >= 3 ? 7 : na , linestyle = hline.style_solid, color = color.rgb(120, 123, 134, 50))
hline(sourceChoices >= 4 ? 6 : na , linestyle = hline.style_solid, color = color.rgb(120, 123, 134, 50))
hline(sourceChoices >= 5 ? 5 : na , linestyle = hline.style_solid, color = color.rgb(120, 123, 134, 50))
hline(sourceChoices >= 6 ? 4 : na , linestyle = hline.style_solid, color = color.rgb(120, 123, 134, 50))
hline(sourceChoices >= 7 ? 3 : na , linestyle = hline.style_solid, color = color.rgb(120, 123, 134, 50))
hline(sourceChoices >= 8 ? 2 : na , linestyle = hline.style_solid, color = color.rgb(120, 123, 134, 50))
hline(sourceChoices >= 9 ? 1 : na , linestyle = hline.style_solid, color = color.rgb(120, 123, 134, 50))
hline(sourceChoices >= 10 ? 0 : na , linestyle = hline.style_solid, color = color.rgb(120, 123, 134, 50))
color [] sourceColorAr = array.from(sourceLCC1 ,sourceLCC2 ,sourceLCC3 ,sourceLCC4 ,sourceLCC5 ,sourceLCC6 , sourceLCC7 , sourceLCC8 , sourceLCC9 , sourceLCC10)
label [] sourceCount = array.new_label(sourceChoices)
label [] sourceCountLabelNames = array.new_label(sourceChoices)
string [] countedTime = array.from(barTF(sourceLC1), barTF(sourceLC2), barTF(sourceLC3), barTF(sourceLC4), barTF(sourceLC5), barTF(sourceLC6), barTF(sourceLC7), barTF(sourceLC8), barTF(sourceLC9), barTF(sourceLC10))
float [] sourceLC = array.from(sourceLC1, sourceLC2, sourceLC3, sourceLC4, sourceLC5, sourceLC6, sourceLC7, sourceLC8, sourceLC9, sourceLC10 )
// if value above the display filter, then add label
for i = 0 to sourceChoices - 1
if displayFilter(aget(sourceLC, i))
array.push( sourceCount , label.new(x = bi, y = 10 - (i + 0.5), text = aget(countedTime, i) , color = outlineColor, textcolor = aget(sourceColorAr, i) , style = label.style_text_outline, size = labelTextSize))
var label [] nameLB1 = array.new_label()
var label [] nameLB2 = array.new_label()
var label [] nameLB3 = array.new_label()
var label [] nameLB4 = array.new_label()
var label [] nameLB5 = array.new_label()
var label [] nameLB6 = array.new_label()
var label [] nameLB7 = array.new_label()
var label [] nameLB8 = array.new_label()
var label [] nameLB9 = array.new_label()
var label [] nameLB10 = array.new_label()
if asize(nameLB1) > 0
label.delete(ashift(nameLB1))
if asize(nameLB2) > 0
label.delete(ashift(nameLB2))
if asize(nameLB3) > 0
label.delete(ashift(nameLB3))
if asize(nameLB4) > 0
label.delete(ashift(nameLB4))
if asize(nameLB5) > 0
label.delete(ashift(nameLB5))
if asize(nameLB6) > 0
label.delete(ashift(nameLB6))
if asize(nameLB7) > 0
label.delete(ashift(nameLB7))
if asize(nameLB8) > 0
label.delete(ashift(nameLB8))
if asize(nameLB9) > 0
label.delete(ashift(nameLB9))
if asize(nameLB10) > 0
label.delete(ashift(nameLB10))
if sourceChoices >= 1
array.unshift(nameLB1, label.new(bi + indicatorNameDistance, y = line1, text = hlSourceOpt1, color = outlineColor, textcolor = color.white, style = label.style_text_outline, textalign = text.align_left, size = labelTextSize))
if sourceChoices >= 2
array.unshift(nameLB2, label.new(bi + indicatorNameDistance, y = line2, text = hlSourceOpt2, color = outlineColor, textcolor = color.white, style = label.style_text_outline, size = labelTextSize))
if sourceChoices >= 3
array.unshift(nameLB3, label.new(bi + indicatorNameDistance, y = line3, text = hlSourceOpt3, color = outlineColor, textcolor = color.white, style = label.style_text_outline, size = labelTextSize))
if sourceChoices >= 4
array.unshift(nameLB4, label.new(bi + indicatorNameDistance, y = line4, text = hlSourceOpt4, color = outlineColor, textcolor = color.white, style = label.style_text_outline, size = labelTextSize))
if sourceChoices >= 5
array.unshift(nameLB5, label.new(bi + indicatorNameDistance, y = line5, text = hlSourceOpt5, color = outlineColor, textcolor = color.white, style = label.style_text_outline, size = labelTextSize))
if sourceChoices >= 6
array.unshift(nameLB6, label.new(bi + indicatorNameDistance, y = line6, text = hlSourceOpt6, color = outlineColor, textcolor = color.white, style = label.style_text_outline, size = labelTextSize))
if sourceChoices >= 7
array.unshift(nameLB7, label.new(bi + indicatorNameDistance, y = line7, text = hlSourceOpt7, color = outlineColor, textcolor = color.white, style = label.style_text_outline, size = labelTextSize))
if sourceChoices >= 8
array.unshift(nameLB8, label.new(bi + indicatorNameDistance, y = line8, text = hlSourceOpt8, color = outlineColor, textcolor = color.white, style = label.style_text_outline, size = labelTextSize))
if sourceChoices >= 9
array.unshift(nameLB9, label.new(bi + indicatorNameDistance, y = line9, text = hlSourceOpt9, color = outlineColor, textcolor = color.white, style = label.style_text_outline, size = labelTextSize))
if sourceChoices == 10
array.unshift(nameLB10, label.new(bi + indicatorNameDistance, y = line10, text = hlSourceOpt10 , color = outlineColor, textcolor = color.white, style = label.style_text_outline, size = labelTextSize)) |
Simple Dominance Momentum Indicator | https://www.tradingview.com/script/RN1Tc7we-Simple-Dominance-Momentum-Indicator/ | CryptoMobster | https://www.tradingview.com/u/CryptoMobster/ | 241 | 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/
// © jrgoodland
//@version=5
indicator("Simple Dominance Momentum Indicator", format = format.percent)
dom_ema_len = input.int(21, "EMA Length", 1)
trend_ema_len = input.int(55, "Trend EMA Length", 1)
string dom_ticker = na
dom_ticker := switch syminfo.currency
"USDT" => "USDT.D+USDC.D+DAI.D"
"USDC" => "USDT.D+USDC.D+DAI.D"
"DAI" => "USDT.D+USDC.D+DAI.D"
"BTC" => "BTC.D"
"ETH" => "ETH.D"
"BNB" => "BNB.D"
=> na
dom = request.security(dom_ticker, timeframe.period, close, ignore_invalid_symbol = true)
dom_ema = ta.ema(dom, dom_ema_len)
trend_ema = ta.ema(dom, trend_ema_len)
plot(na(dom_ticker) ? na : dom, "Stables Dominance", color.green)
plot(na(dom_ticker) ? na : dom_ema, "Dominance EMA", color.white)
plot(na(dom_ticker) ? na : trend_ema, "Trend EMA")
|
Paradigm Trades_VPA Swing Indicator | https://www.tradingview.com/script/RyrJ1Vz0-Paradigm-Trades-VPA-Swing-Indicator/ | PierrePressure | https://www.tradingview.com/u/PierrePressure/ | 26 | 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/
// © PierrePressure
//@version=4
study("VPA Swing Indicator", overlay=true)
// Determine if the current bar is a Volume Climax Up
vc_up = (volume > sma(volume, 20)) and (close > open)
// Determine if the current bar is a Volume Climax Down
vc_down = (volume > sma(volume, 20)) and (close < open)
// Plot signals
plotshape(vc_up, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="VCU")
plotshape(vc_down, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="VCD")
// Add alerts for the signals
alertcondition(vc_up, title="Volume Climax Up", message="A Volume Climax Up has formed")
alertcondition(vc_down, title="Volume Climax Down", message="A Volume Climax Down has formed")
|
Range Analysis - By Leviathan | https://www.tradingview.com/script/nUos1SCj-Range-Analysis-By-Leviathan/ | LeviathanCapital | https://www.tradingview.com/u/LeviathanCapital/ | 3,428 | 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("Range Analysis - By Leviathan", shorttitle='Range Analysis - By Leviathan', overlay=true, max_boxes_count=500, max_bars_back = 500)
timeGroup = 'Time Interval'
vpGroup = 'Volume Profile / Open Interest Profile / Heatmap'
rangeGroup = 'Range Levels'
nstip = 'Node Size inputs controls the scaling of volume profile nodes in relation to the range size. Example: The value of 1 will proportionally extend the nodes to right max of the range, whereas the value of 0.5 will extend the nodes to the middle of the range.'
rstip = 'Increasing the resolution input will improve the volume profile but will also limit the script from generating profiles on longer ranges. Play around and find the higest resolution value that works on your selected range.'
vapcttip = 'Value Area is the area where the most volume occurred. The input is usually 70% or 68%, but you can adjust it to any percentage you want.'
svtip = 'Useful for assets that have very large spikes in volume over large bars. It uses ema of volume instead of just volume and helps create better profiles when needed.'
dirtip = 'Specify the direction of your range (eg. from low to high = UP and high to low = DOWN). This is only significant for level labels and fibbonacci levels'
ndtytip = 'Type 1 means that one node consists of both UP and DOWN data. Type 2 means that UP node will be on the right side of y axis and DOWN node will be on the left side of y axis.'
prfdirtip = 'Choose whether the nodes of the profile are facing left or right.'
prfpostip = 'Choose whether the profile is positioned on the left side of the range or on the right side of the range.'
volndtip = 'Up/Down shows the proportion of UP data and DOWN data in a node. Total shows the net value of UP data + DOWN data. Delta shows the net difference between UP Data and DOWN data.'
dtatyptip = 'Choose the data source used for generating the profile and the heatmaps'
// Range levels inputs
dir = input.string('UP', 'Direction', options = ['UP', 'DOWN'], group = rangeGroup, tooltip = dirtip)
showHL = input.bool(true, '', inline='rm', group = rangeGroup)
rangemax = input.string('Range Max: Close', '', options = ['Range Max: Wick', 'Range Max: Close', 'Range Max: HLC3', 'Range Max:OHLC4'], inline='rm', group = rangeGroup)
rangemaxStyle = input.string('────', '', options=['────', '--------', '┈┈┈┈'], inline='rm', group = rangeGroup)
hlCol = input.color(color.silver, '', inline='rm', group = rangeGroup)
lvl05 = input.bool(true, 'Half ', inline='2', group = rangeGroup)
lvl05Col = input.color(color.rgb(178, 181, 190, 20), '', inline='2', group = rangeGroup)
lvl05Style = input.string('────', '', options=['────', '--------', '┈┈┈┈'], inline='2', group = rangeGroup)
quarters = input.bool(true, 'Quarters ', inline='4', group = rangeGroup)
quartersCol = input.color(color.rgb(178, 181, 190, 70), '', inline='4', group = rangeGroup)
quartersStyle = input.string('────', '', options=['────', '--------', '┈┈┈┈'], inline='4', group = rangeGroup)
eighths = input.bool(false, 'Eighths ', inline='8', group = rangeGroup)
eighthsCol = input.color(color.rgb(178, 181, 190, 80), '', inline='8', group = rangeGroup)
eighthsStyle = input.string('────', '', options=['────', '--------', '┈┈┈┈'], inline='8', group = rangeGroup)
fib = input.bool(false, 'Fibonacci ', inline='F', group = rangeGroup)
fibCol = input.color(color.rgb(178, 181, 190, 80), '', inline='F', group = rangeGroup)
fibStyle = input.string('────', '', options=['────', '--------', '┈┈┈┈'], inline='F', group = rangeGroup)
showvwap = input.bool(false, 'VWAP ', group = rangeGroup, inline='vwap')
vwapCol = input.color(color.silver, '', group = rangeGroup, inline='vwap')
vwapStyle = input.string('•••••••••', '', options=['•••••••••', '────'], inline='vwap', group = rangeGroup)
outer = input.bool(false, 'Outer ', inline='out', group = rangeGroup)
outerCol = input.color(color.rgb(178, 181, 190, 80), '', group = rangeGroup, inline='out')
outerStyle = input.string('────', '', options=['────', '--------', '┈┈┈┈'], inline='out', group = rangeGroup)
extendb = input.bool(false, 'Extend (+Bars)', group = rangeGroup, inline='ex')
extnmb = input.int(50, '', group = rangeGroup, inline='ex')
extend = input.bool(false, 'Extend Right', group = rangeGroup, inline='opt')
labels = input.bool(true, 'Show Labels', group = rangeGroup, inline='opt')
dirline = input.bool(false, 'Diagonal Line', group = rangeGroup, inline='dd')
stats = input.bool(false, 'Stats (Soon)', group = rangeGroup, inline='dd')
// Volume Profile inputs
voltype = input.string('Volume', 'Data Type: ', options=['Volume', 'Open Interest'], group=vpGroup, inline='vp1', tooltip = dtatyptip)
res = input.int(30, 'Resolution', minval=5, tooltip=rstip, group=vpGroup)
showProf = input.bool(false, 'Volume/OI Profile ', group=vpGroup, inline = 'vpm')
bullCol = input.color(color.rgb(76, 175, 79, 50), '', group=vpGroup, inline='vpm')
bearCol = input.color(color.rgb(255, 82, 82, 50), '', group=vpGroup, inline='vpm')
volhm = input.bool(false, 'Vertical Heatmap ', group = vpGroup, inline = 'vhm')
hvolhm = input.bool(false, 'Horizontal Heatmap ', group = vpGroup, inline = 'hhm')
vhmcol1 = input.color(color.rgb(33, 149, 243, 100), '', group=vpGroup, inline='vhm')
vhmcol2 = input.color(color.rgb(20, 94, 255, 63), '', group=vpGroup, inline='vhm')
hhmcol1 = input.color(color.rgb(33, 149, 243, 100), '', group=vpGroup, inline='hhm')
hhmcol2 = input.color(color.rgb(20, 94, 255, 63), '', group=vpGroup, inline='hhm')
volnodes = input.string('Up/Down', 'Node Type', options = ['Up/Down', 'Total', 'Delta'], group=vpGroup, tooltip = volndtip)
profilepos = input.string('Left', 'Profile Position', options=['Left', 'Right'], group=vpGroup, tooltip = prfpostip)
profiledir = input.string('Right', 'Profile Direction', options=['Left', 'Right'], group=vpGroup, tooltip = prfdirtip)
profiletype = input.string('Type 1', 'Profile Type', options=['Type 1', 'Type 2'], group=vpGroup, tooltip = ndtytip)
nodesize = input.float(30, 'Node Size (%)', minval=1, maxval = 600, step = 5, group=vpGroup, tooltip = nstip)
VApct = input.float(70.0, 'Value Area (%)', minval=1, maxval = 100, step=1, group=vpGroup, tooltip = vapcttip)
volval = input.bool(false, 'Profile Node Values', group=vpGroup, inline = 'vl')
hmval = input.bool(false, 'Heatmap Node Values', group=vpGroup, inline='vl')
showPoc = input.bool(false, 'POC ', group=vpGroup, inline='poc')
pocCol = input.color(color.maroon, '', inline='poc', group=vpGroup)
pocStyle = input.string('────', '', options=['────', '--------', '┈┈┈┈'], inline='poc', group = vpGroup)
showVAH = input.bool(false, 'VAH ', group=vpGroup, inline='vah')
vahCol = input.color(color.rgb(255, 153, 0, 36), '', inline='vah', group=vpGroup)
vahStyle = input.string('────', '', options=['────', '--------', '┈┈┈┈'], inline='vah', group = vpGroup)
showVAL = input.bool(false, 'VAL ', group=vpGroup, inline='val')
valCol = input.color(color.rgb(255, 153, 0, 36), '', inline='val', group=vpGroup)
valStyle = input.string('────', '', options=['────', '--------', '┈┈┈┈'], inline='val', group = vpGroup)
showVAbox = input.bool(false, 'VA ', group=vpGroup, inline='vb')
VAboxCol = input.color(color.rgb(2, 68, 122, 85), '', group=vpGroup, inline='vb')
netcol1 = input.color(color.blue, 'Total Volume', group=vpGroup, inline='ttv')
netcol2 = input.color(color.red, '', group=vpGroup, inline='ttv')
smoothVol = input.bool(false, 'Smooth Volume Data', tooltip=svtip, group=vpGroup)
ndsize = input.string('Auto', 'Node Text Style ', options = ['Tiny', 'Small', 'Normal', 'Large', 'Auto'], group= 'Additional Settings', inline = 'nds')
ndpos = input.string('Center', '', options = ['Left', 'Right', 'Center'], group= 'Additional Settings', inline = 'nds')
lblsize = input.string('Small', 'Label Text Style ', options = ['Tiny', 'Small', 'Normal', 'Large', 'Auto'], group= 'Additional Settings', inline = 'lbls')
lblpos = input.string('Right', '', options=['Right', 'Left'], group= 'Additional Settings', inline = 'lbls')
hmsize = input.string('Auto', 'Heatmap Text Style ', options = ['Tiny', 'Small', 'Normal', 'Large', 'Auto'], group= 'Additional Settings', inline = 'hms')
hmpos = input.string('Left', '', options = ['Left', 'Right', 'Center'], group= 'Additional Settings', inline = 'hms')
profbuff = input.int(10, 'Profile Node Buffer',minval = 3,maxval = 12, group= 'Additional Settings')
hmbuff = input.int(1, 'Heatmap Node Buffer', minval = 1,maxval = 10, group= 'Additional Settings')
showRB = input.bool(false, 'Range Box', inline='rb', group= 'Additional Settings')
rangebCol = input.color(color.rgb(178, 181, 190, 98), '', inline='rb', group= 'Additional Settings')
startTime = input.time(defval=0, title='Start Time', confirm=true, group=timeGroup)
endTime = input.time(defval=0, title='End Time', confirm=true, group=timeGroup)
//
bool inZone = time >= startTime and time <= endTime
bool newSession = inZone and not inZone[1]
bool endSession = not inZone and inZone[1]
var int barsInSession = 0
var int zoneStartIndex = 0
var int zoneEndIndex = 0
var int zoneStart = 0
barsInSession := inZone ? barsInSession + 1 : barsInSession
if newSession
zoneStartIndex := bar_index
if endSession
zoneEndIndex := bar_index
int lookback = bar_index - zoneStart
var activeZone = false
//
highest = rangemax=='Range Max: Wick' ? high : rangemax=='Range Max: Close' ? close : rangemax=='Range Max: HLC3' ? hlc3 : ohlc4
lowest = rangemax=='Range Max: Wick' ? low : rangemax=='Range Max: Close' ? close : rangemax=='Range Max: HLC3' ? hlc3 : ohlc4
profHigh = ta.highest(highest, barsInSession+1)[1]
profLow = ta.lowest(lowest, barsInSession+1)[1]
resolution = res
//
var vpGreen = array.new_float(resolution, 0)
var vpRed = array.new_float(resolution, 0)
var zoneBounds = array.new_float(resolution, 0)
//
var float[] ltfOpen = array.new_float(0)
var float[] ltfClose = array.new_float(0)
var float[] ltfHigh = array.new_float(0)
var float[] ltfLow = array.new_float(0)
var float[] ltfVolume = array.new_float(0)
//
string userSymbol = 'BINANCE' + ":" + string(syminfo.basecurrency) + 'USDT.P'
string openInterestTicker = str.format("{0}_OI", userSymbol)
string timeframe = syminfo.type == "futures" and timeframe.isintraday ? "1D" : timeframe.period
deltaOi = request.security(openInterestTicker, timeframe, close-close[1], ignore_invalid_symbol = true)
oi = request.security(openInterestTicker, timeframe.period, close, ignore_invalid_symbol = true)
pldeltaoi = deltaOi
//
vol() =>
out = smoothVol ? ta.ema(volume, 5) : volume
if voltype == 'Open Interest'
out := deltaOi
out
//
float dO = open
float dC = close
float dH = high
float dL = low
float dV = vol()
//
switchLineStyle(x) =>
switch x
'────' => line.style_solid
'--------' => line.style_dashed
'┈┈┈┈' => line.style_dotted
switchPos(x) =>
switch x
'Left' => text.align_left
'Right' => text.align_right
'Center' => text.align_center
switchPlotStyle(x) =>
switch x
'•••••••••' => plot.style_circles
'────' => plot.style_linebr
switchsize(x) =>
switch x
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Large' => size.large
'Auto' => size.auto
//
resetProfile(enable) =>
if enable
array.fill(vpGreen, 0)
array.fill(vpRed, 0)
array.clear(ltfOpen)
array.clear(ltfHigh)
array.clear(ltfLow)
array.clear(ltfClose)
array.clear(ltfVolume)
tr = ta.atr(1)
atr = ta.atr(14)
get_vol(y11, y12, y21, y22, height, vol) =>
nz(math.max(math.min(math.max(y11, y12), math.max(y21, y22)) - math.max(math.min(y11, y12), math.min(y21, y22)), 0) * vol / height)
profileAdd(o, h, l, c, v, g, w) =>
for i = 0 to array.size(vpGreen) - 1
zoneTop = array.get(zoneBounds, i)
zoneBot = zoneTop - g
body_top = math.max(c, o)
body_bot = math.min(c, o)
itsgreen = c >= o
topwick = h - body_top
bottomwick = body_bot - l
body = body_top - body_bot
bodyvol = body * v / (2 * topwick + 2 * bottomwick + body)
topwickvol = 2 * topwick * v / (2 * topwick + 2 * bottomwick + body)
bottomwickvol = 2 * bottomwick * v / (2 * topwick + 2 * bottomwick + body)
if voltype == 'Volume'
array.set(vpGreen, i, array.get(vpGreen, i) + (itsgreen ? get_vol(zoneBot, zoneTop, body_bot, body_top, body, bodyvol) : 0) + get_vol(zoneBot, zoneTop, body_top, h, topwick, topwickvol) / 2 + get_vol(zoneBot, zoneTop, body_bot, l, bottomwick, bottomwickvol) / 2)
array.set(vpRed, i, array.get(vpRed, i) + (itsgreen ? 0 : get_vol(zoneBot, zoneTop, body_bot, body_top, body, bodyvol)) + get_vol(zoneBot, zoneTop, body_top, h, topwick, topwickvol) / 2 + get_vol(zoneBot, zoneTop, body_bot, l, bottomwick, bottomwickvol) / 2)
else if voltype == 'Open Interest'
if v > 0
array.set(vpGreen, i, array.get(vpGreen, i) + get_vol(zoneBot, zoneTop, body_bot, body_top, body, v))// + get_vol(zoneBot, zoneTop, body_top, h, topwick, topwickvol) / 2 + get_vol(zoneBot, zoneTop, body_bot, l, bottomwick, bottomwickvol) / 2)
if v < 0
array.set(vpRed, i, array.get(vpRed, i) + get_vol(zoneBot, zoneTop, body_bot, body_top, body, -v))// + get_vol(zoneBot, zoneTop, body_top, h, topwick, topwickvol) / 2 + get_vol(zoneBot, zoneTop, body_bot, l, bottomwick, bottomwickvol) / 2)
calcSession(update) =>
array.fill(vpGreen, 0)
array.fill(vpRed, 0)
if bar_index > lookback and update and (showPoc or showProf or showVAbox or showVAH or showVAL or hvolhm)
gap = (profHigh - profLow) / resolution
for i = 0 to resolution - 1
array.set(zoneBounds, i, profHigh - gap * i)
if array.size(ltfOpen) > 0
for j = 0 to array.size(ltfOpen) - 1
profileAdd(array.get(ltfOpen, j), array.get(ltfHigh, j), array.get(ltfLow, j), array.get(ltfClose, j), array.get(ltfVolume, j), gap, 1)
pocLevel() =>
float maxVol = 0
int levelInd = 0
for i = 0 to array.size(vpRed) - 1
if array.get(vpRed, i) + array.get(vpGreen, i) > maxVol
maxVol := array.get(vpRed, i) + array.get(vpGreen, i)
levelInd := i
float outLevel = na
if levelInd != array.size(vpRed) - 1
outLevel := array.get(zoneBounds, levelInd) - (array.get(zoneBounds, levelInd) - array.get(zoneBounds, levelInd+1)) / 2
outLevel
valueLevels(poc) =>
float gap = (profHigh - profLow) / resolution
float volSum = array.sum(vpRed) + array.sum(vpGreen)
float volCnt = 0
float vah = profHigh
float val = profLow
int pocInd = 0
for i = 0 to array.size(zoneBounds)-2
if array.get(zoneBounds, i) >= poc and array.get(zoneBounds, i + 1) < poc
pocInd := i
volCnt += (array.get(vpRed, pocInd) + array.get(vpGreen, pocInd))
for i = 1 to array.size(vpRed)
if pocInd + i >= 0 and pocInd + i < array.size(vpRed)
volCnt += (array.get(vpRed, pocInd + i) + array.get(vpGreen, pocInd + i))
if volCnt >= volSum * (VApct/100)
break
else
val := array.get(zoneBounds, pocInd + i) - gap
if pocInd - i >= 0 and pocInd - i < array.size(vpRed)
volCnt += (array.get(vpRed, pocInd - i) + array.get(vpGreen, pocInd - i))
if volCnt >= volSum * (VApct/100)
break
else
vah := array.get(zoneBounds, pocInd - i)
[val, vah]
//
half = (profHigh+profLow) / 2
l75 = (half + profHigh) / 2
l25 = (half + profLow) / 2
l125 = (profLow+l25) / 2
l375 = (half + l25) / 2
l625 = (half + l75) / 2
l875 = (l75 + profHigh) / 2
f618 = dir=='UP' ? (profHigh - ((profHigh-profLow) * 0.618)) : (profLow + ((profHigh-profLow) * 0.618))
f236 = dir=='UP' ? (profHigh - ((profHigh-profLow) * 0.236)) : (profLow + ((profHigh-profLow) * 0.236))
f382 = dir=='UP' ? (profHigh - ((profHigh-profLow) * 0.382)) : (profLow + ((profHigh-profLow) * 0.382))
f786 = dir=='UP' ? (profHigh - ((profHigh-profLow) * 0.786)) : (profLow + ((profHigh-profLow) * 0.786))
f161 = dir=='UP' ? (profHigh - ((profHigh-profLow) * 1.618)) : (profLow + ((profHigh-profLow) * 1.618))
f261 = dir=='UP' ? (profHigh - ((profHigh-profLow) * 2.618)) : (profLow + ((profHigh-profLow) * 2.618))
//
f_newLine(condition,x, y, c, w, s) =>
condition ? line.new(x, y, extendb ? bar_index+extnmb : bar_index, y, color=c, width=w, style=switchLineStyle(s), extend = extend ? extend.right : extend.none) : na
f_newLabel(condition, x, y, txt, txtcl) =>
condition ? label.new(extend ? x : (lblpos=='Right' ? (extendb ? bar_index+extnmb+1 : bar_index+1) : x), y, text=txt, color=color.rgb(255, 255, 255, 100), textcolor = txtcl, style = extend or lblpos=='Left' ? label.style_label_right : label.style_label_left, size=switchsize(lblsize)) : na
f_newNode(condition, x, top, right, bott, col, txt) =>
condition ? box.new(x, top, right, bott, bgcolor=col, border_width=0, text= volval ? txt : na,xloc=xloc.bar_index, text_size = switchsize(ndsize), text_color = chart.fg_color, text_halign = switchPos(ndpos)) : na
f_newHeatmap(condition, x, top, right, bott, col, txt) =>
condition ? box.new(x, top, right, bott, bgcolor=col, border_width=0, text= hmval ? txt : na,xloc=xloc.bar_index, text_size = switchsize(hmsize), text_color = chart.fg_color, text_halign = switchPos(hmpos)) : na
drawNewZone(update) =>
var box [] profileBoxesArray = array.new_box(0)
var line [] levelsLinesArray = array.new_line(0)
var box [] boxes = array.new_box(0)
var line [] RangeLinesArray = array.new_line(0)
var label[] levelLabels = array.new_label(0)
float leftMax = zoneStartIndex
float rightMax = (((barstate.islast and inZone) ? bar_index : zoneEndIndex) - zoneStartIndex) * (nodesize/100) + zoneStartIndex
if update and array.sum(vpGreen) + array.sum(vpRed) > 0
gap = (profHigh - profLow) / resolution
gap2 = (profHigh - profLow) / 10
float rightMaxVol = array.max(vpGreen)+array.max(vpRed)
float buffer = gap / profbuff
float buffer2 = gap / hmbuff
if showProf or hvolhm
size = array.size(profileBoxesArray)
if size > 0
for j = 0 to size - 1
box.delete(array.get(profileBoxesArray, size - 1 - j))
array.remove(profileBoxesArray, size - 1 - j)
for i = 0 to array.size(vpRed) - 1
vpct = array.percentrank(vpGreen, i)/100
netcol = color.from_gradient(vpct, 0, 1, netcol1, netcol2)
hmcol = color.from_gradient(vpct, 0, 1, hhmcol1, hhmcol2)
gleft = profilepos=='Left' ? leftMax : bar_index[0]
greenEnd = int(leftMax + (rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol))
greenEndD = int(gleft - (rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol))
greenEnd2 = int(bar_index[0] + (rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol))
redEnd = int(greenEnd + (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol))
redEndD = int(greenEndD - (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol))
redEnd2 = int(greenEnd2 + (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol))
redEnd3 = int(int(leftMax) - (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol))
redEnd4 = int(bar_index[0] - (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol))
total = int(leftMax + ((rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol)) + (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol))
totalD = int(gleft - ((rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol)) - (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol))
total2 = int(bar_index[0] + ((rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol)) + (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol))
delta = array.get(vpGreen, i)-array.get(vpRed, i)
deltap = (int(gleft + (rightMax - leftMax) * (math.abs(array.get(vpGreen, i)-array.get(vpRed, i)) / rightMaxVol)))
deltap2 = (int(gleft - (rightMax - leftMax) * (math.abs(array.get(vpGreen, i)-array.get(vpRed, i)) / rightMaxVol)))
totvol = str.tostring(array.get(vpGreen, i) + (voltype=='Volume' ? array.get(vpRed, i) : 0), format.volume)
hmvoloi = str.tostring(array.get(vpGreen, i) - array.get(vpRed, i) , format.volume)
gvol = str.tostring(array.get(vpGreen, i), format.volume)
rvol = str.tostring(array.get(vpRed, i), format.volume)
dvol = str.tostring(delta, format.volume)
if profilepos=='Left' and showProf
array.push(profileBoxesArray, f_newNode(volnodes=='Up/Down', int(leftMax), array.get(zoneBounds, i) - buffer, profiledir=='Right' ? greenEnd : greenEndD, array.get(zoneBounds, i) - gap + buffer, bullCol, gvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Up/Down' and profiletype=='Type 1', profiledir=='Right' ? greenEnd : greenEndD, array.get(zoneBounds, i) - buffer, profiledir=='Right' ? redEnd : redEndD, array.get(zoneBounds, i) - gap + buffer, bearCol, rvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Up/Down' and profiletype=='Type 2', int(leftMax), array.get(zoneBounds, i) - buffer, redEnd3, array.get(zoneBounds, i) - gap + buffer, bearCol, rvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Total', int(leftMax), array.get(zoneBounds, i) - buffer, profiledir=='Right' ? total : totalD, array.get(zoneBounds, i) - gap + buffer, netcol, totvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Delta' and profiletype=='Type 1', int(leftMax), array.get(zoneBounds, i) - buffer, deltap, array.get(zoneBounds, i) - gap + buffer, delta>0 ? bullCol : bearCol, dvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Delta' and profiletype=='Type 2', int(leftMax), array.get(zoneBounds, i) - buffer, delta>0 ? deltap : deltap2, array.get(zoneBounds, i) - gap + buffer, delta>0 ? bullCol : bearCol, dvol))
if profilepos=='Right' and showProf
array.push(profileBoxesArray, f_newNode(volnodes=='Up/Down', bar_index[0], array.get(zoneBounds, i) - buffer, profiledir=='Right' ? greenEnd2 : greenEndD, array.get(zoneBounds, i) - gap + buffer, bullCol, gvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Up/Down' and profiletype=='Type 1', profiledir=='Right' ? greenEnd2 : greenEndD , array.get(zoneBounds, i) - buffer, profiledir=='Right' ? redEnd2 : redEndD, array.get(zoneBounds, i) - gap + buffer, bearCol, rvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Up/Down' and profiletype=='Type 2', bar_index[0], array.get(zoneBounds, i) - buffer, redEnd4, array.get(zoneBounds, i) - gap + buffer, bearCol, rvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Total', bar_index[0], array.get(zoneBounds, i) - buffer, profiledir=='Right' ? total2 : totalD, array.get(zoneBounds, i) - gap + buffer, netcol, totvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Delta' and profiletype=='Type 1', int(gleft), array.get(zoneBounds, i) - buffer, deltap, array.get(zoneBounds, i) - gap + buffer, delta>0 ? bullCol : bearCol, dvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Delta' and profiletype=='Type 2', int(gleft), array.get(zoneBounds, i) - buffer, delta>0 ? deltap : deltap2, array.get(zoneBounds, i) - gap + buffer, delta>0 ? bullCol : bearCol, dvol))
if hvolhm
array.push(profileBoxesArray, f_newHeatmap(true, int(leftMax), array.get(zoneBounds, i) - buffer2, bar_index, array.get(zoneBounds, i) - gap + buffer2, hmcol, voltype=='Volume' ? totvol : hmvoloi))
if showHL
line.new(int(leftMax), profHigh, extendb ? bar_index+extnmb : bar_index, profHigh, color=hlCol, width=1, style=line.style_solid, extend = extend ? extend.right : extend.none)
line.new(int(leftMax), profLow, extendb ? bar_index+extnmb : bar_index, profLow, color=hlCol, width=1, style=line.style_solid, extend = extend ? extend.right : extend.none)
if lvl05 or quarters or eighths
f_newLine(true,int(leftMax), half, lvl05Col, 1, lvl05Style)
if quarters or eighths
f_newLine(true,int(leftMax), l75, quartersCol, 1, quartersStyle)
f_newLine(true,int(leftMax), l25, quartersCol, 1, quartersStyle)
if eighths
f_newLine(true,int(leftMax), l125, eighthsCol, 1, eighthsStyle)
f_newLine(true,int(leftMax), l375, eighthsCol, 1, eighthsStyle)
f_newLine(true,int(leftMax), l625, eighthsCol, 1, eighthsStyle)
f_newLine(true,int(leftMax), l875, eighthsCol, 1, eighthsStyle)
if outer
f_newLine(quarters or eighths,int(leftMax), profLow - (l25-profLow), outerCol, 1, outerStyle)
f_newLine(quarters or eighths,int(leftMax), profLow - (half-profLow), outerCol, 1, outerStyle)
f_newLine(quarters or eighths,int(leftMax), profHigh + (l25-profLow), outerCol, 1, outerStyle)
f_newLine(quarters or eighths,int(leftMax), profHigh + (half-profLow), outerCol, 1, outerStyle)
f_newLine(eighths,int(leftMax), profHigh + (l125-profLow), outerCol, 1, outerStyle)
f_newLine(eighths,int(leftMax), profHigh + (l375-profLow), outerCol, 1, outerStyle)
f_newLine(eighths,int(leftMax), profLow - (l125-profLow), outerCol, 1, outerStyle)
f_newLine(eighths,int(leftMax), profLow - (l375-profLow), outerCol, 1, outerStyle)
f_newLine(fib,int(leftMax), f161, fibCol, 1, fibStyle)
f_newLine(fib,int(leftMax), f261, fibCol, 1, fibStyle)
if fib
f_newLine(true,int(leftMax), f618, fibCol, 1, fibStyle)
f_newLine(true,int(leftMax), f236, fibCol, 1, fibStyle)
f_newLine(true,int(leftMax), f382, fibCol, 1, fibStyle)
f_newLine(true,int(leftMax), f786, fibCol, 1, fibStyle)
if dirline
line.new(int(leftMax), dir=='UP' ? profLow : profHigh, bar_index, dir=='UP' ? profHigh : profLow, color=fibCol, width = 1, style=switchLineStyle(fibStyle), extend = extend ? extend.right : extend.none)
if labels
f_newLabel(lvl05, int(leftMax), half, '0.5', hlCol)
f_newLabel(fib, int(leftMax), f618, '0.618', fibCol)
f_newLabel(fib, int(leftMax), f236, '0.236', fibCol)
f_newLabel(fib, int(leftMax), f382, '0.382', fibCol)
f_newLabel(fib, int(leftMax), f786, '0.786', fibCol)
f_newLabel(showHL, int(leftMax), profHigh, dir=='UP' ? '0' : '1', hlCol)
f_newLabel(showHL, int(leftMax), profLow, dir=='UP' ? '1' : '0', hlCol)
f_newLabel(quarters, int(leftMax), l75, dir=='UP' ? '0.25' : '0.75', hlCol)
f_newLabel(quarters, int(leftMax), l25, dir=='UP' ? '0.75' : '0.25', hlCol)
poc = pocLevel()
[val, vah] = valueLevels(poc)
if showPoc or showVAbox or showVAL or showVAH
size = array.size(levelsLinesArray)
if size > 0
for j = 0 to size - 1
line.delete(array.get(levelsLinesArray, size - 1 - j))
array.remove(levelsLinesArray, size - 1 - j)
if showPoc
array.push(levelsLinesArray, line.new(int(leftMax), poc, extendb ? bar_index+extnmb : bar_index, poc, color=pocCol, width=1, xloc=xloc.bar_index, extend = extend ? extend.right : extend.none, style = switchLineStyle(pocStyle)))
if showVAH
array.push(levelsLinesArray, line.new(int(leftMax), vah, extendb ? bar_index+extnmb : bar_index, vah, color=vahCol, width=1, xloc=xloc.bar_index, extend = extend ? extend.right : extend.none, style = switchLineStyle(vahStyle)))
if showVAL
array.push(levelsLinesArray, line.new(int(leftMax), val, extendb ? bar_index+extnmb : bar_index, val, color=valCol, width=1, xloc=xloc.bar_index, extend = extend ? extend.right : extend.none, style = switchLineStyle(valStyle)))
if showVAbox
array.push(boxes, box.new(int(leftMax), vah, extendb ? bar_index+extnmb : bar_index, val, bgcolor=VAboxCol,border_color = na, xloc=xloc.bar_index, extend = extend ? extend.right : extend.none))
if update and (showHL or dirline or lvl05 or quarters or eighths or outer or fib or labels)
size = array.size(RangeLinesArray)
if size > 0
for j = 0 to size - 1
line.delete(array.get(RangeLinesArray, size - 1 - j))
label.delete(array.get(levelLabels, size - 1 - j))
array.remove(RangeLinesArray, size - 1 - j)
array.remove(RangeLinesArray, size - 1 - j)
array.push(RangeLinesArray, showHL ? line.new(int(leftMax), profHigh, extendb ? bar_index+extnmb : bar_index, profHigh, color=hlCol, width=1, style=line.style_solid, extend = extend ? extend.right : extend.none) : na)
array.push(RangeLinesArray, showHL ? line.new(int(leftMax), profLow, extendb ? bar_index+extnmb : bar_index, profLow, color=hlCol, width=1, style=line.style_solid, extend = extend ? extend.right : extend.none) : na)
array.push(RangeLinesArray, dirline ? line.new(int(leftMax), dir=='UP' ? profLow : profHigh, bar_index, dir=='UP' ? profHigh : profLow, color=fibCol, width = 1, style=switchLineStyle(fibStyle), extend = extend ? extend.right : extend.none) : na)
array.push(RangeLinesArray, lvl05 or quarters or eighths ? f_newLine(true,int(leftMax), half, lvl05Col, 1, lvl05Style) : na)
array.push(RangeLinesArray, quarters or eighths ? f_newLine(true,int(leftMax), l75, quartersCol, 1, quartersStyle) : na)
array.push(RangeLinesArray, quarters or eighths ? f_newLine(true,int(leftMax), l25, quartersCol, 1, quartersStyle) : na)
array.push(RangeLinesArray, eighths ? f_newLine(true,int(leftMax), l125, eighthsCol, 1, eighthsStyle) : na)
array.push(RangeLinesArray, eighths ? f_newLine(true,int(leftMax), l375, eighthsCol, 1, eighthsStyle) : na)
array.push(RangeLinesArray, eighths ? f_newLine(true,int(leftMax), l625, eighthsCol, 1, eighthsStyle) : na)
array.push(RangeLinesArray, eighths ? f_newLine(true,int(leftMax), l875, eighthsCol, 1, eighthsStyle) : na)
array.push(RangeLinesArray, outer and (quarters or eighths) ? f_newLine(true,int(leftMax), profLow - (l25-profLow), outerCol, 1, outerStyle) : na)
array.push(RangeLinesArray, outer and (quarters or eighths) ? f_newLine(true,int(leftMax), profLow - (half-profLow), outerCol, 1, outerStyle) : na)
array.push(RangeLinesArray, outer and (quarters or eighths) ? f_newLine(true,int(leftMax), profHigh + (l25-profLow), outerCol, 1, outerStyle) : na)
array.push(RangeLinesArray, outer and eighths ? f_newLine(true,int(leftMax), profLow - (l375-profLow), outerCol, 1, outerStyle) : na)
array.push(RangeLinesArray, outer and eighths ? f_newLine(true,int(leftMax), profLow - (l125-profLow), outerCol, 1, outerStyle) : na)
array.push(RangeLinesArray, outer and (quarters or eighths) ? f_newLine(true,int(leftMax), profHigh + (half-profLow), outerCol, 1, outerStyle) : na)
array.push(RangeLinesArray, outer and eighths ? f_newLine(true,int(leftMax), profHigh + (l125-profLow), outerCol, 1, outerStyle) : na)
array.push(RangeLinesArray, outer and eighths ? f_newLine(true,int(leftMax), profHigh + (l375-profLow), outerCol, 1, outerStyle) : na)
array.push(RangeLinesArray, outer and fib ? f_newLine(true,int(leftMax), f161, fibCol, 1, fibStyle) : na)
array.push(RangeLinesArray, outer and fib ? f_newLine(true,int(leftMax), f261, fibCol, 1, fibStyle) : na)
array.push(RangeLinesArray, fib ? f_newLine(true,int(leftMax), f618, fibCol, 1, fibStyle) : na)
array.push(RangeLinesArray, fib ? f_newLine(true,int(leftMax), f236, fibCol, 1, fibStyle) : na)
array.push(RangeLinesArray, fib ? f_newLine(true,int(leftMax), f382, fibCol, 1, fibStyle) : na)
array.push(RangeLinesArray, fib ? f_newLine(true,int(leftMax), f786, fibCol, 1, fibStyle) : na)
array.push(levelLabels, labels and fib ? f_newLabel(true,int(leftMax), f618, '0.618', hlCol) : na)
array.push(levelLabels, labels and fib ? f_newLabel(true,int(leftMax), f236, '0.236', hlCol) : na)
array.push(levelLabels, labels and fib ? f_newLabel(true,int(leftMax), f382, '0.382', hlCol) : na)
array.push(levelLabels, labels and fib ? f_newLabel(true,int(leftMax), f786, '0.786', hlCol) : na)
array.push(levelLabels, labels and lvl05 ? f_newLabel(true,int(leftMax), half, '0.5', hlCol) : na)
array.push(levelLabels, labels and showHL ? f_newLabel(true,int(leftMax), profHigh, dir=='UP' ? '0' : '1', hlCol) : na)
array.push(levelLabels, labels and showHL ? f_newLabel(true,int(leftMax), profLow, dir=='UP' ? '1' : '0', hlCol) : na)
array.push(levelLabels, labels and quarters ? f_newLabel(true,int(leftMax), l25, dir=='UP' ? '0.75' : '0.25', hlCol) : na)
array.push(levelLabels, labels and quarters ? f_newLabel(true,int(leftMax), l75, dir=='UP' ? '0.25' : '0.75', hlCol) : na)
array.push(boxes, showRB ? box.new(zoneStartIndex, profHigh, bar_index, profLow, border_color=na, bgcolor = rangebCol) : na)
//
combArray(arr1, arr2) =>
out = array.copy(arr1)
if array.size(arr2) > 0
for i = 0 to array.size(arr2) - 1
array.push(out, array.get(arr2, i))
out
//
updateIntra(o, h, l, c, v) =>
array.push(ltfOpen, o)
array.push(ltfHigh, h)
array.push(ltfLow, l)
array.push(ltfClose, c)
array.push(ltfVolume, v)
//
calcSession(endSession or (barstate.islast and inZone))
drawNewZone(endSession or (barstate.islast and inZone))
resetProfile(newSession)
//
if inZone
updateIntra(dO, dH, dL, dC, dV)
if endSession
activeZone := false
if newSession
zoneStart := bar_index
activeZone := true
//
startCalculationDate = startTime
vwap_calc() =>
var srcVolArray = array.new_float(na)
var volArray = array.new_float(na)
if startCalculationDate <= time
array.push(srcVolArray, hlc3*volume)
array.push(volArray, volume)
else
array.clear(srcVolArray), array.clear(volArray)
array.sum(srcVolArray)/array.sum(volArray)
anchoredVwap = vwap_calc()
plot((extend ? true : inZone) and showvwap ? anchoredVwap : na, "VWAP", linewidth=1, color=vwapCol, style = switchPlotStyle(vwapStyle), editable=false)
//
vhmsrc = voltype=='Volume' ? volume : deltaOi
hvol = ta.highest(vhmsrc, 50)
lvol = ta.lowest(vhmsrc, 50)
color1 = color.from_gradient(vhmsrc, 0, hvol, vhmcol1, vhmcol2)
ph = plot((extend ? true : inZone) and volhm ? profHigh : na, color= color.rgb(54, 58, 69, 100), style=plot.style_linebr)
pl = plot((extend ? true : inZone) and volhm ? profLow : na, color= color.rgb(54, 58, 69, 100), style=plot.style_linebr)
fill(ph, pl, color1)
|
Trap Trading - SwaG | https://www.tradingview.com/script/j7bM9Goa-Trap-Trading-SwaG/ | swagato25 | https://www.tradingview.com/u/swagato25/ | 155 | 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/
// © Swag
//@version=5
indicator("Trap Trading - SwaG", overlay = true)
//Inputs
bool red_zone_traps = input.bool(defval = false, title = "Red Zone Traps")
bool avoid_traps_at_support_or_resistance = input.bool(defval = true, title = " Avoid Traps At Support/Resistance Line")
bool support_resistance_levels = input.bool(defval = true, title = "Support Resistance Levels")
color resistance_color = input.color(color.purple, title="Previous Day Resistance", inline = "colors")
color support_color = input.color(color.green, title="Previous Day Support", inline = "colors")
//Static Variables
timeframe = timeframe.period
var float dh = 0.0
var float dl = 0.0
var bool is_support_confirmed = false
var bool is_resistance_confirmed = false
var float highest_green_open = na
var float lowest_red_open = na
var int pre_support_bar = na
var int pre_resistance_bar = na
var int cur_support_bar = na
var int cur_resistance_bar = na
var int total_intraday_bar = 0
if timeframe.isminutes
if timeframe.multiplier == 1
total_intraday_bar := 374
else if timeframe.multiplier == 3
total_intraday_bar := 124
else if timeframe.multiplier == 5
total_intraday_bar := 74
else if timeframe.multiplier == 10
total_intraday_bar := 37
else if timeframe.multiplier == 15
total_intraday_bar := 24
newDayStart = dayofmonth != dayofmonth[1] and timeframe.isintraday
// Set day high day low
if newDayStart
dh := high
dl := low
highest_green_open := na
lowest_red_open := na
else
dh := math.max(dh, high)
dl := math.min(dl, low)
//support & resistance
is_first_bar = request.security(syminfo.tickerid,"D",barstate.isfirst)
if timeframe.isminutes and timeframe.multiplier <= 15 and support_resistance_levels
if newDayStart and not is_first_bar
pre_resistance_bar := cur_resistance_bar
pre_support_bar := cur_support_bar
box.new(left=bar_index, top=high[bar_index-pre_resistance_bar],right= bar_index+total_intraday_bar, bottom=low[bar_index-pre_resistance_bar],border_color = color.new(resistance_color,50),bgcolor = color.new(resistance_color,90))
box.new(left=bar_index, top=high[bar_index-pre_support_bar],right= bar_index+total_intraday_bar, bottom=low[bar_index-pre_support_bar],border_color = color.new(support_color,50),bgcolor = color.new(support_color,90))
if newDayStart
cur_support_bar := na
cur_resistance_bar := na
if volume > volume[1]
if open > close
if na(cur_resistance_bar)
cur_resistance_bar := bar_index
else if high >= high[bar_index-cur_resistance_bar]
cur_resistance_bar := bar_index
if open < close
if na(cur_support_bar)
cur_support_bar := bar_index
else if low <= low[bar_index-cur_support_bar]
cur_support_bar := bar_index
//Valid trap range find
if open < close
if na(highest_green_open)
highest_green_open := open
else
highest_green_open := math.max(highest_green_open,open)
if open > close
if na(lowest_red_open)
lowest_red_open := open
else
lowest_red_open := math.min(lowest_red_open,open)
if not timeframe.isintraday
highest_green_open := na
lowest_red_open := na
// Confirmation of support and resistance
if high >= dh
is_resistance_confirmed := false
if low <= dl
is_support_confirmed := false
support_confirm_condition = close > open and volume > volume[1] and low > dl
resistance_confirmed_condition = open > close and volume > volume[1] and high < dh
if support_confirm_condition
is_support_confirmed := true
if resistance_confirmed_condition
is_resistance_confirmed := true
//finding Trapping candles
sell_trap_condition = open > close and volume > volume[1]
buy_trap_condition = close > open and volume > volume[1]
if timeframe.isintraday and not red_zone_traps
sell_trap_condition := sell_trap_condition and is_support_confirmed and is_resistance_confirmed
buy_trap_condition := buy_trap_condition and is_support_confirmed and is_resistance_confirmed
if avoid_traps_at_support_or_resistance
sell_trap_condition := sell_trap_condition and low > lowest_red_open
buy_trap_condition := buy_trap_condition and high < highest_green_open
sell_trap = request.security(symbol = syminfo.tickerid ,timeframe = timeframe,expression = sell_trap_condition)
buy_trap = request.security(symbol = syminfo.tickerid ,timeframe = timeframe,expression = buy_trap_condition)
//plotting objects
plotshape(sell_trap, color = color.green, style = shape.triangleup, title = "Sellers Trap")
plotshape(buy_trap, color = color.red, style = shape.triangledown,location = location.belowbar, title = "Buyers Trap")
bgcolor( not (is_support_confirmed and is_resistance_confirmed) and timeframe.isintraday? color.new(color.red,90) : na)
plot(highest_green_open, color = color.red, style = plot.style_stepline, title = "Sell below", linewidth = 2)
plot(lowest_red_open, color = color.green, style = plot.style_stepline, title = "Buy Above", linewidth = 2) |
USBOND_BackCalc | https://www.tradingview.com/script/V4c1hFrp/ | Aki_Pine1024 | https://www.tradingview.com/u/Aki_Pine1024/ | 7 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Aki_Pine1024
//@version=5
// Determining bond prices from yields on US Treasuries
// 米国債の利回りから債券価格を求める
indicator("USBOND_BackCalc", precision = 2)
//{ Symbol information シンボルの情報
// Get symbol
// シンボルを取得
string symbolName = syminfo.tickerid
// Determine if a symbol is a US Treasury bond
// シンボルが米国債かどうかを判定
bool isUSBond = str.startswith(symbolName, "TVC:US")
// Determine if the chart is a yield chart
// 利回りのチャートかどうかを判定
bool isYield = str.endswith(syminfo.tickerid, "Y")
// Determining whether the receivables are less than one year old
// 一年未満(月単位)の債権かどうかを判定
bool isMonthlyBond = str.endswith(syminfo.tickerid, "MY")
//}
//{ Determining if the symbol is a US Treasury and Yield chart シンボルから米国債かつ利回りのチャートかどうか判定
if(not (isUSBond and isYield))
runtime.error("Cannot be used because it is not a chart of US Treasuries and yields. 米国債利回り以外のチャートでは使用できません。")
//}
//{ Get the term of a US Bond from a symbol and convert to years シンボルから米国債の期間(年数・月数)を取得し、年単位に変換する
int cutLen = str.pos(symbolName, "S")
float bondYearOrMonth = str.tonumber(str.substring(symbolName, cutLen + 1, cutLen + 3))
// Convert to year if unit is month 単位が月であれば年に直す
if(isMonthlyBond)
bondYearOrMonth /= 12
//}
// Determining bond prices from yields on US Treasuries
// 米国債の利回りから債券価格を求める
float price = 100 * math.pow(1 + close/100, -(bondYearOrMonth))
plot(price) |
DD/RP Calculator | https://www.tradingview.com/script/OFF0R7Pn/ | jam_chen1025 | https://www.tradingview.com/u/jam_chen1025/ | 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/
// © jam_chen1025
//@version=5
indicator("DD/RP Calculator", overlay=true)
// input
show_se_lbl = input.bool(false,"Show Entry/Exit Label")
show_se_li = input.bool(true,"Show Entry/Exit Line")
ddrpc_is_open = input.bool(false,"Is Open")
ddrpc_order_type = input.string("Buy","OrderType",options=["Buy","Sell"])
ddrpc_t_s = input.time(timestamp("1 Jan 1990 00:00 +0000"),"S Time",confirm=true,inline="Order Enter Point")
ddrpc_p_s = input.price(0,title="Price",confirm=true,inline="Order Enter Point")
ddrpc_t_e = input.time(timestamp("1 Jan 1990 00:00 +0000"),"E Time",confirm=true,inline="Order Exit Point")
ddrpc_p_e = input.price(0,title="Price",confirm=true,inline="Order Exit Point")
ddrpc_p_s := math.round_to_mintick(ddrpc_p_s)
ddrpc_p_e := math.round_to_mintick(ddrpc_p_e)
ddrpc_t_e := ddrpc_is_open ? time : ddrpc_t_e
// calculator
var float pts = syminfo.mintick
var float ddrpc_dd = na // draw down
var float ddrpc_rp = na // run up
var float ddrpc_hh = na // highest high
var float ddrpc_ll = na // lowest low
if time[0] <= ddrpc_t_s
ddrpc_dd := 0
ddrpc_rp := 0
ddrpc_hh := ddrpc_p_s
ddrpc_ll := ddrpc_p_s
else if time[0] > ddrpc_t_e
ddrpc_hh := na
ddrpc_ll := na
else
ddrpc_hh := math.max(high, ddrpc_hh)
ddrpc_ll := math.min(low, ddrpc_ll)
ddrpc_dd := int((ddrpc_ll - ddrpc_p_s) / pts)
ddrpc_rp := int((ddrpc_hh - ddrpc_p_s) / pts)
// draw input object
ddrpc_p_hh = plot((time[0] >= ddrpc_t_s and time[0] <= ddrpc_t_e) ? ddrpc_hh : na,"High Track",color=color.new(color.green,0))
ddrpc_p_ll = plot((time[0] >= ddrpc_t_s and time[0] <= ddrpc_t_e) ? ddrpc_ll : na,"Low Track",color=color.new(color.red,0))
if show_se_lbl
ddrpc_lbl_s = label.new(ddrpc_t_s,ddrpc_p_s,"S",xloc=xloc.bar_time,color=color.new(color.gray,0))
ddrpc_lbl_e = label.new(ddrpc_t_e,ddrpc_p_e,"E",xloc=xloc.bar_time,color=color.new(color.gray,0))
label.delete(ddrpc_lbl_s[1])
label.delete(ddrpc_lbl_e[1])
if show_se_li
ddrpc_li = line.new(ddrpc_t_s,ddrpc_p_s,ddrpc_t_e,ddrpc_p_e,xloc=xloc.bar_time,color=color.new(color.gray,0))
line.delete(ddrpc_li[1])
float ddrpc_profit = 0
float ddrpc_dd_final = 0
float ddrpc_rp_final = 0
if ddrpc_order_type == "Buy"
ddrpc_profit := (ddrpc_p_e - ddrpc_p_s) / pts
ddrpc_dd_final := ddrpc_dd
ddrpc_rp_final := ddrpc_rp
else
ddrpc_profit := (ddrpc_p_s - ddrpc_p_e) / pts
ddrpc_dd_final := -ddrpc_rp
ddrpc_rp_final := -ddrpc_dd
ddrpc_str_order_info = ddrpc_order_type + ": " + str.tostring(ddrpc_p_s) + " -> " + str.tostring(ddrpc_p_e) + "\n"
+ "P(" + str.tostring(int(ddrpc_profit)) + "), D(" + str.tostring(str.format("{0,number,#.##}",ddrpc_dd_final)) + "), R(" + str.tostring(str.format("{0,number,#.##}",ddrpc_rp_final)) + ")"
ddrpc_lbl_order_info = label.new(ddrpc_t_e,ddrpc_p_e,ddrpc_str_order_info,xloc=xloc.bar_time,color=color.new(color.gray,0),style=label.style_label_left,textcolor=color.new(color.white,0),textalign=text.align_left)
label.delete(ddrpc_lbl_order_info[1])
|
Volume+ (Time of Day) | https://www.tradingview.com/script/4oAJY0xk-Volume-Time-of-Day/ | Electrified | https://www.tradingview.com/u/Electrified/ | 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/
// © Electrified
//@version=5
indicator("Volume+ (Time of Day)", "Vol+ ⏲")
import Electrified/Color/9
MEASUREMENT = "Measurement"
days = input.int(100, "Days", group = MEASUREMENT, tooltip = "The number of days to measure.")
type TimeOfDay
float[] data
var data = array.new<TimeOfDay>()
dayStart = time("D")
// Time of day in seconds
timeOfDay = (time - dayStart) / 1000
multiple = switch
timeframe.isminutes => 60 * timeframe.multiplier
timeframe.isseconds => timeframe.multiplier
=> timeOfDay
barOfDay = math.floor(timeOfDay / multiple)
while barOfDay >= data.size()
data.push(TimeOfDay.new(array.new_float()))
var empty = array.new_float()
entries = data.size() == 0 ? empty : data.get(barOfDay).data
mean = entries.avg()
diff2sum = 0.0
for e in entries
diff2sum += e * e
variance = diff2sum / entries.size()
standardDeviation = math.sqrt(variance)
// Delay adding today's data
entries.push(nz(volume))
if entries.size() > days
entries.shift()
plus1 = mean + standardDeviation
plus2 = plus1 + standardDeviation
plus3 = plus2 + standardDeviation
HIGHLIGHT = "Bar Highlight"
BRIGHTEN = "Brighten", DARKEN = "Darken", NONE = "None"
highLight = input.string(BRIGHTEN, "Mode", group = HIGHLIGHT, options = [BRIGHTEN, DARKEN, NONE], tooltip = "How to affect the bar color when the volume exeeds one standard deviation.")
warmRange = plus3 - plus1
warmth = 100 * (volume - plus1) / warmRange
THEME = "Theme"
barTheme = input.color(color.gray, "Bar", group = THEME, inline = THEME)
meanColor = input.color(color.orange, "Average", group = THEME, inline = THEME)
devColor = input.color(color.yellow, "Deviation", group = THEME, inline = THEME)
barColor = switch highLight
NONE => barTheme
BRIGHTEN => barTheme.brighten(math.max(0, warmth))
DARKEN => barTheme.darken(math.max(0, warmth))
plot(volume, "Volume", barColor, style = plot.style_columns)
plot(plus1, "+1 Standard Deviation", color.new(devColor, 50), 1, display = display.pane)
plot(mean, "Average", meanColor, 1)
|
Volume Strength | https://www.tradingview.com/script/LW2o2Zyf-Volume-Strength/ | AngelAlgo | https://www.tradingview.com/u/AngelAlgo/ | 149 | 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/
// © AngelAlgo
//@version=5
indicator("Volume Strength", overlay = false)
// Input parameters
length = input.int(14, title="Length", minval=1)
// Define a function that calculates cumulative volume for a given period
CumVol(Period) =>
sum = volume
for i = 1 to Period
sum := sum + nz(volume[i])
sum
// Calculate the cumulative volume
vol_sum = CumVol(length)
// Calculate the average cumulative volume
avg_vol = ta.sma(vol_sum, length)
// Devide the cumulative volume by the average value
vol_strength = vol_sum / avg_vol
// Add horizontal lines to show overbought/oversold levels
hline(1.2, color=color.red, linewidth=2)
hline(0.8, color=color.green, linewidth=2)
// Define a conditional coloring for the volume strength indicator line
volume_strength_color = vol_strength > 1.2 ? color.red : vol_strength < 0.8 ? color.green : color.blue
// Plot the volume strength
plot(vol_strength, title="Volume Strength", color=volume_strength_color, linewidth=2)
// Add alerts for overbought/oversold levels
alertcondition(vol_strength > 1.2, title="Volume Strength Overbought", message="Volume strength is overbought")
alertcondition(vol_strength < 0.8, title="Volume Strength Oversold", message="Volume strength is oversold")
|
Correlation Coefficient Table | https://www.tradingview.com/script/pFMqW8b1-Correlation-Coefficient-Table/ | chill05 | https://www.tradingview.com/u/chill05/ | 33 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © chill05
//@version=5
indicator("Correlation Coefficient Table", shorttitle = "CCT", format = format.price, precision = 2, overlay = true)
tf = input.timeframe(defval="", title = "Timeframe")
symbolInput = input.symbol("BTCUSDT", "Source Symbol", confirm = true, tooltip = "The symbol which will be the source of correlation")
symbolInput1 = input.symbol("", title = "Symbol 1")
symbolInput2 = input.symbol("", title = "Symbol 2")
symbolInput3 = input.symbol("", title = "Symbol 3")
symbolInput4 = input.symbol("", title = "Symbol 4")
symbolInput5 = input.symbol("", title = "Symbol 5")
sourceInput = input.source(close, "Source")
lengthInput = input.int(20, "Length", tooltip = "Numbers of bars back to be used when calculating correlation")
t_VPosition = input.string("top", "Vertical Position", options = ["top", "middle", "bottom"], group = "Table Settings")
t_HPosition = input.string("right", "Horizontal Position", options = ["left", "center", "right"], group = "Table Settings")
t_bgcolor = input.color(color.new(color.gray, 0), "Background Color", group = "Table Settings")
t_bordercolor = input.color(color.new(color.white,0), "Border Color", group = "Table Settings")
t_tsize = input.string("normal", "Text Size", options = ["tiny", "small", "normal", "large", "huge", "auto"], group = "Table Settings")
t_alignment = input.string("center","Table Alignment", options = ["center","left", "right"], group = "Table Settings")
calc_correlation(source, source2, tf, candlesc, length ) =>
s1=request.security(source, tf, candlesc, barmerge.gaps_off)
s2=request.security(source2,tf, candlesc, barmerge.gaps_off)
corr = ta.correlation(s1, s2, length)
string corr_status = if corr == 0.0
"No correlation"
else if corr > 0.0 and corr < 0.2
"Very Weak Correlation"
else if corr >= 0.2 and corr < 0.4
"Weak Correlation"
else if corr >= 0.4 and corr < 0.6
"Moderately Strong Correlation"
else if corr >= 0.6 and corr < 0.8
"Strong Correlation"
else if corr >= 0.8 and corr < 1.0
"Very Strong Correlation"
else if corr == 1.0
"Perfect Correlation"
[corr, corr_status]
[corr1, corr_status1] = calc_correlation(symbolInput, symbolInput1, tf, sourceInput, lengthInput)
[corr2, corr_status2] = calc_correlation(symbolInput, symbolInput2, tf, sourceInput, lengthInput)
[corr3, corr_status3] = calc_correlation(symbolInput, symbolInput3, tf, sourceInput, lengthInput)
[corr4, corr_status4] = calc_correlation(symbolInput, symbolInput4, tf, sourceInput, lengthInput)
[corr5, corr_status5] = calc_correlation(symbolInput, symbolInput5, tf, sourceInput, lengthInput)
if barstate.islast
var table t = table.new(t_VPosition + "_" + t_HPosition, columns = 7, rows = 7, bgcolor = t_bgcolor, border_width=1, border_color = t_bordercolor)
if symbolInput1 != ""
table.cell(t, 0, 0, "Base Symbol")
table.cell(t, 1, 0, "vs Symbol")
table.cell(t, 3, 0, "Corr Value")
table.cell(t, 4, 0, "Corr Status")
table.cell(t, 0, 1, symbolInput)
table.cell(t, 1, 1, symbolInput1)
table.cell(t, 3, 1, str.tostring(corr1,"#.##"))
table.cell(t, 4, 1, corr_status1)
if symbolInput2 != ""
table.cell(t, 0, 2, symbolInput)
table.cell(t, 1, 2, symbolInput2)
table.cell(t, 3, 2, str.tostring(corr2,"#.##"))
table.cell(t, 4, 2, corr_status2)
table.merge_cells(t, 0, 1, 0, 2)
if symbolInput3 != ""
table.cell(t, 0, 3, symbolInput)
table.cell(t, 1, 3, symbolInput3)
table.cell(t, 3, 3, str.tostring(corr3,"#.##"))
table.cell(t, 4, 3, corr_status3)
table.merge_cells(t, 0, 1, 0, 3)
if symbolInput4 != ""
table.cell(t, 0, 4, symbolInput)
table.cell(t, 1, 4, symbolInput4)
table.cell(t, 3, 4, str.tostring(corr4,"#.##"))
table.cell(t, 4, 4, corr_status4)
table.merge_cells(t, 0, 1, 0, 4)
if symbolInput5 != ""
table.cell(t, 0, 5, symbolInput)
table.cell(t, 1, 5, symbolInput5)
table.cell(t, 3, 5, str.tostring(corr5,"#.##"))
table.cell(t, 4, 5, corr_status5)
table.merge_cells(t, 0, 1, 0, 5) |
RSI is in Normal Distribution? | https://www.tradingview.com/script/ds3Ege9v-RSI-is-in-Normal-Distribution/ | Dicargo_Beam | https://www.tradingview.com/u/Dicargo_Beam/ | 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/
// © Dicargo_Beam
//@version=5
indicator("RSI is in Normal Distribution?")
len = input.int(14)
_rsi = ta.rsi(close,len)
modify = input.bool(false, "Use 'Dicargo_Beam's RSI modified Function", tooltip="used in 'RSI Candle Advanced V2'")
// this function is used in 'RSI-Candle-Advanced-V2'
// https://www.tradingview.com/script/kvP8BO4N-RSI-Candle-Advanced-V2/
rsi_modified_function(rsi, len) =>
f = -math.pow(math.abs(math.abs(rsi - 50) - 50), 1 + math.pow(len / 14, 0.618) - 1) / math.pow(50, math.pow(len / 14, 0.618) - 1) + 50
modified = if rsi > 50
f + 50
else
-f + 50
modified
rsi = modify? rsi_modified_function(_rsi,len) : _rsi
var rsi_range = array.new_int(50,0)
get_samples()=>
for i = 0 to 49
if rsi >= i*2 and rsi < (i+1)*2
array.set(rsi_range, i, array.get(rsi_range,i) + 1)
sample_num = array.sum(rsi_range) //sum of number of samples
var rsi_stdev = 0.0
variance_sum = 0.0
mean = 50
for i = 0 to 49
variance_sum += math.pow(i*2+1 - mean,2) * array.get(rsi_range,i)
variance = variance_sum/sample_num
rsi_stdev := math.pow(variance,0.5)
var _30_to_70_percent = 0.0
_30_to_70_nums = 0.0
for i = 14 to 34
_30_to_70_nums += array.get(rsi_range,i)
_30_to_70_percent := _30_to_70_nums/sample_num*100
[sample_num, rsi_stdev, _30_to_70_percent, mean]
[sample_num, rsi_stdev, _30_to_70_percent, mean] = get_samples()
var lines = array.new_line()
var labels = array.new_label()
var box rangebox = na
if barstate.islast
rangebox := box.new(bar_index+5, array.max(rsi_range)/sample_num*100, bar_index+54, 0, bgcolor=color.new(color.green,90),
text = "Samples = "+str.tostring(sample_num)+"\nRSI length = " + str.tostring(len)+"\nstdev = "+str.tostring(rsi_stdev,"#.##")+"\n30 to 70 covers "+ str.tostring(_30_to_70_percent,"#.0")+" %",
text_size = size.normal, text_color = color.rgb(170, 154, 5),text_halign = text.align_right, text_valign = text.align_top)
for i = 0 to 49
array.push(lines, line.new(bar_index+5 + i, 0, bar_index+5 + i, array.get(rsi_range, i)/sample_num*100 ) )
if i == 14 or i == 24 or i == 34
array.push(labels, label.new(bar_index+5 + i, 0, text = " "+str.tostring(i*2+2)+ "\nZ="+str.tostring((i*2+2-mean)/rsi_stdev,"#.##"),
style=label.style_label_up, color=color.new(color.black,99), textcolor=color.rgb(150, 180, 13)))
if array.size(lines) > 49
line_del = array.shift(lines)
line.delete(line_del)
if array.size(labels) > 3
label_del = array.shift(labels)
label.delete(label_del)
box.delete(rangebox[1])
plot(rsi/10, color=color.aqua)
plot(5, color=color.gray)
plot(3, color=color.gray)
plot(7, color=color.gray)
plot(0, color=color.gray)
plot(10, color=color.gray)
|
4C Options Expected Move (Weekly + 0DTE) | https://www.tradingview.com/script/9nOpiEYe-4C-Options-Expected-Move-Weekly-0DTE/ | FourC | https://www.tradingview.com/u/FourC/ | 337 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © FourC
//This indicator plots lines for BOTH the Weekly and 0DTE options expected moves. This version is different than the original script "4C Expected Move (Weekly Options)" where only the weekly expected move could be plotted.
//@version=5
indicator("4C Options Expected Move (Weekly + 0DTE)", shorttitle="4C ExpectedMove", overlay=true)
var grweekem = "Weekly Option Expected Move"
emweeklyinfo = input.text_area(defval="Input next week's expected move value based on weekly option pricing. \nUse your broker or other resource to find the expected move +/- value for your symbol. \nIt is typically best to use the EM for the next week expiration that is generated AFTER the Friday close and/or before the Monday open of the upcoming week. \nThis will give the full expected range for the week.", title="Weekly Expected Move Inputs", group=grweekem)
tickerweek = input.symbol(defval="SPX", title="Input Weekly EM Symbol (for your reference)", group=grweekem)
emweek = input.price(1, "Input Weekly Option Expected Move +/-", group=grweekem)
showweekem = input(title='Show Weekly Option Expected Move', defval=true, group=grweekem)
show2sigmaem = input(title='Show 2 Standard Deviation Weekly EM', defval=false, group=grweekem)
posemcolor = input(title='Upper Weekly Expected Move', defval=color.rgb(0,255,0,0), group=grweekem)
wclosecolor = input(title='Last Week Close', defval=color.rgb(0,255,255,0), group=grweekem)
negemcolor = input(title='Lower Weekly Expected Move', defval=color.rgb(255,0,0,0), group=grweekem)
styleOptionem = input.string(title="Weekly EM Line Style", options=["solid (─)", "dashed (╌)", "dotted (┈)"], defval="solid (─)", group=grweekem)
var gr0dte = "0DTE Option Expected Move"
em0dteinfo = input.text_area(defval="Input 0DTE expected move value based on daily option pricing. \nUse your broker or other resource to find the expected move +/- value for your symbol. \nIt is typically best to use the EM value for the 0DTE option that is generated the night before (after market close), or before the market opens for that 0DTE. \nThis will give the full expected range for the day.", title="0DTE Expected Move Inputs", group=gr0dte)
tickerodte = input.symbol(defval="SPX", title="Input 0DTE Symbol (for your reference)", group=gr0dte)
em0dte = input.price(1, "Input 0DTE Option Expected Move +/-", group=gr0dte)
show0dteem = input(title='Show 0DTE Expected Move', defval=false, group=gr0dte)
show2sigma0dte = input(title='Show 2 Standard Deviation 0DTE EM', defval=false, group=gr0dte)
pos0dtecolor = input(title='Upper 0DTE Expected Move', defval=color.rgb(0,255,0,0), group=gr0dte)
dclosecolor = input(title='Prior Day Close', defval=color.rgb(0,255,255,0), group=gr0dte)
neg0dtecolor = input(title='Lower 0DTE Expected Move', defval=color.rgb(255,0,0,0), group=gr0dte)
styleOption0dte = input.string(title="0DTE EM Line Style", options=["solid (─)", "dashed (╌)", "dotted (┈)"], defval="solid (─)", group=gr0dte)
var settings = "Plot Settings"
linesright = input(title='Extend Lines Right', defval=true, group=settings)
linewidth = input(1, "Line Thickness", group=settings)
styleOptionx2 = input.string(title="2 Standard Deviation Line Style ", options=["solid (─)", "dashed (╌)", "dotted (┈)"], defval= "dashed (╌)", group=settings)
labelcolor = input(title='Expected Move Label Color', defval=color.white, group=settings)
var labels = "Label Settings"
showlabels = input(title='Show Labels', defval=true, group=labels)
labelposition = input(5,'Label Postion (Higher Value = Further Right)', group=labels)
lineStyleem = (styleOptionem == "dotted (┈)") ? line.style_dotted :
(styleOptionem == "dashed (╌)") ? line.style_dashed :
line.style_solid
lineStyle0dte = (styleOption0dte == "dotted (┈)") ? line.style_dotted :
(styleOption0dte == "dashed (╌)") ? line.style_dashed :
line.style_solid
lineStyle2 = (styleOptionx2 == "dotted (┈)") ? line.style_dotted :
(styleOptionx2 == "dashed (╌)") ? line.style_dashed :
line.style_solid
////Weekly EM////
wclose = request.security(syminfo.tickerid, "W", close[1], barmerge.gaps_off, barmerge.lookahead_on)
var line wcloseline = na
var line posemline = na
var line negemline = na
var line posemlinex2 = na
var line negemlinex2 = na
var label wcloselabel = na
var label wemposlabel = na
var label wemneglabel = na
var label wemposlabelx2 = na
var label wemneglabelx2 = na
weekposemcalc = wclose + emweek
weeknegemcalc = wclose - emweek
weekposemx2calc = wclose + (2*emweek)
weeknegemx2calc = wclose - (2*emweek)
//Weekly EM Plots//
if wclose[1] != wclose
line.set_x2(wcloseline, bar_index)
line.set_x2(posemline, bar_index)
line.set_x2(negemline, bar_index)
line.set_x2(posemlinex2, bar_index)
line.set_x2(negemlinex2, bar_index)
line.set_extend(wcloseline, extend.none)
line.set_extend(posemline, extend.none)
line.set_extend(negemline, extend.none)
line.set_extend(posemlinex2, extend.none)
line.set_extend(negemlinex2, extend.none)
label.delete(wcloselabel)
label.delete(wemposlabel)
label.delete(wemneglabel)
label.delete(wemposlabelx2)
label.delete(wemneglabelx2)
//Expected Move Lines
wcloseline := line.new(bar_index, wclose, bar_index, wclose, color=wclosecolor, style=lineStyleem, width=linewidth)
posemline := line.new(bar_index, weekposemcalc, bar_index, weekposemcalc, color=posemcolor, style=lineStyleem, width=linewidth)
negemline := line.new(bar_index, weeknegemcalc, bar_index, weeknegemcalc, color=negemcolor, style=lineStyleem, width=linewidth)
posemlinex2 := line.new(bar_index, weekposemx2calc, bar_index, weekposemx2calc, color=posemcolor, style=lineStyle2, width=linewidth)
negemlinex2 := line.new(bar_index, weeknegemx2calc, bar_index, weeknegemx2calc, color=negemcolor, style=lineStyle2, width=linewidth)
line.delete(wcloseline[1])
line.delete(posemline[1])
line.delete(negemline[1])
line.delete(posemlinex2[1])
line.delete(negemlinex2[1])
if showweekem != true
line.delete(wcloseline)
line.delete(posemline)
line.delete(negemline)
line.delete(posemlinex2)
line.delete(negemlinex2)
if show2sigmaem != true
line.delete(posemlinex2)
line.delete(negemlinex2)
if linesright == true
line.set_x2(wcloseline, bar_index)
line.set_x2(posemline, bar_index)
line.set_x2(negemline, bar_index)
line.set_x2(posemlinex2, bar_index)
line.set_x2(negemlinex2, bar_index)
line.set_extend(wcloseline, extend.right)
line.set_extend(posemline, extend.right)
line.set_extend(negemline, extend.right)
line.set_extend(posemlinex2, extend.right)
line.set_extend(negemlinex2, extend.right)
//Expected Move Labels
if showlabels == true
wcloselabel := label.new(bar_index, wclose, 'WC: ' + str.tostring(wclose, '#.##'), style=label.style_none)
wemposlabel := label.new(bar_index, weekposemcalc, '+WEM ' + str.tostring(weekposemcalc, '#.##'), style=label.style_none)
wemneglabel := label.new(bar_index, weeknegemcalc, '-WEM: ' + str.tostring(weeknegemcalc, '#.##'), style=label.style_none)
wemposlabelx2 := label.new(bar_index, weekposemx2calc, '+2WEM): ' + str.tostring(weekposemx2calc, '#.##'), style=label.style_none)
wemneglabelx2 := label.new(bar_index, weeknegemx2calc, '-2WEM): ' + str.tostring(weeknegemx2calc, '#.##'), style=label.style_none)
label.set_textcolor(wcloselabel, labelcolor)
label.set_textcolor(wemposlabel, labelcolor)
label.set_textcolor(wemneglabel, labelcolor)
label.set_textcolor(wemposlabelx2, labelcolor)
label.set_textcolor(wemneglabelx2, labelcolor)
if show2sigmaem != true
label.delete(wemposlabelx2)
label.delete(wemneglabelx2)
if not na(wcloseline) and line.get_x2(wcloseline) != bar_index
line.set_x2(wcloseline, bar_index)
line.set_x2(posemline, bar_index)
line.set_x2(negemline, bar_index)
line.set_x2(posemlinex2, bar_index)
line.set_x2(negemlinex2, bar_index)
label.set_x(wcloselabel, bar_index + labelposition)
label.set_x(wemposlabel, bar_index + labelposition)
label.set_x(wemneglabel, bar_index + labelposition)
label.set_x(wemposlabelx2, bar_index + labelposition)
label.set_x(wemneglabelx2, bar_index + labelposition)
////Daily 0DTE EM////
dclose = request.security(syminfo.tickerid, "D", close[1], barmerge.gaps_off, barmerge.lookahead_on)
var line dcloseline = na
var line pos0dteline = na
var line neg0dteline = na
var line pos0dtelinex2 = na
var line neg0dtelinex2 = na
var label dcloselabel = na
var label pos0dtelabel = na
var label neg0dtelabel = na
var label pos0dtelabelx2 = na
var label neg0dtelabelx2 = na
pos0dteemcalc = dclose + em0dte
neg0dteemcalc = dclose - em0dte
pos0dteemx2calc = dclose + (2*em0dte)
neg0dteemx2calc = dclose - (2*em0dte)
//Daily 0DTE EM Plots//
if dclose[1] != dclose
line.set_x2(dcloseline, bar_index)
line.set_x2(pos0dteline, bar_index)
line.set_x2(neg0dteline, bar_index)
line.set_x2(pos0dtelinex2, bar_index)
line.set_x2(neg0dtelinex2, bar_index)
line.set_extend(dcloseline, extend.none)
line.set_extend(pos0dteline, extend.none)
line.set_extend(neg0dteline, extend.none)
line.set_extend(pos0dtelinex2, extend.none)
line.set_extend(neg0dtelinex2, extend.none)
label.delete(dcloselabel)
label.delete(pos0dtelabel)
label.delete(neg0dtelabel)
label.delete(pos0dtelabelx2)
label.delete(neg0dtelabelx2)
//Expected Move Lines
dcloseline := line.new(bar_index, dclose, bar_index, dclose, color=wclosecolor, style=lineStyle0dte, width=linewidth)
pos0dteline := line.new(bar_index, pos0dteemcalc, bar_index, pos0dteemcalc, color=posemcolor, style=lineStyle0dte, width=linewidth)
neg0dteline := line.new(bar_index, neg0dteemcalc, bar_index, neg0dteemcalc, color=negemcolor, style=lineStyle0dte, width=linewidth)
pos0dtelinex2 := line.new(bar_index, pos0dteemx2calc, bar_index, pos0dteemx2calc, color=posemcolor, style=lineStyle2, width=linewidth)
neg0dtelinex2 := line.new(bar_index, neg0dteemx2calc, bar_index, neg0dteemx2calc, color=negemcolor, style=lineStyle2, width=linewidth)
line.delete(dcloseline[1])
line.delete(pos0dteline[1])
line.delete(neg0dteline[1])
line.delete(pos0dtelinex2[1])
line.delete(neg0dtelinex2[1])
if show0dteem != true
line.delete(dcloseline)
line.delete(pos0dteline)
line.delete(neg0dteline)
line.delete(pos0dtelinex2)
line.delete(neg0dtelinex2)
if show2sigma0dte != true
line.delete(pos0dtelinex2)
line.delete(neg0dtelinex2)
if linesright == true
line.set_x2(dcloseline, bar_index)
line.set_x2(pos0dteline, bar_index)
line.set_x2(neg0dteline, bar_index)
line.set_x2(pos0dtelinex2, bar_index)
line.set_x2(neg0dtelinex2, bar_index)
line.set_extend(dcloseline, extend.right)
line.set_extend(pos0dteline, extend.right)
line.set_extend(neg0dteline, extend.right)
line.set_extend(pos0dtelinex2, extend.right)
line.set_extend(neg0dtelinex2, extend.right)
//Expected Move Labels
if showlabels and show0dteem == true
dcloselabel := label.new(bar_index, dclose, 'DC: ' + str.tostring(dclose, '#.##'), style=label.style_none)
pos0dtelabel := label.new(bar_index, pos0dteemcalc, '0DTE +EM: ' + str.tostring(pos0dteemcalc, '#.##'), style=label.style_none)
neg0dtelabel := label.new(bar_index, neg0dteemcalc, '0DTE -EM: ' + str.tostring(neg0dteemcalc, '#.##'), style=label.style_none)
pos0dtelabelx2 := label.new(bar_index, pos0dteemx2calc, '0DTE +(2EM): ' + str.tostring(pos0dteemx2calc, '#.##'), style=label.style_none)
neg0dtelabelx2 := label.new(bar_index, neg0dteemx2calc, '0DTE -(2EM): ' + str.tostring(neg0dteemx2calc, '#.##'), style=label.style_none)
label.set_textcolor(dcloselabel, labelcolor)
label.set_textcolor(pos0dtelabel, labelcolor)
label.set_textcolor(neg0dtelabel, labelcolor)
label.set_textcolor(pos0dtelabelx2, labelcolor)
label.set_textcolor(neg0dtelabelx2, labelcolor)
if show2sigma0dte != true
label.delete(pos0dtelabelx2)
label.delete(neg0dtelabelx2)
if not na(dcloseline) and line.get_x2(dcloseline) != bar_index
line.set_x2(dcloseline, bar_index)
line.set_x2(pos0dteline, bar_index)
line.set_x2(neg0dteline, bar_index)
line.set_x2(pos0dtelinex2, bar_index)
line.set_x2(neg0dtelinex2, bar_index)
label.set_x(dcloselabel, bar_index + labelposition)
label.set_x(pos0dtelabel, bar_index + labelposition)
label.set_x(neg0dtelabel, bar_index + labelposition)
label.set_x(pos0dtelabelx2, bar_index + labelposition)
label.set_x(neg0dtelabelx2, bar_index + labelposition) |
Satoshi Indicator | https://www.tradingview.com/script/pt2UikHF/ | Seungdori_ | https://www.tradingview.com/u/Seungdori_/ | 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/
// © Seungdori_
//@version=5
indicator('Satoshi Indicator', overlay=false, precision = 8)
sym = input.symbol(defval = 'BINANCE:BTCUSDT', title = 'Pair', confirm = false)
ma_on = input.bool(defval = true, title = 'Moving Average On/Off', group = 'MA')
len = input.int(defval = 200, title = 'SMA Length', minval = 1, group = 'MA')
filter_indicator = input.string(defval = 'RSI', title = 'Color Satoshi plot with Indicators', options = ['None','RSI', 'Stochastic RSI', 'Disparity', 'Slope'], group = 'Color')
BTC = request.security(sym, timeframe.period, close)
satoshi = (close/BTC)
satoshi_high = (high/BTC)
satoshi_Low = (low/BTC)
ma = ta.sma(source = satoshi, length = len)
//Add on
rsi = ta.rsi(satoshi, length = 14)
stochastic_rsi_k = ta.sma(ta.stoch(rsi, rsi, rsi, 14), 3)
stochastic_rsi_d = ta.sma(stochastic_rsi_k, 3)
disparity = (satoshi - ma) / ma * 100
dis_high = ta.highest(disparity, 100)
dis_low = ta.lowest(disparity, 100)
dis_avg = (dis_high - dis_low)
slope = (ta.hma(satoshi, len) - ta.hma(satoshi, len)[1])
slope_high = ta.highest(slope, len)
slope_low = ta.lowest(slope, len)
mycolor = input.color(color.teal, 'Option Off Color', group = 'Color')
color_overbought= input.color(color.red, 'Overbought', group = 'Color')
color_oversold = input.color(color.green, 'Oversold', group = 'Color')
if filter_indicator == 'RSI'
mycolor := color.from_gradient(rsi, 25, 75, color.new(color_oversold, 0), color.new(color_overbought, 0))
if filter_indicator == 'Stochastic RSI'
mycolor := color.from_gradient(stochastic_rsi_k, 20, 80, color.new(color_oversold, 0), color.new(color_overbought, 0))
if filter_indicator == 'Disparity'
mycolor := color.from_gradient(disparity, -dis_avg, dis_avg, color.new(color_oversold, 0), color.new(color_overbought, 0))
if filter_indicator == 'Slope'
mycolor := color.from_gradient(slope,slope_low,slope_high, color.new(color_oversold, 0), color.new(color_overbought, 0))
//==plots
plot(satoshi, title='Satoshi', linewidth=1, color= mycolor)
plot(ma_on ? ma : na, color = color.new(color.white, 30), title = 'Moving Average', style = plot.style_line)
//==alert
crossover = ta.crossover(satoshi, ma)
crossunder = ta.crossunder(satoshi, ma)
alertcondition(crossover, title = 'Satoshi Crossover MA')
alertcondition(crossunder, title = 'Satoshi Crossunder MA') |
Vigilant Asset Allocation G4 Backtesting Engine | https://www.tradingview.com/script/WzCLgqV0-Vigilant-Asset-Allocation-G4-Backtesting-Engine/ | jamiedubauskas | https://www.tradingview.com/u/jamiedubauskas/ | 18 | 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/
// © jamiedubauskas
//@version=5
indicator("Vigilant Asset Allocation G4 Backtesting Engine", overlay=false, max_bars_back = 5000)
// keeping track of the current monthly holding
varip current_holding = "none"
varip prev_holding = "none"
// checking if it is the start of a new month
bool is_new_month = month[1] != month
// input for starting cash
starting_cash = input.float(title = "Starting Cash", defval = 100000.0, minval = 0.0)
// keeping track of the returns
varip cum_return = starting_cash
varip spy_return = starting_cash
// calculate total trades and max drawdown
varip total_trades = 0
varip model_ath = starting_cash
varip model_max_drawdown = 0.0
varip spy_ath = starting_cash
varip spy_max_drawdown = 0.0
// input for asking if you want to see a comparison of the model to a buy and hold of SPY
show_spy_comparison = input.bool(title = "Show SPY", defval = true, tooltip = "Show the performance of SPY against this model to compare the performance of this model to a buy & hold")
// inputs for the timeframe, lookback periods, and the ticker requests
timeframe_i = input.timeframe(title = "Timeframe", defval = "1M")
// inputs for the risk and safety tickers
risk_ticker1_sym = input.string(title = "Risk Ticker 1 Symbol", defval = "SPY")
risk_ticker2_sym = input.string(title = "Rick Ticker 2 Symbol", defval = "EFA")
risk_ticker3_sym = input.string(title = "Rick Ticker 3 Symbol", defval = "EEM")
risk_ticker4_sym = input.string(title = "Rick Ticker 4 Symbol", defval = "AGG")
safety_ticker1_sym = input.string(title = "Safety Ticker 1 Symbol", defval = "LQD")
safety_ticker2_sym = input.string(title = "Safety Ticker 2 Symbol", defval = "IEF")
safety_ticker3_sym = input.string(title = "Safety Ticker 3 Symbol", defval = "BIL")
// getting the monthly values of the tickers for daily backtesting
risk_ticker1 = request.security(symbol = risk_ticker1_sym, timeframe = timeframe_i, expression = close)
risk_ticker2 = request.security(symbol = risk_ticker2_sym, timeframe = timeframe_i, expression = close)
risk_ticker3 = request.security(symbol = risk_ticker3_sym, timeframe = timeframe_i, expression = close)
risk_ticker4 = request.security(symbol = risk_ticker4_sym, timeframe = timeframe_i, expression = close)
safety_ticker1 = request.security(symbol = safety_ticker1_sym, timeframe = timeframe_i, expression = close)
safety_ticker2 = request.security(symbol = safety_ticker2_sym, timeframe = timeframe_i, expression = close)
safety_ticker3 = request.security(symbol = safety_ticker3_sym, timeframe = timeframe_i, expression = close)
// grabbing SPY ticker info for a comparison to a buy & hold
spy_ticker = request.security(symbol = "SPY", timeframe = timeframe_i, expression = close)
// getting daily returns for backtesting (I tried this and TradingView says I was referencing too much data so daily backtesting is a bust)
//daily_return_risk_ticker1 = ((risk_ticker1[0] / risk_ticker1[1]) - 1) * 100
//daily_return_risk_ticker2 = ((risk_ticker2[0] / risk_ticker2[1]) - 1) * 100
//daily_return_risk_ticker3 = ((risk_ticker3[0] / risk_ticker3[1]) - 1) * 100
//daily_return_risk_ticker4 = ((risk_ticker4[0] / risk_ticker4[1]) - 1) * 100
//daily_return_safety_ticker1 = ((safety_ticker1[0] / safety_ticker1[1]) - 1) * 100
//daily_return_safety_ticker2 = ((safety_ticker2[0] / safety_ticker2[1]) - 1) * 100
//daily_return_safety_ticker3 = ((safety_ticker3[0] / safety_ticker3[1]) - 1) * 100
monthly_return_risk_ticker1 = ((risk_ticker1[0] / risk_ticker1[1]) - 1) * 100
monthly_return_risk_ticker2 = ((risk_ticker2[0] / risk_ticker2[1]) - 1) * 100
monthly_return_risk_ticker3 = ((risk_ticker3[0] / risk_ticker3[1]) - 1) * 100
monthly_return_risk_ticker4 = ((risk_ticker4[0] / risk_ticker4[1]) - 1) * 100
monthly_return_safety_ticker1 = ((safety_ticker1[0] / safety_ticker1[1]) - 1) * 100
monthly_return_safety_ticker2 = ((safety_ticker2[0] / safety_ticker2[1]) - 1) * 100
monthly_return_safety_ticker3 = ((safety_ticker3[0] / safety_ticker3[1]) - 1) * 100
monthly_return_spy = ((spy_ticker[0] / spy_ticker[1]) - 1) * 100
// calculate momentum scores for each risk asset
momentumScoreRiskAsset1 = (12*(risk_ticker1/risk_ticker1[1]))+(4*(risk_ticker1/risk_ticker1[3]))+(2*(risk_ticker1/risk_ticker1[6]))+(risk_ticker1/risk_ticker1[12])-19
momentumScoreRiskAsset2 = (12*(risk_ticker2/risk_ticker2[1]))+(4*(risk_ticker2/risk_ticker2[3]))+(2*(risk_ticker2/risk_ticker2[6]))+(risk_ticker2/risk_ticker2[12])-19
momentumScoreRiskAsset3 = (12*(risk_ticker3/risk_ticker3[1]))+(4*(risk_ticker3/risk_ticker3[3]))+(2*(risk_ticker3/risk_ticker3[6]))+(risk_ticker3/risk_ticker3[12])-19
momentumScoreRiskAsset4 = (12*(risk_ticker4/risk_ticker4[1]))+(4*(risk_ticker4/risk_ticker4[3]))+(2*(risk_ticker4/risk_ticker4[6]))+(risk_ticker4/risk_ticker4[12])-19
// calculate momentum scores for each safety asset
momentumScoreSafetyAsset1 = (12*(safety_ticker1/safety_ticker1[1]))+(4*(safety_ticker1/safety_ticker1[3]))+(2*(safety_ticker1/safety_ticker1[6]))+(safety_ticker1/safety_ticker1[12])-19
momentumScoreSafetyAsset2 = (12*(safety_ticker2/safety_ticker2[1]))+(4*(safety_ticker2/safety_ticker2[3]))+(2*(safety_ticker2/safety_ticker2[6]))+(safety_ticker2/safety_ticker2[12])-19
momentumScoreSafetyAsset3 = (12*(safety_ticker3/safety_ticker3[1]))+(4*(safety_ticker3/safety_ticker3[3]))+(2*(safety_ticker3/safety_ticker3[6]))+(safety_ticker3/safety_ticker3[12])-19
// calculate maximum momentum score of each asset type
maxRiskAssetMomentumScore = math.max(momentumScoreRiskAsset1, momentumScoreRiskAsset2, momentumScoreRiskAsset3, momentumScoreRiskAsset4)
maxSafetyAssetMomentumScore = math.max(momentumScoreSafetyAsset1, momentumScoreRiskAsset2, momentumScoreRiskAsset3)
// determine which asset of each type has the highest momentum score
highestMomentumScoreRiskAsset = (momentumScoreRiskAsset1 == maxRiskAssetMomentumScore) ? risk_ticker1_sym : (momentumScoreRiskAsset2 == maxRiskAssetMomentumScore) ? risk_ticker2_sym : (momentumScoreRiskAsset3 == maxRiskAssetMomentumScore) ? risk_ticker3_sym : risk_ticker4_sym
highestMomentumScoreSafetyAsset = (momentumScoreSafetyAsset1 == maxSafetyAssetMomentumScore) ? safety_ticker1_sym : (momentumScoreSafetyAsset2 == maxSafetyAssetMomentumScore) ? safety_ticker2_sym : safety_ticker3_sym
// grabbing the monthly close of the highestMomentumScoreRiskAsset and highestMomentumScoreSafetyAsset
highestMomentumScoreRiskAssetDailyClose = switch highestMomentumScoreRiskAsset
risk_ticker1_sym => risk_ticker1[0]
risk_ticker2_sym => risk_ticker2[0]
risk_ticker3_sym => risk_ticker3[0]
risk_ticker4_sym => risk_ticker4[0]
highestMomentumScoreSafetyAssetDailyClose = switch highestMomentumScoreSafetyAsset
safety_ticker1_sym => safety_ticker1[0]
safety_ticker2_sym => safety_ticker2[0]
safety_ticker3_sym => safety_ticker3[0]
// setting the color of the line
useRainbowColoring = input.bool(title = "Use Rainbow Coloring?", defval = true, tooltip = "Enables you to see the color of the respective ticker in the equity curve")
risk_ticker1_color = input.color(title = "Risk Ticker 1 Color", defval = color.new(color.red, 0))
risk_ticker2_color = input.color(title = "Risk Ticker 2 Color", defval = color.new(color.aqua, 0))
risk_ticker3_color = input.color(title = "Risk Ticker 3 Color", defval = color.new(color.green, 0))
risk_ticker4_color = input.color(title = "Risk Ticker 4 Color", defval = color.new(color.yellow, 0))
safety_ticker1_color = input.color(title = "Safety Ticker 1 Color", defval = color.new(color.purple, 0))
safety_ticker2_color = input.color(title = "Safety Ticker 2 Color", defval = color.new(color.maroon, 0))
safety_ticker3_color = input.color(title = "Safety Ticker 3 Color", defval = color.new(color.olive, 0))
def_color = input.color(title = "Default Color", defval = color.new(color.white, 0))
// setting current holding
// risk-on entry signal occurs when the momentum of each risk asset is greater than 0
if(momentumScoreRiskAsset1 > 0 and momentumScoreRiskAsset2 > 0 and momentumScoreRiskAsset3 > 0 and momentumScoreRiskAsset4 > 0) and is_new_month
// determine if there is already a position open
if(current_holding != "none")
// if current holding string matches, (i.e. position is already held), just set the previous holding
if(current_holding == highestMomentumScoreRiskAsset)
prev_holding := current_holding
// if current holding string does not match, set it to the current highest momentum risk asset
else if(current_holding != highestMomentumScoreRiskAsset)
prev_holding := current_holding
current_holding := highestMomentumScoreRiskAsset
total_trades += 1
// if no position is currently held, maximally invest in highest momentum risk asset
else
current_holding := highestMomentumScoreRiskAsset
total_trades += 1
// risk-off entry signal occurs when any of the risk asset momentums are less than 0
else if(momentumScoreRiskAsset1 < 0 or momentumScoreRiskAsset2 < 0 or momentumScoreRiskAsset3 < 0 or momentumScoreRiskAsset4 < 0) and is_new_month
// determine if there is already a position open
if(current_holding != "none")
// if current holding string matches, (i.e. position is already held), just set the previous holding
if(current_holding == highestMomentumScoreSafetyAsset)
prev_holding := current_holding
// if current holding string does not match, close open position and reopen in current highest momentum safety asset
if(current_holding != highestMomentumScoreSafetyAsset)
prev_holding := current_holding
current_holding := highestMomentumScoreSafetyAsset
total_trades += 1
// if no position is currently held, maximally invest in highest momentum safety asset
else
current_holding := highestMomentumScoreSafetyAsset
total_trades += 1
// grabbing the bars since the last month change
//since_month_change = ta.barssince()
// input for trading fees
trading_fee_input = input.float(title = "Trading Fee %", defval = 0.0)
trading_fee = 1 - (trading_fee_input / 100)
// boolean expression to check if all tickers have "started"
start_time = input.time(title = "Model Start", defval = timestamp("02 June 2008 00:00 +300"))
all_start = (time(timeframe_i) >= start_time)
// getting the bar count of the model
model_bar_count = ta.cum(all_start ? 1 : 0)
int current_model_bar_count = all_start ? math.round(model_bar_count[0]) : 1
// ***********************************************************
//
// MODEL AND CALCULATING STATS ON IT
//
// ***********************************************************
if current_holding == "none" and all_start
cum_return := starting_cash
else if current_holding == risk_ticker1_sym and all_start
if prev_holding == current_holding
cum_return := cum_return[1] * ((monthly_return_risk_ticker1[0] / 100) + 1)
else
cum_return := cum_return[1] * ((monthly_return_risk_ticker1[0] / 100) + 1) * trading_fee
else if current_holding == risk_ticker2_sym and all_start
if prev_holding == current_holding
cum_return := cum_return[1] * ((monthly_return_risk_ticker2[0] / 100) + 1)
else
cum_return := cum_return[1] * ((monthly_return_risk_ticker2[0] / 100) + 1) * trading_fee
else if current_holding == risk_ticker3_sym and all_start
if prev_holding == current_holding
cum_return := cum_return[1] * ((monthly_return_risk_ticker3[0] / 100) + 1)
else
cum_return := cum_return[1] * ((monthly_return_risk_ticker3[0] / 100) + 1) * trading_fee
else if current_holding == risk_ticker4_sym and all_start
if prev_holding == current_holding
cum_return := cum_return[1] * ((monthly_return_risk_ticker4[0] / 100) + 1)
else
cum_return := cum_return[1] * ((monthly_return_risk_ticker4[0] / 100) + 1) * trading_fee
else if current_holding == safety_ticker1_sym and all_start
if prev_holding == current_holding
cum_return := cum_return[1] * ((monthly_return_safety_ticker1[0] / 100) + 1)
else
cum_return := cum_return[1] * ((monthly_return_safety_ticker1[0] / 100) + 1) * trading_fee
else if current_holding == safety_ticker2_sym and all_start
if prev_holding == current_holding
cum_return := cum_return[1] * ((monthly_return_safety_ticker2[0] / 100) + 1)
else
cum_return := cum_return[1] * ((monthly_return_safety_ticker2[0] / 100) + 1) * trading_fee
else if current_holding == safety_ticker3_sym and all_start
if prev_holding == current_holding
cum_return := cum_return[1] * ((monthly_return_safety_ticker3[0] / 100) + 1)
else
cum_return := cum_return[1] * ((monthly_return_safety_ticker3[0] / 100) + 1) * trading_fee
// calculating the sharpe ratio and grabbing the risk free rate
risk_free_rate_selection = input.string(title = "Risk Free Rate", options = ["Standard 2%","3M TBill","6M TBill","1Y TBill","2Y TBill","3Y TBill","5Y TBill","10Y TBill","30Y TBill"], defval = "Standard 2%", tooltip = "The risk free rate used when calculating Sharpe & Sortino Ratio.")
risk_free_rate_selection_ticker = switch risk_free_rate_selection
"Standard 2%" => "2"
"3M TBill" => "DTB3"
"6M TBill" => "DTB6"
"1Y TBill" => "DTB1YR"
"2Y TBill" => "DGS2"
"3Y TBill" => "DGS3"
"5Y TBill" => "DGS5"
"10Y TBill" => "DGS10"
"30Y TBill" => "DGS30"
risk_free_rate = risk_free_rate_selection_ticker == "2" ? 0.02 : request.security(symbol = risk_free_rate_selection_ticker, timeframe = timeframe_i, expression = close / 100)
// based on number of trading years since inception (a.k.a based on 252 trading days in a year)
num_of_years_since_inception = current_model_bar_count / 12
model_average_return = math.pow(cum_return[0] / cum_return[current_model_bar_count], (1 / num_of_years_since_inception)) - 1
//plot(model_average_return, color = color.new(color.blue,0))
// hand-calculating standard deviation for Sharpe Ratio
model_1yr_pnl = current_model_bar_count > 12 ? (cum_return[0] / cum_return[11]) - 1 : model_average_return
model_variation_squared = math.pow((model_1yr_pnl - model_average_return), 2)
model_total_variation_squared = math.sum(model_variation_squared, 12)
model_stddev = math.sqrt(model_total_variation_squared / current_model_bar_count)
//raw_model_stddev = ta.stdev(raw_cum_return, 365)
sharpe_ratio = (model_average_return - risk_free_rate) / model_stddev
//plot(sharpe_ratio, color = color.new(color.blue,0))
// getting Sortino Ratio
model_average_downside_return = model_average_return
if model_average_return > 0
model_average_downside_return := 0
else
model_average_downside_return := model_average_return
sortino_std_dev = ta.stdev(model_average_downside_return, current_model_bar_count)
sortino_ratio = (model_average_return - risk_free_rate) / sortino_std_dev
//plot(sortino_ratio, color = color.new(color.purple,0))
// getting CAGR (already calculated it as model_average_return bc its the same formula)
cagr = model_average_return * 100
// calculating the drawdown
if cum_return[0] > model_ath
model_ath := cum_return[0]
model_drawdown = ((cum_return / model_ath) - 1) * 100
if model_drawdown[0] < model_max_drawdown
model_max_drawdown := model_drawdown[0]
// ***********************************************************
//
// STANDARDIZED SPY AND CALCULATING STATS ON IT
//
// ***********************************************************
// getting the daily return of spy
if all_start
spy_return := ((monthly_return_spy / 100) + 1) * spy_return[1]
spy_average_return = math.pow(spy_return[0] / spy_return[current_model_bar_count], (1 / num_of_years_since_inception)) - 1
// hand-calculating standard deviation for Sharpe Ratio
spy_1yr_pnl = current_model_bar_count > 12 ? (spy_return[0] / spy_return[11]) - 1 : spy_average_return
spy_variation_squared = math.pow((spy_1yr_pnl - spy_average_return), 2)
spy_total_variation_squared = math.sum(spy_variation_squared, 12)
spy_stddev = math.sqrt(spy_total_variation_squared / current_model_bar_count)
spy_sharpe_ratio = (spy_average_return - risk_free_rate) / spy_stddev
// getting Sortino Ratio
spy_average_downside_return = spy_average_return
if spy_average_return > 0
spy_average_downside_return := 0
else
spy_average_downside_return := spy_average_return
spy_sortino_std_dev = ta.stdev(spy_average_downside_return, current_model_bar_count)
spy_sortino_ratio = (spy_average_return - risk_free_rate) / spy_sortino_std_dev
spy_cagr = spy_average_return * 100
// calculating the drawdown
if spy_return[0] > spy_ath
spy_ath := spy_return[0]
spy_drawdown = ((spy_return / spy_ath) - 1) * 100
if spy_drawdown[0] < spy_max_drawdown
spy_max_drawdown := spy_drawdown[0]
// ***********************************************************
//
// PLOTTING ANALYTICS TABLE AND CHARTS FOR ALL MODELS
//
// ***********************************************************
// plotting the analytics table
var analytics_table = table.new(position = position.bottom_right, columns = 3, rows = 6, frame_color = color.new(color.white, 0), frame_width = 2, border_width = 1, border_color = color.new(color.white,0))
if barstate.islast
// setting the labels of the table
table.cell(table_id = analytics_table, column = 0, row = 0, text = "Trading Model Stats", bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.small)
table.cell(table_id = analytics_table, column = 1, row = 0, text = "Model", bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.small)
table.cell(table_id = analytics_table, column = 2, row = 0, text = "SPY", bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.small)
table.cell(table_id = analytics_table, column = 0, row = 1, text = "CAGR", bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.small)
table.cell(table_id = analytics_table, column = 0, row = 2, text = "# of Trades", bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.small)
table.cell(table_id = analytics_table, column = 0, row = 3, text = "Max Drawdown", bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.small)
table.cell(table_id = analytics_table, column = 0, row = 4, text = "Sharpe Ratio", bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.small)
table.cell(table_id = analytics_table, column = 0, row = 5, text = "Sortino Ratio", bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.small)
// setting the values of the table for the raw model statistics
table.cell(table_id = analytics_table, column = 1, row = 1, text = str.format("{0,number,#.##}%", cagr), bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.normal)
table.cell(table_id = analytics_table, column = 1, row = 2, text = str.tostring(total_trades), bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.normal)
table.cell(table_id = analytics_table, column = 1, row = 3, text = str.format("{0,number,#.##}%", model_max_drawdown), bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.normal)
table.cell(table_id = analytics_table, column = 1, row = 4, text = str.format("{0,number,#.###}", sharpe_ratio), bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.normal)
table.cell(table_id = analytics_table, column = 1, row = 5, text = str.format("{0,number,#.###}", sortino_ratio), bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.normal)
// setting the values of the table for the BTC statistics
table.cell(table_id = analytics_table, column = 2, row = 1, text = str.format("{0,number,#.##}%", spy_cagr), bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.normal)
table.cell(table_id = analytics_table, column = 2, row = 2, text = "-", bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.normal)
table.cell(table_id = analytics_table, column = 2, row = 3, text = str.format("{0,number,#.##}%", spy_max_drawdown), bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.normal)
table.cell(table_id = analytics_table, column = 2, row = 4, text = str.format("{0,number,#.###}", spy_sharpe_ratio), bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.normal)
table.cell(table_id = analytics_table, column = 2, row = 5, text = str.format("{0,number,#.###}", spy_sortino_ratio), bgcolor = color.new(color.green,20), text_color = color.new(color.white,0), text_size = size.normal)
holding_color = switch current_holding
risk_ticker1_sym => risk_ticker1_color
risk_ticker2_sym => risk_ticker2_color
risk_ticker3_sym => risk_ticker3_color
risk_ticker4_sym => risk_ticker4_color
safety_ticker1_sym => safety_ticker1_color
safety_ticker2_sym => safety_ticker2_color
safety_ticker3_sym => safety_ticker3_color
plot_color = useRainbowColoring ? holding_color : def_color
plot(series = cum_return, color = plot_color, title = "Model")
plot(series = all_start and show_spy_comparison ? spy_return : na, color = color.new(color.white,0), title = "SPY")
// ***********************************************************
//
// MAKING TRADINGVIEW ALERTS FOR THE STRATEGY
//
// ***********************************************************
// alert for ticker1 outperforming
//if ticker1_outperf_crossover
// alert(freq = alert.freq_once_per_bar_close, message = "Ticker 1 (" + str.tostring(ticker1_sym) + ") is outperforming. BUY")
// alert for ticker2 outperforming
//if ticker2_outperf_crossover
// alert(freq = alert.freq_once_per_bar_close, message = "Ticker 2 (" + str.tostring(ticker2_sym) + ") is outperforming. BUY")
|
Stx Ma-Trend Finder | https://www.tradingview.com/script/IAfZnyND/ | Strambatax | https://www.tradingview.com/u/Strambatax/ | 35 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Strambatax
// ████████ ██ ██
// ██░██░░░ ██ ██
// ████████░ ██
// ██ ██ ██ ██
// ████████ ██ ██
//@version=5
indicator("Stx Ma-Trend Finder", overlay = true)
ma_type = input.string("hma", "MA type", group="MA Settings", options=["sma", "ema", "hma", "rma", "wma", "swma", "vwma", "tema"])
ma_length = input.int(100, "ma length", group="MA Settings")
ma_source = input.source(close, "source", group="MA Settings")
ma_slope_filter_ratio = input.float(0.053, "ma slope ratio", step=0.001, minval=0, maxval = 1.000, group="MA Settings")
// ---------- @Misc Functions ---------- \\
tema(src, len) =>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
(3 * ema1) - (3 * ema2) + ema3
ma_by_type(src, len, mode) =>
switch str.lower(mode)
"sma" => ta.sma(src, len)
"ema" => ta.ema(src, len)
"hma" => ta.hma(src, len)
"rma" => ta.rma(src, len)
"wma" => ta.wma(src, len)
"swma" => ta.swma(src)
"vwma" => ta.vwma(src, len)
"hull" => ta.wma((2 * ta.wma(src, len / 2)) - ta.wma(src, len), math.round(math.sqrt(len)))
"tema" => tema(src, len)
=> ta.sma(src, len)
// ---------- @ENd Misc Functions ---------- \\
ma = ma_by_type(ma_source, ma_length, ma_type)
// max ma spread observed from the first bar
max_ma_spread = ta.max(math.abs(ma - ma[1]))
ma_spread = ma - ma[1]
// level of slope is proportional to the
// inclination of the slope
ma_slope_level = (ma_spread / max_ma_spread)
ma_slope_bull = ma_slope_level > ma_slope_filter_ratio
ma_slope_bear = ma_slope_level < -ma_slope_filter_ratio
ma_color = ma_slope_bull ? color.green : ma_slope_bear ? color.red : color.rgb(0, 74, 212)
plot(ma, color = ma_color, title = "Ma line") |
Efficiency Gaps | https://www.tradingview.com/script/pCKE0vLT-Efficiency-Gaps/ | BobBasic | https://www.tradingview.com/u/BobBasic/ | 80 | 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/
// © BobBasic
//@version=5
indicator("Efficiency Gaps", overlay=true, max_boxes_count=60, max_lines_count=60)
multi = input.float(0.01, "ATR Multiplier", 0.01, 1, step=0.01)
period = input.int(21, "ATR Period")
upbox_color = input.color(color.rgb(76, 175, 79, 95), "Box Up")
downbox_color = input.color(color.rgb(255, 82, 82, 95), "Box Down")
topline_color = input.color(color.rgb(76, 175, 79), "Top Line")
bottomline_color = input.color(color.rgb(255, 82, 82), "Bottom Line")
_atr = ta.atr(period)
var upboxes = array.new<box>()
var downboxes = array.new<box>()
var toplines = array.new<line>()
var bottomlines = array.new<line>()
if high[2] < low and (low - high[2]) > _atr * multi
b = box.new(left=bar_index -2, bottom=high[2], right=bar_index, top=low, bgcolor=upbox_color, border_width=0, extend=extend.right)
l = line.new(bar_index -2, high[2], bar_index, high[2], color=topline_color, extend=extend.right)
array.push(upboxes, b)
array.push(toplines, l)
if low[2] > high and (low[2] - high) > _atr * multi
b = box.new(left=bar_index - 2, top=low[2], right=bar_index, bottom=high, bgcolor=downbox_color, border_width=0, extend=extend.right)
l = line.new(bar_index -2, low[2], bar_index, low[2], color=bottomline_color, extend=extend.right)
array.push(downboxes, b)
array.push(bottomlines, l)
for i = 0 to (array.size(upboxes) == 0 ? na : array.size(upboxes) - 1)
b = array.get(upboxes, i)
l = array.get(toplines, i)
if box.get_bottom(b) >= close
line.delete(l)
box.delete(b)
else if box.get_bottom(b) <= close and box.get_top(b) >= close
box.set_top(b, close)
else
array.get(upboxes, i)
array.get(toplines, i)
for i = 0 to (array.size(downboxes) == 0 ? na : array.size(downboxes) - 1)
b = array.get(downboxes, i)
l = array.get(bottomlines, i)
if box.get_top(b) <= close
line.delete(l)
box.delete(b)
else if box.get_top(b) >= close and box.get_bottom(b) <= close
box.set_bottom(b, close)
else
array.get(downboxes, i)
array.get(bottomlines, i)
|
Volume+ | https://www.tradingview.com/script/aVjJ6pRD-Volume/ | Electrified | https://www.tradingview.com/u/Electrified/ | 104 | 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/
// © Electrified
//@version=5
indicator("Volume+")
import Electrified/Color/9
MEASUREMENT = "Measurement"
len = input.int(400, "Length", group = MEASUREMENT, tooltip = "The number of bars to measure the weighted average.")
smooting = input.int(50, "Smoothing", group = MEASUREMENT, tooltip = "The number of bars to smooth out the averages.")
getMean(float source) =>
ta.sma(ta.wma(source, len), smooting)
mean = getMean(volume)
diff = nz(volume - mean)
diff2 = diff * diff
variance = getMean(diff2)
standardDeviation = math.sqrt(variance)
plus1 = mean + standardDeviation
plus2 = plus1 + standardDeviation
plus3 = plus2 + standardDeviation
HIGHLIGHT = "Bar Highlight"
BRIGHTEN = "Brighten", DARKEN = "Darken", NONE = "None"
highLight = input.string(BRIGHTEN, "Mode", group = HIGHLIGHT, options = [BRIGHTEN, DARKEN, NONE], tooltip = "How to affect the bar color when the volume exeeds one standard deviation.")
warmRange = plus3 - plus1
warmth = 100 * (volume - plus1) / warmRange
THEME = "Theme"
barTheme = input.color(color.gray, "Bar", group = THEME, inline = THEME)
meanColor = input.color(color.orange, "Average", group = THEME, inline = THEME)
devColor = input.color(color.yellow, "Deviation", group = THEME, inline = THEME)
barColor = switch highLight
NONE => barTheme
BRIGHTEN => barTheme.brighten(math.max(0, warmth))
DARKEN => barTheme.darken(math.max(0, warmth))
// Always lag by one bar to ensure that the current bar doesn't influence the value.
plot(plus1[1], "+1 Standard Deviation", color.new(devColor, 50), offset = 1, display = display.pane)
plot(plus2[1], "+2 Standard Deviations", color.new(devColor, 70), offset = 1, display = display.pane)
plot(plus3[1], "+3 Standard Deviations", color.new(devColor, 90), offset = 1, display = display.pane)
plot(volume, "Volume", barColor, style = plot.style_columns)
plot(mean[1], "Average (WMA)", color.new(meanColor, 30), offset = 1)
|
Parabolic Scalp Take Profit[ChartPrime] | https://www.tradingview.com/script/u2FmZMI9-Parabolic-Scalp-Take-Profit-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 372 | 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/
// © ExoMaven
//@version=5
indicator(title = "Parabolic Scalp Take Profit[ChartPrime]", shorttitle = "Parabolic Scalp Take Profit [V1]", overlay = true)
exponential_value = input.float(title = "Aggressiveness", defval = 125, minval = 101, maxval = 200, group = "Curved Line Settings") / 100
atr_len = 1000
float atr_mult = 10 / 100//input.float(title = "Starting Slope", defval = 10, minval = 10, maxval = 100, group = "Curved Line Settings") / 100
atr_value = ta.atr(atr_len)
start_time = input.time(title = "Starting Candle Time", defval = 1, group = "Setup Settings", confirm = true)
start_price = input.price(title = "Starting Price", defval = 1, group = "Setup Settings", confirm = true)
start_side = input.string(title = "Starting Trade Side", defval = "Long", options = ["Long", "Short"], group = "Setup Settings", confirm = true)
var bool in_trade = false
var float current_price = na
var float starting_slope = na
if not in_trade and barstate.isconfirmed
if start_time == time
in_trade := true
current_price := start_side == "Long" ? start_price - (atr_value * atr_mult * 2) : start_price + (atr_value * atr_mult * 2)
starting_slope := start_side == "Long" ? (start_price + math.abs(atr_value * atr_mult)) - start_price : (start_price - math.abs(atr_value * atr_mult)) - start_price
else if in_trade and barstate.isconfirmed
starting_slope *= exponential_value
current_price += starting_slope
top_of_candle = close > open ? close : open
bot_of_candle = close < open ? close : open
touching = start_side == "Long" ? bot_of_candle <= current_price : top_of_candle >= current_price
if touching
in_trade := false
plotshape(in_trade and not in_trade[1] and start_side == "Long", title = "Green Dot", style = shape.triangleup, location = location.belowbar, color = color.green, show_last = 20000, size = size.tiny)
plotshape(in_trade and not in_trade[1] and start_side == "Short", title = "Red Dot", style = shape.triangledown, location = location.abovebar, color = color.red, show_last = 20000, size = size.tiny)
plotshape(not in_trade and in_trade[1] and start_side == "Long", title = "Green Take Profit", style = shape.xcross, location = location.abovebar, color = color.blue, show_last = 20000, size = size.tiny)
plotshape(not in_trade and in_trade[1] and start_side == "Short", title = "Red Take Profit", style = shape.xcross, location = location.belowbar, color = color.blue, show_last = 20000, size = size.tiny)
|
7 Week Rule | https://www.tradingview.com/script/kDC1dFjU-7-Week-Rule/ | Amphibiantrading | https://www.tradingview.com/u/Amphibiantrading/ | 279 | 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("7 Week Rule", overlay = true)
// inputs
g1 = 'Moving Average'
len = input.int(10, "MA length", group = g1, inline = '1')
matype = input.string('SMA', 'MA type', options = ['EMA', 'SMA'], group = g1, inline = '1')
ma_color = input.color(color.red, 'MA Color', group = g1, inline = '2' )
ma_width = input.int(2, 'MA Line Width', 1, 5, 1, group = g1, inline = '2')
g2 = 'Display Options'
show_ma = input.bool(true, 'Show MA', group = g2, inline = '4')
show_table = input.bool(true,'Show Count Table', group = g2, inline = '5')
table_bg = input.color(color.white, 'Table Background Color', group = g2, inline = '6')
table_text = input.color(color.black, 'Table Background Color', group = g2, inline = '6')
i_tableypos = input.string("top", "Table Position", inline = "i1", options = ["top", "middle", "bottom"], group=g2)
i_tablexpos = input.string("right", "", inline = "i1", options = ["right","center", "left"], group=g2)
hlight = input.bool(true, 'Highlight Background', group = g2, inline = '7')
hcolor1 = input.color(color.new(color.aqua,85), 'Holding MA Background Color', group = g2, inline = '8')
hcolor2 = input.color(color.new(color.red,85), 'Violation Background Color', group = g2, inline = '8')
show_day_1 = input.bool(true, 'Show Day 1 of Count', group = g2, inline = '9')
label_color = input.color(color.blue, 'Day 1 Label Color', group = g2, inline = '9')
//get the ma value
ma = matype == 'EMA' ? ta.ema(close, len) : ta.sma(close,len)
// variables
macount = 0
var holding = false
var violation_low = 0.0
var label day1_label = na
var table emas = table.new(i_tableypos + "_" +i_tablexpos, 2, 2, table_bg, color.black, 1, color.black, 1)
// for loop to count if 7 weeks above the moving average
for i = 34 to 0
if close[i] > ma[i]
macount += 1
else if close[i] < ma[i] and macount != 35
macount := 0
if macount >= 35
holding := true
else
holding := false
// sell signal if holding condition was true
sell_signal = (macount[1] >= 35 and ta.crossunder(close,ma)) or (macount[1] >= 35 and close < ma)
// set stop below low of bar that closes under the moving average
if sell_signal
violation_low := low
// trigger the sell signal
trigger_sell_signal = sell_signal[1] and low < violation_low
if sell_signal[1] and low >= violation_low
holding := true
macount := 35
if macount[1] == 35 and close > ma
holding := true
macount := 35
day1 = macount == 35 ? bar_index - 34 : 0
//plots
plotshape(trigger_sell_signal, 'Sell', shape.triangledown, color=color.red)
plot(show_ma ? ma : na, 'Moving Average', color = ma_color, linewidth = ma_width)
bgcolor(holding and hlight ? hcolor1 : sell_signal and hlight ? hcolor2 : na)
// plotchar(macount, 'Count', "")
//day 1 label
if macount == 35 and macount[1] == 34 and show_day_1
day1_label := label.new(day1, low[35] * .99, style = label.style_label_up, size = size.tiny, color = label_color)
// table to show counter
if barstate.islast and show_table
table.cell(emas,0,0, str.upper(matype) + ' ' + str.tostring(len), text_color = table_text, text_halign = text.align_left)
table.cell(emas,1,0, str.tostring(macount), text_color = table_text)
//alerts
if trigger_sell_signal
alert('Moving Average Violation', alert.freq_once_per_bar_close) |
MACD & RSI Overlay (Expo) | https://www.tradingview.com/script/iOi1pXOX-MACD-RSI-Overlay-Expo/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 1,820 | 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('MACD & RSI Overlay (Expo)', overlay=true)
// ~~ ToolTips {
t1 = "Select if you want to display MACD [12,26] or RSI [14] or both at the same time on your chart."
t2 = "Set the smoothing length"
t3 = "Set the signal line length"
t4 = "Increase this value if you want to factor in the underlying trend. A high value returns a long-term underlying trend and a low value returns the short-term underlying trend."
t5 = "The scale refers to how far or close the MACD and RSI lines should be relative to the price. A higher scale means that the lines should be further away from the price, while a lower scale means that the lines should be closer to the price"
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Input variables {
//MACD & RSI
macd_rsi = input.string("MACD", title="", options=["MACD","RSI 14", "Both"], group="MACD/RSI", inline="macdrsi", tooltip = t1)
macd_rsi_smooth = input.int(1, minval=1, maxval=200, step=1, title="Smooth", group="MACD/RSI", inline="macdrsi", tooltip = t2)
signal_line_Length = input.int(14, minval=5, maxval=200, step=1, title="Signal Length", group="MACD/RSI", inline="macdrsi", tooltip = t3)
macd_col = input.color(color.aqua, title="MACD Line", group="MACD/RSI", inline="col")
rsi_col = input.color(color.rgb(19, 96, 238), title="RSI Line", group="MACD/RSI", inline="col")
signal_line_col = input.color(#F8DE7E, title="Signal Line", group="MACD/RSI", inline="col")
ob = input.int(70, minval=0, maxval=100, title="", group="RSI OB/OS", inline="obos_col")
os = input.int(30, minval=0, maxval=100, title="", group="RSI OB/OS", inline="obos_col")
ob_col = input.color(color.lime, title="", group="RSI OB/OS", inline="obos_col")
os_col = input.color(color.red, title="", group="RSI OB/OS", inline="obos_col")
//Scaling
trendFactor = input.int(30, minval=1, maxval=300, step=2, title="Trend Factor", group="Trend Feature", tooltip = t4)
scalingFactor = input.float(2.5, step=0.1, maxval=10, title="Scaling Factor", group="Scaling", tooltip = t5)
//Table
showTable = input.bool(true,title="Show Trend Table", inline="tbl", group="Trend Table")
TblSize = input.string(size.normal,title="Size",options=[size.auto,size.tiny,size.small,size.normal,size.large,size.huge],inline="tbl")
pos = input.string(position.top_right, title="Location",options =[position.top_right,position.top_center,
position.top_left,position.bottom_right,position.bottom_center,position.bottom_left,position.middle_right,position.middle_left],inline="tbl")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Moving Averages {
priceMa = ta.sma(close, 2)
trendMa = ta.sma(close, trendFactor)
//Calculate Scaled Adaptive Moving Average
error = math.abs(priceMa - trendMa)
errorSum = math.sum(error, 10)
ama = errorSum == 0 ? close[1] : priceMa * (error / errorSum) + trendMa * (1 - error / errorSum)
pma = scalingFactor * close + (1.0 - scalingFactor) * ama[1]
//Averages
macd = ta.wma(ta.rma(pma, 5),macd_rsi_smooth)
rsi = ta.wma(ta.rma(pma, 1),macd_rsi_smooth)
signal = ta.sma(pma, signal_line_Length)
//OB/OS color
rsi_ = ta.rsi(close,14)
rsi_col_ = rsi_>ob?ob_col:rsi_<os?os_col:rsi_col
//Plots
plot(macd_rsi=="MACD" or macd_rsi=="Both"?macd:na,color=color.new(macd_col, 0), title='MACD Line')
plot(macd_rsi=="RSI 14" or macd_rsi=="Both"?rsi:na,color=color.new(rsi_col_, 0), title='RSI Line')
plot(signal, color=color.new(signal_line_col, 0), title='Signal Line')
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Table {
string h1 = switch macd_rsi
"MACD" => "MACD: "+(macd>close?"Bullish":"Bearish")
"RSI 14" => "RSI: "+(close<rsi?"Bullish":"Bearish")
"Both" => "MACD: "+(macd>close?"Bullish":"Bearish")+
"\nRSI: "+(close<rsi?"Bullish":"Bearish")
//Plot Table
var tbl = table.new(pos, 1, 1, frame_color=chart.bg_color, frame_width=2, border_width=2, border_color=chart.bg_color)
color trend_col = str.contains(h1,"Bullish") and str.contains(h1,"Bearish")?color.orange:str.contains(h1,"Bullish")?color.lime:color.red
if barstate.islast and showTable
table.cell(tbl, 0, 0, text=h1, text_color=color.white, bgcolor=color.new(trend_col,30), text_size=TblSize)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Alerts {
indicatorcross(indicator) =>
over = ta.crossover(indicator,signal)
under = ta.crossunder(indicator,signal)
[over,under]
srccross(src,indicator) =>
over = ta.crossover(src,indicator)
under = ta.crossunder(src,indicator)
[over,under]
[over_macd,under_macd] = indicatorcross(macd)
[over_rsi,under_rsi] = indicatorcross(rsi)
[over_macd_price,under_macd_price] = srccross(close,macd)
[over_rsi_price,under_rsi_price] = srccross(close,rsi)
[over_rsi_macd,under_rsi_macd] = srccross(rsi,macd)
alertcondition(over_macd, title="MACD Crosses Over Signal Line", message="MACD Crosses Over Signal Line"),alertcondition(under_macd, title="MACD Crosses Under Signal Line", message="MACD Crosses Under Signal Line")
alertcondition(over_rsi, title="RSI Crosses Over Signal Line", message="RSI Crosses Over Signal Line"),alertcondition(under_rsi, title="RSI Crosses Under Signal Line", message="RSI Crosses Under Signal Line")
alertcondition(over_macd_price, title="Close Crosses Over MACD", message="Close Crosses Over MACD"),alertcondition(under_macd_price, title="Close Crosses Under MACD", message="Close Crosses Under MACD")
alertcondition(over_rsi_price, title="Close Crosses Over RSI", message="Close Crosses Over RSI"),alertcondition(under_rsi_price, title="Close Crosses Under RSI", message="Close Crosses Under RSI")
alertcondition(over_rsi_macd, title="RSI Crosses Over MACD", message="RSI Crosses Over MACD"),alertcondition(under_rsi_macd, title="RSI Crosses Under MACD", message="RSI Crosses Under MACD")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} |
Modified Mannarino Market Risk Indicator MMMRI MMRI | https://www.tradingview.com/script/snuFoPT6-Modified-Mannarino-Market-Risk-Indicator-MMMRI-MMRI/ | allanster | https://www.tradingview.com/u/allanster/ | 1,459 | 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/
// © allanster
// MMRI Gregory Mannarino: https://www.mannarino-market-risk-indicator.com/
// MMRI = (USD Strength * USD Interest Rate) / 1.61
// MMMRI Nobody Special Finance: https://www.mannarino-market-risk-indicator.com/MMMRI/
// MMMRI = (Debt / GDP) * (USD Strength * USD Interest Rate) / 1.61
//@version=5
indicator("Modified Mannarino Market Risk Indicator")
i_fiat = input.symbol('TVC:DXY', 'USD Strength')
i_intr = input.symbol('TVC:US10Y', '10 Year Yield')
i_dgmr = input.float (1.61, 'Denominator', minval = 0.01)
i_nsff = input.bool (true, 'Use Modified MMRI')
i_dgdp = input.symbol('ECONOMICS:USGDG', 'Debt To GDP Ratio')
i_fctr = input.bool (false, 'Use Custom Ratio Below')
i_debt = input.symbol('ECONOMICS:USGD', 'Debt')
i_tgdp = input.symbol('ECONOMICS:USGDP', 'GDP')
i_bars = input.bool (true, 'Color Bars')
i_plot = input.bool (true, 'Color Plot')
i_fill = input.bool (true, 'Color Fills')
i_tabl = input.bool (true, 'Show Values')
repaint(_symbol) => nz(request.security(_symbol, timeframe.period, close, ignore_invalid_symbol = true),
request.security(_symbol, timeframe.isintraday ? 'D' : timeframe.period, close))
dollar = repaint(i_fiat)
intrst = repaint(i_intr)
usdebt = repaint(i_debt)
ustgdp = repaint(i_tgdp)
dbtgdp = repaint(i_dgdp)
mmriGM = (dollar * intrst) / i_dgmr
fctrNS = i_fctr ? usdebt / ustgdp : dbtgdp / 100 // use custom (usdebt / ustgdp) or (dbtgdp / 100)
mmriNS = fctrNS * mmriGM
pcntNS = fctrNS * 100
output = i_nsff ? mmriNS : mmriGM
// 0-50 slight risk, 50-100 low risk, 100-200 moderate risk, 200-300 high risk, 300+ extreme risk
colrSR = #00ffff, colrLR = #00ff00, colrMR = #ffff00, colrHR = #ff7f00, colrER = #ff0000
colors(_valu) =>
colors =
_valu < 050 ? colrSR :
_valu >= 050 and _valu < 100 ? colrLR :
_valu >= 100 and _valu < 200 ? colrMR :
_valu >= 200 and _valu < 300 ? colrHR : colrER
plot(output, 'Plot', i_plot ? colors(output) : #ffffff)
h0 = hline(0), h1 = hline(50), h2 = hline(100), h3 = hline(200), h4 = hline(300), h5 = hline(400)
fill(h5, h4, i_fill ? color.new(colrER, 90) : na)
fill(h4, h3, i_fill ? color.new(colrHR, 90) : na)
fill(h3, h2, i_fill ? color.new(colrMR, 90) : na)
fill(h2, h1, i_fill ? color.new(colrLR, 90) : na)
fill(h1, h0, i_fill ? color.new(colrSR, 90) : na)
barcolor(i_bars ? colors(output) : na)
if i_tabl
coltxt = #ffffff, alignL = text.align_left, alignR = text.align_right, coltbl = #150042
var table t = table.new(position.middle_right, 2, 5, coltbl, #7f7f7f, 2, #7f7f7f, 1)
table.cell(t, 0, 0, 'MMRI:', 0, 0, coltxt, alignR)
table.cell(t, 1, 0, str.format('{0, number, 0.00}', mmriGM), 0, 0, colors(mmriGM), alignL)
table.cell(t, 0, 1, 'MMMRI:', 0, 0, coltxt, alignR)
table.cell(t, 1, 1, str.format('{0, number, 0.00}', mmriNS), 0, 0, colors(mmriNS), alignL)
table.cell(t, 0, 2, str.format('{0}:', i_fiat), 0, 0, coltxt, alignR)
table.cell(t, 1, 2, str.format('{0, number, 0.00}', dollar), 0, 0, coltxt, alignL)
table.cell(t, 0, 3, str.format('{0}:', i_intr), 0, 0, coltxt, alignR)
table.cell(t, 1, 3, str.format('{0, number, 0.00}%', intrst), 0, 0, coltxt, alignL)
table.cell(t, 0, 4, 'Debt To GDP:', 0, 0, coltxt, alignR)
table.cell(t, 1, 4, str.format('{0, number, 0.00}%', pcntNS), 0, 0, coltxt, alignL) |
SLSMA - Smooth LSMA | https://www.tradingview.com/script/AEIs1XbD-SLSMA-Smooth-LSMA/ | veryfid | https://www.tradingview.com/u/veryfid/ | 187 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © veryfid
//@version=5
indicator(title='SLSMA - Smooth LSMA', shorttitle='SLSMA', overlay=true, timeframe='')
src = input(close, title='Source')
length = input(title='Length', defval=21)
offset = input(title='Offset', defval=0)
lsma = ta.linreg(src, length, offset)
slsma = lsma - (lsma - ta.linreg(lsma, length, offset))
plot(slsma, color=color.new(color.yellow, 0), linewidth=2)
|
Blocky's EMA Ribbon | https://www.tradingview.com/script/988Rz11A-Blocky-s-EMA-Ribbon/ | godzcopilot | https://www.tradingview.com/u/godzcopilot/ | 58 | 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/
// Extended EMA inspiration from https://www.tradingview.com/script/hWdwt5XH-Multi-Moving-Average-with-Forecast/
// © godzcopilot
//@version=5
indicator(title="Blocky's EMA Ribbon", shorttitle="BREMA", overlay=true)
// Display Options
show_outer = input.bool(false, "Show outer EMAs", group = "Display")
show_inner = input.bool(false, "Show inner EMAs", group = "Display")
show_gradient = input.bool(true, "Show gradient fill", group = "Display")
show_channels = input.bool(true, "Show offset EMA channel", group = "Display")
// Gradient Options
opacity_multiplier = input.int(6, minval=1, maxval = 100, title="Opacity Multiplier", group = "Display")
bear_color = input.color(color.red,"Bear Color", group = "Display")
bull_color = input.color(color.green,"Bull Color", group = "Display")
ribbon_highlight = input.bool(false, "Highlight gradient", group = "Display")
// Set EMA Colors
ema1color = color.new(color.rgb(102,255,102),0)
ema2color = color.new(color.rgb(153,255,153),0)
ema3color = color.new(color.rgb(178,255,102),0)
ema4color = color.new(color.rgb(255,255,51),0)
ema5color = color.new(color.rgb(255,178,102),0)
ema6color = color.new(color.rgb(255,153,51),0)
ema7color = color.new(color.rgb(255,153,153),0)
ema8color = color.new(color.rgb(255,51,51),0)
// Select EMA Source and lengths
src = input(close, title="Source", group = "Source")
len1 = input.int(21, minval=1, title="Length 1 [Fastest]", group = "EMA")
len2 = input.int(25, minval=1, title="Length 2", group = "EMA")
len3 = input.int(30, minval=1, title="Length 3", group = "EMA")
len4 = input.int(35, minval=1, title="Length 4", group = "EMA")
len5 = input.int(40, minval=1, title="Length 5", group = "EMA")
len6 = input.int(45, minval=1, title="Length 6", group = "EMA")
len7 = input.int(50, minval=1, title="Length 7", group = "EMA")
len8 = input.int(55, minval=1, title="Length 8 [Slowest]", group = "EMA")
len9 = input.int(200, minval=1, title="Length", group = "EMA")
channel_multiplier = input.float(1.5, minval=0.1, maxval = 10.0, title="Channel Multiplier", group = "EMA Channel")
// Calculate EMA's
ema1 = ta.ema(src, len1)
ema2 = ta.ema(src, len2)
ema3 = ta.ema(src, len3)
ema4 = ta.ema(src, len4)
ema5 = ta.ema(src, len5)
ema6 = ta.ema(src, len6)
ema7 = ta.ema(src, len7)
ema8 = ta.ema(src, len8)
ema9 = ta.ema(src, len9)
// Calculate outer channels
upper_channel = math.max(ema1, ema8) + (math.abs(ema1 - ema8) * channel_multiplier)
lower_channel = math.min(ema1, ema8) - (math.abs(ema1 - ema8) * channel_multiplier)
// Calculate gradient transparency based on percentage separation of outer EMA's
color_transp = 100 - math.min(math.round(math.abs(ema1 - ema8) / ((ema1 + ema8) / 2) * 100 * opacity_multiplier,0) + 2,100)
// Calculate color based on EMA's laying in order ie short - fast / fast - short
color_weight = 0
if ema1 > ema2
color_weight := color_weight + 1
if ema1 > ema3
color_weight := color_weight + 1
if ema1 > ema4
color_weight := color_weight + 1
if ema1 > ema5
color_weight := color_weight + 1
if ema1 > ema6
color_weight := color_weight + 1
if ema1 > ema7
color_weight := color_weight + 1
if ema1 > ema8
color_weight := color_weight + 1
if ema2 > ema1
color_weight := color_weight - 1
if ema2 > ema3
color_weight := color_weight + 1
if ema2 > ema4
color_weight := color_weight + 1
if ema2 > ema5
color_weight := color_weight + 1
if ema2 > ema6
color_weight := color_weight + 1
if ema2 > ema7
color_weight := color_weight + 1
if ema2 > ema8
color_weight := color_weight + 1
if ema3 > ema1
color_weight := color_weight - 1
if ema3 > ema2
color_weight := color_weight - 1
if ema3 > ema4
color_weight := color_weight + 1
if ema3 > ema5
color_weight := color_weight + 1
if ema3 > ema6
color_weight := color_weight + 1
if ema3 > ema7
color_weight := color_weight + 1
if ema3 > ema8
color_weight := color_weight + 1
if ema4 > ema1
color_weight := color_weight - 1
if ema4 > ema2
color_weight := color_weight - 1
if ema4 > ema3
color_weight := color_weight - 1
if ema4 > ema5
color_weight := color_weight + 1
if ema4 > ema6
color_weight := color_weight + 1
if ema4 > ema7
color_weight := color_weight + 1
if ema4 > ema8
color_weight := color_weight + 1
if ema5 > ema1
color_weight := color_weight - 1
if ema5 > ema2
color_weight := color_weight - 1
if ema5 > ema3
color_weight := color_weight - 1
if ema5 > ema4
color_weight := color_weight - 1
if ema5 > ema6
color_weight := color_weight + 1
if ema5 > ema7
color_weight := color_weight + 1
if ema5 > ema8
color_weight := color_weight + 1
if ema6 > ema1
color_weight := color_weight - 1
if ema6 > ema2
color_weight := color_weight - 1
if ema6 > ema3
color_weight := color_weight - 1
if ema6 > ema4
color_weight := color_weight - 1
if ema6 > ema5
color_weight := color_weight - 1
if ema6 > ema7
color_weight := color_weight + 1
if ema6 > ema8
color_weight := color_weight + 1
if ema8 > ema1
color_weight := color_weight - 1
if ema8 > ema2
color_weight := color_weight - 1
if ema8 > ema3
color_weight := color_weight - 1
if ema8 > ema4
color_weight := color_weight - 1
if ema8 > ema5
color_weight := color_weight - 1
if ema8 > ema6
color_weight := color_weight - 1
if ema8 > ema7
color_weight := color_weight - 1
// Calculate prediction extension
ma_prediction(_src, _period, _offset) =>
(ta.ema(_src, _period - _offset) * (_period - _offset) + _src * _offset) / _period
pma1_1 = ma_prediction(src, len1, 1)
pma1_2 = ma_prediction(src, len1, 2)
pma1_3 = ma_prediction(src, len1, 3)
pma1_4 = ma_prediction(src, len1, 4)
pma1_5 = ma_prediction(src, len1, 5)
pma2_1 = ma_prediction(src, len2, 1)
pma2_2 = ma_prediction(src, len2, 2)
pma2_3 = ma_prediction(src, len2, 3)
pma2_4 = ma_prediction(src, len2, 4)
pma2_5 = ma_prediction(src, len2, 5)
pma3_1 = ma_prediction(src, len3, 1)
pma3_2 = ma_prediction(src, len3, 2)
pma3_3 = ma_prediction(src, len3, 3)
pma3_4 = ma_prediction(src, len3, 4)
pma3_5 = ma_prediction(src, len3, 5)
pma4_1 = ma_prediction(src, len4, 1)
pma4_2 = ma_prediction(src, len4, 2)
pma4_3 = ma_prediction(src, len4, 3)
pma4_4 = ma_prediction(src, len4, 4)
pma4_5 = ma_prediction(src, len4, 5)
pma5_1 = ma_prediction(src, len5, 1)
pma5_2 = ma_prediction(src, len5, 2)
pma5_3 = ma_prediction(src, len5, 3)
pma5_4 = ma_prediction(src, len5, 4)
pma5_5 = ma_prediction(src, len5, 5)
pma6_1 = ma_prediction(src, len6, 1)
pma6_2 = ma_prediction(src, len6, 2)
pma6_3 = ma_prediction(src, len6, 3)
pma6_4 = ma_prediction(src, len6, 4)
pma6_5 = ma_prediction(src, len6, 5)
pma7_1 = ma_prediction(src, len7, 1)
pma7_2 = ma_prediction(src, len7, 2)
pma7_3 = ma_prediction(src, len7, 3)
pma7_4 = ma_prediction(src, len7, 4)
pma7_5 = ma_prediction(src, len7, 5)
pma8_1 = ma_prediction(src, len8, 1)
pma8_2 = ma_prediction(src, len8, 2)
pma8_3 = ma_prediction(src, len8, 3)
pma8_4 = ma_prediction(src, len8, 4)
pma8_5 = ma_prediction(src, len8, 5)
// Plot all EMA's
p1 = plot(ema1, title="EMA", color=ema1color, style =plot.style_line, linewidth = 1, editable = false, display = show_outer ? display.all : display.none)
p2 = plot(ema2, title="EMA", color=ema2color, style =plot.style_line, linewidth = 1, editable = false, display = show_inner ? display.all : display.none)
p3 = plot(ema3, title="EMA", color=ema3color, style =plot.style_line, linewidth = 1, editable = false, display = show_inner ? display.all : display.none)
p4 = plot(ema4, title="EMA", color=ema4color, style =plot.style_line, linewidth = 1, editable = false, display = show_inner ? display.all : display.none)
p5 = plot(ema5, title="EMA", color=ema5color, style =plot.style_line, linewidth = 1, editable = false, display = show_inner ? display.all : display.none)
p6 = plot(ema6, title="EMA", color=ema6color, style =plot.style_line, linewidth = 1, editable = false, display = show_inner ? display.all : display.none)
p7 = plot(ema7, title="EMA", color=ema7color, style =plot.style_line, linewidth = 1, editable = false, display = show_inner ? display.all : display.none)
p8 = plot(ema8, title="EMA", color=ema8color, style =plot.style_line, linewidth = 1, editable = false, display = show_outer ? display.all : display.none)
p9 = plot(ema9, title="EMA", color=color.new(color.rgb(0,150,150),0), editable = true, linewidth = 2)
// Plot predictive EMA's
plot(pma1_1, title='MA 1 Forecast 1', color=ema1color, linewidth=1, style=plot.style_circles, offset=1, show_last=1)
plot(pma1_2, title='MA 1 Forecast 2', color=ema1color, linewidth=1, style=plot.style_circles, offset=2, show_last=1)
plot(pma1_3, title='MA 1 Forecast 3', color=ema1color, linewidth=1, style=plot.style_circles, offset=3, show_last=1)
plot(pma1_4, title='MA 1 Forecast 4', color=ema1color, linewidth=1, style=plot.style_circles, offset=4, show_last=1)
plot(pma1_5, title='MA 1 Forecast 5', color=ema1color, linewidth=1, style=plot.style_circles, offset=5, show_last=1)
plot(pma2_1, title='MA 1 Forecast 1', color=ema2color, linewidth=1, style=plot.style_circles, offset=1, show_last=1)
plot(pma2_2, title='MA 1 Forecast 2', color=ema2color, linewidth=1, style=plot.style_circles, offset=2, show_last=1)
plot(pma2_3, title='MA 1 Forecast 3', color=ema2color, linewidth=1, style=plot.style_circles, offset=3, show_last=1)
plot(pma2_4, title='MA 1 Forecast 4', color=ema2color, linewidth=1, style=plot.style_circles, offset=4, show_last=1)
plot(pma2_5, title='MA 1 Forecast 5', color=ema2color, linewidth=1, style=plot.style_circles, offset=5, show_last=1)
plot(pma3_1, title='MA 1 Forecast 1', color=ema3color, linewidth=1, style=plot.style_circles, offset=1, show_last=1)
plot(pma3_2, title='MA 1 Forecast 2', color=ema3color, linewidth=1, style=plot.style_circles, offset=2, show_last=1)
plot(pma3_3, title='MA 1 Forecast 3', color=ema3color, linewidth=1, style=plot.style_circles, offset=3, show_last=1)
plot(pma3_4, title='MA 1 Forecast 4', color=ema3color, linewidth=1, style=plot.style_circles, offset=4, show_last=1)
plot(pma3_5, title='MA 1 Forecast 5', color=ema3color, linewidth=1, style=plot.style_circles, offset=5, show_last=1)
plot(pma4_1, title='MA 1 Forecast 1', color=ema4color, linewidth=1, style=plot.style_circles, offset=1, show_last=1)
plot(pma4_2, title='MA 1 Forecast 2', color=ema4color, linewidth=1, style=plot.style_circles, offset=2, show_last=1)
plot(pma4_3, title='MA 1 Forecast 3', color=ema4color, linewidth=1, style=plot.style_circles, offset=3, show_last=1)
plot(pma4_4, title='MA 1 Forecast 4', color=ema4color, linewidth=1, style=plot.style_circles, offset=4, show_last=1)
plot(pma4_5, title='MA 1 Forecast 5', color=ema4color, linewidth=1, style=plot.style_circles, offset=5, show_last=1)
plot(pma5_1, title='MA 1 Forecast 1', color=ema5color, linewidth=1, style=plot.style_circles, offset=1, show_last=1)
plot(pma5_2, title='MA 1 Forecast 2', color=ema5color, linewidth=1, style=plot.style_circles, offset=2, show_last=1)
plot(pma5_3, title='MA 1 Forecast 3', color=ema5color, linewidth=1, style=plot.style_circles, offset=3, show_last=1)
plot(pma5_4, title='MA 1 Forecast 4', color=ema5color, linewidth=1, style=plot.style_circles, offset=4, show_last=1)
plot(pma5_5, title='MA 1 Forecast 5', color=ema5color, linewidth=1, style=plot.style_circles, offset=5, show_last=1)
plot(pma6_1, title='MA 1 Forecast 1', color=ema6color, linewidth=1, style=plot.style_circles, offset=1, show_last=1)
plot(pma6_2, title='MA 1 Forecast 2', color=ema6color, linewidth=1, style=plot.style_circles, offset=2, show_last=1)
plot(pma6_3, title='MA 1 Forecast 3', color=ema6color, linewidth=1, style=plot.style_circles, offset=3, show_last=1)
plot(pma6_4, title='MA 1 Forecast 4', color=ema6color, linewidth=1, style=plot.style_circles, offset=4, show_last=1)
plot(pma6_5, title='MA 1 Forecast 5', color=ema6color, linewidth=1, style=plot.style_circles, offset=5, show_last=1)
plot(pma7_1, title='MA 1 Forecast 1', color=ema7color, linewidth=1, style=plot.style_circles, offset=1, show_last=1)
plot(pma7_2, title='MA 1 Forecast 2', color=ema7color, linewidth=1, style=plot.style_circles, offset=2, show_last=1)
plot(pma7_3, title='MA 1 Forecast 3', color=ema7color, linewidth=1, style=plot.style_circles, offset=3, show_last=1)
plot(pma7_4, title='MA 1 Forecast 4', color=ema7color, linewidth=1, style=plot.style_circles, offset=4, show_last=1)
plot(pma7_5, title='MA 1 Forecast 5', color=ema7color, linewidth=1, style=plot.style_circles, offset=5, show_last=1)
plot(pma8_1, title='MA 1 Forecast 1', color=ema8color, linewidth=1, style=plot.style_circles, offset=1, show_last=1)
plot(pma8_2, title='MA 1 Forecast 2', color=ema8color, linewidth=1, style=plot.style_circles, offset=2, show_last=1)
plot(pma8_3, title='MA 1 Forecast 3', color=ema8color, linewidth=1, style=plot.style_circles, offset=3, show_last=1)
plot(pma8_4, title='MA 1 Forecast 4', color=ema8color, linewidth=1, style=plot.style_circles, offset=4, show_last=1)
plot(pma8_5, title='MA 1 Forecast 5', color=ema8color, linewidth=1, style=plot.style_circles, offset=5, show_last=1)
pUpper = plot(upper_channel, title="Upper Channel", color=color.new(color.yellow, 50), linewidth = 1, style = plot.style_line)
pLower = plot(lower_channel, title="Upper Channel", color=color.new(color.blue, 50), linewidth = 1, style = plot.style_line)
// Fill between fast and slow EMAs with weighted coloring and transparency
fill(p1,p8,color=color.new(color.white, 90),editable = false, display = ribbon_highlight ? display.all : display.none)
fill(p1,p8,color=show_gradient ? color.new(color.from_gradient(math.abs(color_weight),0,28,color.navy,color_weight > 0 ? bull_color : bear_color),color_transp) : na,editable = false) |
Order Blocks & Breaker Blocks [LuxAlgo] | https://www.tradingview.com/script/piIbWMpY-Order-Blocks-Breaker-Blocks-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 8,593 | 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("Order Blocks & Breaker Blocks [LuxAlgo]", overlay = true
, max_lines_count = 500
, max_labels_count = 500
, max_boxes_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input.int(10, 'Swing Lookback' , minval = 3)
showBull = input.int(3, 'Show Last Bullish OB', minval = 0)
showBear = input.int(3, 'Show Last Bearish OB', minval = 0)
useBody = input(false, 'Use Candle Body')
//Style
bullCss = input(color.new(#2157f3, 80), 'Bullish OB' , inline = 'bullcss', group = 'Style')
bullBreakCss = input(color.new(#ff1100, 80), 'Bullish Break', inline = 'bullcss', group = 'Style')
bearCss = input(color.new(#ff5d00, 80), 'Bearish OB' , inline = 'bearcss', group = 'Style')
bearBreakCss = input(color.new(#0cb51a, 80), 'Bearish Break', inline = 'bearcss', group = 'Style')
showLabels = input(false, 'Show Historical Polarity Changes')
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type ob
float top = na
float btm = na
int loc = bar_index
bool breaker = false
int break_loc = na
type swing
float y = na
int x = na
bool crossed = false
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
swings(len)=>
var os = 0
var swing top = swing.new(na, na)
var swing btm = swing.new(na, na)
upper = ta.highest(len)
lower = ta.lowest(len)
os := high[len] > upper ? 0
: low[len] < lower ? 1 : os
if os == 0 and os[1] != 0
top := swing.new(high[length], bar_index[length])
if os == 1 and os[1] != 1
btm := swing.new(low[length], bar_index[length])
[top, btm]
method notransp(color css) => color.rgb(color.r(css), color.g(css), color.b(css))
method display(ob id, css, break_css)=>
if id.breaker
box.new(id.loc, id.top, id.break_loc, id.btm, css.notransp()
, bgcolor = css
, xloc = xloc.bar_time)
box.new(id.break_loc, id.top, time+1, id.btm, na
, bgcolor = break_css
, extend = extend.right
, xloc = xloc.bar_time)
line.new(id.loc, id.top, id.break_loc, id.top, xloc.bar_time, color = css.notransp())
line.new(id.loc, id.btm, id.break_loc, id.btm, xloc.bar_time, color = css.notransp())
line.new(id.break_loc, id.top, time+1, id.top, xloc.bar_time, extend.right, break_css.notransp(), line.style_dashed)
line.new(id.break_loc, id.btm, time+1, id.btm, xloc.bar_time, extend.right, break_css.notransp(), line.style_dashed)
else
box.new(id.loc, id.top, time, id.btm, na
, bgcolor = css
, extend = extend.right
, xloc = xloc.bar_time)
line.new(id.loc, id.top, time, id.top, xloc.bar_time, extend.right, css.notransp())
line.new(id.loc, id.btm, time, id.btm, xloc.bar_time, extend.right, css.notransp())
//-----------------------------------------------------------------------------}
//Detect Swings
//-----------------------------------------------------------------------------{
n = bar_index
[top, btm] = swings(length)
max = useBody ? math.max(close, open) : high
min = useBody ? math.min(close, open) : low
//-----------------------------------------------------------------------------}
//Bullish OB
//-----------------------------------------------------------------------------{
var bullish_ob = array.new<ob>(0)
bull_break_conf = 0
if close > top.y and not top.crossed
top.crossed := true
minima = max[1]
maxima = min[1]
loc = time[1]
for i = 1 to (n - top.x)-1
minima := math.min(min[i], minima)
maxima := minima == min[i] ? max[i] : maxima
loc := minima == min[i] ? time[i] : loc
bullish_ob.unshift(ob.new(maxima, minima, loc))
if bullish_ob.size() > 0
for i = bullish_ob.size()-1 to 0
element = bullish_ob.get(i)
if not element.breaker
if math.min(close, open) < element.btm
element.breaker := true
element.break_loc := time
else
if close > element.top
bullish_ob.remove(i)
else if i < showBull and top.y < element.top and top.y > element.btm
bull_break_conf := 1
//Set label
if bull_break_conf > bull_break_conf[1] and showLabels
label.new(top.x, top.y, '▼', color = na
, textcolor = bearCss.notransp()
, style = label.style_label_down
, size = size.tiny)
//-----------------------------------------------------------------------------}
//Bearish OB
//-----------------------------------------------------------------------------{
var bearish_ob = array.new<ob>(0)
bear_break_conf = 0
if close < btm.y and not btm.crossed
btm.crossed := true
minima = min[1]
maxima = max[1]
loc = time[1]
for i = 1 to (n - btm.x)-1
maxima := math.max(max[i], maxima)
minima := maxima == max[i] ? min[i] : minima
loc := maxima == max[i] ? time[i] : loc
bearish_ob.unshift(ob.new(maxima, minima, loc))
if bearish_ob.size() > 0
for i = bearish_ob.size()-1 to 0
element = bearish_ob.get(i)
if not element.breaker
if math.max(close, open) > element.top
element.breaker := true
element.break_loc := time
else
if close < element.btm
bearish_ob.remove(i)
else if i < showBear and btm.y > element.btm and btm.y < element.top
bear_break_conf := 1
//Set label
if bear_break_conf > bear_break_conf[1] and showLabels
label.new(btm.x, btm.y, '▲', color = na
, textcolor = bullCss.notransp()
, style = label.style_label_up
, size = size.tiny)
//-----------------------------------------------------------------------------}
//Set Order Blocks
//-----------------------------------------------------------------------------{
for bx in box.all
bx.delete()
for l in line.all
l.delete()
if barstate.islast
//Bullish
if showBull > 0
for i = 0 to math.min(showBull-1, bullish_ob.size())
get_ob = bullish_ob.get(i)
get_ob.display(bullCss, bullBreakCss)
//Bearish
if showBear > 0
for i = 0 to math.min(showBear-1, bearish_ob.size())
get_ob = bearish_ob.get(i)
get_ob.display(bearCss, bearBreakCss)
//-----------------------------------------------------------------------------} |
Daily Opening GAP | https://www.tradingview.com/script/d9WZvTC4-Daily-Opening-GAP/ | aaronmefford | https://www.tradingview.com/u/aaronmefford/ | 101 | 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("Daily GAP", shorttitle="Gaps", overlay=true,max_boxes_count=150,max_lines_count = 200)
session = input.session("0930-1600","Session Period",options=["0930-1600"])
line_width = input.int(1,"Box Line Width",1,4)
plot_boxes = input.bool(true,"Plot Boxes")
plot_lines = input.bool(false,"Plot Lines")
plot_mid_line = input.bool(true,"Plot Middle Line")
plot_qtr_line = input.bool(false,"Plot Quarter Line")
border_color = input.color(color.yellow,"Border Color")
fill_color = input.color(color.new(color.yellow,90),"Border Color")
mid_color = input.color(color.yellow,"Mid Color")
qtr_color = input.color(color.yellow,"Qtr Color")
t = time("D", session, "America/New_York")
bool is_new_day = na(t[1]) and not na(t) or t[1] < t
bool in_session = not na(time(timeframe.period, session, "America/New_York"))
bool is_close = not na(t[1]) and na(t) or t[1] < t
float prior_close = na
var line[] gap_levels = array.new_line()
var box[] gap_boxes = array.new_box()
prior_close := prior_close[1]
if is_close
prior_close := close[1]
if is_new_day
top = open > prior_close ? open : prior_close
bottom = open < prior_close ? open : prior_close
mid = (top+bottom)/2
if plot_lines
array.push(gap_levels,line.new(bar_index-1,top,bar_index,top,xloc.bar_index,extend = extend.right,color =border_color,style = line.style_solid,width=line_width))
array.push(gap_levels,line.new(bar_index-1,bottom,bar_index,bottom,xloc.bar_index,extend = extend.right,color =border_color,style = line.style_solid,width=line_width))
if plot_mid_line
array.push(gap_levels,line.new(bar_index-1,mid,bar_index,mid,xloc.bar_index,extend = extend.right,color =border_color,style = line.style_dashed,width=math.max(1,line_width/2)))
if plot_qtr_line
top_qtr = (top+mid)/2
bottom_qtr = (bottom+mid)/2
array.push(gap_levels,line.new(bar_index-1,top_qtr,bar_index,top_qtr,xloc.bar_index,extend = extend.right,color =border_color,style = line.style_dashed,width=math.max(1,line_width/2)))
array.push(gap_levels,line.new(bar_index-1,bottom_qtr,bar_index,bottom_qtr,xloc.bar_index,extend = extend.right,color =border_color,style = line.style_dashed,width=math.max(1,line_width/2)))
if plot_boxes
array.push(gap_boxes,box.new(bar_index-1,top,bar_index+10,bottom,border_color,line_width,line.style_solid,extend.right,xloc.bar_index,fill_color))
if in_session
removals = array.new_int()
for [lineNo,this_line] in gap_levels
y = line.get_y1(this_line)
if (low <= y and high >= y)
line.set_x2(this_line,bar_index)
line.set_extend(this_line,extend.none)
removals.push(lineNo)
while removals.size() > 0
removal = removals.pop()
array.remove(gap_levels,removal)
for [boxNo,gap_box] in gap_boxes
h = box.get_top(gap_box)
l = box.get_bottom(gap_box)
if (low < h and high[1] >= h)
removals.push(boxNo)
box.set_right(gap_box,bar_index)
box.set_extend(gap_box,extend.none)
if low > l
array.push(gap_boxes,box.new(bar_index,low,bar_index+1,l,border_color,line_width,line.style_solid,extend.right,xloc.bar_index,fill_color))
else if ( high > l and low[1] <= l)
removals.push(boxNo)
box.set_right(gap_box,bar_index)
box.set_extend(gap_box,extend.none)
if high < h
array.push(gap_boxes,box.new(bar_index,h,bar_index+1,high,border_color,line_width,line.style_solid,extend.right,xloc.bar_index,fill_color))
while removals.size() > 0
removal = removals.pop()
array.remove(gap_boxes,removal)
|
RedK EVEREX - Effort Versus Results Explorer | https://www.tradingview.com/script/I5qJDPxT-RedK-EVEREX-Effort-Versus-Results-Explorer/ | RedKTrader | https://www.tradingview.com/u/RedKTrader/ | 3,304 | 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/
// © RedKTrader - March 2023
//@version=5
// ******************************
// EVEREX v2.0 adds markers for key patterns based on nPrice:nVol ratios
// starting with EoM and Compression - maybe add "Balanced" and "Mega" ??
// to-do list
// inspecting the effort vs result concept by plotting volume vs. price change
// this is like looking at distance versus fuel consumption - but comparing a normalized average of each
// to help reveal areas of volume & price action anomalies, contraction & expansion
indicator('RedK Effort Versus Results Explorer v2.0', 'RedK EVEREX v2.0', precision = 0,
timeframe = '', timeframe_gaps = false, explicit_plot_zorder = true)
// ***********************************************************************************************************
// This function calcualtes a selectable average type
GetAverage(_data, _len, MAOption) =>
value = switch MAOption
'SMA' => ta.sma(_data, _len)
'EMA' => ta.ema(_data, _len)
'HMA' => ta.hma(_data, _len)
'RMA' => ta.rma(_data, _len)
=>
ta.wma(_data, _len)
// ***********************************************************************************************************
// ========================================================================================
// Normalization function - Normalizes values that are not restricted within a zero to 100 range
// This technique provides a scale that is closer to a "human" estimation of value in "bands"
// as in: low, below average, average, above average, high, super high
// this also avoids the issue of extreme values when using the stoch() -based technique
// these values are subjective, and can be changed - but slight changes here won't lead to major changes in outcome
// since all is relative to the same data series.
//
Normalize(_Value, _Avg) =>
_X = _Value / _Avg
_Nor =
_X > 1.50 ? 1.00 :
_X > 1.20 ? 0.90 :
_X > 1.00 ? 0.80 :
_X > 0.80 ? 0.70 :
_X > 0.60 ? 0.60 :
_X > 0.40 ? 0.50 :
_X > 0.20 ? 0.25 :
0.1
// ===================================================================================
// ===========================================================================================================
// Inputs
// ===========================================================================================================
grp_1 = 'Rate of FLow (RoF)'
grp_2 = 'Lookback Parameters'
grp_3 = 'Bias / Sentiment'
grp_4 = 'EVEREX Bands'
length = input.int(10, minval = 1, inline = 'ROF', group = grp_1)
MA_Type = input.string(defval = 'WMA', title = 'MA type',
options = ['WMA', 'EMA', 'SMA', 'HMA', 'RMA'], inline = 'ROF', group = grp_1)
smooth = input.int(defval = 3, title = 'Smooth', minval = 1, inline = 'ROF', group = grp_1)
//src = input.source(close, title = "Source (for 2-Bar Shift)", group = grp_1)
sig_length = input.int(5, 'Signal Length', minval = 1, inline = 'Signal', group = grp_1)
S_Type = input.string(defval = 'WMA', title = 'Signal Type',
options = ['WMA', 'EMA', 'SMA', 'HMA', 'RMA'], inline = 'Signal', group = grp_1)
lookback = input.int(defval = 20, title = 'Length', minval = 1, inline = 'Lookback', group = grp_2)
lkbk_Calc = input.string(defval = 'Simple', title = 'Averaging',
options = ['Simple', 'Same as RRoF'], inline='Lookback', group = grp_2 )
showBias = input.bool(defval = false, title = 'Bias Plot ? -- ', inline = 'Bias', group = grp_3)
B_Length = input.int(defval = 30, title = 'Length', minval = 1, inline = 'Bias', group = grp_3)
B_Type = input.string(defval = 'WMA', title = 'MA type',
options = ['WMA', 'EMA', 'SMA', 'HMA', 'RMA'], inline = 'Bias', group = grp_3)
showEVEREX = input.bool(true, 'Show EVEREX Bands ? -- ', inline = 'EVEREX', group = grp_4)
// a simple mechanism to control/change the strength band scale for improving visualization
// applies only to the "bands" and the level hlines
bandscale = str.tonumber(input.string("100", title = "Band Scale",
options = ['100', '200', '400'], inline = 'EVEREX', group = grp_4))
DispBias = showBias ? display.pane : display.none
DispBands = showEVEREX ? display.pane : display.none
showhlines = showEVEREX ? display.all : display.none
Disp_vals = display.status_line + display.data_window
// ===========================================================================================================
// Calculations
// ===========================================================================================================
// Volume "effort" Calculation -- will revert to no volume acceleration for instruments with no volume data
v = na(volume) ? 1 : volume // this part ensures we're not hit with calc issues due to NaN's
NoVol_Flag = na(volume) ? true : false // this is a flag to use later
lkbk_MA_Type = lkbk_Calc == 'Simple' ? 'SMA' : MA_Type
Vola = GetAverage(v, lookback, lkbk_MA_Type)
Vola_n_pre = Normalize(v, Vola) * 100
//Now trap the case of no volume data - ensure final calculation not impacted
Vola_n = NoVol_Flag ? 100 : Vola_n_pre
//plot(Vola_n , "Volume Normalized", color = color.white, display = display.none)
// ===============================================================================================================
// Price "result" calculation
// we'll consider "result" (strength or weakness) to be the outcome (average) of 6 elements:
// Same (in-)Bar strength elements:
// 1 - Bar Closing: the closing within the bar --> this will be a direct +100 / -100 value
// 2 - Spread to range: the spread to range ratio (that's BoP formula) --> direct +100 / -100 value
// 3 - Relative Spread: spread relative to average spread during lookback period --> normalized
// 2-bar strength elements:
// 4 - 2-bar closing: the closing within 2-bar range (that accomodates open gap effect)
// 5 - 2-bar Closing Shift to Range: Change in close relative to the 2-bar range
// 6 - 2-bar Relative Shift: the 2-bar Close (or source price) shift - relative to the average 2-bar shift during lookback period --> normalized
BarSpread = close - open
BarRange = high - low
R2 = ta.highest(2) - ta.lowest(2)
SrcShift = ta.change(close)
//TR = ta.tr(true)
sign_shift = math.sign(SrcShift)
sign_spread = math.sign(BarSpread)
// =========================================================================================================
// in-bar assessments
// =========================================================================================================
// 1. Calculate closing within bar - should be max value at either ends of the bar range
barclosing = 2 * (close - low) / BarRange * 100 - 100
//plot(barclosing, "Bar Closing %" , color=color.fuchsia, display = display.none)
// 2. caluclate spread to range ratio
s2r = BarSpread / BarRange * 100
//plot(s2r, "Spread:Range", color = color.lime, display = display.none)
// 3. Calculate relative spread compared to average spread during lookback
BarSpread_abs = math.abs(BarSpread)
BarSpread_avg = GetAverage(BarSpread_abs, lookback, lkbk_MA_Type)
BarSpread_ratio_n = Normalize(BarSpread_abs, BarSpread_avg) * 100 * sign_spread
//plot(BarSpread_ratio_n, "Bar Spread Ratio", color=color.orange, display=display.none)
// =========================================================================================================
// 2-bar assessments
// =========================================================================================================
// 4. Calculate closing within 2 bar range - should be max value at either ends of the 2-bar range
barclosing_2 = 2 * (close - ta.lowest(2)) / R2 * 100 - 100
//plot(barclosing_2, "2-Bar Closing %" , color=color.navy, display = display.none)
// 5. calculate 2-bar shift to range ratio
Shift2Bar_toR2 = SrcShift / R2 * 100
//plot(Shift2Bar_toR2, "2-bar Shift vs 2R", color=color.yellow, display = display.none)
// 6. Calculate 2-bar Relative Shift
SrcShift_abs = math.abs(SrcShift)
srcshift_avg = GetAverage(SrcShift_abs, lookback, lkbk_MA_Type)
srcshift_ratio_n = Normalize(SrcShift_abs, srcshift_avg) * 100 * sign_shift
//plot(srcshift_ratio_n, "2-bar Shift vs Avg", color=color.white, display = display.none)
// ===============================================================================
// =========================================================================================
// Relative Price Strength combining all strength elements
Pricea_n = (barclosing + s2r + BarSpread_ratio_n + barclosing_2 + Shift2Bar_toR2 + srcshift_ratio_n) / 6
//plot(Pricea_n, "Price Normalized", color=color.orange, display = display.none)
//Let's take Bar Flow as the combined price strength * the volume:avg ratio
// this works in a similar way to a volume-weighted RSI
bar_flow = Pricea_n * Vola_n / 100
//plot(bar_flow, 'bar_flow', color=color.green, display = display.none)
// calc avergae relative rate of flow, then smooth the resulting average
// classic formula would be this
//RROF = f_ma(bar_flow, length, MA_Type)
//
// or we can create a relative index by separating bulls from bears, like in an RSI - my preferred method
// here we have an added benefit of plotting the (average) bulls vs bears separately - as an option
bulls = math.max(bar_flow, 0)
bears = -1 * math.min(bar_flow, 0)
bulls_avg = GetAverage(bulls, length, MA_Type)
bears_avg = GetAverage(bears, length, MA_Type)
dx = bulls_avg / bears_avg
RROF = 2 * (100 - 100 / (1 + dx)) - 100
RROF_s = ta.wma(RROF, smooth)
Signal = GetAverage(RROF_s, sig_length, S_Type)
// Calculate Bias / sentiment on longer length
dx_b = GetAverage(bulls, B_Length, B_Type) / GetAverage(bears, B_Length, B_Type)
RROF_b = 2 * (100 - 100 / (1 + dx_b)) - 100
RROF_bs = ta.wma(RROF_b, smooth)
// ===========================================================================================================
// Colors & plots
// ===========================================================================================================
c_zero = color.new(#1163f6, 25)
c_band = color.new(color.yellow, 40)
c_up = color.aqua
c_dn = color.orange
c_sup = color.new(#00aa00, 70)
c_sdn = color.new(#ff180b, 70)
up = RROF_s >= 0
s_up = RROF_bs >=0
// ==================================== Plots ==========================================================
// // Display the ATR & VOl Ratio values only on the indicator status line & in the Data Window
// plotchar(shift, title = "Shift", char = "", color = color.white, editable=false, display=display.status_line + display.data_window)
// plotchar(lbk_tr, title = "Avg Shift", char = "", color = color.aqua, editable=false, display=display.status_line + display.data_window)
// plotchar(vola/lbk_vola, title = "Vol Ratio", char = "", color = color.yellow, editable=false, display=display.status_line + display.data_window)
hline(0, 'Zero Line', c_zero, linestyle = hline.style_solid)
// plot the band scale guide lines -- these lines will show/hide along with the EVEREX "Equalizer Bands Plot"
hline(0.25 * bandscale, title = '1/4 Level', color=c_band, linestyle = hline.style_dotted, display = showhlines)
hline(0.50 * bandscale, title = '2/4 Level', color=c_band, linestyle = hline.style_dotted, display = showhlines)
hline(0.75 * bandscale, title = '3/4 Level', color=c_band, linestyle = hline.style_dotted, display = showhlines)
hline(bandscale, title = '4/4 Level', color=c_band, linestyle = hline.style_dotted, display = showhlines)
// Plot Bulls & Bears - these are optional plots and hidden by default - adjust this section later
plot(ta.wma(bulls_avg, smooth), "Bulls", color = #11ff20, linewidth = 2, display = display.none)
plot(ta.wma(bears_avg, smooth), "Bears", color = #d5180b, linewidth = 2, display = display.none)
// =============================================================================
// Plot Bias / Sentiment
plot (RROF_bs, "Bias / Sentiment", style=plot.style_area,
color = s_up ? c_sup : c_sdn, linewidth = 4, display = DispBias )
// =============================================================================
// Plot Price Strength & Relative Volume as stacked "equalizer bands"
// adding visualization option to make the bands joint or separate at the mid-scale mark
Eq_band_option = input.string("Joint", title = 'Band Option', options = ["Joint", "Separate"], group = grp_4)
nPrice = math.max(math.min(Pricea_n, 100), -100)
nVol = math.max(math.min(Vola_n, 100), -100)
bar = bar_flow
c_vol_grn = color.new(#26a69a, 75)
c_vol_red = color.new(#ef5350, 75)
cb_vol_grn = color.new(#26a69a, 20)
cb_vol_red = color.new(#ef5350, 20)
c_vol = bar > 0 ? c_vol_grn : c_vol_red
cb_vol = bar > 0 ? cb_vol_grn : cb_vol_red
vc_lo = 0
vc_hi = nVol * bandscale / 100 / 2
plotcandle(vc_lo, vc_hi, vc_lo, vc_hi , "Volume Band", c_vol, c_vol, bordercolor = cb_vol, display = DispBands)
c_pri_grn = color.new(#3ed73e, 75)
c_pri_red = color.new(#ff870a, 75)
cb_pri_grn = color.new(#3ed73e, 20)
cb_pri_red = color.new(#ff870a, 20)
c_pri = bar > 0 ? c_pri_grn : c_pri_red
cb_pri = bar > 0 ? cb_pri_grn : cb_pri_red
pc_lo_base = Eq_band_option == "Joint" ? vc_hi : 0.50 * bandscale
pc_lo = pc_lo_base
pc_hi = pc_lo_base + math.abs(nPrice) * bandscale / 100 / 2
plotcandle(pc_lo, pc_hi, pc_lo ,pc_hi , "Price Band", c_pri, c_pri, bordercolor = cb_pri, display = DispBands)
// print the normalized volume and price values - only on statys line and in the data window
// these values are independant of the band scale or visualization options
plotchar(nVol, "Normalized Vol", char = "", color = c_vol, editable = false, display = Disp_vals)
plotchar(nPrice, "Normalized Price", char = "", color = c_pri, editable = false, display = Disp_vals)
// =============================================================================
// =============================================================================
// Plot main plot, smoothed plot and signal line
plot(RROF, 'RROF Raw', color.new(#2470f0, 9), display=display.none)
plot(RROF_s, 'RROF Smooth', color = color.new(#b2b5be,40), linewidth = 2)
plot(Signal, "Signal Line", up ? c_up : c_dn, 3)
// ===========================================================================================================
// basic alerts
// ===========================================================================================================
Alert_up = ta.crossover(RROF_s,0)
Alert_dn = ta.crossunder(RROF_s,0)
Alert_swing = ta.cross(RROF_s,0)
// "." in alert title for the alerts to show in the right order up/down/swing
alertcondition(Alert_up, ". RROF Crossing 0 Up", "RROF Up - Buying Action Detected!")
alertcondition(Alert_dn, ".. RROF Crossing 0 Down", "RROF Down - Selling Action Detected!")
alertcondition(Alert_swing, "... RROF Crossing 0", "RROF Swing - Possible Reversal")
// ===========================================================================================================
// v2.0 Adding Markers for Key Patterns
// ===========================================================================================================
// we can re-utilize the Normailize() function here too - but it's cleaner to have a separate ratio calc
nPrice_abs = math.abs(nPrice)
//EV_Ratio = 100 * Normalize(nPrice_abs, nVol)
EV_Ratio = 100 * nPrice_abs / nVol
// initial mapping of return ratios (to be revised)
// -------------------------------------------------------
// Case (1): Price > Vol => ratio > 120 = Ease of Move (EoM)
// Case (2): Price close to Vol => ratio between 80 - 120 = Reasonable Balance
// Case (3): Price less than Vol but reasonable => ratio between 80 - 50 = Drift / "nothing much to see here" bar
// Case (4): Price a lot less than Vol => 50 or less = Compression / Squat
// we're most interested in cases 1 & 4
//plot (EV_Ratio) // for validation only
is_positive = nPrice > 0
is_Compression = EV_Ratio <= 50
is_EoM = EV_Ratio >= 120
//Provide option to show/hide those EVEREX Markers - and an option for Compression bar
// - some folks would prefer a cross, others may prefer a circle - can adjust based on feedback
// no option for Ease of Move, guessing the triangle has the right significance
var showMarkers = input.bool(true, 'Show EVEREX Markers ?')
var Mshape = input.string("Circles", "Compression Marker", options = ['Circles','Crosses'])
SetShape(_x) =>
switch _x
'Circles' => shape.circle
'Crosses' => shape.cross
// Plot markers
plotshape(showMarkers and is_EoM and is_positive ? 0 : na, "EoM +ve", shape.triangleup, color=color.green,
location=location.absolute, size=size.auto, editable = false, display = display.pane)
plotshape(showMarkers and is_EoM and not(is_positive) ? 0 : na, "EoM -ve", shape.triangledown, color=color.red,
location=location.absolute, size=size.auto, editable = false, display = display.pane)
plotshape(showMarkers and is_Compression and is_positive ? 0 : na, "Compression +ve", style = SetShape(Mshape),
color=color.green, location=location.absolute, size = size.auto, editable = false, display = display.pane)
plotshape(showMarkers and is_Compression and not(is_positive) ? 0 : na, "Compression -ve", style = SetShape(Mshape),
color=color.red, location=location.absolute, size=size.auto, editable = false, display = display.pane)
|
US Treasuries Yield Curve | https://www.tradingview.com/script/zXgTdtml-US-Treasuries-Yield-Curve/ | QuantNomad | https://www.tradingview.com/u/QuantNomad/ | 190 | 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/
// © QuantNomad
//@version=5
indicator("US Treasuries Yield Curve", max_labels_count = 500, max_lines_count = 500)
timFm = input.string("Monthly", "Yield Curve Timeframe", ["Yearly", "Monthly", "Weekly", "Daily"])
yldCol = input.color(color.green, "Yield Curve Line")
num = input.int(1, "Number of Previous Yield Curves", 0, 12)
brtCol = input.bool(true, "Apply Bright Colors for Previous Yield Curves?",
tooltip = "Color of Previous Yield Curves Would be RANDOM.")
mstLst = input.bool(false, "Show Only the Furthest Previous Yield Curve?")
// Colors
boxCol = input.color(#696969, "Background Color", group = "Plots Setting")
txtCol = input.color(color.white, "Text Color", group = "Plots Setting")
invCol = input.color(color.red, "Inverted Status Notice", group = "Plots Setting")
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | CALCULATION |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// US Treasuries
prdRy = array.from("1M", "2M", "3M", "6M", "1Y", "2Y", "3Y", "5Y", "7Y", "10Y", "20Y", "30Y")
m01 = "US01MY", m02 = "US02MY", m03 = "US03MY", m06 = "US06MY", y01 = "US01Y", y02 = "US02Y",
y03 = "US03Y", y05 = "US05Y", y07 = "US07Y", y10 = "US10Y", y20 = "US20Y", y30 = "US30Y"
// Set Color for Yield Curve
var prdRyCol = array.new<color>(na)
if barstate.ishistory
brt = brtCol ? 75 : 0
array.push(prdRyCol, yldCol)
if num > 0
for i = 0 to num - 1
array.push(prdRyCol,
color.rgb(math.random(brt, 255), math.random(brt, 255), math.random(brt, 255), 0))
// Yield Curve Function
frame = timFm == "Yearly" ? "12M" : timFm == "Monthly" ? "1M" : timFm == "Weekly" ? "1W" : "1D"
instVal = matrix.new<float>(mstLst ? 2 : num + 1, 0, na)
yeild(n) =>
yld = array.new<float>(na)
if mstLst
array.push(yld, close)
array.push(yld, close[n])
else
for i = 0 to n
array.push(yld, close[i])
yld
getYield(symbol) =>
yld = request.security(symbol, frame, yeild(num), ignore_invalid_symbol = true)
if not na(yld)
if array.size(yld) > 0
matrix.add_col(instVal, matrix.columns(instVal), yld)
getYield(m01), getYield(m02), getYield(m03), getYield(m06), getYield(y01), getYield(y02),
getYield(y03), getYield(y05), getYield(y07), getYield(y10), getYield(y20), getYield(y30),
// Yield Curve Time Function
yeildTime(n) =>
tim = array.new<int>(na)
if mstLst
array.push(tim, time_close)
array.push(tim, time_close[n])
else
for i = 0 to n
array.push(tim, time_close[i])
tim
instTim = request.security(y30, frame, yeildTime(num), ignore_invalid_symbol = true)
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | DRAWING |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Plot Functions
getTime(t) =>
str.format_time(t, timFm == "Yearly" ? "yyyy" : "yyyy-MM-dd", syminfo.timezone)
// +++++++++ Get X-Axis
x_axis(x, inc) =>
line.new( x, -1.2, x, -1.1, color = boxCol, style = line.style_solid)
label.new(x, -1.33, str.tostring(inc), textcolor = txtCol, color = color.new(boxCol, 100),
style = label.style_label_center)
// +++++++++ Get Y-Axis
y_axis(yy, min, max) =>
y = max - (1-yy)/(2/(max-min))
line.new(bar_index, yy, bar_index - 13, yy, color = color.new(boxCol, 50), style = line.style_dashed)
label.new(bar_index, yy, str.tostring(y, format.percent), textcolor = txtCol, color = color.new(boxCol, 100),
style = label.style_label_left)
// +++++++++ Get Time Curve
scale(y, min, max) => 2/(max-min) * (y - min) - 1
scatter(x, y, max, min, col, tip, s, t) =>
_tiptool = tip ? array.get(prdRy, x) + " | " + getTime(t) +"\nInterest Rate: " + str.tostring(y, format.percent) : na
label.new(bar_index - 12 + x, scale(y, min, max), "⬤", xloc.bar_index, yloc.price,
color.new(boxCol, 100), label.style_label_center, col, s, tooltip = _tiptool)
line(x, y, max, min, x1, y1, col, w, sty) =>
line.new(bar_index - 12 + x1, scale(y1, min, max), bar_index - 12 + x, scale(y, min, max),
color = col, style = sty, width = w)
// +++++++++ Get Legend
legend(y, t, col, sty) =>
_x = timFm == "Yearly" ? 1 : 0
label.new(bar_index - 15 + _x, y, "⬤", xloc.bar_index, yloc.price, color.new(boxCol, 100),
label.style_label_center, col, size.auto)
line.new(bar_index - 16 , y, bar_index - 15 + _x, y, color = col, style = sty, width = 2)
label.new(bar_index - 15 + _x, y, getTime(t), xloc.bar_index, yloc.price, color.new(boxCol, 100),
label.style_label_left, col, size.auto)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Drawing
if barstate.islast
boxs = box.all
if array.size(boxs) > 0
for i = 0 to array.size(boxs) - 1
box.delete(array.get(boxs, i))
labs = label.all
if array.size(labs) > 0
for i = 0 to array.size(labs) - 1
label.delete(array.get(labs, i))
lins = line.all
if array.size(lins) > 0
for i = 0 to array.size(lins) - 1
line.delete(array.get(lins, i))
// Plot Frame
box.new(bar_index-16, 1.2, bar_index, -1.2, color.new(txtCol, 50), 2, bgcolor = color.new(boxCol, 75))
// Title
box.new(bar_index-13, 1.5, bar_index, 1.18, color.new(txtCol, 50), 2, bgcolor = color.new(boxCol, 0),
text = "US Treasuries Yield Curve", text_color = txtCol)
// Legends
box.new(bar_index-16, 1.5, bar_index-13, -1.2, color.new(txtCol, 50), 2, bgcolor = color.new(boxCol, 100))
//Timeframe
box.new(bar_index-16, 1.5, bar_index-13, 1.18, color.new(txtCol, 50), 2, bgcolor = color.new(boxCol, 0),
text = timFm , text_color = txtCol)
if matrix.rows(instVal) > 0
maxVal = matrix.max(instVal)
minVal = matrix.min(instVal)
// Line Plot
for j = 0 to matrix.rows(instVal) - 1
clr = array.get(prdRyCol, j)
if array.size(instTim) > j
legend(1-0.15*j, array.get(instTim, j), clr,
j == 0 ? line.style_solid : line.style_dotted)
for i = 0 to matrix.columns(instVal) - 1
scatter(i, matrix.get(instVal, j, i), maxVal, minVal, clr,
true, j == 0 ? size.normal : size.tiny, array.get(instTim, j))
if i > 0
line(i-1, matrix.get(instVal, j, i-1), maxVal, minVal,
i, matrix.get(instVal, j, i), clr, j == 0 ? 3 : 1,
j == 0 ? line.style_solid : line.style_dotted)
// Y-axis
yInc = array.from(-1, -0.5, 0, 0.5, 1)
for i = 0 to array.size(yInc) - 1
y_axis(array.get(yInc, i), minVal, maxVal)
// Inverted Status
if matrix.get(instVal, 0, 5) > matrix.get(instVal, 0, 9)
box.new(bar_index-16, -1.2, bar_index-13, -1, color.new(txtCol, 50), 2, bgcolor = invCol,
text = "INVERTED" , text_color = txtCol)
// X-axis
for i = 0 to array.size(prdRy) - 1
x_axis(bar_index-12 + i, array.get(prdRy, i))
tbl = table.new(position.bottom_right, 1, 1, bgcolor = boxCol, border_width = 1)
table.cell(tbl, 0, 0, text = "QuantNomad", text_color = txtCol, text_size = size.small)
|
Advanced Price Direction Algorithm | https://www.tradingview.com/script/OfzWxWnE-Advanced-Price-Direction-Algorithm/ | eykpunter | https://www.tradingview.com/u/eykpunter/ | 98 | 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("Advanced Price Direction")
evaltttext="advanced price direction; evaluates n plus n bars lumped together e.g. if you enter 5 the script uses the last 5 bars as a set and the set before that, in total 10 bars."
//input set size
eval=input.int(12,"sets of ## bars to appraise UpDownFalt",1, tooltip=evaltttext)
//bar directions
//compounded bar by lumping together sets of bars
cl=math.avg(close,eval) //close of bars lumped together
pr=cl[eval] //close of previous set of bars lumped together
op=math.avg(open,eval) //open of bars lumped together
//evaluate compunded bar
up=cl>pr and cl>op //up when close >previous close and close>open
dn=cl<pr and cl<op //down when close<previous close and close<open
fa= not up and not dn //falter when neither up nor down
//example output if used as an indicator of its own
fill(hline(0),hline(1),color=up?color.new(color.blue,50):dn?color.new(color.red,50):color.new(color.yellow,50),title="UpDownFalt blue red yellow")
|
MARS - Moving Average Relative Strength | https://www.tradingview.com/script/Lv26g1XV-MARS-Moving-Average-Relative-Strength/ | finallynitin | https://www.tradingview.com/u/finallynitin/ | 688 | 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/
// © finallynitin
//original concept from dman103
//modified from "Percentage Relative Strength" script by dman103 https://www.tradingview.com/v/v3bbnm1Z/
//@version=5
indicator('Moving Average Relative Strength', shorttitle="MARS", timeframe='')
//Inputs
matype = input.string(title='Moving Average Type', defval='SMA', options=['SMA', 'EMA', 'WMA'], group='Moving Average')
malength = input(title='Moving Average Length', defval=50, group='Moving Average')
index = input.string(title='Index to compare To', defval='NSE:NIFTY', options=['NSE:NIFTY', 'NSE:CNX500', 'NSE:NIFTYSMLCAP250', 'NSE:CNXSMALLCAP'],group='Relative Strength')
compareToOtherIndex = input.bool (title="Compare to different index?", defval=false,group='Relative Strength',inline='Different compare')
otherIndex = input.symbol(title='', defval='',group='Relative Strength',inline='Different compare')
Paintbar=input(false,'Paint Bar?', group="Customisation")
Backgroundcolor=input(true,'Background Color?', group="Customisation")
Easycolors=input(false,'Easy Colors?', group="Customisation")
showZeroLine = input.bool(defval=false, title="Show Zero Line", inline='line 1', group="Customisation")
zerocolor = input(color.black, title='', inline='line 1', group="Customisation")
//Color palette
ropcolor = input(#32CD32, "Relative Outperformance", group="Histogram Colors")
gopcolor = input(#228B22, "Gross Outperformance", group="Histogram Colors")
aopcolor = input(#5ea3f0, "Absolute Outperformance", group="Histogram Colors")
rupcolor = input(#df6b90, "Relative Underperformance", group="Histogram Colors")
gupcolor = input(color.maroon, "Gross Underperformance", group="Histogram Colors")
aupcolor = input(color.black, "Absolute Underperformance", group="Histogram Colors")
ColorUp = #5ea3f0
ColorDown = #df6b90
//Configuring the Moving Average
ma_function(source, length) =>
if matype == 'SMA'
ta.sma(source, length)
else
if matype == 'EMA'
ta.ema(source, length)
else
if matype == 'WMA'
ta.wma(source, length)
// Basic conditions
indexToUse = compareToOtherIndex==false ? index : otherIndex
closeIndex = request.security(indexToUse, timeframe.period, close)
ma = ma_function(close, malength)
maIndex = ma_function(closeIndex, malength)
symbolPercent = (close - ma) / ma * 100
indexPercent = (closeIndex - maIndex) / maIndex * 100
val = symbolPercent - indexPercent
priceIsAboveMa = close > ma
priceIsAboveIndexMa = closeIndex > maIndex
indexgreen = request.security(indexToUse, timeframe.period, priceIsAboveIndexMa)
priceIsBelowMa = close <= ma
priceIsBelowIndexMa = closeIndex <= maIndex
indexred = request.security(indexToUse, timeframe.period, priceIsBelowIndexMa)
iff_1 = indexred ? #FBAED2 : color.black
IndexColor = indexgreen ? #9BDDFF : iff_1
//Color coding
rop = indexred and priceIsBelowMa and val>0
gop = indexgreen and priceIsAboveMa and val>0
aop = indexred and priceIsAboveMa
rup = indexgreen and priceIsAboveMa and val<0
gup = indexred and priceIsBelowMa and val<0
aup = indexgreen and priceIsBelowMa
BarColor = rop ? ropcolor : gop ? gopcolor : aop ? aopcolor : rup ? rupcolor : gup ? gupcolor : aup ? aupcolor : color.gray
EasyColor = val >= 0 ? ColorUp : ColorDown
//Plots
BackColor = color.new(IndexColor, 20)
bgcolor(Backgroundcolor? BackColor : na)
barcolor(Paintbar? BarColor : na)
plot(val, color=Easycolors ? EasyColor : BarColor, style=plot.style_columns, linewidth=5)
plot(showZeroLine ? 0 : na, linewidth=1, color=zerocolor, title="Zero Line")
|
Elliott Wave [LuxAlgo] | https://www.tradingview.com/script/KvrhsPTp-Elliott-Wave-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 6,960 | 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("Elliott Wave [LuxAlgo]", max_lines_count=500, max_labels_count=500, overlay=true, max_bars_back=5000)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
i_hi = input.string('high' , title= '' , group='source [high - low]', inline='hl', options=['high', 'close', 'max open/close'])
i_lo = input.string('low' , title= '' , group='source [high - low]', inline='hl', options=['low' , 'close', 'min open/close'])
s1 = input.bool (true , title= '' , group='ZigZag' , inline= '1' )
len1 = input.int ( 4 , title= ' 1 Length', group='ZigZag' , inline= '1', minval =1 )
col1 = input.color (color.red , title= '' , group='ZigZag' , inline= '1' )
s2 = input.bool (true , title= '' , group='ZigZag' , inline= '2' )
len2 = input.int ( 8 , title= ' 2 Length', group='ZigZag' , inline= '2', minval =1 )
col2 = input.color (color.blue , title= '' , group='ZigZag' , inline= '2' )
s3 = input.bool (true , title= '' , group='ZigZag' , inline= '3' )
len3 = input.int (16 , title= ' 3 Length', group='ZigZag' , inline= '3', minval =1 )
col3 = input.color (color.white , title= '' , group='ZigZag' , inline= '3' )
i_500 = input.float (0.500 , title=' level 1', group='Fibonacci values' , minval =0, maxval =1, step =0.01 )
i_618 = input.float (0.618 , title=' level 2', group='Fibonacci values' , minval =0, maxval =1, step =0.01 )
i_764 = input.float (0.764 , title=' level 3', group='Fibonacci values' , minval =0, maxval =1, step =0.01 )
i_854 = input.float (0.854 , title=' level 4', group='Fibonacci values' , minval =0, maxval =1, step =0.01 )
shZZ = input.bool (false , title= '' , group='show ZZ' , inline='zz' )
//-----------------------------------------------------------------------------}
//User Defined Types
//-----------------------------------------------------------------------------{
type ZZ
int [] d
int [] x
float[] y
line [] l
type Ewave
line l1
line l2
line l3
line l4
line l5
label b1
label b2
label b3
label b4
label b5
//
bool on
bool br //= na
//
int dir
//
line lA
line lB
line lC
label bA
label bB
label bC
//
bool next = false
//
label lb
box bx
type fibL
line wave1_0_500
line wave1_0_618
line wave1_0_764
line wave1_0_854
line wave1_pole_
linefill l_fill_
bool _break_ //= na
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
hi = i_hi == 'high' ? high : i_hi == 'close' ? close : math.max(open, close)
lo = i_lo == 'low' ? low : i_hi == 'close' ? close : math.min(open, close)
in_out(aZZ, d, x1, y1, x2, y2, col) =>
aZZ.d.unshift(d), aZZ.x.unshift(x2), aZZ.y.unshift(y2), aZZ.d.pop(), aZZ.x.pop(), aZZ.y.pop()
if shZZ
aZZ.l.unshift(line.new(x1, y1, x2, y2, color= col)), aZZ.l.pop().delete()
method isSame(Ewave gEW, _1x, _2x, _3x, _4x) =>
t1 = _1x == gEW.l1.get_x1()
t2 = _2x == gEW.l2.get_x1()
t3 = _3x == gEW.l3.get_x1()
t4 = _4x == gEW.l4.get_x1()
t1 and t2 and t3 and t4
method isSame2(Ewave gEW, _1x, _2x, _3x) =>
t1 = _1x == gEW.l3.get_x2()
t2 = _2x == gEW.l4.get_x2()
t3 = _3x == gEW.l5.get_x2()
t1 and t2 and t3
method dot(Ewave gEW) =>
gEW.l1.set_style(line.style_dotted)
gEW.l2.set_style(line.style_dotted)
gEW.l3.set_style(line.style_dotted)
gEW.l4.set_style(line.style_dotted)
gEW.l5.set_style(line.style_dotted)
gEW.b1.set_textcolor (color(na))
gEW.b2.set_textcolor (color(na))
gEW.b3.set_textcolor (color(na))
gEW.b4.set_textcolor (color(na))
gEW.b5.set_textcolor (color(na))
gEW.on := false
method dash(Ewave gEW) =>
gEW.lA.set_style(line.style_dashed)
gEW.lB.set_style(line.style_dashed)
gEW.lC.set_style(line.style_dashed)
gEW.bA.set_textcolor (color(na))
gEW.bB.set_textcolor (color(na))
gEW.bC.set_textcolor (color(na))
gEW.bx.set_bgcolor (color(na))
gEW.bx.set_border_color (color(na))
method sol_dot(fibL nFibL, sol_dot, col) =>
style =
sol_dot == 'dot' ?
line.style_dotted :
sol_dot == 'sol' ?
line.style_solid :
line.style_dashed
nFibL.wave1_0_500.set_style(style)
nFibL.wave1_0_618.set_style(style)
nFibL.wave1_0_764.set_style(style)
nFibL.wave1_0_854.set_style(style)
nFibL.l_fill_.set_color(col)
method set(fibL nFibL, int x1, int x2, float max_500, float max_618, float max_764, float max_854, float y2) =>
nFibL.wave1_0_500.set_xy1(x1, max_500)
nFibL.wave1_0_500.set_xy2(x2, max_500)
nFibL.wave1_0_618.set_xy1(x1, max_618)
nFibL.wave1_0_618.set_xy2(x2, max_618)
nFibL.wave1_0_764.set_xy1(x1, max_764)
nFibL.wave1_0_764.set_xy2(x2, max_764)
nFibL.wave1_0_854.set_xy1(x1, max_854)
nFibL.wave1_0_854.set_xy2(x2, max_854)
nFibL.wave1_pole_.set_xy1(x1, y2 )
nFibL.wave1_pole_.set_xy2(x1, max_854)
nFibL.l_fill_.get_line1().set_xy1(x1, max_764)
nFibL.l_fill_.get_line1().set_xy2(x2, max_764)
nFibL.l_fill_.get_line2().set_xy1(x1, max_854)
nFibL.l_fill_.get_line2().set_xy2(x2, max_854)
method setNa(fibL nFibL) =>
nFibL.wave1_0_500.set_xy1(na, na)
nFibL.wave1_0_500.set_xy2(na, na)
nFibL.wave1_0_618.set_xy1(na, na)
nFibL.wave1_0_618.set_xy2(na, na)
nFibL.wave1_0_764.set_xy1(na, na)
nFibL.wave1_0_764.set_xy2(na, na)
nFibL.wave1_0_854.set_xy1(na, na)
nFibL.wave1_0_854.set_xy2(na, na)
nFibL.wave1_pole_.set_xy1(na, na)
nFibL.wave1_pole_.set_xy2(na, na)
nFibL.l_fill_.set_color(color(na))
draw(enabled, left, col, n) =>
//
max_bars_back(time, 2000)
var int dir = na, var int x1= na, var float y1 = na, var int x2 = na, var float y2 = na, var Ewave gEW = na
var int last_0x = na , var float last_0y = na , var int last_6x = na , var float last_6y = na
//
if enabled
var fibL nFibL = fibL.new(
wave1_0_500 = line.new(na, na, na, na, color= color.new(col, 50), style= line.style_solid ),
wave1_0_618 = line.new(na, na, na, na, color= color.new(col, 38), style= line.style_solid ),
wave1_0_764 = line.new(na, na, na, na, color= color.new(col, 24), style= line.style_solid ),
wave1_0_854 = line.new(na, na, na, na, color= color.new(col, 15), style= line.style_solid ),
wave1_pole_ = line.new(na, na, na, na, color= color.new(col, 50), style= line.style_dashed),
l_fill_ = linefill.new(
line.new(na, na, na, na, color= color(na))
, line.new(na, na, na, na, color= color(na))
, color= color(na))
, _break_ = na
)
//
var ZZ aZZ = ZZ.new(array.new < int > ()
, array.new < int > ()
, array.new < float > ()
, array.new < line > () )
var Ewave[] aEW = array.new < Ewave > ()
//
if barstate.isfirst
aEW.unshift(Ewave.new())
for i = 0 to 10
aZZ.d.unshift(0)
aZZ.x.unshift(0)
aZZ.y.unshift(0)
aZZ.l.unshift(shZZ ? line.new(na, na, na, na) : na)
//
sz = aZZ.d.size( )
x2 := bar_index -1
ph = ta.pivothigh(hi, left, 1)
pl = ta.pivotlow (lo, left, 1)
t = n == 2 ? '\n\n' : n == 1 ? '\n' : ''
//
// when a new Pivot High is found
if not na(ph)
gEW := aEW.get (0)
dir := aZZ.d.get (0)
x1 := aZZ.x.get (0)
y1 := aZZ.y.get (0)
y2 := nz(hi[1])
//
if dir < 1 // if previous point was a pl, add, and change direction ( 1)
in_out(aZZ, 1, x1, y1, x2, y2, col)
else
if dir == 1 and ph > y1
aZZ.x.set(0, x2), aZZ.y.set(0, y2)
if shZZ
aZZ.l.get(0).set_xy2(x2, y2)
//
_6x = x2, _6y = y2
_5x = aZZ.x.get(1), _5y = aZZ.y.get(1)
_4x = aZZ.x.get(2), _4y = aZZ.y.get(2)
_3x = aZZ.x.get(3), _3y = aZZ.y.get(3)
_2x = aZZ.x.get(4), _2y = aZZ.y.get(4)
_1x = aZZ.x.get(5), _1y = aZZ.y.get(5)
//
// –––––––––––––––––––––[ 12345 ]–––––––––––––––––––––
_W5 = _6y - _5y
_W3 = _4y - _3y
_W1 = _2y - _1y
min = math.min(_W1, _W3, _W5)
isWave =
_W3 != min and
_6y > _4y and
_3y > _1y and
_5y > _2y
//
same = gEW.isSame(_1x, _2x, _3x, _4x)
if isWave
if same
gEW.l5.set_xy2(_6x, _6y)
gEW.b5.set_xy (_6x, _6y)
else
tx = ''
if _2x == aEW.get(0).b5.get_x()
tx := '(5) (1)'
aEW.get(0).b5.set_text('')
else
tx := '(1)'
//
wave = Ewave.new(
l1 = line.new (_1x, _1y, _2x, _2y , color=col , style= line.style_solid ),
l2 = line.new (_2x, _2y, _3x, _3y , color=col , style= line.style_solid ),
l3 = line.new (_3x, _3y, _4x, _4y , color=col , style= line.style_solid ),
l4 = line.new (_4x, _4y, _5x, _5y , color=col , style= line.style_solid ),
l5 = line.new (_5x, _5y, _6x, _6y , color=col , style= line.style_solid ),
b1 = label.new(_2x, _2y, text= tx + t, textcolor=col, color= color(na), style=label.style_label_down),
b2 = label.new(_3x, _3y, text= t + '(2)', textcolor=col, color= color(na), style=label.style_label_up ),
b3 = label.new(_4x, _4y, text= '(3)' + t, textcolor=col, color= color(na), style=label.style_label_down),
b4 = label.new(_5x, _5y, text= t + '(4)', textcolor=col, color= color(na), style=label.style_label_up ),
b5 = label.new(_6x, _6y, text= '(5)' + t, textcolor=col, color= color(na), style=label.style_label_down),
on = true ,
br = false ,
dir = 1
)
aEW.unshift(wave)
nFibL._break_ := false
alert('New EW Motive Bullish Pattern found' , alert.freq_once_per_bar_close)
//
if not isWave
if same and gEW.on == true
gEW.dot()
alert('Invalidated EW Motive Bullish Pattern', alert.freq_once_per_bar_close)
//
// –––––––––––––––––––––[ ABC ]–––––––––––––––––––––
getEW = aEW.get(0)
last_0x := getEW.l1.get_x1(), last_0y := getEW.l1.get_y1()
last_6x := getEW.l5.get_x2(), last_6y := getEW.l5.get_y2()
diff = math.abs(last_6y - last_0y)
//
if getEW.dir == -1
getX = getEW.l5.get_x2()
getY = getEW.l5.get_y2()
isSame2 = getEW.isSame2 (_1x, _2x, _3x)
isValid =
_3x == getX and
_6y < getY + (diff * i_854) and
_4y < getY + (diff * i_854) and
_5y > getY
//
if isValid
width = _6x - _2x // –––[ width (4) - (c) ]–––
if isSame2 and getEW.bA.get_x() > _3x
getEW.lC.set_xy1(_5x, _5y), getEW.lC.set_xy2(_6x, _6y), getEW.bC.set_xy(_6x, _6y), getEW.bx.set_lefttop(_6x, _6y), getEW.bx.set_right(_6x + width)
else
getEW.lA := line.new (_3x, _3y, _4x, _4y, color=col), getEW.bA := label.new(_4x, _4y, text= '(a)' + t, textcolor=col, color= color(na), style=label.style_label_down)
getEW.lB := line.new (_4x, _4y, _5x, _5y, color=col), getEW.bB := label.new(_5x, _5y, text= t + '(b)', textcolor=col, color= color(na), style=label.style_label_up )
getEW.lC := line.new (_5x, _5y, _6x, _6y, color=col), getEW.bC := label.new(_6x, _6y, text= '(c)' + t, textcolor=col, color= color(na), style=label.style_label_down)
getEW.bx := box.new (_6x, _6y, _6x + width, _4y, bgcolor=color.new(col, 93), border_color=color.new(col, 65))
alert('New EW Corrective Bullish Pattern found' , alert.freq_once_per_bar_close)
else
if isSame2 and getEW.bA.get_x() > _3x
getEW.dash()
alert('Invalidated EW Corrective Bullish Pattern', alert.freq_once_per_bar_close)
//
// –––––––––––––––––––––[ new (1) ? ]–––––––––––––––––––––
if getEW.dir == 1
if _5x == getEW.bC.get_x() and
_6y > getEW.b5.get_y() and
getEW.next == false
getEW.next := true
getEW.lb := label.new(_6x, _6y, style=label.style_circle, color=color.new(col, 65), yloc=yloc.abovebar, size=size.tiny)
alert('Possible new start of EW Motive Bullish Wave', alert.freq_once_per_bar_close)
//
// when a new Pivot Low is found
if not na(pl)
gEW := aEW.get (0)
dir := aZZ.d.get (0)
x1 := aZZ.x.get (0)
y1 := aZZ.y.get (0)
y2 := nz(lo[1])
//
if dir > -1 // if previous point was a ph, add, and change direction (-1)
in_out(aZZ, -1, x1, y1, x2, y2, col)
else
if dir == -1 and pl < y1
aZZ.x.set(0, x2), aZZ.y.set(0, y2)
if shZZ
aZZ.l.get(0).set_xy2(x2, y2)
//
_6x = x2, _6y = y2
_5x = aZZ.x.get(1), _5y = aZZ.y.get(1)
_4x = aZZ.x.get(2), _4y = aZZ.y.get(2)
_3x = aZZ.x.get(3), _3y = aZZ.y.get(3)
_2x = aZZ.x.get(4), _2y = aZZ.y.get(4)
_1x = aZZ.x.get(5), _1y = aZZ.y.get(5)
//
// –––––––––––––––––––––[ 12345 ]–––––––––––––––––––––
_W5 = _5y - _6y
_W3 = _3y - _4y
_W1 = _1y - _2y
min = math.min(_W1, _W3, _W5)
isWave =
_W3 != min and
_4y > _6y and
_1y > _3y and
_2y > _5y
//
same = isSame(gEW, _1x, _2x, _3x, _4x)
if isWave
if same
gEW.l5.set_xy2(_6x, _6y)
gEW.b5.set_xy (_6x, _6y)
else
tx = ''
if _2x == aEW.get(0).b5.get_x()
tx := '(5) (1)'
aEW.get(0).b5.set_text('')
else
tx := '(1)'
//
wave = Ewave.new(
l1 = line.new (_1x, _1y, _2x, _2y , color=col , style= line.style_solid ),
l2 = line.new (_2x, _2y, _3x, _3y , color=col , style= line.style_solid ),
l3 = line.new (_3x, _3y, _4x, _4y , color=col , style= line.style_solid ),
l4 = line.new (_4x, _4y, _5x, _5y , color=col , style= line.style_solid ),
l5 = line.new (_5x, _5y, _6x, _6y , color=col , style= line.style_solid ),
b1 = label.new(_2x, _2y, text= t + tx, textcolor=col, color= color(na), style=label.style_label_up ),
b2 = label.new(_3x, _3y, text= '(2)' + t, textcolor=col, color= color(na), style=label.style_label_down),
b3 = label.new(_4x, _4y, text= t + '(3)', textcolor=col, color= color(na), style=label.style_label_up ),
b4 = label.new(_5x, _5y, text= '(4)' + t, textcolor=col, color= color(na), style=label.style_label_down),
b5 = label.new(_6x, _6y, text= t + '(5)', textcolor=col, color= color(na), style=label.style_label_up ),
on = true ,
br = false ,
dir =-1
)
aEW.unshift(wave)
nFibL._break_ := false
alert('New EW Motive Bearish Pattern found' , alert.freq_once_per_bar_close)
//
if not isWave
if same and gEW.on == true
gEW.dot()
alert('Invalidated EW Motive Bearish Pattern', alert.freq_once_per_bar_close)
//
// –––––––––––––––––––––[ ABC ]–––––––––––––––––––––
getEW = aEW.get(0)
last_0x := getEW.l1.get_x1(), last_0y := getEW.l1.get_y1()
last_6x := getEW.l5.get_x2(), last_6y := getEW.l5.get_y2()
diff = math.abs(last_6y - last_0y)
//
if getEW.dir == 1
getX = getEW.l5.get_x2()
getY = getEW.l5.get_y2()
isSame2 = getEW.isSame2 (_1x, _2x, _3x)
isValid =
_3x == getX and
_6y > getY - (diff * i_854) and
_4y > getY - (diff * i_854) and
_5y < getY
//
if isValid
width = _6x - _2x // –––[ width (4) - (c) ]–––
if isSame2 and getEW.bA.get_x() > _3x
getEW.lC.set_xy1(_5x, _5y), getEW.lC.set_xy2(_6x, _6y), getEW.bC.set_xy(_6x, _6y), getEW.bx.set_lefttop(_6x, _6y), getEW.bx.set_right(_6x + width)
else
getEW.lA := line.new (_3x, _3y, _4x, _4y, color=col), getEW.bA := label.new(_4x, _4y, text= t + '(a)', textcolor=col, color= color(na), style=label.style_label_up )
getEW.lB := line.new (_4x, _4y, _5x, _5y, color=col), getEW.bB := label.new(_5x, _5y, text= '(b)' + t, textcolor=col, color= color(na), style=label.style_label_down)
getEW.lC := line.new (_5x, _5y, _6x, _6y, color=col), getEW.bC := label.new(_6x, _6y, text= t + '(c)', textcolor=col, color= color(na), style=label.style_label_up )
getEW.bx := box.new (_6x, _6y, _6x + width, _4y, bgcolor=color.new(col, 93), border_color=color.new(col, 65))
alert('New EW Corrective Bearish Pattern found' , alert.freq_once_per_bar_close)
else
if isSame2 and getEW.bA.get_x() > _3x
getEW.dash()
alert('Invalidated EW Corrective Bullish Pattern', alert.freq_once_per_bar_close)
//
// –––[ check (only once) for a possible new (1) after an impulsive AND corrective wave ]–––
if getEW.dir == -1
if _5x == getEW.bC.get_x() and
_6y < getEW.b5.get_y() and
getEW.next == false
getEW.next := true
getEW.lb := label.new(_6x, _6y, style=label.style_circle, color=color.new(col, 65), yloc=yloc.belowbar, size=size.tiny)
alert('Possible new start of EW Motive Bearish Wave', alert.freq_once_per_bar_close)
//
// –––[ check for break box ]–––
if aEW.size() > 0
gEW := aEW.get(0)
if gEW.dir == 1
if ta.crossunder(low , gEW.bx.get_bottom()) and bar_index <= gEW.bx.get_right()
label.new(bar_index, low , yloc= yloc.belowbar, style= label.style_xcross, color=color.red, size=size.tiny)
else
if ta.crossover (high, gEW.bx.get_top ()) and bar_index <= gEW.bx.get_right()
label.new(bar_index, high, yloc= yloc.abovebar, style= label.style_xcross, color=color.red, size=size.tiny)
//
if barstate.islast
// –––[ get last 2 EW's ]–––
getEW = aEW.get(0)
if aEW.size() > 1
getEW1 = aEW.get(1)
last_0x := getEW.l1.get_x1(), last_0y := getEW.l1.get_y1()
last_6x := getEW.l5.get_x2(), last_6y := getEW.l5.get_y2()
//
diff = math.abs(last_6y - last_0y) // –––[ max/min difference ]–––
_500 = diff * i_500
_618 = diff * i_618
_764 = diff * i_764
_854 = diff * i_854
bull = getEW.dir == 1
// –––[ if EW is not valid or an ABC has developed -> remove fibonacci lines ]–––
if getEW.on == false or getEW.bC.get_x() > getEW.b5.get_x()
nFibL.setNa()
else
// –––[ get.on == true ~ valid EW ]–––
max_500 = last_6y + ((bull ? -1 : 1) * _500)
max_618 = last_6y + ((bull ? -1 : 1) * _618)
max_764 = last_6y + ((bull ? -1 : 1) * _764)
max_854 = last_6y + ((bull ? -1 : 1) * _854)
//
nFibL.set(last_6x, bar_index + 10, max_500, max_618, max_764, max_854, last_6y)
// –––[ if (2) label overlap with (C) label ]–––
if getEW.b2.get_x() == getEW1.bC.get_x()
getEW.b1.set_textcolor(color(na))
getEW.b2.set_textcolor(color(na))
strB = getEW1.bB.get_text()
strC = getEW1.bC.get_text()
strB_ = str.replace(strB, "(b)", "(b) (1)", 0)
strC_ = str.replace(strC, "(c)", "(c) (2)", 0)
getEW1.bB.set_text(strB_)
getEW1.bC.set_text(strC_)
//
// –––[ check if fib limits are broken ]–––
getP_854 = nFibL.wave1_0_854.get_y1()
for i = 0 to bar_index - nFibL.wave1_0_854.get_x1()
if getEW.dir == -1
if high[i] > getP_854
nFibL._break_ := true
break
else
if low [i] < getP_854
nFibL._break_ := true
break
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
switch nFibL._break_
true => nFibL.sol_dot('dot', color.new(color.red , 95))
false => nFibL.sol_dot('sol', color.new(color.lime, 95))
=>
nFibL.wave1_0_500.set_xy1(na, na)
nFibL.wave1_0_500.set_xy2(na, na)
nFibL.wave1_0_618.set_xy1(na, na)
nFibL.wave1_0_618.set_xy2(na, na)
nFibL.wave1_0_764.set_xy1(na, na)
nFibL.wave1_0_764.set_xy2(na, na)
nFibL.wave1_0_854.set_xy1(na, na)
nFibL.wave1_0_854.set_xy2(na, na)
nFibL.wave1_pole_.set_xy1(na, na)
nFibL.wave1_pole_.set_xy2(na, na)
nFibL.l_fill_.set_color(color(na))
if aEW.size() > 15
pop = aEW.pop()
pop.l1.delete(), pop.b1.delete()
pop.l2.delete(), pop.b2.delete()
pop.l3.delete(), pop.b3.delete()
pop.l4.delete(), pop.b4.delete()
pop.l5.delete(), pop.b5.delete()
pop.lA.delete(), pop.bA.delete()
pop.lB.delete(), pop.bB.delete()
pop.lC.delete(), pop.bC.delete()
pop.lb.delete(), pop.bx.delete()
//----------------------------------
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
draw(s1, len1, col1, 0)
draw(s2, len2, col2, 1)
draw(s3, len3, col3, 2)
//-----------------------------------------------------------------------------} |
Weekly Opening GAP | https://www.tradingview.com/script/OEAEvOz1-Weekly-Opening-GAP/ | aaronmefford | https://www.tradingview.com/u/aaronmefford/ | 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/
//@version=5
// © aaronmefford
indicator("Weekly GAP", shorttitle="WGaps", overlay=true )
daily_session = input.session("0930-1600","Session Period",options=["0930-1600"])
boxColor = input.color(color.orange,"Box Color")
showBoxes = input.bool(true,"Show Boxes")
showLines = input.bool(true,"Show Lines")
showWeek2 = input.bool(true,"Show Last Week Lines")
showWeek3 = input.bool(true,"Show Third Week Lines")
showWeek4 = input.bool(true,"Show Fourth Week Lines")
showWeek5 = input.bool(false,"Show Fifth Week Lines")
showWeek6 = input.bool(false,"Show Sixth Week Lines")
showWeek7 = input.bool(false,"Show Seventh Week Lines")
showWeek8 = input.bool(false,"Show Eighth Week Lines")
showWeek9 = input.bool(false,"Show Ninth Week Lines")
showWeek10 = input.bool(false,"Show Tenth Week Lines")
int week = na
is_session(sess) =>
not na(time(timeframe.period, sess, "America/New_York"))
bool inSession = is_session(daily_session)
float daily_close = na
float weekly_close = na
float gap_half = na
var line[] gap_levels = array.new_line()
var box[] gap_boxes = array.new_box()
float week1_top = na
float week1_bottom = na
float week2_top = na
float week2_bottom = na
float week3_top = na
float week3_bottom = na
float week4_top = na
float week4_bottom = na
float week5_top = na
float week5_bottom = na
float week6_top = na
float week6_bottom = na
float week7_top = na
float week7_bottom = na
float week8_top = na
float week8_bottom = na
float week9_top = na
float week9_bottom = na
float week10_top = na
float week10_bottom = na
daily_close := daily_close[1]
weekly_close := weekly_close[1]
week := week[1]
week1_top := week1_top[1]
week1_bottom := week1_bottom[1]
week2_top := week2_top[1]
week2_bottom := week2_bottom[1]
week3_top := week3_top[1]
week3_bottom := week3_bottom[1]
week4_top := week4_top[1]
week4_bottom := week4_bottom[1]
week5_top := week5_top[1]
week5_bottom := week5_bottom[1]
week6_top := week6_top[1]
week6_bottom := week6_bottom[1]
week7_top := week7_top[1]
week7_bottom := week7_bottom[1]
week8_top := week8_top[1]
week8_bottom := week8_bottom[1]
week9_top := week9_top[1]
week9_bottom := week9_bottom[1]
week10_top := week10_top[1]
week10_bottom := week10_bottom[1]
if inSession[1] == true and not inSession
daily_close := na
else if inSession[2] == true and not inSession[1] and not inSession
daily_close := close[2]
if inSession
week := weekofyear(time(timeframe.period), "America/New_York")
bool new_week = not inSession[1] and inSession and week != week[1]
if new_week
weekly_close := na
week1_top := na
week1_bottom := na
week2_top := na
week2_bottom := na
week3_top := na
week3_bottom := na
week4_top := na
week4_bottom := na
week5_top := na
week5_bottom := na
week6_top := na
week6_bottom := na
week7_top := na
week7_bottom := na
week8_top := na
week8_bottom := na
week9_top := na
week9_bottom := na
week10_top := na
week10_bottom := na
else if new_week[1]
weekly_close := daily_close[2]
level = line.new(bar_index-1,weekly_close,bar_index,weekly_close,xloc.bar_index,extend = extend.right,color = boxColor,style = line.style_solid,width=4)
array.push(gap_levels,level)
top = math.max(open[1],weekly_close)
bottom = math.min(open[1], weekly_close)
gap_qtr = (top-bottom) / 4
array.push(gap_levels,line.new(bar_index-1,bottom+gap_qtr*1,bar_index,bottom+gap_qtr*1,xloc.bar_index,extend = extend.right,color = boxColor,style = line.style_dashed,width=1))
array.push(gap_levels,line.new(bar_index-1,bottom+gap_qtr*2,bar_index,bottom+gap_qtr*2,xloc.bar_index,extend = extend.right,color = boxColor,style = line.style_dashed,width=1))
array.push(gap_levels,line.new(bar_index-1,bottom+gap_qtr*3,bar_index,bottom+gap_qtr*3,xloc.bar_index,extend = extend.right,color = boxColor,style = line.style_dashed,width=1))
array.push(gap_boxes,box.new(bar_index-1,top,bar_index+10,bottom,boxColor,2,line.style_solid,extend.right,xloc.bar_index,color.new(boxColor,80)))
week1_top := top
week1_bottom := bottom
week2_top := week1_top[2]
week2_bottom := week1_bottom[2]
week3_top := week2_top[2]
week3_bottom := week2_bottom[2]
week4_top := week3_top[2]
week4_bottom := week3_bottom[2]
week5_top := week4_top[2]
week5_bottom := week4_bottom[2]
week6_top := week5_top[2]
week6_bottom := week5_bottom[2]
week7_top := week6_top[2]
week7_bottom := week6_bottom[2]
week8_top := week7_top[2]
week8_bottom := week7_bottom[2]
week9_top := week8_top[2]
week9_bottom := week8_bottom[2]
week10_top := week9_top[2]
week10_bottom := week9_bottom[2]
if inSession
for [lineNo,this_line] in gap_levels
y = line.get_y2(this_line)
if (low <= y and high >= y)
array.remove(gap_levels,lineNo)
line.set_x2(this_line,bar_index)
line.set_extend(this_line,extend.none)
for [lineNo,gap_box] in gap_boxes
h = box.get_top(gap_box)
l = box.get_bottom(gap_box)
if (low < h and high[1] >= h)
array.remove(gap_boxes,lineNo)
box.set_right(gap_box,bar_index)
box.set_extend(gap_box,extend.none)
if low > l
array.push(gap_boxes,box.new(bar_index,low,bar_index+1,l,boxColor,2,line.style_solid,extend.right,xloc.bar_index,color.new(boxColor,90)))
else if ( high > l and low[1] <= l)
array.remove(gap_boxes,lineNo)
box.set_right(gap_box,bar_index)
box.set_extend(gap_box,extend.none)
if high < h
array.push(gap_boxes,box.new(bar_index,h,bar_index+1,high,boxColor,2,line.style_solid,extend.right,xloc.bar_index,color.new(boxColor,90)))
plot(showLines?week1_top:na,"Week1 Top",color.aqua,2,plot.style_linebr,display=display.pane)
plot(showLines?week1_bottom:na,"Week1 Bottom",color.aqua,2,plot.style_linebr,display=display.pane)
plot(showWeek2?week2_top:na,"Week2 Top",color.fuchsia,2,plot.style_linebr,display=display.pane)
plot(showWeek2?week2_bottom:na,"Week2 Bottom",color.fuchsia,2,plot.style_linebr,display=display.pane)
plot(showWeek3?week3_top:na,"Week3 Top",color.teal,2,plot.style_linebr,display=display.pane)
plot(showWeek3?week3_bottom:na,"Week3 Bottom",color.teal,2,plot.style_linebr,display=display.pane)
plot(showWeek4?week4_top:na,"Week2 Top",color.lime,2,plot.style_linebr,display=display.pane)
plot(showWeek4?week4_bottom:na,"Week2 Bottom",color.lime,2,plot.style_linebr,display=display.pane)
plot(showWeek5?week5_top:na,"Week5 Top",color.lime,2,plot.style_linebr,display=display.pane)
plot(showWeek5?week5_bottom:na,"Week5 Bottom",color.lime,2,plot.style_linebr,display=display.pane)
plot(showWeek6?week6_top:na,"Week6 Top",color.lime,2,plot.style_linebr,display=display.pane)
plot(showWeek6?week6_bottom:na,"Week6 Bottom",color.lime,2,plot.style_linebr,display=display.pane)
plot(showWeek7?week7_top:na,"Week7 Top",color.lime,2,plot.style_linebr,display=display.pane)
plot(showWeek7?week7_bottom:na,"Week7 Bottom",color.lime,2,plot.style_linebr,display=display.pane)
plot(showWeek8?week8_top:na,"Week8 Top",color.lime,2,plot.style_linebr,display=display.pane)
plot(showWeek8?week8_bottom:na,"Week8 Bottom",color.lime,2,plot.style_linebr,display=display.pane)
plot(showWeek9?week9_top:na,"Week9 Top",color.lime,2,plot.style_linebr,display=display.pane)
plot(showWeek9?week9_bottom:na,"Week9 Bottom",color.lime,2,plot.style_linebr,display=display.pane)
plot(showWeek10?week10_top:na,"Week9 Top",color.lime,2,plot.style_linebr,display=display.pane)
plot(showWeek10?week10_bottom:na,"Week9 Bottom",color.lime,2,plot.style_linebr,display=display.pane)
|
Multi Timeframe Moving Averages | https://www.tradingview.com/script/5UPnfqZF-Multi-Timeframe-Moving-Averages/ | jstntham | https://www.tradingview.com/u/jstntham/ | 30 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jstntham
// _ _ _ _
// (_)___| |_ _ __ | |_| |__ __ _ _ __ ___
// | / __| __| '_ \| __| '_ \ / _` | '_ ` _ \
// | \__ \ |_| | | | |_| | | | (_| | | | | | |
// _/ |___/\__|_| |_|\__|_| |_|\__,_|_| |_| |_|
// |__/
//filename: JT MTF MA.pine
//@version=5
indicator(title = "Multi Timeframe Moving Averages", shorttitle = "MTF MA [JT]", overlay=true)
// *********************************************************************************
// moving averages - 200, 13, 21, 34, 55
// ma timeframes - W, D, 4H, 1H
// *********************************************************************************
// configuration
MA1 = input.int(defval=200, title="Moving Average 1", step=1, inline="MA1")
MA1COLOR = input.color(defval = #0000007f, title = "", inline = "MA1")
MA1SHOW = input.bool(defval = true, title = "", inline = "MA1")
MA2 = input.int(defval=13, title="Moving Average 2", step=1, inline="MA2")
MA2COLOR = input.color(defval = #ff00007f, title = "", inline = "MA2")
MA2SHOW = input.bool(defval = true, title = "", inline = "MA2")
MA3 = input.int(defval=21, title="Moving Average 3", step=1, inline="MA3")
MA3COLOR = input.color(defval = #4caf507f, title = "", inline = "MA3")
MA3SHOW = input.bool(defval = true, title = "", inline = "MA3")
MA4 = input.int(defval=34, title="Moving Average 4", step=1, inline="MA4")
MA4COLOR = input.color(defval = #ff98007f, title = "", inline = "MA4")
MA4SHOW = input.bool(defval = true, title = "", inline = "MA4")
MA5 = input.int(defval=55, title="Moving Average 5", step=1, inline="MA5")
MA5COLOR = input.color(defval = #b228337f, title = "", inline = "MA5")
MA5SHOW = input.bool(defval = true, title = "", inline = "MA5")
SHOWW = input.bool(defval = true, title="Show Weekly", inline = "W")
SHOWD = input.bool(defval = true, title = "Show Daily", inline = "D")
SHOW4H = input.bool(defval = true, title = "Show 4H", inline = "4H")
SHOW1H = input.bool(defval = true, title = "Show 1H", inline = "1H")
// *********************************************************************************
// variables
[MA1_W_EMA, MA2_W_EMA, MA3_W_EMA, MA4_W_EMA, MA5_W_EMA] = request.security(syminfo.tickerid, "W", [ta.ema(close, MA1),ta.ema(close, MA2),ta.ema(close, MA3),ta.ema(close, MA4),ta.ema(close, MA5)])
[MA1_D_EMA, MA2_D_EMA, MA3_D_EMA, MA4_D_EMA, MA5_D_EMA] = request.security(syminfo.tickerid, "D", [ta.ema(close, MA1),ta.ema(close, MA2),ta.ema(close, MA3),ta.ema(close, MA4),ta.ema(close, MA5)])
[MA1_4H_EMA, MA2_4H_EMA, MA3_4H_EMA, MA4_4H_EMA, MA5_4H_EMA] = request.security(syminfo.tickerid, "240", [ta.ema(close, MA1),ta.ema(close, MA2),ta.ema(close, MA3),ta.ema(close, MA4),ta.ema(close, MA5)])
[MA1_1H_EMA, MA2_1H_EMA, MA3_1H_EMA, MA4_1H_EMA, MA5_1H_EMA] = request.security(syminfo.tickerid, "60", [ta.ema(close, MA1),ta.ema(close, MA2),ta.ema(close, MA3),ta.ema(close, MA4),ta.ema(close, MA5)])
// *********************************************************************************
// functions
// *********************************************************************************
// indicator logic
//Weekly
var PMA1_W_EMA = line.new(y1=MA1_W_EMA[0], x1=bar_index, y2=MA1_W_EMA, x2=bar_index - 1, extend = extend.right, color = MA1COLOR, width = 2)
var LMA1_W_EMA = label.new(y=MA1_W_EMA[0], x=bar_index, text=str.tostring(MA1, "# MA(W)"), color=#00000000, textcolor=MA1COLOR, style=label.style_label_left)
var PMA2_W_EMA = line.new(y1=MA2_W_EMA[0], x1=bar_index, y2=MA2_W_EMA, x2=bar_index - 1, extend = extend.right, color = MA2COLOR, width = 2)
var LMA2_W_EMA = label.new(y=MA2_W_EMA[0], x=bar_index, text=str.tostring(MA2, "# MA(W)"), color=#00000000, textcolor=MA2COLOR, style=label.style_label_left)
var PMA3_W_EMA = line.new(y1=MA3_W_EMA[0], x1=bar_index, y2=MA3_W_EMA, x2=bar_index - 1, extend = extend.right, color = MA3COLOR, width = 2)
var LMA3_W_EMA = label.new(y=MA3_W_EMA[0], x=bar_index, text=str.tostring(MA3, "# MA(W)"), color=#00000000, textcolor=MA3COLOR, style=label.style_label_left)
var PMA4_W_EMA = line.new(y1=MA4_W_EMA[0], x1=bar_index, y2=MA4_W_EMA, x2=bar_index - 1, extend = extend.right, color = MA4COLOR, width = 2)
var LMA4_W_EMA = label.new(y=MA4_W_EMA[0], x=bar_index, text=str.tostring(MA4, "# MA(W)"), color=#00000000, textcolor=MA4COLOR, style=label.style_label_left)
var PMA5_W_EMA = line.new(y1=MA5_W_EMA[0], x1=bar_index, y2=MA5_W_EMA, x2=bar_index - 1, extend = extend.right, color = MA5COLOR, width = 2)
var LMA5_W_EMA = label.new(y=MA5_W_EMA[0], x=bar_index, text=str.tostring(MA5, "# MA(W)"), color=#00000000, textcolor=MA5COLOR, style=label.style_label_left)
if (SHOWW)
line.set_xy1(PMA1_W_EMA, bar_index, MA1_W_EMA)
line.set_xy2(PMA1_W_EMA, bar_index - 1, MA1_W_EMA)
label.set_xy(LMA1_W_EMA, bar_index, MA1_W_EMA)
line.set_xy1(PMA2_W_EMA, bar_index, MA2_W_EMA)
line.set_xy2(PMA2_W_EMA, bar_index - 1, MA2_W_EMA)
label.set_xy(LMA2_W_EMA, bar_index, MA2_W_EMA)
line.set_xy1(PMA3_W_EMA, bar_index, MA3_W_EMA)
line.set_xy2(PMA3_W_EMA, bar_index - 1, MA3_W_EMA)
label.set_xy(LMA3_W_EMA, bar_index, MA3_W_EMA)
line.set_xy1(PMA4_W_EMA, bar_index, MA4_W_EMA)
line.set_xy2(PMA4_W_EMA, bar_index - 1, MA4_W_EMA)
label.set_xy(LMA4_W_EMA, bar_index, MA4_W_EMA)
line.set_xy1(PMA5_W_EMA, bar_index, MA5_W_EMA)
line.set_xy2(PMA5_W_EMA, bar_index - 1, MA5_W_EMA)
label.set_xy(LMA5_W_EMA, bar_index, MA5_W_EMA)
else
line.delete(PMA1_W_EMA)
line.delete(PMA2_W_EMA)
line.delete(PMA3_W_EMA)
line.delete(PMA4_W_EMA)
line.delete(PMA5_W_EMA)
//Daily
var PMA1_D_EMA = line.new(y1=MA1_D_EMA[0], x1=bar_index, y2=MA1_D_EMA, x2=bar_index - 1, extend = extend.right, color = MA1COLOR, width = 2)
var LMA1_D_EMA = label.new(y=MA1_D_EMA[0], x=bar_index, text=str.tostring(MA1, "# MA(D)"), color=#00000000, textcolor=MA1COLOR, style=label.style_label_left)
var PMA2_D_EMA = line.new(y1=MA2_D_EMA[0], x1=bar_index, y2=MA2_D_EMA, x2=bar_index - 1, extend = extend.right, color = MA2COLOR, width = 2)
var LMA2_D_EMA = label.new(y=MA2_D_EMA[0], x=bar_index, text=str.tostring(MA2, "# MA(D)"), color=#00000000, textcolor=MA2COLOR, style=label.style_label_left)
var PMA3_D_EMA = line.new(y1=MA3_D_EMA[0], x1=bar_index, y2=MA3_D_EMA, x2=bar_index - 1, extend = extend.right, color = MA3COLOR, width = 2)
var LMA3_D_EMA = label.new(y=MA3_D_EMA[0], x=bar_index, text=str.tostring(MA3, "# MA(D)"), color=#00000000, textcolor=MA3COLOR, style=label.style_label_left)
var PMA4_D_EMA = line.new(y1=MA4_D_EMA[0], x1=bar_index, y2=MA4_D_EMA, x2=bar_index - 1, extend = extend.right, color = MA4COLOR, width = 2)
var LMA4_D_EMA = label.new(y=MA4_D_EMA[0], x=bar_index, text=str.tostring(MA4, "# MA(D)"), color=#00000000, textcolor=MA4COLOR, style=label.style_label_left)
var PMA5_D_EMA = line.new(y1=MA5_D_EMA[0], x1=bar_index, y2=MA5_D_EMA, x2=bar_index - 1, extend = extend.right, color = MA5COLOR, width = 2)
var LMA5_D_EMA = label.new(y=MA5_D_EMA[0], x=bar_index, text=str.tostring(MA5, "# MA(D)"), color=#00000000, textcolor=MA5COLOR, style=label.style_label_left)
if (SHOWD)
line.set_xy1(PMA1_D_EMA, bar_index, MA1_D_EMA)
line.set_xy2(PMA1_D_EMA, bar_index - 1, MA1_D_EMA)
label.set_xy(LMA1_D_EMA, bar_index, MA1_D_EMA)
line.set_xy1(PMA2_D_EMA, bar_index, MA2_D_EMA)
line.set_xy2(PMA2_D_EMA, bar_index - 1, MA2_D_EMA)
label.set_xy(LMA2_D_EMA, bar_index, MA2_D_EMA)
line.set_xy1(PMA3_D_EMA, bar_index, MA3_D_EMA)
line.set_xy2(PMA3_D_EMA, bar_index - 1, MA3_D_EMA)
label.set_xy(LMA3_D_EMA, bar_index, MA3_D_EMA)
line.set_xy1(PMA4_D_EMA, bar_index, MA4_D_EMA)
line.set_xy2(PMA4_D_EMA, bar_index - 1, MA4_D_EMA)
label.set_xy(LMA4_D_EMA, bar_index, MA4_D_EMA)
line.set_xy1(PMA5_D_EMA, bar_index, MA5_D_EMA)
line.set_xy2(PMA5_D_EMA, bar_index - 1, MA5_D_EMA)
label.set_xy(LMA5_D_EMA, bar_index, MA5_D_EMA)
else
line.delete(PMA1_D_EMA)
line.delete(PMA2_D_EMA)
line.delete(PMA3_D_EMA)
line.delete(PMA4_D_EMA)
line.delete(PMA5_D_EMA)
//4 hour
var PMA1_4H_EMA = line.new(y1=MA1_4H_EMA[0], x1=bar_index, y2=MA1_4H_EMA, x2=bar_index - 1, extend = extend.right, color = MA1COLOR, width = 2)
var LMA1_4H_EMA = label.new(y=MA1_4H_EMA[0], x=bar_index, text=str.tostring(MA1, "# MA(4H)"), color=#00000000, textcolor=MA1COLOR, style=label.style_label_left)
var PMA2_4H_EMA = line.new(y1=MA2_4H_EMA[0], x1=bar_index, y2=MA2_4H_EMA, x2=bar_index - 1, extend = extend.right, color = MA2COLOR, width = 2)
var LMA2_4H_EMA = label.new(y=MA2_4H_EMA[0], x=bar_index, text=str.tostring(MA2, "# MA(4H)"), color=#00000000, textcolor=MA2COLOR, style=label.style_label_left)
var PMA3_4H_EMA = line.new(y1=MA3_4H_EMA[0], x1=bar_index, y2=MA3_4H_EMA, x2=bar_index - 1, extend = extend.right, color = MA3COLOR, width = 2)
var LMA3_4H_EMA = label.new(y=MA3_4H_EMA[0], x=bar_index, text=str.tostring(MA3, "# MA(4H)"), color=#00000000, textcolor=MA3COLOR, style=label.style_label_left)
var PMA4_4H_EMA = line.new(y1=MA4_4H_EMA[0], x1=bar_index, y2=MA4_4H_EMA, x2=bar_index - 1, extend = extend.right, color = MA4COLOR, width = 2)
var LMA4_4H_EMA = label.new(y=MA4_4H_EMA[0], x=bar_index, text=str.tostring(MA4, "# MA(4H)"), color=#00000000, textcolor=MA4COLOR, style=label.style_label_left)
var PMA5_4H_EMA = line.new(y1=MA5_4H_EMA[0], x1=bar_index, y2=MA5_4H_EMA, x2=bar_index - 1, extend = extend.right, color = MA5COLOR, width = 2)
var LMA5_4H_EMA = label.new(y=MA5_4H_EMA[0], x=bar_index, text=str.tostring(MA5, "# MA(4H)"), color=#00000000, textcolor=MA5COLOR, style=label.style_label_left)
if (SHOW4H)
line.set_xy1(PMA1_4H_EMA, bar_index, MA1_4H_EMA)
line.set_xy2(PMA1_4H_EMA, bar_index - 1, MA1_4H_EMA)
label.set_xy(LMA1_4H_EMA, bar_index, MA1_4H_EMA)
line.set_xy1(PMA2_4H_EMA, bar_index, MA2_4H_EMA)
line.set_xy2(PMA2_4H_EMA, bar_index - 1, MA2_4H_EMA)
label.set_xy(LMA2_4H_EMA, bar_index, MA2_4H_EMA)
line.set_xy1(PMA3_4H_EMA, bar_index, MA3_4H_EMA)
line.set_xy2(PMA3_4H_EMA, bar_index - 1, MA3_4H_EMA)
label.set_xy(LMA3_4H_EMA, bar_index, MA3_4H_EMA)
line.set_xy1(PMA4_4H_EMA, bar_index, MA4_4H_EMA)
line.set_xy2(PMA4_4H_EMA, bar_index - 1, MA4_4H_EMA)
label.set_xy(LMA4_4H_EMA, bar_index, MA4_4H_EMA)
line.set_xy1(PMA5_4H_EMA, bar_index, MA5_4H_EMA)
line.set_xy2(PMA5_4H_EMA, bar_index - 1, MA5_4H_EMA)
label.set_xy(LMA5_4H_EMA, bar_index, MA5_4H_EMA)
else
line.delete(PMA1_4H_EMA)
line.delete(PMA2_4H_EMA)
line.delete(PMA3_4H_EMA)
line.delete(PMA4_4H_EMA)
line.delete(PMA5_4H_EMA)
//1 hour
var PMA1_1H_EMA = line.new(y1=MA1_1H_EMA[0], x1=bar_index, y2=MA1_1H_EMA, x2=bar_index - 1, extend = extend.right, color = MA1COLOR, width = 2)
var LMA1_1H_EMA = label.new(y=MA1_1H_EMA[0], x=bar_index, text=str.tostring(MA1, "# MA(1H)"), color=#00000000, textcolor=MA1COLOR, style=label.style_label_left)
var PMA2_1H_EMA = line.new(y1=MA2_1H_EMA[0], x1=bar_index, y2=MA2_1H_EMA, x2=bar_index - 1, extend = extend.right, color = MA2COLOR, width = 2)
var LMA2_1H_EMA = label.new(y=MA2_1H_EMA[0], x=bar_index, text=str.tostring(MA2, "# MA(1H)"), color=#00000000, textcolor=MA2COLOR, style=label.style_label_left)
var PMA3_1H_EMA = line.new(y1=MA3_1H_EMA[0], x1=bar_index, y2=MA3_1H_EMA, x2=bar_index - 1, extend = extend.right, color = MA3COLOR, width = 2)
var LMA3_1H_EMA = label.new(y=MA3_1H_EMA[0], x=bar_index, text=str.tostring(MA3, "# MA(1H)"), color=#00000000, textcolor=MA3COLOR, style=label.style_label_left)
var PMA4_1H_EMA = line.new(y1=MA4_1H_EMA[0], x1=bar_index, y2=MA4_1H_EMA, x2=bar_index - 1, extend = extend.right, color = MA4COLOR, width = 2)
var LMA4_1H_EMA = label.new(y=MA4_1H_EMA[0], x=bar_index, text=str.tostring(MA4, "# MA(1H)"), color=#00000000, textcolor=MA4COLOR, style=label.style_label_left)
var PMA5_1H_EMA = line.new(y1=MA5_1H_EMA[0], x1=bar_index, y2=MA5_1H_EMA, x2=bar_index - 1, extend = extend.right, color = MA5COLOR, width = 2)
var LMA5_1H_EMA = label.new(y=MA5_1H_EMA[0], x=bar_index, text=str.tostring(MA5, "# MA(1H)"), color=#00000000, textcolor=MA5COLOR, style=label.style_label_left)
if (SHOW1H)
line.set_xy1(PMA1_1H_EMA, bar_index, MA1_1H_EMA)
line.set_xy2(PMA1_1H_EMA, bar_index - 1, MA1_1H_EMA)
label.set_xy(LMA1_1H_EMA, bar_index, MA1_1H_EMA)
line.set_xy1(PMA2_1H_EMA, bar_index, MA2_1H_EMA)
line.set_xy2(PMA2_1H_EMA, bar_index - 1, MA2_1H_EMA)
label.set_xy(LMA2_1H_EMA, bar_index, MA2_1H_EMA)
line.set_xy1(PMA3_1H_EMA, bar_index, MA3_1H_EMA)
line.set_xy2(PMA3_1H_EMA, bar_index - 1, MA3_1H_EMA)
label.set_xy(LMA3_1H_EMA, bar_index, MA3_1H_EMA)
line.set_xy1(PMA4_1H_EMA, bar_index, MA4_1H_EMA)
line.set_xy2(PMA4_1H_EMA, bar_index - 1, MA4_1H_EMA)
label.set_xy(LMA4_1H_EMA, bar_index, MA4_1H_EMA)
line.set_xy1(PMA5_1H_EMA, bar_index, MA5_1H_EMA)
line.set_xy2(PMA5_1H_EMA, bar_index - 1, MA5_1H_EMA)
label.set_xy(LMA5_1H_EMA, bar_index, MA5_1H_EMA)
else
line.delete(PMA1_1H_EMA)
line.delete(PMA2_1H_EMA)
line.delete(PMA3_1H_EMA)
line.delete(PMA4_1H_EMA)
line.delete(PMA5_1H_EMA)
if (not MA1SHOW)
line.delete(PMA1_W_EMA)
line.delete(PMA1_D_EMA)
line.delete(PMA1_4H_EMA)
line.delete(PMA1_1H_EMA)
label.delete(LMA1_W_EMA)
label.delete(LMA1_D_EMA)
label.delete(LMA1_4H_EMA)
label.delete(LMA1_1H_EMA)
if (not MA2SHOW)
line.delete(PMA2_W_EMA)
line.delete(PMA2_D_EMA)
line.delete(PMA2_4H_EMA)
line.delete(PMA2_1H_EMA)
label.delete(LMA2_W_EMA)
label.delete(LMA2_D_EMA)
label.delete(LMA2_4H_EMA)
label.delete(LMA2_1H_EMA)
if (not MA3SHOW)
line.delete(PMA3_W_EMA)
line.delete(PMA3_D_EMA)
line.delete(PMA3_4H_EMA)
line.delete(PMA3_1H_EMA)
label.delete(LMA3_W_EMA)
label.delete(LMA3_D_EMA)
label.delete(LMA3_4H_EMA)
label.delete(LMA3_1H_EMA)
if (not MA4SHOW)
line.delete(PMA4_W_EMA)
line.delete(PMA4_D_EMA)
line.delete(PMA4_4H_EMA)
line.delete(PMA4_1H_EMA)
label.delete(LMA4_W_EMA)
label.delete(LMA4_D_EMA)
label.delete(LMA4_4H_EMA)
label.delete(LMA4_1H_EMA)
if (not MA5SHOW)
line.delete(PMA5_W_EMA)
line.delete(PMA5_D_EMA)
line.delete(PMA5_4H_EMA)
line.delete(PMA5_1H_EMA)
label.delete(LMA5_W_EMA)
label.delete(LMA5_D_EMA)
label.delete(LMA5_4H_EMA)
label.delete(LMA5_1H_EMA)
|
Market Condition Detector | https://www.tradingview.com/script/tXMfSJNH/ | Fred6724 | https://www.tradingview.com/u/Fred6724/ | 422 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Fred6724
//@version=5
indicator(title="Market Condition Detector", overlay=true)
// Net High Lows
ref = input("SP:SPX", title = 'Reference Ticker') // Changed to SP:SPX
NNH = input("HIGQ", title = 'Net New High Ticker')
NNL = input("LOWQ", title = 'Net New Low Ticker')
hi_q = request.security(NNH, 'D', close)
lo_q = request.security(NNL, 'D', close)
//Input.
//i_plotBoth = input(false, title='Plot New Highs and Lows Separately')
// i_upColor = input(color.green, title='Color Up')
// i_dnColor = input(color.red, title='Color Down')
i_posBackgroundColor = input(color.rgb(76, 175, 80, 85), title='Background Color Up')
i_negBackgroundColor = input(color.rgb(255, 82, 82, 85), title='Background Color Down')
h_q = hi_q
l_q = lo_q
hi_lo = h_q - l_q
//mycolor = hi_lo > 0 ? i_upColor:i_dnColor
// Add color to the script
// Conditions
condGreen = hi_lo > 0 and hi_lo[1] > 0 and hi_lo[2] > 0 ? true:false
condRed = hi_lo < 0 and hi_lo[1] < 0 and hi_lo[2] < 0 ? true:false
// EMA 10 & 20 Da
// SMA/EMA Calculation
ema10 = request.security(ref,'D',ta.ema(close,10))
ema20 = request.security(ref,'D',ta.ema(close,20))
// Da
daEma10 = request.security(ref, 'D', ema10)
daEma20 = request.security(ref, 'D', ema20)
// Da Close
closeDa = request.security(ref, 'D', close)
// hi_lo > 0 = bar net high verte
// Conditions
condUp = hi_lo > 0 and daEma10 > daEma20 and closeDa > daEma20
condDn = hi_lo < 0 and daEma10 < daEma20 and closeDa < daEma20
//Exceptions
// BULLISH
// If the daily close stays above the 20Ema and Net Highs in Red in a previously good condition
if(closeDa > daEma20 and hi_lo <= 0 and condUp[1] == true and condUp[2] == true and condUp[3] == true and daEma10 > daEma20)
condUp := true
// If the close is under 20 EMA but the Net High Low is still in the good color (still with previously good conditions))
if(closeDa < daEma20 and hi_lo > 0 and condUp[1] == true and condUp[2] == true and condUp[3] == true and daEma10 > daEma20)
condUp := true
// BEARISH
if(closeDa < daEma20 and hi_lo >= 0 and condDn[1] == true and condDn[2] == true and condDn[3] == true and daEma10 < daEma20)
condDn := true
if(closeDa > daEma20 and hi_lo < 0 and condDn[1] == true and condDn[2] == true and condDn[3] == true and daEma10 < daEma20)
condDn := true
// Background Color
// COLOR WHEN GOOD
bgcolor(condUp and timeframe.isdaily ? i_posBackgroundColor:na)
// COLOR WHEN NOT GOOD
bgcolor(condDn and timeframe.isdaily ? i_negBackgroundColor:na) |
Volatility Counter | https://www.tradingview.com/script/7n8hNFaf-Volatility-Counter/ | ebanat420 | https://www.tradingview.com/u/ebanat420/ | 7 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ebanat420
//@version=5
indicator("Volatility Counter", shorttitle = "VolCount", timeframe = "", timeframe_gaps = true)
hline(2, title='Threshold lvl 2', color=color.blue, linestyle=hline.style_dotted, linewidth=2)
hline(1, title='Threshold lvl 1', color=color.rgb(255, 255, 255), linestyle=hline.style_dotted, linewidth=1)
VolVal = ( math.abs (math.max (high, low) - math.min (high, low)) / math.max (high, low) ) * 100 // This counts the volatility in a given period
plot (VolVal, "Volatility Counter", color=color.rgb(255, 0, 179)) |
Breakout Identifier + Pivots with pos/neg/neu candles | https://www.tradingview.com/script/0AV8OdnN-Breakout-Identifier-Pivots-with-pos-neg-neu-candles/ | creksar_stock | https://www.tradingview.com/u/creksar_stock/ | 125 | 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/
// © creksar_stock
//@version=5
indicator("Breakout Signals with Pivots", "Breakout indication", overlay = true)
//toggles n other source stuff
bc_src = close
bo_src = open
gap = input.int(250, "Signal Gap", 2, 500)
//define average tru range - defines the range in which a breakout would NOT occur in
atrLen = input.int(14, "atr length", minval = 1)
atrMultiplier = input.int(2, "atr multiplier", minval = 1)
average_true_range = ta.atr(atrLen)
//define average volatility for time frame
volLen = input.int(14, "volatility length", minval = 1)
volMultiplier = input.int(2, "volatility multiplier", minval = 1)
//volatility = standard deviation -> hi-stdev = high volatility vice versa
volatility = ta.stdev(bc_src, volLen)
//breakout calc.
bool BearBreakout = ta.crossover(bc_src, high - atrMultiplier * average_true_range) and volatility < volMultiplier * volatility[1]
bool BullBreakout = ta.crossunder(bc_src, low + atrMultiplier * average_true_range) and volatility < volMultiplier * volatility[1]
//inputs for drawing plots
bo_type = BearBreakout or BullBreakout
Bear_col = input.color(color.new(#2cff37,30))
Bull_col = input.color(color.new(#ff2c2c, 30))
//line signal
//xloc.barindex to pull time at a location, request price at specific time
blLine = BullBreakout ? line.new(bar_index + 25, high, bar_index, high, color = color.red, width = 2) : na
brLine = BearBreakout ? line.new(bar_index + 25, low, bar_index, low, color = color.green, width = 2) : na
hiLoBox = box.new(bar_index - 1, high[1], bar_index, low, border_color = na, bgcolor = color.new(#FFFFFF,70))
line.set_x2(brLine, bar_index)
line.set_x2(blLine, bar_index)
box.set_right(hiLoBox, bar_index)
boxColor = high > high[1] ? color.green : low < low[1] ? color.red : color.silver
box.set_bgcolor(hiLoBox, color.new(boxColor, 80))
//help = BearBreakout ? line.new(bar_index + 25, low, bar_index, low, color = color.green, width = 2) : BullBreakout ? line.new(bar_index + 25, high, bar_index, high, color = color.red, width = 2) : na
if BearBreakout
label.new(bar_index, low - gap, "Bear Breakout", color = Bear_col, style = label.style_triangleup, size = size.auto)
else if BullBreakout
label.new(bar_index, high + gap, "Bear Breakout", color = Bull_col, style = label.style_triangledown, size = size.auto)
plot(na)
//line.new(bar_index - 1, low, bar_index, low, color = color.green, width = 2)
//line.new(bar_index - 1, high, bar_index, high, color = color.red, width = 2)
|
RSI Trendlines with Breakouts | https://www.tradingview.com/script/YcKrOcXe-RSI-Trendlines-with-Breakouts/ | HoanGhetti | https://www.tradingview.com/u/HoanGhetti/ | 1,566 | 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/
// © HoanGhetti
//@version=5
indicator("RSI Trendlines with Breakouts [HG]", precision = 2, max_labels_count = 500, max_lines_count = 500)
import HoanGhetti/SimpleTrendlines/3 as tl
g_trendlines = 'Trendline Settings', g_conditions = 'Conditions', g_styling = 'Styling', g_timeframe = 'Timeframe'
input_timeframe = input.timeframe(defval = '', title = 'Timeframe', group = g_timeframe)
input_pLen = input.int(defval = 4, title = 'Lookback Range', minval = 1, group = g_trendlines, tooltip = 'How many bars to determine when a swing high/low is detected.')
input_rLen = input.int(defval = 14, title = 'RSI Length' , minval = 1, group = g_trendlines)
input_rSrc = input.source(defval = close, title = 'RSI Source', group = g_trendlines)
input_repaint = input.string(defval = 'On', title = 'Repainting', group = g_conditions, options = ['On', 'Off: Bar Confirmation'], tooltip = 'Bar Confirmation: Generates alerts when candle closes. (1 Candle Later)')
input_rsiDiff = input.int(defval = 3, title = 'RSI Difference', group = g_conditions, tooltip = 'The difference between the current RSI value and the breakout value.\n\nHow much higher in value should the current RSI be compared to the breakout value in order to detect a breakout?')
input_rsiCol = input.color(defval = color.blue, title = 'RSI Color', group = g_styling)
input_width = input.int(defval = 2, title = 'Line Width', minval = 1, group = g_styling)
input_lblType = input.string(defval = 'Simple', title = 'Label Type', group = g_styling, options = ['Full', 'Simple'])
input_lblSize = input.string(defval = size.small, title = 'Label Size', group = g_styling, options = [size.huge, size.large, size.normal, size.small, size.tiny])
input_pLowCol = input.color(defval = color.red, title = 'Pivot Low', inline = 'col', group = g_styling)
input_pHighCol = input.color(defval = #089981, title = 'Pivot High', inline = 'col', group = g_styling)
input_override = input.bool(defval = false, title = 'Override Text Color', group = g_styling, inline = 'override')
input_overCol = input.color(defval = color.white, title = ' ', group = g_styling, inline = 'override')
lblText = switch input_lblType
'Simple' => 'Br'
'Full' => 'Break'
repaint = switch input_repaint
'On' => true
'Off: Bar Confirmation' => false
rsi_v = ta.rsi(input_rSrc, input_rLen)
rsi = input_timeframe == '' ? rsi_v : request.security(syminfo.tickerid, input_timeframe, rsi_v, lookahead = barmerge.lookahead_on)
pl = fixnan(ta.pivotlow(rsi, 1, input_pLen))
ph = fixnan(ta.pivothigh(rsi, 1, input_pLen))
pivot(float pType) =>
pivot = pType == pl ? pl : ph
xAxis = ta.valuewhen(ta.change(pivot), bar_index, 0) - ta.valuewhen(ta.change(pivot), bar_index, 1)
prevPivot = ta.valuewhen(ta.change(pivot), pivot, 1)
pivotCond = ta.change(pivot) and (pType == pl ? pivot > prevPivot : pivot < prevPivot)
pData = tl.new(x_axis = xAxis, offset = input_pLen, strictMode = true, strictType = pType == pl ? 0 : 1)
pData.drawLine(pivotCond, prevPivot, pivot, rsi)
pData
breakout(tl.Trendline this, float pType) =>
var bool hasCrossed = false
if ta.change(this.lines.startline.get_y1())
hasCrossed := false
this.drawTrendline(not hasCrossed)
condType = (pType == pl ? rsi < this.lines.trendline.get_y2() - input_rsiDiff : rsi > this.lines.trendline.get_y2() + input_rsiDiff) and not hasCrossed
condition = repaint ? condType : condType and barstate.isconfirmed
if condition
hasCrossed := true
this.lines.startline.set_xy2(this.lines.trendline.get_x2(), this.lines.trendline.get_y2())
this.lines.trendline.set_xy2(na, na)
this.lines.startline.copy()
label.new(
bar_index,
this.lines.startline.get_y2(),
text = lblText, color = pType == pl ? color.new(input_pLowCol, 50) : color.new(input_pHighCol, 50),
size = input_lblSize, style = pType == pl ? label.style_label_lower_left : label.style_label_upper_left,
textcolor = pType == pl ? (input_override ? input_overCol : input_pLowCol) : input_override ? input_overCol : input_pHighCol)
hasCrossed
method style(tl.Trendline this, color col) =>
this.lines.startline.set_color(col)
this.lines.startline.set_width(input_width)
this.lines.trendline.set_color(col)
this.lines.trendline.set_width(input_width)
this.lines.trendline.set_style(line.style_dashed)
plData = pivot(pl)
phData = pivot(ph)
plData.style(input_pLowCol)
phData.style(input_pHighCol)
cu = breakout(plData, pl)
co = breakout(phData, ph)
hline(70, title = 'Overbought', color = input_pHighCol, linestyle = hline.style_dotted)
hline(30, title = 'Oversold', color = input_pLowCol, linestyle = hline.style_dotted)
plot(rsi, title = 'Relative Strength Index', linewidth = 2, color = input_rsiCol)
alertcondition(ta.change(plData.lines.startline.get_y1()), 'New Pivot Low Trendline')
alertcondition(ta.change(cu) and cu, 'Pivot Low Breakout')
alertcondition(ta.change(phData.lines.startline.get_y1()), 'New Pivot High Trendline')
alertcondition(ta.change(co) and co, 'Pivot High Breakout') |
Candle and BG Trend Identifier | https://www.tradingview.com/script/lQiXzDp0-Candle-and-BG-Trend-Identifier/ | creksar_stock | https://www.tradingview.com/u/creksar_stock/ | 13 | 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/
// © creksar_stock
//@version=5
indicator("Candle and BG microtrend identifier", "Microtrend Based Candles", true)
hifunc = high > high[1]
lofunc = low < low[1]
bgcolor(hifunc ? color.new(color.green, 85) : lofunc ? color.new(color.red, 85) : na)
hiline = lofunc ? line.new(bar_index + 25, high, bar_index, high, color = color.new(color.red, 100), width = 2) : na
loline = hifunc ? line.new(bar_index + 25, low, bar_index, low, color = color.new(color.green,100), width = 2) : na
color colorandom = hifunc ? color.new(color.green,30) : lofunc ? color.new(color.red,30) : color.silver
plotcandle(open, high, low, close, "Bearish Candle", color = colorandom, wickcolor = colorandom, editable = false)
//color.new(color.green,30)
//color.new(color.red,30)
|
Bitcoin Relative Value Indicator | https://www.tradingview.com/script/c73jgmcl-Bitcoin-Relative-Value-Indicator/ | bigcitytom | https://www.tradingview.com/u/bigcitytom/ | 6 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © bigcitytom
//@version=5
indicator(title='Bitcoin Trend Analysis', shorttitle='BTC Analysis', overlay=true)
// Define the symbols for Bitcoin, DXY, CPI, M2 money supply, and the total US stock market
btc_symbol = 'COINBASE:BTCUSD'
dxy_symbol = 'DXY'
cpi_symbol = 'FRED/CPIAUCSL'
m2_symbol = 'FRED/M2SL'
us_stock_symbol = 'NYSE'
// Get the close price data for Bitcoin, DXY, CPI, M2 money supply, and the total US stock market
btc_close = request.security(btc_symbol, timeframe.period, close)
dxy_close = request.security(dxy_symbol, timeframe.period, close)
cpi_close = request.security(cpi_symbol, timeframe.period, close)
m2_close = request.security(m2_symbol, timeframe.period, close)
us_stock_close = request.security(us_stock_symbol, timeframe.period, close)
// Calculate the average of DXY, CPI, M2 money supply, and the total US stock market
average_close = (dxy_close + cpi_close + m2_close + us_stock_close) / 4
// Determine if Bitcoin is increasing or decreasing in value relative to the average of the four data points
trend = btc_close > average_close ? 1 : btc_close < average_close ? -1 : 0
// Plot the trend on the chart using green and red circles
plotshape(trend == 1 ? btc_close : na, style=shape.circle, location=location.abovebar, color=color.new(color.green, 0), size=size.large, title='Bitcoin Increasing in Value')
plotshape(trend == -1 ? btc_close : na, style=shape.circle, location=location.abovebar, color=color.new(color.red, 0), size=size.large, title='Bitcoin Decreasing in Value')
|
[JL] Supertrend Zone Pivot Point with zigzag fib | https://www.tradingview.com/script/HrcAAGcU-JL-Supertrend-Zone-Pivot-Point-with-zigzag-fib/ | Jesse.Lau | https://www.tradingview.com/u/Jesse.Lau/ | 1,817 | 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/
// © Jesse.Lau
//@version=5
indicator(title="[JL] Supertrend Zone Pivot Point with zigzag fib", overlay=true,max_labels_count=500,max_bars_back = 4900)
show_zigzag = input(true, "Show zigzag", group="Show")
show_fib = input(true, "Show fibonacci", group="Show")
show_supertrend = input(true, "Show supertrend", group="Show")
show_premiumdiscount = input(true, "Show premium/discount line", group="Show")
// Getting inputs
atrPeriod = input(10, "ATR Length")
factor = input.float(3, "Factor", step = 0.1)
atrline = input.float(1.5, "Premium/Discount", step = 0.1)
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 and show_supertrend ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(direction > 0 and show_supertrend ? supertrend :na, "Down Trend", color = color.red, style=plot.style_linebr)
fill(bodyMiddle, upTrend, show_supertrend ? color.new(color.green, 90):na, fillgaps=false)
fill(bodyMiddle, downTrend,show_supertrend ? color.new(color.red, 90):na, fillgaps=false)
ATR = ta.atr(atrPeriod)
upatrline = supertrend + atrline*ATR
dnatrline = supertrend - atrline*ATR
plot(direction < 0 and show_premiumdiscount ? upatrline : na, "Up ATR", color = color.white, style=plot.style_linebr)
plot(direction > 0 and show_premiumdiscount ? dnatrline : na, "Dn ATR", color = color.white, style=plot.style_linebr)
colorGroupTitle = "Text Color / Label Color"
textColorH = input(title="Pivot High", defval=color.white, inline="Pivot High", group=colorGroupTitle)
labelColorH = input(title="", defval=color.red, inline="Pivot High", group=colorGroupTitle)
textColorL = input(title="Pivot Low", defval=color.white, inline="Pivot Low", group=colorGroupTitle)
labelColorL = input(title="", defval=color.green, inline="Pivot Low", group=colorGroupTitle)
turnGreen = ta.change(direction) < 0
turnRed = ta.change(direction) > 0
barsturngreen = bar_index - ta.valuewhen(turnGreen, bar_index, 0)
barsturnred = bar_index - ta.valuewhen(turnRed, bar_index, 0)
barsg = barsturngreen>0 ? barsturngreen : 1
h1 = ta.highest(high,barsg)
//plot(h1)
barsr = barsturnred>0 ? barsturnred : 1
l2 = ta.lowest(low,barsr)
//plot(l2)
barsh = bar_index - ta.valuewhen(ta.change(h1),bar_index,0)
barsl = bar_index - ta.valuewhen(ta.change(l2),bar_index,0)
barsh2 = bar_index - ta.valuewhen(ta.change(h1),bar_index,1)
barsl2 = bar_index - ta.valuewhen(ta.change(l2),bar_index,1)
h1Index = 0
l2Index = 0
var label h1label = na
var label l2label = na
drawLabel(_offset, _pivot, _style, _color, _textColor) =>
if not na(_pivot)
label.new(bar_index-_offset, _pivot, str.tostring(_pivot, format.mintick), style=_style, color=_color, textcolor=_textColor)
if turnRed
h1label:=drawLabel(barsh, h1, label.style_label_down, labelColorH, textColorH)
if show_zigzag
line.new(bar_index - barsh, h1, bar_index-barsl2, l2[1], width = 3, color=color.lime)
if turnGreen
l2label:=drawLabel(barsl, l2, label.style_label_up, labelColorL, textColorL)
if show_zigzag
line.new(bar_index - barsh2, h1[1], bar_index-barsl, l2, width = 3,color = color.fuchsia)
hh = ta.valuewhen(turnRed, h1, 0)
ll = ta.valuewhen(turnGreen, l2, 0)
mid_val = (hh + ll) / 2
// Plot lines for highest high and lowest low
var line hhLine = na
var line llLine = na
var line midline = na
var label fibLabelh = na
var label fibLabell = na
var label fibLabelm = na
var label fibLabel1 = na
var label fibLabel2 = na
var label fibLabel3 = na
var label fibLabel4 = na
var label fibLabel5 = na
var label fibLabel6 = na
var line fibLine1 = na
var line fibLine2 = na
var line fibLine3 = na
var line fibLine4 = na
var line fibLine5 = na
var line fibLine6 = na
if barstate.islast and show_fib
while high[h1Index] != h1[1]
h1Index := h1Index + 1
while low[l2Index] != l2[1]
l2Index := l2Index + 1
n = math.max(h1Index,l2Index)
if not na(hhLine)
line.delete(hhLine)
if not na(llLine)
line.delete(llLine)
if not na(midline)
line.delete(midline)
if not na(fibLabelh)
label.delete(fibLabelh)
if not na(fibLabell)
label.delete(fibLabell)
if not na(fibLabelm)
label.delete(fibLabelm)
if not na(fibLabel1)
label.delete(fibLabel1)
if not na(fibLabel2)
label.delete(fibLabel2)
if not na(fibLabel3)
label.delete(fibLabel3)
if not na(fibLabel4)
label.delete(fibLabel4)
if not na(fibLabel5)
label.delete(fibLabel5)
if not na(fibLabel6)
label.delete(fibLabel6)
if not na(fibLine1)
line.delete(fibLine1)
if not na(fibLine2)
line.delete(fibLine2)
if not na(fibLine3)
line.delete(fibLine3)
if not na(fibLine4)
line.delete(fibLine4)
if not na(fibLine5)
line.delete(fibLine5)
if not na(fibLine6)
line.delete(fibLine6)
hhLine := line.new(x1=bar_index-n+1, y1=hh, x2=bar_index, y2=hh, color=color.purple, width=1)
fibLabelh := label.new(x=bar_index + 10, y=hh , text="1("+str.tostring(hh )+")", style = label.style_none,xloc=xloc.bar_index, yloc=yloc.price, color=color.white, textcolor=color.gray)
llLine := line.new(x1=bar_index-n+1, y1=ll, x2=bar_index, y2=ll, color=color.purple, width=1)
fibLabell := label.new(x=bar_index + 10, y=ll , text="0("+str.tostring(ll )+")", style = label.style_none,xloc=xloc.bar_index, yloc=yloc.price, color=color.white, textcolor=color.gray)
midline := line.new(bar_index-n+1, mid_val, bar_index, mid_val, color=color.purple, width=1)
fibLabelm := label.new(x=bar_index + 10, y=mid_val , text="0.5("+str.tostring(mid_val )+")", style = label.style_none,xloc=xloc.bar_index, yloc=yloc.price, color=color.white, textcolor=color.gray)
fibLabel1 := label.new(x=bar_index + 10, y=ll + 0.236*(hh-ll), text="0.236("+str.tostring(ll + 0.236*(hh-ll),"#.####")+")", style = label.style_none,xloc=xloc.bar_index, yloc=yloc.price, color=color.white, textcolor=color.gray)
fibLine1 := line.new(x1 = bar_index-n+1,y1 = ll + 0.236*(hh-ll),x2 = bar_index,y2 = ll + 0.236*(hh-ll),color = color.purple,width = 1)
fibLabel2 := label.new(x=bar_index + 10, y=ll + 0.382*(hh-ll), text="0.382("+str.tostring(ll + 0.382*(hh-ll),"#.####")+")", style = label.style_none,xloc=xloc.bar_index, yloc=yloc.price, color=color.white, textcolor=color.gray)
fibLine2 := line.new(x1 = bar_index-n+1,y1 = ll + 0.382*(hh-ll),x2 = bar_index,y2 = ll + 0.382*(hh-ll),color = color.purple,width = 1)
fibLabel3 := label.new(x=bar_index + 10, y=ll + 0.618*(hh-ll), text="0.618("+str.tostring(ll + 0.618*(hh-ll),"#.####")+")", style = label.style_none,xloc=xloc.bar_index, yloc=yloc.price, color=color.white, textcolor=color.gray)
fibLine3 := line.new(x1 = bar_index-n+1,y1 = ll + 0.618*(hh-ll),x2 = bar_index,y2 = ll + 0.618*(hh-ll),color = color.purple,width = 1)
fibLabel4 := label.new(x=bar_index + 10, y=ll + 0.786*(hh-ll), text="0.786("+str.tostring(ll + 0.786*(hh-ll),"#.####")+")", style = label.style_none,xloc=xloc.bar_index, yloc=yloc.price, color=color.white, textcolor=color.gray)
fibLine4 := line.new(x1 = bar_index-n+1,y1 = ll + 0.786*(hh-ll),x2 = bar_index,y2 = ll + 0.786*(hh-ll),color = color.purple,width = 1)
if close>supertrend
fibLabel5 := label.new(x=bar_index + 10, y=ll + 1.618*(hh-ll), text="1.618("+str.tostring(ll + 1.618*(hh-ll),"#.####")+")", style = label.style_none,xloc=xloc.bar_index, yloc=yloc.price, color=color.white, textcolor=color.gray)
fibLine5 := line.new(x1 = bar_index-n+1,y1 = ll + 1.618*(hh-ll),x2 = bar_index,y2 = ll + 1.618*(hh-ll),color = color.purple,width = 1)
if close<supertrend
fibLabel6 := label.new(x=bar_index + 10, y=ll - 0.618*(hh-ll), text="-1.618("+str.tostring(ll - 0.618*(hh-ll),"#.####")+")", style = label.style_none,xloc=xloc.bar_index, yloc=yloc.price, color=color.white, textcolor=color.gray)
fibLine6 := line.new(x1 = bar_index-n+1,y1 = ll - 0.618*(hh-ll),x2 = bar_index,y2 = ll - 0.618*(hh-ll),color = color.purple,width = 1)
|
Drip's 11am rule breakout/breakdown (OG) | https://www.tradingview.com/script/j5fydEzi-Drip-s-11am-rule-breakout-breakdown-OG/ | sensir | https://www.tradingview.com/u/sensir/ | 1,548 | 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/
// © sensir
//@version=5
indicator("Drip's 11am rule breakout/breakdown", overlay = true)
timeFilter = input.timeframe(title = "Cutoff time for indentifying HOD/LOD zone (EST). Recommended 9:30-11:30 AM EST", defval = "0930-1130", options = ['0930-1100', '0930-1130'])
fastMAInput = input(title='Fast EMA Period', defval=9)
slowMAInput = input(title='Slow EMA Period', defval=21)
midMAInput = input(title='Mid EMA Period', defval=13)
srcHi = input(high, "Source for Highs")
srcLo = input(low, "Source for Lows")
showHi = input(true, "Show HOD breakout zone")
showLo = input(true, "Show LOD breakdown zone")
showCloud = input(true, "Show cloud for breakout and breakdown")
showTrendArrow = input(true, "Show trend arrows for breakout and breakdown")
showCandleMomentum = input(true, "Show candlesticks with strong upside/downside momentum")
upConvictionArrow = showTrendArrow
downConvictionArrow = showTrendArrow
[dOpen,dh,dl] = request.security(syminfo.ticker, "D", [open,high,low], lookahead=barmerge.lookahead_on)
rsi = ta.rsi(close[1], 14)
rsi5m = request.security(syminfo.tickerid, '5', rsi)
// Check to see if we are in allowed hours using session info on all 7 days of the week.
timeIsBeforeCriteria = time('1', timeFilter + ":1234567", timezone = "America/New_York")
var hiBeforeCriteria = 10e-10
var loBeforeCriteria = 10e10
var startCounting = false
if timeIsBeforeCriteria
// We are entering allowed hours; reset hi/lo.
if not timeIsBeforeCriteria[1]
hiBeforeCriteria := srcHi
loBeforeCriteria := srcLo
else
// We are in allowed hours; track hi/lo.
hiBeforeCriteria := math.max(srcHi,hiBeforeCriteria)
loBeforeCriteria := math.min(srcLo,loBeforeCriteria)
remainingSession = switch timeFilter
'0930-1100' => '1100-1600'
'0930-1130' => '1130-1600'
// Calculate the fast and slow moving averages
fastMA = ta.ema(close, fastMAInput)
slowMA = ta.ema(close, slowMAInput)
midMA = ta.ema(close, midMAInput)
// Average Directional Index (ADX)
[th, tl, adx] = ta.dmi(7, 3)
// Identify sideways market using ADX
sideways = adx < 30
uptrend = th > 30 and th < 70
downtrend = tl >30 and tl < 70
// Fill the price bars with a specific color when ADX is below 20
// barcolor(sideways ? color.purple : na)
barcolor(uptrend and showCandleMomentum? color.rgb(145, 255, 0) : na)
barcolor(downtrend and showCandleMomentum? color.rgb(255, 0, 200) : na)
t1 = time(timeframe.period, remainingSession, "America/New_York")
// Check if the stock is trading above ...
condition1 = close > slowMA and close > dOpen
// Check if the stock is making a new high after time specified by user
condition2 = time >= t1 and close > (hiBeforeCriteria * 1.001) and close[1] > (hiBeforeCriteria * 1.001)
upConvictionArrow := showTrendArrow and th > 25 and condition1 and condition2 and (close > fastMA)
//upConvictionArrow := showTrendArrow and th > 25 and condition1 and condition2 and (close > fastMA) and (low > low[1])
// plot hi and low at 11
resistanceLowerBound = plot(t1 and showHi ? hiBeforeCriteria: na, style=plot.style_linebr, linewidth=1, color= color.red, title = "HOD lower limit")
resistanceUpperBound = plot(t1 and showHi ? hiBeforeCriteria * 1.001: na, style=plot.style_linebr, linewidth=1, color= color.red, title = "HOD upper limit")
fill(resistanceLowerBound, resistanceUpperBound, color = color.new(color.red, 80), title = "HOD breakout zone")
supportLowerBound = plot(t1 and showLo ? loBeforeCriteria*0.999 : na, style=plot.style_linebr, linewidth=0, color= color.green, title = "LOD lower limit")
supportUpperBound = plot(t1 and showLo ? loBeforeCriteria : na, style=plot.style_linebr, linewidth=0, color= color.green, title = "LOD upper limit")
fill(supportLowerBound, supportUpperBound, color = color.new(color.green, 80), title = "LOD breakdown zone")
fastPlot = plot(condition1 and condition2 and showCloud ? slowMA : na, color=color.new(color.green, 100), style = plot.style_linebr, linewidth = 1, title = "Fast EMA support line")
slowPlot = plot(condition1 and condition2 and showCloud ? fastMA : na, color=color.new(color.green, 100), style = plot.style_linebr, linewidth = 2, title = "Slow EMA support line")
fill(fastPlot, slowPlot, color=color.new(#30ff4c, 75), title = "Breakout support cloud")
plotshape(upConvictionArrow ? 1: 0, style = shape.triangleup, color = color.green, size = size.tiny, location = location.belowbar, title = "Breakout conviction arrow")
// Check if the stock is trading below both moving averages
condition3 = close < slowMA and close < dOpen
condition4 = time >= t1 and close < (loBeforeCriteria * 0.999) and close[1] < (loBeforeCriteria * 0.999)
downConvictionArrow := downConvictionArrow and tl > 25 and condition3 and condition4 and (close < fastMA)
//downConvictionArrow := downConvictionArrow and tl > 25 and condition3 and condition4 and (close < fastMA) and (low < low[1])
// Combine the conditions and plot the result
fastPlot1 = plot(condition3 and condition4 and showCloud? slowMA : na, color=color.new(color.red, 100), style = plot.style_linebr, linewidth = 1, title = "Fast EMA resistance line")
slowPlot1 = plot(condition3 and condition4 and showCloud? fastMA : na, color=color.new(color.red, 100), style = plot.style_linebr, linewidth = 2, title = "Slow EMA resistance line")
fill(fastPlot1, slowPlot1, color=color.new(#ff0202, 75), title = "Breakdown resistance cloud")
plotshape(downConvictionArrow ? 1: 0, style = shape.triangledown, color = color.red, size = size.tiny, location = location.abovebar, title = "Breakdown conviction arrow")
|
VIX Reference Indicator | https://www.tradingview.com/script/vpkUgWcj-VIX-Reference-Indicator/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 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/
// © Steversteves
//@version=5
indicator("VIX Reference", max_labels_count = 500)
// Settings
timeframe = input.timeframe("")
AvgLength = input.int(75, title="Average Length")
vix = request.security("CBOE:VIX", timeframe, close)
RSILength = input.int(14, title="RSI Length")
ZLength = input.int(75, title="Reversal Z-Score Length")
// Calculcate Z Score
vixhx = ta.sma(vix, AvgLength)
vixsd = ta.stdev(vix, AvgLength)
z = (vix - vixhx) / vixsd
// Reversal Points
vixmax = ta.highest(z, ZLength)
vixmin = ta.lowest(z, ZLength)
// RSI
rsi = ta.rsi(vix, RSILength)
bool bearishrsi = rsi <= 30
bool bullishrsi = rsi >= 70
// Color
bear = color.new(color.red, 0)
bull = color.new(color.green, 0)
neutral = color.new(color.blue, 0)
color pallette = bearishrsi ? bear : bullishrsi ? bull : neutral
plot(z, color=pallette, linewidth=4)
// Condition Alerts
var wait = 0
wait := wait + 1
if (z >= vixmax) and (wait > 50)
wait := 10
label.new(x=bar_index, y=vixmax, text="Buy", size = size.tiny, color=color.green)
alert("Buy The Dip "+syminfo.ticker, alert.freq_once_per_bar)
if (z <= vixmin) and (wait > 50)
wait := 10
label.new(x=bar_index, y=vixmin, text="Sell", size = size.tiny, color=color.red)
alert("Sell The Rally "+syminfo.ticker, alert.freq_once_per_bar)
// Fills
upperband = hline(2.5, "Upper Band", color=color.gray)
lowerband = hline(-2.5, "Lower Band", color=color.gray)
centreband = hline(0, "Centre Band", color=color.yellow)
color fillcolor = color.new(color.gray, 95)
fill(upperband, lowerband, color=fillcolor) |
Weighted Deviation Bands [Loxx] | https://www.tradingview.com/script/GnIBQ2jn-Weighted-Deviation-Bands-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 129 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Weighted Deviation Bands [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
greencolor = #2DD204
redcolor = #D2042D
bluecolor = #042dd2
import loxx/loxxexpandedsourcetypes/4
devnWeighted(float value, simple int perin)=>
float valueSum = value
float valueWeightSum = perin * value
var float weightSum = perin
int period = perin
if (bar_index >= perin)
valueSum := nz(valueSum[1]) + value - nz(value[perin])
valueWeightSum := nz(valueWeightSum[1]) - nz(valueSum[1]) + value * perin
else
period := bar_index + 1
weightSum := period
valueWeightSum := period * value
valueSum := value
for int k = 1 to period - 1
float weight = period - k
weightSum += weight
valueWeightSum += nz(value[k]) * weight
valueSum += nz(value[k])
float mean = valueWeightSum / weightSum
float sums = 0.
int weight = period
for k = 0 to period - 1
sums += weight * (nz(value[k]) - mean) * (nz(value[k]) - mean)
float deviation = math.sqrt(sums / weightSum)
[mean, deviation]
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
inpPeriod = input.int(30, "Period", group = "Basic Settings", minval = 1)
inpMultiplier = input.int(1, "Multiplier", group = "Basic Settings", minval = 1)
colorbars = input.bool(true, "Color bars", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = ohlc4
haopen = float(na)
haopen := na(haopen[1]) ? (open + close) / 2 : (nz(haopen[1]) + nz(haclose[1])) / 2
hahigh =math.max(high, math.max(haopen, haclose))
halow = math.min(low, math.min(haopen, haclose))
hamedian = (hahigh + halow) / 2
hatypical = (hahigh + halow + haclose) / 3
haweighted = (hahigh + halow + haclose + haclose)/4
haaverage = (haopen + hahigh + halow + haclose)/4
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
[mean, deviation] = devnWeighted(src, inpPeriod)
bandup = mean + deviation * inpMultiplier
banddn = mean - deviation * inpMultiplier
plot(bandup, "Upper", color = greencolor, linewidth = 2)
plot(banddn, "Lower", color = redcolor, linewidth = 2)
plot(mean, "Mean", color = color.gray, linewidth = 2)
sig = mean[1]
colorout = mean > sig ? greencolor : redcolor
barcolor(colorbars ? colorout : na ) |
Multiple Standard Momentum | https://www.tradingview.com/script/sGD5aatR/ | DOC-STRATEGY | https://www.tradingview.com/u/DOC-STRATEGY/ | 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/
// © DOC-STRATEGY
//██████╗░░█████╗░░█████╗░ ░██████╗████████╗██████╗░░█████╗░████████╗███████╗░██████╗░██╗░░░██╗
//██╔══██╗██╔══██╗██╔══██╗ ██╔════╝╚══██╔══╝██╔══██╗██╔══██╗╚══██╔══╝██╔════╝██╔════╝░╚██╗░██╔╝
//██║░░██║██║░░██║██║░░╚═╝ ╚█████╗░░░░██║░░░██████╔╝███████║░░░██║░░░█████╗░░██║░░██╗░░╚████╔╝░
//██║░░██║██║░░██║██║░░██╗ ░╚═══██╗░░░██║░░░██╔══██╗██╔══██║░░░██║░░░██╔══╝░░██║░░╚██╗░░╚██╔╝░░
//██████╔╝╚█████╔╝╚█████╔╝ ██████╔╝░░░██║░░░██║░░██║██║░░██║░░░██║░░░███████╗╚██████╔╝░░░██║░░░
//╚═════╝░░╚════╝░░╚════╝░ ╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░╚══════╝░╚═════╝░░░░╚═╝░░░
//𓂀𝔻𝕆ℂ 𝕊𝕋ℝ𝔸𝕋𝔼𝔾𝕐𓂀
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//@version=5
indicator('Multiple Standard Momentum', shorttitle='Multiple Standard Momentum', timeframe='')
//Maximum Moving Averages/////////////////////////////////////////////////////////////////////////////////////////////////////
DOC_Strategy = "Configurable: Multiple Standard Momentum"
Momentum(source, length, type) =>
type == "Momentum" ? ta.mom(source, length) :
na
//Momentum 1//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
mom1_type = input.string("Momentum" , "" , inline="Momentum", options=["Momentum"], group=DOC_Strategy)
mom1_source = input.source(close , "" , inline="Momentum", group=DOC_Strategy)
mom1_length = input.int (14 , "" , inline="Momentum", minval=2, group=DOC_Strategy)
mom1_color = input.color (color.rgb(1, 255, 170), "" , inline="Momentum", group=DOC_Strategy)
mom1_color2 = input.color (color.rgb(255, 0, 144), "" , inline="Momentum", group=DOC_Strategy)
mom1 = Momentum(mom1_source, mom1_length, mom1_type)
mom1_colorOK = mom1 >=0 ? mom1_color : mom1_color2
plot(mom1, color = mom1_colorOK, title="Momentum № I 𓂀", linewidth=2, display=display.all)
//Momentum 2//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
mom2_type = input.string("Momentum" , "" , inline="Momentum", options=["Momentum"], group=DOC_Strategy)
mom2_source = input.source(close , "" , inline="Momentum", group=DOC_Strategy)
mom2_length = input.int (12 , "" , inline="Momentum", minval=2, group=DOC_Strategy)
mom2_color = input.color (color.rgb(1, 255, 170, 70), "" , inline="Momentum", group=DOC_Strategy)
mom2_color2 = input.color (color.rgb(255, 0, 144, 70), "" , inline="Momentum", group=DOC_Strategy)
mom2 = Momentum(mom2_source, mom2_length, mom2_type)
mom2_colorOK = mom2 >=0 ? mom2_color : mom2_color2
plot(mom2, color = mom2_colorOK, title="Momentum № II 𓂀", linewidth=1, display=display.none)
//Momentum 3//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
mom3_type = input.string("Momentum" , "" , inline="Momentum", options=["Momentum"], group=DOC_Strategy)
mom3_source = input.source(close , "" , inline="Momentum", group=DOC_Strategy)
mom3_length = input.int (10 , "" , inline="Momentum", minval=2, group=DOC_Strategy)
mom3_color = input.color (color.rgb(1, 255, 170, 70), "" , inline="Momentum", group=DOC_Strategy)
mom3_color2 = input.color (color.rgb(255, 0, 144, 70), "" , inline="Momentum", group=DOC_Strategy)
mom3 = Momentum(mom3_source, mom3_length, mom3_type)
mom3_colorOK = mom3 >=0 ? mom3_color : mom3_color2
plot(mom3, color = mom3_colorOK, title="Momentum № III 𓂀", linewidth=1, display=display.none)
//Momentum 4//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
mom4_type = input.string("Momentum" , "" , inline="Momentum", options=["Momentum"], group=DOC_Strategy)
mom4_source = input.source(close , "" , inline="Momentum", group=DOC_Strategy)
mom4_length = input.int ( 8 , "" , inline="Momentum", minval=2, group=DOC_Strategy)
mom4_color = input.color (color.rgb(1, 255, 170, 70), "" , inline="Momentum", group=DOC_Strategy)
mom4_color2 = input.color (color.rgb(255, 0, 144, 70), "" , inline="Momentum", group=DOC_Strategy)
mom4 = Momentum(mom4_source, mom4_length, mom4_type)
mom4_colorOK = mom4 >=0 ? mom4_color : mom4_color2
plot(mom4, color = mom4_colorOK, title="Momentum № IV 𓂀", linewidth=1, display=display.none)
//Momentum 5//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
mom5_type = input.string("Momentum" , "" , inline="Momentum", options=["Momentum"], group=DOC_Strategy)
mom5_source = input.source(close , "" , inline="Momentum", group=DOC_Strategy)
mom5_length = input.int ( 6 , "" , inline="Momentum", minval=2, group=DOC_Strategy)
mom5_color = input.color (color.rgb(1, 255, 170, 70), "" , inline="Momentum", group=DOC_Strategy)
mom5_color2 = input.color (color.rgb(255, 0, 144, 70), "" , inline="Momentum", group=DOC_Strategy)
mom5 = Momentum(mom5_source, mom5_length, mom5_type)
mom5_colorOK = mom5 >=0 ? mom5_color : mom5_color2
plot(mom5, color = mom5_colorOK, title="Momentum № V 𓂀", linewidth=1, display=display.none)
//Momentum 6//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
mom6_type = input.string("Momentum" , "" , inline="Momentum", options=["Momentum"], group=DOC_Strategy)
mom6_source = input.source(close , "" , inline="Momentum", group=DOC_Strategy)
mom6_length = input.int ( 4 , "" , inline="Momentum", minval=2, group=DOC_Strategy)
mom6_color = input.color (color.rgb(1, 255, 170, 70), "" , inline="Momentum", group=DOC_Strategy)
mom6_color2 = input.color (color.rgb(255, 0, 144, 70), "" , inline="Momentum", group=DOC_Strategy)
mom6 = Momentum(mom6_source, mom6_length, mom6_type)
mom6_colorOK = mom6 >= 0 ? mom6_color : mom6_color2
plot(mom6, color = mom6_colorOK, title="Momentum № VI 𓂀", linewidth=1, display=display.none)
//Momentum 7//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
mom7_type = input.string("Momentum" , "" , inline="Momentum", options=["Momentum"], group=DOC_Strategy)
mom7_source = input.source(close , "" , inline="Momentum", group=DOC_Strategy)
mom7_length = input.int ( 2 , "" , inline="Momentum", minval=2, group=DOC_Strategy)
mom7_color = input.color (color.rgb(1, 255, 170, 70), "" , inline="Momentum", group=DOC_Strategy)
mom7_color2 = input.color (color.rgb(255, 0, 144, 70), "" , inline="Momentum", group=DOC_Strategy)
mom7 = Momentum(mom7_source, mom7_length, mom7_type)
mom7_colorOK = mom7 >= 0 ? mom7_color : mom7_color2
plot(mom7, color = mom7_colorOK, title="Momentum № VII 𓂀", linewidth=1, display=display.none)
//Momentum Area///////////////////////////////////////////////////////////////////////////////////////////////////////////////
mom8_type = input.string("Momentum" , "" , inline="Momentum", options=["Momentum"], group=DOC_Strategy)
mom8_source = input.source(close , "" , inline="Momentum", group=DOC_Strategy)
mom8_length = input.int (14 , "" , inline="Momentum", minval=2, group=DOC_Strategy)
mom8_color = input.color (color.rgb(1, 255, 170, 90), "" , inline="Momentum", group=DOC_Strategy)
mom8_color2 = input.color (color.rgb(255, 0, 144, 90), "" , inline="Momentum", group=DOC_Strategy)
mom8 = Momentum(mom8_source, mom8_length, mom8_type)
mom8_colorOK = mom8 >= 0 ? mom8_color : mom8_color2
plot(mom8, color = mom8_colorOK, title="Momentum Area 𓂀", linewidth=1, style=plot.style_areabr, display=display.all)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Period to calculate main line value
Calculation_Period_For_Line = input.int(defval=10, title='Period to calculate the Trend Line', minval=1, group='Trend Line')
Line_ColorLB = input.color (color.rgb(15, 200, 139), "Long/Buy" , group='Trend Line')
Line_ColorSS = input.color (color.rgb(202, 15, 121), "Short/Sell" , group='Trend Line')
TFTL = input.timeframe('', title='Time Frame the Trend Line - Tickets (Minutes: 1=5, 3=15, 5=30, 15=60)', group='Trend Line')
o = request.security (syminfo.tickerid, TFTL, open, barmerge.gaps_off, barmerge.lookahead_on)
c = request.security (syminfo.tickerid, TFTL, close, barmerge.gaps_off, barmerge.lookahead_on)
h = request.security (syminfo.tickerid, TFTL, high, barmerge.gaps_off, barmerge.lookahead_on)
l = request.security (syminfo.tickerid, TFTL, low, barmerge.gaps_off, barmerge.lookahead_on)
//Function to calculate line value////////////////////////////////////////////////////////////////////////////////////////////
Calculate_Line(Period) =>
float highS = ta.highest(Period) or h > c ? h : na
float lowS = ta.lowest (Period) or l < c ? l : na
int trend = 0
trend := c > h[1] ? 1 : c < l[1] ? -1 : nz(trend[1])
trend
//Function to draw line on chart//////////////////////////////////////////////////////////////////////////////////////////////
Draw_Line(Period, Main_Trend) =>
float highS = ta.highest(Period) or h > c ? h : na
float lowS = ta.lowest (Period) or l < c ? l : na
int trend = 0
trend := c > h[1] ? 1 : c < l[1] ? -1 : nz(trend[1])
Main_Trend == 1 ? trend == 1 ? Line_ColorLB : Line_ColorLB : Main_Trend == -1 ? trend == -1 ? Line_ColorSS : Line_ColorSS : na
//Calculate main line value///////////////////////////////////////////////////////////////////////////////////////////////////
Main_Trend = Calculate_Line(Calculation_Period_For_Line)
//Plot Line Zero//////////////////////////////////////////////////////////////////////////////////////////////////////////////
plot( 0, color=Draw_Line(Calculation_Period_For_Line - 9, Main_Trend), title="Zero Trend Line 𓂀", style=plot.style_stepline, histbase= 0, linewidth=2)
//Activate Signals: Long/Buy or Short/Sell///////////////////////////////////////////////////////////////////////////////
Signal_Momentum = input(false, 'Momentum Signal - Long/Buy or Short/Sell = ▲/▼ ?', group='Signal: Long/Buy or Short/Sell')
//Cross in Long/Buy or Short/Sell////////////////////////////////////////////////////////////////////////////////////////
LB1 = ta.crossover (mom1,0) // Momentum 1
SS1 = ta.crossunder(mom1,0) // Momentum 1
//Alert Condition///////////////////////////////////////////////////////////////////////////////////////////////////////
alertcondition((LB1) , 'Momentum: Long/Buy', 'Momentum: Long/Buy')
alertcondition((SS1) , 'Momentum: Short/Sell', 'Momentum: Short/Sell')
alertcondition((LB1) or (SS1), 'Momentum: Long/Buy or Short/Sell', 'Momentum: Long/Buy or Short/Sell')
//Signal Condition//////////////////////////////////////////////////////////////////////////////////////////////////////
plotshape(Signal_Momentum and (LB1) , title='Signal Momentum - Long/Buy', text='▲', textcolor=color.new(#FFFFFF, 0), style=shape.labelup, size=size.tiny, location=location.bottom, color=color.new(#0ebb9e, 0))
plotshape(Signal_Momentum and (SS1) , title='Signal Momentum - Short/Sell', text='▼', textcolor=color.new(#FFFFFF, 0), style=shape.labeldown, size=size.tiny, location=location.top, color=color.new(#cd0a68, 0))
//The End///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
Trend Indicator with RSI and Fibbonacci Band 0.702 crossings | https://www.tradingview.com/script/dgPKYm97/ | blublub | https://www.tradingview.com/u/blublub/ | 78 | 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/
// © blublub
//@version=4
//strategy("Trend Indicator with RSI crossing", shorttitle="TIR", overlay=true, format=format.price, precision=2, margin_long = 120, margin_short = 120 )
study("Trend Indicator with RSI and Fibbonacci Band 0.702 crossings", shorttitle="TIRF", overlay=true, format=format.price, precision=2, resolution="")
//EMA variables and Plotting
shortest = ema(close, 20)
short = ema(close, 50)
longer = ema(close, 100)
longest = ema(close, 200)
plot(shortest, title='20 EMA', color=color.red, linewidth=2)
plot(short, title='50 EMA', color=color.orange)
plot(longer, title='100 EMA', color=color.aqua)
plot(longest, title='200 EMA', color=color.rgb(8, 137, 243), linewidth=2)
// Trend Indicator
period=input(5,"CCI period")
coeff=input(2,"ATR Multiplier")
AP=input(1,"ATR Period")
ATR=sma(tr,AP)
src=input(hlc3, "Main Input Data/ Symbol") // hlc3 is used to get the average value instead of the candle close value
cci_value=input(20, "CCI Value threshold for Neutral Trend") // for the white dots, Neutral trend calculation
cci_top=input(165, "CCI Top/ Overbought") // variable for the CCI top or bottom signal
cci_bottom=input(-165, "CCI Bottom/ Oversold")
upT=low-ATR*coeff
downT=high+ATR*coeff
Trend=0.0
Trend := cci(src,period)>=0 ? (upT<nz(Trend[1]) ? nz(Trend[1]) : upT) : (downT>nz(Trend[1]) ? nz(Trend[1]) : downT)
// CCI calculation
bullish_trend = cci(src, period) > cci_value
bearish_trend = cci(src, period) < cci_value
neutral_trend = cci(src, period) >= -cci_value and cci(src, period) <= cci_value
cci_beartime = cci(src, period) >= cci_top
cci_bulltime = cci(src, period) <= cci_bottom
// RSI Indicators -----------------------------------------------------------------------------
// Input parameters
rsi_length = input(title="RSI Length", type=input.integer, defval=14)
rsi_oversold = input(title="RSI Oversold", type=input.float, defval=25.0)
rsi_overbought = input(title="RSI Overbought", type=input.float, defval=80.0)
// Calculate RSI value
rsi_value = rsi(close, rsi_length)
// RSI Moving Average
rsi_MaLength = input(14, minval=1, title="RSI Moving Average Length")
rsi_Ma = ema(rsi_value, rsi_MaLength)
// RSI Buy and Sell Signals
rsi_UpCross = crossover(rsi_value, rsi_Ma)
rsi_DownCross = crossunder(rsi_value, rsi_Ma)
rsioversold = rsi_value < rsi_oversold
rsioverbought = rsi_value > rsi_overbought
// FBB 0.702 Crossing ------------------------------------------------------------------------
//setting up the variables
FBB_length = input(200, "Fibbonaci Length", minval=1)
FBB_mult = input(3.0, "Fibbonacci Multiplikator", minval=0.001, maxval=50)
// Calculation of the 0.702 bands
dev = FBB_mult * stdev(src, FBB_length)
FBB_basis = vwma(src, FBB_length)
lower_FBB= FBB_basis - (0.702*dev)
upper_FBB= FBB_basis + (0.702*dev)
// calculation of the crossing
FBB_UpCross = crossover(src, lower_FBB)
FBB_DownCross = crossover(src, upper_FBB)
//Plotting -----------------------------------------------------------------------------------
//Plotting of the trendline
color1= cci(src,period)>=0 ? #0022FC : #FC0400
plot(Trend, color=color1, linewidth=2, title="Trend Line")
// Plot circles below the candle for a bullish trend and above the candle for a bearish trend
plotshape(bullish_trend, location=location.belowbar, style=shape.circle, color=color.green, size=size.auto, title="Bullish Trend/Dots")
plotshape(bearish_trend, location=location.abovebar, style=shape.circle, color=color.red, size=size.auto, title="Bearish Trend/Dots")
plotshape(neutral_trend, location=location.abovebar, style=shape.square, color=color.rgb(255, 255, 255), size=size.auto, title="Neutral Trend")
alertcondition(neutral_trend, title="Trend change", message="Trend went neutral")
alertcondition(bullish_trend, title="Bullish Trend", message="Trend is Bullish")
alertcondition(bearish_trend, title="Bearish Trend", message="Trend went Bearish")
//Plotting of CCI Oversold & Overbought signals
plotshape(cci_bulltime, style=shape.flag, location=location.belowbar, color=color.rgb(4, 245, 12), size=size.small, title="CCI Buy Signal")
plotshape(cci_beartime, style=shape.flag, location=location.abovebar, color=color.rgb(241, 5, 5), size=size.small, title="CCI Sell Signal")
// Alert conditions for CCI overbought and oversold
alertcondition(cci_beartime, title="CCI Sell Signal", message="Sell Signal, CCI value indicates overbought")
alertcondition(cci_bulltime, title="CCI Buy Signal", message="Buy Signal, CCI value indicates oversold")
//Plotting of crossover signals
plotshape(rsi_UpCross, style=shape.triangleup, location=location.belowbar, color=color.rgb(0, 255, 8), size=size.tiny, title="RSI Buy Signal")
plotshape(rsi_DownCross, style=shape.triangledown, location=location.abovebar, color=color.rgb(241, 3, 3), size=size.tiny, title="RSI Sell Signal")
// Alert conditions for RSI crossovers
alertcondition(rsi_UpCross, title="RSI Buy Signal", message="Buy Signal, RSI has crossed above its moving average")
alertcondition(rsi_DownCross, title="RSI Sell Signal", message="Sell Signal, RSI has crossed below its moving average")
//plotting overbought and oversold RSI
bar_color1 = rsioversold ? #da0aff : na
barcolor(bar_color1, title="Oversold RSI")
bar_color2 = rsioverbought ? color.rgb(19, 15, 243) : na
barcolor(bar_color2, title="Overbought RSI")
// Plot Fibbonacci 0.702 crossing and their lines
plotshape(FBB_UpCross, location=location.belowbar, style=shape.circle, color=#eeff00, size=size.small, title="FIB 0.702 Buy Signal")
plotshape(FBB_DownCross, location=location.abovebar, style=shape.circle, color=#eeff00, size=size.small, title="FIB 0.702 Sell Signal")
plot(lower_FBB, color=color.purple, linewidth=2, title="-0.702")
plot(upper_FBB, color=color.purple, linewidth=2, title="0.702")
alertcondition(FBB_UpCross, title="FIB 0.702 Buy Signal", message="Price crossed lower 0.702 Fibbonacci Band, buy?")
alertcondition(FBB_DownCross, title="FIB 0.702 Sell Signal", message="Price crossed higher 0.702. Fibbonacci Band, sell?")
|
UB Profit Signal Indicator | https://www.tradingview.com/script/czqXpu8B-UB-Profit-Signal-Indicator/ | UrbanBull | https://www.tradingview.com/u/UrbanBull/ | 69 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanpblogger
//@version=5
indicator("UB Profit Signal", overlay=true)
// Define input variables
macdFastLength = input.int(title="MACD Fast Length", defval=12)
macdSlowLength = input.int(title="MACD Slow Length", defval=26)
macdSignalLength = input.int(title="MACD Signal Length", defval=9)
rsiLength = input.int(title="RSI Length", defval=9)
volumeEMA = ta.ema(volume, 9)
ma100 = ta.sma(close, 9)
// Calculate MACD
[macdLine, signalLine, _] = ta.macd(hl2, macdFastLength, macdSlowLength, macdSignalLength)
macdHLCC4 = (high + low + 2*close)/4
// Calculate RSI
rsiValue = ta.rsi(close, rsiLength)
// Calculate Bollinger Bands
sma = ta.sma(close, 21)
stdev = ta.stdev(close, 21)
upperBand1 = sma + stdev
upperBand3 = sma + 3 * stdev
lowerBand1 = sma - stdev
lowerBand3 = sma - 3 * stdev
// Calculate Buy and Sell signals
buySignal = rsiValue > 30 and volume > volumeEMA and close > ma100 and close > upperBand1 and close < upperBand3 and close[1] < open[1]
sellSignal = rsiValue < 40 and volume > volumeEMA and close < ma100 and close < lowerBand1 and close > lowerBand3 and close[1] > open[1]
// Plot Buy and Sell signals
plotshape(buySignal, title="Buy", location=location.belowbar, style=shape.triangleup, color=color.green, text="Buy", size=size.small)
plotshape(sellSignal, title="Sell", location=location.abovebar, style=shape.triangledown, color=color.red, text="Sell", size=size.small)
|
Ticker Ratio Levels | https://www.tradingview.com/script/m3iH0y0S-Ticker-Ratio-Levels/ | HALDRO | https://www.tradingview.com/u/HALDRO/ | 93 | 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/
// © HALDRO
opt01 = 'XAU'
opt02 = 'DXY'
opt03 = 'BTC'
opt04 = 'ETH'
opt05 = 'SPX'
opt06 = 'NASDAQ'
opt07 = 'AVG STABLE.D'
opt08 = 'AVG STOCK Price'
opt09 = 'Alt Cap(TOTAL3)'
opt10 = 'Custom'
//@version=5
indicator('Ticker Levels', overlay = true)
mod = input.session (opt01, 'Mode', group='Chart', inline='mode', options=[opt01, opt02, opt03, opt04, opt05, opt06, opt07, opt08, opt09, opt10])
custom = input.symbol ('', 'Custom', group='Chart', inline='mode', tooltip='If you want to select a different ticker, then select the Custom in Mode option')
line1 = input(true, '', group='Lines', inline='date1')
lineDate1 = input.time(timestamp('2017-12-17 00:00 UTC'), 'Line 1', group='Lines', inline='date1')
line2 = input(true, '', group='Lines', inline='date2')
lineDate2 = input.time(timestamp('2019-06-26 00:00 UTC'), 'Line 2', group='Lines', inline='date2')
line3 = input(true, '', group='Lines', inline='date3')
lineDate3 = input.time(timestamp('2020-03-13 00:00 UTC'), 'Line 3', group='Lines', inline='date3')
line4 = input(true, '', group='Lines', inline='date4')
lineDate4 = input.time(timestamp('2017-09-14 00:00 UTC'), 'Line 4', group='Lines', inline='date4')
line5 = input(true, '', group='Lines', inline='date5')
lineDate5 = input.time(timestamp('2021-04-14 00:00 UTC'), 'Line 5', group='Lines', inline='date5')
line6 = input(true, '', group='Lines', inline='date6')
lineDate6 = input.time(timestamp('2021-07-19 14:00 UTC'), 'Line 6', group='Lines', inline='date6')
// Ticker List
TF = timeframe.period
ANY = syminfo.tickerid
CST = custom
BTC = 'BITSTAMP:BTCUSD'
DJI = 'TVC:DJI'
DXY = 'TVC:DXY'
ETH = 'BINANCE:ETHUSDT'
NDX = 'NASDAQ:NDX'
SPX = 'TVC:SPX'
WM2NS = 'FRED:WM2NS'
XAU = 'OANDA:XAUUSD'
USDT_D = 'CRYPTOCAP:USDT.D'
USDC_D = 'CRYPTOCAP:USDC.D'
DDAI_D = 'CRYPTOCAP:DAI.D'
TOTAL3 = 'TOTAL3'
// Request OHLC
[O_ANY, H_ANY, L_ANY, C_ANY] = request.security(ANY, TF, [open, high, low, close])
[O_BTC, H_BTC, L_BTC, C_BTC] = request.security(BTC, TF, [open, high, low, close])
[O_CST, H_CST, L_CST, C_CST] = request.security(CST, TF, [open, high, low, close])
[O_DJI, H_DJI, L_DJI, C_DJI] = request.security(DJI, TF, [open, high, low, close])
[O_DXY, H_DXY, L_DXY, C_DXY] = request.security(DXY, TF, [open, high, low, close])
[O_ETH, H_ETH, L_ETH, C_ETH] = request.security(ETH, TF, [open, high, low, close])
[O_NDX, H_NDX, L_NDX, C_NDX] = request.security(NDX, TF, [open, high, low, close])
[O_SPX, H_SPX, L_SPX, C_SPX] = request.security(SPX, TF, [open, high, low, close])
[O_XAU, H_XAU, L_XAU, C_XAU] = request.security(XAU, TF, [open, high, low, close])
[O_USDT_D, H_USDT_D, L_USDT_D, C_USDT_D] = request.security(USDT_D, TF, [open, high, low, close])
[O_USDC_D, H_USDC_D, L_USDC_D, C_USDC_D] = request.security(USDC_D, TF, [open, high, low, close])
[O_DDAI_D, H_DDAI_D, L_DDAI_D, C_DDAI_D] = request.security(DDAI_D, TF, [open, high, low, close])
[O_TOTAL3, H_TOTAL3, L_TOTAL3, C_TOTAL3] = request.security(TOTAL3, TF, [open, high, low, close])
// STOCK MARKET PRICE
O_STOCKAVG = (O_DJI + O_SPX + O_NDX) / 3
H_STOCKAVG = (H_DJI + H_SPX + H_NDX) / 3
L_STOCKAVG = (L_DJI + L_SPX + L_NDX) / 3
C_STOCKAVG = (C_DJI + C_SPX + C_NDX) / 3
// AVG STABLE COIN DOMINACE
O_AVGDOM = (O_USDT_D + O_USDC_D + O_DDAI_D)
H_AVGDOM = (H_USDT_D + H_USDC_D + H_DDAI_D)
L_AVGDOM = (L_USDT_D + L_USDC_D + L_DDAI_D)
C_AVGDOM = (C_USDT_D + C_USDC_D + C_DDAI_D)
tickerMod(Type) =>
ticker_Close = switch Type
opt01 => C_XAU
opt02 => C_DXY
opt03 => C_BTC
opt04 => C_ETH
opt05 => C_SPX
opt06 => C_NDX
opt07 => C_AVGDOM
opt08 => C_STOCKAVG
opt09 => C_TOTAL3
opt10 => C_CST
getLevel(getDate, Mod)=>
timeStart = time >= getDate and time[1] < getDate
ifStart = ta.valuewhen(timeStart, C_ANY / Mod, 0)
curPrice = (C_ANY / Mod)
result = (ifStart / curPrice)*C_ANY
plot(line1 ? getLevel(lineDate1, tickerMod(mod)) : na, color=color.yellow)
plot(line2 ? getLevel(lineDate2, tickerMod(mod)) : na, color=color.yellow)
plot(line3 ? getLevel(lineDate3, tickerMod(mod)) : na, color=color.yellow)
plot(line4 ? getLevel(lineDate4, tickerMod(mod)) : na, color=color.yellow)
plot(line5 ? getLevel(lineDate5, tickerMod(mod)) : na, color=color.yellow)
plot(line6 ? getLevel(lineDate6, tickerMod(mod)) : na, color=color.yellow) |
Short Term Bubble Risk | https://www.tradingview.com/script/04ha0AJc-Short-Term-Bubble-Risk/ | legroszach | https://www.tradingview.com/u/legroszach/ | 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/
// © legroszach
//@version=5
import kaigouthro/hsvColor/15
indicator('Short Term Bubble Risk', overlay=false)
source = close
smaLength = 20
sma = ta.sma(source, smaLength)
outSma = request.security(syminfo.tickerid, 'W', sma)
extension = close * 100 / outSma - 100
inputFillEnabled = input(true, 'Enable Fill', group='Fill')
inputFillDirection = input.string('Vertical', 'Gradient Direction', options=["Vertical", "Horizontal"], group='Fill')
inputSmaEnabled = input(false, 'Enable SMA')
inputSmaLength = input(8, 'SMA Length')
inputEmaEnabled = input(false, 'Enable EMA')
inputEmaLength = input(8, 'EMA Length')
if inputSmaEnabled
extension := ta.sma(extension, inputSmaLength)
if inputEmaEnabled
extension := ta.ema(extension, inputEmaLength)
risk_color(data) =>
if data >= 0
hsvColor.hsl_gradient(data, 0, 100, hsvColor.hsl(160, 1, 0.5, 1), hsvColor.hsl(0, 1, 0.5, 1))
else
hsvColor.hsl_gradient(data, -50, 0, hsvColor.hsl(245, 1, 0.5, 1), hsvColor.hsl(160, 1, 0.5, 1))
ext100 = plot(100, display=display.none)
ext75 = plot(75, display=display.none)
ext50 = plot(50, display=display.none)
ext25 = plot(25, display=display.none)
ext0 = plot(0, display=display.none)
extMinus25 = plot(-25, display=display.none)
extPlot = plot(extension, color=risk_color(extension), display=display.status_line)
displayVertical = inputFillEnabled and inputFillDirection == 'Vertical' ? display.all : display.none
displayHorizontal = inputFillEnabled and inputFillDirection == 'Horizontal' ? display.all : display.none
displayLine = not inputFillEnabled ? display.pane : display.none
// Vertical Gradient
fill(extPlot, ext0, bottom_value=extension >= 0 ? 0 : na, top_value=25, bottom_color=risk_color(0), top_color=risk_color(25), fillgaps=true, display=displayVertical)
fill(extPlot, ext25, bottom_value=extension >= 25 ? 25 : na, top_value=50, bottom_color=risk_color(25), top_color=risk_color(50), fillgaps=true, display=displayVertical)
fill(extPlot, ext50, bottom_value=extension >= 50 ? 50 : na, top_value=75, bottom_color=risk_color(50), top_color=risk_color(75), fillgaps=true, display=displayVertical)
fill(extPlot, ext75, bottom_value=extension >= 75 ? 75 : na, top_value=100, bottom_color=risk_color(75), top_color=risk_color(100), fillgaps=true, display=displayVertical)
fill(extPlot, ext0, bottom_value=extension < 0 ? -25 : na, top_value=0, bottom_color=risk_color(-25), top_color=risk_color(0), fillgaps=true, display=displayVertical)
fill(extPlot, extMinus25, bottom_value=extension <= -25 ? -50 : na, top_value=-25, bottom_color=risk_color(-50), top_color=risk_color(-25), fillgaps=true, display=displayVertical)
// Horizontal Gradient
fill(extPlot, ext0, color = risk_color(extension), fillgaps=true, display=displayHorizontal)
// Line plot
hline(0, display=inputFillEnabled ? display.none : display.all)
plot(extension, color=risk_color(extension), linewidth=2, display=displayLine) |
Draw Several Horizontal Lines [MsF] | https://www.tradingview.com/script/bHfaQrrN/ | Trader_Morry | https://www.tradingview.com/u/Trader_Morry/ | 215 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Trader_Morry
//@version=5
indicator(title='Draw Several Horizontal Lines [MsF]', shorttitle='Draw H.Lines', overlay=true, max_bars_back = 5000)
////////
// Input values
// [
var GRP1 = "--- Horizontal Lines setting ---"
iDisplay_01 = input.bool(defval = true, title = "01", group = GRP1, inline = "01")
iSymbol_01 = input.symbol(defval = "OANDA:XAUUSD", title = "", group = GRP1, inline = "01")
iHUpperValue_01 = input.float(defval = 1815, title = "H", group = GRP1, inline = "01")
iHLowerValue_01 = input.float(defval = 1810, title = "L", group = GRP1, inline = "01")
iDisplay_02 = input.bool(defval = true, title = "02", group = GRP1, inline = "02")
iSymbol_02 = input.symbol(defval = "OANDA:USDJPY", title = "", group = GRP1, inline = "02")
iHUpperValue_02 = input.float(defval = 138, title = "H", group = GRP1, inline = "02")
iHLowerValue_02 = input.float(defval = 136, title = "L", group = GRP1, inline = "02")
iDisplay_03 = input.bool(defval = true, title = "03", group = GRP1, inline = "03")
iSymbol_03 = input.symbol(defval = "OANDA:EURUSD", title = "", group = GRP1, inline = "03")
iHUpperValue_03 = input.float(defval = 1.06, title = "H", group = GRP1, inline = "03")
iHLowerValue_03 = input.float(defval = 1.05, title = "L", group = GRP1, inline = "03")
iDisplay_04 = input.bool(defval = true, title = "04", group = GRP1, inline = "04")
iSymbol_04 = input.symbol(defval = "OANDA:EURJPY", title = "", group = GRP1, inline = "04")
iHUpperValue_04 = input.float(defval = 145.568, title = "H", group = GRP1, inline = "04")
iHLowerValue_04 = input.float(defval = 144.193, title = "L", group = GRP1, inline = "04")
iDisplay_05 = input.bool(defval = true, title = "05", group = GRP1, inline = "05")
iSymbol_05 = input.symbol(defval = "OANDA:GBPUSD", title = "", group = GRP1, inline = "05")
iHUpperValue_05 = input.float(defval = 1.19, title = "H", group = GRP1, inline = "05")
iHLowerValue_05 = input.float(defval = 1.17, title = "L", group = GRP1, inline = "05")
iDisplay_06 = input.bool(defval = true, title = "06", group = GRP1, inline = "06")
iSymbol_06 = input.symbol(defval = "OANDA:GBPJPY", title = "", group = GRP1, inline = "06")
iHUpperValue_06 = input.float(defval = 164, title = "H", group = GRP1, inline = "06")
iHLowerValue_06 = input.float(defval = 161, title = "L", group = GRP1, inline = "06")
iDisplay_07 = input.bool(defval = true, title = "07", group = GRP1, inline = "07")
iSymbol_07 = input.symbol(defval = "OANDA:AUDUSD", title = "", group = GRP1, inline = "07")
iHUpperValue_07 = input.float(defval = 0.66, title = "H", group = GRP1, inline = "07")
iHLowerValue_07 = input.float(defval = 0.64, title = "L", group = GRP1, inline = "07")
iDisplay_08 = input.bool(defval = true, title = "08", group = GRP1, inline = "08")
iSymbol_08 = input.symbol(defval = "OANDA:AUDJPY", title = "", group = GRP1, inline = "08")
iHUpperValue_08 = input.float(defval = 92, title = "H", group = GRP1, inline = "08")
iHLowerValue_08 = input.float(defval = 90, title = "L", group = GRP1, inline = "08")
iDisplay_09 = input.bool(defval = true, title = "09", group = GRP1, inline = "09")
iSymbol_09 = input.symbol(defval = "OANDA:GBPAUD", title = "", group = GRP1, inline = "09")
iHUpperValue_09 = input.float(defval = 1.81, title = "H", group = GRP1, inline = "09")
iHLowerValue_09 = input.float(defval = 1.78, title = "L", group = GRP1, inline = "09")
iDisplay_10 = input.bool(defval = true, title = "10", group = GRP1, inline = "10")
iSymbol_10 = input.symbol(defval = "OANDA:EURAUD", title = "", group = GRP1, inline = "10")
iHUpperValue_10 = input.float(defval = 1.62, title = "H", group = GRP1, inline = "10")
iHLowerValue_10 = input.float(defval = 1.58, title = "L", group = GRP1, inline = "10")
iBandCount = input.int(defval = 6, minval = 1, maxval = 10, title = "Band Lines Count", group = GRP1)
iUnitedIndividual = "united" //input.string(title='Line Type setting', defval="united", options=["united", "individual"], group = GRP1)
var GRP2 = "--- United Line Type setting ---"
iMainLineColor = input.color(defval = color.yellow, title = "Color", group = GRP2, inline = "main")
iMainLineWidth = input.int(defval = 2, title = "Width", group = GRP2, inline = "main")
iMainLineStyle = input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP2, inline = "main")
iSubLineColor = input.color(defval = color.rgb(255,235,59,80), title = "Color", group = GRP2, inline = "sub")
iSubLineWidth = input.int(defval = 2, title = "Width", group = GRP2, inline = "sub")
iSubLineStyle = input.string(title='Style', defval=line.style_dashed, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP2, inline = "sub")
//var GRP3 = "--- Individual Line Type setting ---"
iMainLineColor_01 = iMainLineColor //input.color(defval = color.yellow, title = "01-M", group = GRP3, inline = "11")
iMainLineWidth_01 = iMainLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "11")
iMainLineStyle_01 = iMainLineStyle //input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "11")
iSubLineColor_01 = iSubLineColor //input.color(defval = color.rgb(255,235,59,80), title = "01-S", group = GRP3, inline = "12")
iSubLineWidth_01 = iSubLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "12")
iSubLineStyle_01 = iSubLineStyle //input.string(title='Style', defval=line.style_dashed, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "12")
iMainLineColor_02 = iMainLineColor //input.color(defval = color.yellow, title = "02-M", group = GRP3, inline = "21")
iMainLineWidth_02 = iMainLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "21")
iMainLineStyle_02 = iMainLineStyle //input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "21")
iSubLineColor_02 = iSubLineColor //input.color(defval = color.rgb(255,235,59,80), title = "02-S", group = GRP3, inline = "22")
iSubLineWidth_02 = iSubLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "22")
iSubLineStyle_02 = iSubLineStyle //input.string(title='Style', defval=line.style_dashed, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "22")
iMainLineColor_03 = iMainLineColor //input.color(defval = color.yellow, title = "03-M", group = GRP3, inline = "31")
iMainLineWidth_03 = iMainLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "31")
iMainLineStyle_03 = iMainLineStyle //input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "31")
iSubLineColor_03 = iSubLineColor //input.color(defval = color.rgb(255,235,59,80), title = "03-S", group = GRP3, inline = "32")
iSubLineWidth_03 = iSubLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "32")
iSubLineStyle_03 = iSubLineStyle //input.string(title='Style', defval=line.style_dashed, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "32")
iMainLineColor_04 = iMainLineColor //input.color(defval = color.yellow, title = "04-M", group = GRP3, inline = "41")
iMainLineWidth_04 = iMainLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "41")
iMainLineStyle_04 = iMainLineStyle //input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "41")
iSubLineColor_04 = iSubLineColor //input.color(defval = color.rgb(255,235,59,80), title = "04-S", group = GRP3, inline = "42")
iSubLineWidth_04 = iSubLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "42")
iSubLineStyle_04 = iSubLineStyle //input.string(title='Style', defval=line.style_dashed, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "42")
iMainLineColor_05 = iMainLineColor //input.color(defval = color.yellow, title = "05-M", group = GRP3, inline = "51")
iMainLineWidth_05 = iMainLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "51")
iMainLineStyle_05 = iMainLineStyle //input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "51")
iSubLineColor_05 = iSubLineColor //input.color(defval = color.rgb(255,235,59,80), title = "05-S", group = GRP3, inline = "52")
iSubLineWidth_05 = iSubLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "52")
iSubLineStyle_05 = iSubLineStyle //input.string(title='Style', defval=line.style_dashed, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "52")
iMainLineColor_06 = iMainLineColor //input.color(defval = color.yellow, title = "06-M", group = GRP3, inline = "61")
iMainLineWidth_06 = iMainLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "61")
iMainLineStyle_06 = iMainLineStyle //input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "61")
iSubLineColor_06 = iSubLineColor //input.color(defval = color.rgb(255,235,59,80), title = "06-S", group = GRP3, inline = "62")
iSubLineWidth_06 = iSubLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "62")
iSubLineStyle_06 = iSubLineStyle //input.string(title='Style', defval=line.style_dashed, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "62")
iMainLineColor_07 = iMainLineColor //input.color(defval = color.yellow, title = "07-M", group = GRP3, inline = "71")
iMainLineWidth_07 = iMainLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "71")
iMainLineStyle_07 = iMainLineStyle //input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "71")
iSubLineColor_07 = iSubLineColor //input.color(defval = color.rgb(255,235,59,80), title = "07-S", group = GRP3, inline = "72")
iSubLineWidth_07 = iSubLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "72")
iSubLineStyle_07 = iSubLineStyle //input.string(title='Style', defval=line.style_dashed, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "72")
iMainLineColor_08 = iMainLineColor //input.color(defval = color.yellow, title = "08-M", group = GRP3, inline = "81")
iMainLineWidth_08 = iMainLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "81")
iMainLineStyle_08 = iMainLineStyle //input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "81")
iSubLineColor_08 = iSubLineColor //input.color(defval = color.rgb(255,235,59,80), title = "08-S", group = GRP3, inline = "82")
iSubLineWidth_08 = iSubLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "82")
iSubLineStyle_08 = iSubLineStyle //input.string(title='Style', defval=line.style_dashed, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "82")
iMainLineColor_09 = iMainLineColor //input.color(defval = color.yellow, title = "09-M", group = GRP3, inline = "91")
iMainLineWidth_09 = iMainLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "91")
iMainLineStyle_09 = iMainLineStyle //input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "91")
iSubLineColor_09 = iSubLineColor //input.color(defval = color.rgb(255,235,59,80), title = "09-S", group = GRP3, inline = "92")
iSubLineWidth_09 = iSubLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "92")
iSubLineStyle_09 = iSubLineStyle //input.string(title='Style', defval=line.style_dashed, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "92")
iMainLineColor_10 = iMainLineColor //input.color(defval = color.yellow, title = "10-M", group = GRP3, inline = "01")
iMainLineWidth_10 = iMainLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "01")
iMainLineStyle_10 = iMainLineStyle //input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "01")
iSubLineColor_10 = iSubLineColor //input.color(defval = color.rgb(255,235,59,80), title = "10-S", group = GRP3, inline = "02")
iSubLineWidth_10 = iSubLineWidth //input.int(defval = 2, title = "Width", group = GRP3, inline = "02")
iSubLineStyle_10 = iSubLineStyle //input.string(title='Style', defval=line.style_dashed, options=[line.style_dotted, line.style_dashed, line.style_solid], group = GRP3, inline = "02")
// ]
// Defines
// [
// ]
// Prepare
// [
// ]
// Functions
// [
// Drawing Horizontal Lines Function
// [
drawing_Horizontal_Lines(aHUpperValue, aHLowerValue, aMainLineColor, aMainLineWidth, aMainLineStyle, aSubLineColor, aSubLineWidth, aSubLineStyle) =>
//Lines type setting
var color _color = na
var int _width = 0
var string _style = ""
if iUnitedIndividual == "united"
_color := iMainLineColor
_width := iMainLineWidth
_style := iMainLineStyle
else
_color := aMainLineColor
_width := aMainLineWidth
_style := aMainLineStyle
//for horizontal lines
_Mainpips = math.abs(aHUpperValue-aHLowerValue)
hSubValue = aHUpperValue-_Mainpips
_bandPips = _Mainpips / 2
// Draw base line
var line line_Base = na
line.delete(line_Base)
line_Base := line.new(bar_index, hSubValue, bar_index+1, hSubValue, extend = extend.both, color = _color, width = _width, style = _style)
// Draw band line
var line line_Band_Upper = na
var line line_Band_Lower = na
// Draw Band Lines
for cnt = 1 to iBandCount
if cnt%2==0 //偶数
if iUnitedIndividual == "united"
_color := iMainLineColor
_width := iMainLineWidth
_style := iMainLineStyle
else
_color := aMainLineColor
_width := aMainLineWidth
_style := aMainLineStyle
else //奇数
if iUnitedIndividual == "united"
_color := iSubLineColor
_width := iSubLineWidth
_style := iSubLineStyle
else
_color := aSubLineColor
_width := aSubLineWidth
_style := aSubLineStyle
line_Band_Upper := line.new(bar_index, hSubValue+_bandPips*cnt, bar_index+1, hSubValue+_bandPips*cnt, extend = extend.both, color = _color, width = _width, style = _style)
line_Band_Lower := line.new(bar_index, hSubValue-_bandPips*cnt, bar_index+1, hSubValue-_bandPips*cnt, extend = extend.both, color = _color, width = _width, style = _style)
// ]
// ]
// Main Program
// [
// Draw horizontal line
// [
if barstate.islast
if iDisplay_01 and syminfo.ticker == syminfo.ticker(iSymbol_01)
drawing_Horizontal_Lines(iHUpperValue_01, iHLowerValue_01, iMainLineColor_01, iMainLineWidth_01, iMainLineStyle_01, iSubLineColor_01, iSubLineWidth_01, iSubLineStyle_01)
if iDisplay_02 and syminfo.ticker == syminfo.ticker(iSymbol_02)
drawing_Horizontal_Lines(iHUpperValue_02, iHLowerValue_02, iMainLineColor_02, iMainLineWidth_02, iMainLineStyle_02, iSubLineColor_02, iSubLineWidth_02, iSubLineStyle_02)
if iDisplay_03 and syminfo.ticker == syminfo.ticker(iSymbol_03)
drawing_Horizontal_Lines(iHUpperValue_03, iHLowerValue_03, iMainLineColor_03, iMainLineWidth_03, iMainLineStyle_03, iSubLineColor_03, iSubLineWidth_03, iSubLineStyle_03)
if iDisplay_04 and syminfo.ticker == syminfo.ticker(iSymbol_04)
drawing_Horizontal_Lines(iHUpperValue_04, iHLowerValue_04, iMainLineColor_04, iMainLineWidth_04, iMainLineStyle_04, iSubLineColor_04, iSubLineWidth_04, iSubLineStyle_04)
if iDisplay_05 and syminfo.ticker == syminfo.ticker(iSymbol_05)
drawing_Horizontal_Lines(iHUpperValue_05, iHLowerValue_05, iMainLineColor_05, iMainLineWidth_05, iMainLineStyle_05, iSubLineColor_05, iSubLineWidth_05, iSubLineStyle_05)
if iDisplay_06 and syminfo.ticker == syminfo.ticker(iSymbol_06)
drawing_Horizontal_Lines(iHUpperValue_06, iHLowerValue_06, iMainLineColor_06, iMainLineWidth_06, iMainLineStyle_06, iSubLineColor_06, iSubLineWidth_06, iSubLineStyle_06)
if iDisplay_07 and syminfo.ticker == syminfo.ticker(iSymbol_07)
drawing_Horizontal_Lines(iHUpperValue_07, iHLowerValue_07, iMainLineColor_07, iMainLineWidth_07, iMainLineStyle_07, iSubLineColor_07, iSubLineWidth_07, iSubLineStyle_07)
if iDisplay_08 and syminfo.ticker == syminfo.ticker(iSymbol_08)
drawing_Horizontal_Lines(iHUpperValue_08, iHLowerValue_08, iMainLineColor_08, iMainLineWidth_08, iMainLineStyle_08, iSubLineColor_08, iSubLineWidth_08, iSubLineStyle_08)
if iDisplay_09 and syminfo.ticker == syminfo.ticker(iSymbol_09)
drawing_Horizontal_Lines(iHUpperValue_09, iHLowerValue_09, iMainLineColor_09, iMainLineWidth_09, iMainLineStyle_09, iSubLineColor_09, iSubLineWidth_09, iSubLineStyle_09)
if iDisplay_10 and syminfo.ticker ==syminfo.ticker( iSymbol_10)
drawing_Horizontal_Lines(iHUpperValue_10, iHLowerValue_10, iMainLineColor_10, iMainLineWidth_10, iMainLineStyle_10, iSubLineColor_10, iSubLineWidth_10, iSubLineStyle_10)
// ]
//// Alert
// [
// ]
// ]
|
CBDE Oscillator | https://www.tradingview.com/script/JIqYG4CA-CBDE-Oscillator/ | DarklyEnergized | https://www.tradingview.com/u/DarklyEnergized/ | 167 | 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/
// © kstrat2001
//@version=5
// Central Bank Dark Energy Oscillator
indicator(title = "CBDE Oscillator", shorttitle = "CBDEO", overlay = false)
oscillator_gradient_color(signal, high_color, low_color) =>
signal_max = ta.max(signal)
signal_min = ta.min(signal)
bull_color = color.from_gradient(signal, 0, signal_max, color.new(high_color, 60), color.new(high_color, 0))
bear_color = color.from_gradient(signal, signal_min, 0, color.new(low_color, 0), color.new(low_color, 60))
osc_color = signal < 0 ? bear_color : bull_color
to_billions(value) =>
billions = value/1000000000
liquidity_sma_length = input.int(12, "SMA length", 1, 1000, 1, tooltip = "The moving average duration used to determine the divergence in liquidity changes")
// CB Assets
include_cbs_group = "Assets To Include"
include_us = input.bool(true, "US Assets", group = include_cbs_group)
include_jpy = input.bool(true, "JPY Assets", group = include_cbs_group)
include_cny = input.bool(true, "CNY Assets", group = include_cbs_group)
include_uk = input.bool(true, "UK Assets", group = include_cbs_group)
include_snb = input.bool(true, "SNB Assets", group = include_cbs_group)
include_ecb = input.bool(true, "ECB Assets", group = include_cbs_group)
include_krc = input.bool(true, "KRC Assets", group = include_cbs_group)
include_cad = input.bool(true, "CAD Assets", group = include_cbs_group)
fed_bal_sheet_group_name = "Include Fed Balance Sheet Items"
include_wshoicl = input.bool(true, "Inflation Compensation (WSHOICL)", "Include Fed 'Inflation Compensation' (WSHOICL) from assets portion of balance sheet", group = fed_bal_sheet_group_name)
include_wupsho = input.bool(true, "Unamortized Premiums (WUPSHO)", "Include Fed 'Unamortized Premiums' (WUPSHO) from assets portion of balance sheet", group = fed_bal_sheet_group_name)
include_wlcfll = input.bool(true, "Loans (WLCFLL)", "Include Fed 'Loans' (WLCFLL) from assets portion of balance sheet", group = fed_bal_sheet_group_name)
include_wlad = input.bool(true, "Other/Remittances (WLAD)", "Include Fed remittances (WLAD) from liabilities portion of balance sheet", group = fed_bal_sheet_group_name)
tga_override = input.bool(false, "TGA Balance Override (Billions)", "Overrides the current balance of the Treasury General Accout. This allows use of the daily balance data rather than waiting for the weekly data to update.", inline = "tga_override", group = fed_bal_sheet_group_name)
tga_override_value = input.float(0, "", 0, 10000000000, 1, inline = "tga_override", group = fed_bal_sheet_group_name)
// FOREIGN CENTRAL BANK ASSETS
line_japan = request.security("FRED:JPNASSETS * FX_IDC:JPYUSD", "D", close, currency = currency.USD)
line_china = request.security("CNCBBS * FX_IDC:CNYUSD", "D", close, currency = currency.USD)
line_uk = request.security("GBCBBS * FX:GBPUSD", "D", close, currency = currency.USD)
line_ecb = request.security("ECBASSETSW * FX:EURUSD", "D", close, currency = currency.USD)
line_snb = request.security("CHCBBS", "D", close, currency = currency.USD)
line_krc = request.security("ECONOMICS:KRCBBS*FX_IDC:KRWUSD", "D", close, currency = currency.USD)
line_cad = request.security("CACBBS * CADUSD", "D", close, currency = currency.USD)
line_fed_walcl = request.security("FRED:WALCL", "D", close, currency = currency.USD)
line_fed_tga = request.security("WDTGAL", "D", close, currency = currency.USD)
line_rrp = request.security("RRPONTSYD", "D", close, currency = currency.USD)
// Optional factors on Fed balance sheet
line_fed_wshoicl = request.security("WSHOICL", "D", close, currency = currency.USD)
line_fed_wupsho = request.security("WUPSHO", "D", close, currency = currency.USD)
line_fed_wlcfll = request.security("WLCFLL", "D", close, currency = currency.USD)
line_fed_wlad = request.security("WLAD", "D", close, currency = currency.USD)
// conditionally determine which CB assets are used in the total liquidity pool based on user settings
jpy_final = (include_jpy ? line_japan : 0)
cny_final = (include_cny ? line_china : 0)
gbp_final = (include_uk ? line_uk : 0)
snb_final = (include_snb ? line_snb : 0)
ecb_final = (include_ecb ? line_ecb : 0)
krc_final = (include_krc ? line_krc : 0)
cad_final = (include_cad ? line_cad : 0)
// Non-US central bank totals
non_us_total = jpy_final + cny_final + gbp_final + snb_final + ecb_final + krc_final + cad_final
// FED subtractions
wshoicl_final = (include_wshoicl ? 0 : line_fed_wshoicl)
wupsho_final = (include_wupsho ? 0 : line_fed_wupsho)
wlcfll_final = (include_wlcfll ? 0 : line_fed_wlcfll)
assets_subtractions = wlcfll_final + wupsho_final + wshoicl_final
assets_total = line_fed_walcl - assets_subtractions
// FED liabilities
tga_final = barstate.islast and tga_override ? tga_override_value * 1000000000 : line_fed_tga
wlad_final = (include_wlad ? line_fed_wlad : 0)
liabilities_total = tga_final + line_rrp + wlad_final
fed_total = assets_total - liabilities_total
// Total liquidity using a scale factor to get the value in billions
total_liquidity = to_billions((include_us ? fed_total : 0) + non_us_total)
// Delta Plot
liquidity_delta = total_liquidity - total_liquidity[1]
plot(liquidity_delta, color = oscillator_gradient_color(liquidity_delta, color.lime, color.red), linewidth = 4, title="Liquidity 1-Bar Delta", style = plot.style_columns)
// TGA vs RRP plot
tga_change_billions = to_billions(tga_final - tga_final[1])
rrp_change_billions = to_billions(line_rrp - line_rrp[1])
tga_rrp_delta = tga_change_billions + rrp_change_billions
plot(tga_rrp_delta, color = oscillator_gradient_color(tga_rrp_delta, color.aqua, color.orange), linewidth = 4, title="TGA+RRP total 1-Bar Delta", style = plot.style_columns, display = display.none)
// SMA Divergence Plot
liquidity_ma = ta.sma(total_liquidity, liquidity_sma_length)
divergence_signal = (liquidity_ma - total_liquidity)*-1.0
plot(divergence_signal, color = oscillator_gradient_color(divergence_signal, color.aqua, color.yellow), linewidth = 2, title="Liquidity SMA Oscillator", display = display.none)
hline(0) |
+ Average Candle Bodies Range | https://www.tradingview.com/script/yYyunIRv-Average-Candle-Bodies-Range/ | ClassicScott | https://www.tradingview.com/u/ClassicScott/ | 90 | 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/
// © ClassicScott
// ACBR, or, Average Candle Bodies Range is a volatility and momentum indicator designed to indicate periods of increasing volatility and/or
// momentum. The genesis of the idea formed from my pondering what a trend trader is really looking for in terms of a volatility indicator. Most
// indicators I've come across haven't, in my opinion, done a satisfactory job of highlighting this. I kept thinking about the ATR (I use it for
// stops and targets) but I realized I didn't care about highs or lows in regards to a candle's volatility or momentum, nor do I care about their
// relation to a previous close. What really matters to me is candle body expansion. That is all. So, I created this.
// ACBR is extremely simple at its heart. I made it more complicated of course, because why would I want anything for myself to be simple?
// Originally it was envisaged to be a simple volatility indicator highlighting areas of increasing and decreasing volatility. Then I decided
// some folks might want an indicator that could show this in a directional manner, i.e., an oscillator, so I spent some more hours tackling that
// To start, the original version of the indicator simply subtracts opening price from closing price if the candle closes above the open, and
// subtracts the close from the open if the candle closes below the open. This way we get a positive number that simply measures candle expansion.
// We then apply a moving average to these values in order to smooth them (if you want). To get an oscillator we always subtract the close from
// the open, thus when a candle closes below its open we get a negative number.
// I've naturally added an optional signal line as a helpful way of gauging volatility because obviously the values themselves may not tell you
// much. But I've also added something that I call a baseline. You can use this in a few ways, but first let me explain the two options for how
// the baseline can be calculated. And what do I mean by 'baseline?' I think of it as an area of the indicator where if the ACBR is below you will
// not want to enter into any trades, and if the ACBR is above then you are free to enter trades based on your system (or you might want to enter
// in areas of low volatility if your system calls for that). Waddah Attar Explosion is another indicator that implements something similar.
// The baseline is calculated in two different ways: one of which is making a Donchian Channel of the ACBR, and then using the basis as the
// baseline, while the other is applying an RMA to the cb_dif, which is the base unit that makes up the ACBR. Now, the basis of a Donchian Channel
// typically is the average of the highs and the lows. If we did that here we would have a baseline much too high (but maybe not...), however,
// I've made the divisor user adjustable. In this way you can adjust the height (or I guess you might say 'width' if it's an oscillator) however
// you like, thus making the indicator more or less sensitive. In the case of using the ACBR as the baseline we apply a multiplier to the values
// in order to adjust the height. Apologies if I'm being overly verbose. If you want to skip all of this I have tooltips in the settings for all of
// the inputs that I think need an explanation.
// When using the indicator as an oscillator there are baselines above and below the zero line. One funny thing: if using the ACBR as calculation
// type for the baselines in oscillator mode, the baselines themselves will oscillate around the zero line. There is no way to fix this due to
// the calculation. That isn't necessarily bad (based on my eyeball test), but I probably wouldn't use it in such a way. But experiment! They
// could actually be a very fine entry or confirmation indicator. And while I'm on the topic of confirmation indicators, using this indicator as
// an oscillator naturally makes it a confirmation indicator. It just happens to have a volatility measurement baked into it. It may also be used
// as an exit and continuation indicator. And speaking of these things, there are optional shapes for indicating when you might want to exit or
// take a continuation trade. I've added alerts for these things too.
// Lastly, oscillator mode is good for identifying divergences.
// ****** \\
// *** A note on colors in the style tab
// I truly do not understand why TradingView has every single color grouped together under (nearly) every single adjustable element of the indicator.
// It makes no sense to me because only certain colors apply to certain aspects of it. I'm going to help you out here by giving you a cheat sheet
// so you can make color changes more easily.
// Colors 0 and 1 apply to the ACBR plot.
// Colors 2, 3, and 4 apply to the background coloring.
// Colors 5 and 6 apply to advancing and declining volatility (bar color for crosses)
// Colors 7, 8, and 9 apply to candle colors
//@version=5
indicator("+ Average Candle Bodies Range", shorttitle='+ AVG CBR', format=format.inherit , timeframe='', timeframe_gaps=true)
////INPUTS\\\\
//ACBR INPUTS
average_type = input.string(defval='EMA', options=['EMA', 'HMA', 'RMA', 'SMA', 'VWMA', 'WMA'], title='Smoothing Type', group='Candle Bodies Inputs')
period = input.int(defval=4, title='Period', group='Candle Bodies Inputs')
//SIGNAL LINE INPUTS
signal_type = input.string(defval='HMA', options=['EMA', 'HMA', 'RMA', 'SMA', 'VWMA', 'WMA'], title='Signal Type', group='Signal Line Inputs')
signal_period = input.int(defval=14, title='Period', group='Signal Line Inputs')
//BASELINE INPUTS
bline_type = input.string(defval='Donchian', options=['Donchian', 'ACBR'], title='Baseline Calculation Type', group='Baseline Inputs', tooltip='How the baseline is calculated to determine volatility is either via a Donchian Channel, whereby the highest and lowest of the average range is calculated over a determined period, and the basis is used as the baseline (this can be adjusted with the height input), or the Average Candle Bodies Range, which is adjusted by its own height input. If you are using this as an oscillator I dont recommend using the ACBR as a baseline because of the way it calculates, however, if you do try to use it this way at least have signal line momentum turned on.')
vol_period_type = input.string(defval='RexDog Self-Adjusting', options=['RexDog Self-Adjusting', 'User Selected'], title='Baseline Period Type', group='Baseline Inputs', tooltip='RexDog Self-Adjusting is based on the RexDog Average by xkavalis. It is an average of six different averages, thus it is dynamic, or self-adjusting, and can not be changed by the user. If you want to be able to choose an averaging period yourself select User Selected.')
vol_period = input.int(defval=200, title='Period', group='Baseline Inputs', tooltip='You can ignore this if using the RexDog BPT above, otherwise, a smaller number is going to be more reactive to changes in volatility, whereas a larger number will not. There is no right or wrong answer here.')
divisor = input.float(defval=3, title='Donchian Calculated Height', minval=0.1, step=0.1, group='Baseline Inputs', tooltip='This adjusts the height of your baseline, and, if using the RexDog BPT, is the only way to adjust the sensitivity. A smaller number makes for a baseline farther away from zero. Probably want to stay above two. Three to three and a half is a good range to start.')
cb_mult = input.float(defval=1, title='ACBR Calculated Height', minval=0.1, step=0.1, group='Baseline Inputs', tooltip='Same as above but for two things. One: contrary to the Donchian height, a larger number increases the distance of the baseline from zero (I recommend no greater than 1 in non-directional mode, and even that, in my opinion, is too high). Two: if using as an oscillator, the baseline period plays heavily into how you will adjust the height. Larger numbers like 200 need a larger height, like 3. However, as stated in the above first tooltip, I dont recommend it being used this way.')
//GENERAL OPTIONS
signal_rise_fall = input.bool(defval=true, title='Require Increasing Momentum of Signal Line', group='General Options', tooltip='Require that the signal line be rising in non-directional mode, or, when in oscillator mode, rising when the ACBR is above zero and falling when it is below zero to highlight increasing volatility. Remember, a moving average (which is what a signal line is) is a measure of the momentum of the underlying source, in this case volatility. In oscillator mode a falling signal line would be defined as increasing in momentum once the ACBR crosses below zero.')
avg_range_style = input.bool(defval=false, title='ACBR is Directional', group='General Options', tooltip='If checked the ACBR oscillates around a zero line indicating bullish or bearish volatility. If unchecked it is a measure of market volatility only, and does not indicate a direction to trade in.')
//BAR COLOR AND BACKGROUND COLOR SIGNAL LINE OPTIONS
bg_signal = input.bool(defval=false, title='Color Background', group='Signal Line Options', tooltip='Colors background if the ACBR is beyond the signal line.')
barcolor_signal = input.bool(defval=false, title='Color Bars', group='Signal Line Options', tooltip='Colors bars if the ACBR is beyond the signal line.')
strong_signal = input.bool(false, 'Volatility Advancing', group='Signal Line Options', tooltip='Colors the bar when the ACBR crosses above the signal line in non-directional mode. Colors the bar when the ACBR crosses above the signal line when above zero or below the signal line when below zero in oscillator mode.')
weak_signal = input.bool(false, 'Volatility Declining', group='Signal Line Options', tooltip='Colors the bar when the ACBR crosses below the signal line when in non-directional mode. Colors the bar when the ACBR crosses below the signal line when above zero or above the signal line when below zero in oscillator mode.')
//BAR COLOR AND BACKGROUND COLOR BASELINE OPTIONS
bg_bline = input.bool(defval=false, title='Color Background', group='Baseline Options', tooltip='Colors background if the ACBR is beyond the baseline(s).')
barcolor_bline = input.bool(defval=true, title='Color Bars', group='Baseline Options', tooltip='Colors bars if the ACBR is beyond the baseline(s).')
strong_bline = input.bool(false, 'Volatility Advancing', group='Baseline Options', tooltip='Colors the bar when the ACBR crosses above the baseline in non-directional mode. Colors the bar when the ACBR crosses above the upper baseline or below the lower baseline when in oscillator mode.')
weak_bline = input.bool(false, 'Volatility Declining', group ='Baseline Options', tooltip='Colors the bar when the ACBR crosses below the baseline in non-directional mode. Colors the bar when the ACBR crosses below the upper baseline or above the lower baseline when in oscillator mode.')
/////////////////////////////////////////////////////////////////////////////////////
////CANDLE BODY CALCULATION
float cb_dif = 0.0
if not avg_range_style and close > open
cb_dif := close - open
else if not avg_range_style and close < open
cb_dif := open - close
else if avg_range_style
cb_dif := close - open
////MOVING AVERAGE TO USE TO CREATE THE AVERAGE
cb_range(type, src, period) =>
float result = 0
if type == 'EMA'
result := ta.ema(cb_dif, period)
if type == 'HMA'
result := ta.hma(cb_dif, period)
if type == 'RMA'
result := ta.rma(cb_dif, period)
if type == 'SMA'
result := ta.sma(cb_dif, period)
if type == 'VWMA'
result := ta.vwma(cb_dif, period)
if type == 'WMA'
result := ta.wma(cb_dif, period)
result
avg_range = cb_range(average_type, cb_dif, period)
////SIGNAL LINE CHOICES
signal(type, src, signal_period) =>
float result = 0
if type == 'EMA'
result := ta.ema(avg_range, signal_period)
if type == 'HMA'
result := ta.hma(avg_range, signal_period)
if type == 'RMA'
result := ta.rma(avg_range, signal_period)
if type == 'SMA'
result := ta.sma(avg_range, signal_period)
if type == 'VWMA'
result := ta.vwma(avg_range, signal_period)
if type == 'WMA'
result := ta.wma(avg_range, signal_period)
result
signal_line = signal(signal_type, avg_range, signal_period)
/////////////////////////////////////////////////////////////////////////////////////
////CALCULATIONS FOR BASELINE VOLATILITY
//DONCHIAN CHANNEL
highest_baseline = vol_period_type == 'RexDog Self-Adjusting' ? (ta.highest(avg_range, 5) + ta.highest(avg_range, 9) + ta.highest(avg_range, 24) + ta.highest(avg_range, 50) + ta.highest(avg_range, 100) + ta.highest(avg_range, 200)) / 6 : ta.highest(avg_range, vol_period)
lowest_baseline = vol_period_type == 'RexDog Self-Adjusting' ? (ta.lowest(avg_range, 5) + ta.lowest(avg_range, 9) + ta.lowest(avg_range, 24) + ta.lowest(avg_range, 50) + ta.lowest(avg_range, 100) + ta.lowest(avg_range, 200)) / 6 : ta.lowest(avg_range, vol_period)
//ACBR
acbr_baseline = vol_period_type == 'RexDog Self-Adjusting' ? (ta.rma(cb_dif, 5) + ta.rma(cb_dif, 9) + ta.rma(cb_dif, 24) + ta.rma(cb_dif, 50) + ta.rma(cb_dif, 100) + ta.rma(cb_dif, 200)) / 6 : ta.rma(cb_dif, vol_period)
//COMPLETE
high_baseline = bline_type == 'Donchian' and avg_range_style ? highest_baseline / divisor : bline_type == 'Donchian' and not avg_range_style ? (highest_baseline + lowest_baseline) / divisor : bline_type == 'ACBR' ? acbr_baseline * cb_mult : na
low_baseline = bline_type == 'Donchian' and avg_range_style ? lowest_baseline / divisor : bline_type == 'ACBR' ? acbr_baseline * cb_mult * -1 : na
/////////////////////////////////////////////////////////////////////////////////////
////ACBR COLOR
avg_range_color = if not avg_range_style and avg_range > avg_range[1]
color.new(#ff9800, 0)
else if not avg_range_style and avg_range < avg_range[1]
color.new(#2962ff, 0)
else if avg_range > 0 and avg_range > avg_range[1] and avg_range_style
color.new(#ff9800, 0)
else if avg_range > 0 and avg_range < avg_range[1] and avg_range_style
color.new(#2962ff, 0)
else if avg_range < 0 and avg_range < avg_range[1] and avg_range_style
color.new(#ff9800, 0)
else if avg_range < 0 and avg_range > avg_range[1] and avg_range_style
color.new(#2962ff, 0)
/////////////////////////////////////////////////////////////////////////////////////
////PLOTS
plot(avg_range, title='Average Candle Bodies Range', color=avg_range_color, linewidth=2, style=plot.style_histogram)
plot(signal_line, title='Signal Line', color=signal_line > 0 and signal_line > signal_line[1] or signal_line < 0 and signal_line < signal_line[1] ? color.new(#00bcd4, 0) : signal_line < 0 and signal_line > signal_line[1] or signal_line > 0 and signal_line < signal_line[1] ? color.new(#e91e63, 0) : na , linewidth=2, style=plot.style_line)
plot(high_baseline, title='High Baseline', color=color.yellow, style=plot.style_line)
plot(avg_range_style ? low_baseline : na, title='Low Baseline', color=color.yellow, style=plot.style_line)
/////////////////////////////////////////////////////////////////////////////////////
//SIGNAL LINE RISING/FALLING -- SEE signal_rise_fall UNDER GENERAL OPTIONS
signal_rising = signal_rise_fall and signal_line > signal_line[1]
signal_falling = signal_rise_fall and signal_line < signal_line[1]
/////////////////////////////////////////////////////////////////////////////////////
////BACKGROUND COLOR CONDITIONS AND COLORING
//DIRECTIONAL
dir_above_bline = bg_bline and avg_range_style and high_baseline > 0 and avg_range > high_baseline or bg_bline and low_baseline > 0 and avg_range > low_baseline
dir_below_bline = bg_bline and avg_range_style and low_baseline < 0 and avg_range < low_baseline or bg_bline and high_baseline < 0 and avg_range < high_baseline
dir_above_signal = bg_signal and avg_range_style and avg_range > 0 and avg_range > signal_line
dir_below_signal = bg_signal and avg_range_style and avg_range < 0 and avg_range < signal_line
//NON-DIRECTIONAL
above_bline = bg_bline and not avg_range_style and avg_range > high_baseline
below_bline = bg_bline and not avg_range_style and avg_range < high_baseline
above_signal = bg_signal and not avg_range_style and avg_range > signal_line
below_signal = bg_signal and not avg_range_style and avg_range < signal_line
//ABOVE BASELINE
AboveBaselineStrongSignal = if (signal_rising and above_bline)
color.new(#00bcd4, 50)
else if (signal_rising and below_bline or signal_falling and below_bline)
color.new(#e91e63, 100)
else if (signal_rising and dir_above_bline)
color.new(#00bcd4, 50)
else if (signal_falling and dir_below_bline)
color.new(#e91e63, 50)
AboveBaseline = if (not signal_rise_fall and above_bline)
color.new(#00bcd4, 50)
else if (not signal_rise_fall and below_bline)
color.new(#e91e63, 100)
else if (not signal_rise_fall and dir_above_bline)
color.new(#00bcd4, 50)
else if (not signal_rise_fall and dir_below_bline)
color.new(#e91e63, 50)
//ABOVE SIGNAL LINE
AboveSignalLineStrongSignal = if (signal_rising and above_signal)
color.new(#00bcd4, 50)
else if (signal_rising and below_signal or signal_falling and below_signal)
color.new(#e91e63, 100)
else if (signal_rising and dir_above_signal)
color.new(#00bcd4, 50)
else if (signal_falling and dir_below_signal)
color.new(#e91e63, 50)
AboveSignalLine = if (not signal_rise_fall and above_signal)
color.new(#00bcd4, 50)
else if (not signal_rise_fall and below_signal)
color.new(#e91e63, 100)
else if (not signal_rise_fall and dir_above_signal)
color.new(#00bcd4, 50)
else if (not signal_rise_fall and dir_below_signal)
color.new(#e91e63, 50)
bgcolor(AboveBaselineStrongSignal, title='Background | ACBR > Baseline & Signal Rising')
bgcolor(AboveBaseline, title='Background | ACBR > Baseline')
bgcolor(AboveSignalLineStrongSignal, title='Background | ACBR > Signal Line & Signal Rising')
bgcolor(AboveSignalLine, title='Background | ACBR > Signal Line')
/////////////////////////////////////////////////////////////////////////////////////
////BAR COLOR CONDITIONS AND COLORING (ACBR CROSSING ABOVE OR BELOW BASELINE/SIGNAL LINE)
//DIRECTIONAL
dir_barcolor_strong_bline_up = strong_bline and avg_range_style and high_baseline > 0 and ta.crossover(avg_range, high_baseline) or strong_bline and avg_range_style and low_baseline > 0 and ta.crossover(avg_range, low_baseline)
dir_barcolor_strong_bline_down = strong_bline and avg_range_style and high_baseline < 0 and ta.crossunder(avg_range, high_baseline) or strong_bline and avg_range_style and low_baseline < 0 and ta.crossunder(avg_range, low_baseline)
dir_barcolor_weak_bline_up = weak_bline and avg_range_style and high_baseline > 0 and ta.crossunder(avg_range, high_baseline) or weak_bline and avg_range_style and low_baseline > 0 and ta.crossunder(avg_range, low_baseline)
dir_barcolor_weak_bline_down = weak_bline and avg_range_style and high_baseline < 0 and ta.crossover(avg_range, high_baseline) or weak_bline and avg_range_style and low_baseline < 0 and ta.crossover(avg_range, low_baseline)
dir_barcolor_strong_signal_up = strong_signal and avg_range_style and avg_range > 0 and ta.crossover(avg_range, signal_line)
dir_barcolor_strong_signal_down = strong_signal and avg_range_style and avg_range < 0 and ta.crossunder(avg_range, signal_line)
dir_barcolor_weak_signal = weak_signal and avg_range_style and avg_range > 0 and ta.crossunder(avg_range, signal_line) or weak_signal and avg_range_style and avg_range < 0 and ta.crossover(avg_range, signal_line)
//NON-DIRECTIONAL
barcolor_strong_bline = not avg_range_style and strong_bline and ta.crossover(avg_range, high_baseline)
barcolor_weak_bline = not avg_range_style and weak_bline and ta.crossunder(avg_range, high_baseline)
barcolor_strong_signal = not avg_range_style and strong_signal and ta.crossover(avg_range, signal_line)
barcolor_weak_signal = not avg_range_style and weak_signal and ta.crossunder(avg_range, signal_line)
BarColorBaselineCrossStrongSignal = if (signal_rising and barcolor_strong_bline)
#ffeb3b
else if (barcolor_weak_bline)
#673ab7
else if (signal_rising and dir_barcolor_strong_bline_up or signal_falling and dir_barcolor_strong_bline_down)
#ffeb3b
else if (dir_barcolor_weak_bline_up or dir_barcolor_weak_bline_down)
#673ab7
BarColorBaselineCross = if (not signal_rise_fall and barcolor_strong_bline)
#ffeb3b
else if (not signal_rise_fall and barcolor_weak_bline)
#673ab7
else if (not signal_rise_fall and dir_barcolor_strong_bline_up or not signal_rise_fall and dir_barcolor_strong_bline_down)
#ffeb3b
else if (dir_barcolor_weak_bline_up or dir_barcolor_weak_bline_down)
#673ab7
BarColorSignalLineCrossStrongSignal = if (signal_rising and barcolor_strong_signal)
#ffeb3b
else if (barcolor_weak_signal)
#673ab7
else if (signal_rising and dir_barcolor_strong_signal_up)
#ffeb3b
else if (signal_falling and dir_barcolor_strong_signal_down)
#ffeb3b
else if (dir_barcolor_weak_signal)
#673ab7
BarColorSignalLineCross = if (not signal_rise_fall and barcolor_strong_signal)
#ffeb3b
else if (not signal_rise_fall and barcolor_weak_signal)
#673ab7
else if (not signal_rise_fall and dir_barcolor_strong_signal_up)
#ffeb3b
else if (not signal_rise_fall and dir_barcolor_strong_signal_down)
#ffeb3b
else if (dir_barcolor_weak_signal)
#673ab7
barcolor(BarColorBaselineCrossStrongSignal, title='Bar Color | ACBR Baseline Cross & Signal Rising')
barcolor(BarColorBaselineCross, title='Bar Color | ACBR Baseline Cross ')
barcolor(BarColorSignalLineCrossStrongSignal, title='Bar Color | ACBR Signal Line Cross & Signal Rising')
barcolor(BarColorSignalLineCross, title='Bar Color | ACBR Signal Line Cross')
/////////////////////////////////////////////////////////////////////////////////////
////BAR COLOR CONDITIONS AND COLORING (ACBR ABOVE OR BELOW BASELINE/SIGNAL LINE)
//DIRECTIONAL
dir_barcolor_above_bline = barcolor_bline and avg_range_style and high_baseline > 0 and avg_range > high_baseline or barcolor_bline and low_baseline > 0 and avg_range > low_baseline
dir_barcolor_below_bline = barcolor_bline and avg_range_style and low_baseline < 0 and avg_range < low_baseline or barcolor_bline and high_baseline < 0 and avg_range < high_baseline
dir_barcolor_neutral_bline = barcolor_bline and avg_range_style and avg_range < high_baseline and avg_range > low_baseline or barcolor_bline and avg_range_style and avg_range > high_baseline and avg_range < low_baseline or barcolor_bline and avg_range_style and signal_falling and avg_range > high_baseline or barcolor_bline and avg_range_style and signal_rising and avg_range < low_baseline
dir_barcolor_above_signal = barcolor_signal and avg_range_style and avg_range > 0 and avg_range > signal_line
dir_barcolor_below_signal = barcolor_signal and avg_range_style and avg_range < 0 and avg_range < signal_line
dir_barcolor_neutral_signal = barcolor_signal and avg_range_style and avg_range > 0 and avg_range < signal_line or barcolor_signal and avg_range_style and avg_range < 0 and avg_range > signal_line or barcolor_signal and avg_range_style and avg_range > 0 and avg_range > signal_line and signal_falling or barcolor_signal and avg_range_style and avg_range < 0 and avg_range < signal_line and signal_rising
//NON-DIRECTIONAL
barcolor_above_bline = barcolor_bline and not avg_range_style and avg_range > high_baseline
barcolor_below_bline = barcolor_bline and not avg_range_style and avg_range < high_baseline
barcolor_above_signal = barcolor_signal and not avg_range_style and avg_range > signal_line
barcolor_below_signal = barcolor_signal and not avg_range_style and avg_range < signal_line
//ABOVE BASELINE
BarColorAboveBaselineStrongSignal = if (signal_rising and barcolor_above_bline)
color.new(#00bcd4, 0)
else if (signal_rising and barcolor_below_bline or signal_falling and barcolor_above_bline or signal_falling and barcolor_below_bline)
color.new(#e91e63, 0)
else if (signal_rising and dir_barcolor_above_bline)
color.new(#00bcd4, 0)
else if (signal_falling and dir_barcolor_below_bline)
color.new(#e91e63, 0)
else if (dir_barcolor_neutral_bline)
color.new(color.gray, 0)
BarColorAboveBaseline = if (not signal_rise_fall and barcolor_above_bline)
color.new(#00bcd4, 0)
else if (not signal_rise_fall and barcolor_below_bline)
color.new(#e91e63, 0)
else if (not signal_rise_fall and dir_barcolor_above_bline)
color.new(#00bcd4, 0)
else if (not signal_rise_fall and dir_barcolor_below_bline)
color.new(#e91e63, 0)
else if (dir_barcolor_neutral_bline)
color.new(color.gray, 0)
//ABOVE SIGNAL LINE
BarColorAboveSignalLineStrongSignal = if (signal_rising and barcolor_above_signal)
color.new(#00bcd4, 0)
else if (signal_rising and barcolor_below_signal or signal_falling and barcolor_above_signal or signal_falling and barcolor_below_signal)
color.new(#e91e63, 0)
else if (signal_rising and dir_barcolor_above_signal)
color.new(#00bcd4, 0)
else if (signal_falling and dir_barcolor_below_signal)
color.new(#e91e63, 0)
else if (dir_barcolor_neutral_signal)
color.new(color.gray, 0)
BarColorAboveSignalLine = if (not signal_rise_fall and barcolor_above_signal)
color.new(#00bcd4, 0)
else if (not signal_rise_fall and barcolor_below_signal)
color.new(#e91e63, 0)
else if (not signal_rise_fall and dir_barcolor_above_signal)
color.new(#00bcd4, 0)
else if (not signal_rise_fall and dir_barcolor_below_signal)
color.new(#e91e63, 0)
else if (dir_barcolor_neutral_signal)
color.new(color.gray, 0)
barcolor(BarColorAboveBaselineStrongSignal, title='Bar Color | ACBR > Baseline & Signal Rising')
barcolor(BarColorAboveBaseline, title='Bar Color | ACBR > Baseline')
barcolor(BarColorAboveSignalLineStrongSignal, title='Bar Color | ACBR > Signal Line & Signal Rising')
barcolor(BarColorAboveSignalLine, title='Bar Color | ACBR > Signal Line')
/////////////////////////////////////////////////////////////////////////////////////
///CONTINUATION TRADE SYMBOLS
bull_cont_trade = avg_range_style and avg_range > 0 and avg_range[1] < signal_line and ta.crossover(avg_range, signal_line)
bear_cont_trade = avg_range_style and avg_range < 0 and avg_range[1] > signal_line and ta.crossunder(avg_range, signal_line)
plotshape(bull_cont_trade, title='Bullish Continuation', style=shape.arrowup, location=location.bottom, color=color.blue)
plotshape(bear_cont_trade, title='Bearish Continuation', style=shape.arrowdown, location=location.top, color=color.red)
////EXIT TRADE SYMBOLS
exit_long_quickly = signal_line > 0 and signal_line < signal_line[1] and signal_line[1] > signal_line[2]
exit_long_slowly = signal_line > 0 and ta.crossunder(avg_range, signal_line)
exit_short_quickly = signal_line < 0 and signal_line > signal_line[1] and signal_line[1] < signal_line[2]
exit_short_slowly = signal_line < 0 and ta.crossover(avg_range, signal_line)
plotshape(exit_short_quickly, title='Quick Exit Short', style=shape.xcross, location=location.bottom, color=color.blue)
plotshape(exit_short_slowly, title='Slow Exit Short', style=shape.xcross, location=location.bottom, color=color.blue)
plotshape(exit_long_quickly, title='Quick Exit Long', style=shape.xcross, location=location.top, color=color.red)
plotshape(exit_long_slowly, title='Slow Exit Long', style=shape.xcross, location=location.top, color=color.red)
hline(0, title='Zero Line', color=color.silver, linestyle=hline.style_dotted)
/////////////////////////////////////////////////////////////////////////////////////
////ALERT CONDITIONS
alertcondition(bull_cont_trade, title='Continuation Trade - Bullish', message='Bullish continuation trade by ACBR.')
alertcondition(bear_cont_trade, title='Continuation Trade - Bearish', message='Bearish continuation trade by ACBR.')
alertcondition(exit_long_quickly, title='Exit Long Quickly', message='Exit long trade, by ACBR.')
alertcondition(exit_long_slowly, title='Exit Long Slowly', message='Exit long trade, by ACBR.')
alertcondition(exit_short_quickly, title='Exit Short Quickly', message='Exit short trade, by ACBR.')
alertcondition(exit_short_slowly, title='Exit Short Slowly', message='Exit short trade, by ACBR.')
alertcondition(high_baseline > 0 and ta.crossover(avg_range, high_baseline) or low_baseline > 0 and ta.crossover(avg_range, low_baseline), title='ACBR Crossing Above Upper Baseline', message='ACBR has crossed above the upper baseline.')
alertcondition(high_baseline < 0 and ta.crossunder(avg_range, high_baseline) or low_baseline < 0 and ta.crossunder(avg_range, low_baseline), title='ACBR Crossing Below Lower Baseline', message='ACBR has crossed below the lower baseline.')
alertcondition(avg_range > 0 and ta.crossover(avg_range, signal_line), title='ACBR Crossing Above Signal Line Trade Entry', message='ACBR has crossed above the signal line. Possible trade entry.')
alertcondition(avg_range < 0 and ta.crossunder(avg_range, signal_line), title='ACBR Crossing Below Signal Line Trade Entry', message='ACBR has crossed below the signal line. Possible trade entry.')
|
Implied and Historical Volatility v4 | https://www.tradingview.com/script/Zj1dAiEK-Implied-and-Historical-Volatility-v4/ | Aziz_PactionTrader | https://www.tradingview.com/u/Aziz_PactionTrader/ | 47 | 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/
// © Aziz_PactionTrader
//@version=4
study("Implied and Historical Volatility v4", overlay=false)
// Define pi
pi = 3.14159265359
// Input variables
strike_price = input(title="Strike Price", type=input.float, defval=100)
time_to_expiry = input(title="Time to Expiry (days)", type=input.integer, defval=30)
historical_volatility_length = input(title="Historical Volatility Length (days)", type=input.integer, defval=30)
// Get current market price of the stock
stock_price = security(syminfo.tickerid, timeframe.period, close)
// Get price and yield of Indian 10-year government bond
bond_price = security("IN10", timeframe.period, close)
bond_face_value = 100
bond_coupon_rate = 10.18
bond_years_to_maturity = 10
bond_interest_rate = (bond_coupon_rate * bond_face_value / bond_price) + ((bond_face_value - bond_price) / bond_years_to_maturity / bond_price) * 100
// Standard normal distribution function
std_norm_dist(x) =>
exp(-0.5 * pow(x, 2)) / sqrt(2 * pi)
// Implied volatility calculation using bisection method and Black 76 model
option_price = input(title="Option Price", type=input.float, defval=5)
tolerance = 0.0001
max_iterations = 100
a = 0.01
b = 5.00
c = (a + b) / 2
//i = 0
for i = 0 to max_iterations
d1 = (log(stock_price/strike_price) + (bond_interest_rate/100 - pow(c, 2)/2)*time_to_expiry/365) / (c * sqrt(time_to_expiry/365))
d2 = d1 - c * sqrt(time_to_expiry/365)
n_d1 = std_norm_dist(d1)
n_d2 = std_norm_dist(d2)
call_price = stock_price * n_d1 - strike_price * exp(-bond_interest_rate/100 * time_to_expiry/365) * n_d2
put_price = strike_price * exp(-bond_interest_rate/100 * time_to_expiry/365) * (1 - n_d2) - stock_price * (1 - n_d1)
if (abs(put_price - option_price) < tolerance)
break
if (put_price < option_price)
a := c
else
b := c
c := (a + b) / 2
implied_volatility = c
// Plot change in implied volatility
implied_change = change(implied_volatility)
plot(implied_change, title="Change in Implied Volatility", color=color.orange, linewidth=2, style=plot.style_line)
plotchar(implied_volatility, title="implied_volatility", char="", color=color.orange, location=location.top)
// Calculate daily returns of the stock
daily_returns = log(close / close[1])
// Calculate historical volatility
historical_volatility = stdev(daily_returns, historical_volatility_length) * sqrt(252)
// Plot change in historical volatility
historical_change = change(historical_volatility)
plot(historical_change, title="Change in Historical Volatility", color=color.blue, linewidth=2, style=plot.style_line)
plotchar(historical_volatility, title="istorical_volatilitylity", char="", color=color.blue, location=location.top)
|
Fundamentals Graphing [Kioseff Trading] | https://www.tradingview.com/script/7qjXp2op-Fundamentals-Graphing-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 790 | 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/
// © KioseffTrading
//@version=5
indicator("Fundamentals Graphing [Kioseff Trading]", overlay = false, max_lines_count = 500, max_labels_count = 500)
import kaigouthro/hsvColor/15 as kai
// THANK YOU TV + PineCoders (:
string FQ = "Financial Quarter"
string FY = "Financial Year"
// Financial legends.
string F_NA = "⸺"
string F000 = "█ INCOME STATEMENTS █"
string F001 = "After tax other income/expense"
string F002 = "Average basic shares outstanding"
string F003 = "Other COGS"
string F004 = "Cost of goods"
string F005 = "Deprecation and amortization"
string F006 = "Diluted net income available to common stockholders"
string F007 = "Diluted shares outstanding"
string F008 = "Dilution adjustment"
string F009 = "Discontinued operations"
string F010 = "Basic EPS"
string F011 = "Diluted EPS"
string F012 = "EBIT"
string F013 = "EBITDA"
string F014 = "Equity in earnings"
string F015 = "Gross profit"
string F016 = "Taxes"
string F017 = "Interest capitalized"
string F018 = "Interest expense on debt"
string F019 = "Non-controlling/minority interest"
string F020 = "Net income before discontinued operations"
string F021 = "Net income"
string F022 = "Non-operating income, excl. interest expenses"
string F023 = "Interest expense, net of interest capitalized"
string F024 = "Non-operating interest income"
string F025 = "Operating income"
string F026 = "Operating expenses (excl. COGS)"
string F027 = "Miscellaneous non-operating expense"
string F028 = "Other operating expenses, total"
string F029 = "Preferred dividends"
string F030 = "Pretax equity in earnings"
string F031 = "Pretax income"
string F032 = "Research & development"
string F033 = "Selling/general/admin expenses, other"
string F034 = "Selling/general/admin expenses, total"
string F035 = "Non-operating income, total"
string F036 = "Total operating expenses"
string F037 = "Total revenue"
string F038 = "Unusual income/expense"
string F100 = "█ BALANCE SHEET █"
string F101 = "Accounts payable"
string F102 = "Accounts receivable - trade, net"
string F103 = "Accrued payroll"
string F104 = "Accumulated depreciation, total"
string F105 = "Additional paid-in capital/Capital surplus"
string F106 = "Tangible book value per share"
string F107 = "Book value per share"
string F108 = "Capitalized lease obligations"
string F109 = "Capital and operating lease obligations"
string F110 = "Cash & equivalents"
string F111 = "Cash and short term investments"
string F112 = "Common equity, total"
string F113 = "Common stock par/Carrying value"
string F114 = "Current portion of LT debt and capital leases"
string F115 = "Deferred income, current"
string F116 = "Deferred income, non-current"
string F117 = "Deferred tax assets"
string F118 = "Deferred tax liabilities"
string F119 = "Dividends payable"
string F120 = "Goodwill, net"
string F121 = "Income tax payable"
string F122 = "Net intangible assets"
string F123 = "Inventories - finished goods"
string F124 = "Inventories - progress payments & other"
string F125 = "Inventories - raw materials"
string F126 = "Inventories - work in progress"
string F127 = "Investments in unconsolidated subsidiaries"
string F128 = "Long term debt excl. lease liabilities"
string F129 = "Long term debt"
string F130 = "Long term investments"
string F131 = "Note receivable - long term"
string F132 = "Other long term assets, total"
string F133 = "Minority interest"
string F134 = "Notes payable"
string F135 = "Operating lease liabilities"
string F136 = "Other common equity"
string F137 = "Other current assets, total"
string F138 = "Other current liabilities"
string F139 = "Other intangibles, net"
string F140 = "Other investments"
string F141 = "Other liabilities, total"
string F142 = "Other receivables"
string F143 = "Other short term debt"
string F144 = "Paid in capital"
string F145 = "Gross property/plant/equipment"
string F146 = "Net property/plant/equipment"
string F147 = "Preferred stock, carrying value"
string F148 = "Prepaid expenses"
string F149 = "Provision for risks & charge"
string F150 = "Retained earnings"
string F151 = "Short term debt excl. current portion of LT debt"
string F152 = "Short term debt"
string F153 = "Short term investments"
string F154 = "Shareholders' equity"
string F155 = "Total assets"
string F156 = "Total current assets"
string F157 = "Total current liabilities"
string F158 = "Total debt"
string F159 = "Total equity"
string F160 = "Total inventory"
string F161 = "Total liabilities"
string F162 = "Total liabilities & shareholders' equities"
string F163 = "Total non-current assets"
string F164 = "Total non-current liabilities"
string F165 = "Total receivables, net"
string F166 = "Treasury stock - common"
string F200 = "█ CASHFLOW █"
string F201 = "Amortization"
string F202 = "Capital expenditures - fixed assets"
string F203 = "Capital expenditures"
string F204 = "Capital expenditures - other assets"
string F205 = "Cash from financing activities"
string F206 = "Cash from investing activities"
string F207 = "Cash from operating activities"
string F208 = "Deferred taxes (cash flow)"
string F209 = "Depreciation & amortization (cash flow)"
string F210 = "Change in accounts payable"
string F211 = "Change in accounts receivable"
string F212 = "Change in accrued expenses"
string F213 = "Change in inventories"
string F214 = "Change in other assets/liabilities"
string F215 = "Change in taxes payable"
string F216 = "Changes in working capital"
string F217 = "Common dividends paid"
string F218 = "Depreciation/depletion"
string F219 = "Free cash flow"
string F220 = "Funds from operations"
string F221 = "Issuance/retirement of debt, net"
string F222 = "Issuance/retirement of long term debt"
string F223 = "Issuance/retirement of other debt"
string F224 = "Issuance/retirement of short term debt"
string F225 = "Issuance/retirement of stock, net"
string F226 = "Net income (cash flow)"
string F227 = "Non-cash items"
string F228 = "Other financing cash flow items, total"
string F229 = "Financing activities - other sources"
string F230 = "Financing activities - other uses"
string F231 = "Other investing cash flow items, total"
string F232 = "Investing activities - other sources"
string F233 = "Investing activities - other uses"
string F234 = "Preferred dividends paid"
string F235 = "Purchase/acquisition of business"
string F236 = "Purchase of investments"
string F237 = "Repurchase of common & preferred stock"
string F238 = "Purchase/sale of business, net"
string F239 = "Purchase/sale of investments, net"
string F240 = "Reduction of long term debt"
string F241 = "Sale of common & preferred stock"
string F242 = "Sale of fixed assets & businesses"
string F243 = "Sale/maturity of investments"
string F244 = "Issuance of long term debt"
string F245 = "Total cash dividends paid"
string F300 = "█ STATISTICS █"
string F301 = "Accruals"
string F302 = "Altman Z-score"
string F303 = "Asset turnover"
string F304 = "Beneish M-score"
string F305 = "Buyback yield %"
string F306 = "Cash conversion cycle"
string F307 = "Cash to debt ratio"
string F308 = "COGS to revenue ratio"
string F309 = "Current ratio"
string F310 = "Days sales outstanding"
string F311 = "Days inventory"
string F312 = "Days payable"
string F313 = "Debt to assets ratio"
string F314 = "Debt to EBITDA ratio"
string F315 = "Debt to equity ratio"
string F316 = "Debt to revenue ratio"
string F317 = "Dividend payout ratio %"
string F318 = "Dividend yield %"
string F319 = "Dividends per share - common stock primary issue"
string F320 = "EPS estimates"
string F321 = "EPS basic one year growth"
string F322 = "EPS diluted one year growth"
string F323 = "EBITDA margin %"
string F324 = "Effective interest rate on debt %"
string F325 = "Enterprise value to EBITDA ratio"
string F326 = "Enterprise value"
string F327 = "Equity to assets ratio"
string F328 = "Enterprise value to EBIT ratio"
string F329 = "Enterprise value to revenue ratio"
string F330 = "Float shares outstanding"
string F331 = "Free cash flow margin %"
string F332 = "Fulmer H factor"
string F333 = "Goodwill to assets ratio"
string F334 = "Graham's number"
string F335 = "Gross margin %"
string F336 = "Gross profit to assets ratio"
string F337 = "Interest coverage"
string F338 = "Inventory to revenue ratio"
string F339 = "Inventory turnover"
string F340 = "KZ index"
string F341 = "Long term debt to total assets ratio"
string F342 = "Net current asset value per share"
string F343 = "Net income per employee"
string F344 = "Net margin %"
string F345 = "Number of employees"
string F346 = "Operating earnings yield %"
string F347 = "Operating margin %"
string F348 = "PEG ratio"
string F349 = "Piotroski F-score"
string F350 = "Price earnings ratio forward"
string F351 = "Price sales ratio forward"
string F352 = "Price to free cash flow ratio"
string F353 = "Price to tangible book ratio"
string F354 = "Quality ratio"
string F355 = "Quick ratio"
string F356 = "Research & development to revenue ratio"
string F357 = "Return on assets %"
string F358 = "Return on equity adjusted to book value %"
string F359 = "Return on equity %"
string F360 = "Return on invested capital %"
string F361 = "Return on tangible assets %"
string F362 = "Return on tangible equity %"
string F363 = "Revenue one year growth"
string F364 = "Revenue per employee"
string F365 = "Revenue estimates"
string F366 = "Shares buyback ratio %"
string F367 = "Sloan ratio %"
string F368 = "Springate score"
string F369 = "Sustainable growth rate"
string F370 = "Tangible common equity ratio"
string F371 = "Tobin's Q (approximate)"
string F372 = "Total common shares outstanding"
string F373 = "Zmijewski score"
string typeInput1 = input.string(F010 , "Data ", inline = "100", group = "Initial Settings",
options = [F_NA,
F000, F001, F002, F003, F004, F005, F006, F007, F008, F009, F010, F011, F012, F013, F014, F015, F016, F017, F018, F019, F020, F021, F022, F023, F024, F025, F026, F027, F028, F029, F030, F031, F032, F033, F034, F035, F036, F037, F038,
F100, F101, F102, F103, F104, F105, F106, F107, F108, F109, F110, F111, F112, F113, F114, F115, F116, F117, F118, F119, F120, F121, F122, F123, F124, F125, F126, F127, F128, F129, F130, F131, F132, F133, F134, F135, F136, F137, F138, F139, F140, F141, F142, F143, F144, F145, F146, F147, F148, F149, F150, F151, F152, F153, F154, F155, F156, F157, F158, F159, F160, F161, F162, F163, F164, F165, F166,
F200, F201, F202, F203, F204, F205, F206, F207, F208, F209, F210, F211, F212, F213, F214, F215, F216, F217, F218, F219, F220, F221, F222, F223, F224, F225, F226, F227, F228, F229, F230, F231, F232, F233, F234, F235, F236, F237, F238, F239, F240, F241, F242, F243, F244, F245,
F300, F301, F302, F303, F304, F305, F306, F307, F308, F309, F310, F311, F312, F313, F314, F315, F316, F317, F318, F319, F320, F321, F322, F323, F324, F325, F326, F327, F328, F329, F330, F331, F332, F333, F334, F335, F336, F337, F338, F339, F340, F341, F342, F343, F344, F345, F346, F347, F348, F349, F350, F351, F352, F353, F354, F355, F356, F357, F358, F359, F360, F361, F362, F363, F364, F365, F366, F367, F368, F369, F370, F371, F372, F373])
px = input.string(defval = "Technology Services", title = "Preset", group = "Initial Settings",
options = ["Technology Services", "Electronic Technology", "Financial Services", "Health Technology", "Consumer Non-Durables", "Energy Minerals", "Consumer Durables", "Commercial Services", "Retail Trade", "Transportation", "Utilities", "Custom"], inline = "100")
period = input.string(defval = "Fiscal Quarter", title = "Period ", options = ["Fiscal Quarter", "Fiscal Year"], inline = "70", group = "Initial Settings")
intervalsback = input.int (defval = 0, minval = 0, title = "Intervals Back ", inline = "70", group = "Initial Settings")
reverse = input.bool (defval = false, title = "Reverse Colors" , inline = "33", group = "Initial Settings")
revScale = input.bool (defval = false, title = "Reverse Scale" , inline = "33", group = "Initial Settings")
columns = input.string(defval = "Scatter + Columns", title = "Plot Type", group = "Plot Type",
options= ["Scatter", "Columns", "Scatter + Columns", "Bar", "Pie Chart","Drop Down"])
sort = input.string(defval = "None", title = "Sort Data ", options = ["None", "Descending", "Ascending"], group = "Scatter / Columns / Bars")
boxnobg = input.bool (defval = false, title = "Move Data to Box", group = "Scatter / Columns / Bars" )
searchF = input.bool (defval = false, title = "Use Search Function", inline = "40", group = "Search Function" )
search = input.string(defval = "", title = "Search Function" , inline = "40", group = "Search Function" )
upcolor = input.color (defval = color.lime, title = "Up Color " , inline = "90", group = "Colors" )
downcolor = input.color (defval = color.red, title = "Down Color" , inline = "90", group = "Colors" )
midCol = input.color (defval = color.white, title = "Median Color", inline = "90", group = "Colors" )
usebg = input.bool (defval = true, title = "Use Background Color", inline = "91", group = "Colors" )
cbg = input.color (defval = #000000, title = "Background Color" , inline = "91", group = "Colors" )
var timeArray = array.new_int()
getId(simple string userFinancialChoice) =>
string result = switch userFinancialChoice
F001 => "AFTER_TAX_OTHER_INCOME"
F002 => "BASIC_SHARES_OUTSTANDING"
F003 => "COST_OF_GOODS_EXCL_DEP_AMORT"
F004 => "COST_OF_GOODS"
F005 => "DEP_AMORT_EXP_INCOME_S"
F006 => "DILUTED_NET_INCOME"
F007 => "DILUTED_SHARES_OUTSTANDING"
F008 => "DILUTION_ADJUSTMENT"
F009 => "DISCONTINUED_OPERATIONS"
F010 => "EARNINGS_PER_SHARE_BASIC"
F011 => "EARNINGS_PER_SHARE_DILUTED"
F012 => "EBIT"
F013 => "EBITDA"
F014 => "EQUITY_IN_EARNINGS"
F015 => "GROSS_PROFIT"
F016 => "INCOME_TAX"
F017 => "INTEREST_CAPITALIZED"
F018 => "INTEREST_EXPENSE_ON_DEBT"
F019 => "MINORITY_INTEREST_EXP"
F020 => "NET_INCOME_BEF_DISC_OPER"
F021 => "NET_INCOME"
F022 => "NON_OPER_INCOME"
F023 => "NON_OPER_INTEREST_EXP"
F024 => "NON_OPER_INTEREST_INCOME"
F025 => "OPER_INCOME"
F026 => "OPERATING_EXPENSES"
F027 => "OTHER_INCOME"
F028 => "OTHER_OPER_EXPENSE_TOTAL"
F029 => "PREFERRED_DIVIDENDS"
F030 => "PRETAX_EQUITY_IN_EARNINGS"
F031 => "PRETAX_INCOME"
F032 => "RESEARCH_AND_DEV"
F033 => "SELL_GEN_ADMIN_EXP_OTHER"
F034 => "SELL_GEN_ADMIN_EXP_TOTAL"
F035 => "TOTAL_NON_OPER_INCOME"
F036 => "TOTAL_OPER_EXPENSE"
F037 => "TOTAL_REVENUE"
F038 => "UNUSUAL_EXPENSE_INC"
F101 => "ACCOUNTS_PAYABLE"
F102 => "ACCOUNTS_RECEIVABLES_NET"
F103 => "ACCRUED_PAYROLL"
F104 => "ACCUM_DEPREC_TOTAL"
F105 => "ADDITIONAL_PAID_IN_CAPITAL"
F106 => "BOOK_TANGIBLE_PER_SHARE"
F107 => "BOOK_VALUE_PER_SHARE"
F108 => "CAPITAL_LEASE_OBLIGATIONS"
F109 => "CAPITAL_OPERATING_LEASE_OBLIGATIONS"
F110 => "CASH_N_EQUIVALENTS"
F111 => "CASH_N_SHORT_TERM_INVEST"
F112 => "COMMON_EQUITY_TOTAL"
F113 => "COMMON_STOCK_PAR"
F114 => "CURRENT_PORT_DEBT_CAPITAL_LEASES"
F115 => "DEFERRED_INCOME_CURRENT"
F116 => "DEFERRED_INCOME_NON_CURRENT"
F117 => "DEFERRED_TAX_ASSESTS"
F118 => "DEFERRED_TAX_LIABILITIES"
F119 => "DIVIDENDS_PAYABLE"
F120 => "GOODWILL"
F121 => "INCOME_TAX_PAYABLE"
F122 => "INTANGIBLES_NET"
F123 => "INVENTORY_FINISHED_GOODS"
F124 => "INVENTORY_PROGRESS_PAYMENTS"
F125 => "INVENTORY_RAW_MATERIALS"
F126 => "INVENTORY_WORK_IN_PROGRESS"
F127 => "INVESTMENTS_IN_UNCONCSOLIDATE"
F128 => "LONG_TERM_DEBT_EXCL_CAPITAL_LEASE"
F129 => "LONG_TERM_DEBT"
F130 => "LONG_TERM_INVESTMENTS"
F131 => "LONG_TERM_NOTE_RECEIVABLE"
F132 => "LONG_TERM_OTHER_ASSETS_TOTAL"
F133 => "MINORITY_INTEREST"
F134 => "NOTES_PAYABLE_SHORT_TERM_DEBT"
F135 => "OPERATING_LEASE_LIABILITIES"
F136 => "OTHER_COMMON_EQUITY"
F137 => "OTHER_CURRENT_ASSETS_TOTAL"
F138 => "OTHER_CURRENT_LIABILITIES"
F139 => "OTHER_INTANGIBLES_NET"
F140 => "OTHER_INVESTMENTS"
F141 => "OTHER_LIABILITIES_TOTAL"
F142 => "OTHER_RECEIVABLES"
F143 => "OTHER_SHORT_TERM_DEBT"
F144 => "PAID_IN_CAPITAL"
F145 => "PPE_TOTAL_GROSS"
F146 => "PPE_TOTAL_NET"
F147 => "PREFERRED_STOCK_CARRYING_VALUE"
F148 => "PREPAID_EXPENSES"
F149 => "PROVISION_F_RISKS"
F150 => "RETAINED_EARNINGS"
F151 => "SHORT_TERM_DEBT_EXCL_CURRENT_PORT"
F152 => "SHORT_TERM_DEBT"
F153 => "SHORT_TERM_INVEST"
F154 => "SHRHLDRS_EQUITY"
F155 => "TOTAL_ASSETS"
F156 => "TOTAL_CURRENT_ASSETS"
F157 => "TOTAL_CURRENT_LIABILITIES"
F158 => "TOTAL_DEBT"
F159 => "TOTAL_EQUITY"
F160 => "TOTAL_INVENTORY"
F161 => "TOTAL_LIABILITIES"
F162 => "TOTAL_LIABILITIES_SHRHLDRS_EQUITY"
F163 => "TOTAL_NON_CURRENT_ASSETS"
F164 => "TOTAL_NON_CURRENT_LIABILITIES"
F165 => "TOTAL_RECEIVABLES_NET"
F166 => "TREASURY_STOCK_COMMON"
F201 => "AMORTIZATION"
F202 => "CAPITAL_EXPENDITURES_FIXED_ASSETS"
F203 => "CAPITAL_EXPENDITURES"
F204 => "CAPITAL_EXPENDITURES_OTHER_ASSETS"
F205 => "CASH_F_FINANCING_ACTIVITIES"
F206 => "CASH_F_INVESTING_ACTIVITIES"
F207 => "CASH_F_OPERATING_ACTIVITIES"
F208 => "CASH_FLOW_DEFERRED_TAXES"
F209 => "CASH_FLOW_DEPRECATION_N_AMORTIZATION"
F210 => "CHANGE_IN_ACCOUNTS_PAYABLE"
F211 => "CHANGE_IN_ACCOUNTS_RECEIVABLE"
F212 => "CHANGE_IN_ACCRUED_EXPENSES"
F213 => "CHANGE_IN_INVENTORIES"
F214 => "CHANGE_IN_OTHER_ASSETS"
F215 => "CHANGE_IN_TAXES_PAYABLE"
F216 => "CHANGES_IN_WORKING_CAPITAL"
F217 => "COMMON_DIVIDENDS_CASH_FLOW"
F218 => "DEPRECIATION_DEPLETION"
F219 => "FREE_CASH_FLOW"
F220 => "FUNDS_F_OPERATIONS"
F221 => "ISSUANCE_OF_DEBT_NET"
F222 => "ISSUANCE_OF_LONG_TERM_DEBT"
F223 => "ISSUANCE_OF_OTHER_DEBT"
F224 => "ISSUANCE_OF_SHORT_TERM_DEBT"
F225 => "ISSUANCE_OF_STOCK_NET"
F226 => "NET_INCOME_STARTING_LINE"
F227 => "NON_CASH_ITEMS"
F228 => "OTHER_FINANCING_CASH_FLOW_ITEMS_TOTAL"
F229 => "OTHER_FINANCING_CASH_FLOW_SOURCES"
F230 => "OTHER_FINANCING_CASH_FLOW_USES"
F231 => "OTHER_INVESTING_CASH_FLOW_ITEMS_TOTAL"
F232 => "OTHER_INVESTING_CASH_FLOW_SOURCES"
F233 => "OTHER_INVESTING_CASH_FLOW_USES"
F234 => "PREFERRED_DIVIDENDS_CASH_FLOW"
F235 => "PURCHASE_OF_BUSINESS"
F236 => "PURCHASE_OF_INVESTMENTS"
F237 => "PURCHASE_OF_STOCK"
F238 => "PURCHASE_SALE_BUSINESS"
F239 => "PURCHASE_SALE_INVESTMENTS"
F240 => "REDUCTION_OF_LONG_TERM_DEBT"
F241 => "SALE_OF_STOCK"
F242 => "SALES_OF_BUSINESS"
F243 => "SALES_OF_INVESTMENTS"
F244 => "SUPPLYING_OF_LONG_TERM_DEBT"
F245 => "TOTAL_CASH_DIVIDENDS_PAID"
F301 => "ACCRUALS_RATIO"
F302 => "ALTMAN_Z_SCORE"
F303 => "ASSET_TURNOVER"
F304 => "BENEISH_M_SCORE"
F305 => "BUYBACK_YIELD"
F306 => "CASH_CONVERSION_CYCLE"
F307 => "CASH_TO_DEBT"
F308 => "COGS_TO_REVENUE"
F309 => "CURRENT_RATIO"
F310 => "DAY_SALES_OUT"
F311 => "DAYS_INVENT"
F312 => "DAYS_PAY"
F313 => "DEBT_TO_ASSET"
F314 => "DEBT_TO_EBITDA"
F315 => "DEBT_TO_EQUITY"
F316 => "DEBT_TO_REVENUE"
F317 => "DIVIDEND_PAYOUT_RATIO"
F318 => "DIVIDENDS_YIELD"
F319 => "DPS_COMMON_STOCK_PRIM_ISSUE"
F320 => "EARNINGS_ESTIMATE"
F321 => "EARNINGS_PER_SHARE_BASIC_ONE_YEAR_GROWTH"
F322 => "EARNINGS_PER_SHARE_DILUTED_ONE_YEAR_GROWTH"
F323 => "EBITDA_MARGIN"
F324 => "EFFECTIVE_INTEREST_RATE_ON_DEBT"
F325 => "ENTERPRISE_VALUE_EBITDA"
F326 => "ENTERPRISE_VALUE"
F327 => "EQUITY_TO_ASSET"
F328 => "EV_EBIT"
F329 => "EV_REVENUE"
F330 => "FLOAT_SHARES_OUTSTANDING"
F331 => "FREE_CASH_FLOW_MARGIN"
F332 => "FULMER_H_FACTOR"
F333 => "GOODWILL_TO_ASSET"
F334 => "GRAHAM_NUMBERS"
F335 => "GROSS_MARGIN"
F336 => "GROSS_PROFIT_TO_ASSET"
F337 => "INTERST_COVER"
F338 => "INVENT_TO_REVENUE"
F339 => "INVENT_TURNOVER"
F340 => "KZ_INDEX"
F341 => "LONG_TERM_DEBT_TO_ASSETS"
F342 => "NCAVPS_RATIO"
F343 => "NET_INCOME_PER_EMPLOYEE"
F344 => "NET_MARGIN"
F345 => "NUMBER_OF_EMPLOYEES"
F346 => "OPERATING_EARNINGS_YIELD"
F347 => "OPERATING_MARGIN"
F348 => "PEG_RATIO"
F349 => "PIOTROSKI_F_SCORE"
F350 => "PRICE_EARNINGS_FORWARD"
F351 => "PRICE_SALES_FORWARD"
F352 => "PRICE_TO_FREE_CASH_FLOW"
F353 => "PRICE_TO_TANGIBLE_BOOK"
F354 => "QUALITY_RATIO"
F355 => "QUICK_RATIO"
F356 => "RESEARCH_AND_DEVELOP_TO_REVENUE"
F357 => "RETURN_ON_ASSETS"
F358 => "RETURN_ON_EQUITY_ADJUST_TO_BOOK"
F359 => "RETURN_ON_EQUITY"
F360 => "RETURN_ON_INVESTED_CAPITAL"
F361 => "RETURN_ON_TANG_ASSETS"
F362 => "RETURN_ON_TANG_EQUITY"
F363 => "REVENUE_ONE_YEAR_GROWTH"
F364 => "REVENUE_PER_EMPLOYEE"
F365 => "SALES_ESTIMATES"
F366 => "SHARE_BUYBACK_RATIO"
F367 => "SLOAN_RATIO"
F368 => "SPRINGATE_SCORE"
F369 => "SUSTAINABLE_GROWTH_RATE"
F370 => "TANGIBLE_COMMON_EQUITY_RATIO"
F371 => "TOBIN_Q_RATIO"
F372 => "TOTAL_SHARES_OUTSTANDING"
F373 => "ZMIJEWSKI_SCORE"
=> ""
upcol = switch reverse
false => revScale == false ? upcolor : downcolor
=> revScale == false ? downcolor : upcolor
dncol = switch reverse
false => revScale == false ? downcolor : upcolor
=> revScale == false ? upcolor : downcolor
per = switch period
"Fiscal Quarter" => "FQ"
"Fiscal Year" => "FY"
var float max = 0.0, var float min = 1e8
if time >= chart.left_visible_bar_time
timeArray.unshift(math.round(time))
max := math.max(high, max)
min := math.min(low, min)
calc = (max - min) / 10, st = "Symbols"
tf(string , string1, string2, string3, string4, string5, string6, string7, string8, string9, string10, stringx) =>
prefix = "BATS:"
switch px
"Technology Services" => prefix + string
"Financial Services" => prefix + string1
"Electronic Technology" => prefix + string2
"Health Technology" => prefix + string3
"Consumer Non-Durables" => prefix + string4
"Energy Minerals" => prefix + string5
"Consumer Durables" => prefix + string6
"Commercial Services" => prefix + string7
"Retail Trade" => prefix + string8
"Transportation" => prefix + string9
"Utilities" => prefix + string10
=> stringx
type values
float symbolData
string symbol
string yearCount
box colmn
color symbolColor
line shapeLines
linefill shapeLinesFill
label symbolLabel
float top
float bot
int l
int r
array <float> dataArr
array <string> symbolArr
symbolMat = matrix.new<values>(2, 40)
req( x, simple string symbol ) =>
n = request.financial(symbol, searchF == false ? getId(typeInput1) : getId(search), per, ignore_invalid_symbol = true)
symbolMat.set(0, x, values.new(symbolData = n)), symbolMat.set(1, x, values.new(symbol = symbol))
[n, symbol]
req(0 , tf("MSFT" ,"BRK.B" , "AAPL" , "JNJ" , "CROX" , "XOM" , "TSLA", "PYPL", "AMZN" , "UBER", "NEE" , input.symbol(defval = "MSFT", title = "Symbol 1", inline = "0" , group = st))), [d1 ,s1 ] = req(1 , tf("GOOGL" ,"JPM" , "NVDA" , "LLY" , "BGS" , "HES" , "HAS" , "NSSC", "W" , "INSW" , "TRGP", input.symbol(defval = "AAPL", title = "Symbol 2 ", inline = "0" , group = st)))
req(2 , tf("META" ,"BAC" , "AVGO" , "ABBV" , "PG" , "OXY" , "RIVN", "TRKA", "BBBY" , "AAL" , "RUN" , input.symbol(defval = "NVDA", title = "Symbol 3 ", inline = "2 ", group = st))), [d3 ,s3 ] = req(3 , tf("PAYX" ,"WFC" , "CSCO" , "MRK" , "CELH" , "AMR" , "RACE" , "ASST", "BBY" , "SKYW" , "FE" , input.symbol(defval = "V" , title = "Symbol 4 ", inline = "2 ", group = st)))
req(4 , tf("ADBE" ,"MS" , "TXN" , "DHR" , "ELF" , "CVX" , "LCID", "V" , "GME" , "LYFT", "D" , input.symbol(defval = "MA" , title = "Symbol 5 ", inline = "4 ", group = st))), [d5 ,s5 ] = req(5 , tf("INTU" ,"SCHW" , "RTX" , "ABT" , "KO" , "TELL" , "IDEX" , "MCO" , "CHWY" , "CSX" , "PEG" , input.symbol(defval = "META", title = "Symbol 6 ", inline = "4 ", group = st)))
req(6 , tf("NFLX" ,"AXP" , "QCOM" , "BMY" , "PEP" , "DVN" , "F" , "MA" , "COST" , "ZIM" , "ES" , input.symbol(defval = "SBUX", title = "Symbol 7 ", inline = "6 ", group = st))), [d7 ,s7 ] = req(7 , tf("ORCL" ,"GS" , "HON" , "PFE" , "KHC" , "AMPY" , "KBH" , "MEDP", "WBA" , "TDW" , "MDU" , input.symbol(defval = "JNJ" , title = "Symbol 8 ", inline = "6 ", group = st)))
req(8 , tf("CRM" ,"PLD" , "INTC" , "TMO" , "VFC" , "COP" , "ROKU", "FOUR", "WMT" , "UAL" , "DUK" , input.symbol(defval = "T" , title = "Symbol 9 ", inline = "8 ", group = st))), [d9 ,s9 ] = req(9, tf("IBM" ,"BLK" , "ADI" , "AMGN", "COTY" , "ARCH" , "RIDE" , "EB" , "EBAY" , "ODFL" , "SRE" , input.symbol(defval = "HD" , title = "Symbol 10", inline = "8 ", group = st)))
req(10, tf("ACN" ,"C" , "NOC" , "REGN" , "COCO" , "VLO" , "GM" , "MQ" , "TGT" , "DAL" , "SO" , input.symbol(defval = "Z" , title = "Symbol 11", inline = "10", group = st))), [d11,s11] = req(11, tf("ROP" ,"AMT" , "AMD" , "ISRG", "NKE" , "RRC" , "ARVL" , "IPDN", "ULTA" , "FLNG" , "EIX" , input.symbol(defval = "AMZN", title = "Symbol 12", inline = "10", group = st)))
req(12, tf("ATVI" ,"CB" , "BA" , "ZTS" , "GLS" , "BTU" , "FSR" , "CHGG", "HD" , "FDX" , "CEG" , input.symbol(defval = "TSLA", title = "Symbol 13", inline = "12", group = st))), [d13,s13] = req(13, tf("SNPS" ,"PGR" , "LMT" , "MDT" , "PM" , "CRK" , "GPRO" , "TWKS", "WISH" , "DHT" , "AQN" , input.symbol(defval = "AMD" , title = "Symbol 14", inline = "12", group = st)))
req(14, tf("CDNS" ,"MMC" , "GD" , "GILD" , "PM" , "MPC" , "NKLA", "CPRT", "CVNA" , "HLBZ", "AEP" , input.symbol(defval = "GOOG", title = "Symbol 15", inline = "14", group = st))), [d15,s15] = req(15, tf("ADSK" ,"USB" , "MU" , "SYK" , "UL" , "PR" , "WHR" , "WEX" , "AAP" , "LPG" , "PPL" , input.symbol(defval = "NIO" , title = "Symbol 16", inline = "14", group = st)))
req(16, tf("NOW" ,"FISV" , "KLAC" , "VRTX" , "BROS" , "MRO" , "GOEV", "PGNY", "LOW" , "UPS" , "AWK" , input.symbol(defval = "BABA", title = "Symbol 17", inline = "16", group = st))), [d17,s17] = req(17, tf("EQIX" ,"CME" , "FTNT" , "BDX" , "BUD" , "VET" , "LZB" , "STGW", "CPNG" , "JBLU" , "NEP" , input.symbol(defval = "IBM" , title = "Symbol 18", inline = "16", group = st)))
req(18, tf("ADP" ,"AON" , "EMR" , "MRNA" , "ONON" , "EQT" , "DHI" , "PAYO", "BYND" , "UNP" , "CLNE", input.symbol(defval = "AFRM", title = "Symbol 19", inline = "18", group = st))), [d19,s19] = req(19, tf("MSCI" ,"PNC" , "MCHP" , "EW" , "MDLZ" , "KOS" , "FTDR" , "HURN", "FTCH" , "GSL" , "NI" , input.symbol(defval = "ABNB", title = "Symbol 20", inline = "18", group = st)))
req(20, tf("CTSH" ,"CCI" , "NXPI" , "DXCM" , "TSN" , "CTRA", "WKHS", "FIS" , "M" , "LUV" , "EXC" , input.symbol(defval = "MSFT", title = "Symbol 21", inline = "20", group = st))), [d21,s21] = req(21, tf("VRSK" ,"SPG" , "HPE" , "A" , "UAA" , "OVV" , "TPX" , "OMC" , "BLDR" , "GOGL" , "ETR" , input.symbol(defval = "AAPL", title = "Symbol 22", inline = "20", group = st)))
req(22, tf("IT" ,"ICE" , "ANET" , "BIIB" , "CLX" , "PXD" , "ARHS", "SPGI", "DLTR" , "ASC" , "PCG" , input.symbol(defval = "NVDA", title = "Symbol 23", inline = "22", group = st))), [d23,s23] = req(23, tf("ANSS" ,"AJG" , "KEYS" , "RMD" , "EL" , "CNQ" , "DPRO" , "TASK", "DG" , "SYY" , "CNP" , input.symbol(defval = "V" , title = "Symbol 24", inline = "22", group = st)))
req(24, tf("EA" ,"MET" , "MSI" , "ILMN" , "IPAR" , "EOG" , "LEN" , "WE" , "KSS" , "STNG", "NFE" , input.symbol(defval = "MA" , title = "Symbol 25", inline = "24", group = st))), [d25,s25] = req(25, tf("VRSN" ,"PRU" , "FTV" , "MTD" , "BTI" , "CEI" , "GT" , "AMN" , "TJX" , "SAVE" , "LNT" , input.symbol(defval = "META", title = "Symbol 26", inline = "24", group = st)))
req(26, tf("EPAM" ,"PSA" , "ROK" , "ALGN" , "K" , "AR" , "VSTO", "BTBT", "ETSY" , "FRO" , "AES" , input.symbol(defval = "SBUX", title = "Symbol 27", inline = "26", group = st))), [d27,s27] = req(27, tf("BR" ,"AMP" , "GRMN" , "WST" , "MO" , "WMB" , "HOG" , "PIXY", "JWN" , "EURN" , "AEE" , input.symbol(defval = "JNJ" , title = "Symbol 28", inline = "26", group = st)))
req(28, tf("FDS" ,"AIG" , "ON" , "BAX" , "HBI" , "SWN" , "FFIE", "RELY", "CHPT" , "BAER", "NOVA", input.symbol(defval = "T" , title = "Symbol 29", inline = "28", group = st))), [d29,s29] = req(29, tf("CSGP" ,"WELL" , "FLSR" , "HOLX", "KDP" , "CHK" , "CENN" , "MLEC", "AZO" , "IMPP" , "ATO" , input.symbol(defval = "HD" , title = "Symbol 30", inline = "28", group = st)))
req(30, tf("TTWO" ,"TRV" , "HPQ" , "STE" , "CL" , "APA" , "TOL" , "BKKT", "MELI" , "VRRM", "NRG" , input.symbol(defval = "Z" , title = "Symbol 31", inline = "30", group = st))), [d31,s31] = req(31, tf("PTC" ,"VICI" , "SWKS" , "WAT" , "DECK" , "HCC" , "LOVE" , "MEG" , "ROST" , "GNK" , "BEP" , input.symbol(defval = "AMZN", title = "Symbol 32", inline = "30", group = st)))
req(32, tf("TRMB" ,"AFL" , "GLW" , "INCY" , "CAG" , "FANG", "FNKO", "GPN" , "CVS" , "GRAB", "XEL" , input.symbol(defval = "TSLA", title = "Symbol 33", inline = "32", group = st))), [d33,s33] = req(33, tf("DXC" ,"ALL" , "HWM" , "COO" , "KMB" , "PARR" , "GRBK" , "ADT" , "TPR" , "TNP" , "DTE" , input.symbol(defval = "AMD" , title = "Symbol 34", inline = "32", group = st)))
req(34, tf("JKHY" ,"COF" , "ENPH" , "PKI" , "TTCF" , "PSX" , "PHM" , "UPWK", "LULU" , "NAT" , "MAXN", input.symbol(defval = "GOOG", title = "Symbol 35", inline = "34", group = st))), [d35,s35] = req(35, tf("CDW" ,"URI" , "TXT" , "BIO" , "SAM" , "CVE" , "NVR" , "PAGS", "SFM" , "TRMD" , "WEC" , input.symbol(defval = "NIO" , title = "Symbol 36", inline = "34", group = st)))
req(36, tf("PAYC" ,"BK" , "MPWR" , "VTRS" , "CPB" , "PBF" , "STLA", "VERI", "KR" , "TNK" , "BWXT", input.symbol(defval = "BABA", title = "Symbol 37", inline = "36", group = st))), [d37,s37] = req(37, tf("TYL" ,"CBRE" , "NTAP" , "CTLT", "STZ" , "WTI" , "GOLF" , "NOTV", "DKS" , "TK" , "PNW" , input.symbol(defval = "IBM" , title = "Symbol 38", inline = "36", group = st)))
req(38, tf("GEN" ,"O" , "TDY" , "TFX" , "TR" , "SU" , "SWK" , "ADV" , "W" , "NSC" , "ED" , input.symbol(defval = "AFRM", title = "Symbol 39", inline = "38", group = st))), [d39,s39] = req(39, tf("MTCH" ,"ARE" , "LDOS" , "TECH", "LEVI" , "CPE" , "LKQ" , "IPG" , "ORLY" , "ALK" , "KEN" , input.symbol(defval = "ABNB", title = "Symbol 40", inline = "38", group = st)))
type dropDown
float data
float coordinate
string symbol
var histData = matrix.new<values>(40, 1), var scatterShapes = matrix.new<values>(7, 40), var pieShapes = matrix.new<values>(4, 1) , mid = 0
cArray = array.new <values>(), var gemMat = matrix.new<dropDown>(10, 40), right = 0
b( float ) =>
max - ((max - min) * float )
x( float , mult ) =>
timeArray.get(math.round(math.max(timeArray.indexof( right) + (mid * (float + (.20 * mult))), 0)))
append(string , bool , int ) =>
if timeframe.change("M") and month == int
histData.add_row(histData.rows())
histData.add_col(histData.columns())
histData.set(histData.rows() - 1, 0, values.new(yearCount = string + str.tostring(bool == false ? year : year - 1)))
for i = 0 to symbolMat.columns() - 1
histData.set(i, histData.columns() - 1, values.new(symbolData = symbolMat.get(0, i).symbolData))
if per == "FQ"
append("Q3 ", false, 10), append("Q4 ", true , 1)
append("Q1 ", false, 4 ), append("Q2 ", false, 7)
else
if ta.change(year)
histData.add_row(histData.rows())
histData.add_col(histData.columns())
histData.set(histData.rows() - 1, 0, values.new(yearCount = str.tostring(year - 1)))
for i = 0 to symbolMat.columns() - 1
histData.set(i, histData.columns() - 1, values.new(symbolData = symbolMat.get(0, i).symbolData))
if barstate.islastconfirmedhistory
if timeframe.multiplier < 240 and not timeframe.isdwm
runtime.error("Please Select 4-Hour Chart or Greater Resolution")
colCond = columns != "Pie Chart" and columns != "Drop Down"
if intervalsback != 0
for i = 0 to 39
n = histData.get(i, histData.columns() - intervalsback)
if not na(n)
symbolMat.set(0, i, values.new(symbolData = nz(n.symbolData)))
string dateF = switch intervalsback != 0
false => "Current"
=> histData.get(histData.rows() - intervalsback, 0).yearCount
copy = values.new(dataArr = array.new_float(), symbolArr = array.new_string()),
for i = 0 to symbolMat.columns() - 1
array.push(copy.dataArr , symbolMat.get(0, i).symbolData)
array.push(copy.symbolArr , symbolMat.get(1, i).symbol )
if sort != "None" or columns == "Pie Chart" or columns == "Drop Down"
if columns != "Pie Chart" and columns != "Drop Down"
order = switch sort
"Descending" => order.ascending
=> order.descending
copy.dataArr.sort(order)
else
order = order.descending, copy.dataArr.sort(order)
for i = 0 to copy.symbolArr.size() - 1
for x = 0 to copy.symbolArr.size() - 1
if symbolMat.get(0, i).symbolData == copy.dataArr.get(x)
copy.symbolArr.set(x, symbolMat.get(1, i).symbol)
right := chart.right_visible_bar_time, left = chart.left_visible_bar_time,
mid := timeArray.indexof(left) - timeArray.indexof(right)
newLeft =
math.round(
math.min(
timeArray.indexof(left) - (mid * .06),
timeArray.size() - 1))
newRight =
math.round(
math.max(
timeArray.indexof(right) + (mid * .06), 0))
mid2 =
math.round(
math.avg(timeArray.indexof(newLeft),
timeArray.indexof( newRight))),
scatterShapes.set(6, 0,
values.new(
colmn = box.new(
timeArray.get(newLeft),
max,
timeArray.get(newRight),
min,
bgcolor = boxnobg and usebg ? cbg : na,
border_color = boxnobg ? color.white : na,
xloc = xloc.bar_time
)))
pieShapes.set(0, 0, values.new(l = timeArray.get(newLeft))), pieShapes.set(1, 0, values.new(top = max))
pieShapes.set(2, 0, values.new(r = timeArray.get(newRight))), pieShapes.set(3, 0, values.new(bot = min))
adcalc = (pieShapes.get(1, 0).top - pieShapes.get(3, 0).bot) / 20
nCalc = copy.dataArr.range() / 20, xz = -1, n = 0.0
if colCond
n := switch revScale
false => copy.dataArr.min()
=> copy.dataArr.max()
else
n := copy.dataArr.min()
strFix = switch revScale
true => copy.dataArr.max() < 0 ? "0" : str.tostring(copy.dataArr.max() + nCalc, "###,###.##")
false => copy.dataArr.min() > 0 ? "0" : str.tostring(copy.dataArr.min() - nCalc, "###,###.##")
scatterShapes.set(1, 0,
values.new(
symbolLabel = label.new(
pieShapes.get(2, 0).r,
pieShapes.get(3, 0).bot - adcalc,
text = strFix,
color = #ffffff00,
style = label.style_label_left,
textcolor = dncol,
xloc = xloc.bar_time,
size = size.small
)))
for x = 0 to 39
pos = str.pos(copy.symbolArr.get(x), ":"), sub = str.substring(copy.symbolArr.get(x), pos + 1), calcY = 0.0
if colCond
calcY := switch revScale
false => (min) + ((max) - (min)) * (copy.dataArr.get(x) - copy.dataArr.min()) / (copy.dataArr.range())
true => (max) - ((max) - (min)) * (copy.dataArr.get(x) - copy.dataArr.min()) / (copy.dataArr.range())
else
calcY := (min) + ((max) - (min)) * (copy.dataArr.get(x) - copy.dataArr.min()) / copy.dataArr.range()
yax = switch x != xz
true and calcY < pieShapes.get(3, 0).bot => pieShapes.get(3, 0).bot
true and calcY > pieShapes.get(1, 0).top => pieShapes.get(1, 0).top
=> calcY
scatterShapes.set(0, x, values.new(symbolLabel =
label.new(
timeArray.get(newRight + ((mid/48) * (x + 1))),
yax,
xloc = xloc.bar_time,
textcolor = color.white,
color = #ffffff00 ,
style = label.style_label_center,
text = sub +"\n⦿", size = size.small,
tooltip = str.tostring(copy.dataArr.get(x), "###,###,###.00")
)))
if x <= 19
loopdn = kai.hsv_gradient(x, 0, 10, dncol, midCol)
loopup = kai.hsv_gradient(x, 11, 19, midCol, upcol), xTrack = -1
col = switch xTrack != x
true and x <= 10 => loopdn
=> loopup
scatterShapes.set(1, x + 1, values.new(symbolLabel =
label.new(
pieShapes.get(2, 0).r,
pieShapes.get(3, 0).bot + (adcalc * x),
text = str.tostring(n, "###,###.##" ) ,
color = #ffffff00,
style = label.style_label_left,
textcolor = col,
xloc = xloc.bar_time,
size = size.small
)))
if colCond
switch revScale
false => n += nCalc
=> n -= nCalc
else
n += nCalc
cArray.push(values.new(symbolColor = col))
scatterShapes.set(1, 21, values.new(symbolLabel =
label.new(
pieShapes.get(2, 0).r,
pieShapes.get(1, 0).top ,
text = str.tostring(colCond ? revScale == false ? copy.dataArr.max() : copy.dataArr.min() : copy.dataArr.max(), "###,###.##"),
color = #ffffff00,
style = label.style_label_left,
textcolor = upcol,
xloc = xloc.bar_time,
size = size.small
)))
pieShapes.set(1, 0, values.new(top = pieShapes.get(1, 0).top + adcalc)), scatterShapes.get(6, 0).colmn.set_top(pieShapes.get(1, 0).top)
strFix2 = switch revScale
false => copy.dataArr.max() < 0 ? "0" : str.tostring(copy.dataArr.max() + nCalc, "###,###.##")
true => copy.dataArr.min() > 0 ? "0" : str.tostring(copy.dataArr.min() - nCalc, "###,###.##")
scatterShapes.set(1, 22,
values.new(
symbolLabel = label.new(
pieShapes.get(2, 0).r,
pieShapes.get(1, 0).top,
text = strFix2,
color = #ffffff00,
style = label.style_label_left,
textcolor = upcol,
xloc = xloc.bar_time,
size = size.small
)))
for i = 0 to 1
cArray.push(values.new(symbolColor = upcol))
pieShapes.set(3, 0, values.new(bot = pieShapes.get(3, 0).bot - adcalc)), scatterShapes.get(6, 0).colmn.set_bottom(pieShapes.get(3, 0).bot), minLab = math.round(20e20)
if boxnobg == false
for i = 0 to 39
minLab := math.min(minLab, scatterShapes.get(0, i).symbolLabel.get_x())
for i = 0 to 1
[x1, y1, x2, y2] = switch i != -1
true and i == 0 => [minLab, pieShapes.get(3, 0).bot, timeArray.get(newRight), pieShapes.get(3, 0).bot ]
=> [timeArray.get(newRight), pieShapes.get(3, 0).bot, timeArray.get(newRight), pieShapes.get(1, 0).top]
scatterShapes.set(2, i, values.new(shapeLines =
line.new(x1, y1, x2, y2,
xloc = xloc.bar_time,
color = color.white
)))
cArray.unshift(values.new(symbolColor = dncol)), sortedy = array.new_float()
for i = 0 to 22
sortedy.push(scatterShapes.get(1, i).symbolLabel.get_y())
sortedy.sort(order.descending), cArray.reverse(), copyColor = array.new_int()
for i = 0 to 39
for x = 1 to 22
if scatterShapes.get(0, i).symbolLabel.get_y() >= sortedy.get(x)
if scatterShapes.get(0, i).symbolLabel.get_y() <= sortedy.get(x - 1)
scatterShapes.get(0, i).symbolLabel.set_textcolor(cArray.get(x).symbolColor), copyColor.push(x)
pos = str.pos (copy.symbolArr.get(i), ":")
sub = str.substring(copy.symbolArr.get(i), pos + 1)
scatterShapes.set(3, i,
values.new(
symbolLabel = label.new(
scatterShapes.get(0, i).symbolLabel.get_x(),
pieShapes.get(3, 0).bot,
style = label.style_label_up,
textcolor = color.white,
color = #ffffff00,
text = "╷\n" + sub,
xloc = xloc.bar_time,
size = size.small
)))
for i = 1 to 39
if scatterShapes.get(3, i).symbolLabel.get_x() == scatterShapes.get(3, i - 1).symbolLabel.get_x()
scatterShapes.get(3, i).symbolLabel.set_text(scatterShapes.get(3, i).symbolLabel.get_text() + "\n" + scatterShapes.get(3, i - 1).symbolLabel.get_text())
scatterShapes.get(3, i - 1).symbolLabel.delete()
if columns == "Columns" or columns == "Scatter + Columns" or columns == "Bar"
for i = 0 to 39
coordinateE = timeArray.indexof(scatterShapes.get(0, 1).symbolLabel.get_x()) - timeArray.indexof(scatterShapes.get(0, 0).symbolLabel.get_x())
[coordinateL, coordinateR] = switch columns
"Bar" => [timeArray.get(timeArray.indexof(scatterShapes.get(0, i).symbolLabel.get_x()) - math.round(coordinateE / 2)),
timeArray.get(timeArray.indexof(scatterShapes.get(0, i).symbolLabel.get_x()) + math.round(coordinateE / 2))]
=> [timeArray.get(timeArray.indexof(scatterShapes.get(0, i).symbolLabel.get_x())),
timeArray.get(timeArray.indexof(scatterShapes.get(0, i).symbolLabel.get_x()))]
scatterShapes.set(4, i,
values.new(
colmn = box.new(
coordinateL,
scatterShapes.get(0, i).symbolLabel.get_y(),
coordinateR,
pieShapes.get(3, 0).bot,
xloc = xloc.bar_time,
border_color = columns == "Bar" ? cbg : na,
border_width = columns == "Bar" ? 3 : 1,
bgcolor = na
)))
for x = 1 to sortedy.size() - 1
if scatterShapes.get(4, i).colmn.get_top() >= sortedy.get(x)
if scatterShapes.get(4, i).colmn.get_top() <= sortedy.get(x - 1)
scatterShapes.get(4, i).colmn.set_bgcolor(cArray.get(x).symbolColor)
if columns != "Bar"
scatterShapes.get(4, i).colmn.set_border_color(cArray.get(x).symbolColor)
if columns == "Columns"
scatterShapes.get(0, i).symbolLabel.delete()
if columns == "Bar"
if i == 39
if boxnobg == false
scatterShapes.get(2, 0).shapeLines.set_x1(scatterShapes.get(4, 39).colmn.get_right())
else
scatterShapes.get(6, 0).colmn.set_bottom(scatterShapes.get(6, 0).colmn.get_bottom() - adcalc)
for x = 0 to 39
scatterShapes.get(0, x).symbolLabel.delete()
add = switch per
"FQ" => " (FQ)\n" + px + "\n" + dateF
"FY" => " (FY)\n" + px + "\n" + dateF
scatterShapes.set(5, 0,
values.new(
symbolLabel = label.new(
math.round(math.avg(pieShapes.get(0, 0).l, pieShapes.get(2, 0).r)),
pieShapes.get(1, 0).top,
color = #ffffff00,
textcolor = color.white,
size = size.large,
text = searchF == false ? typeInput1 + add :
search + add, xloc = xloc.bar_time
)))
allL = label.all, allB = box.all, allLi = line.all
if columns == "Pie Chart"
if allL.size() > 0
for i = 0 to allL.size() - 1
allL.shift().delete()
if allB.size() > 0
for i = 0 to allB.size() - 1
allB.shift().delete()
if allLi.size() > 0
for i = 0 to allLi.size() - 1
allLi.shift().delete()
if mid > 20
newRight2 = math.round(math.max(timeArray.indexof( right) + (mid * .55), 0))
newLeft2 = math.round(math.max(timeArray.indexof( right) + (mid * .45), 0))
sub = timeArray.slice(newRight2, newLeft)
sub2 = timeArray.slice(newRight, newLeft2)
pc = array.new_float(), pc2 = array.new_float()
for i = 0 to 19
pc.push (copy.dataArr.get(i))
pc2.push(copy.dataArr.get(i+20))
perCumu = array.new_float(), perCumu2 = array.new_float()
for i = 0 to 19
pc.set(i, pc.get(i) + math.abs(pc.min() ))
pc2.set(i, pc2.get(i) + math.abs(pc2.min()))
for i = 0 to 19
perCumu .push(pc.get(i) / pc.sum() / 5 * 100)
perCumu2.push(pc2.get(i) / pc2.sum() / 5 * 100)
percCumu = 0.0, percCumu2 = 0.0
for i = 0 to 6
pieShapes.add_row(pieShapes.rows())
for i = 0 to 19
// thanking @rumpypumpydumpy (on every iteration of this loop) for the easy-to-work-with framework!
pieShapes.set(4, pieShapes.columns() - 1,
values.new(shapeLines =
line.new(
sub.get(math.round(math.cos(2 * math.pi / 20 * percCumu) * ((math.round((newLeft - newRight2) / 2)) - 1) +
(math.round((newLeft2 - newRight) / 2)) - 1)),
math.avg(max, min) + math.sin(2 * math.pi / 20 * percCumu) * math.avg(max, min),
sub.get(math.round(sub.size()/2) - 1),
math.avg(max,min),
xloc=xloc.bar_time, color = #000000, width = 2
)))
percCumu += perCumu.get(i)
pieShapes.set(5, pieShapes.columns() - 1,
values.new(shapeLines =
line.new(
sub2.get(math.round(math.cos(2 * math.pi / 20 * percCumu2) * ((math.round((newLeft2 - newRight) / 2)) - 1)
+ (math.round((newLeft2 - newRight) / 2)) - 1)),
math.avg(max, min) + math.sin(2 * math.pi / 20 * percCumu2) * math.avg(max, min),
sub2.get(math.round(sub2.size()/2) - 1),
math.avg(max,min),
xloc=xloc.bar_time, color = #000000, width = 2
)))
percCumu2 += perCumu2.get(i)
pieShapes.add_col(pieShapes.columns())
for i = 4 to 5
[initialSet, plus] = switch i != -1
true and i == 4 => [6, 0 ]
=> [8, 20]
pieShapes.set(initialSet, 0,
values.new(
symbolLabel = label.new(
math.round(math.avg(pieShapes.get(i, 0).shapeLines.get_x1(), pieShapes.get(i, pieShapes.columns() - 2).shapeLines.get_x1())),
math.avg(pieShapes.get(i, 0).shapeLines.get_y1(), pieShapes.get(i, pieShapes.columns() - 2).shapeLines.get_y1()),
text = copy.symbolArr.get(pieShapes.columns() - 2 + plus)
+ "\n" + str.tostring(copy.dataArr.get(pieShapes.columns()-2 + plus)),
color = color.new(cArray.get(copyColor.get(pieShapes.columns() - 2 + plus)).symbolColor, 50),
xloc = xloc.bar_time,
style = label.style_label_center,
textcolor = color.white,
size = size.small
)))
for i = 1 to pieShapes.columns() - 1
if not na(pieShapes.get(4, i))
if perCumu.variance() < 1
pieShapes.set(6, i,
values.new(
shapeLinesFill=linefill.new(
pieShapes.get(4, i).shapeLines,
pieShapes.get(4, i - 1).shapeLines,
color.new(cArray.get(copyColor.get(i - 1)).symbolColor, 33
))))
if i == 1
pieShapes.set(6, 0,
values.new(
shapeLinesFill = linefill.new(
pieShapes.get(4, 0).shapeLines,
pieShapes.get(4, pieShapes.columns() - 2).shapeLines,
color.new(cArray.get(copyColor.get(pieShapes.columns()-2)).symbolColor, 33
))))
else
pieShapes.get(4, i - 1).shapeLines.set_color(color.white)
pieShapes.get(4, i - 1).shapeLines.set_style(line.style_dotted)
pieShapes.set(7, i, values.new(symbolLabel=label.new(
math.round(math.avg(line.get_x1(pieShapes.get(4, i).shapeLines), line.get_x1(pieShapes.get(4, i - 1).shapeLines))),
math.avg(line.get_y1(
pieShapes.get(4, i).shapeLines), line.get_y1(pieShapes.get(4, i - 1).shapeLines)),
text = copy.symbolArr.get(i - 1) + "\n" + str.tostring(copy.dataArr.get(i - 1)),
color = color.new(cArray.get(copyColor.get(i - 1)).symbolColor, 50),
xloc = xloc.bar_time,
style = label.style_label_center,
textcolor = color.white,
size = size.small
)))
if not na(pieShapes.get(5, i))
if perCumu2.variance() < 1
pieShapes.set(8, i,
values.new(
shapeLinesFill=linefill.new(
pieShapes.get(5, i).shapeLines,
pieShapes.get(5, i - 1).shapeLines,
color.new(cArray.get(copyColor.get(i + 20 - (i == pieShapes.columns() - 1 ? 1 : 0))).symbolColor,
33
))))
if i == 1
pieShapes.set(8, 0,
values.new(
shapeLinesFill =
linefill.new(pieShapes.get(5, 0).shapeLines,
pieShapes.get(5, pieShapes.columns() - 2).shapeLines,
color.new(cArray.get(copyColor.get(20)).symbolColor,
33
))))
else
pieShapes.get(5, i - 1).shapeLines.set_color(color.white)
pieShapes.get(5, i - 1).shapeLines.set_style(line.style_dotted)
pieShapes.set(9, i,
values.new(
symbolLabel=label.new(
math.round(math.avg(line.get_x1(pieShapes.get(5, i).shapeLines), line.get_x1(pieShapes.get(5, i - 1).shapeLines))),
math.avg(line.get_y1(pieShapes.get(5, i).shapeLines), line.get_y1(pieShapes.get(5, i - 1).shapeLines)),
text = copy.symbolArr.get(20 + i - 1) + "\n" + str.tostring(copy.dataArr.get(20 + i - 1)),
color =
color.new(cArray.get(copyColor.get(i + 20 - (i == pieShapes.columns() - 1 ? 1 : 0))).symbolColor, 50),
xloc = xloc.bar_time,
style = label.style_label_center,
textcolor = color.white,
size = size.small
)))
maxLine = 0.
for i = 0 to pieShapes.columns() - 1
if not na(pieShapes.get(4, i)) and not na(pieShapes.get(5, i))
maxLine := math.max(
maxLine,
line.get_y1(pieShapes.get(4, i).shapeLines),
line.get_y1(pieShapes.get(5, i).shapeLines
))
pieShapes.add_row(pieShapes.rows()), pieShapes.set(11, 0,
values.new(
symbolLabel = label.new(
math.round(math.avg(timeArray.get( newRight2), timeArray.get( newLeft2))),
maxLine,
color = #ffffff00,
textcolor = color.white,
size = size.large,
text =searchF == false ? typeInput1 + add: search + add, xloc = xloc.bar_time
)))
else
label.new(
math.round(math.avg(chart.left_visible_bar_time, chart.right_visible_bar_time)),
math.avg(max, min), color = #ffffff00,
xloc = xloc.bar_time, size = size.huge, text = "🥧"
)
if columns == "Drop Down"
iTrack = -1, gm = gemMat
if allL.size() > 0
for i = 0 to allL.size() - 1
allL.shift().delete()
if allB.size() > 0
for i = 0 to allB.size() - 1
allB.shift().delete()
if allLi.size() > 0
for i = 0 to allLi.size() - 1
allLi.shift().delete()
aId1 = array.from(.80, .84, .80, .76, .86, .82, .78, .74, .88, .72)
aId2 = array.from(.80, .84, .80, .76, .86, .82, .78, .74, .88, .72)
aId3 = array.from(.0, .0 , .0, .0, .10, .10, .10, .10, .20, .20)
aId4 = array.from(.0, .10 , .10, .10, .20, .20, .20, .20, .30, .30)
for i = 0 to 39
gm.set(0, i, dropDown.new(data = copy.dataArr.get(i )))
gm.set(1, i, dropDown.new(symbol = copy.symbolArr.get(i)))
if i <= 9
gm.set(2, i, dropDown.new(coordinate = aId1.get(i)))
gm.set(3, i, dropDown.new(coordinate = aId2.get(i)))
gm.set(4, i, dropDown.new(coordinate = aId3.get(i)))
gm.set(5, i, dropDown.new(coordinate = aId4.get(i)))
base = array.new_line(), basel = array.new_label(), xT = -1
for x = 0 to 3
for i = 0 to 9
if x >= 1
plus = switch x != xT
true and x == 1 => 10
true and x == 2 => 20
true and x == 3 => 30
gm.set(2, i+plus, dropDown.new(coordinate = gm.get(2 , i ) .coordinate - (.20 * x)))
gm.set(3, i+plus, dropDown.new(coordinate = gm.get(3 , i ) .coordinate - (.20 * x)))
gm.set(4, i+plus, dropDown.new(coordinate = gm.get(4, i) .coordinate))
gm.set(5, i+plus, dropDown.new(coordinate = gm.get(5, i) .coordinate))
if i == 0
gm.set(6, x, dropDown.new(coordinate = .86 - (.20 * x))), gm.set(7, x, dropDown.new(coordinate = .74 - (.20 * x)))
gm.set(8, x, dropDown.new(coordinate = .72 - (.20 * x))), gm.set(9, x, dropDown.new(coordinate = .88 - (.20 * x)))
for i = 0 to gm.columns() - 1
xm = cArray, xb = copyColor
fc = revScale == false ? reverse == false ? downcolor : upcolor : reverse == false ? upcolor : downcolor
basel.push(
label.new(
x = int(x(gm.get(3, i).coordinate, 0)),
y = b (gm.get(5, i).coordinate ),
text = gm.get(1, i).symbol + "\n" + str.tostring(gm.get(0, i).data),
size = size.small,
xloc = xloc.bar_time,
style = label.style_label_center,
textcolor = color.white,
color = color.new(i == gm.columns() - 1 ? fc : xm.get(xb.get(i)).symbolColor, 60)
))
base.push(
line.new(
int(x(gm.get(2, i).coordinate, 0)), b(gm.get(4, i).coordinate),
int(x(gm.get(3, i).coordinate, 0)), b(gm.get(5, i).coordinate),
xloc = xloc.bar_time, color = #ffffff
))
if i <= 3
base.push(
line.new(
int(x(gm.get(6, i).coordinate, 0)), b(.10),
int(x(gm.get(7, i).coordinate, 0)), b(.10),
xloc = xloc.bar_time, color = color.white
))
base.push(
line.new(
int(x(gm.get(8, i).coordinate, 0)), b(.20),
int(x(gm.get(9, i).coordinate, 0)), b(.20),
xloc = xloc.bar_time, color = color.white
))
base.push(
line.new(
int(x(.84, 0)), b(.0), int(x(.16, 0)), b(.0),
xloc = xloc.bar_time, color = color.white
))
bgcolor(usebg and boxnobg == false ? cbg : na) |
[JL] Fractals ATR Block | https://www.tradingview.com/script/DAprOFMl-JL-Fractals-ATR-Block/ | Jesse.Lau | https://www.tradingview.com/u/Jesse.Lau/ | 210 | 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/
// © Jesse.Lau
//@version=5
indicator("[JL] Fractals ATR Block", shorttitle="[JL] FAB", format=format.price, precision=0, overlay=true)
show_fractals = input(true, "Show Fractals", group="Show")
show_atrs = input(true, "Show ATR breaks", group="Show")
show_blocks = input(false, "Show blocks", group="Show")
n = input.int(title="Fractals Periods", defval=1, minval=1)
roclevel = input.float(title="ROC Break Level", defval=2.0, minval=0)
rocup = (close - ta.lowest(n+1))/(open[2*n]-ta.lowest(n+1))
rocdn = (ta.highest(n+1)-close)/(ta.highest(n+1)-open[2*n])
atrPeriod = input(200, "ATR Length")
atrlevel = input.float(title="ATR Break Level", defval=1.5, minval=0)
ATR = ta.atr(atrPeriod)
atrup = (close - low)/ATR[1]
atrdn = (high -close)/ATR[1]
// UpFractal
bool upflagDownFrontier = true
bool upflagUpFrontier0 = true
bool upflagUpFrontier1 = true
bool upflagUpFrontier2 = true
bool upflagUpFrontier3 = true
bool upflagUpFrontier4 = true
for i = 1 to n
upflagDownFrontier := upflagDownFrontier and (high[n-i] < high[n])
upflagUpFrontier0 := upflagUpFrontier0 and (high[n+i] < high[n])
upflagUpFrontier1 := upflagUpFrontier1 and (high[n+1] <= high[n] and high[n+i + 1] < high[n])
upflagUpFrontier2 := upflagUpFrontier2 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+i + 2] < high[n])
upflagUpFrontier3 := upflagUpFrontier3 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+i + 3] < high[n])
upflagUpFrontier4 := upflagUpFrontier4 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+4] <= high[n] and high[n+i + 4] < high[n])
flagUpFrontier = upflagUpFrontier0 or upflagUpFrontier1 or upflagUpFrontier2 or upflagUpFrontier3 or upflagUpFrontier4
upFractal = (upflagDownFrontier and flagUpFrontier)
// downFractal
bool downflagDownFrontier = true
bool downflagUpFrontier0 = true
bool downflagUpFrontier1 = true
bool downflagUpFrontier2 = true
bool downflagUpFrontier3 = true
bool downflagUpFrontier4 = true
for i = 1 to n
downflagDownFrontier := downflagDownFrontier and (low[n-i] > low[n])
downflagUpFrontier0 := downflagUpFrontier0 and (low[n+i] > low[n])
downflagUpFrontier1 := downflagUpFrontier1 and (low[n+1] >= low[n] and low[n+i + 1] > low[n])
downflagUpFrontier2 := downflagUpFrontier2 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+i + 2] > low[n])
downflagUpFrontier3 := downflagUpFrontier3 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+i + 3] > low[n])
downflagUpFrontier4 := downflagUpFrontier4 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+4] >= low[n] and low[n+i + 4] > low[n])
flagDownFrontier = downflagUpFrontier0 or downflagUpFrontier1 or downflagUpFrontier2 or downflagUpFrontier3 or downflagUpFrontier4
downFractal = (downflagDownFrontier and flagDownFrontier)
if show_atrs and atrup > atrlevel
label.new(x=bar_index, y=na,text= "AB"+str.tostring(atrup, '##.##'), //ATR BREAK
color=color.lime,
textcolor=color.black,size=size.small,
style=label.style_label_up, yloc=yloc.belowbar)
if show_atrs and atrdn > atrlevel
label.new(x=bar_index, y=na, text= "AB"+str.tostring(atrdn, '##.##'), //ATR BREAK
color=color.red,
textcolor=color.white,size=size.small,
style=label.style_label_down, yloc=yloc.abovebar)
if downFractal and rocup > roclevel and show_fractals
label.new(x=bar_index-n, y=na, text="FR"+str.tostring(rocup, '##.##'), //Fractal ROC
color=color.lime,
textcolor=color.black, size=size.small,
style=label.style_label_up, yloc=yloc.belowbar)
if upFractal and rocdn > roclevel and show_fractals
label.new(x=bar_index-n, y=na, text="FR"+str.tostring(rocdn, '##.##'), //Fractal ROC
color=color.red,
textcolor=color.white, size=size.small,
style=label.style_label_down, yloc=yloc.abovebar)
var box upBox = na
var box downBox = na
if show_atrs and atrup > atrlevel and show_blocks
if not na(upBox)
box.delete(upBox)
upBox := box.new(left=bar_index-1, top=high[1], right=bar_index, bottom=low[1], border_color=color.lime, border_width=1, border_style=line.style_solid, bgcolor=color.new(color.lime, 50) ,extend=extend.right)
if show_atrs and atrdn > atrlevel and show_blocks
if not na(downBox)
box.delete(downBox)
downBox := box.new(left=bar_index-1, top=high[1], right=bar_index, bottom=low[1], border_color=color.red, border_width=1, border_style=line.style_solid, bgcolor=color.new(color.red, 50), extend=extend.right)
var box upBoxf = na
var box downBoxf = na
lowest_low_2n = ta.lowest(low, 2*n)
highest_hihg_2n = ta.highest(high, 2*n)
if downFractal and rocup > roclevel and show_fractals and show_blocks
if not na(upBoxf)
box.delete(upBoxf)
upBoxf := box.new(left=bar_index-2*n, top=highest_hihg_2n[n+1], right=bar_index, bottom=lowest_low_2n[n+1], border_color=color.lime, border_width=1, border_style=line.style_solid, bgcolor=color.new(color.lime, 50) ,extend=extend.right)
if upFractal and rocdn > roclevel and show_fractals and show_blocks
if not na(downBoxf)
box.delete(downBoxf)
downBoxf := box.new(left=bar_index-2*n, top=highest_hihg_2n[n+1], right=bar_index, bottom=lowest_low_2n[n+1], border_color=color.red, border_width=1, border_style=line.style_solid, bgcolor=color.new(color.red, 50), extend=extend.right)
|
Role Reversal Detection Alert [MsF] | https://www.tradingview.com/script/L3COnlyb/ | Trader_Morry | https://www.tradingview.com/u/Trader_Morry/ | 215 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Trader_Morry
//@version=5
indicator(title='Role Reversal Detection Alert [MsF]', shorttitle='R&R Detection', overlay=true, max_bars_back = 5000)
////////
// Input values
// [
ibaseHValue = input.float(defval = 135.2, title = "Input Horizontal Value")
ibaseBandPips = input.int(defval = 10, title = "Band Range by pips")
ibaseLineColor = input.color(defval = color.blue, title = "Line Color", inline = "iLine")
ibaseLineWidth = input.int(defval = 1, title = "Line Width", inline = "iLine")
ibaseBandColor = input.color(defval = color.blue, title = "Band Color", inline = "iBand")
ibaseBandWidth = input.int(defval = 1, title = "Band Width", inline = "iBand")
iLong = true //input.bool(defval = true, title = "Long Detection")
iShort = true //input.bool(defval = true, title = "Short Detection")
iLookBackCBars = 18 // count of previous Bars for Judging touch in center
// ]
// Defines
// [
LONG = 1
SHORT = -1
// ]
// Functions
// [
check_touch_center(aLongShort, aBars) =>
var touch = false
if ( aLongShort == LONG )
for i=1 to aBars-1
if ibaseHValue >= low[i]
touch := true
break
else if ( aLongShort == SHORT )
for i=1 to aBars-1
if ibaseHValue <= high[i]
touch := true
break
touch
// ]
// Main Program
// [
_pips = ibaseBandPips*syminfo.mintick*10
// Base line
var line line_Base = na
line.delete(line_Base)
line_Base := line.new(bar_index, ibaseHValue, bar_index+1, ibaseHValue, extend = extend.both, color = ibaseLineColor, width = ibaseLineWidth)
// Upper Band line
var line line_Upper = na
line.delete(line_Upper)
line_Upper := line.new(bar_index, ibaseHValue+_pips, bar_index+1, ibaseHValue+_pips, extend = extend.both, color = ibaseBandColor, style = line.style_dashed, width = ibaseBandWidth)
// Lower Band line
var line line_Lower = na
line.delete(line_Lower)
line_Lower := line.new(bar_index, ibaseHValue-_pips, bar_index+1, ibaseHValue-_pips, extend = extend.both, color = ibaseBandColor, style = line.style_dashed, width = ibaseBandWidth)
//// Alert
// [
// 終値で帯を抜けた場合
alert_long_BO = (close[2] < ibaseHValue+_pips and close[1] >= ibaseHValue+_pips)?true:false
alert_short_BO = (close[2] > ibaseHValue-_pips and close[1] <= ibaseHValue-_pips)?true:false
// センタータッチチェック
alert_long_CT = check_touch_center(LONG , iLookBackCBars)
alert_short_CT = check_touch_center(SHORT, iLookBackCBars)
// ALL check Long/Short
alert_long = iLong and alert_long_BO and alert_long_CT
alert_short = iShort and alert_short_BO and alert_short_CT
//alertcondition(alert_long or alert_short,"Role Reversal Alert","Detect Role Reversal!!")
alertcondition(alert_long,"[long] Role Reversal Alert","Detect Role Reversal - long!!")
alertcondition(alert_short,"[short] Role Reversal Alert","Detect Role Reversal - short!!")
// ]
// ]
|
Net USD Liquidity w/ overlays [tedtalksmacro] | https://www.tradingview.com/script/R7sQxk8I-Net-USD-Liquidity-w-overlays-tedtalksmacro/ | tedtalksmacro | https://www.tradingview.com/u/tedtalksmacro/ | 160 | 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/
// © tedtalksmacro
//@version=5
indicator("Net USD Liquidity w/ overlays [tedtalksmacro]", overlay = false)
//USCBBS-RRPONTTLD*1000000000-WTREGEN*1000000000
balance_sheet = request.security("USCBBS", 'D', close)
treasury_gen = request.security("WTREGEN", 'D', close)
rrp = request.security("RRPONTTLD", 'D', close)
value = (balance_sheet-treasury_gen-rrp) / 1000000000000
var booleish = true
seven_sma = ta.ema(value, 20)
bullish = value > seven_sma
bearish = value < seven_sma
if booleish
if bearish
booleish := false
if not booleish
if bullish
booleish := true
// mycolor = higher ? color.silver : lower ? color.blue : na
sentimentColor = booleish ? color.rgb(101, 171, 103) : color.rgb(197, 10, 10)
plot(value, transp = 0, linewidth=2, color= sentimentColor, title = 'USD Liquidity [tln USD]')
plot(treasury_gen / 100000000000, style = plot.style_columns, linewidth=2, color= color.orange, title = 'Treasury General Account [tln USD]')
plot(rrp / 1000000000000, style = plot.style_columns, linewidth=1, color= color.new(color.black, 0), title = 'Reverse Repo [tln USD]') |
Reversal Points | https://www.tradingview.com/script/w5WRygzM/ | Enes_Yetkin_ | https://www.tradingview.com/u/Enes_Yetkin_/ | 586 | 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/
// © enesyetkin
//@version=5
indicator('Reversal Points', overlay=true)
newHighSensitivity = input.int(defval=50, title='New Low Sensitivity', minval=1)
Periods = input(title='ATR Period', defval=10)
src = input(hl2, title='Source')
Multiplier = input.float(title='ATR Multiplier', step=0.1, defval=2.0)
changeATR = input(title='Change ATR Calculation Method ?', defval=true)
Supertrend(src, Multiplier, Periods,changeATR) =>
atr2 = ta.sma(ta.tr, Periods)
atr = changeATR ? ta.atr(Periods) : atr2
up = src - Multiplier * atr
up1 = nz(up[1], up)
up := close[1] > up1 ? math.max(up, up1) : up
dn = src + Multiplier * atr
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? math.min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
[trend, up,dn]
[trend, up,dn] = Supertrend(src, Multiplier, Periods,changeATR)
//upPlot = plot(trend == 1 ? up : na, title='Up Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.green, 0))
buySignal = trend == 1 and trend[1] == -1
//dnPlot = plot(trend == 1 ? na : dn, title='Down Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.red, 0))
sellSignal = trend == -1 and trend[1] == 1
var newHighCondition = 0
higher = ta.highest(newHighSensitivity)
if higher == higher[newHighSensitivity / 10]
newHighCondition := 0
newHighCondition
// lowerLevel:=0.0
if higher != higher[newHighSensitivity / 10] and close > higher[newHighSensitivity / 10]
newHighCondition := 1
newHighCondition
HighColor = newHighCondition == 0 ? color.orange : na
topswitch = 0
topswitch := sellSignal ? 0 : (not newHighCondition == 0) and trend == 1 ? 1 : topswitch[1]
reversalsignal = topswitch[1] == 1 and topswitch == 0 ? true : false
var newLowCondition = 0
lower = ta.lowest(newHighSensitivity)
if lower == lower[newHighSensitivity / 10]
newLowCondition := 0
newLowCondition
// lowerLevel:=0.0
if lower != lower[newHighSensitivity / 10] and close < lower[newHighSensitivity / 10]
newLowCondition := 1
newLowCondition
lowColor = newLowCondition == 0 ? color.orange : na
bottomswitch = 0
bottomswitch := buySignal ? 0 : (not newLowCondition == 0) and trend == -1 ? 1 : bottomswitch[1]
bottomreversalsignal = bottomswitch[1] == 1 and bottomswitch == 0 ? true : false
plotshape(reversalsignal, title='Sell', text='Sell', location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.new(color.red, 0), textcolor=color.new(color.white, 0))
plotshape(bottomreversalsignal, title='Buy', text='Buy', location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.new(color.green, 0), textcolor=color.new(color.white, 0))
//plot(higher, color=HighColor)
|
ATR-Stepped, Another New Adaptive Moving Average [Loxx] | https://www.tradingview.com/script/KUqzlSGC-ATR-Stepped-Another-New-Adaptive-Moving-Average-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 275 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("ATR-Stepped, Another New Adaptive Moving Average [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
adaptiveMovingAverage(float src, int length, atrper, mult)=>
float result = math.abs(src - nz(src[length]))
float effort = math.sum(ta.tr, length)
float alpha = effort != 0 ? result / effort : 0
float anama = 0.0
anama := (alpha * src) + ((1 - alpha) * nz(anama[1]))
float multout = mult
float atr = ta.atr(atrper)
float trig = anama
float stepSize = multout * atr
float _diff = trig - nz(trig[1])
trig := nz(trig[1]) + ((_diff < stepSize and _diff > -stepSize) ? 0 : (_diff / stepSize) * stepSize)
float sig = trig[1]
[trig, sig]
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(30, "Period", group = "Basic Settings")
filter = input.float(0.5, "ATR Multiple", minval = 0, group= "Basic Settings")
filterperiod = input.int(15, "ATR Period", minval = 0, group= "Basic Settings")
colorbars = input.bool(true, "Color bars?", group= "UI Options")
showSigs = input.bool(true, "Show Signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = ohlc4
haopen = float(na)
haopen := na(haopen[1]) ? (open + close) / 2 : (nz(haopen[1]) + nz(haclose[1])) / 2
hahigh =math.max(high, math.max(haopen, haclose))
halow = math.min(low, math.min(haopen, haclose))
hamedian = (hahigh + halow) / 2
hatypical = (hahigh + halow + haclose) / 3
haweighted = (hahigh + halow + haclose + haclose)/4
haaverage = (haopen + hahigh + halow + haclose)/4
float src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
[out, sig] = adaptiveMovingAverage(src, per, filterperiod, filter)
goLong_pre = ta.crossover(out, sig)
goShort_pre = ta.crossunder(out, sig)
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch
goLong = goLong_pre and ta.change(contSwitch)
goShort = goShort_pre and ta.change(contSwitch)
colorout = contSwitch == 1 ? greencolor : redcolor
barcolor(colorbars ? colorout : na)
plot(out, "ATRFANAMA", color = colorout, linewidth = 3)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="ATR-Stepped, Another New Adaptive Moving Average [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="ATR-Stepped, Another New Adaptive Moving Average [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}") |
"The Stocashi" - Stochastic RSI + Heikin-Ashi | https://www.tradingview.com/script/PbJeJTH4-The-Stocashi-Stochastic-RSI-Heikin-Ashi/ | CoffeeshopCrypto | https://www.tradingview.com/u/CoffeeshopCrypto/ | 740 | 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/
//This is just a fun script to give a different representation to the ever popular Stochastic RSI
//Even for me over the years the stochastic has been a difficult one to use in trading mearly beause of its choppy look.
//Since Heikin-Ashi Candles do such a powerful job in smoothing out the look of choppy markets,
//I decided to test it out on the look of the Stochastic RSI.
//From an initial visual standpoint it worked out WAY better than I thought but it seemed to need something more.
//I decided to use the PineScript "Color.From_Gradient" feature to give the Stochastic a more 3 dimentional look, which really brought the "old-school" indicator to life.
// © CoffeeshopCrypto
//@version=5
indicator("Stochastic RSI + Heikin-Ashi", shorttitle="Stocashi", overlay=false)
// Calculate the Stochastic RSI
src = input(close, title="Source")
smoothK = input.int(8, minval=1, title="Stochastic %K Smoothing", group = "Stocashi Inputs")
smoothD = input.int(3, minval=1, title="Stochastic %D Smoothing", group = "Stocashi Inputs")
lengthRSI = input.int(14, minval=1, title="RSI Length", group = "Stocashi Inputs")
rsi1 = ta.rsi(src, lengthRSI)
lengthStoch = input.int(14, minval=1, title="Stochastic Length", group = "Stocashi Inputs")
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK) - 50
d = ta.sma(k, smoothD)
// Calculate the Stochastic Heikin-Ashi candles
ha_open = (k[1] + d[1]) / 2
ha_close = (k + d + d + k) / 4
ha_high = math.max(k, math.max(ha_open, ha_close))
ha_low = math.min(k, math.min(ha_close, ha_open))
// Plot the Heikin-Ashi Stochastic RSI
down_colorbottom = input.color(#086e05, title="Bullish Move Start", inline = "Bullish / Bearish Momentum", group = "Bullish / Bearish Movement")
down_colortop = input.color(#8dc474, title="Bullish Move End", inline = "Bullish / Bearish Momentum", group = "Bullish / Bearish Movement")
up_color_top = input.color(#af0505, title="Bearish Move Start", inline = "Bullish / Bearish Momentum", group = "Bullish / Bearish Movement")
up_color_bottom = input.color(#e08e8e, title="Bearish Move End", inline = "Bullish / Bearish Momentum", group = "Bullish / Bearish Movement")
up_color_ob = input.color(color.rgb(255, 82, 82, 95), title="Overbough Level", inline = "OB/OS Levels", group = "Overbough / Oversould levels")
up_color_os = input.color(color.rgb(122, 255, 82, 95), title="Oversold Level", inline = "OB/OS Levels", group = "Overbough / Oversould levels")
gradientColourup = color.from_gradient(k, -50, 50, up_color_bottom, up_color_top)
//gradientColouruptop = color.from_gradient(k, -50, 30, up_color, down_color)
gradientColourdn = color.from_gradient(k, -50, 50, down_colorbottom, down_colortop)
//gradientColourdntop = color.from_gradient(k, -30, 50, up_color, down_color)
bar_color = ha_close >= ha_open ? gradientColourdn : gradientColourup
// Use the up and down colors in your script
//////////////////////////////////////////////
plotcandle(ha_open, ha_high, ha_low, ha_close,title= "Stochatic Heiken Ashi Gradient", color=bar_color, wickcolor = bar_color)
mindline = hline(0, color=#d47305a1)
line80 = hline(40, color=color.rgb(247, 143, 143, 66), linestyle = hline.style_dotted, editable = false)
overbought = hline(50, color=color.rgb(247, 143, 143, 66), linestyle = hline.style_dotted, editable = false)
linem10 = hline(-40, color=color.rgb(122, 255, 82, 66), linestyle = hline.style_dotted, editable = false)
oversold = hline(-50, color=color.rgb(122, 255, 82, 66), linestyle = hline.style_dotted, editable = false)
fill(line80, overbought, color = color.rgb(255, 82, 82, 95), title = "OB")
fill(linem10, oversold, color = color.rgb(122, 255, 82, 95), title = "OS") |
Pre-market Highs & Lows on regular trading hours (RTH) chart | https://www.tradingview.com/script/OMKhuwOC-Pre-market-Highs-Lows-on-regular-trading-hours-RTH-chart/ | twingall | https://www.tradingview.com/u/twingall/ | 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/
// Added feature to choose only to extend most recent session lines/labels to last bar index
// Fix to work on SPY, Indices (e.g. ES1!) and Stocks (14th Oct'23)
// © twingall
//@version=5
indicator("Pre-market Highs & Lows on RTH chart", overlay = true, max_bars_back = 2000)
showHighs = input.bool(true, "show pre-market high", inline ='1')
showLows = input.bool(true, "show pre-market low", inline ='2')
maxDayLines = input.int(3, minval = 1, title = "Previous Sessions to show")
extendSessChoice = input.string("Previous Only", "Previous Session Lines Extend Choice", options = ["Previous Only", "All", "None"], tooltip = "Extend session lines to last bar index, or have them stop at end of non market hours+input bars forward line length\n\nPrevious Only: only the last completed overnight session lines extend to the last bar index\n\nAll: all previous session lines extend to last bar index\n\nNone: all previous session lines stop at end of overnight session + input bars forward")
rthLineLen = input.int(22, minval=0, title= "(Line length: bars forward from RTH open)", tooltip ="This is only really designed for when chart is toggled to RTH (regular trading hours); i.e. if it were set to 0 on RTH chart you wouldn't see the lines")
showLabels = input.bool(true, "labels", group = 'formatting', inline ='1')
textCol = input.color(color.blue, "|| Color:", group = 'formatting', inline ='1')
textSize = input.string(size.normal, "Size:", options =[size.auto, size.tiny, size.small, size.normal, size.large, size.huge], group = 'formatting', inline ='1')
showLines = input.bool(true, "lines", group = 'formatting', inline ='2')
lineColH = input.color(color.green, "|| High line color:", group = 'formatting', inline ='2')
lineColL = input.color(color.red, "Low line color:", group = 'formatting', inline ='2')
lineWidth = input.int(1, "width", group = 'formatting', inline ='3')
_lineStyle = input.string("dotted", "linestyle", options =["arrow left" ,"solid", "dotted", "dashed"], group = 'formatting', inline ='3', tooltip ="only applies when chart is toggles to ETH(electronic trading hours)")
showdayDate = input.bool(true, "(show day/date on labels)",group = 'formatting', inline = '9')
showNascent = input.bool(true, "Plot realtime pre-Mkt Highest/Lowest", group = 'Plot Currently forming preMkt Highs/Lows', inline = '1', tooltip = "Only applies outside of Regular trading hours\n\nShows currently forming, dynamic Highest/Lowest of preMkt as we progress through the overnight session\n\nNote that if toggled to RTH chart, these nascent levels will not automatically/dynamically shift, but only change on a 'refresh' event (timeframe change, page refresh, indicator reload)")
colNascentHi = input.color(color.blue, "High line color: ", group = 'Plot Currently forming preMkt Highs/Lows', inline = '2')
colNascentLo = input.color(color.fuchsia, "Low line color: ", group = 'Plot Currently forming preMkt Highs/Lows', inline = '2')
_lineStyle2 = input.string("dotted", "| Line style:", options =["arrow left" ,"solid", "dotted", "dashed"], group = 'Plot Currently forming preMkt Highs/Lows', inline ='2')
inpRegTradHrs =input.session('0930-1600', 'Regular Session', group = 'Plot Currently forming preMkt Highs/Lows')
inputNonMktHrs =input.session('1600-0930', 'Non-Market Hours', group = 'Plot Currently forming preMkt Highs/Lows')
string lineStyle = switch _lineStyle
"arrow left" => line.style_arrow_left
"solid" => line.style_solid
"dotted" => line.style_dotted
"dashed" => line.style_dashed
colorNone = color.new(color.white, 100)
extendedTicker = ticker.modify(syminfo.ticker, session = session.extended)
//condition to see if our chart is toggled to electronic trading hours (ETH) or regular trading hours (RTH)
_7_00= timestamp('America/New_York', year, month, dayofmonth, 07, 00, 00) //arbitrary pre-market time used for the 'is RTH or is ETH' condition
outOfHoursClose = ta.valuewhen(time==_7_00, close,0)
isETH = not na(outOfHoursClose)
inNonMktHrs= not na(time(timeframe.period, inputNonMktHrs, "America/New_York"))
inRegSess =not na(time(timeframe.period, inpRegTradHrs, 'America/New_York'))
/// ~~FUNCTIONS~~
high() =>
var float result = na
if inNonMktHrs and not inNonMktHrs[1]
result:=high
else if inNonMktHrs
result:=math.max(result, high)
result
low() =>
var float result = na
if inNonMktHrs and not inNonMktHrs[1]
result:=low
else if inNonMktHrs
result:=math.min(result, low)
result
openTime(_sess)=>
var int _openTime = na
if _sess and not _sess[1]
_openTime := time
int result = _openTime
tickerExtHighest = request.security(extendedTicker, timeframe.period, high()[1], lookahead = barmerge.lookahead_on) // use [1], so it doesn't count 9:30 high as highest pre-market
tickerExtLowest = request.security(extendedTicker, timeframe.period, low()[1], lookahead = barmerge.lookahead_on) // use [1], so it doesn't count 9:30 low as lowest pre-market
nonMktHrsStart = request.security(extendedTicker, timeframe.period, openTime(inNonMktHrs))
MktHrsStart = request.security(extendedTicker, timeframe.period, openTime(inRegSess))
var line hiLine = na
var label hiLineLab =na
var array<line> hiLineArr = array.new<line>(0)
var array<label> hiLineLabArr = array.new<label>(0)
var float lastPreMktHi = na
var line loLine = na
var label loLineLab =na
var array<line> loLineArr = array.new<line>(0)
var array<label> loLineLabArr = array.new<label>(0)
var float lastPreMktLo = na
timeFormatFxn(int _time)=>
_dayNo = str.format_time(_time, "dd", "America/New_York")
dayNo = str.startswith(_dayNo, "0")? str.substring(_dayNo,1):_dayNo
var string superScript = na
if str.length(dayNo) == 1
superScript := str.endswith(dayNo, "1")?"ˢᵗ":str.endswith(dayNo, "2")?"ⁿᵈ":str.endswith(dayNo, "3")?"ʳᵈ":"ᵗʰ"
if str.length(dayNo) == 2 and str.startswith(dayNo, "1")
superScript :="ᵗʰ"
if str.length(dayNo)==2 and str.startswith(dayNo, "2")
superScript := str.endswith(dayNo, "1")?"ˢᵗ":str.endswith(dayNo, "2")?"ⁿᵈ":str.endswith(dayNo, "3")?"ʳᵈ":"ᵗʰ"
if str.length(dayNo)==2 and str.startswith(dayNo, "3")
superScript:= str.endswith(dayNo, "1")?"ˢᵗ":"ᵗʰ"
result = dayNo+ superScript
getDayOfWeekLabel(_time) =>
_dayofweek = dayofweek(_time, "America/New_York")
switch _dayofweek
1 => "Sun"
2 => "Mon"
3 => "Tue"
4 => "Wed"
5 => "Thu"
6 => "Fri"
7 => "Sat"
dayDateStr(_time)=>
string result = " " +getDayOfWeekLabel(_time) +" " + timeFormatFxn(_time)
rthLnLenTime = rthLineLen * 1000 * timeframe.in_seconds(timeframe.period)
var int x2 = na
if syminfo.type == 'stock' or syminfo.type == 'fund'? session.islastbar_regular: inNonMktHrs[1] and not inNonMktHrs
x2:=MktHrsStart[1]
if syminfo.type == 'stock' or syminfo.type == 'fund'? (session.isfirstbar_regular and showHighs): (inNonMktHrs[1] and not inNonMktHrs and showHighs)
lastPreMktHi:= tickerExtHighest
hiLine:=isETH?line.new(nonMktHrsStart, tickerExtHighest, extendSessChoice=="All"?last_bar_time:time, tickerExtHighest, xloc=xloc.bar_time, style= lineStyle,color =showLines?lineColH:colorNone, width =lineWidth):
line.new(time, tickerExtHighest, last_bar_time, tickerExtHighest, xloc=xloc.bar_time, style= line.style_dotted, color =showLines?lineColH:colorNone, width =lineWidth)
hiLineLab:=isETH?label.new(last_bar_time, tickerExtHighest, text=showLabels?str.tostring(tickerExtHighest)+ (showdayDate?dayDateStr(time):""):"", style = label.style_label_left,color = colorNone,textcolor =textCol, xloc=xloc.bar_time, size =textSize):
label.new(last_bar_time,tickerExtHighest, text=showLabels?str.tostring(tickerExtHighest)+ (showdayDate?dayDateStr(time):""):" ", style = label.style_label_left,color = colorNone,textcolor =textCol, xloc=xloc.bar_time, size =textSize)
array.push(hiLineArr, hiLine)
array.push(hiLineLabArr,hiLineLab)
if array.size(hiLineArr)>maxDayLines
line.delete(array.shift(hiLineArr))
label.delete(array.shift(hiLineLabArr))
if extendSessChoice=="Previous Only" and hiLineArr.size()>0
line.set_x2(hiLineArr.last(), last_bar_time)
if hiLineArr.size()>1
_2ndLstHiLn = hiLineArr.get(hiLineArr.size()-2) // getting 2nd last line & label, and setting line x2 to original line x1 + small line length; and setting label x position to the same
line.set_x2(_2ndLstHiLn, x2+rthLnLenTime)
_2ndLstHiLab = hiLineLabArr.get(hiLineLabArr.size()-2)
label.set_x(_2ndLstHiLab, x2+rthLnLenTime)
if extendSessChoice=="None" and hiLineArr.size()>0
lastHiLn = hiLineArr.last()
lastHiLnX1 = isETH?line.get_x2(lastHiLn):line.get_x1(lastHiLn)
line.set_x2(lastHiLn, lastHiLnX1+rthLnLenTime)
lastHiLab = hiLineLabArr.last()
label.set_x(lastHiLab, lastHiLnX1+rthLnLenTime)
if syminfo.type == 'stock' or syminfo.type == 'fund'? (session.isfirstbar_regular and showLows) : (inNonMktHrs[1] and not inNonMktHrs and showLows)
lastPreMktLo:= tickerExtLowest
loLine:=isETH?line.new(nonMktHrsStart, tickerExtLowest, extendSessChoice=="All"?last_bar_time:time, tickerExtLowest, xloc=xloc.bar_time, style= lineStyle,color =showLines?lineColL:colorNone, width =lineWidth):
line.new(time, tickerExtLowest, last_bar_time, tickerExtLowest, xloc=xloc.bar_time, style= line.style_dotted, color =showLines?lineColL:colorNone, width =lineWidth)
loLineLab:=isETH?label.new(last_bar_time, tickerExtLowest, text=showLabels?str.tostring(tickerExtLowest)+ (showdayDate?dayDateStr(time):""):"", style = label.style_label_left, color = colorNone, textcolor =textCol, xloc=xloc.bar_time, size =textSize):
label.new(last_bar_time,tickerExtLowest, text=showLabels?str.tostring(tickerExtLowest)+ (showdayDate?dayDateStr(time):""):" ", style = label.style_label_left, color = colorNone,textcolor =textCol, xloc=xloc.bar_time, size =textSize)
array.push(loLineArr, loLine)
array.push(loLineLabArr,loLineLab)
if array.size(loLineArr)>maxDayLines
line.delete(array.shift(loLineArr))
label.delete(array.shift(loLineLabArr))
if extendSessChoice=="Previous Only" and loLineArr.size()>0
line.set_x2(loLineArr.last(), last_bar_time)
if loLineArr.size()>1
_2ndLstLoLn = loLineArr.get(loLineArr.size()-2) // getting 2nd last line & label, and setting line x2 to original line x1 + small line length; and setting label x position to the same
line.set_x2(_2ndLstLoLn, x2+rthLnLenTime)
_2ndLstLoLab = loLineLabArr.get(loLineLabArr.size()-2)
label.set_x(_2ndLstLoLab, x2+rthLnLenTime)
if extendSessChoice=="None" and loLineArr.size()>0
lastLoLn = loLineArr.last()
lastLoLnX1 = isETH?line.get_x2(lastLoLn):line.get_x1(lastLoLn)
line.set_x2(lastLoLn, lastLoLnX1+rthLnLenTime)
lastLoLab = loLineLabArr.last()
label.set_x(lastLoLab, lastLoLnX1+rthLnLenTime)
//////////////// Nascent preMkt highs and lows : this will only show outside of regular trading hours, but should display on RTH chart dynamically through the overnight session
string lineStyle2 = switch _lineStyle2
"arrow left" => line.style_arrow_left
"solid" => line.style_solid
"dotted" => line.style_dotted
"dashed" => line.style_dashed
barsSinceRTHcloseETH = ta.barssince(inRegSess)
//turns out can only retrieve ETH price info from RTH toggled chart by using request.security_lower_tf (request.security() won't work)
timeDiff = timenow-last_bar_time
extHighsArr = request.security_lower_tf(extendedTicker, timeframe.period, timeDiff>0?high:0)
if timeDiff ==0
array.clear(extHighsArr)
highestOf = array.max(extHighsArr)
extLowsArr = request.security_lower_tf(extendedTicker, timeframe.period, timeDiff>0?low:0)
if timeDiff ==0
array.clear(extLowsArr)
lowestOf = array.min(extLowsArr)
_t_extHcurrRTH = request.security(extendedTicker, timeframe.period, ta.highest(high, barsSinceRTHcloseETH>0?barsSinceRTHcloseETH:1))
_t_extHcurrETH = ta.highest(high, barsSinceRTHcloseETH>0?barsSinceRTHcloseETH:1)
tickerExtHighestCurr = isETH? _t_extHcurrETH:math.max((timeDiff>0?highestOf:_t_extHcurrRTH),_t_extHcurrRTH) //math.max: account for the short period between 4pm 'close' and last bar of RTH 'close'
_t_extLcurrRTH = request.security(extendedTicker, timeframe.period, ta.lowest(low, barsSinceRTHcloseETH>0?barsSinceRTHcloseETH:1))
_t_extLcurrETH = ta.lowest(low, barsSinceRTHcloseETH>0?barsSinceRTHcloseETH:1)
tickerExtLowestCurr = isETH? _t_extLcurrETH: math.min((timeDiff>0?lowestOf:_t_extLcurrRTH),_t_extLcurrRTH) //math.min: account for the short period between 4pm 'close' and last bar of RTH 'close'
var line hiLineCurr = na, var label hiLineLabCurr =na
var line loLineCurr = na, var label loLineLabCurr =na
if isETH?barstate.islast and showNascent and not inRegSess: session.islastbar and showNascent //this could be simpler; but I left it in for the 'partial' functionality of plotting out-of-hours levels on RTH chart. I say 'partial' because levels only refresh on static/out-of-hours RTH chart when a refresh event occurs (timeframe or asset change, page refresh, indicator reload)
hiLineCurr:=isETH?line.new(bar_index, tickerExtHighestCurr, bar_index -barsSinceRTHcloseETH, tickerExtHighestCurr, style= lineStyle2, extend =extend.none,color =colNascentHi, width =lineWidth):
line.new(bar_index, tickerExtHighestCurr,bar_index+rthLineLen, tickerExtHighestCurr, style= line.style_dotted, extend =extend.none, color =color.blue, width =lineWidth)
loLineCurr:=isETH?line.new(bar_index, tickerExtLowestCurr, bar_index -barsSinceRTHcloseETH, tickerExtLowestCurr, style= lineStyle2, extend =extend.none,color =colNascentLo, width =lineWidth):
line.new(bar_index, tickerExtLowestCurr, bar_index+rthLineLen, tickerExtLowestCurr, style= line.style_dotted, extend =extend.none,color =color.red, width =lineWidth)
hiLineLabCurr:=isETH?label.new(bar_index,tickerExtHighestCurr, text=showLabels?str.tostring(tickerExtHighestCurr):"", style = label.style_label_left,color = colorNone,textcolor =textCol, size =textSize):
label.new(bar_index+rthLineLen,tickerExtHighestCurr, text=showLabels?str.tostring(tickerExtHighestCurr):"", style = label.style_label_left,color = colorNone,textcolor =textCol, size =textSize)
loLineLabCurr:=isETH?label.new(bar_index, tickerExtLowestCurr, text=showLabels?str.tostring(tickerExtLowestCurr):"", style = label.style_label_left,color = colorNone,textcolor =textCol, size =textSize):
label.new(bar_index+rthLineLen,tickerExtLowestCurr, text=showLabels?str.tostring(tickerExtLowestCurr):"", style = label.style_label_left,color = colorNone,textcolor =textCol, size =textSize)
if tickerExtHighestCurr!=tickerExtLowestCurr[1]
line.delete(hiLineCurr[1])
label.delete(hiLineLabCurr[1])
line.delete(loLineCurr[1])
label.delete(loLineLabCurr[1])
if isETH? showNascent and session.isfirstbar_regular: showNascent and session.isfirstbar
line.delete(hiLineCurr)
label.delete(hiLineLabCurr)
line.delete(loLineCurr)
label.delete(loLineLabCurr)
//Alerts:
alertcondition(ta.crossover(high, lastPreMktHi), "Cross OVER pre Mkt High", "price crossed above Pre market high") // lastPreMktHi & lastPreMktLo will refresh each day at start of regular trading hours
alertcondition(ta.crossunder(low, lastPreMktLo), "cross UNDER pre Mkt Low", "price crossed below Pre market low")
///****************** debugging
// var Table = table.new(position.top_right, columns = 14, rows = 5, bgcolor = color.orange, border_width = 1)
// if barstate.islast
// table.cell(Table, 0, 0, "DEBUG TABLE", bgcolor=color.blue)
// table.cell(Table, 1, 0, "tickerExtHighestCurr = "+str.tostring(tickerExtHighestCurr))
// table.cell(Table, 1, 1, "inRegSess = " +str.tostring(inRegSess))
// table.cell(Table, 0, 2, "lowestOf = " +str.tostring(lowestOf),bgcolor = color.yellow)
// table.cell(Table, 2, 2, "session.islastbar = " +str.tostring(session.islastbar),bgcolor = color.green)
// table.cell(Table, 0, 3, "isETH = " +str.tostring(isETH),bgcolor = color.green)//
// table.cell(Table, 1, 2, "lastPreMktHi = " +str.tostring(lastPreMktHi, format.mintick))
// table.cell(Table, 1, 3, "lastPreMktLo = " +str.tostring(lastPreMktLo, format.mintick))
// table.cell(Table, 2, 3, "syminfo type: " +str.tostring(syminfo.type))
// table.cell(Table, 2, 4, "session type: " +str.tostring(syminfo.session==session.extended?"extended":syminfo.session==session.regular?"regular":"other"))
|
The Strat [LuxAlgo] | https://www.tradingview.com/script/AkpEZFyO-The-Strat-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,683 | 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("The Strat [LuxAlgo]"
, overlay = true
, max_lines_count = 500
, max_labels_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
asNum = input(true, 'Show Numbers On Chart')
asCandle = input(true, 'Color Candles')
//Search
customCombo = input.string('', 'Combo', group = 'Custom Combo Search', inline = 'highlight')
highlightCss = input(#2157f3, '' , group = 'Custom Combo Search', inline = 'highlight')
//Pivot Machine Gun
showPmgLbl = input(false, 'Show Labels' , group = 'Pivot Machine Gun')
minSeq = input.int(3, 'Min Sequence Length', minval = 1, group = 'Pivot Machine Gun')
minBreak = input.int(3, 'Min Breaks', minval = 1 , group = 'Pivot Machine Gun')
showPmgLvl = input(true, 'Show Levels' , group = 'Pivot Machine Gun', inline = 'pmg_lvl')
bullPmg = input(#0cb51a, '' , group = 'Pivot Machine Gun', inline = 'pmg_lvl')
bearPmg = input(#ff1100, '' , group = 'Pivot Machine Gun', inline = 'pmg_lvl')
//Pivot Combos
showPivotCombos = input(true, 'Display Pivot Combos', group = 'Pivot Combos')
length = input(14, 'Pivot Lookback' , group = 'Pivot Combos')
rightBars = input.int(1, 'Right Bars Scan', minval = 0, group = 'Pivot Combos')
leftBars = input.int(1, 'Left Bars Scan', minval = 0 , group = 'Pivot Combos')
//Dashboard
showDash = input(false, 'Show Dashboard', group = 'Dashboard')
showNum = input(true, 'Number Counter' , group = 'Dashboard')
showPivot = input(true, 'Pivot Combos' , inline = 'dashpivot', group = 'Dashboard')
pivotAsPercent = input(true, '%' , inline = 'dashpivot', group = 'Dashboard')
showTop = input(3, 'Pivot Combos Rows' , group = 'Dashboard')
showMTF = input(true, 'Show MTF', 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')
//------------------------------------------------------------------------------
//Functions
//-----------------------------------------------------------------------------{
n = bar_index
numbers()=>
ins = high < high[1] and low > low[1] ? 1 : 0
dir = high > high[1] and low > low[1] and low < high[1] ? 2
: high < high[1] and low < low[1] and high > low[1] ? -2
: 0
out = high > high[1] and low < low[1] ? 3 : 0
[ins, dir, out]
pmg(bull, show_lines, css)=>
var csum = 0
condition = bull ? high < high[1] : low > low[1]
value = bull ? high : low
csum := condition ? csum + 1 : 0
breaks = 0
if csum < csum[1] and csum[1] + 1 >= minSeq
for i = 1 to csum[1] + 1
if (bull ? high[i] > high : low > low[i])
break
else
breaks += 1
if show_lines
if breaks >= minBreak
for i = 1 to breaks
line.new(n[i], value[i], n, value[i]
, color = css)
breaks
pivot_combo(condition, ins, dir, key, value, css, style)=>
if condition
txt = '|'
for i = leftBars to -rightBars
txt += ins[length+i] ? '1|'
: dir[length+i] == 2 ? '2|'
: dir[length+i] == -2 ? '-2|'
: '3|'
if showPivotCombos
label.new(n - length, condition, txt, color = #00000000
, style = style
, textcolor = css
, size = size.small)
if array.includes(key, txt)
idx = array.indexof(key, txt)
array.set(value, idx, array.get(value, idx) + 1)
else
array.push(key, txt)
array.push(value, 1)
rank_pivot_combo(combo_num, combo_type, tb, col, css, table_size)=>
//Pivot Low
sorted_idx = array.sort_indices(combo_num, order.descending)
len = math.min(showTop-1, array.size(sorted_idx) - 1)
for i = 0 to len
tb.cell(col, 2 + i
, array.get(combo_type, array.get(sorted_idx, i))
, text_color = css
, text_size = table_size)
num = array.get(combo_num, array.get(sorted_idx, i))
den = pivotAsPercent ? array.sum(combo_num) / 100 : 1
tb.cell(col + 1, 2 + i
, str.tostring(num / den, '#.##')
, text_color = css
, text_size = table_size)
len
//-----------------------------------------------------------------------------}
//Strat numbering
//-----------------------------------------------------------------------------{
[ins, dir, out] = numbers()
//Count
ins_count = ta.cum(ins)
dirup_count = ta.cum(math.max(dir / 2, 0))
dirdn_count = ta.cum(math.max(-dir / 2, 0))
out_count = ta.cum(out / 3)
total_count = (ins_count + dirup_count + dirdn_count + out_count) / 100
//MTF
[ins1, dir1, out1] = request.security(syminfo.tickerid, '1', numbers())
[ins15, dir15, out15] = request.security(syminfo.tickerid, '15', numbers())
[ins60, dir60, out60] = request.security(syminfo.tickerid, '60', numbers())
[insD, dirD, outD] = request.security(syminfo.tickerid, 'D', numbers())
[insW, dirW, outW] = request.security(syminfo.tickerid, 'W', numbers())
//-----------------------------------------------------------------------------}
//Pivot machine gun
//-----------------------------------------------------------------------------{
bull_pmg = 0
bear_pmg = 0
if showPmgLvl or showPmgLbl
bull_pmg := pmg(1, showPmgLvl, bullPmg) //Bullish pmg
bear_pmg := pmg(0, showPmgLvl, bearPmg) //Bearish pmg
//-----------------------------------------------------------------------------}
//Custom combo search
//-----------------------------------------------------------------------------{
custom_combo = false
if customCombo != ''
str_src = str.replace_all(customCombo, '-', '')
len = str.length(str_src)
txt = ''
max = high
min = low
for i = 0 to len-1
num = ins[i] ? '1'
: dir[i] == 2 ? '2'
: dir[i] == -2 ? '-2'
: '3'
txt := num + txt
max := math.max(high[i], max)
min := math.min(low[i], min)
if txt == customCombo
box.new(n-len+1, max, n, min
, border_color = highlightCss
, bgcolor = na)
custom_combo := true
//-----------------------------------------------------------------------------}
//Label pivots
//-----------------------------------------------------------------------------{
var ph_combo_type = array.new_string(0)
var ph_combo_num = array.new_int(0)
var pl_combo_type = array.new_string(0)
var pl_combo_num = array.new_int(0)
ph = ta.pivothigh(length, length)
pl = ta.pivotlow(length, length)
//Pivot high combo
pivot_combo(ph
, ins
, dir
, ph_combo_type
, ph_combo_num
, color.red
, label.style_label_down)
//Pivot low combo
pivot_combo(pl
, ins
, dir
, pl_combo_type
, pl_combo_num
, color.teal
, label.style_label_up)
//-----------------------------------------------------------------------------}
//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, 9, math.max(showTop + 3, 6)
, bgcolor = #1e222d
, border_color = #373a46
, border_width = 1
, frame_color = #373a46
, frame_width = 1)
if barstate.isfirst and showDash
if showPivot
tb.cell(0, 0, 'Pivots Combo', text_color = color.white, text_size = table_size)
tb.merge_cells(0, 0, 3, 0)
tb.cell(0, 1, 'Combo', text_color = color.teal, text_size = table_size)
tb.cell(1, 1, pivotAsPercent ? '%' : 'Count', text_color = color.teal, text_size = table_size)
tb.cell(2, 1, 'Combo', text_color = color.red , text_size = table_size)
tb.cell(3, 1, pivotAsPercent ? '%' : 'Count', text_color = color.red , text_size = table_size)
//Merge Cells
tb.merge_cells(0, showTop+2, 1, showTop+2)
tb.merge_cells(2, showTop+2, 3, showTop+2)
if showNum
tb.cell(4, 0, 'Numbers Counter', text_color = color.white, text_size = table_size)
tb.merge_cells(4, 0, 7, 0)
tb.cell(5, 1, 'Count', text_color = color.white, text_size = table_size)
tb.merge_cells(5, 1, 6, 1)
tb.cell(7, 1, '%', text_color = color.white, text_size = table_size)
//Merge Cells
tb.merge_cells(5, 2, 6, 2)
tb.merge_cells(5, 3, 6, 3)
tb.merge_cells(5, 4, 6, 4)
tb.merge_cells(5, 5, 6, 5)
if showMTF
tb.cell(8, 0, 'MTF', text_color = color.white, text_size = table_size)
var max_len = 0
if barstate.islast and showDash
if showPivot
//Pivot Low
rank_pivot_combo(pl_combo_num, pl_combo_type, tb, 0, color.teal, table_size)
//Pivot High
rank_pivot_combo(ph_combo_num, ph_combo_type, tb, 2, color.red, table_size)
//Pivot cells
tb.cell(0, showTop+2, 'Pivot Low', text_color = color.teal, text_size = table_size)
tb.cell(2, showTop+2, 'Pivot High', text_color = color.red, text_size = table_size)
if showNum
tb.cell(4, 2, '1', text_color = color.white, text_size = table_size)
tb.cell(5, 2, str.tostring(ins_count), text_color = color.white, text_size = table_size)
tb.cell(7, 2, str.tostring(ins_count / total_count, '#.##'), text_color = color.white, text_size = table_size)
tb.cell(4, 3, '2', text_color = color.white, text_size = table_size)
tb.cell(5, 3, str.tostring(dirup_count), text_color = color.white, text_size = table_size)
tb.cell(7, 3, str.tostring(dirup_count / total_count, '#.##'), text_color = color.white, text_size = table_size)
tb.cell(4, 4, '-2', text_color = color.white, text_size = table_size)
tb.cell(5, 4, str.tostring(dirdn_count), text_color = color.white, text_size = table_size)
tb.cell(7, 4, str.tostring(dirdn_count / total_count, '#.##'), text_color = color.white, text_size = table_size)
tb.cell(4, 5, '3', text_color = color.white, text_size = table_size)
tb.cell(5, 5, str.tostring(out_count), text_color = color.white, text_size = table_size)
tb.cell(7, 5, str.tostring(out_count / total_count, '#.##'), text_color = color.white, text_size = table_size)
if showMTF
tb.cell(8, 1, str.format('1m ({0})', ins1 + dir1 + out1) , text_color = color.white, text_size = table_size, text_halign = text.align_right)
tb.cell(8, 2, str.format('15m ({0})', ins15 + dir15 + out15) , text_color = color.white, text_size = table_size, text_halign = text.align_right)
tb.cell(8, 3, str.format('1h ({0})', ins60 + dir60 + out60) , text_color = color.white, text_size = table_size, text_halign = text.align_right)
tb.cell(8, 4, str.format('D ({0})', insD + dirD + outD) , text_color = color.white, text_size = table_size, text_halign = text.align_right)
tb.cell(8, 5, str.format('W ({0})', insW + dirW + outW) , text_color = color.white, text_size = table_size, text_halign = text.align_right)
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
//Plot as candles
barcolor(dir == 2 ? color.teal : dir == -2 ? color.red : na)
plotcandle(high, high, low, low
, bordercolor = asCandle and out and close > open ? color.teal : asCandle and out and close < open ? color.red : na
, color = na
, wickcolor = na
, display = display.all - display.status_line)
plotcandle(open, high, low, close
, wickcolor = asCandle and ins and close > open ? color.teal : asCandle and ins and close < open ? color.red : na
, color = na
, bordercolor = na
, display = display.all - display.status_line)
//Plot as numbers
plotchar(ins and close > open and asNum, 'Bullish Inside', '1', location.belowbar, color.teal)
plotchar(ins and close < open and asNum, 'Bearish Inside', '1', location.abovebar, color.red)
plotchar(dir == 2 and asNum, 'Directional Upward', '2', location.belowbar, color.teal)
plotchar(dir == -2 and asNum, 'Directional Downward', '2', location.abovebar, color.red)
plotchar(out and close > open and asNum, 'Bullish Outside', '3', location.belowbar, color.teal)
plotchar(out and close < open and asNum, 'Bearish Outside', '3', location.abovebar, color.red)
//Plot pmg
plotchar(bull_pmg >= minBreak and showPmgLbl, 'Bull PMG', '🔫', location.abovebar)
plotchar(bear_pmg >= minBreak and showPmgLbl, 'Bear PMG', '🔫', location.belowbar)
//-----------------------------------------------------------------------------}
//Alerts
//-----------------------------------------------------------------------------{
//Numbers
alertcondition(ins , '1 Inside Bar' , 'Inside bar detected')
alertcondition(dir == 2 , '2 Directional Bar' , 'Upside directional bar detected')
alertcondition(dir == -2, '-2 Directional Bar', 'Downside directional bar detected')
alertcondition(out , '3 Directional Bar' , 'Outside bar detected')
//Detected Combo
alertcondition(custom_combo, 'Detected Combo' , 'Custom combo detected')
//PMG's
alertcondition(bull_pmg, 'Bullish PMG' , 'Bullish PMG detected')
alertcondition(bear_pmg, 'Bearish PMG' , 'Bearish PMG detected')
//-----------------------------------------------------------------------------} |
Moving Averages + Premarket High/Low + Yesterday High/Low V2 | https://www.tradingview.com/script/SkwGgW8d-Moving-Averages-Premarket-High-Low-Yesterday-High-Low-V2/ | carsonhughes | https://www.tradingview.com/u/carsonhughes/ | 26 | 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/
// © convicted
//@version=5
indicator(title='MovingAvg', shorttitle='MovingAvg', overlay=true)
//Yesterday high and low
bool preHours = (hour == 4 or hour >= 4) and (hour < 9 and minute <= 30)
bool marketHours = (hour >= 9 and minute >= 30) and hour < 16
bool afterHours = hour >= 16 and (hour <= 20 or hour == 20)
//Current High And Low
currentdayhigh = request.security(syminfo.tickerid, 'D', high[0])
currentdaylow = request.security(syminfo.tickerid, 'D', low[0])
//Yesterday high and low
previousdayhigh = request.security(syminfo.tickerid, 'D', high[1])
previousdaylow = request.security(syminfo.tickerid, 'D', low[1])
if marketHours
previousdayhigh := previousdayhigh
previousdaylow := previousdaylow
if preHours
previousdayhigh := currentdayhigh
previousdaylow := currentdaylow
if afterHours
previousdayhigh := currentdayhigh
previousdaylow := currentdaylow
//Premarket high and low
t = time('1440', '0400-0930:23456') // 1440 is the number of minutes in a whole day.
is_first = na(t[1]) and not na(t) or t[1] < t
ending_hour = 9
ending_minute = 30
pm_high = float(na)
pm_low = float(na)
k = int(na)
if is_first and barstate.isnew and (hour < ending_hour or hour >= 0400 or hour == ending_hour and minute < ending_minute)
pm_high := high
pm_low := low
pm_low
else
pm_high := pm_high[1]
pm_low := pm_low[1]
pm_low
if high > pm_high and (hour < ending_hour or hour >= 0400 or hour == ending_hour and minute < ending_minute)
pm_high := high
pm_high
if low < pm_low and (hour < ending_hour or hour >= 0400 or hour == ending_hour and minute < ending_minute)
pm_low := low
pm_low
LastOnly = true
if LastOnly == true
k := -9999
k
else
k := 0
k
//Just a variable here for the label coordinates
td = time - time[100]
//Previous day high and low lines
plot(previousdayhigh, style=plot.style_line, title='Yesterday High', color=color.new(#e8f287, 0), linewidth=1, trackprice=true, offset=k)
plot(previousdaylow, style=plot.style_line, title='Yesterday Low', color=color.new(#e8f287, 0), linewidth=1, trackprice=true, offset=k)
//Premarket high and low lines
plot(pm_high, style=plot.style_line, title='Premarket High', trackprice=true, color=color.new(#64ffda, 0), linewidth=1, offset=k)
pmh = label.new(x=time + td, y=pm_high, xloc=xloc.bar_time, style=label.style_none, textcolor=#64ffda, size=size.small, textalign=text.align_right)
label.delete(pmh[1])
plot(pm_low, style=plot.style_line, title='Premarket Low', trackprice=true, color=color.new(#64ffda, 0), linewidth=1, offset=k)
pml = label.new(x=time + td, y=pm_low, xloc=xloc.bar_time, style=label.style_none, textcolor=#64ffda, size=size.small, textalign=text.align_right)
label.delete(pml[1])
//PLOT EMAs AND VWAP
ema9 = ta.ema(close, 9)
expo9 = if (timeframe.in_seconds() <= timeframe.in_seconds("65"))
ema9
else
na
plot(series=expo9, title="EMA 9", color= #e8f287, linewidth=1)
ema21 = ta.ema(close, 21)
expo21 = if (timeframe.in_seconds() <= timeframe.in_seconds("65"))
ema21
else
na
plot(series=expo21, title="EMA 21", color= #e2affc, linewidth=1)
ema50 = ta.ema(close, 50)
expo50 = if (timeframe.in_seconds() <= timeframe.in_seconds("65"))
ema50
else
na
//plot(series=expo50, title="EMA 50", color= #ffec68, linewidth=1)
ema100 = ta.ema(close, 100)
expo100 = if (timeframe.in_seconds() <= timeframe.in_seconds("65"))
ema100
else
na
//plot(series=expo100, title="EMA 100", color= #22ab94, linewidth=1)
ema200 = ta.ema(close, 200)
expo200 = if (timeframe.in_seconds() <= timeframe.in_seconds("65"))
ema200
else
na
plot(series=expo200, title="EMA 200", color= #2d6a84 , linewidth=1)
vwap = ta.vwap(close)
VWAP = if (timeframe.in_seconds() <= timeframe.in_seconds("65"))
vwap
else
na
//plot(series=VWAP, title="VWAP", color= #ffec68, linewidth=1)
//EXPO MOVING AVERAGES (DAILY+)
sma21 = ta.sma(close, 21)
simple21 = if (timeframe.in_seconds() >= timeframe.in_seconds("120"))
sma21
else
na
plot(series=simple21, title="SMA 21", color= #e8f287, linewidth=1)
sma50 = ta.sma(close, 50)
simple50 = if (timeframe.in_seconds() >= timeframe.in_seconds("120"))
sma50
else
na
plot(series=simple50, title="SMA 50", color= #e2affc, linewidth=1)
sma100 = ta.sma(close, 100)
simple100 = if (timeframe.in_seconds() >= timeframe.in_seconds("120"))
sma100
else
na
plot(series=simple100, title="SMA 100", color= #a6e4fc, linewidth=1)
sma200 = ta.sma(close, 200)
simple200 = if (timeframe.in_seconds() >= timeframe.in_seconds("120"))
sma200
else
na
plot(series=simple200, title="SMA 200", color= #2d6a84, linewidth=1) |
2B Reversal Pattern (Expo) | https://www.tradingview.com/script/dHb3Hn12-2B-Reversal-Pattern-Expo/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 4,870 | 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("2B Reversal Pattern (Expo)",overlay=true,max_lines_count=500)
// ~~ ToolTips {
t1 = "Set the pivot period."
t2 = "Set the maximum bars until the pattern should be completed. This means establishing a limit on the number of bars allowed for the completion of the pattern. A high value returns more signals."
t3 = "Set the minimum bars before the breakout. This means establishing a minimum number of bars that must be completed before the breakout. A low value returns more signals."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Inputs {
prd = input.int(20, title="Period",minval=1, tooltip=t1)
max = input.int(10, title="Maximum Break Length",minval=1, tooltip=t2)
min = input.int(3, title="Minimum Break Length",minval=1, tooltip=t3)
bUp = input.color(#6ce5a0,"", inline="col"), bDn = input.color(#f23645,"", inline="col"), pCol = input.color(color.new(color.aqua,0),"",inline="col")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Variables {
b = bar_index
var ph = float(na)
var pl = float(na)
var phL = int(na)
var plL = int(na)
var bo = float(na)
var boL= int(na)
breakoutup = false
breakoutdn = false
var array<line> lines = array.new<line>(0)
var active= line(na)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Pivots {
pvtHi = ta.pivothigh(high,prd,prd)
pvtLo = ta.pivotlow(low,prd,prd)
if pvtHi
ph := high[prd]
phL:= b[prd]
if pvtLo
pl := low[prd]
plL:= b[prd]
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Pattern Detection {
if ta.crossover(close,ph)
bo := low
boL:= b
lines.push(line.new(phL,ph,b,ph,color=pCol,style=line.style_dashed))
ph := float(na)
if ta.crossunder(close,pl)
bo := high
boL:= b
lines.push(line.new(plL,pl,b,pl,color=pCol,style=line.style_dashed))
pl := float(na)
if ta.crossunder(close,bo) and b-boL<=max and b-boL>=min
line.delete(active)
lines.push(line.new(boL,bo,b,bo,color=bDn,style=line.style_solid,width=2))
breakoutdn := true
bo := float(na)
if ta.crossover(close,bo) and b-boL<=max and b-boL>=min
line.delete(active)
lines.push(line.new(boL,bo,b,bo,color=bUp,style=line.style_solid,width=2))
breakoutup := true
bo := float(na)
if ta.cross(close,bo)
bo := float(na)
p2 = lines.pop()
line.delete(p2)
if not na(bo)
active := line.new(boL,bo,b,bo,color=pCol,style=line.style_solid,width=2)
line.delete(active[1])
if b-boL>max
bo := float(na)
p2 = lines.pop()
line.delete(p2)
line.delete(active)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plots {
plotshape(breakoutup?low:na, title="Breakout Up", color=bUp, style=shape.triangleup,location=location.belowbar,size=size.small)
plotshape(breakoutdn?high:na, title="Breakout Down", color=bDn, style=shape.triangledown,location=location.abovebar,size=size.small)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Alerts {
alertcondition(breakoutup, 'Breakout Up', 'Breakout Up')
alertcondition(breakoutdn, 'Breakout Down', 'Breakout Down')
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} |
Correlation Matrix + Heatmap - By Leviathan | https://www.tradingview.com/script/uy1LMmRg-Correlation-Matrix-Heatmap-By-Leviathan/ | LeviathanCapital | https://www.tradingview.com/u/LeviathanCapital/ | 671 | 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("Correlation Matrix - By Leviathan")
length = input.int(50, 'Correlation Length', tooltip='The number of bars back used to calculate correlation')
change = input.int(20, 'Price Change Length', tooltip = 'The number of bars back used to calculate the price change. Eg. If the Price Change Length number is 10, the script will calculate the price increase/decrease from 10 bars ago.')
tf = input.timeframe('', 'Timeframe')
hmct = input.string('Gradient', 'Heatmap Colors', options = ['Custom', 'Gradient'])
showchg = input.bool(false, 'Price Change', inline='1')
heatmap = input.bool(true, 'Heatmap', inline='1')
// Symbol inputs
a = input.symbol('BINANCE:BTCUSDT', 'Asset 1', group = 'SYMBOLS')
b = input.symbol('BINANCE:ETHUSDT', 'Asset 2', group = 'SYMBOLS')
c = input.symbol('BINANCE:BNBUSDT', 'Asset 3', group = 'SYMBOLS')
d = input.symbol('BINANCE:AVAXUSDT', 'Asset 4', group = 'SYMBOLS')
e = input.symbol('BINANCE:ADAUSDT', 'Asset 5', group = 'SYMBOLS')
f = input.symbol('BINANCE:MATICUSDT', 'Asset 6', group = 'SYMBOLS')
g = input.symbol('BINANCE:WOOUSDT', 'Asset 7', group = 'SYMBOLS')
h = input.symbol('BINANCE:SOLUSDT', 'Asset 8', group = 'SYMBOLS')
i = input.symbol('BINANCE:DOTUSDT', 'Asset 9', group = 'SYMBOLS')
j = input.symbol('SP:SPX', 'Asset 10', group = 'SYMBOLS')
// Appearance
cellh = input.int(8, 'Cell Height', group = 'APPEARANCE')
cellw = input.int(8, 'Cell Width', group = 'APPEARANCE')
valuecol = input.color(color.white, 'Value Color', group = 'APPEARANCE')
textcol = input.color(color.white, 'Label Color', group = 'APPEARANCE')
tablecol = input.color(color.rgb(25, 24, 24), 'Table Color', group = 'APPEARANCE')
fullsym = input.bool(false, 'Full Pair Label')
// Defining colors for the heatmap
gr1 = input.color(#3179f5, 'Gradient', group = 'HEATMAP COLORS', inline='gr')
gr2 = input.color(color.rgb(25, 24, 24), '', group = 'HEATMAP COLORS', inline='gr')
corr1 = input.color(color.rgb(179, 14, 29) , '', inline='1', group = 'HEATMAP COLORS')
corr2 = input.color(color.rgb(201, 46, 44) , '', inline='1', group = 'HEATMAP COLORS')
corr3 = input.color(color.rgb(223, 78, 59) , '', inline='1', group = 'HEATMAP COLORS')
corr4 = input.color(color.rgb(235, 108, 77) , '', inline='1', group = 'HEATMAP COLORS')
corr5 = input.color(color.rgb(247, 139, 96) , '', inline='1', group = 'HEATMAP COLORS')
corr6 = input.color(color.rgb(252, 169, 115), '', inline='2', group = 'HEATMAP COLORS')
corr7 = input.color(color.rgb(253, 188, 129), '', inline='2', group = 'HEATMAP COLORS')
corr8 = input.color(color.rgb(253, 207, 143), '', inline='2', group = 'HEATMAP COLORS')
corr9 = input.color(color.rgb(255, 215, 154), '', inline='2', group = 'HEATMAP COLORS')
corr10 = input.color(color.rgb(220, 169, 129), '', inline='2', group = 'HEATMAP COLORS')
corr11 = input.color(color.rgb(168, 198, 218), '', inline='3', group = 'HEATMAP COLORS')
corr12 = input.color(color.rgb(135, 168, 189), '', inline='3', group = 'HEATMAP COLORS')
corr13 = input.color(color.rgb(101, 139, 159), '', inline='3', group = 'HEATMAP COLORS')
corr14 = input.color(color.rgb(68, 110, 129) , '', inline='3', group = 'HEATMAP COLORS')
corr15 = input.color(color.rgb(60, 98, 115) , '', inline='3', group = 'HEATMAP COLORS')
corr16 = input.color(color.rgb(53, 87, 101) , '', inline='4', group = 'HEATMAP COLORS')
corr17 = input.color(color.rgb(47, 75, 88) , '', inline='4', group = 'HEATMAP COLORS')
corr18 = input.color(color.rgb(40, 64, 74) , '', inline='4', group = 'HEATMAP COLORS')
corr19 = input.color(color.rgb(34, 53, 61) , '', inline='4', group = 'HEATMAP COLORS')
corr20 = input.color(color.rgb(68, 92, 220) , '', inline='4', group = 'HEATMAP COLORS')
// Getting data
[asset1c, base1, ticker1] = request.security(a, tf, [close, syminfo.basecurrency, syminfo.ticker])
[asset2c, base2, ticker2] = request.security(b, tf, [close, syminfo.basecurrency, syminfo.ticker])
[asset3c, base3, ticker3] = request.security(c, tf, [close, syminfo.basecurrency, syminfo.ticker])
[asset4c, base4, ticker4] = request.security(d, tf, [close, syminfo.basecurrency, syminfo.ticker])
[asset5c, base5, ticker5] = request.security(e, tf, [close, syminfo.basecurrency, syminfo.ticker])
[asset6c, base6, ticker6] = request.security(f, tf, [close, syminfo.basecurrency, syminfo.ticker])
[asset7c, base7, ticker7] = request.security(g, tf, [close, syminfo.basecurrency, syminfo.ticker])
[asset8c, base8, ticker8] = request.security(h, tf, [close, syminfo.basecurrency, syminfo.ticker])
[asset9c, base9, ticker9] = request.security(i, tf, [close, syminfo.basecurrency, syminfo.ticker])
[asset10c, base10, ticker10] = request.security(j, tf, [close, syminfo.basecurrency, syminfo.ticker])
// Getting ticker names
tickera = fullsym or base1 =='' ? ticker1 : base1
tickerb = fullsym or base2 =='' ? ticker2 : base2
tickerc = fullsym or base3 =='' ? ticker3 : base3
tickerd = fullsym or base4 =='' ? ticker4 : base4
tickere = fullsym or base5 =='' ? ticker5 : base5
tickerf = fullsym or base6 =='' ? ticker6 : base6
tickerg = fullsym or base7 =='' ? ticker7 : base7
tickerh = fullsym or base8 =='' ? ticker8 : base8
tickeri = fullsym or base9 =='' ? ticker9 : base9
tickerj = fullsym or base10 =='' ? ticker10 : base10
// Calculating price change
f_calc_change(asset) =>
((asset - asset[change]) / asset[change]) * 100
asset1_chg = f_calc_change(asset1c)
asset2_chg = f_calc_change(asset2c)
asset3_chg = f_calc_change(asset3c)
asset4_chg = f_calc_change(asset4c)
asset5_chg = f_calc_change(asset5c)
asset6_chg = f_calc_change(asset6c)
asset7_chg = f_calc_change(asset7c)
asset8_chg = f_calc_change(asset8c)
asset9_chg = f_calc_change(asset9c)
asset10_chg = f_calc_change(asset10c)
// Calculating correlation
f_calc_corr(a1, a2) =>
ta.correlation(a1, a2, length)
float aa = f_calc_corr(asset1c, asset1c), float ab = f_calc_corr(asset1c, asset2c), float ac = f_calc_corr(asset1c, asset3c), float ad = f_calc_corr(asset1c, asset4c), float ae = f_calc_corr(asset1c, asset5c), float ch = f_calc_corr(asset3c, asset8c)
float bb = f_calc_corr(asset2c, asset2c), float bc = f_calc_corr(asset2c, asset3c), float bd = f_calc_corr(asset2c, asset4c), float be = f_calc_corr(asset2c, asset5c), float bf = f_calc_corr(asset2c, asset6c), float dj = f_calc_corr(asset4c, asset10c)
float cc = f_calc_corr(asset3c, asset3c), float cd = f_calc_corr(asset3c, asset4c), float ce = f_calc_corr(asset3c, asset5c), float cf = f_calc_corr(asset3c, asset6c), float cg = f_calc_corr(asset3c, asset7c), float ci = f_calc_corr(asset3c, asset9c)
float dd = f_calc_corr(asset4c, asset4c), float de = f_calc_corr(asset4c, asset5c), float df = f_calc_corr(asset4c, asset6c), float dg = f_calc_corr(asset4c, asset7c), float dh = f_calc_corr(asset4c, asset8c), float di = f_calc_corr(asset4c, asset9c)
float ee = f_calc_corr(asset5c, asset5c), float ef = f_calc_corr(asset5c, asset6c), float eg = f_calc_corr(asset5c, asset7c), float eh = f_calc_corr(asset5c, asset8c), float ei = f_calc_corr(asset5c, asset9c), float cj = f_calc_corr(asset3c, asset10c)
float ff = f_calc_corr(asset6c, asset6c), float fg = f_calc_corr(asset6c, asset7c), float fh = f_calc_corr(asset6c, asset8c), float fi = f_calc_corr(asset6c, asset9c), float fj = f_calc_corr(asset6c, asset10c)
float gg = f_calc_corr(asset7c, asset7c), float gh = f_calc_corr(asset7c, asset8c), float gi = f_calc_corr(asset7c, asset9c), float gj = f_calc_corr(asset7c, asset10c), float bi = f_calc_corr(asset2c, asset9c)
float hh = f_calc_corr(asset8c, asset8c), float hi = f_calc_corr(asset8c, asset9c), float hj = f_calc_corr(asset8c, asset10c), float bj = f_calc_corr(asset2c, asset10c), float aj = f_calc_corr(asset1c, asset10c)
float ii = f_calc_corr(asset9c, asset9c), float ij = f_calc_corr(asset9c, asset10c), float bg = f_calc_corr(asset2c, asset7c), float bh = f_calc_corr(asset2c, asset8c), float ej = f_calc_corr(asset5c, asset10c)
float jj = f_calc_corr(asset10c, asset10c),float af = f_calc_corr(asset1c, asset6c), float ag = f_calc_corr(asset1c, asset7c), float ah = f_calc_corr(asset1c, asset8c), float ai = f_calc_corr(asset1c, asset9c)
// Setting ticker label text
f_set_text(txt1, txt2) =>
showchg ? str.tostring(txt1) + ' (' + str.tostring(txt2, format.percent) + ')' : str.tostring(txt1)
// Creating a table
table = table.new(position.middle_center,14, 14, bgcolor=tablecol)
// Horizontal ticker labels
table.cell(table, 2, 1, text=f_set_text(tickera, asset1_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 3, 1, text=f_set_text(tickerb, asset2_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 4, 1, text=f_set_text(tickerc, asset3_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 5, 1, text=f_set_text(tickerd, asset4_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 6, 1, text=f_set_text(tickere, asset5_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 7, 1, text=f_set_text(tickerf, asset6_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 8, 1, text=f_set_text(tickerg, asset7_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 9, 1, text=f_set_text(tickerh, asset8_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 10, 1, text=f_set_text(tickeri, asset9_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 11, 1, text=f_set_text(tickerj, asset10_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
// Vertical ticker labels
table.cell(table, 1, 2, text=f_set_text(tickera, asset1_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 1, 3, text=f_set_text(tickerb, asset2_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 1, 4, text=f_set_text(tickerc, asset3_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 1, 5, text=f_set_text(tickerd, asset4_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 1, 6, text=f_set_text(tickere, asset5_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 1, 7, text=f_set_text(tickerf, asset6_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 1, 8, text=f_set_text(tickerg, asset7_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 1, 9, text=f_set_text(tickerh, asset8_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 1, 10, text=f_set_text(tickeri, asset9_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
table.cell(table, 1, 11, text=f_set_text(tickerj, asset10_chg), text_halign = text.align_center, text_color = textcol, height = cellh, width = cellw)
// Setting heatmap color conditions
f_set_col(corrval) =>
if heatmap and hmct=='Custom'
((corrval==1) ? corr1 : (corrval>0.90) ? corr2 : (corrval>0.8 and corrval<0.90) ? corr3 : (corrval>0.70 and corrval<0.80) ? corr4 : (corrval>0.60 and corrval<0.70) ? corr5 : (corrval>0.50 and corrval<0.60) ? corr6 : (corrval>0.40 and corrval<0.50) ? corr7 : (corrval>0.30 and corrval<0.40) ? corr8 : (corrval>0.20 and corrval<0.30) ? corr9 : (corrval>0.10 and corrval<0.20) ? corr10 : (corrval>0 and corrval<0.10) ? corr11 : (corrval>-0.1 and corrval<0) ? corr12 : (corrval>-0.2 and corrval<-0.1) ? corr13 : (corrval>-0.3 and corrval<-0.2) ? corr14 : (corrval>-0.4 and corrval<-0.3) ? corr15 : (corrval>-0.5 and corrval<-0.4) ? corr16 : (corrval>-0.6 and corrval<-0.5) ? corr17 : (corrval>-0.7 and corrval<-0.6) ? corr18 : (corrval>-0.8 and corrval<-0.7) ? corr19 : (corrval<-0.9) ? corr20 : na)
else if heatmap and hmct=='Gradient'
color.from_gradient(corrval, -1, 1, gr2, gr1)
else
tablecol
// Rounding the correlation coefficient
f_round_val(roundval) =>
str.tostring(math.round(roundval, 3))
// Setting correlation values in the table
f_set_values(r, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9)=>
table.cell(table_id=table, column=2, row=r, text=f_round_val(_0), text_halign = text.align_center,text_color = textcol, width=cellw, height=cellh, bgcolor = f_set_col(_0))
table.cell(table_id=table, column=3, row=r, text=f_round_val(_1), text_halign = text.align_center,text_color = textcol, width=cellw, height=cellh, bgcolor = f_set_col(_1))
table.cell(table_id=table, column=4, row=r, text=f_round_val(_2), text_halign = text.align_center,text_color = textcol, width=cellw, height=cellh, bgcolor = f_set_col(_2))
table.cell(table_id=table, column=5, row=r, text=f_round_val(_3), text_halign = text.align_center,text_color = textcol, width=cellw, height=cellh, bgcolor = f_set_col(_3))
table.cell(table_id=table, column=6, row=r, text=f_round_val(_4), text_halign = text.align_center,text_color = textcol, width=cellw, height=cellh, bgcolor = f_set_col(_4))
table.cell(table_id=table, column=7, row=r, text=f_round_val(_5), text_halign = text.align_center,text_color = textcol, width=cellw, height=cellh, bgcolor = f_set_col(_5))
table.cell(table_id=table, column=8, row=r, text=f_round_val(_6), text_halign = text.align_center,text_color = textcol, width=cellw, height=cellh, bgcolor = f_set_col(_6))
table.cell(table_id=table, column=9, row=r, text=f_round_val(_7), text_halign = text.align_center,text_color = textcol, width=cellw, height=cellh, bgcolor = f_set_col(_7))
table.cell(table_id=table, column=10, row=r, text=f_round_val(_8), text_halign = text.align_center,text_color = textcol, width=cellw, height=cellh, bgcolor = f_set_col(_8))
table.cell(table_id=table, column=11, row=r, text=f_round_val(_9), text_halign = text.align_center,text_color = textcol, width=cellw, height=cellh, bgcolor = f_set_col(_9))
f_set_values(2, aa, ab, ac, ad, ae, af, ag, ah, ai, aj)
f_set_values(3, ab, bb, bc, bd, be, bf, bg, bh, bi, bj)
f_set_values(4, ac, bc, cc, cd, ce, cf, cg, ch, ci, cj)
f_set_values(5, ad, bd, cd, dd, de, df, dg, dh, di, dj)
f_set_values(6, ae, be, ce, de, ee, ef, eg, eh, ei, ej)
f_set_values(7, af, bf, cf, df, ef, ff, fg, fh, fi, fj)
f_set_values(8, ag, bg, cg, dg, eg, fg, gg, gh, gi, gj)
f_set_values(9, ah, bh, ch, dh, eh, fh, gh, hh, hi, hj)
f_set_values(10, ai, bi, ci, di, ei, fi, gi, hi, ii, ij)
f_set_values(11, aj, bj, cj, dj, ej, fj, gj, hj, ij, jj)
|
Pin Candle Detection | https://www.tradingview.com/script/6OEpSAhf-Pin-Candle-Detection/ | xfuturesgod | https://www.tradingview.com/u/xfuturesgod/ | 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/
// © xfuturesgod
//@version=5
indicator("Pin Candle Detection", overlay = true)
fibLevel = input.float(0.55,"Candle Fibonacci Level", minval = 0, maxval = 1)
wickSize = input.float(7, "Wick Length", minval = 1)
greenCandle = close > open
redCandle = open < close
fibCalc = (low - high) * fibLevel + high
// Determine which price source closes or opens highest/lowest
lowestBody = close < open ? close : open
// Determine if we have a valid pin/hammer candle
validClose = lowestBody >= fibLevel
wickFilter = lowestBody - low >= 7
validPin = validClose and wickFilter
plotchar(validPin, title = "Pin Candle", char = "P", color = color.purple)
alertcondition(validPin, "Pin Candle Setup", "Pin Candle") |
[-_-] Dictionary | https://www.tradingview.com/script/P67EBBPr-Dictionary/ | sabricat | https://www.tradingview.com/u/sabricat/ | 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/
// © -_-
//@version=5
indicator("[-_-] Dictionary", overlay=true)
// Custom type that has two string arrays (one for storing keys, another for storing values)
type Dictionary
array<string> keys
array<string> values
// Convert key or value to string to be stored in dictionary
_convertTo(string key_or_value) => "DTS_" + key_or_value
_convertTo(int key_or_value) => "DTI_" + str.tostring(key_or_value)
_convertTo(float key_or_value) => "DTF_" + str.tostring(key_or_value)
_convertTo(bool key_or_value) => "DTB_" + (key_or_value ? 'T' : 'F')
_convertTo(color key_or_value) =>
r = str.tostring(color.r(key_or_value))
g = str.tostring(color.g(key_or_value))
b = str.tostring(color.b(key_or_value))
a = str.tostring(color.t(key_or_value))
"DTC_" + r + "." + g + "." + b + "." + a
// Convert key or value stored in dictionary as string to string
_convertFromString(string key_or_value) =>
if not na(key_or_value)
str.substring(key_or_value, 4)
else
na
// Convert key or value stored in dictionary as string to integer
_convertFromInt(string key_or_value) =>
if not na(key_or_value)
int(str.tonumber(str.substring(key_or_value, 4)))
else
na
// Convert key or value stored in dictionary as string to float
_convertFromFloat(string key_or_value) =>
if not na(key_or_value)
str.tonumber(str.substring(key_or_value, 4))
else
na
// Convert key or value stored in dictionary as string to boolean
_convertFromBool(string key_or_value) =>
if not na(key_or_value)
(str.substring(key_or_value, 4, 5) == 'T') ? true : false
else
na
// Convert key or value stored in dictionary as string to color
_convertFromColor(string key_or_value) =>
if not na(key_or_value)
components = str.split(str.substring(key_or_value, 4), '.')
r = str.tonumber(array.get(components, 0))
g = str.tonumber(array.get(components, 1))
b = str.tonumber(array.get(components, 2))
a = str.tonumber(array.get(components, 3))
color.new(color.rgb(r, g, b), a)
else
na
// Without this the script will display error "Can't call array methods when ID of array is na"
method init(Dictionary dict) =>
dict.keys := array.new<string>(0, na)
dict.values := array.new<string>(0, na)
// Set value by key (key and value can have any of the following types: string, int, float, bool, color); if key already exists, changes the value for that key to new one
method set(Dictionary dict, key, value) =>
key_ = _convertTo(key)
value_ = _convertTo(value)
id_ = dict.keys.indexof(key_)
if id_ == -1
dict.values.push(value_)
dict.keys.push(key_)
else
dict.values.set(id_, value_)
dict.keys.set(id_, key_)
// Converts key to string representation used by dictionary and checks if such key exists
method _get(Dictionary dict, key) =>
key_ = _convertTo(key)
id_ = dict.keys.indexof(key_)
if id_ != -1
dict.values.get(id_)
else
na
// Get a string value by key of string/int/float/bool/color
method getS(Dictionary dict, string key) => _convertFromString(dict._get(key))
method getS(Dictionary dict, int key) => _convertFromString(dict._get(key))
method getS(Dictionary dict, float key) => _convertFromString(dict._get(key))
method getS(Dictionary dict, bool key) => _convertFromString(dict._get(key))
method getS(Dictionary dict, color key) => _convertFromString(dict._get(key))
// Get an integer value by key of string/int/float/bool/color
method getI(Dictionary dict, string key) => _convertFromInt(dict._get(key))
method getI(Dictionary dict, int key) => _convertFromInt(dict._get(key))
method getI(Dictionary dict, float key) => _convertFromInt(dict._get(key))
method getI(Dictionary dict, bool key) => _convertFromInt(dict._get(key))
method getI(Dictionary dict, color key) => _convertFromInt(dict._get(key))
// Get a float value by key of string/int/float/bool/color
method getF(Dictionary dict, string key) => _convertFromFloat(dict._get(key))
method getF(Dictionary dict, int key) => _convertFromFloat(dict._get(key))
method getF(Dictionary dict, float key) => _convertFromFloat(dict._get(key))
method getF(Dictionary dict, bool key) => _convertFromFloat(dict._get(key))
method getF(Dictionary dict, color key) => _convertFromFloat(dict._get(key))
// Get a boolean value by key of string/int/float/bool/color
method getB(Dictionary dict, string key) => _convertFromBool(dict._get(key))
method getB(Dictionary dict, int key) => _convertFromBool(dict._get(key))
method getB(Dictionary dict, float key) => _convertFromBool(dict._get(key))
method getB(Dictionary dict, bool key) => _convertFromBool(dict._get(key))
method getB(Dictionary dict, color key) => _convertFromBool(dict._get(key))
// Get a color value by key of string/int/float/bool/color
method getC(Dictionary dict, string key) => _convertFromColor(dict._get(key))
method getC(Dictionary dict, int key) => _convertFromColor(dict._get(key))
method getC(Dictionary dict, float key) => _convertFromColor(dict._get(key))
method getC(Dictionary dict, bool key) => _convertFromColor(dict._get(key))
method getC(Dictionary dict, color key) => _convertFromColor(dict._get(key))
// Removes element from dictionary
method remove(Dictionary dict, string key) =>
key_ = _convertTo(key)
id_ = dict.keys.indexof(key_)
if id_ != -1
dict.keys.remove(id_)
dict.values.remove(id_)
// Returns length of the dictionary (number of keys)
method len(Dictionary dict) => dict.keys.size()
// Create dictionary and put some values in it
d = Dictionary.new()
d.init()
d.set('12', 'something')
d.set(2, color.rgb(0, 100, 240))
d.set(true, false)
d.set(12.24, 18)
d.set(color.rgb(24, 12, 298), 0.982)
// Get values from dictionary
v1 = d.getS('12')
v2 = d.getC(2)
v2_str = 'RGBA(' + str.tostring(color.r(v2)) + ', ' + str.tostring(color.g(v2)) + ', ' + str.tostring(color.b(v2)) + ', ' + str.tostring(color.t(v2)) + ')'
v3 = d.getB(true)
v3_str = str.tostring(v3)
v4 = d.getI(12.24)
v4_str = str.tostring(v4)
v5 = d.getF(color.rgb(24, 12, 298))
v5_str = str.tostring(v5)
// Testing if the value of an already existing key will be changed for new one)
d2 = Dictionary.new()
d2.init()
// Add a key 2 with value 'value'
d2.set(2, 'value')
// Change the value of key 2 for 'new value'
d2.set(2, true)
// Get the value by key 2
v6 = d2.getB(2)
v6_str = str.tostring(v6)
// Testing if an item will be removed from dictionary
d3 = Dictionary.new()
d3.init()
// Add 2 items
d3.set('key1', 'Value 1')
d3.set('key2', 'Value 2')
// Remove key1
d3.remove('key1')
// Try to get value by key 'key1'
v7 = d3.getS('key1')
v8 = d3.getS('key2')
// Get dictionary length
v9 = d3.len()
v9_str = str.tostring(v9)
// Display label
if barstate.islast
te = "GET VALUES:\n• '12' = " + v1 + '\n• 2 = ' + v2_str + '\n• true = ' + v3_str + '\n• 12.24 = ' + v4_str + '\n• color.rgb(24, 12, 298) = ' + v5_str + '\n\n'
te := te + "CHANGE EXISTING ITEM:\n• " + v6_str + '\n\n'
te := te + "REMOVE ITEM:\n• key1 = " + v7 + '\n• key2 = ' + v8 + '\n\n'
te := te + "LENGTH:\n• " + v9_str
var label lbl = label.new(bar_index + 50, close, text=te, textalign=text.align_left) |
War Times | https://www.tradingview.com/script/UwQu3JvT-War-Times/ | trevor1617 | https://www.tradingview.com/u/trevor1617/ | 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/
// © jdehorty
// @version=5
indicator('War Times', overlay=true, scale=scale.none, max_lines_count=500)
import trevor1617/WarCalendar/1 as calendar
// ==================
// ==== Settings ====
// ==================
show_war_start = input.bool(defval = true, title = "📅 Start", inline = "Start", group="⚙️ Settings", tooltip="War start date")
c_warstart = input.color(color.new(color.red, 50), title = "Color", group="⚙️ Settings", inline = "Start")
show_legend = input.bool(true, "Show Legend", group="⚙️ Settings", inline = "Legend", tooltip="Show the color legend for the economic calendar events.")
use_alt_date_resolution = input.bool(false, "Use Alternative Date Resolution", group="⚙️ Settings", inline = "AlternativeDateResolution", tooltip="Use alternative date resolution for the economic calendar events. May help in scenarios where the daily timeframe is off by a day.")
// =======================
// ==== Dates & Times ====
// =======================
getUnixTime(eventArr, i) =>
int t = array.get(eventArr, i)
switch
timeframe.isdaily => timestamp(year(t), month(t), dayofmonth(t)-timeframe.multiplier+1, 00, 00, 00)
timeframe.isweekly => timestamp(year(t), month(t), dayofmonth(t)-7*timeframe.multiplier+1, 00, 00, 00)
timeframe.ismonthly => timestamp(year(t), month(t)-timeframe.multiplier+1, 00, 00, 00, 00)
timeframe.isminutes and timeframe.multiplier > 60 => timestamp(year(t), month(t), dayofmonth(t), hour(t)-timeframe.multiplier/60+1, minute(t), second(t))
=> timestamp(year(t), month(t), dayofmonth(t), hour(t), minute(t), second(t))
// Note: The following is an alternative implementation of getUnixTime. It is useful for independently double-checking the resulting vertical lines of the above function.
getUnixTimeAlt(eventArr, i) =>
int t = array.get(eventArr, i)
switch
timeframe.isdaily and timeframe.multiplier >= 1 => t - timeframe.multiplier*86400000 // -n days
timeframe.isweekly => t - timeframe.multiplier*604800000 // -n week(s)
timeframe.ismonthly => t - timeframe.multiplier*2592000000 // -n month(s)
timeframe.isminutes and timeframe.multiplier > 60 => t - timeframe.multiplier*60000 // -n minutes
=> t
// Note: An offset of -n units is needed to realign events with the timeframe in which they occurred
if show_war_start
warstartArr = calendar.warstart()
for i = 0 to array.size(warstartArr) - 1
unixTime = use_alt_date_resolution ? getUnixTimeAlt(warstartArr, i) : getUnixTime(warstartArr, i)
line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_warstart, width=2, xloc=xloc.bar_time)
// ================
// ==== Legend ====
// ================
if show_legend
var tbl = table.new(position.top_right, columns=1, rows=8, frame_color=#151715, frame_width=1, border_width=2, border_color=color.new(color.black, 100))
units = timeframe.isminutes ? "m" : ""
if barstate.islast
table.cell(tbl, 0, 0, syminfo.ticker + ' | ' + str.tostring(timeframe.period) + units, text_halign=text.align_center, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 0, 1, 'War Start', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_warstart, 10), text_size=size.small)
|
Time of Day - Volatility Report | https://www.tradingview.com/script/ddgvttDd-Time-of-Day-Volatility-Report/ | sbtnc | https://www.tradingview.com/u/sbtnc/ | 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/
// © sbtnc
// Created: 2023-02-23
// Last modified: 2023-02-23
// Version 1.0
//@version=5
indicator("Time of Day - Volatility Report", format=format.percent)
//--------------------------------------------------------------------
// Constants
//--------------------------------------------------------------------
var DEFAULT_COLUMN_BORDERCOLOR = chart.bg_color
var DEFAULT_COLUMN_WIDTH = 2
var DEFAULT_COLUMN_GAP = 2
var DEFAULT_CAPTION_COLOR = color.gray
//--------------------------------------------------------------------
// Inputs
//--------------------------------------------------------------------
t_timezone = "Exchange and geographical time zones may observe Daylight Saving Time (DST)."
t_atrPeriod = "By default, compares the hourly volatility relatively to the average daily volatility of the past 20 days."
t_output = "Mean: the average of all values in the dataset.\nMedian: the middle value in the ordered dataset."
i_timezone = input.string ("Exchange", "Time Zone",
[
"UTC",
"Exchange",
"Africa/Cairo",
"Africa/Johannesburg",
"Africa/Lagos",
"Africa/Nairobi",
"Africa/Tunis",
"America/Argentina/Buenos_Aires",
"America/Bogota",
"America/Caracas",
"America/Chicago",
"America/Denver",
"America/El_Salvador",
"America/Juneau",
"America/Lima",
"America/Los_Angeles",
"America/New_York",
"America/Mexico_City",
"America/Phoenix",
"America/Santiago",
"America/Sao_Paulo",
"America/Toronto",
"America/Vancouver",
"Asia/Almaty",
"Asia/Ashgabat",
"Asia/Bahrain",
"Asia/Bangkok",
"Asia/Dubai",
"Asia/Chongqing",
"Asia/Colombo",
"Asia/Ho_Chi_Minh",
"Asia/Hong_Kong",
"Asia/Istanbul",
"Asia/Jakarta",
"Asia/Jerusalem",
"Asia/Karachi",
"Asia/Kathmandu",
"Asia/Kolkata",
"Asia/Kuwait",
"Asia/Manila",
"Asia/Muscat",
"Asia/Nicosia",
"Asia/Qatar",
"Asia/Riyadh",
"Asia/Seoul",
"Asia/Shanghai",
"Asia/Singapore",
"Asia/Taipei",
"Asia/Tehran",
"Asia/Tokyo",
"Asia/Yangon",
"Atlantic/Reykjavik",
"Australia/Adelaide",
"Australia/Brisbane",
"Australia/Perth",
"Australia/Sydney",
"Europe/Amsterdam",
"Europe/Athens",
"Europe/Belgrade",
"Europe/Berlin",
"Europe/Bratislava",
"Europe/Brussels",
"Europe/Bucharest",
"Europe/Budapest",
"Europe/Copenhagen",
"Europe/Dublin",
"Europe/Helsinki",
"Europe/Madrid",
"Europe/Malta",
"Europe/Moscow",
"Europe/Lisbon",
"Europe/London",
"Europe/Luxembourg",
"Europe/Oslo",
"Europe/Paris",
"Europe/Riga",
"Europe/Rome",
"Europe/Stockholm",
"Europe/Tallinn",
"Europe/Vilnius",
"Europe/Warsaw",
"Europe/Zurich",
"Pacific/Auckland",
"Pacific/Chatham",
"Pacific/Fakaofo",
"Pacific/Honolulu",
"Pacific/Norfolk"
],
t_timezone
)
i_atrPeriod = input.int (20, "Daily ATR Period", minval=1, tooltip=t_atrPeriod)
i_output = input.string ("Median", "Ouput", ["Mean", "Median"], t_output)
i_highVolatilityColor = input.color (color.red, "High Volatility")
i_lowVolatilityColor = input.color (color.blue, "Low Volatility")
//--------------------------------------------------------------------
// Variables declarations
//--------------------------------------------------------------------
var a_results = array.new_float(24)
var a_sizes = array.new_float(24)
var a_dataset0 = array.new_float()
var a_dataset1 = array.new_float()
var a_dataset2 = array.new_float()
var a_dataset3 = array.new_float()
var a_dataset4 = array.new_float()
var a_dataset5 = array.new_float()
var a_dataset6 = array.new_float()
var a_dataset7 = array.new_float()
var a_dataset8 = array.new_float()
var a_dataset9 = array.new_float()
var a_dataset10 = array.new_float()
var a_dataset11 = array.new_float()
var a_dataset12 = array.new_float()
var a_dataset13 = array.new_float()
var a_dataset14 = array.new_float()
var a_dataset15 = array.new_float()
var a_dataset16 = array.new_float()
var a_dataset17 = array.new_float()
var a_dataset18 = array.new_float()
var a_dataset19 = array.new_float()
var a_dataset20 = array.new_float()
var a_dataset21 = array.new_float()
var a_dataset22 = array.new_float()
var a_dataset23 = array.new_float()
//--------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------
// @function Get the time zone from the input settings
// @return string
f_getTimezone() =>
switch i_timezone
"UTC" => "UTC+0"
"Exchange" => syminfo.timezone
=> i_timezone
// @function Check if current bar's time is at a given hour
// @return bool
f_checkTime(int _hour) =>
var _tz = f_getTimezone()
hour(time, _tz) == _hour
// @function Get the output data based on the input settings
// @return float
f_getData(array<float> data) =>
switch i_output
"Mean" => array.avg(data)
"Median" => array.median(data)
// @function Draw a chart column
// @return void
f_drawColumn(int _index) =>
var box _col = box.new(na, na, na, na, DEFAULT_COLUMN_BORDERCOLOR)
var label _legend = label.new(na, na, color=color(na), style=label.style_label_up)
var label _value = label.new(na, na, color=color(na), style=label.style_label_down)
var _gridMultiplier = DEFAULT_COLUMN_WIDTH + DEFAULT_COLUMN_GAP
if barstate.islast
_hasValue = not na(array.get(a_results, _index))
_y = _hasValue ? array.get(a_results, _index) : 0.0
_x1 = bar_index + (_index - 24) * _gridMultiplier
_x2 = _x1 + DEFAULT_COLUMN_WIDTH
_center = _x1 + DEFAULT_COLUMN_WIDTH / 2
_min = array.min(a_results)
_max = array.max(a_results)
_color = color.from_gradient(_y, _min, _max, i_lowVolatilityColor, i_highVolatilityColor)
_samples = array.get(a_sizes, _index)
// Column
box.set_lefttop (_col, _x1, _y)
box.set_rightbottom (_col, _x2, 0)
box.set_bgcolor (_col, _color)
// Legend
label.set_xy (_legend, _center, 0)
label.set_text (_legend, str.tostring(_index))
label.set_textcolor (_legend, _color)
label.set_tooltip (_legend, str.format("{0}:00 to {0}:59 ({1})", _index, f_getTimezone()))
// Value
if _hasValue
label.set_xy (_value, _center, _y)
label.set_text (_value, str.tostring(math.round(_y)))
label.set_textcolor (_value, _color)
label.set_tooltip (_value, str.format("{0} based on {1} samples", str.tostring(_y, format.percent), _samples))
//--------------------------------------------------------------------
// Logic
//--------------------------------------------------------------------
if not (timeframe.isminutes and timeframe.multiplier == 60)
runtime.error("The report need to compute data from the hourly timeframe. Please change to 60 or 1H timeframe.")
dailyAtr = request.security(syminfo.tickerid, "D", ta.atr(i_atrPeriod))
relativeToAtr = ta.tr * 100 / dailyAtr
// Collect the volatility data
switch
f_checkTime(0) => array.push(a_dataset0, relativeToAtr)
f_checkTime(1) => array.push(a_dataset1, relativeToAtr)
f_checkTime(2) => array.push(a_dataset2, relativeToAtr)
f_checkTime(3) => array.push(a_dataset3, relativeToAtr)
f_checkTime(4) => array.push(a_dataset4, relativeToAtr)
f_checkTime(5) => array.push(a_dataset5, relativeToAtr)
f_checkTime(6) => array.push(a_dataset6, relativeToAtr)
f_checkTime(7) => array.push(a_dataset7, relativeToAtr)
f_checkTime(8) => array.push(a_dataset8, relativeToAtr)
f_checkTime(9) => array.push(a_dataset9, relativeToAtr)
f_checkTime(10) => array.push(a_dataset10, relativeToAtr)
f_checkTime(11) => array.push(a_dataset11, relativeToAtr)
f_checkTime(12) => array.push(a_dataset12, relativeToAtr)
f_checkTime(13) => array.push(a_dataset13, relativeToAtr)
f_checkTime(14) => array.push(a_dataset14, relativeToAtr)
f_checkTime(15) => array.push(a_dataset15, relativeToAtr)
f_checkTime(16) => array.push(a_dataset16, relativeToAtr)
f_checkTime(17) => array.push(a_dataset17, relativeToAtr)
f_checkTime(18) => array.push(a_dataset18, relativeToAtr)
f_checkTime(19) => array.push(a_dataset19, relativeToAtr)
f_checkTime(20) => array.push(a_dataset20, relativeToAtr)
f_checkTime(21) => array.push(a_dataset21, relativeToAtr)
f_checkTime(22) => array.push(a_dataset22, relativeToAtr)
f_checkTime(23) => array.push(a_dataset23, relativeToAtr)
// Compute on last bar for optimizing performances
if barstate.islast
// The results
array.set(a_results, 0, f_getData(a_dataset0))
array.set(a_results, 1, f_getData(a_dataset1))
array.set(a_results, 2, f_getData(a_dataset2))
array.set(a_results, 3, f_getData(a_dataset3))
array.set(a_results, 4, f_getData(a_dataset4))
array.set(a_results, 5, f_getData(a_dataset5))
array.set(a_results, 6, f_getData(a_dataset6))
array.set(a_results, 7, f_getData(a_dataset7))
array.set(a_results, 8, f_getData(a_dataset8))
array.set(a_results, 9, f_getData(a_dataset9))
array.set(a_results, 10, f_getData(a_dataset10))
array.set(a_results, 11, f_getData(a_dataset11))
array.set(a_results, 12, f_getData(a_dataset12))
array.set(a_results, 13, f_getData(a_dataset13))
array.set(a_results, 14, f_getData(a_dataset14))
array.set(a_results, 15, f_getData(a_dataset15))
array.set(a_results, 16, f_getData(a_dataset16))
array.set(a_results, 17, f_getData(a_dataset17))
array.set(a_results, 18, f_getData(a_dataset18))
array.set(a_results, 19, f_getData(a_dataset19))
array.set(a_results, 20, f_getData(a_dataset20))
array.set(a_results, 21, f_getData(a_dataset21))
array.set(a_results, 22, f_getData(a_dataset22))
array.set(a_results, 23, f_getData(a_dataset23))
// The sample sizes
array.set(a_sizes, 0, array.size(a_dataset0))
array.set(a_sizes, 1, array.size(a_dataset1))
array.set(a_sizes, 2, array.size(a_dataset2))
array.set(a_sizes, 3, array.size(a_dataset3))
array.set(a_sizes, 4, array.size(a_dataset4))
array.set(a_sizes, 5, array.size(a_dataset5))
array.set(a_sizes, 6, array.size(a_dataset6))
array.set(a_sizes, 7, array.size(a_dataset7))
array.set(a_sizes, 8, array.size(a_dataset8))
array.set(a_sizes, 9, array.size(a_dataset9))
array.set(a_sizes, 10, array.size(a_dataset10))
array.set(a_sizes, 11, array.size(a_dataset11))
array.set(a_sizes, 12, array.size(a_dataset12))
array.set(a_sizes, 13, array.size(a_dataset13))
array.set(a_sizes, 14, array.size(a_dataset14))
array.set(a_sizes, 15, array.size(a_dataset15))
array.set(a_sizes, 16, array.size(a_dataset16))
array.set(a_sizes, 17, array.size(a_dataset17))
array.set(a_sizes, 18, array.size(a_dataset18))
array.set(a_sizes, 19, array.size(a_dataset19))
array.set(a_sizes, 20, array.size(a_dataset20))
array.set(a_sizes, 21, array.size(a_dataset21))
array.set(a_sizes, 22, array.size(a_dataset22))
array.set(a_sizes, 23, array.size(a_dataset23))
//--------------------------------------------------------------------
// Plotting & styling
//--------------------------------------------------------------------
// Draw the column chart
f_drawColumn(0)
f_drawColumn(1)
f_drawColumn(2)
f_drawColumn(3)
f_drawColumn(4)
f_drawColumn(5)
f_drawColumn(6)
f_drawColumn(7)
f_drawColumn(8)
f_drawColumn(9)
f_drawColumn(10)
f_drawColumn(11)
f_drawColumn(12)
f_drawColumn(13)
f_drawColumn(14)
f_drawColumn(15)
f_drawColumn(16)
f_drawColumn(17)
f_drawColumn(18)
f_drawColumn(19)
f_drawColumn(20)
f_drawColumn(21)
f_drawColumn(22)
f_drawColumn(23) |
EMA Power Ranking [wbburgin] | https://www.tradingview.com/script/X13Iue8a-EMA-Power-Ranking-wbburgin/ | wbburgin | https://www.tradingview.com/u/wbburgin/ | 55 | 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("EMA Power Ranking [wbburgin]",overlay = true,max_bars_back=5000)
maLength = input.int(100,"MA LENGTH",group="Moving Averages")
format = input.string("Pure EMA",options=["Pure EMA","RMA","Volatility-Weighted EMA","Volume-Weighted EMA","Cumulative Volatility-Weighted EMA","Inverse Volatility-Weighted MA","TRMA"],title="MA Type",group="Moving Averages")
showMAs = input.bool(false,"Show MA's",group="Moving Averages")
screenlength = input.int(0,"Screen Length",minval=0,maxval=2,group="Precision")
lookBack = input.int(100,"Volatility Period (in bars)",group="Config",tooltip="Only necessary for volatility-weighted MAs")
//Functions
calc_elma(float priceType,int length,float weightType) =>
sum = math.sum(weightType,length)
data = 0.0
data := (nz(data[1]) * (sum - weightType)/sum) + (weightType*priceType/sum)
data
//The Elastic Moving Average (ELMA) calculates the continuous weighted average by weightType. Inspired by
//LazyBear's 'Elastic Volume Moving Average' indicator and generalized for any weight type.
cumVolatility() =>
currentIndex = switch
close>=open and open==low => (close-open)-(high-close)
close>=open and open>=low => (close-open)-(high-close)+(open-low)
close<=open and open==high => (close-open)+(close-low)
close<=open and open<=high => (close-open)+(close-low)-(high-open)
cIndex = ta.cum(currentIndex)
//The cumulative volatility function uses a body-wick analysis to determine resistance and indexes this resistance.
volatility(float source,int length) =>
2*(ta.highest(source,length)-ta.lowest(source,length))/(ta.highest(source,length)+ta.lowest(source,length))
//The volatility function uses my personal definition of volatility - the relationship between the median and the
//average - to identify a correlative coefficient. Data analysis confirms a 1:1 correlation with the "Beta"
//statistic in traditional wealth markets.
// Pure EMA's
ema1 = ta.ema(close,maLength)
ema2 = ta.ema(close,maLength*2)
ema3 = ta.ema(close,maLength*3)
ema4 = ta.ema(close,maLength*4)
ema5 = ta.ema(close,maLength*5)
//RMA
rma1= ta.rma(close,maLength)
rma2= ta.rma(close,maLength*2)
rma3= ta.rma(close,maLength*3)
rma4= ta.rma(close,maLength*4)
rma5= ta.rma(close,maLength*5)
//VWEMA's
volatility = volatility(close,lookBack)
vwema1 = calc_elma(close, maLength,volatility)
vwema2 = calc_elma(close, maLength*2,volatility)
vwema3 = calc_elma(close, maLength*3,volatility)
vwema4 = calc_elma(close, maLength*4,volatility)
vwema5 = calc_elma(close, maLength*5,volatility)
//Volume-Weighted EMA's
vw1 = calc_elma(close,maLength,volume)
vw2 = calc_elma(close,maLength*2,volume)
vw3 = calc_elma(close,maLength*3,volume)
vw4 = calc_elma(close,maLength*4,volume)
vw5 = calc_elma(close,maLength*5,volume)
//Cumulative Volatility-Weighted EMA's
cumVol = cumVolatility()
c1 = calc_elma(close,maLength,cumVol)
c2 = calc_elma(close,maLength*2,cumVol)
c3 = calc_elma(close,maLength*3,cumVol)
c4 = calc_elma(close,maLength*4,cumVol)
c5 = calc_elma(close,maLength*5,cumVol)
//Inverse Volatility-Weighted EMA
inverseVolatility = 1/volatility(close,lookBack)
iv1 = calc_elma(close,maLength,inverseVolatility)
iv2 = calc_elma(close,maLength*2,inverseVolatility)
iv3 = calc_elma(close,maLength*3,inverseVolatility)
iv4 = calc_elma(close,maLength*4,inverseVolatility)
iv5 = calc_elma(close,maLength*5,inverseVolatility)
//Assignment
ema100 = switch
format=="Pure EMA"=>ema1
format=="RMA"=>rma1
format=="Volatility-Weighted EMA"=>vwema1
format=="Volume-Weighted EMA"=>vw1
format=="Cumulative Volatility-Weighted EMA"=>c1
format=="Inverse Volatility-Weighted MA"=>iv1
ema200 = switch
format=="Pure EMA"=>ema2
format=="RMA"=>rma2
format=="Volatility-Weighted EMA"=>vwema2
format=="Volume-Weighted EMA"=>vw2
format=="Cumulative Volatility-Weighted EMA"=>c2
format=="Inverse Volatility-Weighted MA"=>iv2
ema300 = switch
format=="Pure EMA"=>ema3
format=="RMA"=>rma3
format=="Volatility-Weighted EMA"=>vwema3
format=="Volume-Weighted EMA"=>vw3
format=="Cumulative Volatility-Weighted EMA"=>c3
format=="Inverse Volatility-Weighted MA"=>iv3
ema400 = switch
format=="Pure EMA"=>ema4
format=="RMA"=>rma4
format=="Volatility-Weighted EMA"=>vwema4
format=="Volume-Weighted EMA"=>vw4
format=="Cumulative Volatility-Weighted EMA"=>c4
format=="Inverse Volatility-Weighted MA"=>iv4
ema500 = switch
format=="Pure EMA"=>ema5
format=="RMA"=>rma5
format=="Volatility-Weighted EMA"=>vwema5
format=="Volume-Weighted EMA"=>vw5
format=="Cumulative Volatility-Weighted EMA"=>c5
format=="Inverse Volatility-Weighted MA"=>iv5
//Calculation
emadif0= ema100-ema200
emadif1= ema200-ema300
emadif2= ema300-ema400
emadif3= ema400-ema500
rising0 = emadif0>emadif0[1]
rising1 = emadif1>emadif1[1]
rising2 = emadif2>emadif2[1]
rising3 = emadif3>emadif3[1]
over0 = ema100>ema200
over1 = ema200>ema300
over2 = ema300>ema400
over3 = ema400>ema500
//States
state0 = switch
rising0==true and over0==true => "up0"
rising0==false and over0==false => "dn0"
=> "osc0"
state1 = switch
rising1==true and over1==true => "up1"
rising1==false and over1==false => "dn1"
=> "osc1"
state2 = switch
rising2==true and over2==true => "up2"
rising2==false and over2==false => "dn2"
=> "osc2"
state3 = switch
rising3==true and over3==true => "up3"
rising3==false and over3==false => "dn3"
=> "osc3"
//Buy and Sell Conditions
condition = switch //Normal
(state0[1] == "dn0")and(state1[1] == "dn1")and(state0!="dn0")=>"buy"
(state0[1] == "up0")and(state1[1] == "up1")and(state0!="up0")=>"sell"
condition_1 = switch //dx
(state0[1] == "dn0")and(state1[1] == "dn1")and(state2[1] == "dn2")and(state0!="dn0")=>"buy"
(state0[1] == "up0")and(state1[1] == "up1")and(state2[1] == "up2")and(state0!="up0")=>"sell"
condition_2 = switch //d2x
(state0[1] == "dn0")and(state1[1] == "dn1")and(state2[1] == "dn2")and(state3[1] == "dn3")and(state0!="dn0")=>"buy"
(state0[1] == "up0")and(state1[1] == "up1")and(state2[1] == "up2")and(state3[1] == "up3")and(state0!="up0")=>"sell"
//Assigning Signals
bullSignal = switch
screenlength==0 => condition=="buy"
screenlength==1 => condition_1=="buy"
screenlength==2 => condition_2=="buy"
bearSignal = switch
screenlength==0 => condition=="sell"
screenlength==1 => condition_1=="sell"
screenlength==2 => condition_2=="sell"
//Plotting
plotshape(bullSignal,title="Buy Condition",style=shape.triangleup,location=location.belowbar,color=color.lime,size=size.tiny)
plotshape(bearSignal,title="Sell Condition",style=shape.triangledown,location=location.abovebar,color=color.red,size=size.tiny)
bg0 = switch
state0 == "osc0" => color.new(color.yellow,95)
state0 == "up0" => color.new(color.green,95)
state0 == "dn0" => color.new(color.red,95)
bg1 = switch
state1 == "osc1" => color.new(color.yellow,95)
state1 == "up1" => color.new(color.green,95)
state1 == "dn1" => color.new(color.red,95)
bg2 = switch
state2 == "osc2" => color.new(color.yellow,95)
state2 == "up2" => color.new(color.green,95)
state2 == "dn2" => color.new(color.red,95)
bg3 = switch
state3 == "osc3" => color.new(color.yellow,95)
state3 == "up3" => color.new(color.green,95)
state3 == "dn3" => color.new(color.red,95)
bgcolor(bg0)
bgcolor(bg1)
bgcolor(bg2)
bgcolor(bg3)
plot(showMAs==true?ema100:na,color=color.white,title="MA 100")
plot(showMAs==true?ema200:na,color=color.yellow,title="MA 200")
plot(showMAs==true?ema300:na,color=color.red,title="MA 300")
//Updated |
Return Abnormality Score [SpiritualHealer117] | https://www.tradingview.com/script/HCPEp4pn-Return-Abnormality-Score-SpiritualHealer117/ | spiritualhealer117 | https://www.tradingview.com/u/spiritualhealer117/ | 45 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © spiritualhealer117
//@version=5
indicator("Return Abnormality Score [SpiritualHealer117]")
import spiritualhealer117/Statistical_Tool_Pack/3 as statistics
sr_len = input.int(14, "Short Run Length", group="Input")
lr_len = input.int(300,"Long Run Length", group ="Input")
src = input.source(close,"Source", group="Input")
significance_level = input.float(0.2,"Significance Level", group="Indicator Settings")
smo = input.string("Smoothed", "Mode",["Smoothed","Unsmoothed"],group="Indicator Settings")
clr1 = input.color(#4caf50,"Bull Color", group="Style")
clr2 = input.color(#f8bbd0,"Bear Color", group="Style")
outlier_transp = input.int(60, "Default Outlier Transparency", group = "Style")
norm_transp = input.int(100, "Normal Transparency", group = "Style")
ret = (src-src[1])/src[1]
mu = ta.ema(ret,lr_len)
sigma = ta.stdev(ret,lr_len)
mu_sr = ta.ema(ret,sr_len)
sigma_sr = ta.stdev(ret,sr_len)
lr_price_abnormality = statistics.normcdf(x=ret,mu=mu,sigma=sigma)*(ret>0?1:-1)
sr_price_abnormality = statistics.normcdf(x=ret,mu=mu_sr,sigma=sigma_sr)*(ret>0?1:-1)
lr_smoothed_abnormality = ta.swma(lr_price_abnormality)
sr_smoothed_abnormality = ta.swma(sr_price_abnormality)
lr_abnormality = smo=="Smoothed"?lr_smoothed_abnormality:lr_price_abnormality
sr_abnormality = smo=="Smoothed"?sr_smoothed_abnormality:sr_price_abnormality
cond1 = lr_abnormality > 1-significance_level or sr_abnormality > 1 - significance_level
cond2 = lr_abnormality < significance_level-1 or sr_abnormality < significance_level - 1
indic_clr = color.new(sr_abnormality>lr_abnormality?clr1:clr2,(cond1 or cond2)?100-norm_transp:100-outlier_transp)
l1=plot(smo=="Smoothed"?lr_smoothed_abnormality:lr_price_abnormality, color=indic_clr, style=plot.style_columns)
hline(1-significance_level)
hline(significance_level-1) |
[Uhokang] Bollinger Band BB EMA SMMA SMA Multy timeframe | https://www.tradingview.com/script/1eVeA6Lf-Uhokang-Bollinger-Band-BB-EMA-SMMA-SMA-Multy-timeframe/ | atomicbear96 | https://www.tradingview.com/u/atomicbear96/ | 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/
// © atomicbear96
//@version=5
indicator("[Uhokang] Bollinger Band BB EMA SMMA SMA Multy timeframe", overlay = true)
// import Timeframes
import atomicbear96/MultyTimeframe/1 as MultyTimeframe
[big_interval, big_interval_2, big_mult, big_mult_2] = MultyTimeframe.MultTimeframes()
// Safe Security
nonRepaintingSecurity(sym, tf, src) =>
request.security(sym, tf, src[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]
// 1. Bollinger Band Multy timeframe
bb_len = input.int(20, "BB len", group = "Bollinger Band")
bb_mult = input.float(2, "BB mult", group = "Bollinger Band")
// bb
[bb_mid, bb_top, bb_bot] = ta.bb(close, bb_len, bb_mult)
// Timeframe BB Calc
f_bb(src, length, mult, _interval) =>
float basis = nonRepaintingSecurity(syminfo.tickerid, _interval,ta.sma(src, length))
float dev = nonRepaintingSecurity(syminfo.tickerid, _interval,mult * ta.stdev(src, length))
[basis, basis + dev, basis - dev]
[bb_mid_big, bb_top_big, bb_bot_big] = f_bb(close, bb_len, bb_mult, big_interval)
[bb_mid_big_2, bb_top_big_2, bb_bot_big_2] = f_bb(close, bb_len, bb_mult, big_interval_2)
// draw
bb_color = input.color(color.new(color.navy,10), group = "Bollinger Band")
bb_color_big = input.color(color.new(color.navy,70), group = "Bollinger Band")
bb_color_big_2 = input.color(color.new(color.navy,90), group = "Bollinger Band")
p_bb_mid = plot(bb_mid, color = bb_color, title = "BB Middle 1")
p_bb_top = plot(bb_top, color = bb_color, title = "BB Top 1")
p_bb_bot = plot(bb_bot, color = bb_color, title = "BB Bottom 1")
p_bb_mid_big = plot(bb_mid_big, color = bb_color_big, title = "BB Middle 2")
p_bb_top_big = plot(bb_top_big, color = bb_color_big, title = "BB Top 2")
p_bb_bot_big = plot(bb_bot_big, color = bb_color_big, title = "BB Bottom 2")
p_bb_mid_big_2 = plot(bb_mid_big_2, color = bb_color_big_2, title = "BB Middle 3")
p_bb_top_big_2 = plot(bb_top_big_2, color = bb_color_big_2, title = "BB Top 3")
p_bb_bot_big_2 = plot(bb_bot_big_2, color = bb_color_big_2, title = "BB Bottom 3")
fill(p_bb_top_big, p_bb_top_big_2, color = bb_color_big_2, title = "BB Top Big Zone")
fill(p_bb_bot_big, p_bb_bot_big_2, color = bb_color_big_2, title = "BB Bottom Big Zone")
// 2. Select Moving Averages Multy timeframe
mas_type = input.string("SMA", title = "Select Ma Type", options = ["EMA","SMMA","SMA"], group = "Select MA")
// 2-1. EMA Multy timeframe
ema_len = input.int(200, minval=1, title="EMA Length", group = "EMA")
ema_src = input(close, title="EMA Source", group = "EMA")
ema = ta.ema(close, ema_len)
ema_big = nonRepaintingSecurity(syminfo.tickerid, big_interval, ema)
ema_big_2 = nonRepaintingSecurity(syminfo.tickerid, big_interval_2, ema)
// 2-2. SMMA Multy timeframe
smma_len = input.int(7, minval=1, title="SMMA Length", group = "SMMA")
smma_src = input(close, title="SMMA Source", group = "SMMA")
smma = 0.0
smma_high = 0.0
smma_low = 0.0
smma := na(smma[1]) ? ta.sma(smma_src, smma_len) : (smma[1] * (smma_len - 1) + smma_src) / smma_len
smma_high := na(smma_high[1]) ? ta.sma(high, smma_len) : (smma_high[1] * (smma_len - 1) + high) / smma_len
smma_low := na(smma_low[1]) ? ta.sma(low, smma_len) : (smma_low[1] * (smma_len - 1) + low) / smma_len
// smma big
smma_big_src = nonRepaintingSecurity(syminfo.tickerid, big_interval ,close)
smma_big = 0.0
smma_big := na(smma_big[big_mult]) ? nonRepaintingSecurity(syminfo.tickerid, big_interval ,ta.sma(smma_big_src, smma_len)) : (smma_big[big_mult] * (smma_len - 1) + smma_big_src) / smma_len
// smma big 2
smma_big_src_2 = nonRepaintingSecurity(syminfo.tickerid, big_interval_2 ,close)
smma_big_2 = 0.0
smma_big_2 := na(smma_big_2[big_mult_2]) ? nonRepaintingSecurity(syminfo.tickerid, big_interval_2 ,ta.sma(smma_big_src_2, smma_len)) : (smma_big_2[big_mult_2] * (smma_len - 1) + smma_big_src_2) / smma_len
// 2-3. SMA Multy timeframe
sma_len = input.int(20, minval=1, title="SMA Length", group = "SMA")
sma_src = input(close, title="SMA Source", group = "SMA")
sma = ta.sma(close, sma_len)
sma_big = nonRepaintingSecurity(syminfo.tickerid, big_interval, sma)
sma_big_2 = nonRepaintingSecurity(syminfo.tickerid, big_interval_2, sma)
// draw
mas = close
mas_big = close
mas_big_2 = close
if mas_type == "EMA"
mas := ema
mas_big := ema_big
mas_big_2 := ema_big_2
if mas_type == "SMMA"
mas := smma
mas_big := smma_big
mas_big_2 := smma_big_2
if mas_type == "SMA"
mas := sma
mas_big := sma_big
mas_big_2 := sma_big_2
mas_up_color = input.color(color.new(color.green,20), group = "Select MA")
mas_down_color = input.color(color.new(color.red,20), group = "Select MA")
mas_up_color_big = input.color(color.new(color.green,70), group = "Select MA")
mas_down_color_big = input.color(color.new(color.fuchsia,70), group = "Select MA")
mas_trend = mas > mas_big ? true : false
mas_trend_color = mas_trend ? mas_up_color : mas_down_color
mas_trend_big = mas_big > mas_big_2 ? true : false
mas_trend_big_color = mas_trend_big ? mas_up_color_big : mas_down_color_big
p_mas = plot(mas, color = mas_trend_color, title = "MA 1")
p_mas_big = plot(mas_big, color = mas_trend_color, title = "MA 2")
p_mas_big_2 = plot(mas_big_2, color = mas_trend_big_color , title = "MA 3")
fill(p_mas, p_mas_big, color = mas_trend_color, title = "MA Trend")
fill(p_mas_big, p_mas_big_2, color = mas_trend_big_color, title = "MA Big Trend") |
Distance from the High/Low price | https://www.tradingview.com/script/fNoJM9lo/ | Seungdori_ | https://www.tradingview.com/u/Seungdori_/ | 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/
// © Seungdori_
//@version=5
indicator('Distance from the High/Low price', precision=3, overlay=false)
// Input//
length = input.int(defval = 400, title = 'Lengths', minval = 1, group = 'High/Low')
src = input.string(defval = 'High/Low', options = ['Close', 'High/Low'], group = 'High/Low')
show_maxmin = input.bool(defval = false, title = 'Show Maximum High Line ?', group = 'High/Low')
show_table = input.bool(defval = true, title = 'Show table?')
show_retracement = input.bool(defval = false, title = 'Show Retracement Ratio?', group = 'Retracement')
reverse_retracement = input.bool(defval = false, title = 'Reverse Retracement?', group = 'Retracement')
hi_source = close
lo_source = close
if src == 'Close'
hi_source := close
lo_source := close
if src == 'High/Low'
hi_source := low
lo_source := high
//Var//
Distance_from_PH = 0.
Distance_to_PH = 0.
PH_reached = false
Distance_from_PL = 0.
Distance_to_PL = 0.
PL_reached = false
//Pivots//
highest_1 = ta.highest(high, length)
lowest_1 = ta.lowest(low, length)
if bar_index >= 1
Distance_from_PH := math.round(100 * (1 - (lo_source / highest_1)),2)
Distance_from_PL := math.round(100 * ((hi_source/lowest_1)-1),2)
if Distance_from_PH == 0
PH_reached := true
PH_reached
plotshape(PH_reached, title='Top renew', color=color.new(#94ee6d, 10), style=shape.circle, location = location.top)
if Distance_from_PL == 0
PL_reached := true
PL_reached
plotshape(PL_reached, title='Bottom renew', color=color.new(#f18080, 10), style=shape.circle, location = location.top)
max_up = ta.highest(Distance_from_PL, length)
//Retracement//
Retracement = 1-math.round((close-lowest_1)/(highest_1-lowest_1),2)
if reverse_retracement
Retracement := math.round((close-lowest_1)/(highest_1-lowest_1),2)
//Plots//
plot(Distance_from_PH, 'Distance from Bottom (%)', color=color.new(color.maroon, 0), linewidth=1)
plot(Distance_from_PL, 'Distance from Top (%)', color=color.new(color.green, 0), linewidth=1)
plot(show_retracement ? Retracement*100 : na, 'REt', color=color.new(color.white, 0), linewidth=1)
plot(show_maxmin ? max_up : na, title = 'Maximum High from Bottom', color=color.new(#4f884b, 0), style=plot.style_line, trackprice = true)
hline(show_retracement ? 75 : na, '0.75', color=color.new(color.white, 60), linewidth=1)
hline(show_retracement ? 50 : na, '0.5', color=color.new(color.white, 60), linewidth=1)
hline(show_retracement ? 25 : na, '0.25', color=color.new(color.white, 60), linewidth=1)
h_0 = hline(0, '0% line', color=color.new(color.white, 80))
if (barstate.islast)
line.new(bar_index[length], 0, bar_index[length], 0 * 1.01, extend = extend.both, color=color.new(color.white, 30), style = line.style_dashed)
if show_table
var Table = table.new(position = position.top_right, columns = 4, rows = 4, frame_width = 1, bgcolor = color.rgb(0,0,0, 50), border_width = 1, border_color = color.gray, frame_color = color.gray)
table.cell(table_id = Table, column = 0, row = 1, text = 'From Bottom :', text_color = color.white)
table.cell(table_id = Table, column = 0, row = 2, text = 'From Top:', text_color = color.white)
if show_retracement
table.cell(table_id = Table, column = 0, row = 3, text = 'Retrace Ratio:', text_color = color.white)
table.cell(table_id = Table, column = 1, row = 1, text = str.tostring(Distance_from_PL)+'%', text_color =color.new(color.green, 0))
table.cell(table_id = Table, column = 1, row = 2, text = str.tostring(Distance_from_PH)+'%', text_color =color.new(color.maroon, 0))
if show_retracement
table.cell(table_id = Table, column = 1, row = 3, text = str.tostring(Retracement), text_color =color.new(color.white, 10))
|
Cuck Wick | https://www.tradingview.com/script/Y7wktqTK-Cuck-Wick/ | Kila_Whale | https://www.tradingview.com/u/Kila_Whale/ | 453 | 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/
// © KiLA-WHALE
// What's a cuck wick? It's that fast stophunting wick that cucks everyone by triggering their stoploss and liquidation.
// This indicator is dedicated to my friend Alexandru who saved me from getting liquidated by one of these scam wicks which almost liquidated me.
// Alexandru is one of the best scalpers out there and he always nails his entries at the tip of these wicks. This inspired me to create this indicator.
//@version=5
// Declare indicator name
indicator('Cuck Wick', overlay=true)
// Define variables
Wick_Ratio = input(2,'Wick Ratio',tooltip = 'Candle wick to body size ratio.')
Candle_Ratio = input(0.75, 'Candle Ratio', tooltip = 'Percentage of current price.')
Bull_Candle_Colour = input(color.aqua, 'Bull Candle Colour',tooltip = 'Colour of the bullish cuck candle.')
Bear_Candle_Colour = input(color.orange, 'Bear Candle Colour',tooltip = 'Colour of the bearish cuck candle.')
// Calculate the size of the body of a candle
body = math.abs(close - open)
// Calculate the size of the upper wick of a candle
upper_wick = high - math.max(open, close)
// Calculate the size of the lower wick of a candle
lower_wick = math.min(open, close) - low
// Find bull cuck by calculating size of the wick and body
BullCuck = body + upper_wick + lower_wick >= (Candle_Ratio * close) / 100 and (upper_wick > (body + lower_wick) * Wick_Ratio)
// Find bear cuck by calculating size of the wick and body
BearCuck = body + upper_wick + lower_wick >= (Candle_Ratio * close) / 100 and (lower_wick > (body + upper_wick) * Wick_Ratio)
// Highlight cuck wick with the specified colours
Cuck_Wick = (BullCuck ? Bull_Candle_Colour : BearCuck ? Bear_Candle_Colour : na)
// Calculate size of the current bull candle
Current_Bull = close - open >= (Candle_Ratio * close) / 100
// Calculate size of the current bear candle
Current_Bear = open - close >= (Candle_Ratio * close) / 100
// Calculate current cuck candle
Cuck_Candle = (Current_Bull ? Bull_Candle_Colour : Current_Bear ? Bear_Candle_Colour : na)
// Find the current candle
Current_Candle = barstate.islast ? 1 : 0
// Highlight cuck candles and cuck wicks
barcolor(Current_Candle ? Cuck_Candle : Cuck_Wick) |
Faytterro Market Structere | https://www.tradingview.com/script/RUNiTECF-Faytterro-Market-Structere/ | faytterro | https://www.tradingview.com/u/faytterro/ | 538 | 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/
// © faytterro
//@version=5
indicator("Faytterro Market Structere", overlay = true, max_bars_back =2000)
max_bars_back(time, 2000)
n = input.int(10, "length", minval = 1)
g = input.int(0,"go to past",minval = 0)
h = true
h0 = true
if last_bar_index-bar_index<500+g*n*2
for i=0 to 2*n
h := h and high[n]>=high[i]
h0 := h0 and high>=high[math.round(i/2)]
lows = array.new_float()
lows2 = array.new_float()
a = ta.valuewhen(h, bar_index,0+g)
b = ta.valuewhen(h, bar_index,1+g)
c = ta.valuewhen(h0, bar_index,0+g)
lb = last_bar_index
for i = 0 to a-b-1
array.push(lows,low[i+lb-a+n])
thelow=array.min(lows)
lowindex=array.indexof(lows,thelow)
for i = 0 to c>a? c+n-a-1 : c+n-b-1
array.push(lows2,low[i+lb-c])
thelow2=array.min(lows2)
lowindex2=array.indexof(lows2,thelow2)
hp = ta.valuewhen(h, high[n],0+g)
hp1 = ta.valuewhen(h, high[n],1+g)
flows = array.new_float()
for i = 0 to lb-a-1+n
array.push(flows,low[i])
theflow=array.min(flows)
theflowindex=array.indexof(flows,theflow)
linebot = line.new(-lowindex2-n+a*0+c+n, thelow2,last_bar_index+10, thelow2, style = line.style_dashed, color= color.rgb(233, 111, 111))
line.delete(linebot[1])
linetop = line.new( a-n, hp, last_bar_index+10, hp, color= color.rgb(123, 235, 130), style = line.style_dashed)
line.delete(linetop[1])
line = line.new(-lowindex-n+a, thelow, a-n, hp, color= hp>hp1? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line[1])
line2 = line.new(b-n,hp1,-lowindex-n+a, thelow, color= hp>hp1? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line2[1])
lineo= line.new(-lowindex2-n+a*0+c+n, thelow2, a-n, hp, color= thelow2<thelow? color.rgb(233, 111, 111) : hp>hp1? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(lineo[1])
//////////////////////////////////////////
dt = math.round(100*hp*100/close-10000)/100
dd = math.round(100*thelow2*100/close-10000)/100
var tbl = table.new(position.top_center, 2, 2, color.rgb(120, 123, 134, 100), color.rgb(0,0,0,100), 1, color.rgb(255, 255, 255,100), 5)
if barstate.islast
table.cell(tbl, 0, 1, str.tostring(dt)+"%", width = 10,
text_color = color.rgb(0, 0, 0), bgcolor = color.rgb(100, 255, 100,50), text_size = size.large) //table_id = testTable, column = 0, row = 0, text = "Open is " + str.tostring(open))
table.cell(tbl, 1, 1, str.tostring(dd)+"%", width = 10,
text_color = color.rgb(255, 255, 255), bgcolor = color.rgb(255, 0, 0,50), text_size = size.large)
table.cell(tbl, 0, 0, "distance\n to the high", width = 2,
text_color = color.rgb(0, 0, 0), bgcolor = color.rgb(100, 255, 100,50), text_size = size.normal) //table_id = testTable, column = 0, row = 0, text = "Open is " + str.tostring(open))
table.cell(tbl, 1, 0,"distance\n to the low", width = 2,
text_color = color.rgb(255, 255, 255), bgcolor = color.rgb(255, 0, 0,50), text_size = size.normal)
msbb = label.new(ta.valuewhen(ta.crossunder(dt,0), bar_index,0),ta.valuewhen(ta.crossunder(dt,0), low,0), "MSB", color=color.rgb(0, 153, 5), textcolor = color.white, style= label.style_label_up)
label.delete(msbb[1])
msbs = label.new(ta.valuewhen(ta.crossover(dd,0), bar_index,0),ta.valuewhen(ta.crossover(dd,0), high,0), "MSB", color=color.rgb(153, 0, 0), textcolor = color.white)
label.delete(msbs[1])
/////////////////////
lows2p = array.new_float()
a2 = ta.valuewhen(h, bar_index,1+g)
b2 = ta.valuewhen(h, bar_index,2+g)
for i = 0 to a2-b2-1
array.push(lows2p,low[i+lb-a2+n])
thelow2p=array.min(lows2p)
lowindex2p=array.indexof(lows2p,thelow2p)
hp2 = ta.valuewhen(h, high[n],1+g)
hp12 = ta.valuewhen(h, high[n],2+g)
line21 = line.new(-lowindex2p-n+a2, thelow2p, a2-n, hp2, color= hp2>hp12? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line21[1])
line22 = line.new(b2-n,hp12,-lowindex2p-n+a2, thelow2p, color= hp2>hp12? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line22[1])
/////////////////
lows3 = array.new_float()
a3 = ta.valuewhen(h, bar_index,2+g)
b3= ta.valuewhen(h, bar_index,3+g)
for i = 0 to a3-b3-1
array.push(lows3,low[i+lb-a3+n])
thelow3=array.min(lows3)
lowindex3=array.indexof(lows3,thelow3)
hp3= ta.valuewhen(h, high[n],2+g)
hp13 = ta.valuewhen(h, high[n],3+g)
line31 = line.new(-lowindex3-n+a3, thelow3, a3-n, hp3, color= hp3>hp13? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line31[1])
line32 = line.new(b3-n,hp13,-lowindex3-n+a3, thelow3, color= hp3>hp13? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line32[1])
//////////////////////////////
lows4 = array.new_float()
a4 = ta.valuewhen(h, bar_index,3+g)
b4= ta.valuewhen(h, bar_index,3+1+g)
for i = 0 to a4-b4-1
array.push(lows4,low[i+lb-a4+n])
thelow4=array.min(lows4)
lowindex4=array.indexof(lows4,thelow4)
hp4= ta.valuewhen(h, high[n],3+g)
hp14 = ta.valuewhen(h, high[n],3+1+g)
line41 = line.new(-lowindex4-n+a4, thelow4, a4-n, hp4, color= hp4>hp14? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line41[1])
line42 = line.new(b4-n,hp14,-lowindex4-n+a4, thelow4, color= hp4>hp14? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line42[1])
///////////////////////////
lows5= array.new_float()
a5 = ta.valuewhen(h, bar_index,4+g)
b5 = ta.valuewhen(h, bar_index,4+1+g)
for i = 0 to a5-b5-1
array.push(lows5,low[i+lb-a5+n])
thelow5=array.min(lows5)
lowindex5=array.indexof(lows5,thelow5)
hp5 = ta.valuewhen(h, high[n],4+g)
hp15 = ta.valuewhen(h, high[n],4+1+g)
line51 = line.new(-lowindex5-n+a5, thelow5, a5-n, hp5, color= hp5>hp15? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line51[1])
line52 = line.new(b5-n,hp15,-lowindex5-n+a5, thelow5, color= hp5>hp15? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line52[1])
////////////////////////
lows := array.new_float()
a := ta.valuewhen(h, bar_index,5+g)
b := ta.valuewhen(h, bar_index,5+1+g)
for i = 0 to a-b-1
array.push(lows,low[i+lb-a+n])
thelow:=array.min(lows)
lowindex:=array.indexof(lows,thelow)
hp := ta.valuewhen(h, high[n],5+g)
hp1 := ta.valuewhen(h, high[n],5+1+g)
line61 = line.new(-lowindex-n+a, thelow, a-n, hp, color= hp>hp1? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line61[1])
line62 = line.new(b-n,hp1,-lowindex-n+a, thelow, color= hp>hp1? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line62[1])
////////////////////////
lows := array.new_float()
a := ta.valuewhen(h, bar_index,6+g)
b := ta.valuewhen(h, bar_index,6+1+g)
for i = 0 to a-b-1
array.push(lows,low[i+lb-a+n])
thelow:=array.min(lows)
lowindex:=array.indexof(lows,thelow)
hp := ta.valuewhen(h, high[n],6+g)
hp1 := ta.valuewhen(h, high[n],6+1+g)
line71 = line.new(-lowindex-n+a, thelow, a-n, hp, color= hp>hp1? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line71[1])
line72 = line.new(b-n,hp1,-lowindex-n+a, thelow, color= hp>hp1? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line72[1])
///////////////////////////////////
lows := array.new_float()
a := ta.valuewhen(h, bar_index,7+g)
b := ta.valuewhen(h, bar_index,7+1+g)
for i = 0 to a-b-1
array.push(lows,low[i+lb-a+n])
thelow:=array.min(lows)
lowindex:=array.indexof(lows,thelow)
hp := ta.valuewhen(h, high[n],7+g)
hp1 := ta.valuewhen(h, high[n],7+1+g)
line81 = line.new(-lowindex-n+a, thelow, a-n, hp, color= hp>hp1? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line81[1])
line82 = line.new(b-n,hp1,-lowindex-n+a, thelow, color= hp>hp1? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line82[1])
///////////////////////////////////////
lows := array.new_float()
a := ta.valuewhen(h, bar_index,8+g)
b := ta.valuewhen(h, bar_index,8+1+g)
for i = 0 to a-b-1
array.push(lows,low[i+lb-a+n])
thelow:=array.min(lows)
lowindex:=array.indexof(lows,thelow)
hp := ta.valuewhen(h, high[n],8+g)
hp1 := ta.valuewhen(h, high[n],8+1+g)
line91 = line.new(-lowindex-n+a, thelow, a-n, hp, color= hp>hp1? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line91[1])
line92 = line.new(b-n,hp1,-lowindex-n+a, thelow, color= hp>hp1? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line92[1])
////////////////
lows := array.new_float()
a := ta.valuewhen(h, bar_index,9+g)
b := ta.valuewhen(h, bar_index,9+1+g)
for i = 0 to a-b-1
array.push(lows,low[i+lb-a+n])
thelow:=array.min(lows)
lowindex:=array.indexof(lows,thelow)
hp := ta.valuewhen(h, high[n],9+g)
hp1 := ta.valuewhen(h, high[n],9+1+g)
line101 = line.new(-lowindex-n+a, thelow, a-n, hp, color= hp>hp1? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line101[1])
line102 = line.new(b-n,hp1,-lowindex-n+a, thelow, color= hp>hp1? color.rgb(123,235,130) : color.rgb(233, 111, 111))
line.delete(line102[1])
//////////////////
|
Zazzamira 50-25-25 Trend System Alerts Only | https://www.tradingview.com/script/PrCnYJO2-Zazzamira-50-25-25-Trend-System-Alerts-Only/ | philipbianchi | https://www.tradingview.com/u/philipbianchi/ | 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/
// © Hiubris_Indicators
//@version=5
indicator(title = "Opening Range Levels Alerts Only", overlay = true)
// Open Session
tz0 = input.string('UTC-5', title="Timezone", inline='tz', group='Time-Range Settings')
auto_tz = input(true, title="Exchange Timezone", inline='tz', group='Time-Range Settings')
tz = auto_tz? syminfo.timezone : tz0
timeinput = input.session('0830-0915', title="Asian Range", group='Time-Range Settings') + ':1234567'
tses_time = time(timeframe.period, timeinput, tz)
tses = na(tses_time) ? 0 : 1
end_t = tses[1] and not tses
start_t = tses and not tses[1]
// Trading Session
session = input.session("0915-1300", title="Trading Time")+":1234567"
t = time(timeframe.period, session, tz)
trading_session_filter = na(t) ? 0 : 1
t_exit = time(timeframe.period, "1500-0000:1234567", tz)
trading_session_exit = na(t_exit) ? 0 : 1
// Highs Lows - Open sesssion
h = 0.0
l = 0.0
h := start_t ? high : tses and high > h[1] ? high : h[1]
l := start_t ? low : tses and low < l[1] ? low : l[1]
r = h-l
last_start_n = ta.valuewhen(start_t, bar_index, 0)
//col = input.color(color.orange, title="Levels Color")
draw_level(txt, x, col)=>
if start_t
line.new (bar_index-4, x, last_start_n[1], x, color=col)
label.new(bar_index-10, x, style=label.style_none, text=txt, color=col, textcolor=col)
l1 = h+r*0.216
l2 = h+r*0.618
l3 = h+r*1
l4 = h+r*1.618
s1 = l-r*0.216
s2 = l-r*0.618
s3 = l-r*1
s4 = l-r*1.618
plot(tses? na : h, style=plot.style_linebr, title="H", color=color.green)
plot(tses? na : l, style=plot.style_linebr, title="L", color=color.green)
plot(tses? na : l1, style=plot.style_linebr, title="Fib 1", color=color.orange)
plot(tses? na : l2, style=plot.style_linebr, title="Fib 2", color=color.orange)
plot(tses? na : l3, style=plot.style_linebr, title="Fib 3", color=color.orange)
plot(tses? na : l4, style=plot.style_linebr, title="Fib 4", color=color.orange)
plot(tses? na : s1, style=plot.style_linebr, title="Fib 1", color=color.orange)
plot(tses? na : s2, style=plot.style_linebr, title="Fib 2", color=color.orange)
plot(tses? na : s3, style=plot.style_linebr, title="Fib 3", color=color.orange)
plot(tses? na : s4, style=plot.style_linebr, title="Fib 4", color=color.orange)
//draw_level('H' , h[1], color.gray )
//draw_level('Fib 23.6% ' , l1, color.yellow)
//draw_level('Fib 61.8% ' , l2, color.orange)
//draw_level('Fib 100% ' , l3, color.orange)
//draw_level('Fib 161.8% ', l4, color.orange)
//draw_level('H' , l[1], color.gray )
//draw_level('Fib 23.6% ' , s1, color.yellow)
//draw_level('Fib 61.8% ' , s2, color.orange)
//draw_level('Fib 100% ' , s3, color.orange)
//draw_level('Fib 161.8% ', s4, color.orange)
bgcolor(tses?color.new(color.orange , 80):na)
plotshape(ta.crossover (close, h) and not tses and trading_session_filter, textcolor=color.lime, color=color.lime, style=shape.triangleup , title="Cross", text="" , location=location.belowbar, offset=0, size=size.tiny)
plotshape(ta.crossunder(close, l) and not tses and trading_session_filter, textcolor=color.red, color=color.red, style=shape.triangledown, title="Cross", text="", location=location.abovebar, offset=0, size=size.tiny)
// ————— MA
ribbon_grp = "MA SETTINGS"
ma(source, length, type) =>
type == "SMA" ? ta.sma(source, length) :
type == "EMA" ? ta.ema(source, length) :
type == "SMMA (RMA)" ? ta.rma(source, length) :
type == "WMA" ? ta.wma(source, length) :
type == "VWMA" ? ta.vwma(source, length) :
na
ma1_type = input.string("EMA" , "" , inline="MA #1", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group=ribbon_grp)
ma1_source = input.source(close , "" , inline="MA #1", group=ribbon_grp)
ma1_length = input.int (5 , "" , inline="MA #1", minval=1, group=ribbon_grp)
ma1 = ma(ma1_source, ma1_length, ma1_type)
plot(ma1, color = color.green, title="MA №1")
ma2_type = input.string("EMA" , "" , inline="MA #2", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group=ribbon_grp)
ma2_source = input.source(close , "" , inline="MA #2", group=ribbon_grp)
ma2_length = input.int (13 , "" , inline="MA #2", minval=1, group=ribbon_grp)
ma2 = ma(ma2_source, ma2_length, ma2_type)
plot(ma2, color = color.orange, title="MA №2")
use_3 = input(true, title='Use 3rd MA as Entry Condition')
ma3_type = input.string("EMA" , "" , inline="MA #3", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group=ribbon_grp)
ma3_source = input.source(close , "" , inline="MA #3", group=ribbon_grp)
ma3_length = input.int (34 , "" , inline="MA #3", minval=1, group=ribbon_grp)
ma3 = ma(ma3_source, ma3_length, ma3_type)
plot(ma3, color = color.blue, title="MA №3")
ma4_type = input.string("EMA" , "" , inline="MA #4", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group=ribbon_grp)
ma4_source = input.source(close , "" , inline="MA #4", group=ribbon_grp)
ma4_length = input.int (50 , "" , inline="MA #4", minval=1, group=ribbon_grp)
ma4 = ma(ma4_source, ma4_length, ma4_type)
plot(ma4, color = color.red, title="MA #4")
ma_long = ma1>ma2 and ma2>ma3 and ma3>ma4
ma_short= ma1<ma2 and ma2<ma3 and ma3<ma4
long0 = ma_long and trading_session_filter and high<l1 and ta.crossover (close, h)
short0= ma_short and trading_session_filter and low >s1 and ta.crossunder(close, l)
long_setup = 0
long_setup:= high>l1? 0 : long0? 1 : long_setup[1]
long = low<h and long_setup[1]==1
if long
long_setup := 0
short_setup = 0
short_setup:= low<s1? 0 : short0? 1 : short_setup[1]
short = high>l and short_setup[1]==1
if short
short_setup := 0
retest = input(true, title='Use RETEST')
longf = retest? long : long0
shortf= retest? short : short0
// Position Management Tools
pos = 0.0
pos:= longf? 1 : shortf? -1 : pos[1]
longCond = longf and (pos[1]!= 1 or na(pos[1]))
shortCond = shortf and (pos[1]!=-1 or na(pos[1]))
// EXIT FUNCTIONS //
atr = ta.atr(14)
sl = input.float(1.0, title="Initial Stop Loss ATR", minval=0, step=0.1)
atr_long = ta.valuewhen(longCond , atr, 0)
atr_short = ta.valuewhen(shortCond, atr, 0)
tp_long = l3
tp_short = s3
// Inprofit
inprofit_long = 0
inprofit_short = 0
inprofit_long := pos==0 or longCond ? 0 : high>l1[1]? 1 : inprofit_long [1]
inprofit_short := pos==0 or shortCond? 0 : low <s1[1]? 1 : inprofit_short[1]
inprofit_long2 = 0
inprofit_short2 = 0
inprofit_long2 := pos==0 or longCond ? 0 : high>l2[1]? 1 : inprofit_long2 [1]
inprofit_short2 := pos==0 or shortCond? 0 : low <s2[1]? 1 : inprofit_short2[1]
// Trailing Stop Loss
trail_long = 0.0, trail_short = 0.0
trail_long := long0 ? h : longCond ? high : high>trail_long[1]? high : pos<1 ? 0 : trail_long[1]
trail_short := short0? l : shortCond? low : low<trail_short[1]? low : pos>-1 ? 99999 : trail_short[1]
trail_long_final1 = trail_long - sl * atr_long
trail_short_final1 = trail_short + sl * atr_short
trail_long_final2 = trail_long - r * 0.236
trail_short_final2 = trail_short + r * 0.236
trail_long_final3 = trail_long - r * 0.382
trail_short_final3 = trail_short + r * 0.382
sl_long = inprofit_long2 ? trail_long_final3 : inprofit_long ? trail_long_final2 : trail_long_final1
sl_short = inprofit_short2? trail_short_final3 : inprofit_short? trail_short_final2 : trail_short_final1
// Position Adjustment
long_sl = low <sl_long[1] and pos[1]== 1
short_sl = high>sl_short[1] and pos[1]==-1
final_long_tp = high>tp_long[1] and pos[1]== 1
final_short_tp = low <tp_short[1] and pos[1]==-1
if ((long_sl or final_long_tp) and not shortCond) or ((short_sl or final_short_tp) and not longCond)
pos:=0
long_tp1 = l1
long_tp2 = l2
long_tp3 = l3
short_tp1 = s1
short_tp2 = s2
short_tp3 = s3
pre_long_tp1 = 0.0 , pre_long_tp2 = 0.0 , pre_long_tp3 = 0.0, pre_long_tp4 = 0.0
pre_short_tp1 = 0.0 , pre_short_tp2 = 0.0 , pre_short_tp3 = 0.0, pre_short_tp4 = 0.0
pre_long_tp1 := longCond? 1 : (high>long_tp1[1])? 0 : pre_long_tp1[1]
pre_long_tp2 := longCond? 1 : (high>long_tp2[1])? 0 : pre_long_tp2[1]
pre_long_tp3 := longCond? 1 : (high>long_tp3[1])? 0 : pre_long_tp3[1]
pre_short_tp1 := shortCond? 1 : (low<short_tp1[1])? 0 : pre_short_tp1[1]
pre_short_tp2 := shortCond? 1 : (low<short_tp2[1])? 0 : pre_short_tp2[1]
pre_short_tp3 := shortCond? 1 : (low<short_tp3[1])? 0 : pre_short_tp3[1]
tp_long1 = high>long_tp1[1] and pre_long_tp1[1] and pos[1]==1
tp_long2 = high>long_tp2[1] and pre_long_tp2[1] and pos[1]==1
tp_long3 = high>long_tp3[1] and pre_long_tp3[1] and pos[1]==1
tp_short1 = low<short_tp1[1] and pre_short_tp1[1] and pos[1]==-1
tp_short2 = low<short_tp2[1] and pre_short_tp2[1] and pos[1]==-1
tp_short3 = low<short_tp3[1] and pre_short_tp3[1] and pos[1]==-1
long_exit = trading_session_exit and pos[1]== 1
short_exit= trading_session_exit and pos[1]==-1
if (long_exit and not shortCond) or (short_exit and not longCond)
pos:=0
// DEBUGGING
bgcolor(long ?color.new(color.green , 80):na)
bgcolor(short?color.new(color.red , 80):na)
bgcolor(false?color.new(color.white , 80):na)
bgcolor(false?color.new(color.orange , 80):na)
// Chart Plot & Alerts
plotshape(longCond, textcolor=color.lime, color=color.lime, style=shape.triangleup , title="Buy" , text="Buy" , location=location.belowbar, offset=0, size=size.small)
plotshape(shortCond, textcolor=color.red, color=color.red, style=shape.triangledown, title="Sell", text="Sell", location=location.abovebar, offset=0, size=size.small)
plotshape(long_exit, textcolor=color.purple, color=color.purple, style=shape.circle, text="Long Exit" , title="Long Exit" , location=location.abovebar, offset=0, size=size.tiny)
plotshape(short_exit, textcolor=color.purple, color=color.purple, style=shape.circle, text="Short Exit", title="Short Exit", location=location.belowbar, offset=0, size=size.tiny)
plotshape(long_sl , textcolor=color.purple, color=color.purple, style=shape.circle, text="SL" , location=location.belowbar, offset=0, size=size.tiny)
plotshape(short_sl, textcolor=color.purple, color=color.purple, style=shape.circle, text="SL", location=location.abovebar, offset=0, size=size.tiny)
plotshape(tp_long1 , textcolor=color.purple, color=color.purple, style=shape.circle, text="TP1" , location=location.abovebar, offset=0, size=size.tiny)
plotshape(tp_short1, textcolor=color.purple, color=color.purple, style=shape.circle, text="TP1", location=location.belowbar, offset=0, size=size.tiny)
plotshape(tp_long2 , textcolor=color.purple, color=color.purple, style=shape.circle, text="TP2" , location=location.abovebar, offset=0, size=size.tiny)
plotshape(tp_short2, textcolor=color.purple, color=color.purple, style=shape.circle, text="TP2", location=location.belowbar, offset=0, size=size.tiny)
plotshape(tp_long3 , textcolor=color.purple, color=color.purple, style=shape.circle, text="TP3" , location=location.abovebar, offset=0, size=size.tiny)
plotshape(tp_short3, textcolor=color.purple, color=color.purple, style=shape.circle, text="TP3", location=location.belowbar, offset=0, size=size.tiny)
longCond_txt = input.text_area("", title='Alert Msg: LONG Entry', group='Alert Message')
shortCond_txt = input.text_area("", title='Alert Msg: SHORT Entry', group='Alert Message')
long_tp1_txt = input.text_area("", title='Alert Msg: LONG TP1', group='Alert Message')
short_tp1_txt = input.text_area("", title='Alert Msg: SHORT TP1', group='Alert Message')
long_tp2_txt = input.text_area("", title='Alert Msg: LONG TP2', group='Alert Message')
short_tp2_txt = input.text_area("", title='Alert Msg: SHORT TP2', group='Alert Message')
long_tp3_txt = input.text_area("", title='Alert Msg: LONG TP3', group='Alert Message')
short_tp3_txt = input.text_area("", title='Alert Msg: SHORT TP3', group='Alert Message')
long_exit_txt = input.text_area("", title='Alert Msg: LONG Time Exit', group='Alert Message')
short_exit_txt = input.text_area("", title='Alert Msg: SHORT Time Exit', group='Alert Message')
long_sl_txt = input.text_area("", title='Alert Msg: LONG SL', group='Alert Message')
short_sl_txt = input.text_area("", title='Alert Msg: SHORT SL', group='Alert Message')
if longCond
alert(longCond_txt, alert.freq_once_per_bar)
if shortCond
alert(shortCond_txt, alert.freq_once_per_bar)
if long_sl
alert(long_sl_txt, alert.freq_once_per_bar)
if short_sl
alert(short_sl_txt, alert.freq_once_per_bar)
if tp_long1
alert(long_tp1_txt, alert.freq_once_per_bar)
if tp_short1
alert(short_tp1_txt, alert.freq_once_per_bar)
if tp_long2
alert(long_tp2_txt, alert.freq_once_per_bar)
if tp_short2
alert(short_tp2_txt, alert.freq_once_per_bar)
if tp_long3
alert(long_tp3_txt, alert.freq_once_per_bar)
if tp_short3
alert(short_tp3_txt, alert.freq_once_per_bar)
if long_exit
alert(long_exit_txt, alert.freq_once_per_bar_close)
if short_exit
alert(short_exit_txt, alert.freq_once_per_bar_close)
|
Super 6x: RSI, MACD, Stoch, Loxxer, CCI, & Velocity [Loxx] | https://www.tradingview.com/script/U30edqhu-Super-6x-RSI-MACD-Stoch-Loxxer-CCI-Velocity-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 592 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Super 6x: RSI, MACD, Stoch, Loxxer, CCI, & Velocity [Loxx]",
shorttitle="S6XRMSDCV [Loxx]",
overlay = false)
greencolor = #2DD204
redcolor = #D2042D
_pulldat(src, res, rep)=>
out = request.security(syminfo.tickerid, res, src[rep ? 0 : barstate.isrealtime ? 1 : 0])[rep ? 0 : barstate.isrealtime ? 0 : 1]
out
_imom(src, length, powSlow, powFast)=>
suma = 0., sumwa=0.
sumb = 0., sumwb=0.
for k = 0 to length
weight = length-k
suma += nz(src[k]) * math.pow(weight, powSlow)
sumb += nz(src[k]) * math.pow(weight, powFast)
sumwa += math.pow(weight, powSlow)
sumwb += math.pow(weight, powFast)
out = (sumb/sumwb-suma/sumwa)
out
_dm(per, res, rep)=>
highin = _pulldat(high, res, rep)
lowin = _pulldat(low, res, rep)
demax = math.max(ta.change(highin), 0)
demin = -math.min(ta.change(lowin), 0)
maxma= ta.sma(demax, per)
minma = ta.sma(demin, per)
loxxer = 100 * maxma / (maxma + minma)
loxxer
loxxper = input(title='Loxxer Period', defval=14, group = "Loxxer Settings")
loxxres = input.timeframe("", 'Loxxer Resolution', group = "Loxxer Settings")
loxxrep = input(true, 'Loxxer Allow Repainting?', group = "Loxxer Settings")
macdsrcin = input.source(close, "MACD Source", group = "MACD Settings")
fmacd = input(title='MACD Fast Period', defval=12, group = "MACD Settings")
smacd = input(title='MACD Slow Period', defval=26, group = "MACD Settings")
macdres = input.timeframe("", 'MACD Resolution', group = "MACD Settings")
macdrep = input(true, 'MACD Allow Repainting?', group = "MACD Settings")
rsisrcin = input.source(close, "RSI Source", group = "RSI Settings")
rsiper = input.int(14, "RSI Period", group = "RSI Settings")
rsires = input.timeframe("", 'RSI Resolution', group = "RSI Settings")
rsirep = input(true, 'RSI Allow Repainting?', group = "RSI Settings")
velsrcin = input.source(close, "Velocity Source", group = "Velocity Settings")
velper = input.int(32, "Velocity Period", group = "Velocity Settings")
velfast = input.int(1, "Velocity Fast Period", group = "Velocity Settings")
velslow = input.int(2, "Velocity Slow Period", group = "Velocity Settings")
velres = input.timeframe("", 'Velocity Resolution', group = "Velocity Settings")
velrep = input(true, 'Velocity Allow Repainting?', group = "Velocity Settings")
ccisrcin = input.source(close, "CCI Source", group = "CCI Settings")
cciper = input.int(14, "CCI Period", group = "CCI Settings")
ccires = input.timeframe("", 'CCI Resolution', group = "CCI Settings")
ccirep = input(true, 'CCI Allow Repainting?', group = "CCI Settings")
periodK = input.int(14, title="Stochasitc %K Length", minval=1, group = "Stochasitc Settings")
smoothK = input.int(1, title="Stochasitc %K Smoothing", minval=1, group = "Stochasitc Settings")
periodD = input.int(3, title="Stochasitc %D Smoothing", minval=1, group = "Stochasitc Settings")
stochres = input.timeframe("", 'Stochasitc Resolution', group = "Stochasitc Settings")
stochrep = input(true, 'Stochasitc Allow Repainting?', group = "Stochasitc Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
macdsrc = _pulldat(macdsrcin, macdres, macdrep)
rsisrc = _pulldat(rsisrcin, rsires, rsirep)
velsrc = _pulldat(velsrcin, velres, velrep)
ccisrc = _pulldat(ccisrcin, ccires, ccirep)
stochhi =_pulldat(high, stochres, stochrep)
stochlo = _pulldat(low, stochres, stochrep)
stochclose = _pulldat(close, stochres, stochrep)
dmark = _dm(loxxper, loxxres, loxxrep)
[macd, _, _] = ta.macd(macdsrc, fmacd, smacd, 9)
rsi = ta.rsi(rsisrc, rsiper)
stoch = ta.sma(ta.stoch(stochclose, stochhi, stochlo, periodK), smoothK)
cci = ta.cci(ccisrc, cciper)
vel = _imom(velsrc, velper, velfast, velslow)
plotshape(1, color = dmark > 50 ? greencolor : redcolor, style = shape.circle, location = location.absolute)
plotshape(2, color = macd > 0 ? greencolor : redcolor, style = shape.circle, location = location.absolute)
plotshape(3, color = rsi > 50 ? greencolor : redcolor, style = shape.circle, location = location.absolute)
plotshape(4, color = stoch > 50 ? greencolor : redcolor, style = shape.circle, location = location.absolute)
plotshape(5, color = cci > 0 ? greencolor : redcolor, style = shape.circle, location = location.absolute)
plotshape(6, color = vel > 0 ? greencolor : redcolor, style = shape.circle, location = location.absolute)
colorout =
dmark > 50 and macd > 0 and rsi > 50 and stoch > 50 and cci > 0 and vel > 0 ? greencolor :
dmark < 50 and macd < 0 and rsi < 50 and stoch < 50 and cci < 0 and vel < 0 ? redcolor :
color.gray
barcolor(colorbars ? colorout : na)
goLong_pre = dmark > 50 and macd > 0 and rsi > 50 and stoch > 50 and cci > 0 and vel > 0
goShort_pre = dmark < 50 and macd < 0 and rsi < 50 and stoch < 50 and cci < 0 and vel < 0
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch
goLong = goLong_pre and ta.change(contSwitch)
goShort = goShort_pre and ta.change(contSwitch)
plotshape(colorout == redcolor ? 7 : na, style = shape.triangledown, location = location.absolute, size = size.auto, color = color.fuchsia)
plotshape(colorout == greencolor ? 0 : na, style = shape.triangleup, location = location.absolute, size = size.auto, color = color.yellow)
alertcondition(goLong, title="Long", message="Super 6x: RSI, MACD, Stoch, Loxxer, CCI, & Velocity [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Super 6x: RSI, MACD, Stoch, Loxxer, CCI, & Velocity [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Trampoline Dots | https://www.tradingview.com/script/w3ej2qYB-Trampoline-Dots/ | lnlcapital | https://www.tradingview.com/u/lnlcapital/ | 86 | 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
//
// Trampoline Dots (Price Divergence Dots)
//
// Trampoline Dots serve as a "quick bounce" tool. These little dots will trigger whenever the higher aggregation MACD is above / below zero and the price
// is below / above the 50 period simple moving average. When these criteria are met, the price is usually under pressure & reverse within the next few bars..
//
// Created by L&L Capital
//
indicator("Trampoline Dots", shorttitle = "Trampoline Dots", overlay=false)
// Inputs
length = input(defval= 50, title="MA Length")
// Trampoline Dots Calculations
funcM() =>
price = close
v1 = ta.ema(price , 12) - ta.ema(price , 26)
v2 = ta.ema(v1, 9)
data = (v1 - v2) * 3
currentPeriod = timeframe.period
CurrentAggPeriod = currentPeriod == '1' or currentPeriod == '2' ? request.security(syminfo.tickerid, '5', funcM())
: currentPeriod == '3' ? request.security(syminfo.tickerid, '10', funcM())
: currentPeriod == '5' ? request.security(syminfo.tickerid, '15', funcM())
: currentPeriod == '10' ? request.security(syminfo.tickerid, '30', funcM())
: currentPeriod == '15' ? request.security(syminfo.tickerid, '60', funcM())
: currentPeriod == '30' ? request.security(syminfo.tickerid, '120', funcM())
: currentPeriod == '45' ? request.security(syminfo.tickerid, '120', funcM())
: currentPeriod == '60' ? request.security(syminfo.tickerid, 'D', funcM())
: currentPeriod == '120' ? request.security(syminfo.tickerid, 'D', funcM())
: currentPeriod == '180' ? request.security(syminfo.tickerid, 'D', funcM())
: currentPeriod == '240' ? request.security(syminfo.tickerid, '2D', funcM())
: currentPeriod == 'D' ? request.security(syminfo.tickerid, 'W', funcM())
: currentPeriod == 'W' ? request.security(syminfo.tickerid, 'M', funcM())
: currentPeriod == 'M' ? request.security(syminfo.tickerid, '3M', funcM())
: na
price = CurrentAggPeriod
ema = ta.sma(close,50)
M = funcM()
// Plots
trampoline = if ((CurrentAggPeriod < 0 and close > ema) or (CurrentAggPeriod > 0 and close < ema))
0
color1 = close < ema ? #27c22e : #ff0000
plotshape(trampoline, title="Trampoline Dots", style=shape.circle, location=location.absolute, color = color1) |
PA-Adaptive T3 Loxxer [Loxx] | https://www.tradingview.com/script/zIIHaytd-PA-Adaptive-T3-Loxxer-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 212 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("PA-Adaptive T3 Loxxer [Loxx]",
shorttitle="PAAT3L [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxpaaspecial/1
darkGreenColor = #1B7E02
darkRedColor = #93021F
greencolor = #2DD204
redcolor = #D2042D
_iT3(src, per, hot, org)=>
a = hot
_c1 = -a * a * a
_c2 = 3 * a * a + 3 * a * a * a
_c3 = -6 * a * a - 3 * a - 3 * a * a * a
_c4 = 1 + 3 * a + a * a * a + 3 * a * a
alpha = 0.
if (org)
alpha := 2.0 / (1.0 + per)
else
alpha := 2.0 / (2.0 + (per - 1.0) / 2.0)
_t30 = src, _t31 = src
_t32 = src, _t33 = src
_t34 = src, _t35 = src
_t30 := nz(_t30[1]) + alpha * (src - nz(_t30[1]))
_t31 := nz(_t31[1]) + alpha * (_t30 - nz(_t31[1]))
_t32 := nz(_t32[1]) + alpha * (_t31 - nz(_t32[1]))
_t33 := nz(_t33[1]) + alpha * (_t32 - nz(_t33[1]))
_t34 := nz(_t34[1]) + alpha * (_t33 - nz(_t34[1]))
_t35 := nz(_t35[1]) + alpha * (_t34 - nz(_t35[1]))
out =
_c1 * _t35 + _c2 * _t34 +
_c3 * _t33 + _c4 * _t32
out
_dm(per, hot, org)=>
demax = math.max(ta.change(high), 0)
demin = -math.min(ta.change(low), 0)
maxma= _iT3(demax, per, hot, org)
minma = _iT3(demin, per, hot, org)
loxxer = 100 * maxma / (maxma + minma)
loxxer
smthtype = input.string("Kaufman", "Fast Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcin = input.string("Median", "Fast Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
t3hot = input.float(.5, "T3 Factor", step = 0.01, maxval = 1, minval = 0, group = "T3 Settings")
t3swt = input.bool(false, "T3 Original?", group = "T3 Settings")
fregcycles = input.float(1., title = "PA Cycles", group= "Phase Accumulation Cycle Settings")
fregfilter = input.float(0., title = "PA Filter", group= "Phase Accumulation Cycle Settings")
lbR = input(title="Pivot Lookback Right", defval=5, group = "Divergences Settings")
lbL = input(title="Pivot Lookback Left", defval=5, group = "Divergences Settings")
rangeUpper = input(title="Max of Lookback Range", defval=60, group = "Divergences Settings")
rangeLower = input(title="Min of Lookback Range", defval=5, group = "Divergences Settings")
plotBull = input(title="Plot Bullish", defval=true, group = "Divergences Settings")
plotHiddenBull = input(title="Plot Hidden Bullish", defval=false, group = "Divergences Settings")
plotBear = input(title="Plot Bearish", defval=true, group = "Divergences Settings")
plotHiddenBear = input(title="Plot Hidden Bearish", defval=false, group = "Divergences Settings")
bearColor = darkRedColor
bullColor = darkGreenColor
hiddenBullColor = color.new(darkGreenColor, 80)
hiddenBearColor = color.new(darkRedColor, 80)
textColor = color.white
noneColor = color.new(color.white, 100)
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showsignals = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
int flen = math.floor(loxxpaaspecial.paa(src, fregcycles, fregfilter))
flen := flen < 1 ? 1 : flen
out = _dm(flen, t3hot, t3swt)
sig = out[1]
colorout = out > sig ? greencolor : redcolor
osc = out
plFound = na(ta.pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(osc, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL = osc[lbR] > ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
// Price: Lower Low
priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bullCond = plotBull and priceLL and oscHL and plFound
plot(
plFound ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish",
linewidth=2,
color=(bullCond ? bullColor : noneColor)
)
plotshape(
bullCond ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish Label",
text="R",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor
)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL = osc[lbR] < ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
// Price: Higher Low
priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound
plot(
plFound ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish",
linewidth=2,
color=(hiddenBullCond ? hiddenBullColor : noneColor)
)
plotshape(
hiddenBullCond ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish Label",
text="H",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor
)
//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High
oscLH = osc[lbR] < ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
// Price: Higher High
priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
bearCond = plotBear and priceHH and oscLH and phFound
plot(
phFound ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish",
linewidth=2,
color=(bearCond ? bearColor : noneColor)
)
plotshape(
bearCond ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish Label",
text="R",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor
)
//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High
oscHH = osc[lbR] > ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
// Price: Lower High
priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)
hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound
plot(
phFound ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish",
linewidth=2,
color=(hiddenBearCond ? hiddenBearColor : noneColor)
)
plotshape(
hiddenBearCond ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish Label",
text="H",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor
)
plot(out, "T3 Loxxer", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
goLong = ta.crossover(out, sig)
goShort = ta.crossunder(out, sig)
plotshape(goLong and showsignals, title = "Long", color = greencolor, textcolor = greencolor, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(goShort and showsignals, title = "Short", color = redcolor, textcolor = redcolor, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="PA-Adaptive T3 Loxxer [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="PA-Adaptive T3 Loxxer [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(hiddenBearCond, title="Hidden Bear Divergence", message="PA-Adaptive T3 Loxxer [Loxx]: Hidden Bear Divergence\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(bearCond, title="Regular Bear Divergence", message="PA-Adaptive T3 Loxxer [Loxx]: Regular Bear Divergence\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(hiddenBullCond, title="Hidden Bull Divergence", message="PA-Adaptive T3 Loxxer [Loxx]: Hidden Bull Divergence\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(bullCond, title="Regular Bull Divergence", message="PA-Adaptive T3 Loxxer [Loxx]: Regular Bull Divergence\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Quick Shot[ChartPrime] | https://www.tradingview.com/script/IUSxvoWl-Quick-Shot-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 267 | 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/
// © ExoMaven
//@version=5
indicator(title = "Quick Shot[ChartPrime]", shorttitle = "Quick Shot [V1]", overlay = true)
//User Input
length = input.int(title = "Length", defval = 50, maxval = 100, minval = 10, group = "Dot Settings")
exp_mult = input.int(title = "Agressiveness", defval = 8, minval = 5, maxval = 12, step = 1, group = "Curved Line Settings") / 4
//Indicators
ma = ta.ema(close, length)
ma2 = ta.ema(close, 200)
ma_up = ta.crossover(ma, ma[1]) and ma > ma2 and barstate.isconfirmed
ma_dn = ta.crossunder(ma, ma[1]) and ma < ma2 and barstate.isconfirmed
//Main Logic
var bool exp_go = false
var float exp_sl = na
float exp_value = na
var float high_val = na
var float low_val = na
exp_go := ma_up or ma_dn ? true : exp_go
high_val := ma_up ? high : high > high_val ? high : high_val
low_val := ma_dn ? low : low < low_val ? low : low_val
// exp_sl := ma_up or ma_dn ? ma - ma[1] : exp_sl > 0 and high_val > high_val[1] ? exp_sl * exp_mult : exp_sl < 0 and low_val < low_val[1] ? exp_sl * exp_mult : exp_sl
exp_sl := ma_up or ma_dn ? ma - ma[1] : exp_sl > 0 or exp_sl < 0 ? exp_sl * exp_mult : exp_sl
exp_value := ma_up or ma_dn ? ma : exp_go ? exp_value[1] + exp_sl : na
exp_go := exp_value > exp_value[1] ? (exp_value < (close < open ? close : open) ? true : false) : exp_value < exp_value[1] ? (exp_value > (close > open ? close : open) ? true : false) : exp_go
buy_exit = exp_value > exp_value[1] and not exp_go and exp_go[1]
sell_exit = exp_value < exp_value[1] and not exp_go and exp_go[1]
//Plots
plotshape(ma_up, title = "Buy", style = shape.circle, location = location.belowbar, color = color.green, show_last = 20000, size = size.tiny)
plotshape(ma_dn, title = "Sell", style = shape.circle, location = location.abovebar, color = color.red, show_last = 20000, size = size.tiny)
plotshape(buy_exit, title = "Buy Exit", style = shape.xcross, location = location.abovebar, color = color.blue, show_last = 20000, size = size.tiny)
plotshape(sell_exit, title = "Sell Exit", style = shape.xcross, location = location.belowbar, color = color.blue, show_last = 20000, size = size.tiny)
plot(exp_value, title = "Exp Line", color = exp_value < close ? color.new(color.green, 25) : color.new(color.red, 25), linewidth = 1, style = plot.style_cross)
//Alertconditions
alertcondition(condition = ma_up, title = "Green Dot Alert")
alertcondition(condition = ma_dn, title = "Red Dot")
alertcondition(condition = buy_exit, title = "Green Dot Exit")
alertcondition(condition = sell_exit, title = "Red Dot Exit")
|
Vector MACD | https://www.tradingview.com/script/UL8mHBNf-Vector-MACD/ | BobBasic | https://www.tradingview.com/u/BobBasic/ | 166 | 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/
// © BobBasic
//@version=5
indicator(title="Vector MACD", shorttitle="Vector MACD")
vp1 = input.int(89, "Vector Period 1")
vp2 = input.int(55, "Vector Period 2")
vp3 = input.int(34, "Vector Period 3")
vp4 = input.int(21, "Vector Period 4")
vp5 = input.int(13, "Vector Period 5")
vp6 = input.int(8, "Vector Period 6")
origin_ma = ta.alma(hl2, vp1, 0.85, 6)
vector_ma1 = ta.hma(close, vp1) - origin_ma
vector_ma2 = ta.hma(close, vp2) - origin_ma
vector_ma3 = ta.hma(close, vp3) - origin_ma
vector_ma4 = ta.hma(close, vp4) - origin_ma
vector_ma5 = ta.hma(close, vp5) - origin_ma
vector_ma6 = ta.hma(close, vp6) - origin_ma
vector = (vector_ma1 + vector_ma2 + vector_ma3 + vector_ma4 + vector_ma5 + vector_ma6) / 6
normalize(_src, _cap) =>
xMax = ta.highest(_src, _cap)
xMin = ta.lowest(_src, _cap)
_range = xMax - xMin
n = _cap * _src / _range
n
hline(50, "Zero Line", color=color.gray)
hline(0, "Zero Line", color=color.gray, linestyle = hline.style_dotted, linewidth = 2)
hline(-50, "Zero Line", color=color.gray)
plot(normalize(vector, 100),"vmacd" , color= vector < vector[1] ? color.red : color.green, linewidth = 2)
|
Signals and pivot divergences | https://www.tradingview.com/script/d5z6zLpr-Signals-and-pivot-divergences/ | mickes | https://www.tradingview.com/u/mickes/ | 372 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mickes
//@version=5
indicator("Signals and pivot divergences", overlay = true, max_labels_count = 500, max_lines_count = 500)
_pivotLengthLeft = input.int(8, "Pivot length left", group = "General")
_pivotLengthRight = input.int(5, "Pivot length right", group = "General")
_source = input.source(close, "Source", group = "General")
_showPivots = input.bool(false, "Show pivots", group = "General", tooltip = "Only shows 'real' pivots, not 'end pivots' (if enabled)")
_pivotEnd = input.bool(true, "Different pivot in the end", tooltip = "Will create faster pivots in the end (wothout the right length) that are removed when real pivots are active")
_lastBarIndex = input.int(-1, "Last bar index")
_showSignals = input.bool(true, "Enable", group = "Signals")
_minBarsBackForSignal = input.int(20, "Indicator lookback", tooltip = "If there is a similar buy/sell signal from the same indicator within the bar limit it will not show", group = "Signals")
_minSignals = input.int(5, "Minimum number of signals", minval = 1, group = "Signals", tooltip = "Including the current one")
_minSignalsLookback = input.int(5, "Minimum number of signals lookback", minval = 0, group = "Signals", tooltip = "The minimun number of signals must be fulfilled within the lookback period (e.g. if set to 0 the minimum number of signals must be on the same bar)")
_buySignalColor = input.color(color.new(color.aqua, 20), "Buy", group = "Signals", inline = "buysignal")
_showBuySignals = input.bool(true, "", inline = "buysignal", group = "Signals")
_sellSignalColor = input.color(color.new(#fff59d, 20), "Sell", inline = "sellsignal", group = "Signals")
_showSellSignals = input.bool(true, "", inline = "sellsignal", group = "Signals")
_showBbSignals = input.bool(true, "Bollinger Band (BB)", group = "Signals")
_showRsiSignals = input.bool(true, "Relative Strength Index (RSI)", group = "Signals")
_showMacdSignals = input.bool(true, "Moving Average Convergence/Divergence (MACD)", group = "Signals")
_showCciSignals = input.bool(true, "Commodity Channel Index (CCI)", group = "Signals")
_showStochasticSignals = input.bool(true, "Stochastic", group = "Signals")
_showMfiSignals = input.bool(true, "Money Flow Index (MFI)", group = "Signals")
_showDivergences = input.bool(true, "Enable", group = "Divergences")
_maxDivergenceLookback = input.int(40, "Lookback", group = "Divergences")
_maxBarsOnWrongSide = input.float(20, "Maximum bars on wrong side %", minval = 0, maxval = 100, inline = "maxbars", group = "Divergences")
_maxBarsOnWrongSideCheck = input.bool(true, "", inline = "maxbars", tooltip = "use to disable lines that crosses highs or lows", group = "Divergences")
_minDivergences = input.int(2, "Minimum number of divergences", minval = 1, group = "Divergences")
_positiveRegularDivergenceColor = input.color(color.new(color.green, 20), "Positive regular", inline = "posiveregular", group = "Divergences")
_positiveRegularDivergenceStyle = input.string("Solid", "", ["Solid", "Dashed", "Dotted"], inline = "posiveregular", group = "Divergences")
_showPositiveRegularDivergence = input.bool(true, "", inline = "posiveregular", group = "Divergences")
_negativeRegularDivergenceColor = input.color(color.new(color.red, 20), "Negative regular", inline = "negativeregular", group = "Divergences")
_negativeRegularDivergenceStyle = input.string("Solid", "", ["Solid", "Dashed", "Dotted"], inline = "negativeregular", group = "Divergences")
_showNegativeRegularDivergence = input.bool(true, "", inline = "negativeregular", group = "Divergences")
_positiveHiddenDivergenceColor = input.color(color.new(color.olive, 20), "Positive hidden", inline = "posivehidden", group = "Divergences")
_positiveHiddenDivergenceStyle = input.string("Dashed", "", ["Solid", "Dashed", "Dotted"], inline = "posivehidden", group = "Divergences")
_showPositiveHiddenDivergence = input.bool(true, "", inline = "posivehidden", group = "Divergences")
_negativeHiddenDivergenceColor = input.color(color.new(color.orange, 20), "Negative hidden", inline = "negativehidden", group = "Divergences")
_negativeHiddenDivergenceStyle = input.string("Dashed", "", ["Solid", "Dashed", "Dotted"], inline = "negativehidden", group = "Divergences")
_showNegativeHiddenDivergence = input.bool(true, "", inline = "negativehidden", group = "Divergences")
_showRsiDivergences = input.bool(true, "Relative Strength Index (RSI)", group = "Divergences")
_showMacdDivergences = input.bool(true, "Moving Average Convergence/Divergence (MACD)", group = "Divergences")
_showMomentumDivergences = input.bool(true, "Momentum", group = "Divergences")
_showCciDivergences = input.bool(true, "Commodity Channel Index (CCI)", group = "Divergences")
_showObvDivergences = input.bool(true, "On Balance Volume (OBV)", group = "Divergences")
_showStochasticDivergences = input.bool(true, "Stochastic", group = "Divergences")
_showVwMacdDivergences = input.bool(true, "Volume Weighed MACD (VWMACD)", group = "Divergences")
_showChaikinMoneyFlowDivergences = input.bool(true, "Chaikin Money Flow (CMF)", group = "Divergences")
_showMoneyFlowIndexDivergences = input.bool(true, "Money Flow Index (MFI)", group = "Divergences")
_showVolumeDivergences = input.bool(true, "Volume", group = "Divergences")
_alertOn = input.string("All", "On", ["All", "Signals", "Divergences"], group = "Alert", tooltip = "Divergences alerts lag by right pivot length + 1. Doesn't affect 'end pivots' (if enabled)")
_alertFrequency = input.string("Once per bar close", "Frequency", ["All", "Once per bar", "Once per bar close"], group = "Alert")
_alertPivotEndOnBarClose = input.bool(true, "Alert 'end pivots' only on close", group = "Alert", tooltip = "'end pivots' (if enabled) are always notified when a new one occures (but not when more divergences happens (to avoid spaming)) unless this is checked")
type signalType
bool Active = false
bool Shown = false
bool Show = false
float Value
int BarIndex
string Name
type indicatorType
float Price
string Text
type pivotsType
float Price
int BarIndex
int Pivot // 0 = low, 1 = high
indicatorType Macd
indicatorType Rsi
indicatorType Momentum
indicatorType Cci
indicatorType OnBalanceVolume
indicatorType Stochastic
indicatorType VwMacd
indicatorType ChaikinMoneyFlow
indicatorType MoneyFlowIndex
indicatorType Volume
type divergenceInfoType
int StartBarIndex
float StartPrice
int EndBarIndex
float EndPrice
string Text
string Type
int Pivot // 0 = low, 1 = high
type divergenceDrawingType
line Line
label Label
int EndBarIndex = 0
int StartBarIndex = 0
type pivotEndType
float High = 0
float Low = 2147483647
int Start = -2147483648
int End = 0
box Box
var _pivotLows = array.new<pivotsType>()
var _pivotHighs = array.new<pivotsType>()
var _divergenceDrawingsEnd = array.new<divergenceDrawingType>()
varip _divergenceAlerts = array.new<int>()
_atr = ta.atr(14)
[_, _bollingerBandUpper, _bollingerBandLower] = ta.bb(_source, 20, 2)
_rsi = ta.rsi(_source, 14)
[_macdLine, _macdSignalLine, _] = ta.macd(_source, 12, 26, 9)
_trueStrengthIndex = ta.tsi(_source, 13, 25)
// taken from 'LonesomeTheBlue's indicator https://www.tradingview.com/v/n8AGnIZd/n8AGnIZd
_momentum = ta.mom(close, 10)
_cci = ta.cci(close, 10)
_onBalanceVolume = ta.obv
_stochastic = ta.sma(ta.stoch(close, high, low, 14), 3)
_maFast = ta.vwma(close, 12), _maSlow = ta.vwma(close, 26), _vwMacd = _maFast - _maSlow
_cmfm = ((close - low) - (high - close)) / (high - low), _cmfv = _cmfm * volume, _chaikinMoneyFlow = ta.sma(_cmfv, 21) / ta.sma(volume, 21)
_moneyFlowIndex = ta.mfi(hlc3, 14)
_volume = volume
lastBarIteration() =>
barstate.islast and barstate.isconfirmed
toI(array) =>
toI = array.size(array) - 1
if toI < 0
toI := na
toI
unixTimeToString(unixTime) =>
timeString = str.format_time(unixTime, "yyyy-MM-dd HH:mm:ss", syminfo.timezone)
timeString
getAlertText(alertTexts) =>
string alertText = na
for [i, txt] in alertTexts
if i == 0
alertText := txt
else
alertText += "\n" + txt
alertText
_alertTexts = array.new<string>()
addAlert(type, txt) =>
if type == _alertOn
or _alertOn == "All"
array.push(_alertTexts, txt)
sendAlert() =>
alerts = array.size(_alertTexts)
if alerts > 0
alertText = getAlertText(_alertTexts)
switch _alertFrequency
"All" =>
alert(alertText, alert.freq_all)
"Once per bar" =>
alert(alertText, alert.freq_once_per_bar)
"Once per bar close" =>
alert(alertText, alert.freq_once_per_bar_close)
_endAlertTexts = array.new<string>()
addEndAlert(type, txt, length) =>
if type == _alertOn
or _alertOn == "All"
if _alertPivotEndOnBarClose
if lastBarIteration()
array.push(_endAlertTexts, txt)
else if not array.includes(_divergenceAlerts, length)
array.push(_divergenceAlerts, length)
array.push(_endAlertTexts, txt)
sendEndAlert() =>
alerts = array.size(_endAlertTexts)
if alerts > 0
alertText = getAlertText(_endAlertTexts)
if _alertPivotEndOnBarClose
alert(alertText, alert.freq_once_per_bar_close)
else
alert(alertText, alert.freq_all)
clearEndDivergenceLengths() =>
if lastBarIteration()
array.clear(_divergenceAlerts)
signals(buyCross, sellCross, value, name) =>
var buys = array.new<signalType>()
var sells = array.new<signalType>()
buy = signalType.new(), sell = signalType.new()
if buyCross
buy.Active := true
buy.BarIndex := bar_index
buy.Name := name
buy.Value := value
array.unshift(buys, buy)
if sellCross
sell.Active := true
sell.BarIndex := bar_index
sell.Name := name
sell.Value := value
array.unshift(sells, sell)
[buy, sell, buys, sells]
bollingerBandSignals(name) =>
sellCross = ta.crossover(high, _bollingerBandUpper)
buyCross = ta.crossunder(low, _bollingerBandLower)
signals(buyCross, sellCross, _bollingerBandUpper, name)
macdSignals(name) =>
buyCross = ta.crossover(_macdLine, _macdSignalLine)
sellCross = ta.crossunder(_macdLine, _macdSignalLine)
signals(buyCross, sellCross, -1, name)
rsiSignals(name) =>
sellCross = ta.crossover(_rsi, 70)
buyCross = ta.crossunder(_rsi, 30)
signals(buyCross, sellCross, _rsi, name)
cciSignals(name) =>
sellCross = ta.crossunder(_cci, 100)
buyCross = ta.crossover(_cci, -100)
signals(buyCross, sellCross, _cci, name)
stochasticSignals(name) =>
sellCross = ta.crossover(_stochastic, 80)
buyCross = ta.crossunder(_stochastic, 20)
signals(buyCross, sellCross, _stochastic, name)
mfiSignals(name) =>
sellCross = ta.crossunder(_moneyFlowIndex, 80)
buyCross = ta.crossover(_moneyFlowIndex, 20)
signals(buyCross, sellCross, _moneyFlowIndex, name)
// also handles limitations on the same type indicator
createSignal(s, previousSignals, signals, allSignals) =>
if s.Active
array.unshift(allSignals, s)
for previousSignal in previousSignals
if previousSignal.BarIndex == bar_index
continue // skip current if already added
if previousSignal.Shown
and previousSignal.BarIndex >= bar_index - _minBarsBackForSignal
array.push(signals, s)
break
else if previousSignal.BarIndex < bar_index - _minBarsBackForSignal
s.Show := true
array.push(signals, s)
break
getSignalsTextAndSetShown(signals, size) =>
string txt = na, string tooltip = na, allIsNoShow = true
for i = 0 to size - 1
s = array.get(signals, i)
string signalText = na
switch s.Show
true =>
s.Shown := true
signalText := str.format("{0}", s.Name)
allIsNoShow := false
false =>
signalText := str.format("({0})", s.Name)
if na(tooltip)
tooltip := str.format("{0} should not be shown alone", s.Name)
else
tooltip += str.format("\n{0} should not be shown alone", s.Name)
if i == 0
txt := signalText
else
txt += "\n" + signalText
if allIsNoShow
txt := na
[txt, tooltip]
createSingnalsLabel(signals, direction) =>
signalSize = array.size(signals)
if signalSize > 0
[txt, tooltip] = getSignalsTextAndSetShown(signals, signalSize)
if not na(txt)
alertText = str.replace_all(txt, "\n", ", ")
switch direction
0 =>
if _showSellSignals
label.new(bar_index, high, txt, color = _sellSignalColor, tooltip = tooltip)
addAlert("Signals", str.format("Sell signal from {0}", alertText))
1 =>
if _showBuySignals
label.new(bar_index, low, txt, color = _buySignalColor, tooltip = tooltip, style = label.style_label_up)
addAlert("Signals", str.format("Buy signal from {0}", alertText))
showPivots(pivotLow, pivotHigh) =>
var float previousPivotPrice = na
var int previousPivotBarIndex = na
barIndex = bar_index - _pivotLengthRight
isLow = not na(pivotLow)
price = isLow ? low[_pivotLengthRight] : high[_pivotLengthRight]
if isLow
label.new(barIndex, price, "▼", style = label.style_label_up, color = color.new(color.red, 70))
if not na(previousPivotBarIndex)
line.new(previousPivotBarIndex, previousPivotPrice, barIndex, price, color = color.new(color.orange, 80), style = line.style_dashed)
previousPivotBarIndex := barIndex
previousPivotPrice := price
else
label.new(barIndex, price, "▲", color = color.new(color.green, 70))
if not na(previousPivotBarIndex)
line.new(previousPivotBarIndex, previousPivotPrice, barIndex, price, color = color.new(color.green, 80), style = line.style_dashed)
previousPivotBarIndex := barIndex
previousPivotPrice := price
pivots() =>
pivotLow = ta.pivotlow(low, _pivotLengthLeft, _pivotLengthRight)
pivotHigh = ta.pivothigh(high, _pivotLengthLeft, _pivotLengthRight)
pivotLowEnd = ta.pivotlow(low, _pivotLengthLeft, 0)
pivotHighEnd = ta.pivothigh(high, _pivotLengthLeft, 0)
lastBarIndex = _lastBarIndex != -1 ? _lastBarIndex : last_bar_index
if _pivotEnd
and (bar_index > lastBarIndex - _pivotLengthRight and bar_index <= lastBarIndex)
var pivotEnd = pivotEndType.new()
if na(pivotEnd.Box)
pivotEnd.Box := box.new(bar_index, high, lastBarIndex, low, bgcolor = color.new(color.blue,70))
if low < pivotEnd.Low
pivotEnd.Low := low
box.set_bottom(pivotEnd.Box, low)
if high > pivotEnd.High
pivotEnd.High := high
box.set_top(pivotEnd.Box, high)
if lastBarIndex > pivotEnd.End
pivotEnd.End := lastBarIndex
box.set_right(pivotEnd.Box, lastBarIndex)
if bar_index + _pivotLengthRight > pivotEnd.Start
pivotEnd.Start := bar_index - (_pivotLengthRight - 1)
box.set_left(pivotEnd.Box, bar_index - (_pivotLengthRight - 1))
[pivotLow, pivotHigh, pivotLowEnd, pivotHighEnd]
else if bar_index < lastBarIndex - _pivotLengthRight
[pivotLow, pivotHigh, na, na]
else
[na, na, na, na]
barsIsOnRightSide(l, pivotExtreme, startBarIndex, endBarIndex) =>
barsOnWrongSide = 0
for j = bar_index - startBarIndex to bar_index - endBarIndex
linePrice = line.get_price(l, bar_index - j)
if pivotExtreme == 0 // low pivot
if low[j] < linePrice
barsOnWrongSide += 1
else if pivotExtreme == 1 // high pivot
if high[j] > linePrice
barsOnWrongSide += 1
barsIsOnRightSide = barsOnWrongSide / ((bar_index - startBarIndex) - (bar_index - endBarIndex)) <= _maxBarsOnWrongSide * 0.01
barsIsOnRightSide
getIndicator(pivot, name) =>
indicatorType indicator = na
switch name
"RSI" => indicator := pivot.Rsi
"MACD" => indicator := pivot.Macd
"MOM" => indicator := pivot.Momentum
"CCI" => indicator := pivot.Cci
"OBV" => indicator := pivot.OnBalanceVolume
"Stoch" => indicator := pivot.Stochastic
"VWMACD" => indicator := pivot.VwMacd
"CMF" =>indicator := pivot.ChaikinMoneyFlow
"MFI" => indicator := pivot.MoneyFlowIndex
"VOL" => indicator := pivot.Volume
indicator
addOrUpdateDivergenceInfos(divergenceInfos, startBarIndex, startPrice, endBarIndex, endPrice, pivotText, pivot, divergenceTypeText) =>
updated = false
for divergenceRow in divergenceInfos
if divergenceRow.StartBarIndex == startBarIndex
divergenceRow.Text := divergenceRow.Text + "\n" + pivotText
updated := true
break
if not updated
array.push(divergenceInfos, divergenceInfoType.new(startBarIndex, startPrice, endBarIndex, endPrice, pivotText, divergenceTypeText, pivot))
setDivergence(pivots, name, divergenceInfos, pivotExtreme, barsAgo) =>
toI = array.size(pivots) - 1
if toI >= 1
basePivot = array.get(pivots, toI)
if basePivot.BarIndex == bar_index - barsAgo
for i = toI - 1 to 0
currentPivot = array.get(pivots, i)
if currentPivot.BarIndex <= basePivot.BarIndex - _maxDivergenceLookback
break
baseIndicator = getIndicator(basePivot, name)
currentIndicator = getIndicator(currentPivot, name)
if basePivot.Price < currentPivot.Price // \
and baseIndicator.Price > currentIndicator.Price
string divergenceTypeText = na
if pivotExtreme == 0
and basePivot.Pivot == 0
divergenceTypeText := "Positive regular"
else if pivotExtreme == 1
and basePivot.Pivot == 1
divergenceTypeText := "Negative hidden"
addOrUpdateDivergenceInfos(divergenceInfos, currentPivot.BarIndex, currentPivot.Price, basePivot.BarIndex, basePivot.Price, currentIndicator.Text, pivotExtreme, divergenceTypeText)
else if basePivot.Price > currentPivot.Price // /
and baseIndicator.Price < currentIndicator.Price
string divergenceTypeText = na
if pivotExtreme == 0
and basePivot.Pivot == 0
divergenceTypeText := "Positive hidden"
else if pivotExtreme == 1
and basePivot.Pivot == 1
divergenceTypeText := "Negative regular"
addOrUpdateDivergenceInfos(divergenceInfos, currentPivot.BarIndex, currentPivot.Price, basePivot.BarIndex, basePivot.Price, currentIndicator.Text, pivotExtreme, divergenceTypeText)
createDivergenceLineAndLabel(divergenceInfos) =>
for divergenceRow in divergenceInfos
if array.size(str.split(divergenceRow.Text, "\n")) < _minDivergences
continue
if not _showPositiveRegularDivergence
and divergenceRow.Type == "Positive regular"
continue
else if not _showNegativeRegularDivergence
and divergenceRow.Type == "Negative regular"
continue
else if not _showPositiveHiddenDivergence
and divergenceRow.Type == "Positive hidden"
continue
else if not _showNegativeHiddenDivergence
and divergenceRow.Type == "Negative hidden"
continue
divergenceLine = line.new(divergenceRow.StartBarIndex, divergenceRow.StartPrice, divergenceRow.EndBarIndex, divergenceRow.EndPrice, width = 2)
if _maxBarsOnWrongSideCheck
if not barsIsOnRightSide(divergenceLine, divergenceRow.Pivot, divergenceRow.StartBarIndex, divergenceRow.EndBarIndex)
line.delete(divergenceLine)
continue
labelLocation = divergenceRow.StartBarIndex + ((divergenceRow.EndBarIndex - divergenceRow.StartBarIndex) / 2)
labelPrice = divergenceRow.Pivot == 0 ? line.get_price(divergenceLine, labelLocation) - _atr : line.get_price(divergenceLine, labelLocation) + _atr
labelStyle = divergenceRow.Pivot == 0 ? label.style_label_up : label.style_label_down
end = divergenceRow.EndBarIndex == bar_index
labelText = end ? "(end)\n" + divergenceRow.Text : divergenceRow.Text
divergenceLabel = label.new(labelLocation, labelPrice, labelText, style = labelStyle, color = color.green)
alertText = str.format("{0} pivot divergence ({1} bars) from {2}", divergenceRow.Type, divergenceRow.EndBarIndex - divergenceRow.StartBarIndex, str.replace_all(divergenceRow.Text, "\n", ", "))
if end
addEndAlert("Divergences", str.format("{0} (end)", alertText), divergenceRow.EndBarIndex - divergenceRow.StartBarIndex)
else
addAlert("Divergences", alertText)
switch divergenceRow.Type
"Positive regular" =>
line.set_color(divergenceLine, _positiveRegularDivergenceColor)
switch _positiveRegularDivergenceStyle
"Dashed" => line.set_style(divergenceLine, line.style_dashed)
"Dotted" => line.set_style(divergenceLine, line.style_dotted)
label.set_color(divergenceLabel, _positiveRegularDivergenceColor)
"Negative regular" =>
line.set_color(divergenceLine, _negativeRegularDivergenceColor)
switch _negativeRegularDivergenceStyle
"Dashed" => line.set_style(divergenceLine, line.style_dashed)
"Dotted" => line.set_style(divergenceLine, line.style_dotted)
label.set_color(divergenceLabel, _negativeRegularDivergenceColor)
"Positive hidden" =>
line.set_color(divergenceLine, _positiveHiddenDivergenceColor)
switch _positiveHiddenDivergenceStyle
"Dashed" => line.set_style(divergenceLine, line.style_dashed)
"Dotted" => line.set_style(divergenceLine, line.style_dotted)
label.set_color(divergenceLabel, _positiveHiddenDivergenceColor)
"Negative hidden" =>
line.set_color(divergenceLine, _negativeHiddenDivergenceColor)
switch _negativeHiddenDivergenceStyle
"Dashed" => line.set_style(divergenceLine, line.style_dashed)
"Dotted" => line.set_style(divergenceLine, line.style_dotted)
label.set_color(divergenceLabel, _negativeHiddenDivergenceColor)
if end
array.push(_divergenceDrawingsEnd, divergenceDrawingType.new(divergenceLine, divergenceLabel, divergenceRow.EndBarIndex, divergenceRow.StartBarIndex))
removeLimitSignals(signals, allSignals) =>
previousSignalsWithinLookback = 0
for s in allSignals
if s.BarIndex >= bar_index - _minSignalsLookback
previousSignalsWithinLookback += 1
if s.BarIndex < bar_index - _minSignalsLookback
if previousSignalsWithinLookback < _minSignals
array.clear(signals)
break
signalsLabelsAll() =>
var allSellSignals = array.new<signalType>()
var allBuySignals = array.new<signalType>()
[bollingerBandBuy, bollingerBandSell, bollingerBandBuys, bollingerBandSells] = bollingerBandSignals("BB")
[macdBuy, macdSell, macdBuys, macdSells] = macdSignals("MACD")
[rsiBuy, rsiSell, rsiBuys, rsiSells] = rsiSignals("RSI")
[cciBuy, cciSell, cciBuys, cciSells] = cciSignals("CCI")
[stochasticBuy, stochasticSell, stochasticBuys, stochasticSells] = stochasticSignals("Stoch")
[mfiBuy, mfiSell, mfiBuys, mfiSells] = mfiSignals("MFI")
sellSignals = array.new<signalType>()
buySignals = array.new<signalType>()
if _showBbSignals
createSignal(bollingerBandSell, bollingerBandSells, sellSignals, allSellSignals)
createSignal(bollingerBandBuy, bollingerBandBuys, buySignals, allBuySignals)
if _showMacdSignals
createSignal(macdSell, macdSells, sellSignals, allSellSignals)
createSignal(macdBuy, macdBuys, buySignals, allBuySignals)
if _showRsiSignals
createSignal(rsiSell, rsiSells, sellSignals, allSellSignals)
createSignal(rsiBuy, rsiBuys, buySignals, allBuySignals)
if _showCciSignals
createSignal(cciSell, cciSells, sellSignals, allSellSignals)
createSignal(cciBuy, cciBuys, buySignals, allBuySignals)
if _showStochasticSignals
createSignal(stochasticSell, stochasticSells, sellSignals, allSellSignals)
createSignal(stochasticBuy, stochasticBuys, buySignals, allBuySignals)
if _showMfiSignals
createSignal(mfiSell, mfiSells, sellSignals, allSellSignals)
createSignal(mfiBuy, mfiBuys, buySignals, allBuySignals)
removeLimitSignals(sellSignals, allSellSignals)
removeLimitSignals(buySignals, allBuySignals)
createSingnalsLabel(sellSignals, 0)
createSingnalsLabel(buySignals, 1)
setIndicatorValues(pivot, value, name) =>
switch name
"RSI" => pivot.Rsi := indicatorType.new(value, name)
"MACD" => pivot.Macd := indicatorType.new(value, name)
"MOM" => pivot.Momentum := indicatorType.new(value, name)
"CCI" => pivot.Cci := indicatorType.new(value, name)
"OBV" => pivot.OnBalanceVolume := indicatorType.new(value, name)
"Stoch" => pivot.Stochastic := indicatorType.new(value, name)
"VWMACD" => pivot.VwMacd := indicatorType.new(value, name)
"CMF" => pivot.ChaikinMoneyFlow := indicatorType.new(value, name)
"MFI" => pivot.MoneyFlowIndex := indicatorType.new(value, name)
"VOL" => pivot.Volume := indicatorType.new(value, name)
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, value, name, barsAgo) =>
setIndicatorValues(pivot, value, name)
setDivergence(pivots, name, divergenceInfos, pivotExtreme, barsAgo)
divergencePivotAndValuesAll(pivotLow, pivotHigh, pivotLowEnd, pivotHighEnd) =>
if pivotLow
divergenceInfos = array.new<divergenceInfoType>()
pivotExtreme = 0, barsAgo = _pivotLengthRight
pivot = pivotsType.new(pivotLow, bar_index - barsAgo, pivotExtreme)
array.push(_pivotLows, pivot)
if _showMacdDivergences
divergencePivotAndValue(_pivotLows, pivot, divergenceInfos, pivotExtreme, _macdLine[barsAgo], "MACD", barsAgo)
if _showRsiDivergences
divergencePivotAndValue(_pivotLows, pivot, divergenceInfos, pivotExtreme, _rsi[barsAgo], "RSI", barsAgo)
if _showMomentumDivergences
divergencePivotAndValue(_pivotLows, pivot, divergenceInfos, pivotExtreme, _momentum[barsAgo], "MOM", barsAgo)
if _showCciDivergences
divergencePivotAndValue(_pivotLows, pivot, divergenceInfos, pivotExtreme, _cci[barsAgo], "CCI", barsAgo)
if _showObvDivergences
divergencePivotAndValue(_pivotLows, pivot, divergenceInfos, pivotExtreme, _onBalanceVolume[barsAgo], "OBV", barsAgo)
if _showStochasticDivergences
divergencePivotAndValue(_pivotLows, pivot, divergenceInfos, pivotExtreme, _stochastic[barsAgo], "Stoch", barsAgo)
if _showVwMacdDivergences
divergencePivotAndValue(_pivotLows, pivot, divergenceInfos, pivotExtreme, _vwMacd[barsAgo], "VWMACD", barsAgo)
if _showChaikinMoneyFlowDivergences
divergencePivotAndValue(_pivotLows, pivot, divergenceInfos, pivotExtreme, _chaikinMoneyFlow[barsAgo], "CMF", barsAgo)
if _showMoneyFlowIndexDivergences
divergencePivotAndValue(_pivotLows, pivot, divergenceInfos, pivotExtreme, _moneyFlowIndex[barsAgo], "MFI", barsAgo)
if _showVolumeDivergences
divergencePivotAndValue(_pivotLows, pivot, divergenceInfos, pivotExtreme, _volume[barsAgo], "VOL", barsAgo)
createDivergenceLineAndLabel(divergenceInfos)
if pivotLowEnd
divergenceInfos = array.new<divergenceInfoType>()
pivotExtreme = 0, barsAgo = 0, pivots = _pivotLows
pivot = pivotsType.new(pivotLowEnd, bar_index - barsAgo, pivotExtreme)
array.push(pivots, pivot)
if _showMacdDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _macdLine[barsAgo], "MACD", barsAgo)
if _showRsiDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _rsi[barsAgo], "RSI", barsAgo)
if _showMomentumDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _momentum[barsAgo], "MOM", barsAgo)
if _showCciDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _cci[barsAgo], "CCI", barsAgo)
if _showObvDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _onBalanceVolume[barsAgo], "OBV", barsAgo)
if _showStochasticDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _stochastic[barsAgo], "Stoch", barsAgo)
if _showVwMacdDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _vwMacd[barsAgo], "VWMACD", barsAgo)
if _showChaikinMoneyFlowDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _chaikinMoneyFlow[barsAgo], "CMF", barsAgo)
if _showMoneyFlowIndexDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _moneyFlowIndex[barsAgo], "MFI", barsAgo)
if _showVolumeDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _volume[barsAgo], "VOL", barsAgo)
createDivergenceLineAndLabel(divergenceInfos)
if pivotHigh
divergenceInfos = array.new<divergenceInfoType>()
pivotExtreme = 1, barsAgo = _pivotLengthRight
pivot = pivotsType.new(pivotHigh, bar_index - barsAgo, pivotExtreme)
array.push(_pivotHighs, pivot)
if _showMacdDivergences
divergencePivotAndValue(_pivotHighs, pivot, divergenceInfos, pivotExtreme, _macdLine[barsAgo], "MACD", barsAgo)
if _showRsiDivergences
divergencePivotAndValue(_pivotHighs, pivot, divergenceInfos, pivotExtreme, _rsi[barsAgo], "RSI", barsAgo)
if _showMomentumDivergences
divergencePivotAndValue(_pivotHighs, pivot, divergenceInfos, pivotExtreme, _momentum[barsAgo], "MOM", barsAgo)
if _showCciDivergences
divergencePivotAndValue(_pivotHighs, pivot, divergenceInfos, pivotExtreme, _cci[barsAgo], "CCI", barsAgo)
if _showObvDivergences
divergencePivotAndValue(_pivotHighs, pivot, divergenceInfos, pivotExtreme, _onBalanceVolume[barsAgo], "OBV", barsAgo)
if _showStochasticDivergences
divergencePivotAndValue(_pivotHighs, pivot, divergenceInfos, pivotExtreme, _stochastic[barsAgo], "Stoch", barsAgo)
if _showVwMacdDivergences
divergencePivotAndValue(_pivotHighs, pivot, divergenceInfos, pivotExtreme, _vwMacd[barsAgo], "VWMACD", barsAgo)
if _showChaikinMoneyFlowDivergences
divergencePivotAndValue(_pivotHighs, pivot, divergenceInfos, pivotExtreme, _chaikinMoneyFlow[barsAgo], "CMF", barsAgo)
if _showMoneyFlowIndexDivergences
divergencePivotAndValue(_pivotHighs, pivot, divergenceInfos, pivotExtreme, _moneyFlowIndex[barsAgo], "MFI", barsAgo)
if _showVolumeDivergences
divergencePivotAndValue(_pivotHighs, pivot, divergenceInfos, pivotExtreme, _volume[barsAgo], "VOL", barsAgo)
createDivergenceLineAndLabel(divergenceInfos)
if pivotHighEnd
divergenceInfos = array.new<divergenceInfoType>()
pivotExtreme = 1, barsAgo = 0, pivots = _pivotHighs
pivot = pivotsType.new(pivotHighEnd, bar_index - barsAgo, pivotExtreme)
array.push(pivots, pivot)
if _showMacdDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _macdLine[barsAgo], "MACD", barsAgo)
if _showRsiDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _rsi[barsAgo], "RSI", barsAgo)
if _showMomentumDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _momentum[barsAgo], "MOM", barsAgo)
if _showCciDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _cci[barsAgo], "CCI", barsAgo)
if _showObvDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _onBalanceVolume[barsAgo], "OBV", barsAgo)
if _showStochasticDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _stochastic[barsAgo], "Stoch", barsAgo)
if _showVwMacdDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _vwMacd[barsAgo], "VWMACD", barsAgo)
if _showChaikinMoneyFlowDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _chaikinMoneyFlow[barsAgo], "CMF", barsAgo)
if _showMoneyFlowIndexDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _moneyFlowIndex[barsAgo], "MFI", barsAgo)
if _showVolumeDivergences
divergencePivotAndValue(pivots, pivot, divergenceInfos, pivotExtreme, _volume[barsAgo], "VOL", barsAgo)
createDivergenceLineAndLabel(divergenceInfos)
clearDivergenceDrawings() =>
if bar_index >= last_bar_index - _pivotLengthRight// barstate.islast
removed = 0, toI = toI(_divergenceDrawingsEnd)
for i = 0 to toI
if removed == toI
break
drawing = array.get(_divergenceDrawingsEnd, i - removed)
if drawing.EndBarIndex == bar_index - _pivotLengthRight
line.delete(drawing.Line)
label.delete(drawing.Label)
array.remove(_divergenceDrawingsEnd, i - removed)
removed += 1
clearEndPivots(pivots) =>
removed = 0, toI = toI(pivots)
for i = 0 to toI
if removed == toI
break
pivot = array.get(pivots, i - removed)
if pivot.BarIndex == last_bar_index - _pivotLengthRight
array.remove(pivots, i - removed)
removed += 1
if _pivotEnd
clearEndPivots(_pivotLows)
clearEndPivots(_pivotHighs)
if _showSignals
signalsLabelsAll()
[pivotLow, pivotHigh, pivotLowEnd, pivotHighEnd] = pivots()
if _showPivots
and (not na(pivotHigh) or not na(pivotLow))
showPivots(pivotLow, pivotHigh)
if _showDivergences
divergencePivotAndValuesAll(pivotLow, pivotHigh, pivotLowEnd, pivotHighEnd)
clearDivergenceDrawings()
sendAlert()
sendEndAlert()
clearEndDivergenceLengths() |
Open Interest with Heikin Ashi candles | https://www.tradingview.com/script/ZOd77kTZ-Open-Interest-with-Heikin-Ashi-candles/ | MyFire_Yiannis | https://www.tradingview.com/u/MyFire_Yiannis/ | 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/
// © MyFire_Yiannis 2023
//
//@version=5
indicator(title = "Open Interest with Heikin Ashi", shorttitle = "OIHA v1.0", format = format.volume, overlay=false)
bool overwriteSymbolInput = input.bool(false, "Override symbol", inline = "Override symbol")
string tickerInput = input.symbol("", "", inline = "Override symbol")
string symbolOnly = syminfo.ticker(tickerInput)
string userSymbol = overwriteSymbolInput ? symbolOnly : syminfo.prefix + ":" + syminfo.ticker
string openInterestTicker = str.format("{0}_OI", userSymbol)
string timeframe = syminfo.type == "futures" and timeframe.isintraday ? "1D" : timeframe.period
[oiOpen, oiHigh, oiLow, oiClose, oiColorCond] = request.security(openInterestTicker, timeframe, [open, high, low, close, close > close[1]], ignore_invalid_symbol = true)
oiOpen := oiOpen ? oiOpen : na
oiHigh := oiHigh ? oiHigh : na
oiLow := oiLow ? oiLow : na
if barstate.islastconfirmedhistory and na(oiClose)
runtime.error(str.format("No Open Interest data found for the `{0}` symbol.", userSymbol))
hasOHLC = ta.cum(oiOpen)
color openInterestColor = oiColorCond ? color.teal : color.red
// plot(hasOHLC ? na : oiClose, "Futures Open Interest", openInterestColor, style = plot.style_stepline, linewidth = 4)
// plotcandle(oiOpen, oiHigh, oiLow, hasOHLC ? oiClose : na, "Crypto Open Interest", color = openInterestColor, wickcolor = openInterestColor, bordercolor = openInterestColor)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// HA start
//
bgHA = input.bool(true, "Background color", inline = "Background color")
heikenashi = ticker.heikinashi(openInterestTicker)
o = request.security(heikenashi, timeframe.period, open)
h = request.security(heikenashi, timeframe.period, high)
l = request.security(heikenashi, timeframe.period, low)
c = request.security(heikenashi, timeframe.period, close)
clr = c > o ? color.lime : color.red
plotcandle(o, h, l, c, 'Heiken Ashi', clr, color.black)
bgcolor(bgHA ? color.new(clr, 90) : na)
// HA stop
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
Subsets and Splits