0% found this document useful (0 votes)
143 views37 pages

HAlgo Pieki

The document contains a Pine Script™ code for the Pieki Algo V2 Indicator, which is designed for trading analysis on financial charts. It includes various user input options for customizing colors, signals, features, and market structure settings. The script also incorporates risk management tools and ICT kill zones for enhanced trading strategies.

Uploaded by

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

HAlgo Pieki

The document contains a Pine Script™ code for the Pieki Algo V2 Indicator, which is designed for trading analysis on financial charts. It includes various user input options for customizing colors, signals, features, and market structure settings. The script also incorporates risk management tools and ICT kill zones for enhanced trading strategies.

Uploaded by

woxiyew292
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 37

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.

0
at https://mozilla.org/MPL/2.0/
// Thanks to Efrem for Market Structure | StratifyTrade - formerly know as
HunterAlgos
// © Pieki

//@version=5
// # ========================================================================= #
// # | Pieki Algo V2 Indicator |
// # ========================================================================= #
indicator(title = "Pieki Algo [2.0]", shorttitle = "Pieki Algo", overlay = true,
max_bars_back = 500 ,max_lines_count = 500, max_labels_count = 500,
max_boxes_count = 500)
// # ========================================================================= #
// # | Pieki Algo V2 Indicator |
// # ========================================================================= #

// # ============================[GET USERS INPUT]============================ #


