TR
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Original pattern formation by plasmapug, rise retrace continuation to the upside by infernix and peshocore
// Please note while the code is open source and you are free to use it however you like - the 'TR' name is not - ie if you produce derivatives of this 
// source code you to name those scripts using "TR", "Pattern Watchers" or any other name that relates to Traders Reality in any way.


 
//Session	            Local Time	                   DST OFF (UCT+0)	DST ON (UTC+0)	DST ON 2022	  DST OFF 2022	DST ON 2023	  DST OFF 2023	  DST ON 2024	DST OFF 2024
//London	            8am-430pm	                   0800-1630	    0700-1530	    March, 27	  October, 30	March, 26	  October, 29	  March, 31	    October, 27
//NewYork	            930am-4pm	                   1430-2100	    1330-2000	    March, 13	  November, 6	March, 12	  November, 5	  March, 10	    November, 3
//Tokyo	                9am-3pm	                       0000-0600	    0000-0600	    N/A	          N/A	        N/A	          N/A	          N/A	        N/A
//HongKong	            930am-4pm	                   0130-0800	    0130-0800	    N/A	          N/A	        N/A	          N/A	          N/A	        N/A
//Sydney (NZX+ASX)	    NZX start 10am, ASX end 4pm	   2200-0600	    2100-0500	    October, 2	  April, 3	    October, 1	  April, 2	      October, 6	April, 7
//EU Brinx	            730am-830am	                   0730-0830	    0630-0730	    March, 27	  October, 30	March, 26	  October, 29	  March, 31	    October, 27
//US Brinx	            900am-10am	                   1400-1500	    1300-1400	    March, 13	  November, 6	March, 12	  November, 5	  March, 10	    November, 3
//Frankfurt	            800am-530pm	                   0700-1630	    0600-1530	    March, 27	  October, 30	March, 26	  October, 29	  March, 31	    October, 27
 

//@version=5
indicator('TR', overlay=true, max_bars_back=300)
// ----------------------------


// Config
adr_offset_input = input.int(group='Label offsets', title='ADR', defval=25, inline='labeloffset')
pivot_offset_input = input.int(group='Label offsets', title='Pivot', defval=-5, inline='labeloffset')
label_offset_input = input.int(group='Label offsets', title='MA/HiLo', defval=5, inline='labeloffset')
showEmas = input.bool(group='EMAs', title='Show EMAs?', defval=true, inline='showemas')
labelEmas = input.bool(group='EMAs', title='EMA Labels?', defval=false, inline='showemas')
oneEmaColor = input.color(group='EMAs', title='EMA Color: 5', defval=color.rgb(254, 234, 74, 0), inline='emacolors')
twoEmaColor = input.color(group='EMAs', title='13', defval=color.rgb(253, 84, 87, 0), inline='emacolors')
threeEmaColor = input.color(group='EMAs', title='50', defval=color.rgb(31, 188, 211, 0), inline='emacolors')
fourEmaColor = input.color(group='EMAs', title='200', defval=color.rgb(255, 255, 255, 0), inline='emacolors')
fiveEmaColor = input.color(group='EMAs', title='800', defval=color.rgb(50, 34, 144, 0), inline='emacolors')
EmaCloudColor = input.color(group='EMAs', title='EMA Cloud', defval=color.rgb(155, 47, 174, 60), inline='emacloud')
EmaCloudBorderColor = input.color(group='EMAs', title='Border', defval=color.rgb(18, 137, 123, 100), inline='emacloud')

