Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //@ZPayab
- //@version=5
- indicator(title='DIY Custom Strategy Builder [ZP] - v1', overlay=true)
- ma(_source, _length, _type) =>
- switch _type
- "SMA" => ta.sma (_source, _length)
- "EMA" => ta.ema (_source, _length)
- "RMA" => ta.rma (_source, _length)
- "WMA" => ta.wma (_source, _length)
- "VWMA" => ta.vwma(_source, _length)
- alarm(_osc, _message) =>
- alert(syminfo.ticker + ' ' + _osc + ' : ' + _message + ', price (' + str.tostring(close, format.mintick) + ')')
- //Conditional Sampling EMA Function
- Cond_EMA(x, cond, n) =>
- var val = array.new_float(0)
- var ema_val = array.new_float(1)
- if cond
- array.push(val, x)
- if array.size(val) > 1
- array.remove(val, 0)
- if na(array.get(ema_val, 0))
- array.fill(ema_val, array.get(val, 0))
- array.set(ema_val, 0, (array.get(val, 0) - array.get(ema_val, 0)) * (2 / (n + 1)) + array.get(ema_val, 0))
- EMA = array.get(ema_val, 0)
- EMA
- //Conditional Sampling SMA Function
- Cond_SMA(x, cond, n) =>
- var vals = array.new_float(0)
- if cond
- array.push(vals, x)
- if array.size(vals) > n
- array.remove(vals, 0)
- SMA = array.avg(vals)
- SMA
- //Standard Deviation Function
- Stdev(x, n) =>
- math.sqrt(Cond_SMA(math.pow(x, 2), 1, n) - math.pow(Cond_SMA(x, 1, n), 2))
- //Range Size Function
- rng_size(x, scale, qty, n) =>
- ATR = Cond_EMA(ta.tr(true), 1, n)
- AC = Cond_EMA(math.abs(x - x[1]), 1, n)
- SD = Stdev(x, n)
- rng_size = scale == 'Pips' ? qty * 0.0001 : scale == 'Points' ? qty * syminfo.pointvalue : scale == '% of Price' ? close * qty / 100 : scale == 'ATR' ? qty * ATR : scale == 'Average Change' ? qty * AC : scale == 'Standard Deviation' ? qty * SD : scale == 'Ticks' ? qty * syminfo.mintick : qty
- rng_size
- //Two Type Range Filter Function
- rng_filt(h, l, rng_, n, type, smooth, sn, av_rf, av_n) =>
- rng_smooth = Cond_EMA(rng_, 1, sn)
- r = smooth ? rng_smooth : rng_
- var rfilt = array.new_float(2, (h + l) / 2)
- array.set(rfilt, 1, array.get(rfilt, 0))
- if type == 'Type 1'
- if h - r > array.get(rfilt, 1)
- array.set(rfilt, 0, h - r)
- if l + r < array.get(rfilt, 1)
- array.set(rfilt, 0, l + r)
- if type == 'Type 2'
- if h >= array.get(rfilt, 1) + r
- array.set(rfilt, 0, array.get(rfilt, 1) + math.floor(math.abs(h - array.get(rfilt, 1)) / r) * r)
- if l <= array.get(rfilt, 1) - r
- array.set(rfilt, 0, array.get(rfilt, 1) - math.floor(math.abs(l - array.get(rfilt, 1)) / r) * r)
- rng_filt1 = array.get(rfilt, 0)
- hi_band1 = rng_filt1 + r
- lo_band1 = rng_filt1 - r
- rng_filt2 = Cond_EMA(rng_filt1, rng_filt1 != rng_filt1[1], av_n)
- hi_band2 = Cond_EMA(hi_band1, rng_filt1 != rng_filt1[1], av_n)
- lo_band2 = Cond_EMA(lo_band1, rng_filt1 != rng_filt1[1], av_n)
- rng_filt = av_rf ? rng_filt2 : rng_filt1
- hi_band = av_rf ? hi_band2 : hi_band1
- lo_band = av_rf ? lo_band2 : lo_band1
- [hi_band, lo_band, rng_filt]
- ma_function(source, length, type) =>
- if type == 'RMA'
- ta.rma(source, length)
- else if type == 'SMA'
- ta.sma(source, length)
- else if type == 'EMA'
- ta.ema(source, length)
- else if type == 'WMA'
- ta.wma(source, length)
- else if type == 'HMA'
- if(length<2)
- ta.hma(source,2)
- else
- ta.hma(source, length)
- else
- ta.vwma(source, length)
- respect_expiry_count = input.bool (false, "", group='========= Indicator Setup =========', inline='expiry')
- signalexpiry = input.int(defval=3, title='Signal Expiry Candle Count',group='========= Indicator Setup =========', inline='expiry')
- alternatesignal = input.bool (true, "Alternate Signal", group='========= Indicator Setup =========', inline='alternate')
- showdashboard = input.bool (true, "Show Dashboard", group='========= Indicator Setup =========',inline='respectema')
- string i_tab1Ypos = input.string('bottom', 'Dashboard Position',group='========= Indicator Setup =========', inline='dashboard', options=['top', 'middle', 'bottom'])
- string i_tab1Xpos = input.string('right', '', inline='dashboard', group='========= Indicator Setup =========',options=['left', 'center', 'right'])
- //candlecount = input.int(defval=3, title='Candle Count', group='cc', inline='cc',tooltip = "Max number of candles to wait for leading and confirmation indicators to generaate signal")
- ///////////////////////////////////////////////
- ///// Signal filters
- /////////////////////////////////////////////
- leadingindicator = input.string(title="Leading Indicator", defval="Range Filter",
- options=["Range Filter", "RQK", "Trend Trader","Supertrend","Ichimoku Cloud","SuperIchi","VMC","Donchian Trend Ribbon","Stochastic","RSI","VWAP","CCI","2 EMA Cross","3 EMA Cross","B-Xtrender","Bull Bear Power Trend","BB Oscillator","Trend Meter","Chandelier Exit","DMI (Adx)","Parabolic SAR (PSAR)","MACD","SSL Channel","Waddah Attar Explosion","Chaikin Money Flow","Vortex Index","Schaff Trend Cycle (STC)","Awesome Oscillator","Volatility Oscillator","Wolfpack Id","QQE Mod","Hull Suite"], group='========= Main Indicator (signal) =========', inline='li')
- ema_tooltip = "EMA filter for confirmation.\n\n Validates Long signal if price is above the EMA FILTER level, and validates Short signal if price is below the EMA FILTER level. \n\nDefault is 200, you can change that to meet your requiremnt."
- respectema = input.bool (false, "EMA Filter", group='========= Confirmation Indicators (filter) =========', inline='respectema')
- respectemaperiod = input.int(defval=200, minval=1, title='', group='========= Confirmation Indicators (filter) =========', inline='respectema', tooltip=ema_tooltip)
- ema2_tooltip = "Generates Long signal if Fast EMA cross above Slow EMA.\n\n Generates Short signal when Fast EMA cross below the Slow EMA.\n\n Default values are 50 and 200. you can change that to meet your requirement."
- respect2ma = input.bool (false, "2 EMA Cross : ", group='========= Confirmation Indicators (filter) =========', inline='2ma')
- respect2maperiod_1 = input.int(defval=50, title='',group='========= Confirmation Indicators (filter) =========', inline='2ma')
- respect2maperiod_2 = input.int(defval=200, title='',group='========= Confirmation Indicators (filter) =========', inline='2ma',tooltip=ema2_tooltip)
- ema3_tooltip = "Generates Long signal if first EMA (Fastest) cross above 2nd and 3rd EMA and 2nd EMA cross above 3rd EMA.\n\n Generates Short signal if first EMA (Fastest) cross below 2nd and 3rd EMA and 2nd EMA cross below 3rd EMA .\n\n Default values are 9,21 and 55. you can change that to meet your requirement."
- respect3ma = input.bool (false, "3 EMA Cross : ", group='========= Confirmation Indicators (filter) =========', inline='3ma',tooltip=ema3_tooltip)
- respect3maperiod_1 = input.int(defval=9, title='',group='========= Confirmation Indicators (filter) =========', inline='3ma',tooltip=ema3_tooltip)
- respect3maperiod_2 = input.int(defval=21, title='',group='========= Confirmation Indicators (filter) =========', inline='3ma',tooltip=ema3_tooltip)
- respect3maperiod_3 = input.int(defval=55, title='',group='========= Confirmation Indicators (filter) =========', inline='3ma',tooltip=ema3_tooltip)
- respectrf = input.bool (false, "Range Filter", group='========= Confirmation Indicators (filter) =========', inline='rf')
- rftype = input.string(title="", defval="Default", options=["Default","DW"], group='========= Confirmation Indicators (filter) =========', inline='rf')
- respectrqk = input.bool (true, "RQK", group='========= Confirmation Indicators (filter) =========', inline='rqk')
- respectst = input.bool (false, "SuperTrend", group='========= Confirmation Indicators (filter) =========', inline='st')
- respectdonchian = input.bool (false, "Donchian Trend Ribbon", group='========= Confirmation Indicators (filter) =========', inline='donchian')
- respectichi = input.bool (false, "Ichimoku Cloud", group='========= Confirmation Indicators (filter) =========', inline='ichi')
- //ichitype = input.string(title="", defval="Standard", options=["Standard", "Price above cloud","Conversion and baseline crossover", "Lagging Span above cloud","Leading cloud green/rred"], group='========= Confirmation Indicators (filter) =========', inline='ichi',tooltip="Ichimoku Cloud Conditions: \n \n Standarrd \n\n When all the 4 conditions are satisfied \n\n 2. Candle above cloud \n \n 3. Converstion Line above base line \n \n 4. Leading 26 bar cloud is green \n \n 5. lagging span is above the cloud")
- respectsuperichi = input.bool (false, "SuperIchi", group='========= Confirmation Indicators (filter) =========', inline='ichi',tooltip="Ichimoku Cloud Conditions: \n \n 1. Candle above cloud \n \n 2. Converstion Line above base line \n \n 3. Leading 26 bar cloud is green \n \n 4. lagging span is above the cloud")
- respectbx = input.bool (false, "B-Xtrender", group='========= Confirmation Indicators (filter) =========', inline='bx')
- bxtype = input.string(title="", defval="Short and Long term trend", options=["Short and Long term trend","Short Term trend"], group='========= Confirmation Indicators (filter) =========', inline='bx', tooltip = "Short term trend:\n\n===================== \n\n For buy signal the short term trend line must turn green, and for the sell signal, the short term trend line must turn red. \n\n Short and Long term trend: \n\n===================== \n\n For buy signal, the short term trend must change from red to green and long term trend cross above zero line, for Sell signal the short term trend must turn red and long term trend line cross down the zero line..")
- respectbbpt = input.bool (false, "Bull bear Power Trend", group='========= Confirmation Indicators (filter) =========', inline='bbpt')
- bbpttype = input.string(title="", defval="Follow Trend", options=["Follow Trend","Without Trend"], group='========= Confirmation Indicators (filter) =========', inline='bbpt', tooltip = "Follow Trend:\n\n===================== \n\n Buy signal will be validated if the BBPT trend line is above 2, and Sell signal will be validated if BBPT trend line is below -2. \n\n Without Trend: \n\n===================== \n\n Ignore the BBPT trend line.")
- respectvwap = input.bool (false, "VWAP", group='========= Confirmation Indicators (filter) =========', inline='vwap')
- respectbbosc = input.bool (false, "BB Oscillator", group='========= Confirmation Indicators (filter) =========', inline='bbosc')
- bbtype = input.string(title="", defval="Entering Lower/Upper Band", options=["Entering Lower/Upper Band","Exiting Lower/Upper Band"], group='========= Confirmation Indicators (filter) =========', inline='bbosc')
- respecttm = input.bool (false, "Trend Meter", group='========= Confirmation Indicators (filter) =========', inline='tm')
- tmtype = input.string(title="", defval="3 TM and 2 TB change to same color", options=["3 TM change to same color", "3 TM and 2 TB change to same color", "3 TM, 2 TB and Wavetrend change to same color"], group='========= Confirmation Indicators (filter) =========', inline='tm')
- respectce = input.bool (false, "Chandelier Exit", group='========= Confirmation Indicators (filter) =========', inline='ce')
- respectcci = input.bool (false, "CCI", group='========= Confirmation Indicators (filter) =========', inline='cci')
- //ccitype = input.string(title="", defval="Standard", options=["Standard"], group='========= Confirmation Indicators (filter) =========', inline='cci')
- respectao = input.bool (false, "Awesome Oscillator", group='========= Confirmation Indicators (filter) =========', inline='ao')
- aotype = input.string(title="", defval="Zero Line Cross", options=["Zero Line Cross","AC Zero Line Cross","AC Momentum Bar"], group='========= Confirmation Indicators (filter) =========', inline='ao', tooltip = "Zero Line Cross:\n\n If AO value cross the zero line up, Buy signal will be generated, and if AO value cross down the zero line, sell signal will be generated.")
- respectadx = input.bool (false, "DMI (ADx)", group='========= Confirmation Indicators (filter) =========', inline='adx')
- adxtype = input.string(title="", defval="Adx & +Di -Di", options=["Adx Only","Adx & +Di -Di", "Advance"], group='========= Confirmation Indicators (filter) =========', inline='adx', tooltip = "Adx Only:\n\n If Adx value is above the defined level. \n\n Adx & +Di -DI :\n\n When Adx value is above the defined level and croseeover between +di and -di. Di will determine the direction of the movement. \n\n Advance: ")
- respectsar = input.bool (false, "Parabolic SAR (PSAR)", group='========= Confirmation Indicators (filter) =========', inline='sar')
- respectwae = input.bool (false, "Waddah Attar Explosion", group='========= Confirmation Indicators (filter) =========', inline='wae')
- vo_tooltip = "Volatility Oscillator: \n\n ======================= \n\n If the spike line is above the upper line, buy signal is generated (or validated). \n\n If the spike line is below the lower line, sell signal is generated (or validated)."
- respectvo = input.bool (false, "Volatility Oscillator", group='========= Confirmation Indicators (filter) =========', inline='vo', tooltip = vo_tooltip)
- respectdv = input.bool (false, "Damiani Volatility (DV)", group='========= Confirmation Indicators (filter) =========', inline='dv')
- dvtype = input.string(title="", defval="Simple", options=["Simple", "Threshold","10p Difference"], group='========= Confirmation Indicators (filter) =========', inline='dv', tooltip = "Simple\n Volatility is green. \nThreshold\n Volatility green and >1.1")
- stochtooltip="CrossOver:\n------------------\n\n CrossOver of K and D line at any level. \n\n CrossOver in OB & OS levels:\n\n Generate buy signal if crossover happens in oversold area and crossing up oversold level.\n\n Generate sell signal on crossover in overbought area and cross down upper level. \n------------------\n\n %K above/below %D\n------------------\n: Generate Buy signal or validate other signal if %K is above %D and opposite for Sell Signal."
- respectstochastic = input.bool (false, "Stochastic", group='========= Confirmation Indicators (filter) =========', inline='stoch')
- stochtype = input.string(title="", defval="CrossOver", options=["CrossOver", "CrossOver in OB & OS levels","%K above/below %D"],tooltip=stochtooltip, group='========= Confirmation Indicators (filter) =========', inline='stoch')
- rsi_tooltip = "RSI MA Cross:\n=============\n Generate buy signal when RSI cross up RSI MA line and sell signal when RSI cross down RSI MA line.\n\nRSI Exits OB/OS zones:\n==================\n Generate Buy signal when RSI crosses down the overbough zone and sell signal when RSI crosses up the oversold zone.\n\nRSI Level:\n==========\nGenerate buy signal if RSI cross above the specific level and sell signal when RSI crossdown the level.\n\n\n +++++\nYou can change the setting to define the OB/OS and MidLine Levels"
- respectrsi = input.bool (false, "RSI", group='========= Confirmation Indicators (filter) =========', inline='rsi')
- rsitype = input.string(title="", defval="RSI MA Cross", options=["RSI MA Cross", "RSI Exits OB/OS zones","RSI Level"], tooltip=rsi_tooltip, group='========= Confirmation Indicators (filter) =========', inline='rsi')
- rsima_tooltip = "RSI MA Direction:\n=============\n The buy and sell signal will respect the RSI MA direction. For buy signal, the RSI MA should be increasing or same compared to previous RSI MA. \n\n for SHORT, the RSI MA should be same or decreasing compared to last RSI MA"
- respectrsima = input.bool (false, "RSI MA Direction", group='========= Confirmation Indicators (filter) =========', inline='rsi2',tooltip=rsima_tooltip)
- rsilimit_tooltip = "RSI Limit:\n=============\n This is to allow you to set limit for the RSI value for long and short. default value for long is 40, which means if the RSI is 40 or above, only then BUY signal will be validated. \n\nfor short if RSI is 60 or less, only then sell signal willbe validated."
- respectrsilimit = input.bool (false, "RSI Limit : ", group='========= Confirmation Indicators (filter) =========', inline='rsi3',tooltip=rsilimit_tooltip)
- rsilimitup = input.int(40, title="Long",inline='rsi3', group='========= Confirmation Indicators (filter) =========')
- rsilimitdown = input.int(60, title="short",inline='rsi3', group='========= Confirmation Indicators (filter) =========')
- rsimalimit_tooltip = "RSI MA Limit:\n=============\n This is to allow you to set limit for the RSI MA value for long and short. default value for long is 40, which means if the RSI MA is 40 or above, only then BUY signal will be validated. \n\nfor short if RSI MA is 60 or less, only then sell signal willbe validated."
- respectrsimalimit = input.bool (false, "RSI MA Limit : ", group='========= Confirmation Indicators (filter) =========', inline='rsi4',tooltip=rsimalimit_tooltip)
- rsimalimitup = input.int(40, title="Long",inline='rsi4', group='========= Confirmation Indicators (filter) =========')
- rsimalimitdown = input.int(60, title="short",inline='rsi4', group='========= Confirmation Indicators (filter) =========')
- macdtooltip="MACD Crossover:\n------------------\n\n CrossOver of MACD and the Signal line. Generates Long signal when MACD cross up Signal line and Short signal when MACD cross down Signal Line. . \n\n Zero line crossover:\n------------------\n\n Generate buy signal when MACD cross up the zero line and Sell signal when MACD cross down the zero line."
- respectmacd = input.bool (false, "MACD", group='========= Confirmation Indicators (filter) =========', inline='macd')
- macdtype = input.string(title="", defval="MACD Crossover", options=["MACD Crossover", "Zero line crossover"],tooltip=macdtooltip, group='========= Confirmation Indicators (filter) =========', inline='macd')
- respectssl = input.bool (false, "SSL Channel", group='========= Confirmation Indicators (filter) =========', inline='ssl')
- respectstc = input.bool (false, "Schaff Trend Cycle (STC)", group='========= Confirmation Indicators (filter) =========', inline='stc')
- respectchaikin = input.bool (false, "Chaikin Money Flow", group='========= Confirmation Indicators (filter) =========', inline='chaikin')
- respectvol = input.bool (false, "Volume", group='========= Confirmation Indicators (filter) =========', inline='volume')
- volumetype = input.string(title="", defval="Simple", options=["Simple", "Delta"], group='========= Confirmation Indicators (filter) =========', inline='volume', tooltip = "Simple volume is comparing the up/down volme with previous candle. \nVolume delta will compare the delta or difference between up and down volume with previous candle.\nExample:\n up volume = 100 \n Down volume=-1100\n Delta = -1000\n Satisfy the bear flag condition if previous -ve delta is lower")
- respectwolf = input.bool (false, "Wolfpack Id", group='========= Confirmation Indicators (filter) =========', inline='wolf')
- respectqqe = input.bool (false, "QQE Mod", group='========= Confirmation Indicators (filter) =========', inline='qqe')
- qqetype = input.string(title="", defval="Line", options=["Line", "Bar","Line & Bar"], group='========= Confirmation Indicators (filter) =========', inline='qqe', tooltip = "Line: signal generated when QQE line is above or below 0. \nBar: when Blue bar is above 0 or Red bar below 0 \nLine & Bar: Both Bar and Line to be above(bullist) or below (bearish) 0" )
- respecthull = input.bool (false, "Hull Suite",group='========= Confirmation Indicators (filter) =========', inline='hull')
- respectvi = input.bool (false, "Vortex Indicator",group='========= Confirmation Indicators (filter) =========', inline='vi')
- vitype = input.string(title="", defval="Simple", options=["Simple", "Advance"],group='========= Confirmation Indicators (filter) =========', inline='vi',
- tooltip = "Simple\n Green Cross Red. \Advance\n vipcondition := vip > vim and vip > viupper and vip > vip[1] and vim < vim[1] and vim[1] <= vilower and vip[1] >= viupper
- vimcondition := vip < vim and vim > viupper and vim > vim[1] and vip < vip [1] and vip[1] <= vilower and vim [1] >= viupper ")
- /////////////////////////////////////////////////////////////////////////
- // Switch Board
- ////////////////////////////////////////////////////////////////////////
- switch_ema = input.bool (false, "EMA", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch1')
- switch_supportresistance = input.bool (false, "S/R", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch1')
- switch_poi = input.bool (true, "Supply/Demand Zone", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch1')
- switch_sar = input.bool (false, "PSAR", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch1')
- switch_ichi = input.bool (false, "Ichimoku Cloud", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch2')
- switch_superichi = input.bool (false, "SuperIchi", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch2')
- switch_vwap = input.bool (false, "VWAP", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch3')
- switch_supertrend = input.bool (false, "Supertrend", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch2')
- switch_rangefilter = input.bool (false, "Range Filter", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch2')
- switch_rangefilter2 = input.bool (false, "Range Filter DW", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch2')
- switch_atr = input.bool (false, "ATR", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch2')
- switch_stc = input.bool (false, "STC", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch3')
- switch_pvsra = input.bool (true, "PVSRA", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch3')
- switch_vectorzone = input.bool (false, "Liquidity Zone", group='-------Switch Board (Turn On/Off Overlay Indicators)-------', inline='Switch3')
- bool show_markets = input.bool(true, group='-------Switch Board (Turn On/Off Overlay Indicators)-------', title='Show Market Sessions?', tooltip='Turn on or off all market sessions')
- string rectStyle = input.string(group='-------Switch Board (Turn On/Off Overlay Indicators)-------', defval='Dashed', title='Line style of Market Session hi/lo line', options=['Dashed', 'Solid'])
- sessLineStyle = line.style_dashed
- bool show_markets_weekends = input.bool(false, group='-------Switch Board (Turn On/Off Overlay Indicators)-------', 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')
- /////////////////////////////////////////////////////////////////////////
- // EMA Selection
- ////////////////////////////////////////////////////////////////////////
- len1bool = input.bool(true,'',group='-------------------------MAs line-------------------------',inline='len1')
- len1 = input.int(5, title='MA 1',group='-------------------------MAs line-------------------------',inline='len1')
- string ma_1_type = input.string(defval='EMA', title='Type', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='len1',group='-------------------------MAs line-------------------------')
- color ma_1_colour = input.color(color.rgb(254, 234, 74, 0), '', inline='len1',group='-------------------------MAs line-------------------------')
- len2bool = input.bool(true,'',group='-------------------------MAs line-------------------------',inline='len2')
- len2 = input.int(13, minval=1, title='MA 2',group='-------------------------MAs line-------------------------',inline='len2')
- string ma_2_type = input.string(defval='EMA', title='Type', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='len2',group='-------------------------MAs line-------------------------')
- color ma_2_colour = input.color(color.rgb(253, 84, 87, 0), '', inline='len2',group='-------------------------MAs line-------------------------')
- len3bool = input.bool(false,'',group='-------------------------MAs line-------------------------',inline='len3')
- len3 = input.int(20, minval=1, title='MA 3',group='-------------------------MAs line-------------------------',inline='len3')
- string ma_3_type = input.string(defval='EMA', title='Type', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='len3',group='-------------------------MAs line-------------------------')
- color ma_3_colour = input.color(color.new(color.aqua, 0), '', inline='len3',group='-------------------------MAs line-------------------------')
- len4bool = input.bool(true,'',group='-------------------------MAs line-------------------------',inline='len4')
- len4 = input.int(50, minval=1, title='MA 4',group='-------------------------MAs line-------------------------',inline='len4')
- string ma_4_type = input.string(defval='EMA', title='Type', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='len4',group='-------------------------MAs line-------------------------')
- color ma_4_colour = input.color(color.new(color.blue, 0), '', inline='len4',group='-------------------------MAs line-------------------------')
- len5bool = input.bool(true,'',group='-------------------------MAs line-------------------------',inline='len5')
- len5 = input.int(200, minval=1, title='MA 5',group='-------------------------MAs line-------------------------',inline='len5')
- string ma_5_type = input.string(defval='EMA', title='Type', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='len5',group='-------------------------MAs line-------------------------')
- color ma_5_colour = input.color(color.new(color.white, 0), '', inline='len5',group='-------------------------MAs line-------------------------')
- //ema1 = ta.ema(close, len1)
- ema1 = request.security(syminfo.tickerid, timeframe.period, ma_function(close, len1, ma_1_type))
- ema2 = request.security(syminfo.tickerid, timeframe.period, ma_function(close, len2, ma_2_type))
- ema3 = request.security(syminfo.tickerid, timeframe.period, ma_function(close, len3, ma_3_type))
- ema4 = request.security(syminfo.tickerid, timeframe.period, ma_function(close, len4, ma_4_type))
- ema5 = request.security(syminfo.tickerid, timeframe.period, ma_function(close, len5, ma_5_type))
- plot(len1bool and switch_ema ? ema1:na, color=ma_1_colour, linewidth=2, title='MA 1')
- plot(len2bool and switch_ema? ema2:na, color=ma_2_colour, linewidth=2, title='MA 2')
- plot(len3bool and switch_ema? ema3:na, color=ma_3_colour, linewidth=2, title='MA 3')
- plot(len4bool and switch_ema? ema4:na, color=ma_4_colour, linewidth=2, title='MA 4')
- plot(len5bool and switch_ema? ema5:na, color=ma_5_colour, linewidth=2, title='MA 5')
- ////////////////////////////////////////////////////////////////////////////
- //////////// 2EMA cross
- ////////////////////////////////////////////////////////////////////////////
- first_2ema = ta.ema(close, respect2maperiod_1)
- second_2ema = ta.ema(close, respect2maperiod_2)
- ////////////////////////////////////////////////////////////////////////////
- //////////// 3EMA cross
- ////////////////////////////////////////////////////////////////////////////
- first_3ema = ta.ema(close, respect3maperiod_1)
- second_3ema = ta.ema(close, respect3maperiod_2)
- third_3ema = ta.ema(close, respect3maperiod_3)
- //////////////////////////////////////////////////////////////////////////
- // Range Filter
- //////////////////////////////////////////////////////////////////////////
- //switch_rangefilter = input.bool (true, "Show Range Filter Signals", group='-------------------------Range Filter-------------------------')
- showrfline = input.bool (true, "Show RF line", group='-------------------------Range Filter-------------------------')
- // Source
- src = input.source(defval=close, title='Source', group='-------------------------Range Filter-------------------------',inline = 'rf')
- // Sampling Period
- // Settings for 5min chart, BTCUSDC. For Other coin, change the paremeters
- per = input.int(defval=100, minval=1, title='Period', group='-------------------------Range Filter-------------------------',inline = 'rf')
- // Range Multiplier
- mult = input.float(defval=3.0, minval=0.1, title='Multiplier', group='-------------------------Range Filter-------------------------',inline = 'rf')
- // Smooth Average Range
- smoothrng(x, t, m) =>
- wper = t * 2 - 1
- avrng = ta.ema(math.abs(x - x[1]), t)
- smoothrng = ta.ema(avrng, wper) * m
- smoothrng
- smrng = smoothrng(src, per, mult)
- // Range Filter
- rngfilt(x, r) =>
- rngfilt = x
- rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r : x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
- rngfilt
- filt = rngfilt(src, smrng)
- // Filter Direction
- upward = 0.0
- upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
- downward = 0.0
- downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])
- // Target Bands
- hband = filt + smrng
- lband = filt - smrng
- // Colors
- ///////////////////////////////
- ////// RF2
- ///////////////////////////////
- //Filter Type
- f_type = input.string(defval='Type 1', options=['Type 1', 'Type 2'], title='Filter Type')
- //Movement Source
- mov_src = input.string(defval='Close', options=['Wicks', 'Close'], title='Movement Source')
- //Range Size Inputs
- rng_qty = input.float(defval=2.618, minval=0.0000001, title='Range Size')
- rng_scale = input.string(defval='Average Change', options=['Points', 'Pips', 'Ticks', '% of Price', 'ATR', 'Average Change', 'Standard Deviation', 'Absolute'], title='Range Scale')
- //Range Period
- rng_per = input.int(defval=14, minval=1, title='Range Period (for ATR, Average Change, and Standard Deviation)')
- //Range Smoothing Inputs
- smooth_range = input(defval=true, title='Smooth Range')
- smooth_per = input.int(defval=27, minval=1, title='Smoothing Period')
- //Filter Value Averaging Inputs
- av_vals = input(defval=false, title='Average Filter Changes')
- av_samples = input.int(defval=2, minval=1, title='Number Of Changes To Average')
- //-----------------------------------------------------------------------------------------------------------------------------------------------------------------
- //Definitions
- //-----------------------------------------------------------------------------------------------------------------------------------------------------------------
- //High And Low Values
- h_val = mov_src == 'Wicks' ? high : close
- l_val = mov_src == 'Wicks' ? low : close
- //Range Filter Values
- [h_band, l_band, filt2] = rng_filt(h_val, l_val, rng_size((h_val + l_val) / 2, rng_scale, rng_qty, rng_per), rng_per, f_type, smooth_range, smooth_per, av_vals, av_samples)
- //Direction Conditions
- var fdir2 = 0.0
- fdir2 := filt2 > filt2[1] ? 1 : filt2 < filt2[1] ? -1 : fdir2
- rfupward = fdir2 == 1 ? 1 : 0
- rfdownward= fdir2 == -1 ? 1 : 0
- //-----------------------------------------------------------------------------------------------------------------------------------------------------------------
- //color and switchboard rf
- //-----------------------------------------------------------------------------------------------------------------------------------------------------------------
- filtcolor = upward > 0 ? color.lime : downward > 0 ? color.red : color.orange
- filt2_color = rfupward ? #05ff9b : rfdownward ? #ff0583 : #cccccc
- filttype = string(na)
- if rftype == "Default"
- filttype := "filt"
- else if rftype == "DW"
- filttype := "filt2"
- filtplot = plot(switch_rangefilter and showrfline?filt:na, color=filtcolor, linewidth=2, title='Range Filter')
- filtplot2 = plot(switch_rangefilter2 ?filt2:na, color=filt2_color, linewidth=2, title='Range Filter')
- ////////////////////////////////
- /////Trend Trader
- //////////////////////////////////
- ttgroupname = '------------------------Trend Trader------------------------'
- ttLength = input.int(21, minval=1,group=ttgroupname)
- ttMultiplier = input.float(3, minval=0.000001,group=ttgroupname)
- avgTR = ta.wma(ta.atr(1), ttLength)
- highestC = ta.highest(ttLength)
- lowestC = ta.lowest(ttLength)
- hiLimit = highestC[1] - avgTR[1] * ttMultiplier
- loLimit = lowestC[1] + avgTR[1] * ttMultiplier
- ret = 0.0
- pos = 0.0
- ret:= close > hiLimit and close > loLimit ? hiLimit :
- close < loLimit and close < hiLimit ? loLimit : nz(ret[1], close)
- pos:= close > ret ? 1 :close < ret ? -1 : nz(pos[1], 0)
- if pos != pos[1] and pos == 1
- alert("Color changed - Buy", alert.freq_once_per_bar_close)
- if pos != pos[1] and pos == -1
- alert("Color changed - Sell", alert.freq_once_per_bar_close)
- ttlong = close > ret
- ttshort = close < ret
- ////////////////////////////////
- /// RQK
- ////////////////////////////////
- rqkgroupname = '------------------------RQK------------------------'
- rqksrc = input.source(close, 'Source', group=rqkgroupname)
- h2 = input.float(8., 'Lookback Window', minval=3., tooltip='The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50', group=rqkgroupname)
- r = input.float(8., 'Relative Weighting', step=0.25, group=rqkgroupname, tooltip='Relative weighting of time frames. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel. Recommended range: 0.25-25')
- x_0 = input.int(25, "Start Regression at Bar", group=rqkgroupname, tooltip='Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit. Recommended range: 5-25')
- smoothColors = input.bool(false, "Smooth Colors", group=rqkgroupname, tooltip="Uses a crossover based mechanism to determine colors. This often results in less color transitions overall.", inline='1')
- lag = input.int(2, "Lag", group=rqkgroupname, tooltip="Lag for crossover detection. Lower values result in earlier crossovers. Recommended range: 1-2", inline='1')
- size = array.size(array.from(rqksrc)) // size of the data series
- // Further Reading:
- // The Kernel Cookbook: Advice on Covariance functions. David Duvenaud. Published June 2014.
- // Estimation of the bandwidth parameter in Nadaraya-Watson kernel non-parametric regression based on universal threshold level. Ali T, Heyam Abd Al-Majeed Hayawi, Botani I. Published February 26, 2021.
- kernel_regression(_rqksrc, _size, _h2) =>
- float _currentWeight = 0.
- float _cumulativeWeight = 0.
- for i = 0 to _size + x_0
- y = _rqksrc[i]
- w = math.pow(1 + (math.pow(i, 2) / ((math.pow(_h2, 2) * 2 * r))), -r)
- _currentWeight += y*w
- _cumulativeWeight += w
- _currentWeight / _cumulativeWeight
- // Estimations
- yhat1 = kernel_regression(rqksrc, size, h2)
- yhat2 = kernel_regression(rqksrc, size, h2-lag)
- // Rates of Change
- bool wasBearish = yhat1[2] > yhat1[1]
- bool wasBullish = yhat1[2] < yhat1[1]
- bool isBearish = yhat1[1] > yhat1
- bool isBullish = yhat1[1] < yhat1
- bool isBearishChange = isBearish and wasBullish
- bool isBullishChange = isBullish and wasBearish
- // Crossovers
- bool isBullishCross = ta.crossover(yhat2, yhat1)
- bool isBearishCross = ta.crossunder(yhat2, yhat1)
- bool isBullishSmooth = yhat2 > yhat1
- bool isBearishSmooth = yhat2 < yhat1
- // Colors
- color c_bullish = input.color(#3AFF17, 'Bullish Color', group='Colors')
- color c_bearish = input.color(#FD1707, 'Bearish Color', group='Colors')
- color colorByCross = isBullishSmooth ? c_bullish : c_bearish
- color colorByRate = isBullish ? c_bullish : c_bearish
- color plotColor = smoothColors ? colorByCross : colorByRate
- rqkuptrend = yhat1[1] < yhat1
- rqkdowntrend = yhat1[1] > yhat1
- ////////////////////////////////
- ///// Super Trend
- //////////////////////////////
- Periods = input(title='ATR Period', defval=10, group='--------------------SuperTrend----------------------------')
- stsrc = input(hl2, title='Source', group='--------------------SuperTrend----------------------------')
- Multiplier = input.float(title='ATR Multiplier', step=0.1, defval=3.0, group='--------------------SuperTrend----------------------------')
- changeATR = input(title='Change ATR Calculation Method ?', defval=true, group='--------------------SuperTrend----------------------------')
- showsignals = input(title='Show Buy/Sell Signals ?', defval=true, group='--------------------SuperTrend----------------------------')
- highlighting = input(title='Highlighter On/Off ?', defval=true, group='--------------------SuperTrend----------------------------')
- statr2 = ta.sma(ta.tr, Periods)
- statr = changeATR ? ta.atr(Periods) : statr2
- stup = stsrc - Multiplier * statr
- up1 = nz(stup[1], stup)
- stup := close[1] > up1 ? math.max(stup, up1) : stup
- dn = stsrc + Multiplier * statr
- dn1 = nz(dn[1], dn)
- dn := close[1] < dn1 ? math.min(dn, dn1) : dn
- sttrend = 1
- sttrend := nz(sttrend[1], sttrend)
- sttrend := sttrend == -1 and close > dn1 ? 1 : sttrend == 1 and close < up1 ? -1 : sttrend
- upPlot = plot(sttrend == 1 and switch_supertrend ? stup : na, title='Up Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.green, 0))
- stbuySignal = sttrend == 1 and sttrend[1] == -1
- plotshape(stbuySignal and switch_supertrend ? stup : na, title='UpTrend Begins', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(color.green, 0))
- //plotshape(stbuySignal and showsignals ? up : na, title='Buy', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.green, 0), textcolor=color.new(color.white, 0))
- dnPlot = plot(sttrend != 1 and switch_supertrend ? dn : na , title='Down Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.red, 0))
- stsellSignal = sttrend == -1 and sttrend[1] == 1
- plotshape(stsellSignal and switch_supertrend ? dn : na, title='DownTrend Begins', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(color.red, 0))
- //plotshape(sellSignal and showsignals ? dn : na, title='Sell', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.red, 0), textcolor=color.new(color.white, 0))
- //mPlot = plot(showst ? ohlc4:na, title='', style=plot.style_circles, linewidth=0)
- //////////////////////////////////////////////
- ////// Ichimoku
- /////////////////////////////////////////////
- conversionPeriods = input.int(9, minval=1, title="Conversion Line Length")
- basePeriods = input.int(26, minval=1, title="Base Line Length")
- laggingSpan2Periods = input.int(52, minval=1, title="Leading Span B Length")
- displacement = input.int(26, minval=1, title="Lagging Span")
- donchian(len) => math.avg(ta.lowest(len), ta.highest(len))
- conversionLine = donchian(conversionPeriods)
- baseLine = donchian(basePeriods)
- leadLine1 = math.avg(conversionLine, baseLine)
- leadLine2 = donchian(laggingSpan2Periods)
- ChikouSpan = close[25] + (close - close[25])
- lead1 = leadLine1[displacement - 1]
- lead2 = leadLine2[displacement - 1]
- plot(switch_ichi?conversionLine:na, color=#2962FF, title="Conversion Line",linewidth = 1)
- plot(switch_ichi ? baseLine:na, color=#B71C1C, title="Base Line",linewidth = 1)
- plot(switch_ichi?close:na, offset = -displacement + 1, color=#43A047, title="Lagging Span")
- p1 = plot(switch_ichi?leadLine1:na, offset = displacement - 1, color=#A5D6A7,
- title="Leading Span A")
- p2 = plot(switch_ichi?leadLine2:na, offset = displacement - 1, color=#EF9A9A,
- title="Leading Span B")
- fill(p1, p2, color = leadLine1 > leadLine2 and switch_ichi ? color.rgb(67, 160, 71, 70) : color.rgb(244, 67, 54, 70))
- ichi_long = conversionLine > baseLine and leadLine1> leadLine2 and close >leadLine1[displacement -1] and close >leadLine2[displacement -1] and (ChikouSpan > leadLine1[50] and ChikouSpan > leadLine2[50])
- ichi_short = conversionLine < baseLine and leadLine1 < leadLine2 and close < leadLine1[displacement -1] and close < leadLine2[displacement -1] and (ChikouSpan < leadLine2[50] and ChikouSpan < leadLine1[50])
- //////////////////////////////
- ///////// SuperIchi
- /////////////////////////////
- tenkan_len = input(9,'Tenkan ',inline='tenkan')
- tenkan_mult = input(2.,'',inline='tenkan')
- kijun_len = input(26,'Kijun ',inline='kijun')
- kijun_mult = input(4.,'',inline='kijun')
- spanB_len = input(52,'Senkou Span B ',inline='span')
- spanB_mult = input(6.,'',inline='span')
- offset = input(26,'Displacement')
- //------------------------------------------------------------------------------
- avg(src,length,mult)=>
- atr = ta.atr(length)*mult
- up = hl2 + atr
- dn = hl2 - atr
- upper = 0.,lower = 0.
- upper := src[1] < upper[1] ? math.min(up,upper[1]) : up
- lower := src[1] > lower[1] ? math.max(dn,lower[1]) : dn
- os = 0,max = 0.,min = 0.
- os := src > upper ? 1 : src < lower ? 0 : os[1]
- spt = os == 1 ? lower : upper
- max := ta.cross(src,spt) ? math.max(src,max[1]) : os == 1 ? math.max(src,max[1]) : spt
- min := ta.cross(src,spt) ? math.min(src,min[1]) : os == 0 ? math.min(src,min[1]) : spt
- math.avg(max,min)
- //------------------------------------------------------------------------------
- tenkan = avg(close,tenkan_len,tenkan_mult)
- kijun = avg(close,kijun_len,kijun_mult)
- senkouA = math.avg(kijun,tenkan)
- senkouB = avg(close,spanB_len,spanB_mult)
- //------------------------------------------------------------------------------
- tenkan_css = #2157f3
- kijun_css = #ff5d00
- cloud_a = color.new(color.teal,80)
- cloud_b = color.new(color.red,80)
- chikou_css = #7b1fa2
- plot(switch_superichi?tenkan:na,'Tenkan-Sen',tenkan_css)
- plot(switch_superichi?kijun:na,'Kijun-Sen',kijun_css)
- A = plot(switch_superichi ? senkouA:na,'Senkou Span A',na,offset=offset-1)
- B = plot(switch_superichi ? senkouB:na,'Senkou Span B',na,offset=offset-1)
- fill(A,B,senkouA > senkouB and switch_superichi? cloud_a : cloud_b)
- plot(switch_superichi?close:na,'Chikou',chikou_css,offset=-offset+1,display=display.none)
- superichi_long = tenkan > kijun and senkouA> senkouB and close >senkouA[displacement -1] and close >senkouB[displacement -1] and (ChikouSpan > senkouA[50] and ChikouSpan > senkouB[50])
- superichi_short = tenkan < kijun and senkouA < senkouB and close < senkouA[displacement -1] and close < senkouB[displacement -1] and (ChikouSpan < senkouB[50] and ChikouSpan < senkouA[50])
- //////////////////////////////////
- ///////////Donchian Channel Ribbon
- ///////////////////////////////////
- donchiangroup = "-------------------------Donchian Channel Ribbon-------------------------"
- dlen = input.int(defval=15, title='Donchian Channel Period', group=donchiangroup)
- dchannel(len) =>
- float hh = ta.highest(len)
- float ll = ta.lowest(len)
- int trend = 0
- trend := close > hh[1] ? 1 : close < ll[1] ? -1 : nz(trend[1])
- trend
- dchannelalt(len, maintrend) =>
- float hh = ta.highest(len)
- float ll = ta.lowest(len)
- int trend = 0
- trend := close > hh[1] ? 1 : close < ll[1] ? -1 : nz(trend[1])
- maintrend == 1 ? trend == 1 ? #00FF00ff : #00FF009f : maintrend == -1 ? trend == -1 ? #FF0000ff : #FF00009f : na
- maintrend = dchannel(dlen)
- donchian_long = maintrend == 1 ? true:na
- donchian_short = maintrend == -1 ? true:na
- ////////////////////////////////
- // DMI code
- ////////////////////////////////
- adxlen = input(5, title="ADX", group='-------------------------DMI-------------------------', inline='dmi')
- keyLevel = input(20, title='ADX limit',group='-------------------------DMI-------------------------', inline='dmi')
- dilen = input.int(10, title="DI Length",group='-------------------------DMI-------------------------', inline='dmi')
- lensig = adxlen
- upp = ta.change(high)
- downn = ta.change(low)
- plusDM = na(upp) ? na : upp > downn and upp > 0 ? upp : 0
- minusDM = na(downn) ? na : downn > upp and downn > 0 ? downn : 0
- trur = ta.rma(ta.tr, dilen)
- plus = fixnan(100 * ta.rma(plusDM, dilen) / trur)
- minus = fixnan(100 * ta.rma(minusDM, dilen) / trur)
- sum = plus + minus
- adxx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lensig)
- dirmov(dilen) =>
- up = ta.change(high)
- down = -ta.change(low)
- truerange = ta.rma(ta.tr, dilen)
- plus = fixnan(100 * ta.rma(up > down and up > 0 ? up : 0, dilen) / truerange)
- minus = fixnan(100 * ta.rma(down > up and down > 0 ? down : 0, dilen) / truerange)
- [plus, minus]
- adx(dilen, adxlen) =>
- [plus, minus] = dirmov(dilen)
- sum = plus + minus
- adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
- [adx, plus, minus]
- [adx, diplus, diminus] = adx(dilen, adxlen)
- ////////////////////////////////////////////////
- //Parabolic SAR
- ///////////////////////////////////////////////
- //showsar = input.bool (false, "Show SAR", group='-------------------------Parabolic SAR-------------------------')
- start = input.float(0.02, group='-------------------------Parabolic SAR-------------------------', inline ='sar')
- increment = input.float(0.02, group='-------------------------Parabolic SAR-------------------------', inline ='sar')
- maximum = input.float(0.2, 'Max Value', group='-------------------------Parabolic SAR-------------------------', inline ='sar')
- out = ta.sar(start, increment, maximum)
- sarcolor = if (out>close)
- color.red
- else
- color.green
- if (switch_sar )
- color.red
- else
- color.green
- plot(switch_sar ? out : na, 'ParabolicSAR', style=plot.style_cross, color=sarcolor)
- //////////////////////////////////////////////////
- ///////// CCI
- /////////////////////////////////////////////////
- ccilength = input.int(20,title="CCI Length", minval=1,inline="cci", group="---------------------- CCI ------------------------")
- ccisrc = input(hlc3, title="Source",inline="cci", group="---------------------- CCI ------------------------")
- cciupperband = input.int(100,title="Upper Band",inline="cci2", group="---------------------- CCI ------------------------")
- ccilowerband = input.int(-100,title="Lower Band",inline="cci2", group="---------------------- CCI ------------------------")
- ma = ta.sma(ccisrc, ccilength)
- cci = (ccisrc - ma) / (0.015 * ta.dev(ccisrc, ccilength))
- typeMA = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing",inline="cci4")
- smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing",inline="cci3")
- smoothingLine = ma(cci, smoothingLength, typeMA)
- // plot(smoothingLine, title="Smoothing Line", color=#f37f20, display=display.none)
- ccilong = cci > cciupperband
- ccishort = cci < ccilowerband
- ///////////////////////////////////////////////
- /////// B-Xtrender
- /////////////////////////////////////////////
- bxgroup= "---------------------- B-Xtrender ------------------------"
- short_l1 = input(5, title='Short - L1',group=bxgroup)
- short_l2 = input(20, title='Short - L2',group=bxgroup)
- short_l3 = input(15, title='Short - L3',group=bxgroup)
- long_l1 = input(5, title='Long - L1',group=bxgroup)
- long_l2 = input(10, title='Long - L2',group=bxgroup)
- shortTermXtrender = ta.rsi(ta.ema(close, short_l1) - ta.ema(close, short_l2), short_l3) - 50
- longTermXtrender = ta.rsi(ta.ema(close, long_l1), long_l2) - 50
- shortXtrenderCol = shortTermXtrender > 0 ? shortTermXtrender > shortTermXtrender[1] ? color.lime : #228B22 : shortTermXtrender > shortTermXtrender[1] ? color.red : #8B0000
- // plot(shortTermXtrender, color=shortXtrenderCol, style=plot.style_columns, linewidth=1, title='B-Xtrender Osc. - Histogram', transp=50)
- t3(src, len) =>
- xe1_1 = ta.ema(src, len)
- xe2_1 = ta.ema(xe1_1, len)
- xe3_1 = ta.ema(xe2_1, len)
- xe4_1 = ta.ema(xe3_1, len)
- xe5_1 = ta.ema(xe4_1, len)
- xe6_1 = ta.ema(xe5_1, len)
- b_1 = 0.7
- c1_1 = -b_1 * b_1 * b_1
- c2_1 = 3 * b_1 * b_1 + 3 * b_1 * b_1 * b_1
- c3_1 = -6 * b_1 * b_1 - 3 * b_1 - 3 * b_1 * b_1 * b_1
- c4_1 = 1 + 3 * b_1 + b_1 * b_1 * b_1 + 3 * b_1 * b_1
- nT3Average_1 = c1_1 * xe6_1 + c2_1 * xe5_1 + c3_1 * xe4_1 + c4_1 * xe3_1
- nT3Average_1
- maShortTermXtrender = t3(shortTermXtrender, 5)
- colShortTermXtrender = maShortTermXtrender > maShortTermXtrender[1] ? color.lime : color.red
- longXtrenderCol = longTermXtrender > 0 ? longTermXtrender > longTermXtrender[1] ? color.lime : #228B22 : longTermXtrender > longTermXtrender[1] ? color.red : #8B0000
- macollongXtrenderCol = longTermXtrender > longTermXtrender[1] ? color.lime : color.red
- bx_long = bool(na)
- bx_short = bool(na)
- if bxtype == "Short Term trend"
- bx_long := maShortTermXtrender > maShortTermXtrender[1]
- bx_short := maShortTermXtrender < maShortTermXtrender[1]
- else if bxtype == "Short and Long term trend"
- bx_long := maShortTermXtrender > maShortTermXtrender[1] and (longTermXtrender > 0 and longTermXtrender > longTermXtrender[1]) and (shortTermXtrender > shortTermXtrender[1] and shortTermXtrender > 0)
- bx_short := maShortTermXtrender < maShortTermXtrender[1] and (longTermXtrender < 0 and longTermXtrender < longTermXtrender[1]) and (shortTermXtrender < shortTermXtrender[1] and shortTermXtrender < 0)
- ////////////////////////////////////////////////
- ////// Bull Bear Power Trend (BBPT)
- ///////////////////////////////////////////////
- BullTrend_hist = 0.0
- BearTrend_hist = 0.0
- BullTrend = (close - ta.lowest(low, 50)) / ta.atr(5)
- BearTrend = (ta.highest(high, 50) - close) / ta.atr(5)
- BearTrend2 = -1 * BearTrend
- Trend = BullTrend - BearTrend
- if BullTrend < 2
- BullTrend_hist := BullTrend - 2
- BullTrend_hist
- //plot(BullTrend_hist, title='Bear Trend Hist', color=color.new(#FF0000, 0), linewidth=1, style=plot.style_columns)
- if BearTrend2 > -2
- BearTrend_hist := BearTrend2 + 2
- BearTrend_hist
- //plot(BearTrend_hist, title='Bull Trend Hist', color=color.new(#008000, 0), linewidth=1, style=plot.style_columns)
- bbpt_long = bool(na)
- bbpt_short = bool(na)
- if bbpttype =="Follow Trend"
- bbpt_long := BearTrend_hist > 0 and Trend>=2
- bbpt_short := BullTrend_hist < 0 and Trend<=-2
- else if bbpttype == "Without Trend"
- bbpt_long := BearTrend_hist > 0
- bbpt_short := BullTrend_hist < 0
- ///////////////////////////////////////////////
- //////////// VWAP
- /////////////////////////////////////////////
- hideonDWM = input(false, title="Hide VWAP on 1D or Above", group="---------------------VWAP Settings-------------------------")
- var anchor = input.string(defval = "Session", title="Anchor Period",
- options=["Session", "Week", "Month", "Quarter", "Year", "Decade", "Century", "Earnings", "Dividends", "Splits"], group="---------------------VWAP Settings-------------------------")
- srcvwap = input(title = "Source", defval = hlc3, group="---------------------VWAP Settings-------------------------")
- offsetvwap = input(0, title="Offset", group="---------------------VWAP Settings-------------------------")
- showBand_1 = input(true, title="", group="Standard Deviation Bands Settings", inline="band_1")
- stdevMult_1 = input(1.0, title="Bands Multiplier #1", group="Standard Deviation Bands Settings", inline="band_1")
- showBand_2 = input(false, title="", group="Standard Deviation Bands Settings", inline="band_2")
- stdevMult_2 = input(2.0, title="Bands Multiplier #2", group="Standard Deviation Bands Settings", inline="band_2")
- showBand_3 = input(false, title="", group="Standard Deviation Bands Settings", inline="band_3")
- stdevMult_3 = input(3.0, title="Bands Multiplier #3", group="Standard Deviation Bands Settings", inline="band_3")
- if barstate.islast and ta.cum(volume) == 0
- runtime.error("No volume is provided by the data vendor.")
- new_earnings = request.earnings(syminfo.tickerid, earnings.actual, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true)
- new_dividends = request.dividends(syminfo.tickerid, dividends.gross, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true)
- new_split = request.splits(syminfo.tickerid, splits.denominator, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true)
- isNewPeriod = switch anchor
- "Earnings" => not na(new_earnings)
- "Dividends" => not na(new_dividends)
- "Splits" => not na(new_split)
- "Session" => timeframe.change("D")
- "Week" => timeframe.change("W")
- "Month" => timeframe.change("M")
- "Quarter" => timeframe.change("3M")
- "Year" => timeframe.change("12M")
- "Decade" => timeframe.change("12M") and year % 10 == 0
- "Century" => timeframe.change("12M") and year % 100 == 0
- => false
- isEsdAnchor = anchor == "Earnings" or anchor == "Dividends" or anchor == "Splits"
- if na(srcvwap[1]) and not isEsdAnchor
- isNewPeriod := true
- float vwapValue = na
- float upperBandValue1 = na
- float lowerBandValue1 = na
- float upperBandValue2 = na
- float lowerBandValue2 = na
- float upperBandValue3 = na
- float lowerBandValue3 = na
- if not (hideonDWM and timeframe.isdwm)
- [_vwap, _stdevUpper, _] = ta.vwap(srcvwap, isNewPeriod, 1)
- vwapValue := _vwap
- stdevAbs = _stdevUpper - _vwap
- upperBandValue1 := _vwap + stdevAbs * stdevMult_1
- lowerBandValue1 := _vwap - stdevAbs * stdevMult_1
- upperBandValue2 := _vwap + stdevAbs * stdevMult_2
- lowerBandValue2 := _vwap - stdevAbs * stdevMult_2
- upperBandValue3 := _vwap + stdevAbs * stdevMult_3
- lowerBandValue3 := _vwap - stdevAbs * stdevMult_3
- plot(switch_vwap? vwapValue:na, title="VWAP", color=#2962FF, offset=offsetvwap)
- long_vwap = close>vwapValue
- short_vwap = close < vwapValue
- ////////////////////////////////////////////////
- ////// Chandelier Exit
- ///////////////////////////////////////////////
- ChandelierE = "--------------Chandelier Exit--------------------"
- ce_length = input(title='ATR Period', defval=22)
- ce_mult = input.float(title='ATR Multiplier', step=0.1, defval=3.0)
- showLabels = input(title='Show Buy/Sell Labels ?', defval=true)
- useClose = input(title='Use Close Price for Extremums ?', defval=true)
- highlightState = input(title='Highlight State ?', defval=true)
- ce_atr = ce_mult * ta.atr(ce_length)
- longStop = (useClose ? ta.highest(close, ce_length) : ta.highest(ce_length)) - ce_atr
- longStopPrev = nz(longStop[1], longStop)
- longStop := close[1] > longStopPrev ? math.max(longStop, longStopPrev) : longStop
- shortStop = (useClose ? ta.lowest(close, ce_length) : ta.lowest(ce_length)) + ce_atr
- shortStopPrev = nz(shortStop[1], shortStop)
- shortStop := close[1] < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop
- var int dir = 1
- dir := close > shortStopPrev ? 1 : close < longStopPrev ? -1 : dir
- ce_long = dir == 1
- ce_short = dir == -1
- ////////////////////////////////////////////////
- ////// SSL Channel
- ///////////////////////////////////////////////
- group_ssl = "------------SSL Channel-------------------"
- SSLperiod = input(title='Period', defval=10, group=group_ssl)
- SSLlen = input(title='Period', defval=10, group=group_ssl)
- smaHigh = ta.sma(high, SSLlen)
- smaLow = ta.sma(low, SSLlen)
- Hlv = int(na)
- Hlv := close > smaHigh ? 1 : close < smaLow ? -1 : Hlv[1]
- sslDown = Hlv < 0 ? smaHigh : smaLow
- sslUp = Hlv < 0 ? smaLow : smaHigh
- ssl_long = sslUp>sslDown
- ssl_short = sslUp<sslDown
- ////////////////////////////////////////////////
- ////// Chaikin Money Flow
- ///////////////////////////////////////////////
- group_chaikin = "--------------Chaiken Money Flow----------------"
- chaiking_length = input.int(20, minval=1, group = group_chaikin )
- ad = close == high and close == low or high == low ? 0 : (2 * close - low - high) / (high - low) * volume
- mf = math.sum(ad, chaiking_length) / math.sum(volume, chaiking_length)
- chaikin_long = mf>0
- chaikin_short = mf<0
- ////////////////////////////////////////////////
- ////// Vortex INdex
- ///////////////////////////////////////////////
- period_ = input.int(14, title="Length", minval=2, group='-------------------------Vortex Index-------------------------', inline = 'vi')
- viupper = input.float(1.1, title="Upper band",group='-------------------------Vortex Index-------------------------', inline = 'vi')
- vilower = input.float(0.9, title="Lower Band", group='-------------------------Vortex Index-------------------------', inline = 'vi')
- VMP = math.sum( math.abs( high - low[1]), period_ )
- VMM = math.sum( math.abs( low - high[1]), period_ )
- STR = math.sum( ta.atr(1), period_ )
- vip = VMP / STR
- vim = VMM / STR
- //plot(VIP, title="VI +", color=#2962FF)
- //plot(VIM, title="VI -", color=#E91E63)
- /////////////////////////////////////////////////
- ////////Waddar Atar explosion (WAR)
- //////////////////////////////////////////////////
- group_wae = "-------------------Waddah Attar Explosion-----------------------"
- wae_sensitivity = input(150, title="Sensitivity",group=group_wae)
- wae_fastLength=input(20, title="FastEMA Length",group=group_wae)
- wae_slowLength=input(40, title="SlowEMA Length",group=group_wae)
- channelLength=input(20, title="BB Channel Length",group=group_wae)
- wae_mult=input(2.0, title="BB Stdev Multiplier",group=group_wae)
- deadzone = nz(ta.rma(ta.tr(true),100)) * 3.7
- calc_macd(source, wae_fastLength, wae_slowLength) =>
- fastMA = ta.ema(source, wae_fastLength)
- slowMA = ta.ema(source, wae_slowLength)
- fastMA - slowMA
- calc_BBUpper(source, length, wae_mult) =>
- basis = ta.sma(source, length)
- dev = wae_mult * ta.stdev(source, length)
- basis + dev
- calc_BBLower(source, length, wae_mult) =>
- basis = ta.sma(source, length)
- dev = wae_mult * ta.stdev(source, length)
- basis - dev
- t1 = (calc_macd(close, wae_fastLength, wae_slowLength) - calc_macd(close[1], wae_fastLength, wae_slowLength))*wae_sensitivity
- e1 = (calc_BBUpper(close, channelLength, wae_mult) - calc_BBLower(close, channelLength, wae_mult))
- trendUp = (t1 >= 0) ? t1 : 0
- trendDown = (t1 < 0) ? (-1*t1) : 0
- wae_long = trendUp and trendUp >e1 and e1 > deadzone and trendUp>deadzone
- wae_short = trendDown and trendDown >e1 and e1 > deadzone and trendDown>deadzone
- /////////////////////////////////////////////////
- ////////Volatility Oscillator
- //////////////////////////////////////////////////
- group_vo = "-------------------Volatility Oscillator-----------------------"
- volength = input(100, group = group_vo)
- spike = close - open
- vox = ta.stdev(spike,volength)
- voy = ta.stdev(spike,volength) * -1
- vo_long = spike > vox
- vo_short = spike < voy
- //////////////////////////////////////////////////
- ////////Damiani Volatmeter
- //////////////////////////////////////////////////
- int vis_atr = input.int(13,title="Vis ATR", group='-------------------------Damiani Volatmeter-------------------------', inline = '1')
- int vis_std = input.int(20,title="Vis STD", group='-------------------------Damiani Volatmeter-------------------------', inline = '1')
- int sed_atr = input.int(40,title="Sed ATR", group='-------------------------Damiani Volatmeter-------------------------', inline = '1')
- int sed_std = input.int(100,title="SEd STD", group='-------------------------Damiani Volatmeter-------------------------', inline = '1')
- float threshold_level = input.float(1.4,title="Threshold", group='-------------------------Damiani Volatmeter-------------------------', inline = '1')
- bool lag_supressor = input.bool(true,title="Lag Supressor", group='-------------------------Damiani Volatmeter-------------------------', inline = '1')
- lag_s_K = 0.5
- vol = 0.0
- s1=nz(vol[1], 0)
- s3=nz(vol[3], 0)
- vol := lag_supressor ? ta.atr(vis_atr) / ta.atr(sed_atr) + lag_s_K*(s1-s3) : ta.atr(vis_atr) / ta.atr(sed_atr)
- anti_thres = ta.stdev(close, vis_std) / ta.stdev(close, sed_std)
- t = threshold_level - anti_thres
- vol_m = vol > t ? -1 : 0.03
- //////////////////////////////////////////////
- /////// MACD
- /////////////////////////////////////////////
- fast_length = input(title="Fast Length", defval=12,group='-------------------------MACD-------------------------')
- slow_length = input(title="Slow Length", defval=26,group='-------------------------MACD-------------------------')
- macdsrc = input(title="Source", defval=close,group='-------------------------MACD-------------------------')
- signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9,group='-------------------------MACD-------------------------')
- sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"],group='-------------------------MACD-------------------------')
- sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"],group='-------------------------MACD-------------------------')
- fast_ma = sma_source == "SMA" ? ta.sma(macdsrc, fast_length) : ta.ema(macdsrc, fast_length)
- slow_ma = sma_source == "SMA" ? ta.sma(macdsrc, slow_length) : ta.ema(macdsrc, slow_length)
- macdd = fast_ma - slow_ma
- signal = sma_signal == "SMA" ? ta.sma(macdd, signal_length) : ta.ema(macdd, signal_length)
- hist = macdd - signal
- /////////////////////////////////////////////
- ///// Awesome Oscillator
- ////////////////////////////////////////////
- nLengthSlow = input(34, title="Length Slow")
- nLengthFast = input(5, title="Length Fast")
- reverse = input(false, title="Trade reverse")
- xSMA1_hl2 = ta.sma(hl2, nLengthFast)
- xSMA2_hl2 = ta.sma(hl2, nLengthSlow)
- xSMA1_SMA2 = xSMA1_hl2 - xSMA2_hl2
- xSMA_hl2 = ta.sma(xSMA1_SMA2, nLengthFast)
- nRes = xSMA1_SMA2 - xSMA_hl2
- //// zero line cross (standard code)
- ao = ta.sma(hl2,5) - ta.sma(hl2,34)
- diff = ao - ao[1]
- ao_long = bool(na)
- ao_short = bool(na)
- if aotype == "AC Zero Line Cross"
- ao_long := nRes > nRes[1] and nRes > 0
- ao_short := nRes < nRes[1] and nRes < 0
- else if aotype == "AC Momentum Bar"
- ao_long := nRes > nRes[1]
- ao_short := nRes < nRes[1]
- else if aotype == "Zero Line Cross"
- ao_long := ao > 0
- ao_short := ao < 0
- /////////////////////////////////////////////
- ///// WolfPack ID
- ////////////////////////////////////////////
- wolfgroup = "-------------------Wolf Pack ID ---------------------"
- input1 = input(title='Fast Length', group=wolfgroup,defval=3)
- input2 = input(title='Slow Length',group=wolfgroup, defval=8)
- pivR = input(title='Wolfpack Wave Pivot Lookback Right', group=wolfgroup,defval=1)
- pivL = input(title='Wolfpack Wave Pivot Lookback Left',group=wolfgroup, defval=15)
- fastmaa = ta.ema(close, input1)
- fastmab = ta.ema(close, input2)
- wolfsrc = close
- bspread = (fastmaa - fastmab) * 1.001
- adline = 0
- m = bspread > 0 ? color.new(color.lime, 0) : color.new(color.red, 0)
- wolfup = ta.rma(math.max(ta.change(wolfsrc), 0), 3)
- wolfdown = ta.rma(-math.min(ta.change(wolfsrc), 0), 3)
- lbR = input(title='Divergence Pivot Lookback Right',group=wolfgroup, defval=1)
- lbL = input(title='Divergence Pivot Lookback Left', group=wolfgroup,defval=10)
- rangeUpper = input(title='Max of Lookback Range',group=wolfgroup, defval=100)
- rangeLower = input(title='Min of Lookback Range', group=wolfgroup,defval=2)
- osc = bspread
- _inRange(cond) =>
- bars = ta.barssince(cond == true)
- rangeLower <= bars and bars <= rangeUpper
- wolf_long = bspread > 0
- wolf_short = bspread < 0
- /////////////////////////////////////////////
- ///// BB Oscillator
- ////////////////////////////////////////////
- bbgroup = "-------------------Bollinger Band (BB) Oscillator ---------------------"
- bbosc_length = input.int(20, minval=1,group=bbgroup)
- bbosc_src = input(close, title='Source',group=bbgroup)
- bbosc_mult = input.float(2.0, minval=0.001, maxval=50, title='StdDev',group=bbgroup)
- bbosc_basis = ta.sma(bbosc_src, bbosc_length)
- dlength = input.int(4, minval=1, title='Trigger Length',group=bbgroup)
- bbosc_offset = input.int(0, 'Offset', minval=-500, maxval=500,group=bbgroup, tooltip = "Use Offset and Show Last to turn indicator into a widget.\nExample:\nOffset = 120\nShow Last = 100 ")
- bbosc_last = input(0, 'Show Last',group=bbgroup)
- bbosc_dev = bbosc_mult * ta.stdev(bbosc_src, bbosc_length)
- bbosc_upper = bbosc_basis + bbosc_dev
- bbosc_lower = bbosc_basis - bbosc_dev
- upercent = (bbosc_upper - close) / (bbosc_upper + close / 2)
- lpercent = (bbosc_lower - close) / (bbosc_lower + close / 2)
- bpercent = (bbosc_basis - close) / (bbosc_basis + close / 2)
- usmooth = ta.wma(upercent, 6)
- lsmooth = ta.wma(lpercent, 6)
- bsmooth = ta.wma(bpercent, 6)
- d1 = ta.sma(bsmooth, 2)
- j = (bsmooth + d1) * -1
- d2 = ta.sma(j, dlength)
- bbosc_long = bool(na)
- bbosc_short = bool(na)
- bbcycle = 0
- bbup = ta.crossover(j, usmooth)
- bbdown = ta.crossunder(j, lsmooth)
- bbcycle := bbup ? 1 : bbdown ? -1 : bbcycle[1]
- if bbtype == "Entering Lower/Upper Band"
- bbosc_long := j > d2 and (j==lsmooth or j>lsmooth) and bbcycle==-1
- bbosc_short:= j < d2 and (j==usmooth or j<usmooth) and bbcycle==1
- else if bbtype == "Exiting Lower/Upper Band"
- bbosc_long := j > d2 and (j>usmooth)
- bbosc_short:= j < d2 and (j<lsmooth)
- //////////////////////////////////////////////
- /////// Trend Meter
- //////////////////////////////////////////////
- ShowTrendBar = true
- WTSetups = input.bool(true, 'Wave Trend Filtered by Trend', group='-------------------------Trend Meter-------------------------', inline = 'tm')
- TMSetups = input.bool(true, 'All 3 Trend Meters Now Align', group='-------------------------Trend Meter-------------------------', inline = 'tm2')
- MSBar1 = 'Trend Filter' // input(title= "1 - Wave Trend Signals", defval = "Trend Filter", options = ["N/A", "Trend Filter", "Filter X", "Filter X + Trend Filter"])
- MSBar2 = 'Trend Filter' // input(title= "2 - Wave Trend Signals", defval = "Filter X", options = ["N/A", "Trend Filter", "Filter X", "Filter X + Trend Filter"])
- TrendBar1 = input.string(title='Trend Meter 1', defval='MACD Crossover - Fast - 8, 21, 5', options=['MACD Crossover - 12, 26, 9', 'MACD Crossover - Fast - 8, 21, 5', 'Mom Dad Cross (Top Dog Trading)', 'RSI Signal Line Cross - RSI 13, Sig 21', 'RSI 13: > or < 50', 'RSI 5: > or < 50', 'Trend Candles', 'N/A'], group='Trend Meters') // "MA Crossover", "DAD Direction (Top Dog Trading)",
- TrendBar2 = input.string(title='Trend Meter 2', defval='RSI 13: > or < 50', options=['MACD Crossover - 12, 26, 9', 'MACD Crossover - Fast - 8, 21, 5', 'Mom Dad Cross (Top Dog Trading)', 'RSI Signal Line Cross - RSI 13, Sig 21', 'RSI 13: > or < 50', 'RSI 5: > or < 50', 'Trend Candles', 'N/A'], group='Trend Meters') // "MA Crossover", "DAD Direction (Top Dog Trading)",
- TrendBar3 = input.string(title='Trend Meter 3', defval='RSI 5: > or < 50', options=['MACD Crossover - 12, 26, 9', 'MACD Crossover - Fast - 8, 21, 5', 'Mom Dad Cross (Top Dog Trading)', 'RSI Signal Line Cross - RSI 13, Sig 21', 'RSI 13: > or < 50', 'RSI 5: > or < 50', 'Trend Candles', 'N/A'], group='Trend Meters') // "MA Crossover", "DAD Direction (Top Dog Trading)",
- TrendBar4 = input.string(title='Trend Bar 1', defval='MA Crossover', options=['MA Crossover', 'MA Direction - Fast MA - TB1', 'MA Direction - Slow MA - TB1', 'N/A'], group='Trend Bars') // "MACD Crossover - 12, 26 9", "MACD Crossover - Fast - 8, 21, 5", "DAD Direction (Top Dog Trading)",
- TrendBar5 = input.string(title='Trend Bar 2', defval='MA Crossover', options=['MA Crossover', 'MA Direction - Fast MA - TB2', 'MA Direction - Slow MA - TB2', 'N/A'], group='Trend Bars') // "MACD Crossover - 12, 26 9", "MACD Crossover - Fast - 8, 21, 5", "DAD Direction (Top Dog Trading)",
- ////////////////Signals - Wave Trend/////////////////////////////////////////////////////////////////////////////////////////////////
- // Wave Trend - RSI
- RSIMC = ta.rsi(close, 14)
- // Wave Trend
- ap = hlc3 // input(hlc3, "Wave Trend - Source")
- n1 = 9 //input(9, "Wave Trend - WT Channel Length")
- n2 = 12 // input(12, "Wave Trend - WT Average Length")
- esa = ta.ema(ap, n1)
- de = ta.ema(math.abs(ap - esa), n1)
- ci = (ap - esa) / (0.015 * de)
- tci = ta.ema(ci, n2)
- wt11 = tci
- wt22 = ta.sma(wt11, 3)
- // Wave Trend - Overbought & Oversold lines
- obLevel2 = 60 // input( 60, "Wave Trend - WT Very Overbought")
- obLevel = 50 // input( 50, "Wave Trend - WT Overbought")
- osLevel = -50 // input(-50, "Wave Trend - WT Oversold")
- osLevel2 = -60 // input(-60, "Wave Trend - WT Very Oversold")
- // Wave Trend - Conditions
- WTCross = ta.cross(wt11, wt22)
- WTCrossUp = wt22 - wt11 <= 0
- WTCrossDown = wt22 - wt11 >= 0
- WTOverSold = wt22 <= osLevel2
- WTOverBought = wt22 >= obLevel2
- // MA Inputs
- MA1_Length = input.int(5, title='Fast MA', minval=1, group='Trend Bar 1 - Settings', inline='TB1 Fast')
- MA1_Type = input.string(title='', defval='EMA', options=['EMA', 'SMA'], group='Trend Bar 1 - Settings', inline='TB1 Fast')
- MA2_Length = input.int(11, title='Slow MA', minval=1, group='Trend Bar 1 - Settings', inline='TB1 Slow')
- MA2_Type = input.string(title='', defval='EMA', options=['EMA', 'SMA'], group='Trend Bar 1 - Settings', inline='TB1 Slow')
- MA3_Length = input.int(9, title='Fast MA', minval=1, group='Trend Bar 2 - Settings', inline='TB2 Fast')
- MA3_Type = input.string(title='', defval='EMA', options=['EMA', 'SMA'], group='Trend Bar 2 - Settings', inline='TB2 Fast')
- MA4_Length = input.int(21, title='Slow MA', minval=1, group='Trend Bar 2 - Settings', inline='TB2 Slow')
- MA4_Type = input.string(title='', defval='SMA', options=['EMA', 'SMA'], group='Trend Bar 2 - Settings', inline='TB2 Slow')
- // MA Calculations
- Close = request.security(syminfo.tickerid, timeframe.period, close, lookahead=barmerge.lookahead_on)
- MA1 = if MA1_Type == 'SMA'
- ta.sma(Close, MA1_Length)
- else
- ta.ema(Close, MA1_Length)
- MA2 = if MA2_Type == 'SMA'
- ta.sma(Close, MA2_Length)
- else
- ta.ema(Close, MA2_Length)
- MA3 = if MA3_Type == 'SMA'
- ta.sma(Close, MA3_Length)
- else
- ta.ema(Close, MA3_Length)
- MA4 = if MA4_Type == 'SMA'
- ta.sma(Close, MA4_Length)
- else
- ta.ema(Close, MA4_Length)
- // MA Crossover Condition
- MACrossover1 = MA1 > MA2 ? 1 : 0
- MACrossover2 = MA3 > MA4 ? 1 : 0
- // MA Direction Condition
- MA1Direction = MA1 > MA1[1] ? 1 : 0
- MA2Direction = MA2 > MA2[1] ? 1 : 0
- MA3Direction = MA3 > MA3[1] ? 1 : 0
- MA4Direction = MA4 > MA4[1] ? 1 : 0
- // MA Direction Change Condition
- MA1PositiveDirectionChange = MA1Direction and not MA1Direction[1] ? 1 : 0
- MA2PositiveDirectionChange = MA2Direction and not MA2Direction[1] ? 1 : 0
- MA3PositiveDirectionChange = MA3Direction and not MA3Direction[1] ? 1 : 0
- MA4PositiveDirectionChange = MA4Direction and not MA4Direction[1] ? 1 : 0
- MA1NegativeDirectionChange = not MA1Direction and MA1Direction[1] ? 1 : 0
- MA2NegativeDirectionChange = not MA2Direction and MA2Direction[1] ? 1 : 0
- MA3NegativeDirectionChange = not MA3Direction and MA3Direction[1] ? 1 : 0
- MA4NegativeDirectionChange = not MA4Direction and MA4Direction[1] ? 1 : 0
- // MACD and MOM & DAD - Top Dog Trading
- // Standard MACD Calculations
- MACDfastMA = 12
- MACDslowMA = 26
- MACDsignalSmooth = 9
- MACDLine = ta.ema(close, MACDfastMA) - ta.ema(close, MACDslowMA)
- SignalLine = ta.ema(MACDLine, MACDsignalSmooth)
- MACDHistogram = MACDLine - SignalLine
- // MACD- Background Color Change Condition
- MACDHistogramCross = MACDHistogram > 0 ? 1 : 0
- MACDLineOverZero = MACDLine > 0 ? 1 : 0
- MACDLineOverZeroandHistogramCross = MACDHistogramCross and MACDLineOverZero ? 1 : 0
- MACDLineUnderZeroandHistogramCross = not MACDHistogramCross and not MACDLineOverZero ? 1 : 0
- // Fast MACD Calculations
- FastMACDfastMA = 8
- FastMACDslowMA = 21
- FastMACDsignalSmooth = 5
- FastMACDLine = ta.ema(close, FastMACDfastMA) - ta.ema(close, FastMACDslowMA)
- FastSignalLine = ta.ema(FastMACDLine, FastMACDsignalSmooth)
- FastMACDHistogram = FastMACDLine - FastSignalLine
- // Fast MACD- Background Color Change Condition
- FastMACDHistogramCross = FastMACDHistogram > 0 ? 1 : 0
- FastMACDLineOverZero = FastMACDLine > 0 ? 1 : 0
- FastMACDLineOverZeroandHistogramCross = FastMACDHistogramCross and FastMACDLineOverZero ? 1 : 0
- FastMACDLineUnderZeroandHistogramCross = not FastMACDHistogramCross and not FastMACDLineOverZero ? 1 : 0
- // Top Dog Trading - Mom Dad Calculations
- TopDog_Fast_MA = 5
- TopDog_Slow_MA = 20
- TopDog_Sig = 30
- TopDogMom = ta.ema(close, TopDog_Fast_MA) - ta.ema(close, TopDog_Slow_MA)
- TopDogDad = ta.ema(TopDogMom, TopDog_Sig)
- // Top Dog Dad - Background Color Change Condition
- TopDogDadDirection = TopDogDad > TopDogDad[1] ? 1 : 0
- TopDogMomOverDad = TopDogMom > TopDogDad ? 1 : 0
- TopDogMomOverZero = TopDogMom > 0 ? 1 : 0
- TopDogDadDirectandMomOverZero = TopDogDadDirection and TopDogMomOverZero ? 1 : 0
- TopDogDadDirectandMomUnderZero = not TopDogDadDirection and not TopDogMomOverZero ? 1 : 0
- ////// Trend Barmeter Calculations //////
- haclose_tm = ohlc4
- haopen_tm = 0.0
- haopen_tm := na(haopen_tm[1]) ? (open + close) / 2 : (haopen_tm[1] + haclose_tm[1]) / 2
- //hahigh = max(high, max(haopen_tm, haclose_tm))
- //halow = min(low, min(haopen_tm, haclose_tm))
- ccolor = haclose_tm - haopen_tm > 0 ? 1 : 0
- inside6 = haopen_tm <= math.max(haopen_tm[6], haclose_tm[6]) and haopen_tm >= math.min(haopen_tm[6], haclose_tm[6]) and haclose_tm <= math.max(haopen_tm[6], haclose_tm[6]) and haclose_tm >= math.min(haopen_tm[6], haclose_tm[6]) ? 1 : 0
- inside5 = haopen_tm <= math.max(haopen_tm[5], haclose_tm[5]) and haopen_tm >= math.min(haopen_tm[5], haclose_tm[5]) and haclose_tm <= math.max(haopen_tm[5], haclose_tm[5]) and haclose_tm >= math.min(haopen_tm[5], haclose_tm[5]) ? 1 : 0
- inside4 = haopen_tm <= math.max(haopen_tm[4], haclose_tm[4]) and haopen_tm >= math.min(haopen_tm[4], haclose_tm[4]) and haclose_tm <= math.max(haopen_tm[4], haclose_tm[4]) and haclose_tm >= math.min(haopen_tm[4], haclose_tm[4]) ? 1 : 0
- inside3 = haopen_tm <= math.max(haopen_tm[3], haclose_tm[3]) and haopen_tm >= math.min(haopen_tm[3], haclose_tm[3]) and haclose_tm <= math.max(haopen_tm[3], haclose_tm[3]) and haclose_tm >= math.min(haopen_tm[3], haclose_tm[3]) ? 1 : 0
- inside2 = haopen_tm <= math.max(haopen_tm[2], haclose_tm[2]) and haopen_tm >= math.min(haopen_tm[2], haclose_tm[2]) and haclose_tm <= math.max(haopen_tm[2], haclose_tm[2]) and haclose_tm >= math.min(haopen_tm[2], haclose_tm[2]) ? 1 : 0
- inside1 = haopen_tm <= math.max(haopen_tm[1], haclose_tm[1]) and haopen_tm >= math.min(haopen_tm[1], haclose_tm[1]) and haclose_tm <= math.max(haopen_tm[1], haclose_tm[1]) and haclose_tm >= math.min(haopen_tm[1], haclose_tm[1]) ? 1 : 0
- colorvalue = inside6 ? ccolor[6] : inside5 ? ccolor[5] : inside4 ? ccolor[4] : inside3 ? ccolor[3] : inside2 ? ccolor[2] : inside1 ? ccolor[1] : ccolor
- TrendBarTrend_Candle_Color = colorvalue ? #288a75 : color.red
- TrendBarTrend_Candle = colorvalue ? 1 : 0
- // RSI 5 Trend Barmeter Calculations
- RSI5 = ta.rsi(close, 5)
- RSI5Above50 = RSI5 > 50 ? 1 : 0
- RSI5Color = RSI5Above50 ? #288a75 : color.red
- TrendBarRSI5Color = RSI5Above50 ? #288a75 : color.red
- // RSI 5 Trend Barmeter Calculations
- RSI13 = ta.rsi(close, 13)
- // Linear Regression Calculation For RSI Signal Line
- SignalLineLength1 = 21
- x = bar_index
- y = RSI13
- x_ = ta.sma(x, SignalLineLength1)
- y_ = ta.sma(y, SignalLineLength1)
- mx = ta.stdev(x, SignalLineLength1)
- my = ta.stdev(y, SignalLineLength1)
- c = ta.correlation(x, y, SignalLineLength1)
- slope = c * (my / mx)
- inter = y_ - slope * x_
- LinReg1 = x * slope + inter
- RSISigDirection = LinReg1 > LinReg1[1] ? 1 : 0
- RSISigCross = RSI13 > LinReg1 ? 1 : 0
- RSI13Above50 = RSI13 > 50 ? 1 : 0
- // Trend Barmeter Color Calculation
- RSI13Color = RSI13Above50 ? #288a75 : color.red
- TrendBarRSI13Color = RSI13Above50 ? #288a75 : color.red
- TrendBarRSISigCrossColor = RSISigCross ? #288a75 : color.red
- TrendBarMACDColor = MACDHistogramCross ? #288a75 : color.red
- TrendBarFastMACDColor = FastMACDHistogramCross ? #288a75 : color.red
- TrendBarMACrossColor = MACrossover1 ? #288a75 : color.red
- TrendBarMomOverDadColor = TopDogMomOverDad ? #288a75 : color.red
- TrendBarDadDirectionColor = TopDogDadDirection ? #288a75 : color.red
- TrendBar1Result = TrendBar1 == 'MA Crossover' ? MACrossover1 : TrendBar1 == 'MACD Crossover - 12, 26, 9' ? MACDHistogramCross : TrendBar1 == 'MACD Crossover - Fast - 8, 21, 5' ? FastMACDHistogramCross : TrendBar1 == 'Mom Dad Cross (Top Dog Trading)' ? TopDogMomOverDad : TrendBar1 == 'DAD Direction (Top Dog Trading)' ? TopDogDadDirection : TrendBar1 == 'RSI Signal Line Cross - RSI 13, Sig 21' ? RSISigCross : TrendBar1 == 'RSI 5: > or < 50' ? RSI5Above50 : TrendBar1 == 'RSI 13: > or < 50' ? RSI13Above50 : TrendBar1 == 'Trend Candles' ? TrendBarTrend_Candle : na
- TrendBar2Result = TrendBar2 == 'MA Crossover' ? MACrossover1 : TrendBar2 == 'MACD Crossover - 12, 26, 9' ? MACDHistogramCross : TrendBar2 == 'MACD Crossover - Fast - 8, 21, 5' ? FastMACDHistogramCross : TrendBar2 == 'Mom Dad Cross (Top Dog Trading)' ? TopDogMomOverDad : TrendBar2 == 'DAD Direction (Top Dog Trading)' ? TopDogDadDirection : TrendBar2 == 'RSI Signal Line Cross - RSI 13, Sig 21' ? RSISigCross : TrendBar2 == 'RSI 5: > or < 50' ? RSI5Above50 : TrendBar2 == 'RSI 13: > or < 50' ? RSI13Above50 : TrendBar2 == 'Trend Candles' ? TrendBarTrend_Candle : na
- TrendBar3Result = TrendBar3 == 'MA Crossover' ? MACrossover1 : TrendBar3 == 'MACD Crossover - 12, 26, 9' ? MACDHistogramCross : TrendBar3 == 'MACD Crossover - Fast - 8, 21, 5' ? FastMACDHistogramCross : TrendBar3 == 'Mom Dad Cross (Top Dog Trading)' ? TopDogMomOverDad : TrendBar3 == 'DAD Direction (Top Dog Trading)' ? TopDogDadDirection : TrendBar3 == 'RSI Signal Line Cross - RSI 13, Sig 21' ? RSISigCross : TrendBar3 == 'RSI 5: > or < 50' ? RSI5Above50 : TrendBar3 == 'RSI 13: > or < 50' ? RSI13Above50 : TrendBar3 == 'Trend Candles' ? TrendBarTrend_Candle : na
- TrendBars2Positive = TrendBar1Result and TrendBar2Result or TrendBar1Result and TrendBar3Result or TrendBar2Result and TrendBar3Result ? 1 : 0
- TrendBars2Negative = not TrendBar1Result and not TrendBar2Result or not TrendBar1Result and not TrendBar3Result or not TrendBar2Result and not TrendBar3Result ? 1 : 0
- TrendBars3Positive = TrendBar1Result and TrendBar2Result and TrendBar3Result ? 1 : 0
- TrendBars3Negative = not TrendBar1Result and not TrendBar2Result and not TrendBar3Result ? 1 : 0
- FilterXUp = FastMACDHistogramCross and ta.ema(close, 15) > ta.ema(close, 15)[1]
- FilterXDown = not FastMACDHistogramCross and ta.ema(close, 15) < ta.ema(close, 15)[1]
- TrendFilterPlus = ta.ema(close, 15) > ta.ema(close, 20) and ta.ema(close, 20) > ta.ema(close, 30) and ta.ema(close, 30) > ta.ema(close, 40) and ta.ema(close, 40) > ta.ema(close, 50) ? 1 : 0
- TrendFilterMinus = ta.ema(close, 15) < ta.ema(close, 20) and ta.ema(close, 20) < ta.ema(close, 30) and ta.ema(close, 30) < ta.ema(close, 40) and ta.ema(close, 40) < ta.ema(close, 50) ? 1 : 0
- MSBar1PositiveWaveTrendSignal = MSBar1 == 'Filter X' ? FilterXUp and WTCross and WTCrossUp : MSBar1 == 'Trend Filter' ? TrendFilterPlus and WTCross and WTCrossUp : MSBar1 == 'Filter X + Trend Filter' ? FilterXUp and TrendFilterPlus and WTCross and WTCrossUp : WTCross and WTCrossUp
- MSBar1NegativeWaveTrendSignal = MSBar1 == 'Filter X' ? FilterXDown and WTCross and WTCrossDown : MSBar1 == 'Trend Filter' ? TrendFilterMinus and WTCross and WTCrossDown : MSBar1 == 'Filter X + Trend Filter' ? FilterXDown and TrendFilterMinus and WTCross and WTCrossDown : WTCross and WTCrossDown
- MSBar2PositiveWaveTrendSignal = MSBar2 == 'Filter X' ? FilterXUp and WTCross and WTCrossUp : MSBar2 == 'Trend Filter' ? TrendFilterPlus and WTCross and WTCrossUp : MSBar2 == 'Filter X + Trend Filter' ? FilterXUp and TrendFilterPlus and WTCross and WTCrossUp : WTCross and WTCrossUp
- MSBar2NegativeWaveTrendSignal = MSBar2 == 'Filter X' ? FilterXDown and WTCross and WTCrossDown : MSBar2 == 'Trend Filter' ? TrendFilterMinus and WTCross and WTCrossDown : MSBar2 == 'Filter X + Trend Filter' ? FilterXDown and TrendFilterMinus and WTCross and WTCrossDown : WTCross and WTCrossDown
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
- BackgroundColorChangePositive = TrendBars3Positive and not TrendBars3Positive[1]
- BackgroundColorChangeNegative = TrendBars3Negative and not TrendBars3Negative[1]
- // Signals Color Calculations
- MSBar1Color = MSBar1PositiveWaveTrendSignal ? #288a75 : MSBar1NegativeWaveTrendSignal ? color.red : na
- MSBar2Color = BackgroundColorChangePositive ? #288a75 : BackgroundColorChangeNegative ? color.red : na
- // Trend Barmeter Color Assignments
- TrendBar1Color = TrendBar1 == 'N/A' ? na : TrendBar1 == 'MACD Crossover - 12, 26, 9' ? TrendBarMACDColor : TrendBar1 == 'MACD Crossover - Fast - 8, 21, 5' ? TrendBarFastMACDColor : TrendBar1 == 'Mom Dad Cross (Top Dog Trading)' ? TrendBarMomOverDadColor : TrendBar1 == 'DAD Direction (Top Dog Trading)' ? TrendBarDadDirectionColor : TrendBar1 == 'RSI Signal Line Cross - RSI 13, Sig 21' ? TrendBarRSISigCrossColor : TrendBar1 == 'RSI 5: > or < 50' ? TrendBarRSI5Color : TrendBar1 == 'RSI 13: > or < 50' ? TrendBarRSI13Color : TrendBar1 == 'Trend Candles' ? TrendBarTrend_Candle_Color : TrendBar1 == 'MA Crossover' ? TrendBarMACrossColor : na
- TrendBar2Color = TrendBar2 == 'N/A' ? na : TrendBar2 == 'MACD Crossover - 12, 26, 9' ? TrendBarMACDColor : TrendBar2 == 'MACD Crossover - Fast - 8, 21, 5' ? TrendBarFastMACDColor : TrendBar2 == 'Mom Dad Cross (Top Dog Trading)' ? TrendBarMomOverDadColor : TrendBar2 == 'DAD Direction (Top Dog Trading)' ? TrendBarDadDirectionColor : TrendBar2 == 'RSI Signal Line Cross - RSI 13, Sig 21' ? TrendBarRSISigCrossColor : TrendBar2 == 'RSI 5: > or < 50' ? TrendBarRSI5Color : TrendBar2 == 'RSI 13: > or < 50' ? TrendBarRSI13Color : TrendBar2 == 'Trend Candles' ? TrendBarTrend_Candle_Color : TrendBar2 == 'MA Crossover' ? TrendBarMACrossColor : na
- TrendBar3Color = TrendBar3 == 'N/A' ? na : TrendBar3 == 'MACD Crossover - 12, 26, 9' ? TrendBarMACDColor : TrendBar3 == 'MACD Crossover - Fast - 8, 21, 5' ? TrendBarFastMACDColor : TrendBar3 == 'Mom Dad Cross (Top Dog Trading)' ? TrendBarMomOverDadColor : TrendBar3 == 'DAD Direction (Top Dog Trading)' ? TrendBarDadDirectionColor : TrendBar3 == 'RSI Signal Line Cross - RSI 13, Sig 21' ? TrendBarRSISigCrossColor : TrendBar3 == 'RSI 5: > or < 50' ? TrendBarRSI5Color : TrendBar3 == 'RSI 13: > or < 50' ? TrendBarRSI13Color : TrendBar3 == 'Trend Candles' ? TrendBarTrend_Candle_Color : TrendBar3 == 'MA Crossover' ? TrendBarMACrossColor : na
- CrossoverType2 = TrendBar4 == 'DAD Direction (Top Dog Trading)' ? TopDogDadDirection : TrendBar4 == 'MACD Crossover' ? MACDHistogramCross : TrendBar4 == 'MA Direction - Fast MA - TB1' ? MA1Direction : TrendBar4 == 'MA Direction - Slow MA - TB1' ? MA2Direction : MACrossover1
- color_1 = color.new(color.green, 15)
- color_2 = color.new(color.red, 20)
- TrendBar4Color1 = TrendBar4 == 'N/A' ? na : CrossoverType2 ? color_1 : color_2
- // TrendBar4Color2 = TrendBar4=="N/A" ? na : TrendBar4=="DAD Direction (Top Dog Trading)" and TopDogDadDirectandMomOverZero ? color(green, 70) : TrendBar4=="DAD Direction (Top Dog Trading)" and TopDogDadDirectandMomUnderZero ? color(red, 70) : TrendBar4=="MACD Crossover - 12, 26, 9" and MACDLineOverZeroandHistogramCross ? color(green, 70) : TrendBar4=="MACD Crossover - 12, 26, 9" and MACDLineUnderZeroandHistogramCross ? color(red, 70) : TrendBar4=="MA Crossover" and CrossoverType2 ? color(green, 40) : TrendBar4=="MA Crossover" and not CrossoverType2 ? color(red, 40) : TrendBar4=="MA Direction - Fast MA" and CrossoverType2 ? color(green, 40) : TrendBar4=="MA Direction - Fast MA" and not CrossoverType2 ? color(red, 40) : na
- CrossoverType3 = TrendBar5 == 'DAD Direction (Top Dog Trading)' ? TopDogDadDirection : TrendBar5 == 'MACD Crossover' ? MACDHistogramCross : TrendBar5 == 'MA Direction - Fast MA - TB2' ? MA3Direction : TrendBar5 == 'MA Direction - Slow MA - TB2' ? MA4Direction : MACrossover2
- color_3 = color.new(color.green, 15)
- color_4 = color.new(color.red, 20)
- TrendBar5Color1 = TrendBar5 == 'N/A' ? na : CrossoverType3 ? color_3 : color_4
- // TrendBar5Color2 = TrendBar5=="N/A" ? na : TrendBar5=="DAD Direction (Top Dog Trading)" and TopDogDadDirectandMomOverZero ? color(green, 70) : TrendBar5=="DAD Direction (Top Dog Trading)" and TopDogDadDirectandMomUnderZero ? color(red, 70) : TrendBar5=="MACD Crossover - 12, 26, 9" and MACDLineOverZeroandHistogramCross ? color(green, 70) : TrendBar5=="MACD Crossover - 12, 26, 9" and MACDLineUnderZeroandHistogramCross ? color(red, 70) : TrendBar5=="MA Crossover" and CrossoverType3 ? color(green, 40) : TrendBar5=="MA Crossover" and not CrossoverType3 ? color(red, 40) : TrendBar5=="MA Direction - Fast MA" and CrossoverType3 ? color(green, 40) : TrendBar5=="MA Direction - Fast MA" and not CrossoverType3 ? color(red, 40) : na
- TrendBar3BarsSame = TrendBars3Positive ? color.green : TrendBars3Negative ? color.red : na
- TrendMetersNoLongerAlign = (not TrendBars3Positive or not TrendBars3Negative) and TrendBars3Positive[1] or (not TrendBars3Positive or not TrendBars3Negative) and TrendBars3Negative[1]
- // alertcondition(TrendMetersNoLongerAlign, title='3 Trend Meters No Longer Align', message='3 Trend Meters No Longer Align - Trend Meter')
- RapidColorChangePositive = TrendBars3Positive and (TrendBars3Negative[1] or TrendBars3Negative[2])
- RapidColorChangeNegative = TrendBars3Negative and (TrendBars3Positive[1] or TrendBars3Positive[2])
- MaxValueMACrossUp = ta.crossover(ta.ema(Close, 5), ta.ema(Close, 11))
- MaxValueMACrossDown = ta.crossunder(ta.ema(Close, 5), ta.ema(Close, 11))
- TB1MACrossUp = ta.crossover(MA1, MA2)
- TB1MACrossDown = ta.crossunder(MA1, MA2)
- TB2MACrossUp = ta.crossover(MA3, MA4)
- TB2MACrossDown = ta.crossunder(MA3, MA4)
- TB1Green = MA1 > MA2
- TB1Red = MA1 < MA2
- TB2Green = MA3 > MA4
- TB2Red = MA3 < MA4
- TB12Green = TB1Green and TB2Green and (TB1MACrossUp or TB2MACrossUp)
- TB12Red = TB1Red and TB2Red and (TB1MACrossDown or TB2MACrossDown)
- /////////////////////////////////
- /////// Stochastic
- /////////////////////////////////
- groupname = "==================Stochastic=================="
- len = input.int(14, minval=1, title="Length",group=groupname)
- smoothK = input.int(3, minval=1, title="K Smoothing",group=groupname)
- smoothD = input.int(3, minval=1, title="D Smoothing",group=groupname)
- upLine = input.int(80, minval=50, maxval=90, title="Overbought level",group=groupname)
- lowLine = input.int(20, minval=10, maxval=50, title="Oversold level",group=groupname)
- // sl = input(true, title="Show 'B' and 'S' Letters When Stoch Crosses High/Low Line & D?")
- // sac = input(false, title="Show Back Ground Highlights When Stoch Cross - Any Cross?")
- // sacl = input(false, title="Show 'B' and 'S' Letters When Stoch Crosses - Any Cross?")
- //Resolutioon for MTF
- resstoch = timeframe.period
- //Stoch formula
- kk = ta.sma(ta.stoch(close, high, low, len), smoothK)
- dd = ta.sma(kk, smoothD)
- outK = request.security(syminfo.tickerid, resstoch, kk)
- outD = request.security(syminfo.tickerid, resstoch, dd)
- //definitions for Cross
- aboveLine = outK > upLine ? 1 : 0
- belowLine = outK < lowLine ? 1 : 0
- stoch_long = bool (na)
- stoch_short = bool (na)
- if stochtype == "CrossOver"
- stoch_long := (outK[1] < outD[1] and outK > outD) ? 1 : 0
- stoch_short := (outK[1] > outD[1] and outK < outD) ? 1 : 0
- else if stochtype == "CrossOver in OB & OS levels"
- stoch_long := (outK[1] < outD[1] and outK[1] < lowLine[1]) and (outK > outD) and outK > lowLine? 1 : 0
- stoch_short := (outK[1] > outD[1] and outK[1] > upLine[1]) and (outK < outD) and outK < upLine? 1 : 0
- else if stochtype == "%K above/below %D"
- stoch_long := outK > outD
- stoch_short := outK < outD
- ///////////////////////////////////////////////
- ///////RSI
- ///////////////////////////////////////////////
- rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="---------------------RSI Settings---------------------")
- rsiSourceInput = input.source(close, "Source", group="---------------------RSI Settings---------------------")
- maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="---------------------RSI Settings---------------------")
- rsi_upper = input.int(defval=80, title='Overbought Zone', group="---------------------RSI Settings---------------------", inline='zone')
- rsi_lower = input.int(defval=20, title='Oversold Zone', group="---------------------RSI Settings---------------------", inline='zone')
- respectrsilevel = input.int(defval=50, minval=1, title='RSI MidLine', group="---------------------RSI Settings---------------------")
- maLengthInput = input.int(14, title="MA Length", group="---------------------RSI Settings---------------------")
- up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
- down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
- rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
- rsiMA = ma(rsi, maLengthInput, maTypeInput)
- isBB = maTypeInput == "Bollinger Bands"
- ///////////////////////////////////////////////
- /// HULL SUITE
- //////////////////////////////////////////////
- //INPUT
- hullsrc = input(close, title='Source',group="---------------------HullSuite Settings---------------------")
- modeSwitch = input.string('Hma', title='Hull Variation', options=['Hma', 'Thma', 'Ehma'],group="---------------------HullSuite Settings---------------------")
- hull_length = input(55, title='hull_length(180-200 for floating S/R , 55 for swing entry)',group="---------------------HullSuite Settings---------------------")
- hull_lengthMult = input(1.0, title='hull_length multiplier (Used to view higher timeframes with straight band)',group="---------------------HullSuite Settings---------------------")
- useHtf = input(false, title='Show Hull MA from X timeframe? (good for scalping)',group="---------------------HullSuite Settings---------------------")
- htf = input.timeframe('240', title='Higher timeframe',group="---------------------HullSuite Settings---------------------")
- switchColor = input(true, 'Color Hull according to trend?',group="---------------------HullSuite Settings---------------------")
- candleCol = input(false, title='Color candles based on Hull\'s Trend?',group="---------------------HullSuite Settings---------------------")
- visualSwitch = input(true, title='Show as a Band?'),group="---------------------HullSuite Settings---------------------"
- thicknesSwitch = input(1, title='Line Thickness',group="---------------------HullSuite Settings---------------------")
- transpSwitch = input.int(40, title='Band Transparency', step=5,group="---------------------HullSuite Settings---------------------")
- //FUNCTIONS
- //HMA
- HMA(_hullsrc, _hull_length) =>
- ta.wma(2 * ta.wma(_hullsrc, _hull_length / 2) - ta.wma(_hullsrc, _hull_length), math.round(math.sqrt(_hull_length)))
- //EHMA
- EHMA(_hullsrc, _hull_length) =>
- ta.ema(2 * ta.ema(_hullsrc, _hull_length / 2) - ta.ema(_hullsrc, _hull_length), math.round(math.sqrt(_hull_length)))
- //THMA
- THMA(_hullsrc, _hull_length) =>
- ta.wma(ta.wma(_hullsrc, _hull_length / 3) * 3 - ta.wma(_hullsrc, _hull_length / 2) - ta.wma(_hullsrc, _hull_length), _hull_length)
- //SWITCH
- Mode(modeSwitch, hullsrc, len) =>
- modeSwitch == 'Hma' ? HMA(hullsrc, len) : modeSwitch == 'Ehma' ? EHMA(hullsrc, len) : modeSwitch == 'Thma' ? THMA(hullsrc, len / 2) : na
- //OUT
- _hull = Mode(modeSwitch, hullsrc, int(hull_length * hull_lengthMult))
- HULL = useHtf ? request.security(syminfo.ticker, htf, _hull) : _hull
- MHULL = HULL[0]
- SHULL = HULL[2]
- //COLOR
- hullColor = switchColor ? HULL > HULL[2] ? #00ff00 : #ff0000 : #ff9800
- ////////////////////////////////////////////////
- //ATR Automation
- ///////////////////////////////////////////////
- Showtable = input.bool (false, "Show ATR SL/TP Table", group='-------------------------ATR-------------------------')
- TimeFrame = input.timeframe("", "Timeframe the ATR is Calculated off of", group='-------------------------ATR-------------------------')
- ATRPercentageRisk = input.float (1.5, "SL ATR", group='-------------------------ATR-------------------------')
- ATRPercentageReward = input.float (2, "TP ATR", group='-------------------------ATR-------------------------')
- ShowStop = input.bool (true, "Long Stop Price", group='-------------------------ATR-------------------------')
- ShowStopS = input.bool (true, "Short Stop Price", group='-------------------------ATR-------------------------')
- ShowATR = input.bool(true, "Show ATR on the table?", group='-------------------------ATR-------------------------')
- PlotLongStop = input.bool(true, "A line on the Long Stop Level", tooltip = "These will keep moving", group='-------------------------ATR-------------------------')
- PlotShortStop = input.bool(true, "A line on the Short Stop Level", tooltip = "These will keep moving", group='-------------------------ATR-------------------------')
- textcolor = input.color(color.white, "Color of Table Text")
- BoxPlacement = input.string(position.bottom_center, "Box Placement", options = [position.bottom_right, position.bottom_left, position.top_right, position.top_center, position.bottom_center])
- //import time frame
- O = request.security(syminfo.ticker, TimeFrame, open)
- H = request.security(syminfo.ticker, TimeFrame, high)
- L = request.security(syminfo.ticker, TimeFrame, low)
- C = request.security(syminfo.ticker, TimeFrame, close)
- //Indicator math stuff
- atr = request.security(syminfo.ticker, TimeFrame, ta.atr(14))
- atr2 = math.round(atr,6)
- dtr = request.security(syminfo.ticker, "", math.round(high - low,2))
- atrp = math.round(dtr/atr * 100)
- //position size math stuff
- ATRPRisk = ATRPercentageRisk * atr2
- ATRPReward = ATRPercentageReward * atr2
- Stop = C - ATRPRisk
- StopS = C + ATRPRisk
- Stop2 = C + ATRPReward
- StopS2 = C - ATRPReward
- var table myTable = table.new(BoxPlacement, 3, 8, border_width=1)
- if barstate.islast
- if switch_atr
- //Table Cells
- table.cell(myTable, 0,0, "ATR " + str.tostring(atr2),text_color = ShowATR and switch_atr ? textcolor : na, bgcolor =color.black)
- table.cell(myTable, 1,0, "Long",text_color = ShowATR and switch_atr ? textcolor : na, bgcolor = color.green)
- table.cell(myTable, 2,0, "Short",text_color = ShowATR and switch_atr ? textcolor : na, bgcolor = color.red)
- table.cell(myTable, 0,2, "SL",text_color = ShowATR and switch_atr ? textcolor : na, bgcolor = color.red)
- table.cell(myTable, 0,1, "TP",text_color = ShowATR and switch_atr ? textcolor : na, bgcolor = color.green)
- table.cell(myTable, 1,2, ShowStop? str.tostring(Stop):na, text_color = ShowStop and switch_atr ? textcolor : na, bgcolor = color.red)
- table.cell(myTable, 2,2, ShowStopS? str.tostring(StopS):na, text_color = ShowStopS and switch_atr ? textcolor : na, bgcolor = color.red)
- table.cell(myTable, 1,1, ShowStop? str.tostring(Stop2):na, text_color = ShowStop and switch_atr ? textcolor : na, bgcolor = color.green)
- table.cell(myTable, 2,1, ShowStopS? str.tostring(StopS2):na, text_color = ShowStopS and switch_atr ? textcolor : na,bgcolor = color.green)
- //////////////////////////////////////////////////////////////////////////////////
- //Dynamic Support resistance with divergence.
- ///////////////////////////////////////////////////////////////////////////////////
- import HeWhoMustNotBeNamed/zigzag/3 as zg
- import HeWhoMustNotBeNamed/enhanced_ta/8 as eta
- import HeWhoMustNotBeNamed/supertrend/4 as st
- //showsrd = input.bool (true, "Show S/R Divergences", group='------------------------S/R Divergence-------------------------')
- maxItems = input.int(5, step=5, title="Max Depth", group='------------------------S/R Divergence-------------------------')
- showZigzag1 = input.bool(true, "",group='------------------------S/R Divergence-------------------------', inline="z1")
- zigzag1Length = input.int(8, "", group='------------------------S/R Divergence-------------------------', inline="z1")
- showZigzag2 = input.bool(true, "", group='------------------------S/R Divergence-------------------------', inline="z2")
- zigzag2Length = input.int(13, "", group='------------------------S/R Divergence-------------------------', inline="z2")
- var useAlternativeSource = true
- source = close
- oscillatorType = input.string('rsi', title='Oscillator Source ', options=["cci", "cmo", "cog", "mfi", "roc", "rsi", "stoch", "tsi", "wpr"], group='------------------------S/R Divergence-------------------------', inline='osc')
- useExternalSource = input.bool(false, title='External Source', group='------------------------S/R Divergence-------------------------', inline="osce")
- externalSource = input.source(close, title='', group='------------------------S/R Divergence-------------------------', inline="osce")
- var history = 1
- var waitForClose = true
- var atrMaType = "rma"
- var atrMultiplier = 1
- add_to_array(arr, val, maxItems)=>
- array.unshift(arr, val)
- if(array.size(arr) > maxItems)
- array.pop(arr)
- add_to_line_array(arr, val, maxItems)=>
- array.unshift(arr, val)
- if(array.size(arr) > maxItems)
- line.delete(array.pop(arr))
- add_to_label_array(arr, val, maxItems)=>
- array.unshift(arr, val)
- if(array.size(arr) > maxItems)
- label.delete(array.pop(arr))
- getSentimentDetails(sentiment) =>
- [sentimentSymbol, sentimentColor] = switch sentiment
- 4 => ['⬆', color.green]
- -4 => ['⬇', color.red]
- 3 => ['↗', color.lime]
- -3 => ['↘', color.orange]
- 2 => ['⤴',color.rgb(202, 224, 13, 0)]
- -2 => ['⤵',color.rgb(250, 128, 114, 0)]
- => ['▣', color.silver]
- [sentimentSymbol, sentimentColor]
- plot_support_resistence(showZigzag, zigzagLength, srArray, lnArray, lblArray, maxItems, largest, switch_supportresistance )=>
- if(showZigzag and switch_supportresistance )
- length = zigzagLength * 3
- longLength = zigzagLength*5
- atrLength = zigzagLength*5
- [oscillator, overbought, oversold] = eta.oscillator(oscillatorType, length, length, longLength)
- [dir_zigzag, supertrend] = st.supertrend_zigzag(length=zigzagLength, history = history, useAlternativeSource = useAlternativeSource, alternativeSource=source,
- waitForClose=waitForClose, atrlength=atrLength, multiplier=atrMultiplier, atrMaType=atrMaType)
- [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators,
- zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence,
- newPivot, doublePivot] =
- zg.zigzag(zigzagLength, oscillatorSource=useExternalSource ? externalSource : oscillator, directionBias = dir_zigzag)
- if(array.size(zigzagpivots)>1)
- price = array.get(zigzagpivots, 1)
- divergence = array.get(zigzagdivergence, 1)
- if(math.abs(divergence) == 2 or math.abs(divergence) == 3)
- if(array.indexof(srArray, price) == -1)
- add_to_array(srArray, price, maxItems)
- [sentimentSymbol, sentimentColor] = getSentimentDetails(divergence)
- lblSize = largest? size.normal : size.small
- lnStyle = largest? line.style_solid : line.style_dashed
- ln = line.new(time, price, time+1, price, extend=extend.right, xloc=xloc.bar_time, color=sentimentColor, style=lnStyle, width=largest? 1 : 0)
- lbl = label.new(time, price, sentimentSymbol, color=sentimentColor, xloc=xloc.bar_time, textcolor=sentimentColor, style=label.style_none, yloc=yloc.price, size=lblSize)
- add_to_line_array(lnArray, ln, maxItems)
- add_to_label_array(lblArray, lbl, maxItems)
- var srArray1 = array.new_float()
- var srArray2 = array.new_float()
- var lnArray1 = array.new_line()
- var lblArray1 = array.new_label()
- var lnArray2 = array.new_line()
- var lblArray2 = array.new_label()
- plot_support_resistence(showZigzag1, zigzag1Length, srArray1, lnArray1, lblArray1, maxItems, zigzag1Length>zigzag2Length, switch_supportresistance )
- plot_support_resistence(showZigzag2, zigzag2Length, srArray2, lnArray2, lblArray2, maxItems, zigzag2Length>zigzag1Length, switch_supportresistance )
- /////////////////////////
- /// STC overlay signal
- /////////////////////////
- fastLength = input(title='MACD Fast Length', defval=23, group='------------------------STC-------------------------')
- slowLength = input(title='MACD Slow Length', defval=50, group='------------------------STC-------------------------')
- cycleLength = input(title='Cycle Length', defval=10, group='------------------------STC-------------------------')
- d1Length = input(title='1st %D Length', defval=3, group='------------------------STC-------------------------')
- d2Length = input(title='2nd %D Length', defval=3, group='------------------------STC-------------------------')
- srcstc = input(title='Source', defval=close, group='------------------------STC-------------------------')
- upper = input(title='Upper Band', defval=75, group='------------------------STC-------------------------')
- lower = input(title='Lower Band', defval=25, group='------------------------STC-------------------------')
- v_show_last = input(2000, "Plotting Length", group='------------------------STC-------------------------')
- macd = ta.ema(srcstc, fastLength) - ta.ema(srcstc, slowLength)
- k = nz(fixnan(ta.stoch(macd, macd, macd, cycleLength)))
- d = ta.ema(k, d1Length)
- kd = nz(fixnan(ta.stoch(d, d, d, cycleLength)))
- stc = ta.ema(kd, d2Length)
- stc := math.max(math.min(stc, 100), 0)
- stcColor1 = stc > stc[1] ? color.green : color.red
- stcColor2 = stc > upper ? color.green : stc <= lower ? color.red : color.orange
- // buySignal = ta.crossover(stc, lower)
- // sellSignal = ta.crossunder(stc, upper)
- upperCrossover = ta.crossover(stc, upper)
- upperCrossunder = ta.crossunder(stc, upper)
- lowerCrossover = ta.crossover(stc, lower)
- lowerCrossunder = ta.crossunder(stc, lower)
- stcup = stc >= upper
- stcdown = stc <= lower
- plotshape(stcdown and switch_stc? true :na, style=shape.circle, location=location.top , show_last = v_show_last, color=color.new(color.red, 0), title='STC Sell')
- plotshape(stcup and switch_stc? true:na, style=shape.circle, location=location.top, show_last = v_show_last, color=color.new(color.green, 0), title='STC Buy')
- //////////////////////////////////////////////////////
- //vector candles
- /////////////////////////////////////////////////////
- // Indicator Settings
- var overideCandleColours = input.bool(title='Override Candles with PVSRA Colour', defval=true, tooltip="Indicator must be dragged to the top of the Object Tree to display correctly", group='------------------------PVSRA-------------------------')
- var bool override_imnt = input.bool(defval=false, title="Overide Symbol", group='------------------------PVSRA-------------------------', inline="0")
- var string pvsra_sym = input.symbol(title="", defval="BINANCE:BTCUSDTPERP", group='------------------------PVSRA-------------------------', inline="0")
- var Bull200CandleColor = input.color(color.new(color.lime, 0), title="200% Volume", group='------------------------PVSRA-------------------------', inline="1")
- var Bear200CandleColor = input.color(color.new(color.red, 0), title="", group='------------------------PVSRA-------------------------', inline = "1")
- var Bull150CandleColor = input.color(color.new(color.blue, 0), title="150% Volume", group='------------------------PVSRA-------------------------', inline="2")
- var Bear150CandleColor = input.color(color.new(color.fuchsia, 0), title="", group='------------------------PVSRA-------------------------', inline="2")
- var BullNormCandleColor = input.color(color.new(#999999, 0), title="Norm Volume", group='------------------------PVSRA-------------------------', inline="3")
- var BearNormCandleColor = input.color(color.new(#4d4d4d, 0), title="", group='------------------------PVSRA-------------------------', inline="3")
- var color candleColor = na
- var color imbalanceColor = na
- var color imbalancedLineColor = na
- var color NO_COLOR = na
- var bool chartIs120MinOrMore = false
- // Logic to reference another Instruments Volume Profile
- pvsra_imnt(sresolution,sseries) => request.security(override_imnt ? pvsra_sym : syminfo.tickerid ,sresolution,sseries, barmerge.gaps_off,barmerge.lookahead_off)
- volume_imnt = override_imnt == true? pvsra_imnt("",volume): volume
- high_imnt = override_imnt == true? pvsra_imnt("",high): high
- low_imnt = override_imnt == true? pvsra_imnt("",low): low
- close_imnt = override_imnt == true? pvsra_imnt("",close): close
- open_imnt = override_imnt == true? pvsra_imnt("",open): open
- av = ta.sma(volume_imnt, 10)//sum_2 = math.sum(volume, 10)
- value2 = volume_imnt * (high_imnt - low_imnt)
- hivalue2 = ta.highest(value2, 10)
- imnt_override_pvsra_calc_part2 = volume_imnt >= av * 1.5 ? 2 : 0
- va = volume_imnt >= av * 2 or value2 >= hivalue2 ? 1 : imnt_override_pvsra_calc_part2
- // Bull or bear Candle Colors
- isBull = close_imnt > open_imnt
- var bool is200Bull = na
- var bool is150Bull = na
- var bool is100Bull = na
- var bool is200Bear = na
- var bool is150Bear = na
- var bool is100Bear = na
- if isBull
- if va == 1
- candleColor := Bull200CandleColor
- is200Bull := true
- else
- if va == 2
- candleColor := Bull150CandleColor
- is150Bull := true
- else
- is200Bull := false
- is150Bull := false
- candleColor := BullNormCandleColor
- imbalanceColor := na
- imbalancedLineColor := na
- else
- if va == 1
- candleColor := Bear200CandleColor
- is200Bear := true
- else
- if va == 2
- candleColor := Bear150CandleColor
- is150Bear := true
- else
- is200Bear := false
- is150Bear := false
- candleColor := BearNormCandleColor
- imbalanceColor := na
- imbalancedLineColor := na
- barcolor(overideCandleColours and switch_pvsra ? candleColor : NO_COLOR)
- plotcandle(open, high, low, close, color=(overideCandleColours and switch_pvsra ? candleColor : NO_COLOR), wickcolor=(overideCandleColours and switch_pvsra? candleColor : NO_COLOR), bordercolor=(overideCandleColours and switch_pvsra? candleColor : NO_COLOR), display = display.all)
- ///////////////////////////////////////////////////
- //////// SUpply/Demand POI
- //////////////////////////////////////////////////
- // INDICATOR SETTINGS
- poi_group = '======== Supply/Demand Zone ========='
- swing_length = input.int(10, title = 'Swing High/Low Length', group = poi_group, minval = 1, maxval = 50)
- history_of_demand_to_keep = input.int(20, title = 'History To Keep', minval = 5, maxval = 50, group = poi_group)
- box_width = input.float(2.5, title = 'Supply/Demand Box Width', group = poi_group, minval = 1, maxval = 10, step = 0.5)
- // INDICATOR VISUAL SETTINGS
- show_zigzag = input.bool(false, title = 'Show Zig Zag', group = 'Visual Settings', inline = '1')
- show_price_action_labels = input.bool(false, title = 'Show Price Action Labels', group = 'Visual Settings', inline = '2')
- supply_color = input.color(color.new(#EDEDED,70), title = 'Supply', group = 'Visual Settings', inline = '3')
- supply_outline_color = input.color(color.new(color.white,100), title = 'Outline', group = 'Visual Settings', inline = '3')
- demand_color = input.color(color.new(#00FFFF,70), title = 'Demand', group = 'Visual Settings', inline = '4')
- demand_outline_color = input.color(color.new(color.white,100), title = 'Outline', group = 'Visual Settings', inline = '4')
- bos_label_color = input.color(color.white, title = 'BOS Label', group = 'Visual Settings', inline = '5')
- poi_label_color = input.color(color.white, title = 'POI Label', group = 'Visual Settings', inline = '7')
- swing_type_color = input.color(color.black, title = 'Price Action Label', group = 'Visual Settings', inline = '8')
- zigzag_color = input.color(color.new(#000000,0), title = 'Zig Zag', group = 'Visual Settings', inline = '9')
- //
- //END SETTINGS
- //
- atrpoi = ta.atr(50)
- //
- //FUNCTIONS
- //
- // FUNCTION TO ADD NEW AND REMOVE LAST IN ARRAY
- f_array_add_pop(array, new_value_to_add) =>
- array.unshift(array, new_value_to_add)
- array.pop(array)
- // FUNCTION SWING H & L LABELS
- f_sh_sl_labels(array, swing_type) =>
- var string label_text = na
- if swing_type == 1
- if array.get(array, 0) >= array.get(array, 1)
- label_text := 'HH'
- else
- label_text := 'LH'
- label.new(bar_index - swing_length, array.get(array,0), text = label_text, style=label.style_label_down, textcolor = swing_type_color, color = color.new(swing_type_color, 100), size = size.tiny)
- else if swing_type == -1
- if array.get(array, 0) >= array.get(array, 1)
- label_text := 'HL'
- else
- label_text := 'LL'
- label.new(bar_index - swing_length, array.get(array,0), text = label_text, style=label.style_label_up, textcolor = swing_type_color, color = color.new(swing_type_color, 100), size = size.tiny)
- // FUNCTION MAKE SURE SUPPLY ISNT OVERLAPPING
- f_check_overlapping(new_poi, box_array, atrpoi) =>
- atr_threshold = atrpoi * 2
- okay_to_draw = true
- for i = 0 to array.size(box_array) - 1
- top = box.get_top(array.get(box_array, i))
- bottom = box.get_bottom(array.get(box_array, i))
- poi = (top + bottom) / 2
- upper_boundary = poi + atr_threshold
- lower_boundary = poi - atr_threshold
- if new_poi >= lower_boundary and new_poi <= upper_boundary
- okay_to_draw := false
- break
- else
- okay_to_draw := true
- okay_to_draw
- // FUNCTION TO DRAW SUPPLY OR DEMAND ZONE
- f_supply_demand(value_array, bn_array, box_array, label_array, box_type, atrpoi) =>
- atr_buffer = atrpoi * (box_width / 10)
- box_left = array.get(bn_array, 0)
- box_right = bar_index
- var float box_top = 0.00
- var float box_bottom = 0.00
- var float poi = 0.00
- if box_type == 1
- box_top := array.get(value_array, 0)
- box_bottom := box_top - atr_buffer
- poi := (box_top + box_bottom) / 2
- else if box_type == -1
- box_bottom := array.get(value_array, 0)
- box_top := box_bottom + atr_buffer
- poi := (box_top + box_bottom) / 2
- okay_to_draw = f_check_overlapping(poi, box_array, atrpoi)
- // okay_to_draw = true
- //delete oldest box, and then create a new box and add it to the array
- if box_type == 1 and okay_to_draw and switch_poi
- box.delete( array.get(box_array, array.size(box_array) - 1) )
- f_array_add_pop(box_array, box.new( left = box_left, top = box_top, right = box_right, bottom = box_bottom, border_color = supply_outline_color,
- bgcolor = supply_color, extend = extend.right, text = 'SUPPLY', text_halign = text.align_center, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index))
- box.delete( array.get(label_array, array.size(label_array) - 1) )
- f_array_add_pop(label_array, box.new( left = box_left, top = poi, right = box_right, bottom = poi, border_color = color.new(poi_label_color,90),
- bgcolor = color.new(poi_label_color,90), extend = extend.right, text = 'POI', text_halign = text.align_left, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index))
- else if box_type == -1 and okay_to_draw and switch_poi
- box.delete( array.get(box_array, array.size(box_array) - 1) )
- f_array_add_pop(box_array, box.new( left = box_left, top = box_top, right = box_right, bottom = box_bottom, border_color = demand_outline_color,
- bgcolor = demand_color, extend = extend.right, text = 'DEMAND', text_halign = text.align_center, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index))
- box.delete( array.get(label_array, array.size(label_array) - 1) )
- f_array_add_pop(label_array, box.new( left = box_left, top = poi, right = box_right, bottom = poi, border_color = color.new(poi_label_color,90),
- bgcolor = color.new(poi_label_color,90), extend = extend.right, text = 'POI', text_halign = text.align_left, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index))
- // FUNCTION TO CHANGE SUPPLY/DEMAND TO A BOS IF BROKEN
- f_sd_to_bos(box_array, bos_array, label_array, zone_type) =>
- if zone_type == 1 and switch_poi
- for i = 0 to array.size(box_array) - 1
- level_to_break = box.get_top(array.get(box_array,i))
- // if ta.crossover(close, level_to_break)
- if close >= level_to_break
- copied_box = box.copy(array.get(box_array,i))
- f_array_add_pop(bos_array, copied_box)
- mid = (box.get_top(array.get(box_array,i)) + box.get_bottom(array.get(box_array,i))) / 2
- box.set_top(array.get(bos_array,0), mid)
- box.set_bottom(array.get(bos_array,0), mid)
- box.set_extend( array.get(bos_array,0), extend.none)
- box.set_right( array.get(bos_array,0), bar_index)
- box.set_text( array.get(bos_array,0), 'BOS' )
- box.set_text_color( array.get(bos_array,0), bos_label_color)
- box.set_text_size( array.get(bos_array,0), size.small)
- box.set_text_halign( array.get(bos_array,0), text.align_center)
- box.set_text_valign( array.get(bos_array,0), text.align_center)
- box.delete(array.get(box_array, i))
- box.delete(array.get(label_array, i))
- if zone_type == -1 and switch_poi
- for i = 0 to array.size(box_array) - 1
- level_to_break = box.get_bottom(array.get(box_array,i))
- // if ta.crossunder(close, level_to_break)
- if close <= level_to_break
- copied_box = box.copy(array.get(box_array,i))
- f_array_add_pop(bos_array, copied_box)
- mid = (box.get_top(array.get(box_array,i)) + box.get_bottom(array.get(box_array,i))) / 2
- box.set_top(array.get(bos_array,0), mid)
- box.set_bottom(array.get(bos_array,0), mid)
- box.set_extend( array.get(bos_array,0), extend.none)
- box.set_right( array.get(bos_array,0), bar_index)
- box.set_text( array.get(bos_array,0), 'BOS' )
- box.set_text_color( array.get(bos_array,0), bos_label_color)
- box.set_text_size( array.get(bos_array,0), size.small)
- box.set_text_halign( array.get(bos_array,0), text.align_center)
- box.set_text_valign( array.get(bos_array,0), text.align_center)
- box.delete(array.get(box_array, i))
- box.delete(array.get(label_array, i))
- // FUNCTION MANAGE CURRENT BOXES BY CHANGING ENDPOINT
- f_extend_box_endpoint(box_array) =>
- for i = 0 to array.size(box_array) - 1
- box.set_right(array.get(box_array, i), bar_index + 100)
- // CALCULATE SWING HIGHS & SWING LOWS
- swing_high = ta.pivothigh(high, swing_length, swing_length)
- swing_low = ta.pivotlow(low, swing_length, swing_length)
- // ARRAYS FOR SWING H/L & BN
- var swing_high_values = array.new_float(5,0.00)
- var swing_low_values = array.new_float(5,0.00)
- var swing_high_bns = array.new_int(5,0)
- var swing_low_bns = array.new_int(5,0)
- // ARRAYS FOR SUPPLY / DEMAND
- var current_supply_box = array.new_box(history_of_demand_to_keep, na)
- var current_demand_box = array.new_box(history_of_demand_to_keep, na)
- // ARRAYS FOR SUPPLY / DEMAND POI LABELS
- var current_supply_poi = array.new_box(history_of_demand_to_keep, na)
- var current_demand_poi = array.new_box(history_of_demand_to_keep, na)
- // ARRAYS FOR BOS
- var supply_bos = array.new_box(5, na)
- var demand_bos = array.new_box(5, na)
- //
- //END CALCULATIONS
- //
- // NEW SWING HIGH
- if not na(swing_high)
- //MANAGE SWING HIGH VALUES
- f_array_add_pop(swing_high_values, swing_high)
- f_array_add_pop(swing_high_bns, bar_index[swing_length])
- if show_price_action_labels
- f_sh_sl_labels(swing_high_values, 1)
- f_supply_demand(swing_high_values, swing_high_bns, current_supply_box, current_supply_poi, 1, atrpoi)
- // NEW SWING LOW
- else if not na(swing_low)
- //MANAGE SWING LOW VALUES
- f_array_add_pop(swing_low_values, swing_low)
- f_array_add_pop(swing_low_bns, bar_index[swing_length])
- if show_price_action_labels
- f_sh_sl_labels(swing_low_values, -1)
- f_supply_demand(swing_low_values, swing_low_bns, current_demand_box, current_demand_poi, -1, atrpoi)
- f_sd_to_bos(current_supply_box, supply_bos, current_supply_poi, 1)
- f_sd_to_bos(current_demand_box, demand_bos, current_demand_poi, -1)
- f_extend_box_endpoint(current_supply_box)
- f_extend_box_endpoint(current_demand_box)
- //ZIG ZAG
- h = ta.highest(high, swing_length * 2 + 1)
- l = ta.lowest(low, swing_length * 2 + 1)
- f_isMin(len) =>
- l == low[len]
- f_isMax(len) =>
- h == high[len]
- var dirUp = false
- var lastLow = high * 100
- var lastHigh = 0.0
- var timeLow = bar_index
- var timeHigh = bar_index
- var line li = na
- f_drawLine() =>
- _li_color = show_zigzag and switch_poi ? zigzag_color : color.new(#ffffff,100)
- line.new(timeHigh - swing_length, lastHigh, timeLow - swing_length, lastLow, xloc.bar_index, color=_li_color, width=2)
- if dirUp
- if f_isMin(swing_length) and low[swing_length] < lastLow
- lastLow := low[swing_length]
- timeLow := bar_index
- line.delete(li)
- li := f_drawLine()
- li
- if f_isMax(swing_length) and high[swing_length] > lastLow
- lastHigh := high[swing_length]
- timeHigh := bar_index
- dirUp := false
- li := f_drawLine()
- li
- if not dirUp
- if f_isMax(swing_length) and high[swing_length] > lastHigh
- lastHigh := high[swing_length]
- timeHigh := bar_index
- line.delete(li)
- li := f_drawLine()
- li
- if f_isMin(swing_length) and low[swing_length] < lastHigh
- lastLow := low[swing_length]
- timeLow := bar_index
- dirUp := true
- li := f_drawLine()
- if f_isMax(swing_length) and high[swing_length] > lastLow
- lastHigh := high[swing_length]
- timeHigh := bar_index
- dirUp := false
- li := f_drawLine()
- li
- ///////////////////////////////////////////////////
- /////////// Vector Zone
- //////////////////////////////////////////////////
- import TradersReality/Traders_Reality_Lib/1 as trLib
- color redVectorColor = input.color(title='Vector: Red', group='------------Liquidity Zone---------------', defval=color.red, inline='vectors')
- color greenVectorColor = input.color(title='Green', group='------------Liquidity Zone---------------', defval=color.lime, inline='vectors')
- color violetVectorColor = input.color(title='Violet', group='------------Liquidity Zone---------------', defval=color.fuchsia, inline='vectors')
- color blueVectorColor = input.color(title='Blue', group='------------Liquidity Zone---------------', defval=color.blue, inline='vectors', tooltip='Bull bars are green and bear bars are red when the bar is with volume >= 200% of the average volume of the 10 previous bars, or bars where the product of candle spread x candle volume is >= the highest for the 10 previous bars.\n Bull bars are blue and bear are violet when the bar is with with volume >= 150% of the average volume of the 10 previous bars.')
- color regularCandleUpColor = input.color(title='Regular: Up Candle', group='------------Liquidity Zone---------------', defval=#999999, inline='nonVectors')
- color regularCandleDownColor = input.color(title='Down Candle', group='------------Liquidity Zone---------------', defval=#4d4d4d, inline='nonVectors', tooltip='Bull bars are light gray and bear are dark gray when none of the red/green/blue/violet vector conditions are met.')
- bool setcandlecolors = input.bool(false, title='Set PVSRA candle colors?', group='------------Liquidity Zone---------------', inline='setCandle')
- int zonesMax = input.int(500, 'Maximum zones to draw', group='------------Liquidity Zone---------------')
- string zoneType = input.string(group='------------Liquidity Zone---------------', defval='Body only', title='Zone top/bottom is defined with: ', options=['Body only', 'Body with wicks'])
- string zoneUpdateType = input.string(group='------------Liquidity Zone---------------', defval='Body with wicks', title='Zones are cleared using candle: ', options=['Body only', 'Body with wicks'])
- int borderWidth = input.int(0, 'Zone border width', group='------------Liquidity Zone---------------')
- bool colorOverride = input.bool(true, 'Override color?' , group='------------Liquidity Zone---------------', inline="vcz1")
- color zoneColor = input.color(title='Color', group='------------Liquidity Zone---------------', defval=color.rgb(255, 230, 75, 90), inline="vcz1", tooltip='the vector candle zones color to use if you dont not want to use the PVSRA Candle Colors.')
- int transperancy = input.int(90, 'Zone Transperancy', minval = 0, maxval = 100, group='------------Liquidity Zone---------------', tooltip='If the vector candle zones color is not overriden, then we want to set the transparancy of the vector candle colors as defined by the PBSRA candle colors. This setting only affects the candle zone colors not the candle colors themselves.')
- bool overrideSym = input.bool(group='PVSRA Override', title='Override chart symbol?', defval=false, inline='pvsra')
- string pvsraSym = input.string(group='PVSRA Override', 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')
- pvsraVolume(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
- request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', volume, barmerge.gaps_off, barmerge.lookahead_off)
- pvsraHigh(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
- request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', high, barmerge.gaps_off, barmerge.lookahead_off)
- pvsraLow(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
- request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', low, barmerge.gaps_off, barmerge.lookahead_off)
- pvsraClose(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
- request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', close, barmerge.gaps_off, barmerge.lookahead_off)
- pvsraOpen(overrideSymbolX, pvsraSymbolX, tickerIdX) =>
- request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', open, barmerge.gaps_off, barmerge.lookahead_off)
- pvsraVolume = pvsraVolume(overrideSym, pvsraSym, syminfo.tickerid)
- pvsraHigh = pvsraHigh(overrideSym, pvsraSym, syminfo.tickerid)
- pvsraLow = pvsraLow(overrideSym, pvsraSym, syminfo.tickerid)
- pvsraClose = pvsraClose(overrideSym, pvsraSym, syminfo.tickerid)
- pvsraOpen = pvsraOpen(overrideSym, pvsraSym, syminfo.tickerid)
- [pvsraColor, alertFlag, averageVolume, volumeSpread, highestVolumeSpread] = trLib.calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, regularCandleDownColor, regularCandleUpColor)
- var zoneBoxesAbove = array.new_box()
- var zoneBoxesBelow = array.new_box()
- barcolor(setcandlecolors ? pvsraColor : na)
- pvsra = trLib.getPvsraFlagByColor(switch_vectorzone ? pvsraColor:na, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, regularCandleUpColor)
- trLib.updateZones(pvsra, 0, zoneBoxesBelow, zonesMax, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneUpdateType, zoneColor, zoneType, borderWidth, colorOverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor)
- trLib.updateZones(pvsra, 1, zoneBoxesAbove, zonesMax, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneUpdateType, zoneColor, zoneType, borderWidth, colorOverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor)
- trLib.cleanarr(zoneBoxesAbove)
- trLib.cleanarr(zoneBoxesBelow)
- //*****************
- // Market sessions
- //*****************
- string weekend_sessions = ':1234567'
- string no_weekend_sessions = ':23456'
- bool show_rectangle1 = input.bool(group='Market session: London (0800-1630 UTC+0) - DST Aware', 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) - DST Aware', 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) - DST Aware', 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) - DST Aware', defval='London', title='Name:', inline='session1style')
- color sess1col = input.color(group='Market session: London (0800-1630 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(120, 123, 134, 75), inline='session1style')
- color sess1colLabel = input.color(group='Market session: London (0800-1630 UTC+0) - DST Aware', title='Label', defval=color.rgb(120, 123, 134, 0), inline='session1style')
- string sess1TimeX = '0800-1630'//input.session(group='Market session: London (0800-1630 UTC+0)', 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 and times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
- sess1Time = show_markets_weekends ? sess1TimeX + weekend_sessions : sess1TimeX + no_weekend_sessions
- bool show_rectangle2 = input.bool(group='Market session: New York (1430-2100 UTC+0) - DST Aware', 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) - DST Aware', 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) - DST Aware', 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) - DST Aware', defval='NewYork', title='Name:', inline='session2style')
- color sess2col = input.color(group='Market session: New York (1430-2100 UTC+0) - DST Aware', 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) - DST Aware', title='Label', defval=color.rgb(253, 84, 87, 25), inline='session2style')
- string sess2TimeX = '1430-2100'//input.session(group='Market session: New York (1430-2100 UTC+0)', 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 times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
- sess2Time = show_markets_weekends ? sess2TimeX + weekend_sessions : sess2TimeX + no_weekend_sessions
- bool show_rectangle3 = input.bool(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', 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: Tokyo (0000-0600 UTC+0) - DST Aware', defval=true, title='Label?', inline='session3conf') and show_rectangle3 and show_markets
- bool show_or3 = input.bool(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', 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: Tokyo (0000-0600 UTC+0) - DST Aware', defval='Tokyo', title='Name:', inline='session3style')
- color sess3col = input.color(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(80, 174, 85, 75), inline='session3style')
- color sess3colLabel = input.color(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', title='Label', defval=color.rgb(80, 174, 85, 25), inline='session3style')
- string sess3TimeX = '0000-0600'//input.session(group='Market session: Tokyo (0000-0600 UTC+0)', 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 times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
- sess3Time = show_markets_weekends ? sess3TimeX + weekend_sessions : sess3TimeX + no_weekend_sessions
- bool show_rectangle4 = input.bool(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', 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) - DST Aware', 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) - DST Aware', 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) - DST Aware', defval='HongKong', title='Name:', inline='session4style')
- color sess4col = input.color(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', 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) - DST Aware', title='Label', defval=color.rgb(128, 127, 23, 25), inline='session4style')
- string sess4TimeX = '0130-0800'//input.session(group='Market session: Hong Kong (0130-0800 UTC+0)', 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 times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
- sess4Time = show_markets_weekends ? sess4TimeX + weekend_sessions : sess4TimeX + no_weekend_sessions
- bool show_rectangle5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', 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) - DST Aware', 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) - DST Aware', 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) - DST Aware', defval='Sydney', title='Name:', inline='session5style')
- color sess5col = input.color(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', 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) - DST Aware', title='Label', defval=color.rgb(37, 228, 123, 25), inline='session5style')
- string sess5TimeX = '2200-0600'//input.session(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', 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 times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
- sess5Time = show_markets_weekends ? sess5TimeX + weekend_sessions : sess5TimeX + no_weekend_sessions
- bool show_rectangle6 = input.bool(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', 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 (0800-0900 UTC+0) - DST Aware', defval=true, title='Label?', inline='session6conf') and show_rectangle6 and show_markets
- bool show_or6 = input.bool(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', 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 (0800-0900 UTC+0) - DST Aware', defval='EU Brinks', title='Name:', inline='session6style')
- color sess6col = input.color(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(255, 255, 255, 65), inline='session6style')
- color sess6colLabel = input.color(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', title='Label', defval=color.rgb(255, 255, 255, 25), inline='session6style')
- string sess6TimeX = '0800-0900'//input.session(group='Market session: EU Brinks (0800-0900 UTC+0)', defval='0800-0900', 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 times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
- sess6Time = show_markets_weekends ? sess6TimeX + weekend_sessions : sess6TimeX + no_weekend_sessions
- bool show_rectangle7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', 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) - DST Aware', 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) - DST Aware', 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) - DST Aware', defval='US Brinks', title='Name:', inline='session7style')
- color sess7col = input.color(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', 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) - DST Aware', title='Label', defval=color.rgb(255, 255, 255, 25), inline='session7style')
- string sess7TimeX = '1400-1500'//input.session(group='Market session: US Brinks (1400-1500 UTC+0)', 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 times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
- sess7Time = show_markets_weekends ? sess7TimeX + weekend_sessions : sess7TimeX + no_weekend_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
- 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 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]
- if newTF
- 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_y(line_label, hi)
- int(na)
- //*****************************//
- // Daylight Savings Time Flags //
- //*****************************//
- int previousSunday = dayofmonth - dayofweek + 1
- bool nyDST = na
- bool ukDST = na
- bool sydDST = na
- if month < 3 or month > 11
- nyDST := false
- ukDST := false
- sydDST := true
- else if month > 4 and month < 10
- nyDST := true
- ukDST := true
- sydDST := false
- else if month == 3
- nyDST := previousSunday >= 8
- ukDST := previousSunday >= 24
- sydDST := true
- else if month == 4
- nyDST := true
- ukDST := true
- sydDST := previousSunday <= 0
- else if month == 10
- nyDST := true
- ukDST := previousSunday <= 24
- sydDST := previousSunday >= 0
- else // month == 11
- nyDST := previousSunday <= 0
- ukDST := false
- sydDST := true
- if ukDST
- 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 nyDST
- 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')
- // Tokyo
- draw_open_range(sess3Time,sess3col,show_or3,'GMT+0')
- draw_session_hilo(sess3Time, show_rectangle3, show_label3, sess3colLabel, sess3Label, 'GMT+0')
- // Hong Kong
- draw_open_range(sess4Time,sess4col,show_or4,'GMT+0')
- draw_session_hilo(sess4Time, show_rectangle4, show_label4, sess4colLabel, sess4Label, 'GMT+0')
- if sydDST
- 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 nyDST
- 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')
- //////////////////////////////////////////////////
- ////QQE MOD
- /////////////////////////////////////////////////
- RSI_Period = input(6, title='RSI Length', group='------------------------QQE-------------------------')
- SF = input(5, title='RSI Smoothing', group='------------------------QQE-------------------------')
- QQE = input(3, title='Fast QQE Factor', group='------------------------QQE-------------------------')
- ThreshHold = input(3, title='Thresh-hold', group='------------------------QQE-------------------------')
- //
- srcqqe = input(close, title='RSI Source', group='------------------------QQE-------------------------')
- //
- //
- Wilders_Period = RSI_Period * 2 - 1
- Rsi = ta.rsi(srcqqe, RSI_Period)
- RsiMa = ta.ema(Rsi, SF)
- AtrRsi = math.abs(RsiMa[1] - RsiMa)
- MaAtrRsi = ta.ema(AtrRsi, Wilders_Period)
- dar = ta.ema(MaAtrRsi, Wilders_Period) * QQE
- longband = 0.0
- shortband = 0.0
- trend = 0
- DeltaFastAtrRsi = dar
- RSIndex = RsiMa
- newshortband = RSIndex + DeltaFastAtrRsi
- newlongband = RSIndex - DeltaFastAtrRsi
- longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? math.max(longband[1], newlongband) : newlongband
- shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? math.min(shortband[1], newshortband) : newshortband
- cross_1 = ta.cross(longband[1], RSIndex)
- trend := ta.cross(RSIndex, shortband[1]) ? 1 : cross_1 ? -1 : nz(trend[1], 1)
- FastAtrRsiTL = trend == 1 ? longband : shortband
- length = input.int(50, minval=1, title='Bollinger Length', group='------------------------QQE-------------------------')
- multqqe = input.float(0.35, minval=0.001, maxval=5, step=0.1, title='BB Multiplier', group='------------------------QQE-------------------------')
- basis = ta.sma(FastAtrRsiTL - 50, length)
- dev = multqqe * ta.stdev(FastAtrRsiTL - 50, length)
- upperqqe = basis + dev
- lowerqqe = basis - dev
- color_bar = RsiMa - 50 > upperqqe ? #00c3ff : RsiMa - 50 < lowerqqe ? #ff0062 : color.gray
- //
- // Zero cross
- QQEzlong = 0
- QQEzlong := nz(QQEzlong[1])
- QQEzshort = 0
- QQEzshort := nz(QQEzshort[1])
- QQEzlong := RSIndex >= 50 ? QQEzlong + 1 : 0
- QQEzshort := RSIndex < 50 ? QQEzshort + 1 : 0
- //
- ////////////////////////////////////////////////////////////////
- RSI_Period2 = input(6, title='RSI Length', group='------------------------QQE-------------------------')
- SF2 = input(5, title='RSI Smoothing', group='------------------------QQE-------------------------')
- QQE2 = input(1.61, title='Fast QQE2 Factor', group='------------------------QQE-------------------------')
- ThreshHold2 = input(3, title='Thresh-hold', group='------------------------QQE-------------------------')
- src2 = input(close, title='RSI Source', group='------------------------QQE-------------------------')
- //
- //
- Wilders_Period2 = RSI_Period2 * 2 - 1
- Rsi2 = ta.rsi(src2, RSI_Period2)
- RsiMa2 = ta.ema(Rsi2, SF2)
- AtrRsi2 = math.abs(RsiMa2[1] - RsiMa2)
- MaAtrRsi2 = ta.ema(AtrRsi2, Wilders_Period2)
- dar2 = ta.ema(MaAtrRsi2, Wilders_Period2) * QQE2
- longband2 = 0.0
- shortband2 = 0.0
- trend2 = 0
- DeltaFastAtrRsi2 = dar2
- RSIndex2 = RsiMa2
- newshortband2 = RSIndex2 + DeltaFastAtrRsi2
- newlongband2 = RSIndex2 - DeltaFastAtrRsi2
- longband2 := RSIndex2[1] > longband2[1] and RSIndex2 > longband2[1] ? math.max(longband2[1], newlongband2) : newlongband2
- shortband2 := RSIndex2[1] < shortband2[1] and RSIndex2 < shortband2[1] ? math.min(shortband2[1], newshortband2) : newshortband2
- cross_2 = ta.cross(longband2[1], RSIndex2)
- trend2 := ta.cross(RSIndex2, shortband2[1]) ? 1 : cross_2 ? -1 : nz(trend2[1], 1)
- FastAtrRsi2TL = trend2 == 1 ? longband2 : shortband2
- //
- // Zero cross
- QQE2zlong = 0
- QQE2zlong := nz(QQE2zlong[1])
- QQE2zshort = 0
- QQE2zshort := nz(QQE2zshort[1])
- QQE2zlong := RSIndex2 >= 50 ? QQE2zlong + 1 : 0
- QQE2zshort := RSIndex2 < 50 ? QQE2zshort + 1 : 0
- //
- qqeline = FastAtrRsi2TL - 50
- hcolor2 = RsiMa2 - 50 > ThreshHold2 ? color.silver : RsiMa2 - 50 < 0 - ThreshHold2 ? color.silver : na
- Greenbar1 = RsiMa2 - 50 > ThreshHold2
- Greenbar2 = RsiMa - 50 > upperqqe
- Redbar1 = RsiMa2 - 50 < 0 - ThreshHold2
- Redbar2 = RsiMa - 50 < lowerqqe
- /////////////////////////////////////////////////
- /////////////// Volume Up/Down
- ////////////////////////////////////////////////
- lowerTimeframeTooltip = "The indicator scans lower timeframe data to approximate Up/Down volume. By default, the timeframe is chosen automatically. These inputs override this with a custom timeframe.
- \n\nHigher timeframes provide more historical data, but the data will be less precise."
- useCustomTimeframeInput = input.bool(false, "Use custom timeframe", tooltip = lowerTimeframeTooltip)
- lowerTimeframeInput = input.timeframe("1", "Timeframe")
- upAndDownVolume() =>
- posVol = 0.0
- negVol = 0.0
- switch
- close > open => posVol += volume
- close < open => negVol -= volume
- close >= close[1] => posVol += volume
- close < close[1] => negVol -= volume
- [posVol, negVol]
- lowerTimeframe = switch
- useCustomTimeframeInput => lowerTimeframeInput
- timeframe.isintraday => "1"
- timeframe.isdaily => "5"
- => "60"
- [upVolumeArray, downVolumeArray] = request.security_lower_tf(syminfo.tickerid, lowerTimeframe, upAndDownVolume())
- upVolume = array.sum(upVolumeArray)
- downVolume = array.sum(downVolumeArray)
- delta = upVolume + downVolume
- prevdelta = delta[1]
- var cumVol = 0.
- cumVol += nz(volume)
- if barstate.islast and cumVol == 0
- runtime.error("The data vendor doesn't provide volume data for this symbol.")
- respectemavalue = ta.ema(src, respectemaperiod)
- isaboverespectema = close > respectemavalue
- isbelowrespectema = close < respectemavalue
- isqqebarabove = Greenbar1 and Greenbar2
- isqqebarbelow = Redbar1 and Redbar2
- dv2up = bool (na)
- dvup = bool (na)
- if dvtype == 'Threshold'
- dvup := vol > t and vol>=1.1
- else if dvtype == '10p Difference'
- dvup := vol > t and (vol - t >= 0.1)
- else
- dvup := vol > t
- sarup = out < close
- sardown = out > close
- longvol = bool(na)
- shortvol = bool (na)
- if volumetype == 'Delta'
- longvol := delta > 0 and delta > delta[1]
- shortvol := delta < 0 and delta < delta[1]
- else
- longvol := upVolume > upVolume[1]
- shortvol := downVolume < downVolume[1]
- longCond = bool(na)
- shortCond = bool(na)
- longCond2 = bool(na)
- shortCond2 = bool(na)
- vipcondition = bool(na)
- vimcondition = bool(na)
- if vitype == 'Simple'
- vipcondition := vip > vim
- vimcondition := vip < vim
- else
- vipcondition := vip > vim and vip > viupper and vip > vip[1] and vim < vim[1] and vim[1] <= vilower and vip[1] >= viupper
- vimcondition := vip < vim and vim > viupper and vim > vim[1] and vip < vip [1] and vip[1] <= vilower and vim [1] >= viupper
- vipcondition2 = vip > vim
- vimcondition2 = vip < vim
- ///////////////////////////////////ADX Condition ////////////////////////////////////////
- adxcycle = 0
- adxup = ta.crossover(adx, keyLevel)
- adxdown = ta.crossunder(adx, keyLevel)
- adxcycle := adxup ? 1 : adxdown ? -1 : adxcycle[1]
- adxcondition = string(na)
- adxupcondition = bool(na)
- adxdowncondition = bool (na)
- if adxtype == 'Adx & +Di -Di'
- adxupcondition := diplus > diminus and adx>=keyLevel
- adxdowncondition := diplus < diminus and adx>=keyLevel
- if adxtype == 'Adx Only'
- adxupcondition := adx>keyLevel
- adxdowncondition := adx>keyLevel
- else
- if adxcycle == -1
- adxupcondition := diplus > diminus and adx>=keyLevel and diplus - diminus > 1
- adxdowncondition := diplus < diminus and adx>=keyLevel and diminus - diplus > 1
- else if adxcycle==1
- adxupcondition := diplus > diminus and adx>=keyLevel and adx<55 and (adx>adx[1] or (diplus > diplus[1] and diminus < diminus[1])) and diplus - diminus > 1
- adxdowncondition := diplus < diminus and adx>=keyLevel and adx<55 and (adx>adx[1] or (diplus < diplus[1] and diminus > diminus[1])) and diminus - diplus > 1
- ///////////////adx condition end/////////////////////////////////////////////////////
- justcontinue = bool(true)
- isstup = bool(na)
- isstdown = bool(na)
- isstup := sttrend == 1
- isstdown := sttrend != 1
- ismacdup = bool(na)
- ismacddown = bool(na)
- isqqeabove = bool(na)
- isqqebelow = bool(na)
- if qqetype == 'Line'
- isqqeabove := qqeline>0
- isqqebelow := qqeline<0
- else if qqetype == 'Bar'
- isqqeabove := RsiMa2 - 50 > 0 and (Greenbar1 and Greenbar2)
- isqqebelow := RsiMa2 - 50 < 0 and (Redbar1 and Redbar2)
- else if qqetype == 'Line & Bar'
- isqqeabove := RsiMa2 - 50 > 0 and (Greenbar1 and Greenbar2) and qqeline>0
- isqqebelow := RsiMa2 - 50 < 0 and (Redbar1 and Redbar2) and qqeline<0
- rsimalong2 = bool(na)
- rsimashort2 = bool(na)
- rsimalong2:= rsiMA >= rsiMA[1]
- rsimashort2:= rsiMA <= rsiMA[1]
- rsilimitlong = rsi >= rsilimitup
- rsilimitshort = rsi <= rsilimitdown
- rsimalimitlong = rsiMA >= rsimalimitup
- rsimalimitshort = rsiMA <= rsimalimitdown
- leadinglongcond = bool(na)
- leadingshortcond = bool(na)
- if leadingindicator == 'Range Filter'
- if rftype == 'Default'
- leadinglongcond := src > filt and src > src[1] and upward > 0 or src > filt and src < src[1] and upward > 0
- leadingshortcond := src < filt and src < src[1] and downward > 0 or src < filt and src > src[1] and downward > 0
- else if rftype == 'DW'
- leadinglongcond := rfupward
- leadingshortcond := rfdownward
- else if leadingindicator == 'DMI (Adx)'
- // respectadx := true
- if adxtype == 'Basic'
- leadinglongcond := diplus > diminus and adx>=keyLevel
- leadingshortcond := diplus < diminus and adx>=keyLevel
- else
- if adxcycle == -1
- leadinglongcond := diplus > diminus and adx>=keyLevel and diplus - diminus > 1
- leadingshortcond := diplus < diminus and adx>=keyLevel and diminus - diplus > 1
- else if adxcycle==1
- leadinglongcond := diplus > diminus and adx>=keyLevel and adx<55 and (adx>adx[1] or (diplus > diplus[1] and diminus < diminus[1])) and diplus - diminus > 1
- leadingshortcond := diplus < diminus and adx>=keyLevel and adx<55 and (adx>adx[1] or (diplus < diplus[1] and diminus > diminus[1])) and diminus - diplus > 1
- else if leadingindicator == 'Parabolic SAR (PSAR)'
- // respectsar := true
- leadinglongcond := out < close
- leadingshortcond := out > close
- else if leadingindicator == 'RQK'
- // respectsar := true
- leadinglongcond := rqkuptrend
- leadingshortcond := rqkdowntrend
- else if leadingindicator == 'Trend Trader'
- // respectsar := true
- leadinglongcond := ttlong
- leadingshortcond := ttshort
- else if leadingindicator == 'Donchian Trend Ribbon'
- // respectsar := true
- leadinglongcond := donchian_long
- leadingshortcond := donchian_short
- else if leadingindicator == '2 EMA Cross'
- // respectsar := true
- leadinglongcond := first_2ema > second_2ema
- leadingshortcond := first_2ema < second_2ema
- else if leadingindicator == '3 EMA Cross'
- // respectsar := true
- leadinglongcond := first_3ema > second_3ema and first_3ema > third_3ema and second_3ema>third_3ema
- leadingshortcond := first_3ema < second_3ema and first_3ema < third_3ema and second_3ema<third_3ema
- else if leadingindicator == 'Chandelier Exit'
- // respectsar := true
- leadinglongcond := ce_long
- leadingshortcond := ce_short
- else if leadingindicator == 'Stochastic'
- // respectsar := true
- leadinglongcond := stoch_long
- leadingshortcond := stoch_short
- else if leadingindicator == 'Vortex Index'
- // respectvi := true
- if vitype == 'Simple'
- leadinglongcond := vip > vim
- leadingshortcond := vip < vim
- else
- leadinglongcond := vip > vim and vip > viupper and vip > vip[1] and vim < vim[1] and vim[1] <= vilower and vip[1] >= viupper
- leadingshortcond := vip < vim and vim > viupper and vim > vim[1] and vip < vip [1] and vip[1] <= vilower and vim [1] >= viupper
- else if leadingindicator == 'Schaff Trend Cycle (STC)'
- // respectstc := true
- leadinglongcond := stc >= upper
- leadingshortcond := stc <= upper
- else if leadingindicator == 'Wolfpack Id'
- // respectstc := true
- leadinglongcond := wolf_long
- leadingshortcond := wolf_short
- else if leadingindicator == 'B-Xtrender'
- // respectstc := true
- leadinglongcond := bx_long
- leadingshortcond := bx_short
- else if leadingindicator == 'Bull Bear Power Trend'
- // respectstc := true
- leadinglongcond := bbpt_long
- leadingshortcond := bbpt_short
- else if leadingindicator == 'QQE Mod'
- // respectqqe := true
- if qqetype == 'Line'
- leadinglongcond := qqeline>0
- leadingshortcond := qqeline<0
- else if qqetype == 'Bar'
- leadinglongcond := RsiMa2 - 50 > 0 and (Greenbar1 and Greenbar2)
- leadingshortcond := RsiMa2 - 50 < 0 and (Redbar1 and Redbar2)
- else if qqetype == 'Line & Bar'
- leadinglongcond := RsiMa2 - 50 > 0 and (Greenbar1 and Greenbar2) and qqeline>0
- leadingshortcond := RsiMa2 - 50 < 0 and (Redbar1 and Redbar2) and qqeline<0
- else if leadingindicator == 'MACD'
- // respectqqe := true
- if macdtype == 'MACD Crossover'
- leadinglongcond := macdd > signal
- leadingshortcond := macdd < signal
- else if macdtype == 'Zero line crossover'
- leadinglongcond := macdd > signal and macdd > 0.00000
- leadingshortcond := macdd < signal and macdd < 0.00000
- else if leadingindicator == 'RSI'
- // respectqqe := true
- if rsitype == 'RSI MA Cross'
- leadinglongcond := rsi > rsiMA
- leadingshortcond := rsi < rsiMA
- else if rsitype == 'RSI Exits OB/OS zones'
- leadinglongcond := rsi > rsi_lower and rsi[1] < rsi_lower
- leadingshortcond := rsi < rsi_upper and rsi[1] > rsi_upper
- else if rsitype == 'RSI Level'
- leadinglongcond := rsi > respectrsilevel
- leadingshortcond := rsi < respectrsilevel
- else if leadingindicator == 'Chaikin Money Flow'
- // respectqqe := true
- leadinglongcond := chaikin_long
- leadingshortcond := chaikin_short
- else if leadingindicator == 'Volatility Oscillator'
- // respectqqe := true
- leadinglongcond := vo_long
- leadingshortcond := vo_short
- else if leadingindicator == 'SSL Channel'
- // respectqqe := true
- leadinglongcond := ssl_long
- leadingshortcond := ssl_short
- else if leadingindicator == 'Awesome Oscillator'
- // respectqqe := true
- leadinglongcond := ao_long
- leadingshortcond := ao_short
- else if leadingindicator == 'Supertrend'
- leadinglongcond := sttrend == 1
- leadingshortcond := sttrend != 1
- else if leadingindicator == 'Waddah Attar Explosion'
- leadinglongcond := wae_long
- leadingshortcond := wae_short
- else if leadingindicator == 'Hull Suite'
- leadinglongcond := HULL > HULL[2]
- leadingshortcond := HULL < HULL[2]
- else if leadingindicator == 'BB Oscillator'
- leadinglongcond := bbosc_long
- leadingshortcond := bbosc_short
- else if leadingindicator == 'Ichimoku Cloud'
- leadinglongcond := ichi_long
- leadingshortcond := ichi_short
- else if leadingindicator == 'VWAP'
- leadinglongcond := long_vwap
- leadingshortcond := short_vwap
- else if leadingindicator == 'SuperIchi'
- leadinglongcond := superichi_long
- leadingshortcond := superichi_short
- else if leadingindicator == 'Trend Meter'
- if tmtype == '3 TM and 2 TB change to same color'
- leadinglongcond := TB1Green and TB2Green and (TrendBar1Result and TrendBar2Result and TrendBar3Result ? 1 : 0)
- leadingshortcond := TB1Red and TB2Red and (not TrendBar1Result and not TrendBar2Result and not TrendBar3Result ? 1 : 0)
- else if tmtype == '3 TM change to same color'
- leadinglongcond := TrendBar1Result and TrendBar2Result and TrendBar3Result ? 1 : 0
- leadingshortcond := not TrendBar1Result and not TrendBar2Result and not TrendBar3Result ? 1 : 0
- else if tmtype == '3 TM, 2 TB and Wavetrend change to same color'
- leadinglongcond := TB1Green and TB2Green and (TrendBar1Result and TrendBar2Result and TrendBar3Result ? 1 : 0) and MSBar1PositiveWaveTrendSignal
- leadingshortcond := TB1Red and TB2Red and (not TrendBar1Result and not TrendBar2Result and not TrendBar3Result ? 1 : 0) and MSBar1NegativeWaveTrendSignal
- else if leadingindicator == 'CCI'
- leadinglongcond := ccilong
- leadingshortcond := ccishort
- tmup = bool(na)
- tmdown = bool(na)
- if tmtype == '3 TM and 2 TB change to same color'
- tmup := TB1Green and TB2Green and (TrendBar1Result and TrendBar2Result and TrendBar3Result ? 1 : 0)
- tmdown := TB1Red and TB2Red and (not TrendBar1Result and not TrendBar2Result and not TrendBar3Result ? 1 : 0)
- else if tmtype == '3 TM change to same color'
- tmup := TrendBar1Result and TrendBar2Result and TrendBar3Result ? 1 : 0
- tmdown := not TrendBar1Result and not TrendBar2Result and not TrendBar3Result ? 1 : 0
- else if tmtype == '3 TM, 2 TB and Wavetrend change to same color'
- tmup := TB1Green and TB2Green and (TrendBar1Result and TrendBar2Result and TrendBar3Result ? 1 : 0) and MSBar1PositiveWaveTrendSignal
- tmdown := TB1Red and TB2Red and (not TrendBar1Result and not TrendBar2Result and not TrendBar3Result ? 1 : 0) and MSBar1NegativeWaveTrendSignal
- hullup = bool(na)
- hulldown = bool(na)
- if respecthull
- hullup := HULL > HULL[2]
- hulldown := HULL < HULL[2]
- rsiup = bool (na)
- rsidown = bool (na)
- if rsitype == 'RSI MA Cross'
- rsiup := rsi > rsiMA
- rsidown := rsi < rsiMA
- else if rsitype == 'RSI Exits OB/OS zones'
- rsiup := rsi > rsi_lower and rsi[1] < rsi_lower
- rsidown := rsi < rsi_upper and rsi[1] > rsi_upper
- else if rsitype == 'RSI Level'
- rsiup := rsi > respectrsilevel
- rsidown := rsi < respectrsilevel
- if macdtype == 'MACD Crossover'
- ismacdup := macdd > signal
- ismacddown := macdd < signal
- else if macdtype == 'Zero line crossover'
- ismacdup := macdd > signal and macdd > 0.00000
- ismacddown := macdd < signal and macdd < 0.00000
- ema2_long = first_2ema > second_2ema
- ema2_short = first_2ema < second_2ema
- uprf = bool (na)
- downrf = bool(na)
- if rftype == 'Default'
- uprf := src > filt and src > src[1] and upward > 0 or src > filt and src < src[1] and upward > 0
- downrf := src < filt and src < src[1] and downward > 0 or src < filt and src > src[1] and downward > 0
- else if rftype == 'DW'
- uprf := rfupward
- downrf := rfdownward
- ema3_long = first_3ema > second_3ema and first_3ema > third_3ema and second_3ema>third_3ema
- ema3_short = first_3ema < second_3ema and first_3ema < third_3ema and second_3ema<third_3ema
- longCond := leadinglongcond and (respectrf?uprf:justcontinue) and
- (respectadx?adxupcondition:justcontinue) and (respectdonchian?donchian_long:justcontinue) and (respectbbpt?bbpt_long:justcontinue) and (respectrqk?rqkuptrend:justcontinue) and (respectbx?bx_long:justcontinue) and (respectbbosc?bbosc_long:justcontinue) and (respectwae?wae_long:justcontinue) and (respectce?ce_long:justcontinue) and (respectssl?ssl_long:justcontinue) and (respect2ma?ema2_long:justcontinue) and (respect3ma?ema3_long:justcontinue) and (respectstochastic?stoch_long:justcontinue) and (respectcci?ccilong:justcontinue) and (respectst?isstup:justcontinue) and (respectrsi?rsiup:justcontinue) and (respectrsimalimit?rsimalimitlong:justcontinue) and (respectrsilimit?rsilimitlong:justcontinue) and (respectrsima?rsimalong2:justcontinue) and (respectema?isaboverespectema:justcontinue) and (respectqqe?isqqeabove:justcontinue) and (respectsar?sarup:justcontinue) and
- (respectvol?longvol:justcontinue) and (respectchaikin?chaikin_long:justcontinue) and (respectvwap?long_vwap:justcontinue) and (respectvo?vo_long:justcontinue) and (respectao?ao_long:justcontinue) and (respectsuperichi?superichi_long:justcontinue) and (respectwolf?wolf_long:justcontinue) and (respectichi?ichi_long:justcontinue) and (respectmacd?ismacdup:justcontinue) and (respecthull?hullup:justcontinue) and (respectvi?vipcondition:justcontinue) and (respecttm?tmup:justcontinue) and (respectstc?stcup:justcontinue) and (respectdv?dvup:justcontinue)
- shortCond := leadingshortcond and (respectrf?downrf:justcontinue) and
- (respectadx?adxdowncondition:justcontinue) and (respectdonchian?donchian_short:justcontinue) and (respectbbpt?bbpt_short:justcontinue) and (respectrqk?rqkdowntrend:justcontinue) and (respectbx?bx_short:justcontinue) and (respectbbosc?bbosc_short:justcontinue) and (respectwae?wae_short:justcontinue) and (respectce?ce_short:justcontinue) and (respectssl?ssl_short:justcontinue) and (respectchaikin?chaikin_short:justcontinue) and (respect2ma?ema2_short:justcontinue) and (respect3ma?ema3_short:justcontinue) and (respectstochastic?stoch_short:justcontinue) and (respectcci?ccishort:justcontinue) and (respectrsimalimit?rsimalimitshort:justcontinue) and (respectrsilimit?rsilimitshort:justcontinue) and (respectrsima?rsimashort2:justcontinue) and (respectst?isstdown:justcontinue) and (respectrsi?rsidown:justcontinue) and (respectema?isbelowrespectema:justcontinue) and (respectqqe?isqqebelow:justcontinue) and (respectsar?sardown:justcontinue) and
- (respectvol?shortvol:justcontinue) and (respectvwap?short_vwap:justcontinue) and (respectvo?vo_short:justcontinue) and (respectao?ao_short:justcontinue) and (respectsuperichi?superichi_short:justcontinue) and (respectwolf?wolf_short:justcontinue) and (respectichi?ichi_short:justcontinue) and (respectmacd?ismacddown:justcontinue) and (respecthull?hulldown:justcontinue) and (respectvi?vimcondition:justcontinue) and (respecttm?tmdown:justcontinue) and (respectstc?stcdown:justcontinue) and (respectdv?dvup:justcontinue)
- var int leadinglong_count = 0
- var int leadinglong_count2 = 0
- var int leadingshort_count = 0
- var int leadingshort_count2 = 0
- if leadinglongcond
- leadinglong_count := leadinglong_count + 1
- leadinglong_count2 := leadinglong_count
- for i = 1 to 100
- if leadinglongcond[i]
- leadinglong_count := leadinglong_count + 1
- leadinglong_count2 := leadinglong_count
- else
- leadinglong_count := 0
- break
- if leadingshortcond
- leadingshort_count := leadingshort_count + 1
- leadingshort_count2 := leadingshort_count
- for i = 1 to 100
- if leadingshortcond[i]
- leadingshort_count := leadingshort_count + 1
- leadingshort_count2 := leadingshort_count
- else
- leadingshort_count := 0
- break
- CondIni = 0
- longCondition = bool (na)
- shortCondition = bool(na)
- // if expiry option is used
- longcond_withexpiry = longCond and leadinglong_count2 <= signalexpiry
- shortcond_withexpiry = shortCond and leadingshort_count2 <= signalexpiry
- //without expiry
- longCondition := longcond_withexpiry and CondIni[1] == -1
- shortCondition := shortcond_withexpiry and CondIni[1] == 1
- if respect_expiry_count
- if alternatesignal
- longCondition := longcond_withexpiry and CondIni[1] == -1 and leadinglong_count2 <= signalexpiry
- shortCondition := shortcond_withexpiry and CondIni[1] == 1 and leadingshort_count2 <= signalexpiry
- else
- longCondition := longcond_withexpiry and leadinglong_count2 <= signalexpiry
- shortCondition := shortcond_withexpiry and leadingshort_count2 <= signalexpiry
- else
- if alternatesignal
- longCondition := longcond_withexpiry and CondIni[1] == -1
- shortCondition := shortcond_withexpiry and CondIni[1] == 1
- else
- longCondition := longcond_withexpiry
- shortCondition := shortcond_withexpiry
- CondIni := longcond_withexpiry ? 1 : shortcond_withexpiry ? -1 : CondIni[1]
- is_expiry_count_crossed_long = leadinglong_count2 > signalexpiry
- is_expiry_count_crossed_short = leadingshort_count2 > signalexpiry
- plotshape(longCondition[1] ?false :longCondition, title='Buy Signal', text='long', textcolor=color.new(color.white, 0), style=shape.labelup, size=size.tiny, location=location.belowbar, color=color.new(color.green, 0))
- plotshape(shortCondition, title='Sell Signal', text='short', textcolor=color.new(color.white, 0), style=shape.labeldown, size=size.tiny, location=location.abovebar, color=color.new(color.red, 0))
- //plotchar(is_expiry_count_crossed_long, title='count')
- plotshape(is_expiry_count_crossed_long and not is_expiry_count_crossed_long[1] and CondIni == -1 ? true:false, title='Expired Signal',text='', textcolor=color.new(color.white, 0), style=shape.circle, size=size.tiny, location=location.abovebar, color=color.new(color.red, 0))
- plotshape(is_expiry_count_crossed_short and not is_expiry_count_crossed_short[1] and CondIni == 1? true:false, title='Expired Signal',text='', textcolor=color.new(color.white, 0), style=shape.circle, size=size.tiny, location=location.belowbar, color=color.new(#dd1111, 0))
- alertcondition(longCondition, title='Buy Alert', message='BUY')
- alertcondition(shortCondition, title='Sell Alert', message='SELL')
- rsitype2 = rsitype
- if rsitype2 == "RSI Level"
- rsitype2 := "RSI Level (" + str.tostring(respectrsilevel) +")"
- confirmation_counter = array.new_string(0)
- confirmation_val = array.new_string(0)
- confirmation_val_short = array.new_string(0)
- pushConfirmation(respect, label, longCondition, shortCondition) =>
- if respect
- array.push(confirmation_counter, label)
- array.push(confirmation_val, longCondition ? "✔️" : "❌")
- array.push(confirmation_val_short, shortCondition ? "✔️" : "❌")
- pushConfirmation(respectema, "EMA", isaboverespectema, isbelowrespectema)
- pushConfirmation(respect2ma, "2 EMA Cross (" + str.tostring(respect2maperiod_1) + "," + str.tostring(respect2maperiod_2) + ")", ema2_long, ema2_short)
- pushConfirmation(respect3ma, "3 EMA Cross (" + str.tostring(respect3maperiod_1) + "," + str.tostring(respect3maperiod_2) + "," + str.tostring(respect3maperiod_3) + ")", ema3_long, ema3_short)
- pushConfirmation(respectrf, "Range Filter", uprf, downrf)
- pushConfirmation(respectrqk, "RQK", rqkuptrend, rqkdowntrend)
- pushConfirmation(respectst, "SuperTrend", isstup, isstdown)
- pushConfirmation(respectdonchian, "Donchian Trend Ribbon", donchian_long, donchian_short)
- pushConfirmation(respectbx, "B-Xtrender (" + str.tostring(bxtype) + ")", bx_long, bx_short)
- pushConfirmation(respectbbpt, "Bull Bear Power Trend (" + str.tostring(bbpttype) + ")", bbpt_long, bbpt_short)
- pushConfirmation(respectvwap, "VWAP", long_vwap, short_vwap)
- pushConfirmation(respectichi, "Ichimoku Cloud", ichi_long, ichi_short)
- pushConfirmation(respectsuperichi, "Superichi", superichi_long, superichi_short)
- pushConfirmation(respectbbosc, "BB Oscillator", bbosc_long, bbosc_short)
- pushConfirmation(respecttm, "Trend Meter", tmup, tmdown)
- pushConfirmation(respectce, "Chandelier Exit", ce_long, ce_short)
- pushConfirmation(respectcci, "CCI", ccilong, ccishort)
- pushConfirmation(respectadx, "DMI (Adx) (" + str.tostring(adxtype) + ")", adxupcondition, adxdowncondition)
- pushConfirmation(respectsar, "Parabolic SAR", sarup, sardown)
- pushConfirmation(respectssl, "SSL Channel", ssl_long, ssl_short)
- pushConfirmation(respectvo, "Volatility Oscillator", vo_long, vo_short)
- pushConfirmation(respectdv, "DV", dvup, dvup) // Note: Both are 'dvup'. Double-check if it's intended.
- pushConfirmation(respectstochastic, "Stochastic (" + str.tostring(stochtype) + ")", stoch_long, stoch_short)
- pushConfirmation(respectrsi, "RSI (" + str.tostring(rsitype2) + ")", rsiup, rsidown)
- pushConfirmation(respectmacd, "MACD (" + str.tostring(macdtype) + ")", ismacdup, ismacddown)
- pushConfirmation(respectstc, "Schaff Trend Cycle", stcup, stcdown)
- pushConfirmation(respectwae, "Waddah Attar Explosion", wae_long, wae_short)
- pushConfirmation(respectchaikin, "Chaikin Money Flow", chaikin_long, chaikin_short)
- pushConfirmation(respectvol, "Volume", longvol, shortvol)
- pushConfirmation(respectao, "Awesome Oscillator(" + str.tostring(aotype) + ")", ao_long, ao_short)
- pushConfirmation(respectwolf, "Wolfpack Id", wolf_long, wolf_short)
- pushConfirmation(respectqqe, "QQE Mod (" + str.tostring(qqetype) + ")", isqqeabove, isqqebelow)
- pushConfirmation(respecthull, "HullSuite", hullup, hulldown)
- pushConfirmation(respectvi, "Vortex Index (" + str.tostring(vitype) + ")", vipcondition, vimcondition)
- leadingstatus = leadinglongcond ? "✔️" : "❌"
- leadingstatus_short = leadingshortcond ? "✔️" : "❌"
- rowcount = int(na)
- if array.size(confirmation_counter) ==0
- rowcount := 5
- else
- rowcount := array.size(confirmation_counter)+4
- if showdashboard
- var table tab1 = table.new(i_tab1Ypos + '_' + i_tab1Xpos, 3, rowcount, color.rgb(42, 46, 57), color.rgb(204, 204, 204), 0, color.rgb(77, 71, 71), 1)
- table.cell(tab1, 1, 0,"Long", text_halign=text.align_left, text_size=size.normal, bgcolor=color.rgb(61, 189, 72),text_color=color.white)
- table.cell(tab1, 2, 0,"Short", text_halign=text.align_left, text_size=size.normal, bgcolor=color.rgb(243, 77, 77),text_color=color.white)
- table.cell(tab1, 0, 1, "Leading Indicator", text_halign=text.align_left, text_size=size.normal, bgcolor=color.rgb(68, 68, 67),text_color=color.white)
- table.cell(tab1, 1, 1,"", text_halign=text.align_left, text_size=size.normal, bgcolor=color.rgb(68, 68, 67),text_color=color.white)
- table.cell(tab1, 2, 1,"", text_halign=text.align_left, text_size=size.normal, bgcolor=color.rgb(68, 68, 67),text_color=color.white)
- table.cell(tab1, 0, 2, leadingindicator, text_halign=text.align_left, text_size=size.normal, text_color=color.white)
- table.cell(tab1, 1, 2, leadingstatus, text_halign=text.align_left, text_size=size.normal, text_color=color.white)
- table.cell(tab1, 2, 2, leadingstatus_short, text_halign=text.align_left, text_size=size.normal, text_color=color.white)
- table.cell(tab1, 0, 3, "Confirmation Indicators", text_halign=text.align_left, text_size=size.normal, bgcolor=color.rgb(68, 68, 67),text_color=color.white)
- table.cell(tab1, 1, 3, "", text_halign=text.align_left, text_size=size.normal, bgcolor=color.rgb(68, 68, 67),text_color=color.white)
- table.cell(tab1, 2, 3, "", text_halign=text.align_left, text_size=size.normal, bgcolor=color.rgb(68, 68, 67),text_color=color.white)
- if array.size(confirmation_counter) > 0
- for i=0 to array.size(confirmation_counter)-1
- table.cell(tab1, 0, 4+i, array.get(confirmation_counter,i), text_halign=text.align_left, text_size=size.normal, text_color=color.white)
- else
- table.cell(tab1, 0, 4, "None Selected", text_halign=text.align_left, text_size=size.normal, text_color=color.white)
- if array.size(confirmation_val) > 0
- for j=0 to array.size(confirmation_val)-1
- table.cell(tab1, 1, 4+j, array.get(confirmation_val,j), text_halign=text.align_left, text_size=size.normal, text_color=color.white)
- table.cell(tab1, 2, 4+j, array.get(confirmation_val_short,j), text_halign=text.align_left, text_size=size.normal, text_color=color.white)
- iff_1 = close[0] == close[1] ? color.rgb(42, 46, 57) : color.rgb(42, 46, 57)
- iff_2 = close[0] < close[1] ? color.red : iff_1
- // ALERTS {
Comments
-
- i got all types of premium tradingview indicators codes available on telegram -
- https://t.me/tradingview_premium_indicator
Add Comment
Please, Sign In to add comment