// Colors
gr_col = "Colors"
bullish = input.color(#0068ca, "Bullish", tooltip = "Changes the color of the
Bullish trend", inline = "1",group = gr_col)
bearish = input.color(#818181, "Bearish", tooltip = "Changes the color of the
Bearish trend", inline = "1",group = gr_col)
// Signals
gr_sig = "SIGNAL SETTINGS"
showsignal = input(true, "Show Signals", tooltip = "Turns on or off the display of
signals" , group = gr_sig)
sigsensiviti = input(3, "Sensivity", tooltip = "Changes the signal display
frequency", group = gr_sig)
colorbar = input(true, "Coloring Candle", tooltip = "Colors the bars depending on
the direction of the trend", group = gr_sig)
// Features
gr_fts = "FEATURES"
wavetrend = input(true, "Wave Trend", inline = "1", group = gr_fts)
wavelenght = input(20, "", inline = "1", tooltip = "Smoothed Moving Average (HMA),
helps in the direction of the current trend.", group = gr_fts)
trendline = input(true, "Trend Lines", inline = "2", group = gr_fts)
trendlilenght = input.int(50, "", inline = "2", step = 1, minval = 2, tooltip =
"Enables automatic drawing of trend lines", group = gr_fts)
volumeprofile = input(false, "Volume Profile", inline = "3",group = gr_fts)
volumerows = input.int(300,'', minval = 100, maxval = 2500, step = 100, tooltip =
"Displays the volume profile functions on the right side of the chart", inline =
"3", group = gr_fts, display = display.none)
liquidity = input(false, "Liquidity", inline = "4", group = gr_fts)
htfTF = input.timeframe("", "", inline = "4", tooltip = "Shows areas of market
liquidity", group = gr_fts)
vwap = input(false, "Vwap", inline = "5", group = gr_fts)
vwaplen = input(8, "", inline = "5", tooltip = "Showing 2 vwap lines", group =
gr_fts)
// Dashboard
gr_dash = "DASHBOARD SETTINGS"
showDashboard = input(true, "DASHBOARD", inline = "1", tooltip = "1", group =
gr_dash )
locationDashboard = input.string("Bottom Right", "Location", ["Top Right","Bottom
Right", "Bottom Left"], inline = "2", group = gr_dash)
sizeDashboard = input.string("Small", "Size", ["Large", "Normal", "Small",
"Tiny"], inline = "2", group = gr_dash)
exchange = input(false,"UTC Exchange", inline = "3", group = gr_dash )
utc_exchange = input(0, "", inline = "3", group = gr_dash)
// Market Structure
gr_ms = "Market Structur"
show_swing_ms = input.string ("All"
, "Swing " , inline = "1", group = gr_ms , options =
["All", "CHoCH", "CHoCH+", "BOS", "None"])
show_internal_ms = input.string ("All"
, "Internal " , inline = "2", group = gr_ms , options =
["All", "CHoCH", "CHoCH+", "BOS", "None"])
internal_r_lookback = input.int (5
, "" , inline = "2", group = gr_ms , minval =
2)
swing_r_lookback = input.int (50
, "" , inline = "1", group = gr_ms , minval =
2)
ms_mode = input.string ("Manual"
, "Market Structure Mode" , inline = "a", group = gr_ms , tooltip
= "[Manual] Use selected lenght\n[Dynamic] Use automatic lenght" ,options =
["Manual", "Dynamic"])
show_mtf_str = input.bool (false
, "MTF Scanner" , inline = "9", group = gr_ms , tooltip
= "Display Multi-Timeframe Market Structure Trend Directions. Green = Bullish. Red
= Bearish")
show_eql = input.bool (false
, "Show EQH/EQL" , inline = "6", group = gr_ms)
i_ms_up_BOS = input.color (#0068ca
, "" , inline = "2", group = gr_ms)
i_ms_dn_BOS = input.color (#818181
, "" , inline = "2", group = gr_ms)
s_ms_up_BOS = input.color (#0068ca
, "" , inline = "1", group = gr_ms)
s_ms_dn_BOS = input.color (#818181
, "" , inline = "1", group = gr_ms)

// High & LOWS


gr_hl = "Highs & Lows"
lvl_daily = input.bool (false
, "Day " , inline = "1", group = gr_hl)
lvl_weekly = input.bool (false
, "Week " , inline = "2", group = gr_hl)
lvl_monthly = input.bool (false
, "Month" , inline = "3", group = gr_hl)
lvl_yearly = input.bool (false
, "Year " , inline = "4", group = gr_hl)
css_d = input.color (color.blue
, "" , inline = "1", group = gr_hl)
css_w = input.color (color.blue
, "" , inline = "2", group = gr_hl)
css_m = input.color (color.blue
, "" , inline = "3", group = gr_hl)
css_y = input.color (color.blue
, "" , inline = "4", group = gr_hl)
s_d = input.string ('⎯⎯⎯'
, '' , inline = '1', group = gr_hl ,
options = ['⎯⎯⎯', '----', '····'])
s_w = input.string ('⎯⎯⎯'
, '' , inline = '2', group = gr_hl ,
options = ['⎯⎯⎯', '----', '····'])
s_m = input.string ('⎯⎯⎯'
, '' , inline = '3', group = gr_hl ,
options = ['⎯⎯⎯', '----', '····'])
s_y = input.string ('⎯⎯⎯'
, '' , inline = '4', group = gr_hl ,
options = ['⎯⎯⎯', '----', '····'])

// Risk Managments
gr_risk = "RISK MANAGEMENT"
levels = input.bool(false, "Show TP/SL Levels" , group = gr_risk , inline = "1")
lvlLines = input.bool(false, "Show Lines ", inline="2", group = gr_risk)
linesStyle = input.string("SOLID", "", ["SOLID", "DASHED", "DOTTED"], inline="2",
group = gr_risk)
atrRisk = input.int(1, "Risk % ", 1, group = gr_risk , inline="3")
lvlDecimals = input.int(2, "Decimals", 1, 8, inline="3", group = gr_risk)
// ICT KILL Zones
gr_ict = "ICT KILL ZONES"
i_tz = input.string('GMT-5', title= 'Timezone', options=['GMT-
11', 'GMT-10', 'GMT-9', 'GMT-8', 'GMT-7', 'GMT-6', 'GMT-5', 'GMT-4', 'GMT-3', 'GMT-
2', 'GMT-1', 'GMT', 'GMT+1', 'GMT+2', 'GMT+3', 'GMT+330', 'GMT+4', 'GMT+430',
'GMT+5', 'GMT+530', 'GMT+6', 'GMT+7', 'GMT+8', 'GMT+9', 'GMT+10', 'GMT+11',
'GMT+12'], tooltip='e.g. \'America/New_York\', \'Asia/Tokyo\', \'GMT-
4\', \'GMT+9\'...', group=gr_ict, inline = "1")
i_history_period = input.int(1, 'History', minval=0, maxval=100, group =
gr_ict, inline = "1" )
var bool canPlot = (timeframe.isminutes and timeframe.multiplier <= 60) or
timeframe.isseconds
i_show = i_history_period > 0 and canPlot
i_lookback = 12 * 60
LoSB = input(false, title="3-4 am", group = gr_ict,inline = "2")
NYSB = input(false, title="10-11 am", group = gr_ict,inline = "2")
NYPM = input(false, title="2-3 Pm", group = gr_ict,inline = "2")
LSBcolor = input.color(color.new(#5d606b,0),title="", group = gr_ict,inline
= "2")
LSBstyle = input.string ("Dashed", "", options=["Solid", "Dotted", "Dashed"],
group = gr_ict,inline = "2")
LST = LSBstyle == "Solid" ? line.style_solid : LSBstyle == "Dotted" ?
line.style_dotted : line.style_dashed
i_show_sess1 = input.bool(defval= true, title ="" ,group=gr_ict,
inline="a") and i_show
i_sess1Text = input.string ("Asian Range", title ="" ,group=gr_ict,
inline="a")
i_sess1_color = input.color(defval=color.new(#2a2e39, 0), title="",
group=gr_ict, inline="a")
i_sess1 = input.session('1900-2400', 'Time', group=gr_ict,
inline="a")
var i_sess1_extend ='× No'
var i_sess1_op = true
i_show_sess2 = input.bool(defval= true, title ="" , group=gr_ict,
inline="b") and i_show
i_sess2Text = input.string ("London", title ="" , group=gr_ict,
inline="b")
i_sess2_color = input.color(defval=color.new(#5b9cf6, 0), title="",
group=gr_ict, inline="b")
i_sess2 = input.session('0200-0500', "Time" , group=gr_ict,
inline="b")
var i_sess2_extend ='× No'
var i_sess2_op = true
i_show_sess3 = input.bool(defval= true, title ="" ,group=gr_ict,
inline="t") and i_show
i_sess3Text = input.string ("New York", title ="" ,group=gr_ict,
inline="t")
i_sess3_color = input.color(defval=color.new(#22ab94, 0), title="",
group=gr_ict, inline="t")
i_sess3 = input.session('0700-1000', "Time" , group=gr_ict,
inline="t")
var i_sess3_extend ='× No'
var i_sess3_op = true
i_show_sess4 = input.bool(defval= false , title ="" ,group=gr_ict,
inline="h" ) and i_show
i_sess4Text = input.string ("New York cl", title ="" ,group=gr_ict,
inline="h")
i_sess4_color = input.color(defval=color.new(#ec407a, 0), title="",
group=gr_ict, inline="h")
i_sess4 = input.session('1300-1600', "Time" , group=gr_ict,
inline="h")
var i_sess4_extend ='× No'
var i_sess4_op = true
i_show_sess5 = input.bool(defval= false , title ="" ,group=gr_ict,
inline="hz" ) and i_show
i_sess5Text = input.string ("input name", title ="" ,group=gr_ict,
inline="hz")
i_sess5_color = input.color(defval=color.new(#ba68c8, 0), title="",
group=gr_ict, inline="hz")
i_sess5 = input.session('1600-1630', "Time" , group=gr_ict,
inline="hz")
var i_sess5_extend ='× No'
var i_sess5_op = true
i_sess_box_style = input.string('Sandwich', 'Style', options=['Box',
'Sandwich'], group=gr_ict, inline="q")
i_sess_border_style = input.string(line.style_solid, 'Line style',
options=[line.style_solid, line.style_dotted, line.style_dashed], group=gr_ict,
inline="q")
i_sess_border_width = input.int(1, 'Thickness', minval=0, group=gr_ict,
inline="qq")
i_sess_bgopacity = input.int(94, 'Transp', minval=0, maxval=100, step=1,
group=gr_ict, tooltip='Setting the 100 is no background color', inline="qq")
f_get_label_position (_y, _side) =>
switch _y
'top' => _side == 'outside' ? label.style_label_lower_left :
label.style_label_upper_left
'bottom' => _side == 'outside' ? label.style_label_upper_left :
label.style_label_lower_left
i_label_show = input.bool(true, 'Show labels', group=gr_ict,
inline='label_show') and i_show
i_label_size = str.lower(input.string('Small', '', options=['Auto',
'Tiny', 'Small', 'Normal', 'Large', 'Huge'], group=gr_ict, inline='label_show'))
i_label_position_y = str.lower(input.string('Top', '', options=['Top',
'Bottom'], group=gr_ict, inline='label_show'))
i_label_position_s = str.lower(input.string('Outside', '', options=['Inside',
'Outside'], group=gr_ict, inline='label_show'))
i_label_position = f_get_label_position(i_label_position_y,
i_label_position_s)
i_label_format_name = input.bool(true, 'Name', group=gr_ict,
inline='label_format')
i_label_format_day = input.bool(false, 'Day', group=gr_ict,
inline='label_format')
i_label_format_price = input.bool(false, 'Price', group=gr_ict,
inline='label_format')
i_label_format_pips = input.bool(false, 'Pips', group=gr_ict,
inline='label_format')
// # ============================[SIGNALS]============================ #
supertrend(_close, factor, atrLen) =>
atr = ta.atr(atrLen)
upperBand = _close + factor * atr
lowerBand = _close - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ?
lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ?
upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend[1]
if na(atr[1])
direction := 1
else if prevSuperTrend == prevUpperBand
direction := close > upperBand ? -1 : 1
else
direction := close < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
[superTrend, direction]

sma1 = ta.sma(close, 8)
sma2 = ta.sma(close, 9)
sma3 = ta.sma(close, 13)
[supertrend, direction] = supertrend(close, sigsensiviti*2, 11)

bull = ta.crossover(close, supertrend) and close >= sma3


bear = ta.crossunder(close, supertrend) and close <= sma3
y1 = low - (ta.atr(30) * 2), y1B = low - ta.atr(30)
y2 = high + (ta.atr(30) * 2), y2B = high + ta.atr(30)

buy = bull and showsignal ? label.new(bar_index, y1, sma1 >= sma2 ? "▲ +" : "▲",
xloc.bar_index, yloc.price, bullish, label.style_label_up, color.white,
size.normal) : na
sell = bear and showsignal ? label.new(bar_index, y2, sma1 <= sma2 ? "▼ +" : "▼",
xloc.bar_index, yloc.price, bearish, label.style_label_down, color.white,
size.normal) : na
// # ============================[BAR COLOR]============================ #
atrb = 10 * ta.atr(sigsensiviti)
longStop = hl2 - atrb * 1
longStopPrev = nz(longStop[1], longStop)
longStop := close[1] > longStopPrev ? math.max(longStop, longStopPrev) : longStop
shortStop = hl2 + atrb * 1
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := close[1] < shortStopPrev ? math.min(shortStop, shortStopPrev) :
shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and close > shortStopPrev ? 1 : dir == 1 and close <
longStopPrev ? -1 : dir
barcolor(colorbar ? (dir == 1 ? bullish : bearish) : na)
// # ============================[Wave Trend]============================ #
wma = ta.wma(close, wavelenght)
wma1 = ta.wma(close, wavelenght)
a = 3 * wma - 2 * wma1
a1 = ta.sma(close, wavelenght)
diff = a - a1
x = diff
len = 100
xMax = ta.highest(x, len)
xMin = ta.lowest(x, len)
range_ = xMax - xMin
y = x / range_
g = math.round(y*40)
color1 = color.from_gradient(g, -2, 2, bearish, bullish)
tw1 = plot(wavetrend ? a : na, 'WaveTrend 1', color1, 2, editable = false)
tw2 = plot(wavetrend ? a1 : na, 'WaveTrend 2', color1, 2, editable = false)
fill(tw1, tw2, color = color1)
// # ============================[Trend Lines]============================ #
//Downtrendline
var int phx1 = na
var float phslope = na
var float phy1 = na
var float upper = na
var float plotH = na
var bool isOnH = false

//Uptrendline
var int plx1 = na
var float plslope = na
var float ply1 = na
var float lower = na
var float plotL = na
var bool isOnL = false

var line testLine = line.new(na, na, na, na, color=color.new(color.blue, 100))


//Calculations
n = bar_index
source = close
ph = ta.pivothigh(trendlilenght, trendlilenght)
pl = ta.pivotlow(trendlilenght, trendlilenght)
bg = chart.bg_color
fg = chart.fg_color
bars = 500 , height = bars / 3
Xaxis = math.min(math.max(1, n), bars)
Yaxis = ta.highest(Xaxis) - ta.lowest(Xaxis)
srcBl = source
srcBr = source
//Function
calculate_slope(x1, x2, y1, y2) =>
diffX = x2 - x1, diffY = y2 - y1
diffY_to_Yaxis = Yaxis / diffY
normalised_slope = (height / diffY_to_Yaxis) / diffX
slope = diffY / diffX
angle = math.round(math.atan(normalised_slope) * 180 / math.pi, 2)
[normalised_slope, slope, angle]
//Execution
if trendline
if not na(ph)
if ph < phy1
[normalised_slope, slope, angle] = calculate_slope(phx1, n -
trendlilenght, phy1, ph)
testLine.set_xy1(phx1, phy1), testLine.set_xy2(n, ph + slope *
trendlilenght)
src = source, max_bars_back(src, 2000)
isOnH := false
broken = false
if math.abs(angle) > 0.1 and math.abs(angle) < 90
for i = trendlilenght to n - plx1
if src[i] > testLine.get_price(n - i)
broken := true
break
if not broken
phslope := slope
isOnH := true
upper := ph + slope * trendlilenght
line.new(phx1, phy1, n, ph + slope * trendlilenght,
color=bearish, style=line.style_dotted)

phy1 := ph
phx1 := n - trendlilenght

upper += phslope
plotH := not na(ph) and ta.change(phslope) ? na : srcBl[1] > upper[1] ? na :
upper
bs_H = ta.barssince(na(plotH))

if not na(pl)
if pl > ply1
[normalised_slope, slope, angle] = calculate_slope(plx1, n - trendlilenght,
ply1, pl)
testLine.set_xy1(plx1, ply1), testLine.set_xy2(n, pl + slope *
trendlilenght)
src = source, max_bars_back(src, 2000)
isOnL := false
broken = false
if angle > 0.1 and angle < 90
for i = trendlilenght to n - plx1
if src[i] < testLine.get_price(n - i)
broken := true
break
if not broken
plslope := slope
isOnL := true
lower := pl + slope * trendlilenght
line.new(plx1, ply1, n, pl + slope * trendlilenght,
color=bullish, style=line.style_dotted)

ply1 := pl
plx1 := n - trendlilenght

lower += plslope
plotL := not na(pl) and ta.change(plslope) ? na : srcBr[1] < lower[1] ? na :
lower
bs_L = ta.barssince(na(plotL))
// # ============================[VolumeProfile]============================ #
// Get Components
import algotraderdev/contrast/1
int BASE_OFFSET = 20 + 80
int LABEL_OFFSET = BASE_OFFSET + 2
int START_TIME = switch volumeprofile
volumeprofile => chart.left_visible_bar_time
USE_SECOND_BASED_TIMEFRAMES = false
int MIN_TIMEFRAME_IN_SECONDS = USE_SECOND_BASED_TIMEFRAMES ? 1 : 60
// Function
maxIndex(float[] a) =>
if a.size() == 0
na
float max = a.first()
int maxIndex = 0
for [i, v] in a
if v > max
max := v
maxIndex := i
maxIndex
const int DIRECTION_NONE = 0
const int DIRECTION_BUY = 1
const int DIRECTION_SELL = -1
type Candle
float high
float low
float volume
int direction
type Marker
polyline poly
line extendedLine
label label
method set(Marker this, string name, int left, int right, float price, color bg,
float height) =>
if not na(this.poly)
this.poly.delete()
float bottom = price - height / 2
float top = bottom + height
chart.point[] points = array.from(
chart.point.from_index(left, bottom),
chart.point.from_index(left, top),
chart.point.from_index(right, top),
chart.point.from_index(right, bottom))
this.poly := polyline.new(points, line_color = bg, fill_color = bg)
if not na(this.extendedLine)
this.extendedLine.delete()
if volumeprofile
this.extendedLine := line.new(
x1 = left,
y1 = price,
x2 = right,
y2 = price,
extend = extend.left,
style = line.style_dotted,
color = bg)
if na(this.label)
this.label.delete()
string txt = str.format('{0}: {1}', name, math.round_to_mintick(price))
this.label := label.new(
x = bar_index + LABEL_OFFSET,
y = price,
text = txt,
style = label.style_label_left,
size = size.small,
color = bg,
textcolor = bg.contrast(0.6))

this
type VP
Candle[] candles
float minPrice
float maxPrice
float step
polyline poly
polyline buyPoly
polyline sellPoly
map<string, Marker> markers
method init(VP this) =>
this.candles := array.new<Candle>()
this.markers := map.new<string, Marker>()
this
method getBucketIndex(VP this, float price) =>
math.min(math.floor((price - this.minPrice) / this.step), volumerows - 1)
method getBucketedPrice(VP this, int index) =>
(index + 0.5) * this.step + this.minPrice
method mark(VP this, string name, float price, int left, color bg, float height) =>
int right = bar_index + BASE_OFFSET
Marker marker = this.markers.get(name)
if na(marker)
marker := Marker.new().set(name = name, left = left, right = right, price =
price, bg = bg, height = height)
method store(VP this, Candle candle) =>
this.candles.push(candle)
this.minPrice := na(this.minPrice) ? candle.low : math.min(this.minPrice,
candle.low)
this.maxPrice := na(this.maxPrice) ? candle.high : math.max(this.maxPrice,
candle.high)
this.step := (this.maxPrice - this.minPrice) / volumerows
method drawHistogram(VP this, int[] xs, int baseX, float step, float height, color
color) =>
chart.point[] points = array.new<chart.point>()
float gap = (step - height) / 2
for [i, x] in xs
float lo = i * step + gap + this.minPrice
float hi = lo + height
points.push(chart.point.from_index(index = baseX, price = lo))
points.push(chart.point.from_index(index = x, price = lo))
points.push(chart.point.from_index(index = x, price = hi))
points.push(chart.point.from_index(index = baseX, price = hi))
polyline.new(points, closed = true, line_color = color, fill_color = color)
method update(VP this) =>
float step = (this.maxPrice - this.minPrice) / volumerows
float[] dist = array.new_float(volumerows, 0)
float[] deltaDist = array.new_float(volumerows, 0)
for c in this.candles
int start = this.getBucketIndex(c.low)
int end = this.getBucketIndex(c.high)
int buckets = end - start + 1

float vol = c.volume / buckets


for i = start to end
dist.set(i, dist.get(i) + vol)
deltaDist.set(i, deltaDist.get(i) + vol * c.direction)
float maxVol = dist.max()

int baseX = bar_index + BASE_OFFSET


int[] xs = array.new_int()
for vol in dist
int width = math.round(vol / maxVol * 80)
int x = baseX - width
xs.push(x)
float height = 40 / 100 * step

// Plot
if not na(this.poly)
this.poly.delete()
this.poly := volumeprofile ? this.drawHistogram(xs, baseX, step, height,
color.new(#5d606b77,45)) : na

if volumeprofile
int[] buyXs = array.new_int()
int[] sellXs = array.new_int()
for vol in deltaDist
int width = math.round(math.abs(vol) / maxVol * 80)
int x = baseX - width
buyXs.push(vol > 0 ? x : baseX)
sellXs.push(vol < 0 ? x : baseX)
if not na(this.buyPoly)
this.buyPoly.delete()
this.buyPoly := this.drawHistogram(buyXs, baseX, step, height,
color.new(#089981, 50))
if not na(this.sellPoly)
this.sellPoly.delete()
this.sellPoly := this.drawHistogram(sellXs, baseX, step, height,
color.new(#f23645,50))

float[] cumdist = dist.copy()


for i = 1 to cumdist.size() - 1
cumdist.set(i, cumdist.get(i - 1) + cumdist.get(i))
float totalVolume = cumdist.last()

if volumeprofile
float valPercentile = (100 - 70) / 100 / 2
float vahPercentile = 1 - valPercentile
int valIndex = cumdist.binary_search_leftmost(totalVolume * valPercentile)
this.mark(
name = 'VAL',
price = this.getBucketedPrice(valIndex),
left = xs.get(valIndex),
bg = color.blue,
height = height)

int vahIndex = cumdist.binary_search_leftmost(totalVolume * vahPercentile)


this.mark(
name = 'VAH',
price = this.getBucketedPrice(vahIndex),
left = xs.get(vahIndex),
bg = color.blue,
height = height)

if volumeprofile
int pocIndex = maxIndex(dist)
this.mark(
name = 'POC',
price = this.getBucketedPrice(pocIndex),
left = xs.get(pocIndex),
bg = color.yellow,
height = height)

chart.point maxPoint = chart.point.from_index(index = baseX, price =


this.maxPrice)
chart.point minPoint = chart.point.from_index(index = baseX, price =
this.minPrice)
polyline.new(array.from(maxPoint, minPoint), line_color = chart.bg_color)

var VP vp = VP.new().init()

ltf(simple int multiplier) =>


timeframe.from_seconds(math.max(MIN_TIMEFRAME_IN_SECONDS,
math.round(timeframe.in_seconds() / multiplier)))

simple string ltf1 = timeframe.period


simple string ltf2 = ltf(2)
simple string ltf4 = ltf(4)
simple string ltf8 = ltf(8)
simple string ltf16 = ltf(16)
bool canProcess = time >= START_TIME and (last_bar_index - bar_index) < 5000
bool cp1 = canProcess
bool cp2 = request.security(syminfo.tickerid, ltf2, canProcess)
bool cp4 = request.security(syminfo.tickerid, ltf4, canProcess)
bool cp8 = request.security(syminfo.tickerid, ltf8, canProcess)
bool cp16 = request.security(syminfo.tickerid, ltf16, canProcess)
int dir2 = switch
close > open => DIRECTION_BUY
close < open => DIRECTION_SELL
=> DIRECTION_NONE
Candle candle = Candle.new(high, low, volume, dir2)
Candle[] c1 = array.from(candle)
Candle[] c2 = request.security_lower_tf(syminfo.tickerid, ltf2, candle,
ignore_invalid_timeframe = true)
Candle[] c4 = request.security_lower_tf(syminfo.tickerid, ltf4, candle,
ignore_invalid_timeframe = true)
Candle[] c8 = request.security_lower_tf(syminfo.tickerid, ltf8, candle,
ignore_invalid_timeframe = true)
Candle[] c16 = request.security_lower_tf(syminfo.tickerid, ltf16, candle,
ignore_invalid_timeframe = true)

var string ltf = na


if na(ltf)
ltf := switch
cp16 => ltf16
cp8 => ltf8
cp4 => ltf4
cp2 => ltf2
cp1 => ltf1

Candle[] cs = switch ltf


ltf1 => c1
ltf2 => c2
ltf4 => c4
ltf8 => c8
ltf16 => c16

if not na(cs)
for c in cs
vp.store(c)

if barstate.islast
vp.update()

// # ============================[Liquidity]============================ #

// Get Components
mitiOptions = "Remove"
displayStyle_liq = "Boxes"
hh = close
ll = close
timediff=(time[1]-time[101])/100
atr_liq = ta.atr(300)
float thold_liq = atr_liq * (2.5 / 10)
// Functions
tf_multi(tf) =>
ts = timeframe.in_seconds("")
htfs = timeframe.in_seconds(tf)
htfs/ts
display_limit_line(_array) =>
if array.size(_array) > 6/2
a = array.shift(_array)
line.delete(a)
display_limit_box(_array) =>
if array.size(_array) > 6/2
a = array.shift(_array)
box.delete(a)
remove_mitigated_lines(_array, _hl) =>
m = false
if array.size(_array) > 0
for i = array.size(_array) - 1 to 0 by 1
l = array.get(_array, i)
if _hl == "High" and hh > line.get_y1(l)
array.remove(_array, i)
if mitiOptions == "Show"
line.new(line.get_x1(l),line.get_y1(l),time,line.get_y1(l),
xloc=xloc.bar_time, color = color.new(#f23645,50), style=line.style_solid, width =
2)
line.delete(l)
m := true
if _hl == "Low" and ll < line.get_y1(l)
array.remove(_array, i)
if mitiOptions == "Show"
line.new(line.get_x1(l),line.get_y1(l),time,line.get_y1(l),
xloc=xloc.bar_time, color = color.new(#089981,50), style=line.style_solid, width =
2)
line.delete(l)
m := true
display_limit_line(_array)
m
remove_mitigated_boxes(_array, _hl) =>
m = false
if array.size(_array) > 0
for i = array.size(_array) - 1 to 0 by 1
l = array.get(_array, i)
if _hl == "High" and hh > box.get_top(l)
array.remove(_array, i)
if mitiOptions == "Show"
box.new(box.get_left(l),box.get_top(l),time,box.get_bottom(l),
xloc=xloc.bar_time, bgcolor = color.new(#f23645, 90), border_color =
color.new( #f23645, 90), border_style = line.style_solid)
box.delete(l)
m := true
if _hl == "Low" and ll < box.get_top(l)
array.remove(_array, i)
if mitiOptions == "Show"
box.new(box.get_left(l),box.get_top(l),time,box.get_bottom(l),
xloc=xloc.bar_time, bgcolor = color.new(#089981, 90), border_color =
color.new(#089981, 90), border_style = line.style_solid)
box.delete(l)
m := true
display_limit_box(_array)
m
extend_line_to_current(lineArray) =>
if array.size(lineArray) > 0
for i = array.size(lineArray) - 1 to 0 by 1
l = array.get(lineArray, i)
timeExt = timenow + ((timediff)*30)
line.set_x2(l, timeExt)

extend_box_to_current(boxArray) =>
if array.size(boxArray) > 0
for i = array.size(boxArray) - 1 to 0 by 1
b = array.get(boxArray, i)
timeExt = timenow + ((timediff)*30)
box.set_right(b, timeExt)

// ----------------------------------------------------
// Higher TimeFrame
// ----------------------------------------------------
// Varibles
// Lines
var highLineArrayHTF = array.new_line()
var lowLineArrayHTF = array.new_line()

// Boxes
var highBoxArrayHTF = array.new_box()
var lowBoxArrayHTF = array.new_box()

// Get HTF
[_time, _open, _high, _low, _close] = request.security(syminfo.tickerid, htfTF,
[time, open, high, low, close])

// Pivots
pivotHighHTF = ta.pivothigh(_high, 8*tf_multi(htfTF), 8+tf_multi(htfTF))
pivotLowHTF = ta.pivotlow(_low, 8*tf_multi(htfTF), 8+tf_multi(htfTF))

if liquidity
timeExt = time+((time[1]-time[2])*10)
dis = 8+tf_multi(htfTF)
if pivotHighHTF
if displayStyle_liq == "Lines"
array.push(highLineArrayHTF,
line.new(_time[dis],_high[dis],_time[+1],_high[dis],color = color.new(#f23645,50),
style=line.style_solid, xloc=xloc.bar_time, extend=extend.none, width = 2))
else
y1 = _high[dis]-thold_liq//math.max(_open[dis], _close[dis])
array.push(highBoxArrayHTF,
box.new(_time[dis],_high[dis],_time[+1],y1,bgcolor = color.new(#f23645,50) ,
border_color=color.new(#f23645,90), xloc=xloc.bar_time, border_style =
line.style_solid, extend=extend.none, border_width = 2,text="$",text_halign =
text.align_center,text_color = color.white,text_size = size.small))
if pivotLowHTF
if displayStyle_liq == "Lines"
array.push(lowLineArrayHTF,
line.new(_time[dis],_low[dis],_time[+1],_low[dis],color = color.new(#089981,50),
style=line.style_solid, xloc=xloc.bar_time, extend=extend.none, width = 2))
else
y1 = _low[dis]+thold_liq//math.min(_open[dis], _close[dis])
array.push(lowBoxArrayHTF,
box.new(_time[dis],_low[dis],_time[+1],y1,bgcolor = color.new(#089981,50),
border_color=color.new(#089981,90), xloc=xloc.bar_time, border_style =
line.style_solid, extend=extend.none, border_width = 2,text="$",text_halign =
text.align_center,text_color = color.white,text_size = size.small))

// ----------------------------------------------------
// Run Functions
// ----------------------------------------------------
highLineAlertHTF = remove_mitigated_lines(highLineArrayHTF, "High")
lowLineAlertHTF = remove_mitigated_lines(lowLineArrayHTF, "Low")
highBoxAlertHTF = remove_mitigated_boxes(highBoxArrayHTF, "High")
lowBoxAlertHTF = remove_mitigated_boxes(lowBoxArrayHTF, "Low")

extend_line_to_current(highLineArrayHTF)
extend_line_to_current(lowLineArrayHTF)
extend_box_to_current(highBoxArrayHTF)
extend_box_to_current(lowBoxArrayHTF)
// # ============================[VWAP]============================ #
vwapLength = 20
vwapValue = ta.vwma(close, vwapLength)
plot(vwap ? vwapValue : na, color=color.orange, title="VWAP")

bbUpper = ta.sma(close, vwaplen) + 3 * ta.stdev(close, vwaplen)


bbLower = ta.sma(close, vwaplen) - 3 * ta.stdev(close, vwaplen)
plot(vwap ? bbUpper : na, color=#5a5a5a, title="Up Line Vwap")
plot(vwap ? bbLower : na, color=#5a5a5a, title= "Down Line Vwap")

// # ============================[DASHBOARD]============================ #
indicatorTF = "Chart"
// -- MTF Function
f_chartTfInMinutes() =>
float _resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1. / 60 :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 60. * 24 :
timeframe.isweekly ? 60. * 24 * 7 :
timeframe.ismonthly ? 60. * 24 * 30.4375 : na)

equal_tf(res) => str.tonumber(res) == f_chartTfInMinutes()


higher_tf(res) => str.tonumber(res) > f_chartTfInMinutes()
too_small_tf(res) => (timeframe.isweekly and res=="1") or (timeframe.ismonthly and
str.tonumber(res) < 10)
securityNoRep(sym, res, src) =>
bool bull = na
bull := equal_tf(res) ? src : bull
bull := higher_tf(res) ? request.security(sym, res, src, barmerge.gaps_off,
barmerge.lookahead_on) : bull
bull_array = request.security_lower_tf(syminfo.tickerid, higher_tf(res) ?
str.tostring(f_chartTfInMinutes()) : too_small_tf(res) ? (timeframe.isweekly ?
"3" : "10") : res, src)
if array.size(bull_array) > 1 and not equal_tf(res) and not higher_tf(res)
bull := array.pop(bull_array)
array.clear(bull_array)
bull
// Checking Trend
di_length = 14
adx_smoothing = 14
bullish_threshold_multiplier = 1.2
bearish_threshold_multiplier = 0.8
[dmp, dmn, adx] = ta.dmi(di_length, adx_smoothing)
median_adx = ta.sma(adx, 14)
bullish_threshold = median_adx * bullish_threshold_multiplier
bearish_threshold = median_adx * bearish_threshold_multiplier
detectADXTrend() =>
isBullish = adx > bullish_threshold
isBearish = adx < bearish_threshold
trendQuality = isBullish ? 1 : isBearish ? -1 : 0

// Wywołanie funkcji
adxTrend = detectADXTrend()
// MTF
TF1Bull = securityNoRep(syminfo.tickerid, "1" , adxTrend)
TF3Bull = securityNoRep(syminfo.tickerid, "3" , adxTrend)
TF5Bull = securityNoRep(syminfo.tickerid, "5" , adxTrend)
TF10Bull = securityNoRep(syminfo.tickerid, "10" , adxTrend)
TF15Bull = securityNoRep(syminfo.tickerid, "15" , adxTrend)
TF30Bull = securityNoRep(syminfo.tickerid, "30" , adxTrend)
TF60Bull = securityNoRep(syminfo.tickerid, "60" , adxTrend)
TF120Bull = securityNoRep(syminfo.tickerid, "120" , adxTrend)
TF240Bull = securityNoRep(syminfo.tickerid, "240" , adxTrend)
TF720Bull = securityNoRep(syminfo.tickerid, "720" , adxTrend)
TFDBull = securityNoRep(syminfo.tickerid, "1440", adxTrend)

// -- Optimal Sensitivity
knnSensitivity(close, sensitivity, k) =>
data = request.security(syminfo.tickerid, "D", close)
input_data = ta.sma(data, 20)
distance = math.abs(close - input_data)
array_size = 100

distance_array = array.new_float(size = array_size)


array.set(distance_array, 0, distance)
array.sort(distance_array)
lowest_distance = array.min(distance_array, k)
avg_distance = ta.sma(lowest_distance, k)
knn_sensitivity = avg_distance / ta.atr(14)
knn_sensitivity_bounded = math.min(math.max(knn_sensitivity, 1), 26)
knn_sensitivity_bounded
optimal_sensitivity = knnSensitivity(close, sigsensiviti, 5)
final_sensitivity = ta.crossover(close, sma3) ? sigsensiviti : optimal_sensitivity
// -- Trend Strength
❄️
trendIndication = adxTrend == 1 ? "" : " "
// -- Volatility
atrr = 3 * ta.atr(10)
stdAtr = 2 * ta.stdev(atrr, 20)
smaAtr = ta.sma(atrr, 20)
topAtrDev = smaAtr + stdAtr
bottomAtrDev = smaAtr - stdAtr
calcDev = (atrr - bottomAtrDev) / (topAtrDev - bottomAtrDev)

percentVol = 40 * calcDev + 30
// -- Squeeze
conv = 50
lengthsq = 20
srcs = close

var max = 0.0


var min = 0.0

max := nz(math.max(srcs, max - (max - srcs) / conv), srcs)


min := nz(math.min(srcs, min + (srcs - min) / conv), srcs)
diffd = math.log(max - min)

psi = -50 * ta.correlation(diffd, bar_index, lengthsq) + 50

squeezePercentage = psi > 80 ? 100 : psi


// -- Sesion
sqz(bbLen, bbMult, kcLen, kcMult, source) =>
upperBB = ta.sma(source, bbLen) + ta.stdev(source, bbLen) * bbMult
lowerBB = ta.sma(source, bbLen) - ta.stdev(source, bbLen) * bbMult
upperKC = ta.sma(source, kcLen) + ta.sma(ta.tr, kcLen) * kcMult
lowerKC = ta.sma(source, kcLen) - ta.sma(ta.tr, kcLen) * kcMult
sqzOn = lowerBB > lowerKC and upperBB < upperKC
sqzOff = lowerBB < lowerKC and upperBB > upperKC
[sqzOn, sqzOff]
qqe(rsiLen, rsiSmooth, factor, source, bbLen, bbMult) =>
rsiMa = ta.ema(ta.rsi(source, rsiLen), rsiSmooth)
delta = ta.ema(ta.ema(math.abs(ta.mom(rsiMa, 1)), rsiLen * 2 - 1), rsiLen *
2 - 1) * factor
longBand = 0.0, longBand := rsiMa > longBand[1] and rsiMa[1] >
longBand[1] ? math.max(longBand[1], rsiMa - delta) : rsiMa - delta
shortBand = 0.0, shortBand := rsiMa < shortBand[1] and rsiMa[1] <
shortBand[1] ? math.min(shortBand[1], rsiMa + delta) : rsiMa + delta
cross1 = ta.cross(rsiMa, shortBand[1])
cross2 = ta.cross(rsiMa, longBand[1])
trend = 0.0, trend := cross1 ? 1 : cross2 ? -1 : nz(trend[1], 1)
fastDelta = trend == 1 ? longBand : shortBand
_hist = rsiMa - 50
_line = fastDelta - 50
[_, upper, lower] = ta.bb(_line, bbLen, bbMult)
[_hist, _line, upper, lower]

// Get components
cond(_offset) =>
top = ta.highest(high, 10)
bot = ta.lowest(low, 10)
osc = ta.ema(hlc3, 5) - ta.ema(ohlc4, 20)
oscRis = osc > osc[1]
oscFal = osc < osc[1]
oscA0 = osc > 0
oscB0 = osc < 0
oscTop = oscFal and oscRis[1]
oscBot = oscRis and oscFal[1]
bullR = oscB0 and oscBot and ((osc > ta.valuewhen(oscB0 and oscBot, osc, 1)
and bot < ta.valuewhen(oscB0 and oscBot, bot, 1)))
bearR = oscA0 and oscTop and ((osc < ta.valuewhen(oscA0 and oscTop, osc, 1)
and top > ta.valuewhen(oscA0 and oscTop, top, 1)))
bullH = oscB0 and oscBot and ((osc < ta.valuewhen(oscB0 and oscBot, osc, 1)
and bot > ta.valuewhen(oscB0 and oscBot, bot, 1)))
bearH = oscA0 and oscTop and ((osc > ta.valuewhen(oscA0 and oscTop, osc, 1)
and top < ta.valuewhen(oscA0 and oscTop, top, 1)))
[sqzOn, sqzOff] = sqz(20, 2, 20, 2, close)
[_hist1, _line1, upper1, lower1] = qqe(6, 6, 3, close, 50, 0.001)
[_hist2, _line2, upper2, lower2] = qqe(6, 5, 1.618, close, 50, 1)
[_, _, tvr] = ta.dmi(14, 14)
[osc[_offset], oscRis[_offset], oscFal[_offset], oscA0[_offset],
oscB0[_offset], oscTop[_offset], oscBot[_offset], bullR[_offset], bearR[_offset],
bullH[_offset], bearH[_offset], sqzOn[_offset], sqzOff[_offset], _hist1[_offset],
upper1[_offset], lower1[_offset], _hist2[_offset], _line2[_offset], tvr[_offset]]
tf = indicatorTF == "Chart" ? timeframe.period : indicatorTF == "1 minute" ? "1" :
indicatorTF == "3 minutes" ? "3" : indicatorTF == "5 minutes" ? "5" : indicatorTF
== "10 minutes" ? "10" : indicatorTF == "15 minutes" ? "15" : indicatorTF == "30
minutes" ? "30" : indicatorTF == "45 minutes" ? "45" : indicatorTF == "1 hour" ?
"60" : indicatorTF == "2 hours" ? "120" : indicatorTF == "3 hours" ? "180" :
indicatorTF == "4 hours" ? "240" : indicatorTF == "12 hours" ? "720" : indicatorTF
== "1 day" ? "1D" : indicatorTF == "1 week" ? "1W" : indicatorTF == "1 month" ?
"1M" : na
[osc, oscRis, oscFal, oscA0, oscB0, oscTop, oscBot, bullR, bearR, bullH, bearH,
sqzOn, sqzOff, _hist1, upper1, lower1, _hist2, _line2, tvr] =
request.security(syminfo.tickerid, tf, cond(indicatorTF != "Chart" and
barstate.isrealtime ? 1 : 0))
//Session A
NYSes = true
NYTxt = 'New York'
NYTime = '1300-2200'
//Session B
LDSes = true
sesb_txt = 'London'
sesb_ses = '0700-1600'
//Session C
show_sesc = true
sesc_txt = 'Tokyo'
sesc_ses = '0000-0900'
//Session D
show_sesd = true
sesd_txt = 'Sydney'
sesd_ses = '2100-0600'
tff = timeframe.period
var tz = exchange ? syminfo.timezone :
str.format('UTC{0}{1}', utc_exchange >= 0 ? '+' : '-', math.abs(utc_exchange))

is_sesa = math.sign(nz(time(tff, NYTime, tz)))


is_sesb = math.sign(nz(time(tff, sesb_ses, tz)))
is_sesc = math.sign(nz(time(tff, sesc_ses, tz)))
is_sesd = math.sign(nz(time(tff, sesd_ses, tz)))
SessionText = "Default"
if is_sesd
SessionText := sesd_txt

if is_sesc
SessionText := sesc_txt

if is_sesb
SessionText := sesb_txt

if is_sesa
SessionText := NYTxt

if is_sesd and is_sesc


SessionText := "Sydney/Tokyo"

if is_sesb and is_sesc


SessionText := "Tokyo/London"

if is_sesb and is_sesa


SessionText := "London/Newyork"

if is_sesa and is_sesd


SessionText := "Newyork/Sydney"
// Dashboard Function
var dashboard_loc = locationDashboard == "Top Right" ? position.top_right :
locationDashboard == "Bottom Right" ? position.bottom_right : locationDashboard ==
"Bottom Left" ? position.bottom_left : position.bottom_left
var dashboard_size = sizeDashboard == "Large" ? size.large : sizeDashboard ==
"Normal" ? size.normal : sizeDashboard == "Small" ? size.small : size.tiny
var dashboard = showDashboard ? table.new(dashboard_loc, 3, 7, color.rgb(30,
34, 45 , 60), #3d384300, 2, color.rgb(30, 34, 45 , 60), 1) : na

dashboard_cell(column, row, txt, signal=false) => table.cell(dashboard, column,


row, txt, 0, 0, signal ? #000000 : color.white, text_size=dashboard_size)
dashboard_cell_bg(column, row, col) => table.cell_set_bgcolor(dashboard, column,
row, col)
if barstate.islast and showDashboard

// MTF Trend
dashboard_cell(0, 0 , "MTF")
dashboard_cell(0, 2 , "M5") , dashboard_cell_bg(0, 2 , TF5Bull ?
color.new(bullish, 20) : color.new(bearish,20))
dashboard_cell(0, 3 , "M15") , dashboard_cell_bg(0, 3 , TF15Bull ?
color.new(bullish, 20) : color.new(bearish,20))
dashboard_cell(0, 4 , "M30") , dashboard_cell_bg(0, 4 , TF30Bull ?
color.new(bullish, 20) : color.new(bearish,20))
dashboard_cell(0, 5 , "1H") , dashboard_cell_bg(0, 5 , TF60Bull ?
color.new(bullish, 20): color.new(bearish,20))
dashboard_cell(0, 6 , "4H") , dashboard_cell_bg(0, 6 , TF240Bull ?
color.new(bullish, 20): color.new(bearish,20))

// Middel part
dashboard_cell(1, 0 , " Pieki Algo V.2")
dashboard_cell(1, 2 , "🔎 Optimal Sensitivity ")
dashboard_cell(1, 3 , str.tostring(trendIndication) + " Trend Strength ")
dashboard_cell(1, 4 , "⚠️ Volatility ")
dashboard_cell(1, 5 , "💠 Squeeze ")
dashboard_cell(1, 6 , "🕒 Current Session (UTC) ")

// End part
dashboard_cell(2, 0 , "")
dashboard_cell(2, 2 , str.tostring(final_sensitivity , "#"))
dashboard_cell(2, 3 , str.tostring(adx, format.percent))
dashboard_cell(2, 4 , str.tostring(percentVol, format.percent))
dashboard_cell(2, 5 , str.tostring(squeezePercentage, format.percent))
dashboard_cell(2, 6 , SessionText)
// # ============================[Market Structure]============================ #
// Get comp
boolean =
array.from(false, false , false , false , false , false , false , false, false)

s_BOS = 0
s_CHoCH = 1
i_BOS = 2
i_CHoCH = 3
i_pp_CHoCH = 4
green_candle = 5
red_candle = 6
s_CHoCHP = 7
i_CHoCHP = 8
ob_filter = "None"
invcol = color.new(color.white,100)
type bar
float o = open
float c = close
float h = high
float l = low
float v = volume
int n = bar_index
int t = time
type ms
float[] p
int [] n
float[] l
type msDraw
int n
float p
color css
string txt
bool bull
type ehl
float pt
int t
float pb
int b
// General Setup
bar b = bar.new()

f_zscore(src, lookback) =>

(src - ta.sma(src, lookback)) / ta.stdev(src, lookback)

var int iLen = internal_r_lookback


var int sLen = swing_r_lookback

vv = f_zscore(((close - close[iLen]) / close[iLen]) * 100,iLen)


if ms_mode == "Dynamic"

switch

vv >= 1.5 or vv <= -1.5 => iLen := 10


vv >= 1.6 or vv <= -1.6 => iLen := 9
vv >= 1.7 or vv <= -1.7 => iLen := 8
vv >= 1.8 or vv <= -1.8 => iLen := 7
vv >= 1.9 or vv <= -1.9 => iLen := 6
vv >= 2.0 or vv <= -2.0 => iLen := 5
=> iLen

var msline = array.new<line>(0)

iH = ta.pivothigh(high, iLen, iLen)


sH = ta.pivothigh(high, sLen, sLen)
iL = ta.pivotlow (low , iLen, iLen)
sL = ta.pivotlow (low , sLen, sLen)
// Arrays
hl () => [high, low]
[pdh, pdl] = request.security(syminfo.tickerid , 'D' , hl() , lookahead =
barmerge.lookahead_on)
[pwh, pwl] = request.security(syminfo.tickerid , 'W' , hl() , lookahead =
barmerge.lookahead_on)
[pmh, pml] = request.security(syminfo.tickerid , 'M' , hl() , lookahead =
barmerge.lookahead_on)
[pyh, pyl] = request.security(syminfo.tickerid , '12M', hl() , lookahead =
barmerge.lookahead_on)

lstyle(style) =>

out = switch style

'⎯⎯⎯' => line.style_solid


'----' => line.style_dashed
'····' => line.style_dotted

mtfphl(h, l ,tf ,css, pdhl_style) =>

var line hl = line.new(


na
, na
, na
, na
, xloc = xloc.bar_time
, color = css
, style = lstyle(pdhl_style)
)

var line ll = line.new(


na
, na
, na
, na
, xloc = xloc.bar_time
, color = css
, style = lstyle(pdhl_style)
)
var label lbl = label.new(
na
, na
, xloc = xloc.bar_time
, text = str.format('P{0}L', tf)
, color = invcol
, textcolor = css
, size = size.small
, style = label.style_label_left
)

var label hlb = label.new(


na
, na
, xloc = xloc.bar_time
, text = str.format('P{0}H', tf)
, color = invcol
, textcolor = css
, size = size.small
, style = label.style_label_left
)

hy = ta.valuewhen(h != h[1] , h , 1)
hx = ta.valuewhen(h == high , time , 1)
ly = ta.valuewhen(l != l[1] , l , 1)
lx = ta.valuewhen(l == low , time , 1)

if barstate.islast

extension = time + (time - time[1]) * 50

line.set_xy1(hl , hx , hy)
line.set_xy2(hl , extension , hy)
label.set_xy(hlb, extension , hy)
line.set_xy1(ll , lx , ly)
line.set_xy2(ll , extension , ly)
label.set_xy(lbl, extension , ly)

if lvl_daily

mtfphl(pdh , pdl , 'D' , css_d, s_d)

if lvl_weekly

mtfphl(pwh , pwl , 'W' , css_w, s_w)

if lvl_monthly

mtfphl(pmh , pml, 'M' , css_m, s_m)

if lvl_yearly

mtfphl(pyh , pyl , '12M', css_y, s_y)


// MS
method darkcss(color css, float factor, bool bull) =>

blue = color.b(css) * (1 - factor)


red = color.r(css) * (1 - factor)
green = color.g(css) * (1 - factor)

color.rgb(red, green, blue, 0)

method f_line(msDraw d, size, style) =>

var line id = na
var label lbl = na

id := line.new(
d.n
, d.p
, b.n
, d.p
, color = d.css
, width = 1
, style = style
)

if msline.size() >= 250

line.delete(msline.shift())

msline.push(id)

lbl := label.new(
int(math.avg(d.n, b.n))
, d.p
, d.txt
, color = invcol
, textcolor = d.css
, style = d.bull ? label.style_label_down : label.style_label_up
, size = size
, text_font_family = font.family_monospace
)

structure(bool mtf) =>

msDraw drw = na

bool isdrw = false


bool isdrwS = false

var color css = na


var color icss = na

var int itrend = 0


var int trend = 0

bool bull_ob = false


bool bear_ob = false

bool s_bull_ob = false


bool s_bear_ob = false

n = bar_index

var ms up = ms.new(
array.new<float>()
, array.new< int >()
, array.new<float>()
)

var ms dn = ms.new(
array.new<float>()
, array.new< int >()
, array.new<float>()
)

var ms sup = ms.new(


array.new<float>()
, array.new< int >()
, array.new<float>()
)

var ms sdn = ms.new(


array.new<float>()
, array.new< int >()
, array.new<float>()
)

switch show_swing_ms

"All" => boolean.set(s_BOS , true ), boolean.set(s_CHoCH, true ) ,


boolean.set(s_CHoCHP, true )
"CHoCH" => boolean.set(s_BOS , false), boolean.set(s_CHoCH, true ) ,
boolean.set(s_CHoCHP, false )
"CHoCH+" => boolean.set(s_BOS , false), boolean.set(s_CHoCH, false) ,
boolean.set(s_CHoCHP, true )
"BOS" => boolean.set(s_BOS , true ), boolean.set(s_CHoCH, false) ,
boolean.set(s_CHoCHP, false )
"None" => boolean.set(s_BOS , false), boolean.set(s_CHoCH, false) ,
boolean.set(s_CHoCHP, false )
=> na

switch show_internal_ms

"All" => boolean.set(i_BOS, true ), boolean.set(i_CHoCH, true ),


boolean.set(i_CHoCHP, true )
"CHoCH" => boolean.set(i_BOS, false), boolean.set(i_CHoCH, true ),
boolean.set(i_CHoCHP, false)
"CHoCH+" => boolean.set(i_BOS, false), boolean.set(i_CHoCH, false ),
boolean.set(i_CHoCHP, true )
"BOS" => boolean.set(i_BOS, true ), boolean.set(i_CHoCH, false ),
boolean.set(i_CHoCHP, false)
"None" => boolean.set(i_BOS, false), boolean.set(i_CHoCH, false ),
boolean.set(i_CHoCHP, false)
=> na

switch
iH =>

up.p.unshift(b.h[iLen])
up.l.unshift(b.h[iLen])
up.n.unshift(n [iLen])

iL =>
dn.p.unshift(b.l[iLen])
dn.l.unshift(b.l[iLen])
dn.n.unshift(n [iLen])

sL =>

sdn.p.unshift(b.l[sLen])
sdn.l.unshift(b.l[sLen])
sdn.n.unshift(n [sLen])

sH =>

sup.p.unshift(b.h[sLen])
sup.l.unshift(b.h[sLen])
sup.n.unshift(n [sLen])

// INTERNAL BULLISH STRUCTURE


if up.p.size() > 0 and dn.l.size() > 1

if ta.crossover(b.c, up.p.first())

bool CHoCH = na
string txt = na

if itrend < 0

CHoCH := true

switch

not CHoCH =>

txt := "BOS"
css := i_ms_up_BOS

if boolean.get(i_BOS) and mtf == false and na(drw)

isdrw := true
drw := msDraw.new(
up.n.first()
, up.p.first()
, i_ms_up_BOS
, txt
, true
)

CHoCH =>

txt := dn.l.first() > dn.l.get(1) ? "CHoCH+" :


"CHoCH"
css := i_ms_up_BOS.darkcss(0.25, true)

if (dn.l.first() > dn.l.get(1) ?


boolean.get(i_CHoCHP) : boolean.get(i_CHoCH)) and mtf == false and na(drw)

isdrw := true
drw := msDraw.new(
up.n.first()
, up.p.first()
, i_ms_up_BOS.darkcss(0.25, true)
, txt
, true
)

if mtf == false

switch

ob_filter == "None" =>


bull_ob := true
ob_filter == "BOS" and txt == "BOS" =>
bull_ob := true
ob_filter == "CHoCH" and txt == "CHoCH" =>
bull_ob := true
ob_filter == "CHoCH+" and txt == "CHoCH+" =>
bull_ob := true

itrend := 1
up.n.clear()
up.p.clear()

// INTERNAL BEARISH STRUCTURE


if dn.p.size() > 0 and up.l.size() > 1

if ta.crossunder(b.c, dn.p.first())

bool CHoCH = na
string txt = na

if itrend > 0

CHoCH := true

switch

not CHoCH =>

txt := "BOS"
css := i_ms_dn_BOS

if boolean.get(i_BOS) and mtf == false and na(drw)

isdrw := true
drw := msDraw.new(
dn.n.first()
, dn.p.first()
, i_ms_dn_BOS
, txt
, false
)

CHoCH =>

txt := up.l.first() < up.l.get(1) ? "CHoCH+" :


"CHoCH"
css := i_ms_dn_BOS.darkcss(0.25, false)

if (up.l.first() < up.l.get(1) ?


boolean.get(i_CHoCHP) : boolean.get(i_CHoCH)) and mtf == false and na(drw)

isdrw := true
drw := msDraw.new(
dn.n.first()
, dn.p.first()
, i_ms_dn_BOS.darkcss(0.25, false)
, txt
, false
)

if mtf == false

switch

ob_filter == "None" =>


bear_ob := true
ob_filter == "BOS" and txt == "BOS" =>
bear_ob := true
ob_filter == "CHoCH" and txt == "CHoCH" =>
bear_ob := true
ob_filter == "CHoCH+" and txt == "CHoCH+" =>
bear_ob := true

itrend := -1
dn.n.clear()
dn.p.clear()

// SWING BULLISH STRUCTURE


if sup.p.size() > 0 and sdn.l.size() > 1

if ta.crossover(b.c, sup.p.first())

bool CHoCH = na
string txt = na

if trend < 0

CHoCH := true

switch

not CHoCH =>

txt := "BOS"
icss := s_ms_up_BOS

if boolean.get(s_BOS) and mtf == false and na(drw)

isdrwS := true
drw := msDraw.new(
sup.n.first()
, sup.p.first()
, s_ms_up_BOS
, txt
, true
)

CHoCH =>

txt := sdn.l.first() > sdn.l.get(1) ? "CHoCH+" :


"CHoCH"
icss := s_ms_up_BOS.darkcss(0.25, true)

if (sdn.l.first() > sdn.l.get(1) ?


boolean.get(s_CHoCHP) : boolean.get(s_CHoCH)) and mtf == false and na(drw)

isdrwS := true
drw := msDraw.new(
sup.n.first()
, sup.p.first()
, s_ms_up_BOS.darkcss(0.25, true)
, txt
, true
)

if mtf == false

switch

ob_filter == "None" =>


s_bull_ob := true
ob_filter == "BOS" and txt == "BOS" =>
s_bull_ob := true
ob_filter == "CHoCH" and txt == "CHoCH" =>
s_bull_ob := true
ob_filter == "CHoCH+" and txt == "CHoCH+" =>
s_bull_ob := true

trend := 1
sup.n.clear()
sup.p.clear()

// SWING BEARISH STRUCTURE


if sdn.p.size() > 0 and sup.l.size() > 1

if ta.crossunder(b.c, sdn.p.first())

bool CHoCH = na
string txt = na

if trend > 0

CHoCH := true

switch

not CHoCH =>

txt := "BOS"
icss := s_ms_dn_BOS

if boolean.get(s_BOS) and mtf == false and na(drw)


isdrwS := true
drw := msDraw.new(
sdn.n.first()
, sdn.p.first()
, s_ms_dn_BOS
, txt
, false
)

CHoCH =>

txt := sup.l.first() < sup.l.get(1) ? "CHoCH+" :


"CHoCH"
icss := s_ms_dn_BOS.darkcss(0.25, false)

if (sup.l.first() < sup.l.get(1) ?


boolean.get(s_CHoCHP) : boolean.get(s_CHoCH)) and mtf == false and na(drw)

isdrwS := true
drw := msDraw.new(
sdn.n.first()
, sdn.p.first()
, s_ms_dn_BOS.darkcss(0.25, false)
, txt
, false
)

if mtf == false

switch

ob_filter == "None" =>


s_bear_ob := true
ob_filter == "BOS" and txt == "BOS" =>
s_bear_ob := true
ob_filter == "CHoCH" and txt == "CHoCH" =>
s_bear_ob := true
ob_filter == "CHoCH+" and txt == "CHoCH+" =>
s_bear_ob := true

trend := -1
sdn.n.clear()
sdn.p.clear()

[css, bear_ob, bull_ob, itrend, drw, isdrw, s_bear_ob, s_bull_ob, trend, icss,
isdrwS]

[css, bear_ob, bull_ob, itrend, drw, isdrw, s_bear_ob, s_bull_ob, trend, icss,
isdrwS] = structure(false)

if isdrw
f_line(drw, size.small, line.style_dashed)

if isdrwS
f_line(drw, size.small, line.style_solid)

[_, _, _, itrend15, _, _, _, _, _, _, _] = request.security("", "15" ,


structure(true))
[_, _, _, itrend1H, _, _, _, _, _, _, _] = request.security("", "60" ,
structure(true))
[_, _, _, itrend4H, _, _, _, _, _, _, _] = request.security("", "240" ,
structure(true))
[_, _, _, itrend1D, _, _, _, _, _, _, _] = request.security("", "1440" ,
structure(true))

if show_mtf_str

var tab = table.new(position = position.top_right, columns = 10, rows = 10,


bgcolor = na, frame_color = color.rgb(54, 58, 69, 0), frame_width = 1, border_color
= color.rgb(54, 58, 69, 100), border_width = 1)
table.cell(tab, 0, 1, text = "15" , text_color = color.silver, text_halign =
text.align_center, text_size = size.normal, bgcolor = chart.bg_color,
text_font_family = font.family_monospace, width = 2)
table.cell(tab, 0, 2, text = "1H" , text_color = color.silver, text_halign =
text.align_center, text_size = size.normal, bgcolor = chart.bg_color,
text_font_family = font.family_monospace, width = 2)
table.cell(tab, 0, 3, text = "4H" , text_color = color.silver, text_halign =
text.align_center, text_size = size.normal, bgcolor = chart.bg_color,
text_font_family = font.family_monospace, width = 2)
table.cell(tab, 0, 4, text = "1D" , text_color = color.silver, text_halign =
text.align_center, text_size = size.normal, bgcolor = chart.bg_color,
text_font_family = font.family_monospace, width = 2)

table.cell(tab, 1, 1, text = itrend15 == 1 ? "BULLISH" : itrend15 == -1 ?


"BEARISH" : na , text_halign = text.align_center, text_size = size.normal,
text_color = itrend15 == 1 ? i_ms_up_BOS.darkcss(-0.25, true) : itrend15 == -1 ?
i_ms_dn_BOS.darkcss(0.25, false) : color.gray, bgcolor = chart.bg_color,
text_font_family = font.family_monospace)
table.cell(tab, 1, 2, text = itrend1H == 1 ? "BULLISH" : itrend1H == -1 ?
"BEARISH" : na , text_halign = text.align_center, text_size = size.normal,
text_color = itrend1H == 1 ? i_ms_up_BOS.darkcss(-0.25, true) : itrend1H == -1 ?
i_ms_dn_BOS.darkcss(0.25, false) : color.gray, bgcolor = chart.bg_color,
text_font_family = font.family_monospace)
table.cell(tab, 1, 3, text = itrend4H == 1 ? "BULLISH" : itrend4H == -1 ?
"BEARISH" : na , text_halign = text.align_center, text_size = size.normal,
text_color = itrend4H == 1 ? i_ms_up_BOS.darkcss(-0.25, true) : itrend4H == -1 ?
i_ms_dn_BOS.darkcss(0.25, false) : color.gray, bgcolor = chart.bg_color,
text_font_family = font.family_monospace)
table.cell(tab, 1, 4, text = itrend1D == 1 ? "BULLISH" : itrend1D == -1 ?
"BEARISH" : na , text_halign = text.align_center, text_size = size.normal,
text_color = itrend1D == 1 ? i_ms_up_BOS.darkcss(-0.25, true) : itrend1D == -1 ?
i_ms_dn_BOS.darkcss(0.25, false) : color.gray, bgcolor = chart.bg_color,
text_font_family = font.family_monospace)

table.merge_cells(tab, 0, 5, 1, 5)
table.merge_cells(tab, 0, 5, 1, 5)
// EQH/EQL
dEHL() =>

var ehl w = ehl.new(0, 0, 0, 0)


top = ta.pivothigh(high, 1, 1)
btm = ta.pivotlow(low , 1, 1)
atr = ta.atr(200)

switch

top =>
mx = math.max(top, w.pt)
mn = math.min(top, w.pt)

switch

mx < mn + atr * 0.1 =>

var aZ = array.new<line>()
var aL = array.new<label>()

if aZ.size() > 50

aZ.pop().delete()
aL.pop().delete()

aZ.unshift(line.new(w.t, w.pt, b.n - 1, top, color =


i_ms_dn_BOS, style = line.style_dotted))
aL.unshift(label.new(int(math.avg(b.n - 1, w.t)), top, "EQH",
color = invcol, textcolor = i_ms_dn_BOS, style = label.style_label_down, size =
size.tiny))

w.pt := top
w.t := b.n - 1

btm =>

mx = math.max(btm, w.pb)
mn = math.min(btm, w.pb)

switch

mn > mx - atr * 0.1 =>

var aZ = array.new<line>()
var aL = array.new<label>()

if aZ.size() > 50

aZ.pop().delete()
aL.pop().delete()

aZ.unshift(line.new(w.b, w.pb, b.n - 1, btm, color =


i_ms_up_BOS, style = line.style_dotted))
aL.unshift(label.new(int(math.avg(b.n - 1, w.b)), btm, "EQL",
color = invcol, textcolor = i_ms_up_BOS, style = label.style_label_up, size =
size.tiny))

w.pb := btm
w.b := b.n - 1

if show_eql
dEHL()
// # ============================[RISK MANAGEMENT]============================ #
decimals = lvlDecimals == 1 ? "#.#" : lvlDecimals == 2 ? "#.##" : lvlDecimals == 3
? "#.###" : lvlDecimals == 4 ? "#.####" : lvlDecimals == 5 ? "#.#####" :
lvlDecimals == 6 ? "#.######" : lvlDecimals == 7 ? "#.#######" : "#.########"
atrLen = 14
rigger2 = bull ? 1 : 0
countBull = ta.barssince(bull)
countBear = ta.barssince(bear)
trigger = nz(countBull, bar_index) < nz(countBear, bar_index) ? 1 : 0
atrBand = ta.atr(atrLen) * atrRisk
atrStop = trigger == 1 ? low - atrBand : high + atrBand

lastTrade(close) => ta.valuewhen(bull or bear , close, 0)

stop_y = lastTrade(atrStop)
stop = levels ? label.new(time, close, "SL " + str.tostring(stop_y, decimals),
xloc.bar_time, yloc.price, bearish, label.style_label_left, color.white,
size.normal) : na
label.set_x(stop, label.get_x(stop) + math.round(ta.change(time) * 1))
label.set_y(stop, stop_y)
label.delete(stop[1])

tp1Rl_y = (lastTrade(close)-lastTrade(atrStop))*1 + lastTrade(close)


tp1Rl = levels ? label.new(time, close, "1:1 TP " + str.tostring(tp1Rl_y,
decimals), xloc.bar_time, yloc.price, bullish, label.style_label_left, color.white,
size.normal ) : na
label.set_x(tp1Rl, label.get_x(tp1Rl) + math.round(ta.change(time) * 1))
label.set_y(tp1Rl, tp1Rl_y)
label.delete(tp1Rl[1])

tp2RL_y = (lastTrade(close)-lastTrade(atrStop))*2 + lastTrade(close)


tp2RL = levels ? label.new(time, close, "2:1 TP " + str.tostring(tp2RL_y,
decimals), xloc.bar_time, yloc.price, bullish, label.style_label_left, color.white,
size.normal) : na
label.set_x(tp2RL, label.get_x(tp2RL) + math.round(ta.change(time) * 1))
label.set_y(tp2RL, tp2RL_y)
label.delete(tp2RL[1])

tp3RL_y = (lastTrade(close)-lastTrade(atrStop))*3 + lastTrade(close)


tp3RL = levels ? label.new(time, close, "3:1 TP " + str.tostring(tp3RL_y,
decimals), xloc.bar_time, yloc.price, bullish, label.style_label_left, color.white,
size.normal) : na
label.set_x(tp3RL, label.get_x(tp3RL) + math.round(ta.change(time) * 1))
label.set_y(tp3RL, tp3RL_y)
label.delete(tp3RL[1])

style = linesStyle == "SOLID" ? line.style_solid : linesStyle == "DASHED" ?


line.style_dashed : line.style_dotted
lineStop = levels and lvlLines ? line.new(bar_index - (trigger == 0 ? countBull :
countBear), stop_y, bar_index + 1, stop_y, xloc.bar_index, extend.none, bearish,
style, 2) : na, line.delete(lineStop[1])
lineTp1Rl = levels and lvlLines ? line.new(bar_index - (trigger == 0 ?
countBull : countBear), tp1Rl_y, bar_index + 1, tp1Rl_y, xloc.bar_index,
extend.none, bullish, style, 2) : na, line.delete(lineTp1Rl[1])
lineTp2RL = levels and lvlLines ? line.new(bar_index - (trigger == 0 ?
countBull : countBear), tp2RL_y, bar_index + 1, tp2RL_y, xloc.bar_index,
extend.none, bullish, style, 2) : na, line.delete(lineTp2RL[1])
lineTp3RL = levels and lvlLines ? line.new(bar_index - (trigger == 0 ?
countBull : countBear), tp3RL_y, bar_index + 1, tp3RL_y, xloc.bar_index,
extend.none, bullish, style, 2) : na, line.delete(lineTp3RL[1])
// # ============================[ICT KILL ZONES]============================ #
import boitoki/AwesomeColor/4 as ac
import boitoki/Utilities/3 as util
// London Silver Bullet
L1 = time ("1", '0300-0301:1234567')
LL = time ("1", '0330-0331:1234567')
L2 = time ("1", '0400-0401:1234567')

if LoSB and L1 == L1 and i_show


line.new(L1, high, L1, low, xloc.bar_time, extend.both, LSBcolor, LST, 1)

if LoSB and L2 == L2 and i_show


line.new(L2, high, L2, low, xloc.bar_time, extend.both, LSBcolor, LST, 1)

plotchar(LoSB ? LL and i_show : false, text= "3-4 am", char = " ", textcolor =
LSBcolor, location=location.top, offset=0)
// 10-11 am Silver Bullet
N1 = time ("1", '1000-1001:1234567')
NN = time ("1", '1030-1031:1234567')
N2 = time ("1", '1100-1101:1234567')

if NYSB and N1 == N1 and i_show


line.new(N1, high, N1, low, xloc.bar_time, extend.both, LSBcolor, LST, 1)

if NYSB and N2 == N2 and i_show


line.new(N2, high, N2, low, xloc.bar_time, extend.both, LSBcolor, LST, 1)

plotchar(NYSB ? NN and i_show : false, text= "10-11 am", char = " ", textcolor =
LSBcolor, location=location.top, offset=0)
// 2-3 pm Silver Bullet
P1 = time ("1", '1400-1401:1234567')
PSB = time ("1", '1430-1431:1234567')
P2 = time ("1", '1500-1501:1234567')

if NYPM and P1 == P1 and i_show


line.new(P1, high, P1, low, xloc.bar_time, extend.both, LSBcolor, LST, 1)

if NYPM and P2 == P2 and i_show


line.new(P2, high, P2, low, xloc.bar_time, extend.both, LSBcolor, LST, 1)

plotchar(NYPM ? PSB and i_show : false, text= "2-3 pm", char = " ", textcolor =
LSBcolor, location=location.top, offset=0)
// Definded
max_bars = 500

option_yes = 'Yes'
option_no = '× No'
option_extend1 = 'Yes'
option_hide = '× Hide'

fmt_price = '{0,number,#.#####}'
fmt_pips = '{0,number,#.#}'

icon_separator = ' • '

color_none = color.new(color.black, 100)


// Functions
f_get_time_by_bar(bar_count) => timeframe.multiplier * bar_count * 60 * 1000

f_get_period (_session, _start, _lookback) =>


result = math.max(_start, 1)
for i = result to _lookback
if na(_session[i+1]) and _session[i]
result := i+1
break
result
f_get_started (_session) => na(_session[1]) and _session

f_get_ended (_session) => na(_session) and _session[1]

f_message_limit_bars (_v) => '⚠️ This box\'s right position exceeds 500 bars(' +
str.tostring(_v) + '). This box is not displayed correctly.'

f_set_line_x1 (_line, _x) =>


if (line.get_x1(_line) != _x)
line.set_x1(_line, _x)

f_set_line_x2 (_line, _x) =>


if (line.get_x2(_line) != _x)
line.set_x2(_line, _x)

f_set_box_right (_box, _x) =>


if box.get_right(_box) != _x
box.set_right(_box, _x)
// OSC Mod
i_osc = bool(false)
i_osc_min = float(0)
i_osc_max = float(100)
// Drawing Labels
f_render_label (_show, _session, _is_started, _color, _top, _bottom, _text,
_labels) =>
var label my_label = na
var int start_time = na

v_position_y = (i_label_position_y == 'top') ? _top : _bottom


v_label = array.new_string()
v_chg = _top - _bottom

if _is_started
start_time := time

if i_label_format_name and not na(_text)


array.push(v_label, _text)

if i_label_format_day
array.push(v_label, util.get_day(dayofweek(start_time, i_tz)))

if i_label_format_price
array.push(v_label, str.format(fmt_price, v_chg))

if i_label_format_pips
array.push(v_label, str.format(fmt_pips, util.toPips(v_chg)) + ' pips')

if _show
if _is_started
my_label := label.new(bar_index, v_position_y, array.join(v_label,
icon_separator), textcolor=_color, color=color_none, size=i_label_size,
style=i_label_position)

array.push(_labels, my_label)

util.clear_labels(_labels, i_history_period)
else if _session
label.set_y(my_label, v_position_y)
label.set_text(my_label, array.join(v_label, icon_separator))
// Rendering Limit Massage
f_render_limitmessage (_show, _session, _is_started, _is_ended, _x, _y, _rightbars)
=>
var label my_note = na

if _show
if _is_started
if _rightbars > max_bars
my_note := label.new(_x, _y, f_message_limit_bars(_rightbars),
style=label.style_label_upper_left, color=color.yellow, textalign=text.align_left,
yloc=yloc.price)

else if _session
if _rightbars > max_bars
label.set_y(my_note, _y)
label.set_text(my_note, f_message_limit_bars(_rightbars))
else
label.delete(my_note)

else if _is_ended
label.delete(my_note)
true
// Rendering session
f_render_sessionrange (_show, _session, _is_started, _is_ended, _color, _top,
_bottom, _x1, _x2, _is_extend, _lines) =>
var line above_line = na
var line below_line = na

if _show
if _is_started
above_line := line.new(_x1, _top, _x2, _top, width=i_sess_border_width,
style=i_sess_border_style, color=_color)
below_line := line.new(_x1, _bottom, _x2, _bottom,
width=i_sess_border_width, style=i_sess_border_style, color=_color)
linefill.new(above_line, below_line, color.new(_color,
i_sess_bgopacity))

array.push(_lines, above_line)
array.push(_lines, below_line)

util.clear_lines(_lines, i_history_period * 2)

if _is_extend
line.set_extend(above_line, extend.right)
line.set_extend(below_line, extend.right)

else if _session
line.set_y1(above_line, _top)
line.set_y2(above_line, _top)
line.set_x2(above_line, _x2)

line.set_y1(below_line, _bottom)
line.set_y2(below_line, _bottom)
line.set_x2(below_line, _x2)
true
else if _is_ended

true
true
// Rendering session box
f_render_session (_show, _session, _is_started, _is_ended, _color, _top, _bottom,
_x1, _x2, _is_extend, _boxes) =>
var box my_box = na

if _show
if _is_started
my_box := box.new(_x1, _top, _x2, _bottom, _color, i_sess_border_width,
i_sess_border_style, bgcolor=color.new(_color, i_sess_bgopacity))
array.push(_boxes, my_box)

util.clear_boxes(_boxes, i_history_period)

if _is_extend
box.set_extend(my_box, extend.right)

else if _session
box.set_top(my_box, _top)
box.set_bottom(my_box, _bottom)
f_set_box_right(my_box, _x2)

else if _is_ended
box.set_right(my_box, bar_index)

my_box
// Drawing market
f_render_main (_show, _session, _is_started, _is_ended, _color, _top, _bottom) =>
var box my_box = na
var label my_note = na
var x1 = 0
var x2 = 0
var session_open = 0.0
var session_high = 0.0
var session_low = 0.0

x0_1 = ta.valuewhen(na(_session[1]) and _session, bar_index, 1)


x0_2 = ta.valuewhen(na(_session) and _session[1], bar_index, 0)
x0_d = math.abs(x0_2 - x0_1)
limit_bars = max_bars
rightbars = x0_d

if _show
if _is_started
x1 := bar_index
x2 := bar_index + (math.min(x0_d, limit_bars))

session_open := open
session_high := _top
session_low := _bottom

else if _session
true_x2 = x1 + x0_d
rightbars := true_x2 - bar_index
limit_bars := bar_index + max_bars
x2 := math.min(true_x2, limit_bars)

session_high := _top
session_low := _bottom

else if _is_ended
session_open := na

[x1, x2, session_open, session_high, session_low, rightbars]


// Drawing
draw (_show, _session, _color, _label, _extend, _show_op, _lookback,
_boxes_session, _lines_session, _boxes_op, _labels) =>
max = f_get_period(_session, 1, _lookback)
top = ta.highest(high, max)
bottom = ta.lowest(low, max)

if i_osc
top := i_osc_max
bottom := i_osc_min

is_started = f_get_started(_session)
is_ended = f_get_ended(_session)
is_extend = _extend != option_no

[x1, x2, _open, _high, _low, _rightbars] = f_render_main(_show, _session,


is_started, is_ended, _color, top, bottom)

if i_sess_box_style == 'Box'
f_render_session(_show, _session, is_started, is_ended, _color, top,
bottom, x1, x2, is_extend, _boxes_session)

if i_sess_box_style == 'Sandwich'
f_render_sessionrange(_show, _session, is_started, is_ended, _color, top,
bottom, x1, x2, is_extend, _lines_session)

if i_label_show
f_render_label(_show, _session, is_started, _color, top, bottom, _label,
_labels)

f_render_limitmessage(_show, _session, is_started, is_ended, x1, bottom,


_rightbars)

[_session, _open, _high, _low]


// Calculation
string tz1 = (i_tz == option_no or i_tz == '') ? na : i_tz
int sess1 = time(timeframe.period, i_sess1, tz1)
int sess2 = time(timeframe.period, i_sess2, tz1)
int sess3 = time(timeframe.period, i_sess3, tz1)
int sess4 = time(timeframe.period, i_sess4, tz1)
int sess5 = time(timeframe.period, i_sess5, tz1)
// Ploting
var sess1_box = array.new<box>()
var sess2_box = array.new<box>()
var sess3_box = array.new<box>()
var sess4_box = array.new<box>()
var sess5_box = array.new<box>()
var sess1_line = array.new<line>()
var sess2_line = array.new<line>()
var sess3_line = array.new<line>()
var sess4_line = array.new<line>()
var sess5_line = array.new<line>()
var sess1_op = array.new<box>()
var sess2_op = array.new<box>()
var sess3_op = array.new<box>()
var sess4_op = array.new<box>()
var sess5_op = array.new<box>()
var sess1_labels = array.new<label>()
var sess2_labels = array.new<label>()
var sess3_labels = array.new<label>()
var sess4_labels = array.new<label>()
var sess5_labels = array.new<label>()

[is_sess1, sess1_open, sess1_high, sess1_low] = draw(i_show_sess1, sess1,


i_sess1_color, i_sess1Text, i_sess1_extend, i_sess1_op, i_lookback, sess1_box,
sess1_line, sess1_op, sess1_labels)
[is_sess2, sess2_open, sess2_high, sess2_low] = draw(i_show_sess2, sess2,
i_sess2_color, i_sess2Text, i_sess2_extend, i_sess2_op, i_lookback, sess2_box,
sess2_line, sess2_op, sess2_labels)
[is_sess3, sess3_open, sess3_high, sess3_low] = draw(i_show_sess3, sess3,
i_sess3_color, i_sess3Text, i_sess3_extend, i_sess3_op, i_lookback, sess3_box,
sess3_line, sess3_op, sess3_labels)
[is_sess4, sess4_open, sess4_high, sess4_low] = draw(i_show_sess4, sess4,
i_sess4_color, i_sess4Text, i_sess4_extend, i_sess4_op, i_lookback, sess4_box,
sess4_line, sess4_op, sess4_labels)
[is_sess5, sess5_open, sess5_high, sess5_low] = draw(i_show_sess5, sess5,
i_sess5_color, i_sess5Text, i_sess5_extend, i_sess5_op, i_lookback, sess5_box,
sess5_line, sess5_op, sess5_labels)

You might also like