//Daily Pivot Points
showLevelOnePivotPoints = input.bool(group='Pivot Points', title='Show Level: 1 R/S?', defval=false, inline='pivotlevels')
showLevelTwoPivotPoints = input.bool(group='Pivot Points', title='2 R/S?', defval=false, inline='pivotlevels')
showLevelThreePivotPoints = input.bool(group='Pivot Points', title=' 3 R/S?', defval=false, inline='pivotlevels')
showPivotLabels = input.bool(group='Pivot Points', title='Show labels?', defval=true, inline='pivotlevels')
string rsStyleX = input.string(group='Pivot Points', defval='Dashed', title='R/S Levels Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='pivotcolorsRS')
rsStyle = rsStyleX == 'Dotted' ? line.style_dotted : (rsStyleX == 'Dashed' ? line.style_dashed : (rsStyleX == 'Solid' ? line.style_solid : line.style_dashed))

activeM = input.bool(group='Pivot Points', title='Show M levels?', defval=true, inline='mlevels')
showMLabels = input.bool(group='Pivot Points', title='Labels?', defval=true, inline='mlevels')
extendPivots = input.bool(group='Pivot Points', title='Extend lines in both directions?', defval=false)
pivotColor = input.color(group='Pivot Points', title='Colors: Pivot Point', defval=color.rgb(254, 234, 78, 50), inline='pivotcolors')
mColor = input.color(group='Pivot Points', title='M Levels', defval=color.rgb(255, 255, 255, 50), inline='pivotcolors')
string mStyleX = input.string(group='Pivot Points', defval='Dashed', title='M Levels Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='pivotcolors')
mStyle = mStyleX == 'Dotted' ? line.style_dotted : (mStyleX == 'Dashed' ? line.style_dashed : (mStyleX == 'Solid' ? line.style_solid : line.style_dashed))

showDayHighLow = input.bool(group="Yesterday's and Last Week's High/low", title='Show Hi/Lo: Daily?', defval=true, inline='highlow')
showWeekHighLow = input.bool(group="Yesterday's and Last Week's High/low", title='Weekly?', defval=true, inline='highlow')
showDayHighLowLabels = input.bool(group="Yesterday's and Last Week's High/low", title='Show labels?', defval=true, inline='highlow')

showADR = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Show ADR?', defval=true, inline='adr')
showADRLabels = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Labels?', defval=true, inline='adr')
showADRRange = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Range label?', defval=false, inline='adr')
adrColor = input.color(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='ADR Color', defval=color.new(color.silver, 50), inline='adr1')
string adrStyleX = input.string(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', defval='Dotted', title='ADR Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='adr1')
adrStyle = adrStyleX == 'Dotted' ? line.style_dotted : (adrStyleX == 'Dashed' ? line.style_dashed : (adrStyleX == 'Solid' ? line.style_solid : line.style_dotted))


showAWR = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Show AWR?', defval=false, inline='awr')
showAWRLabels = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Labels?', defval=false, inline='awr')
showAWRRange = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Range label?', defval=false, inline='awr')
awrColor = input.color(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='AWR Color', defval=color.new(color.orange, 50), inline='awr1')
string awrStyleX = input.string(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', defval='Dotted', title='AWR Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='awr1')
awrStyle = awrStyleX == 'Dotted' ? line.style_dotted : (awrStyleX == 'Dashed' ? line.style_dashed : (awrStyleX == 'Solid' ? line.style_solid : line.style_dotted))


showAMR = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Show AMR?', defval=false, inline='amr')
showAMRLabels = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Labels?', defval=false, inline='amr')
showAMRRange = input.bool(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='Range label?', defval=false, inline='amr')
amrColor = input.color(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', title='AMR Color', defval=color.new(color.red, 50), inline='amr1')
string amrStyleX = input.string(group='ADR/AWR/AMR(Average Daily/Weekly/Monthly Range)', defval='Dotted', title='AMR Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='amr1')
amrStyle = amrStyleX == 'Dotted' ? line.style_dotted : (amrStyleX == 'Dashed' ? line.style_dashed : (amrStyleX == 'Solid' ? line.style_solid : line.style_dotted))

showAdrTable = input.bool(group='ADR/ADRx3/AWR/AMR Table', title='Show ADR Table : ', inline='adrt', defval=true)
choiceAdrTable = input.string(group='ADR/ADRx3/AWR/AMR Table', title='ADR Table postion', inline='adrt', defval='top_right', options=['top_right', 'top_left', 'top_center', 'bottom_right', 'bottom_left', 'bottom_center'])
adrTableBgColor = input.color(group='ADR/ADRx3/AWR/AMR Table', title='ADR Table: Background Color', inline='adrtc', defval=color.rgb(93, 96, 107, 70))
adrTableTxtColor = input.color(group='ADR/ADRx3/AWR/AMR Table', title='Text Color', inline='adrtc', defval=color.rgb(31, 188, 211, 0))


/// market boxes and daily open only on intraday
bool show = timeframe.isminutes and timeframe.multiplier <= 240 and timeframe.multiplier >= 1
time_now_exchange = timestamp(year, month, dayofmonth, hour, minute, second)
bool show_dly = timeframe.isminutes  //and timeframe.multiplier < 240
bool show_rectangle9 = input.bool(group='Daily Open', defval=true, title='Show: line ?', inline='dopenconf') and show_dly
bool show_label9 = input.bool(group='Daily Open', defval=true, title='Label?', inline='dopenconf') and show_rectangle9 and show_dly
bool showallDly = input.bool(group='Daily Open', defval=false, title='Show historical daily opens?', inline='dopenconf')
color sess9col = input.color(group='Daily Open', title='Daily Open Color', defval=color.rgb(254, 234, 78, 0), inline='dopenconf1')
//color sess9colLabel = input(group="Daily Open", title="", type=input.color, defval=color.rgb(254,234,78,0), inline="dopenconf1")

bool overridesym = input.bool(group='PVSRA', title='Override chart symbol?', defval=false, inline='pvsra')
string pvsra_sym = input.symbol(group='PVSRA', title='', defval='INDEX:BTCUSD', tooltip='You can use INDEX:BTCUSD or you can combine multiple feeds, for example \'(BINANCE:BTCUSDT+COINBASE:BTCUSD)\'. Note that adding too many will slow things down.', inline='pvsra')

string rectStyle = input.string(group='Market sessions', defval='Dashed', title='Line style of Market Session hi/lo line', options=['Dashed', 'Solid'])
sessLineStyle = line.style_dashed
bool show_markets = input.bool(true, group='Market sessions', title='Show Market Sessions?', tooltip='Turn on or off all market sessions') and show
bool show_markets_weekends = input.bool(false, group='Market sessions', title='Show Market Session on Weekends?', tooltip='Turn on or off market sessions in the weekends. Note do not turn this on for exchanges that dont have weekend data like OANDA') and show
string weekend_sessions = ':1234567'
string no_weekend_sessions = ':23456'

bool show_rectangle1 = input.bool(group='Market session: London (0800-1630 UTC+0)', defval=true, title='Show: session?', inline='session1conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label1 = input.bool(group='Market session: London (0800-1630 UTC+0)', defval=true, title='Label?', inline='session1conf') and show_rectangle1 and show_markets
bool show_or1 = input.bool(group='Market session: London (0800-1630 UTC+0)', defval=true, title='Opening Range?', inline='session1conf', tooltip='This controls the shaded area for the session') and show_rectangle1 and show_markets
string sess1Label = input.string(group='Market session: London (0800-1630 UTC+0)', defval='London', title='Name:', inline='session1style')
color sess1col = input.color(group='Market session: London (0800-1630 UTC+0)', title='Color: Box', defval=color.rgb(120, 123, 134, 75), inline='session1style')
color sess1colLabel = input.color(group='Market session: London (0800-1630 UTC+0)', title='Label', defval=color.rgb(120, 123, 134, 0), inline='session1style')
string sess1TimeX = '0800-1630'//input.session(group='Market session 1', defval='0800-1630', title='Time (UTC+0):', inline='session1style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst1_startTime = input.time(group='Market session 1', defval=timestamp('27 Mar 2022 02:00 +0000'), title='DST Start', inline='ms11', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst1_endTime = input.time(group='Market session 1', defval=timestamp('30 Oct 2022 03:00 +0000'), title='DST End ', inline='ms12', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess1Time = show_markets_weekends ? sess1TimeX + weekend_sessions : sess1TimeX + no_weekend_sessions
//sess_dst_on1 = time_now_exchange >= dst1_startTime and time_now_exchange <= dst1_endTime
bool sess_dst_on1 = input.bool(group='Market session: London (0800-1630 UTC+0)', defval=false, title='DST On?', inline='session1dst', tooltip='When checked (signifies that London is in DST) and this effectively makes the London session be 0700-1530 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')


bool show_rectangle2 = input.bool(group='Market session: New York (1430-2100 UTC+0)', defval=true, title='Show: session?', inline='session2conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label2 = input.bool(group='Market session: New York (1430-2100 UTC+0)', defval=true, title='Label?', inline='session2conf') and show_rectangle2 and show_markets
bool show_or2 = input.bool(group='Market session: New York (1430-2100 UTC+0)', defval=true, title='Opening Range?', inline='session2conf', tooltip='This controls the shaded area for the session') and show_rectangle2 and show_markets
string sess2Label = input.string(group='Market session: New York (1430-2100 UTC+0)', defval='NewYork', title='Name:', inline='session2style')
color sess2col = input.color(group='Market session: New York (1430-2100 UTC+0)', title='Color: Box', defval=color.rgb(251, 86, 91, 75), inline='session2style')
color sess2colLabel = input.color(group='Market session: New York (1430-2100 UTC+0)', title='Label', defval=color.rgb(253, 84, 87, 25), inline='session2style')
string sess2TimeX = '1430-2100'//input.session(group='Market session 2', defval='1430-2100', title='Time (UTC+0):', inline='session2style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst2_startTime = input.time(group='Market session 2', defval=timestamp('13 Mar 2022 02:00 +0000'), title='DST Start', inline='ms21', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst2_endTime = input.time(group='Market session 2', defval=timestamp('06 Nov 2022 03:00 +0000'), title='DST End ', inline='ms22', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess2Time = show_markets_weekends ? sess2TimeX + weekend_sessions : sess2TimeX  + no_weekend_sessions
//sess_dst_on2 = time_now_exchange >= dst2_startTime and time_now_exchange <= dst2_endTime
bool sess_dst_on2 = input.bool(group='Market session: New York (1430-2100 UTC+0)', defval=false, title='DST On?', inline='session2dst', tooltip='When checked (signifies that New York is in DST) and this effectively makes the New York session be 1330-2000 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')


bool show_rectangle3 = input.bool(group='Market session: Tokio (0000-0600 UTC+0)', defval=true, title='Show: session?', inline='session3conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label3 = input.bool(group='Market session: Tokio (0000-0600 UTC+0)', defval=true, title='Label?', inline='session3conf') and show_rectangle3 and show_markets
bool show_or3 = input.bool(group='Market session: Tokio (0000-0600 UTC+0)', defval=true, title='Opening Range?', inline='session3conf', tooltip='This controls the shaded area for the session') and show_rectangle3 and show_markets
string sess3Label = input.string(group='Market session: Tokio (0000-0600 UTC+0)', defval='Tokyo', title='Name:', inline='session3style')
color sess3col = input.color(group='Market session: Tokio (0000-0600 UTC+0)', title='Color: Box', defval=color.rgb(80, 174, 85, 75), inline='session3style')
color sess3colLabel = input.color(group='Market session: Tokio (0000-0600 UTC+0)', title='Label', defval=color.rgb(80, 174, 85, 25), inline='session3style')
string sess3TimeX = '0000-0600'//input.session(group='Market session 3', defval='0000-0600', title='Time (UTC+0):', inline='session3style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst3_startTime = input.time(group='Market session 3', defval=timestamp('31 Dec 2019 00:00 +0000'), title='DST Start', inline='ms31', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst3_endTime = input.time(group='Market session 3', defval=timestamp('31 Dec 2019 00:00 +0000'), title='DST End ', inline='ms32', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for the past year. Note each year the day for starting and ending DST is different.')
sess3Time = show_markets_weekends ? sess3TimeX + weekend_sessions : sess3TimeX + no_weekend_sessions
//sess_dst_on3 = time_now_exchange >= dst3_startTime and time_now_exchange <= dst3_endTime
bool sess_dst_on3 = false//input.bool(group='Market session: Tokio (0000-0600 UTC+0)', defval=false, title='DST On?', inline='session3dst', tooltip='Tokio does not observe DST so do not check this checkbox. When checked (signifies that Tokio is in DST) and this effectively makes the Tokio session be 2300-0500 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')



bool show_rectangle4 = input.bool(group='Market session: Hong Kong (0130-0800 UTC+0)', defval=true, title='Show: session?', inline='session4conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label4 = input.bool(group='Market session: Hong Kong (0130-0800 UTC+0)', defval=true, title='Label?', inline='session4conf') and show_rectangle4 and show_markets
bool show_or4 = input.bool(group='Market session: Hong Kong (0130-0800 UTC+0)', defval=true, title='Opening Range?', inline='session4conf', tooltip='This controls the shaded area for the session') and show_rectangle4 and show_markets
string sess4Label = input.string(group='Market session: Hong Kong (0130-0800 UTC+0)', defval='HongKong', title='Name:', inline='session4style')
color sess4col = input.color(group='Market session: Hong Kong (0130-0800 UTC+0)', title='Color: Box', defval=color.rgb(128, 127, 23, 75), inline='session4style')
color sess4colLabel = input.color(group='Market session: Hong Kong (0130-0800 UTC+0)', title='Label', defval=color.rgb(128, 127, 23, 25), inline='session4style')
string sess4TimeX = '0130-0800'//input.session(group='Market session 4', defval='0130-0800', title='Time (UTC+0):', inline='session4style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst4_startTime = input.time(group='Market session 4', defval=timestamp('31 Dec 2019 00:00 +0000'), title='DST Start', inline='ms41', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst4_endTime = input.time(group='Market session 4', defval=timestamp('31 Dec 2019 00:00 +0000'), title='DST End ', inline='ms42', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess4Time = show_markets_weekends ? sess4TimeX + weekend_sessions : sess4TimeX + no_weekend_sessions
//sess_dst_on4 = time_now_exchange >= dst4_startTime and time_now_exchange <= dst4_endTime
bool sess_dst_on4 = false//input.bool(group='Market session: Hong Kong (0130-0800 UTC+0)', defval=false, title='DST On?', inline='session4dst', tooltip='Hong Kong does not observe DST so do not check this checkbox. When checked (signifies that Hong Kong is in DST) and this effectively makes the Hong Kong session be 0030-0700 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')

bool show_rectangle5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', defval=true, title='Show: session?', inline='session5conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', defval=true, title='Label?', inline='session5conf') and show_rectangle5 and show_markets
bool show_or5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', defval=true, title='Opening Range?', inline='session5conf', tooltip='This controls the shaded area for the session') and show_rectangle5 and show_markets
string sess5Label = input.string(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', defval='Sydney', title='Name:', inline='session5style')
color sess5col = input.color(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', title='Color: Box', defval=color.rgb(37, 228, 123, 75), inline='session5style')
color sess5colLabel = input.color(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', title='Label', defval=color.rgb(37, 228, 123, 25), inline='session5style')
string sess5TimeX = '2200-0600'//input.session(group='Market session 5', defval='2200-0600', title='Time (UTC+0):', inline='session5style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst5_startTime = input.time(group='Market session 5', defval=timestamp('02 Oct 2021 07:01 +0000'), title='DST Start', inline='ms51', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst5_endTime = input.time(group='Market session 5', defval=timestamp('03 Apr 2022 08:01 +0000'), title='DST End ', inline='ms52', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess5Time = show_markets_weekends ? sess5TimeX + weekend_sessions : sess5TimeX + no_weekend_sessions
//sess_dst_on5 = time_now_exchange >= dst5_startTime and time_now_exchange <= dst5_endTime
bool sess_dst_on5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', defval=true, title='DST On?', inline='session5dst', tooltip='When checked (signifies that Sydney is in DST) and this effectively makes the Sydney session be 2100-0500 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')

bool show_rectangle6 = input.bool(group='Market session: EU Brinks (0730-0830 UTC+0)', defval=true, title='Show: session?', inline='session6conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label6 = input.bool(group='Market session: EU Brinks (0730-0830 UTC+0)', defval=true, title='Label?', inline='session6conf') and show_rectangle6 and show_markets
bool show_or6 = input.bool(group='Market session: EU Brinks (0730-0830 UTC+0)', defval=true, title='Opening Range?', inline='session6conf', tooltip='This controls the shaded area for the session') and show_rectangle6 and show_markets
string sess6Label = input.string(group='Market session: EU Brinks (0730-0830 UTC+0)', defval='EU Brinks', title='Name:', inline='session6style')
color sess6col = input.color(group='Market session: EU Brinks (0730-0830 UTC+0)', title='Color: Box', defval=color.rgb(255, 255, 255, 65), inline='session6style')
color sess6colLabel = input.color(group='Market session: EU Brinks (0730-0830 UTC+0)', title='Label', defval=color.rgb(255, 255, 255, 25), inline='session6style')
string sess6TimeX = '0730-0830'//input.session(group='Market session 6', defval='0730-0830', title='Time (UTC+0):', inline='session6style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst6_startTime = input.time(group='Market session 6', defval=timestamp('27 Mar 2022 02:00 +0000'), title='DST Start', inline='ms61', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst6_endTime = input.time(group='Market session 6', defval=timestamp('30 Oct 2022 03:00 +0000'), title='DST End ', inline='ms62', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess6Time = show_markets_weekends ? sess6TimeX + weekend_sessions : sess6TimeX + no_weekend_sessions
//sess_dst_on6 = time_now_exchange >= dst6_startTime and time_now_exchange <= dst6_endTime
bool sess_dst_on6 = input.bool(group='Market session: EU Brinks (0730-0830 UTC+0)', defval=false, title='DST On?', inline='session6dst', tooltip='When checked (signifies that EU Brinks - London is in DST) and this effectively makes the EU Brinks session be 0630-0730 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')

bool show_rectangle7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0)', defval=true, title='Show: session?', inline='session7conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0)', defval=true, title='Label?', inline='session7conf') and show_rectangle7 and show_markets
bool show_or7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0)', defval=true, title='Opening Range?', inline='session7conf', tooltip='This controls the shaded area for the session') and show_rectangle7 and show_markets
string sess7Label = input.string(group='Market session: US Brinks (1400-1500 UTC+0)', defval='US Brinks', title='Name:', inline='session7style')
color sess7col = input.color(group='Market session: US Brinks (1400-1500 UTC+0)', title='Color: Box', defval=color.rgb(255, 255, 255, 65), inline='session7style')
color sess7colLabel = input.color(group='Market session: US Brinks (1400-1500 UTC+0)', title='Label', defval=color.rgb(255, 255, 255, 25), inline='session7style')
string sess7TimeX = '1400-1500'//input.session(group='Market session 7', defval='1400-1500', title='Time (UTC+0):', inline='session7style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst7_startTime = input.time(group='Market session 7', defval=timestamp('13 Mar 2022 02:00 +0000'), title='DST Start', inline='ms71', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst7_endTime = input.time(group='Market session 7', defval=timestamp('06 Nov 2022 03:00 +0000'), title='DST End ', inline='ms72', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess7Time = show_markets_weekends ? sess7TimeX + weekend_sessions : sess7TimeX + no_weekend_sessions
//sess_dst_on7 = time_now_exchange >= dst7_startTime and time_now_exchange <= dst7_endTime
bool sess_dst_on7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0)', defval=false, title='DST On?', inline='session7dst', tooltip='When checked (signifies that US Brinks - New York is in DST) and this effectively makes the US Brinks session be 1300-1400 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')

bool show_rectangle8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0)', defval=false, title='Show: session?', inline='session8conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0)', defval=true, title='Label?', inline='session8conf') and show_rectangle8 and show_markets
bool show_or8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0)', defval=true, title='Opening Range?', inline='session8conf', tooltip='This controls the shaded area for the session') and show_rectangle8 and show_markets
string sess8Label = input.string(group='Market session: Frankfurt (0700-1630 UTC+0)', defval='Frankfurt', title='Name:', inline='session8style')
color sess8col = input.color(group='Market session: Frankfurt (0700-1630 UTC+0)', title='Color: Box', defval=color.rgb(253, 152, 39, 75), inline='session8style')
color sess8colLabel = input.color(group='Market session: Frankfurt (0700-1630 UTC+0)', title='Label', defval=color.rgb(253, 152, 39, 25), inline='session8style')
string sess8TimeX = '0700-1630'//input.session(group='Market session 8', defval='0800-1630', title='Time (UTC+0):', inline='session8style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST')
//int dst8_startTime = input.time(group='Market session 8', defval=timestamp('27 Mar 2022 02:00 +0000'), title='DST Start', inline='ms81', tooltip='For this session when does the DST start in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
//int dst8_endTime = input.time(group='Market session 8', defval=timestamp('30 Oct 2022 03:00 +0000'), title='DST End ', inline='ms82', tooltip='For this session when does the DST end in that Country? If country does not observe DST set to midnight on Dec 31 for a past year. Note each year the day for starting and ending DST is different.')
sess8Time = show_markets_weekends ? sess8TimeX + weekend_sessions : sess8TimeX + no_weekend_sessions
//sess_dst_on8 = time_now_exchange >= dst8_startTime and time_now_exchange <= dst8_endTime
bool sess_dst_on8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0)', defval=false, title='DST On?', inline='session8dst', tooltip='When checked (signifies that Frankfurt is in DST) and this effectively makes the Frankfurt session be 0600-1530 UTC+0 due to DST. Each country changes daylight savings time (DST) at different times. Is this country currently in DST? If so this check box should be checked, otherwise unchecked. For countries that dont observe DST leave unchecked. Note countries that are in the southern hemisphere that observe DST generaly are in DST when countries in the northern hemisphere are not in DST.')


bool showPsy = timeframe.isminutes and (timeframe.multiplier == 60 or timeframe.multiplier == 30 or timeframe.multiplier == 15 or timeframe.multiplier == 5 or timeframe.multiplier == 3 or timeframe.multiplier == 1)   
bool show_psylevels = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=true, title='Show: Levels?', inline='psyconf') and showPsy
bool show_psylabel = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=true, title='Labels?', inline='psyconf', tooltip="The Psy High/Low will only show on these timeframes: 1h/30min/15min/5min/3min/1min. It is disabled on all others. This is because the calculation requires a candle to start at the correct time for Sydney but in other timeframes the data does not have values at the designated time for the Sydney session.") and show_psylevels
bool showallPsy = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=false, title='Show historical psy levels?', inline='psyconf')
color psycolH = input.color(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', title='Psy Hi Color', defval=color.new(color.orange, 30), inline='psyconf1')
color psycolL = input.color(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', title='Psy Low Color', defval=color.new(color.orange, 30), inline='psyconf1')
string psyType = input.string(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval='crypto', title='Psy calc type', options=['crypto', 'forex'], inline='psyconf12', tooltip="Are you looking at Crypto or Forex? Crypto calculations start with the Sydney session on Saturday night. Forex calculations start with the Tokyo session on Monday morning. Note some exchanges like Oanda do not have sessions on the weekends so you might be forced to select Forex for exchanges like Oanda even when looking at symbols like BITCOIN on Oanda.")
//int dstPsy_startTime = input.time(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=timestamp('02 Oct 2021 02:00 +0000'), title='DST Start (crypto only)', inline='psyconf13', tooltip='Sydney observes DST. Sydney DST start is generally the first Sunday of October. BUT since Sydney is in the southern hemishpere this setting should basically be set to the first Sunday of October for the previous year. This setting thus must be changed once a year when Sydney is out of DST. Note for different years the first Sunday of October will have a different date each year. This setting has no effect when forex is selected for the psy calc type - this is because Tokio does not observe DST at all.')
//int dstPsy_endTime = input.time(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=timestamp('03 Apr 2022 03:00 +0000'), title='DST End (crypto only)', inline='psyconf14', tooltip='Sydney observes DST. Sydney DST end is generally the first Sunday of April. BUT since Sydney is in the southern hemishpere this setting should basically be set to the first Sunday of April for the current year. This setting thus must be changed once a year when Sydney is out of DST. Note for different years the first Sunday of April will have a different date each year. This setting has no effect when forex is selected for the psy calc type - this is because Tokio does not observe DST at all.')
var string cryptoCalcSession = '2200-0600:1'
var string forexCalcSession = '0000-0800:2'
//sess_dst_onPsy = time_now_exchange >= dstPsy_startTime and time_now_exchange <= dstPsy_endTime
bool sess_dst_onPsy = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=true, title='DST On?', inline='psyconf13', tooltip="This only affects Psy calc type of crypto. For crypto - the psy hi/lo calculations in general start at the start of the Sydney market and since Sydney observes DST the calculation needs to shift in respect to when Sydney is in or out of DST. The Psy calc type for forex is taken as the Tokio session and since Tokio does not observe DST this check box value has no effect for forex sessions.")

showDstTable = input.bool(group='Daylight Saving Time Info (DST)', title='Show DST Table : ', inline='dstt', defval=false)
choiceDstTable = input.string(group='Daylight Saving Time Info (DST)', title='DST Table postion', inline='dstt', defval='bottom_center', options=['top_right', 'top_left', 'top_center', 'bottom_right', 'bottom_left', 'bottom_center'])
dstTableBgColor = input.color(group='Daylight Saving Time Info (DST)', title='DST Table: Background Color', inline='dsttc', defval=color.rgb(93, 96, 107, 70))
dstTableTxtColor = input.color(group='Daylight Saving Time Info (DST)', title='Text Color', inline='dsttc', defval=color.rgb(31, 188, 211, 0))





//Non repainting security
f_security(_symbol, _res, _src, _repaint) =>
    request.security(_symbol, _res, _src[_repaint ? 0 : barstate.isrealtime ? 1 : 0])[_repaint ? 0 : barstate.isrealtime ? 0 : 1]


// Basic vars (needed in functions)

// Only render intraday
validTimeFrame = timeframe.isintraday == true

// If above the 5 minute, we start drawing yesterday. below, we start today
levelsstart = timeframe.isseconds == true or timeframe.isminutes == true and timeframe.multiplier < 5 ? time('D') : time('D') - 86400 * 1000
levelsstartbar = ta.barssince(levelsstart)


// Functions
// new_bar: check if we're on a new bar within the session in a given resolution
new_bar(res) =>
    ta.change(time(res)) != 0

// adr: Calculate average daily range for a given length
adr(length) =>
    // This is effectively an atr, which is what is used in MT4 to get those levels. FWIW, true range can be also calculated with tr(true)
    trueRange = na(high[1]) ? high - low : math.max(math.max(high - low, math.abs(high - close[1])), math.abs(low - close[1]))
    // Switched to SMA from RMA because somehow it matches MT4 better
    ta.sma(trueRange[1], length)

// adr_high: Calculate the ADR high given an ADR
adr_high(adr) =>
    high - low < adr ? low + adr : close >= open ? low + adr : high

// adr_low: Calculate the ADR low given an ADR
adr_low(adr) =>
    high - low < adr ? high - adr : close >= open ? low : high - adr

// to_pips: Convert to pips
to_pips(val) =>
    math.round(val / syminfo.mintick * 100) / 100

pivot_label_x_offset = time_close + pivot_offset_input * timeframe.multiplier * 60 * 1000
label_x_offset = time_close + label_offset_input * timeframe.multiplier * 60 * 1000
adr_label_x_offset = time_close + adr_offset_input * timeframe.multiplier * 60 * 1000

//Right_Label
r_label(ry, rtext, rstyle, rcolor, valid) =>
    if valid and barstate.isrealtime
        rLabel = label.new(x=label_x_offset, y=ry, text=rtext, xloc=xloc.bar_time, style=rstyle, textcolor=rcolor, textalign=text.align_right)
        label.delete(rLabel[1])

draw_line(x_series, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset) =>
    var line x_line = na

    if new_bar(res) and validTimeFrame
        line.set_x2(x_line, bar_index)
        line.set_extend(x_line, extend.none)

        x_line := line.new(bar_index, x_series, bar_index, x_series, extend=xExtend, color=xColor, style=xStyle, width=xWidth)
        line.delete(x_line[1])

    if not na(x_line) and line.get_x2(x_line) != bar_index
        line.set_x2(x_line, bar_index)

    if isLabelValid  //showADRLabels and validTimeFrame
        x_label = label.new(xLabelOffset, x_series, tag, xloc=xloc.bar_time, style=label.style_none, textcolor=xColor)
        label.delete(x_label[1])


draw_pivot(pivot_level, res, tag, pivotColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid) =>
    var line pivot_line = na

    // Start drawing yesterday
    if new_bar(res) and validTimeFrame
        line.set_x2(pivot_line, bar_index)
        line.set_extend(pivot_line, extend.none)
        pivot_line := line.new(bar_index, pivot_level, bar_index, pivot_level, extend=pivotExtend, color=pivotColor, style=pivotStyle, width=pivotWidth)
        line.delete(pivot_line[1])
    if not na(pivot_line) and line.get_x2(pivot_line) != bar_index
        line.set_x2(pivot_line, bar_index)
    if isLabelValid  //showADRLabels and validTimeFrame
        pivot_label = label.new(pivot_label_x_offset, pivot_level, tag, xloc=xloc.bar_time, style=label.style_none, textcolor=pivotColor, textalign=text.align_right)

        label.delete(pivot_label[1])
    if not barstate.islast
        line.set_x2(pivot_line, x=bar_index)
    else
        line.set_xloc(pivot_line, levelsstart, time_close + 1 * 86400000, xloc=xloc.bar_time)
    pivot_line

draw_linelabel_gmt_custSession(pivot_level, res, sessionString, tag, pivotColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid, label_offset, gmt_off_val) =>
    var line pivot_line = na

    gmtD = gmt_off_val
    current_session = time(res, sessionString, gmtD) 
    if not na(current_session) 
        pivot_line = line.new(current_session, pivot_level, timenow, pivot_level, xloc=xloc.bar_time, extend=pivotExtend, color=pivotColor, style=pivotStyle, width=pivotWidth)
        line.delete(pivot_line[1])
    if isLabelValid
        pivot_label = label.new(label_offset, pivot_level, tag, xloc=xloc.bar_time, style=label.style_none, textcolor=pivotColor, textalign=text.align_right)
        label.delete(pivot_label[1])
    pivot_line


update_pivot(pivot_line, pivot_level, res, tag, pivotColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid) =>
    if new_bar(res) and validTimeFrame
        line.set_x1(pivot_line, bar_index)
        line.set_y1(pivot_line, pivot_level)
        line.set_y2(pivot_line, pivot_level)
    if not barstate.islast
        line.set_x2(pivot_line, x=bar_index)
    else
        line.set_xloc(pivot_line, levelsstart, time_close + 1 * 86400000, xloc=xloc.bar_time)



//Emas
oneEmaLength = 5
twoEmaLength = 13
threeEmaLength = 50
fourEmaLength = 200
fiveEmaLength = 800

oneEma = ta.ema(close, oneEmaLength)
plot(showEmas ? oneEma : na, color=oneEmaColor, title='5 Ema')

twoEma = ta.ema(close, twoEmaLength)
plot(showEmas ? twoEma : na, color=twoEmaColor, title='13 Ema')

threeEma = ta.ema(close, threeEmaLength)
plot(showEmas ? threeEma : na, color=threeEmaColor, title='50 Ema')

fourEma = ta.ema(close, fourEmaLength)
plot(showEmas ? fourEma : na, color=fourEmaColor, title='200 Ema')

fiveEma = ta.ema(close, fiveEmaLength)
plot(showEmas ? fiveEma : na, color=fiveEmaColor, linewidth=2, title='800 Ema')


// Ema 50 cloud placed here for readability on data window
cloudSize = ta.stdev(close, threeEmaLength * 2) / 4
p1 = plot(showEmas ? threeEma + cloudSize : na, 'Upper 50 Ema Cloud', color=EmaCloudBorderColor, offset=0)
p2 = plot(showEmas ? threeEma - cloudSize : na, 'Lower 50 Ema Cloud', color=EmaCloudBorderColor, offset=0)
fill(p1, p2, title='EMA 50 Cloud', color=EmaCloudColor, transp=90)

//Label emas


r_label(oneEma, '5 Ema', label.style_none, oneEmaColor, labelEmas)  //ry, rtext, rstyle, rcolor,valid
r_label(twoEma, '13 Ema', label.style_none, twoEmaColor, labelEmas)
r_label(threeEma, '50 Ema', label.style_none, threeEmaColor, labelEmas)
r_label(fourEma, '200 Ema', label.style_none, fourEmaColor, labelEmas)
r_label(fiveEma, '800 Ema', label.style_none, fiveEmaColor, labelEmas)


// Get Daily price data
dayHigh = f_security(syminfo.tickerid, 'D', high, false)
dayLow = f_security(syminfo.tickerid, 'D', low, false)
dayOpen = f_security(syminfo.tickerid, 'D', open, false)
dayClose = f_security(syminfo.tickerid, 'D', close, false)

//Compute Values
pivotPoint = (dayHigh + dayLow + dayClose) / 3

// Updated 2021-03-25 by infernix
pivR1 = 2 * pivotPoint - dayLow
pivS1 = 2 * pivotPoint - dayHigh
pivR2 = pivotPoint - pivS1 + pivR1
pivS2 = pivotPoint - pivR1 + pivS1
pivR3 = 2 * pivotPoint + dayHigh - 2 * dayLow
pivS3 = 2 * pivotPoint - (2 * dayHigh - dayLow)

//Plot Values
//plot(validTimeFrame and showLevelOnePivotPoints? pivotPoint : na, linewidth = 1, color = color.yellow, style = plot.style_circles, transp = 25, title = "Daily Pivot Point", show_last = plot_bars)

pivline = draw_pivot(validTimeFrame and (showLevelOnePivotPoints or showLevelTwoPivotPoints or showLevelThreePivotPoints or activeM) ? pivotPoint : na, 'D', 'PP', pivotColor, mStyle, 1, extendPivots ? extend.both : extend.right, showPivotLabels and validTimeFrame)
pivr1line = draw_pivot(validTimeFrame and showLevelOnePivotPoints ? pivR1 : na, 'D', 'R1', color.new(color.green, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelOnePivotPoints and showPivotLabels and validTimeFrame)
pivs1line = draw_pivot(validTimeFrame and showLevelOnePivotPoints ? pivS1 : na, 'D', 'S1', color.new(color.red, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelOnePivotPoints and showPivotLabels and validTimeFrame)
pivr2line = draw_pivot(validTimeFrame and showLevelTwoPivotPoints ? pivR2 : na, 'D', 'R2', color.new(color.green, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelTwoPivotPoints and showPivotLabels and validTimeFrame)
pivs2line = draw_pivot(validTimeFrame and showLevelTwoPivotPoints ? pivS2 : na, 'D', 'S2', color.new(color.red, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelTwoPivotPoints and showPivotLabels and validTimeFrame)
pivr3line = draw_pivot(validTimeFrame and showLevelThreePivotPoints ? pivR3 : na, 'D', 'R3', color.new(color.green, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelThreePivotPoints and showPivotLabels and validTimeFrame)
pivs3line = draw_pivot(validTimeFrame and showLevelThreePivotPoints ? pivS3 : na, 'D', 'S3', color.new(color.red, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelThreePivotPoints and showPivotLabels and validTimeFrame)


if not na(pivotPoint)
    update_pivot(pivline, validTimeFrame and (showLevelOnePivotPoints or showLevelTwoPivotPoints or showLevelThreePivotPoints or activeM) ? pivotPoint : na, 'D', 'PP', pivotColor, line.style_dashed, 1, extendPivots ? extend.both : extend.right, showPivotLabels and validTimeFrame)

if not na(pivR1)
    update_pivot(pivr1line, validTimeFrame and showLevelOnePivotPoints ? pivR1 : na, 'D', 'R1', color.new(color.green, 50), line.style_dashed, 1, extendPivots ? extend.both : extend.right, showLevelOnePivotPoints and showPivotLabels and validTimeFrame)

if not na(pivS1)
    update_pivot(pivs1line, validTimeFrame and showLevelOnePivotPoints ? pivS1 : na, 'D', 'S1', color.new(color.red, 50), line.style_dashed, 1, extendPivots ? extend.both : extend.right, showLevelOnePivotPoints and showPivotLabels and validTimeFrame)

if not na(pivR2)
    update_pivot(pivr2line, validTimeFrame and showLevelTwoPivotPoints ? pivR2 : na, 'D', 'R2', color.new(color.green, 50), line.style_dashed, 1, extendPivots ? extend.both : extend.right, showLevelTwoPivotPoints and showPivotLabels and validTimeFrame)

if not na(pivS2)
    update_pivot(pivs2line, validTimeFrame and showLevelTwoPivotPoints ? pivS2 : na, 'D', 'S2', color.new(color.red, 50), line.style_dashed, 1, extendPivots ? extend.both : extend.right, showLevelTwoPivotPoints and showPivotLabels and validTimeFrame)

if not na(pivR3)
    update_pivot(pivr3line, validTimeFrame and showLevelThreePivotPoints ? pivR3 : na, 'D', 'R3', color.new(color.green, 50), line.style_dashed, 1, extendPivots ? extend.both : extend.right, showLevelThreePivotPoints and showPivotLabels and validTimeFrame)

if not na(pivS3)
    update_pivot(pivs3line, validTimeFrame and showLevelThreePivotPoints ? pivS3 : na, 'D', 'S3', color.new(color.red, 50), line.style_dashed, 1, extendPivots ? extend.both : extend.right, showLevelThreePivotPoints and showPivotLabels and validTimeFrame)



// Daily H/L 

weekHigh = f_security(syminfo.tickerid, 'W', high, false)
weekLow = f_security(syminfo.tickerid, 'W', low, false)

validDHLTimeFrame = timeframe.isintraday == true
validWHLTimeFrame = timeframe.isintraday == true or timeframe.isdaily == true
isToday = year(timenow) == year(time) and month(timenow) == month(time) and dayofmonth(timenow) == dayofmonth(time)
isThisWeek = year(timenow) == year(time) and weekofyear(timenow) == weekofyear(time)


plot(validDHLTimeFrame and showDayHighLow and (showDayHighLow ? true : isToday) ? dayHigh : na, linewidth=2, color=color.new(color.blue, 50), style=plot.style_circles, title="YDay Hi")
plot(validDHLTimeFrame and showDayHighLow and (showDayHighLow ? true : isToday) ? dayLow : na, linewidth=2, color=color.new(color.blue, 50), style=plot.style_circles, title="YDay Lo")
r_label(dayHigh, 'YDay Hi', label.style_none, color.blue, validDHLTimeFrame and showDayHighLow and showDayHighLowLabels)  //ry, rtext, rstyle, rcolor, valid
r_label(dayLow, 'YDay Lo', label.style_none, color.blue, validDHLTimeFrame and showDayHighLow and showDayHighLowLabels)

plot(validWHLTimeFrame and showWeekHighLow and (showWeekHighLow ? true : isThisWeek) ? weekHigh : na, linewidth=2, color=color.new(color.green, 60), style=plot.style_circles, title="LWeek Hi")
plot(validWHLTimeFrame and showWeekHighLow and (showWeekHighLow ? true : isThisWeek) ? weekLow : na, linewidth=2, color=color.new(color.green, 60), style=plot.style_circles, title="LWeek Lo")

r_label(weekHigh, 'LWeek Hi', label.style_none, color.green, validWHLTimeFrame and showWeekHighLow and showDayHighLowLabels)  //ry, rtext, rstyle, rcolor, valid
r_label(weekLow, 'LWeek Lo', label.style_none, color.green, validWHLTimeFrame and showWeekHighLow and showDayHighLowLabels)

// PVSRA
// From MT4 source:

//   Situation "Climax"
//   Bars with volume >= 200% of the average volume of the 10 previous chart TFs, and bars
//   where the product of candle spread x candle volume is >= the highest for the 10 previous
//   chart time TFs.
//   Default Colors:  Bull bars are green and bear bars are red.

//   Situation "Volume Rising Above Average"
//   Bars with volume >= 150% of the average volume of the 10 previous chart TFs.
//   Default Colors:  Bull bars are blue and bear are blue-violet.

// We want to be able to override where we get the volume data for the candles.


pvsra_security(sresolution, sseries) =>
    request.security(overridesym ? pvsra_sym : syminfo.tickerid, sresolution, sseries[barstate.isrealtime ? 1 : 0], barmerge.gaps_off, barmerge.lookahead_off)
pvsra_security_1 = pvsra_security('', volume)
pvsra_volume = overridesym == true ? pvsra_security_1 : volume
pvsra_security_2 = pvsra_security('', high)
pvsra_high = overridesym == true ? pvsra_security_2 : high
pvsra_security_3 = pvsra_security('', low)
pvsra_low = overridesym == true ? pvsra_security_3 : low
pvsra_security_4 = pvsra_security('', close)
pvsra_close = overridesym == true ? pvsra_security_4 : close
pvsra_security_5 = pvsra_security('', open)
pvsra_open = overridesym == true ? pvsra_security_5 : open


r_label(high - (high - low) / 2, 'PVSRA Override Active!', label.style_none, color.orange, overridesym)  //ry, rtext, rstyle, rcolor, valid

//label.new(overridesym ? 0 : na, low, text = "PVSRA Override: " + pvsra_sym, xloc = xloc.bar_index, yloc=yloc.belowbar,style=label.style_label_down, size=size.huge)

// The below math matches MT4 PVSRA indicator source
// average volume from last 10 candles
sum_1 = math.sum(pvsra_volume, 10)
sum_2 = math.sum(volume, 10)
av = overridesym == true ? sum_1 / 10 : sum_2 / 10
//climax volume on the previous candle
value2 = overridesym == true ? pvsra_volume * (pvsra_high - pvsra_low) : volume * (high - low)
// highest climax volume of the last 10 candles
hivalue2 = ta.highest(value2, 10)
// VA value determines the bar color. va = 0: normal. va = 1: climax.  va = 2: rising
iff_1 = pvsra_volume >= av * 1.5 ? 2 : 0
iff_2 = pvsra_volume >= av * 2 or value2 >= hivalue2 ? 1 : iff_1
iff_3 = volume >= av * 1.5 ? 2 : 0
iff_4 = volume >= av * 2 or value2 >= hivalue2 ? 1 : iff_3
va = overridesym == true ? iff_2 : iff_4

// Bullish or bearish coloring
isBull = overridesym == true ? pvsra_close > pvsra_open : close > open

CUColor = color.lime  // Climax up (bull) bull and bear both start with b so it would be weird hence up down
CDColor = color.red  // Climax down (bear)

AUColor = color.blue  //Avobe average up (bull)
ADColor = color.fuchsia  //Above average down (bear))

NUColor = #999999
NDColor = #4d4d4d



// candleColor = iff(climax,iff(isBull,CUColor,CDColor),iff(aboveA,iff(isBull,AUColor,ADColor),iff(isBull,NUColor,NDColor)))
iff_5 = va == 2 ? AUColor : NUColor
iff_6 = va == 1 ? CUColor : iff_5
iff_7 = va == 2 ? ADColor : NDColor
iff_8 = va == 1 ? CDColor : iff_7
candleColor = isBull ? iff_6 : iff_8
barcolor(candleColor)

alertcondition(va > 0, title='Alert on Any Vector Candle', message='{{ticker}} Vector Candle on the {{interval}}')



redGreen = candleColor ==  color.lime and candleColor[1] == color.red
greenRed = candleColor ==  color.red and candleColor[1] == color.lime
redBlue = candleColor ==  color.blue and candleColor[1] == color.red
blueRed = candleColor ==  color.red and candleColor[1] == color.blue
greenPurpule = candleColor ==  color.fuchsia and candleColor[1] == color.green
purpleGreen = candleColor ==  color.green and candleColor[1] == color.fuchsia
bluePurpule = candleColor ==  color.fuchsia and candleColor[1] == color.blue
purpleBlue = candleColor ==  color.blue and candleColor[1] == color.fuchsia
alertcondition(redGreen, title='Red/Green Vector Candle Pattern', message='{{ticker}} Red/Green Vector Candle Pattern on the {{interval}}')
alertcondition(greenRed, title='Green/Red Vector Candle Pattern', message='{{ticker}} Green/Red Vector Candle Pattern on the {{interval}}')
alertcondition(redBlue, title='Red/Blue Vector Candle Pattern', message='{{ticker}} Red/Blue Vector Candle Pattern on the {{interval}}')
alertcondition(blueRed, title='Blue/Red Vector Candle Pattern', message='{{ticker}} Blue/Red Vector Candle Pattern on the {{interval}}')
alertcondition(greenPurpule, title='Green/Purple Vector Candle Pattern', message='{{ticker}} Green/Purple Vector Candle Pattern on the {{interval}}')
alertcondition(purpleGreen, title='Purple/Green Vector Candle Pattern', message='{{ticker}} Purple/Green Vector Candle Pattern on the {{interval}}')
alertcondition(bluePurpule, title='Blue/Purple Vector Candle Pattern', message='{{ticker}} Blue/Purple Vector Candle Pattern on the {{interval}}')
alertcondition(purpleBlue, title='Purple/Blue Vector Candle Pattern', message='{{ticker}} Purple/Blue Vector Candle Pattern on the {{interval}}')


//ADR
// Daily ADR
//
day_adr = request.security(syminfo.tickerid, 'D', adr(15), lookahead=barmerge.lookahead_on)
day_adr_high = request.security(syminfo.tickerid, 'D', adr_high(day_adr), lookahead=barmerge.lookahead_on)
day_adr_low = request.security(syminfo.tickerid, 'D', adr_low(day_adr), lookahead=barmerge.lookahead_on)

if showADR
    draw_line(day_adr_high, 'D', 'Hi-ADR', adrColor, adrStyle, 2, extend.right, showADRLabels and validTimeFrame, adr_label_x_offset)
    draw_line(day_adr_low, 'D', 'Lo-ADR', adrColor, adrStyle, 2, extend.right, showADRLabels and validTimeFrame, adr_label_x_offset)
    r_label((day_adr_high + day_adr_low) / 2, 'ADR ' + str.tostring(to_pips(day_adr)), label.style_none, adrColor, showADRLabels and validTimeFrame and showADRRange)  //ry, rtext, rstyle, rcolor, valid

alertcondition(close >= day_adr_high and day_adr_high != 0 , "ADR High reached", "PA has reached the calculated ADR High")
alertcondition(close <= day_adr_low and day_adr_low != 0 , "ADR Low reached", "PA has reached the calculated ADR Low")

//Weekly ADR    
week_adr = request.security(syminfo.tickerid, 'W', adr(1), lookahead=barmerge.lookahead_on)
week_adr_high = request.security(syminfo.tickerid, 'W', adr_high(week_adr), lookahead=barmerge.lookahead_on)
week_adr_low = request.security(syminfo.tickerid, 'W', adr_low(week_adr), lookahead=barmerge.lookahead_on)

if showAWR
    draw_line(week_adr_high, 'W', 'Hi-AWR', awrColor, awrStyle, 1, extend.right, showAWRLabels and validTimeFrame, adr_label_x_offset)
    draw_line(week_adr_low, 'W', 'Lo-AWR', awrColor, awrStyle, 1, extend.right, showAWRLabels and validTimeFrame, adr_label_x_offset)
    r_label((week_adr_high + week_adr_low) / 2, 'AWR ' + str.tostring(to_pips(week_adr)), label.style_none, awrColor, showAWRLabels and validTimeFrame and showAWRRange)  //ry, rtext, rstyle, rcolor, valid
alertcondition(close >= week_adr_high and week_adr_high != 0 , "AWR High reached", "PA has reached the calculated AWR High")
alertcondition(close <= week_adr_low and week_adr_low != 0 , "AWR Low reached", "PA has reached the calculated AWR Low")


//Monthly ADR 
month_adr = request.security(syminfo.tickerid, 'M', adr(1), lookahead=barmerge.lookahead_on)
month_adr_high = request.security(syminfo.tickerid, 'M', adr_high(week_adr), lookahead=barmerge.lookahead_on)
month_adr_low = request.security(syminfo.tickerid, 'M', adr_low(week_adr), lookahead=barmerge.lookahead_on)

if showAMR
    draw_line(month_adr_high, 'M', 'Hi-AMR', amrColor, amrStyle, 1, extend.right, showAMRLabels and validTimeFrame, adr_label_x_offset)
    draw_line(month_adr_low, 'M', 'Lo-AMR', amrColor, amrStyle, 1, extend.right, showAMRLabels and validTimeFrame, adr_label_x_offset)
    r_label((month_adr_high + month_adr_low) / 2, 'AMR ' + str.tostring(to_pips(month_adr)), label.style_none, amrColor, showAMRLabels and validTimeFrame and showAMRRange)  //ry, rtext, rstyle, rcolor, valid

alertcondition(close >= month_adr_high and month_adr_high != 0 , "AMR High reached", "PA has reached the calculated AMR High")
alertcondition(close <= month_adr_low and month_adr_low != 0 , "AMR Low reached", "PA has reached the calculated AMR Low")

if barstate.islast and showAdrTable and validTimeFrame
    var table panel = table.new(choiceAdrTable, 2, 5, bgcolor=adrTableBgColor)

    // Table header.
    table.cell(panel, 0, 0, '')
    table.cell(panel, 1, 0, '')
    table.cell(panel, 0, 1, 'ADR', text_color=adrTableTxtColor)
    table.cell(panel, 1, 1, str.format('{0,number,#.##}', to_pips(day_adr)) , text_color=adrTableTxtColor)
    table.cell(panel, 0, 2, 'ADRx3', text_color=adrTableTxtColor)
    table.cell(panel, 1, 2, str.format('{0,number,#.##}', to_pips(day_adr) * 3), text_color=adrTableTxtColor)
    table.cell(panel, 0, 3, 'AWR', text_color=adrTableTxtColor)
    table.cell(panel, 1, 3, str.format('{0,number,#.##}', to_pips(week_adr)), text_color=adrTableTxtColor)
    table.cell(panel, 0, 4, 'AMR', text_color=adrTableTxtColor)
    table.cell(panel, 1, 4, str.format('{0,number,#.##}', to_pips(month_adr)), text_color=adrTableTxtColor)


// M - Levels


//Calculate Pivot Point
// 2021-03025 updated by infernix 
//M calculations
m0C = (pivS2 + pivS3) / 2
m1C = (pivS1 + pivS2) / 2
m2C = (pivotPoint + pivS1) / 2
m3C = (pivotPoint + pivR1) / 2
m4C = (pivR1 + pivR2) / 2
m5C = (pivR2 + pivR3) / 2


m0line = draw_pivot(validTimeFrame and activeM and m0C ? m0C : na, 'D', 'M0', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
m1line = draw_pivot(validTimeFrame and activeM and m1C ? m1C : na, 'D', 'M1', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
m2line = draw_pivot(validTimeFrame and activeM and m2C ? m2C : na, 'D', 'M2', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
m3line = draw_pivot(validTimeFrame and activeM and m3C ? m3C : na, 'D', 'M3', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
m4line = draw_pivot(validTimeFrame and activeM and m4C ? m4C : na, 'D', 'M4', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
m5line = draw_pivot(validTimeFrame and activeM and m5C ? m5C : na, 'D', 'M5', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)

if not na(m0C)
    update_pivot(m0line, validTimeFrame and activeM and m0C ? m0C : na, 'D', 'M0', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
if not na(m1C)
    update_pivot(m1line, validTimeFrame and activeM and m1C ? m1C : na, 'D', 'M1', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
if not na(m2C)
    update_pivot(m2line, validTimeFrame and activeM and m2C ? m2C : na, 'D', 'M2', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
if not na(m3C)
    update_pivot(m3line, validTimeFrame and activeM and m3C ? m3C : na, 'D', 'M3', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
if not na(m4C)
    update_pivot(m4line, validTimeFrame and activeM and m4C ? m4C : na, 'D', 'M4', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)
if not na(m5C)
    update_pivot(m5line, validTimeFrame and activeM and m5C ? m5C : na, 'D', 'M5', mColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame)


//*****************
// Market sessions
//*****************
splitSessionString(sessXTime) =>
    //session stirng looks like this: 0000-0000:1234567 ie start time, end time, day of the week
    //we need to parse the sessXTime string into hours and min for start and end times so we can use those in the timestampfunction below

    //string times contains "0000-2300" as an example
    string times = array.get(str.split(sessXTime, ':'), 0)

    //string startTime contains "0000"
    string startTime = array.get(str.split(times, '-'), 0)
    //string endTime contains "2300"
    string endTime = array.get(str.split(times, '-'), 1)

    //now we need to get the start hour and start min, sing 0 index - hour is the characters in index 0 and index 1 while min is the chars at index 2 and 3
    string[] startTimeChars = str.split(startTime, '')
    string[] endTimeChars = str.split(endTime, '')

    //so now startHour contains 00 and start min contains 00
    string startHour = array.get(startTimeChars, 0) + array.get(startTimeChars, 1)
    string startMin = array.get(startTimeChars, 2) + array.get(startTimeChars, 3)

    //so now endHour contains 23 and end min contains 00
    string endHour = array.get(endTimeChars, 0) + array.get(endTimeChars, 1)
    string endMin = array.get(endTimeChars, 2) + array.get(endTimeChars, 3)
    [startHour, startMin, endHour, endMin]
    
calc_session_startend(sessXTime, gmt) =>
    [startHour, startMin, endHour, endMin] = splitSessionString(sessXTime)
    targetstartTimeX = timestamp(gmt, year, month, dayofmonth, math.round(str.tonumber(startHour)), math.round(str.tonumber(startMin)), 00)
    targetendTimeX = timestamp(gmt, year, month, dayofmonth, math.round(str.tonumber(endHour)), math.round(str.tonumber(endMin)), 00)
    time_now = timestamp(year, month, dayofmonth, hour, minute, 00) 
    midnight_exchange = timestamp(year, month, dayofmonth, 00, 00, 00)  


    //if start hour is greater than end hour we are dealing with a session that starts towards the end of one day 
    //and ends the next day. ie advance the end time by 24 hours - its the next day
    bool adjusted = false
    if gmt == 'GMT+0'
        if math.round(str.tonumber(startHour)) > math.round(str.tonumber(endHour))
            if time_now - targetstartTimeX >= 0
                targetendTimeX := targetendTimeX + 24 * 60 * 60 * 1000
                adjusted := true
                targetendTimeX
    if gmt == 'GMT+1'
        if math.round(str.tonumber(startHour)) == 0
            startHour := '24'
        if math.round(str.tonumber(endHour)) == 0
            endHour := '24'    
        if math.round(str.tonumber(startHour))-1 > math.round(str.tonumber(endHour))-1
            if time_now - targetstartTimeX >= 0
                targetendTimeX := targetendTimeX + 24 * 60 * 60 * 1000
                adjusted := true
                targetendTimeX
    
    //now is the exchange is at some utc offset and the market session crosses days even when start hour is not greater than end hour
    //we still need to adjust the end time. 
    
    if targetstartTimeX < midnight_exchange and midnight_exchange < targetendTimeX and not adjusted
        targetendTimeX := targetendTimeX + 24 * 60 * 60 * 1000
        targetendTimeX                
            
    [targetstartTimeX,targetendTimeX]
                

draw_open_range(sessXTime, sessXcol, show_orX, gmt)=>
    if show_orX
        // Initialize variables on bar zero only, so they preserve their values across bars.
        var hi = float(na)
        var lo = float(na)
        var box hiLoBox = na
        // Detect changes in timeframe.
        session = time(timeframe.period, sessXTime, gmt)
        bool newTF = session and not session[1]
        if newTF
            // New bar in higher timeframe; reset values and create new lines and box.
            [targetstartTimeX,targetendTimeX] = calc_session_startend(sessXTime, gmt)
            sessionDuration = math.round(math.abs(time  - targetendTimeX)/(timeframe.multiplier*60*1000))
   
            hi := high
            lo := low
            hiLoBox := box.new(bar_index, hi, timeframe.multiplier == 1? bar_index : bar_index+sessionDuration, lo, border_color = na, bgcolor = sessXcol)
            int(na)
        else
            if timeframe.multiplier == 1 and (na(session[1]) and not na(session) or session[1] < session)
                box.set_right(hiLoBox, bar_index+1)
            int(na)
draw_session_hilo(sessXTime, show_rectangleX, show_labelX, sessXcolLabel, sessXLabel, gmt)=>
    if show_rectangleX
        // Initialize variables on bar zero only, so they preserve their values across bars.
        var hi = float(0)
        var lo = float(10000000000.0)
        var beginIndex = int(na)
        var line line_t = na
        var line line_b = na
        var label line_label = na
        // var box hiLoBox = na
        // Detect changes in timeframe.
        session = time(timeframe.period, sessXTime, gmt)
        sessLineStyleX = rectStyle == 'Solid' ? line.style_solid : line.style_dashed
        bool newTF = session and not session[1]
        hi := newTF ? high : session ? math.max(high, hi[1]) : hi[1]
        lo := newTF ? low : session ? math.min(low, lo[1]) : lo[1]
        difference = timestamp(year,month,dayofmonth,00,00,00) - (10*24*60*60*1000)   
        if newTF and timenow > difference
            beginIndex := bar_index 
            [targetstartTimeX,targetendTimeX] = calc_session_startend(sessXTime, gmt)
            sessionDuration = math.round(math.abs(time  - targetendTimeX)/(timeframe.multiplier*60*1000))
        
            line_t := line.new(beginIndex, hi, timeframe.multiplier == 1? bar_index : bar_index+sessionDuration, hi, xloc=xloc.bar_index, style=sessLineStyleX, color=sessXcolLabel)
            line_b := line.new(beginIndex, lo, timeframe.multiplier == 1? bar_index : bar_index+sessionDuration, lo, xloc=xloc.bar_index, style=sessLineStyleX, color=sessXcolLabel)
            line.delete(line_t[1])
            line.delete(line_b[1])
            if show_labelX
                line_label := label.new(beginIndex, hi, sessXLabel, xloc=xloc.bar_index, textcolor=sessXcolLabel, style=label.style_none, size=size.normal, textalign=text.align_right)
                label.delete(line_label[1])
  
            int(na)
        else
            if na(session[1]) and not na(session) or session[1] < session
                if timeframe.multiplier == 1
                    line.set_x2(line_t,bar_index+1)
                    line.set_x2(line_b,bar_index+1)
                line.set_y1(line_t,hi)
                line.set_y2(line_t,hi)
                line.set_y1(line_b,lo)
                line.set_y2(line_b,lo)
                if show_labelX and not na(line_label)
                    label.set_xy(line_label, beginIndex, hi)
            int(na)
            
            
if sess_dst_on1
    draw_open_range(sess1Time,sess1col,show_or1,'GMT+1')
    draw_session_hilo(sess1Time, show_rectangle1, show_label1, sess1colLabel, sess1Label, 'GMT+1')
else
    draw_open_range(sess1Time,sess1col,show_or1,'GMT+0')
    draw_session_hilo(sess1Time, show_rectangle1, show_label1, sess1colLabel, sess1Label, 'GMT+0')

if sess_dst_on2
    draw_open_range(sess2Time,sess2col,show_or2,'GMT+1')
    draw_session_hilo(sess2Time, show_rectangle2, show_label2, sess2colLabel, sess2Label, 'GMT+1')
else
    draw_open_range(sess2Time,sess2col,show_or2,'GMT+0')
    draw_session_hilo(sess2Time, show_rectangle2, show_label2, sess2colLabel, sess2Label, 'GMT+0')

if sess_dst_on3
    draw_open_range(sess3Time,sess3col,show_or3,'GMT+1')
    draw_session_hilo(sess3Time, show_rectangle3, show_label3, sess3colLabel, sess3Label, 'GMT+1')
else
    draw_open_range(sess3Time,sess3col,show_or3,'GMT+0')
    draw_session_hilo(sess3Time, show_rectangle3, show_label3, sess3colLabel, sess3Label, 'GMT+0')

if sess_dst_on4
    draw_open_range(sess4Time,sess4col,show_or4,'GMT+1')
    draw_session_hilo(sess4Time, show_rectangle4, show_label4, sess4colLabel, sess4Label, 'GMT+1')
else
    draw_open_range(sess4Time,sess4col,show_or4,'GMT+0')
    draw_session_hilo(sess4Time, show_rectangle4, show_label4, sess4colLabel, sess4Label, 'GMT+0')

if sess_dst_on5
    draw_open_range(sess5Time,sess5col,show_or5,'GMT+1')
    draw_session_hilo(sess5Time, show_rectangle5, show_label5, sess5colLabel, sess5Label, 'GMT+1')
else
    draw_open_range(sess5Time,sess5col,show_or5,'GMT+0')
    draw_session_hilo(sess5Time, show_rectangle5, show_label5, sess5colLabel, sess5Label, 'GMT+0')

if sess_dst_on6
    draw_open_range(sess6Time,sess6col,show_or6,'GMT+1')
    draw_session_hilo(sess6Time, show_rectangle6, show_label6, sess6colLabel, sess6Label, 'GMT+1')
else
    draw_open_range(sess6Time,sess6col,show_or6,'GMT+0')
    draw_session_hilo(sess6Time, show_rectangle6, show_label6, sess6colLabel, sess6Label, 'GMT+0')

if sess_dst_on7
    draw_open_range(sess7Time,sess7col,show_or7,'GMT+1')
    draw_session_hilo(sess7Time, show_rectangle7, show_label7, sess7colLabel, sess7Label, 'GMT+1')
else
    draw_open_range(sess7Time,sess7col,show_or7,'GMT+0')
    draw_session_hilo(sess7Time, show_rectangle7, show_label7, sess7colLabel, sess7Label, 'GMT+0')

if sess_dst_on8
    draw_open_range(sess8Time,sess8col,show_or8,'GMT+1')
    draw_session_hilo(sess8Time, show_rectangle8, show_label8, sess8colLabel, sess8Label, 'GMT+1')
else
    draw_open_range(sess8Time,sess8col,show_or8,'GMT+0')
    draw_session_hilo(sess8Time, show_rectangle8, show_label8, sess8colLabel, sess8Label, 'GMT+0')

//***********
// Daily open
//***********
getdayOpen()=>
    in_sessionDly = time('D', '24x7')
    bool isDly = ta.change(time('D'))//ta.change(in_sessionDly)//in_sessionDly and not in_sessionDly[1]
    var dlyOpen = float(na)
    if isDly
        dlyOpen := open
    dlyOpen
daily_open = getdayOpen()
//this plot is only to show historical values when the option is selected.
plot(show_rectangle9 and validTimeFrame and showallDly ? daily_open : na, color=sess9col, style=plot.style_stepline, linewidth=2, editable=false, title="Daily Open")
if showallDly
    //if historical values are selected to be shown - then add a label to the plot
    r_label(daily_open, 'Daily Open', label.style_none, sess9col, validTimeFrame and show_label9)
    showallDly
else
    if show_rectangle9
        //othewise we draw the line and label together - showing only todays line.
        draw_line(daily_open, 'D', 'Daily Open', sess9col, line.style_solid, 1, extend.none, validTimeFrame and show_label9, label_x_offset)
    


//************//
// Psy Levels //
//************//
calc_psy_hilo(gmtoffsetPsy, sessionPsyX) =>

    //4 hour res based on how mt4 does it
    //mt4 code
    //int Li_4 = iBarShift(NULL, PERIOD_H4, iTime(NULL, PERIOD_W1, Li_0)) - 2 - Offset;
    //ObjectCreate("PsychHi", OBJ_TREND, 0, Time[0], iHigh(NULL, PERIOD_H4, iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)), iTime(NULL, PERIOD_W1, 0), iHigh(NULL, PERIOD_H4,
    //iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)));

    //so basically because the session is 8 hours and we are looking at a 4 hour resolution we only need to take the highest high an lowest low of 2 bars
    //we use the gmt offset to adjust the 0000-0800 session to Sydney open which is at 2100 during dst and at 2200 otherwize. (dst - spring foward, fall back)
    //keep in mind sydney is in the souther hemisphere so dst is oposite of when london and new york go into dst
    in_session = time('240', sessionPsyX, gmtoffsetPsy)
    new_session = in_session and not in_session[1]
    float psy_high = 0.0
    float psy_low = 100000000000.0

    psy_high := new_session ? high : in_session ? math.max(high, psy_high[1]) : psy_high[1]
    psy_low := new_session ? low : in_session ? math.min(low, psy_low[1]) : psy_low[1]
    
    
    //if barstate.isnew
    psy_calc_start = timestamp(gmtoffsetPsy, year, month, dayofweek.wednesday, 00, 00, 00)
    psy_calc_end = timestamp(gmtoffsetPsy, year, month, dayofweek.wednesday, 08, 00, 00)
    time_now_gmt = time('D', sessionPsyX, gmtoffsetPsy)
    psy_calc_inProgress = not na(time_now_gmt - psy_calc_start >= 0) and not na(time_now_gmt - psy_calc_end <= 0)
    

    psy_hi_label = 'Psy-Hi'  
    psy_lo_label = 'Psy-Lo'
    
    if psy_calc_inProgress
            //stylePsy := line.style_dashed //this does not work for style correctly but it does for the label which is odd
        psy_hi_label := 'Psy-Hi calculating...'
        psy_lo_label := 'Psy-Lo calculating...'  
        psy_lo_label
    else
        psy_hi_label := 'Psy-Hi'  
        psy_lo_label := 'Psy-Lo'
 
    [psy_high, psy_low, psy_hi_label, psy_lo_label]
    
draw_psy_levels(psy_high,psy_low, psy_hi_label, psy_lo_label,sessionPsyX, gmt) =>
    if showallPsy
        r_label(psy_high, psy_hi_label, label.style_none, psycolH, validTimeFrame and show_psylabel)
        r_label(psy_low, psy_lo_label, label.style_none, psycolL, validTimeFrame and show_psylabel)
        showallPsy  //just here to trick if-else into working
    else
        if show_psylevels
            draw_linelabel_gmt_custSession(psy_high, 'D', sessionPsyX, psy_hi_label, psycolH, line.style_solid, 1, extend.none, show_psylabel and show_psylevels, label_x_offset, gmt)
            draw_linelabel_gmt_custSession(psy_low, 'D', sessionPsyX, psy_lo_label, psycolL, line.style_solid, 1, extend.none, show_psylabel and show_psylevels, label_x_offset, gmt)
        showallPsy  //just here to trick if-else into working
    

float psy_high = na 
float psy_low = na


if psyType == 'crypto'
    if sess_dst_onPsy
        [psy_highX, psy_lowX, psy_hi_label, psy_lo_label] = calc_psy_hilo("GMT+1", cryptoCalcSession)
        psy_high := psy_highX
        psy_low := psy_lowX
        draw_psy_levels(psy_high,psy_low, psy_hi_label, psy_lo_label, cryptoCalcSession, "GMT+1")
    else
        [psy_highX, psy_lowX, psy_hi_label, psy_lo_label] = calc_psy_hilo("GMT+0", cryptoCalcSession)
        psy_high := psy_highX
        psy_low := psy_lowX
        draw_psy_levels(psy_high,psy_low, psy_hi_label, psy_lo_label,cryptoCalcSession,"GMT+0")
else
    [psy_highX, psy_lowX, psy_hi_label, psy_lo_label] = calc_psy_hilo("GMT+0",forexCalcSession)
    psy_high := psy_highX
    psy_low := psy_lowX  
    draw_psy_levels(psy_high,psy_low, psy_hi_label, psy_lo_label,forexCalcSession,"GMT+0")

plot(showPsy and show_psylevels and showallPsy ? psy_high : na, color=psycolH, style=plot.style_stepline, linewidth=2, editable=false, title="Psy-Hi")  //, offset=psy_plot_offset)
plot(showPsy and show_psylevels and showallPsy ? psy_low : na, color=psycolL, style=plot.style_stepline, linewidth=2, editable=false, title="Psy-Lo")  //, offset=psy_plot_offset)



//London DST Starts Last Sunday of March DST Edns Last Sunday of October
//New York DST Starts 2nd Sunday of March DST Edns 1st Sunday of November
//Sydney DST Start on 1st Sunday of October DST ends 1st Sunday of Arpil
//Frankfurt DST Starts Last Sunday of March DST Edns Last Sunday of October

 
if barstate.islast and showDstTable


    var table dstTable = table.new(choiceDstTable, 2, 8, bgcolor=dstTableBgColor)

    //general
    table.cell(dstTable, 0, 0, 'London DST Starts Last Sunday of March | DST Edns Last Sunday of October', text_color=adrTableTxtColor)
    table.cell(dstTable, 0, 1, 'New York DST Starts 2nd Sunday of March | DST Edns 1st Sunday of November', text_color=adrTableTxtColor)
    table.cell(dstTable, 0, 2, 'Tokio does not observe DST', text_color=adrTableTxtColor)
    table.cell(dstTable, 0, 3, 'Hong Kong does not observe DST', text_color=adrTableTxtColor)
    table.cell(dstTable, 0, 4, 'Sydney DST Start on 1st Sunday of October | DST ends 1st Sunday of Arpil', text_color=adrTableTxtColor)
    table.cell(dstTable, 0, 5, 'EU Brinks DST Starts Last Sunday of March | DST Edns Last Sunday of October', text_color=adrTableTxtColor)
    table.cell(dstTable, 0, 6, 'US Brinks DST Starts 2nd Sunday of March | DST Edns 1st Sunday of November', text_color=adrTableTxtColor)
    table.cell(dstTable, 0, 7, 'Frankfurt DST Starts Last Sunday of March | DST Edns Last Sunday of October', text_color=adrTableTxtColor)