name
stringlengths 1
64
| url
stringlengths 44
135
| author
stringlengths 3
30
| author_url
stringlengths 34
61
| likes_count
int64 0
33.2k
| kind
stringclasses 3
values | pine_version
int64 1
5
| license
stringclasses 3
values | source
stringlengths 177
279k
|
---|---|---|---|---|---|---|---|---|
GRIDBOT Scalper by nnam | https://www.tradingview.com/script/Ddjr6zNy-GRIDBOT-Scalper-by-nnam/ | nnamdert | https://www.tradingview.com/u/nnamdert/ | 678 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © nnamdert
//@version=5
indicator("GRIDBOT Scalper", overlay = true, max_lines_count = 500)
//BEGIN SCRIPT
//Begin Settings Box============================================================================================================//
easy_settings = input.bool(true, title='Show Easy Access Settngs Tool on Chart?', group = 'Settings Tool') //
settings_location_bottom_right = input.bool( //
defval = false, //
title = 'Move Settings Tool to Bottom Right?', //
group = 'Settings Tool') //
? position.bottom_right : position.middle_right //
if easy_settings == true //
var table settings_tool = table.new(settings_location_bottom_right, 1, 1, frame_color = color.black, frame_width = 0) //
table.cell(settings_tool, 0, 0, text_size = size.small, //
text = "⚙️", //
tooltip='Double Click to Access Settings', //
//Questions regarding this indicator or need training? https://discord.com/invite/nZfY854MXR //
text_color = color.black, bgcolor = color.new(color.orange, 100)) //
//End Settings Box==============================================================================================================//
//HANDLES MAX_LINES_COUNTS ISSUE================================================================================================//
lineLimitInput = input.int( //
defval = 30, //
title = 'Max Lines to Show', //
tooltip = 'Adjust this number to increase or decrease the total number of lines seen on the chart. (ONLY this indicator)', //
group = 'Line Settings' //
) //
if array.size(line.all) > lineLimitInput //
for i = 0 to array.size(line.all) - lineLimitInput - 1 //
line.delete(array.get(line.all, i)) //
//END MAX_LINES_COUNTS ISSUE====================================================================================================//
//BEGIN Get User Inputs=========================================================================================================//
//BEGIN LINE SETTINGS //
extend_lines = input.bool( //
defval = false, //
title = 'Extend Lines to the right?', //
tooltip = 'Checking this box will extend the current lines on the chart to the right', //
group = 'Line Settings' //
) ? extend.right : extend.none //
use_low_bullish = input.bool( //
defval = false, //
title = 'Use Low for Bullish Reversal Support Line?', //
tooltip = 'The default for the support line is the close of the candle, this setting changes it to the candle Low (wick)', //
group = 'Line Settings' //
) ? low : close //
use_high_bearish = input.bool( //
defval = false, //
title = 'Use High for Bearish Reversal Resistance Line?', //
tooltip = 'The default for the resistance line is the close of the candle, this setting changes it to the candle High (wick)', //
group = 'Line Settings' //
) ? high : close //
//END LINE SETTINGS //
showlabel = input.bool(true, title='Show Alerts Box', group = ' Alert Box') //
only_bearish = input.bool( //
defval = false, //
title = ' Show only Bearish Labels on Chart', //
tooltip = 'checking this box will hide Bullish Reversal and only show Bearish Reversals', //
group = 'Signal Label Settings' //
) //
only_bullish = input.bool( //
defval = false, //
title = ' Show only Bullish Labels on Chart', //
tooltip = 'checking this box will hide Bearish Reversal and only show Bullish Reversals', //
group = 'Signal Label Settings' //
) //
//END Get User Inputs===========================================================================================================//
//BEGIN OPTIONAL PRICE LABEL SCRIPT=============================================================================================//
var priceArray = array.new_float(0) //
array.push(priceArray, close) //
size = array.size(priceArray) //
price = array.get(priceArray, size -1) //
//BEGIN USER INPUT FOR OPTIONAL PRICE LABEL //
show_price_label = input.bool( //
defval = true, //
title = ' Show Price Label on Chart', //
tooltip = 'Unchecking this box will hide the optional price label from the chart', //
group = "Price Label Settings" //
) //
//END USER INPUT FOR OPTIONAL PRICE LABEL //
//BEGIN LABEL script for OPTIONAL PRICE LABEL //
label pricelabel = na //
if barstate.islast and show_price_label //
pricelabel := label.new(bar_index, //
y=0, //
yloc=yloc.abovebar, //
color = color.new(color.yellow, 0), //
style = label.style_none, //
text="Price:\n " + str.tostring(array.get(priceArray, size -1)), //
textcolor = color.new(color.orange, 0)) //
label.delete(pricelabel[1]) //
//END LABEL script for OPTIONAL PRICE LABEL //
//END OPTIONAL PRICE LABEL SCRIPT===============================================================================================//
//BEGIN Definitions=============================================================================================================//
bullish_break = //
price > high[1] //
and price > high[2] //
and price > high[3] //
and price > high[4] //
and price > high[5] //
and price > high[6] //
and price > high[7] //
and price > high[8] //
and price > high[9] //
and price > high[10] //
and price > high[11] //
and price > high[12] //
and price > high[13] //
and price > high[14] //
// //
bearish_break = //
price < low[1] //
and price < low[2] //
and price < low[3] //
and price < low[4] //
and price < low[5] //
and price < low[6] //
and price < low[7] //
and price < low[8] //
and price < low[9] //
and price < low[10] //
and price < low[11] //
and price < low[11] //
and price < low[12] //
and price < low[13] //
and price < low[14] //
// //
//BEGIN RSI---------------------------------------------------------------------------------------------------------------------//
// Get user input //
use_rsi_confirmation = input.bool( //
defval = false, //
title = 'Use RSI Signals to Confirm Reversals?', //
tooltip = 'Checking this box will require the indicator to use RSI settings before a signal is triggered.', //
group = 'RSI SETTINGS') //
showrsi = input.bool( //
defval = false, //
title = 'Plot RSI Signals on Chart', //
group='RSI SETTINGS') //
showoverbtrsi = input.bool( //
defval = true, //
title = 'Show Overbought RSI Signals', //
group='RSI SETTINGS') //
showoversldrsi = input.bool( //
defval = true, //
title = 'Show Oversold RSI Signals', //
group='RSI SETTINGS') //
rsiSource = input( //
title = 'RSI Source', //
defval = close, //
group ='RSI SETTINGS') //
LenofRSI = input( //
title = 'RSI Length', //
defval = 6, //
group='RSI SETTINGS') //
rsiOverbought = input( //
title = 'RSI Overbought Level', //
defval=85, //
group='RSI SETTINGS') //
rsiOversold = input( //
title = 'RSI Oversold Level', //
defval = 15, //
group='RSI SETTINGS') //
// Get RSI value //
rsiValue = ta.rsi(rsiSource, LenofRSI) //
rsiisoverbt = rsiValue >= rsiOverbought //
rsiisoversld = rsiValue <= rsiOversold //
// Plot RSI signals to chart //
plotshape(showrsi and showoverbtrsi and not only_bullish? //
rsiisoverbt : na, //
title='RSI Overbought', //
display=display.all, //
location=location.abovebar, //
color=color.new(color.yellow, 0), //
style=shape.triangledown, size=size.tiny, //
text='OB', //
textcolor=color.new(color.yellow, 0)) //
plotshape(showrsi and showoversldrsi and not only_bearish? //
rsiisoversld : na, //
title='RSI Oversold', //
display=display.all, //
location=location.belowbar, //
color=color.new(color.yellow, 0), //
style=shape.triangleup, //
size=size.tiny, //
text='OS', //
textcolor=color.new(color.yellow, 0)) //
//Alerts for RSI //
alertcondition(rsiisoverbt, title='Overbought RSI', message='RSI Overbought') //
alertcondition(rsiisoversld, title='Oversold RSI', message='RSI Oversold') //
//END RSI-----------------------------------------------------------------------------------------------------------------------//
bearish_signal_rsi = (rsiisoversld[1] and not rsiisoversld) //
bearish_signal = (bearish_break[1] and not bearish_break) //
bullish_signal_rsi = (rsiisoverbt[1] and not rsiisoverbt) //
bullish_signal = (bullish_break[1] and not bullish_break) //
//END Definitions===============================================================================================================//
//PLOTSHAPES BULLISH============================================================================================================//
var label bullishlabel = na //
if barstate.isconfirmed and bullish_signal and not only_bullish//bullish_break[1] and not bullish_break //
bullishlabel := label.new( //
bar_index, //
y=0, //
yloc=yloc.abovebar, //
style= label.style_triangledown, //
size = size.normal, //
color = color.new(color.red, 0), //
text = "Potential \n Bearish \n Reversal", //
textcolor = color.new(color.red, 0) //
) //
label.delete(bullishlabel[1]) //
// //
var line bullishline = na //
if barstate.isconfirmed and bullish_break //
bullishline := line.new( //
x1=bar_index, //
y1=use_high_bearish, //
x2=bar_index+30, //
y2=use_high_bearish, //
color = color.new(color.red, 0), //
extend = extend_lines //
) //
line.delete(bullishline[1]) //
//PLOTSHAPES BEARISH============================================================================================================//
var label bearishlabel = na //
if barstate.isconfirmed and bearish_signal and not only_bearish//bearish_break[1] and not bearish_break //
bearishlabel := label.new( //
bar_index, //
y=0, //
yloc=yloc.belowbar, //
style= label.style_triangleup, //
size = size.normal, //
color = color.new(color.green, 0), //
text = "Potential \n Bullish \n Reversal", //
textcolor = color.new(color.green, 0) //
) //
label.delete(bearishlabel[1]) //
// //
var line bearishline = na //
if barstate.isconfirmed and bearish_break //
bearishline := line.new( //
bar_index, //
use_low_bullish, //
bar_index+30, //
use_low_bullish, //
color = color.new(color.green, 0), //
extend = extend_lines //
) //
line.delete(bearishline[1]) //
//END Script====================================================================================================================//
//SCREENER BEGIN ===============================================================================================================//
//Begin User Inputs
//Ticker 01 Begin
tickerinput01 = input.symbol("KUCOIN:BTCUSDT", title = 'Ticker 01', group = 'Screener', inline = 'ticker01')
tickertimeframe01 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker01')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref01 = syminfo.prefix(tickerinput01)
tick01 = syminfo.ticker(tickerinput01)
t01 = ticker.new(pref01, tick01)
//Ticker 01 End
//
//Ticker 02 Begin
tickerinput02 = input.symbol("KUCOIN:ETHUSDT", title = 'Ticker 02', group = 'Screener', inline = 'ticker02')
tickertimeframe02 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker02')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref02 = syminfo.prefix(tickerinput02)
tick02 = syminfo.ticker(tickerinput02)
t02 = ticker.new(pref02, tick02)
//Ticker 02 End
//
//Ticker 03 Begin
tickerinput03 = input.symbol("KUCOIN:BNBUSDT", title = 'Ticker 03', group = 'Screener', inline = 'ticker03')
tickertimeframe03 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker03')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref03 = syminfo.prefix(tickerinput03)
tick03 = syminfo.ticker(tickerinput03)
t03 = ticker.new(pref03, tick03)
//Ticker 03 End
//
//Ticker 04 Begin
tickerinput04 = input.symbol("KUCOIN:XRPUSDT", title = 'Ticker 04', group = 'Screener', inline = 'ticker04')
tickertimeframe04 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker04')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref04 = syminfo.prefix(tickerinput04)
tick04 = syminfo.ticker(tickerinput04)
t04 = ticker.new(pref04, tick04)
//Ticker 04 End
//
//Ticker 05 Begin
tickerinput05 = input.symbol("KUCOIN:ADAUSDT", title = 'Ticker 04', group = 'Screener', inline = 'ticker05')
tickertimeframe05 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker05')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref05 = syminfo.prefix(tickerinput05)
tick05 = syminfo.ticker(tickerinput05)
t05 = ticker.new(pref05, tick05)
//Ticker 05 End
//
//Ticker 06 Begin
tickerinput06 = input.symbol("KUCOIN:DOGEUSDT", title = 'Ticker 06', group = 'Screener', inline = 'ticker06')
tickertimeframe06 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker06')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref06 = syminfo.prefix(tickerinput06)
tick06 = syminfo.ticker(tickerinput06)
t06 = ticker.new(pref06, tick06)
//Ticker 06 End
//
//Ticker 07 Begin
tickerinput07 = input.symbol("KUCOIN:MATICUSDT", title = 'Ticker 07', group = 'Screener', inline = 'ticker07')
tickertimeframe07 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker07')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref07 = syminfo.prefix(tickerinput07)
tick07 = syminfo.ticker(tickerinput07)
t07 = ticker.new(pref07, tick07)
//Ticker 07 End
//
//Ticker 08 Begin
tickerinput08 = input.symbol("KUCOIN:DOTUSDT", title = 'Ticker 08', group = 'Screener', inline = 'ticker08')
tickertimeframe08 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker08')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref08 = syminfo.prefix(tickerinput08)
tick08 = syminfo.ticker(tickerinput08)
t08 = ticker.new(pref08, tick08)
//Ticker 08 End
//
//Ticker 09 Begin
tickerinput09 = input.symbol("KUCOIN:SOLUSDT", title = 'Ticker 09', group = 'Screener', inline = 'ticker09')
tickertimeframe09 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker09')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref09 = syminfo.prefix(tickerinput09)
tick09 = syminfo.ticker(tickerinput09)
t09 = ticker.new(pref09, tick09)
//Ticker 09 End
//
//Ticker 10 Begin
tickerinput10 = input.symbol("KUCOIN:SHIBUSDT", title = 'Ticker 10', group = 'Screener', inline = 'ticker10')
tickertimeframe10 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker10')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref10 = syminfo.prefix(tickerinput10)
tick10 = syminfo.ticker(tickerinput10)
t10 = ticker.new(pref10, tick10)
//Ticker 10 End
//
//Ticker 11 Begin
tickerinput11 = input.symbol("KUCOIN:TRXUSDT", title = 'Ticker 11', group = 'Screener', inline = 'ticker11')
tickertimeframe11 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker11')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref11 = syminfo.prefix(tickerinput11)
tick11 = syminfo.ticker(tickerinput11)
t11 = ticker.new(pref11, tick11)
//Ticker 11 End
//
//Ticker 12 Begin
tickerinput12 = input.symbol("KUCOIN:AVAXUSDT", title = 'Ticker 12', group = 'Screener', inline = 'ticker12')
tickertimeframe12 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker12')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref12 = syminfo.prefix(tickerinput12)
tick12 = syminfo.ticker(tickerinput12)
t12 = ticker.new(pref12, tick12)
//Ticker 12 End
//
//Ticker 13 Begin
tickerinput13 = input.symbol("KUCOIN:UNIUSDT", title = 'Ticker 13', group = 'Screener', inline = 'ticker13')
tickertimeframe13 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker13')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref13 = syminfo.prefix(tickerinput13)
tick13 = syminfo.ticker(tickerinput13)
t13 = ticker.new(pref13, tick13)
//Ticker 13 End
//
//Ticker 14 Begin
tickerinput14 = input.symbol("KUCOIN:LTCUSDT", title = 'Ticker 14', group = 'Screener', inline = 'ticker14')
tickertimeframe14 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker14')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref14 = syminfo.prefix(tickerinput14)
tick14 = syminfo.ticker(tickerinput14)
t14 = ticker.new(pref14, tick14)
//Ticker 14 End
//
//Ticker 15 Begin
tickerinput15 = input.symbol("NASDAQ:AAPL", title = 'Ticker 15', group = 'Screener', inline = 'ticker15')
tickertimeframe15 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker15')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref15 = syminfo.prefix(tickerinput15)
tick15 = syminfo.ticker(tickerinput15)
t15 = ticker.new(pref15, tick15)
//Ticker 15 End
//
//Ticker 16 Begin
tickerinput16 = input.symbol("KUCOIN:LINKUSDT", title = 'Ticker 16', group = 'Screener', inline = 'ticker16')
tickertimeframe16 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker16')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref16 = syminfo.prefix(tickerinput16)
tick16 = syminfo.ticker(tickerinput16)
t16 = ticker.new(pref16, tick16)
//Ticker 16 End
//Ticker 17 Begin
tickerinput17 = input.symbol("KRAKEN:USDCAD", title = 'Ticker 17', group = 'Screener', inline = 'ticker17')
tickertimeframe17 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker17')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref17 = syminfo.prefix(tickerinput17)
tick17 = syminfo.ticker(tickerinput17)
t17 = ticker.new(pref17, tick17)
//Ticker 17 End
//Ticker 18 Begin
tickerinput18 = input.symbol("TVC:DXY", title = 'Ticker 18', group = 'Screener', inline = 'ticker18')
tickertimeframe18 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker18')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref18 = syminfo.prefix(tickerinput18)
tick18 = syminfo.ticker(tickerinput18)
t18 = ticker.new(pref18, tick18)
//Ticker 18 End
//Ticker 19 Begin
tickerinput19 = input.symbol("NASDAQ:TSLA", title = 'Ticker 19', group = 'Screener', inline = 'ticker19')
tickertimeframe19 = input.timeframe('30', "Timeframe",
options=['1', '3', '5', '15', '30', '45', '60', '120', '180', '240', 'D', '5D', 'W', 'M', '3M' ],
group = 'Screener',
inline = 'ticker19')
//t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
pref19 = syminfo.prefix(tickerinput19)
tick19 = syminfo.ticker(tickerinput19)
t19 = ticker.new(pref19, tick19)
//Ticker 19 End
//
//Custom Functions
Sell_Signal = bullish_signal
Buy_Signal = bearish_signal
//end user inputs
bull_function() => Buy_Signal
bear_function() => Sell_Signal
custom_signal() => (bull_function() or bear_function())
//close > open
//and close[1] > open[1]
//and close[2] > open[2]
//and close[3] > open[3]
//or close < open
//and close[1] < open[1]
//and close[2] < open[2]
//and close[3] < open[3]
//buythedip
s1 = request.security(t01, tickertimeframe01, custom_signal())
s2 = request.security(t02, tickertimeframe02, custom_signal())
s3 = request.security(t03, tickertimeframe03, custom_signal())
s4 = request.security(t04, tickertimeframe04, custom_signal())
s5 = request.security(t05, tickertimeframe05, custom_signal())
s6 = request.security(t06, tickertimeframe06, custom_signal())
s7 = request.security(t07, tickertimeframe07, custom_signal())
s8 = request.security(t08, tickertimeframe08, custom_signal())
s9 = request.security(t09, tickertimeframe09, custom_signal())
s10 = request.security(t10, tickertimeframe10, custom_signal())
s11 = request.security(t11, tickertimeframe11, custom_signal())
s12 = request.security(t12, tickertimeframe12, custom_signal())
s13 = request.security(t13, tickertimeframe13, custom_signal())
s14 = request.security(t14, tickertimeframe14, custom_signal())
s15 = request.security(t15, tickertimeframe15, custom_signal())
s16 = request.security(t16, tickertimeframe16, custom_signal())
s17 = request.security(t17, tickertimeframe17, custom_signal())
s18 = request.security(t18, tickertimeframe18, custom_signal())
s19 = request.security(t19, tickertimeframe19, custom_signal())
scr_label = 'Alerts\n'
scr_label := s1 ?
scr_label + '\n' + tick01 :
scr_label
scr_label := s2 ? scr_label + '\n' + tick02 : scr_label
scr_label := s3 ? scr_label + '\n' + tick03 : scr_label
scr_label := s4 ? scr_label + '\n' + tick04 : scr_label
scr_label := s5 ? scr_label + '\n' + tick05 : scr_label
scr_label := s6 ? scr_label + '\n' + tick06 : scr_label
scr_label := s7 ? scr_label + '\n' + tick07 : scr_label
scr_label := s8 ? scr_label + '\n' + tick08 : scr_label
scr_label := s9 ? scr_label + '\n' + tick09 : scr_label
scr_label := s10 ? scr_label + '\n' + tick10 : scr_label
scr_label := s11 ? scr_label + '\n' + tick11 : scr_label
scr_label := s12 ? scr_label + '\n' + tick12 : scr_label
scr_label := s13 ? scr_label + '\n' + tick13 : scr_label
scr_label := s14 ? scr_label + '\n' + tick14 : scr_label
scr_label := s15 ? scr_label + '\n' + tick15 : scr_label
scr_label := s16 ? scr_label + '\n' + tick16 : scr_label
scr_label := s17 ? scr_label + '\n' + tick17 : scr_label
scr_label := s18 ? scr_label + '\n' + tick18 : scr_label
scr_label := s19 ? scr_label + '\n' + tick19 : scr_label
//Label
//label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family) → series label
if showlabel
lab_l = label.new(
bar_index, 0, scr_label,
color=color.yellow,
textcolor=color.blue,
style = label.style_none,
yloc = yloc.belowbar)
label.delete(lab_l[1])
//SIGNALS
alertcondition(bearish_signal, title = 'Potential Bullish Reversal', message = 'Possible Bullish Reversal')
alertcondition(bullish_signal, title = 'Potential Bearish Reversal', message = 'Possible Bearish Reversal')
alertcondition(Sell_Signal, title = 'Potential Bearish GRID Entry', message = 'Possible Bearish GRID Entry')
alertcondition(Buy_Signal, title = 'Potential Bullish GRID Entry', message = 'Possible Bullish GRID Entry')
// Plot BUY SELL signals to chart
show_sell_signals = input.bool(true, title = 'Show Short Entries on Chart?')
show_buy_signals = input.bool(true, title = "Show Long Entries on Chart?")
plotshape(
showrsi and show_sell_signals and not only_bullish ? Sell_Signal : na,
title='RSI Overbought',
display=display.all,
location=location.abovebar,
color=color.new(color.red, 0),
style=shape.triangledown,
size=size.tiny, text='',
textcolor=color.new(color.yellow, 0))
plotshape(
showrsi and show_buy_signals and not only_bearish ? Buy_Signal : na,
title='RSI Oversold',
display=display.all,
location=location.belowbar,
color=color.new(color.lime, 0),
style=shape.triangleup, size=size.tiny,
text='',
textcolor=color.new(color.yellow, 0))
|
RSI TREND FILTER | https://www.tradingview.com/script/KOGbpAT0-RSI-TREND-FILTER/ | traderharikrishna | https://www.tradingview.com/u/traderharikrishna/ | 396 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © traderharikrishna
// Idea and Code by @traderharikrishna
//@version=5
indicator("RSI TREND FILTER",overlay=true)
showrsi=input.bool(false,title='Show RSI Cloud',group='RSI ')
showmidband=input.bool(false,title='Show RSI Mid Band',group='RSI ')
showgrid=input.bool(false,title='Show RSI Levels',group='RSI Levels')
grid=input.color(color.rgb(26, 22, 22, 34),'RSI LEVELS',group='RSI Levels')
rsilen=input.int(14,'RSI LENGTH',group='RSI')
rsima=input.int(100,'RSI 50 level',group='RSI')
emalen=input.int(20,'RSI EMA Length',group='RSI')
orsi=ta.rsi(close,rsilen)
adjrsi=close+ta.atr(100)*orsi/100
rma=ta.ema(adjrsi,rsima)
r1=plot(showrsi?adjrsi:na,display=display.all,title='RSI')
r2=plot(rma,color=open>rma?#00ff08:open<rma?#ff0404:color.white,title='RSI MA',linewidth=2)
fill(r1,r2,color=adjrsi>rma?color.rgb(76, 175, 79, 70):color.rgb(255, 82, 82, 75),title='RSI Cloud',display=showrsi?display.all:display.none)
level2=input.float(10,'RSI LEVEL2',minval=10,maxval=100,group='RSI Levels')
rmau=rma+ta.atr(100)*level2/10
rmal=rma-ta.atr(100)*level2/10
u=plot(rmau,display=showgrid?display.all:display.none,title='70',color=grid)
l=plot(rmal,display=showgrid?display.all:display.none,title='30',color=grid)
fill(u,l,color=color.rgb(232, 237, 242, 82),title='RSI ZeroBand',display=showmidband?display.all:display.none)
level3=input.float(40,'RSI LEVEL3',minval=10,maxval=100,group='RSI Levels')
rmau3=rma+ta.atr(100)*level3/10
rmal3=rma-ta.atr(100)*level3/10
o8=plot(rmau3,display=showgrid?display.all:display.none,title='80',color=grid)
o2=plot(rmal3,display=showgrid?display.all:display.none,title='20',color=grid)
level5=input.float(50,'RSI LEVEL5',minval=10,maxval=100,group='RSI Levels')
rmau5=rma+ta.atr(100)*level5/10
rmal5=rma-ta.atr(100)*level5/10
ul=plot(rmau5,color=grid,display=showgrid?display.all:display.none,title='100')
ll=plot(rmal5,color=grid,display=showgrid?display.all:display.none,title='0')
fill(o8,ul,color=color.rgb(232, 4, 205, 45),title='OverBought')
fill(o2,ll,color=color.rgb(9, 198, 15, 53),title='OverSold')
fill(r2,ul,color=color.rgb(76, 175, 79, 85),title='UP TREND')
fill(r2,ll,color=color.rgb(175, 76, 167, 85),title='DOWN TREND')
rsiMA=ta.ema(adjrsi,emalen)
plot(rsiMA,color=color.yellow) |
Price Distance Ratio | https://www.tradingview.com/script/Slf5XqIv-price-distance-ratio/ | Pandorra | https://www.tradingview.com/u/Pandorra/ | 37 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Wheeelman, © Pandorra
//@version=5
indicator(title='Price Ratio', overlay=false)
bars_back = input(200, title='Bars Back')
dhigh = request.security(syminfo.tickerid, 'D', high)
dlow = request.security(syminfo.tickerid, 'D', low)
dclose = request.security(syminfo.tickerid, 'D', close)
Ratio = dclose/dclose[bars_back]
plot(Ratio, color=color.new(color.orange, 0), title='Price Ratio', linewidth=1)
plot(close) |
PAC new | https://www.tradingview.com/script/HHpoTUkE-PAC-new/ | table47 | https://www.tradingview.com/u/table47/ | 183 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator("Sma Script",overlay=true)
len_sma=input.int(4,title ="Sma Len",group="Sma Set")
scr_smah=input.source(high,title ="Sma High",group="Sma Set")
scr_smal=input.source(low,title ="Sma Low",group="Sma Set")
//sma condition
sma_h=ta.sma(scr_smah,len_sma)
sma_l=ta.sma(scr_smal,len_sma)
plot(sma_h ,title="Sma High",color=color.yellow)
plot(sma_l ,title="Sma Plot",color=color.yellow)
//hikenashi candle
ha_t = ticker.heikinashi(syminfo.tickerid)
ha_open = request.security(ha_t, timeframe.period, open)
ha_high = request.security(ha_t, timeframe.period, high)
ha_low = request.security(ha_t, timeframe.period, low)
ha_close = request.security(ha_t, timeframe.period, close)
//green and red candle
green_candle=(ha_close[1] > ha_open[1])
red_candle=(ha_close [1] < ha_open[1])
sma_buy1=ta.crossover(ha_close,sma_h) and red_candle
sma_sell1=ta.crossunder(ha_close,sma_l) and green_candle
plotshape(sma_buy1,"Buy Cond",shape.arrowup,location.belowbar,color.green,size=size.normal,text="Buy Signal",textcolor=color.white)
plotshape(sma_sell1,"Sell Cond",shape.arrowdown,location.abovebar,color.red,size=size.normal,text="Sell Signal",textcolor=color.white)
// when previous candle is green and previous before red
green_candle2=(ha_close[2] > ha_open[2])
red_candle2=(ha_close [2] < ha_open[2])
sma_buy2=ta.crossover(ha_close,sma_h) and green_candle and red_candle2
sma_sell2=ta.crossunder(ha_close,sma_l) and red_candle and green_candle2
plotshape(sma_buy2,"Buy Cond2",shape.triangleup,location.belowbar,color.green,size=size.normal,text="Buy Signal2",textcolor=color.green)
plotshape(sma_sell2,"Sell Cond2",shape.triangledown,location.abovebar,color.red,size=size.normal,text="Sell Signal2",textcolor=color.red)
alertcondition(sma_buy1 or sma_buy2,title ="Buy Signal",message ="Buy1 or Buy2 condition mat")
alertcondition(sma_sell1 or sma_sell2,title ="Sell Signal",message ="Sell1 or Sell2 condition mat")
alertcondition(sma_buy1 or sma_buy2 or sma_sell1 or sma_sell2,title ="Combined Signal",message ="Buy1 or Buy2 or Sell1 or Sell2 condition mat")
|
[CLX] Motion. - Logo | https://www.tradingview.com/script/2uypyzaW-CLX-Motion-Logo/ | cryptolinx | https://www.tradingview.com/u/cryptolinx/ | 8 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © cryptolinx - jango_blockchained - open 💙 source
//@version=5
indicator("[CLX] Motion. - Logo", overlay = true)
// ———— Simple Animated Logo/Tag Idea {
//
renderLogo(string _tagline, string _sizeLogo = size.huge, string _sizeTag = size.normal, color _colorLogo = #ff5252, color _colorTag = #ffffff96, _colorDecor = #ff525234, int _x = bar_index, float _y = 1000) =>
// >>
array.from(
label.new(_x, _y, text = '', size = _sizeLogo, color = #00000000, textcolor = _colorLogo, text_font_family = font.family_default, style = label.style_label_center, textalign = text.align_center),
label.new(_x, _y, text = '└', size = _sizeLogo, color = #00000000, textcolor = _colorDecor, text_font_family = font.family_default, style = label.style_label_upper_right, textalign = text.align_left),
label.new(_x, _y, text = '┘', size = _sizeLogo, color = #00000000, textcolor = _colorDecor, text_font_family = font.family_default, style = label.style_label_upper_left, textalign = text.align_left),
label.new(_x, _y, text = '┌', size = _sizeLogo, color = #00000000, textcolor = _colorDecor, text_font_family = font.family_default, style = label.style_label_lower_right, textalign = text.align_left),
label.new(_x, _y, text = '┐', size = _sizeLogo, color = #00000000, textcolor = _colorDecor, text_font_family = font.family_default, style = label.style_label_lower_left, textalign = text.align_left),
label.new(_x, _y, text = ' ', size = _sizeLogo, color = #00000000, textcolor = color.new(_colorLogo, 75), text_font_family = font.family_default, style = label.style_label_down, textalign = text.align_left),
label.new(_x, _y, text = '\n\n\n\n' + _tagline, size = _sizeTag, color = #00000000, textcolor = _colorTag, text_font_family = font.family_monospace, style = label.style_label_up, textalign = text.align_left))
// }
// ———— Update Logo {
//
update(array <label> _logo, string _textLogo, string _textTagline, int _x = bar_index, float _y = 1000) =>
// --
if barstate.islast
for i = 0 to array.size(_logo) - 1
label.set_xy(array.get(_logo, i), _x, _y)
label.set_text(array.get(_logo, 0), _textLogo)
label.set_text(array.get(_logo, 6), _textTagline)
// >>
// void
// }
// ———— Import Motion Library {
//
import cryptolinx/Motion/10 as motion
// --
varip logoKf = motion.keyframe.new(1, 7)
string marquee = motion.transition(logoKf, _fx = 'marquee', _seq = 'M◞TION.M◟TION.M◜TION.M◝TION.', _subLen = 7)
varip taglineKf = motion.keyframe.new(4, 1)
motion.iteration(taglineKf, _seqArr = array.from('Showcase','Library'), _refill = true)
// --
var array <label> LOGO = renderLogo('A Pine Script™ Showcase -', size.huge)
update(LOGO, marquee, '\n\n\n\n' + '- A Pine Script™ ' + taglineKf.output + ' -')
// }
// # EOF |
Golden Pocket | https://www.tradingview.com/script/wtMG0NgE-Golden-Pocket/ | TradingWolf | https://www.tradingview.com/u/TradingWolf/ | 1,276 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradingWolf
import TradingWolf/TradingWolfLibary/6 as tw
import HeWhoMustNotBeNamed/RecursiveAlerts/2 as al
//@version=5
indicator(title = "Golden Pocket", shorttitle = "GP", overlay=true, max_boxes_count = 500, max_lines_count = 500)
//#region Inputs
lineGroup = "=== Line ==="
show_line = input.bool(true, title="Fib Line", inline="0", group=lineGroup)
line_colour = input.color(color.black, title="", inline="0", group=lineGroup)
line_style = input.string(defval=line.style_dashed, title='', options=[line.style_dashed, line.style_dotted, line.style_solid], inline="0", group=lineGroup)
boxGroup = "=== Box ==="
box_color = input.color(color.new(#FFD700,80), title="Box Colour", group=boxGroup, inline="0")
closed_color = input.color(color.new(color.gray,90), title="Closed", group=boxGroup, inline="0")
settingsGroup = "=== Settings ==="
fib_level_1 = input.float(0.618, title="Fib Level 1", group=settingsGroup, inline="0")
fib_level_2 = input.float(0.65, title="Fib Level 2", group=settingsGroup, inline="0")
piv_distance = input.int(10, title="Pivot Distance", group=settingsGroup, tooltip="Used to calculate where to take the pivot highs and lows from")
ma_filter = input.string("Both Lines", title="MA Filter", group=settingsGroup, options=["Both Lines","Fast Line","None"], tooltip="Both Lines - Both trend lines must be trending the same direction\nFast Line - Only the First MA will be taken into account as a filter\nNone - No filter")
percentage_away = input.float(10.0, title="Remove Box if (%) away", group=settingsGroup, tooltip="If price moves this % distance away from the box, the box will stop extending keeping your chart cleaner")*0.01
alert_on = input.bool(true, title="Alerts", group=settingsGroup, tooltip="Click Add alert and leave the conditon box on 'Any alert() function call'")
maGroup = "=== Moving Average ==="
ma_on = input.bool(true, title = "", inline="0", group=maGroup)
ma_distance = input.int(21, title="MA", inline="0", group=maGroup)
ma_type = input.string("EMA",title="", inline="0", group=maGroup, options=["EMA", "SMA"])
ma_tf = input.timeframe("", title="", inline="0", group=maGroup)
ma_color = input.color(color.orange, title="", inline="0", group=maGroup)
ma_on_2 = input.bool(true, title = "", inline="0.0", group=maGroup)
ma_distance_2 = input.int(50, title="MA", inline="0.0", group=maGroup)
ma_type_2 = input.string("EMA",title="", inline="0.0", group=maGroup, options=["EMA", "SMA"])
ma_tf_2 = input.timeframe("", title="", inline="0.0", group=maGroup)
ma_color_2 = input.color(color.navy, title="", inline="0.0", group=maGroup)
//#endregion
//#region Arrays
//arrays
var int[] _highIndex = array.new_int()
var int[] _lowIndex = array.new_int()
var float[] _highPrice = array.new_float()
var float[] _lowPrice = array.new_float()
var box[] _bearBoxes = array.new_box()
var box[] _bullBoxes = array.new_box()
var line[] _bearLines = array.new_line()
var line[] _bullLines = array.new_line()
//#endregion
//#region MA
ma = request.security(syminfo.tickerid, ma_tf, tw.getMA(ma_type,ma_distance))
ma_2 = request.security(syminfo.tickerid, ma_tf_2, tw.getMA(ma_type_2,ma_distance_2))
plot(ma_on ? ma : na, color=ma_color)
plot(ma_on_2 ? ma_2 : na, color=ma_color_2)
//#endregion
//#region Pivots
//Pivots
pivot_high = ta.pivothigh(high,piv_distance,piv_distance)
pivot_low = ta.pivotlow(low,piv_distance,piv_distance)
//Add to array if new piv high or low found
if pivot_high
array.unshift(_highIndex, bar_index-piv_distance)
array.unshift(_highPrice, pivot_high)
if pivot_low
array.unshift(_lowIndex, bar_index-piv_distance)
array.unshift(_lowPrice, pivot_low)
//#endregion
//#region Fib Calculation/Drawing
draw_fib()=>
//Check array size
if array.size(_highIndex)>0 and array.size(_lowIndex)>0
//Check which index is older/newer
direction = math.min(array.get(_highIndex,0),array.get(_lowIndex,0)) == array.get(_highIndex,0) ? 1 : 0
//Determine Line Positions
x1 = direction==1 ? array.get(_lowIndex,0) : array.get(_highIndex,0)
x2 = direction==1 ? array.get(_highIndex,0) : array.get(_lowIndex,0)
y1 = direction==1 ? array.get(_lowPrice,0) : array.get(_highPrice,0)
y2 = direction==1 ? array.get(_highPrice,0) : array.get(_lowPrice,0)
ma_bull_filter = ma_filter=="Both Lines" ? y1 > ma and y2 > ma and ma > ma_2 : ma_filter=="Fast Line" ? y1 > ma and y2 > ma : true
ma_bear_filter = ma_filter=="Both Lines" ? y1 < ma and y2 < ma and ma < ma_2 : ma_filter=="Fast Line" ? y1 < ma and y2 < ma : true
//Piv High Fib
if pivot_high and ma_bull_filter
//Line from low - High
if show_line
line.new(x1,y1,x2,y2, style=line_style, color=line_colour)
//Fib Box
_boxLow = direction==0 ? ((y2-y1)*fib_level_2)+y1 : ((y1-y2)*fib_level_2)+y2
_boxHigh = direction==0 ? ((y2-y1)*fib_level_1)+y1 : ((y1-y2)*fib_level_1)+y2
array.push(_bullBoxes,box.new(x1,_boxLow, bar_index, _boxHigh, bgcolor=box_color, border_color = box_color))
//Piv Low Fib
if pivot_low and ma_bear_filter
if show_line
//Line from low - High
line.new(x1,y1,x2,y2, style=line_style, color=line_colour)
//Fib Box
_boxLow = direction==1 ? ((y2-y1)*fib_level_2)+y1 : ((y1-y2)*fib_level_2)+y2
_boxHigh = direction==1 ? ((y2-y1)*fib_level_1)+y1 : ((y1-y2)*fib_level_1)+y2
array.push(_bearBoxes,box.new(x2,_boxLow, bar_index, _boxHigh, bgcolor=box_color, border_color = box_color))
draw_fib()
//#endregion
//#region Extend Boxes
extend_boxes(_array, _type)=>
if array.size(_array)>0
for i = 0 to array.size(_array)-1
_box = array.get(_array,i)
_boxLow = box.get_bottom(_box)
_boxHigh = box.get_top(_box)
_boxLeft = box.get_left(_box)
_boxRight = box.get_right(_box)
if _type=="bull" and _boxRight == bar_index
if low > _boxHigh
box.set_right(_box,bar_index+1)
else
box.set_bgcolor(_box, closed_color)
box.set_border_color(_box, closed_color)
box.set_text_color(_box, closed_color)
box.set_right(_box,bar_index)
if _type=="bear" and _boxRight == bar_index
if high < _boxLow
box.set_right(_box,bar_index+1)
else
box.set_bgcolor(_box, closed_color)
box.set_border_color(_box, closed_color)
box.set_text_color(_box, closed_color)
box.set_right(_box,bar_index)
extend_boxes(_bullBoxes,"bull")
extend_boxes(_bearBoxes,"bear")
//#endregion
//#region alert
alertArray(_boxArray, _high,_low)=>
if array.size(_boxArray)>0
for i = 0 to array.size(_boxArray)-1
_box = array.get(_boxArray,i)
_boxLow = box.get_bottom(_box)
_boxHigh = box.get_top(_box)
_boxRight = box.get_right(_box)
_alertSignal = "Golden Pocket Hit on "
alert_message = _alertSignal + syminfo.tickerid
if (_low <= _boxHigh and _low[1]>_boxHigh and _boxRight==bar_index) or (_high >= _boxLow and _high[1] < _boxLow and _boxRight==bar_index)
al.rAlert(alert_message, str.tostring(i))
if alert_on
alertArray(_bearBoxes, high, low)
alertArray(_bullBoxes, high, low)
if array.size(_bullBoxes)>1
for i = 0 to array.size(_bullBoxes)-1
_box = array.get(_bullBoxes,i)
_boxHigh = box.get_top(_box)
if close*(1-percentage_away) > _boxHigh
array.remove(_bullBoxes,i)
break
if array.size(_bearBoxes)>1
for i = 0 to array.size(_bearBoxes)-1
_box = array.get(_bearBoxes,i)
_boxLow = box.get_bottom(_box)
if close*(1+percentage_away) < _boxLow
array.remove(_bearBoxes,i)
break
//#endregion
|
3 Zigzag for MTF Fib Alert [MsF] | https://www.tradingview.com/script/RDhgaIHB/ | Trader_Morry | https://www.tradingview.com/u/Trader_Morry/ | 463 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Trader_Morry
//@version=5
indicator(title='3 Zigzag for MTF Fib Alert [MsF]', shorttitle='3 ZigZag MTF Fib', overlay=true, max_bars_back = 5000)
///////
// Input values
// [
var GRP1 = "--- Zigzag setting 1 ---"
prd1 = input.int(8, "Period", minval=1, step=1, group = GRP1)
upcol1 = input.color(defval = color.lime, title = "Up Color", group = GRP1)
dncol1 = input.color(defval = color.red, title = "Down Color", group = GRP1)
zz1style = input.string(defval = "Dashed", title = "Line Style", options = ["Solid", "Dashed", "Dotted"], group = GRP1)
zz1width = input.int(defval = 2, title = "Line Width", minval = 1, maxval = 4, group = GRP1)
cLeg1 = input.string(defval = "Previous", title = "Choice ZigZag Leg for Fib", options = ["Latest", "Previous", "N-Calculation"], group = GRP1)
showZZ1 = input.bool(defval = true, title = "Show Zigzag", group = GRP1, inline = "show")
showFIB1 = input.bool(defval = true, title = "Show Fib", group = GRP1, inline = "show")
var GRP2 = "--- Zigzag setting 2 ---"
prd2 = input.int(20, "Period", minval=1, step=1, group = GRP2)
upcol2 = input.color(defval = color.olive, title = "Up Color", group = GRP2)
dncol2 = input.color(defval = color.purple, title = "Down Color", group = GRP2)
zz2style = input.string(defval = "Solid", title = "Line Style", options = ["Solid", "Dashed", "Dotted"], group = GRP2)
zz2width = input.int(defval = 2, title = "Line Width", minval = 1, maxval = 4, group = GRP2)
cLeg2 = input.string(defval = "Latest", title = "Choice ZigZag Leg for Fib", options = ["Latest", "Previous"], group = GRP2)
showZZ2 = input.bool(defval = true, title = "Show Zigzag", group = GRP2, inline = "show")
showFIB2 = input.bool(defval = true, title = "Show Fib", group = GRP2, inline = "show")
showHL2 = input.bool(defval = false, title = "H.Line", group = GRP2, inline = "show")
fibolinecol2= input.color(defval=color.white, title = "", group = GRP2, inline = "show")
labelcol2 = fibolinecol2
var GRP3 = "--- Zigzag setting 3 ---"
prd3 = input.int(100, "Period", minval=1, step=1, group = GRP3)
upcol3 = input.color(defval = color.blue, title = "Up Color", group = GRP3)
dncol3 = input.color(defval = color.orange, title = "Down Color", group = GRP3)
zz3style = input.string(defval = "Solid", title = "Line Style", options = ["Solid", "Dashed", "Dotted"], group = GRP3)
zz3width = input.int(defval = 2, title = "Line Width", minval = 1, maxval = 4, group = GRP3)
cLeg3 = input.string(defval = "Latest", title = "Choice ZigZag Leg for Fib", options = ["Latest", "Previous"], group = GRP3)
showZZ3 = input.bool(defval = true, title = "Show Zigzag", group = GRP3, inline = "show")
showFIB3 = input.bool(defval = true, title = "Show Fib", group = GRP3, inline = "show")
showHL3 = input.bool(defval = false, title = "H.Line", group = GRP3, inline = "show")
fibolinecol3= input.color(defval=color.orange, title = "", group = GRP3, inline = "show")
labelcol3 = fibolinecol3
var GRP6 = "Zigzag Common setting"
plotZZ = input.bool(defval = false, title = "Zigzag -> Plot", group = GRP6)
var GRP4 = "Fibonacci Common Color setting"
fbCol0000_0236 = input.color(defval = color.rgb(255, 0, 0, 80), title = "Fib Color 0000_0236", group = GRP4)
fbCol0236_0382 = input.color(defval = color.rgb(255, 152, 0, 80), title = "Fib Color 0236_0382", group = GRP4)
fbCol0382_0500 = input.color(defval = color.rgb(255, 235, 59, 80), title = "Fib Color 0382_0500", group = GRP4)
fbCol0500_0618 = input.color(defval = color.rgb(0, 230, 118, 80), title = "Fib Color 0500_0618", group = GRP4)
fbCol0618_0764 = input.color(defval = color.rgb(33, 150, 243, 80), title = "Fib Color 0618_0764", group = GRP4)
fbCol0764_1000 = input.color(defval = color.rgb(156, 39, 176, 80), title = "Fib Color 0764_1000", group = GRP4)
var GRP5 = "Horizontal Lines Common setting"
fiboLineStyle2 = input.string(defval = "Solid", title = "Style", options = ["Solid", "Dashed", "Dotted"], group = GRP5)
fibolinewidth2 = input.int(defval = 1, title = "Width", minval = 1, maxval = 4, group = GRP5)
labelloc2 = input.string(defval='Left', title='Label', options=['Left', 'Right'], group = GRP5)
fiboLineStyle3 = fiboLineStyle2
fibolinewidth3 = fibolinewidth2
labelloc3 = labelloc2
// ]
// Drawing Fibonacci Function
// [
var alertCode_1 = ""
var alertCode_2 = ""
var alertCode_3 = ""
drawing_Fibonacci(z, x, a_cnt) =>
_range = x-z
// Fibonacci value caluculation
fib0000 = z
fib0236 = z+_range*0.236
fib0382 = z+_range*0.382
fib0500 = z+_range*0.500
fib0618 = z+_range*0.618
fib0764 = z+_range*0.764
fib1000 = x
// Fibonacci position calculation
x_begin = bar_index + 5 + (a_cnt * 20)
x_end = bar_index + 20 + (a_cnt * 20)
// Drawing Fibonacci boxes
b000_236 = box(na)
if barstate.islast
b000_236 := box.new(x_begin, fib0000, x_end, fib0236, bgcolor=fbCol0000_0236, border_color=fbCol0000_0236)
box.delete(b000_236[1])
b236_382 = box(na)
if barstate.islast
b236_382 := box.new(x_begin, fib0236, x_end, fib0382, bgcolor=fbCol0236_0382, border_color=fbCol0236_0382)
box.delete(b236_382[1])
b382_500 = box(na)
if barstate.islast
b382_500 := box.new(x_begin, fib0382, x_end, fib0500, bgcolor=fbCol0382_0500, border_color=fbCol0382_0500)
box.delete(b382_500[1])
b500_618 = box(na)
if barstate.islast
b500_618 := box.new(x_begin, fib0500, x_end, fib0618, bgcolor=fbCol0500_0618, border_color=fbCol0500_0618)
box.delete(b500_618[1])
b618_764 = box(na)
if barstate.islast
b618_764 := box.new(x_begin, fib0618, x_end, fib0764, bgcolor=fbCol0618_0764, border_color=fbCol0618_0764)
box.delete(b618_764[1])
b764_1000 = box(na)
if barstate.islast
b764_1000 := box.new(x_begin, fib0764, x_end, fib1000, bgcolor=fbCol0764_1000, border_color=fbCol0764_1000)
box.delete(b764_1000[1])
// ]
// Noticification Judge
// [
alertCode = ""
if (((fib0000 > close and fib0000 <= close[1]) or (fib0000 < close and fib0000 >= close[1])))
alertCode := "fib0000"
if (((fib0236 > close and fib0236 <= close[1]) or (fib0236 < close and fib0236 >= close[1])))
alertCode := "fib0236"
if (((fib0382 > close and fib0382 <= close[1]) or (fib0382 < close and fib0382 >= close[1])))
alertCode := "fib0382"
if (((fib0500 > close and fib0500 <= close[1]) or (fib0500 < close and fib0500 >= close[1])))
alertCode := "fib0500"
if (((fib0618 > close and fib0618 <= close[1]) or (fib0618 < close and fib0618 >= close[1])))
alertCode := "fib0618"
if (((fib0764 > close and fib0764 <= close[1]) or (fib0764 < close and fib0764 >= close[1])))
alertCode := "fib0764"
if (((fib1000 > close and fib1000 <= close[1]) or (fib1000 < close and fib1000 >= close[1])))
alertCode := "fib1000"
alertCode
// ]
// ]
// Calculation zigzag
// [
float ph1 = ta.highestbars(high, prd1) == 0 ? high : na
float pl1 = ta.lowestbars(low, prd1) == 0 ? low : na
float ph2 = ta.highestbars(high, prd2) == 0 ? high : na
float pl2 = ta.lowestbars(low, prd2) == 0 ? low : na
float ph3 = ta.highestbars(high, prd3) == 0 ? high : na
float pl3 = ta.lowestbars(low, prd3) == 0 ? low : na
var dir1 = 0
var dir2 = 0
var dir3 = 0
iff_1 = pl1 and na(ph1) ? -1 : dir1
dir1 := ph1 and na(pl1) ? 1 : iff_1
iff_2 = pl2 and na(ph2) ? -1 : dir2
dir2 := ph2 and na(pl2) ? 1 : iff_2
iff_3 = pl3 and na(ph3) ? -1 : dir3
dir3 := ph3 and na(pl3) ? 1 : iff_3
var max_array_size = 10 // [5, 2] matrix
var zigzag1 = array.new_float(0)
var zigzag2 = array.new_float(0)
var zigzag3 = array.new_float(0)
var fib_zigzag1 = array.new_float(0)
var fib_zigzag2 = array.new_float(0)
var fib_zigzag3 = array.new_float(0)
oldzigzag1 = array.copy(zigzag1)
oldzigzag2 = array.copy(zigzag2)
oldzigzag3 = array.copy(zigzag3)
add_to_zigzag(pointer, value, bindex) =>
array.unshift(pointer, bindex)
array.unshift(pointer, value)
if array.size(pointer) > max_array_size
array.pop(pointer)
array.pop(pointer)
update_zigzag(pointer, value, bindex, dir) =>
if array.size(pointer) == 0
add_to_zigzag(pointer, value, bindex)
else
if dir == 1 and value > array.get(pointer, 0) or dir == -1 and value < array.get(pointer, 0)
array.set(pointer, 0, value)
array.set(pointer, 1, bindex)
0.
// Add for Fibonacci array -> [H, L, H, L,...]
add_to_fib_zigzag(pointer, value) =>
array.unshift(pointer, value)
if array.size(pointer) > max_array_size
array.pop(pointer)
dir1changed = ta.change(dir1)
if ph1 or pl1
if dir1changed
add_to_zigzag(zigzag1, dir1 == 1 ? ph1 : pl1, bar_index)
else
update_zigzag(zigzag1, dir1 == 1 ? ph1 : pl1, bar_index, dir1)
dir2changed = ta.change(dir2)
if ph2 or pl2
if dir2changed
add_to_zigzag(zigzag2, dir2 == 1 ? ph2 : pl2, bar_index)
else
update_zigzag(zigzag2, dir2 == 1 ? ph2 : pl2, bar_index, dir2)
dir3changed = ta.change(dir3)
if ph2 or pl2 or pl3
if dir3changed
add_to_zigzag(zigzag3, dir3 == 1 ? ph3 : pl3, bar_index)
else
update_zigzag(zigzag3, dir3 == 1 ? ph3 : pl3, bar_index, dir3)
if array.size(zigzag1) >= 6
var line zzline1 = na
var label zzlabel1 = na
if array.get(zigzag1, 0) != array.get(oldzigzag1, 0) or array.get(zigzag1, 1) != array.get(oldzigzag1, 1)
if array.get(zigzag1, 2) == array.get(oldzigzag1, 2) and array.get(zigzag1, 3) == array.get(oldzigzag1, 3)
line.delete(zzline1)
label.delete(zzlabel1)
zzline1 := line.new(x1=math.round(array.get(zigzag1, 1)), y1=array.get(zigzag1, 0), x2=math.round(array.get(zigzag1, 3)), y2=array.get(zigzag1, 2), color=(plotZZ or not showZZ1)?color.rgb(255,255,255,100):dir1 == 1 ? upcol1 : dncol1, width=zz1width, style=zz1style == 'Dashed' ? line.style_dashed : (zz1style == 'Dotted') ? line.style_dotted : line.style_solid)
zzline1
if showZZ1
zzlabel1 := plotZZ?label.new(x=math.round(array.get(zigzag1, 1)), y=array.get(zigzag1, 0), yloc=dir1==1?yloc.abovebar:yloc.belowbar, color=dir1 == 1 ? upcol1 : dncol1, size=size.tiny, style = label.style_circle):na
if showFIB1
if cLeg1 == "Latest"
add_to_fib_zigzag(fib_zigzag1, array.get(zigzag1, 0))
add_to_fib_zigzag(fib_zigzag1, array.get(zigzag1, 2))
else if cLeg1 == "Previous"
if line.get_y1(zzline1[1]) > 0
add_to_fib_zigzag(fib_zigzag1, line.get_y1(zzline1[1]))
else // N-Caluculation
if line.get_y1(zzline1[1]) > 0
add_to_fib_zigzag(fib_zigzag1, line.get_y1(zzline1[1]))
add_to_fib_zigzag(fib_zigzag1, line.get_y2(zzline1[1]))
// Drawing Fibonacci 1
if array.size(fib_zigzag1) >= 2
if cLeg1 == "N-Calculation" and array.size(fib_zigzag1) >= 4
if array.get(fib_zigzag1, 0) > 0 and array.get(fib_zigzag1, 1) > 0 and array.get(fib_zigzag1, 2) > 0 and array.get(fib_zigzag1, 3) > 0
if dir1 == 1 // Up trend
y1 = array.get(fib_zigzag1, 1)
y2 = array.get(fib_zigzag1, 1)-array.get(fib_zigzag1, 2)+array.get(fib_zigzag1, 0)
alertCode_1 := drawing_Fibonacci(y1, y2, 0)
else // Down trend
y1 = array.get(fib_zigzag1, 1)
y2 = array.get(fib_zigzag1, 1)-array.get(fib_zigzag1, 2)+array.get(fib_zigzag1, 0)
alertCode_1 := drawing_Fibonacci(y1, y2, 0)
else
alertCode_1 := drawing_Fibonacci(array.get(fib_zigzag1, 0), array.get(fib_zigzag1, 1), 0)
if array.size(zigzag2) >= 6
var line zzline2 = na
var label zzlabel2 = na
if array.get(zigzag2, 0) != array.get(oldzigzag2, 0) or array.get(zigzag2, 1) != array.get(oldzigzag2, 1)
if array.get(zigzag2, 2) == array.get(oldzigzag2, 2) and array.get(zigzag2, 3) == array.get(oldzigzag2, 3)
line.delete(zzline2)
label.delete(zzlabel2)
zzline2 := line.new(x1=math.round(array.get(zigzag2, 1)), y1=array.get(zigzag2, 0), x2=math.round(array.get(zigzag2, 3)), y2=array.get(zigzag2, 2), color=(plotZZ or not showZZ2)?color.rgb(255,255,255,100):dir2 == 1 ? upcol2 : dncol2, width=zz2width, style=zz2style == 'Dashed' ? line.style_dashed : (zz2style == 'Dotted') ? line.style_dotted : line.style_solid)
zzline2
if showZZ2
zzlabel2 := plotZZ?label.new(x=math.round(array.get(zigzag2, 1)), y=array.get(zigzag2, 0), yloc=dir2==1?yloc.abovebar:yloc.belowbar, color=dir2 == 1 ? upcol2 : dncol2, size=size.small, style = label.style_circle):na
if showFIB2
if cLeg2 == "Latest"
add_to_fib_zigzag(fib_zigzag2, array.get(zigzag2, 0))
add_to_fib_zigzag(fib_zigzag2, array.get(zigzag2, 2))
else
if line.get_y1(zzline2[1]) > 0
add_to_fib_zigzag(fib_zigzag2, line.get_y1(zzline2[1]))
// Drawing Fibonacci 2
if array.size(fib_zigzag2) >= 2
alertCode_2 := drawing_Fibonacci(array.get(fib_zigzag2, 0), array.get(fib_zigzag2, 1), 1)
// Drawing Horizontal Line 2
// -------------------------------------------------------------------------------
var fibo_ratios = array.new_float(0)
shownlevels = 1
if barstate.isfirst
array.push(fibo_ratios, 0.0)
array.push(fibo_ratios, 1.0)
// -------------------------------------------------------------------------------
var fibolinesPrev2 = array.new_line(0)
var fibolabelsPrev2 = array.new_label(0)
var fibolinesLatest2 = array.new_line(0)
var fibolabelsLatest2 = array.new_label(0)
// -------------------------------------------------------------------------------
if cLeg2 != "Latest" and showHL2 and showFIB2 and array.size(zigzag2) >= 6 and barstate.islast
if array.size(fibolinesPrev2) > 0
for x = 0 to array.size(fibolinesPrev2) - 1 by 1
line.delete(array.get(fibolinesPrev2, x))
label.delete(array.get(fibolabelsPrev2, x))
if array.size(fibolinesPrev2) > 0
for x = 0 to array.size(fibolinesPrev2) - 1 by 1
line.delete(array.get(fibolinesPrev2, x))
label.delete(array.get(fibolabelsPrev2, x))
diff = array.get(zigzag2, 4) - array.get(zigzag2, 2)
stopit = false
for x = 0 to array.size(fibo_ratios) - 1 by 1
if stopit and x > shownlevels
break
array.unshift(fibolinesPrev2, line.new(x1=math.round(array.get(zigzag2, 5)), y1=array.get(zigzag2, 2) + diff * array.get(fibo_ratios, x), x2=bar_index, y2=array.get(zigzag2, 2) + diff * array.get(fibo_ratios, x), color=fibolinecol2, extend=extend.right, style=fiboLineStyle2 == 'Dashed' ? line.style_dashed : (zz1style == 'Dotted') ? line.style_dotted : line.style_solid))
label_x_loc = labelloc2 == 'Left' ? math.round(array.get(zigzag2, 5)) - 1 : bar_index + 15
// array.unshift(fibolabelsPrev2, label.new(x=label_x_loc, y=array.get(zigzag2, 2) + diff * array.get(fibo_ratios, x), text=str.tostring(array.get(fibo_ratios, x), '#.###') + '(' + str.tostring(math.round_to_mintick(array.get(zigzag2, 2) + diff * array.get(fibo_ratios, x))) + ')', textcolor=labelcol2, style=label.style_none))
array.unshift(fibolabelsPrev2, label.new(x=label_x_loc, y=array.get(zigzag2, 2) + diff * array.get(fibo_ratios, x), text=str.tostring(math.round_to_mintick(array.get(zigzag2, 2) + diff * array.get(fibo_ratios, x))) , textcolor=labelcol2, style=label.style_none))
if dir2 == 1 and array.get(zigzag2, 2) + diff * array.get(fibo_ratios, x) > array.get(zigzag2, 0) or dir2 == -1 and array.get(zigzag2, 2) + diff * array.get(fibo_ratios, x) < array.get(zigzag2, 0)
stopit := true
stopit
// Addition to © LonesomeTheBlue origial code ------------------------------------
if cLeg2 == "Latest" and showHL2 and showFIB2 and array.size(zigzag2) >= 6 and barstate.islast
if array.size(fibolinesLatest2) > 0
for x = 0 to array.size(fibolinesLatest2) - 1 by 1
line.delete(array.get(fibolinesLatest2, x))
label.delete(array.get(fibolabelsLatest2, x))
if array.size(fibolinesLatest2) > 0
for x = 0 to array.size(fibolinesLatest2) - 1 by 1
line.delete(array.get(fibolinesLatest2, x))
label.delete(array.get(fibolabelsLatest2, x))
diff2 = array.get(zigzag2, 0) - array.get(zigzag2, 2)
stopit2 = false
for x = 0 to array.size(fibo_ratios) - 1 by 1
if stopit2 and x > shownlevels
break
array.unshift(fibolinesLatest2, line.new(x1=math.round(array.get(zigzag2, 3)), y1=array.get(zigzag2, 2) + diff2 * (1-array.get(fibo_ratios, x)), x2=bar_index, y2=array.get(zigzag2, 2) + diff2 * (1-array.get(fibo_ratios, x)), color=fibolinecol2, extend=extend.right, style=fiboLineStyle2 == 'Dashed' ? line.style_dashed : (zz1style == 'Dotted') ? line.style_dotted : line.style_solid))
label_x_loc2 = labelloc2 == 'Left' ? math.round(array.get(zigzag2, 3)) - 1 : bar_index + 15
// array.unshift(fibolabelsLatest2, label.new(x=label_x_loc2, y=array.get(zigzag2, 2) + diff2 * (1-array.get(fibo_ratios, x)), text=str.tostring(array.get(fibo_ratios, x), '#.###') + '(' + str.tostring(math.round_to_mintick(array.get(zigzag2, 2) + diff2 * (1-array.get(fibo_ratios, x)))) + ')', textcolor=labelcol2, style=label.style_none))
array.unshift(fibolabelsLatest2, label.new(x=label_x_loc2, y=array.get(zigzag2, 2) + diff2 * (1-array.get(fibo_ratios, x)), text=str.tostring(math.round_to_mintick(array.get(zigzag2, 2) + diff2 * (1-array.get(fibo_ratios, x)))) , textcolor=labelcol2, style=label.style_none))
if dir2 == 1 and array.get(zigzag2, 2) + diff2 * array.get(fibo_ratios, x) > array.get(zigzag2, 0) or dir2 == -1 and array.get(zigzag2, 2) + diff2 * array.get(fibo_ratios, x) < array.get(zigzag2, 0)
stopit2 := true
stopit2
// -------------------------------------------------------------------------------
if array.size(zigzag3) >= 6
var line zzline3 = na
var label zzlabel3 = na
if array.get(zigzag3, 0) != array.get(oldzigzag3, 0) or array.get(zigzag3, 1) != array.get(oldzigzag3, 1)
if array.get(zigzag3, 2) == array.get(oldzigzag3, 2) and array.get(zigzag3, 3) == array.get(oldzigzag3, 3)
line.delete(zzline3)
label.delete(zzlabel3)
zzline3 := line.new(x1=math.round(array.get(zigzag3, 1)), y1=array.get(zigzag3, 0), x2=math.round(array.get(zigzag3, 3)), y2=array.get(zigzag3, 2), color=(plotZZ or not showZZ3)?color.rgb(255,255,255,100):dir3 == 1 ? upcol3 : dncol3, width=zz3width, style=zz3style == 'Dashed' ? line.style_dashed : (zz3style == 'Dotted') ? line.style_dotted : line.style_solid)
zzline3
if showZZ3
zzlabel3 := plotZZ?label.new(x=math.round(array.get(zigzag3, 1)), y=array.get(zigzag3, 0), yloc=dir3==1?yloc.abovebar:yloc.belowbar, color=dir3 == 1 ? upcol3 : dncol3, size=size.normal, style = label.style_circle):na
if showFIB3
if cLeg3 == "Latest"
add_to_fib_zigzag(fib_zigzag3, array.get(zigzag3, 0))
add_to_fib_zigzag(fib_zigzag3, array.get(zigzag3, 2))
else
if line.get_y1(zzline3[1]) > 0
add_to_fib_zigzag(fib_zigzag3, line.get_y1(zzline3[1]))
// Drawing Fibonacci 3
if array.size(fib_zigzag3) >= 2
alertCode_3 := drawing_Fibonacci(array.get(fib_zigzag3, 0), array.get(fib_zigzag3, 1), 2)
// ]
// Drawing Horizontal Line 3
// -------------------------------------------------------------------------------
var fibolinesPrev3 = array.new_line(0)
var fibolabelsPrev3 = array.new_label(0)
var fibolinesLatest3 = array.new_line(0)
var fibolabelsLatest3 = array.new_label(0)
// -------------------------------------------------------------------------------
if cLeg3 != "Latest" and showHL3 and showFIB3 and array.size(zigzag3) >= 6 and barstate.islast
if array.size(fibolinesPrev3) > 0
for x = 0 to array.size(fibolinesPrev3) - 1 by 1
line.delete(array.get(fibolinesPrev3, x))
label.delete(array.get(fibolabelsPrev3, x))
if array.size(fibolinesPrev3) > 0
for x = 0 to array.size(fibolinesPrev3) - 1 by 1
line.delete(array.get(fibolinesPrev3, x))
label.delete(array.get(fibolabelsPrev3, x))
diff = array.get(zigzag3, 4) - array.get(zigzag3, 2)
stopit = false
for x = 0 to array.size(fibo_ratios) - 1 by 1
if stopit and x > shownlevels
break
array.unshift(fibolinesPrev3, line.new(x1=math.round(array.get(zigzag3, 5)), y1=array.get(zigzag3, 2) + diff * array.get(fibo_ratios, x), x2=bar_index, y2=array.get(zigzag3, 2) + diff * array.get(fibo_ratios, x), color=fibolinecol3, extend=extend.right, style=fiboLineStyle3 == 'Dashed' ? line.style_dashed : (zz1style == 'Dotted') ? line.style_dotted : line.style_solid))
label_x_loc = labelloc3 == 'Left' ? math.round(array.get(zigzag3, 5)) - 1 : bar_index + 15
// array.unshift(fibolabelsPrev3, label.new(x=label_x_loc, y=array.get(zigzag3, 2) + diff * array.get(fibo_ratios, x), text=str.tostring(array.get(fibo_ratios, x), '#.###') + '(' + str.tostring(math.round_to_mintick(array.get(zigzag3, 2) + diff * array.get(fibo_ratios, x))) + ')', textcolor=labelcol3, style=label.style_none))
array.unshift(fibolabelsPrev3, label.new(x=label_x_loc, y=array.get(zigzag3, 2) + diff * array.get(fibo_ratios, x), text=str.tostring(math.round_to_mintick(array.get(zigzag3, 2) + diff * array.get(fibo_ratios, x))) , textcolor=labelcol3, style=label.style_none))
if dir3 == 1 and array.get(zigzag3, 2) + diff * array.get(fibo_ratios, x) > array.get(zigzag3, 0) or dir3 == -1 and array.get(zigzag3, 2) + diff * array.get(fibo_ratios, x) < array.get(zigzag3, 0)
stopit := true
stopit
// Addition to © LonesomeTheBlue origial code ------------------------------------
if cLeg3 == "Latest" and showHL3 and showFIB3 and array.size(zigzag3) >= 6 and barstate.islast
if array.size(fibolinesLatest3) > 0
for x = 0 to array.size(fibolinesLatest3) - 1 by 1
line.delete(array.get(fibolinesLatest3, x))
label.delete(array.get(fibolabelsLatest3, x))
if array.size(fibolinesLatest3) > 0
for x = 0 to array.size(fibolinesLatest3) - 1 by 1
line.delete(array.get(fibolinesLatest3, x))
label.delete(array.get(fibolabelsLatest3, x))
diff2 = array.get(zigzag3, 0) - array.get(zigzag3, 2)
stopit2 = false
for x = 0 to array.size(fibo_ratios) - 1 by 1
if stopit2 and x > shownlevels
break
array.unshift(fibolinesLatest3, line.new(x1=math.round(array.get(zigzag3, 3)), y1=array.get(zigzag3, 2) + diff2 * (1-array.get(fibo_ratios, x)), x2=bar_index, y2=array.get(zigzag3, 2) + diff2 * (1-array.get(fibo_ratios, x)), color=fibolinecol3, extend=extend.right, style=fiboLineStyle3 == 'Dashed' ? line.style_dashed : (zz1style == 'Dotted') ? line.style_dotted : line.style_solid))
label_x_loc2 = labelloc3 == 'Left' ? math.round(array.get(zigzag3, 3)) - 1 : bar_index + 15
// array.unshift(fibolabelsLatest3, label.new(x=label_x_loc2, y=array.get(zigzag3, 2) + diff2 * (1-array.get(fibo_ratios, x)), text=str.tostring(array.get(fibo_ratios, x), '#.###') + '(' + str.tostring(math.round_to_mintick(array.get(zigzag3, 2) + diff2 * (1-array.get(fibo_ratios, x)))) + ')', textcolor=labelcol3, style=label.style_none))
array.unshift(fibolabelsLatest3, label.new(x=label_x_loc2, y=array.get(zigzag3, 2) + diff2 * (1-array.get(fibo_ratios, x)), text=str.tostring(math.round_to_mintick(array.get(zigzag3, 2) + diff2 * (1-array.get(fibo_ratios, x)))) , textcolor=labelcol3, style=label.style_none))
if dir3 == 1 and array.get(zigzag3, 2) + diff2 * array.get(fibo_ratios, x) > array.get(zigzag3, 0) or dir3 == -1 and array.get(zigzag3, 2) + diff2 * array.get(fibo_ratios, x) < array.get(zigzag3, 0)
stopit2 := true
stopit2
// -------------------------------------------------------------------------------
// ]
// Fibonacci Notification
// [
alertcondition(alertCode_1 == "fib0000" , "Fib 1 - Crossing 0.00", "Fib 1 Crossing 0.00")
alertcondition(alertCode_1 == "fib0236" , "Fib 1 - Crossing 23.6", "Fib 1 Crossing 23.6")
alertcondition(alertCode_1 == "fib0382" , "Fib 1 - Crossing 38.2", "Fib 1 Crossing 38.2")
alertcondition(alertCode_1 == "fib0500" , "Fib 1 - Crossing 50.0", "Fib 1 Crossing 50.0")
alertcondition(alertCode_1 == "fib0618" , "Fib 1 - Crossing 61.8", "Fib 1 Crossing 61.8")
alertcondition(alertCode_1 == "fib0764" , "Fib 1 - Crossing 76.4", "Fib 1 Crossing 76.4")
alertcondition(alertCode_1 == "fib1000" , "Fib 1 - Crossing 100.0", "Fib 1 Crossing 100.0")
alertcondition(alertCode_2 == "fib0000" , "Fib 2 - Crossing 0.00", "Fib 2 Crossing 0.00")
alertcondition(alertCode_2 == "fib0236" , "Fib 2 - Crossing 23.6", "Fib 2 Crossing 23.6")
alertcondition(alertCode_2 == "fib0382" , "Fib 2 - Crossing 38.2", "Fib 2 Crossing 38.2")
alertcondition(alertCode_2 == "fib0500" , "Fib 2 - Crossing 50.0", "Fib 2 Crossing 50.0")
alertcondition(alertCode_2 == "fib0618" , "Fib 2 - Crossing 61.8", "Fib 2 Crossing 61.8")
alertcondition(alertCode_2 == "fib0764" , "Fib 2 - Crossing 76.4", "Fib 2 Crossing 76.4")
alertcondition(alertCode_2 == "fib1000" , "Fib 2 - Crossing 100.0", "Fib 2 Crossing 100.0")
alertcondition(alertCode_3 == "fib0000" , "Fib 3 - Crossing 0.00", "Fib 3 Crossing 0.00")
alertcondition(alertCode_3 == "fib0236" , "Fib 3 - Crossing 23.6", "Fib 3 Crossing 23.6")
alertcondition(alertCode_3 == "fib0382" , "Fib 3 - Crossing 38.2", "Fib 3 Crossing 38.2")
alertcondition(alertCode_3 == "fib0500" , "Fib 3 - Crossing 50.0", "Fib 3 Crossing 50.0")
alertcondition(alertCode_3 == "fib0618" , "Fib 3 - Crossing 61.8", "Fib 3 Crossing 61.8")
alertcondition(alertCode_3 == "fib0764" , "Fib 3 - Crossing 76.4", "Fib 3 Crossing 76.4")
alertcondition(alertCode_3 == "fib1000" , "Fib 3 - Crossing 100.0", "Fib 3 Crossing 100.0")
// ]
|
Average HL Range - SAT | https://www.tradingview.com/script/RnWPKw4s-Average-HL-Range-SAT/ | sosso_bott | https://www.tradingview.com/u/sosso_bott/ | 53 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sosso_bott
//@version=5
indicator(title="Average Range - SAT", shorttitle="Average Range - SAT", overlay=true)
import sosso_bott/SAT_LIB/28 as sat
import sosso_bott/LevelsManager/12 as lm
no_rep(_symbol, _res, _src) =>
request.security(_symbol, _res, _src[barstate.isrealtime ? 1:0], barmerge.gaps_off, barmerge.lookahead_off)
no_rep2(_symbol, _res, _src) =>
request.security(_symbol, _res, _src[1])
darkMode = input.bool(defval=false, title="Dark Mode", group="== DISPLAY ==")
showMid = input.bool(defval=true, title="Show Average", group="== DISPLAY ==")
showRange = input.bool(defval=true, title="Show range", group="== DISPLAY ==")
colorBg = input.bool(defval=true, title="color Background", group="== DISPLAY ==")
showRangeColor = input.bool(defval=false, title="Color range Background", group="== DISPLAY ==")
colorSignalBg = input.bool(defval=false, title="Color Signal Background", group="== DISPLAY ==")
/////// ******** AVERAGE RANGE **********\\\\\\\\\\\\\\\\\\\\\\\\
res_mid = input.timeframe(defval="", title="timeFrame", group="MID")
src_mid = input.source(defval=close, title="mid source", group="MID")
choice = input.bool(defval=true, title="Heikin Ashi Ticker Data", group="MID")
ha_t_mid = choice ? ticker.heikinashi(syminfo.tickerid) : syminfo.tickerid
//tf
ha_close = no_rep(ha_t_mid, res_mid, src_mid)
ha_high = no_rep(ha_t_mid, res_mid, high)
ha_low = no_rep(ha_t_mid, res_mid, low)
[mid, ranje, midColor, mid_state, uppish, downish, midUp, midDn, realb, reals] = sat.rangeValue(ha_close, ha_high, ha_low, darkMode)
var bool rangeState = na
rangeState := mid == mid[1] ? true : false
/////// ******** AVERAGE RANGE END **********\\\\\\\\\\\\\\\\\\\\\\\\
// ++++++++++++++++++++++++++++ LEVELS TRACK +++++++++++++++++++++++++ \\
reward = input.float(title="Reward Value", defval=1, step=0.5, minval=0.5, group="=== RISK:REWARD ===")
rr_tp = input.float(title='Percentage', defval=0.05, step=0.1, group="=== RISK:REWARD ===")
use_breakSignals = input.bool(title="Use Range Break Signals", defval=true, group="Signals")
buyEntrySource_o = input.string(title = "Buy entry source", defval="Range Mid", options=["CLOSE", "LOW", "HL2", "Range Mid", "MID DN"], group="Signals")
sellEntrySource_o = input.string(title = "Sell entry source", defval="Range Mid", options=["CLOSE", "HIGH", "HL2", "Range Mid", "MID UP"], group="Signals")
use_TPs = input.bool(title="Use Take profit levels ?", defval=false, group="=== TAKEPROFIT LEVELS ===")
useTp1 = input.bool(title="Use TP1 ?", defval=true, group="=== TAKEPROFIT LEVELS ===")
useTp2 = input.bool(title="Use TP2 ?", defval=true, group="=== TAKEPROFIT LEVELS ===")
useTp3 = input.bool(title="Use TP3 ?", defval=true, group="=== TAKEPROFIT LEVELS ===")
useTp4 = input.bool(title="Use TP4 ?", defval=true, group="=== TAKEPROFIT LEVELS ===")
useTp5 = input.bool(title="Use TP5 ?", defval=true, group="=== TAKEPROFIT LEVELS ===")
useTp6 = input.bool(title="Use TP6 ?", defval=true, group="=== TAKEPROFIT LEVELS ===")
slr = input.float(title="Percentage to SL", defval=0.10, step=0.05, group="=== TAKEPROFIT LEVELS ===")
tp1x = input.float(title="Percentage to TP1", defval=0.10, step=0.05, group="=== TAKEPROFIT LEVELS ===")
tp2x = input.float(title="Percentage to TP2", defval=0.30, step=0.05, group="=== TAKEPROFIT LEVELS ===")
tp3x = input.float(title="Percentage to TP3", defval=0.45, step=0.05, group="=== TAKEPROFIT LEVELS ===")
tp4x = input.float(title="Percentage to TP4", defval=0.60, step=0.05, group="=== TAKEPROFIT LEVELS ===")
tp5x = input.float(title="Percentage to TP5", defval=0.80, step=0.05, group="=== TAKEPROFIT LEVELS ===")
tp6x = input.float(title="Percentage to TP6", defval=1.00, step=0.05, group="=== TAKEPROFIT LEVELS ===")
tp1_r = not use_TPs ? rr_tp * reward : tp1x
tp2_r = not use_TPs ? 2 * (rr_tp * reward) : tp2x
tp3_r = not use_TPs ? 4 * (rr_tp * reward) : tp3x
tp4_r = not use_TPs ? 6 * (rr_tp * reward) : tp4x
tp5_r = not use_TPs ? 8 * (rr_tp * reward) : tp5x
tp6_r = not use_TPs ? 10 * (rr_tp * reward) : tp6x
slx = not use_TPs ? rr_tp : slr
// ENTRY LEVEL
sellEntrySource = switch sellEntrySource_o
"CLOSE" => close
"HIGH" => high
"HL2" => hl2
"Range Mid" => mid
"MID UP" => midUp
=> mid
buyEntrySource = switch sellEntrySource_o
"CLOSE" => close
"LOW" => low
"HL2" => hl2
"Range Mid" => mid
"MID DN" => midDn
=> mid
// +++++++++++++++++++++++++++LEVELS TRACK END+++++++++++++++++++++++++ \\
/////// ******** SIGNALS ********** \\\\\\\\\\\\\\\\\\\\\\\\
[L1_S1entry_touched, L1_S1entry, L1_S1_tp1, L1_S1_tp2, L1_S1_tp3, L1_S1_tp4, L1_S1_tp5, L1_S1_tp6, L1_S1_sl, OL1, OS1, L1_buyTP1_touched, L1_buyTP2_touched, L1_buyTP3_touched, L1_buyTP4_touched, L1_buyTP5_touched, L1_buyTP6_touched, L1_buySL_touched, S1_sellTP1_touched, S1_sellTP2_touched, S1_sellTP3_touched, S1_sellTP4_touched, S1_sellTP5_touched, S1_sellTP6_touched, S1_sellSL_touched] = lm.manageTrade(use_breakSignals, realb, reals, "L_1", "S_1", buyEntrySource, sellEntrySource, useTp1, useTp2, useTp3, useTp4, useTp5, useTp6, tp1_r, tp2_r, tp3_r, tp4_r, tp5_r, tp6_r, slx)
// =================== PLOT ===================================
// @RANGE MID
plot(showRange ? uppish :na, color=color.red, linewidth=1, style=plot.style_linebr, title="Up")
plot(showRange ? downish:na, color=color.green, linewidth=1, style=plot.style_linebr, title="Down")
plot(showRange ? midUp :na, color=color.orange, linewidth=1, style=plot.style_linebr, title="mid Up")
plot(showRange ? midDn :na, color=color.blue, linewidth=1, style=plot.style_linebr, title="mid Down")
plot(not showMid ? na :mid, color=midColor, linewidth=3, title="mid")
//--SIGNAL PLOT ---\\
plotshape(OL1, style=shape.triangleup, color=color.new(color.green, 50), location = location.belowbar, text="L", size=size.normal)
plotshape(OS1, style=shape.triangledown, color=color.new(color.red, 50), location = location.abovebar, text="S", size=size.normal)
bgcolor(not colorSignalBg ? na : OL1 ? color.new(color.green, 70) : OS1 ? color.new(color.red, 70) : na, title="Signals Background")
bgcolor(not colorBg ? na: mid_state == 1 ? color.new(color.green, 95) : mid_state == -1 ? color.new(color.red, 95) : na, title="zones Background")
// ================ PLOT END ==================================== |
ER-Adaptive ATR Limit Channels w/ States [Loxx] | https://www.tradingview.com/script/3HVBY2wE-ER-Adaptive-ATR-Limit-Channels-w-States-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 211 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("ER-Adaptive ATR Limit Channels w/ States [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
bluecolor = #042dd2
lightgreencolor = #96E881
lightredcolor = #DF4F6C
lightbluecolor = #4f6cdf
darkGreenColor = #1B7E02
darkRedColor = #93021F
darkBlueColor = #021f93
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Median", "Source", group = "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
inpAtrPeriod = input.int(14, "ATR Period", group = "Basic Settings")
inpAtrMultiplier = input.float(5, "Multiplier", group = "Basic Settings")
bandlevel = input.int(3, "States", minval = 1, maxval = 3, group = "Basic Settings")
adaptit = input.bool(true, "Make it Adaptive?", group = "Basic Settings")
colorbars = input.bool(false, "Color bars?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
t3hot = input.float(.7, "* T3 Only - T3 Hot", group = "Moving Average Inputs")
t3swt = input.string("T3 New", "* T3 Only - T3 Type", options = ["T3 New", "T3 Original"], group = "Moving Average Inputs")
mper = (inpAtrPeriod > 1) ? inpAtrPeriod : 1
mfast = math.max(mper / 2.0, 1)
mslow = mper * 5
mperDiff = mslow - mfast
noise = 0., aatr = 0.
haopen = (nz(open[1], open) + nz(close[1], close)) / 2
haclose = (open + close + high + low) / 4
hahigh = math.max(high, open, close)
halow = math.min(low, open, close)
hamedian = (hahigh + halow) / 2
hatypical = (hahigh + halow + haclose) / 3
haweighted = (hahigh + halow + haclose + haclose)/4
haaverage = (haopen + hahigh + halow + haclose)/4
srcout(srcin, smthtype)=>
outer = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
outer
src = srcout(srcin, smthtype)
diff = math.abs(src - nz(src[1]))
signal = math.abs(src - nz(src[mper]))
noise := nz(noise[1]) + diff - nz(diff[mper])
avgper = (noise != 0) ? (signal / noise) * mperDiff + mfast : mper
aatr := nz(aatr[1]) + (2.0 / (1.0 + avgper)) * ((high - low) - nz(aatr[1]))
up1 = high
up2 = high
up3 = high
down1 = low
down2 = low
down3 = low
_atr = adaptit ? aatr * inpAtrMultiplier : ta.atr(inpAtrPeriod) * inpAtrMultiplier
if high > nz(up3[1])
up3 := high
else if high < nz(up3[1])
up3 := math.min(high + _atr * 1.0, nz(up3[1]))
else
up3 := nz(up3[1])
if high > nz(up2[1])
up2 := high
else if high < nz(up2[1])
up2 := math.min(high + _atr * 0.5, nz(up2[1]))
else
up2 := nz(up2[1])
if high > nz(up1[1])
up1 := high
else if high < nz(up1[1])
up1 := math.min(high + _atr * 0.1, nz(up1[1]))
else
up1 := nz(up1[1])
if low < nz(down1[1])
down1 := low
else if (low > nz(down1[1]))
down1 := math.max(low - _atr * 0.1, nz(down1[1]))
else
down1 := nz(down1[1])
if low < nz(down2[1])
down2 := low
else if low > nz(down2[1])
down2 := math.max(low - _atr * 0.5, nz(down2[1]))
else
down2 := nz(down2[1])
if low < nz(down3[1])
down3 := low
else if low > nz(down3[1])
down3 := math.max(low - _atr * 1.0, nz(down3[1]))
else
down3 := nz(down3[1])
mid = bandlevel == 1 ? (up1 + down1) / 2 : bandlevel == 2 ? (up2 + down2) / 2 : (up3 + down3) / 2
histoup = 0.
histodn = 0.
histoc = 0
histoc := (mid > mid[1]) ? 1 : (mid < mid[1]) ? 2 : histoc[1]
colorout = histoc == 1 ? greencolor : histoc == 2 ? redcolor : color.gray
plot(mid, "Mid", color = colorout, linewidth = 3)
plot(up1, "Level 1 Up", color = color.new(color.gray, 0), linewidth = 1)
plot(up2, "Level 2 Up",color = color.new(darkGreenColor, 0), linewidth = 1)
plot(up3, "Level 3 Up",color = color.new(greencolor, 0), linewidth = 2)
plot(down1, "Level 1 Down",color = color.new(color.gray, 0), linewidth = 1)
plot(down2, "Level 2 Down",color = color.new(darkRedColor, 0), linewidth = 1)
plot(down3, "Level 3 Down",color = color.new(redcolor, 0), linewidth = 2)
barcolor(colorbars ? colorout : na) |
Fibonacci Step Indicator | https://www.tradingview.com/script/jsVQhdSf-Fibonacci-Step-Indicator/ | Sofien-Kaabar | https://www.tradingview.com/u/Sofien-Kaabar/ | 140 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sofien-Kaabar
//@version=5
indicator("Fibonacci Step Indicator", overlay = true)
lower_fibonacci_step = (low[2] + low[3] + low[5] + low[8] + low[13] + low[21] + low[34] + low[55] + low[89] + low[144] + low[233] + low[377]) / 12
upper_fibonacci_step = (high[2] + high[3] + high[5] + high[8] + high[13] + high[21] + high[34] + high[55] + high[89] + high[144] + high[233] + high[377]) / 12
plot(ta.lowest(lower_fibonacci_step, 13), color = color.orange)
plot(ta.highest(upper_fibonacci_step, 13), color = color.blue)
|
Custom HTF candle overlay, ICT True Day | https://www.tradingview.com/script/yT5CsdEj-Custom-HTF-candle-overlay-ICT-True-Day/ | twingall | https://www.tradingview.com/u/twingall/ | 231 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Set custom higher time frame session from which to overlay higher time frame candles and wicks
// Currently set to ICT's 'True Day' as HTF Custom candle overlay
//added Wick CE midlines
//added option to plot 2x session htf candles in a day
//added option to plot weekly candle overlay
//added border color options
//@twingall
//@version=5
indicator(title='Custom HTF candle overlay, ICT True Day', shorttitle="True Day - Overlay", overlay=true, max_boxes_count = 250, max_lines_count = 500)
_inputSession = input.session('0000-1500', title='custom HTF range', group = "custom range")
showHTFoverlay = input.bool(true, "show HTF candle overlay",group = "custom range")
showOpenPrice = input.bool(false, "show opening price",group = "custom range")
twoSessions = input.bool(false, "show two sessions in day", group = "_____two sessions [override]")
inputSessionA = input.session('0830-0930', title='(session#1)', group = "_____two sessions [override]")
inputSessionB = input.session('1400-1600', title='(session#2)', group = "_____two sessions [override]")
htfWeeklyCandle = input.bool(false, "Weekly candle overlay", group = "_____weekly candle overlay [override]", tooltip="this is week-long session is mon-friday, midnight-midnight; does not include Sunday's price action")
inputSessionC = '0000-0000:234567'
inputSession = htfWeeklyCandle?inputSessionC:_inputSession
days =input.int(250, "days lookback", group="~~~ options ~~~")
lookbackTime = 1000*60*60*24*(days+1)
visible = time >= timenow - lookbackTime
colorBull = input.color(color.new(color.green, 70), "bull body", group="~~~ options ~~~", inline = "3")
colorBear = input.color(color.new(color.red, 70), "bear body", group="~~~ options ~~~", inline = "3")
colBorderBull = input.color(color.new(color.green, 100), "bull border", group="~~~ options ~~~", inline = "4", tooltip = "Default is invisible.\n\nIncrease transparency from 0 to make borders visible")
colBorderBear = input.color(color.new(color.red, 100), "bear border", group="~~~ options ~~~", inline = "4")
borderWidth = input.int(2, "width", options = [1,2,3,4,5,6,7,8,9,10], inline = "4", group="~~~ options ~~~")
wickColor =input.color(color.new(color.purple, 70), "wick", inline = "5", group="~~~ options ~~~")
wickWidth = input.int(5, "wick width", options = [1,2,3,4,5,6,7,8,9,10], inline = "5", group="~~~ options ~~~")
showWickCE =input.bool(false, "Wick midpoint lines", inline = "5", group = "midlines", tooltip="Ignores small wicks, based on their length as a fraction of high-low range; tweak this fraction filter by editing the number in lines 110-111")
wickCEcolor = input.color(color.gray, "",inline = "5", group = "midlines")
showBodyCE =input.bool(false, "Body midpoint lines", inline = "6", group = "midlines")
BodyCEcolor = input.color(color.gray, "",inline = "6", group = "midlines")
wickCEbarsExtend = input.int(0, "Extend line(bars):", inline = "7", group = "midlines" , tooltip = "This can be inconsistent across timeframes; especially when using weekly candle overlay (try 2000 if using ltf charts with weekly overlay)")
colorNone = color.new(color.white, 100)
inSession = twoSessions and not htfWeeklyCandle ?not na(time(timeframe.period,inputSessionA +","+ inputSessionB+":23456", "America/New_York")):not na(time(timeframe.period, str.tostring(inputSession), "America/New_York"))
/// ~~FUNCTIONS~~
open()=>
var float result =na
if inSession and not inSession[1]
result:=open
result
close()=>
var float result =na
if inSession
result:=close
result
high() =>
var float result = na
if inSession and not inSession[1]
result:=high
else if inSession
result:=math.max(result, high)
result
low() =>
var float result = na
if inSession and not inSession[1]
result:=low
else if inSession
result:=math.min(result, low)
result
closeTime()=>
var int closeTime = na
if inSession[1] and not inSession
closeTime := time[1]
int result = closeTime
openTime()=>
var int _openTime = na
if inSession and not inSession[1]
_openTime := time
int result = _openTime
float htfOpen = open()
float htfHigh = high()
float htfLow = low()
int htfHighTime = ta.valuewhen(high==htfHigh and inSession,time,0)
int htfLowTime = ta.valuewhen(low==htfLow and inSession,time,0)
float htfClose =close()
int htfCloseTime = ta.valuewhen(close==htfClose and inSession,time,0)
int htfOpenTime = openTime()
int htfMidTime = htfOpenTime + ((htfCloseTime-htfOpenTime)/2)
int half_x_body = (htfCloseTime-htfOpenTime)/2
// Plots opening price of the custom range
plot(inSession and showOpenPrice and visible ? htfOpen : na, title='open line', color=color.new(color.red, 0), linewidth=1, style=plot.style_linebr)
////////
// ~~Draw overlay candle bodies and wicks~~
//initialize variables
bodyBox = box (na)
wickLine = line (na)
BodyMidLine = line (na)
tailLine = line (na)
wickCEline = line(na)
tailCEline = line(na)
isBull = htfOpen>=htfClose?false:true
bodyHigh = isBull?htfClose:htfOpen
bodyLow = isBull?htfOpen:htfClose
wickCE = bodyHigh+(htfHigh-bodyHigh)/2
tailCE = bodyLow-(bodyLow-htfLow)/2
isWickSignificant = (htfHigh-bodyHigh)>= (htfHigh-htfLow)/6 //change denominator: make it smaller to filter out smaller wicks
isTailSignificant = (bodyLow-htfLow)>= (htfHigh-htfLow)/6 //change denominator: make it smaller to filter out smaller wicks
extTime = wickCEbarsExtend * 1000* timeframe.in_seconds(timeframe.period)
if inSession and showHTFoverlay and visible
if inSession [1]
box.delete(bodyBox[1])
line.delete(wickLine[1])
line.delete(tailLine[1])
line.delete(BodyMidLine[1])
bodyBox := box.new(htfOpenTime, htfOpen, htfCloseTime, htfClose, xloc = xloc.bar_time, border_color = isBull?colBorderBull:colBorderBear, bgcolor = isBull?colorBull:colorBear, border_width = borderWidth)
wickLine:= line.new(htfMidTime, htfHigh, htfMidTime, bodyHigh, xloc=xloc.bar_time, color = wickColor, width = wickWidth)
tailLine:= line.new(htfMidTime, bodyLow, htfMidTime, htfLow, xloc=xloc.bar_time, color = wickColor, width = wickWidth)
BodyMidLine:= line.new(htfOpenTime, isBull?htfClose-((htfClose-htfOpen)/2):htfOpen-((htfOpen-htfClose)/2),
htfCloseTime,isBull?htfClose-((htfClose-htfOpen)/2):htfOpen-((htfOpen-htfClose)/2), xloc=xloc.bar_time, color = showBodyCE?BodyCEcolor: colorNone )
//wick midlines
if inSession and showHTFoverlay and visible and showWickCE
if inSession [1]
line.delete(wickCEline[1])
line.delete(tailCEline[1])
wickCEline := line.new(htfMidTime, wickCE, (htfCloseTime+extTime), wickCE, xloc=xloc.bar_time,color =isWickSignificant? wickCEcolor:colorNone, width = 1, style = line.style_dotted)
tailCEline := line.new(htfMidTime, tailCE, (htfCloseTime+extTime) ,tailCE, xloc=xloc.bar_time,color =isTailSignificant? wickCEcolor:colorNone, width = 1,style = line.style_dotted)
|
Zigzag Array Experimental | https://www.tradingview.com/script/aCehxH4S-Zigzag-Array-Experimental/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 107 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RozaniGhani-RG
//@version=5
indicator('Zigzag Array Experimental', 'ZAE', true)
// 0. Inputs
// 1. Types
// 2. Switches
// 3. Variables and arrays
// 4. Custom Functions
// 5. Execution
// 6. Constructs
//#region ———————————————————— 0. Inputs
T0 = 'Zigzag values\nDefault : 14\nMin : 2\nMax : 50'
T1 = 'Bar values\nDefault : 10\nMin : 0\nMax : 20'
T2 = 'Small font size recommended for mobile app or multiple layout'
T3 = 'Default\nStyle : Solid\nWidth : 4'
length = input.int( 14, 'Length', inline = '0', minval = 2, maxval = 50, tooltip = T0)
bar = input.int( 10, 'Bar', minval = 0, maxval = 20, tooltip = T1)
colorUp = input.color(color.lime, 'Trend', inline = '0')
colorDn = input.color( color.red, '', inline = '0')
showLabel = input.bool( true, 'Label', group = 'Show / hide', inline = '1')
showLine = input.bool( true, 'Line', group = 'Show / hide', inline = '1')
showTable = input.string( 'Label', '| Table', group = 'Show / hide', inline = '1', options = ['Label', 'Line', 'None'])
fontSize = input.string( 'normal', 'Size', group = 'Label', inline = '4', options = ['tiny', 'small', 'normal', 'large', 'huge'], tooltip = T2)
lineType = input.string( 'solid', 'Display', group = 'Line', inline = '5', options = ['dash', 'dot', 'solid', 'arrow right', 'arrow left'])
width = input.int( 4, '', group = 'Line', inline = '5', minval = 1, maxval = 4, tooltip = T3)
//#endregion
//#region ———————————————————— 1. Types
// @type Used for point especially for array
// @field x int value for bar_index
// @field y float value for price
// @field sty label style
// @field col color for text label
// @field str high or low string
type point
int x = na
float y = na
string sty = na
color col = na
string str = na
// @type Used for initial setup
// @field hi high value
// @field lo low value
// @field colorHi color for high value
// @field colorLo color for low value
// @field strHi string for high value
// @field strLo string for low value
type startUp
float hi = na
float lo = na
color colorHi = na
color colorLo = na
string strHi = na
string strLo = na
//#endregion
//#region ———————————————————— 2. Switches
switchLine = switch lineType
'dash' => line.style_dashed
'dot' => line.style_dotted
'solid' => line.style_solid
'arrow right' => line.style_arrow_right
'arrow left' => line.style_arrow_left
//#endregion
//#region ———————————————————— 3. Variables and arrays
float ph = na, ph := ta.highestbars(high, length) == 0 ? high : na
float pl = na, pl := ta.lowestbars( low, length) == 0 ? low : na
var dir = 0, dir := ph and na(pl) ? 1 : pl and na(ph) ? -1 : dir
var zigzag = array.new<point>(0)
oldzigzag = zigzag.copy()
dirchanged = ta.change(dir)
varSetup = startUp.new(ph, pl, colorUp, colorDn, 'H', 'L')
//#endregion
//#region ———————————————————— 4. Custom Functions
// @function variable for point
// @param setup type containing ternary conditional operator
// @returns newPoint to be used later in initialize
method dirVariables(startUp setup = na) =>
var point newPoint = na
x = bar_index
y = dir == 1 ? setup.hi : setup.lo
sty = dir == 1 ? label.style_label_down : label.style_label_up
col = dir == 1 ? setup.colorHi : setup.colorLo
str = dir == 1 ? setup.strHi : setup.strLo
newPoint := point.new(x, y, sty, col, str)
newPoint
// @function initialize zigzag array
// @param setup type containing ternary conditional operator
// @param maxSize maximum array size
// @returns zigzag array after cleanup
method initialize(point[] zigzag = na, startUp setup = na, int maxSize = 10)=>
newPoint = setup.dirVariables()
zigzag.unshift(newPoint)
if zigzag.size() > maxSize
zigzag.pop()
// @function update zigzag array
// @param setup type containing ternary conditional operator
// @param maxSize maximum array size
// @param dir direction value
// @returns zigzag array after cleanup
method update(point[] zigzag = na, startUp setup = na, maxSize = 10, int dir = na)=>
if array.size(zigzag) == 0
zigzag.initialize(setup, maxSize)
else
newPoint = setup.dirVariables()
dirOver = dir == 1 and newPoint.y > zigzag.get(0).y
dirLess = dir == -1 and newPoint.y < zigzag.get(0).y
if dirOver or dirLess
zigzag.set(0, newPoint)
point.new(na, na, na, na, na)
// @function compare zigzag
// @param zigzag original array
// @param oldzigzag copied array
// @returns boolOr Or statement
// @returns boolAnd And statement
method boolPoint(point[] zigzag = na, point[] oldzigzag = na, int offset = 0) =>
boolOr = zigzag.get(offset + 0).x != oldzigzag.get(offset + 0).x or zigzag.get(offset + 0).y != oldzigzag.get(offset + 0).y
boolAnd = zigzag.get(offset + 1).x == oldzigzag.get(offset + 1).x and zigzag.get(offset + 1).y == oldzigzag.get(offset + 1).y
[boolOr, boolAnd]
// @function create label based on zigzag array
// @param zigzag original array
// @param size font size
// @param offset default value zero
// @returns new label
method createLabel(point[] zigzag = na, string size = na, int offset = 0, bool enable = true, color col = chart.fg_color) =>
compare = dir == 1 ? zigzag.get(offset + 0).y > zigzag.get(offset + 2).y ? 'H' : 'L' :
zigzag.get(offset + 0).y < zigzag.get(offset + 2).y ? 'L' : 'H'
draw = label.new(
x = int(zigzag.get(offset + 0).x),
y = zigzag.get(offset + 0).y,
text = compare + zigzag.get(offset + 0).str,
xloc = xloc.bar_index,
color = color.new(color.blue, 100),
style = zigzag.get(offset + 0).sty,
textcolor = enable ? zigzag.get(offset + 0).col : col,
size = size,
tooltip = compare + zigzag.get(offset + 0).str + '\n' + str.tostring(zigzag.get(offset + 0).y))
draw
// @function create point based on zigzag array
// @param zigzag original array
// @param offset default value zero
// @returns new point
method createPoint(point[] zigzag = na, int offset = 0) =>
point.new(
x = int(zigzag.get(offset + 0).x),
y = zigzag.get(offset + 0).y,
sty = zigzag.get(offset + 0).sty,
col = zigzag.get(offset + 0).col,
str = zigzag.get(offset + 0).str)
// @function create line based on zigzag array
// @param zigzag original array
// @param width line thickness
// @param style line style
// @param offset default value zero
// @returns new line
method createLine(point[] zigzag = na, int width = na, string style = na, int offset = 0, bool enable = true, color col = chart.fg_color) =>
line.new(x1 = int(zigzag.get(offset + 1).x),
y1 = zigzag.get(offset + 1).y,
x2 = int(zigzag.get(offset + 0).x),
y2 = zigzag.get(offset + 0).y,
xloc = xloc.bar_index,
color = enable ? zigzag.get(offset + 0).col : col,
style = style,
width = width)
//#endregion
//#region ———————————————————— 5. Execution
if ph or pl
if dirchanged
zigzag.initialize( varSetup, 4)
else
zigzag.update(varSetup, 4, dir)
//#endregion
//#region ———————————————————— 6. Constructs
var dirLine = array.new<line>()
var dirLabel = array.new<label>()
var dirPoint = array.new<point>()
if zigzag.size() >= 3
[boolOr, boolAnd] = zigzag.boolPoint(oldzigzag)
if boolOr
if boolAnd
line.delete(dirLine.shift())
label.delete(dirLabel.shift())
dirPoint.unshift(zigzag.createPoint(0))
if showLabel
dirLabel.unshift(zigzag.createLabel(fontSize, 0, true))
else
dirLabel.unshift(na)
if showLine
dirLine.unshift(zigzag.createLine(width, switchLine, 0, true))
else
dirLine.unshift(na)
var tbl = table.new(position.top_right, 3, bar + 3, border_width = 1)
if barstate.islast
for i = dirLine.size() - 1 to bar + 1
line.delete(array.get(dirLine, i))
for i = dirLabel.size() - 1 to bar + 2
label.delete(array.get(dirLabel, i))
if showTable != 'None'
tbl.cell(0, 0, 'SELECTED', text_color = color.white, text_size = fontSize , bgcolor = color.black)
tbl.cell(0, 1, 'BAR_INDEX', text_color = color.white, text_size = fontSize , bgcolor = color.black)
tbl.cell(1, 1, 'PRICE', text_color = color.white, text_size = fontSize , bgcolor = color.black)
if showTable == 'Label'
tbl.cell(2, 1, 'HIGH LOW', text_color = color.white, text_size = fontSize, bgcolor = color.black)
tbl.cell(1, 0, 'LABEL', text_color = color.white, text_size = fontSize, bgcolor = color.blue)
tbl.merge_cells(1, 0, 2, 0)
for i = 0 to bar
tbl.cell(0, i + 2, str.tostring(label.get_x( dirLabel.get(i))), text_color = color.black, text_size = fontSize, bgcolor = str.endswith(label.get_text(dirLabel.get(i)), 'H') ? colorUp : colorDn)
tbl.cell(1, i + 2, str.tostring(label.get_y( dirLabel.get(i))), text_color = color.black, text_size = fontSize, bgcolor = str.endswith(label.get_text(dirLabel.get(i)), 'H') ? colorUp : colorDn)
tbl.cell(2, i + 2, str.tostring(label.get_text(dirLabel.get(i))), text_color = color.black, text_size = fontSize, bgcolor = str.endswith(label.get_text(dirLabel.get(i)), 'H') ? colorUp : colorDn)
if showTable == 'Line'
tbl.cell(1, 0, 'LINE', text_color = color.white, text_size = fontSize, bgcolor = color.blue)
for i = 0 to bar
tbl.cell(0, i + 2, str.tostring(line.get_x2( dirLine.get(i))), text_color = color.black, text_size = fontSize, bgcolor = color.white)
tbl.cell(1, i + 2, str.tostring(line.get_y2( dirLine.get(i))), text_color = color.black, text_size = fontSize, bgcolor = color.white)
//#endregion |
Global Money Supply USD-Adjusted | https://www.tradingview.com/script/nQ5EvcBI-Global-Money-Supply-USD-Adjusted/ | SirChub | https://www.tradingview.com/u/SirChub/ | 35 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SirChub
//@version=5
indicator("Global Money Supply USD-Adjusted", overlay=true, scale=scale.right)
i_res = input.timeframe('D', "Resolution", options=['D', 'W', 'M'])
unit_input = input.string('Trillions', options=['Millions', 'Billions', 'Trillions'])
units = unit_input == 'Billions' ? 1e3 : unit_input == 'Millions' ? 1e0 : unit_input == 'Trillions' ? 1e6 : na
US_MS = (request.security('FRED:WM2NS', i_res, close)*100)/request.security('TVC:DXY',i_res,close)
CN_MS = (request.security('ECONOMICS:CNM2',i_res, close))/request.security('FX:USDCNH',i_res,close)
JP_MS = (request.security('ECONOMICS:JPM3',i_res, close))/request.security('FX:USDJPY',i_res,close)
EU_MS = (request.security('ECONOMICS:EUM3',i_res, close))*request.security('FX:EURUSD',i_res,close)
UK_MS = (request.security('ECONOMICS:GBM3',i_res, close))*request.security('FX:GBPUSD',i_res,close)
KR_MS = (request.security('ECONOMICS:KRM3',i_res, close))/request.security('FX_IDC:USDKRW',i_res,close)
IN_MS = (request.security('ECONOMICS:INM3',i_res, close))/request.security('FX_IDC:USDINR',i_res,close)
CA_MS = (request.security('ECONOMICS:CAM3',i_res, close))*request.security('FX_IDC:CADUSD',i_res,close)
AU_MS = (request.security('ECONOMICS:AUM3',i_res, close))*request.security('FX:AUDUSD',i_res,close)
TW_MS = (request.security('ECONOMICS:TWM2',i_res, close))/request.security('FX_IDC:USDTWD',i_res,close)
BR_MS = (request.security('ECONOMICS:BRM3',i_res, close))/request.security('FX_IDC:USDBRL',i_res,close)
CH_MS = (request.security('ECONOMICS:CHM3',i_res, close))*request.security('FX_IDC:CHFUSD',i_res,close)
RU_MS = (request.security('ECONOMICS:RUM2',i_res, close))/request.security('FX_IDC:USDRUB',i_res,close)
MX_MS = (request.security('ECONOMICS:MXM3',i_res, close))/request.security('FX:USDMXN',i_res,close)
TH_MS = (request.security('ECONOMICS:THM3',i_res, close))/request.security('FX_IDC:USDTHB',i_res,close)
ID_MS = (request.security('ECONOMICS:IDM2',i_res, close))/request.security('FX_IDC:USDIDR',i_res,close)
SG_MS = (request.security('ECONOMICS:SGM3',i_res, close))/request.security('FX_IDC:USDSGD',i_res,close)
Global_MS = (US_MS+CN_MS+JP_MS+EU_MS+UK_MS+KR_MS+IN_MS+CA_MS+AU_MS+TW_MS+BR_MS+CH_MS+RU_MS+MX_MS+TH_MS+ID_MS+SG_MS)/1e12
var Global_MS_offset = 0 // 2-week offset for use with daily charts
if timeframe.isdaily
Global_MS_offset := 0
if timeframe.isweekly
Global_MS_offset := 0
if timeframe.ismonthly
Global_MS_offset := 0
plot(Global_MS, title='Global Money Supply', color=color.new(color.black, 10), style=plot.style_line, offset=Global_MS_offset)
|
[E5 Trading] Moving Averages | https://www.tradingview.com/script/spZlnxjY-E5-Trading-Moving-Averages/ | E5Trading | https://www.tradingview.com/u/E5Trading/ | 38 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator(title = '[E5 Trading] Moving Averages', shorttitle ='[E5 Trading] Moving Averages ' , max_bars_back = 4000, overlay=true, max_lines_count=400, max_labels_count=400, explicit_plot_zorder = true)
//***********************************************************************************
//Import Library
//***********************************************************************************
import E5Trading/E5TradingLibrary/1 as EngineUtility
//***********************************************************************************
//Constants
//***********************************************************************************
//{
var RED = #F3300C
var ORANGE = #FB6D04
var YELLOW = #F7D608
var GREEN = #6BBE49
var BLUE = #407FC1
var PINK = #F48FB1
//Largest to Smallest Space
//EM_SPACE and SIX_SPACE for Gross Movements
var EM_SPACE = " "
var SIX_SPACE = " "
//THIN_SPACE and HAIR_SPACE for Fine Movements
var THIN_SPACE = " "
var HAIR_SPACE = " "
//}
//***********************************************************************************
// Source Data
//***********************************************************************************
//{
src_close = close
//}
//***********************************************************************************
//Tooltips
//***********************************************************************************
//{
var readMeToolTip = "Plot up to 12 moving averages and customize colors directly on the inputs tab.\n\n" +
"Select from any of one of eight [8] moving averages types from the drop-down menu " +
"including EMA, HMA, LINREG, SWMA, SINE, SMA, VWMA, and WMA. Default [SMA] for " +
"plots 1 through 6 [Group A], and default [EMA] for plots 7 through 12 [Group B].\n\n" +
"Customize the moving averages timeframe for Group A and Group B using the respective " +
"timeframe selector drop-down boxes."
//}
//***********************************************************************************
//MENU Top
//***********************************************************************************
//{
var trendSettingGroup = 'Settings'
boolReadme = input.bool(true, title ="Read Me", inline = "10", group = trendSettingGroup, tooltip = readMeToolTip)
//}
//***********************************************************************************
//MENU Moving Average
//***********************************************************************************
//{
var maGroupA = 'Moving Averages: Group A'
var maGroupB = 'Moving Averages: Group B'
//Set timeframe input for each group
timeframeA = input.timeframe('', "Timeframe Group A" + ' ' + ' ', group = maGroupA)
timeframeB = input.timeframe('', "Timeframe Group B", group = maGroupB)
//Turn On/Off Moving Average
//Group A
ma0Switch = input.bool(defval = true, title = "", inline = "10", group = maGroupA)
ma1Switch = input.bool(defval = true, title = "", inline = "20", group = maGroupA)
ma2Switch = input.bool(defval = true, title = "", inline = "30", group = maGroupA)
ma3Switch = input.bool(defval = true, title = "", inline = "40", group = maGroupA)
ma4Switch = input.bool(defval = true, title = "", inline = "50", group = maGroupA)
ma5Switch = input.bool(defval = true, title = "", inline = "60", group = maGroupA)
//Group B
ma6Switch = input.bool(defval = false, title = "", inline = "70" , group = maGroupB)
ma7Switch = input.bool(defval = false, title = "", inline = "80" , group = maGroupB)
ma8Switch = input.bool(defval = false, title = "", inline = "90" , group = maGroupB)
ma9Switch = input.bool(defval = false, title = "", inline = "100", group = maGroupB)
ma10Switch = input.bool(defval = false, title = "", inline = "110", group = maGroupB)
ma11Switch = input.bool(defval = false, title = "", inline = "120", group = maGroupB)
//Get Moving Average Type
//Group A
ma0Type = input.string('SMA', title='', options=['EMA', 'HMA', 'LINREG', 'SWMA', 'SINE', 'SMA', 'VWMA', 'WMA'], inline = "10", group = maGroupA)
ma1Type = input.string('SMA', title='', options=['EMA', 'HMA', 'LINREG', 'SWMA', 'SINE', 'SMA', 'VWMA', 'WMA'], inline = "20", group = maGroupA)
ma2Type = input.string('SMA', title='', options=['EMA', 'HMA', 'LINREG', 'SWMA', 'SINE', 'SMA', 'VWMA', 'WMA'], inline = "30", group = maGroupA)
ma3Type = input.string('SMA', title='', options=['EMA', 'HMA', 'LINREG', 'SWMA', 'SINE', 'SMA', 'VWMA', 'WMA'], inline = "40", group = maGroupA)
ma4Type = input.string('SMA', title='', options=['EMA', 'HMA', 'LINREG', 'SWMA', 'SINE', 'SMA', 'VWMA', 'WMA'], inline = "50", group = maGroupA)
ma5Type = input.string('SMA', title='', options=['EMA', 'HMA', 'LINREG', 'SWMA', 'SINE', 'SMA', 'VWMA', 'WMA'], inline = "60", group = maGroupA)
//Group B
ma6Type = input.string('EMA', title='', options=['EMA', 'HMA', 'LINREG', 'SWMA', 'SINE', 'SMA', 'VWMA', 'WMA'], inline = "70", group = maGroupB)
ma7Type = input.string('EMA', title='', options=['EMA', 'HMA', 'LINREG', 'SWMA', 'SINE', 'SMA', 'VWMA', 'WMA'], inline = "80", group = maGroupB)
ma8Type = input.string('EMA', title='', options=['EMA', 'HMA', 'LINREG', 'SWMA', 'SINE', 'SMA', 'VWMA', 'WMA'], inline = "90", group = maGroupB)
ma9Type = input.string('EMA', title='', options=['EMA', 'HMA', 'LINREG', 'SWMA', 'SINE', 'SMA', 'VWMA', 'WMA'], inline = "100", group = maGroupB)
ma10Type = input.string('EMA', title='', options=['EMA', 'HMA', 'LINREG', 'SWMA', 'SINE', 'SMA', 'VWMA', 'WMA'], inline = "110", group = maGroupB)
ma11Type = input.string('EMA', title='', options=['EMA', 'HMA', 'LINREG', 'SWMA', 'SINE', 'SMA', 'VWMA', 'WMA'], inline = "120", group = maGroupB)
//Get Moving Average Length
//Group A
ma0Length = input.int(title = "", defval = 5, inline = "10", group = maGroupA)
ma1Length = input.int(title = "", defval = 10, inline = "20", group = maGroupA)
ma2Length = input.int(title = "", defval = 20, inline = "30", group = maGroupA)
ma3Length = input.int(title = "", defval = 50, inline = "40", group = maGroupA)
ma4Length = input.int(title = "", defval = 100, inline = "50", group = maGroupA)
ma5Length = input.int(title = "", defval = 200, inline = "60", group = maGroupA)
//Group B
ma6Length = input.int(title = "", defval = 8, inline = "70", group = maGroupB)
ma7Length = input.int(title = "", defval = 13, inline = "80", group = maGroupB)
ma8Length = input.int(title = "", defval = 21, inline = "90", group = maGroupB)
ma9Length = input.int(title = "", defval = 34, inline = "100", group = maGroupB)
ma10Length = input.int(title = "", defval = 55, inline = "110", group = maGroupB)
ma11Length = input.int(title = "", defval = 89, inline = "120", group = maGroupB)
//Get Moving Average Color
//Group A
ma0Color = input.color(title = "", defval = RED, inline = "10", group = maGroupA)
ma1Color = input.color(title = "", defval = ORANGE, inline = "20", group = maGroupA)
ma2Color = input.color(title = "", defval = YELLOW, inline = "30", group = maGroupA)
ma3Color = input.color(title = "", defval = GREEN, inline = "40", group = maGroupA)
ma4Color = input.color(title = "", defval = BLUE, inline = "50", group = maGroupA)
ma5Color = input.color(title = "", defval = PINK, inline = "60", group = maGroupA)
//Group B
ma6Color = input.color(title = "", defval = RED, inline = "70", group = maGroupB)
ma7Color = input.color(title = "", defval = ORANGE, inline = "80", group = maGroupB)
ma8Color = input.color(title = "", defval = YELLOW, inline = "90", group = maGroupB)
ma9Color = input.color(title = "", defval = GREEN, inline = "100", group = maGroupB)
ma10Color = input.color(title = "", defval = BLUE, inline = "110", group = maGroupB)
ma11Color = input.color(title = "", defval = PINK, inline = "120", group = maGroupB)
//}
//***********************************************************************************
//Moving Average
//***********************************************************************************
//{
//Get the moving average data
//Group A
ma0 = request.security(syminfo.tickerid, timeframeA,EngineUtility.getMA(src_close, ma0Length, ma0Type),barmerge.gaps_on, barmerge.lookahead_on)
ma1 = request.security(syminfo.tickerid, timeframeA,EngineUtility.getMA(src_close, ma1Length, ma1Type),barmerge.gaps_on, barmerge.lookahead_on)
ma2 = request.security(syminfo.tickerid, timeframeA,EngineUtility.getMA(src_close, ma2Length, ma2Type),barmerge.gaps_on, barmerge.lookahead_on)
ma3 = request.security(syminfo.tickerid, timeframeA,EngineUtility.getMA(src_close, ma3Length, ma3Type),barmerge.gaps_on, barmerge.lookahead_on)
ma4 = request.security(syminfo.tickerid, timeframeA,EngineUtility.getMA(src_close, ma4Length, ma4Type),barmerge.gaps_on, barmerge.lookahead_on)
ma5 = request.security(syminfo.tickerid, timeframeA,EngineUtility.getMA(src_close, ma5Length, ma5Type),barmerge.gaps_on, barmerge.lookahead_on)
//Group B
ma6 = request.security(syminfo.tickerid, timeframeB,EngineUtility.getMA(src_close, ma6Length, ma6Type),barmerge.gaps_on, barmerge.lookahead_on)
ma7 = request.security(syminfo.tickerid, timeframeB,EngineUtility.getMA(src_close, ma7Length, ma7Type),barmerge.gaps_on, barmerge.lookahead_on)
ma8 = request.security(syminfo.tickerid, timeframeB,EngineUtility.getMA(src_close, ma8Length, ma8Type),barmerge.gaps_on, barmerge.lookahead_on)
ma9 = request.security(syminfo.tickerid, timeframeB,EngineUtility.getMA(src_close, ma9Length, ma9Type),barmerge.gaps_on, barmerge.lookahead_on)
ma10 = request.security(syminfo.tickerid, timeframeB,EngineUtility.getMA(src_close, ma10Length, ma10Type),barmerge.gaps_on, barmerge.lookahead_on)
ma11 = request.security(syminfo.tickerid, timeframeB,EngineUtility.getMA(src_close, ma11Length, ma11Type),barmerge.gaps_on, barmerge.lookahead_on)
//Plot Moving Average
plot(ma0, title = "Moving Average 0", color = ma0Switch ? ma0Color : na, editable = false)
plot(ma1, title = "Moving Average 1", color = ma1Switch ? ma1Color : na, editable = false)
plot(ma2, title = "Moving Average 2", color = ma2Switch ? ma2Color : na, editable = false)
plot(ma3, title = "Moving Average 3", color = ma3Switch ? ma3Color : na, editable = false)
plot(ma4, title = "Moving Average 4", color = ma4Switch ? ma4Color : na, editable = false)
plot(ma5, title = "Moving Average 5", color = ma5Switch ? ma5Color : na, editable = false)
plot(ma6, title = "Moving Average 6", color = ma6Switch ? ma6Color : na, editable = false)
plot(ma7, title = "Moving Average 7", color = ma7Switch ? ma7Color : na, editable = false)
plot(ma8, title = "Moving Average 8", color = ma8Switch ? ma8Color : na, editable = false)
plot(ma9, title = "Moving Average 9", color = ma9Switch ? ma9Color : na, editable = false)
plot(ma10, title = "Moving Average 10", color = ma10Switch ? ma10Color : na, editable = false)
plot(ma11, title = "Moving Average 11", color = ma11Switch ? ma11Color : na, editable = false)
//Add Labels to end of Moving Average
var MA0Label = label.new(x = bar_index,
y = ma0,
style = label.style_label_left,
color = ma0Switch ? chart.bg_color : na,
textcolor = ma0Switch ? ma0Color : na,
text = ma0Type + " " + str.tostring(ma0Length),
text_font_family = font.family_monospace
)
label.set_xy(MA0Label, x = bar_index, y = ma0)
var MA1Label = label.new(x = bar_index,
y = ma1,
style = label.style_label_left,
color = ma1Switch ? chart.bg_color : na,
textcolor = ma1Switch ? ma1Color : na,
text = ma1Type + " " + str.tostring(ma1Length),
text_font_family = font.family_monospace
)
label.set_xy(MA1Label, x = bar_index, y = ma1)
var MA2Label = label.new(x = bar_index,
y = ma2,
style = label.style_label_left,
color = ma2Switch ? chart.bg_color : na,
textcolor = ma2Switch ? ma2Color : na,
text = ma2Type + " " + str.tostring(ma2Length),
text_font_family = font.family_monospace
)
label.set_xy(MA2Label, x = bar_index, y = ma2)
var MA3Label = label.new(x = bar_index,
y = ma3,
style = label.style_label_left,
color = ma3Switch ? chart.bg_color : na,
textcolor = ma3Switch ? ma3Color : na,
text = ma3Type + " " + str.tostring(ma3Length),
text_font_family = font.family_monospace
)
label.set_xy(MA3Label, x = bar_index, y = ma3)
var MA4Label = label.new(x = bar_index,
y = ma4,
style = label.style_label_left,
color = ma4Switch ? chart.bg_color : na,
textcolor = ma4Switch ? ma4Color : na,
text = ma4Type + " " + str.tostring(ma4Length),
text_font_family = font.family_monospace
)
label.set_xy(MA4Label, x = bar_index, y = ma4)
var MA5Label = label.new(x = bar_index,
y = ma5,
style = label.style_label_left,
color = ma5Switch ? chart.bg_color : na,
textcolor = ma5Switch ? ma5Color : na,
text = ma5Type + " " + str.tostring(ma5Length),
text_font_family = font.family_monospace
)
label.set_xy(MA5Label, x = bar_index, y = ma5)
var MA6Label = label.new(x = bar_index,
y = ma6,
style = label.style_label_left,
color = ma6Switch ? chart.bg_color : na,
textcolor = ma6Switch ? ma6Color : na,
text = ma6Type + " " + str.tostring(ma6Length),
text_font_family = font.family_monospace
)
label.set_xy(MA6Label, x = bar_index, y = ma6)
var MA7Label = label.new(x = bar_index,
y = ma7,
style = label.style_label_left,
color = ma7Switch ? chart.bg_color : na,
textcolor = ma7Switch ? ma7Color : na,
text = ma7Type + " " + str.tostring(ma7Length),
text_font_family = font.family_monospace
)
label.set_xy(MA7Label, x = bar_index, y = ma7)
var MA8Label = label.new(x = bar_index,
y = ma8,
style = label.style_label_left,
color = ma8Switch ? chart.bg_color : na,
textcolor = ma8Switch ? ma8Color : na,
text = ma8Type + " " + str.tostring(ma8Length),
text_font_family = font.family_monospace
)
label.set_xy(MA8Label, x = bar_index, y = ma8)
var MA9Label = label.new(x = bar_index,
y = ma9,
style = label.style_label_left,
color = ma9Switch ? chart.bg_color : na,
textcolor = ma9Switch ? ma9Color : na,
text = ma9Type + " " + str.tostring(ma9Length),
text_font_family = font.family_monospace
)
label.set_xy(MA9Label, x = bar_index, y = ma9)
var MA10Label = label.new(x = bar_index,
y = ma10,
style = label.style_label_left,
color = ma10Switch ? chart.bg_color : na,
textcolor = ma10Switch ? ma10Color : na,
text = ma10Type + " " + str.tostring(ma10Length),
text_font_family = font.family_monospace
)
label.set_xy(MA10Label, x = bar_index, y = ma10)
var MA11Label = label.new(x = bar_index,
y = ma11,
style = label.style_label_left,
color = ma11Switch ? chart.bg_color: na,
textcolor = ma11Switch ? ma11Color : na,
text = ma11Type + " " + str.tostring(ma11Length),
text_font_family = font.family_monospace
)
label.set_xy(MA11Label, x = bar_index, y = ma11)
|
Fair value bands / quantifytools | https://www.tradingview.com/script/eos9U1qM-Fair-value-bands-quantifytools/ | quantifytools | https://www.tradingview.com/u/quantifytools/ | 3,117 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © quantifytools
//@version=5
indicator("Fair value bands", overlay=true, max_labels_count=500, max_lines_count=500)
// Inputs
//Settings
groupFair1 = "Fair value basis & bands"
i_btCheck = input.bool(false, "Highlight metric calculations", group=groupFair1, tooltip="Enables lot based coloring and time/volume distribution counters, found in Data Window tab.")
i_boost = input.float(1, "Threshold band width", group=groupFair1, step=0.10, minval = 0)
i_bandBoost = input.float(1, "Deviation band width", group=groupFair1, step=0.10, minval = 0)
i_anchorTf = input.timeframe("1D", "VWAP anchor", group=groupFair1, tooltip="Timeframe to which VWAP is anchored to. Choose VWAP from fair value basis menu to activate.")
i_sourceString = input.string("OHLC4", "", options=["OHLC4", "Open", "High", "Low", "Close", "HL2", "HLC3", "HLCC4"], inline="source", group=groupFair1)
i_smoothingType = input.string("SMA", "", options=["SMA", "EMA", "HMA", "RMA", "WMA", "VWMA", "Median", "VWAP"], inline="source", group=groupFair1)
i_length = input.int(20, "", inline="source", group=groupFair1, minval=1)
i_trendMode = input.string("Cross", "", options=["Cross", "Direction"], inline="sourcecross", group=groupFair1)
i_thresholdUpString = input.string("Low", "▲", options=["OHLC4", "Open", "High", "Low", "Close", "HL2", "HLC3", "HLCC4"], inline="sourcecross", group=groupFair1)
i_thresholdDownString = input.string("High", "▼", options=["OHLC4", "Open", "High", "Low", "Close", "HL2", "HLC3", "HLCC4"], inline="sourcecross", group=groupFair1)
//Visual elements
groupVisual = "Visuals"
i_upColorLine = input.color(color.new(color.white, 50), "Fair value basis ▲ / ▼", group=groupVisual, inline="line")
i_downColorLine = input.color(color.new(color.red, 50), "", group=groupVisual, inline="line")
i_upColorFill = input.color(color.new(color.white, 97), "Threshold band ▲ / ▼", group=groupVisual, inline="fill")
i_downColorFill = input.color(color.new(color.red, 97), "", group=groupVisual, inline="fill")
extremeDeviationUp = input.color(color.new(color.red, 10), "Deviation hue ▲ / ▼", group=groupVisual, inline="deviation")
extremeDeviationDown = input.color(color.new(#3c699e, 10), "", group=groupVisual, inline="deviation")
extremeUpColor = input.color(color.new(color.red, 90), "Deviation bands extreme ▲ / ▼", group=groupVisual, inline="band")
extremeDownColor = input.color(color.new(#205497, 90), "", group=groupVisual, inline="band")
deviationBandColor = input.color(color.new(color.white, 95), "Deviation bands", group=groupVisual, inline="dev")
groupTable = "Table"
tablePos = input.string("Top right", "Table position", options=["Top right", "Bottom right", "Bottom left", "Top left"], group=groupTable)
tableSize = input.int(3, "Table size", maxval=5, minval=1, group=groupTable)
// Fair value basis
//Converting settings table source string to price source
stringSrc(source) =>
src = source == "Open" ? open : source == "High" ? high :
source == "Low" ? low : source == "Close" ? close : source == "HL2" ? hl2 :
source == "HLC3" ? hlc3 : source == "HLC44" ? hlcc4 : ohlc4
i_source = stringSrc(i_sourceString)
i_thresholdUpSrc = stringSrc(i_thresholdUpString)
i_thresholdDownSrc = stringSrc(i_thresholdDownString)
//VWAP anchor change
anchor = timeframe.change(i_anchorTf)
//User defined source and smoothing
smoothedValue(source, length) =>
i_smoothingType == "SMA" ? ta.sma(source, length) : i_smoothingType == "EMA" ? ta.ema(source, length) :
i_smoothingType == "HMA" ? ta.hma(source, length) : i_smoothingType == "RMA" ? ta.rma(source, length) :
i_smoothingType == "VWMA" ? ta.vwma(source, length) : i_smoothingType == "Median" ? ta.median(source, length) :
i_smoothingType == "VWAP" ? ta.vwap(source, anchor) : ta.wma(source, length)
//Fair value basis
fairPriceSmooth = smoothedValue(i_source, i_length)
// Threshold band
//Percentage distance between high/low and fair value basis
lowSpread = low / fairPriceSmooth
highSpread = high / fairPriceSmooth
//Calculate low/high deviations from fair value basis
deviationDown = low < fairPriceSmooth and high > fairPriceSmooth ? lowSpread : na
deviationUp = low < fairPriceSmooth and high > fairPriceSmooth ? highSpread : na
//Arrays for deviation values
var deviationUpList = array.new_float(0, 0)
var deviationDownList = array.new_float(0, 0)
//Array size
deviationUpSize = array.size(deviationUpList)
deviationDownSize = array.size(deviationDownList)
//Keeping array sizes fixed
sizeLimitDev = 1000
if deviationUpSize > sizeLimitDev
array.remove(deviationUpList, 0)
if deviationDownSize > sizeLimitDev
array.remove(deviationDownList, 0)
//Populating arrays
array.push(deviationUpList, deviationUp)
array.push(deviationDownList, deviationDown)
//Median deviations
medianUpDeviation = array.median(deviationUpList)
medianDownDeviation = array.median(deviationDownList)
//Defining threshold band based on median deviations
upperBand = fairPriceSmooth * medianUpDeviation
lowerBand = fairPriceSmooth * medianDownDeviation
//Calculating band spread from fair value basis
bandUpSpread = upperBand - fairPriceSmooth
bandDownSpread = fairPriceSmooth - lowerBand
//Threshold band
upperBandBoosted = fairPriceSmooth + (bandUpSpread * i_boost)
lowerBandBoosted = fairPriceSmooth - (bandDownSpread * i_boost)
// Fair value deviation bands
//Switch for trend logic
var int dirSwitch = 0
//Trend rules up/down
trendRuleUp = i_trendMode == "Cross" ? i_thresholdUpSrc > upperBandBoosted : fairPriceSmooth > fairPriceSmooth[1]
trendRuleDown = i_trendMode == "Cross" ? i_thresholdDownSrc < lowerBandBoosted : fairPriceSmooth < fairPriceSmooth[1]
//Trend up/down switch as per user defined rules
if trendRuleDown
dirSwitch := -1
else
if trendRuleUp
dirSwitch := 1
//Percentage spread between fair value basis and OHLC4
ohlcSpread = ohlc4 / fairPriceSmooth
//Arrays for spread pivots
var pivotUps = array.new_float(0, 0)
var pivotDowns = array.new_float(0, 0)
//Array size
pivotUpsSize = array.size(pivotUps)
pivotDownsSize = array.size(pivotDowns)
//Keeping array sizes fixed
sizeLimitBand = 2000
if array.size(pivotUps) > sizeLimitBand
array.remove(pivotUps, 0)
if array.size(pivotDowns) > sizeLimitBand
array.remove(pivotDowns, 0)
//Spread pivots
pivotUp = ta.pivothigh(ohlcSpread, 5, 5)
pivotDown = ta.pivotlow(ohlcSpread, 5, 5)
//Populating arrays. To exclude insignficant pivots, arrays are populated only when price is sufficently far away from the mean.
if low > upperBand
array.push(pivotUps, pivotUp)
else
if high < lowerBand
array.push(pivotDowns, pivotDown)
//Calculating median pivots from arrays
medianPivotUp = array.median(pivotUps)
medianPivotDown = array.median(pivotDowns)
//Pivot bands 1x median
pivotBandUpBase = fairPriceSmooth * (medianPivotUp)
pivotBandDownBase = fairPriceSmooth * (medianPivotDown)
//Spread between pivot band and fair value basis
pBandUpSpread = (pivotBandUpBase - fairPriceSmooth) * i_bandBoost
pBandDownSpread = (fairPriceSmooth - pivotBandDownBase) * i_bandBoost
//Pivot bands 1x median
pivotBandUp = fairPriceSmooth + pBandUpSpread
pivotBandDown = fairPriceSmooth - pBandDownSpread
//Pivot bands 2x median
pivotBandUp2 = pivotBandUp + pBandUpSpread
pivotBandDown2 = pivotBandDown - pBandDownSpread
//Pivot bands 3x median
pivotBandUp3 = pivotBandUp2 + pBandUpSpread
pivotBandDown3 = pivotBandDown2 - pBandDownSpread
// Metrics
//Volume relative to volume moving average (SMA 20)
volSma = ta.sma(volume, 20)
volMultiplier = na(volSma) ? 0 : volume / volSma
//Defining fair value deviation lots
abovePos2 = (i_source > pivotBandUp2)
betweenPos1AndPos2 = (i_source > pivotBandUp) and (i_source <= pivotBandUp2)
betweenMidAndPos1 = (i_source > fairPriceSmooth) and (i_source <= pivotBandUp)
betweenMidAndNeg1 = (i_source < fairPriceSmooth) and (i_source >= pivotBandDown)
betweenNeg1AndNeg2 = (i_source < pivotBandDown) and (i_source >= pivotBandDown2)
belowNeg2 = (i_source < pivotBandDown2)
//Counters for fair value deviation lots
var int abovePos2Count = 0
var float abovePos2Vol = 0
var int betweenPos1AndPos2Count = 0
var float betweenPos1AndPos2Vol = 0
var int betweenMidAndPos1Count = 0
var float betweenMidAndPos1Vol = 0
var int betweenMidAndNeg1Count = 0
var float betweenMidAndNeg1Vol = 0
var int betweenNeg1AndNeg2Count = 0
var float betweenNeg1AndNeg2Vol = 0
var int belowNeg2Count = 0
var float belowNeg2Vol = 0
//Populating counters
if abovePos2
abovePos2Count += 1
abovePos2Vol += volMultiplier
if betweenPos1AndPos2
betweenPos1AndPos2Count += 1
betweenPos1AndPos2Vol += volMultiplier
if betweenMidAndPos1
betweenMidAndPos1Count += 1
betweenMidAndPos1Vol += volMultiplier
if betweenMidAndNeg1
betweenMidAndNeg1Count += 1
betweenMidAndNeg1Vol += volMultiplier
if betweenNeg1AndNeg2
betweenNeg1AndNeg2Count += 1
betweenNeg1AndNeg2Vol += volMultiplier
if belowNeg2
belowNeg2Count += 1
belowNeg2Vol += volMultiplier
//All counts combined
allCounts = belowNeg2Count + betweenPos1AndPos2Count + betweenMidAndPos1Count + betweenMidAndNeg1Count + betweenNeg1AndNeg2Count + abovePos2Count
//Time and volume distribution percentages
above2PosPerc = math.round(abovePos2Count / allCounts, 3) * 100
above2PosPercVol = math.round(abovePos2Vol / abovePos2Count, 2)
above1PosPerc = math.round(betweenPos1AndPos2Count / allCounts, 2) * 100
above1PosPercVol = math.round(betweenPos1AndPos2Vol / betweenPos1AndPos2Count, 2)
aboveMidPosPerc = math.round(betweenMidAndPos1Count / allCounts, 2) * 100
aboveMidPosPercVol = math.round(betweenMidAndPos1Vol / betweenMidAndPos1Count, 2)
belowMidNegPerc = math.round(betweenMidAndNeg1Count / allCounts, 2) * 100
belowMidNegPercVol = math.round(betweenMidAndNeg1Vol / betweenMidAndNeg1Count, 2)
below1NegPerc = math.round(betweenNeg1AndNeg2Count / allCounts, 2) * 100
below1NegPercVol = math.round(betweenNeg1AndNeg2Vol / betweenNeg1AndNeg2Count, 2)
below2NegPerc = math.round(belowNeg2Count / allCounts, 3) * 100
below2NegPercVol = math.round(belowNeg2Vol / belowNeg2Count, 2)
// Table
//Dividers
n = "\n"
l = "⎯⎯"
vl = "|"
//Length text. If using VWAP, plot VWAP anchor timeframe in hours.
lengthText = i_smoothingType == "VWAP" ? str.tostring(timeframe.in_seconds(i_anchorTf) / 3600) + "H" : str.tostring(i_length)
//Settings texts
settingsText = "Settings" + n + "⎯⎯⎯⎯⎯⎯⎯⎯⎯" + n + i_sourceString + vl + i_smoothingType + vl + lengthText + n +
(i_trendMode == "Cross" ? "Cross" + vl + "▲ " + i_thresholdUpString + vl + "▼ " + i_thresholdDownString : "Direction") + n +
"Mid: " + str.tostring(i_boost) + vl + "Out: " + str.tostring(i_bandBoost)
//Table position and size
tablePosition = tablePos == "Top right" ? position.top_right : tablePos == "Bottom right" ? position.bottom_right : tablePos == "Bottom left" ? position.bottom_left : position.top_left
tableTextSize = tableSize == 1 ? size.tiny : tableSize == 2 ? size.small : tableSize == 3 ? size.normal : tableSize == 4 ? size.huge : size.large
//Initializing table
var metricTable = table.new(position = tablePosition, columns = 50, rows = 50, bgcolor = color.new(color.black, 80), border_width = 3, border_color=color.rgb(23, 23, 23))
//Populating table
table.cell(table_id = metricTable, column = 1, row = 0, text = "Position" + n + "⎯⎯⎯⎯" + n + "Time" + n + "⎯⎯⎯⎯" + n + "Volume", text_color=color.white, text_halign = text.align_left, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 2, row = 0, text = "+3" + n + l + n + str.tostring(above2PosPerc) + "%" + n + l + n + str.tostring(above2PosPercVol) + "x" , text_color=color.white, text_halign = text.align_center, bgcolor=color.new(color.red, 70), text_size=tableTextSize)
table.cell(table_id = metricTable, column = 3, row = 0, text = "+2" + n + l + n + str.tostring(above1PosPerc) + "%" + n + l + n + str.tostring(above1PosPercVol) + "x", text_color=color.white, text_halign = text.align_center, bgcolor=color.new(color.red, 90), text_size=tableTextSize)
table.cell(table_id = metricTable, column = 4, row = 0, text = "+1" + n + l + n + str.tostring(aboveMidPosPerc) + "%" + n + l + n + str.tostring(aboveMidPosPercVol) + "x", text_color=color.white, text_halign = text.align_center, bgcolor=color.new(color.gray, 80), text_size=tableTextSize)
table.cell(table_id = metricTable, column = 6, row = 0, text = "-1 " + n + l + n + str.tostring(belowMidNegPerc) + "%" + n + l + n + str.tostring(belowMidNegPercVol) + "x", text_color=color.white, text_halign = text.align_center, bgcolor=color.new(color.gray, 80), text_size=tableTextSize)
table.cell(table_id = metricTable, column = 7, row = 0, text = "-2" + n + l + n + str.tostring(below1NegPerc) + "%" + n + l + n + str.tostring(below1NegPercVol) + "x", text_color=color.white, text_halign = text.align_center, bgcolor=color.new(color.blue, 90), text_size=tableTextSize)
table.cell(table_id = metricTable, column = 8, row = 0, text = "-3" + n + l + n + str.tostring(below2NegPerc) + "%" + n + l + n + str.tostring(below2NegPercVol) + "x", text_color=color.white, text_halign = text.align_center, bgcolor=color.new(color.blue, 70), text_size=tableTextSize)
table.cell(table_id = metricTable, column = 10, row = 0, text = settingsText, text_color=color.white, text_halign = text.align_left, text_valign = text.align_top, bgcolor=color.new(#100e48, 80), text_size=tableTextSize)
// Plots
//Colors
midColorLine = dirSwitch == 1 ? i_upColorLine : i_downColorLine
midColorBand = dirSwitch == 1 ? i_upColorFill : i_downColorFill
deviationColor = dirSwitch == 1 ? extremeDeviationUp : extremeDeviationDown
extremeUpFill = extremeUpColor
extremeDownFill = extremeDownColor
//Plots
pOhlc = plot(ohlc4, "OHLC4", color=color.new(color.white, 100), display=display.all - display.status_line)
pUpper = plot(upperBandBoosted, "Threshold band up", color=color.new(color.white, 100), style=plot.style_linebr, display=display.all - display.status_line)
pLower = plot(lowerBandBoosted, "Threshold band down", color=color.new(color.white, 100), style=plot.style_linebr, display=display.all - display.status_line)
pMid = plot(fairPriceSmooth, "Fair value basis", color=midColorLine, linewidth=1, display=display.all - display.status_line)
p1U = plot(pivotBandUp, "Fair value deviation band up 1x", color=deviationBandColor, display=display.all - display.status_line)
p1D = plot(pivotBandDown, "Fair value deviation band down 1x", color=deviationBandColor, display=display.all - display.status_line)
p2U = plot(pivotBandUp2, "Fair value deviation band up 2x", color=deviationBandColor, display=display.all - display.status_line)
p2D = plot(pivotBandDown2, "Fair value deviation band down 2x", color=deviationBandColor, display=display.all - display.status_line)
p3U = plot(pivotBandUp3, "Fair value deviation band up 3x", color=deviationBandColor, display=display.all - display.status_line)
p3D = plot(pivotBandDown3, "Fair value deviation band down 3x", color=deviationBandColor, display=display.all - display.status_line)
//Fills
fill(p3U, p2U, color= extremeUpFill, title="Extreme fair value deviation band up fill")
fill(p3D, p2D, color= extremeDownFill, title="Extreme fair value deviation band down fill")
fill(pOhlc, pLower, pivotBandDown3, lowerBandBoosted, extremeDeviationDown, color.new(color.gray, 100), title="Extreme fair value deviation up hue fill")
fill(pOhlc, pUpper, pivotBandUp3, upperBandBoosted, extremeDeviationUp, color.new(color.gray, 100), title="Extreme fair value deviation down hue fill")
fill(pUpper, pLower, color= midColorBand, title="Threshold band fill")
// Metric plots
barcolor(i_btCheck and belowNeg2 ? color.blue : i_btCheck and betweenNeg1AndNeg2 ? color.rgb(124, 147, 239) :
i_btCheck and betweenMidAndNeg1 ? color.aqua : i_btCheck and betweenMidAndPos1 ? color.yellow :
i_btCheck and betweenPos1AndPos2 ? color.orange : i_btCheck and abovePos2 ? color.red : na)
plot(i_btCheck ? volMultiplier : na, title="Relative volume", color=color.new(color.fuchsia, 100), display=display.data_window)
plot(i_btCheck ? allCounts : na, title="All time counts", color=color.new(color.fuchsia, 100), display=display.data_window)
plot(i_btCheck ? abovePos2Count : na, title="+3 time count", color=color.new(color.red, 100), display=display.data_window)
plot(i_btCheck ? abovePos2Vol : na, title="+3 volume count cumulative", color=color.new(color.red, 100), display=display.data_window)
plot(i_btCheck ? abovePos2Vol / abovePos2Count : na, title="+3 volume count average", color=color.new(color.red, 100), display=display.data_window)
plot(i_btCheck ? betweenPos1AndPos2Count : na, title="+2 time count", color=color.new(color.orange, 100), display=display.data_window)
plot(i_btCheck ? betweenPos1AndPos2Vol : na, title="+2 volume count cumulative", color=color.new(color.orange, 100), display=display.data_window)
plot(i_btCheck ? betweenPos1AndPos2Vol / betweenPos1AndPos2Count : na, title="+2 volume count average", color=color.new(color.orange, 100), display=display.data_window)
plot(i_btCheck ? betweenMidAndPos1Count : na, title="+1 time count", color=color.new(color.yellow, 100), display=display.data_window)
plot(i_btCheck ? betweenMidAndPos1Vol : na, title="+1 volume count cumulative", color=color.new(color.yellow, 100), display=display.data_window)
plot(i_btCheck ? betweenMidAndPos1Vol / betweenMidAndPos1Count : na, title="+1 volume count average", color=color.new(color.yellow, 100), display=display.data_window)
plot(i_btCheck ? betweenMidAndNeg1Count : na, title="-1 time count", color=color.new(color.aqua, 100), display=display.data_window)
plot(i_btCheck ? betweenMidAndNeg1Vol : na, title="-1 volume count cumulative", color=color.new(color.aqua, 100), display=display.data_window)
plot(i_btCheck ? betweenMidAndNeg1Vol / betweenMidAndNeg1Count : na, title="-1 volume count average", color=color.new(color.aqua, 100), display=display.data_window)
plot(i_btCheck ? betweenNeg1AndNeg2Count : na, title="-2 time count", color=color.new(color.rgb(124, 147, 239) , 100), display=display.data_window)
plot(i_btCheck ? betweenNeg1AndNeg2Vol : na, title="-2 volume count cumulative", color=color.new(color.rgb(124, 147, 239) , 100), display=display.data_window)
plot(i_btCheck ? betweenNeg1AndNeg2Vol / betweenNeg1AndNeg2Count : na, title="-2 volume count average", color=color.new(color.rgb(124, 147, 239) , 100), display=display.data_window)
plot(i_btCheck ? belowNeg2Count : na, title="-3 time count", color=color.new(color.blue, 100), display=display.data_window)
plot(i_btCheck ? belowNeg2Vol : na, title="-3 volume count cumulative", color=color.new(color.blue, 100), display=display.data_window)
plot(i_btCheck ? belowNeg2Vol / belowNeg2Count : na, title="-3 volume count average", color=color.new(color.blue, 100), display=display.data_window)
// Alerts
//Band cross scenarios
deviation1CrossUp = ta.crossover(high, pivotBandUp)
deviation2CrossUp = ta.crossover(high, pivotBandUp2)
deviation3CrossUp = ta.crossover(high, pivotBandUp3)
deviation1CrossDown = ta.crossunder(low, pivotBandDown)
deviation2CrossDown = ta.crossunder(low, pivotBandDown2)
deviation3CrossDown = ta.crossunder(low, pivotBandDown3)
//Price at fair value basis during trend scenarios
fairPriceInUp = dirSwitch == 1 and low <= upperBandBoosted
fairPriceInDown = dirSwitch == -1 and high >= lowerBandBoosted
//New trend scenarios
newTrendUp = dirSwitch[1] == -1 and dirSwitch == 1 and barstate.isconfirmed
newTrendDown = dirSwitch[1] == 1 and dirSwitch == -1 and barstate.isconfirmed
//Individual
alertcondition(deviation1CrossUp, "Deviation band +1 cross", "High cross above +1 band detected.")
alertcondition(deviation2CrossUp, "Deviation band +2 cross", "High cross above +2 band detected.")
alertcondition(deviation3CrossUp, "Deviation band +3 cross", "High cross above +3 band detected.")
alertcondition(deviation1CrossDown, "Deviation band -1 cross", "Low cross below -1 band detected.")
alertcondition(deviation2CrossDown, "Deviation band -2 cross", "Low cross below -2 band detected.")
alertcondition(deviation3CrossDown, "Deviation band -3 cross", "Low cross below -3 band detected.")
alertcondition(fairPriceInUp, "Low at fair value basis in an uptrend", "Low at fair value basis in an uptrend detected.")
alertcondition(fairPriceInDown, "High at fair value basis in a downtrend", "High at fair value basis in a downtrend detected.")
alertcondition(newTrendUp, "New trend up", "New trend up detected")
alertcondition(newTrendDown, "New trend down", "New trend down detected")
//Grouped
alertcondition(deviation1CrossDown or deviation1CrossUp, "Deviation band -1 cross or +1 cross", "Low cross below -1/high cross above +1 band detected.")
alertcondition(deviation2CrossDown or deviation2CrossUp, "Deviation band -2 cross or +2 cross", "Low cross below -2/high cross above +2 band detected.")
alertcondition(deviation3CrossDown or deviation3CrossUp, "Deviation band -3 cross or +3 cross", "Low cross below -3/high cross above +3 band detected.")
alertcondition(newTrendUp or newTrendDown, "New trend up or new trend down", "New trend up/down detected.") |
Color Agreement Aggregate (CAA) | https://www.tradingview.com/script/2YcYFc4E-Color-Agreement-Aggregate-CAA/ | More-Than-Enough | https://www.tradingview.com/u/More-Than-Enough/ | 27 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © More-Than-Enough
//@version=5
indicator(title = "Color Agreement Aggregate", shorttitle = "CAA", precision = 3)
G1 = input.color(color.rgb(219, 250, 210), "", inline = "Higher Colors")
G2 = input.color(color.rgb(140, 228, 180), "", inline = "Higher Colors")
G3 = input.color(color.rgb(129, 199, 132), "", inline = "Higher Colors")
G4 = input.color(color.rgb( 56, 142, 60), "", inline = "Higher Colors")
G5 = input.color(color.rgb( 5, 102, 86), "", inline = "Higher Colors")
R1 = input.color(color.rgb(255, 231, 217), "", inline = "Lower Colors")
R2 = input.color(color.rgb(252, 192, 195), "", inline = "Lower Colors")
R3 = input.color(color.rgb(247, 124, 128), "", inline = "Lower Colors")
R4 = input.color(color.rgb(194, 24, 91), "", inline = "Lower Colors")
R5 = input.color(color.rgb(128, 25, 34), "", inline = "Lower Colors")
Inverse_Colors = input.bool(false, "Inverse Colors", "Toggle on to perceive the levels as buy/sell pressure. Toggle off to perceive the levels as momentum.")
Background_On = input.bool(false, "Background", inline = "Background")
Background_Color = input.color(color.white, "", inline = "Background")
float KPAM = 0.0
float CCI = ta.cci(hlc3, 20) * 0.01
float RSI = ta.rsi(close, 14)
Rsi = RSI * 0.1 - 5
float Stoch = ta.sma(ta.stoch(close, high, low, 14) * 0.1 - 5, 1)
float Stoch_RSI = ta.sma(ta.stoch(Rsi, Rsi, Rsi, 14) * 0.1 - 5, 3)
if Stoch_RSI >= 0 and Stoch >= 0 and Stoch_RSI >= Stoch
KPAM := Stoch_RSI - ((Stoch_RSI - Stoch) / 2)
if Stoch_RSI >= 0 and Stoch >= 0 and Stoch_RSI < Stoch
KPAM := Stoch_RSI + ((Stoch - Stoch_RSI) / 2)
if Stoch_RSI < 0 and Stoch < 0 and Stoch_RSI >= Stoch
KPAM := Stoch_RSI + ((Stoch - Stoch_RSI) / 2)
if Stoch_RSI < 0 and Stoch < 0 and Stoch_RSI < Stoch
KPAM := Stoch_RSI - ((Stoch_RSI - Stoch) / 2)
if Stoch_RSI >= 0 and Stoch < 0
KPAM := Stoch_RSI - ((Stoch_RSI - Stoch) / 2)
if Stoch_RSI < 0 and Stoch >= 0
KPAM := Stoch_RSI + ((Stoch - Stoch_RSI) / 2)
///// Reach /////
R_Grow = KPAM > KPAM[1]
R_Stay = KPAM == KPAM[1]
R_Up1 = KPAM >= 0 and KPAM < 1
R_Up2 = KPAM >= 1 and KPAM < 2
R_Up3 = KPAM >= 2 and KPAM < 3
R_Up4 = KPAM >= 3 and KPAM < 4
R_Up5 = KPAM >= 4
R_Dn1 = KPAM < 0 and KPAM > -1
R_Dn2 = KPAM <= -1 and KPAM > -2
R_Dn3 = KPAM <= -2 and KPAM > -3
R_Dn4 = KPAM <= -3 and KPAM > -4
R_Dn5 = KPAM <= -4
Precise_Reach =
KPAM >= 0 and KPAM < 0.5 or
KPAM >= 1 and KPAM < 1.5 or
KPAM >= 2 and KPAM < 2.5 or
KPAM >= 3 and KPAM < 3.5 or
KPAM >= 4 and KPAM < 4.5 or
KPAM < 0 and KPAM > -0.5 or
KPAM <= -1 and KPAM > -1.5 or
KPAM <= -2 and KPAM > -2.5 or
KPAM <= -3 and KPAM > -3.5 or
KPAM <= -4 and KPAM > -4.5
///// Energy /////
E_Grow = CCI > CCI[1]
E_Stay = CCI == CCI[1]
E_Up1 = CCI >= 0 and CCI < 1
E_Up2 = CCI >= 1 and CCI < 2
E_Up3 = CCI >= 2 and CCI < 3
E_Up4 = CCI >= 3 and CCI < 4
E_Up5 = CCI >= 4
E_Dn1 = CCI < 0 and CCI > -1
E_Dn2 = CCI <= -1 and CCI > -2
E_Dn3 = CCI <= -2 and CCI > -3
E_Dn4 = CCI <= -3 and CCI > -4
E_Dn5 = CCI <= -4
Precise_Energy =
CCI >= 0 and CCI < 0.5 or
CCI >= 1 and CCI < 1.5 or
CCI >= 2 and CCI < 2.5 or
CCI >= 3 and CCI < 3.5 or
CCI >= 4 and CCI < 4.5 or
CCI < 0 and CCI > -0.5 or
CCI <= -1 and CCI > -1.5 or
CCI <= -2 and CCI > -2.5 or
CCI <= -3 and CCI > -3.5 or
CCI <= -4 and CCI > -4.5
///// Basis /////
B_Grow = RSI > RSI[1]
B_Stay = RSI == RSI[1]
B_Up1 = RSI >= 50 and RSI < 55
B_Up2 = RSI >= 55 and RSI < 60
B_Up3 = RSI >= 60 and RSI < 65
B_Up4 = RSI >= 65 and RSI < 70
B_Up5 = RSI >= 70
B_Dn1 = RSI < 50 and RSI > 45
B_Dn2 = RSI <= 45 and RSI > 40
B_Dn3 = RSI <= 40 and RSI > 35
B_Dn4 = RSI <= 35 and RSI > 30
B_Dn5 = RSI <= 30
Precise_Basis =
RSI >= 50 and RSI < 52.5 or
RSI >= 55 and RSI < 57.5 or
RSI >= 60 and RSI < 62.5 or
RSI >= 65 and RSI < 67.5 or
RSI >= 70 and RSI < 72.5 or
RSI < 50 and RSI > 47.5 or
RSI <= 45 and RSI > 42.5 or
RSI <= 40 and RSI > 37.5 or
RSI <= 35 and RSI > 32.5 or
RSI <= 30 and RSI > 27.5
/////// Plots & Fills ///////
plot(Background_On == false ? na : 6.7, "Background", Background_Color, style = plot.style_area, offset = 1, editable = false)
hline(0, color = color.new(color.black, 100), editable = false) // Base line to add some spacing on the bottom for the up/down of Basis (see last line)
Reach_Label = label.new(bar_index + 5, 5.5, "← Reach (fast)", color = color.blue, style = label.style_label_left, textcolor = color.white, size = size.small)
Energy_Label = label.new(bar_index + 5, 3.5, "← Energy (medium)", color = color.blue, style = label.style_label_left, textcolor = color.white, size = size.small)
Basis_Label = label.new(bar_index + 5, 1.5, "← Basis (slow)", color = color.blue, style = label.style_label_left, textcolor = color.white, size = size.small)
label.delete(Reach_Label[1])
label.delete(Energy_Label[1])
label.delete(Basis_Label[1])
///// Reach /////
plot(6.0, "Reach: Red Highs",
color = R_Up1 ? R1 : R_Up2 ? R2 : R_Up3 ? R3 : R_Up4 ? R4 : R_Up5 ? R5 : R_Dn1 ? G1 : R_Dn2 ? G2 : R_Dn3 ? G3 : R_Dn4 ? G4 : R_Dn5 ? G5 : na,
style = plot.style_columns,
histbase = 5.0,
editable = false,
display = Inverse_Colors ? display.all : display.none)
plot(6.0, "Reach: Green Highs",
color = R_Up1 ? G1 : R_Up2 ? G2 : R_Up3 ? G3 : R_Up4 ? G4 : R_Up5 ? G5 : R_Dn1 ? R1 : R_Dn2 ? R2 : R_Dn3 ? R3 : R_Dn4 ? R4 : R_Dn5 ? R5 : na,
style = plot.style_columns,
histbase = 5.0,
editable = false,
display = Inverse_Colors ? display.none : display.all)
plot(Precise_Reach ? 5.5 : na, "Precise Reach", color = color.white, style = plot.style_columns, histbase = 6.0, display = display.none)
plot(4.8, "Reach Up/Down", R_Grow ? color.lime : R_Stay ? color.white : color.red, linewidth = 3, style = plot.style_histogram, histbase = 4.7)
///// Energy /////
plot(4.0, "Energy: Red Highs",
color = E_Up1 ? R1 : E_Up2 ? R2 : E_Up3 ? R3 : E_Up4 ? R4 : E_Up5 ? R5 : E_Dn1 ? G1 : E_Dn2 ? G2 : E_Dn3 ? G3 : E_Dn4 ? G4 : E_Dn5 ? G5 : na,
style = plot.style_columns,
histbase = 3.0,
editable = false,
display = Inverse_Colors ? display.all : display.none)
plot(4.0, "Energy: Green Highs",
color = E_Up1 ? G1 : E_Up2 ? G2 : E_Up3 ? G3 : E_Up4 ? G4 : E_Up5 ? G5 : E_Dn1 ? R1 : E_Dn2 ? R2 : E_Dn3 ? R3 : E_Dn4 ? R4 : E_Dn5 ? R5 : na,
style = plot.style_columns,
histbase = 3.0,
editable = false,
display = Inverse_Colors ? display.none : display.all)
plot(Precise_Energy ? 3.5 : na, "Precise Energy", color = color.white, style = plot.style_columns, histbase = 4.0, display = display.none)
plot(2.8, "Energy Up/Down", E_Grow ? color.lime : E_Stay ? color.white : color.red, linewidth = 3, style = plot.style_histogram, histbase = 2.7)
///// Basis /////
plot(2.0, "Basis: Red Highs",
color = B_Up1 ? R1 : B_Up2 ? R2 : B_Up3 ? R3 : B_Up4 ? R4 : B_Up5 ? R5 : B_Dn1 ? G1 : B_Dn2 ? G2 : B_Dn3 ? G3 : B_Dn4 ? G4 : B_Dn5 ? G5 : na,
style = plot.style_columns,
histbase = 1.0,
editable = false,
display = Inverse_Colors ? display.all : display.none)
plot(2.0, "Basis: Green Highs",
color = B_Up1 ? G1 : B_Up2 ? G2 : B_Up3 ? G3 : B_Up4 ? G4 : B_Up5 ? G5 : B_Dn1 ? R1 : B_Dn2 ? R2 : B_Dn3 ? R3 : B_Dn4 ? R4 : B_Dn5 ? R5 : na,
style = plot.style_columns,
histbase = 1.0,
editable = false,
display = Inverse_Colors ? display.none : display.all)
plot(Precise_Basis ? 1.5 : na, "Precise Basis", color = color.white, style = plot.style_columns, histbase = 2.0, display = display.none)
plot(0.8, "Basis Up/Down", B_Grow ? color.lime : B_Stay ? color.white : color.red, linewidth = 3, style = plot.style_histogram, histbase = 0.7) |
[WRx450] FED net liquidity | https://www.tradingview.com/script/6ZrnKXzh/ | WRx450 | https://www.tradingview.com/u/WRx450/ | 36 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © WRx450
//@version=5
indicator("[WRx450] FED net liquidity", overlay=true, timeframe='D')
offset = input.int(0,"Offset curves in days", tooltip = "offset all data") // move data on time line by days
Symbol1 = input.symbol("FRED:WALCL", "FED Total Asset") // weekly report on Wednesday
FEDasset = request.security(Symbol1,"",close)
Symbol2 = input.symbol("FRED:RRPONTSYD", "FED Repo market") // Daily report
FEDrepo = request.security(Symbol2,"",close)
Symbol3 = input.symbol("FRED:WTREGEN", "FED Treasury General Account") // weekly report on Wednesday
FEDtreasury = request.security(Symbol3,"",close)
ShowTA = input.bool(false,"Show Total Asset") // activate the curves on graphique
ShowRepo = input.bool(false,"Show Repo")
ShowTGA = input.bool(false,"Show TGA")
ShowNetLiquid = input.bool(true,"Show Net Liquidity","Net liquidity is updated only on wednesday because Total Asset and TGA are updated only on wednesday, making the result on daily unacurate")
ShowChange = input.bool(false,"Show Net Liquidity change","show only the weekly change on wednesday. Add the same indicator and move it to a new graph down for clearer view")
float NetLiquidity = 0
if FEDasset != FEDasset[1]
NetLiquidity := FEDasset - FEDrepo - FEDtreasury
else
NetLiquidity := NetLiquidity[1]
NetChange = NetLiquidity - NetLiquidity[1]
plot(not ShowChange and ShowTA ? FEDasset : na, "FED TA", color.blue, style = plot.style_stepline, offset = offset)
plot(not ShowChange and ShowRepo ? FEDrepo : na, "FED TA", color.yellow, style = plot.style_stepline, offset = offset)
plot(not ShowChange and ShowTGA ? FEDtreasury : na, "FED TA", color.orange, style = plot.style_stepline, offset = offset)
plot(not ShowChange and ShowNetLiquid ? NetLiquidity : na, "FED net liquidity", color.white, style = plot.style_stepline_diamond, offset = offset)
plot(ShowChange ? NetChange : na, "FED Net Liquiditity change", color = NetChange >= 0 ? color.green : color.red , style = plot.style_columns, offset = offset)
|
ATR Pivots | https://www.tradingview.com/script/P4XzXmTh-ATR-Pivots/ | tradeblinks | https://www.tradingview.com/u/tradeblinks/ | 203 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tradeblinks
//Based on my own ideas and ideas from satymahajan.
//@version=5
indicator('ATR Pivots', shorttitle='ATR Pivots', overlay=true)
// Candle Pattern
InsideCandle = input(title='Inside Candle', defval=false,group='plot')
IC = high < high[1] and low > low[1] ? 1 : 0
plotshape(InsideCandle ? IC : na, title='Inside Candle', text='IC', color=color.new(color.aqua, 60), style=shape.diamond, textcolor=color.new( color.aqua,50), location=location.belowbar)
// Input Options
atr_length = input(14, 'ATR Length')
_Index = input.string('Nifty', 'Dash for Index', options=['BankNifty', 'Nifty'], group='Dash Settings')
t1 = _Index == 'Nifty' ? 'NSE:NIFTY': 'NSE:BANKNIFTY'
ticker1 = _Index == 'Nifty' ? 'NSE:NIFTY1!':'NSE:BANKNIFTY1!'
ATR_Levels = input(title='ATR all Fib Levels', defval=false,group='plot')
// Data
ticker = ticker.new(syminfo.prefix, syminfo.ticker, session=session.regular)
previous_close = request.security(ticker, 'D', close[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
atr = request.security(ticker, 'D', ta.atr(atr_length)[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
period_high = request.security(ticker, 'D', high[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
period_low = request.security(ticker, 'D', low[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
range_1 = period_high - period_low
tr_percent_of_atr = range_1 / atr * 100
lower_0236 = previous_close - atr * 0.236
upper_0236 = previous_close + atr * 0.236
lower_0382 = previous_close - atr * 0.382
upper_0382 = previous_close + atr * 0.382
lower_0500 = previous_close - atr * 0.5
upper_0500 = previous_close + atr * 0.5
lower_0618 = previous_close - atr * 0.618
upper_0618 = previous_close + atr * 0.618
lower_0786 = previous_close - atr * 0.786
upper_0786 = previous_close + atr * 0.786
lower_1000 = previous_close - atr
upper_1000 = previous_close + atr
// Add levels
plot(lower_1000, color=color.new(color.red, 0), linewidth=1, title='-100', style=plot.style_circles)
plot(ATR_Levels? lower_0786 : na, color=color.new(color.red, 0), linewidth=1, title='-78.6', style=plot.style_cross)
plot(lower_0618, color=color.new(color.red, 0), linewidth=1, title='-61.8', style=plot.style_circles)
plot(ATR_Levels? lower_0500 : na, color=color.new(color.red, 0), linewidth=1, title='-50.0', style=plot.style_cross)
plot(ATR_Levels? lower_0382 : na, color=color.new(color.red, 0), linewidth=1, title='-38.2', style=plot.style_cross)
plot(lower_0236, color=color.new(color.red, 0), linewidth=1, title='-23.6', style=plot.style_circles)
plot(upper_0236, color=color.new(color.green, 0), linewidth=1, title='23.6', style=plot.style_circles)
plot(ATR_Levels? upper_0382 : na, color=color.new(color.green, 0), linewidth=1, title='38.2', style=plot.style_cross)
plot(ATR_Levels? upper_0500 : na, color=color.new(color.green, 0), linewidth=1, title='50.0', style=plot.style_cross)
plot(upper_0618, color=color.new(color.green, 0), linewidth=1, title='61.8', style=plot.style_circles)
plot(ATR_Levels? upper_0786 : na, color=color.new(color.green, 0), linewidth=1, title='78.6', style=plot.style_cross)
plot(upper_1000, color=color.new(color.green, 0), linewidth=1, title='100', style=plot.style_circles)
plot(previous_close, color=color.new(color.aqua, 0), linewidth=1, title='Previous Close', style=plot.style_circles)
// PDH / PDL
PHPL = input(title='PDH/PDL', defval=true,group='plot')
PH = high
PL = low
PDH = request.security(syminfo.tickerid, 'D', PH[1], barmerge.gaps_off, barmerge.lookahead_on)
PDL = request.security(syminfo.tickerid, 'D', PL[1], barmerge.gaps_off, barmerge.lookahead_on)
PDHColour = PDH != PDH[1] ? na : color.black
PDLColour = PDL != PDL[1] ? na : color.black
plot(PHPL ? PDH : na, title='PDH', color=PDHColour, style=plot.style_line, linewidth=2)
plot(PHPL ? PDL : na, title='PDL', color=PDLColour, style=plot.style_line, linewidth=2)
//EMA Cloud
EMA_Cloud = input(title='EMA Cloud', defval=false,group='plot')
EMA = input.color(color.black)
len = input.int(200, minval=1, title=" EMA Length")
src = close
ema = ta.ema(src, len)
tema=plot(ema, title="EMA", color=EMA, linewidth=1)
FEMA = input.color(color.aqua,title="Fast EMA",group='EMA Cloud')
len1 = input.int(5, minval=1, title=" Fast EMA Length",group='EMA Cloud')
src1 = close
ema1 = ta.ema(src1, len1)
fema1=plot(EMA_Cloud ? ema1 : na, title="Fast EMA", color=FEMA, linewidth=1)
SEMA = input.color(color.blue,title="Slow EMA",group='EMA Cloud')
len2 = input.int(21, minval=1, title=" Slow EMA Length",group='EMA Cloud')
src2 = close
ema2 = ta.ema(src2, len2)
fema2=plot(EMA_Cloud ? ema2 : na, title="Slow EMA", color=SEMA, linewidth=1)
Bull = ema1 > ema2
Bear = ema1 < ema2
cloud = Bull ? input.color(color.new(color.green,95),"Bullish",group='EMA Cloud') : Bear ? input.color(color.new(color.red,95),"Bearish",group='EMA Cloud') : na
fill(fema1,fema2, color = cloud)
//ADR side of script below
text_ADR1_high = 'ADR1 Upper'
text_ADR2_high = 'ADR2 Upper'
text_ADR1_low = 'ADR1 Lower'
text_ADR2_low = 'ADR2 Lower'
//***Start of Inputs
ADR = input(title='ADR', defval=true,group='plot')
var labels_enabled = input.bool(defval=true, title='Show labels')
var adr_1 = input.int(title='ADR 1 Period', defval = 10, minval = 1, group='ADR')
var adr_2 = input.int(title='ADR 2 Period', defval = 5, minval = 1, group='ADR')
var color_ADR1_high = input.color(defval=color.new(color.red ,0), title=text_ADR1_high, group='ADR')
var color_ADR2_high = input.color(defval=color.new(color.red,0), title=text_ADR2_high, group='ADR')
var color_ADR1_low = input.color(defval=color.new(color.green ,0), title=text_ADR1_low, group='ADR')
var color_ADR2_low = input.color(defval=color.new(color.green,0), title=text_ADR2_low, group='ADR')
adrUppercolorfill = input.color(color.red, "Upper Zone Fill",group='ADR',tooltip="Color of zone between Upper Adr 1 and 2")
adrlowercolorfill = input.color(color.green, "Lower Zone Fill",group='ADR',tooltip="Color of zone between Lower Adr 1 and 2")
var plot_history = input.bool(defval=true, group='ADR',title='Historical levels')
//***Start of local functions definiton***
draw_line(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width) =>
dline = line.new(x1=_x1, y1=_y1, x2=_x2, y2=_y2, xloc=_xloc, extend=_extend, color=_color, style=_style, width=_width)
line.delete(dline[1])
//If security is futures - replace the ticker with continuous contract
tickerid_func() =>
tickerid = syminfo.tickerid
if syminfo.type == 'futures'
tickerid := syminfo.root + '1!'
//Function to calculate ADR levels
//Parameters:
// * lengthInput - ADR period
// * hi_low - true-->High, else-->Low
adr_func(lengthInput,hi_low) =>
float result = 0
float adr = 0
open_ = request.security(tickerid_func(), "D", open, barmerge.gaps_off, barmerge.lookahead_on)
adr_High = request.security(tickerid_func(), "D", ta.sma(high[1], lengthInput), barmerge.gaps_off, barmerge.lookahead_on)
adr_Low = request.security(tickerid_func(), "D", ta.sma(low[1], lengthInput), barmerge.gaps_off, barmerge.lookahead_on)
adr := (adr_High - adr_Low)
if hi_low//High
result := adr/2 + open_
else //Low
result := open_ - adr/2
transp_func() =>
transp_0 = 0
//***End of local functions definiton***
//***Start of getting data
start_time = request.security(tickerid_func(), "D", time_close[1],barmerge.gaps_off,barmerge.lookahead_on)
adr1_high = adr_func(adr_1,true)
adr1_low = adr_func(adr_1,false)
adr2_high = adr_func(adr_2,true)
adr2_low = adr_func(adr_2,false)
//***End of getting data
float _adr1_high = na
float _adr1_low = na
float _adr2_high = na
float _adr2_low = na
var show_chart = false
if timeframe.isintraday
show_chart := true
//Plot all days
if show_chart and plot_history
_adr1_high := adr1_high
_adr1_low := adr1_low
_adr2_high := adr2_high
_adr2_low := adr2_low
ADR1H = plot(ADR ? _adr1_high : na, title=text_ADR1_high, color=color_ADR1_high, style=plot.style_circles,linewidth = 0)
ADR2H = plot(ADR ? _adr2_high : na, title=text_ADR2_high, color=color_ADR2_high, style=plot.style_circles,linewidth = 0)
ADR1L = plot(ADR ?_adr1_low : na, title=text_ADR1_low, color=color_ADR1_low, style=plot.style_circles,linewidth = 0)
ADR2L = plot(ADR ?_adr2_low : na, title=text_ADR2_low, color=color_ADR2_low, style=plot.style_circles,linewidth = 0)
fill(ADR1H,ADR2H,color.new(adrUppercolorfill,80))
fill(ADR1L,ADR2L,color.new(adrlowercolorfill,80))
if show_chart and not plot_history
draw_line1 = line.new(start_time, adr1_high, time, adr1_high, xloc.bar_time, extend.none, color_ADR1_high, line.style_dotted, 2)
line.delete(draw_line1[1])
draw_line2 = line.new(start_time, adr2_high, time, adr2_high, xloc.bar_time, extend.none, color_ADR2_high, line.style_dotted, 2)
line.delete(draw_line2[1])
draw_line3 = line.new(start_time, adr1_low, time, adr1_low, xloc.bar_time, extend.none, color_ADR1_low, line.style_dotted, 2)
line.delete(draw_line3[1])
draw_line4 = line.new(start_time, adr2_low, time, adr2_low, xloc.bar_time, extend.none, color_ADR2_low, line.style_dotted, 2)
line.delete(draw_line4[1])
linefill.new(draw_line1, draw_line2, color.new(adrUppercolorfill,80))
linefill.new(draw_line3, draw_line4, color.new(adrlowercolorfill, 80))
//Dash
normalcolor = color.new(color.aqua,0 )
colorchangefirst = color.new(color.green,0 )
Bullish = color.new(color.green,0 )
Bearish = color.new(color.red,0 )
Top_Right = position.top_right
Bottom_Right = position.bottom_right
DashPlacement = input.string(Top_Right, "Dash Location",options = [Top_Right, Bottom_Right],group='Dash Settings')
//Day ATR
t1atr = request.security(t1, 'D', ta.atr(atr_length)[1])
t1ATR = math.round(t1atr,2)
t1dtr = request.security(t1,'D', math.round(high - low,2))
t1atrp = math.round(t1dtr/t1atr * 100,2)
// 1min ATR
TimeFrame = input.timeframe("1", "Timeframe for ATR Intraday", tooltip="Time you want Indtradat ATR based on",group='Dash Settings')
atr1 = request.security(ticker1, TimeFrame, ta.atr(14))
atrindex = math.round(atr1,2)
dtr_color = color.gray
if t1atrp <=23.6
dtr_color := color.gray
else if t1atrp >= 78.6
dtr_color := color.red
else
dtr_color := color.green
//RSI
rsiVal = input(defval=14, title='RSI Input',group='Dash Settings')
rsiMax = input(defval=55, title='RSI Top',group='Dash Settings')
rsiMin = input(defval=45, title='RSI Bottom',group='Dash Settings')
indexRSI= request.security(_Index,"",ta.rsi(close, rsiVal))
rsiIndexColor = indexRSI >= rsiMax ? Bullish : indexRSI <= rsiMin ? Bearish : normalcolor
//Draw Table
var table ATR = table.new(DashPlacement, 4, 6,frame_color=color.new(color.black, 0), frame_width = 1, border_color= color.new(color.black, 40), border_width = 1)
if barstate.islast
table.cell(ATR,1,1,text = _Index == 'Nifty' ? 'NIFTY ATR Dash' : 'BANKNIFTY ATR Dash',text_color=#e53238,bgcolor=color.new(color.black,90))
table.cell(ATR,1,2,text='ATR | DTR | DTR% ',bgcolor=color.new(color.black,90))
table.cell(ATR,1,3, str.tostring(t1ATR, '#') + ' | ' + str.tostring(t1dtr, '#')+ ' | ' + str.tostring(t1atrp, '#.#')+"%",text_color=color.new(dtr_color,0),bgcolor=color.new(dtr_color,70))
table.cell(ATR,1,4, text = _Index == 'Nifty' ? TimeFrame + "min ATR : " + str.tostring(atrindex,format.mintick) :TimeFrame + "min ATR : " + str.tostring(atrindex,format.mintick),text_color=_Index == 'Nifty' ? color.new(atr1 > 11? colorchangefirst:normalcolor,0) :color.new(atr1 > 30? colorchangefirst:normalcolor,0),bgcolor=_Index == 'Nifty' ? color.new(atr1 > 11? colorchangefirst:normalcolor,70) :color.new(atr1 > 30? colorchangefirst:normalcolor,70))
table.cell(ATR,1,5, text = _Index == 'Nifty' ? 'RSI : ' + str.tostring(indexRSI,format.mintick) : 'RSI : ' + str.tostring(indexRSI,format.mintick),text_color=color.new(rsiIndexColor,0),bgcolor= color.new(rsiIndexColor,70))
//Table Logo
var table logo = table.new(position.top_center, 1, 1)
if barstate.islast
table.cell(logo, 0, 0, "tradeblinks",text_color =#e53238)
//END
|
[WRx450] FED net liquidity | https://www.tradingview.com/script/4Iexb8EV/ | WRx450 | https://www.tradingview.com/u/WRx450/ | 105 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © WRx450
//@version=5
indicator("[WRx450] FED net liquidity", overlay=true, timeframe='D')
offset = input.int(0,"Offset curves in days", tooltip = "offset all data") // move data on time line by days
Symbol1 = input.symbol("FRED:WALCL", "FED Total Asset") // weekly report on Wednesday
FEDasset = request.security(Symbol1,"",close)
Symbol2 = input.symbol("FRED:RRPONTSYD", "FED Repo market") // Daily report
FEDrepo = request.security(Symbol2,"",close)
Symbol3 = input.symbol("FRED:WTREGEN", "FED Treasury General Account") // weekly report on Wednesday
FEDtreasury = request.security(Symbol3,"",close)
ShowTA = input.bool(false,"Show Total Asset") // activate the curves on graphique
ShowRepo = input.bool(false,"Show Repo")
ShowTGA = input.bool(false,"Show TGA")
ShowNetLiquid = input.bool(true,"Show Net Liquidity","Net liquidity is updated only on wednesday because Total Asset and TGA are updated only on wednesday, making the result on daily unacurate")
ShowChange = input.bool(false,"Show Net Liquidity change","show only the weekly change on wednesday. Add the same indicator and move it to a new graph down for clearer view")
float NetLiquidity = 0
if FEDasset != FEDasset[1]
NetLiquidity := FEDasset - FEDrepo - FEDtreasury
else
NetLiquidity := NetLiquidity[1]
NetChange = NetLiquidity - NetLiquidity[1]
plot(not ShowChange and ShowTA ? FEDasset : na, "FED TA", color.blue, style = plot.style_stepline, offset = offset)
plot(not ShowChange and ShowRepo ? FEDrepo : na, "FED TA", color.yellow, style = plot.style_stepline, offset = offset)
plot(not ShowChange and ShowTGA ? FEDtreasury : na, "FED TA", color.orange, style = plot.style_stepline, offset = offset)
plot(not ShowChange and ShowNetLiquid ? NetLiquidity : na, "FED net liquidity", color.white, style = plot.style_stepline_diamond, offset = offset)
plot(ShowChange ? NetChange : na, "FED Net Liquiditity change", color = NetChange >= 0 ? color.green : color.red , style = plot.style_columns, offset = offset)
|
Volume Price Balance by serkany88 | https://www.tradingview.com/script/dmkcVg0b-Volume-Price-Balance-by-serkany88/ | serkany88 | https://www.tradingview.com/u/serkany88/ | 314 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © serkany88
//@version=5
indicator("Volume Price Balance", overlay=false, precision=2)
import Bjorgum/BjCandlePatterns/4 as cp
//Define function for checking condition in last candles
f_ideal_TimesInLast(_cond, _len) => math.sum(_cond ? 1 : 0, _len)
rejectionCandles = input.bool(defval=true, title='Rejection Candle Confluence', group="Comparison", tooltip="Calculates rejection candles based on body size and wicks. This is required to be enabled to show rejection points.")
showRejectionPoints = input.bool(defval=true, title='Show Rejection Points', group="Comparison")
bBLength = input.int(defval=50, title='Length of Last Volume Price Comparison', group="Comparison", tooltip="Overall result lookback length")
smoothing = input.int(defval=20, title='Smoothing', group="Comparison")
bUltraMultiplier = input.float(defval=2.2, title='Ultra High Comparison Multiplier', group="Comparison")
bVeryHighMultiplier = input.float(defval=1.8, title='Very High Comparison Multiplier', group="Comparison")
bHighMultiplier = input.float(defval=1.2, title='High Comparison Multiplier', group="Comparison")
//////////////// Volume Spread Analysis Area ////////////////
lengthVolumeMA = input(defval=20, title='Length of MA applied on Volume', group="VSA Volume")
ratioUltraVolume = input(defval=2.2, title='Ultra High Volume Ratio', group="VSA Volume")
ratioVeryHighVolume = input(defval=1.8, title='Very High Volume Ratio', group="VSA Volume")
ratioHighVolume = input(defval=1.2, title='High Volume Ratio', group="VSA Volume")
ratioNormalVolume = input(defval=0.8, title='Normal Volume Ratio', group="VSA Volume")
ratioLowVolume = input(defval=0.4, title='Low Volume Ratio', group="VSA Volume")
ratioVeryLowVolume = input(defval=0.4, title='Very Low Volume Ratio', group="VSA Volume")
float volumeMA = 0
volumeMA := nz(volumeMA[1]) + (volume - nz(volumeMA[1])) / lengthVolumeMA
ultraHighVolumeMin = volumeMA * ratioUltraVolume
veryHighVolumeMin = volumeMA * ratioVeryHighVolume
highVolumeMin = volumeMA * ratioHighVolume
normalVolumeMin = volumeMA * ratioNormalVolume
lowVolumeMin = volumeMA * ratioLowVolume
veryLowVolumeMin = volumeMA * ratioVeryLowVolume
volUltraHigh = volume >= ultraHighVolumeMin ? true : false
volVeryHigh = volume >= veryHighVolumeMin and volume < ultraHighVolumeMin ? true : false
volHigh = volume >= highVolumeMin and volume < veryHighVolumeMin ? true : false
volNormal = volume >= normalVolumeMin and volume < highVolumeMin ? true : false
volLow = volume >= lowVolumeMin and volume < normalVolumeMin ? true : false
volVeryLow = volume < lowVolumeMin ? true : false
//Vol Last Calculations
lastVolUltraHigh = f_ideal_TimesInLast(volUltraHigh, bBLength)
lastVolVeryHigh = f_ideal_TimesInLast(volVeryHigh, bBLength)
lastVolHigh = f_ideal_TimesInLast(volHigh, bBLength)
lastVolNormal = f_ideal_TimesInLast(volNormal, bBLength)
//////////////// Price Spread Analysis Area ////////////////
lengthPriceMA = input(defval=20, title='Length of MA applied on Price', group="PSA Price")
ratioUltraPrice = input(defval=2.2, title='Ultra High Price Ratio', group="PSA Price")
ratioVeryHighPrice = input(defval=1.8, title='Very High Price Ratio', group="PSA Price")
ratioHighPrice = input(defval=1.2, title='High Price Ratio', group="PSA Price")
ratioNormalPrice = input(defval=0.8, title='Normal Price Ratio', group="PSA Price")
ratioLowPrice = input(defval=0.4, title='Low Price Ratio', group="PSA Price")
ratioVeryLowPrice = input(defval=0.4, title='Very Low Price Ratio', group="PSA Price")
currentP = math.abs(close - open)
float PriceMA = 0
PriceMA := nz(PriceMA[1]) + (currentP - nz(PriceMA[1])) / lengthPriceMA
ultraHighPriceMin = PriceMA * ratioUltraPrice
veryHighPriceMin = PriceMA * ratioVeryHighPrice
highPriceMin = PriceMA * ratioHighPrice
normalPriceMin = PriceMA * ratioNormalPrice
lowPriceMin = PriceMA * ratioLowPrice
veryLowPriceMin = PriceMA * ratioVeryLowPrice
PUltraHigh = currentP >= ultraHighPriceMin ? true : false
PVeryHigh = currentP >= veryHighPriceMin and currentP < ultraHighPriceMin ? true : false
PHigh = currentP >= highPriceMin and currentP < veryHighPriceMin ? true : false
PNormal = currentP >= normalPriceMin and currentP < highPriceMin ? true : false
PLow = currentP >= lowPriceMin and currentP < normalPriceMin ? true : false
PVeryLow = currentP < lowPriceMin ? true : false
/////////////////////////// Other Calculations ////////////////////////
// Rejection Candle Functions
bullishhRejection() => rejectionCandles ? close > open and cp.topWick() > cp.body() * 1.15 : false
bearishRejection() => rejectionCandles ? close < open and cp.bottomWick() > cp.body() * 1.15 : false
//Bullish Definitions
bullishUltraP = close > open and PUltraHigh and (volUltraHigh or volVeryHigh or volHigh) and bullishhRejection() == false
bullishVeryHighP = close > open and PVeryHigh and (volUltraHigh or volVeryHigh or volHigh) and bullishhRejection() == false
bullishHighP = close > open and PHigh and (volUltraHigh or volVeryHigh or volHigh) and bullishhRejection() == false
//bullishNormalP = close > open and PNormal and (volUltraHigh or volVeryHigh)
// Rejection Points Variables
bullishUltraRejection = close > open and PUltraHigh and (volUltraHigh or volVeryHigh or volHigh) and bullishhRejection()
bullishVeryHighRejection = close > open and PVeryHigh and (volUltraHigh or volVeryHigh or volHigh) and bullishhRejection()
bullishHighRejection = close > open and PHigh and (volUltraHigh or volVeryHigh or volHigh) and bullishhRejection()
// Calculate how many times we've faced certain condition
lastBUltra = f_ideal_TimesInLast(bullishUltraP, bBLength)
lastBVeryHigh = f_ideal_TimesInLast(bullishVeryHighP, bBLength)
lastBHigh = f_ideal_TimesInLast(bullishHighP, bBLength)
//Bearish Definitions
bearishUltraP = close < open and PUltraHigh and (volUltraHigh or volVeryHigh or volHigh) and bearishRejection() == false
bearishVeryHighP = close < open and PVeryHigh and (volUltraHigh or volVeryHigh or volHigh) and bearishRejection() == false
bearishHighP = close < open and PHigh and (volUltraHigh or volVeryHigh or volHigh) and bearishRejection() == false
// Rejection Points Variables
bearishUltraRejection = close < open and PUltraHigh and (volUltraHigh or volVeryHigh or volHigh) and bearishRejection()
bearishVeryHighRejection = close < open and PVeryHigh and (volUltraHigh or volVeryHigh or volHigh) and bearishRejection()
bearishHighRejection = close < open and PHigh and (volUltraHigh or volVeryHigh or volHigh) and bearishRejection()
lastBearUltra = f_ideal_TimesInLast(bearishUltraP, bBLength)
lastBearVeryHigh = f_ideal_TimesInLast(bearishVeryHighP, bBLength)
lastBearHigh = f_ideal_TimesInLast(bearishHighP, bBLength)
// Define Calculations With Strengths
TotalBullStrength = lastBUltra * bUltraMultiplier + lastBVeryHigh * bVeryHighMultiplier + lastBHigh * bHighMultiplier
TotalBearStrength = lastBearUltra * bUltraMultiplier + lastBearVeryHigh * bVeryHighMultiplier + lastBearHigh * bHighMultiplier
// Draw the Plots and Fills
bullPlot = plot(ta.sma(TotalBullStrength, smoothing), title="Bull Strength", color=color.green, linewidth = 1, style= plot.style_line)
bearPlot = plot(ta.sma(TotalBearStrength, smoothing), title="Bear Strength", color=color.red, linewidth = 1, style= plot.style_line)
fill(plot1 = bullPlot, plot2 = bearPlot, color=ta.sma(TotalBullStrength, smoothing) > ta.sma(TotalBearStrength, smoothing) ? color.new(color.green, 70) : color.new(color.red, 70))
plotshape(showRejectionPoints ? bullishUltraRejection : na, title= "Bullish Ultra Rejection", style= shape.circle, location = location.top, color=color.red, size = size.tiny)
plotshape(showRejectionPoints ? bullishVeryHighRejection : na, title= "Bullish Very High Rejection", style= shape.circle, location = location.top, color=color.white, size = size.tiny)
plotshape(showRejectionPoints ? bullishHighRejection : na, title= "Bullish High Rejection", style= shape.circle, location = location.top, color=color.gray, size = size.tiny)
plotshape(showRejectionPoints ? bearishUltraRejection : na, title= "Bearish Ultra Rejection", style= shape.circle, location = location.bottom, color=color.green, size = size.tiny)
plotshape(showRejectionPoints ? bearishVeryHighRejection : na, title= "Bearish Very High Rejection", style= shape.circle, location = location.bottom, color=color.white, size = size.tiny)
plotshape(showRejectionPoints ? bearishHighRejection : na, title= "Bearish High Rejection", style= shape.circle, location = location.bottom, color=color.gray, size = size.tiny)
//================== Table Status ==================
showStrategyStatus =input.bool(true, "Show Current Status Table", group='Current Status')
statusTableSize =input.string(size.small, "Table Size", options=[size.tiny, size.small, size.normal, size.large, size.huge], group='Current Status')
if showStrategyStatus and barstate.islast
var toptablesize = statusTableSize
////////////// Current Status Table /////////////
var table strategyStatus = table.new(position.top_right, 5, 3, frame_color = #d1d1d1, bgcolor = #d1d1d1, frame_width = 1,border_width=2)
table.cell(strategyStatus, 1, 0, text='Bull Strength', bgcolor=#292b2b, text_color=color.white, text_halign=text.align_center, text_valign=text.align_center, text_size=toptablesize)
table.cell(strategyStatus, 2, 0, text='Bear Strength', bgcolor=#292b2b, text_color=color.white, text_halign=text.align_center, text_valign=text.align_center, text_size=toptablesize)
table.cell(strategyStatus, 1, 1, text=str.tostring(TotalBullStrength), bgcolor=#292b2b, text_color=color.white, text_halign=text.align_center, text_valign=text.align_center, text_size=toptablesize)
table.cell(strategyStatus, 2, 1, text=str.tostring(TotalBearStrength), bgcolor=#292b2b, text_color=color.white, text_halign=text.align_center, text_valign=text.align_center, text_size=toptablesize) |
Balance of Force (BOF) | https://www.tradingview.com/script/Ott1RO0A-Balance-of-Force-BOF/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 61 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("Balance of Force")
import lastguru/DominantCycle/2 as d
length = input.int(20, "Length", 1)
rng = input.bool(true, "Open/Close", "Toggle High/Low or Open/Close")
bes(float source = close, float length = 9)=>
alpha = 2 / (length + 1)
var float smoothed = na
smoothed := alpha * (source) + (1 - alpha) * nz(smoothed[1])
var int count = na
var float deviation = na
var int count_bearish = na
var int count_bullish = na
var float bearish = na
var float bullish = na
if open > close
bearish := nz(bearish[1]) + math.abs((rng ? open : high) - (rng ? close : low))
count_bearish := nz(count_bearish[1]) + 1
if close > open
bullish := nz(bullish[1]) + math.abs((rng ? close : high) - (rng ? open : low))
count_bullish := nz(count_bullish[1]) + 1
bearish_true_range = (bearish - nz(bearish[length]))/(count_bearish - count_bearish[length])
bullish_true_range = (bullish - nz(bullish[length]))/(count_bullish - count_bullish[length])
bullish_bearish_ratio = math.log(bullish_true_range/bearish_true_range)
if 1 == 1//lol
count := nz(count[1]) + 1
deviation := nz(deviation[1]) + math.pow(bullish_bearish_ratio - math.log(1), 2)
square_diff = math.sqrt(deviation/(count-1))
smooth_length = d.mamaPeriod(bullish_bearish_ratio, 2, 4096)
smoothed_ratio = bes(bullish_bearish_ratio, smooth_length)
center = plot(math.log(1), color = color.new(color.silver, 20))
plot(smoothed_ratio, color = color.orange)
plot(bullish_bearish_ratio)
band_top_1 = plot(square_diff, color = color.new(color.silver, 95))
band_bot_1 = plot(-square_diff, color = color.new(color.silver, 95))
band_top_2 = plot(square_diff * 2, color = color.new(color.silver, 95))
band_bot_2 = plot(-square_diff * 2, color = color.new(color.silver, 95))
band_top_3 = plot(square_diff * 3, color = color.new(color.silver, 95))
band_bot_3 = plot(-square_diff * 3, color = color.new(color.silver, 95))
fill(band_top_3, center, top_value = square_diff * 3, bottom_value = math.log(1), top_color = color.new(color.red, 90), bottom_color = color.new(color.green, 90))
fill(band_bot_3, center, top_value = math.log(1), bottom_value = -square_diff * 3, bottom_color = color.new(color.red, 90), top_color = color.new(color.green, 90))
|
Buy Sell Calendar [LuxAlgo] | https://www.tradingview.com/script/k5QMLWCA-Buy-Sell-Calendar-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,070 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Buy Sell Calendar [LuxAlgo]", overlay = true
, max_lines_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
freq = input.string('Daily', 'Frequency', options = ['Daily', 'Monthly'])
method = input.string('Linreg', 'Trend Method', options = ['Linreg', 'Accumulated Delta', 'Max/Min'])
tzOffset = input(0, 'Timezone Offset')
useDate = input(false, 'Choose Date', inline = 'inline0')
setDate = input.time(0, '' , inline = 'inline0')
//Calendar
showDash = input(true, 'Show Calendar' , group = 'Calendar')
dashLoc = input.string('Top Right', 'Location', options = ['Top Right', 'Bottom Right', 'Bottom Left'], group = 'Calendar')
textSize = input.string('Small', 'Size' , options = ['Tiny', 'Small', 'Normal'] , group = 'Calendar')
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
trend_lreg(reset, accumulate)=>
var float wma = na
var float sma = na
var bull = 0
var den = 1
if reset
bull := 0
wma := close
sma := close
den := 1
if accumulate
bull += wma / (den*(den+1)/2) > sma / den ? 1 : 0
wma := close
sma := close
den := 1
else
den += 1
wma += close * den
sma += close
trend = wma / (den*(den+1)/2) > sma / den ? 1 : 0
[trend, bull]
trend_delta(reset, accumulate)=>
var up = 0.
var dn = 0.
var bull = 0
d = close - open
if reset
bull := 0
up := math.max(d, 0)
dn := math.max(-d, 0)
if accumulate
bull += up > dn ? 1 : 0
up := math.max(d, 0)
dn := math.max(-d, 0)
else
up += math.max(d, 0)
dn += math.max(-d, 0)
trend = up > dn ? 1 : 0
[trend, bull]
trend_maxmin(reset, accumulate)=>
var max = high
var min = low
var bull = 0
if reset
bull := 0
max := high
min := low
if accumulate
bull += close[1] > math.avg(max, min) ? 1 : 0
max := high
min := low
else
max := math.max(high, max)
min := math.min(low, min)
trend = close > math.avg(max, min) ? 1 : 0
[trend, bull]
trend_fun(reset, accumulate)=>
[trend, bull] = switch method
'Linreg'=> trend_lreg(reset, accumulate)
'Accumulated Delta'=> trend_delta(reset, accumulate)
'Max/Min'=> trend_maxmin(reset, accumulate)
//-----------------------------------------------------------------------------}
//Global variables
//-----------------------------------------------------------------------------{
var line l = na
var months = array.from('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
var tz = str.format('UTC{0}{1}', tzOffset > 0 ? '+' : '', tzOffset)
tz_year = year(time, tz)
tz_month = month(time, tz)
dmonth = dayofmonth(time, tz)
dweek = dayofweek(time, tz)
//Dashboard
var table_position = dashLoc == 'Bottom Left' ? position.bottom_left
: dashLoc == 'Top Right' ? position.top_right
: position.bottom_right
var table_size = textSize == 'Tiny' ? size.tiny
: textSize == 'Small' ? size.small
: size.normal
var tb = table.new(table_position, 7, 9
, bgcolor = #1e222d
, border_color = #373a46
, border_width = 1
, frame_color = #373a46
, frame_width = 1)
n = bar_index
display = useDate ? time < setDate : true
//-----------------------------------------------------------------------------}
//Daily Calendar
//-----------------------------------------------------------------------------{
var row = 2
//Set calendar days
if barstate.isfirst and freq == 'Daily'
table.cell(tb, 0, 1, 'Su', text_color = color.white, text_size = table_size)
table.cell(tb, 1, 1, 'Mo', text_color = color.white, text_size = table_size)
table.cell(tb, 2, 1, 'Tu', text_color = color.white, text_size = table_size)
table.cell(tb, 3, 1, 'We', text_color = color.white, text_size = table_size)
table.cell(tb, 4, 1, 'Th', text_color = color.white, text_size = table_size)
table.cell(tb, 5, 1, 'Fr', text_color = color.white, text_size = table_size)
table.cell(tb, 6, 1, 'Sa', text_color = color.white, text_size = table_size)
if display and freq == 'Daily'
//Set month and clear table
if dmonth < dmonth[1]
table.cell(tb, 0, 0, str.tostring(array.get(months, month-1)) + ' ' + str.tostring(year)
, text_color = color.white
, text_size = table_size)
table.merge_cells(tb, 0, 0, 6, 0)
table.clear(tb, 0, 2, 6, 8)
row := 2
if dweek < dweek[1]
row += 1
//Set line and most recent line color/calendar cell
if dmonth != dmonth[1]
l := line.new(n, close + syminfo.mintick,n, close - syminfo.mintick
, extend = extend.both
, style = line.style_dashed
, color = na)
[trend, bull] = trend_fun(dmonth < dmonth[1], dmonth > dmonth[1])
trend_css = trend
? color.teal
: color.red
line.set_color(l, trend_css)
table.cell(tb, dweek-1, row, str.tostring(dmonth)
, text_color = color.white
, bgcolor = trend_css
, text_size = table_size)
table.cell(tb, 0, 8, str.format('{0, number, percent} Bullish', (bull + trend) / dmonth)
, text_color = color.white
, text_size = table_size)
if freq == 'Daily'
table.merge_cells(tb, 0, 8, 6, 8)
//-----------------------------------------------------------------------------}
//Monthly Calendar
//-----------------------------------------------------------------------------{
if display and freq == 'Monthly'
//Set month and clear table
if tz_year > nz(tz_year[1])
for i = 1 to 12
table.cell(tb, (i-1)%4, math.ceil(i/4)
, text = str.substring(array.get(months, i-1), 0, 3)
, text_color = color.white
, text_size = table_size)
table.cell(tb, 0, 0, str.tostring(tz_year)
, text_color = color.white
, text_size = table_size)
table.merge_cells(tb, 0, 0, 3, 0)
if tz_month != tz_month[1]
l := line.new(n, close + syminfo.mintick, n, close - syminfo.mintick
, style = line.style_dashed, extend = extend.both)
[trend, bull] = trend_fun(tz_year > nz(tz_year[1]), tz_month != tz_month[1])
trend_css = trend
? color.teal
: color.red
line.set_color(l, trend_css)
table.cell(tb, (tz_month-1) % 4, math.ceil(tz_month / 4)
, text = str.substring(array.get(months, tz_month - 1), 0, 3)
, text_color = color.white
, bgcolor = trend_css
, text_size = table_size)
table.cell(tb, 0, 4, str.format('{0, number, percent} Bullish', (bull + trend) / tz_month)
, text_color = color.white
, text_size = table_size)
if freq == 'Monthly'
table.merge_cells(tb, 0, 4, 3, 4)
//-----------------------------------------------------------------------------} |
ValueBands for Acceptable P/E/ and P/B | https://www.tradingview.com/script/UoCHbQE7/ | NatsukiKano | https://www.tradingview.com/u/NatsukiKano/ | 30 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © NatsukiKano
//@version=5
// # What's this script?
// - Plot of BookValue and TangibleBookValue
// - Visualization of Price Bands for Acceptable P/E and P/B
// - Adaptation to Currency Change
// - Combine long term financial data and short term financial data
// - 2023/01/23:Set timeframe="W" for stable loading of financial data.
indicator(title="ValueBands for Acceptable P/E/ and P/B",shorttitle="ValueBands",timeframe="W" ,format= format.price, precision=0, overlay=true)
// ====================
// PRE
// ====================
// <import_statements>
// --------------------
Group1 ="Acceptable Ratio"
AcceptablePERatio = input(15.0 , "Price per Earnings" , group = Group1)
AcceptablePBRatio = input(1.5 , "Price per BookValue" , group = Group1)
AcceptablePTBRatio = input(1.5 , "Price per TangibleBookValue" , group = Group1)
Group2 ="Line Color"
ColorBookValue = input(color.new(color.teal ,10) , "BookValue" , group = Group2)
ColorTangibleBookValue = input(color.new(color.navy,10) , "TangibleBookValue" , group = Group2)
ColorAcceptablePE = input(color.new(color.orange,10) , "P/E" , group = Group2)
ColorAcceptablePB = input(color.new(color.blue,10) , "P/B" , group = Group2)
ColorAcceptablePTB = input(color.new(color.navy,10) , "P/TB" , group = Group2)
ColorGeometricMean = input(color.new(color.silver,10) , "GeometricMean of P/E and P/B" , group = Group2)
FillingTransparency = input(95, "FillingTransparency" , group = Group2)
// <request>
// --------------------
EPS_Y = request.financial(syminfo.tickerid , "EARNINGS_PER_SHARE" , "FY" , barmerge.gaps_off , false , syminfo.currency)
EPS_TTM = request.financial(syminfo.tickerid , "EARNINGS_PER_SHARE" , "TTM" , barmerge.gaps_off , false , syminfo.currency)
BVPS_Y = request.financial(syminfo.tickerid , "BOOK_VALUE_PER_SHARE" , "FY" , barmerge.gaps_off , false , syminfo.currency)
BVPS_Q = request.financial(syminfo.tickerid , "BOOK_VALUE_PER_SHARE" , "FQ" , barmerge.gaps_off , false , syminfo.currency)
TBPS_Y = request.financial(syminfo.tickerid , "BOOK_TANGIBLE_PER_SHARE" , "FY" , barmerge.gaps_off , false , syminfo.currency)
TBPS_Q = request.financial(syminfo.tickerid , "BOOK_TANGIBLE_PER_SHARE" , "FQ" , barmerge.gaps_off , false , syminfo.currency)
// ====================
// Calc.
// ====================
// Combine long term financial data and short term financial data
// --------------------
EPS = EPS_TTM ? EPS_TTM : EPS_Y
BVPS = BVPS_Q ? BVPS_Q : BVPS_Y
TBPS = TBPS_Q ? TBPS_Q : TBPS_Y
// Acceptable Price
// --------------------
APE = math.max(0, AcceptablePERatio * EPS)
APB = math.max(0, AcceptablePBRatio * BVPS)
APTB = math.max(0, AcceptablePTBRatio * TBPS)
// Geometric mean of Acceptable Prices
// if APE15 & APB1.5 then GM_APE_APB=GrahamNumber
// --------------------
GM_APE_APB = math.sqrt( APE * APB )
GM_APE_APTB = math.sqrt( APE * APTB )
// ====================
// POST
// ====================
// Draw BookValue and TangibleBookValue
// --------------------
lineTBV = plot( TBPS , "TangibleBookValue" , ColorTangibleBookValue , linewidth = 2)
lineBV = plot( BVPS , "BookValue" , ColorBookValue , linewidth = 2)
fill(lineBV ,lineTBV ,color.new(ColorTangibleBookValue,FillingTransparency), title="Area:BV-TBV",fillgaps=true)
// Draw Acceptable Price Band
// --------------------
lineATPB = plot( APTB , "Acceptable P/TB" , ColorAcceptablePTB , linewidth = 1)
lineAPB = plot( APB , "Acceptable P/B" , ColorAcceptablePB , linewidth = 1)
lineAPE = plot( APE , "Acceptable P/E" , ColorAcceptablePE , linewidth = 2)
lineGN = plot( GM_APE_APB , "GeometricMean(APE&APB)" , ColorGeometricMean , linewidth = 1)
lineGNTBV = plot( GM_APE_APTB , "GeometricMean(APE&APTB)" , ColorGeometricMean , linewidth = 1)
fill(lineAPB ,lineAPE ,color=color.new(APB > APE ? ColorAcceptablePB : ColorAcceptablePE ,FillingTransparency), title="Area:PE-PB",fillgaps=true)
|
Multi TF High/Low/Open/Close Line | https://www.tradingview.com/script/H9XSuq1p-Multi-TF-High-Low-Open-Close-Line/ | goofoffgoose | https://www.tradingview.com/u/goofoffgoose/ | 153 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © goofoffgoose
//@version=5
//This is a requested spin-off version of my previous HLOC for the Daily/Weekly/Monthly that allows users to choose 3 different
// timeframe units (Mins, Hours, Days, ect..) from the dropdown menu and then select the lookback periord in which to draw the HLOC.
//
// This indicator draws a line on the TF 1, TF 2, and TF 3 bar at the High, Low, Open and Close of user input Timeframe unit and selected lookback period.
// The lookback period will go back the number of candles entered. So for example if you choose a 5 Min chart with a lookback of 3, the lines will be drawn on
// the HLOC 3 closed 5 min candles back. Selecting 0 will show data on the current Real-Time candle.
// Each set of lines has an optional identifying label with its own color set that can be shown with or without
// price value, and has drop down menues for size and style of each set of labels. The TF unit value is displayed on the label, but not the lookback.
// So if you are using the hourly on all 3 TF's with different lookback periods, they will all say "60" on the label.
// I recommend using the line and label options to distinguish between the different lookback values.
// Each set of lines has inputs for line/text color, line width and style and each line arguement can be selected independently.
// I recommend going into Chart Settings/Status Line and turning off indicator arguments OR moving the script to the top
// of the indicator list to avoid obstructed chart view with this indicators arguments. When script allows, I will update it to hide them.
indicator("Multi TF High/Low/Open/Close Line", shorttitle= "Muti TF HLOC", overlay=true)
t = ticker.new(syminfo.prefix, syminfo.ticker)
///////// Label input options and colors //////////
////// TF 1 line and label options ////
// Show Lines and TF
show_dhloc = input.bool(defval=true, title=" Show Timeframe 1 Lines?", group="Timeframe 1 High, Low, Open and Close Lines", inline="TF 1 Line")
tf_1 = input.timeframe('60', title="Timeframe 1 - ", group="Timeframe 1 High, Low, Open and Close Lines", inline="TF 1")
tf_1_m = input.int(1, title=" TF Lookback - ", tooltip="Input the number of TF units selected in the drop-down menu you want to lookback. 0 is current candle where 1 and higher will lookback. Example: You select 1 hour in the drop-down menu with a lookback number of 2, lines will be drawn on hourly data from 2 candles back",
group="Timeframe 1 High, Low, Open and Close Lines", inline="TF 1")
// Line style and size
dLineWidth = input.int(1, title="Line Width - ", minval=1, group="Timeframe 1 High, Low, Open and Close Lines", inline="TF 1 Line Style")
dLineStyleOption = input.string(defval="solid (─)",title=" Line Style - ",
options=["solid (─)", "dotted (┈)", "dashed (╌)",
"arrow left (←)", "arrow right (→)", "arrows both (↔)"],
group="Timeframe 1 High, Low, Open and Close Lines", inline="TF 1 Line Style")
dLineStyle = (dLineStyleOption == "dotted (┈)") ? line.style_dotted :
(dLineStyleOption == "dashed (╌)") ? line.style_dashed :
(dLineStyleOption == "arrow left (←)") ? line.style_arrow_left :
(dLineStyleOption == "arrow right (→)") ? line.style_arrow_right :
(dLineStyleOption == "arrows both (↔)") ? line.style_arrow_both :
line.style_solid
// Show Lines and colors
show_dh = input.bool(defval=true, title="-", group="Timeframe 1 High, Low, Open and Close Lines", inline="TF 1 Select Line")
dhcolor = input(color.rgb(133, 245, 86, 30), title="High ", group="Timeframe 1 High, Low, Open and Close Lines", inline="TF 1 Select Line")
show_dl = input.bool(defval=true, title="-", group="Timeframe 1 High, Low, Open and Close Lines", inline="TF 1 Select Line")
dlcolor = input(color.rgb(246, 135, 135, 30), title="Low ", group="Timeframe 1 High, Low, Open and Close Lines", inline="TF 1 Select Line")
show_do = input.bool(defval=true, title="-", group="Timeframe 1 High, Low, Open and Close Lines", inline="TF 1 Select Line")
docolor = input(color.rgb(120, 167, 241, 30), title="Open ", group="Timeframe 1 High, Low, Open and Close Lines", inline="TF 1 Select Line")
show_dc = input.bool(defval=true, title="-", group="Timeframe 1 High, Low, Open and Close Lines", inline="TF 1 Select Line")
dccolor = input(color.rgb(246, 221, 96, 30), title="Close ", group="Timeframe 1 High, Low, Open and Close Lines", inline="TF 1 Select Line")
// TF 1 label options
// Show labels and colors
show_dhlocLabel = input(defval=true, title="Show Timeframe 1 Labels? ", group="Timeframe 1 Label Options", inline="TF 1")
show_dVal = input.bool(defval=true, title="Show Timeframe 1 Line Value? ", group="Timeframe 1 Label Options", inline="TF 1")
dLblHOffset = input.int(0, title="Horizontal Offset - ", group="Timeframe 1 Label Options", inline="TF 1 offsets")
dLblVOffset = input(.05, title=" Vertical Offset - ", group="Timeframe 1 Label Options", inline="TF 1 offsets")
// Size and style drop down
dSizeOption = input.string(defval="Normal", title="Label Size - ", options = ["Auto","Huge","Large","Normal","Small","Tiny"], group="Timeframe 1 Label Options", inline="TF 1 options")
dStyleOption = input.string(title=" Label Style - ", options=["Triangle up (▲)", "Triangle down (▼)",
"Label up (⬆)", "Label down (⬇)", "Plus (+)", "Text Outline", "None"], defval="Text Outline", group="Timeframe 1 Label Options", inline="TF 1 options")
dLabelStyle = (dStyleOption == "Triangle up (▲)") ? label.style_triangleup :
(dStyleOption == "Triangle down (▼)") ? label.style_triangledown :
(dStyleOption == "Label up (⬆)") ? label.style_label_up :
(dStyleOption == "Label down (⬇)") ? label.style_label_down :
(dStyleOption == "Plus (+)") ? label.style_cross:
(dStyleOption == "Text Outline") ? label.style_text_outline:
(dStyleOption == "None") ? label.style_none :
label.style_label_down
dLabelSize = (dSizeOption == "Huge") ? size.huge :
(dSizeOption == "Large") ? size.large :
(dSizeOption == "Small") ? size.small :
(dSizeOption == "Tiny") ? size.tiny :
(dSizeOption == "Auto") ? size.auto :
size.normal
dHighLblClr = input(color.rgb(00,153,00,80), title= "High Color ", group="Timeframe 1 Label Options", inline="TF 1 label colors")
dLowLblClr = input(color.rgb(204,00,00,80), title= "Low Color ", group="Timeframe 1 Label Options", inline="TF 1 label colors")
dOpenLblClr = input(color.rgb(00,102,204,80), title= "Open Color ", group="Timeframe 1 Label Options", inline="TF 1 label colors")
dCloseLblClr = input(color.rgb(255,153,51,80), title= "Close Color ", group="Timeframe 1 Label Options", inline="TF 1 label colors")
////// TF 2 line and label options ////
// Show Lines and colors
show_whloc = input.bool(defval=true, title=" Show Timeframe 2 Line?", group="Timeframe 2 High, Low, Open and Close Lines", inline="TF 2 Line")
tf_2 = input.timeframe('D', title="Timeframe 2 - ", group="Timeframe 2 High, Low, Open and Close Lines", inline="TF 2")
tf_2_m = input.int(1, title=" TF Lookback - ", tooltip="Input the number of TF units selected in the drop-down menu you want to lookback. 0 is current candle where 1 and higher will lookback. Example: You select 1 hour in the drop-down menu with a lookback number of 2, lines will be drawn on hourly data from 2 candles back",
group="Timeframe 2 High, Low, Open and Close Lines", inline="TF 2")
// Line style and size
wLineWidth = input.int(1, title="Line Width - ", minval=1, group="Timeframe 2 High, Low, Open and Close Lines", inline="TF 2 Line Style")
wLineStyleOption = input.string(defval="solid (─)",title=" Line Style - ",
options=["solid (─)", "dotted (┈)", "dashed (╌)",
"arrow left (←)", "arrow right (→)", "arrows both (↔)"],
group="Timeframe 2 High, Low, Open and Close Lines", inline="TF 2 Line Style")
wLineStyle = (wLineStyleOption == "dotted (┈)") ? line.style_dotted :
(wLineStyleOption == "dashed (╌)") ? line.style_dashed :
(wLineStyleOption == "arrow left (←)") ? line.style_arrow_left :
(wLineStyleOption == "arrow right (→)") ? line.style_arrow_right :
(wLineStyleOption == "arrows both (↔)") ? line.style_arrow_both :
line.style_solid
show_wh = input.bool(defval=true, title="-", group="Timeframe 2 High, Low, Open and Close Lines", inline="TF 2 Select Line")
whcolor = input(color.rgb(133, 245, 86, 30), title="High ", group="Timeframe 2 High, Low, Open and Close Lines", inline="TF 2 Select Line")
show_wl = input.bool(defval=true, title="-", group="Timeframe 2 High, Low, Open and Close Lines", inline="TF 2 Select Line")
wlcolor = input(color.rgb(246, 135, 135, 30), title="Low ", group="Timeframe 2 High, Low, Open and Close Lines", inline="TF 2 Select Line")
show_wo = input.bool(defval=true, title="-", group="Timeframe 2 High, Low, Open and Close Lines", inline="TF 2 Select Line")
wocolor = input(color.rgb(120, 167, 241, 30), title="Open ", group="Timeframe 2 High, Low, Open and Close Lines", inline="TF 2 Select Line")
show_wc = input.bool(defval=true, title="-", group="Timeframe 2 High, Low, Open and Close Lines", inline="TF 2 Select Line")
wccolor = input(color.rgb(246, 221, 96, 30), title="Close ", group="Timeframe 2 High, Low, Open and Close Lines", inline="TF 2 Select Line")
// TF 2 label options
// Show labels and colors
show_whlocLabel = input(defval=true, title="Show Timeframe 2 Labels? ", group="Timeframe 2 Label Options", inline="TF 2")
show_wVal = input.bool(defval=true, title="Show Timeframe 2 Line Value? ", group="Timeframe 2 Label Options", inline="TF 2")
wLblHOffset = input.int(0, title="Horizontal Offset - ", group="Timeframe 2 Label Options", inline="TF 2 offsets")
wLblVOffset = input(.05, title=" Vertical Offset - ", group="Timeframe 2 Label Options", inline="TF 2 offsets")
// Size and style drop down
wSizeOption = input.string(defval="Normal", title="Label Size - ", options = ["Auto","Huge","Large","Normal","Small","Tiny"], group="Timeframe 2 Label Options", inline="TF 2 options")
wStyleOption = input.string(title=" Label Style - ", options=["Triangle up (▲)", "Triangle down (▼)",
"Label up (⬆)", "Label down (⬇)", "Plus (+)", "Text Outline", "None"], defval="Text Outline", group="Timeframe 2 Label Options", inline= "TF 2 options")
wLabelStyle = (wStyleOption == "Triangle up (▲)") ? label.style_triangleup :
(wStyleOption == "Triangle down (▼)") ? label.style_triangledown :
(wStyleOption == "Label up (⬆)") ? label.style_label_up :
(wStyleOption == "Label down (⬇)") ? label.style_label_down :
(wStyleOption == "Plus (+)") ? label.style_cross:
(wStyleOption == "Text Outline") ? label.style_text_outline:
(wStyleOption == "None") ? label.style_none :
label.style_label_down
wLabelSize = (wSizeOption == "Huge") ? size.huge :
(wSizeOption == "Large") ? size.large :
(wSizeOption == "Small") ? size.small :
(wSizeOption == "Tiny") ? size.tiny :
(wSizeOption == "Auto") ? size.auto :
size.normal
wHighLblClr = input(color.rgb(00,153,00,80), title= "High Color ", group="Timeframe 2 Label Options", inline="weekly label colors")
wLowLblClr = input(color.rgb(204,00,00,80), title= "Low Color ", group="Timeframe 2 Label Options", inline="weekly label colors")
wOpenLblClr = input(color.rgb(00,102,204,80), title= "Open Color ", group="Timeframe 2 Label Options", inline="weekly label colors")
wCloseLblClr = input(color.rgb(255,153,51,80), title= "Close Color ", group="Timeframe 2 Label Options", inline="weekly label colors")
////// TF 3 line and label options ////
// Show Lines and colors
show_mhloc = input.bool(defval=true, title=" Show Timeframe 3 Line?", group="Timeframe 3 High, Low, Open and Close Lines", inline="TF 3 Line")
tf_3 = input.timeframe('W', title="Timeframe 3 - ", group="Timeframe 3 High, Low, Open and Close Lines", inline="TF 3")
tf_3_m = input.int(1, title=" TF Lookback - ", tooltip="Input the number of TF units selected in the drop-down menu you want to lookback. 0 is current candle where 1 and higher will lookback. Example: You select 1 hour in the drop-down menu with a lookback number of 2, lines will be drawn on hourly data from 2 candles back",
group="Timeframe 3 High, Low, Open and Close Lines", inline="TF 3")
// Line style and size
mLineWidth = input.int(1, title="Line Width - ", minval=1, group="Timeframe 3 High, Low, Open and Close Lines", inline="TF 3 Line Style")
mLineStyleOption = input.string(defval="solid (─)",title=" Line Style - ",
options=["solid (─)", "dotted (┈)", "dashed (╌)",
"arrow left (←)", "arrow right (→)", "arrows both (↔)"],
group="Timeframe 3 High, Low, Open and Close Lines", inline="TF 3 Line Style")
mLineStyle = (mLineStyleOption == "dotted (┈)") ? line.style_dotted :
(mLineStyleOption == "dashed (╌)") ? line.style_dashed :
(mLineStyleOption == "arrow left (←)") ? line.style_arrow_left :
(mLineStyleOption == "arrow right (→)") ? line.style_arrow_right :
(mLineStyleOption == "arrows both (↔)") ? line.style_arrow_both :
line.style_solid
show_mh = input.bool(defval=true, title="-", group="Timeframe 3 High, Low, Open and Close Lines", inline="Select Line")
mhcolor = input(color.rgb(133, 245, 86, 30), title="High ", group="Timeframe 3 High, Low, Open and Close Lines", inline="Select Line")
show_ml = input.bool(defval=true, title="-", group="Timeframe 3 High, Low, Open and Close Lines", inline="Select Line")
mlcolor = input(color.rgb(246, 135, 135, 30), title="Low ", group="Timeframe 3 High, Low, Open and Close Lines", inline="Select Line")
show_mo = input.bool(defval=true, title="-", group="Timeframe 3 High, Low, Open and Close Lines", inline="Select Line")
mocolor = input(color.rgb(120, 167, 241, 30), title="Open ", group="Timeframe 3 High, Low, Open and Close Lines", inline="Select Line")
show_mc = input.bool(defval=true, title="-", group="Timeframe 3 High, Low, Open and Close Lines", inline="Select Line")
mccolor = input(color.rgb(246, 221, 96, 30), title="Close ", group="Timeframe 3 High, Low, Open and Close Lines", inline="Select Line")
// TF 3 label options
// Show labels and colors
show_mhlocLabel = input(defval=true, title="Show Timeframe 3 Labels? ", group="Timeframe 3 Label Options", inline="TF 3")
show_mVal = input.bool(defval=true, title="Show Timeframe 3 Line Value? ", group="Timeframe 3 Label Options", inline="TF 3")
mLblHOffset = input.int(0, title="Horizontal Offset - ", group="Timeframe 3 Label Options", inline="TF 3 offsets")
mLblVOffset = input(.05, title="Vertical Offset - ", group="Timeframe 3 Label Options", inline="TF 3 offsets")
// Size and style drop down
mSizeOption = input.string(defval="Normal", title="Label Size - ", options = ["Auto","Huge","Large","Normal","Small","Tiny"], group="Timeframe 3 Label Options", inline="TF 3 Options")
mStyleOption = input.string(title=" Label Style - ", options=["Triangle up (▲)", "Triangle down (▼)",
"Label up (⬆)", "Label down (⬇)", "Plus (+)", "Text Outline", "None"], defval="Text Outline",group="Timeframe 3 Label Options", inline="TF 3 Options")
mLabelStyle = (mStyleOption == "Triangle up (▲)") ? label.style_triangleup :
(mStyleOption == "Triangle down (▼)") ? label.style_triangledown :
(mStyleOption == "Label up (⬆)") ? label.style_label_up :
(mStyleOption == "Label down (⬇)") ? label.style_label_down :
(mStyleOption == "Plus (+)") ? label.style_cross:
(mStyleOption == "Text Outline") ? label.style_text_outline:
(mStyleOption == "None") ? label.style_none :
label.style_label_down
mLabelSize = (mSizeOption == "Huge") ? size.huge :
(mSizeOption == "Large") ? size.large :
(mSizeOption == "Small") ? size.small :
(mSizeOption == "Tiny") ? size.tiny :
(mSizeOption == "Auto") ? size.auto :
size.normal
mHighLblClr = input(color.rgb(00,153,00,80), title= "High Color ", group="Timeframe 3 Label Options", inline="TF 3 label colors")
mLowLblClr = input(color.rgb(204,00,00,80), title= "Low Color ", group="Timeframe 3 Label Options", inline="TF 3 label colors")
mOpenLblClr = input(color.rgb(00,102,204,80), title= "Open Color ", group="Timeframe 3 Label Options", inline="TF 3 label colors")
mCloseLblClr = input(color.rgb(255,153,51,80), title= "Close Color ", group="Timeframe 3 Label Options", inline="TF 3 label colors")
////////HLOC Lines and Label Plots///////
// TF 1 HLOC
// Call TF 1 data
dhigh = request.security(t, tf_1, high[tf_1_m])
dlow = request.security(t, tf_1, low[tf_1_m])
dopen = request.security(t, tf_1, open[tf_1_m])
dclose = request.security(t, tf_1, close[tf_1_m])
// Line Conditions
if (show_dhloc)
if (show_dh)
dh_line = line.new(x1=bar_index-1, y1=dhigh, color=dhcolor, x2=bar_index, y2=dhigh, xloc=xloc.bar_index, style=dLineStyle, width=dLineWidth , extend=extend.both)
line.delete(dh_line[1])
if (show_dl)
dl_line = line.new(x1=bar_index-1, y1=dlow, color=dlcolor, x2=bar_index, y2=dlow, xloc=xloc.bar_index, style=dLineStyle, width=dLineWidth , extend=extend.both)
line.delete(dl_line[1])
if (show_do)
do_line = line.new(x1=bar_index-1, y1=dopen, color=docolor, x2=bar_index, y2=dopen, xloc=xloc.bar_index, style=dLineStyle, width=dLineWidth , extend=extend.both)
line.delete(do_line[1])
if (show_dc)
dc_line = line.new(x1=bar_index-1, y1=dclose, color=dccolor, x2=bar_index, y2=dclose, xloc=xloc.bar_index, style=dLineStyle, width=dLineWidth , extend=extend.both)
line.delete(dc_line[1])
// TF 1 Labels //
// Label Value String
dHigh = str.tostring(dhigh, format.mintick)
dhValNa = " "
string dhVal = if show_dVal
dHigh
else
dhValNa
dLow = str.tostring(dlow, format.mintick)
dlValNa = " "
string dlVal = if show_dVal
dLow
else
dlValNa
dOpen = str.tostring(dopen, format.mintick)
doValNa = " "
string doVal = if show_dVal
dOpen
else
doValNa
dClose = str.tostring(dclose, format.mintick)
dcValNa = " "
string dcVal = if show_dVal
dClose
else
dcValNa
// Label Conditions
if (show_dhlocLabel) and (show_dhloc)
if (show_dh)
dHighLabel = label.new(x=bar_index-1, y=dhigh, xloc=xloc.bar_index[0],
color=(dHighLblClr), textcolor=dhcolor,
style=dLabelStyle)
label.set_text(id=dHighLabel, text= str.tostring(tf_1) + " High " + str.tostring(dhVal))
label.set_size(dHighLabel,dLabelSize)
label.set_y(dHighLabel, dhigh + dLblVOffset)
label.set_x(dHighLabel, label.get_x(dHighLabel) + dLblHOffset)
label.delete(dHighLabel[1])
if (show_dl)
dlowLabel = label.new(x=bar_index-1, y=dlow, xloc=xloc.bar_index[0],
color=(dLowLblClr), textcolor=dlcolor,
style=dLabelStyle)
label.set_text(id=dlowLabel, text=str.tostring(tf_1) + " Low " + str.tostring(dlVal))
label.set_size(dlowLabel,dLabelSize)
label.set_y(dlowLabel, dlow - dLblVOffset)
label.set_x(dlowLabel, label.get_x(dlowLabel) + dLblHOffset)
label.delete(dlowLabel[1])
if (show_do)
dopenLabel = label.new(x=bar_index-1, y=dopen, xloc=xloc.bar_index[0],
color=(dOpenLblClr), textcolor=docolor,
style=dLabelStyle)
label.set_text(id=dopenLabel, text=str.tostring(tf_1) + " Open " + str.tostring(doVal))
label.set_size(dopenLabel,dLabelSize)
label.set_y(dopenLabel, dopen + dLblVOffset)
label.set_x(dopenLabel, label.get_x(dopenLabel) + dLblHOffset)
label.delete(dopenLabel[1])
if (show_dc)
dcloseLabel = label.new(x=bar_index-1, y=dclose, xloc=xloc.bar_index[0],
color=(dCloseLblClr), textcolor=dccolor,
style=dLabelStyle)
label.set_text(id=dcloseLabel, text=str.tostring(tf_1) + " Close " + str.tostring(dcVal))
label.set_size(dcloseLabel,dLabelSize)
label.set_y(dcloseLabel, dclose - dLblVOffset)
label.set_x(dcloseLabel, label.get_x(dcloseLabel) + dLblHOffset)
label.delete(dcloseLabel[1])
// TF 2 HLOC
// Call weekly data
whigh = request.security(t, tf_2, high[tf_2_m])
wlow = request.security(t, tf_2, low[tf_2_m])
wopen = request.security(t, tf_2, open[tf_2_m])
wclose = request.security(t, tf_2, close[tf_2_m])
// Line Condition
if (show_whloc)
if (show_wh)
wh_line = line.new(x1=bar_index-1, y1=whigh, color=whcolor, x2=bar_index, y2=whigh, xloc=xloc.bar_index, style=wLineStyle, width=wLineWidth , extend=extend.both)
line.delete(wh_line[1])
if (show_wl)
wl_line = line.new(x1=bar_index-1, y1=wlow, color=wlcolor, x2=bar_index, y2=wlow, xloc=xloc.bar_index, style=wLineStyle, width=wLineWidth , extend=extend.both)
line.delete(wl_line[1])
if (show_wo)
wo_line = line.new(x1=bar_index-1, y1=wopen, color=wocolor, x2=bar_index, y2=wopen, xloc=xloc.bar_index, style=wLineStyle, width=wLineWidth , extend=extend.both)
line.delete(wo_line[1])
if (show_wc)
wc_line = line.new(x1=bar_index-1, y1=wclose, color=wccolor, x2=bar_index, y2=wclose, xloc=xloc.bar_index, style=wLineStyle, width=wLineWidth , extend=extend.both)
line.delete(wc_line[1])
// TF 2 Labels//
// Label Value String
wHigh = str.tostring(whigh, format.mintick)
whValNa = " "
string whVal = if show_wVal
wHigh
else
whValNa
wLow = str.tostring(wlow, format.mintick)
wlValNa = " "
string wlVal = if show_wVal
wLow
else
wlValNa
wOpen = str.tostring(wopen, format.mintick)
woValNa = " "
string woVal = if show_wVal
wOpen
else
woValNa
wClose = str.tostring(wclose, format.mintick)
wcValNa = " "
string wcVal = if show_wVal
wClose
else
wcValNa
// Label Conditions
if (show_whlocLabel) and (show_whloc)
if (show_wh)
wHighLabel = label.new(x=bar_index-1, y=whigh, xloc=xloc.bar_index[0],
color=(wHighLblClr), textcolor=whcolor,
style=wLabelStyle)
label.set_text(id=wHighLabel, text=str.tostring(tf_2) + " High " + str.tostring(whVal))
label.set_size(wHighLabel,wLabelSize)
label.set_y(wHighLabel, whigh + wLblVOffset)
label.set_x(wHighLabel, label.get_x(wHighLabel) + wLblHOffset)
label.delete(wHighLabel[1])
if (show_wl)
wlowLabel = label.new(x=bar_index-1, y=wlow, xloc=xloc.bar_index[0],
color=(wLowLblClr), textcolor=wlcolor,
style=wLabelStyle)
label.set_text(id=wlowLabel, text=str.tostring(tf_2) + " Low " + str.tostring(wlVal))
label.set_size(wlowLabel,wLabelSize)
label.set_y(wlowLabel, wlow - wLblVOffset)
label.set_x(wlowLabel, label.get_x(wlowLabel) + wLblHOffset)
label.delete(wlowLabel[1])
if (show_wo)
wopenLabel = label.new(x=bar_index-1, y=wopen, xloc=xloc.bar_index[0],
color=(wOpenLblClr), textcolor=wocolor,
style=wLabelStyle)
label.set_text(id=wopenLabel, text=str.tostring(tf_2) + " Open " + str.tostring(woVal))
label.set_size(wopenLabel,wLabelSize)
label.set_y(wopenLabel, wopen + wLblVOffset)
label.set_x(wopenLabel, label.get_x(wopenLabel) + wLblHOffset)
label.delete(wopenLabel[1])
if (show_wc)
wcloseLabel = label.new(x=bar_index-1, y=wclose, xloc=xloc.bar_index[0],
color=(wCloseLblClr), textcolor=wccolor,
style=wLabelStyle)
label.set_text(id=wcloseLabel, text=str.tostring(tf_2) + " Close " + str.tostring(wcVal))
label.set_size(wcloseLabel,wLabelSize)
label.set_y(wcloseLabel, wclose - wLblVOffset)
label.set_x(wcloseLabel, label.get_x(wcloseLabel) + wLblHOffset)
label.delete(wcloseLabel[1])
// TF 3 HLOC //
// Call TF 3 data
mhigh = request.security(t, tf_3, high[tf_3_m])
mlow = request.security(t, tf_3, low[tf_3_m])
mopen = request.security(t, tf_3, open[tf_3_m])
mclose = request.security(t, tf_3, close[tf_3_m])
// Line Condition
if (show_mhloc)
if (show_mh)
mh_line = line.new(x1=bar_index-1, y1=mhigh, color=mhcolor, x2=bar_index, y2=mhigh, xloc=xloc.bar_index, style=mLineStyle, width=mLineWidth , extend=extend.both)
line.delete(mh_line[1])
if (show_ml)
ml_line = line.new(x1=bar_index-1, y1=mlow, color=mlcolor, x2=bar_index, y2=mlow, xloc=xloc.bar_index, style=mLineStyle, width=mLineWidth , extend=extend.both)
line.delete(ml_line[1])
if (show_mo)
mo_line = line.new(x1=bar_index-1, y1=mopen, color=mocolor, x2=bar_index, y2=mopen, xloc=xloc.bar_index, style=mLineStyle, width=mLineWidth , extend=extend.both)
line.delete(mo_line[1])
if (show_mc)
mc_line = line.new(x1=bar_index-1, y1=mclose, color=mccolor, x2=bar_index, y2=mclose, xloc=xloc.bar_index, style=mLineStyle, width=mLineWidth , extend=extend.both)
line.delete(mc_line[1])
// TF 3 Labels //
// Label Value String
mHigh = str.tostring(mhigh, format.mintick)
mhValNa = " "
string mhVal = if show_mVal
mHigh
else
mhValNa
mLow = str.tostring(mlow, format.mintick)
mlValNa = " "
string mlVal = if show_mVal
mLow
else
mlValNa
mOpen = str.tostring(mopen, format.mintick)
moValNa = " "
string moVal = if show_mVal
mOpen
else
moValNa
mClose = str.tostring(mclose, format.mintick)
mcValNa = " "
string mcVal = if show_mVal
mClose
else
mcValNa
// Label Condition
if (show_mhlocLabel) and (show_mhloc)
if (show_mh)
mHighLabel = label.new(x=bar_index-1, y=mhigh, xloc=xloc.bar_index[0],
color=(mHighLblClr), textcolor=mhcolor,
style=mLabelStyle)
label.set_text(id=mHighLabel, text=str.tostring(tf_3) +" High " + str.tostring(mhVal))
label.set_size(mHighLabel,mLabelSize)
label.set_y(mHighLabel, mhigh + mLblVOffset)
label.set_x(mHighLabel, label.get_x(mHighLabel) + mLblHOffset)
label.delete(mHighLabel[1])
if (show_ml)
mlowLabel = label.new(x=bar_index-1, y=mlow, xloc=xloc.bar_index[0],
color=(mLowLblClr), textcolor=mlcolor,
style=mLabelStyle)
label.set_text(id=mlowLabel, text=str.tostring(tf_3) + " Low " + str.tostring(mlVal))
label.set_size(mlowLabel,mLabelSize)
label.set_y(mlowLabel, mlow - mLblVOffset)
label.set_x(mlowLabel, label.get_x(mlowLabel) + mLblHOffset)
label.delete(mlowLabel[1])
if (show_mo)
mopenLabel = label.new(x=bar_index-1, y=mopen, xloc=xloc.bar_index[0],
color=(mOpenLblClr), textcolor=mocolor,
style=mLabelStyle)
label.set_text(id=mopenLabel, text=str.tostring(tf_3) + " Open " + str.tostring(moVal))
label.set_size(mopenLabel,mLabelSize)
label.set_y(mopenLabel, mopen + mLblVOffset)
label.set_x(mopenLabel, label.get_x(mopenLabel) + mLblHOffset)
label.delete(mopenLabel[1])
if (show_mc)
mcloseLabel = label.new(x=bar_index-1, y=mclose, xloc=xloc.bar_index[0],
color=(mCloseLblClr), textcolor=mccolor,
style=mLabelStyle)
label.set_text(id=mcloseLabel, text=str.tostring(tf_3) + " Close " + str.tostring(mcVal))
label.set_size(mcloseLabel,mLabelSize)
label.set_y(mcloseLabel, mclose - mLblVOffset)
label.set_x(mcloseLabel, label.get_x(mcloseLabel) + mLblHOffset)
label.delete(mcloseLabel[1])
|
Regression Channel Alternative MTF V2 | https://www.tradingview.com/script/anklcF4a-Regression-Channel-Alternative-MTF-V2/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 263 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RozaniGhani-RG
//@version=5
indicator('Regression Channel Alternative MTF V2', shorttitle = 'RCAMV2', overlay = true)
// 0. Inputs
// 1. Types
// 2. Variables
// 3. Arrays
// 4. Switches
// 5. Custom Functions
// 6. Final Calculations
// 7. Constructs
//#region ———————————————————— 0. Inputs
G0 = 'Enable Regression Channel'
G1 = 'Timeframe Table'
G2 = 'Helper'
T1 = 'TF reference applicable to HIGHER, PRIMARY, LOWER and LOWEST'
T2 = 'Otherwise use TF color'
T3 = 'Affect both label and table'
bool0 = input.bool( true, '1', group = G0, inline = '0')
bool1 = input.bool( true, '2', group = G0, inline = '0')
bool2 = input.bool( true, '3', group = G0, inline = '0', tooltip = T1)
i_c_dir = input.bool( false, 'Use Direction Color', group = G0, tooltip = T2)
i_s_dir = input.string( 'Full', 'Direction text', group = G0, tooltip = T3, options = ['Up-Down', 'Up-Dn', 'Arrow', 'Full'])
i_s_font = input.string('normal', 'Font size', group = G0, tooltip = T3, options = ['tiny', 'small', 'normal', 'large', 'huge'])
i_b_TF = input.bool( true, '', group = G1, inline = '1')
i_s_Y = input.string('bottom', '', group = G1, inline = '1', options = ['top', 'middle', 'bottom'])
i_s_X = input.string( 'left', '', group = G1, inline = '1', options = ['left', 'center', 'right'])
helpLine = input.bool( false, 'Line', group = G2, inline = '2')
helpTbl = input.bool( false, 'Table', group = G2, inline = '2')
//#endregion
//#region ———————————————————— 1. Types
// @type Used for int
// @field hi Int value for hi
// @field md Int value for md
// @field lo Int value for lo
type length
int hi = na
int md = na
int lo = na
// @type Used for string
// @field hi String value for hi
// @field md String value for md
// @field lo String value for lo
type name
string hi = na
string md = na
string lo = na
// @type Used for color
// @field hi Color value for hi
// @field md Color value for md
// @field lo Color value for lo
type pastel
color hi = na
color md = na
color lo = na
// @type Used for color
// @field scenario Values such as POSITION, SWING and INTRADAY
// @field period Values such as HIGHER, PRIMARY, LOW and LOWEST
// @field timeframe Values sudh W, D, 60, 15, 5 and 1
// @field len Int values based on timeframe
// @field thick Linewidth thickness based on timeframe
// @field palette Color for line
type found
string scenario = na
name period = na
name timeframe = na
length len = na
length thick = na
pastel palette = na
// @type Regression Type
// @field startY Price for Start Regression
// @field endY Price for End Regression
// @field dev Standard Deviation
// @field slope Regression Slope
type reg
float startY = na
float endY = na
float dev = na
float slope = na
//#endregion
//#region ———————————————————— 2. Variables
clockW = name.new( 'W', 'D','60'), LW = length.new( 100, 20, 4), HPL = name.new( 'HIGHER', 'PRIMARY', 'LOWER'), W123 = length.new(1, 2, 3), FBP = pastel.new(chart.fg_color, color.blue, color.purple)
clockD = name.new( 'W', 'D','60'), LD = length.new( 465,100, 12)
clock60 = name.new( 'D','60','15'), L60 = length.new( 700,100, 28)
clock15 = name.new('60','15', '5'), L15 = length.new( 356,100, 33)
clock05 = name.new('15', '5', '1'), L05 = length.new( 300,100, 22), W234 = length.new(2, 3, 4), BPY = pastel.new( color.blue, color.purple, color.yellow)
clock01 = name.new('15', '5', '1'), L01 = length.new(1461,479,100), PLL = name.new('PRIMARY', 'LOWER', 'LOWEST'), NBN = pastel.new(color.new(color.blue, 100), color.blue, na)
clock00 = name.new( na, na, na), L00 = length.new( 100,100,100), NNA = name.new( na, 'PRIMARY', na), W111 = length.new(1, 1, 1)
var tbl = table.new(i_s_Y + '_' + i_s_X, 20, 10, border_width = 1)
var hpTbl = table.new(position.middle_center, 4, 4, border_width = 1)
//#endregion
//#region ———————————————————— 3. Arrays
var lineTF0 = array.new<line>(3), var labelTF0 = array.new<label>(1), var lineHelp0 = array.new<line>(3), var labelHelp0 = array.new<label>(1)
var lineTF1 = array.new<line>(3), var labelTF1 = array.new<label>(1), var lineHelp1 = array.new<line>(3), var labelHelp1 = array.new<label>(1)
var lineTF2 = array.new<line>(3), var labelTF2 = array.new<label>(1), var lineHelp2 = array.new<line>(3), var labelHelp2 = array.new<label>(1)
boolTF = array.new_bool(6)
for i = 0 to 5
boolTF.set(0, timeframe.period == 'W')
boolTF.set(1, timeframe.period == 'D')
boolTF.set(2, timeframe.period == '60')
boolTF.set(3, timeframe.period == '15')
boolTF.set(4, timeframe.period == '5')
boolTF.set(5, timeframe.period == '1')
PSI = array.from('POSITION', 'SWING', 'INTRADAY')
TFF = array.from( 'HIGHER', 'PRIMARY', 'LOWER')
DCP = array.from( 'DISTAL', 'CLEAR', 'PROXIMATE')
WDS = array.from( 'W', 'D', '60')
DSF = array.from( 'D', '60', '15')
SFF = array.from( '60', '15', '5')
m = matrix.new<string>(4, 4), m.set(0, 0, '')
for i = 0 to 2
m.set(i + 1, 0, PSI.get(i))
m.set(i + 1, 1, WDS.get(i))
m.set(i + 1, 2, DSF.get(i))
m.set(i + 1, 3, SFF.get(i))
m.set( 0, i + 1, TFF.get(i) + ' / ' + DCP.get(i))
//#endregion
//#region ———————————————————— 4. Switches
[scenarioTF, periodTF, clockTF, lenTF, widthTF, colorTF] = switch timeframe.period
'W' => ['POSITION', HPL, clockW , LW, W123, FBP]
'D' => ['POSITION', HPL, clockD , LD, W123, FBP]
'60' => [ 'SWING', HPL, clock60, L60, W123, FBP]
'15' => ['INTRADAY', HPL, clock15, L15, W123, FBP]
'5' => ['INTRADAY', HPL, clock05, L05, W234, BPY]
'1' => ['INTRADAY', PLL, clock01, L01, W234, BPY]
=> [ na, PLL, clock00, L00, W111, NBN]
[strUP, strDN] = switch i_s_dir
'Up-Down' => [ 'UP ', 'DOWN']
'Up-Dn' => [ 'UP ', 'DN']
'Arrow' => [ '▲', '▼']
'Full' => [' UP ▲', 'DOWN ▼']
//#endregion
//#region ———————————————————— 5. Custom Functions
// @function calculateRegression
// @param Int value of len
// @returns Channel values of reg type
calculateRegression(int len = 100) =>
mid = math.sum( close, len) / len
slope = ta.linreg(close, len, 0) - ta.linreg(close, len, 1)
startY = mid - slope * math.floor(len / 2) + (1 - len % 2) / 2 * slope
endY = startY + slope * (len - 1)
dev = 0.0
for x = 0 to len - 1
dev += math.pow(close[x] - (slope * (len - x) + startY), 2)
dev
dev := math.sqrt(dev / len)
channel = reg.new(startY, endY, dev, slope)
channel
// @function createLine
// @param id, TF, foundTF, i, ref
// @returns regression line
method createLine(line[] id = na, bool enable = na, reg TF = na, found foundTF = na, int i = na, int ref = na, bool trendcolor = na) =>
if enable
[x, c, w] = switch ref
0 => [foundTF.len.hi, foundTF.palette.hi, foundTF.thick.hi]
1 => [foundTF.len.md, foundTF.palette.md, foundTF.thick.md]
2 => [foundTF.len.lo, foundTF.palette.lo, foundTF.thick.lo]
col = switch trendcolor
true => TF.slope > 0 ? color.lime : color.red
false => c
line.delete(id.get(i))
id.set(i, line.new(
x1 = bar_index - (x - 1),
y1 = TF.startY + TF.dev * 2 * (i - 1),
x2 = bar_index,
y2 = TF.endY + TF.dev * 2 * (i - 1),
style = i % 2 == 1 ? line.style_dashed : line.style_solid,
color = col,
width = w))
id
// @function createHelpLine
// @param id, TF, foundTF, ref
// @returns Helper Line
method createHelpLine(line[] id = na, bool enable = na, reg TF = na, found foundTF = na, int ref = na) =>
if enable
[x, c] = switch ref
0 => [foundTF.len.hi, foundTF.palette.hi]
1 => [foundTF.len.md, foundTF.palette.md]
2 => [foundTF.len.lo, foundTF.palette.lo]
line.delete(id.get(0))
id.set(0, line.new(
x1 = bar_index - (x - 1),
y1 = TF.startY + TF.dev * -2,
x2 = bar_index,
y2 = TF.startY + TF.dev * -2,
color = c,
style = line.style_arrow_both))
id
// @function createLabel
// @param id, TF, foundTF, ref, size
// @returns regression label
method createLabel(label[] id = na, bool enable = na, reg TF = na, found foundTF = na, int ref = na, string size = na) =>
if enable
[x, strPeriod, strTF] = switch ref
0 => [foundTF.len.hi, foundTF.period.hi, foundTF.timeframe.hi]
1 => [foundTF.len.md, foundTF.period.md, foundTF.timeframe.md]
2 => [foundTF.len.lo, foundTF.period.lo, foundTF.timeframe.lo]
label.delete(id.get(0))
id.set(0, label.new(
x = bar_index - (x - 1),
y = TF.startY + TF.dev * 2 * (TF.slope > 0 ? 1 : -1),
text = strPeriod + '\n'+ strTF + '\n'+ (TF.slope > 0 ? strUP : strDN),
color = color.new(color.blue, 100),
style = TF.slope > 0 ? label.style_label_lower_right : label.style_label_upper_right,
textcolor = TF.slope > 0 ? color.lime : color.red,
size = size))
id
// @function createHelpLabel
// @param id, TF, foundTF, ref, size
// @returns Helper label
method createHelpLabel(label[] id = na, bool enable = na, reg TF = na, found foundTF = na, int ref = na, string size = na) =>
if enable
[x, strPeriod, strTF, bgTF] = switch ref
0 => [foundTF.len.hi, foundTF.period.hi, foundTF.timeframe.hi, foundTF.palette.hi]
1 => [foundTF.len.md, foundTF.period.md, foundTF.timeframe.md, foundTF.palette.md]
2 => [foundTF.len.lo, foundTF.period.lo, foundTF.timeframe.lo, foundTF.palette.lo]
label.delete(id.get(0))
id.set(0, label.new(
x = int(bar_index - x/2 + 1),
y = TF.startY + TF.dev * -2,
color = color.new(color.blue, 100),
text = strPeriod + '\n'+ strTF + '\n' + str.tostring(x) + ' BARS',
textcolor = bgTF,
size = size))
id
// @function row
// @param id, column, row, _text, size, col, bg
// @returns cell properties
method row(table id = na, int column = na, int row = na, string _text = na,
string size = na, color col = chart.bg_color, color bg = chart.fg_color)=>
id.cell(column, row, _text, text_color = col, text_size = i_s_font, bgcolor = bg)
// @function rowTF
// @param id, row, foundTF, TF, size, ref
// @returns 3 rows of selected TF
method rowTF(table id = na, int row = na, found foundTF = na, reg TF = na, string size = na, int ref = na) =>
[strPeriod, strTF, bgTF] = switch ref
0 => [foundTF.period.hi, foundTF.timeframe.hi, foundTF.palette.hi]
1 => [foundTF.period.md, foundTF.timeframe.md, foundTF.palette.md]
2 => [foundTF.period.lo, foundTF.timeframe.lo, foundTF.palette.lo]
id.row(0, row, strPeriod, size, TF.slope > 0 ? color.lime : color.red, bgTF)
id.row(1, row, strTF, size, TF.slope > 0 ? color.lime : color.red, bgTF)
id.row(2, row, TF.slope > 0 ? strUP : strDN, size, TF.slope > 0 ? color.lime : color.red, bgTF)
//#endregion
//#region ———————————————————— 6. Final Calculations
foundTF = found.new(scenarioTF, periodTF, clockTF, lenTF, widthTF, colorTF)
TF0 = calculateRegression(lenTF.hi)
TF1 = calculateRegression(lenTF.md)
TF2 = calculateRegression(lenTF.lo)
//#endregion
//#region ———————————————————— 7. Contructs
for i = 0 to 2
lineTF0.createLine( bool0, TF0, foundTF, i, 0, i_c_dir)
lineTF1.createLine( bool1, TF1, foundTF, i, 1, i_c_dir)
lineTF2.createLine( bool2, TF2, foundTF, i, 2, i_c_dir)
if boolTF.includes(true)
labelTF0.createLabel(bool0, TF0, foundTF, 0, i_s_font)
labelTF1.createLabel(bool1, TF1, foundTF, 1, i_s_font)
labelTF2.createLabel(bool2, TF2, foundTF, 2, i_s_font)
lineHelp0.createHelpLine(helpLine, TF0, foundTF, 0)
lineHelp1.createHelpLine(helpLine, TF1, foundTF, 1)
lineHelp2.createHelpLine(helpLine, TF2, foundTF, 2)
labelHelp0.createHelpLabel(helpLine, TF0, foundTF, 0, i_s_font)
labelHelp1.createHelpLabel(helpLine, TF1, foundTF, 1, i_s_font)
labelHelp2.createHelpLabel(helpLine, TF2, foundTF, 2, i_s_font)
if barstate.islast
if i_b_TF
if boolTF.includes(true)
tbl.row(0, 0, foundTF.scenario + ' TRADER', i_s_font), tbl.merge_cells(0, 0, 2, 0)
tbl.row(0, 1, 'TIMEFRAME', i_s_font), tbl.merge_cells(0, 1, 1, 1)
tbl.row(2, 1, 'ITEM', i_s_font)
tbl.rowTF(2, foundTF, TF0, i_s_font, 0)
tbl.rowTF(3, foundTF, TF1, i_s_font, 1)
tbl.rowTF(4, foundTF, TF2, i_s_font, 2)
if timeframe.period == '1'
tbl.row(0, 5, 'CHECK PRIMARY', i_s_font, bg = color.new(color.blue, 100)), tbl.merge_cells(0, 5, 2, 5)
tbl.row(0, 6, '', i_s_font, bg = color.new(color.blue, 100))
else
tbl.row(0, 5, '', i_s_font, bg = color.new(color.blue, 100))
else
tbl.row(0, 0, 'TIMEFRAME NOT SUPPORTED FOR MTF', i_s_font, color.red, color.new(color.blue, 100))
tbl.row(0, 1, '', i_s_font, bg = color.new(color.blue, 100))
if helpTbl
for x = 0 to 3
for y = 0 to 3
hpTbl.cell(y, x, m.get(y, x), text_color = color.white, text_size = i_s_font, bgcolor = color.black)
for y = 0 to 3
hpTbl.cell_set_bgcolor(y, 1, color.gray)
hpTbl.cell_set_bgcolor(y, 2, color.blue)
hpTbl.cell_set_bgcolor(y, 3, color.purple)
hpTbl.cell_set_bgcolor(0, 0, color.new(color.blue, 100))
//#endregion |
Cloak & Dagger Heikin-ashi | https://www.tradingview.com/script/92JdLKxz-Cloak-Dagger-Heikin-ashi/ | boitoki | https://www.tradingview.com/u/boitoki/ | 535 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © boitoki
//@version=5
indicator("Cloak & Dagger Heikin-ashi", "CD_HA", overlay=false, scale=scale.right, max_labels_count=500, max_lines_count=500, max_boxes_count=500, max_bars_back=10)
import boitoki/AwesomeColor/13 as ac
import boitoki/Heikinashi/6 as heikinashi
import boitoki/ma_function/5 as ma
import boitoki/Utilities/9 as util
import boitoki/CurrentlyPositionIndicator/5 as cp
/////////////
// Defined //
var mintick = syminfo.mintick
var pips = syminfo.mintick * 10
var icon_bull = '🐂'
var icon_bear = '🐻'
var OPTION_COLOR_X = 'Custom'
var OPTION_MODE_STANDARD = 'Standard heikin-ashi'
var OPTION_MODE_CD = 'Cloak & Dagger'
var OPTION_MODE_C = 'Cloak'
var OPTION_MODE_D = 'Dagger'
var OPTION_BORDER_STYLE1 = '──'
var OPTION_BORDER_STYLE2 = '••••'
var OPTION_BORDER_STYLE3 = '- - -'
var OPTION_LABEL_X = 'None'
var OPTION_LABEL_1 = 'Buy・Sell'
var OPTION_LABEL_5 = 'B・S'
var OPTION_LABEL_2 = 'Long・Short'
var OPTION_LABEL_3 = 'L・S'
var OPTION_LABEL_4 = icon_bull + '・' + icon_bear
var OPTION_ALERT1 = 'Once Per Bar Close'
var OPTION_ALERT2 = 'Once Per Bar'
var FILTER_INSIDE = 0
var FILTER_CLOSE_VS_TB = 1
var FILTER_BALANCE = 2
var FILTER_HOPEN2_VS_HCLOSE = 3
var FILTER_CLOSE_VS_HL = 4
var FILTER_TINY_AND_UNBALANCE = 5
var FILTER_ID_AND_GO = 6
var COLOR_NONE = color.new(#000000, 100)
var GP_DEV = 'Development & Testing'
var i_show_flag = false
///////////////
// Variables //
var bt_filters = array.new<bool>()
////////////
// Inputs //
i_type = input.string('Heikin-Ashi', 'Display', options=['Heikin-Ashi', 'Candles', 'Barcolor', 'None'], group='General')
i_show_candle = i_type == 'Candles'
i_show_heikinashi = i_type == 'Heikin-Ashi'
i_show_barcolor = i_type == 'Barcolor'
i_mode = input.string(OPTION_MODE_CD, 'Mode', options=[OPTION_MODE_CD, OPTION_MODE_C, OPTION_MODE_D, OPTION_MODE_STANDARD], group='General')
i_candle_close = input.string('Signal only', 'Actual Close Level', options=['Always', 'Signal only', 'Never'], group="General")
i_alert_trigger = input.string(OPTION_ALERT1, 'Alert trigger', options=[OPTION_ALERT1, OPTION_ALERT2], group='General')
i_show_triggers = input.bool(true, "Flip", group='Flags', inline='trigger_flip')
i_trigger_label = input.string(OPTION_LABEL_5, '', options=[OPTION_LABEL_X, OPTION_LABEL_1, OPTION_LABEL_5, OPTION_LABEL_2, OPTION_LABEL_3, OPTION_LABEL_4], group='Flags', inline='trigger_flip')
i_show_range_contraction = input.bool(false, 'Range contraction ×', group='Flags') and i_show_triggers
i_show_qqe = input.bool(false, 'QQE triggers', group='Flags') and i_show_triggers
i_show_indicator = input.bool(true, 'Indicator', group='Position indicator', inline='position_indicator')
i_position_ind_placement = input.int(4, '', minval=0, group="Position indicator", inline='position_indicator')
i_show_exections = input.bool(false, 'History', group='Position indicator')
i_ma1_displayed = input.bool(false, '1', inline='ma1', group='MOVING AVERAGE')
i_ma1_source = input.string('open', '', inline='ma1', options=['open', 'close', 'os2', 'hlc3', 'ohlc4'], group='MOVING AVERAGE')
i_ma1_period = input.int(30, '', minval=1, inline='ma1', group='MOVING AVERAGE')
i_ma1_type = input.string('EMA', '', options=['ALMA', 'AMA', 'BWMA', 'DEMA', 'EMA', 'HMA', 'KAMA', 'LSMA', 'MAV', 'RMA', 'SMA', 'SWMA', 'TEMA', 'TMA', 'VWMA', 'WMA', 'ZLEMA'], inline='ma1', group='MOVING AVERAGE')
i_ma1_style = input.string(OPTION_BORDER_STYLE1, '', options=[OPTION_BORDER_STYLE1, OPTION_BORDER_STYLE2, OPTION_BORDER_STYLE3], inline='ma1', group='MOVING AVERAGE')
i_ma2_displayed = input.bool(false, '2', inline='ma2', group='MOVING AVERAGE')
i_ma2_source = input.string('open', '', inline='ma2', options=['open', 'close', 'os2', 'hlc3', 'ohlc4'], group='MOVING AVERAGE')
i_ma2_period = input.int(200, '', minval=1, inline='ma2', group='MOVING AVERAGE')
i_ma2_type = input.string('EMA', '', options=['ALMA', 'AMA', 'DEMA', 'EMA', 'HMA', 'KAMA', 'LSMA', 'MAV', 'RMA', 'SMA', 'SWMA', 'TEMA', 'TMA', 'VWMA', 'WMA', 'ZLEMA'], inline='ma2', group='MOVING AVERAGE')
i_ma2_style = input.string(OPTION_BORDER_STYLE2, '', options=[OPTION_BORDER_STYLE1, OPTION_BORDER_STYLE2, OPTION_BORDER_STYLE3], inline='ma2', group='MOVING AVERAGE')
i_hollow = input.bool(true, 'Hollow candle', group='options')
i_color = input.string('TradingView', 'Color theme', options=[OPTION_COLOR_X,
'TradingView', 'monokai', 'monokaipro', 'panda', 'Gruvbox', 'Spacemacs_light', 'Spacemacs_dark', 'Guardians', 'st3', 'st4',
'gogh_tarascon', 'gogh_crows', 'gogh_cafeterrace',
'frankenthaler_flood', 'frankenthaler_thebay',
'okeeffe_sun', 'okeeffe_reflection', 'okeeffe_lake', 'okeeffe_music',
'grayscale', 'grayscale_light', 'blackscale'
], group='options')
i_color_1 = input.color(color.green , 'Posi color' , group='custom color')
i_color_2 = input.color(color.red , 'Nega color' , group='custom color')
i_color_7 = input.color(color.blue , 'Buy color' , group='custom color')
i_color_8 = input.color(color.red , 'Sell color' , group='custom color')
i_color_4 = input.color(color.orange , 'TP color' , group='custom color')
i_color_5 = input.color(color.purple , 'SL color' , group='custom color')
i_color_6 = input.color(color.gray , 'Default color' , group='custom color')
i_color_3 = input.color(color.aqua , 'MA color' , group='custom color')
i_color_9 = input.color(color.yellow , 'ID box color' , group='custom color')
i_show_idbox = input.bool(false, 'Inside box', group="Options")
///////////
// Types //
type ma
float o
float h
float l
float c
method source (ma this, string name) =>
switch name
'open' => this.o
'close' => this.c
'oc2' => math.avg(this.o, this.h)
'hlc3' => math.avg(this.c, this.h, this.l)
'ohlc4' => math.avg(this.o, this.c, this.h, this.l)
=> this.o
method create (ma this, string ma_type, string ma_source, int length) =>
ma.calc(ma_type, this.source(ma_source), length)
///////////////
// Functions //
f_color (_package, _color, _costomColor = color.gray) =>
switch _package
OPTION_COLOR_X => _costomColor
=> na(ac.package(_package, _color)) ? _costomColor : ac.package(_package, _color)
f_trigger_text_color (_package_name) =>
switch _package_name
'monokai' => [ac.monokai('black'), ac.monokai('white')]
'monokaipro' => [ac.monokaipro('black'), ac.monokaipro('white')]
=> [ac.panda('white'), ac.panda('white')]
f_border_style (_style) =>
switch _style
OPTION_BORDER_STYLE1 => line.style_solid
OPTION_BORDER_STYLE2 => line.style_dotted
OPTION_BORDER_STYLE3 => line.style_dashed
=> _style
f_trading_method (is_buy) => is_buy ? 'Buy' : 'Sell'
f_range (h, l) => math.abs(h - l)
f_ratio (a, b) => a / b * 100
f_cp_doji (_p = 0.01) => math.abs(open - close) <= (high - low) * _p
f_cp_insidebar (h = high, l = low, _t = 1) => t = math.max(_t, 1), h[t-1] <= h[t] and l[t-1] >= l[t]
f_cp_body_id (t, b, t1, b1) => t < t1 and b > b1
f_cp_id_by (_top, _bot, _by = 1) =>
c_top = array.get(_top, 0)
c_bot = array.get(_bot, 0)
t_top = array.get(_top, _by)
t_bot = array.get(_bot, _by)
c_top < t_top and c_bot > t_bot
f_cp_id_for (h_, l_, _t = 1, _top, _bot) =>
result = false
for i = 1 to _t
t = array.get(_top, i)
b = array.get(_bot, i)
if h_ < t and l_ > b
result := true
break
result
f_cp_id_for2 (t, b, _t = 1, _top, _bot, _high, _low) =>
result = false
h = array.get(_high, 0)
l = array.get(_low, 0)
for i = 1 to math.min(_t, 10)
that_t = array.get(_top, i)
that_b = array.get(_bot, i)
that_h = array.get(_high, i)
that_l = array.get(_low, i)
// 昔のHL / 今のHL
r = f_ratio(f_range(that_h, that_l), f_range(h, l))
if (t < that_t and b > that_b) and (r > 90)
result := true
break
result
f_cp_range_contraction (a, b, a1, b1) => a1 > a and b1 < b
f_flag (_show, string _text, float _number, int _dir=1, _color=color.purple) =>
if _show
yloc = _dir == 1 ? yloc.belowbar : yloc.abovebar
style = _dir == 1 ? label.style_label_up : label.style_label_down
p = (not na(_number)) and _number != 0.0 ? str.tostring(_number, format.mintick) : ''
label.new(bar_index, na, _text + p, yloc=yloc, color=_color, style=style, size=size.small)
// 前足が下向き: H_Close が H_Openの2期間平均より下なら、bartype[1] を引き継ぐ
// 前足が上向き: H_Close が H_Openの2期間平均より上なら、bartype[1] を引き継ぐ
f_bartype_filter_1 (bt, bt1, _c, _avg, _use = false) =>
cond1 = bt == 1 and bt1 == -1 and _c < _avg
cond2 = bt == -1 and bt1 == 1 and _c > _avg
_use and (cond1 or cond2)
f_bartype_filter_2 (bt, bt1, _c, _avg, _use = false) =>
cond1 = bt == 1 and bt1 == -1 and _c < _avg // [0]陽線 [1]陰線 終値強い
cond2 = bt == -1 and bt1 == 1 and _c > _avg // [0]陰線 [1]陽線 終値弱い
_use and (cond1 or cond2)
f_is_changed_bar (bt, bt1) => bt != bt1
is_danger_zone = (hour == 16)
// -- High
// │
// ┌┴┐ -- Top
// │ │
// └┬┘ -- Bottom
// │
// -- Low
//
f_bartype (_o, _h, _l, _c, _arr_top, _arr_bot, _arr_high, _arr_low, _is_insidebar, _is_tinybar, _use_filter, _colors, _show_flag) =>
var is_keep_inside = false
var float keep_inside_top = na
var float keep_inside_bot = na
var color_idbox = array.get(_colors, 0)
bt = _c >= _o ? 1 : -1
btt = bt
up = array.get(_arr_high, 0) - array.get(_arr_high, 1)
dn = array.get(_arr_low, 0) - array.get(_arr_low, 1)
t = math.max(_o, _c) // top
b = math.min(_o, _c) // btm
h = math.max(_h, t)
l = math.min(_l, b)
h_t = math.max(math.max(h - t, 0), mintick) // high - top
b_l = math.max(math.max(b - l, 0), mintick) // btm - low
height = t - b
r1 = h_t / b_l
r2 = b_l / h_t
r3 = h_t / (h_t + b_l)
r4 = b_l / (h_t + b_l)
LV1 = 1.618
LV2 = 2.618
is_up = up > 0 and dn > 0
is_dn = dn < 0 and up < 0
is_all_up = h > h[1] and l > l[1] and t > t[1] and b > b[1] and close >= close[1] and _h > _h[1] and _l > _l[1]
is_all_dn = h < h[1] and l < l[1] and t < t[1] and b < b[1] and close <= close[1] and _h < _h[1] and _l < _l[1]
is_rc = (f_cp_range_contraction(t, b, t[1], b[1]) and f_cp_range_contraction(t[1], b[1], t[2], b[2]))
// インサイドバーなら前の bartype を引き継ぐ
if _is_insidebar
bt := bt[1]
else if _is_tinybar
// 極小足なら前の bartype を引き継ぐ
bt := bt[1]
// 現在が極小足でも、前の足が極小足ではない場合
if (not _is_tinybar[1]) and f_is_changed_bar(btt, btt[1])
// 1. 前足が陰線で、上髭が長いなら 1
// 2. 前足が陽線で、下髭が長いなら -1
if bt[1] == -1 and ((h_t / h_t[1] > LV1 and r1 > LV1))
bt := 1
if bt[1] == 1 and ((b_l / b_l[1] > LV1 and r2 > LV1))
bt := -1
// インサイドチェック
if is_keep_inside
if array.get(_arr_top, 0) > keep_inside_top
f_flag(_show_flag, 'x', 0, bt, color.red)
bt := 1
is_keep_inside := false
else if array.get(_arr_bot, 0) < keep_inside_bot
f_flag(_show_flag, 'x', 0, bt, color.yellow)
bt := -1
is_keep_inside := false
else
bt := bt[1]
if i_show_idbox
box.new(bar_index - 1, keep_inside_top, bar_index, keep_inside_bot, bgcolor=color.new(color_idbox, 70), border_color=color.new(color_idbox, 40))
if f_cp_id_by(_arr_top, _arr_bot, 1) and is_keep_inside == false
f_flag(_show_flag, 'I', 0, bt)
bt := bt[1]
keep_inside_top := array.get(_arr_top, 1)
keep_inside_bot := array.get(_arr_bot, 1)
is_keep_inside := true
//box.new(bar_index - 1, keep_inside_top, bar_index, keep_inside_bot, bgcolor=color.new(color.yellow, 30), border_color=color.new(color.yellow, 30))
if f_cp_id_by(_arr_high, _arr_low, 1) and f_is_changed_bar(bt, bt[1])
bt := bt[1]
f_flag(_show_flag, 'IHL', 0, bt)
// 終値が, H_Top と H_Bottom の間にあるなら、bartype[1] を引き継ぐ
if array.get(_use_filter, FILTER_CLOSE_VS_TB)
if f_is_changed_bar(bt, bt[1]) and (close < t and close > b)
bt := bt[1]
f_flag(_show_flag, 'F4', 0, bt)
// 上髭と下髭の比率が同程度なら、bartype[1] を引き継ぐ
if array.get(_use_filter, FILTER_BALANCE)
if f_is_changed_bar(bt, bt[1]) and ((r3 <= 0.6 and r3 >= 0.4) or (r4 <= 0.6 and r4 >= 0.4))
bt := bt[1]
f_flag(_show_flag, 'F5', 0, bt)
// H_Openの過去2期間平均と、H_Closeを比較
if array.get(_use_filter, FILTER_HOPEN2_VS_HCLOSE)
if f_bartype_filter_1(bt, bt[1], _c, math.avg(_o[1], _o[2]), true)
bt := bt[1]
f_flag(_show_flag, 'F1', 0, bt)
// 終値とH_HighとH_Lowの平均を比較
// if array.get(_use_filter, FILTER_CLOSE_VS_HL)
// if f_bartype_filter_2(bt, bt[1], close, math.avg(h, l), true)
// f_flag(_show_flag, 'F2', math.avg(_h, _l), bt)
// bt := bt[1]
[bt, btt]
//////////
// Vars //
var color_bull = f_color(i_color, 'up' , i_color_1)
var color_bear = f_color(i_color, 'down' , i_color_2)
var color_ma = f_color(i_color, 'neutral', i_color_3)
var color_sl = f_color(i_color, 'sl' , i_color_5)
var color_tp = f_color(i_color, 'to' , i_color_4)
var color_buy = f_color(i_color, 'buy' , i_color_7)
var color_sell = f_color(i_color, 'sell' , i_color_8)
var color_gray = f_color(i_color, 'gray' , i_color_6)
var color_black = f_color(i_color, 'black' , color.black)
var color_idbox = f_color(i_color, 'yellow' , i_color_9)
var color_bar = COLOR_NONE
var cpi_colors = array.from(color_buy, color_sell, color_sl, color_tp, color_gray)
//i_show_flag := input.bool(false, 'Flag', group=GP_DEV)
i_averaged_times = 1
i_close_type = 'ohlc4'
i_use_filter_1 = true
i_use_filter_2 = true
i_use_filter_3 = true
i_use_filter_4 = true
i_use_filter_5 = true
i_use_filter_6 = true
i_use_filter_7 = true
// i_use_filter_1 := input.bool(false, 'B: Inside')
// i_use_filter_5 := input.bool(false, 'B: Close vs HL')
// i_use_filter_4 := input.bool(false, 'B: H_Open2 VS H_Close')
// i_use_filter_3 := input.bool(false, 'B: Unbalance shadow')
// i_use_filter_2 := input.bool(false, 'B: Close vs TB')
// i_use_filter_7 := input.bool(false, 'F: Inside2 and Go')
// i_use_filter_6 := input.bool(false, 'F: Tiny and Unbalance')
//i_averaged_times := input.int(1, 'Averaged by (times)', minval=1, maxval=10, group="Development & Testing")
//i_close_type := input.string('ohlc4', 'Close calculated by', options=['ohlc4', 'ohlc4-s2', 'ohlc4-s3', 'ohlc4-s4', 'hlc3', 'oc2', 'hl2', 'close'], group="Development & Testing")
// Setting param by mode
if i_mode == OPTION_MODE_CD
i_averaged_times := 3
i_close_type := 'oc2'
i_use_filter_1 := true
i_use_filter_2 := true
i_use_filter_3 := true
i_use_filter_4 := true
i_use_filter_5 := true
i_use_filter_6 := true
i_use_filter_7 := true
else if i_mode == OPTION_MODE_D
i_averaged_times := 3
i_close_type := 'ohlc4'
i_use_filter_1 := true
i_use_filter_2 := true
i_use_filter_3 := true
i_use_filter_4 := true
i_use_filter_5 := false
i_use_filter_6 := false
i_use_filter_7 := false
else if i_mode == OPTION_MODE_C
i_averaged_times := 5
i_close_type := 'oc2'
i_use_filter_1 := true
i_use_filter_2 := true
i_use_filter_3 := true
i_use_filter_4 := true
i_use_filter_5 := false
i_use_filter_6 := false
i_use_filter_7 := false
if barstate.isfirst
array.clear(bt_filters)
array.push(bt_filters, i_use_filter_1) // FILTER_INSIDE
array.push(bt_filters, i_use_filter_2) // FILTER_CLOSE_VS_TB
array.push(bt_filters, i_use_filter_3) // FILTER_BALANCE
array.push(bt_filters, i_use_filter_4) // FILTER_HOPEN2_VS_HCLOSE
array.push(bt_filters, i_use_filter_5) // FILTER_CLOSE_VS_HL
array.push(bt_filters, i_use_filter_6) // FILTER_TINY_AND_UNBALANCE
array.push(bt_filters, i_use_filter_7) // FILTER_ID_AND_GO
//////////
// Calc //
htf_changed = ta.change(time(util.auto_htf()))
[hopen, _, _, hclose] = heikinashi.calcFor_v1(open, high, low, close, i_close_type, i_averaged_times)
htop = math.max(hopen, hclose)
hbtm = math.min(hopen, hclose)
hhigh = math.max(high, htop)
hlow = math.min(low , hbtm)
hoc2 = math.avg(hopen, hclose)
hchg = ta.sma(math.abs(hoc2[1] - hoc2[2]), 16)
ma1 = ma.new(hopen, hhigh, hlow, hclose).create(i_ma1_type, i_ma1_source, i_ma1_period)
ma2 = ma.new(hopen, hhigh, hlow, hclose).create(i_ma2_type, i_ma2_source, i_ma2_period)
hl_pips = util.to_pips(math.abs(high - low))
oc_pips = util.to_pips(math.abs(hopen - hclose))
// Conditions
is_insidebar = f_cp_insidebar(hhigh, hlow)
is_tinybar = oc_pips < math.round(ta.stdev(oc_pips, 100) / 3) // 15min: 3pips
is_super_tinybar = oc_pips < math.round(ta.stdev(oc_pips, 100) / 5) // 15min: 3pips
is_id_body = f_cp_body_id(htop, hbtm, htop[1], hbtm[1])
// is_largebar = hl_pips > math.round(ta.stdev(hl_pips, 100) * 3) // 15min: 30pips
top_list = array.from(htop[0] , htop[1] , htop[2] , htop[3] , htop[4] , htop[5] )
btm_list = array.from(hbtm[0] , hbtm[1] , hbtm[2] , hbtm[3] , hbtm[4] , hbtm[5] )
low_list = array.from(hlow[0] , hlow[1] , hlow[2] , hlow[3] , hlow[4] , hlow[5] )
high_list = array.from(hhigh[0], hhigh[1], hhigh[2], hhigh[3], hhigh[4], hhigh[5] )
[bartype, bartype_true] = f_bartype(hopen, high, low, hclose, top_list, btm_list, high_list, low_list, is_insidebar, is_tinybar, bt_filters, array.from(color_idbox), i_show_flag)
// Triggers
cond_buy = ta.change(bartype) > 0
cond_sell = ta.change(bartype) < 0
var bar_count = 0, bar_count := bartype != bartype[1] ? 0 : bar_count + 1
var rc_count = 0, rc_count := bar_count == 0 ? 0 : rc_count
// Range contraction
cond_buy_rc = is_id_body and is_super_tinybar and bartype == 1 and bar_count > 3
cond_sell_rc = is_id_body and is_super_tinybar and bartype == -1 and bar_count > 3
if (bar_count > 0) and (cond_buy_rc or cond_sell_rc)
rc_count += 1
/////////
// QQE //
oc2 = math.avg(open, close)
[osc, vosc, QLine] = util.qqe_func(oc2, 3, 6, 5, 5)
var qqeTrend = 0
qqeLong = ta.crossover (vosc, 0) and (not cond_buy) and bartype == 1
qqeShort = ta.crossunder(vosc, 0) and (not cond_sell) and bartype == -1
qqeLongTrend = qqeLong and qqeTrend != 1
qqeShortTrend = qqeShort and qqeTrend != -1
qqeTrend := qqeLong ? 1 : qqeShort ? -1 : qqeTrend[1]
/////////////////
// Plot colors //
color_bar := bartype == 1 ? color_bull : color_bear
if i_mode == OPTION_MODE_STANDARD
color_bar := hclose > hopen ? color_bull : color_bear
c_border = color_bar
c_body = color_bar
c_close = COLOR_NONE
c_close := if i_show_heikinashi
switch i_candle_close
'Always' => color_bar
'Signal only' => (cond_buy or cond_sell or (i_show_qqe and (qqeLong or qqeShort))) ? color_bar : COLOR_NONE
'Never' => COLOR_NONE
if i_hollow
if bartype == 1
c_body := COLOR_NONE
else if i_mode == OPTION_MODE_STANDARD and (hclose > hopen)
c_body := COLOR_NONE
//////////////
// Plotting //
[plot_open, plot_close] = if i_show_heikinashi
[hopen, hclose]
else if i_show_candle
[open, close]
else
[na, na]
plot_high = math.max(plot_open, plot_close, high)
plot_low = math.min(plot_open, plot_close, low)
plotcandle(plot_open, plot_high, plot_low, plot_close, 'Heikin-ashi', color=c_body, wickcolor=c_border, bordercolor=c_border)
plotcandle(close, close, close, close, 'Close level', color=COLOR_NONE, wickcolor=COLOR_NONE, bordercolor=c_close)
plot(plot_open, 'open', editable=false, display=display.none)
ma_offset = 0
// MA
plot(i_ma1_displayed and i_ma1_style == OPTION_BORDER_STYLE1 ? ma1[ma_offset] : na, 'MA1', color=color_ma, linewidth=1)
plot(i_ma2_displayed and i_ma2_style == OPTION_BORDER_STYLE1 ? ma2[ma_offset] : na, 'MA2', color=color_ma, linewidth=1)
if i_ma1_displayed and i_ma1_style != OPTION_BORDER_STYLE1
line.new(bar_index, ma1[ma_offset], bar_index-1, ma1[ma_offset+1], style=f_border_style(i_ma1_style), color=color_ma)
if i_ma2_displayed and i_ma2_style != OPTION_BORDER_STYLE1
line.new(bar_index, ma2[ma_offset], bar_index-1, ma2[ma_offset+1], style=f_border_style(i_ma2_style), color=color_ma)
// Bar colors
barcolor(i_show_barcolor ? c_body : na)
//////////////////
// Entry Levels //
var entry_index = 0
var entry_side = 0
var entry_price = 0.0
var entry_entered = false
var entry_range_high = 0.0
var entry_range_low = 0.0
var entry_lc = 0.0
var scale_lines = array.new<line>()
var scale_x = 0
cond_sell_index = math.max(nz(ta.barssince(cond_sell), 1), 1)
cond_buy_index = math.max(nz(ta.barssince(cond_buy ), 1), 1)
lowest_index = math.abs(ta.lowestbars (plot_low , cond_sell_index))
highest_index = math.abs(ta.highestbars(plot_high, cond_buy_index ))
if i_show_exections
chg_type = syminfo.type == 'forex' ? 'pips' : 'price'
cp.history(entry_index, entry_price, entry_lc, entry_range_high, entry_range_low, entry_side, entry_entered, cpi_colors, (cond_buy or cond_sell), chg_type)
if cond_buy
scale_x := bar_index - lowest_index
t = math.max(util.round(util.to_pips(hchg)), 0.5)
p = util.rounded_price(hhigh, t * 10, 'ceil', true, 1)
entry_price := p
entry_index := bar_index
entry_side := 1
entry_entered := false
entry_lc := hlow
entry_range_high := p
entry_range_low := p
else if cond_sell
scale_x := bar_index - highest_index
t = math.max(util.round(util.to_pips(hchg)), 0.5)
p = util.rounded_price(hlow, t * 10, 'floor', false, 1)
entry_price := p
entry_index := bar_index
entry_side := -1
entry_entered := false
entry_lc := hhigh
entry_range_high := p
entry_range_low := p
else
entry_range_high := math.max(entry_range_high, high )
entry_range_low := math.min(entry_range_low , low )
if (entry_side == 1 and high > entry_price) or (entry_side == -1 and low < entry_price)
entry_entered := true
if i_show_indicator
cp.run(entry_index, entry_price, entry_lc, entry_range_high, entry_range_low, entry_side, entry_entered, cpi_colors, i_position_ind_placement)
//////////////
// Triggers //
margin_top1 = math.round(ta.stdev(oc_pips, 1000) / 2.00)
margin_top2 = math.round(ta.stdev(oc_pips, 1000) / 0.50)
p_top = hhigh + util.to_price(margin_top1)
p_btm = hlow - util.to_price(margin_top1)
[textcolor1, textcolor2] = f_trigger_text_color(i_color)
rc_show_num = 3
plotshape(i_show_range_contraction and cond_buy_rc and (not cond_buy_rc[1] ) and rc_count <= rc_show_num ? p_top : na, 'Range Contraction', style=shape.xcross, color=color.from_gradient(80, 0, 100, color_black, color_buy), location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_range_contraction and cond_sell_rc and (not cond_sell_rc[1]) and rc_count <= rc_show_num ? p_btm : na, 'Range Contraction', style=shape.xcross, color=color.from_gradient(80, 0, 100, color_black, color_sell), location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_triggers and i_trigger_label == OPTION_LABEL_X and cond_buy ? p_btm : na, 'Buy' , text='', textcolor=textcolor1, color=color_buy, style=shape.labelup, location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_triggers and i_trigger_label == OPTION_LABEL_X and cond_sell ? p_top : na, 'Sell', text='', textcolor=textcolor2, color=color_sell, style=shape.labeldown, location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_triggers and i_trigger_label == OPTION_LABEL_1 and cond_buy ? p_btm : na, 'Buy' , text='Buy', textcolor=textcolor1, color=color_buy, style=shape.labelup, location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_triggers and i_trigger_label == OPTION_LABEL_1 and cond_sell ? p_top : na, 'Sell', text='Sell', textcolor=textcolor2, color=color_sell, style=shape.labeldown, location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_triggers and i_trigger_label == OPTION_LABEL_5 and cond_buy ? p_btm : na, 'Buy' , text='B', textcolor=textcolor1, color=color_buy, style=shape.labelup, location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_triggers and i_trigger_label == OPTION_LABEL_5 and cond_sell ? p_top : na, 'Sell', text='S', textcolor=textcolor2, color=color_sell, style=shape.labeldown, location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_triggers and i_trigger_label == OPTION_LABEL_2 and cond_buy ? p_btm : na, 'Buy' , text='Long', textcolor=textcolor1, color=color_buy, style=shape.labelup, location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_triggers and i_trigger_label == OPTION_LABEL_2 and cond_sell ? p_top : na, 'Sell', text='Short', textcolor=textcolor2, color=color_sell, style=shape.labeldown, location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_triggers and i_trigger_label == OPTION_LABEL_3 and cond_buy ? p_btm : na, 'Buy' , text='L', textcolor=textcolor1, color=color_buy, style=shape.labelup, location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_triggers and i_trigger_label == OPTION_LABEL_3 and cond_sell ? p_top : na, 'Sell', text='S', textcolor=textcolor2, color=color_sell, style=shape.labeldown, location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_triggers and i_trigger_label == OPTION_LABEL_4 and cond_buy ? p_btm : na, 'Buy' , text=icon_bull, textcolor=textcolor1, color=color_buy, style=shape.labelup, location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_triggers and i_trigger_label == OPTION_LABEL_4 and cond_sell ? p_top : na, 'Sell', text=icon_bear, textcolor=textcolor2, color=color_sell, style=shape.labeldown, location=location.absolute, size=size.tiny, editable=false)
plotshape(i_show_qqe and qqeLong ? p_btm : na, '' , color=color_buy, style=shape.labelup, location=location.absolute, size=size.tiny)
plotshape(i_show_qqe and qqeShort ? p_top : na, '', color=color_sell, style=shape.labeldown, location=location.absolute, size=size.tiny)
///////////
// Alert //
if cond_buy or cond_sell
alert_message = syminfo.ticker + ': ' + f_trading_method(cond_buy) + ' @' + str.tostring(entry_price, format.mintick)
if i_alert_trigger == OPTION_ALERT1
alert(alert_message, alert.freq_once_per_bar_close)
else
alert(alert_message, alert.freq_once_per_bar)
|
Machine Learning: Lorentzian Classification | https://www.tradingview.com/script/WhBzgfDu-Machine-Learning-Lorentzian-Classification/ | jdehorty | https://www.tradingview.com/u/jdehorty/ | 13,460 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ©jdehorty
// @version=5
indicator('Machine Learning: Lorentzian Classification', 'Lorentzian Classification', true, precision=4, max_labels_count=500)
import jdehorty/MLExtensions/2 as ml
import jdehorty/KernelFunctions/2 as kernels
// ====================
// ==== Background ====
// ====================
// When using Machine Learning algorithms like K-Nearest Neighbors, choosing an
// appropriate distance metric is essential. Euclidean Distance is often used as
// the default distance metric, but it may not always be the best choice. This is
// because market data is often significantly impacted by proximity to significant
// world events such as FOMC Meetings and Black Swan events. These major economic
// events can contribute to a warping effect analogous a massive object's
// gravitational warping of Space-Time. In financial markets, this warping effect
// operates on a continuum, which can analogously be referred to as "Price-Time".
// To help to better account for this warping effect, Lorentzian Distance can be
// used as an alternative distance metric to Euclidean Distance. The geometry of
// Lorentzian Space can be difficult to visualize at first, and one of the best
// ways to intuitively understand it is through an example involving 2 feature
// dimensions (z=2). For purposes of this example, let's assume these two features
// are Relative Strength Index (RSI) and the Average Directional Index (ADX). In
// reality, the optimal number of features is in the range of 3-8, but for the sake
// of simplicity, we will use only 2 features in this example.
// Fundamental Assumptions:
// (1) We can calculate RSI and ADX for a given chart.
// (2) For simplicity, values for RSI and ADX are assumed to adhere to a Gaussian
// distribution in the range of 0 to 100.
// (3) The most recent RSI and ADX value can be considered the origin of a coordinate
// system with ADX on the x-axis and RSI on the y-axis.
// Distances in Euclidean Space:
// Measuring the Euclidean Distances of historical values with the most recent point
// at the origin will yield a distribution that resembles Figure 1 (below).
// [RSI]
// |
// |
// |
// ...:::....
// .:.:::••••••:::•::..
// .:•:.:•••::::••::••....::.
// ....:••••:••••••••::••:...:•.
// ...:.::::::•••:::•••:•••::.:•..
// ::•:.:•:•••••••:.:•::::::...:..
// |--------.:•••..•••••••:••:...:::•:•:..:..----------[ADX]
// 0 :•:....:•••••::.:::•••::••:.....
// ::....:.:••••••••:•••::••::..:.
// .:...:••:::••••••••::•••....:
// ::....:.....:•::•••:::::..
// ..:..::••..::::..:•:..
// .::..:::.....:
// |
// |
// |
// |
// _|_ 0
//
// Figure 1: Neighborhood in Euclidean Space
// Distances in Lorentzian Space:
// However, the same set of historical values measured using Lorentzian Distance will
// yield a different distribution that resembles Figure 2 (below).
//
// [RSI]
// ::.. | ..:::
// ..... | ......
// .••••::. | :••••••.
// .:•••••:. | :::••••••.
// .•••••:... | .::.••••••.
// .::•••••::.. | :..••••••..
// .:•••••••::.........::••••••:..
// ..::::••••.•••••••.•••••••:.
// ...:•••••••.•••••••••::.
// .:..••.••••••.••••..
// |---------------.:•••••••••••••••••.---------------[ADX]
// 0 .:•:•••.••••••.•••••••.
// .••••••••••••••••••••••••:.
// .:••••••••••::..::.::••••••••:.
// .::••••••::. | .::•••:::.
// .:••••••.. | :••••••••.
// .:••••:... | ..•••••••:.
// ..:••::.. | :.•••••••.
// .:•.... | ...::.:••.
// ...:.. | :...:••.
// :::. | ..::
// _|_ 0
//
// Figure 2: Neighborhood in Lorentzian Space
// Observations:
// (1) In Lorentzian Space, the shortest distance between two points is not
// necessarily a straight line, but rather, a geodesic curve.
// (2) The warping effect of Lorentzian distance reduces the overall influence
// of outliers and noise.
// (3) Lorentzian Distance becomes increasingly different from Euclidean Distance
// as the number of nearest neighbors used for comparison increases.
// ======================
// ==== Custom Types ====
// ======================
// This section uses PineScript's new Type syntax to define important data structures
// used throughout the script.
type Settings
float source
int neighborsCount
int maxBarsBack
int featureCount
int colorCompression
bool showExits
bool useDynamicExits
type Label
int long
int short
int neutral
type FeatureArrays
array<float> f1
array<float> f2
array<float> f3
array<float> f4
array<float> f5
type FeatureSeries
float f1
float f2
float f3
float f4
float f5
type MLModel
int firstBarIndex
array<int> trainingLabels
int loopSize
float lastDistance
array<float> distancesArray
array<int> predictionsArray
int prediction
type FilterSettings
bool useVolatilityFilter
bool useRegimeFilter
bool useAdxFilter
float regimeThreshold
int adxThreshold
type Filter
bool volatility
bool regime
bool adx
// ==========================
// ==== Helper Functions ====
// ==========================
series_from(feature_string, _close, _high, _low, _hlc3, f_paramA, f_paramB) =>
switch feature_string
"RSI" => ml.n_rsi(_close, f_paramA, f_paramB)
"WT" => ml.n_wt(_hlc3, f_paramA, f_paramB)
"CCI" => ml.n_cci(_close, f_paramA, f_paramB)
"ADX" => ml.n_adx(_high, _low, _close, f_paramA)
get_lorentzian_distance(int i, int featureCount, FeatureSeries featureSeries, FeatureArrays featureArrays) =>
switch featureCount
5 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +
math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i))) +
math.log(1+math.abs(featureSeries.f3 - array.get(featureArrays.f3, i))) +
math.log(1+math.abs(featureSeries.f4 - array.get(featureArrays.f4, i))) +
math.log(1+math.abs(featureSeries.f5 - array.get(featureArrays.f5, i)))
4 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +
math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i))) +
math.log(1+math.abs(featureSeries.f3 - array.get(featureArrays.f3, i))) +
math.log(1+math.abs(featureSeries.f4 - array.get(featureArrays.f4, i)))
3 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +
math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i))) +
math.log(1+math.abs(featureSeries.f3 - array.get(featureArrays.f3, i)))
2 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +
math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i)))
// ================
// ==== Inputs ====
// ================
// Settings Object: General User-Defined Inputs
Settings settings =
Settings.new(
input.source(title='Source', defval=close, group="General Settings", tooltip="Source of the input data"),
input.int(title='Neighbors Count', defval=8, group="General Settings", minval=1, maxval=100, step=1, tooltip="Number of neighbors to consider"),
input.int(title="Max Bars Back", defval=2000, group="General Settings"),
input.int(title="Feature Count", defval=5, group="Feature Engineering", minval=2, maxval=5, tooltip="Number of features to use for ML predictions."),
input.int(title="Color Compression", defval=1, group="General Settings", minval=1, maxval=10, tooltip="Compression factor for adjusting the intensity of the color scale."),
input.bool(title="Show Default Exits", defval=false, group="General Settings", tooltip="Default exits occur exactly 4 bars after an entry signal. This corresponds to the predefined length of a trade during the model's training process.", inline="exits"),
input.bool(title="Use Dynamic Exits", defval=false, group="General Settings", tooltip="Dynamic exits attempt to let profits ride by dynamically adjusting the exit threshold based on kernel regression logic.", inline="exits")
)
// Trade Stats Settings
// Note: The trade stats section is NOT intended to be used as a replacement for proper backtesting. It is intended to be used for calibration purposes only.
showTradeStats = input.bool(true, 'Show Trade Stats', tooltip='Displays the trade stats for a given configuration. Useful for optimizing the settings in the Feature Engineering section. This should NOT replace backtesting and should be used for calibration purposes only. Early Signal Flips represent instances where the model changes signals before 4 bars elapses; high values can indicate choppy (ranging) market conditions.', group="General Settings")
useWorstCase = input.bool(false, "Use Worst Case Estimates", tooltip="Whether to use the worst case scenario for backtesting. This option can be useful for creating a conservative estimate that is based on close prices only, thus avoiding the effects of intrabar repainting. This option assumes that the user does not enter when the signal first appears and instead waits for the bar to close as confirmation. On larger timeframes, this can mean entering after a large move has already occurred. Leaving this option disabled is generally better for those that use this indicator as a source of confluence and prefer estimates that demonstrate discretionary mid-bar entries. Leaving this option enabled may be more consistent with traditional backtesting results.", group="General Settings")
// Settings object for user-defined settings
FilterSettings filterSettings =
FilterSettings.new(
input.bool(title="Use Volatility Filter", defval=true, tooltip="Whether to use the volatility filter.", group="Filters"),
input.bool(title="Use Regime Filter", defval=true, group="Filters", inline="regime"),
input.bool(title="Use ADX Filter", defval=false, group="Filters", inline="adx"),
input.float(title="Threshold", defval=-0.1, minval=-10, maxval=10, step=0.1, tooltip="Whether to use the trend detection filter. Threshold for detecting Trending/Ranging markets.", group="Filters", inline="regime"),
input.int(title="Threshold", defval=20, minval=0, maxval=100, step=1, tooltip="Whether to use the ADX filter. Threshold for detecting Trending/Ranging markets.", group="Filters", inline="adx")
)
// Filter object for filtering the ML predictions
Filter filter =
Filter.new(
ml.filter_volatility(1, 10, filterSettings.useVolatilityFilter),
ml.regime_filter(ohlc4, filterSettings.regimeThreshold, filterSettings.useRegimeFilter),
ml.filter_adx(settings.source, 14, filterSettings.adxThreshold, filterSettings.useAdxFilter)
)
// Feature Variables: User-Defined Inputs for calculating Feature Series.
f1_string = input.string(title="Feature 1", options=["RSI", "WT", "CCI", "ADX"], defval="RSI", inline = "01", tooltip="The first feature to use for ML predictions.", group="Feature Engineering")
f1_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 1.", defval=14, inline = "02", group="Feature Engineering")
f1_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 2 (if applicable).", defval=1, inline = "02", group="Feature Engineering")
f2_string = input.string(title="Feature 2", options=["RSI", "WT", "CCI", "ADX"], defval="WT", inline = "03", tooltip="The second feature to use for ML predictions.", group="Feature Engineering")
f2_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 2.", defval=10, inline = "04", group="Feature Engineering")
f2_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 2 (if applicable).", defval=11, inline = "04", group="Feature Engineering")
f3_string = input.string(title="Feature 3", options=["RSI", "WT", "CCI", "ADX"], defval="CCI", inline = "05", tooltip="The third feature to use for ML predictions.", group="Feature Engineering")
f3_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 3.", defval=20, inline = "06", group="Feature Engineering")
f3_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 3 (if applicable).", defval=1, inline = "06", group="Feature Engineering")
f4_string = input.string(title="Feature 4", options=["RSI", "WT", "CCI", "ADX"], defval="ADX", inline = "07", tooltip="The fourth feature to use for ML predictions.", group="Feature Engineering")
f4_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 4.", defval=20, inline = "08", group="Feature Engineering")
f4_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 4 (if applicable).", defval=2, inline = "08", group="Feature Engineering")
f5_string = input.string(title="Feature 5", options=["RSI", "WT", "CCI", "ADX"], defval="RSI", inline = "09", tooltip="The fifth feature to use for ML predictions.", group="Feature Engineering")
f5_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 5.", defval=9, inline = "10", group="Feature Engineering")
f5_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 5 (if applicable).", defval=1, inline = "10", group="Feature Engineering")
// FeatureSeries Object: Calculated Feature Series based on Feature Variables
featureSeries =
FeatureSeries.new(
series_from(f1_string, close, high, low, hlc3, f1_paramA, f1_paramB), // f1
series_from(f2_string, close, high, low, hlc3, f2_paramA, f2_paramB), // f2
series_from(f3_string, close, high, low, hlc3, f3_paramA, f3_paramB), // f3
series_from(f4_string, close, high, low, hlc3, f4_paramA, f4_paramB), // f4
series_from(f5_string, close, high, low, hlc3, f5_paramA, f5_paramB) // f5
)
// FeatureArrays Variables: Storage of Feature Series as Feature Arrays Optimized for ML
// Note: These arrays cannot be dynamically created within the FeatureArrays Object Initialization and thus must be set-up in advance.
var f1Array = array.new_float()
var f2Array = array.new_float()
var f3Array = array.new_float()
var f4Array = array.new_float()
var f5Array = array.new_float()
array.push(f1Array, featureSeries.f1)
array.push(f2Array, featureSeries.f2)
array.push(f3Array, featureSeries.f3)
array.push(f4Array, featureSeries.f4)
array.push(f5Array, featureSeries.f5)
// FeatureArrays Object: Storage of the calculated FeatureArrays into a single object
featureArrays =
FeatureArrays.new(
f1Array, // f1
f2Array, // f2
f3Array, // f3
f4Array, // f4
f5Array // f5
)
// Label Object: Used for classifying historical data as training data for the ML Model
Label direction =
Label.new(
long=1,
short=-1,
neutral=0
)
// Derived from General Settings
maxBarsBackIndex = last_bar_index >= settings.maxBarsBack ? last_bar_index - settings.maxBarsBack : 0
// EMA Settings
useEmaFilter = input.bool(title="Use EMA Filter", defval=false, group="Filters", inline="ema")
emaPeriod = input.int(title="Period", defval=200, minval=1, step=1, group="Filters", inline="ema", tooltip="The period of the EMA used for the EMA Filter.")
isEmaUptrend = useEmaFilter ? close > ta.ema(close, emaPeriod) : true
isEmaDowntrend = useEmaFilter ? close < ta.ema(close, emaPeriod) : true
useSmaFilter = input.bool(title="Use SMA Filter", defval=false, group="Filters", inline="sma")
smaPeriod = input.int(title="Period", defval=200, minval=1, step=1, group="Filters", inline="sma", tooltip="The period of the SMA used for the SMA Filter.")
isSmaUptrend = useSmaFilter ? close > ta.sma(close, smaPeriod) : true
isSmaDowntrend = useSmaFilter ? close < ta.sma(close, smaPeriod) : true
// Nadaraya-Watson Kernel Regression Settings
useKernelFilter = input.bool(true, "Trade with Kernel", group="Kernel Settings", inline="kernel")
showKernelEstimate = input.bool(true, "Show Kernel Estimate", group="Kernel Settings", inline="kernel")
useKernelSmoothing = input.bool(false, "Enhance Kernel Smoothing", tooltip="Uses a crossover based mechanism to smoothen kernel color changes. This often results in less color transitions overall and may result in more ML entry signals being generated.", inline='1', group='Kernel Settings')
h = input.int(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="Kernel Settings", inline="kernel")
r = input.float(8., 'Relative Weighting', step=0.25, 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', group="Kernel Settings", inline="kernel")
x = input.int(25, "Regression Level", tooltip='Bar index on which to start regression. Controls how tightly fit the kernel estimate is to the data. Smaller values are a tighter fit. Larger values are a looser fit. Recommended range: 2-25', group="Kernel Settings", inline="kernel")
lag = input.int(2, "Lag", tooltip="Lag for crossover detection. Lower values result in earlier crossovers. Recommended range: 1-2", inline='1', group='Kernel Settings')
// Display Settings
showBarColors = input.bool(true, "Show Bar Colors", tooltip="Whether to show the bar colors.", group="Display Settings")
showBarPredictions = input.bool(defval = true, title = "Show Bar Prediction Values", tooltip = "Will show the ML model's evaluation of each bar as an integer.", group="Display Settings")
useAtrOffset = input.bool(defval = false, title = "Use ATR Offset", tooltip = "Will use the ATR offset instead of the bar prediction offset.", group="Display Settings")
barPredictionsOffset = input.float(0, "Bar Prediction Offset", minval=0, tooltip="The offset of the bar predictions as a percentage from the bar high or close.", group="Display Settings")
// =================================
// ==== Next Bar Classification ====
// =================================
// This model specializes specifically in predicting the direction of price action over the course of the next 4 bars.
// To avoid complications with the ML model, this value is hardcoded to 4 bars but support for other training lengths may be added in the future.
src = settings.source
y_train_series = src[4] < src[0] ? direction.short : src[4] > src[0] ? direction.long : direction.neutral
var y_train_array = array.new_int(0)
// Variables used for ML Logic
var predictions = array.new_float(0)
var prediction = 0.
var signal = direction.neutral
var distances = array.new_float(0)
array.push(y_train_array, y_train_series)
// =========================
// ==== Core ML Logic ====
// =========================
// Approximate Nearest Neighbors Search with Lorentzian Distance:
// A novel variation of the Nearest Neighbors (NN) search algorithm that ensures a chronologically uniform distribution of neighbors.
// In a traditional KNN-based approach, we would iterate through the entire dataset and calculate the distance between the current bar
// and every other bar in the dataset and then sort the distances in ascending order. We would then take the first k bars and use their
// labels to determine the label of the current bar.
// There are several problems with this traditional KNN approach in the context of real-time calculations involving time series data:
// - It is computationally expensive to iterate through the entire dataset and calculate the distance between every historical bar and
// the current bar.
// - Market time series data is often non-stationary, meaning that the statistical properties of the data change slightly over time.
// - It is possible that the nearest neighbors are not the most informative ones, and the KNN algorithm may return poor results if the
// nearest neighbors are not representative of the majority of the data.
// Previously, the user @capissimo attempted to address some of these issues in several of his PineScript-based KNN implementations by:
// - Using a modified KNN algorithm based on consecutive furthest neighbors to find a set of approximate "nearest" neighbors.
// - Using a sliding window approach to only calculate the distance between the current bar and the most recent n bars in the dataset.
// Of these two approaches, the latter is inherently limited by the fact that it only considers the most recent bars in the overall dataset.
// The former approach has more potential to leverage historical price action, but is limited by:
// - The possibility of a sudden "max" value throwing off the estimation
// - The possibility of selecting a set of approximate neighbors that are not representative of the majority of the data by oversampling
// values that are not chronologically distinct enough from one another
// - The possibility of selecting too many "far" neighbors, which may result in a poor estimation of price action
// To address these issues, a novel Approximate Nearest Neighbors (ANN) algorithm is used in this indicator.
// In the below ANN algorithm:
// 1. The algorithm iterates through the dataset in chronological order, using the modulo operator to only perform calculations every 4 bars.
// This serves the dual purpose of reducing the computational overhead of the algorithm and ensuring a minimum chronological spacing
// between the neighbors of at least 4 bars.
// 2. A list of the k-similar neighbors is simultaneously maintained in both a predictions array and corresponding distances array.
// 3. When the size of the predictions array exceeds the desired number of nearest neighbors specified in settings.neighborsCount,
// the algorithm removes the first neighbor from the predictions array and the corresponding distance array.
// 4. The lastDistance variable is overriden to be a distance in the lower 25% of the array. This step helps to boost overall accuracy
// by ensuring subsequent newly added distance values increase at a slower rate.
// 5. Lorentzian distance is used as a distance metric in order to minimize the effect of outliers and take into account the warping of
// "price-time" due to proximity to significant economic events.
lastDistance = -1.0
size = math.min(settings.maxBarsBack-1, array.size(y_train_array)-1)
sizeLoop = math.min(settings.maxBarsBack-1, size)
if bar_index >= maxBarsBackIndex //{
for i = 0 to sizeLoop //{
d = get_lorentzian_distance(i, settings.featureCount, featureSeries, featureArrays)
if d >= lastDistance and i%4 //{
lastDistance := d
array.push(distances, d)
array.push(predictions, math.round(array.get(y_train_array, i)))
if array.size(predictions) > settings.neighborsCount //{
lastDistance := array.get(distances, math.round(settings.neighborsCount*3/4))
array.shift(distances)
array.shift(predictions)
//}
//}
//}
prediction := array.sum(predictions)
//}
// ============================
// ==== Prediction Filters ====
// ============================
// User Defined Filters: Used for adjusting the frequency of the ML Model's predictions
filter_all = filter.volatility and filter.regime and filter.adx
// Filtered Signal: The model's prediction of future price movement direction with user-defined filters applied
signal := prediction > 0 and filter_all ? direction.long : prediction < 0 and filter_all ? direction.short : nz(signal[1])
// Bar-Count Filters: Represents strict filters based on a pre-defined holding period of 4 bars
var int barsHeld = 0
barsHeld := ta.change(signal) ? 0 : barsHeld + 1
isHeldFourBars = barsHeld == 4
isHeldLessThanFourBars = 0 < barsHeld and barsHeld < 4
// Fractal Filters: Derived from relative appearances of signals in a given time series fractal/segment with a default length of 4 bars
isDifferentSignalType = ta.change(signal)
isEarlySignalFlip = ta.change(signal) and (ta.change(signal[1]) or ta.change(signal[2]) or ta.change(signal[3]))
isBuySignal = signal == direction.long and isEmaUptrend and isSmaUptrend
isSellSignal = signal == direction.short and isEmaDowntrend and isSmaDowntrend
isLastSignalBuy = signal[4] == direction.long and isEmaUptrend[4] and isSmaUptrend[4]
isLastSignalSell = signal[4] == direction.short and isEmaDowntrend[4] and isSmaDowntrend[4]
isNewBuySignal = isBuySignal and isDifferentSignalType
isNewSellSignal = isSellSignal and isDifferentSignalType
// Kernel Regression Filters: Filters based on Nadaraya-Watson Kernel Regression using the Rational Quadratic Kernel
// For more information on this technique refer to my other open source indicator located here:
// https://www.tradingview.com/script/AWNvbPRM-Nadaraya-Watson-Rational-Quadratic-Kernel-Non-Repainting/
c_green = color.new(#009988, 20)
c_red = color.new(#CC3311, 20)
transparent = color.new(#000000, 100)
yhat1 = kernels.rationalQuadratic(settings.source, h, r, x)
yhat2 = kernels.gaussian(settings.source, h-lag, x)
kernelEstimate = yhat1
// Kernel Rates of Change
bool wasBearishRate = yhat1[2] > yhat1[1]
bool wasBullishRate = yhat1[2] < yhat1[1]
bool isBearishRate = yhat1[1] > yhat1
bool isBullishRate = yhat1[1] < yhat1
isBearishChange = isBearishRate and wasBullishRate
isBullishChange = isBullishRate and wasBearishRate
// Kernel Crossovers
bool isBullishCrossAlert = ta.crossover(yhat2, yhat1)
bool isBearishCrossAlert = ta.crossunder(yhat2, yhat1)
bool isBullishSmooth = yhat2 >= yhat1
bool isBearishSmooth = yhat2 <= yhat1
// Kernel Colors
color colorByCross = isBullishSmooth ? c_green : c_red
color colorByRate = isBullishRate ? c_green : c_red
color plotColor = showKernelEstimate ? (useKernelSmoothing ? colorByCross : colorByRate) : transparent
plot(kernelEstimate, color=plotColor, linewidth=2, title="Kernel Regression Estimate")
// Alert Variables
bool alertBullish = useKernelSmoothing ? isBullishCrossAlert : isBullishChange
bool alertBearish = useKernelSmoothing ? isBearishCrossAlert : isBearishChange
// Bullish and Bearish Filters based on Kernel
isBullish = useKernelFilter ? (useKernelSmoothing ? isBullishSmooth : isBullishRate) : true
isBearish = useKernelFilter ? (useKernelSmoothing ? isBearishSmooth : isBearishRate) : true
// ===========================
// ==== Entries and Exits ====
// ===========================
// Entry Conditions: Booleans for ML Model Position Entries
startLongTrade = isNewBuySignal and isBullish and isEmaUptrend and isSmaUptrend
startShortTrade = isNewSellSignal and isBearish and isEmaDowntrend and isSmaDowntrend
// Dynamic Exit Conditions: Booleans for ML Model Position Exits based on Fractal Filters and Kernel Regression Filters
lastSignalWasBullish = ta.barssince(startLongTrade) < ta.barssince(startShortTrade)
lastSignalWasBearish = ta.barssince(startShortTrade) < ta.barssince(startLongTrade)
barsSinceRedEntry = ta.barssince(startShortTrade)
barsSinceRedExit = ta.barssince(alertBullish)
barsSinceGreenEntry = ta.barssince(startLongTrade)
barsSinceGreenExit = ta.barssince(alertBearish)
isValidShortExit = barsSinceRedExit > barsSinceRedEntry
isValidLongExit = barsSinceGreenExit > barsSinceGreenEntry
endLongTradeDynamic = (isBearishChange and isValidLongExit[1])
endShortTradeDynamic = (isBullishChange and isValidShortExit[1])
// Fixed Exit Conditions: Booleans for ML Model Position Exits based on a Bar-Count Filters
endLongTradeStrict = ((isHeldFourBars and isLastSignalBuy) or (isHeldLessThanFourBars and isNewSellSignal and isLastSignalBuy)) and startLongTrade[4]
endShortTradeStrict = ((isHeldFourBars and isLastSignalSell) or (isHeldLessThanFourBars and isNewBuySignal and isLastSignalSell)) and startShortTrade[4]
isDynamicExitValid = not useEmaFilter and not useSmaFilter and not useKernelSmoothing
endLongTrade = settings.useDynamicExits and isDynamicExitValid ? endLongTradeDynamic : endLongTradeStrict
endShortTrade = settings.useDynamicExits and isDynamicExitValid ? endShortTradeDynamic : endShortTradeStrict
// =========================
// ==== Plotting Labels ====
// =========================
// Note: These will not repaint once the most recent bar has fully closed. By default, signals appear over the last closed bar; to override this behavior set offset=0.
plotshape(startLongTrade ? low : na, 'Buy', shape.labelup, location.belowbar, color=ml.color_green(prediction), size=size.small, offset=0)
plotshape(startShortTrade ? high : na, 'Sell', shape.labeldown, location.abovebar, ml.color_red(-prediction), size=size.small, offset=0)
plotshape(endLongTrade and settings.showExits ? high : na, 'StopBuy', shape.xcross, location.absolute, color=#3AFF17, size=size.tiny, offset=0)
plotshape(endShortTrade and settings.showExits ? low : na, 'StopSell', shape.xcross, location.absolute, color=#FD1707, size=size.tiny, offset=0)
// ================
// ==== Alerts ====
// ================
// Separate Alerts for Entries and Exits
alertcondition(startLongTrade, title='Open Long ▲', message='LDC Open Long ▲ | {{ticker}}@{{close}} | ({{interval}})')
alertcondition(endLongTrade, title='Close Long ▲', message='LDC Close Long ▲ | {{ticker}}@{{close}} | ({{interval}})')
alertcondition(startShortTrade, title='Open Short ▼', message='LDC Open Short | {{ticker}}@{{close}} | ({{interval}})')
alertcondition(endShortTrade, title='Close Short ▼', message='LDC Close Short ▼ | {{ticker}}@{{close}} | ({{interval}})')
// Combined Alerts for Entries and Exits
alertcondition(startShortTrade or startLongTrade, title='Open Position ▲▼', message='LDC Open Position ▲▼ | {{ticker}}@{{close}} | ({{interval}})')
alertcondition(endShortTrade or endLongTrade, title='Close Position ▲▼', message='LDC Close Position ▲▼ | {{ticker}}@[{{close}}] | ({{interval}})')
// Kernel Estimate Alerts
alertcondition(condition=alertBullish, title='Kernel Bullish Color Change', message='LDC Kernel Bullish ▲ | {{ticker}}@{{close}} | ({{interval}})')
alertcondition(condition=alertBearish, title='Kernel Bearish Color Change', message='LDC Kernel Bearish ▼ | {{ticker}}@{{close}} | ({{interval}})')
// =========================
// ==== Display Signals ====
// =========================
atrSpaced = useAtrOffset ? ta.atr(1) : na
compressionFactor = settings.neighborsCount / settings.colorCompression
c_pred = prediction > 0 ? color.from_gradient(prediction, 0, compressionFactor, #787b86, #009988) : prediction <= 0 ? color.from_gradient(prediction, -compressionFactor, 0, #CC3311, #787b86) : na
c_label = showBarPredictions ? c_pred : na
c_bars = showBarColors ? color.new(c_pred, 50) : na
x_val = bar_index
y_val = useAtrOffset ? prediction > 0 ? high + atrSpaced: low - atrSpaced : prediction > 0 ? high + hl2*barPredictionsOffset/20 : low - hl2*barPredictionsOffset/30
label.new(x_val, y_val, str.tostring(prediction), xloc.bar_index, yloc.price, color.new(color.white, 100), label.style_label_up, c_label, size.normal, text.align_left)
barcolor(showBarColors ? color.new(c_pred, 50) : na)
// =====================
// ==== Backtesting ====
// =====================
// The following can be used to stream signals to a backtest adapter
backTestStream = switch
startLongTrade => 1
endLongTrade => 2
startShortTrade => -1
endShortTrade => -2
plot(backTestStream, "Backtest Stream", display=display.none)
// The following can be used to display real-time trade stats. This can be a useful mechanism for obtaining real-time feedback during Feature Engineering. This does NOT replace the need to properly backtest.
// Note: In this context, a "Stop-Loss" is defined instances where the ML Signal prematurely flips directions before an exit signal can be generated.
[totalWins, totalLosses, totalEarlySignalFlips, totalTrades, tradeStatsHeader, winLossRatio, winRate] = ml.backtest(high, low, open, startLongTrade, endLongTrade, startShortTrade, endShortTrade, isEarlySignalFlip, maxBarsBackIndex, bar_index, settings.source, useWorstCase)
init_table() =>
c_transparent = color.new(color.black, 100)
table.new(position.top_right, columns=2, rows=7, frame_color=color.new(color.black, 100), frame_width=1, border_width=1, border_color=c_transparent)
update_table(tbl, tradeStatsHeader, totalTrades, totalWins, totalLosses, winLossRatio, winRate, stopLosses) =>
c_transparent = color.new(color.black, 100)
table.cell(tbl, 0, 0, tradeStatsHeader, text_halign=text.align_center, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 0, 1, 'Winrate', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 1, 1, str.tostring(totalWins / totalTrades, '#.#%'), text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 0, 2, 'Trades', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 1, 2, str.tostring(totalTrades, '#') + ' (' + str.tostring(totalWins, '#') + '|' + str.tostring(totalLosses, '#') + ')', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 0, 5, 'WL Ratio', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 1, 5, str.tostring(totalWins / totalLosses, '0.00'), text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 0, 6, 'Early Signal Flips', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 1, 6, str.tostring(totalEarlySignalFlips, '#'), text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
if showTradeStats
var tbl = ml.init_table()
if barstate.islast
update_table(tbl, tradeStatsHeader, totalTrades, totalWins, totalLosses, winLossRatio, winRate, totalEarlySignalFlips) |
MAD - Mean Absolute Deviation | https://www.tradingview.com/script/N60E4Nx2-MAD-Mean-Absolute-Deviation/ | patmaba | https://www.tradingview.com/u/patmaba/ | 51 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator("Mean Absolute Deviation", shorttitle="MAD", overlay=true)
// author : patmaba
// purpose :implementation of MAD Mean Absolute Deviation in pinescript
// Mean absolute deviation
// The mean absolute deviation of a dataset is the average distance between each data point and the mean. It gives us an idea about the variability in a dataset.
// Here's how to calculate the median absolute deviation.
// Step 1: Calculate the mean.
// Step 2: Calculate how far away each data point is from the mean using positive distances. These are called absolute deviations.
// Step 3: Add those deviations together.
// Step 4: Divide the sum by the number of data points.
//
// Source :
// https://www.khanacademy.org/math/statistics-probability/summarizing-quantitative-data/other-measures-of-spread/a/mean-absolute-deviation-mad-review
//
// Formula :
//
// ∑ |xi−µ|
// MAD = ----------
// n
//
// where
// xi = the value of a data point
// |xi − µ| = absolute deviation
// µ = mean
// n = sample size
// inputs
x = input.source(title="source", defval=close)
p = input.int(title="period", defval=50, minval=1, maxval=520)
// Constant scale factor dependent on the distribution. Default is 1.4826 expecting the data is normally distributed.
float k = 1.4826
mult = input.float(title="multiply factor k", defval=k, minval=0.01, maxval=12.0)
// Function to find mean absolute
// deviation of given elements.
mad(p_x, p_mean_value) =>
float _absSum = 0.0
// Step 2: Calculate how far away each data point is from the mean using positive distances. These are called absolute deviations.
for _i = 0 to p
_absSum := _absSum + math.abs(p_x[_i] - p_mean_value)
// Step 4: Divide the sum by the number of data points.
_mad_value = (_absSum/p)
// Return mean absolute deviation about mean.
_mad_value
// end mad -------------------------------------
// Step 1: Calculate the mean.
med = ta.sma(x,p)
// Get the mad value
mad_value = mad(close, med)
// Step 3: Add those deviations together.
mad_boundaries = mad_value*mult
// add boundaries
mad_hb = med+(mad_boundaries)
mad_lb = med-(mad_boundaries)
// apply a color information
// gray is trending
// orange warning be carreful place stop
// red bear market
var indicator_color=color.gray
if (mad_lb > close) and ( high < med )
indicator_color:=color.purple
else if (hl2 < med )
indicator_color:=color.orange
else
indicator_color:=color.gray
// Draw all
plot(mad_hb, title="mad high bound", color=indicator_color)
plot(med, title="mean", color=indicator_color)
plot(mad_lb, title="mad low bound", color=indicator_color)
|
Exponential Bollinger Bands (EBB) | https://www.tradingview.com/script/TQ4yLK9e-Exponential-Bollinger-Bands-EBB/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 38 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("Exponential Bollinger Bands", "EBB", overlay = true)
import Electrified/Interpolation/1 as i
sma(source, length)=>
var float sum = na
sum := nz(sum[1]) + close
if length % 1 != 0
sma = (sum - sum[int(length)] + (i.linear(length % 1, sum[int(length)] - sum[int(length)+1], 0, false)))/length
else
sma = (sum - sum[length])/length
stdev(source, length)=>
var float sum = na
average = sma(source, length)
sum := nz(sum[1]) + math.pow(source - average, 2)
if length % 1 != 0
stdev = math.sqrt((sum - sum[int(length)] + (i.linear(length % 1, sum[int(length)] - sum[int(length)+1], 0, false)))/(length - 1))
else
stdev = math.sqrt((sum - sum[length])/(length - 1))
bes(float source = close, float length = 9)=>
alpha = 2 / (length + 1)
var float smoothed = na
smoothed := alpha * source + (1 - alpha) * nz(smoothed[1])
estdev(source, length)=>
average = bes(source, length)
alpha = 2 / (length + 1)
var float smoothed = na
smoothed := alpha * math.pow(source-average, 2) + (1 - alpha) * nz(smoothed[1])
estdev = math.sqrt(smoothed)
average(source, length, select)=>
switch select
"SMA" => sma(source, length)
"EMA" => bes(source, length)
=> na
standard_deviation(source, length, select)=>
switch select
"SMA" => stdev(source, length)
"EMA" => estdev(source, length)
=> na
select = input.string("EMA", "Style Select", ["SMA","EMA"])
source = input.source(close, "Source")
length = input.float(20.25, "Length", 1, 2000, 0.25)
multiplier = input.float(2, "Multiplier", 0, 20, 0.25)
average = average(source, length, select)
stdev = standard_deviation(source, length, select)
top = average + stdev * multiplier
bot = average - stdev * multiplier
plot(top)
plot(average)
plot(bot)
|
Ratio Smoothed, Volume Weighted Moving Average | https://www.tradingview.com/script/WWLEKnY7-Ratio-Smoothed-Volume-Weighted-Moving-Average/ | Electrified | https://www.tradingview.com/u/Electrified/ | 134 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Electrified
// @version=5
// @This is experimental moving average doesn't use a period/length but instead buffers the price per share and transfers that price per share at a given ratio per bar while also releasing the previous values at a decay ratio.
indicator("Ratio Smoothed, Volume Weighted Moving Average", "RS-VWMA", overlay = true)
import Electrified/Time/7
src = input(hlcc4, "Source")
var useTime = input.bool(false, "Use minutes instead of bars.", tooltip = "When true will tend to make the values consistent across timeframes.")
var minutesPerBar = Time.bar() / 1000 / 60
var m = useTime ? minutesPerBar : 1
var transferRatio = input.float(10.0, "Transfer Ratio (%)", 0.00000001, 100, step = 0.1, tooltip = "The ratio at which buffered data is applied to the average.") / 100
var retainRatio = 1 - input.float(2, "Release Ratio (%)", 0.00000001, 100, step = 0.1, tooltip = "The ratio at which data is released from the average") / 100
type VWAP
float sum
float volume
float value
vwap(float sum, float vol, float ratio = 1) =>
VWAP.new(ratio * sum, ratio * vol, sum/vol)
sum(VWAP a, VWAP b, float ratio = 1) =>
s = a.sum + b.sum
v = a.volume + b.volume
vwap(s, v, ratio)
var active = VWAP.new(0, 0, 0)
var surplus = VWAP.new(0, 0, 0)
getNewSurplus() =>
var r = math.pow(1 - transferRatio, m)
s = surplus.sum + src * volume
v = surplus.volume + volume
[vwap(s, v, 1 - r), vwap(s, v, r)]
[transfer, remainder] = getNewSurplus()
surplus := remainder
active := sum(active, transfer, math.pow(retainRatio, m))
plot(active.value, "RS-VWMA", color.rgb(155, 78, 214), 2)
|
Stablecoin supplies [USD bn] | https://www.tradingview.com/script/JNMLXipF-Stablecoin-supplies-USD-bn/ | tedtalksmacro | https://www.tradingview.com/u/tedtalksmacro/ | 234 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tedtalksmacro
//@version=5
indicator("Crypto USD Liquidity [tedtalksmacro]")
usdt_supply = request.security("GLASSNODE:USDT_SUPPLY", 'D', close)
busd_supply = request.security("GLASSNODE:BUSD_SUPPLY", 'D', close)
usdc_supply = request.security("GLASSNODE:USDC_SUPPLY", 'D', close)
dai_supply = request.security("CRYPTOCAP:DAI", 'D', close)
tusd_supply = request.security("CRYPTOCAP:TUSD", 'D', close)
value = (usdt_supply + busd_supply + usdc_supply + dai_supply + tusd_supply) / 1000000000
var lineColor = true
ema20 = ta.ema(value, 20)
bullish = value > ema20
bearish = value < ema20
if lineColor
if bearish
lineColor := false
if not lineColor
if bullish
lineColor := true
// mycolor = higher ? color.silver : lower ? color.blue : na
supplyColor = lineColor ? color.rgb(101, 171, 103) : color.rgb(197, 10, 10)
plot(value, transp = 0, linewidth=2, color= supplyColor) |
Stochastic RSI Screener | https://www.tradingview.com/script/eDkbHmhH-Stochastic-RSI-Screener/ | Forex_Associate | https://www.tradingview.com/u/Forex_Associate/ | 82 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Forex_Associate (Abbas Borji)
//@version=5
indicator('Stochastic RSI Screener', overlay=true)
////////////
// Inputs //
candle = input(close, title='Candle State')
rsi_len = input.int(14, title = "RSI Length", group = 'Stochastic RSI')
rsi_os = input.float(30, title = "RSI Overbought", group = 'Stochastic RSI')
rsi_ob = input.float(70, title = "RSI Oversold", group = 'Stochastic RSI')
smoothKD = input.int(3, 'K & D Smoothing', minval=1, group='Stochastic RSI')
lengthStoch = input.int(14, 'Stochastic Length', minval=1, group='Stochastic RSI')
stoch_low = input.int(20, title='Stoch Oversold Level', group='Stochastic RSI')
stoch_high = input.int(80, title='Stoch Overbought Level', group='Stochastic RSI')
// Flags & Symbols
u01 = input.bool(true, title = "", group = 'Symbols', inline = 's01')
u02 = input.bool(true, title = "", group = 'Symbols', inline = 's02')
u03 = input.bool(true, title = "", group = 'Symbols', inline = 's03')
u04 = input.bool(true, title = "", group = 'Symbols', inline = 's04')
u05 = input.bool(true, title = "", group = 'Symbols', inline = 's05')
s01 = input.symbol('EURUSD', group = 'Symbols', inline = 's01')
s02 = input.symbol('GBPUSD', group = 'Symbols', inline = 's02')
s03 = input.symbol('AUDUSD', group = 'Symbols', inline = 's03')
s04 = input.symbol('USDJPY', group = 'Symbols', inline = 's04')
s05 = input.symbol('USDCAD', group = 'Symbols', inline = 's05')
//////////////////
// Functions //
// Get Only Symbol
only_symbol(symbol) =>
array.get(str.split(symbol, ":"), 1)
// Calculations
calculate() =>
rsi = ta.rsi(candle, rsi_len)
k_value = ta.sma(ta.stoch(rsi, rsi, rsi, lengthStoch), smoothKD)
d_value = ta.sma(k_value, smoothKD)
[math.round_to_mintick(candle), rsi, k_value, d_value]
////////////
// Security Calls //
[candle01, rsi01, k01, d01] = request.security(s01, timeframe.period, calculate())
[candle02, rsi02, k02, d02] = request.security(s02, timeframe.period, calculate())
[candle03, rsi03, k03, d03] = request.security(s03, timeframe.period, calculate())
[candle04, rsi04, k04, d04] = request.security(s04, timeframe.period, calculate())
[candle05, rsi05, k05, d05] = request.security(s05, timeframe.period, calculate())
////////////
// Arrays //
s_arr = array.new_string(0)
u_arr = array.new_bool(0)
candle_arr = array.new_float(0)
rsi_arr = array.new_float(0)
k_arr = array.new_float(0)
d_arr = array.new_float(0)
///////////
// Symbols //
array.push(s_arr, only_symbol(s01))
array.push(s_arr, only_symbol(s02))
array.push(s_arr, only_symbol(s03))
array.push(s_arr, only_symbol(s04))
array.push(s_arr, only_symbol(s05))
///////////
// Flags //
array.push(u_arr, u01)
array.push(u_arr, u02)
array.push(u_arr, u03)
array.push(u_arr, u04)
array.push(u_arr, u05)
///////////
// Candle Values //
array.push(candle_arr, candle01)
array.push(candle_arr, candle02)
array.push(candle_arr, candle03)
array.push(candle_arr, candle04)
array.push(candle_arr, candle05)
/////////
// RSI Values//
array.push(rsi_arr, rsi01)
array.push(rsi_arr, rsi02)
array.push(rsi_arr, rsi03)
array.push(rsi_arr, rsi04)
array.push(rsi_arr, rsi05)
/////////
// K Values //
array.push(k_arr, k01)
array.push(k_arr, k02)
array.push(k_arr, k03)
array.push(k_arr, k04)
array.push(k_arr, k05)
/////////
// D Values //
array.push(d_arr, d01)
array.push(d_arr, d02)
array.push(d_arr, d03)
array.push(d_arr, d04)
array.push(d_arr, d05)
///////////
// Table //
var tbl = table.new(position.top_right, 5, 6, frame_color=color.navy, frame_width=1, border_width=2, border_color=color.new(color.white, 100))
if barstate.islast
table.cell(tbl, 0, 0, 'Symbol', text_halign = text.align_center, bgcolor = color.navy, text_color = color.white, text_size = size.small)
table.cell(tbl, 1, 0, 'Price', text_halign = text.align_center, bgcolor = color.navy, text_color = color.white, text_size = size.small)
table.cell(tbl, 2, 0, 'RSI', text_halign = text.align_center, bgcolor = color.navy, text_color = color.white, text_size = size.small)
table.cell(tbl, 3, 0, 'K Value', text_halign = text.align_center, bgcolor = color.navy, text_color = color.white, text_size = size.small)
table.cell(tbl, 4, 0, 'D Value', text_halign = text.align_center, bgcolor = color.navy, text_color = color.white, text_size = size.small)
for i = 0 to 4
if array.get(u_arr, i)
rsi_col = array.get(rsi_arr, i) > rsi_ob ? color.red : array.get(rsi_arr, i) < rsi_os ? color.green : #aaaaaa
k_col = array.get(k_arr, i) > stoch_high ? color.red : array.get(k_arr, i) < stoch_low ? color.green : #aaaaaa
d_col = array.get(d_arr, i) > stoch_high ? color.red : array.get(d_arr, i) < stoch_low ? color.green : #aaaaaa
table.cell(tbl, 0, i + 1, array.get(s_arr, i), text_halign = text.align_left, bgcolor = #FFA500, text_color = color.navy, text_size = size.small)
table.cell(tbl, 1, i + 1, str.tostring(array.get(candle_arr, i)), text_halign = text.align_center, bgcolor = #aaaaaa, text_color = color.white, text_size = size.small)
table.cell(tbl, 2, i + 1, str.tostring(array.get(rsi_arr, i), "#.##"), text_halign = text.align_center, bgcolor = rsi_col, text_color = color.white, text_size = size.small)
table.cell(tbl, 3, i + 1, str.tostring(array.get(k_arr, i), "#.##"), text_halign = text.align_center, bgcolor = k_col, text_color = color.white, text_size = size.small)
table.cell(tbl, 4, i + 1, str.tostring(array.get(d_arr, i), "#.##"), text_halign = text.align_center, bgcolor = d_col, text_color = color.white, text_size = size.small) |
KST-Based MACD | https://www.tradingview.com/script/ZwhyF7TU-KST-Based-MACD/ | akikostas | https://www.tradingview.com/u/akikostas/ | 268 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © akikostas
//@version=5
indicator(title="MACD (KST Based)", shorttitle="MACD-KST", timeframe="", timeframe_gaps=true)
// Getting inputs
roclen1 = input.int(10, minval=1, title = "ROC Length #1", group = "KST Settings")
roclen2 = input.int(15, minval=1, title = "ROC Length #2", group = "KST Settings")
roclen3 = input.int(20, minval=1, title = "ROC Length #3", group = "KST Settings")
roclen4 = input.int(30, minval=1, title = "ROC Length #4", group = "KST Settings")
smalen1 = input.int(10, minval=1, title = "SMA Length #1", group = "KST Settings")
smalen2 = input.int(10, minval=1, title = "SMA Length #2", group = "KST Settings")
smalen3 = input.int(10, minval=1, title = "SMA Length #3", group = "KST Settings")
smalen4 = input.int(15, minval=1, title = "SMA Length #4", group = "KST Settings")
source = input(close, title = "Source", group = "KST Settings")
typeMA = input.string(title = "Method", defval = "EMA", options=["SMA", "EMA"], group="KST Settings")
exotic = input.bool(false, title = "Exotic Calculations", group = "KST Settings")
fast_length = input(title="Fast Length", defval=7, group = "MACD Settings")
slow_length = input(title="Slow Length", defval=14, group = "MACD Settings")
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 14, group = "MACD Settings")
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"], group = "MACD Settings")
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"], group = "MACD Settings")
length1 = input.int(5, title="EMA-1 period", minval=1, group = "Ribbon Settings")
length2 = input.int(10, title="EMA-2 period", minval=1, group = "Ribbon Settings")
length3 = input.int(15, title="EMA-3 period", minval=1, group = "Ribbon Settings")
length4 = input.int(20, title="EMA-4 period", minval=1, group = "Ribbon Settings")
length5 = input.int(25, title="EMA-5 period", minval=1, group = "Ribbon Settings")
length6 = input.int(30, title="EMA-6 period", minval=1, group = "Ribbon Settings")
length7 = input.int(35, title="EMA-7 period", minval=1, group = "Ribbon Settings")
length8 = input.int(40, title="EMA-8 period", minval=1, group = "Ribbon Settings")
// Plot colors
col_macd = input(#00bcd4, "MACD Line ", group="Color Settings", inline="MACD")
col_signal = input(#f57c00cc, "Signal Line ", group="Color Settings", inline="Signal")
col_grow_above = input(#056656, "Above Grow", group="Histogram", inline="Above")
col_fall_above = input(#d1d4dc, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#d1d4dc, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#e91e63, "Fall", group="Histogram", inline="Below")
// Calculating
logarithmic(src)=> math.sign(src) * math.log(math.abs(src) + 1)
mas(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
price = source
roc(p, l)=> 100 * (p - p[l]) / p[l]
rocl(p, l)=> 100 * (logarithmic(p) - logarithmic(p[l]))
smaroc(roclen, smalen) => mas(roc(price, roclen), smalen, typeMA)
smarocl(roclen, smalen) => mas(rocl(price, roclen), smalen, typeMA)
kst = smaroc(roclen1, smalen1) + 2 * smaroc(roclen2, smalen2) + 3 * smaroc(roclen3, smalen3) + 4 * smaroc(roclen4, smalen4)
if (exotic)
kst := smarocl(roclen1, smalen1) + 2 * smarocl(roclen2, smalen2) + 3 * smarocl(roclen3, smalen3) + 4 * smarocl(roclen4, smalen4)
fast_ma = sma_source == "SMA" ? ta.sma(kst, fast_length) : ta.ema(kst, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(kst, slow_length) : ta.ema(kst, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
hline(0, "Zero Line", color=color.new(#787B86, 75), linestyle=hline.style_solid)
p8 = plot(ta.ema(macd, length8), title="EMA-8", color=#3c066340, linewidth=2)
p7 = plot(ta.ema(macd, length7), title="EMA-7", color=#4a0a7740, linewidth=2)
p6 = plot(ta.ema(macd, length6), title="EMA-6", color=#5a108f40, linewidth=2)
p5 = plot(ta.ema(macd, length5), title="EMA-5", color=#6818a540, linewidth=2)
p4 = plot(ta.ema(macd, length4), title="EMA-4", color=#8b2fc940, linewidth=2)
p3 = plot(ta.ema(macd, length3), title="EMA-3", color=#ab51e340, linewidth=2)
p2 = plot(ta.ema(macd, length2), title="EMA-2", color=#bd68ee40, linewidth=2)
p1 = plot(ta.ema(macd, length1), title="EMA-1", color=#d283ff40, linewidth=2)
plot(hist, title="Histogram", style=plot.style_area, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
plot(signal, title="Signal", color=col_signal, linewidth=3, display=display.none)
p0 = plot(macd, title="MACD", color=col_macd, linewidth=3)
fill(p8, p7, title="Area 8", color=#3c066320)
fill(p7, p6, title="Area 7", color=#4a0a7720)
fill(p6, p5, title="Area 6", color=#5a108f20)
fill(p5, p4, title="Area 5", color=#6818a520)
fill(p4, p3, title="Area 4", color=#8b2fc920)
fill(p3, p2, title="Area 3", color=#ab51e320)
fill(p2, p1, title="Area 2", color=#bd68ee20)
fill(p1, p0, title="Area 1", color=#d283ff20) |
Oscillator: Which follows Normal Distribution? | https://www.tradingview.com/script/WGz99Mfk-Oscillator-Which-follows-Normal-Distribution/ | Dicargo_Beam | https://www.tradingview.com/u/Dicargo_Beam/ | 60 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Dicargo_Beam
//@version=5
indicator("Oscillator: Which follows Normal Distribution?", max_lines_count = 120)
//When doing machine learning using oscillators,
//it would be better if the oscillators were normally distributed.
//So I analyzed the distribution of oscillators.
len = input.int(14,"Oscillator Length", minval=2)
src = input.source(close,"Source")
wavetrend(src, len1, len2, normalize)=>
//[LazyBear]
//default value: src = hlc3, len1 = 10, len2 = 21
esa = ta.ema(src, len1)
d = ta.ema(math.abs(src - esa), len1)
ci = (src - esa) / (0.015 * d)
tci = ta.ema(ci, len2)
normalize? tci/2+50 : tci
adx(len, normalize)=> //
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / trur)
minus = fixnan(100 * ta.rma(minusDM, len) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), len)
//below is empirical expression
adx := normalize? (math.log(adx)-ta.cum(math.log(adx))/bar_index)/1.7*50+50 : (adx-40)/4*5+50
plus := normalize? (math.log(plus)-ta.cum(math.log(plus))/bar_index)/1.7*50+50 : (plus-40)/4*5+50
minus := normalize? (math.log(minus)-ta.cum(math.log(minus))/bar_index)/1.7*50+50 : (minus-40)/4*5+50
[adx, plus, minus]
[_adx, _plus, _minus] = adx(len, true)
[adx, plus, minus] = adx(len, false)
rvi(src,len) => //Relative Volatility Index
stddev = ta.stdev(src, len)
upper = ta.ema(ta.change(src) <= 0 ? 0 : stddev, len)
lower = ta.ema(ta.change(src) > 0 ? 0 : stddev, len)
rvi = upper / (upper + lower) * 100
cmo(src,len) => //Chande Momentum Oscillator
momm = ta.change(src)
m1 = momm >= 0.0 ? momm : 0.0
m2 = momm >= 0.0 ? 0.0 : -momm
sm1 = math.sum(m1, len)
sm2 = math.sum(m2, len)
chandeMO = 100 * (sm1-sm2) / (sm1+sm2)
normalized_cmo = chandeMO/2+50
imi(len) => //Intraday Momentum Index
gain = close > open ? close - open : 0
loss = close > open ? 0 : open - close
upSum = math.sum(gain, len)
downSum = math.sum(loss, len)
imi = 100 * upSum / (upSum + downSum)
williamsR(src,len)=>
max = ta.highest(len)
min = ta.lowest(len)
100 * (src - max) / (max - min) + 100
vrsi(src,len)=>
ta.rsi(ta.cum(ta.change(src)*volume),len) // by RicardoSantos
Osc_Type = input.string("Relative Strength Index", "Ocilator type",
options = ["Relative Strength Index", "Money Flow Index", "Average Directional Index(ADX)","+DI", "-DI",
"Logged ADX", "WaveTrend", "Stochastic", "Stoch_Only_Close",
"Relative Volatility Index", "Chande Momentum Oscillator", "Intraday Momentum Index", "Williams %R", "Volume Relative Strength Index"],
tooltip="WaveTrend(length, length*2+1)\nStoch(length, 2)\nLogged ADX is log(adx) # try length under 22")
osc = switch Osc_Type
"Money Flow Index" => ta.mfi(src, len)
"Average Directional Index(ADX)" => adx
"+DI" => plus
"-DI" => minus
"Logged ADX" => _adx
"WaveTrend" => wavetrend(close, len, len*2+1, true)
"Stochastic" => ta.sma(ta.stoch(close, high, low, len),2)
"Stoch_Only_Close" => ta.sma(ta.stoch(close, close, close, len),2)
"Relative Volatility Index" => rvi(src,len)
"Chande Momentum Oscillator" => cmo(src,len)
"Intraday Momentum Index" => imi(len)
"Williams %R" => williamsR(src, len)
"Volume Relative Strength Index" => vrsi(src,len)
=> ta.rsi(src,len)
//get values
var osc_range = array.new_int(51,0)
get_samples()=>
mean = 50
for i = 0 to 50
if math.round(osc/2)*2 > i*2-0.5 and math.round(osc/2)*2 < i*2+0.5
array.set(osc_range, i, array.get(osc_range,i) + 1)
sample_num = array.sum(osc_range) //sum of number of samples
variance_sum = 0.0
for i = 0 to 50
variance_sum += math.pow(i*2 - mean,2) * array.get(osc_range,i)
var osc_stdev = 0.0
variance = variance_sum/sample_num
osc_stdev := math.pow(variance,0.5)
var _95_percent_confidence_interval = 0.0
//Z = (X-50) / rsi_stdev
var X1 = 0
var X2 = 0
X1 := math.max(0,math.round((50 - 1.96*osc_stdev)/2)*2), X2 := math.min(math.round((50 + 1.96*osc_stdev)/2)*2,100)
_95_percent_confidence_interval_num = 0.0
for i = int(X1/2) to int(X2/2)
_95_percent_confidence_interval_num += array.get(osc_range,i)
_95_percent_confidence_interval := _95_percent_confidence_interval_num/sample_num*100
[sample_num, osc_stdev, _95_percent_confidence_interval, mean, X1, X2]
[sample_num, osc_stdev, _95_percent_confidence_interva, mean, X1, X2] = get_samples()
//draw Normalized Distribution Graph
pdf(x) => 1/(math.pow(math.pi*2,0.5)*osc_stdev)*math.exp(-0.5*math.pow(x,2)/math.pow(osc_stdev,2))
var pdf_range = array.new_float(51,0)
get_pdf()=>
for i = 0 to 50
array.set(pdf_range, i, pdf((i*2-50)))
get_pdf()
var pdf_lines = array.new_line()
if barstate.islast
for i = 0 to 49
array.push(pdf_lines, line.new(bar_index+5 + i*2, array.get(pdf_range, i)*2000, bar_index+5 + i*2+2, array.get(pdf_range, i+1)*2000, color=color.orange))
if array.size(pdf_lines) > 50
pdf_line_del = array.shift(pdf_lines)
line.delete(pdf_line_del)
//check if it follows Normal Distribution
check()=>
variance_sum = 0.0
for i = 0 to 50
variance_sum += math.abs((array.get(osc_range, i)/sample_num*1000-array.get(pdf_range, i)*2000)*(math.pow(math.abs(i-25)+2,0.5)))
var check_stdev = 0.0
variance = variance_sum/5
check_stdev := math.pow(variance,0.5)
var string txt = na
var color col = na
//verifying normal distribution
if check_stdev > 9 //this is empirical constant
txt := "This not follow normal distribution "
col := color.red
else
txt := "This follow normal distribution "
col := color.green
[txt, col, check_stdev]
[verification_txt, verification_col, check_stdev] = check()
var label check_label = na
if barstate.islast
check_label := label.new(bar_index+55 , math.max(100,array.max(osc_range)/sample_num*1000), text = verification_txt,
style=label.style_label_down, color=color.new(color.black,99), textcolor=verification_col)
label.delete(check_label[1])
//Oscillator Name
var label name_label = na
if barstate.islast
name_label := label.new(bar_index-20, 100, text = Osc_Type,
style=label.style_label_down, color=color.new(color.black,99), textcolor=color.rgb(131, 236, 44))
label.delete(name_label[1])
//draw Oscillator's Distribution
var lines = array.new_line()
var labels = array.new_label()
var box rangebox = na
conf_msg = if X1 != 0
str.tostring(X1) + " to "+ str.tostring(X2) + " covers " +str.tostring(_95_percent_confidence_interva,"#.0")+" %"
else
""
txt_length = if Osc_Type == "WaveTrend"
str.tostring(len)+", "+str.tostring(len*2+1)
else if Osc_Type == "Stochastic" or Osc_Type == "Stoch_Only_Close"
str.tostring(len)+", 2"
else
str.tostring(len)
if barstate.islast
rangebox := box.new(bar_index+5, math.max(100,array.max(osc_range)/sample_num*1000), bar_index+105, 0, bgcolor=color.new(color.green,90),
text = "Samples = "+str.tostring(sample_num)+"\n"+Osc_Type+"'s length = " + txt_length+"\nstdev = "+str.tostring(osc_stdev,"#.##")+"\n"+conf_msg,
text_size = size.normal, text_color = color.rgb(170, 154, 5),text_halign = text.align_right, text_valign = text.align_top)
for i = 0 to 50
array.push(lines, line.new(bar_index+5 + i*2, 0, bar_index+5 + i*2, array.get(osc_range, i)/sample_num*1000 ) )
if i == 25
array.push(labels, label.new(bar_index+5 + i*2, 0, text = " "+str.tostring(i*2)+ "\nZ="+str.tostring((i*2-mean)/osc_stdev,"#.##"),
style=label.style_label_up, color=color.new(color.black,99), textcolor=color.rgb(150, 180, 13)))
if (i == int(X1/2) or i == int(X2/2)) and X1!=0
array.push(labels, label.new(bar_index+5 + i*2, 0, text = " "+str.tostring(i*2)+ "\nZ="+str.tostring((i*2-mean)/osc_stdev,"#.##"),
style=label.style_label_up, color=color.new(color.black,99), textcolor=color.rgb(150, 180, 13)))
if array.size(lines) > 51
line_del = array.shift(lines)
line.delete(line_del)
n = X1!=0? 3:1
if array.size(labels) > n
label_del = array.shift(labels)
label.delete(label_del)
box.delete(rangebox[1])
//plot Oscillator
plot(osc, "Oscillator", color=color.aqua)
plot(0, "0", color=color.gray)
plot(50,"50", color=color.gray)
plot(100,"100", color=color.gray)
|
Rev FX Avg Spread | https://www.tradingview.com/script/MZSOeTFe-Rev-FX-Avg-Spread/ | SparkBux | https://www.tradingview.com/u/SparkBux/ | 3 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SparkBux
//@version=5
// edit 09:22:00
indicator("Rev FX Spread", overlay=true)
plot(close*0.9991, color=color.lime)
plot(close*1.0007, color=color.red) |
Morning Option Pullback Indicator | https://www.tradingview.com/script/ltcNJdtB-Morning-Option-Pullback-Indicator/ | benjaminbarch | https://www.tradingview.com/u/benjaminbarch/ | 190 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © benjaminbarch
//@version=5
indicator(title="Morning Option Pullback Indicator", shorttitle="MOPI", overlay = true)
// --- WHAT THIS INDICATOR DOES --- {
//
// Name: MOPI (Morning Option Pullback Indicator)
//
// Use at your own risk. No guarantees come with this indicator.
// Designed for use on the 1 min chart for the SPY and QQQ tickers to assist me in Option CALL and PUT Signals
// This indicator watches for morning opening price to break above or below the pre-market channel
// Then waits for a specific type of pull back where the price touches the Medium Length EMA (EMA20 default)
// And indicates a Buy signal for a CALL or a PUT depending on certain other conditions
//
// END WHAT THIS INDICATOR DOES }
// --- INPUTS ---{
//Calculate Live or at Candle Close?
UseLiveCalculation = input.bool(defval = true, title = "Calculate on Live Candle?", group="General Settings", tooltip = "Checked = The indicator checks for the pocess during live candles at every tick. Unchecked = The Indicator looks for the process only when the Candle Closes.")
LimitOneTradePerSession = input.bool(defval = true, title = "Limit to One Trade per Session?", group="General Settings", tooltip = "Checked = Only the first signal of each session goes off per ticker, Unchecked = Subsequent signals could go off in the same day")
//Debug and Verbose Mode
DebugVerboseMode = input.bool(title="Debug Verbose Mode?", defval = true, group="General Settings", tooltip="Plots more data to help in debugging code or to just give more info")
//Close position at end of session
ClosePositionAtEndOfDay = input.bool(title="Force Close Position at End of Day?", defval = true, group="General Settings", tooltip="Closes any open positions at the end of each session if a trade has not yet hit it's Profit Target or Stop Loss")
//Take Profit and Stop Loss Settings
rewardTarget = input.float(title="Profit Target", defval = 2.0, minval=0.01, maxval = 100, step=0.1, group="Target TP/SL Points")
riskTarget = input.float(title="Stop Loss Risk", defval = 0.5, minval=0.01, maxval = 100, step=0.1, group="Target TP/SL Points")
// Ignore signals after recent entry or exit
UseIgnoreTrade = input.bool(defval = true, title = "Ignore if recent Signal -", group="History", inline="ignore", tooltip = "Helps prevent multiple signals in a row for a single entry. Ignore signaling a subsequent buy if we've recently signaled, entered, or exited a trade?")
NumCandlesToIgnore = input.int(defval=12, minval=1, maxval=1000, title="# of Candles", group="History", inline="ignore")
//EMA Hold Time
NumCandlesEMA = input.int(defval=4, minval=1, maxval=1000, title="EMA Uncrossed Candle History", group="History", tooltip="# of recent historic candles EMAs must stay apart without touching or crossing. This helps filter a clear EMA trend vs chop")
//Padding
paddingPriceToEMA = input.float(title="Price to EmaMedium Distance", defval=0.10, step=0.01, minval=0.0, maxval=1000.0, group="How Close is Close Enough?", tooltip = "Set to 0 to disable. The price distance within the price and EmaMedium line need to be to one another to consider it close enough")
//paddingPriceToPMHL = input.float(title="Price to PM H/L Distance", defval=0.15, step=0.01, minval=0.0, maxval=1000.0, group="How Close is Close Enough?", tooltip = "Set to 0 to disable. How far the price can dip back within the channel to consider it close enough to still be considrered outside the channel")
// % of PM spread
SpreadPercentUpperLimit = input.int(title="Upper % limit", defval=150, step=5, group="% price distance from H/L as related to PM spread", tooltip="If the spread of premarket was $2, then setting this to 100% allows the signal to go off up to $2 higher than the PM high. Set it to 200% and it allows it to go off up to $4 higher than the PM high line for a good signal. Keeping this in check can help deter a fake signal when there is a huge parabolic move before a first pullback")
SpreadPercentLowerLimit= input.int(title="Lower % limit", defval=-10, step=5, group="% price distance from H/L as related to PM spread", tooltip="A negative number allows the price to be under the PM high line (or witihin the channel) in case padding was used for an entry")
//Display EMAs
DisplayEmaShort = input.bool(title="Display Short", defval=true, group="General Settings", inline="short")
EmaShortInput = input.int(title="EMA?", defval=5, step=1, group="General Settings", inline="short", tooltip="Short Time Frame EMA")
DisplayEmaMedium = input.bool(title="Display Medium", defval=true, group="General Settings", inline="medium")
EmaMediumInput = input.int(title="EMA?", defval=20, step=1, group="General Settings", inline="medium", tooltip="Medium Time Frame EMA")
DisplayEmaLong = input.bool(title="Display Long", defval=true, group="General Settings", inline="long")
EmaLongInput = input.int(title="EMA?", defval=233, step=1, group="General Settings", inline="long", tooltip="Long Time Frame EMA")
//Pre-Market Inputs
thresholdAtrPercent = input.float(title="ATR threshold %", defval=300, step=10, minval=1, maxval=10000, group="Pre-Market H/L Calculation", tooltip="Compares ATR(2) with ATR(14), Threshold must be under this number. The larger the number, the tighter to price action the PM Lines stick to. A lower number in this setting will allow quick price ation to blow over")
PreMarketSession = input.session(title="Pre-Market Hours", defval="0400-0930", group="Pre-Market H/L Calculation")
// Set the Trading Session Hours
MorningTradingSession = input.session(defval="0935-1100", title="Morning Hours", group="Trading Sessions")
//UseAfternoonSession = input.bool(defval = false, title = "Use", group="Trading Sessions", inline="Afternoon", tooltip = "Must be checked in order to use Afternoon Hours, otherwise Afternon hours will be ignored. Check the box if you want to divde your day into two separate sessions")
//AfternoonTradingSession = input.session(defval="1400-1530", title="Afternoon Hours?", group="Trading Sessions", inline="Afternoon")
// Define if we are using the TICK.US filter
UseTickFilter = input.bool(defval = false, title = "Use TICK.US Filter?", group="TICK.US Filter", tooltip = "Affects Buy signals. When checked, signals and alerts will only go off when levels exceed the threshold. Checks TICK.US to see if the average of the EMA5 and EMA20 lines on the 10 min chart are more than +/- threshold range.")
NumCandlesTICKRequirement = input.int(defval=0, minval=0, maxval=1000, title="Also require # of history Candles", group="TICK.US Filter", tooltip="Set to 0 to disable. Requires that a number of historical bars TICK.US filter also be true")
UseTickFilterBG = input.bool(defval = false, title = "Color the Background?", group="TICK.US Filter", tooltip = "Should Color be applied the background? Colors the background green if the avg >= upper threshold and red if the avg is <= lower threshold. No color if within the thresholds.")
UpperTenMinEmaTickUSthreshold = input.int(title="TICK.US Upper avg threshold", defval=100, minval=1, maxval=1000, step=50, group="TICK.US Filter", tooltip="The average of the EMA 5 and EMA 20 of the TICK.US chart on the 10 min timeframe. This is the threshold which will trigger a green background. 100 by default")
LowerTenMinEmaTickUSthreshold = input.int(title="TICK.US Lower avg threshold", defval=-100, minval=-1000, maxval=-1, step=50, group="TICK.US Filter", tooltip="The average of the EMA 5 and EMA 20 of the TICK.US chart on the 10 min timeframe. This is the threshold which will trigger a red background. -100 by default")
okToTradeMonday = input.bool(defval = true, title = "Monday", group="Trading Days", tooltip = "Which days of the week do you want to get signals? For instance I leave Friday turned off because it's the worst performing day of the week for this indicator")
okToTradeTuesday = input.bool(defval = true, title = "Tuesday", group="Trading Days", tooltip = "Which days of the week do you want to get signals? For instance I leave Friday turned off because it's the worst performing day of the week for this indicator")
okToTradeWednesday = input.bool(defval = true, title = "Wednesday", group="Trading Days", tooltip = "Which days of the week do you want to get signals? For instance I leave Friday turned off because it's the worst performing day of the week for this indicator")
okToTradeThursday = input.bool(defval = true, title = "Thursday", group="Trading Days", tooltip = "Which days of the week do you want to get signals? For instance I leave Friday turned off because it's the worst performing day of the week for this indicator")
okToTradeFriday = input.bool(defval = true, title = "Friday", group="Trading Days", tooltip = "Which days of the week do you want to get signals? For instance I leave Friday turned off because it's the worst performing day of the week for this indicator")
SignalBoxColor = input.color(defval = color.new(color.blue, 0), title = "Signal Box Color", group = "Box Color")
ProfitBoxColor = input.color(defval = color.new(color.green, 0), title = "Profit Box Color", group = "Box Color")
LossBoxColor = input.color(defval = color.new(color.red, 0), title = "Loss Box Color", group = "Box Color")
// --- END INPUTS --- }
// --- VARIABLES --- {
var float PMcalculatedHigh = na // The ending results of the calculated PreMarketSession
var float PMcalculatedLow = na
var currentlyInCallTrade = false
var currentlyInPutTrade = false
var TradedToday = false
var BuyCallSignal = false
var BuyPutSignal = false
var float TP = na
var float SL = na
var float EntryPrice = na
atr2 = ta.atr(2)
atr14 = ta.atr(14)
CurrentAtrPercent = 0.0
EmaShort = ta.ema(close, EmaShortInput)
EmaMedium = ta.ema(close, EmaMediumInput)
EmaLong = ta.ema(close,EmaLongInput)
SellProfitSignal = false
SellLossSignal = false
recentSignal = false // resets back to false to start every calulation and we will check to see if it's true with each new tick
EmaShortStayedAboveEmaMediumRecently = false
EmaShortStayedBelowEmaMediumRecently = false
IsTickBeyondThreshold = false
IsTickHistoryBeyondThreshold = false
BarCloseAndLowOnOppositeSidesOfEmaMedium = false //used when Live Calcluation is off.
BarCloseAndHighOnOppositeSidesOfEmaMedium = false
lastBarOfRegularHours = false
okToTradeThisDay = false
// --- END VARIABLES --- }
// --- CUSTOM FUNCTIONS --- {
//establish a new function to check if we are in a session. This will simplify the code.
isInSession(_sess) => not na(time(timeframe.period, _sess))
// --- END CUSTOM FUNCTIONS }
// --- MAIN BODY CALCULATIONS --- {
//Check if we are ok to trade this day of week
if dayofweek == 2 and okToTradeMonday
okToTradeThisDay := true
else if dayofweek == 3 and okToTradeTuesday
okToTradeThisDay := true
else if dayofweek == 4 and okToTradeWednesday
okToTradeThisDay := true
else if dayofweek == 5 and okToTradeThursday
okToTradeThisDay := true
else if dayofweek == 6 and okToTradeFriday
okToTradeThisDay := true
//Check if this is the last bar of the day
if hour == 15 and minute == 59
lastBarOfRegularHours := true
// Highlight the last bar in the session with a fuchsia background for debugging
//bgcolor(lastBarOfRegularHours ? color.new(color.fuchsia, 80) : na)
//Reset the TradedToday boolean flag at the beginning of each session
if isInSession(MorningTradingSession) and not isInSession(MorningTradingSession)[1] // First tick of Morning session
TradedToday := false
//else if isInSession(AfternoonTradingSession) and not isInSession(AfternoonTradingSession)[1] // First tick of Afternoon session
// TradedToday := false
// --- GET PRE-MARKET H/L --- {
CurrentAtrPercent := (atr2 / atr14) * 100
if isInSession(PreMarketSession) and (not isInSession(PreMarketSession)[1]) // If this is the first bar of pre-market
PMcalculatedHigh := na //reset variables
PMcalculatedLow := na
if isInSession(PreMarketSession)
if (na(PMcalculatedHigh) and CurrentAtrPercent <= thresholdAtrPercent) or (CurrentAtrPercent <= thresholdAtrPercent and (close > PMcalculatedHigh or open > PMcalculatedHigh))//If we don't have a Calculated PM High yet or our current open/close is higher, update the calcuated highest
PMcalculatedHigh := close > open ? close : open //store the higher of either the open or the close
if (na(PMcalculatedLow) and CurrentAtrPercent <= thresholdAtrPercent) or (CurrentAtrPercent <= thresholdAtrPercent and (close < PMcalculatedLow or open < PMcalculatedLow))
PMcalculatedLow := close < open ? close : open
// --- END GET PRE-MARKET H/L}
// --- CHECKING THE PROCESS ---{
// TICK.US Filter data - Check the EMA5 and EMA20 on the TICK.US 10 min chart.
extendedTicker = ticker.modify("TICK.US", session = session.extended) //set session to include extended hours. default session for request security function only grabs data from regular hours.
ema5TICK = request.security(symbol=extendedTicker, timeframe="10", expression=ta.ema(close, 5)) // We want repainting to happen and get the most recent calculation, dont code it out
ema20TICK = request.security(symbol=extendedTicker, timeframe="10", expression=ta.ema(close, 20))
tenMinEmaTickUS = (ema5TICK + ema20TICK) / 2 // Get the average of the EMA5/20 lines and set our "ten min TICK EMA variable"
if (tenMinEmaTickUS > UpperTenMinEmaTickUSthreshold or tenMinEmaTickUS < LowerTenMinEmaTickUSthreshold) // Are we over or under the threshold (outside of the channel)
IsTickBeyondThreshold := true
else
IsTickBeyondThreshold := false
// Is Price Crossing Under EMA 20 line and wasn't on the previous candle?
priceCrossingUnderEmaMedium = (low-paddingPriceToEMA <= EmaMedium and low[1] > EmaMedium)
priceCrossingAboveEmaMedium = (high+paddingPriceToEMA >= EmaMedium and high[1] < EmaMedium)
//Is this completed bar close on one side of EMA while it's low/high end is on the other side of EmaMedium? This tells us if the bar is in a freefall against our potential trade direction, or if we've touched and reversed. We only want in if we've touched and reversed
BarCloseAndLowOnOppositeSidesOfEmaMedium := barstate.isconfirmed and (close - paddingPriceToEMA) > EmaMedium and (low - paddingPriceToEMA) <= EmaMedium // for a Call trade
BarCloseAndHighOnOppositeSidesOfEmaMedium := barstate.isconfirmed and (close + paddingPriceToEMA) < EmaMedium and (high + paddingPriceToEMA) >= EmaMedium // for a Put trade
// Have we had a recent signal or currently in a trade?
for i = 1 to NumCandlesToIgnore
if BuyCallSignal[i] or BuyPutSignal[i] or currentlyInCallTrade[i] or currentlyInPutTrade[i]
recentSignal := true // this gets erased, recreated, and set to false by default at the start of this code every time
// Has TICK.US History stayed Beyond Threshold?
for i = 0 to NumCandlesTICKRequirement
if IsTickBeyondThreshold[i]
IsTickHistoryBeyondThreshold := true // this gets erased, recreated, and set to false by default at the start of this code every time
else
IsTickHistoryBeyondThreshold := false
break //once we find a false history, leave variable set as false
// Has EmaShort stayed above EmaMedium over recent x number of candles?
for i = 1 to NumCandlesEMA
if EmaShort[i] > EmaMedium[i]
EmaShortStayedAboveEmaMediumRecently := true
else //as soon as a false is detected, break out of this loop and leave variable set to false
EmaShortStayedAboveEmaMediumRecently := false
break
// Has EmaShort stayed below EmaMedium over recent x number of candles?
for i = 1 to NumCandlesEMA
if EmaShort[i] < EmaMedium[i]
EmaShortStayedBelowEmaMediumRecently := true
else //as soon as a false is detected, break out of this loop and leave variable set to false
EmaShortStayedBelowEmaMediumRecently := false
break
// Calculate % of the PM Spread that the EmaMedium is from PM High
PercentOfPMSpreadAboveHigh = (EmaMedium - PMcalculatedHigh) / (PMcalculatedHigh - PMcalculatedLow) * 100
WithinTolerablePMSpreadRangeAboveHigh = PercentOfPMSpreadAboveHigh >= SpreadPercentLowerLimit and PercentOfPMSpreadAboveHigh <= SpreadPercentUpperLimit
// Calculate % of the PM Spread that the close is from PM Low
PercentOfPMSpreadBelowLow = (PMcalculatedLow - EmaMedium) / (PMcalculatedHigh - PMcalculatedLow) * 100
WithinTolerablePMSpreadRangeBelowLow = PercentOfPMSpreadBelowLow >= SpreadPercentLowerLimit and PercentOfPMSpreadBelowLow <= SpreadPercentUpperLimit
// Calculate if Buy signals are true
//BuyCallSignal := (isInSession(MorningTradingSession) == true) and priceCrossingUnderEmaMedium and EmaMedium+paddingPriceToPMHL > PMcalculatedHigh and (close + paddingPriceToPMHL) > PMcalculatedHigh and EmaShortStayedAboveEmaMediumRecently and WithinTolerablePMSpreadRangeAboveHigh and (UseTickFilter ? (IsTickBeyondThreshold and IsTickHistoryBeyondThreshold) : true) and (UseIgnoreTrade ? (recentSignal or currentlyInCallTrade == true ? false : true) : true) and (UseLiveCalculation ? true : BarCloseAndLowOnOppositeSidesOfEmaMedium) and (LimitOneTradePerSession ? not TradedToday : true) and okToTradeThisDay
BuyCallSignal := (isInSession(MorningTradingSession) == true) and priceCrossingUnderEmaMedium and EmaShortStayedAboveEmaMediumRecently and WithinTolerablePMSpreadRangeAboveHigh and (UseTickFilter ? (IsTickBeyondThreshold and IsTickHistoryBeyondThreshold) : true) and (UseIgnoreTrade ? (recentSignal or currentlyInCallTrade == true ? false : true) : true) and (UseLiveCalculation ? true : BarCloseAndLowOnOppositeSidesOfEmaMedium) and (LimitOneTradePerSession ? not TradedToday : true) and okToTradeThisDay
//BuyPutSignal := (isInSession(MorningTradingSession) == true) and priceCrossingAboveEmaMedium and EmaMedium-paddingPriceToPMHL < PMcalculatedLow and (close - paddingPriceToPMHL) < PMcalculatedLow and EmaShortStayedBelowEmaMediumRecently and WithinTolerablePMSpreadRangeBelowLow and (UseTickFilter ? (IsTickBeyondThreshold and IsTickHistoryBeyondThreshold) : true) and (UseIgnoreTrade ? (recentSignal or currentlyInPutTrade == true ? false : true) : true) and (UseLiveCalculation ? true : BarCloseAndHighOnOppositeSidesOfEmaMedium) and (LimitOneTradePerSession ? not TradedToday : true) and okToTradeThisDay
BuyPutSignal := (isInSession(MorningTradingSession) == true) and priceCrossingAboveEmaMedium and EmaShortStayedBelowEmaMediumRecently and WithinTolerablePMSpreadRangeBelowLow and (UseTickFilter ? (IsTickBeyondThreshold and IsTickHistoryBeyondThreshold) : true) and (UseIgnoreTrade ? (recentSignal or currentlyInPutTrade == true ? false : true) : true) and (UseLiveCalculation ? true : BarCloseAndHighOnOppositeSidesOfEmaMedium) and (LimitOneTradePerSession ? not TradedToday : true) and okToTradeThisDay
//Calculate TP/SL points upon entering a trade
if (BuyCallSignal and currentlyInCallTrade == false)
EntryPrice := (UseLiveCalculation ? EmaMedium + paddingPriceToEMA : close)
currentlyInCallTrade := true
TradedToday := true
TP := EntryPrice + rewardTarget
SL := EntryPrice - riskTarget
if (BuyPutSignal and currentlyInPutTrade == false)
EntryPrice := (UseLiveCalculation ? EmaMedium - paddingPriceToEMA : close)
currentlyInPutTrade := true
TradedToday := true
TP := EntryPrice - rewardTarget
SL := EntryPrice + riskTarget
// --- END CHECKING THE PROCESS}
// --- END MAIN BODY CALCULATIONS ---}
// --- PLOT DATA --- {
//plot the Buy Call and Buy Put Signals for Strategy Testers signal input. It uses 1 for buy and -1 for sell
plot((BuyCallSignal or BuyPutSignal) ? (BuyCallSignal ? 1 : -1) : na, title="Buy/Sell Signal for Strategy Tester", display = display.none )
//plot the calculated Pre-Market High/Low Lines
plot(PMcalculatedHigh-PMcalculatedLow, title="Pre-market Spread", display = display.status_line, color = color.gray)
plot(PMcalculatedHigh, title="Calculated PM High Line", color=color.new(color.green, 50), style=plot.style_linebr, display = display.pane)
plot(PMcalculatedLow, title="Calculated PM Low Line", color=color.new(color.red, 50), style=plot.style_linebr, display = display.pane)
//set the bg color based on TICK.US settings if option selected
bgcolor(color=UseTickFilterBG ? (tenMinEmaTickUS >= UpperTenMinEmaTickUSthreshold ? color.new(color=color.green, transp=90) : tenMinEmaTickUS <= LowerTenMinEmaTickUSthreshold ? color.new(color=color.red, transp = 90) : na) : na, title="BG TICK.US Color", editable=false)
//Plot the EMA's if turned on
plot(DisplayEmaShort ? EmaShort : na, title="EMA Short Line", color=color.aqua, style=plot.style_line, linewidth = 2)
plot(DisplayEmaMedium ? EmaMedium : na, title="EMA Medium Line", color=color.yellow, style=plot.style_line, linewidth = 2)
plot(DisplayEmaLong ? EmaLong : na, title="EMA Long Line", color=color.red, style=plot.style_circles, linewidth = 1)
//Plot the Buy Signals
plotshape(BuyCallSignal, title="Buy Call Signal", style=shape.triangleup, color=color.green, location=location.belowbar, size=size.normal, display = display.pane)
plotshape(BuyPutSignal, title="Buy Put Signal", style=shape.triangledown, color=color.red, location=location.abovebar, size=size.normal, display = display.pane)
//Plot the TP and SL targets
plot((currentlyInCallTrade or currentlyInPutTrade) ? TP : na, title="Take Profit Line", color = color.new(color.green, 0), style=plot.style_linebr)
plot((currentlyInCallTrade or currentlyInPutTrade) ? SL : na, title="Stop Loss Line", color = color.new(color.red, 0), style=plot.style_linebr)
//If we are in a trade, should exit the trade?
if currentlyInCallTrade == true
//has price hit TP/SL targets or is it the end of the day? If hit or end of day, reset TP/SL back to na and flag the sell signal
if (high >= TP) or (high >= EntryPrice and hour == 15 and minute == 59)
SellProfitSignal := true
if (low <= SL) or (low <= EntryPrice and hour == 15 and minute == 59)
SellLossSignal := true
if currentlyInPutTrade == true
if (low <= TP) or (low <= EntryPrice and hour == 15 and minute == 59)
SellProfitSignal := true
if (high >= SL) or (high >= EntryPrice and hour == 15 and minute == 59)
SellLossSignal := true
//Verbose mode
if DebugVerboseMode
if BuyCallSignal
truncPerc = math.round(PercentOfPMSpreadAboveHigh, 1)
truncEntryPrice = math.round(EntryPrice, 2)
textString = "Distance= " + str.tostring(truncPerc) + "%\nEnter CALL at " + str.tostring(truncEntryPrice) + ".\n TP=" + str.tostring(truncEntryPrice + rewardTarget) + "\n SL=" + str.tostring(truncEntryPrice - riskTarget)
mylabel = label.new(x=bar_index[0], y=high + atr14 * 3, text=textString, style=label.style_label_down, color = SignalBoxColor)
if BuyPutSignal
truncPerc = math.round(PercentOfPMSpreadBelowLow, 1)
truncEntryPrice = math.round(EntryPrice, 2)
textString = "Distance= " + str.tostring(truncPerc) + "%\nEnter PUT at " + str.tostring(truncEntryPrice) + ".\n TP=" + str.tostring(truncEntryPrice - rewardTarget) + "\n SL=" + str.tostring(truncEntryPrice + riskTarget)
mylabel = label.new(x=bar_index, y=low - atr14 * 3, text=textString, style=label.style_label_up, color = SignalBoxColor)
if SellProfitSignal or SellLossSignal
if SellProfitSignal
ExitPrice = (lastBarOfRegularHours ? close : math.round(TP, 2))
ProfitPoints = math.abs(math.round(ExitPrice - EntryPrice, 2))
textString = "Exit Profit at "+ str.tostring(ExitPrice) + "\n " + str.tostring(ProfitPoints) + " Points"
mylabel = label.new(x=bar_index, y=high + atr14 * 3, text=textString, style=label.style_label_down, color = ProfitBoxColor)
if SellLossSignal
ExitPrice = (lastBarOfRegularHours ? close : math.round(SL, 2))
LossPoints = math.round(ExitPrice - EntryPrice, 2)
textString = "Exit Loss at " + str.tostring(ExitPrice) + "\n " + str.tostring(LossPoints) + " Points"
mylabel = label.new(x=bar_index, y=low - atr14 * 3, text=textString, style=label.style_label_up, color = LossBoxColor)
// }
// --- ALERT CONDITIONS --- {
alertcondition(BuyCallSignal, title="Buy CALL Signal", message="CALL signal for {{ticker}} at {{close}}")
alertcondition(BuyPutSignal, title="Buy PUT Signal", message="PUT signal for {{ticker}} at {{close}}")
alertcondition((SellProfitSignal or SellLossSignal), title="SELL Position Signal", message="SELL signal for {{ticker}} at {{close}}")
// --- END ALERT CONDITIONS --- }
// --- RESET VARIABLES AT END --- {
// Lastly Reset our variables if we exited a trade
if (currentlyInCallTrade or currentlyInPutTrade) and (SellLossSignal or SellProfitSignal)
TP := na
SL := na
currentlyInCallTrade := false
currentlyInPutTrade := false
EntryPrice := na
// } |
Moving Average Zones | https://www.tradingview.com/script/cdxtLQlj-Moving-Average-Zones/ | HoanGhetti | https://www.tradingview.com/u/HoanGhetti/ | 164 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HoanGhetti
//@version=5
indicator("Moving Average Zones [HG]", overlay = true)
// There won't be an input option for these settings to keep it simple.
// Feel free to change the values here although it's recommended to keep them like this.
// These are offset multipliers from the base moving average. All of these will offset off the script's default Simple Moving Average for example.
type levelMultiplier
float one = 12.0
float two = 8.0
float three = 6.0
float four = 4.5
float five = 3.5
float six = 2.5
float seven = 0.3
allBoxes = box.all
allLabels = label.all
allLines = line.all
noDisplay = display.all - display.status_line
color_input = input.color(defval = color.new(#5e5a55, 80), title = 'Zone Color', inline = 'zonetouch')
bb_input = input.int(defval = 100, title = 'Lookback Range', minval = 1, maxval = 4999, step = 10, inline = 'zonetouch', tooltip = 'Allows the script to check how many touches have occured between zones within the specified bars back period')
ma_input = input.string(defval = 'SMA', title = 'MA Type ', inline = 'maconv', options = ['EMA', 'SMA', 'RMA', 'HMA', 'WMA', 'VWMA', 'ALMA', 'SWMA'])
len_input = input.int(defval = 50, title = 'MA Length', minval = 1, inline = 'lensrc')
src_input = input.source(defval = close, title = 'MA Source', inline = 'lensrc')
offset_input = input.float(defval = 0.85, title = 'MA Offset ', minval = 0, step = 0.05, inline = 'offsig')
sigma_input = input.float(defval = 6, title = 'MA Sigma ', minval = 0, step = 0.05, inline = 'offsig', tooltip = 'Offset and sigma are used for ALMA')
aoc_input = input.bool(defval = false, title = 'Areas of Confluence', group = 'AOC', tooltip = 'Allows the user to visually see which zones are currently active in terms of how many touches have occured within the given lookback period.')
zero_input = input.bool(defval = false, title = 'Display Zero-Touch Zones', group = 'AOC', tooltip = 'If using AOC, allows zones to still be slightly displayed even if inactive.')
extend_input = input.bool(defval = false, title = 'Extend Plot Levels', group = 'AOC', tooltip = 'Extends zones to the right.')
touch_input = input.bool(defval = true, title = 'Display Touch Count', group = 'AOC', tooltip = 'Creates labels on the right side of the zones displaying how many touches have occured for that specific zone.')
data_input = input.bool(defval = false, title = 'Display Data Window', group = 'Data Window')
// Determine which MA Input is selected, and then assign maType to it's specified moving average.
maType = switch ma_input
'EMA' => ta.ema(src_input, len_input)
'SMA' => ta.sma(src_input, len_input)
'RMA' => ta.rma(src_input, len_input)
'HMA' => ta.hma(src_input, len_input)
'WMA' => ta.wma(src_input, len_input)
'VWMA' => ta.vwma(src_input, len_input)
'SWMA' => ta.swma(src_input)
'ALMA' => ta.alma(src_input, len_input, offset_input, sigma_input)
// Offsets a moving average both upward and downward of it's base moving average.
offsetMA(float movingAverage, float multiplier, int atrLength) =>
atr = ta.atr(atrLength)
multi = atr * multiplier
ma_up = movingAverage + multi
ma_dn = movingAverage - multi
[ma_up, ma_dn]
// A neat way of fetching all right decimals universally, since other variants out there wouldn't work on futures.
getDecimals = str.length(str.tostring(syminfo.mintick)) - 2
// Used for touch detection.
hitDetection(up, dn, hi = high, lo = low) => hi > dn and hi < up or lo < up and lo > dn
// Create an instance for the properties made above
l = levelMultiplier.new()
// Utilize our offsetMA function here. ATR will always be MA length * 2
[maUpOne, maDnOne] = offsetMA(maType, l.one, len_input * 2)
[maUpTwo, maDnTwo] = offsetMA(maType, l.two, len_input * 2)
[maUpThree, maDnThree] = offsetMA(maType, l.three, len_input * 2)
[maUpFour, maDnFour] = offsetMA(maType, l.four, len_input * 2)
[maUpFive, maDnFive] = offsetMA(maType, l.five, len_input * 2)
[maUpSix, maDnSix] = offsetMA(maType, l.six, len_input * 2)
[maUpSeven, maDnSeven] = offsetMA(maType, l.seven, len_input * 2)
// Creating each individual variable of the hitDetection event, and counting how many hits have occured between each individual zone. This is used for color transparency
hit_one = math.sum(hitDetection(maUpOne, maUpTwo) ? 1 : 0, bb_input)
hit_two = math.sum(hitDetection(maUpThree, maUpFour) ? 1 : 0, bb_input)
hit_three = math.sum(hitDetection(maUpFive, maUpSix) ? 1 : 0, bb_input)
hit_four = math.sum(hitDetection(maUpSeven, maDnSeven) ? 1 : 0, bb_input)
hit_five = math.sum(hitDetection(maDnSix, maDnFive) ? 1 : 0, bb_input)
hit_six = math.sum(hitDetection(maDnFour, maDnThree) ? 1 : 0, bb_input)
hit_seven = math.sum(hitDetection(maDnTwo, maDnOne) ? 1 : 0, bb_input)
// Separate data into multiple arrays/matrix to easily determine if price is between each zone.
m = matrix.new<float>(7, 2)
upPlots = array.from(maUpOne, maUpThree, maUpFive, maUpSeven, maDnSix, maDnFour, maDnTwo)
dnPlots = array.from(maUpTwo, maUpFour, maUpSix, maDnSeven, maDnFive, maDnThree, maDnOne)
maxHits = array.from(hit_one, hit_two, hit_three, hit_four, hit_five, hit_six, hit_seven)
alpha = array.new<float>()
transp = zero_input ? 98 : 100
// Color Transparency
for i = 0 to array.size(maxHits) - 1
array.push(alpha, math.abs(transp - (array.get(maxHits, i) / array.sum(maxHits)) * 100))
// Delete past objects
delObj(arr, inputOption, condition) =>
if array.size(arr) > 0 and inputOption
for i = 0 to array.size(arr) - 1
if condition == 'lbl'
label.delete(array.get(allLabels, i))
if condition == 'box'
box.delete(array.get(allBoxes, i))
delObj(allLabels, touch_input, 'lbl')
delObj(allBoxes, extend_input, 'box')
// Create two separate arrays that will track rejection count. See the bottom of script for visual guide.
var bearRevCount = array.new<int>()
var bullRevCount = array.new<int>()
// Here we loop through the arrays that we listed above so we can then create the plot extensions and touch count labels.
for i = 0 to array.size(upPlots) - 1
matrix.set(m, i, 0, math.round(array.get(upPlots, i), getDecimals))
matrix.set(m, i, 1, math.round(array.get(dnPlots, i), getDecimals))
median = (matrix.get(m, i, 0) + matrix.get(m, i, 1)) / 2
if touch_input
label.new(bar_index + 5, median, str.tostring(array.get(maxHits, i)), style = label.style_none, textcolor = color.new(color_input, 0))
if extend_input
box.new(bar_index, matrix.get(m, i, 0), bar_index, matrix.get(m, i, 1), border_color = na, extend = extend.right, bgcolor = aoc_input ? color.new(color_input, array.get(alpha, i)) : color_input)
// Fill and plot the zones.
fill(plot(maUpOne, color = na, display = noDisplay, editable = false), plot(maUpTwo, color = na, display = noDisplay, editable = false), color = aoc_input ? color.new(color_input, array.get(alpha, 0)) : color_input)
fill(plot(maUpThree, color = na, display = noDisplay, editable = false), plot(maUpFour, color = na, display = noDisplay, editable = false), color = aoc_input ? color.new(color_input, array.get(alpha, 1)) : color_input)
fill(plot(maUpFive, color = na, display = noDisplay, editable = false), plot(maUpSix, color = na, display = noDisplay, editable = false), color = aoc_input ? color.new(color_input, array.get(alpha, 2)) : color_input)
fill(plot(maUpSeven, color = na, display = noDisplay, editable = false), plot(maDnSeven, color = na, display = noDisplay, editable = false), color = aoc_input ? color.new(color_input, array.get(alpha, 3)) : color_input)
fill(plot(maDnSix, color = na, display = noDisplay, editable = false), plot(maDnFive, color = na, display = noDisplay, editable = false), color = aoc_input ? color.new(color_input, array.get(alpha, 4)) : color_input)
fill(plot(maDnFour, color = na, display = noDisplay, editable = false), plot(maDnThree, color = na, display = noDisplay, editable = false), color = aoc_input ? color.new(color_input, array.get(alpha, 5)) : color_input)
fill(plot(maDnTwo, color = na, display = noDisplay, editable = false), plot(maDnOne, color = na, display = noDisplay, editable = false), color = aoc_input ? color.new(color_input, array.get(alpha, 6)) : color_input)
// Data Window (Displaying collected data)
if data_input
data = table.new(position.top_center, 20, 20, bgcolor = color.new(color_input, 40), border_color = color_input, border_width = 2, frame_color = color_input, frame_width = 2)
totalHits = array.sum(maxHits)
table.cell(data, 0, 0, 'Type', text_color = color.white)
table.cell(data, 0, 1, str.tostring(ma_input), text_color = color.white)
table.cell(data, 1, 0, 'Length', text_color = color.white)
table.cell(data, 1, 1, str.tostring(len_input), text_color = color.white)
table.cell(data, 2, 0, 'Touch LBR', text_color = color.white)
table.cell(data, 2, 1, str.tostring(bb_input), text_color = color.white)
table.cell(data, 3, 0, 'Total Touches', text_color = color.white)
table.cell(data, 3, 1, str.tostring(array.sum(maxHits)), text_color = color.white) |
MACD MTF Lines | https://www.tradingview.com/script/iX8CobJs-MACD-MTF-Lines/ | danilogalisteu | https://www.tradingview.com/u/danilogalisteu/ | 78 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © danilogalisteu
//@version=5
indicator("MACD MTF Lines")
// Price source
price = input.source(close, "Price source", group="Price source")
// MACD parameters
group_macd = "MACD parameters"
pfast = input.int(1, "Fast Period", minval=1, group=group_macd)
pslow = input.int(33, "Slow Period", minval=1, group=group_macd)
psign = input.int(3, "Signal Period", minval=1, group=group_macd)
tmain = input.string("EMA", "Type of MA for main line", options=["EMA", "SMA"], group=group_macd)
tsign = input.string("EMA", "Type of MA for signal line", options=["EMA", "SMA"], group=group_macd)
// Timeframe selection
group_tf = "Timeframe selection and score weights"
tf1 = input.timeframe( "1", "TF 1", group=group_tf, inline="tf1")
en1 = input.bool(true, "Show", group=group_tf, inline="tf1")
sc1 = input.float(1.0, "Weight", group=group_tf, inline="tf1")
tf2 = input.timeframe( "3", "TF 2", group=group_tf, inline="tf2")
en2 = input.bool(true, "Show", group=group_tf, inline="tf2")
sc2 = input.float(1.0, "Weight", group=group_tf, inline="tf2")
tf3 = input.timeframe( "5", "TF 3", group=group_tf, inline="tf3")
en3 = input.bool(true, "Show", group=group_tf, inline="tf3")
sc3 = input.float(1.0, "Weight", group=group_tf, inline="tf3")
tf4 = input.timeframe( "15", "TF 4", group=group_tf, inline="tf4")
en4 = input.bool(true, "Show", group=group_tf, inline="tf4")
sc4 = input.float(1.0, "Weight", group=group_tf, inline="tf4")
tf5 = input.timeframe( "30", "TF 5", group=group_tf, inline="tf5")
en5 = input.bool(true, "Show", group=group_tf, inline="tf5")
sc5 = input.float(1.0, "Weight", group=group_tf, inline="tf5")
tf6 = input.timeframe( "45", "TF 6", group=group_tf, inline="tf6")
en6 = input.bool(true, "Show", group=group_tf, inline="tf6")
sc6 = input.float(1.0, "Weight", group=group_tf, inline="tf6")
tf7 = input.timeframe( "60", "TF 7", group=group_tf, inline="tf7")
en7 = input.bool(true, "Show", group=group_tf, inline="tf7")
sc7 = input.float(1.0, "Weight", group=group_tf, inline="tf7")
tf8 = input.timeframe("120", "TF 8", group=group_tf, inline="tf8")
en8 = input.bool(true, "Show", group=group_tf, inline="tf8")
sc8 = input.float(1.0, "Weight", group=group_tf, inline="tf8")
tf9 = input.timeframe("180", "TF 9", group=group_tf, inline="tf9")
en9 = input.bool(true, "Show", group=group_tf, inline="tf9")
sc9 = input.float(1.0, "Weight", group=group_tf, inline="tf9")
tf10 = input.timeframe("240", "TF 10", group=group_tf, inline="tf10")
en10 = input.bool(true, "Show", group=group_tf, inline="tf10")
sc10 = input.float(1.0, "Weight", group=group_tf, inline="tf10")
tf11 = input.timeframe( "1D", "TF 11", group=group_tf, inline="tf11")
en11 = input.bool(true, "Show", group=group_tf, inline="tf11")
sc11 = input.float(1.0, "Weight", group=group_tf, inline="tf11")
tf12 = input.timeframe( "1W", "TF 12", group=group_tf, inline="tf12")
en12 = input.bool(true, "Show", group=group_tf, inline="tf12")
sc12 = input.float(1.0, "Weight", group=group_tf, inline="tf12")
tf13 = input.timeframe( "1M", "TF 13", group=group_tf, inline="tf13")
en13 = input.bool(true, "Show", group=group_tf, inline="tf13")
sc13 = input.float(1.0, "Weight", group=group_tf, inline="tf13")
// Trend detection
group_trend = "Trend detection"
show_bg = input.bool(false, "Show trend color in background", group=group_trend)
enable_trend_alert = input.bool(false, "Enable alert on trend change", group=group_trend)
score_threshold_trend = input.float(7, "Minimum score for trend change", minval=0, group=group_trend)
enable_extra_alert = input.bool(false, "Enable extra alert", group=group_trend)
score_threshold_alert = input.float(7, "Minimum score for extra alert", minval=0, group=group_trend)
// MTF helpers
ma_mtf(ts, period, tf, matype) =>
expr = matype == "EMA" ? ta.ema(ts, period) : math.sum(ts, period) - ts[period-1]
prev = request.security(syminfo.tickerid, tf, expr[1], barmerge.gaps_off, barmerge.lookahead_on)
period > 1 ? matype == "EMA" ? (2 * ts + (1 + period - 2) * prev) / (1 + period) : (ts + prev) / period : ts
macd_sign_mtf(ts, fast, slow, signal, tf, main_func, sign_func) =>
m1 = ma_mtf(ts, fast, tf, main_func) - ma_mtf(ts, slow, tf, main_func)
m2 = ma_mtf(m1, signal, tf, sign_func)
math.sign(m1 - m2)
// Signals
v1 = nz(macd_sign_mtf(price, pfast, pslow, psign, tf1, tmain, tsign))
v2 = nz(macd_sign_mtf(price, pfast, pslow, psign, tf2, tmain, tsign))
v3 = nz(macd_sign_mtf(price, pfast, pslow, psign, tf3, tmain, tsign))
v4 = nz(macd_sign_mtf(price, pfast, pslow, psign, tf4, tmain, tsign))
v5 = nz(macd_sign_mtf(price, pfast, pslow, psign, tf5, tmain, tsign))
v6 = nz(macd_sign_mtf(price, pfast, pslow, psign, tf6, tmain, tsign))
v7 = nz(macd_sign_mtf(price, pfast, pslow, psign, tf7, tmain, tsign))
v8 = nz(macd_sign_mtf(price, pfast, pslow, psign, tf8, tmain, tsign))
v9 = nz(macd_sign_mtf(price, pfast, pslow, psign, tf9, tmain, tsign))
v10 = nz(macd_sign_mtf(price, pfast, pslow, psign, tf10, tmain, tsign))
v11 = nz(macd_sign_mtf(price, pfast, pslow, psign, tf11, tmain, tsign))
v12 = nz(macd_sign_mtf(price, pfast, pslow, psign, tf12, tmain, tsign))
v13 = nz(macd_sign_mtf(price, pfast, pslow, psign, tf13, tmain, tsign))
score = v1 * sc1 + v2 * sc2 + v3 * sc3 + v4 * sc4 + v5 * sc5 + v6 * sc6 + v7 * sc7 + v8 * sc8 + v9 * sc9 + v10 * sc10 + v11 * sc11 + v12 * sc12 + v13 * sc13
score_max = math.abs(sc1) + math.abs(sc2) + math.abs(sc3) + math.abs(sc4) + math.abs(sc5) + math.abs(sc6) + math.abs(sc7) + math.abs(sc8) + math.abs(sc9) + math.abs(sc10) + math.abs(sc11) + math.abs(sc12) + math.abs(sc13)
// State changes
state_trend = 0
state_trend := nz(state_trend[1])
if state_trend[1] < 1 and score >= score_threshold_trend
state_trend := 1
if state_trend[1] > -1 and score <= -score_threshold_trend
state_trend := -1
state_alert = 0
state_alert := nz(state_alert[1])
if state_alert[1] < 1 and score >= score_threshold_alert
state_alert := 1
if state_alert[1] > -1 and score <= -score_threshold_alert
state_alert := -1
// Alerts
s_dir_trend = state_trend == 1 ? 'long' : state_trend == -1 ? 'short' : "neutral"
alert_msg_trend = str.format("MACD-MTF({0}, {1}, {2}) Trend Change\nsignal {3}\nticker {4}\ntimeframe {5}\nprice {6}", pfast, pslow, psign, s_dir_trend, syminfo.tickerid, timeframe.period, close)
if enable_trend_alert and state_trend != state_trend[1]
alert(alert_msg_trend, alert.freq_once_per_bar_close)
s_dir_alert = state_alert == 1 ? 'long' : state_alert == -1 ? 'short' : "neutral"
alert_msg_alert = str.format("MACD-MTF({0}, {1}, {2}) Trend Alert\nsignal {3}\nticker {4}\ntimeframe {5}\nprice {6}", pfast, pslow, psign, s_dir_alert, syminfo.tickerid, timeframe.period, close)
if enable_extra_alert and state_alert != state_alert[1]
alert(alert_msg_alert, alert.freq_once_per_bar_close)
// Colors
lw = 3
color_pos = color.green
color_neg = color.red
color_neu = color.yellow
color_pos_bg = color.rgb(76, 175, 79, 85)
color_neg_bg = color.rgb(255, 82, 82, 85)
color_neu_bg = color.rgb(255, 235, 59, 85)
// Enable or disable specific lines
plot_level = 0.0
plot_level := en1 ? plot_level - 10.0 : plot_level
plot_level1 = en1 ? plot_level : na
plot_level := en2 ? plot_level - 10.0 : plot_level
plot_level2 = en2 ? plot_level : na
plot_level := en3 ? plot_level - 10.0 : plot_level
plot_level3 = en3 ? plot_level : na
plot_level := en4 ? plot_level - 10.0 : plot_level
plot_level4 = en4 ? plot_level : na
plot_level := en5 ? plot_level - 10.0 : plot_level
plot_level5 = en5 ? plot_level : na
plot_level := en6 ? plot_level - 10.0 : plot_level
plot_level6 = en6 ? plot_level : na
plot_level := en7 ? plot_level - 10.0 : plot_level
plot_level7 = en7 ? plot_level : na
plot_level := en8 ? plot_level - 10.0 : plot_level
plot_level8 = en8 ? plot_level : na
plot_level := en9 ? plot_level - 10.0 : plot_level
plot_level9 = en9 ? plot_level : na
plot_level := en10 ? plot_level - 10.0 : plot_level
plot_level10 = en10 ? plot_level : na
plot_level := en11 ? plot_level - 10.0 : plot_level
plot_level11 = en11 ? plot_level : na
plot_level := en12 ? plot_level - 10.0 : plot_level
plot_level12 = en12 ? plot_level : na
plot_level := en13 ? plot_level - 10.0 : plot_level
plot_level13 = en13 ? plot_level : na
// Plotting
plot(plot_level1, "TF1", color=v1 > 0 ? color_pos : v1 < 0 ? color_neg : color_neu, linewidth=lw, display=display.pane)
plot(plot_level2, "TF2", color=v2 > 0 ? color_pos : v2 < 0 ? color_neg : color_neu, linewidth=lw, display=display.pane)
plot(plot_level3, "TF3", color=v3 > 0 ? color_pos : v3 < 0 ? color_neg : color_neu, linewidth=lw, display=display.pane)
plot(plot_level4, "TF4", color=v4 > 0 ? color_pos : v4 < 0 ? color_neg : color_neu, linewidth=lw, display=display.pane)
plot(plot_level5, "TF5", color=v5 > 0 ? color_pos : v5 < 0 ? color_neg : color_neu, linewidth=lw, display=display.pane)
plot(plot_level6, "TF6", color=v6 > 0 ? color_pos : v6 < 0 ? color_neg : color_neu, linewidth=lw, display=display.pane)
plot(plot_level7, "TF7", color=v7 > 0 ? color_pos : v7 < 0 ? color_neg : color_neu, linewidth=lw, display=display.pane)
plot(plot_level8, "TF8", color=v8 > 0 ? color_pos : v8 < 0 ? color_neg : color_neu, linewidth=lw, display=display.pane)
plot(plot_level9, "TF9", color=v9 > 0 ? color_pos : v9 < 0 ? color_neg : color_neu, linewidth=lw, display=display.pane)
plot(plot_level10, "TF10", color=v10 > 0 ? color_pos : v10 < 0 ? color_neg : color_neu, linewidth=lw, display=display.pane)
plot(plot_level11, "TF11", color=v11 > 0 ? color_pos : v11 < 0 ? color_neg : color_neu, linewidth=lw, display=display.pane)
plot(plot_level12, "TF12", color=v12 > 0 ? color_pos : v12 < 0 ? color_neg : color_neu, linewidth=lw, display=display.pane)
plot(plot_level13, "TF13", color=v13 > 0 ? color_pos : v13 < 0 ? color_neg : color_neu, linewidth=lw, display=display.pane)
// Trend/alert score and state
color_trend = state_trend > 0 ? color_pos : state_trend < 0 ? color_neg : color_neu
color_alert = state_alert > 0 ? color_pos : state_alert < 0 ? color_neg : color_neu
plot(score, "Score", color=color_trend, display=display.data_window)
plot(score_max, "Maximum score (+/-)", color=color_neu, display=display.data_window)
plot(state_trend, "Trend", color=color_trend, display=display.data_window)
plot(state_alert, "Alert", color=color_alert, display=display.data_window)
// Background
color_bg = state_trend > 0 ? color_pos_bg : state_trend < 0 ? color_neg_bg : color_neu_bg
bgcolor(show_bg ? color_bg : na)
|
Rotational Gravity Oscillator | https://www.tradingview.com/script/Xn3WvFu9-Rotational-Gravity-Oscillator/ | burgercrisis | https://www.tradingview.com/u/burgercrisis/ | 90 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © burgercrisis, parts © Cheatcountry
//@version=5
//Written using elements from Cheatcountry scripts ( https://www.tradingview.com/u/cheatcountry/ )
// https://www.tradingview.com/script/UyA4515j-Stock-Rotation-Model-CC/
// https://www.tradingview.com/script/pOc6pmT3-True-Range-Adjusted-Exponential-Moving-Average-CC/
//Most of the code was technically written by him via these two scripts; I modified parts, tweaked the COG slightly, looked at possibilities that I didn't incorporate, and essentially "linked" these blocks of code together to form a novel new oscillator using recycled code from Cheatcountry, mostly.
//Give him a follow. Seriously. His work enables awesome stuff like this and he's super chill.
indicator("Rotational Gravity Oscillator", 'RGO')
spSym = input.symbol(title='Comparative Symbol', defval='CRYPTOCAP:TOTAL') // https://www.tradingview.com/script/UyA4515j-Stock-Rotation-Model-CC/
inp = input(title='Source', defval=hlcc4)
res = input.timeframe(title='Resolution', defval='')
rep = input(title='Allow Repainting?', defval=false)
bar = input(title='Allow Bar Color Change?', defval=false)
src = request.security(syminfo.tickerid, res, inp[rep ? 0 : barstate.isrealtime ? 1 : 0])[rep ? 0 : barstate.isrealtime ? 0 : 1]
spSrc = request.security(spSym, res, inp[rep ? 0 : barstate.isrealtime ? 1 : 0])[rep ? 0 : barstate.isrealtime ? 0 : 1] //end // https://www.tradingview.com/script/UyA4515j-Stock-Rotation-Model-CC/
bandhide = input(true, 'Hide Distant Bands?', 'True = only displays the bands that are above and below the main oscillator. False = always display bands.')
BandColors = input(false, 'Band Colors', 'True: Band colors are set by their own directional movement ; False: Band colors are set by the moving averages position above or below the 0 line')
Arrows = input(true, 'Display Arrows', 'Potential trend reversals')
triangles = input(true, 'Triangles', 'True = display arrows as triangles. False, display arrows as... arrows.')
transp = input.int(50, title= 'Arrow Transparency', minval=0, maxval=100)
Length1 = input(10, "Internal Length 1", "Length of internal oscillator 1")
Length2 = input(25, "Internal Length 2", "Length of internal oscillator 2")
Length3 = input(50, "Internal Length 3", "Length of internal oscillator 3")
Length4 = input(100, "Internal Length 4", "Length of internal oscillator 4")
Length5 = input(12, "Internal Smoothing Length", "Length of internal moving average smoothing")
Length6 = input(12, "External Smoothing Length", "Length of final external moving average smoothing")
mult = input(5.0, "Moving Average Multiplier", "The multiplier for the internal ATR for the All-True-Range Adjusted EMAs used in the script")
Length7 = input(500, "Bollinger Bands Length", "Length of Bollinger Bands")
Length8 = input(0, "Bollinger Bands StdDEV Modifier", "Adds this length to the length of the STDdev for the Bollinger Bands, without affecting the moving average length for them.")
dev11 = input(1.0, "Bollinger Bands Multiplier 1", "The multiplier for the first Bollinger Bands")
dev22 = input(2.0, "Bollinger Bands Multiplier 2", "The multiplier for the second Bollinger Bands")
trAdjEma(src, lengthy) => // https://www.tradingview.com/script/pOc6pmT3-True-Range-Adjusted-Exponential-Moving-Average-CC/
int lengthe = int(lengthy)
float alpha = 2.0 / (lengthe + 1)
float trL = ta.lowest(ta.tr, lengthe)
float trH = ta.highest(ta.tr, lengthe)
float trAdj = trH - trL != 0 ? (ta.tr - trL) / (trH - trL) : 0
float trAdjEma = 0.0
trAdjEma := nz(trAdjEma[1]) + (alpha * (1 + (trAdj * mult)) * (src - nz(trAdjEma[1]))) //end // https://www.tradingview.com/script/pOc6pmT3-True-Range-Adjusted-Exponential-Moving-Average-CC/
pine_cog(source, length) =>
sum = math.sum(source, length)
num = 0.0
for i = 0 to length - 1
price = source - source[i]
num := num + price * (i + 1)
num / sum
satan1 = trAdjEma(pine_cog(src, Length1), Length5) // https://www.tradingview.com/script/UyA4515j-Stock-Rotation-Model-CC/
satan2 = trAdjEma(pine_cog(src, Length2), Length5)
satan3 = trAdjEma(pine_cog(src, Length3), Length5)
satan4 = trAdjEma(pine_cog(src, Length4), Length5)
god1 = trAdjEma(pine_cog(spSrc, Length1), Length5)
god2 = trAdjEma(pine_cog(spSrc, Length2), Length5)
god3 = trAdjEma(pine_cog(spSrc, Length3), Length5)
god4 = trAdjEma(pine_cog(spSrc, Length4), Length5)
satan = trAdjEma((satan1 * 4) + (satan2 * 3) + (satan3 * 2) + satan4, Length6)
god = trAdjEma((god1 * 4) + (god2 * 3) + (god3 * 2) + god4, Length6)
dank = satan - god
slo = dank - nz(dank[1])
sig = slo > 0 ? slo > nz(slo[1]) ? 2 : 1 : slo < 0 ? slo < nz(slo[1]) ? -2 : -1 : 0
alertcondition(ta.crossover(sig, 1), "Strong Buy Signal", "Strong Bullish Change Detected")
alertcondition(ta.crossunder(sig, -1), "Strong Sell Signal", "Strong Bearish Change Detected")
alertcondition(ta.crossover(sig, 0), "Buy Signal", "Bullish Change Detected")
alertcondition(ta.crossunder(sig, 0), "Sell Signal", "Bearish Change Detected")
alertcondition(ta.crossover(sig, 0) or ta.crossover(sig, 1), "All Buy Signals", "Any Bullish Change Detected")
alertcondition(ta.crossunder(sig, 0) or ta.crossunder(sig, -1), "All Sell Signals", "Any Bearish Change Detected")
dankColor = sig > 1 ? color.rgb(150, 255, 150) : sig > 0 ? color.rgb(0, 126, 0) : sig < -1 ? color.rgb(255, 120, 120) : sig < 0 ? color.rgb(126, 0, 0) : color.black
float alpha = 2.0 / (Length7 + 1) // https://www.tradingview.com/script/pOc6pmT3-True-Range-Adjusted-Exponential-Moving-Average-CC/
float trL = ta.lowest(ta.tr, Length7)
float trH = ta.highest(ta.tr, Length7)
float trAdj = trH - trL != 0 ? (ta.tr - trL) / (trH - trL) : 0
float trAdjEma = 0.0
trAdjEma := nz(trAdjEma[1]) + (alpha * (1 + (trAdj * 1)) * ((satan - god) - nz(trAdjEma[1]))) //end // https://www.tradingview.com/script/pOc6pmT3-True-Range-Adjusted-Exponential-Moving-Average-CC/
dev = dev11 * ta.stdev(satan - god, Length7 + Length8)
dev2 = dev22 * ta.stdev(satan - god, Length7 + Length8)
upper = trAdjEma + dev
lower = trAdjEma - dev
upper2 = trAdjEma + dev2
lower2 = trAdjEma - dev2
slo2 = trAdjEma - nz(trAdjEma[1]) // https://www.tradingview.com/script/UyA4515j-Stock-Rotation-Model-CC/
sig2 = slo2 > 0 ? slo2 > nz(slo2[1]) ? 2 : 1 : slo2 < 0 ? slo2 < nz(slo2[1]) ? -2 : -1 : 0
dankColor2 = sig2 > 1 ? color.rgb(150, 255, 150) : sig2 > 0 ? color.rgb(0, 126, 0) : sig2 < -1 ? color.rgb(255, 120, 120) : sig2 < 0 ? color.rgb(126, 0, 0) : color.black
slo3 = upper - nz(upper[1])
sig3 = slo3 > 0 ? slo3 > nz(slo3[1]) ? 2 : 1 : slo3 < 0 ? slo3 < nz(slo3[1]) ? -2 : -1 : 0
dankColor3 = sig3 > 1 ? color.rgb(120, 255, 120) : sig3 > 0 ? color.rgb(0, 90, 0) : sig3 < -1 ? color.rgb(255, 90, 90) : sig3 < 0 ? color.rgb(90, 0, 0) : color.black
slo4 = lower - nz(lower[1])
sig4 = slo4 > 0 ? slo4 > nz(slo4[1]) ? 2 : 1 : slo4 < 0 ? slo4 < nz(slo4[1]) ? -2 : -1 : 0
dankColor4 = sig4 > 1 ? color.rgb(120, 255, 120) : sig4 > 0 ? color.rgb(0, 90, 0) : sig4 < -1 ? color.rgb(255, 90, 90) : sig4 < 0 ? color.rgb(90, 0, 0) : color.black
slo5 = upper2 - nz(upper2[1])
sig5 = slo5 > 0 ? slo5 > nz(slo5[1]) ? 2 : 1 : slo5 < 0 ? slo5 < nz(slo5[1]) ? -2 : -1 : 0
dankColor5 = sig5 > 1 ? color.rgb(120, 255, 120) : sig5 > 0 ? color.rgb(0, 90, 0) : sig5 < -1 ? color.rgb(255, 90, 90) : sig5 < 0 ? color.rgb(90, 0, 0) : color.black
slo6 = lower2 - nz(lower2[1])
sig6 = slo6 > 0 ? slo6 > nz(slo6[1]) ? 2 : 1 : slo6 < 0 ? slo6 < nz(slo6[1]) ? -2 : -1 : 0
dankColor6 = sig6 > 1 ? color.rgb(120, 255, 120) : sig6 > 0 ? color.rgb(0, 90, 0) : sig6 < -1 ? color.rgb(255, 90, 90) : sig6 < 0 ? color.rgb(90, 0, 0) : color.black //end // https://www.tradingview.com/script/UyA4515j-Stock-Rotation-Model-CC/
barcolor(bar ? dankColor : na)
plotshape(Arrows ? sig==2 and sig2==2 and dank>0 and ta.barssince(sig>=1 and sig2>=1 and dank>0 )[1]>1 and ta.barssince(dank<0)<ta.barssince(sig<=1 and dank>0 )[1] : na, 'Strong Uptrend Started', triangles ? shape.triangleup : shape.arrowup, location=location.bottom, size=size.large, color=color.new(color.blue, transp))
plotshape(Arrows ? sig==2 and sig2==2 and ta.barssince(sig==2 and sig2==2)[1]>ta.barssince(sig2<0) : na, 'Uptrend Started', triangles ? shape.triangleup : shape.arrowup, location=location.bottom, size=size.small, color=color.new(color.blue, transp))
plotshape(Arrows ? sig==2 and sig2==2 and dank>0 and ta.barssince(sig==2 and sig2==2 and dank>0 )[1]>ta.barssince(sig2<0) : na, 'Uptrend Started', triangles ? shape.triangleup : shape.arrowup, location=location.bottom, size=size.small, color=color.new(color.teal, transp))
plotshape(Arrows ? sig==2 and sig2<0 and dank<0 and ta.barssince(sig>=1 and sig2<0 and dank<0 )[1]>1 : na, 'Early Uptrend Started', triangles ? shape.triangleup : shape.arrowup, location=location.bottom, size=size.tiny, color=color.new(color.blue, transp))
plotshape(Arrows ? sig==-2 and sig2==-2 and dank<0 and ta.barssince(sig<=-1 and sig2<=-1 and dank<0 )[1]>1 and ta.barssince(dank>0)<ta.barssince(sig<=-1 and dank<0 )[1] : na, 'Strong Downtrend Started', triangles ? shape.triangledown : shape.arrowdown, location=location.top, size=size.large, color=color.new(color.yellow, transp))
plotshape(Arrows ? sig==-2 and sig2==-2 and ta.barssince(sig==-2 and sig2==-2)[1]>ta.barssince(sig2>0) : na, 'Downtrend Started', triangles ? shape.triangledown : shape.arrowdown, location=location.top, size=size.small, color=color.new(color.yellow, transp))
plotshape(Arrows ? sig==-2 and sig2==-2 and dank<0 and ta.barssince(sig==-2 and sig2==-2 and dank<0)[1]>ta.barssince(sig2>0) : na, 'Downtrend Started', triangles ? shape.triangledown : shape.arrowdown, location=location.top, size=size.small, color=color.new(color.rgb(143, 86, 0), transp))
plotshape(Arrows ? sig==-2 and sig2>0 and dank>0 and ta.barssince(sig<=-1 and sig2>0 and dank>0 )[1]>1 : na, 'Early Downtrend Started', triangles ? shape.triangledown : shape.arrowdown, location=location.top, size=size.tiny, color=color.new(color.yellow, transp))
//plotshape(Arrows ? : na, 'Early Downtrend Started', shape.xcross, location=location.absolute, size=size.tiny, color=color.yellow)
plot(dank, color=dankColor, linewidth = 2, title='RGO') //end // https://www.tradingview.com/script/UyA4515j-Stock-Rotation-Model-CC/
linexx = plot(0, color=dank>0 ? color.green : color.red, title='0-Line')
trAdjEmapl = plot(trAdjEma, "MA", dankColor2)
plot(bandhide ? dank > trAdjEma ? upper : na : upper, "Upper Band 1", BandColors ? dankColor3 : trAdjEma>0 ? color.green : color.red, style=plot.style_linebr)
plot(bandhide ? dank < trAdjEma ? lower : na : lower, "Lower Band 1", BandColors ? dankColor4 : trAdjEma>0 ? color.green : color.red, style=plot.style_linebr)
plot(bandhide ? dank > upper ? upper2 : na : upper2, "Upper Band 2", BandColors ? dankColor5 : trAdjEma>0 ? color.green : color.red, style=plot.style_linebr)
plot(bandhide ? dank < lower ? lower2 : na : lower2, "Lower Band 2", BandColors ? dankColor6 : trAdjEma>0 ? color.green : color.red, style=plot.style_linebr)
fill(trAdjEmapl, linexx, color=trAdjEma>0 ? color.new(color.green, 80) : color.new(color.red, 80)) |
Volume With Color | https://www.tradingview.com/script/1VMYD19h-Volume-With-Color/ | Amphibiantrading | https://www.tradingview.com/u/Amphibiantrading/ | 345 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Amphibiantrading
//@version=5
indicator(title="Volume With Color", shorttitle="Vol W/ Color", format=format.volume)
//inputs
var g1 = 'Moving Average'
showMA = input(true, "Show Moving Average", group = g1)
ilength = input.int(50, "MA Length", minval = 1, maxval = 500, step = 1, inline = '1', group = g1)
macolor = input(color.orange, 'MA Color', inline = '1', group = g1)
tfSwitch = input.bool(false, 'Auto change MA length for weekly chart', group = g1)
weeklyLen = input.int(10, 'Weekly MA Length', group = g1)
var g2 = 'Display'
idownday = input(color.red, "Down Day Color", inline = "1", group = g2)
idday = input(color.maroon, "Distribution Color", inline = "1", group = g2)
iupday = input(color.green, "Up Day Color", inline = "2", group = g2)
iaday = input(color.lime, "Acumulation Day Color", inline= "2", group = g2)
dryUpBool = input.bool(false, 'Show Volume Dry Ups', inline = '3', group = g2)
dryUp = input(color.orange, ' ', inline = '3', group = g2)
plotstyle = input.string('Columns', "Plot Style", options = ['Columns', 'Histogram', 'Line'])
var g3 = 'Info'
showpp = input.bool(true, 'Show Pocket Pivots', inline = '1', group = g3)
tenDay = input.bool(true, '10 Day P.P.', inline = '2', group = g3 )
pp10color = input(color.yellow, '', inline = '2', group = g3)
fiveDay = input.bool(true, '5 Day P.P.', inline = '2', group = g3 )
pp5color = input(color.blue, '', inline = '2', group = g3)
showProjected = input.bool(true, 'Show Projected Volume Bar', inline = '3', group = g3)
projColor = input.color(color.new(color.aqua,80), ' ', inline = '3', group = g3)
showTable = input.bool(true, 'Show Volume Info', inline = '4', group = g3)
yPos = input.string("Top", " ", options = ["Top", "Middle", "Bottom"], inline = '4', group= g3)
xPos = input.string("Right", " ", options = ["Right","Center", "Left"], inline = '4', group = g3)
addInfo = input.bool(false, 'Show Additional Volume Info', inline = '5', group = g3)
tableSize = input.string('Normal', 'Text Size', options = ['Tiny', 'Small', 'Normal', 'Large'], inline = '6', group = g3)
textColor = input.color(color.rgb(0, 0, 0), 'Text Color', inline = '7', group = g3)
bgColor = input.color(color.new(color.rgb(192, 195, 206),70), 'Background Color', inline = '7', group = g3)
var g4 = 'Highest Volumes'
showSky = input.bool(true, 'Show Skyscrappers', inline = '1', group = g4 )
showPer = input.bool(true, 'Percentages', inline = '1', group = g4)
showHVE = input.bool(false, 'Show Highest Volume Ever', inline = '2', group = g4)
showHV1 = input.bool(false, 'Show Highest Volume In a Year', inline = '3', group = g4)
labelSize = input.string('Normal', 'Text Size', options = ['Tiny', 'Small', 'Normal', 'Large'], inline = '4', group = g4)
colorHV = input.bool(false, 'Text Color Based on Previous Close', inline = '5', group = g4)
showLines = input.bool(false, 'Show 2x, 3x Volume Lines', inline = '6', group = g4)
lineColor = input.color(color.black, ' ', inline = '6', group = g4)
sizer = switch tableSize
'Normal' => size.normal
'Tiny' => size.tiny
'Small' => size.small
'Large' => size.large
sizerLabel = switch labelSize
'Normal' => size.normal
'Tiny' => size.tiny
'Small' => size.small
'Large' => size.large
//define days
down_day = close < close[1]
up_day = close > close[1]
avg_vol = tfSwitch and timeframe.isweekly ? ta.sma(volume,weeklyLen) : ta.sma(volume,ilength)
d_day = down_day and volume > avg_vol
a_day = up_day and volume > avg_vol
highVolYear = ta.highest(volume,252)
ph = ta.pivothigh(volume,13,13)
twoX = avg_vol * 2
threeX = avg_vol * 3
avgDollarVol = avg_vol * close
upVol = close > close[1] ? volume : 0
dnVol = close < close[1] ? volume : 0
sumUp = math.sum(upVol, 50)
sumDn = math.sum(dnVol, 50)
upDnVolRatio = sumUp / sumDn
volDry = (volume / avg_vol * 100) < 60
//variables
var table volInfo = table.new(str.lower(yPos) + '_' + str.lower(xPos), 4, 2, color.new(color.white,100),
border_color = color.new(color.white,100), border_width = 2)
var float h10 = 0
var float h5 = 0
vols = array.new<float>()
vols5 = array.new<float>()
float volSec = na
projVol = float(volume)
var hve = volume
var label hveLabel = na
var label hv1Label = na
var label phLabel = na
var line twoXLine = na
var line threeXLine = na
//select colors and style
colors = down_day ? idownday : iupday
colors := d_day ? idday : a_day ? iaday : colors
colors := dryUpBool and volDry ? dryUp : colors
// pocket pivots
for i = 0 to 10
if close[i] < close[i + 1]
array.push(vols, volume[i])
h10 := array.max(vols)
pocketpivot = close > close[1] and volume > h10
for i = 0 to 5
if close[i] < close[i + 1]
array.push(vols5, volume[i])
h5 := array.max(vols5)
pocketpivot5 = close > close[1] and volume >h5
//projected volume
timePassed = timenow - time
timeLeft = time_close - timenow
if timeLeft > 0
volSec := (volume / timePassed)
projVol := (volume + (volSec * timeLeft))
runRate = (projVol / avg_vol * 100) - 100
volPerChng = nz((volume / avg_vol * 100) - 100)
//highest volumes
if volume > hve
hve := volume
if volume == hve and showHVE
hveLabel := label.new(bar_index,volume,'HVE ' + str.tostring(volume,format.volume) + '(' + str.tostring(volPerChng, '#') + '%)',
style = label.style_none, textcolor = (colorHV ? (close[13] > close[14] ? iaday : idday) : textColor), size = sizerLabel)
else if volume == highVolYear and showHV1
hv1Label := label.new(bar_index,volume,'HVY ' + str.tostring(volume,format.volume) + '(' + str.tostring(volPerChng, '#') + '%)',
style = label.style_none, textcolor = (colorHV ? (close[13] > close[14] ? iaday : idday) : textColor), size = sizerLabel)
else if (showSky and ph)
phLabel := label.new(bar_index[13], volume[13],(showPer ? str.tostring(volume[13],format.volume) + '(' + str.tostring(volPerChng[13], '#') + '%)' :
str.tostring(volume[13],format.volume)) , style = label.style_none,
textcolor = (colorHV ? (close[13] > close[14] ? iaday : idday) : textColor), size = sizerLabel)
if (volume[13] == hve and showHVE) or (volume[13] == highVolYear and showHV1)
label.delete(phLabel)
//plots
styleplot = switch plotstyle
'Histogram' => plot.style_histogram
'Line' => plot.style_line
=> plot.style_columns
plot(volume, color = colors, style = styleplot, title="Volume")
plot(showMA ? avg_vol : na, color=macolor, title="Volume MA")
plot(showProjected and timeLeft > 0 ? projVol : na, 'Projected Vol.', color = projColor, style = plot.style_columns)
plotshape(showpp and tenDay ? pocketpivot : na, '10 Day Pocket Pivot', shape.diamond, color = pp10color, location = location.bottom, display = display.pane)
plotshape(showpp and fiveDay and not pocketpivot ? pocketpivot5 : na, '5 Day Pocket Pivot', style = shape.diamond, location = location.bottom, color = pp5color, display = display.pane)
if barstate.islast and showTable
table.cell(volInfo, 0, 0, ' ')
table.cell(volInfo, 0, 1, 'Volume: ' + str.tostring(volume,format.volume) + ', ' +
(runRate > 0 ? '+' + str.tostring(runRate, '#') + '%' : str.tostring(runRate, '#') + '%'),
bgcolor = bgColor, text_color = textColor, text_size = sizer)
if addInfo
table.cell(volInfo, 0, 0, 'Volume: ' + str.tostring(volume,format.volume) + ', ' +
(runRate > 0 ? '+' + str.tostring(runRate, '#') + '%' : str.tostring(runRate, '#') + '%'),
bgcolor = bgColor, text_color = textColor, text_size = sizer)
table.cell(volInfo, 1, 0, 'Avg. Vol: ' + str.tostring(avg_vol, format.volume),
bgcolor =bgColor, text_color = textColor, text_size = sizer)
table.cell(volInfo, 2, 0, 'Avg: $ Vol: ' + str.tostring(avgDollarVol, format.volume),
bgcolor =bgColor, text_color = textColor, text_size = sizer)
table.cell(volInfo, 3, 0, 'U/D Ratio: ' + str.tostring(upDnVolRatio, '#.##'), bgcolor =bgColor,
text_color = textColor, text_size = sizer)
table.clear(volInfo, 0, 1, 3, 1)
if barstate.islast and showLines
(twoXLine[1]).delete(), (threeXLine[1]).delete()
twoXLine := line.new(bar_index[1], twoX, bar_index + 1, twoX, color = lineColor, width = 2)
threeXLine := line.new(bar_index[1], threeX, bar_index + 1, threeX, color = lineColor, width = 2)
//alerts
if pocketpivot
alert('Pocket Pivot', alert.freq_once_per_bar_close)
else if volume >= twoX
alert('2x Average Volume', alert.freq_once_per_bar)
else if volume >= threeX
alert('3x Average Volume', alert.freq_once_per_bar) |
Up Down Volatility | https://www.tradingview.com/script/Cv49oCPG-Up-Down-Volatility/ | Koalems | https://www.tradingview.com/u/Koalems/ | 15 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Koalems
// @version=5
import Koalems/Library_Smoothers/3 as Smoothers
RMA(float src, int len) =>
alpha = 1 / len
sum = 0.0
sum := na(sum[1]) ? ta.sma(src, len) : alpha * src + (1 - alpha) * nz(sum[1])
ATR(float High, float Low, float Close, int len) =>
tr = na(High[1]) ? High - Low : math.max(math.max(High - Low, math.abs(High - Close[1])), math.abs(Low - Close[1]))
atr = RMA(tr, len)
atr
// v = σ√T
// where:
// v = volatility over some interval of time
// σ = standard deviation of returns
// T = number of periods in the time horizon
Volatility(rVolSrc, len) => ta.stdev(rVolSrc, len) * math.sqrt(len)
indicator(
title = "Up Down Volatility",
shorttitle = "UD Volatility",
overlay = false
)
Group0000 = 'Show'
rVolShowVolatility = input.bool(false, 'Volatility', group=Group0000)
rVolShowUpDown = input.bool(true, 'Up/down', group=Group0000, inline='rVolMa.2')
rVolShowDiff = input.bool(true, 'Relative strength', group=Group0000, inline='rVolMa.2')
rVolShowUpDownRel = input.bool(false, 'Relative up/down', group=Group0000, inline='rVolMa.3')
rVolShowDiffRel = input.bool(false, 'Relative strength', group=Group0000, inline='rVolMa.3')
Group0010 = 'Settings'
rVolUseAtrAsSrc = input.bool(false, "Use ATR's of high/low/close as the source", group=Group0010, tooltip='Otherwise uses high/low/close')
useMA = input.bool(false, "Use moving average", group=Group0010)
atrLen = input.int(10, 'ATR length', group=Group0010, minval=1)
Group0020 = 'MA: Settings'
correctedToolTip="Corrected Average indicator by A.Uhl (also known as the “Optimal Moving Average“).\n\nThe strengths of the corrected Average (CA) is that the current value of the time series must exceed a the current volatility-dependent threshold, so that the filter increases or falls, avoiding false signals in a weak trend phase.\n– by Prof. A.Uhl –"
rVolMaCorrected = input.bool(false, 'Corrected', group=Group0020, tooltip=correctedToolTip)
rVolMaType = input.string('SMMA', 'MA type', group=Group0020, inline='rVolMa.4', options=['None', 'AST_RMA', 'EMA', 'EHMA', 'FRAMA', 'Jurik', 'HMA', 'LINREG', 'RMA', 'SMA', 'SMMA', 'SrVolUper Smoother', 'SWMA', 'VAWMA', 'VIDYA', 'VWMA', 'WMA'])
rVolMaLength = input.int(10, 'Length', group=Group0020, inline='rVolMa.4', minval=1, step=10)
Group0030 = 'MA: Settings: Extra'
rVolMaFramaFast = input.int(2, 'FRAMA: Fast', group=Group0030, inline='rVolMa.5', minval=1, step=1)
rVolMaFramaSlow = input.int(200, 'Slow', group=Group0030, inline='rVolMa.5', minval=1, step=10)
rVolMaJurikPhase = input.int(50, 'Jurik: Phase', group=Group0030, inline='rVolMa.6', minval=-100, maxval=100, step=5)
rVolMaJurikPower = input.float(2, 'Power', group=Group0030, inline='rVolMa.6', minval=0, step=0.25)
rVolMaLinRegOffset = input.int(0, 'Lin. Reg.: Offset', group=Group0030, inline='rVolMa.6', minval=0, step=1)
rVolMaVwwmaStartingWeight = input.int(1, 'VAWMA: Starting weight', group=Group0030, inline='rVolMa.7', minval=0, step=1)
rVolMaVwwmaVolumeDefault = input.int(0, 'Vol. default', group=Group0030, inline='rVolMa.7', minval=0, step=1)
rVolUpDown = math.sign(close - close[1])
var rVolDnClose = 0., var rVolDnHigh = 0., var rVolDnLow = 0.
var rVolUpClose = 0., var rVolUpHigh = 0., var rVolUpLow = 0.
if rVolUpDown == 1
rVolUpClose := close, rVolUpHigh := high, rVolUpLow := low
if rVolUpDown == -1
rVolDnClose := close, rVolDnHigh := high, rVolDnLow := low
rVolAtr = ta.atr(atrLen)
rVolDnAtr = ATR(rVolDnHigh, rVolDnLow, rVolDnClose, atrLen)
rVolUpAtr = ATR(rVolUpHigh, rVolUpLow, rVolUpClose, atrLen)
rVolSrc = rVolUseAtrAsSrc ? rVolAtr : close
rVolDnSrc = rVolUseAtrAsSrc ? rVolDnAtr : low
rVolUpSrc = rVolUseAtrAsSrc ? rVolUpAtr : high
srcMA = Smoothers.SmootherType(rVolMaType, rVolSrc, rVolMaLength, rVolMaFramaFast, rVolMaFramaSlow, rVolMaLinRegOffset, rVolMaJurikPhase, rVolMaJurikPower, rVolMaVwwmaStartingWeight, rVolMaVwwmaVolumeDefault, rVolMaCorrected)
rVolDnSrcMA = Smoothers.SmootherType(rVolMaType, rVolDnSrc, rVolMaLength, rVolMaFramaFast, rVolMaFramaSlow, rVolMaLinRegOffset, rVolMaJurikPhase, rVolMaJurikPower, rVolMaVwwmaStartingWeight, rVolMaVwwmaVolumeDefault, rVolMaCorrected)
rVolUpSrcMA = Smoothers.SmootherType(rVolMaType, rVolUpSrc, rVolMaLength, rVolMaFramaFast, rVolMaFramaSlow, rVolMaLinRegOffset, rVolMaJurikPhase, rVolMaJurikPower, rVolMaVwwmaStartingWeight, rVolMaVwwmaVolumeDefault, rVolMaCorrected)
rVolSrc := useMA ? srcMA : rVolSrc
rVolDnSrc := useMA ? rVolDnSrcMA : rVolDnSrc
rVolUpSrc := useMA ? rVolUpSrcMA : rVolUpSrc
rVolVol = Volatility(rVolSrc, atrLen)
rVolDnVol = Volatility(rVolDnSrc, atrLen)
rVolUpVol = Volatility(rVolUpSrc, atrLen)
rVolDnUpVol = rVolUpVol - rVolDnVol
rVolDnVolRel = rVolDnVol / rVolSrc
rVolUpVolRel = rVolUpVol / rVolSrc
rVolDnUpVolRel = rVolUpVolRel - rVolDnVolRel
plot(rVolShowDiff or rVolShowDiffRel ? 0 : na, color=color.new(color.gray, 50), title="Zero")
plot(rVolShowVolatility ? rVolVol : na, color=color.new(#00ff95, 0), title="Volatility")
plot(rVolShowUpDown ? rVolDnVol : na, color=color.new(color.orange, 0), title="Down")
plot(rVolShowUpDown ? rVolUpVol : na, color=color.new(color.blue, 0), title="Up")
plot(rVolShowDiff ? rVolDnUpVol : na, color=color.new(#af4c93, 0), title="Down/up")
plot(rVolShowUpDownRel ? rVolDnVolRel : na, color=color.new(color.orange, 0), title="Relative down")
plot(rVolShowUpDownRel ? rVolUpVolRel : na, color=color.new(color.blue, 0), title="Relative up")
plot(rVolShowDiffRel ? rVolDnUpVolRel : na, color=color.new(#e14da3, 0), title="Relative down/up")
|
Pivot Point Moving Average (PPMA) | https://www.tradingview.com/script/kg4fBuPe-Pivot-Point-Moving-Average-PPMA/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 33 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("PPMA", overlay = true)
ppma(left, right)=>
signal = ta.change(ta.pivothigh(high, left, right)) or ta.change(ta.pivotlow(low, left, right))
var int count = na
var float sum = na
if not signal
count := nz(count[1]) + 1
sum := nz(sum[1]) + close
else
count := na
sum := na
sum/count
left = input.int(50, "Pivot Left", 0)
right = input.int(0, "Pivot Right", 0)
plot(ppma(left, right))
|
Zig Zag Stochastic (ZZS) | https://www.tradingview.com/script/GVSbYxhK-Zig-Zag-Stochastic-ZZS/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 39 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("Zig Zag Stochastic", "ZZS")
import lastguru/DominantCycle/2 as d
bes(float source = close, float length = 9)=>
alpha = 2 / (length + 1)
var float smoothed = na
smoothed := alpha * source + (1 - alpha) * nz(smoothed[1])
smoothing_length = input.int(14, "Smoothing length", 0, 3000, 1, tooltip = "1 represents no smoothing, 0 represents auto smoothing.")
high_left = input.int(50, "High Zig Zag Length", 0)
low_left = input.int(50, "Low Zig Zag Length", 0)
var float high_scale = na
var float low_scale = na
pivot_high = ta.pivothigh(high, high_left, 0)
pivot_low = ta.pivotlow(low, low_left, 0)
high_scale := na(pivot_high) ? nz(high_scale[1]) : pivot_high
low_scale := na(pivot_low) ? nz(low_scale[1]) : pivot_low
smoothed = ta.sma(100 * (close - low_scale)/(high_scale - low_scale), smoothing_length < 1 ? 1 : smoothing_length )
scale_price = 100 * (close - low_scale)/(high_scale - low_scale)
k_length = d.mamaPeriod(scale_price, 2, 4096)
k_line = bes(scale_price, k_length)
d_length = d.mamaPeriod(smoothing_length == 0 ? k_line : smoothed, 2, 4096)
d_line = bes(smoothing_length == 0 ? k_line : smoothed, d_length)
plot(smoothing_length == 0 ? k_line : smoothed, "Zig Zag Stochastic", color.blue)
plot(d_line, "ZZS D Line", color.orange)
top = hline(80, linestyle = hline.style_solid)
hline(50)
bot = hline(20, linestyle = hline.style_solid)
fill(top, bot, top_color = color.new(color.navy, 90), top_value = 80, bottom_value = 20, bottom_color = color.new(color.purple, 90)) |
Forex Strength Indicator | https://www.tradingview.com/script/3CYG5RXB-Forex-Strength-Indicator/ | ThiagoSchmitz | https://www.tradingview.com/u/ThiagoSchmitz/ | 149 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ThiagoSchmitz
//@version=5
indicator("Forex Strength Indicator", "FSI", explicit_plot_zorder = true)
// ◢✥◣
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Constants • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
var string magroup = "MA Settings"
var string ulgroup = "Upper Levels Settings"
var string mainline = "masettings"
var string llgroup = "Lower Levels Settings"
var string levelsgroup = "Level Settings"
var string ulinline1 = "upperinline1"
var string ulinline2 = "upperinline2"
var string ulinline3 = "upperinline3"
var string llinline1 = "lowerinline1"
var string llinline2 = "lowerinline2"
var string llinline3 = "lowerinline3"
var string cigroup = "colors"
var string generalgroup = "Layout Settings"
var string lengthinline = "length"
var string labelStyle = label.style_label_left
var string xloc = xloc.bar_time
var string yloc = yloc.price
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Constants • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ◢✥◣
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Inputs • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
var bool darkMode = input.bool(true, "Dark Mode", group=generalgroup, inline=generalgroup)
var bool barColoring = input.bool(true, "Bar Coloring", group=generalgroup, inline=generalgroup)
var float src = input.source(close, "Source", group=magroup, inline=mainline)
var string maType = input.string("EMA", "Type", ["EMA", "SMA", "HMA", "RMA", "WMA", "SWMA", "Linear Regression"], group=magroup, inline=mainline)
var int period = input.int(20, "Period", group=magroup, inline=mainline)
var int delta = input.int(5, "Delta", group=magroup, inline=mainline)
var bool showLevels = input.bool(true, "Show Levels", group=levelsgroup)
var int linearRegLength = input.int(400, "Linear Reg Length", group=levelsgroup, inline=lengthinline)
var int stdevLength = input.int(4000, "Std Dev Length", group=levelsgroup, inline=lengthinline)
var bool showUpperLevel1 = input.bool(true, "", inline=ulinline1, group=ulgroup)
var float upperLevel1 = input.float(0.618, "Level 1", inline=ulinline1, group=ulgroup)
var bool showUpperLevel2 = input.bool(true, "", inline=ulinline1, group=ulgroup)
var float upperLevel2 = input.float(1.000, "Level 2", inline=ulinline1, group=ulgroup)
var bool showUpperLevel3 = input.bool(true, "", inline=ulinline2, group=ulgroup)
var float upperLevel3 = input.float(1.618, "Level 3", inline=ulinline2, group=ulgroup)
var bool showUpperLevel4 = input.bool(true, "", inline=ulinline2, group=ulgroup)
var float upperLevel4 = input.float(2.000, "Level 4", inline=ulinline2, group=ulgroup)
var bool showUpperLevel5 = input.bool(true, "", inline=ulinline3, group=ulgroup)
var float upperLevel5 = input.float(2.618, "Level 5", inline=ulinline3, group=ulgroup)
var bool showLowerLevel1 = input.bool(true, "", inline=llinline1, group=llgroup)
var float lowerLevel1 = input.float(0.618, "Level 1", inline=llinline1, group=llgroup)
var bool showLowerLevel2 = input.bool(true, "", inline=llinline1, group=llgroup)
var float lowerLevel2 = input.float(1.000, "Level 2", inline=llinline1, group=llgroup)
var bool showLowerLevel3 = input.bool(true, "", inline=llinline2, group=llgroup)
var float lowerLevel3 = input.float(1.618, "Level 3", inline=llinline2, group=llgroup)
var bool showLowerLevel4 = input.bool(true, "", inline=llinline2, group=llgroup)
var float lowerLevel4 = input.float(2.000, "Level 4", inline=llinline2, group=llgroup)
var bool showLowerLevel5 = input.bool(true, "", inline=llinline3, group=llgroup)
var float lowerLevel5 = input.float(2.618, "Level 5", inline=llinline3, group=llgroup)
var color colorEUR = input.color(#EC407A, "EUR", inline=cigroup, group = cigroup)
var color colorGBP = input.color(#FFA726, "GBP", inline=cigroup, group = cigroup)
var color colorAUD = input.color(#FFCA28, "AUD", inline=cigroup, group = cigroup)
var color colorNZD = input.color(#66BB6A, "NZD", inline=cigroup, group = cigroup)
var color colorUSD = input.color(#26C6DA, "USD", inline=cigroup, group = cigroup)
var color colorCAD = input.color(#42A5F5, "CAD", inline=cigroup, group = cigroup)
var color colorCHF = input.color(#7E57C2, "CHF", inline=cigroup, group = cigroup)
var color colorJPY = input.color(#FF7043, "JPY", inline=cigroup, group = cigroup)
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Inputs • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ◢✥◣
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Functions • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
getCalc() =>
value = switch maType
"EMA" => ta.ema(close, period)
"SMA" => ta.sma(close, period)
"HMA" => ta.hma(close, period)
"RMA" => ta.rma(close, period)
"WMA" => ta.wma(close, period)
"SWMA" => ta.swma(close)
"Linear Regression" => ta.linreg(close, period, 0)
del = value / value[delta]
del
format(txt) => str.format("{0,number,#.###}", txt)
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Functions • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ◢✥◣
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Requests • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
float EURGBP = request.security("EURGBP", "", getCalc())
float EURAUD = request.security("EURAUD", "", getCalc())
float EURNZD = request.security("EURNZD", "", getCalc())
float EURUSD = request.security("EURUSD", "", getCalc())
float EURCAD = request.security("EURCAD", "", getCalc())
float EURCHF = request.security("EURCHF", "", getCalc())
float EURJPY = request.security("EURJPY", "", getCalc())
float GBPAUD = request.security("GBPAUD", "", getCalc())
float GBPNZD = request.security("GBPNZD", "", getCalc())
float GBPUSD = request.security("GBPUSD", "", getCalc())
float GBPCAD = request.security("GBPCAD", "", getCalc())
float GBPCHF = request.security("GBPCHF", "", getCalc())
float GBPJPY = request.security("GBPJPY", "", getCalc())
float AUDNZD = request.security("AUDNZD", "", getCalc())
float AUDUSD = request.security("AUDUSD", "", getCalc())
float AUDCAD = request.security("AUDCAD", "", getCalc())
float AUDCHF = request.security("AUDCHF", "", getCalc())
float AUDJPY = request.security("AUDJPY", "", getCalc())
float NZDUSD = request.security("NZDUSD", "", getCalc())
float NZDCAD = request.security("NZDCAD", "", getCalc())
float NZDCHF = request.security("NZDCHF", "", getCalc())
float NZDJPY = request.security("NZDJPY", "", getCalc())
float USDCAD = request.security("USDCAD", "", getCalc())
float USDCHF = request.security("USDCHF", "", getCalc())
float USDJPY = request.security("USDJPY", "", getCalc())
float CADCHF = request.security("CADCHF", "", getCalc())
float CADJPY = request.security("CADJPY", "", getCalc())
float CHFJPY = request.security("CHFJPY", "", getCalc())
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Requests • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ◢✥◣
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Variables • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
var table tab = table.new(position.middle_right, 1, 9)
var color labelColor = darkMode ? color.new(color.white, 40) : color.new(color.black, 40)
var color levelColor = darkMode ? color.new(color.white, 90) : color.new(color.black, 90)
var color labelStyleColor = color.new(color.white, 99)
var label[] labelsGroup = array.from(
showUpperLevel1 ? label.new(time, close, format(upperLevel1), xloc, yloc, labelStyleColor, labelStyle, labelColor) : na,
showUpperLevel2 ? label.new(time, close, format(upperLevel2), xloc, yloc, labelStyleColor, labelStyle, labelColor) : na,
showUpperLevel3 ? label.new(time, close, format(upperLevel3), xloc, yloc, labelStyleColor, labelStyle, labelColor) : na,
showUpperLevel4 ? label.new(time, close, format(upperLevel4), xloc, yloc, labelStyleColor, labelStyle, labelColor) : na,
showUpperLevel5 ? label.new(time, close, format(upperLevel5), xloc, yloc, labelStyleColor, labelStyle, labelColor) : na,
showLowerLevel1 ? label.new(time, close, format(lowerLevel1), xloc, yloc, labelStyleColor, labelStyle, labelColor) : na,
showLowerLevel2 ? label.new(time, close, format(lowerLevel2), xloc, yloc, labelStyleColor, labelStyle, labelColor) : na,
showLowerLevel3 ? label.new(time, close, format(lowerLevel3), xloc, yloc, labelStyleColor, labelStyle, labelColor) : na,
showLowerLevel4 ? label.new(time, close, format(lowerLevel4), xloc, yloc, labelStyleColor, labelStyle, labelColor) : na,
showLowerLevel5 ? label.new(time, close, format(lowerLevel5), xloc, yloc, labelStyleColor, labelStyle, labelColor) : na)
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Variables • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ◢✥◣
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Definitions • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
float EUR = (EURGBP * EURAUD * EURNZD * EURUSD * EURCAD * EURCHF * EURJPY) - 1
float GBP = (1 / EURGBP * GBPAUD * GBPNZD * GBPUSD * GBPCAD * GBPCHF * GBPJPY) - 1
float AUD = (1 / EURAUD * 1 / GBPAUD * AUDNZD * AUDUSD * AUDCAD * AUDCHF * AUDJPY) - 1
float NZD = (1 / EURNZD * 1 / GBPNZD * 1 / AUDNZD * NZDUSD * NZDCAD * NZDCHF * NZDJPY) - 1
float USD = (1 / EURUSD * 1 / GBPUSD * 1 / AUDUSD * 1 / NZDUSD * USDCAD * USDCHF * USDJPY) - 1
float CAD = (1 / EURCAD * 1 / GBPCAD * 1 / AUDCAD * 1 / NZDCAD * 1 / USDCAD * CADCHF * CADJPY) - 1
float CHF = (1 / EURCHF * 1 / GBPCHF * 1 / AUDCHF * 1 / NZDCHF * 1 / USDCHF * 1 / CADCHF * CHFJPY) - 1
float JPY = (1 / EURJPY * 1 / GBPJPY * 1 / AUDJPY * 1 / NZDJPY * 1 / USDJPY * 1 / CADJPY * 1 / CHFJPY) - 1
bool isEURbase = syminfo.basecurrency == "EUR"
bool isEURcurr = syminfo.currency == "EUR"
bool isGBPbase = syminfo.basecurrency == "GBP"
bool isGBPcurr = syminfo.currency == "GBP"
bool isAUDbase = syminfo.basecurrency == "AUD"
bool isAUDcurr = syminfo.currency == "AUD"
bool isNZDbase = syminfo.basecurrency == "NZD"
bool isNZDcurr = syminfo.currency == "NZD"
bool isUSDbase = syminfo.basecurrency == "USD"
bool isUSDcurr = syminfo.currency == "USD"
bool isCADbase = syminfo.basecurrency == "CAD"
bool isCADcurr = syminfo.currency == "CAD"
bool isCHFbase = syminfo.basecurrency == "CHF"
bool isCHFcurr = syminfo.currency == "CHF"
bool isJPYbase = syminfo.basecurrency == "JPY"
bool isJPYcurr = syminfo.currency == "JPY"
bool isEUR = isEURbase or isEURcurr
bool isGBP = isGBPbase or isGBPcurr
bool isAUD = isAUDbase or isAUDcurr
bool isNZD = isNZDbase or isNZDcurr
bool isUSD = isUSDbase or isUSDcurr
bool isCAD = isCADbase or isCADcurr
bool isCHF = isCHFbase or isCHFcurr
bool isJPY = isJPYbase or isJPYcurr
float activeBase =
isEURbase ? EUR :
isGBPbase ? GBP :
isAUDbase ? AUD :
isNZDbase ? NZD :
isUSDbase ? USD :
isCADbase ? CAD :
isCHFbase ? CHF :
isJPYbase ? JPY : 0
float activeCurrency =
isEURcurr ? EUR :
isGBPcurr ? GBP :
isAUDcurr ? AUD :
isNZDcurr ? NZD :
isUSDcurr ? USD :
isCADcurr ? CAD :
isCHFcurr ? CHF :
isJPYcurr ? JPY : 0
float linearReg = ta.linreg((activeBase + activeCurrency) / 2, linearRegLength, 0)
float stdev = ta.stdev(linearReg, stdevLength)
float strongest = array.max(array.from(EUR, GBP, AUD, NZD, CAD, CHF, JPY))
float weakest = array.min(array.from(EUR, GBP, AUD, NZD, CAD, CHF, JPY))
float[] levelsGroup = array.from(
linearReg + stdev * upperLevel1 * 10, linearReg + stdev * upperLevel2 * 10,
linearReg + stdev * upperLevel3 * 10, linearReg + stdev * upperLevel4 * 10,
linearReg + stdev * upperLevel5 * 10, linearReg - stdev * lowerLevel1 * 10,
linearReg - stdev * lowerLevel2 * 10, linearReg - stdev * lowerLevel3 * 10,
linearReg - stdev * lowerLevel4 * 10, linearReg - stdev * lowerLevel5 * 10)
string EURStrength = strongest == EUR ? " ↑" : weakest == EUR ? " ↓" : " ◌"
string GBPStrength = strongest == GBP ? " ↑" : weakest == GBP ? " ↓" : " ◌"
string AUDStrength = strongest == AUD ? " ↑" : weakest == AUD ? " ↓" : " ◌"
string NZDStrength = strongest == NZD ? " ↑" : weakest == NZD ? " ↓" : " ◌"
string USDStrength = strongest == USD ? " ↑" : weakest == USD ? " ↓" : " ◌"
string CADStrength = strongest == CAD ? " ↑" : weakest == CAD ? " ↓" : " ◌"
string CHFStrength = strongest == CHF ? " ↑" : weakest == CHF ? " ↓" : " ◌"
string JPYStrength = strongest == JPY ? " ↑" : weakest == JPY ? " ↓" : " ◌"
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Definitions • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ◢✥◣
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Table • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
table.cell(tab, 0, 0, "EUR" + EURStrength, text_color = isEUR ? color.white : colorEUR, bgcolor = isEUR ? colorEUR : na)
table.cell(tab, 0, 1, "GBP" + GBPStrength, text_color = isGBP ? color.white : colorGBP, bgcolor = isGBP ? colorGBP : na)
table.cell(tab, 0, 2, "AUD" + AUDStrength, text_color = isAUD ? color.white : colorAUD, bgcolor = isAUD ? colorAUD : na)
table.cell(tab, 0, 3, "NZD" + NZDStrength, text_color = isNZD ? color.white : colorNZD, bgcolor = isNZD ? colorNZD : na)
table.cell(tab, 0, 4, "USD" + USDStrength, text_color = isUSD ? color.white : colorUSD, bgcolor = isUSD ? colorUSD : na)
table.cell(tab, 0, 5, "CAD" + CADStrength, text_color = isCAD ? color.white : colorCAD, bgcolor = isCAD ? colorCAD : na)
table.cell(tab, 0, 6, "CHF" + CHFStrength, text_color = isCHF ? color.white : colorCHF, bgcolor = isCHF ? colorCHF : na)
table.cell(tab, 0, 7, "JPY" + JPYStrength, text_color = isJPY ? color.white : colorJPY, bgcolor = isJPY ? colorJPY : na)
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Table • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ◢✥◣
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Plots • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
plot(0, "Zero Line", color.white)
plot(isEUR ? na : EUR, "EUR", color.new(colorEUR, 50))
plot(isGBP ? na : GBP, "GBP", color.new(colorGBP, 50))
plot(isAUD ? na : AUD, "AUD", color.new(colorAUD, 50))
plot(isNZD ? na : NZD, "NZD", color.new(colorNZD, 50))
plot(isUSD ? na : USD, "USD", color.new(colorUSD, 50))
plot(isCAD ? na : CAD, "CAD", color.new(colorCAD, 50))
plot(isCHF ? na : CHF, "CHF", color.new(colorCHF, 50))
plot(isJPY ? na : JPY, "JPY", color.new(colorJPY, 50))
plot(isEUR ? EUR : na, "EUR", colorEUR, 3)
plot(isGBP ? GBP : na, "GBP", colorGBP, 3)
plot(isAUD ? AUD : na, "AUD", colorAUD, 3)
plot(isNZD ? NZD : na, "NZD", colorNZD, 3)
plot(isUSD ? USD : na, "USD", colorUSD, 3)
plot(isCAD ? CAD : na, "CAD", colorCAD, 3)
plot(isCHF ? CHF : na, "CHF", colorCHF, 3)
plot(isJPY ? JPY : na, "JPY", colorJPY, 3)
plot(showLevels and showUpperLevel1 ? array.get(levelsGroup, 0) : na, "Upper Level 1", color.new(levelColor, 90))
plot(showLevels and showUpperLevel2 ? array.get(levelsGroup, 1) : na, "Upper Level 2", color.new(levelColor, 80))
plot(showLevels and showUpperLevel3 ? array.get(levelsGroup, 2) : na, "Upper Level 3", color.new(levelColor, 70))
plot(showLevels and showUpperLevel4 ? array.get(levelsGroup, 3) : na, "Upper Level 4", color.new(levelColor, 60))
plot(showLevels and showUpperLevel5 ? array.get(levelsGroup, 4) : na, "Upper Level 5", color.new(levelColor, 50))
plot(showLevels and showLowerLevel1 ? array.get(levelsGroup, 5) : na, "Lower Level 1", color.new(levelColor, 90))
plot(showLevels and showLowerLevel2 ? array.get(levelsGroup, 6) : na, "Lower Level 2", color.new(levelColor, 80))
plot(showLevels and showLowerLevel3 ? array.get(levelsGroup, 7) : na, "Lower Level 3", color.new(levelColor, 70))
plot(showLevels and showLowerLevel4 ? array.get(levelsGroup, 8) : na, "Lower Level 4", color.new(levelColor, 60))
plot(showLevels and showLowerLevel5 ? array.get(levelsGroup, 9) : na, "Lower Level 5", color.new(levelColor, 50))
barcolor(barColoring ? activeCurrency > activeBase ? color.red : color.green : na)
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Plots • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ◢✥◣
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Updates • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
if barstate.islast and showLevels
for i = 0 to array.size(labelsGroup) - 1 by 1
el = array.get(labelsGroup, i)
if not na(el)
label.set_xy(el, chart.right_visible_bar_time, array.get(levelsGroup, i))
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Updates • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ◢✥◣
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Alerts • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
alertcondition(ta.crossover(activeBase, activeCurrency), "Base/Currency Crossover")
alertcondition(ta.crossunder(activeBase, activeCurrency), "Base/Currency Crossunder")
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Alerts • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲ |
Wavechart v2 | https://www.tradingview.com/script/TfDFX1Sn-Wavechart-v2/ | Asano_Voyl | https://www.tradingview.com/u/Asano_Voyl/ | 78 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MNR_Anas
//@version=5
indicator("Wave Chart v2","WaveChartV2", overlay=true ,max_lines_count=500,max_bars_back=5000)
////input
TF = input.timeframe('W', "Resolution", options=['30','60','240','D','W','2W','M','2M','3M','6M','1Y','2Y','2.5Y','5Y'])
lineWidth = input.int(2, title="line ", minval=1,inline = "2")
linecolor = input.color(color.blue,title="",inline = "2")
show_unsure = input.bool(false,title="Show an unsure line",inline = "3",tooltip = "Not sure whether high or low comes first,\nIt is recommended to check in a lower Timeframe")
unsureColor = input.color(color.gray,title="",inline = "3")
bg = input.bool(false,title="Show Time Divider")
last_bar_plot = input.bool(false,title="Force plot on the last Bar")
targetTime1 = timestamp(year, month, dayofmonth, 00, 00, 00) // 1D
var count = 0
var year_count = year
var mont_count = 0
if ta.change(time('12M')) > 0
year_count:=year_count+1
if TF == '2.5Y' and ta.change(time('M')) > 0 and mont_count != 0
mont_count:=mont_count+1
if TF == '2.5Y' and year_count%5==0
mont_count:=month
preAction = switch TF
"1Y" => year_count != year_count[1] ? true : false
"2Y" => year_count != year_count[1] and year_count%2 == 0? true : false
"2.5Y" => mont_count != mont_count[1] and mont_count%30 == 1 and mont_count != 0 ? true : false
"5Y" => year_count != year_count[1] and year_count%5 == 0? true : false
=> ta.change(time(TF)) > 0
TFCheck = switch TF
"D" => timeframe.isdwm ? false : true
"W" => timeframe.isintraday or timeframe.isdaily ? true : false
"2W" => timeframe.isintraday or timeframe.isdaily ? true : false
"M" => timeframe.isintraday or timeframe.isdaily or (timeframe.isweekly and timeframe.multiplier == 1) ? true : false
"2M" => timeframe.isintraday or timeframe.isdaily or (timeframe.isweekly and timeframe.multiplier == 1) ? true : false
"3M" => timeframe.ismonthly and timeframe.multiplier>1 ? false : true
"6M" => timeframe.ismonthly and timeframe.multiplier>1 ? false : true
"1Y" => timeframe.ismonthly and timeframe.multiplier>1 ? false : true
"2Y" => timeframe.ismonthly and timeframe.multiplier>1 ? false : true
"2.5Y" => timeframe.ismonthly and timeframe.multiplier>1 ? false : true
"5Y" => timeframe.ismonthly and timeframe.multiplier>1 ? false : true
=> timeframe.isintraday and timeframe.multiplier <= str.tonumber(TF)/4 ? true : false
action = preAction and TFCheck
if(last_bar_plot and barstate.islast)
action:=true
bgcolor(action and bg?color.new(color.gray,70):na)
if(TFCheck)
count:=count+1
if(action)
count:=1
hbar=TFCheck?ta.highestbars(count):na //bar that highest in range
lbar=TFCheck?ta.lowestbars(count):na //bar that lowest in range
whigh=(high[-hbar])[1] //value of height from habr
wlow=(low[-lbar])[1] //value of low from lbar
var vx1=0, vx2=0
var px=0 //Previous x
var py=0.0 //Provious y
var vy1=0.0
var vy2=0.0
center = ((count[1]+1)/2) // Center Point
mid_left = (center+1)/2 // Center of first to center
mid_right = count[1]-(mid_left-1) // Center of center to lastBar
h_before_l = false
l_before_h = false
h_l_in_samebar = false
if(action and hbar[1]<lbar[1] ) //check whether high or low comes first
h_before_l:=true
else if(action and hbar[1]>lbar[1] )
l_before_h:=true
else if(action and hbar[1]==lbar[1]) //But if the highest and lowest are from the same bar,
linecolor:=show_unsure?unsureColor:linecolor
h_l_in_samebar:=true
// Assume it is from a bar close
if (h_l_in_samebar and (close[-hbar])[1]<(open[-hbar])[1])
h_before_l:=true
else if(h_l_in_samebar)
l_before_h:=true
if(action) //Runs only action Bar
if(h_before_l) //If the highest point comes before the lowest point
vx1:=bar_index[mid_right]
vy1:=whigh
vx2:=bar_index[mid_left]
vy2:=wlow
if(l_before_h) //If the Lowestest point comes before the lowest point
vx1:=bar_index[mid_right]
vy1:=wlow
vx2:=bar_index[mid_left]
vy2:=whigh
//plot line
if(px!=0 and py!=0)
line.new(x1=px, y1=py, x2=vx1, y2=vy1,color=linecolor,width=lineWidth) //line between previous points
line.new(x1=vx1, y1=vy1, x2=vx2, y2=vy2,color=linecolor,width=lineWidth) //line between high and low
//memory last point
px:=vx2
py:=vy2
/////
// Message Box
if(not TFCheck and barstate.islast)
statusText = "please use Lower Timeframe"
text_location = 0.0
l = label.new(bar_index,na) //label.new(bar_index, na)
label.set_text(l, statusText)
label.set_y(l,high)
boxColor = color.lime
label.set_color(l, color.red)
label.set_size(l,size.huge) |
WRBHG with visual gap block | https://www.tradingview.com/script/B4IGXVLO-WRBHG-with-visual-gap-block/ | MalibuKenny | https://www.tradingview.com/u/MalibuKenny/ | 40 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MalibuKenny
//@version=5
indicator("v.2 WRBHG with visual gap box", overlay = true, max_bars_back=5000, max_lines_count=500, max_labels_count=500, max_boxes_count = 500)
group0 = 'Period under study'
startDate = input.time(title='Start Date', defval=timestamp("2000-01-19 09:00:00 GMT+8"), group=group0)
endDate = input.time(title='End Date', defval=timestamp('2099-09-01 09:00:00 GMT+8'), tooltip='Date & time to stop analysis', group=group0)
use_custom_period = input.bool(title='use_custom_period', defval=true, group=group0, inline='HLline')
var timeSession = '0900-0800'
// This function returns true if the current bar falls within the given time session (:1234567 is to include all weekdays)
inSession(sess) => //custom function input sess
na(time(timeframe.period, sess + ':1234567', 'GMT+8')) == false and time >= startDate and time <= endDate
// Check if a new session has begun (not in ==> in)
var withinSession = false
if not inSession(timeSession)[1] and inSession(timeSession)
withinSession := true
if inSession(timeSession)[1] and not inSession(timeSession)
withinSession := false
var WRBHG_upper = 0.0
var WRBHG_upper_index = 0
var WRBHG_lower = 0.0
var WRBHG_lower_index = 0
var fillColor = color.black
bool rising = na
x_extend_count = input.int(title="x extend count", defval = 30)
transp = input.int(title="Transparency", defval = 70)
// WRBHQ begin
body = math.abs(open-close)
wrb_value = body>body[1] and body>body[2] and body>body[3] ? math.avg(open,close) : na
hg_value = (wrb_value[1] and (low>high[2] or high<low[2]))? wrb_value[1] : na
wrb = body>body[1] and body>body[2] and body>body[3]
hg = (wrb[1] and (low>high[2] or high<low[2]))
if withinSession
if hg
if close[1] > open[1] and low > high [2]// rising HG
WRBHG_upper := low
WRBHG_lower := high[2]
rising := true
fillColor := color.new(color.green, transp)
else if close[1] < open[1] and low > high [2]// rising HG
WRBHG_upper := low
WRBHG_lower := high[2]
rising := true
fillColor := color.new(color.green, transp)
else // dropping HG
WRBHG_upper := low[2]
WRBHG_lower := high
rising := false
fillColor := color.new(color.red, transp)
box.new(bar_index-1, WRBHG_upper, bar_index + x_extend_count, WRBHG_lower, border_color = na, bgcolor = fillColor)
s3=ta.ema(ohlc4,3)
plot(s3,color=color.new(color.black,0))
|
Interpolated SMA (ISMA) | https://www.tradingview.com/script/FyQrRzEc-Interpolated-SMA-ISMA/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 19 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("Interpolated SMA", "ISMA", overlay = true)
import Electrified/Interpolation/1 as i
sma(source, length)=>
var float sum = na
sum := nz(sum[1]) + close
if length % 1 != 0
sma = (sum - sum[int(length)] + (i.linear(length % 1, sum[int(length)] - sum[int(length)+1], 0, false)))/length
else
sma = (sum - sum[length])/length
source = input.source(close, "Source")
length = input.float(20.25, "Length", 1, 2000, 0.25)
plot(sma(source, length))
|
TICK Divergence + Heikin Ashi [Pt] | https://www.tradingview.com/script/zOQNkPHO-TICK-Divergence-Heikin-Ashi-Pt/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 205 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PtGambler
//@version=5
indicator(title='TICK Divergence + Heikin Ashi [Pt]', shorttitle='[Pt] TICK Dvg', overlay=false)
// ----------------------------------- Inputs ------------------------------------------
tick_symbol = input.symbol("USI:TICK", "Symbol")
display = input.string("Line", "Show TICK as:", options = ["Line", "Bar", "Heikin Ashi"], inline = "tick")
line_col = input.color(color.white, "─", inline = "tick")
bar_up_col = input.color(color.lime, "↑", inline = "tick")
bar_down_col = input.color(color.red, "↓", inline = "tick")
// Dual MA
showma1 = input.bool(true, "Fast MA", inline = "grp1len1", group = "Dual Moving Average")
matype1 = input.string("EMA", "", ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], inline = "grp1len1", group = "Dual Moving Average")
malen1 = input.int(9, "Length", inline = "grp1len1", group = "Dual Moving Average")
ma_col1 = input.color(color.yellow, "", inline = "grp1len1", group = "Dual Moving Average")
showma2 = input.bool(true, "Slow MA", inline = "grp1len2", group = "Dual Moving Average")
matype2 = input.string("EMA", "", ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], inline = "grp1len2", group = "Dual Moving Average")
malen2 = input.int(21, "Length", inline = "grp1len2", group = "Dual Moving Average")
ma_col2 = input.color(color.orange, "", inline = "grp1len2", group = "Dual Moving Average")
show_ma_x1 = input.bool(true, "Show MA cross", inline = "x1", group = "Dual Moving Average")
x_up_col1 = input.color(color.green, "▲", inline = "x1", group = "Dual Moving Average")
x_down_col1 = input.color(color.red, "▼", inline = "x1", group = "Dual Moving Average")
// MA and Smoothed MA
showma3 = input.bool(true, "Base MA", inline = "grp2len1", group = "Moving Average / Smoothed MA")
matype3 = input.string("HMA", "", ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], inline = "grp2len1", group = "Moving Average / Smoothed MA")
malen3 = input.int(21, "Length", inline = "grp2len1", group = "Moving Average / Smoothed MA")
ma_col3 = input.color(color.aqua, "", inline = "grp2len1", group = "Moving Average / Smoothed MA")
showma4 = input.bool(true, "Smoothed MA", inline = "grp2len2", group = "Moving Average / Smoothed MA")
matype4 = input.string("EMA", "", ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], inline = "grp2len2", group = "Moving Average / Smoothed MA")
malen4 = input.int(5, "Length", inline = "grp2len2", group = "Moving Average / Smoothed MA")
ma_col4 = input.color(color.red, "", inline = "grp2len2", group = "Moving Average / Smoothed MA")
show_ma_x2 = input.bool(true, "Show MA cross", inline = "x2" , group = "Moving Average / Smoothed MA")
x_up_col2 = input.color(color.blue, "▲", inline = "x2", group = "Moving Average / Smoothed MA")
x_down_col2 = input.color(color.orange, "▼", inline = "x2", group = "Moving Average / Smoothed MA")
// Divergence
dvg_src = input.string('High/Low', 'Source', options = ['High/Low', 'Close'], group = "Divergence - Pivot based")
lbR = input(2, title='Pivot Lookback Right', group = "Divergence - Pivot based")
lbL = input(5, title='Pivot Lookback Left', group = "Divergence - Pivot based")
rangeUpper = input(60, title='Max of Lookback Range', group = "Divergence - Pivot based")
rangeLower = input(5, title='Min of Lookback Range', group = "Divergence - Pivot based")
plotBull = input(true, title='Plot Bullish', group = "Divergence - Pivot based")
plotHiddenBull = input(true, title='Plot Hidden Bullish', group = "Divergence - Pivot based")
plotBear = input(true, title='Plot Bearish', group = "Divergence - Pivot based")
plotHiddenBear = input(true, title='Plot Hidden Bearish', group = "Divergence - Pivot based")
//Backgroun colors
bg_ma = input.string("Slow MA", "Change Background Color based on:", options = ["Fast MA", "Slow MA", "Base MA", "Smoothed MA", "TICK", "None"], group = "Background Color")
bg_bull_col = input.color(color.new(color.green, 90), "Bullish BG Color", group = "Background Color", tooltip = "Above zero line")
bg_bear_col = input.color(color.new(color.red, 90), "Bearish BG Color", group = "Background Color", tooltip = "Below zero line")
// Significant levels
neutralH = input.int(200, title="Neutral zone +/- from 0", minval = 0, step=10, inline = "neutral", group = "Significant Levels")
neutral_col = input.color(color.new(color.gray,90), "", inline = "neutral", group = "Significant Levels")
neutralL = -neutralH
BullishH = input.int(500, title="Trend zone +/- from 0", minval = 0, step=10, inline = "trend", group = "Significant Levels", tooltip = "Background will turn Bullish color if TICK is above this level, Bearish color if below negative of this level")
uptrend_col = input.color(color.new(color.green,70), "", inline = "trend", group = "Significant Levels")
downtrend_col = input.color(color.new(color.red,70), "", inline = "trend", group = "Significant Levels")
showtrend = input.bool(true, "", inline = "trend", group = "Significant Levels")
BearishL = -BullishH
OverH = input.int(800, title="OB/OS extremes +/- from 0", minval = 0, step=10, inline = "over", group = "Significant Levels", tooltip = "Background will turn bright Bullish color if TICK is above this level indicating Overbought, bright Bearish color if below negative of this level indicating Oversold")
ob_col = input.color(color.new(color.green,30), "", inline = "over", group = "Significant Levels")
os_col = input.color(color.new(color.red,30), "", inline = "over", group = "Significant Levels")
showOBOS = input.bool(true, "", inline = "over", group = "Significant Levels")
OverL = -OverH
// ---------------------------------------------- Functions -----------------------------------------------
f_hma(_src, _length) =>
_return = ta.wma(2 * ta.wma(_src, _length / 2) - ta.wma(_src, _length), math.round(math.sqrt(_length)))
_return
f_ma(_src, _length, _type) =>
switch _type
"SMA" => ta.sma(_src, _length)
"EMA" => ta.ema(_src, _length)
"SMMA (RMA)" => ta.rma(_src, _length)
"WMA" => ta.wma(_src, _length)
"VWMA" => ta.vwma(_src, _length)
"HMA" => f_hma(_src, _length)
// --------------------------------------------- Calculations -------------------------------------------------
//get TICK data
[tickO, tickH, tickL, tickC, tickfb, ticklb] = request.security(tick_symbol, timeframe.period, [open, high, low, close, session.isfirstbar, session.islastbar])
[ha_tickO, ha_tickH, ha_tickL, ha_tickC] = request.security(ticker.heikinashi(tick_symbol), timeframe.period, [open, high, low, close])
tickMA1 = f_ma(tickC, malen1, matype1)
tickMA2 = f_ma(tickC, malen2, matype2)
tickMA3 = f_ma(tickC, malen3, matype3)
tickMA4 = f_ma(tickMA3, malen4, matype4)
// ------------------------------------------------- Plots ----------------------------------------------------
var in_session = false
in_session := tickfb ? true : ticklb[1] ? false : in_session[1]
float O = na
float H = na
float L = na
float C = na
if in_session
O := display == "Bar" ? tickO : display == "Heikin Ashi" ? ha_tickO : na
H := display == "Bar" ? tickH : display == "Heikin Ashi" ? ha_tickH : na
L := display == "Bar" ? tickL : display == "Heikin Ashi" ? ha_tickL : na
C := display == "Bar" ? tickC : display == "Heikin Ashi" ? ha_tickC : na
plot(display == "Line" and in_session ? tickC : na, title='TICK', color = line_col , style=plot.style_linebr, linewidth = 2)
plotcandle(O, H, L, C, "TICK", color = C > O ? bar_up_col : bar_down_col, wickcolor = C > O ? bar_up_col : bar_down_col, bordercolor = C > O ? bar_up_col : bar_down_col)
plot(showma1 ? tickMA1 : na, title='TICK Fast MA', color = ma_col1, style=plot.style_line, linewidth = 2)
plot(showma2 ? tickMA2 : na, title='TICK Slow MA', color = ma_col2, style=plot.style_line, linewidth = 2)
plot(showma3 ? tickMA3 : na, title='TICK Base MA', color = ma_col3, style=plot.style_line, linewidth = 3)
plot(showma4 ? tickMA4 : na, title='TICK Smoothed MA', color = ma_col4, style=plot.style_line, linewidth = 3)
OB = hline(OverH, color=color.gray, linestyle=hline.style_dashed)
upperbull = hline(BullishH, color=color.gray, linestyle=hline.style_dashed)
lowerbull = hline(neutralH, color=color.gray, linestyle=hline.style_dashed)
median = hline(0, color=color.orange, linestyle = hline.style_dotted, linewidth = 2)
upperbear = hline(neutralL, color=color.gray, linestyle=hline.style_dashed)
lowerbear = hline(BearishL, color=color.gray, linestyle=hline.style_dashed)
OS = hline(OverL, color=color.gray, linestyle=hline.style_dashed)
fill( upperbull, OB, color.new(color.green,90), title = "Upper Bull trend zone")
fill( lowerbull, upperbull, color.new(color.green,80), title = "Lower Bull trend zone")
fill( upperbear, lowerbear, color.new(color.red,80), title = "Upper Bear trend zone")
fill( lowerbear, OS, color.new(color.red,90), title = "Lower Bear trend zone")
dma_bullx = ta.crossover(tickMA1,tickMA2)
dma_bearx = ta.crossunder(tickMA1,tickMA2)
smma_bullx = ta.crossover(tickMA3,tickMA4)
smma_bearx = ta.crossunder(tickMA3,tickMA4)
plotshape(show_ma_x1 ? dma_bearx : na ,"Cross down", color=x_down_col1, style=shape.triangledown, location = location.top, size =size.tiny)
plotshape(show_ma_x1 ? dma_bullx : na ,"Cross up", color=x_up_col1, style=shape.triangleup, location = location.bottom, size =size.tiny)
plotshape(show_ma_x2 ? smma_bearx : na ,"Cross down", color=x_down_col2, style=shape.triangledown, location = location.top, size =size.tiny)
plotshape(show_ma_x2 ? smma_bullx : na ,"Cross up", color=x_up_col2, style=shape.triangleup, location = location.bottom, size =size.tiny)
//Background
bg_ma_src = switch bg_ma
"Fast MA" => tickMA1
"Slow MA" => tickMA2
"Base MA" => tickMA3
"Smoothed MA" => tickMA4
"TICK" => tickC
"None" => na
bgcolor(in_session and bg_ma_src > 0 ? bg_bull_col : in_session and bg_ma_src < 0 ? bg_bear_col : na)
bgcolor(in_session and showtrend and tickC > BullishH ? uptrend_col : na)
bgcolor(in_session and showtrend and tickC < BearishL ? downtrend_col : na)
bgcolor(in_session and showOBOS and tickC > OverH ? ob_col : na)
bgcolor(in_session and showOBOS and tickC < OverL ? os_col : na)
// ------------------------------------------------ Divergence ------------------------------------
bearColor = color.red
bullColor = color.green
hiddenBullColor = color.new(color.green, 80)
hiddenBearColor = color.new(color.red, 80)
textColor = color.white
noneColor = color.new(color.white, 100)
osc_src_H = tickH
osc_src_L = tickL
if dvg_src == "Close"
osc_src_H := tickC
osc_src_L := tickC
plFound = na(ta.pivotlow(osc_src_L, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(osc_src_H, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL = osc_src_L[lbR] > ta.valuewhen(plFound, osc_src_L[lbR], 1) and _inRange(plFound[1])
// Price: Lower Low
priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bullCond = plotBull and priceLL and oscHL and plFound
plot(plFound ? osc_src_L[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond ? bullColor : noneColor)
plotshape(bullCond ? osc_src_L[lbR] : na, offset=-lbR, title='Regular Bullish Label', text=' Bull ', style=shape.labelup, location=location.absolute, color=color.new(bullColor, 0), textcolor=color.new(textColor, 0))
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL = osc_src_L[lbR] < ta.valuewhen(plFound, osc_src_L[lbR], 1) and _inRange(plFound[1])
// Price: Higher Low
priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound
plot(plFound ? osc_src_L[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond ? osc_src_L[lbR] : na, offset=-lbR, title='Hidden Bullish Label', text=' H Bull ', style=shape.labelup, location=location.absolute, color=color.new(bullColor, 0), textcolor=color.new(textColor, 0))
//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High
oscLH = osc_src_H[lbR] < ta.valuewhen(phFound, osc_src_H[lbR], 1) and _inRange(phFound[1])
// Price: Higher High
priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
bearCond = plotBear and priceHH and oscLH and phFound
plot(phFound ? osc_src_H[lbR] : na, offset=-lbR, title='Regular Bearish', linewidth=2, color=bearCond ? bearColor : noneColor)
plotshape(bearCond ? osc_src_H[lbR] : na, offset=-lbR, title='Regular Bearish Label', text=' Bear ', style=shape.labeldown, location=location.absolute, color=color.new(bearColor, 0), textcolor=color.new(textColor, 0))
//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High
oscHH = osc_src_H[lbR] > ta.valuewhen(phFound, osc_src_H[lbR], 1) and _inRange(phFound[1])
// Price: Lower High
priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)
hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound
plot(phFound ? osc_src_H[lbR] : na, offset=-lbR, title='Hidden Bearish', linewidth=2, color=hiddenBearCond ? hiddenBearColor : noneColor)
plotshape(hiddenBearCond ? osc_src_H[lbR] : na, offset=-lbR, title='Hidden Bearish Label', text=' H Bear ', style=shape.labeldown, location=location.absolute, color=color.new(bearColor, 0), textcolor=color.new(textColor, 0))
// Alerts ---------------------------------------------------------------------------------
alertcondition(dma_bullx, "Dual MA Bullish Crossover", 'Dual MA Bullish Crossover')
alertcondition(dma_bearx, "Dual MA Bearish Crossover", 'Dual MA Bearish Crossover')
alertcondition(smma_bullx, "Smoothed MA Bullish Crossover", 'Smoothed MA Bullish Crossover')
alertcondition(smma_bullx, "Smoothed MA Bearish Crossover", 'Smoothed MA Bearish Crossover')
alertcondition(bullCond, "Bullish Divergence", 'Bullish Divergence')
alertcondition(bearCond, "Bearish Divergence", 'Bearish Divergence')
alertcondition(hiddenBullCond, "Hidden Bullish Divergence", 'Bullish Divergence')
alertcondition(hiddenBearCond, "Hidden Bearish Divergence", 'Bearish Divergence')
|
Fibonacci compression | https://www.tradingview.com/script/xD24tH8E-Fibonacci-compression/ | Greg_007 | https://www.tradingview.com/u/Greg_007/ | 563 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Greg_007
//@version=5
indicator(title="Fibonacci compression" , shorttitle="Fib compression", overlay=true)
var length = input.int(300, title="How many bars to look back?")
min_length = 50
bool searchBull = input.bool(true, title="Search for bullish structures, uncheck for bearish")
int version = input.int(1,"Version", options=[1,2])
float RRR = input.float(3.0, "Risk to reward based on statistics to hit TP1 (only in version 2)")
float fib1 = input.float(defval=0.786, title="Minumum fib level for 2nd leg", options=[0.786,0.618])
float fib2 = input.float(0.618, title="Minumum fib level for 3rd leg")
float fib3 = input.float(0.618, title="Minumum fib level for 4th leg")
float fib4 = input.float(defval=0.5, title="Minumum fib level for 5th leg", options=[0.5,0.382,0.236])
color lblTxtCol = input.color(defval = color.yellow, title = "Text color labels")
float high1 = 0.0
float high2 = 0.0
float high3 = 0.0
float low1 = 0.0
float low2 = 0.0
float low3 = 0.0
arr_all_highs = array.new_float(length, 0) //will contain the highs
arr_all_lows = array.new_float(length, 0) //will contain the lows
arr_cumul_vol = array.new_float(length, 0) //will contain the cumulative volume
//temporary arrays
b = array.new_float()
c = array.new_float()
d = array.new_float()
e = array.new_float()
f = array.new_float()
int positionH1 = 0
int positionH2 = 0
int positionH3 = 0
int positionL1 = 0
int positionL2 = 0
int positionL3 = 0
var cumVol = 0.0
float cumVolH1 = 0.0
float cumVolH2 = 0.0
float cumVolH3 = 0.0
float cumVolL1 = 0.0
float cumVolL2 = 0.0
float cumVolL3 = 0.0
label l_nothingFound = na
label l_H1 = na
label l_H2 = na
label l_H3 = na
label l_L1 = na
label l_L2 = na
label l_L3 = na
label l_info = na
label l_optiEntry = na
label SLLabel = na
label.delete(l_H1)
label.delete(l_H2)
label.delete(l_H3)
label.delete(l_L1)
label.delete(l_L2)
label.delete(l_L3)
label.delete(l_info)
label.delete(l_optiEntry)
label.delete(SLLabel)
line stoploss = na
line.delete(stoploss)
//FUNCTIONS
drawPivotLines(H, posH, L, posL) =>
pivotLine = line.new(bar_index - length + posH + 1, H, bar_index - length + posL + 1, L, color = color.purple)
line.delete(pivotLine[1])
calcDrawTPlevels(A, B, C) =>
TP1 = math.round_to_mintick(A + ((B - C) * 0.236))
TP2 = math.round_to_mintick(A + ((B - C) * 0.618))
TP3 = math.round_to_mintick(A + ((B - C) * 1))
TP1_line = line.new(bar_index,TP1, bar_index + 100, TP1, color=#00aeff, width=2, style=line.style_dashed)
TP2_line = line.new(bar_index,TP2, bar_index + 100, TP2, color=#043308, width=2, style=line.style_dashed)
TP3_line = line.new(bar_index,TP3, bar_index + 100, TP3, color=#043308, width=2, style=line.style_dashed)
line.delete(TP1_line[1])
line.delete(TP2_line[1])
line.delete(TP3_line[1])
TP1Label = label.new(bar_index + 101 , TP1, text = "TP1 - "+ str.tostring(TP1), color=#00aeff, style=label.style_label_left, textcolor=lblTxtCol)
label.delete(TP1Label[1])
TP2Label = label.new(bar_index + 101 , TP2, text = "TP2 - "+ str.tostring(TP2), color=#043308, style=label.style_label_left, textcolor=lblTxtCol)
label.delete(TP2Label[1])
TP3Label = label.new(bar_index + 101 , TP3, text = "TP3 - "+ str.tostring(TP3), color=#043308, style=label.style_label_left, textcolor=lblTxtCol)
label.delete(TP3Label[1])
[TP1, TP2, TP3]
// END FUNCTIONS
l_nothingFound := label.new(bar_index + 10 ,high,"No matching setup found", style = label.style_label_left, textcolor = lblTxtCol)
label.delete(l_nothingFound[1])
if barstate.islast
i = length - 1
while i > -1
array.set(arr_all_highs, length - 1 - i, high[i])
array.set(arr_all_lows,length - 1 - i, low[i])
array.set(arr_cumul_vol,length - 1 - i, cumVol[i])
i -= 1
if searchBull
//Search High 1
high1 := array.max(arr_all_highs)
positionH1 := array.indexof(arr_all_highs, high1)
cumVolH1 := array.get(arr_cumul_vol, positionH1)
if positionH1 < length - min_length //Don't search if the high is too close to the current candle
//Search Low 1
b := array.slice(arr_all_lows, positionH1 + 1, array.size(arr_all_lows))
len = array.size(b)
low1 := array.min(b)
positionL1 := length - array.size(b) + array.indexof(b, low1)
cumVolL1 := array.get(arr_cumul_vol, positionL1)
//Search High 2
if positionL1 + 1 == length //avoid slicing index error when we already reached the current candle
c := array.slice(arr_all_highs, positionL1, array.size(arr_all_highs))
else
c := array.slice(arr_all_highs, positionL1 + 1, array.size(arr_all_highs))
high2 := array.max(c)
positionH2 := length - array.size(c) + array.indexof(c, high2)
cumVolH2 := array.get(arr_cumul_vol, positionH2)
if high2 >= low1 + ((high1 - low1) * fib1)
l_H1 := label.new(bar_index - length + positionH1 + 1,high1,"High", style = label.style_label_down, textcolor = lblTxtCol)
l_L1 := label.new(bar_index - length + positionL1 + 1,low1,"Low", style = label.style_label_up, textcolor = lblTxtCol)
l_H2 := label.new(bar_index - length + positionH2 + 1,high2,"Lower high", style = label.style_label_down, textcolor = lblTxtCol)
label.delete(l_nothingFound)
label.delete(l_H1[1])
label.delete(l_L1[1])
label.delete(l_H2[1])
drawPivotLines(high1, positionH1, low1, positionL1)
drawPivotLines(high2, positionH2, low1, positionL1)
//Search Low 2
if positionH2 + 1 == length
d := array.slice(arr_all_lows, positionH2, array.size(arr_all_lows))
else
d := array.slice(arr_all_lows, positionH2 + 1, array.size(arr_all_lows))
low2 := array.min(d)
positionL2 := length - array.size(d) + array.indexof(d, low2)
cumVolL2 := array.get(arr_cumul_vol, positionL2)
if low2 <= high2 - ((high2 - low1) * fib2)
l_L2 := label.new(bar_index - length + positionL2 + 1,low2,"Higher low", style = label.style_label_up, textcolor = lblTxtCol)
label.delete(l_L2[1])
drawPivotLines(high2, positionH2, low2, positionL2)
[TP1, TP2, TP3] = calcDrawTPlevels(high2, high1, low1)
if version == 2
optiEntry = math.round_to_mintick(low1+((TP1 - low1)/(RRR+1)))
optimalEntry = line.new(bar_index,optiEntry, bar_index + 100, optiEntry, color=#0ff807, width=2)
l_optiEntry := label.new(bar_index + 101,optiEntry,"Optimal entry " + str.tostring(optiEntry), color=#043308, style=label.style_label_left, textcolor = lblTxtCol)
label.delete(l_optiEntry[1])
stoploss := line.new(bar_index - length + positionL1 + 1,low1, bar_index + 100, low1, color=#ff0000, width=2)
line.delete(stoploss[1])
SLLabel := label.new(bar_index + 101 , low1, text = "Stop/Loss "+ str.tostring(low1), color=#ff0000, style=label.style_label_left, textcolor = lblTxtCol)
label.delete(SLLabel[1])
lineEntrytoTP1 = line.new(bar_index + 25,optiEntry, bar_index + 25,TP1, color = color.green, style=line.style_arrow_right)
line.delete(lineEntrytoTP1[1])
lineEntrytoSL = line.new(bar_index + 25,optiEntry, bar_index + 25,low1, color = color.red, style=line.style_arrow_right)
line.delete(lineEntrytoSL[1])
//Search High 3
if positionL2 + 1 == length //avoid slicing index error when we already reached the current candle
e := array.slice(arr_all_highs, positionL2, array.size(arr_all_highs))
else
e := array.slice(arr_all_highs, positionL2 + 1, array.size(arr_all_highs))
high3 := array.max(e)
positionH3 := length - array.size(e) + array.indexof(e, high3)
cumVolH3 := array.get(arr_cumul_vol, positionH3)
if high3 >= low2 + ((high2 - low2) * fib3)
l_H3 := label.new(bar_index - length + positionH3 + 1,high3,"2nd lower high", style = label.style_label_down, textcolor = lblTxtCol)
label.delete(l_H3[1])
drawPivotLines(high3, positionH3, low2, positionL2)
//Search Low 3
if positionH3 + 1 == length //avoid slicing index error when we already reached the current candle
f := array.slice(arr_all_lows, positionH3, array.size(arr_all_lows))
else
f := array.slice(arr_all_lows, positionH3 + 1, array.size(arr_all_lows))
low3 := array.min(f)
positionL3 := length - array.size(f) + array.indexof(f, low3)
cumVolL3 := array.get(arr_cumul_vol, positionL3)
if low3 <= high3 - ((high3 - low2) * fib4)
alert("Fib compression - 2nd Higher Low formed", alert.freq_once_per_bar)
l_L3 := label.new(bar_index - length + positionL3 + 1,low3,"2nd higher low", style = label.style_label_up, textcolor = lblTxtCol)
label.delete(l_L3[1])
drawPivotLines(high3, positionH3, low3, positionL3)
if version == 1
stoploss := line.new(bar_index - length + positionL3 + 1,low3, bar_index + 100, low3, color=#ff0000, width=2)
line.delete(stoploss[1])
SLLabel := label.new(bar_index + 101 , low3, text = "Stop/Loss "+ str.tostring(low3), color=#ff0000, style=label.style_label_left, textcolor = lblTxtCol)
label.delete(SLLabel[1])
lineL3to0618 = line.new(bar_index - length + positionL3 + 1,low3, bar_index + 50,TP2, color = color.green, style=line.style_arrow_right)
line.delete(lineL3to0618[1])
else
//Search Low 1
low1 := array.min(arr_all_lows)
positionL1 := array.indexof(arr_all_lows, low1)
cumVolL1 := array.get(arr_cumul_vol, positionL1)
if positionL1 < length - min_length //Don't search if the low is too close to the current candle
//Search High 1
b := array.slice(arr_all_highs, positionL1 + 1, array.size(arr_all_highs))
high1 := array.max(b)
positionH1 := length - array.size(b) + array.indexof(b, high1)
cumVolH1 := array.get(arr_cumul_vol, positionH1)
//Search Low 2
if positionH1 + 1 == length //avoid slicing index error when we already reached the current candle
c := array.slice(arr_all_lows, positionH1, array.size(arr_all_lows))
else
c := array.slice(arr_all_lows, positionH1 + 1, array.size(arr_all_lows))
low2 := array.min(c)
positionL2 := length - array.size(c) + array.indexof(c, low2)
cumVolL2 := array.get(arr_cumul_vol, positionL2)
if low2 <= high1 + ((low1 - high1) * fib1)
l_L1 := label.new(bar_index - length + positionL1 + 1,low1,"Low", style = label.style_label_up, textcolor=color.yellow)
l_H1 := label.new(bar_index - length + positionH1 + 1,high1,"High", style = label.style_label_down, textcolor=color.yellow)
l_L2 := label.new(bar_index - length + positionL2 + 1,low2,"Higher low", style = label.style_label_up, textcolor=color.yellow)
label.delete(l_nothingFound)
label.delete(l_L1[1])
label.delete(l_H1[1])
label.delete(l_L2[1])
drawPivotLines(high1, positionH1, low1, positionL1)
drawPivotLines(high1, positionH1, low2, positionL2)
//Search High 2
if positionL2 + 1 == length //avoid slicing index error when we already reached the current candle
d := array.slice(arr_all_highs, positionL2, array.size(arr_all_highs))
else
d := array.slice(arr_all_highs, positionL2 + 1, array.size(arr_all_highs))
high2 := array.max(d)
positionH2 := length - array.size(d) + array.indexof(d, high2)
cumVolH2 := array.get(arr_cumul_vol, positionH2)
if high2 >= low2 - ((low2 - high1) * fib2)
l_H2 := label.new(bar_index - length + positionH2 + 1,high2,"Lower high", style = label.style_label_down, textcolor=color.yellow)
label.delete(l_H2[1])
drawPivotLines(high2, positionH2, low2, positionL2)
[TP1, TP2, TP3] = calcDrawTPlevels(low2, low1, high1)
if version == 2
optiEntry = math.round_to_mintick(high1-((high1 - TP1)/(RRR+1)))
optimalEntry = line.new(bar_index,optiEntry, bar_index + 100, optiEntry, color=#0ff807, width=2)
l_optiEntry := label.new(bar_index + 101,optiEntry,"Optimal entry " + str.tostring(optiEntry), color=#043308, style=label.style_label_left, textcolor = lblTxtCol)
label.delete(l_optiEntry[1])
stoploss := line.new(bar_index - length + positionH1 + 1,high1, bar_index + 100, high1, color=#ff0000, width=2)
line.delete(stoploss[1])
SLLabel := label.new(bar_index + 101 , high1, text = "Stop/Loss "+ str.tostring(high1), color=#ff0000, style=label.style_label_left, textcolor = lblTxtCol)
label.delete(SLLabel[1])
lineEntrytoTP1 = line.new(bar_index + 25,optiEntry, bar_index + 25,TP1, color = color.green, style=line.style_arrow_right)
line.delete(lineEntrytoTP1[1])
lineEntrytoSL = line.new(bar_index + 25,optiEntry, bar_index + 25,high1, color = color.red, style=line.style_arrow_right)
line.delete(lineEntrytoSL[1])
//Search Low 3
if positionH2 + 1 == length //avoid slicing index error when we already reached the current candle
e := array.slice(arr_all_lows, positionH2, array.size(arr_all_lows))
else
e := array.slice(arr_all_lows, positionH2 + 1, array.size(arr_all_lows))
low3 := array.min(e)
positionL3 := length - array.size(e) + array.indexof(e, low3)
cumVolL3 := array.get(arr_cumul_vol, positionL3)
if low3 <= high2 + ((low2 - high2) * fib3)
l_L3 := label.new(bar_index - length + positionL3 + 1,low3,"2nd higher low", style = label.style_label_up, textcolor=color.yellow)
label.delete(l_L3[1])
drawPivotLines(high2, positionH2, low3, positionL3)
//Search High 3
if positionL3 + 1 == length //avoid slicing index error when we already reached the current candle
f := array.slice(arr_all_highs, positionL3, array.size(arr_all_highs))
else
f := array.slice(arr_all_highs, positionL3 + 1, array.size(arr_all_highs))
high3 := array.max(f)
positionH3 := length - array.size(f) + array.indexof(f, high3)
cumVolH3 := array.get(arr_cumul_vol, positionH3)
if high3 >= low3 - ((low3 - high2) * fib4)
alert("Fib compression - 2nd Lower High formed", alert.freq_once_per_bar)
l_H3 := label.new(bar_index - length + positionH3 + 1,high3,"2nd lower high", style = label.style_label_down, textcolor=color.yellow)
label.delete(l_L3[1])
drawPivotLines(high3, positionH3, low3, positionL3)
if version == 1
stoploss := line.new(bar_index - length + positionH3 + 1,high3, bar_index + 100, high3, color=#ff0000, width=2)
line.delete(stoploss[1])
SLLabel := label.new(bar_index + 101 , high3, text = "Stop/Loss "+ str.tostring(high3), color=#ff0000, style=label.style_label_left, textcolor = lblTxtCol)
label.delete(SLLabel[1])
lineH3to0618 = line.new(bar_index - length + positionH3 + 1,high3, bar_index + 50,TP2, color = color.green, style=line.style_arrow_right)
line.delete(lineH3to0618[1]) |
DR/IDR Case Study [TFO] | https://www.tradingview.com/script/jU17SmIf-DR-IDR-Case-Study-TFO/ | tradeforopp | https://www.tradingview.com/u/tradeforopp/ | 1,072 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tradeforopp
//@version=5
indicator("DR/IDR Case Study [TFO]", "DR/IDR Case Study [TFO]", true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
var g1 = "DR Session"
dr_timeframe = input.timeframe("5", "Timeframe", tooltip = "This timeframe will be used to define the DR and IDR, even on different chart timeframes", group = g1)
session = input.session("0930-1030", "Defining Range", tooltip = "New York local time", group = g1)
session_ext = input.session("1030-1600", "Session", tooltip = "New York local time", group = g1)
dr_criteria = input.string(defval = 'Wick', title = "Success Criteria", options = ['Wick', 'Close'], tooltip = "Close will check if price invalidated the DR session by closing through the opposing side of the range. Wick will use any break of the opposing side, not just a close", group = g1)
var g2 = "Style"
dr_style = input.string(defval = 'Solid', title = "DR Style", options = ['Solid', 'Dotted', 'Dashed'], inline = "DR", group = g2)
dr_color = input.color(color.gray, "", inline = "DR", group = g2)
idr_style = input.string(defval = 'Dashed', title = "IDR Style", options = ['Solid', 'Dotted', 'Dashed'], inline = "IDR", group = g2)
idr_color = input.color(color.green, "", inline = "IDR", group = g2)
table_position = input.string('Top Right', "Table Position", options = ['Bottom Center', 'Bottom Left', 'Bottom Right', 'Middle Center', 'Middle Left', 'Middle Right', 'Top Center', 'Top Left', 'Top Right'], group = g2)
// Variables
var dr_not_broken = true
var line drh = na
var line drl = na
var line idrh = na
var line idrl = na
var box dr_box = na
var float lod = na
var float hod = na
var float clod = na
var float chod = na
var int track_ruling = 0
var int track_total = 0
dr_time = not na(time(dr_timeframe, session, "America/New_York"))
dr_extension = not na(time(dr_timeframe, session_ext, "America/New_York"))
dr_style := switch dr_style
'Solid' => line.style_solid
'Dotted' => line.style_dotted
'Dashed' => line.style_dashed
idr_style := switch idr_style
'Solid' => line.style_solid
'Dotted' => line.style_dotted
'Dashed' => line.style_dashed
table_position := switch table_position
"Bottom Center" => position.bottom_center
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
"Middle Center" => position.middle_center
"Middle Left" => position.middle_left
"Middle Right" => position.middle_right
"Top Center" => position.top_center
"Top Left" => position.top_left
"Top Right" => position.top_right
[dr_tf_open, dr_tf_high, dr_tf_low, dr_tf_close] = request.security(syminfo.tickerid, dr_timeframe, [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
// Initiate new DR
if dr_time and not dr_time[1]
dr_not_broken := true
lod := dr_tf_low
hod := dr_tf_high
clod := dr_tf_close
chod := dr_tf_close
drh := line.new(bar_index, dr_tf_high, bar_index + 1, dr_tf_high, color = dr_color, style = dr_style)
drl := line.new(bar_index, dr_tf_low, bar_index + 1, dr_tf_low, color = dr_color, style = dr_style)
idrh := line.new(bar_index, dr_tf_close, bar_index + 1, dr_tf_close, color = idr_color, style = idr_style)
idrl := line.new(bar_index, dr_tf_close, bar_index + 1, dr_tf_close, color = idr_color, style = idr_style)
dr_box := box.new(bar_index, math.max(dr_tf_close, dr_tf_open), bar_index + 1, math.min(dr_tf_close, dr_tf_open), border_color = na, bgcolor = color.new(color.gray, 70))
// Manage current DR
if not na(drh)
if dr_time or dr_extension
line.set_x2(drh, bar_index)
line.set_x2(drl, bar_index)
line.set_x2(idrh, bar_index)
line.set_x2(idrl, bar_index)
if dr_tf_low < lod
lod := dr_tf_low
if dr_tf_high > hod
hod := dr_tf_high
if dr_tf_close < clod
clod := dr_tf_close
if dr_tf_close > chod
chod := dr_tf_close
if dr_time
box.set_right(dr_box, bar_index)
if dr_tf_high > line.get_y1(drh)
line.set_y1(drh, dr_tf_high)
line.set_y2(drh, dr_tf_high)
if dr_tf_low < line.get_y1(drl)
line.set_y1(drl, dr_tf_low)
line.set_y2(drl, dr_tf_low)
body_high = math.max(dr_tf_close, dr_tf_open)
if body_high > line.get_y1(idrh)
line.set_y1(idrh, body_high)
line.set_y2(idrh, body_high)
box.set_top(dr_box, body_high)
body_low = math.min(dr_tf_close, dr_tf_open)
if body_low < line.get_y1(idrl)
line.set_y1(idrl, body_low)
line.set_y2(idrl, body_low)
box.set_bottom(dr_box, body_low)
// Check if DR was broken (5m close through DRH/DRL)
break_high = false
break_low = false
if dr_extension and dr_not_broken
if dr_tf_close > line.get_y1(drh)
break_high := true
dr_not_broken := false
if dr_tf_close < line.get_y1(drl)
break_low := true
dr_not_broken := false
if break_high
label.new(bar_index, dr_tf_high, "Close Through DRH", style = label.style_label_down, color = color.blue, textcolor = color.white)
if break_low
label.new(bar_index, dr_tf_low, "Close Through DRL", style = label.style_label_up, color = color.blue, textcolor = color.white)
// Check if DR rule succeeded
// ------------------------------
// Note that part of the claimed 88% success rate is due to the fact that it's NOT accounting for days with high impact news drivers
// I am NOT accounting for high impact news days in this indicator
// ------------------------------
high_more_recent = ta.barssince(break_high) < ta.barssince(break_low)
if not dr_not_broken[1] and dr_extension[1] and not dr_extension
if high_more_recent
ruling_criteria = dr_criteria == 'Wick' ? lod[1] : clod[1]
ruling = line.get_y1(drl[1]) <= ruling_criteria
label_string = ruling ? "Held" : "Not Held"
label.new(bar_index - 1, dr_tf_low[1], "DRL " + label_string, style = label.style_label_up, color = ruling ? color.green : color.red, textcolor = color.white)
track_total := track_total + 1
if ruling
track_ruling := track_ruling + 1
else
ruling_criteria = dr_criteria == 'Wick' ? hod[1] : chod[1]
ruling = line.get_y1(drh[1]) >= ruling_criteria
label_string = ruling ? "Held" : "Not Held"
label.new(bar_index - 1, dr_tf_high[1], "DRH " + label_string, style = label.style_label_down, color = ruling ? color.green : color.red, textcolor = color.white)
track_total := track_total + 1
if ruling
track_ruling := track_ruling + 1
var table stats = table.new(table_position, 10, 10)
if barstate.islast
table.cell(stats, 0, 0, "DR Success Rate: ", bgcolor = color.new(color.white, 20))
table.cell(stats, 1, 0, str.tostring(track_ruling / track_total * 100, format.percent), bgcolor = color.new(color.white, 20))
table.cell(stats, 0, 1, "Total Sessions: ", bgcolor = color.new(color.white, 30))
table.cell(stats, 1, 1, str.tostring(track_total), bgcolor = color.new(color.white, 30)) |
Dynamic Fibonacci Retracement | https://www.tradingview.com/script/ArZEl1sg-Dynamic-Fibonacci-Retracement/ | HoanGhetti | https://www.tradingview.com/u/HoanGhetti/ | 870 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HoanGhetti
//@version=5
indicator("Dynamic Fibonacci Retracement [HG]", overlay = true)
input_lookback = input.int(defval = 50, title = 'Lookback Range', minval = 5)
input_extend = input.string(defval = 'None', title = 'Extend', options = ['None', 'Right', 'Left', 'Both'])
input_width = input.int(defval = 1, title = 'Width', minval = 0)
input_labels = input.bool(defval = true, title = 'Labels', inline = 'Labels')
input_offset = input.int(defval = 5, title = '| Offset Right', inline = 'Labels')
input_prices = input.bool(defval = false, title = 'Prices', tooltip = 'Prints the price of the level next to the retracement level.')
input_bullColor = input.color(defval = color.green, title = 'Bull', inline = 'color')
input_bearColor = input.color(defval = color.red, title = 'Bear', inline = 'color')
input_trendline = input.bool(defval = true, title = 'Use Trendline', group = 'Levels')
input_use236 = input.bool(defval = true, title = '', inline = '0', group = 'Levels')
input_236 = input.float(defval = 0.236, title = '', inline = '0', group = 'Levels', step = 0.01)
input_use382 = input.bool(defval = true, title = '', inline = '382', group = 'Levels')
input_382 = input.float(defval = 0.382, title = '', inline = '382', group = 'Levels', step = 0.01)
input_use5 = input.bool(defval = true, title = '', inline = '382', group = 'Levels')
input_5 = input.float(defval = 0.5, title = '', inline = '382', group = 'Levels', step = 0.01)
input_use618 = input.bool(defval = true, title = '', inline = '618', group = 'Levels')
input_618 = input.float(defval = 0.618, title = '', inline = '618', group = 'Levels', step = 0.01)
input_use786 = input.bool(defval = true, title = '', inline = '618', group = 'Levels')
input_786 = input.float(defval = 0.786, title = '', inline = '618', group = 'Levels', step = 0.01)
exType = switch input_extend
'None' => extend.none
'Right' => extend.right
'Left' => extend.left
'Both' => extend.both
pl = fixnan(ta.pivotlow(input_lookback, input_lookback))
ph = fixnan(ta.pivothigh(input_lookback, input_lookback))
plC = ta.barssince(ta.change(pl))
phC = ta.barssince(ta.change(ph))
var string dir = na
since = phC < plC ? plC + input_lookback : phC + input_lookback
if ta.change(ph) or ta.crossunder(low, pl)
dir := 'bear'
if ta.change(pl) or ta.crossover(high, ph)
dir := 'bull'
col = dir == 'bull' ? input_bullColor : input_bearColor
getOuter(pivot, src) =>
var srcValue = src
if ta.change(pivot)
srcValue := pivot
if pivot == ph ? src > srcValue : src < srcValue
srcValue := src
[srcValue]
[h] = getOuter(ph, high)
[l] = getOuter(pl, low)
calcFib(float lo, float hi, float perc) => dir == 'bull' ? lo - (lo - hi) * perc : hi - (hi - lo) * perc
levelsArr = array.from(0, input_use236 ? input_236 : na, input_use382 ? input_382 : na, input_use5 ? input_5 : na, input_use618 ? input_618 : na, input_use786 ? input_786 : na, 1)
var trendline = line.new(na, na, na, na, style = line.style_dashed, width = input_width)
var innerLines = array.new<line>()
for i = 0 to 6
if innerLines.size() < 7
innerLines.push(line.new(na, na, na, na, width = input_width))
innerLines.get(i).set_xy1(bar_index - since, calcFib(l, h, levelsArr.get(i)))
innerLines.get(i).set_xy2(bar_index, calcFib(l, h, levelsArr.get(i)))
innerLines.get(i).set_color(col)
innerLines.get(i).set_extend(exType)
if input_labels
var labelArray = array.new<label>()
if labelArray.size() < 7
labelArray.push(label.new(na, na, na, style = label.style_none))
labelArray.get(i).set_xy(bar_index + input_offset, calcFib(l, h, levelsArr.get(i)))
labelArray.get(i).set_text(str.tostring(levelsArr.get(i)) + (input_prices ? ' (' + str.tostring(calcFib(l, h, levelsArr.get(i)), format.mintick) + ')' : na))
labelArray.get(i).set_textcolor(col)
if input_trendline
if dir == 'bull'
trendline.set_xy1(bar_index - since, l)
trendline.set_xy2(bar_index, h)
else
trendline.set_xy1(bar_index - since, h)
trendline.set_xy2(bar_index, l)
trendline.set_color(col) |
Cumulative Volume Delta [Aggregated] | https://www.tradingview.com/script/IiIxguuf-Cumulative-Volume-Delta-Aggregated/ | jeesauce | https://www.tradingview.com/u/jeesauce/ | 481 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jeesauce
//@version=5
Title = "Cumulative Volume Delta [Aggregated]"
ShortcutName = "Aggr CVD"
indicator(Title, ShortcutName, false, format.volume)
import jeesauce/JeeSauceScripts/2 as scripts
//Color
bearcol = #990707
bullcol = #969a9d
//Inputs
datatype = input.string("Aggregated Data", title = "Data Type", options = ["Single Data", "Aggregated Data"], tooltip = "Choose between Single or AGG data for CVD. NOTE: AGGR only works for BTC")
plottype = input.string("Candle", title = "Plot Type", options = ["Line", "Candle", "RSI"], tooltip = "Choose between Plotting CVD as Line or Candle type")
currentsym = syminfo.tickerid
symswitch1 = input.bool(true, title = "", inline = "1", group = "Aggregated Data"), futsym1 = input.symbol(defval = 'BINANCE:BTCUSDTPERP', title = "", inline = "1", group = "Aggregated Data")
symswitch2 = input.bool(true, title = "", inline = "2", group = "Aggregated Data"), futsym2 = input.symbol(defval = 'BINANCE:BTCBUSDPERP', title = "", inline = "2", group = "Aggregated Data")
symswitch3 = input.bool(true, title = "", inline = "3", group = "Aggregated Data"), futsym3 = input.symbol(defval = 'BYBIT:BTCUSDT.P', title = "", inline = "3", group = "Aggregated Data")
symswitch4 = input.bool(true, title = "", inline = "4", group = "Aggregated Data"), futsym4 = input.symbol(defval = 'OKX:BTCUSDT.P', title = "", inline = "4", group = "Aggregated Data")
symswitch5 = input.bool(true, title = "", inline = "5", group = "Aggregated Data"), futsym5 = input.symbol(defval = 'DELTA:BTCUSDT.P', title = "", inline = "5", group = "Aggregated Data")
symswitch6 = input.bool(true, title = "", inline = "6", group = "Aggregated Data"), futsym6 = input.symbol(defval = 'WOONETWORK:BTCUSDT.P', title = "", inline = "6", group = "Aggregated Data")
//Aggregated Data
[upvolume , downvolume] = request.security_lower_tf(currentsym, "1" , scripts.getupdnvol())
[upvolume1, downvolume1] = request.security_lower_tf(futsym1 , "1" , scripts.getupdnvol())
[upvolume2, downvolume2] = request.security_lower_tf(futsym2 , "1" , scripts.getupdnvol())
[upvolume3, downvolume3] = request.security_lower_tf(futsym3 , "1" , scripts.getupdnvol())
[upvolume4, downvolume4] = request.security_lower_tf(futsym4 , "1" , scripts.getupdnvol())
[upvolume5, downvolume5] = request.security_lower_tf(futsym5 , "1" , scripts.getupdnvol())
[upvolume6, downvolume6] = request.security_lower_tf(futsym6 , "1" , scripts.getupdnvol())
//Current Vol
float totalUpVolume = 0.0, float totalDnVolume = 0.0, float delta = 0.0, float maxUpVolume = 0.0, float maxDnVolume = 0.0
totalUpVolume := scripts.GetTotalUpVolume(upvolume), totalDnVolume := scripts.GetTotalDnVolume(downvolume)
maxUpVolume := scripts.GetMaxUpVolume(upvolume), maxDnVolume := scripts.GetMaxDnVolume(downvolume)
delta := scripts.GetDelta(totalUpVolume, totalDnVolume)
var float cvd = scripts.Getcvd()
float cvdopen = scripts.Getcvdopen(cvd)
float cvdhigh = scripts.Getcvdhigh(cvd, maxUpVolume)
float cvdlow = scripts.Getcvdlow(cvd, maxDnVolume)
float cvdclose = scripts.Getcvdclose(cvd, delta)
//////////////////////////////////Aggregated Volume//////////////////////////////////////////////
float totalpositivevolume1 = 0.0, float totalpositivevolume2 = 0.0, float totalpositivevolume3 = 0.0, float totalpositivevolume4 = 0.0, float totalpositivevolume5 = 0.0, float totalpositivevolume6 = 0.0
float totalnegativevolume1 = 0.0, float totalnegativevolume2 = 0.0, float totalnegativevolume3 = 0.0, float totalnegativevolume4 = 0.0, float totalnegativevolume5 = 0.0, float totalnegativevolume6 = 0.0
float maxpositivevolume1 = 0.0, float maxpositivevolume2 = 0.0, float maxpositivevolume3 = 0.0, float maxpositivevolume4 = 0.0, float maxpositivevolume5 = 0.0, float maxpositivevolume6 = 0.0
float maxnegativevolume1 = 0.0, float maxnegativevolume2 = 0.0, float maxnegativevolume3 = 0.0, float maxnegativevolume4 = 0.0, float maxnegativevolume5 = 0.0, float maxnegativevolume6 = 0.0
float delta1 = 0.0, float delta2 = 0.0, float delta3 = 0.0, float delta4 = 0.0, float delta5 = 0.0, float delta6 = 0.0
if symswitch1
totalpositivevolume1 := scripts.GetTotalUpVolume(upvolume1), totalnegativevolume1 := scripts.GetTotalDnVolume(downvolume1)
maxpositivevolume1 := scripts.GetMaxUpVolume(upvolume1), maxnegativevolume1 := scripts.GetMaxDnVolume(downvolume1)
delta1 := scripts.GetDelta(totalpositivevolume1, totalnegativevolume1)
if symswitch2
totalpositivevolume2 := scripts.GetTotalUpVolume(upvolume2), totalnegativevolume2 := scripts.GetTotalDnVolume(downvolume2)
maxpositivevolume2 := scripts.GetMaxUpVolume(upvolume2), maxnegativevolume2 := scripts.GetMaxDnVolume(downvolume2)
delta2 := scripts.GetDelta(totalpositivevolume2, totalnegativevolume2)
if symswitch3
totalpositivevolume3 := scripts.GetTotalUpVolume(upvolume3), totalnegativevolume3 := scripts.GetTotalDnVolume(downvolume3)
maxpositivevolume3 := scripts.GetMaxUpVolume(upvolume3), maxnegativevolume3 := scripts.GetMaxDnVolume(downvolume3)
delta3 := scripts.GetDelta(totalpositivevolume3, totalnegativevolume3)
if symswitch4
totalpositivevolume4 := scripts.GetTotalUpVolume(upvolume4), totalnegativevolume4 := scripts.GetTotalDnVolume(downvolume4)
maxpositivevolume4 := scripts.GetMaxUpVolume(upvolume4), maxnegativevolume4 := scripts.GetMaxDnVolume(downvolume4)
delta4 := scripts.GetDelta(totalpositivevolume4, totalnegativevolume4)
if symswitch5
totalpositivevolume5 := scripts.GetTotalUpVolume(upvolume5), totalnegativevolume5 := scripts.GetTotalDnVolume(downvolume5)
maxpositivevolume5 := scripts.GetMaxUpVolume(upvolume5), maxnegativevolume5 := scripts.GetMaxDnVolume(downvolume5)
delta5 := scripts.GetDelta(totalpositivevolume5, totalnegativevolume5)
if symswitch6
totalpositivevolume6 := scripts.GetTotalUpVolume(upvolume6), totalnegativevolume6 := scripts.GetTotalDnVolume(downvolume6)
maxpositivevolume6 := scripts.GetMaxUpVolume(upvolume6), maxnegativevolume6 := scripts.GetMaxDnVolume(downvolume6)
delta6 := scripts.GetDelta(totalpositivevolume6, totalnegativevolume6)
//CVD
var float cvd1 = scripts.Getcvd(), var float cvd2 = scripts.Getcvd(), var float cvd3 = scripts.Getcvd()
var float cvd4 = scripts.Getcvd(), var float cvd5 = scripts.Getcvd(), var float cvd6 = scripts.Getcvd()
//OPEN
float cvdopen1 = scripts.Getcvdopen(cvd1), float cvdopen2 = scripts.Getcvdopen(cvd2), float cvdopen3 = scripts.Getcvdopen(cvd3)
float cvdopen4 = scripts.Getcvdopen(cvd4), float cvdopen5 = scripts.Getcvdopen(cvd5), float cvdopen6 = scripts.Getcvdopen(cvd6)
//HIGH
float cvdhigh1 = scripts.Getcvdhigh(cvd1, maxpositivevolume1), float cvdhigh2 = scripts.Getcvdhigh(cvd2, maxpositivevolume2)
float cvdhigh3 = scripts.Getcvdhigh(cvd3, maxpositivevolume3), float cvdhigh4 = scripts.Getcvdhigh(cvd4, maxpositivevolume4)
float cvdhigh5 = scripts.Getcvdhigh(cvd5, maxpositivevolume5), float cvdhigh6 = scripts.Getcvdhigh(cvd6, maxpositivevolume6)
//LOW
float cvdlow1 = scripts.Getcvdlow(cvd1, maxnegativevolume1), float cvdlow2 = scripts.Getcvdlow(cvd2, maxnegativevolume2)
float cvdlow3 = scripts.Getcvdlow(cvd3, maxnegativevolume3), float cvdlow4 = scripts.Getcvdlow(cvd4, maxnegativevolume4)
float cvdlow5 = scripts.Getcvdlow(cvd5, maxnegativevolume5), float cvdlow6 = scripts.Getcvdlow(cvd6, maxnegativevolume6)
//CLOSE
float cvdclose1 = scripts.Getcvdclose(cvd1, delta1), float cvdclose2 = scripts.Getcvdclose(cvd2, delta2)
float cvdclose3 = scripts.Getcvdclose(cvd3, delta3), float cvdclose4 = scripts.Getcvdclose(cvd4, delta4)
float cvdclose5 = scripts.Getcvdclose(cvd5, delta5), float cvdclose6 = scripts.Getcvdclose(cvd6, delta6)
cvd1 += delta1, cvd2 += delta2, cvd3 += delta3, cvd4 += delta4, cvd5 += delta5, cvd6 += delta6, cvd += delta
aggropen = 0.0, aggrhigh = 0.0, aggrlow = 0.0, aggrclose = 0.0
//Color Switch
enablebodycol = input.bool(true, title = "", inline = "7", group = "Candle Color Settings")
enablebordercol = input.bool(true, title = "", inline = "8", group = "Candle Color Settings")
enablewickcol = input.bool(true, title = "", inline = "9", group = "Candle Color Settings")
//Body Color
bodycolpos = input.color(bullcol, title = "Bodyㅤ", group = "Candle Color Settings", inline = "7", tooltip = "Candle Body Color")
bodycolneg = input.color(bearcol, title = "", group = "Candle Color Settings", inline = "7")
//Border Color
bordercolpos = input.color(bullcol, title = "Borders", group = "Candle Color Settings", inline = "8", tooltip = "Candle Border Color")
bordercolneg = input.color(bearcol, title = "", group = "Candle Color Settings", inline = "8")
//Wick Color
wickcolpos = input.color(bullcol, title = "Wickㅤ", group = "Candle Color Settings", inline = "9", tooltip = "Candle Wick Color")
wickcolneg = input.color(bearcol, title = "", group = "Candle Color Settings", inline = "9")
//Candle Color Change Function
if enablebodycol == false
bodycolpos := na
bodycolneg := na
if enablebordercol == false
bordercolpos := na
bordercolneg := na
if enablewickcol == false
wickcolpos := na
wickcolneg := na
bodycolorchange = close > open ? bodycolpos : bodycolneg
wickcolorchange = close > open ? wickcolpos : wickcolneg
bordercolorchange = close > open ? bordercolpos : wickcolneg
if plottype == "Line"
bodycolorchange := na
wickcolorchange := na
bordercolorchange := na
//Candle Aggregated OHLC Calculation
if plottype == "Candle"
aggropen := scripts.CombineData(cvdopen1, cvdopen2, cvdopen3, cvdopen4, cvdopen5, cvdopen6)
aggrhigh := scripts.CombineData(cvdhigh1, cvdhigh2, cvdhigh3, cvdhigh4, cvdhigh5, cvdhigh6)
aggrlow := scripts.CombineData(cvdlow1, cvdlow2, cvdlow3, cvdlow4, cvdlow5, cvdlow6)
aggrclose := scripts.CombineData(cvdclose1, cvdclose2, cvdclose3, cvdclose4, cvdclose5, cvdclose6)
//AGGR Data Calculation
aggrCVDperp = scripts.CombineData(cvdclose1, cvdclose2, cvdclose3, cvdclose4, cvdclose5, cvdclose6)
//Aggr - Single Function
chooseopen = datatype == "Aggregated Data" ? aggropen : cvdopen
choosehigh = datatype == "Aggregated Data" ? aggrhigh : cvdhigh
chooselow = datatype == "Aggregated Data" ? aggrlow : cvdlow
chooseclose = datatype == "Aggregated Data" ? aggrclose : cvdclose
//Goes back to single type data when not in BTC Pair
chooseopenfinal = scripts.FindData(currentsym, "BTC") ? chooseopen : cvdopen
choosehighfinal = scripts.FindData(currentsym, "BTC") ? choosehigh : cvdhigh
chooselowfinal = scripts.FindData(currentsym, "BTC") ? chooselow : cvdlow
chooseclosefinal = scripts.FindData(currentsym, "BTC") ? chooseclose : cvdclose
chooseaggrfinal = scripts.FindData(currentsym, "BTC") ? aggrCVDperp : cvdclose
//RSI input
rsilength = input(14, "RSI Length", group = "RSI PLOT SETTINGS")
upline = input(70, "Upper Line Threshold", group = "RSI PLOT SETTINGS")
downline = input(30, "Lower Line Threshold", group = "RSI PLOT SETTINGS")
//Plot
hline(plottype == "RSI" ? upline : na, color = color.gray, linestyle = hline.style_dashed)
hline(plottype == "RSI" ? downline : na, color = color.gray, linestyle = hline.style_dashed)
plotcandle(plottype == "Candle" ? chooseopenfinal : na, plottype == "Candle" ? choosehighfinal : na, plottype == "Candle" ? chooselowfinal : na, plottype == "Candle" ? chooseclosefinal : na, "Candle", bodycolorchange, wickcolorchange, bordercolor = bordercolorchange, editable = false)
plot(plottype == "Line" and datatype == "Aggregated Data" ? chooseaggrfinal : plottype == "Line" and datatype == "Single Data" ? cvdclose : na, title = "CVD", color = color.yellow)
plot(ta.rsi(plottype == "RSI" and datatype == "Aggregated Data" ? chooseaggrfinal : plottype == "RSI" and datatype == "Single Data" ? cvdclose : na, rsilength), "RSI Plot", color = color.yellow)
|
Altcoin Dominance Excluding Ethereum | https://www.tradingview.com/script/lD7YitK0-Altcoin-Dominance-Excluding-Ethereum/ | CryptoGrit | https://www.tradingview.com/u/CryptoGrit/ | 16 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Unsymetric
//@version=5
indicator("Alt.D w/o ETH", overlay=true)
timeframeInput = input.timeframe("D", "Timeframe")
sourceInput = input.source(hl2, "Source")
periodInput = input(1, "Period")
btc_cap = request.security(input.symbol("BTC_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
eth_cap = request.security(input.symbol("ETH_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
crypto_cap = request.security(input.symbol("TOTAL", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
usdc_cap = request.security(input.symbol("USDC_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
usdt_cap = request.security(input.symbol("USDT_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
busd_cap = request.security(input.symbol("BUSD_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
dai_cap = request.security(input.symbol("DAI_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
index = (crypto_cap - eth_cap - btc_cap - usdc_cap - usdt_cap - busd_cap - dai_cap) / (crypto_cap) *100
plot(index)
|
Hurst Diamond Notation Pivots | https://www.tradingview.com/script/DaukfrmD-Hurst-Diamond-Notation-Pivots/ | BarefootJoey | https://www.tradingview.com/u/BarefootJoey/ | 1,061 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BarefootJoey
// ██████████████████████████████████████████████████████████████████████
// █▄─▄─▀██▀▄─██▄─▄▄▀█▄─▄▄─█▄─▄▄─█─▄▄─█─▄▄─█─▄─▄─███▄─▄█─▄▄─█▄─▄▄─█▄─█─▄█
// ██─▄─▀██─▀─███─▄─▄██─▄█▀██─▄███─██─█─██─███─███─▄█─██─██─██─▄█▀██▄─▄██
// █▄▄▄▄██▄▄█▄▄█▄▄█▄▄█▄▄▄▄▄█▄▄▄███▄▄▄▄█▄▄▄▄██▄▄▄██▄▄▄███▄▄▄▄█▄▄▄▄▄██▄▄▄██
//@version=5
indicator("Hurst Diamond Notation Pivots", overlay=false)
philo = input.string("Lows", "Highs or Lows?", options=["Highs", "Lows"])
linecolor = input.color(color.new(color.gray,0), "Label/Line Color")
ptransp = input.int(33, "Radar Transparency", minval=0, maxval=100)
ltransp = input.int(100, "Line Transparency", minval=0, maxval=100)
n = bar_index
// Input/2 (Default 5) Length Pivot Cycle
hcol = input.color(color.purple, "Half Cycle Color", inline="hc")
cych = input.int(5, "Length", inline="hc")
labh = input.bool(true, "Label?", inline="hc")
labhf = input.bool(true, "Forecast?", inline="hc")
plh = philo == "Highs" ? ta.pivothigh(cych, cych) : ta.pivotlow(cych, cych) // Define a PL or PH based on L/H Switch in settings
plhy = philo == "Highs" ? -5 : 5 // Position the pivot on the Y axis of the oscillator
plhi = ta.barssince(plh) // Bars since pivot occured?
plhp = plhi>cych // Bars since pivot occured greater than cycle length?
lowhin = philo == "Highs" ? ta.highest(close, cych*2) : ta.lowest(close, cych*2) // Highest/Lowest for the cycle
lowh = ta.barssince(plh)>cych ? lowhin : na // If the barssince pivot are greater than cycle length, show the uncomnfirmed "pivot tracker"
plot(plhy, "Half Cycle Radar Line", color=plhp?hcol:color.new(linecolor,ltransp), offset=(cych*-1), display=display.none) // Cycle detection lines v1
plotshape(plh ? plhy : na, "Half Cycle Confirmed", style=shape.diamond, location=location.absolute, color=hcol, size = size.tiny, offset=(cych*-1)) // Past Pivots
plotshape(lowh ? plhy : na, "Half Cycle Radar", style=shape.circle, location=location.absolute, color=color.new(hcol, ptransp), size = size.tiny, offset=(cych*-1), show_last=1, display=display.none) // AKA the "Tracker/Radar" v1
// LuxAlgo pivot average calculation used for the forecast
barssince_ph = 0
ph_x2 = ta.valuewhen(plh, n - cych, 1) // x values for pivot
if plh
barssince_ph := (n - cych) - ph_x2 // if there is a pivot, then BarsSincePivot = (BarIndex - Cycle Length) - x values for pivot
avg_barssince_ph = ta.cum(barssince_ph) / ta.cum(math.sign(barssince_ph)) // AvgBarsSincePivot = Sum of the BarsSincePivot divided by (Sum of the number of signs of BarsSincePivot, AKA the number of BarsSincePivots)
// Draw a diamond forecast label and forecast range line
tooltiph = "🔄 Pivot Cycle: " + str.tostring(cych) + " bars" +
"\n⏱ Last Pivot: " + str.tostring(plhi + cych) + " bars ago" +
"\n🧮 Average Pivot: " + str.tostring(math.round(avg_barssince_ph)) + " bars" +
"\n🔮 Next Pivot: " + str.tostring(math.round(avg_barssince_ph)-(plhi + cych)) + " bars" +
"\n📏 Range: +/- " + str.tostring(math.round(avg_barssince_ph/2)) + " bars"
var label fh = na
var line lh = na
if labhf
fh := label.new(n + math.min((math.round(avg_barssince_ph) - (plhi+cych)), 500), y=plhy, size=size.tiny, style=label.style_diamond, color=color.new(hcol,ptransp),tooltip =tooltiph)
label.delete(fh[1])
lh := line.new(x1=n + math.min(math.round((avg_barssince_ph - (plhi+cych))-(avg_barssince_ph/2)), 500), x2=n + math.min(math.round((avg_barssince_ph - (plhi+cych))+(avg_barssince_ph/2)), 500), y1=plhy, y2=plhy, color=color.new(hcol,ptransp))
line.delete(lh[1])
var label ch = na // Create a label
if labh // Define the label
ch := label.new(bar_index, y=plhy, text=str.tostring(cych), size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(plhp?hcol:linecolor,0), tooltip=tooltiph)
label.delete(ch[1])
// Input (Default 10) Length Pivot Cycle
col = input.color(color.blue, "Full Cycle Color", inline="fc")
cyc = input.int(10, "Length", inline="fc")
labf = input.bool(true, "Label?", inline="fc")
labff = input.bool(true, "Forecast?", inline="fc")
pl = philo == "Highs" ? ta.pivothigh(cyc, cyc) : ta.pivotlow(cyc, cyc)
ply = philo == "Highs" ? -10 : 10
pli = ta.barssince(pl)
plp = pli>cyc
lowin = philo == "Highs" ? ta.highest(close, cyc*2) : ta.lowest(close, cyc*2)
lowf = ta.barssince(pl)>cyc ? lowin : na
plot(ply, "Full Cycle Radar Line", color=plp?col:color.new(linecolor,ltransp), offset=(cyc*-1), display=display.none)
plotshape(pl ? ply : na, "Full Cycle Confirmed", style=shape.diamond, location=location.absolute, color=col, size = size.tiny, offset=(cyc*-1))
plotshape(lowf ? ply : na, "Full Cycle Radar", style=shape.circle, location=location.absolute, color=color.new(col, ptransp), size = size.tiny, offset=(cyc*-1), show_last=1, display=display.none)
// Forecast & Labels
barssince_p = 0
p_x2 = ta.valuewhen(pl, n - cyc, 1)
p_y2 = ta.valuewhen(pl, pl, 1)
if pl
barssince_p := (n - cyc) - p_x2
avg_barssince_p = ta.cum(barssince_p) / ta.cum(math.sign(barssince_p))
tooltipf = "🔄 Pivot Cycle: " + str.tostring(cyc) + " bars" +
"\n⏱ Last Pivot: " + str.tostring(pli + cyc) + " bars ago" +
"\n🧮 Average Pivot: " + str.tostring(math.round(avg_barssince_p)) + " bars" +
"\n🔮 Next Pivot: " + str.tostring(math.round(avg_barssince_p)-(pli + cyc)) + " bars" +
"\n📏 Range: +/- " + str.tostring(math.round(avg_barssince_p/2)) + " bars"
var label ff = na
var line lf = na
if labff
ff := label.new(n + math.min((math.round(avg_barssince_p) - (pli+cyc)), 500), y=ply, size=size.tiny, style=label.style_diamond, color=color.new(col,ptransp),tooltip =tooltipf)
label.delete(ff[1])
lf := line.new(x1=n + math.min(math.round((avg_barssince_p - (pli+cyc))-(avg_barssince_p/2)), 500), x2=n + math.min(math.round((avg_barssince_p - (pli+cyc))+(avg_barssince_p/2)), 500), y1=ply, y2=ply, color=color.new(col,ptransp))
line.delete(lf[1])
var label cf = na
if labf
cf := label.new(bar_index, y=ply, text=str.tostring(cyc), size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(plp?col:linecolor,0), tooltip=tooltipf)
label.delete(cf[1])
// Input x2 (Default 20) Length Pivot Cycle
col2 = input.color(color.aqua, "2x Cycle Color ", inline="2c")
cyc2 = input.int(20, "Length", inline="2c")
lab2 = input.bool(true, "Label?", inline="2c")
lab2f = input.bool(true, "Forecast?", inline="2c")
pl2 = philo == "Highs" ? ta.pivothigh(cyc2, cyc2) : ta.pivotlow(cyc2, cyc2)
pl2y = philo == "Highs" ? -15 : 15
pl2i = ta.barssince(pl2)
pl2p = pl2i>cyc2
low2in = philo == "Highs" ? ta.highest(close, cyc2*2) : ta.lowest(close, cyc2*2)
low2 = ta.barssince(pl2)>cyc2 ? low2in : na
plot(pl2y, "2x Cycle Radar Line", color=pl2p?col2:color.new(linecolor,ltransp), offset=(cyc2*-1), display=display.none)
plotshape(pl2 ? pl2y : na, "2x Cycle Confirmed", style=shape.diamond, location=location.absolute, color=col2, size = size.tiny, offset=(cyc2*-1))
plotshape(low2 ? pl2y : na, "2x Cycle Radar", style=shape.circle, location=location.absolute, color=color.new(col2, ptransp), size = size.tiny, offset=(cyc2*-1), show_last=1, display=display.none)
// Forecast & Labels
barssince_p2 = 0
p2_x2 = ta.valuewhen(pl2, n - cyc2, 1)
p2_y2 = ta.valuewhen(pl2, pl2, 1)
if pl2
barssince_p2 := (n - cyc2) - p2_x2
avg_barssince_p2 = ta.cum(barssince_p2) / ta.cum(math.sign(barssince_p2))
tooltip2 = "🔄 Pivot Cycle: " + str.tostring(cyc2) + " bars" +
"\n⏱ Last Pivot: " + str.tostring(pl2i + cyc2) + " bars ago" +
"\n🧮 Average Pivot: " + str.tostring(math.round(avg_barssince_p2)) + " bars" +
"\n🔮 Next Pivot: " + str.tostring(math.round(avg_barssince_p2)-(pl2i + cyc2)) + " bars" +
"\n📏 Range: +/- " + str.tostring(math.round(avg_barssince_p2/2)) + " bars"
var label f2 = na
var line l2 = na
if lab2f
f2 := label.new(n + math.min((math.round(avg_barssince_p2) - (pl2i+cyc2)), 500), y=pl2y, size=size.tiny, style=label.style_diamond, color=color.new(col2,ptransp),tooltip =tooltip2)
label.delete(f2[1])
l2 := line.new(x1=n + math.min(math.round((avg_barssince_p2 - (pl2i+cyc2))-(avg_barssince_p2/2)), 500), x2=n + math.min(math.round((avg_barssince_p2 - (pl2i+cyc2))+(avg_barssince_p2/2)), 500), y1=pl2y, y2=pl2y, color=color.new(col2,ptransp))
line.delete(l2[1])
var label c2 = na
if lab2
c2 := label.new(bar_index, y=pl2y, text=str.tostring(cyc2), size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(pl2p?col2:linecolor,0), tooltip=tooltip2)
label.delete(c2[1])
// Input x4 (Default 40) Length Pivot Cycle
col4 = input.color(color.green, "4x Cycle Color ", inline="4c")
cyc4 = input.int(40, "Length", inline="4c")
lab4 = input.bool(true, "Label?", inline="4c")
lab4f = input.bool(true, "Forecast?", inline="4c")
pl4 = philo == "Highs" ? ta.pivothigh(cyc4, cyc4) : ta.pivotlow(cyc4, cyc4)
pl4y = philo == "Highs" ? -20 : 20
pl4i = ta.barssince(pl4)
pl4p = pl4i>cyc4
low4in = philo == "Highs" ? ta.highest(close, cyc4*2): ta.lowest(close, cyc4*2)
low4 = ta.barssince(pl4)>cyc4 ? low4in : na
plot(pl4y, "4x Cycle Radar Line", color=pl4p?col4:color.new(linecolor,ltransp), offset=(cyc4*-1), display=display.none)
plotshape(pl4 ? pl4y : na, "4x Cycle Confirmed", style=shape.diamond, location=location.absolute, color=col4, size = size.tiny, offset=(cyc4*-1))
plotshape(low4 ? pl4y : na, "4x Cycle Radar", style=shape.circle, location=location.absolute, color=color.new(col4, ptransp), size = size.tiny, offset=(cyc4*-1), show_last=1, display=display.none)
// Forecast & Labels
barssince_p4 = 0
p4_x2 = ta.valuewhen(pl4, n - cyc4, 1)
p4_y2 = ta.valuewhen(pl4, pl4, 1)
if pl4
barssince_p4 := (n - cyc4) - p4_x2
avg_barssince_p4 = ta.cum(barssince_p4) / ta.cum(math.sign(barssince_p4))
tooltip4 = "🔄 Pivot Cycle: " + str.tostring(cyc4) + " bars" +
"\n⏱ Last Pivot: " + str.tostring(pl4i + cyc4) + " bars ago" +
"\n🧮 Average Pivot: " + str.tostring(math.round(avg_barssince_p4)) + " bars" +
"\n🔮 Next Pivot: " + str.tostring(math.round(avg_barssince_p4)-(pl4i + cyc4)) + " bars" +
"\n📏 Range: +/- " + str.tostring(math.round(avg_barssince_p4/2)) + " bars"
var label f4 = na
var line l4 = na
if lab4f
f4 := label.new(n + math.min((math.round(avg_barssince_p4) - (pl4i+cyc4)), 500), y=pl4y, size=size.tiny, style=label.style_diamond, color=color.new(col4,ptransp),tooltip =tooltip4)
label.delete(f4[1])
l4 := line.new(x1=n + math.min(math.round((avg_barssince_p4 - (pl4i+cyc4))-(avg_barssince_p4/2)), 500), x2=n + math.min(math.round((avg_barssince_p4 - (pl4i+cyc4))+(avg_barssince_p4/2)), 500), y1=pl4y, y2=pl4y, color=color.new(col4,ptransp))
line.delete(l4[1])
var label c4 = na
if lab4
c4 := label.new(bar_index, y=pl4y, text=str.tostring(cyc4), size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(pl4p?col4:linecolor,0), tooltip=tooltip4)
label.delete(c4[1])
// Input x8 (Default 80) Length Pivot Cycle
col8 = input.color(color.yellow, "8x Cycle Color ", inline="8c")
cyc8 = input.int(80, "Length", inline="8c")
lab8 = input.bool(true, "Label?", inline="8c")
lab8f = input.bool(true, "Forecast?", inline="8c")
pl8 = philo == "Highs" ? ta.pivothigh(cyc8, cyc8) : ta.pivotlow(cyc8, cyc8)
pl8y = philo == "Highs" ? -25 : 25
pl8i = ta.barssince(pl8)
pl8p = pl8i>cyc8
low8in = philo == "Highs" ? ta.highest(close, cyc8*2) : ta.lowest(close, cyc8*2)
low8t = ta.barssince(pl8)>cyc8 ? low8in : na
low8p = ta.barssince(low8in)
plot(pl8y, "8x Cycle Radar Line", color=pl8p?col8:color.new(linecolor,ltransp), offset=(cyc8*-1), display=display.none)
plotshape(pl8 ? pl8y : na, "8x Cycle Confirmed", style=shape.diamond, location=location.absolute, color=col8, size = size.tiny, offset=(cyc8*-1))
plotshape(low8t ? pl8y : na, "8x Cycle Radar", style=shape.circle, location=location.absolute, color=color.new(col8, ptransp), size = size.tiny, offset=(cyc8*-1), show_last=1, display=display.none)
// Forecast & Labels
barssince_p8 = 0
p8_x2 = ta.valuewhen(pl8, n - cyc8, 1)
p8_y2 = ta.valuewhen(pl8, pl8, 1)
if pl8
barssince_p8 := (n - cyc8) - p8_x2
avg_barssince_p8 = ta.cum(barssince_p8) / ta.cum(math.sign(barssince_p8))
tooltip8 = "🔄 Pivot Cycle: " + str.tostring(cyc8) + " bars" +
"\n⏱ Last Pivot: " + str.tostring(pl8i + cyc8) + " bars ago" +
"\n🧮 Average Pivot: " + str.tostring(math.round(avg_barssince_p8)) + " bars" +
"\n🔮 Next Pivot: " + str.tostring(math.round(avg_barssince_p8)-(pl8i + cyc8)) + " bars" +
"\n📏 Range: +/- " + str.tostring(math.round(avg_barssince_p8/2)) + " bars"
var label f8 = na
var line l8 = na
if lab8f
f8 := label.new(n + math.min((math.round(avg_barssince_p8) - (pl8i+cyc8)), 500), y=pl8y, size=size.tiny, style=label.style_diamond, color=color.new(col8,ptransp),tooltip =tooltip8)
label.delete(f8[1])
l8 := line.new(x1=n + math.min(math.round((avg_barssince_p8 - (pl8i+cyc8))-(avg_barssince_p8/2)), 500), x2=n + math.min(math.round((avg_barssince_p8 - (pl8i+cyc8))+(avg_barssince_p8/2)), 500), y1=pl8y, y2=pl8y, color=color.new(col8,ptransp))
line.delete(l8[1])
var label c8 = na
if lab8
c8 := label.new(bar_index, y=pl8y, text=str.tostring(cyc8), size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(pl8p?col8:linecolor,0), tooltip=tooltip8)
label.delete(c8[1])
// Input x16 (Default 160) Length Pivot Cycle
col16 = input.color(color.orange, "16x Cycle Color", inline="16c")
cyc16 = input.int(160, "Length", inline="16c")
lab16 = input.bool(true, "Label?", inline="16c")
lab16f = input.bool(true, "Forecast?", inline="16c")
pl16 = philo == "Highs" ? ta.pivothigh(cyc16, cyc16) : ta.pivotlow(cyc16, cyc16)
pl16y = philo == "Highs" ? -30 : 30
pl16i = ta.barssince(pl16)
pl16p = pl16i>cyc16
low16in = philo == "Highs" ? ta.highest(close, cyc16*2) : ta.lowest(close, cyc16*2)
low16 = ta.barssince(pl16)>cyc16 ? low16in : na
plot(pl16y, "16x Cycle Radar Line", color=pl16p?col16:color.new(linecolor,ltransp), offset=(cyc16*-1), display=display.none)
plotshape(pl16 ? pl16y : na, "16x Cycle Confirmed", style=shape.diamond, location=location.absolute, color=col16, size = size.tiny, offset=(cyc16*-1))
plotshape(low16 ? pl16y : na, "16x Cycle Radar", style=shape.circle, location=location.absolute, color=color.new(col16, ptransp), size = size.tiny, offset=(cyc16*-1), show_last=1, display=display.none)
// Forecast & Labels
barssince_p16 = 0
p16_x2 = ta.valuewhen(pl16, n - cyc16, 1)
p16_y2 = ta.valuewhen(pl16, pl16, 1)
if pl16
barssince_p16 := (n - cyc16) - p16_x2
avg_barssince_p16 = ta.cum(barssince_p16) / ta.cum(math.sign(barssince_p16))
tooltip16 = "🔄 Pivot Cycle: " + str.tostring(cyc16) + " bars" +
"\n⏱ Last Pivot: " + str.tostring(pl16i + cyc16) + " bars ago" +
"\n🧮 Average Pivot: " + str.tostring(math.round(avg_barssince_p16)) + " bars" +
"\n🔮 Next Pivot: " + str.tostring(math.round(avg_barssince_p16)-(pl16i + cyc16)) + " bars" +
"\n📏 Range: +/- " + str.tostring(math.round(avg_barssince_p16/2)) + " bars"
var label f16 = na
var line l16 = na
if lab16f
f16 := label.new(n + math.min((math.round(avg_barssince_p16) - (pl16i+cyc16)), 500), y=pl16y, size=size.tiny, style=label.style_diamond, color=color.new(col16,ptransp),tooltip =tooltip16)
label.delete(f16[1])
l16 := line.new(x1=n + math.min(math.round((avg_barssince_p16 - (pl16i+cyc16))-(avg_barssince_p16/2)), 500), x2=n + math.min(math.round((avg_barssince_p16 - (pl16i+cyc16))+(avg_barssince_p16/2)), 500), y1=pl16y, y2=pl16y, color=color.new(col16,ptransp))
line.delete(l16[1])
var label c16 = na
if lab16
c16 := label.new(bar_index, y=pl16y, text=str.tostring(cyc16), size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(pl16p?col16:linecolor,0), tooltip=tooltip16)
label.delete(c16[1])
// Input x32 (Default 230) Length Pivot Cycle
col32 = input.color(color.red, "32x Cycle Color", inline="32c")
cyc32 = input.int(320, "Length", inline="32c")
lab32 = input.bool(true, "Label?", inline="32c")
lab32f = input.bool(true, "Forecast?", inline="32c")
pl32 = philo == "Highs" ? ta.pivothigh(cyc32, cyc32) : ta.pivotlow(cyc32, cyc32)
pl32y = philo == "Highs" ? -35 : 35
pl32i = ta.barssince(pl32)
pl32p = pl32i>cyc32
low32in = philo == "Highs" ? ta.highest(close, cyc32*2) : ta.lowest(close, cyc32*2)
low32 = ta.barssince(pl32)>cyc32 ? low32in : na
plot(pl32y, "32x Cycle Radar Line", color=pl32p?col32:color.new(linecolor,ltransp), offset=(cyc32*-1), display=display.none)
plotshape(pl32 ? pl32y : na, "32x Cycle Confirmed", style=shape.diamond, location=location.absolute, color=col32, size = size.tiny, offset=(cyc32*-1))
plotshape(low32 ? pl32y : na, "16x Cycle Radar", style=shape.circle, location=location.absolute, color=color.new(col32, ptransp), size = size.tiny, offset=(cyc32*-1), show_last=1, display=display.none)
// Forecast & Labels
barssince_p32 = 0
p32_x2 = ta.valuewhen(pl32, n - cyc32, 1)
p32_y2 = ta.valuewhen(pl32, pl32, 1)
if pl32
barssince_p32 := (n - cyc32) - p32_x2
avg_barssince_p32 = ta.cum(barssince_p32) / ta.cum(math.sign(barssince_p32))
tooltip32 = "🔄 Pivot Cycle: " + str.tostring(cyc32) + " bars" +
"\n⏱ Last Pivot: " + str.tostring(pl32i + cyc32) + " bars ago" +
"\n🧮 Average Pivot: " + str.tostring(math.round(avg_barssince_p32)) + " bars" +
"\n🔮 Next Pivot: " + str.tostring(math.round(avg_barssince_p32)-(pl32i + cyc32)) + " bars" +
"\n📏 Range: +/- " + str.tostring(math.round(avg_barssince_p32/2)) + " bars"
var label f32 = na
var line l32 = na
if lab32f
f32 := label.new(n + math.min((math.round(avg_barssince_p32) - (pl32i+cyc32)), 500), y=pl32y, size=size.tiny, style=label.style_diamond, color=color.new(col32,ptransp),tooltip =tooltip32)
label.delete(f32[1])
l32 := line.new(x1=n + math.min(math.round((avg_barssince_p32 - (pl32i+cyc32))-(avg_barssince_p32/2)), 500), x2=n + math.min(math.round((avg_barssince_p32 - (pl32i+cyc32))+(avg_barssince_p32/2)), 500), y1=pl32y, y2=pl32y, color=color.new(col32,ptransp))
line.delete(l32[1])
var label c32 = na
if lab32
c32 := label.new(bar_index, y=pl32y, text=str.tostring(cyc32), size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(pl32p?col32:linecolor,0), tooltip=tooltip32)
label.delete(c32[1])
// EoS made w/ ❤ by @BarefootJoey ✌💗📈 |
Altcoin Dominance (without ETH) Excluding Stablecoins Unsymetric | https://www.tradingview.com/script/WvyIrAFU-Altcoin-Dominance-without-ETH-Excluding-Stablecoins-Unsymetric/ | CryptoGrit | https://www.tradingview.com/u/CryptoGrit/ | 42 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Unsymetric
//@version=5
indicator("Alt.D w/o ETH - Stable", overlay=true)
timeframeInput = input.timeframe("D", "Timeframe")
sourceInput = input.source(hl2, "Source")
periodInput = input(1, "Period")
btc_cap = request.security(input.symbol("BTC_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
eth_cap = request.security(input.symbol("ETH_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
crypto_cap = request.security(input.symbol("TOTAL", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
usdc_cap = request.security(input.symbol("USDC_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
usdt_cap = request.security(input.symbol("USDT_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
busd_cap = request.security(input.symbol("BUSD_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
dai_cap = request.security(input.symbol("DAI_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
index = (crypto_cap - eth_cap - btc_cap - usdc_cap - usdt_cap - busd_cap - dai_cap) / (crypto_cap - usdc_cap - usdt_cap - busd_cap - dai_cap) *100
plot(index)
|
ETH Dominance Excluding Stablecoins | https://www.tradingview.com/script/VeyFqeL3-ETH-Dominance-Excluding-Stablecoins/ | CryptoGrit | https://www.tradingview.com/u/CryptoGrit/ | 13 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Unsymetric
//@version=5
indicator("ETH.D, -Stable", overlay=true)
timeframeInput = input.timeframe("D", "Timeframe")
sourceInput = input.source(hl2, "Source")
periodInput = input(1, "Period")
eth_cap = request.security(input.symbol("ETH_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
crypto_cap = request.security(input.symbol("TOTAL", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
usdc_cap = request.security(input.symbol("USDC_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
usdt_cap = request.security(input.symbol("USDT_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
busd_cap = request.security(input.symbol("BUSD_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
dai_cap = request.security(input.symbol("DAI_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
index = eth_cap / (crypto_cap - usdc_cap - usdt_cap - busd_cap - dai_cap) *100
plot(index)
|
Stablecoins Dominance | https://www.tradingview.com/script/yaOrWgtf-Stablecoins-Dominance/ | CryptoGrit | https://www.tradingview.com/u/CryptoGrit/ | 25 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ©Unsymetric
//@version=5
indicator("Stable.D", overlay=true)
timeframeInput = input.timeframe("D", "Timeframe")
sourceInput = input.source(hl2, "Source")
periodInput = input(1, "Period")
crypto_cap = request.security(input.symbol("TOTAL", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
usdc_cap = request.security(input.symbol("USDC_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
usdt_cap = request.security(input.symbol("USDT_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
busd_cap = request.security(input.symbol("BUSD_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
dai_cap = request.security(input.symbol("DAI_MARKETCAP", "Symbol") , timeframeInput, ta.sma(sourceInput, periodInput))
index = (usdc_cap + usdt_cap + busd_cap + dai_cap) / (crypto_cap) *100
plot(index) |
Cryptoverse | https://www.tradingview.com/script/IzvOCLtq/ | HasanGocmen | https://www.tradingview.com/u/HasanGocmen/ | 119 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HasanGocmen
// Designed by Hasan Göçmen
//@version=5
indicator("Cryptoverse", overlay = true, max_labels_count = 500, max_lines_count = 500)
period = input.int(defval = 6, title="Pivot Period", minval = 2, maxval = 100, group = "GENERAL SETUP")
source = input.source(title="Pivot Source", defval = close, group = "GENERAL SETUP")
// Support / Resistance Setups
b_back = input.int(defval=500, title="Custom Bars Back", group = "SUPPORT / RESISTANCE SETUP")
cbd = input.int(defval=0, title="Current Bar Decrease", group = "SUPPORT / RESISTANCE SETUP")
showSR = input.bool(true, "Show S/R Lines", group = "SUPPORT / RESISTANCE SETUP")
autoSmplfctn = input.bool(true, "Auto Simplification", group = "SUPPORT / RESISTANCE SETUP", tooltip = "If Auto Simplification Checked, Simplification Steps are not working!")
fltr_stps = input(defval = 14, title = "Simplifaction Steps", group = "SUPPORT / RESISTANCE SETUP")
labelloc = input(defval = 50, title = "Label Location", group = "SUPPORT / RESISTANCE SETUP", tooltip = "Positive numbers reference future bars, negative numbers reference historical bars")
line_clr = input.color(color.rgb(57, 137, 184, 30), "S/R Lines Color", group = "SUPPORT / RESISTANCE SETUP")
// Trend Lines Setups
showTL = input.bool(true, "Show All Trend Lines", group = "TREND LINES SETUP")
hideOL = input.bool(false, "Hide Old Trend Lines", group = "TREND LINES SETUP")
hideML = input.bool(false, "Hide Middle Trend Lines", group = "TREND LINES SETUP")
hlpr_l_f = input.string(title="Helper Line Format", defval="$", options=["%", "$"], group = "TREND LINES SETUP")
ut_clr = input.color(color.rgb(113, 165, 42), "Up Trend Color", group = "TREND LINES SETUP", inline = "trendcolor")
dt_clr = input.color(color.rgb(246, 12, 122), "Down Trend Color", group = "TREND LINES SETUP", inline = "trendcolor")
t_c_w = input.int(defval = 1, title="Trend Channel Width", minval = 1, maxval = 4, group = "TREND LINES SETUP")
t_c_s = input.string("dashed (╌)", title="Trend Channel Style", options=["solid (─)", "dotted (┈)", "dashed (╌)"], group = "TREND LINES SETUP")
uto_show = input.bool(true, "Show Up Trend Overflow", group = "TREND LINES SETUP", inline = "upoverflow")
uto_clr = input.color(color.rgb(255, 153, 0), "", group = "TREND LINES SETUP", inline = "upoverflow")
dto_show = input.bool(true, "Show Down Trend Overflow", group = "TREND LINES SETUP", inline = "downoverflow")
dto_clr = input.color(color.rgb(250, 81, 29), "", group = "TREND LINES SETUP", inline = "downoverflow")
// RSI Divergence Setups
showReg = input.bool(true, "Show Regular", group = "RSI DIVERGENCE SETUP", inline = "Divergence")
showHid = input.bool(true, "Show Hidden", group = "RSI DIVERGENCE SETUP", inline = "Divergence")
showOPD = input.bool(true, "Show Old Potential Divergence", group = "RSI DIVERGENCE SETUP")
bullD_clr = input.color(color.rgb(12, 158, 87), "Bullish Divergence Label Color", group = "RSI DIVERGENCE SETUP")
bearD_clr = input.color(color.rgb(141, 19, 19), "Bearish Divergence Label Color", group = "RSI DIVERGENCE SETUP")
pod_clr = input.color(color.rgb(26, 82, 182, 50), "Potential Divergence Label Color", group = "RSI DIVERGENCE SETUP")
rsiLength = input.int(defval = 14, title="Rsi Length", minval = 1, maxval = 100, group = "RSI DIVERGENCE SETUP")
rsiSource = input.source(title="Rsi Source", defval = close, group = "RSI DIVERGENCE SETUP")
// EMA Setups
sEL = input.bool(true, "Show Ema Labels", group = "EMA SETUP")
ema_1 = input.int(defval = 21, title = 'Ema 1', group = "EMA SETUP", inline = "Ema 1")
ema_1_color = input.color(color.rgb(255, 169, 0), "", group = "EMA SETUP", inline = "Ema 1")
ema_2 = input.int(defval = 50, title = 'Ema 2', group = "EMA SETUP", inline = "Ema 2")
ema_2_color = input.color(color.rgb(255, 118, 0), "", group = "EMA SETUP", inline = "Ema 2")
ema_3 = input.int(defval = 100, title = 'Ema 3', group = "EMA SETUP", inline = "Ema 3")
ema_3_color = input.color(color.rgb(205, 17, 59), "", group = "EMA SETUP", inline = "Ema 3")
ema_4 = input.int(defval = 200, title = 'Ema 4', group = "EMA SETUP", inline = "Ema 4")
ema_4_color = input.color(color.rgb(82, 0, 106), "", group = "EMA SETUP", inline = "Ema 4")
float src1 = math.max(source, source)
float src2 = math.min(source, source)
float ph = ta.pivothigh(src1, period, period)
float pl = ta.pivotlow(src2, period, period)
plotshape(ph, style = shape.triangledown, color = color.red, textcolor = color.red, location = location.abovebar, offset = -period, size = size.auto)
plotshape(pl, style = shape.triangleup, color = color.lime, textcolor = color.lime, location = location.belowbar, offset = -period)
ema1 = ta.ema(close, ema_1)
plot(ema1, 'Ema1', color = ema_1_color)
ema2 = ta.ema(close, ema_2)
plot(ema2, 'Ema2', color = ema_2_color, linewidth = 1)
ema3 = ta.ema(close, ema_3)
plot(ema3, 'Ema3', color = ema_3_color, linewidth = 1)
ema4 = ta.ema(close, ema_4)
plot(ema4, 'Ema4', color = ema_4_color, linewidth = 1)
var label ema1Label = na
var label ema2Label = na
var label ema3Label = na
var label ema4Label = na
if(sEL)
label.delete(ema1Label)
ema1Label := label.new(bar_index, ema1, text="Ema " + str.tostring(ema_1) + ": " + str.tostring(ema1, '#.####'), color=color.rgb(0,0,0,100), textcolor= ema_1_color, style = label.style_label_left, textalign = text.align_left, size = size.small)
label.delete(ema2Label)
ema2Label := label.new(bar_index, ema2, text="Ema " + str.tostring(ema_2) + ": " + str.tostring(ema2, '#.####'), color=color.rgb(0,0,0,100), textcolor= ema_2_color, style = label.style_label_left, textalign = text.align_left, size = size.small)
label.delete(ema3Label)
ema3Label := label.new(bar_index, ema3, text="Ema " + str.tostring(ema_3) + ": " + str.tostring(ema3, '#.####'), color=color.rgb(0,0,0,100), textcolor= ema_3_color, style = label.style_label_left, textalign = text.align_left, size = size.small)
label.delete(ema4Label)
ema4Label := label.new(bar_index, ema4, text="Ema " + str.tostring(ema_4) + ": " + str.tostring(ema4, '#.####'), color=color.rgb(0,0,0,100), textcolor= ema_4_color, style = label.style_label_left, textalign = text.align_left, size = size.small)
var pvtH = array.new_float(0)
var pvtHRsi = array.new_float(0)
var pvtL = array.new_float(0)
var pvtLRsi = array.new_float(0)
var pvtHI = array.new_int(0)
var pvtLI = array.new_int(0)
var pvtvals = array.new_float(0)
var pvtIdxs = array.new_int(0)
var f_l = array.new_float(0)
var temp_f_l = array.new_float(0)
var l_s = array.new_int(0)
var temp_l_s = array.new_int(0)
prdhighest = ta.highest(close, b_back)
prdlowest = ta.lowest(close, b_back)
cw = (prdhighest - prdlowest) * 100 / prdlowest
smplfctn = 0
if(autoSmplfctn)
if(cw < 5)
smplfctn := 25
else if(cw >= 5 and cw < 7)
smplfctn := 35
else if(cw >= 7 and cw < 10)
smplfctn := 70
else if(cw >= 10 and cw < 20)
smplfctn := 100
else if(cw >= 20 and cw < 40)
smplfctn := 150
else if(cw >= 40 and cw < 100)
smplfctn := 250
else
smplfctn := 500
else
smplfctn := fltr_stps
var f_stps = array.new_float(0)
array.clear(f_stps)
for x = 1 to smplfctn
val = 0.0001 * x
array.push(f_stps, 1.0000 + val)
f_match_line_w_step(indx, nextIndx, stepVal)=>
float c_line = array.get(f_l, indx)
float a_line = array.size(f_l) > nextIndx ? array.get(f_l, nextIndx) : 0.0
int strength = array.get(l_s, indx)
int nextStrength = array.size(f_l) > nextIndx ? array.get(l_s, nextIndx) : 0
rtrn = false
float perc = c_line * stepVal
if a_line > 0 and a_line != c_line and perc > a_line
rtrn := true
strength := strength + 1
[rtrn, c_line, a_line, strength]
if(showSR)
var sr_lines = array.new_line(0)
var sr_labels = array.new_label(0)
var temp_sr_lines = array.new_line(0)
var temp_sr_labels = array.new_label(0)
var temp_pvtvals = array.new_float(0)
var temp_pvtIdxs = array.new_int(0)
if ph or pl
array.push(pvtvals, ph ? ph : pl)
array.push(pvtIdxs, bar_index - period)
array.clear(temp_pvtvals)
array.clear(temp_pvtIdxs)
for z = 0 to array.size(pvtIdxs) - 1
if(bar_index[period] - b_back < array.get(pvtIdxs, z))
array.push(temp_pvtvals, array.get(pvtvals, z))
array.push(temp_pvtIdxs, array.get(pvtIdxs, z))
array.sort(temp_pvtvals, order.ascending)
l_s := array.new_int(array.size(temp_pvtvals))
array.fill(l_s, 1)
f_l := array.copy(temp_pvtvals)
for x = 0 to smplfctn - 1
step_val = array.get(f_stps, x)
whileCondition = true
while whileCondition
whileCondition := false
int m_i = -1
if(array.size(f_l) > 1)
for f = 0 to array.size(f_l) - 1
[rtrn, c_line, a_line, strength] = f_match_line_w_step(f, f + 1, step_val)
if rtrn
whileCondition := true
new_line = ((a_line + c_line) / 2)
m_i := f + 1
array.push(temp_f_l, new_line)
array.push(temp_l_s, strength)
else
if f != m_i and a_line != c_line
array.push(temp_f_l, c_line)
array.push(temp_l_s, strength)
f_l := array.copy(temp_f_l)
l_s := array.copy(temp_l_s)
array.clear(temp_f_l)
array.clear(temp_l_s)
if(array.size(sr_lines) > 0)
for x = 0 to array.size(sr_lines) - 1
line.delete(array.get(sr_lines, x))
label.delete(array.get(sr_labels, x))
array.clear(sr_lines)
array.clear(sr_labels)
if array.size(f_l) > 0
for x = 0 to array.size(f_l) - 1
line_val = array.get(f_l, x)
rate = 100 * (line_val - close) / close
array.push(sr_labels,
label.new(x = bar_index + labelloc,
y = line_val,
text = str.tostring(line_val) + "(" + str.tostring(rate,'#.##') + "%)",
color = line_val >= close ? color.rgb(150, 53, 53) : color.rgb(58, 180, 121),
textcolor = line_val >= close ? color.white : color.black,
style = line_val >= close ? label.style_label_lower_left : label.style_label_upper_left))
array.push(sr_lines,
line.new(x1 = bar_index, y1 = line_val, x2 = bar_index - 1, y2 = line_val,
extend = extend.both,
color = line_clr,
style = line.style_solid,
width = 1))
if(array.size(sr_lines) > 0)
for x = 0 to array.size(sr_lines) - 1
first = array.get(sr_labels, 0)
c_lbl = array.get(sr_labels, x)
c_Strength = array.get(l_s, x)
l_lbl_rate = 0.0
h_lbl_rate = 0.0
if(x > 0 and array.size(sr_lines) > 1)
l_lbl_rate := 100 * (label.get_y(array.get(sr_labels, x - 1)) - label.get_y(c_lbl)) / label.get_y(c_lbl)
if(array.size(sr_lines) > 1 and x < array.size(sr_lines) - 1)
h_lbl_rate := 100 * (label.get_y(array.get(sr_labels, x + 1)) - label.get_y(c_lbl)) / label.get_y(c_lbl)
rate = 100 * (label.get_y(c_lbl) - close) / close
label.set_text(c_lbl, text = "Line: " + str.tostring(label.get_y(c_lbl), '#.#####') + " | Distance: (" + str.tostring(rate,'#.##') + "%)\n▲ (" + str.tostring(h_lbl_rate, '#.##') + "%) | ▼ (" + str.tostring(l_lbl_rate, '#.##') + "%) | Strength: " + str.tostring(c_Strength) + "\nC. Width: " + str.tostring(cw, '#.##') + "%, S. Steps: " + str.tostring(smplfctn))
label.set_x(c_lbl, x = bar_index + labelloc)
label.set_color(c_lbl, color = label.get_y(c_lbl) >= close ? color.rgb(150, 53, 53) : color.rgb(120, 212, 168))
label.set_textcolor(c_lbl, textcolor = label.get_y(c_lbl) >= close ? color.white : color.black)
label.set_style(c_lbl, style = label.get_y(c_lbl) >= close ? label.style_label_lower_left : label.style_label_upper_left)
var line t_h_l = na
var line t_l_l = na
var line t_c_l = na
var line b_l_l = na
var line b_h_l = na
var line b_c_l = na
var label lbl_dtuo = na
var label lbl_dtdo = na
var label lbl_utuo = na
var label lbl_utdo = na
t_l_s = t_c_s == "dotted (┈)" ? line.style_dotted : t_c_s == "dashed (╌)" ? line.style_dashed : line.style_solid
add_to_array(arr, indexArr, val)=>
array.push(arr, val)
array.push(indexArr, bar_index - period)
c_e_p(price, process, percent)=>
result = 0.0
if(process == "plus")
result := price + (price / 100) * percent
else
result := price - (price / 100) * percent
u_d_l(line, type)=>
l_x_i = line.get_x1(line)
l_x_p = line.get_y1(line)
l_y_i = line.get_x2(line)
l_y_p = line.get_y2(line)
l_b_c = l_y_i - l_x_i
l_d_p = type == "top" ? l_x_p - l_y_p : l_y_p - l_x_p
l_u_p = l_d_p / l_b_c
d_l_f_p = (bar_index - period) - l_x_i
c_l_p_p = 0.0
if(type == "top")
c_l_p_p := l_x_p - (l_u_p * d_l_f_p)
else
c_l_p_p := l_x_p + (l_u_p * d_l_f_p)
c_l_p_p
d_t_h_l(pHI, pHP, lHP)=>
new_l_b_c = (bar_index - period) - pHI
new_l_d_p = pHP - lHP
new_l_u_p = new_l_d_p / new_l_b_c
lowest = 100000.0
t_lowest = 100000.0
l_i = 0
for y = 0 to new_l_b_c
if(close[period + new_l_b_c - y] - (new_l_u_p * (new_l_b_c - y)) < t_lowest)
lowest := close[period + new_l_b_c - y]
t_lowest := close[period + new_l_b_c - y] - (new_l_u_p * (new_l_b_c - y))
l_i := bar_index - (period + new_l_b_c - y)
d_l_b_c = l_i - pHI
c_l_l_p = pHP - (new_l_u_p * d_l_b_c)
pLP = 0.0
lLP = 0.0
pCP = 0.0
lCP = 0.0
if(hlpr_l_f == '%')
l_perc = (lowest - c_l_l_p) * 100 / c_l_l_p
pLP := pHP * ((100 - math.abs(l_perc)) / 100)
lLP := lHP * ((100 - math.abs(l_perc)) / 100)
c_perc = ((lowest - c_l_l_p) * 100 / c_l_l_p) / 2
pCP := pHP * ((100 - math.abs(c_perc)) / 100)
lCP := lHP * ((100 - math.abs(c_perc)) / 100)
else
pLP := pHP + (lowest - c_l_l_p)
lLP := lHP + (lowest - c_l_l_p)
pCP := pHP + ((lowest - c_l_l_p) / 2)
lCP := lHP + ((lowest - c_l_l_p) / 2)
[pLP, lLP, pCP, lCP]
c_u_p(h_l)=>
uf = false
uf_i = 0
uf_p = 100000.0
c_c = 0.0
c_i = 0
l_x_i = line.get_x1(h_l)
l_x_p = line.get_y1(h_l)
l_y_i = line.get_x2(h_l)
l_y_p = line.get_y2(h_l)
l_b_c = l_y_i - l_x_i
l_d_p = l_x_p - l_y_p
l_u_p = l_d_p / l_b_c
for x = 0 to l_b_c
c_c := close[period + l_b_c - x]
c_i := bar_index - (period + l_b_c - x)
d_l_f_p = (bar_index - period) - l_x_i
c_p_p = l_x_p - (l_u_p * x)
if(c_c < c_p_p)
uf := true
uf_i := c_c < uf_p ? c_i : uf_i
uf_p := c_c < uf_p ? c_c : uf_p
[uf, uf_i, uf_p, l_u_p]
r_d_t_h_l(h_l, uf_i, uf_p, l_u_p)=>
g_x_i = line.get_x1(h_l)
g_x_p = line.get_y1(h_l)
g_y_i = line.get_x2(h_l)
g_y_p = line.get_y2(h_l)
c_l_b_c = g_y_i - g_x_i
d_l_b_c = uf_i - g_x_i
c_l_l_p = g_x_p - (l_u_p * d_l_b_c)
pLP = 0.0
lLP = 0.0
pCP = 0.0
lCP = 0.0
if(hlpr_l_f == '%')
l_perc = (uf_p - c_l_l_p) * 100 / c_l_l_p
pLP := g_x_p * ((100 - math.abs(l_perc)) / 100)
lLP := g_y_p * ((100 - math.abs(l_perc)) / 100)
c_perc = ((uf_p - c_l_l_p) * 100 / c_l_l_p) / 2
pCP := g_x_p * ((100 - math.abs(c_perc)) / 100)
lCP := g_y_p * ((100 - math.abs(c_perc)) / 100)
else
pLP := g_x_p + (uf_p - c_l_l_p)
lLP := g_y_p + (uf_p - c_l_l_p)
pCP := g_x_p + ((uf_p - c_l_l_p) / 2)
lCP := g_y_p + ((uf_p - c_l_l_p) / 2)
line.set_y1(t_l_l, pLP)
line.set_y2(t_l_l, lLP)
line.set_y1(t_c_l, pCP)
line.set_y2(t_c_l, lCP)
d_b_h_l(pLI, pLP, lLP)=>
new_l_b_c = (bar_index - period) - pLI
new_l_d_p = lLP - pLP
new_l_u_p = new_l_d_p / new_l_b_c
highest = 0.0
t_highest = 0.0
h_i = 0
for y = 0 to new_l_b_c
if(close[period + new_l_b_c - y] + (new_l_u_p * (new_l_b_c - y)) > t_highest)
highest := close[period + new_l_b_c - y]
t_highest := close[period + new_l_b_c - y] + (new_l_u_p * (new_l_b_c - y))
h_i := bar_index - (period + new_l_b_c - y)
d_l_b_c = h_i - pLI
c_h_l_p = pLP + (new_l_u_p * d_l_b_c)
pHP = 0.0
lHP = 0.0
pCP = 0.0
lCP = 0.0
if(hlpr_l_f == '%')
l_perc = (highest - c_h_l_p) * 100 / c_h_l_p
pHP := pLP * ((100 + math.abs(l_perc)) / 100)
lHP := lLP * ((100 + math.abs(l_perc)) / 100)
c_perc = ((highest - c_h_l_p) * 100 / c_h_l_p) / 2
pCP := pLP * ((100 - math.abs(c_perc)) / 100)
lCP := lLP * ((100 - math.abs(c_perc)) / 100)
else
pHP := pLP + (highest - c_h_l_p)
lHP := lLP + (highest - c_h_l_p)
pCP := pLP + ((highest - c_h_l_p) / 2)
lCP := lLP + ((highest - c_h_l_p) / 2)
[pHP, lHP, pCP, lCP]
c_o_p(h_l)=>
of = false
of_i = 0
of_p = 0.0
c_c = 0.0
c_i = 0
l_x_i = line.get_x1(h_l)
l_x_p = line.get_y1(h_l)
l_y_i = line.get_x2(h_l)
l_y_p = line.get_y2(h_l)
l_b_c = l_y_i - l_x_i
l_d_p = l_y_p - l_x_p
l_u_p = l_d_p / l_b_c
for x = 0 to l_b_c
c_c := close[period + l_b_c - x]
c_i := bar_index - (period + l_b_c - x)
d_l_f_p = (bar_index - period) - l_x_i
c_p_p = l_x_p + (l_u_p * x)
if(c_c > c_p_p)
of := true
of_i := c_c > of_p ? c_i : of_i
of_p := c_c > of_p ? c_c : of_p
[of, of_i, of_p, l_u_p]
r_d_b_h_l(h_l, of_i, of_p, l_u_p)=>
g_x_i = line.get_x1(h_l)
g_x_p = line.get_y1(h_l)
g_y_i = line.get_x2(h_l)
g_y_p = line.get_y2(h_l)
c_l_b_c = g_y_i - g_x_i
d_h_b_c = of_i - g_x_i
c_h_l_p = g_x_p + (l_u_p * d_h_b_c)
pHP = 0.0
lHP = 0.0
pCP = 0.0
lCP = 0.0
if(hlpr_l_f == '%')
l_perc = (of_p - c_h_l_p) * 100 / c_h_l_p
pHP := g_x_p * ((100 + math.abs(l_perc)) / 100)
lHP := g_y_p * ((100 + math.abs(l_perc)) / 100)
c_perc = ((of_p - c_h_l_p) * 100 / c_h_l_p) / 2
pCP := g_x_p * ((100 - math.abs(c_perc)) / 100)
lCP := g_y_p * ((100 - math.abs(c_perc)) / 100)
else
pHP := g_x_p + (of_p - c_h_l_p)
lHP := g_y_p + (of_p - c_h_l_p)
pCP := g_x_p + ((of_p - c_h_l_p) / 2)
lCP := g_y_p + ((of_p - c_h_l_p) / 2)
line.set_y1(b_h_l, pHP)
line.set_y2(b_h_l, lHP)
line.set_y1(b_c_l, pCP)
line.set_y2(b_c_l, lCP)
c_d_t_o_lbl(t_l, b_l, d_lbl, u_lbl)=>
d_lbl_indx = label.get_x(d_lbl)
u_lbl_indx = label.get_x(u_lbl)
t_l_x_indx = line.get_x1(t_l)
t_l_x_p = line.get_y1(t_l)
t_l_y_indx = line.get_x2(t_l)
t_l_y_p = line.get_y2(t_l)
b_l_x_p = line.get_y1(b_l)
d_lbl_b_c = close[bar_index - d_lbl_indx]
p_d_lbl_b_c = close[bar_index - d_lbl_indx + 1]
u_lbl_b_c = close[bar_index - u_lbl_indx]
p_u_lbl_b_c = close[bar_index - u_lbl_indx + 1]
l_b_c = t_l_y_indx - t_l_x_indx
l_d_p = t_l_x_p - t_l_y_p
l_u_p = l_d_p / l_b_c
diff_d_lbl_indx = d_lbl_indx - t_l_x_indx
diff_u_lbl_indx = u_lbl_indx - t_l_x_indx
d_l_t_t = t_l_x_p - (l_u_p * diff_d_lbl_indx)
d_l_t_b = b_l_x_p - (l_u_p * diff_d_lbl_indx)
d_l_p_t_t = t_l_x_p - (l_u_p * (diff_d_lbl_indx - 1))
d_l_p_t_b = b_l_x_p - (l_u_p * (diff_d_lbl_indx - 1))
u_l_t_t = t_l_x_p - (l_u_p * diff_u_lbl_indx)
u_l_t_b = b_l_x_p - (l_u_p * diff_u_lbl_indx)
u_l_p_t_t = t_l_x_p - (l_u_p * (diff_u_lbl_indx - 1))
u_l_p_t_b = b_l_x_p - (l_u_p * (diff_u_lbl_indx - 1))
if(t_l_x_indx < d_lbl_indx and (p_d_lbl_b_c > d_l_p_t_b or d_lbl_b_c > d_l_t_b))
label.delete(d_lbl)
if(t_l_x_indx < u_lbl_indx and (p_u_lbl_b_c < u_l_p_t_t or u_lbl_b_c < u_l_t_t))
label.delete(u_lbl)
c_u_t_o_lbl(b_l, t_l, d_lbl, u_lbl)=>
d_lbl_indx = label.get_x(d_lbl)
u_lbl_indx = label.get_x(u_lbl)
b_l_x_indx = line.get_x1(b_l)
b_l_x_p = line.get_y1(b_l)
b_l_y_indx = line.get_x2(b_l)
b_l_y_p = line.get_y2(b_l)
t_l_x_p = line.get_y1(t_l)
d_lbl_b_c = close[bar_index - d_lbl_indx]
p_d_lbl_b_c = close[bar_index - d_lbl_indx + 1]
u_lbl_b_c = close[bar_index - u_lbl_indx]
p_u_lbl_b_c = close[bar_index - u_lbl_indx + 1]
l_b_c = b_l_y_indx - b_l_x_indx
l_d_p = b_l_y_p - b_l_x_p
l_u_p = l_d_p / l_b_c
diff_d_lbl_indx = d_lbl_indx - b_l_x_indx
diff_u_lbl_indx = u_lbl_indx - b_l_x_indx
d_l_t_t = t_l_x_p + (l_u_p * diff_d_lbl_indx)
d_l_t_b = b_l_x_p + (l_u_p * diff_d_lbl_indx)
d_l_p_t_t = t_l_x_p + (l_u_p * (diff_d_lbl_indx - 1))
d_l_p_t_b = b_l_x_p + (l_u_p * (diff_d_lbl_indx - 1))
u_l_t_t = t_l_x_p + (l_u_p * diff_u_lbl_indx)
u_l_t_b = b_l_x_p + (l_u_p * diff_u_lbl_indx)
u_l_p_t_t = t_l_x_p + (l_u_p * (diff_u_lbl_indx - 1))
u_l_p_t_b = b_l_x_p + (l_u_p * (diff_u_lbl_indx - 1))
if(b_l_x_indx < d_lbl_indx and (p_d_lbl_b_c > d_l_p_t_b or d_lbl_b_c > d_l_t_b))
label.delete(d_lbl)
if(b_l_x_indx < u_lbl_indx and (p_u_lbl_b_c < u_l_p_t_t or u_lbl_b_c < u_l_t_t))
label.delete(u_lbl)
var uf_c = 0
var of_c = 0
if(ph)
if(array.size(pvtH) > 0 and showTL)
pPH = array.get(pvtH, array.size(pvtH) - 1)
two_pPH = array.size(pvtH) > 1 ? array.get(pvtH, array.size(pvtH) - 2) : 0
prev_pvtHI = array.get(pvtHI, array.size(pvtHI) - 1)
c_HLPP = u_d_l(t_h_l, "top")
c_LLPP = u_d_l(t_l_l, "top")
c_CLPP = u_d_l(t_c_l, "top")
a_LTP = line.get_y1(t_h_l)
if(a_LTP > ph * 1.001 and ph >= c_HLPP and two_pPH == a_LTP)
line.set_xy2(t_h_l, bar_index - period, ph)
uf_c := 1
[pLP, lLP, pCP, lCP] = d_t_h_l(line.get_x1(t_h_l), line.get_y1(t_h_l), ph)
line.set_xy1(t_l_l, line.get_x1(t_l_l), pLP)
line.set_xy2(t_l_l, bar_index - period, lLP)
line.set_xy1(t_c_l, line.get_x1(t_c_l), pCP)
line.set_xy2(t_c_l, bar_index - period, lCP)
c_d_t_o_lbl(t_h_l, t_l_l, lbl_dtdo, lbl_dtuo)
else if(pPH >= two_pPH and ph * 1.001 < pPH)
line.set_xy2(t_h_l, bar_index - period, c_HLPP)
line.set_xy2(t_l_l, bar_index - period, c_LLPP)
line.set_xy2(t_c_l, bar_index - period, c_CLPP)
if(na(c_HLPP) or c_e_p(c_HLPP, "plus", 0.35) < ph or c_e_p(c_LLPP, "minus", 0.35) > ph)
line.set_color(t_h_l, color.new(dt_clr, 50))
line.set_color(t_l_l, color.new(dt_clr, 50))
line.set_color(t_c_l, color.new(dt_clr, 75))
line.set_extend(t_h_l, extend.none)
line.set_extend(t_l_l, extend.none)
line.set_extend(t_c_l, extend.none)
if(hideOL)
line.delete(t_h_l)
line.delete(t_l_l)
line.delete(t_c_l)
label.delete(lbl_dtdo)
label.delete(lbl_dtuo)
uf_c := 0
t_h_l := line.new(prev_pvtHI, pPH, bar_index - period, ph, extend = extend.right, width = 1, color= dt_clr, style = t_l_s)
[pLP, lLP, pCP, lCP] = d_t_h_l(prev_pvtHI, pPH, ph)
t_l_l := line.new(prev_pvtHI, pLP, bar_index - period, lLP, extend = extend.right, width = 1, color= dt_clr, style = t_l_s)
if not hideML
t_c_l := line.new(prev_pvtHI, pCP, bar_index - period, lCP, extend = extend.right, width = t_c_w, color = color.new(dt_clr, 50), style = t_l_s)
else
if(a_LTP > ph)
line.set_xy2(t_h_l, bar_index - period, c_HLPP)
line.set_xy2(t_l_l, bar_index - period, c_LLPP)
line.set_xy2(t_c_l, bar_index - period, c_CLPP)
[uf, uf_i, uf_p, l_u_p] = c_u_p(t_l_l)
if(uf and c_LLPP < ph and c_HLPP > ph and c_LLPP < open[period] and uf_c == 0)
uf_c := uf_c + 1
r_d_t_h_l(t_h_l, uf_i, uf_p, l_u_p)
c_d_t_o_lbl(t_h_l, t_l_l, lbl_dtdo, lbl_dtuo)
if(pl)
if(array.size(pvtL) > 0 and showTL)
pPL = array.get(pvtL, array.size(pvtL) - 1)
two_pPL = array.size(pvtL) > 1 ? array.get(pvtL, array.size(pvtL) - 2) : 0
prev_pvtLI = array.get(pvtLI, array.size(pvtLI) - 1)
c_LLPP = u_d_l(b_l_l, "bottom")
c_HLPP = u_d_l(b_h_l, "bottom")
c_CLPP = u_d_l(b_c_l, "bottom")
a_LBP = line.get_y1(b_l_l)
if(a_LBP < pl * 0.999 and pl <= c_LLPP and two_pPL == a_LBP)
line.set_xy2(b_l_l, bar_index - period, pl)
of_c := 1
[pHP, lHP, pCP, lCP] = d_b_h_l(line.get_x1(b_l_l), line.get_y1(b_l_l), pl)
line.set_xy1(b_h_l, line.get_x1(b_h_l), pHP)
line.set_xy2(b_h_l, bar_index - period, lHP)
line.set_xy1(b_c_l, line.get_x1(b_h_l), pCP)
line.set_xy2(b_c_l, bar_index - period, lCP)
c_u_t_o_lbl(b_l_l, b_h_l, lbl_utdo, lbl_utuo)
else if(pPL <= two_pPL and pl * 0.999 > pPL)
line.set_xy2(b_l_l, bar_index - period, c_LLPP)
line.set_xy2(b_h_l, bar_index - period, c_HLPP)
line.set_xy2(b_c_l, bar_index - period, c_CLPP)
if(na(c_LLPP) or c_e_p(c_LLPP, "minus", 0.35) > pl or c_e_p(c_HLPP, "plus", 0.35) < pl)
line.set_color(b_h_l, color.new(ut_clr, 50))
line.set_color(b_l_l, color.new(ut_clr, 50))
line.set_color(b_c_l, color.new(ut_clr, 75))
line.set_extend(b_h_l, extend.none)
line.set_extend(b_l_l, extend.none)
line.set_extend(b_c_l, extend.none)
if(hideOL)
line.delete(b_h_l)
line.delete(b_l_l)
line.delete(b_c_l)
label.delete(lbl_utdo)
label.delete(lbl_utuo)
of_c := 0
b_l_l := line.new(prev_pvtLI, pPL, bar_index - period, pl, extend = extend.right, width = 1, color= ut_clr, style = t_l_s)
[pHP, lHP, pCP, lCP] = d_b_h_l(prev_pvtLI, pPL, pl)
b_h_l := line.new(prev_pvtLI, pHP, bar_index - period, lHP, extend = extend.right, width = 1, color= ut_clr, style = t_l_s)
if not hideML
b_c_l := line.new(prev_pvtLI, pCP, bar_index - period, lCP, extend = extend.right, width = t_c_w, color= color.new(ut_clr, 50), style = t_l_s)
else
if(a_LBP < pl)
line.set_xy2(b_l_l, bar_index - period, c_LLPP)
line.set_xy2(b_h_l, bar_index - period, c_HLPP)
line.set_xy2(b_c_l, bar_index - period, c_CLPP)
[of, of_i, of_p, l_u_p] = c_o_p(b_h_l)
if(of and c_HLPP > pl and c_LLPP < pl and c_HLPP > open[period] and of_c == 0)
of_c := of_c + 1
r_d_b_h_l(b_l_l, of_i, of_p, l_u_p)
c_u_t_o_lbl(b_l_l, b_h_l, lbl_utdo, lbl_utuo)
c_p_t_o(h_l, l_l)=>
dtuo = false
dtdo = false
h_l_x_i = line.get_x1(h_l)
h_l_x_p = line.get_y1(h_l)
h_l_y_i = line.get_x2(h_l)
h_l_y_p = line.get_y2(h_l)
l_l_x_i = line.get_x1(l_l)
l_l_x_p = line.get_y1(l_l)
l_l_y_i = line.get_x2(l_l)
l_l_y_p = line.get_y2(l_l)
l_b_c = h_l_y_i - h_l_x_i
l_d_p = h_l_x_p - h_l_y_p
l_u_p = l_d_p / l_b_c
cd = bar_index - h_l_x_i
pcd = bar_index[1] - h_l_x_i
tpcd = bar_index[2] - h_l_x_i
clhp = h_l_x_p - (l_u_p * cd)
cllp = l_l_x_p - (l_u_p * cd)
pclhp = h_l_x_p - (l_u_p * pcd)
pcllp = l_l_x_p - (l_u_p * pcd)
tpclhp = h_l_x_p - (l_u_p * tpcd)
tpcllp = l_l_x_p - (l_u_p * tpcd)
if(close[2] < tpclhp and
close[2] > tpcllp and
open[2] < tpclhp and
open[2] > tpcllp
)
if(close[1] > pclhp and close[1] > open[1] and close > clhp and close > open)
dtuo := true
else if(close[1] < pcllp and close[1] < open[1] and close < cllp and close < open)
dtdo := true
[dtuo, dtdo]
c_p_t_u(h_l, l_l)=>
utdo = false
utuo = false
h_l_x_i = line.get_x1(h_l)
h_l_x_p = line.get_y1(h_l)
h_l_y_i = line.get_x2(h_l)
h_l_y_p = line.get_y2(h_l)
l_l_x_i = line.get_x1(l_l)
l_l_x_p = line.get_y1(l_l)
l_l_y_i = line.get_x2(l_l)
l_l_y_p = line.get_y2(l_l)
l_b_c = h_l_y_i - h_l_x_i
l_d_p = h_l_y_p - h_l_x_p
l_u_p = l_d_p / l_b_c
cd = bar_index - h_l_x_i
pcd = bar_index[1] - h_l_x_i
tpcd = bar_index[2] - h_l_x_i
clhp = h_l_x_p + (l_u_p * cd)
cllp = l_l_x_p + (l_u_p * cd)
pclhp = h_l_x_p + (l_u_p * pcd)
pcllp = l_l_x_p + (l_u_p * pcd)
tpclhp = h_l_x_p + (l_u_p * tpcd)
tpcllp = l_l_x_p + (l_u_p * tpcd)
if(close[2] < tpclhp and
close[2] > tpcllp and
open[2] < tpclhp and
open[2] > tpcllp
)
if(close[1] < pcllp and close[1] < open[1] and close < cllp and close < open)
utdo := true
else if(close[1] > pclhp and close[1] > open[1] and close > clhp and close > open)
utuo := true
[utdo, utuo]
[dtuo, dtdo] = c_p_t_o(t_h_l, t_l_l)
if(not na(t_h_l) and not na(t_l_l))
if(dtuo and dto_show)
if(hideOL)
label.delete(lbl_dtuo)
lbl_dtuo := label.new(bar_index, close, text = "Down Trend\nUp Overflow", textcolor = dto_clr, color = dto_clr, style = label.style_arrowup, yloc = yloc.belowbar, size = size.small)
if(dtdo and dto_show)
if(hideOL)
label.delete(lbl_dtdo)
lbl_dtdo := label.new(bar_index, close, text = "Down Trend\nDown Overflow", textcolor = dto_clr, color = dto_clr, style = label.style_arrowdown, yloc = yloc.abovebar, size = size.small)
[utdo, utuo] = c_p_t_u(b_h_l, b_l_l)
if(not na(b_h_l) and not na(b_l_l))
if(utdo and uto_show)
if(hideOL)
label.delete(lbl_utdo)
lbl_utdo := label.new(bar_index, close, text = "Up Trend\nDown Overflow", textcolor = uto_clr, color = uto_clr, style = label.style_arrowdown, yloc = yloc.abovebar, size = size.small)
if(utuo and uto_show)
if(hideOL)
label.delete(lbl_utuo)
lbl_utuo := label.new(bar_index, close, text = "Up Trend\nUp Overflow", textcolor = uto_clr, color = uto_clr, style = label.style_arrowup, yloc = yloc.belowbar, size = size.small)
rsi = ta.rsi(close, 14)
var label bullD = na
var label bearD = na
var label potbullD = na
var label potbearD = na
if pl
if(array.size(pvtL) > 0)
l_l = array.get(pvtL, array.size(pvtL) - 1)
l_l_i = array.get(pvtLI, array.size(pvtLI) - 1)
p_l_l = array.size(pvtL) > 1 ? array.get(pvtL, array.size(pvtL) - 2) : 0
l_l_r = array.get(pvtLRsi, array.size(pvtLRsi) - 1)
distance = bar_index[period] - l_l_i
l_r = 101.0
h_p = 0.0
for x = 1 to distance - 1
l_r := rsi[period + x] < l_r ? rsi[period + x] : l_r
h_p := close[period + x] > h_p ? close[period + x] : h_p
if(p_l_l and p_l_l > l_l and rsi[period] <= l_r and h_p > l_l * 1.01)
if(pl < l_l and rsi[period] > l_l_r + 1 and l_l_r < 50 and showReg)
label.delete(potbullD)
textDiv = "Regular\nDivergence"
bullD := label.new(bar_index - period, pl, text = textDiv, textcolor = color.white, color = color.new(bullD_clr, 25), style = label.style_label_up, yloc = yloc.belowbar, size = size.small)
else if(pl > l_l and rsi[period] + 1 < l_l_r and rsi[period] < 50 and showHid)
label.delete(potbullD)
textDiv = "Hidden\nDivergence"
bullD := label.new(bar_index - period, pl, text = textDiv, textcolor = color.white, color = color.new(bullD_clr, 75), style = label.style_label_up, yloc = yloc.belowbar, size = size.small)
if ph
if(array.size(pvtH) > 0)
l_h = array.get(pvtH, array.size(pvtH) - 1)
l_h_i = array.get(pvtHI, array.size(pvtHI) - 1)
p_l_h = array.size(pvtH) > 1 ? array.get(pvtH, array.size(pvtH) - 2) : 0
l_h_r = array.get(pvtHRsi, array.size(pvtHRsi) - 1)
distance = bar_index[period] - l_h_i
h_r = 0.0
l_p = 100000.0
for x = 1 to distance - 1
h_r := rsi[period + x] > h_r ? rsi[period + x] : h_r
l_p := close[period + x] < l_p ? close[period + x] : l_p
if(p_l_h and p_l_h < l_h and rsi[period] >= h_r and l_p * 1.01 < l_h)
if(ph > l_h and rsi[period] + 1 < l_h_r and l_h_r > 50 and showReg)
label.delete(potbearD)
textDiv = "Regular\nDivergence"
bearD := label.new(bar_index - period, ph, text = textDiv, textcolor = color.white, color = color.new(bearD_clr, 25), style = label.style_label_down, yloc = yloc.abovebar, size = size.small)
else if(ph < l_h and rsi[period] > l_h_r + 1 and rsi[period] > 50 and showHid)
label.delete(potbearD)
textDiv = "Hidden\nDivergence"
bearD := label.new(bar_index - period, ph, text = textDiv, textcolor = color.white, color = color.new(bearD_clr, 75), style = label.style_label_down, yloc = yloc.abovebar, size = size.small)
if(array.size(pvtL) > 0)
l_l = array.get(pvtL, array.size(pvtL) - 1)
l_l_i = array.get(pvtLI, array.size(pvtLI) - 1)
p_l_l = array.size(pvtL) > 1 ? array.get(pvtL, array.size(pvtL) - 2) : 0
l_l_r = array.get(pvtLRsi, array.size(pvtLRsi) - 1)
distance = bar_index[1] - l_l_i
l_r = 101.0
h_p = 0.0
for x = 2 to distance
l_r := rsi[x] < l_r ? rsi[x] : l_r
h_p := close[x] > h_p ? close[x] : h_p
if(close >= open and close[1] <= open[1] and close[1] != l_l and rsi[1] <= l_r and p_l_l and p_l_l > l_l and h_p > l_l * 1.01)
if(close[1] < l_l and rsi[1] > l_l_r + 1 and l_l_r < 50 and showReg)
if not showOPD
label.delete(potbullD)
textDiv = "Potential\nRegular\nDivergence"
potbullD := label.new(bar_index[1], close[1], text = textDiv, textcolor = color.white, color = color.new(pod_clr, 25), style = label.style_label_up, yloc = yloc.belowbar, size = size.small)
else if(close[1] > l_l and rsi[1] + 1 < l_l_r and rsi[1] < 50 and showHid)
if not showOPD
label.delete(potbullD)
textDiv = "Potential\nHidden\nDivergence"
potbullD := label.new(bar_index[1], close[1], text = textDiv, textcolor = color.white, color = color.new(pod_clr, 25), style = label.style_label_up, yloc = yloc.belowbar, size = size.small)
if(array.size(pvtH) > 0)
l_h = array.get(pvtH, array.size(pvtH) - 1)
l_h_i = array.get(pvtHI, array.size(pvtHI) - 1)
p_l_h = array.size(pvtH) > 1 ? array.get(pvtH, array.size(pvtH) - 2) : 0
l_h_r = array.get(pvtHRsi, array.size(pvtHRsi) - 1)
distance = bar_index[1] - l_h_i
h_r = 0.0
l_p = 100000.0
for x = 2 to distance
h_r := rsi[x] > h_r ? rsi[x] : h_r
l_p := close[x] < l_p ? close[x] : l_p
if(close <= open and close[1] >= open[1] and close[1] != l_h and rsi[1] >= h_r and p_l_h and p_l_h < l_h and l_p * 1.01 < l_h)
if(close[1] > l_h and rsi[1] + 1 < l_h_r and l_h_r > 50 and showReg)
if not showOPD
label.delete(potbearD)
textDiv = "Potential\nRegular\nDivergence"
potbearD := label.new(bar_index[1], close[1], text = textDiv, textcolor = color.white, color = color.new(pod_clr, 25), style = label.style_label_down, yloc = yloc.abovebar, size = size.small)
else if(close[1] < l_h and rsi[1] > l_h_r + 1 and rsi[1] > 50 and showHid)
if not showOPD
label.delete(potbearD)
textDiv = "Potential\nHidden\nDivergence"
potbearD := label.new(bar_index[1], close[1], text = textDiv, textcolor = color.white, color = color.new(pod_clr, 25), style = label.style_label_down, yloc = yloc.abovebar, size = size.small)
if(ph)
add_to_array(pvtH, pvtHI, ph)
array.push(pvtHRsi, rsi[period])
if(pl)
add_to_array(pvtL, pvtLI, pl)
array.push(pvtLRsi, rsi[period])
|
Volume Weighted Standard Deviation (VWSD) | https://www.tradingview.com/script/IkHB33ir-Volume-Weighted-Standard-Deviation-VWSD/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 27 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("Volume Weighted Standard Deviation", overlay = true)
vstdev(source, length)=>
mean_price = ta.sma(source, length)
mean_volume = ta.sma(volume, length)
squared_diff_price = math.sum(math.pow(source - mean_price, 2) * volume, length)
vstdev = math.sqrt((squared_diff_price) / math.sum(volume, length))
source = input.source(close, "Source")
length = input.int(20, "Length", 1)
mult = input.float(1.5, "Deviation", 0)
sma = ta.sma(close, 20)
vstdev = vstdev(close, 20)
plot(sma)
plot(sma - vstdev * mult)
plot(sma + vstdev * mult)
|
Ma Pullback | https://www.tradingview.com/script/F39LhPg8-Ma-Pullback/ | Shauryam_or | https://www.tradingview.com/u/Shauryam_or/ | 297 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Shauryam_or
//@version=5
indicator("Ma Pullback",overlay = true)
//Ema 1
on_ma=input.bool(true,"Enable EMa 1 Plot On/Off",group="EMa Set")
ma_len= input.int(32, minval=1, title="Ema Length",group = "EMa Set")
ma_src = input.source(close, title="Ema Source",group = "EMa Set")
ma_out = ta.ema(ma_src, ma_len)
//Ema 2
on_ma2=input.bool(true,"Enable EMa 2 Plot On/Off",group="EMa2 Set")
ma_len2= input.int(32, minval=1, title="Ema2 Length",group = "EMa2 Set")
ma_src2 = input.source(low, title="Ema2 Source",group = "EMa2 Set")
ma_out2 = ta.ema(ma_src2, ma_len2)
// Ema 3
on_ma3=input.bool(true,"Enable EMa 3 Plot On/Off",group="EMa3 Set")
ma_len3= input.int(32, minval=1, title="Ema3 Length",group = "EMa3 Set")
ma_src3 = input.source(high, title="Ema3 Source",group = "EMa3 Set")
ma_out3 = ta.ema(ma_src3, ma_len3)
//ploting ema
plot(on_ma?ma_out:na, color=color.white, title="MA")
plot(on_ma2?ma_out2:na, color=color.lime, title="MA")
plot(on_ma3?ma_out3:na, color=color.lime, title="MA")
//ema as cloud
cloud_top = math.max(ma_out2 , ma_out3)
cloud_bottom = math.min(ma_out2, ma_out3)
var buy_cond1=false
var sell_cond1=false
if ta.crossover(close, cloud_top)
buy_cond1:=true
sell_cond1:=false
if ta.crossunder(close, cloud_bottom )
sell_cond1:=true
buy_cond1:=false
buy_cond = buy_cond1
sell_cond =sell_cond1
// plotshape(buy_cond,title = "Buy1",style = shape.labelup,location = location.belowbar,color = color.green,text = "1st buyc t",textcolor =color.white)
// plotshape(sell_cond ,title = "Sell1",style = shape.labeldown,location = location.abovebar,color = color.red,text = "1st sellc t",textcolor =color.white)
var pullback_crossup=false
var pullback_crossdown=false
if (ta.crossover(high,ma_out2) or ta.crossover(high,ma_out) or ta.crossover(high,ma_out3)) and close<cloud_top and close>open and sell_cond
pullback_crossup:=true
if (ta.crossunder(low,ma_out2) or ta.crossunder(low,ma_out) or ta.crossunder(low,ma_out3)) and close>cloud_bottom and close<open and buy_cond
pullback_crossdown:=true
// plotshape(pullback_crossup,title = "Buy2",style = shape.labelup,location = location.belowbar,color = color.green,text = "2nd buyc t",textcolor =color.white)
// plotshape(pullback_crossdown,title = "Sell2",style = shape.labeldown,location = location.abovebar,color = color.red,text = "2nd sellc t",textcolor =color.white)
if ta.crossunder(close, cloud_bottom )
pullback_crossdown:=false
if ta.crossover(close, cloud_top)
pullback_crossup:=false
final_buy= pullback_crossdown and ta.crossover(close, cloud_top) and close>open
final_sell=pullback_crossup and ta.crossunder(close, cloud_bottom ) and close<open
if final_buy
pullback_crossdown:=false
if final_sell
pullback_crossup:=false
//input to check bar distance
bar_limit=input.int(7,title ="Candle Limit",group ="Candle Setting",tooltip ="Barsince Candle 7 should be greater/lower then ema band")
perc_candle=input.float(0.1,step =0.1,title ="%Candle Size",group ="Candle Setting",tooltip ="Percentage candle size to check movementam candle")
//candle size
candle_size=math.abs(open - close) / math.abs(high - low) > perc_candle
since_x=(close[bar_limit]>cloud_top)
since_y=(close[bar_limit]<cloud_bottom)
plotshape(final_buy and since_x and candle_size,title = "Buy3",style = shape.labelup,location = location.belowbar,color = color.green,text = "Buy",textcolor =color.white,size=size.tiny)
plotshape(final_sell and since_y and candle_size,title = "Sell3",style = shape.labeldown,location = location.abovebar,color = color.red,text = "Sell",textcolor =color.white,size=size.tiny)
|
Chatterjee Correlation | https://www.tradingview.com/script/jbC5eZKb-Chatterjee-Correlation/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 104 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
// __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __
// / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / |
// $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ |
// $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ |
// $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ |
// $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ |
// $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ |
// $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ |
// $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/
//
//
//
//@version=5
indicator("Chatterjee Correlation", precision=4)
import HeWhoMustNotBeNamed/BinaryInsertionSort/1 as bis
source = input.string('volume', 'Source', options = ['volume', 'volatility'])
loopback = input.int(100, 'Loopback', minval=10, step=20)
sampleSize = input.int(20000, "Sample Size", minval=5000, maxval = 30000, step=5000)
plotSize = input.int(500, "Plot Last X bars", minval = 100, maxval=5000, step=100)
averageVolume = ta.sma(volume, loopback)
atr = ta.atr(loopback)
float x = source == 'volume'? averageVolume : atr
float y = close - ta.sma(close, loopback)
float correlation = na
float correlationAnton = na
if(bar_index >= last_bar_index-sampleSize)
[xArray, xSortedArray, xSortIndices] = bis.get_sorted_arrays(x)
[yArray, ySortedArray, ySortIndices] = bis.get_sorted_arrays(y)
coefficient = 0.0
n = array.size(xArray)
if(bar_index >= last_bar_index-plotSize)
index = array.get(xSortIndices, 0)
for i=1 to n > 1? n -1 : na
indexNext = array.get(xSortIndices, i)
coefficient := coefficient + math.abs(array.get(ySortIndices, indexNext)-array.get(ySortIndices, index))
index := indexNext
correlation := 1 - 3*coefficient/(math.pow(n,2)-1)
plot(correlation, "Chatterjee Correlation", color=color.blue)
|
BTC Pair Change % | https://www.tradingview.com/script/MM9ta5hs-BTC-Pair-Change/ | backslash-f | https://www.tradingview.com/u/backslash-f/ | 37 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © backslash-f
//
// This script makes it easier to quickly check how the BTC pair of the current symbol is performing.
// It adds a "change percentage widget" to the top right of the chart with two rows, one for each timeframe.
// The default timeframes are: 1. current chart timeframe; 2. 1D timeframe. These can be customized.
//
// The calculation is performed as described here:
// https://www.tradingview.com/support/solutions/43000635852-how-are-the-most-popular-filters-calculated/
//
// In short, this script:
// - Searches for the BTC pair of the current symbol
// - Calculates the change % using the above described logic (links) for the two target timeframes
// - Adds a change percentage "widget" to the top right of the chart with 2 rows, one for each timeframe
//
// Note to self: If the system detects that a required symbol doesn't exist or cannot be asked by any reason,
// then the script will not execute any subsequent logic. This makes it impossible to plot something when a
// BTC pair is non existent (e.g. "No BTC Pair"). Source: https://stackoverflow.com/a/60132079/584548
//@version=5
indicator("BTC Pair Change %", overlay=true)
/////////
// INPUT
/////////
var timeframeGroup = "Timeframes"
timeframe1 = input.timeframe(title="Timeframe 1", defval="", group=timeframeGroup, tooltip = "The target timeframe for the first row. Default is the current timeframe.")
timeframe2 = input.timeframe(title="Timeframe 2", defval="1D", group=timeframeGroup, tooltip = "The target timeframe for the second row. Default is 1 day.")
var tableColorGroup = "Table Colors"
tableBackgroundColor = input.color(title="Background", defval=color.new(color.black, 100), group=tableColorGroup)
tableBorderColor = input.color(title="Border", defval=color.new(color.black, 10), group=tableColorGroup)
tableStaticTextColor = input.color(title="Text", defval=color.new(color.white, 20), group=tableColorGroup, tooltip = "Color for the table's static text, like header and cell titles. Does not apply to the change percentage text, which is dynamic between red, green and white.")
/////////////
// FUNCTIONS
/////////////
currentPrice(symbol, timeframe) =>
request.security(symbol, timeframe, close)
previousPrice(symbol, timeframe) =>
request.security(symbol, timeframe, close[1])
priceChangePercentage(btcPairPriceCurrent, btcPairPricePrevious) =>
btcPairPriceChange = btcPairPriceCurrent - btcPairPricePrevious
btcPairPriceChangePercent = (btcPairPriceChange / btcPairPricePrevious) * 100
btcPairPriceChangePercentString = str.tostring(btcPairPriceChangePercent, '#.##') + "%"
priceChangeTextColor(btcPairPriceCurrent, btcPairPricePrevious) =>
btcPairPriceChange = btcPairPriceCurrent - btcPairPricePrevious
btcPairPriceChangePercent = (btcPairPriceChange / btcPairPricePrevious) * 100
btcPairPriceChangePercent == 0 ? color.white : btcPairPriceChangePercent > 0 ? color.green : color.red
//////////////
// PROPERTIES
//////////////
tickerPrefix = syminfo.basecurrency // E.g: ETH
btcPair = tickerPrefix + "BTC" // E.g: ETHBTC
// Timeframe 1
btcPairPriceTimeframe1Current = currentPrice(btcPair, timeframe1)
btcPairPriceTimeframe1Previous = previousPrice(btcPair, timeframe1)
btcPairPriceTimeframe1ChangePercent = priceChangePercentage(btcPairPriceTimeframe1Current, btcPairPriceTimeframe1Previous)
btcPairPriceTimeframe1ChangePercentTextColor = priceChangeTextColor(btcPairPriceTimeframe1Current, btcPairPriceTimeframe1Previous)
timeframe1String = (timeframe1 == "") ? str.tostring(timeframe.period) : str.tostring(timeframe1)
// Timeframe 2
btcPairPriceTimeframe2Current = currentPrice(btcPair, timeframe2)
btcPairPriceTimeframe2Previous = previousPrice(btcPair, timeframe2)
btcPairPriceTimeframe2ChangePercent = priceChangePercentage(btcPairPriceTimeframe2Current, btcPairPriceTimeframe2Previous)
btcPairPriceTimeframe2ChangePercentTextColor = priceChangeTextColor(btcPairPriceTimeframe2Current, btcPairPriceTimeframe2Previous)
/////////
// TABLE
/////////
if barstate.islast
table = table.new(position = position.top_right, columns = 2, rows = 4, bgcolor = tableBackgroundColor, border_width = 1, border_color = tableBorderColor)
// Header
table.cell(table, 0, 0, btcPair, text_color = tableStaticTextColor)
table.merge_cells(table, start_column = 0, start_row = 0, end_row = 0, end_column = 1)
// Timeframe column
table.cell(table, 0, 1, "Timeframe", text_color = tableStaticTextColor)
table.cell(table, 0, 2, timeframe1String, text_color = tableStaticTextColor)
table.cell(table, 0, 3, str.tostring(timeframe2), text_color = tableStaticTextColor)
// Change column
table.cell(table, 1, 1, "Chg%", text_color = tableStaticTextColor)
table.cell(table, 1, 2, btcPairPriceTimeframe1ChangePercent, text_color = btcPairPriceTimeframe1ChangePercentTextColor)
table.cell(table, 1, 3, btcPairPriceTimeframe2ChangePercent, text_color = btcPairPriceTimeframe2ChangePercentTextColor) |
FOREX MASTER PATTERN Companion Tool | https://www.tradingview.com/script/azaKIMyu-FOREX-MASTER-PATTERN-Companion-Tool/ | nnamdert | https://www.tradingview.com/u/nnamdert/ | 463 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//NOT A REQUIREMENT, BUT IT WOULD BE NICE TO RECEIVE A QUICK SHOUT OUT /CREDIT IF YOU USE THIS SCRIPT IN YOUR SCRIPT
// © nnamdert
//@version=5
indicator("FOREX MASTER PATTERN Companion Tool", overlay = true, max_lines_count = 500)
//BEGIN ENGULFING CANDLE SCRIPT
//BEGIN Get User Inputs - LINES===============================================================================================================//
show_lines = input.bool( //
defval = true, //
title = 'Show Lines on Chart?', //
tooltip = 'Checking this box will show lines on the chart. Unchecking it will hide only the chart lines, but everything else will remain.', //
group = 'Line Settings' //
) //
//HANDLES MAX_LINES_COUNTS ISSUE==============================================================================================================//
lineLimitInput = input.int( //
defval = 10, //
title = 'Max Lines to Show', //
tooltip = 'Adjust the number to increase / decrease the total number of lines shown on the chart. This setting only affects this Indicator.',//
group = 'Line Settings' //
) //
if array.size(line.all) > lineLimitInput //
for i = 0 to array.size(line.all) - lineLimitInput - 1 //
line.delete(array.get(line.all, i)) //
//CONTINUE Get User Inputs - LINES============================================================================================================//
int value_line_width_settings = input.int( //
defval = 2, //
title = 'Line Width', //
tooltip = 'coming soon',
group = 'Line Settings' //
) //
extend_lines_Bullish = input.bool( //
defval = false, //
title = 'Extend Bullish Lines?', //
tooltip = 'Checking will extend all lines from Bullish Engulfing candle areas to the right on the chart (past lanes will be visible too)', //
group = 'Line Settings' //
) ? extend.right : extend.none //
extend_lines_Bearish = input.bool( //
defval = false, //
title = 'Extend Bearish Lines?', //
tooltip = 'Checking will extend all lines from Bearish Engulfing candle areas to the right on the chart (past lanes will be visible too)', //
group = 'Line Settings' //
) ? extend.right : extend.none //
//END Get User Inputs - LINES=================================================================================================================//
//BEGIN Get User Inputs - ENGULFING AREA BOX==================================================================================================//
hide_engulfing_pattern_areas = input.bool( //
defval = false, //
title = 'Hide all Engulfing Pattern Shaded Area Boxes', // //
tooltip = '', //
group = 'ENGULFING PATTERNS - SHADED AREA BOXES' //
) //
//END Get User Inputs - ENGULFING AREA BOX====================================================================================================//
//BEGIN GET USER INPUTS - BOX COLOR SETTINGS==================================================================================================//
bearish_engulfing_box_color = input.color( //
defval = #9598a1, //
title = 'Bearish Engulfing Area Background Color', //
tooltip = 'This is the background color of a Bearish Engulfing Box', //
group = 'Box Settings - Bearish', //
confirm = false) //
bearish_engulfing_box_transp = input.int( //
defval = 80, //
title = 'Bearish Engulfing Area Background Color Transparency', //
tooltip = 'This is the transparency of the background color for the Bearish shaded area (box).', //
group = 'Box Settings - Bearish' //
) //
bearish_engulfing_box_border_color = input.color( //
defval = color.red, //
title = 'Bearish Engulfing Area Border Color', //
tooltip = 'This is the border color of a Bearish Engulfing Box', //
group = 'Box Settings - Bearish', //
confirm = false) //
bearish_engulfing_box_border_width = input.int( //
defval = 2, //
title = 'Bearish Engulfing Area Border Width', //
tooltip = 'This is the border width for the Bearish shaded area (box) created when a Bearish Engulfing candle formed.', //
group = 'Box Settings - Bearish' //
) //
bullish_engulfing_box_color = input.color( //
defval = #9598a1, //
title = 'Bullish Engulfing Area Background Color', //
tooltip = 'This is the background color of a Bullish Engulfing Box', //
group = 'Box Settings - Bullish', //
confirm = false) //
bullish_engulfing_box_transp = input.int( //
defval = 80, //
title = 'Bullish Engulfing Area Background Color Transparency', //
tooltip = 'This is the background color Transparency for the Bullish shaded area (box) created when a Bullish Engulfing candle formed.', //
group = 'Box Settings - Bullish' //
) //
bullish_engulfing_box_border_color = input.color( //
defval = color.lime, //
title = 'Bullish Engulfing Area Border Color', //
tooltip = 'This is the border color of a Bullish Engulfing Box', //
group = 'Box Settings - Bullish', //
confirm = false) //
bullish_engulfing_box_border_width = input.int( //
defval = 2, //
title = 'Bullish Engulfing Area Border Width', //
tooltip = 'This is the border width for the Bullish shaded area (box) created when a Bullish Engulfing candle formed.', //
group = 'Box Settings - Bullish' //
) //
//END GET USER INPUTS - BOX COLOR SETTINGS=============================++=====================================================================//
//END Get User Inputs - ENGULFING BARS========================================================================================================//
hide_engulfing_patterns = input.bool( //
defval=false, //
title = 'Hide all Engulfing Plotshapes and Color Candles?', //
group = 'ENGULFING PATTERNS - PLOTS AND CANDLES' //
) //
hide_bullish_engulfing_patterns = input.bool( //
defval=false, //
title ='Hide Bullish Engulfing Plotshapes and Color Candles (check to hide on chart)', //
group = 'Engulfing Candle Patterns and Plots') //
hide_bearish_engulfing_patterns = input.bool( //
defval=false, //
title ='Hide Bearish Engulfing Plotshapes and Color Candles (check to hide on chart)', //
group = 'Engulfing Candle Patterns and Plots') //
//END Get User Inputs - ENGULFING BARS========================================================================================================//
//BEGIN Get User Inputs - Size Factor=========================================================================================================//
bearish_engulfing_size = input.float( //
defval = 2, //
title = 'Bearish Engulfing Candle Size Ratio', //
minval = 2, //
maxval = 6, //
step = 1, //
tooltip = '2 is default. Better NOT to change. Engulfing candle size is TWO times the size of the engulfed candle. Choose between 2 and 6', //
group = 'Engulfing Candle Size Setting - Default is Recommended', //
confirm = false) //
bullish_engulfing_size = input.float( //
defval = 2, //
title = 'Bullish Engulfing Candle Size Ratio', //
minval = 2, //
maxval = 6, //
step = 1, //
tooltip = '2 is default. Better NOT to change. Engulfing candle size is TWO times the size of the engulfed candle. Choose between 2 and 6', //
group = 'Engulfing Candle Size Setting - Default is Recommended', //
confirm = false) //
//END Get User Inputs - Size Factor===========================================================================================================//
//BEGIN Get User Inputs - BAR COLORS==========================================================================================================//
bearish_engulfing_bar_color = input.color( //
defval = color.yellow, //
title = 'Bearish Engulfing Candle', //
tooltip = 'This is the color of a Bearish Engulfing Candle', //
group = 'Candle Colors', //
confirm = false) //
bullish_engulfing_bar_color = input.color( //
defval = color.yellow, //
title = 'Bullish Engulfing Candle', //
tooltip = 'This is the color of a Bullish Engulfing Candle', //
group = 'Candle Colors', //
confirm = false) //
//END Get User Inputs - BAR COLORS============================================================================================================//
//BEGIN BEARISH ENGULFING DEFINITION+=========================================================================================================//
atr = ta.atr(14) //
bar_bearish_engulfing = //
//CLOSE Price of the CURRENT Engulfing candle /session must be (less than) the OPEN Price of PREVIOUS session //
close <= open[1] //
//OPEN Price of the CURRENT Engulfing candle /session must be (greater than) the CLOSE Price of PREVIOUS session //
and open >= close[1] //
//Previous Session (before the engulfing candle) - the candle /session being Engulfed MUST be a GREEN candle /session //
and (close[1] > open[1]) //
//OPEN and CLOSE of the CURRENT Engulfing Session is (greater than or equal to) the previous candle /session being Engulfed and //
//is LARGER by a factor of 2 - 6 based on user input - (or basically twice as big) - ENGULFING CANDLE MUST BE RED [open - close = RED] //
and (open - close) > ((close[1] - open[1]) * bearish_engulfing_size) //
//CURRENT Engulfing candle /session needs to be (greater than) the atr //
and (open - close) > atr //
//END BEARISH ENGULFING DEFINITION============================================================================================================//
//BEGIN BULLISH ENGULFING DEFINITION==========================================================================================================//
bar_bullish_engulfing = //
close >= open[1] //
and open <= close[1] //
and (close[1] < open[1]) //
and (close - open) > ((open[1] - close[1]) * bullish_engulfing_size) //
and (close - open) > atr //
//END BULLISH ENGULFING DEFINITION============================================================================================================//
//BEGIN ENGULFING CANDLE BAR COLOR CODE=======================================================================================================//
barcolor( //
hide_engulfing_patterns or hide_bullish_engulfing_patterns ? na : bar_bullish_engulfing ? //
color.new(bullish_engulfing_bar_color, 0) : na, title = 'Bullish Engulfing') //
barcolor( //
hide_engulfing_patterns or hide_bearish_engulfing_patterns ? na : bar_bearish_engulfing ? //
color.new(bearish_engulfing_bar_color, 0) : na, title = 'Bearish Engulfing') //
//END ENGULFING CANDLE BAR COLOR CODE=========================================================================================================//
//BEGIN ENGULFING CANDLE ALERTS===============================================================================================================//
alertcondition( //
bar_bullish_engulfing, //
title = 'Bullish Engulfing Alert', //
message = 'Bullish Engulfing Pattern Identified' //
) //
alertcondition( //
bar_bearish_engulfing, //
title = 'Bearish Engulfing Alert', //
message = 'Bearish Engulfing Pattern Identified' //
) //
//END ENGULFING CANDLE ALERTS=================================================================================================================//
//BEGIN ENGULFING CANDLE PLOTS================================================================================================================//
plotshape(hide_engulfing_patterns or hide_bullish_engulfing_patterns ? na : //
bar_bullish_engulfing, //
title = 'Bullish Engulfing Plot', //
style = shape.arrowup, //
location = location.belowbar, //
color = color.new(#08f500, 0), //
size = size.large //
) //
plotshape(hide_engulfing_patterns or hide_bearish_engulfing_patterns ? na : //
bar_bearish_engulfing, //
title = 'Bearish Engulfing Plot', //
style = shape.arrowdown, //
location = location.abovebar, //
color = color.new(#f50014, 0), //
size = size.large //
) //
//END ENGULFING CANDLE PLOTS==================================================================================================================//
//BEGIN ENGULFING BOXES CODE==================================================================================================================//
var box[] Open_Bullish_Engulfing_Box = array.new_box() //
var box[] Closed_Open_Bullish_Engulfing_Box = array.new_box() //
var box[] Open_Bearish_Engulfing_Box = array.new_box() //
var box[] Closed_Open_Bearish_Engulfing_Box = array.new_box() //
// //
Bullish_Engulfing_Is_True = //
close >= open[1] //
and open <= close[1] //
and (close[1] < open[1]) //
and (close - open) > ((open[1] - close[1]) * bullish_engulfing_size) //
and (close - open) > atr //
// //
Bearish_Engulfing_Is_True = //
close <= open[1] //
and open >= close[1] //
and (close[1] > open[1]) //
and (open - close) > ((close[1] - open[1]) * bearish_engulfing_size) //
and (open - close) > atr //
// //
Still_Bull = ta.barssince(Bullish_Engulfing_Is_True) >= 1 //
Still_Bear = ta.barssince(Bearish_Engulfing_Is_True) >= 1 //
// //
if Bullish_Engulfing_Is_True and not hide_engulfing_pattern_areas //
array.push( //
Open_Bullish_Engulfing_Box, //
box.new(bar_index - 1, high[1], bar_index, low[1], //
border_color = color.new(bullish_engulfing_box_border_color, 0), //
border_width = bullish_engulfing_box_border_width, //
border_style = line.style_dotted, //
extend=extend.right, //
bgcolor=color.new(bullish_engulfing_box_color, bullish_engulfing_box_transp) //
)) //
// //
if Bearish_Engulfing_Is_True and not hide_engulfing_pattern_areas //
array.push( //
Open_Bearish_Engulfing_Box, //
box.new(bar_index - 1, high[1], bar_index, low[1], //
border_color = color.new(bearish_engulfing_box_border_color, 0), //
border_width=bearish_engulfing_box_border_width, //
border_style = line.style_dotted, //
extend=extend.right, //
bgcolor=color.new(bearish_engulfing_box_color, bearish_engulfing_box_transp) //
)) //
// //
for Area_Box in Open_Bullish_Engulfing_Box //
Breached_Level_Occurred = box.get_bottom(Area_Box) > low //
if Breached_Level_Occurred and Still_Bull //
box.set_extend(Area_Box, extend.none) //
box.set_right(Area_Box, bar_index) //
Closed_Area_Box = box.copy(Area_Box) //
array.push(Closed_Open_Bullish_Engulfing_Box, Closed_Area_Box) //
box.delete(Area_Box) //
// //
for Area_Box in Open_Bearish_Engulfing_Box //
Breached_Level_Occurred = box.get_top(Area_Box) < high //
if Breached_Level_Occurred and Still_Bear //
box.set_extend(Area_Box, extend.none) //
box.set_right(Area_Box, bar_index) //
Closed_Area_Box = box.copy(Area_Box) //
array.push(Closed_Open_Bullish_Engulfing_Box, Closed_Area_Box) //
box.delete(Area_Box) //
//END ENGULFING BOXES CODE====================================================================================================================//
// //
//BEGIN MIDLINE CODE==========================================================================================================================//
// BULLISH //
var float middleBody_Bullish = na //
// //
if bar_bullish_engulfing and show_lines //
middleBody_Bullish := ((open[1] + close[1]) / 2) // (high + low) / 2) //
midline = line.new(bar_index[1], middleBody_Bullish, bar_index+100, //
middleBody_Bullish, //
width = value_line_width_settings, //
color = color.new(color.green, 0), //
extend=extend_lines_Bullish //
) //
// //
else //
if bar_bearish_engulfing //
middleBody_Bullish := ((open[1] + close[1]) / 2) // or (high + low) / 2) //
midline = line.new(bar_index[1], middleBody_Bullish, bar_index+100, //
middleBody_Bullish, //
width = value_line_width_settings, //
color = color.new(color.red, 0), //
extend=extend_lines_Bullish //
) //
line.delete(midline) //
// //
NotValid_Bull = not bar_bearish_engulfing or bar_bullish_engulfing //
if NotValid_Bull //
middleBody_Bullish := na //
// //
// BEARISH LINES //
var float middleBody_Bearish = na //
// //
if bar_bearish_engulfing and show_lines //
middleBody_Bearish := ((open[1] + close[1]) / 2) // (high + low) / 2) // //
midline = line.new(bar_index[1], middleBody_Bearish, bar_index+100, //
middleBody_Bearish, //
width = value_line_width_settings, //
color = color.new(color.red, 0), //
extend=extend_lines_Bearish //
) //
// //
else //
if bar_bullish_engulfing //
middleBody_Bearish := ((open[1] + close[1]) / 2) // or (high + low) / 2) //
midline = line.new(bar_index[1], middleBody_Bearish, bar_index+100, //
middleBody_Bearish, //
width = value_line_width_settings, //
color = color.new(color.green, 0), //
extend=extend_lines_Bearish //
) //
line.delete(midline) //
// //
NotValid_Bear = not bar_bullish_engulfing or bar_bearish_engulfing //
if NotValid_Bear //
middleBody_Bearish := na //
//END MIDLINE SCRIPT==========================================================================================================================//
//END ENGULFING CANDLE SCRIPT
|
BBFIB | https://www.tradingview.com/script/mcHFxgMX-BBFIB/ | avsr90 | https://www.tradingview.com/u/avsr90/ | 32 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © avsr90
//@version=5
indicator('Regular/Intraday BB/FIB ', overlay=true, max_bars_back=5000)
//Regular/Intraday inputs
var grp1="regular/Intraday"
var grp2="regular"
var grp3="Fibonacci/Bolloinger Band"
var grp4="Fibonacci"
Regular=input.bool(defval=true,title="Regular",group=grp1,inline=grp2)
Intraday = input.bool(defval=false,title="Intraday",group=grp1,inline=grp2)
Fib=input.bool(defval=true,title="Fibonacci",group=grp3,inline=grp4)
BB=input.bool(defval=false,title="Bollinger Bands",group=grp3,inline=grp4)
//Intraday Length
Open= request.security(syminfo.tickerid ,"D",close[1],barmerge.gaps_off, barmerge.lookahead_on)
Nifnum= ta.change(Open)
Lb=int(math.max(1, nz(ta.barssince(Nifnum)) + 1))
//Length for moving average and Fib Levels
var gpr5=" Lenghths "
var gpr6="Len"
Len1= input.int(title="Len Reg BB ", defval=20,minval=2, maxval=1000,group=gpr5,inline=gpr6)
Len2=input.int(defval=20,title="Len Reg Fib",group=gpr5,inline=gpr6)
Len3=input.int(defval=20,title="Len for MA",group=gpr5,inline=gpr6)
//Oscillations
var gpr7="Input for Oscillation"
var gpr8="S"
Regular_Sou=input.string(title="Regular Osc",defval='SMA', options=['SMA', 'EMA', 'WMA', 'VWMA'],group=gpr7,inline=gpr8)
Lb_sou=input.string(title="Intraday Osc",defval='SMA', options=['SMA', 'WMA', 'VWMA'],group=gpr7,inline=gpr8)
MA_sou=input.string(title="Moving Avg Osc",defval='SMA', options=['SMA', "EMA",'WMA', 'VWMA'],group=gpr7,inline=gpr8)
//Source
Src = input(title="Source", defval=close,group="Source")
//Moving average calculations for BB
Ma7=Regular_Sou == 'SMA' ? ta.sma(Src, Len1) : Regular_Sou == 'EMA' ? ta.ema(Src, Len1) : Regular_Sou == 'WMA' ?
ta.wma(Src,Len1) : Regular_Sou == 'VWMA' ? ta.vwma(Src, Len1) : na
//Intra day moving average calculations
Ma8=Lb_sou == 'SMA' ? ta.sma(Src, Lb) : Lb_sou == 'WMA' ? ta.wma(Src,Lb) :
Lb_sou == 'VWMA' ? ta.vwma(Src, Lb) : na
//General Moving average Calculations
MA=MA_sou == 'SMA' ? ta.sma(Src,Len3 ) : MA_sou == 'EMA' ? ta.ema(Src,Len3): MA_sou == 'WMA' ? ta.wma(Src,Len3) :
MA_sou == 'VWMA' ? ta.vwma(Src, Len3) : na
//BB multiplier
Mul=input.float(defval=2.00,title="BB Multiplier",minval=2.00,maxval=100.00,group="Others")
//BB Calculations
Basisa=Intraday== true ? ta.stdev(Src,Lb): ta.stdev(Src,Len1)
Upb= Intraday and BB ==true ?Ma8+Basisa*Mul:Regular and BB ==true? Ma7+Basisa*2 :na
Dnb= Intraday and BB ==true ?Ma8-Basisa*Mul:Regular and BB ==true? Ma7-Basisa*2 :na
//Fibonacci Levels for BB
Dif=Upb-Dnb
Lev1=Upb-Dif*0.236
Lev2=Upb-Dif*0.382
Lev3=Upb-Dif*0.50
Lev4=Upb-Dif*0.618
Lev5=Upb-Dif*0.786
//Plots for BB
plot(MA,title="Moving Averegae",color=color.rgb(140, 8, 163))
U=plot(Upb,"Upb",color.green)
L=plot(Dnb,"Dnb",color.red)
U1=plot(Lev1,"23.6", color.blue)
U2=plot(Lev2,"38.2", color.blue)
M=plot(Lev3,"50", color.blue)
D1=plot(Lev4,"61.8", color.blue)
D2=plot(Lev5,"78.6", color.blue)
//Fill colors for BB
fill(U,U2,color.rgb(157, 225, 159),"UP zone",show_last=500)
fill(D1,L,color.rgb(228, 162, 162),"DN zone",show_last=500)
fill(U2,D1,color.rgb(216, 220, 233),"Gray Zone",show_last=500)
//Fibonacci High Low for Chart
//Fibonacci High and Low for Intra day
Hid=ta.highest(Src,Lb)
Lid=ta.lowest(Src,Lb)
//Fibonacci High and Low for Regular
Hid1=ta.highest(Src,Len2)
Lid1=ta.lowest(Src,Len2)
//Fibonacci for Intraday and Regular
Uph=Regular and Fib ==true ? Hid1:Intraday and Fib ?Hid:na
Dnh= Regular and Fib ==true ? Lid1:Intraday and Fib ?Lid:na
//Fibonacci Levels for Chart
Difh=Uph-Dnh
Le1=Uph-Difh*0.236
Le2=Uph-Difh*0.382
Le3=Uph-Difh*0.50
Le4=Uph-Difh*0.618
Le5=Uph-Difh*0.786
//Plots for Fibonacci levels for Chart
Uh=plot(Uph,"Upb",color.green)
Lh=plot(Dnh,"Dnb",color.red)
Uh1=plot(Le1,"23.6", color.blue)
Uh2=plot(Le2,"38.2", color.blue)
Mh=plot(Le3,"50", color.blue)
Dh1=plot(Le4,"61.8", color.blue)
Dh2=plot(Le5,"78.6", color.blue)
//Fill colors for Fibonacci Chart
fill(Uh,Uh2,color.rgb(157, 225, 159),"UP zone",show_last=500)
fill(Dh1,Lh,color.rgb(228, 162, 162),"DN zone",show_last=500)
fill(Uh2,Dh1,color.rgb(216, 220, 233),"Gray Zone",show_last=500)
//Labels for BB
Chper = time -time[1]
Chper := ta.change(Chper) > 0 ? Chper[1] : Chper
Lab1=label.new(x=time+Chper*30,y=Upb,xloc=xloc.bar_time,yloc=yloc.price,text="HID",textcolor=color.blue,
size=size.small,style=label.style_none)
max_bars_back(Lab1,500)
label.delete(Lab1[1])
Lab2=label.new(x=time+Chper*30,y=Lev1,xloc=xloc.bar_time,yloc=yloc.price,text="78.6/23.6",textcolor=color.blue,
size=size.small,style=label.style_none)
label.delete(Lab2[1])
max_bars_back(Lab2,500)
Lab3=label.new(x=time+Chper*30,y=Lev2,xloc=xloc.bar_time,yloc=yloc.price,text="61.8/38.2",textcolor=color.blue,
size=size.small,style=label.style_none)
label.delete(Lab3[1])
max_bars_back(Lab3,500)
Lab4=label.new(x=time+Chper*30,y=Lev3,xloc=xloc.bar_time,yloc=yloc.price,text="50",textcolor=color.blue,
size=size.small,style=label.style_none)
label.delete(Lab4[1])
max_bars_back(Lab4,500)
Lab5=label.new(x=time+Chper*30,y=Lev4,xloc=xloc.bar_time,yloc=yloc.price,text="38.2/61.8",textcolor=color.blue,
size=size.small,style=label.style_none)
label.delete(Lab5[1])
max_bars_back(Lab5,500)
Lab6=label.new(x=time+Chper*30,y=Lev5,xloc=xloc.bar_time,yloc=yloc.price,text="23.6/78.6",textcolor=color.blue,
size=size.small,style=label.style_none)
label.delete(Lab6[1])
max_bars_back(Lab6,500)
Lab7=label.new(x=time+Chper*30,y=Dnb,xloc=xloc.bar_time,yloc=yloc.price,text="LID",textcolor=color.white,
size=size.small,style=label.style_none)
label.delete(Lab7[1])
max_bars_back(Lab7,500)
plotcandle(open,high,low,close,"Bcandle",open>close? color.red:color.green)
//Labels for Fibonacci Chart
Lab11=label.new(x=time+Chper*30,y=Uph,xloc=xloc.bar_time,yloc=yloc.price,text="HID",textcolor=color.blue,
size=size.small,style=label.style_none)
max_bars_back(Lab11,500)
label.delete(Lab11[1])
Lab12=label.new(x=time+Chper*30,y=Le1,xloc=xloc.bar_time,yloc=yloc.price,text="78.6/23.6",textcolor=color.blue,
size=size.small,style=label.style_none)
label.delete(Lab12[1])
max_bars_back(Lab12,500)
Lab13=label.new(x=time+Chper*30,y=Le2,xloc=xloc.bar_time,yloc=yloc.price,text="61.8/38.2",textcolor=color.blue,
size=size.small,style=label.style_none)
label.delete(Lab13[1])
max_bars_back(Lab13,500)
Lab14=label.new(x=time+Chper*30,y=Le3,xloc=xloc.bar_time,yloc=yloc.price,text="50",textcolor=color.blue,
size=size.small,style=label.style_none)
label.delete(Lab14[1])
max_bars_back(Lab14,500)
Lab15=label.new(x=time+Chper*30,y=Le4,xloc=xloc.bar_time,yloc=yloc.price,text="38.2/61.8",textcolor=color.blue,
size=size.small,style=label.style_none)
label.delete(Lab15[1])
max_bars_back(Lab15,500)
Lab16=label.new(x=time+Chper*30,y=Le5,xloc=xloc.bar_time,yloc=yloc.price,text="23.6/78.6",textcolor=color.blue,
size=size.small,style=label.style_none)
label.delete(Lab16[1])
max_bars_back(Lab16,500)
Lab17=label.new(x=time+Chper*30,y=Dnh,xloc=xloc.bar_time,yloc=yloc.price,text="LID",textcolor=color.white,
size=size.small,style=label.style_none)
label.delete(Lab17[1])
max_bars_back(Lab17,500)
//Messages for Intraday and Regular combinations on Table
Msg1=Intraday and BB ? "You are on Intraday/BB":na
Msg2=Intraday and Fib ? "You are on Intraday/Fibonacci":na
Msg3=Regular and BB ? "You are on Regular/BB":na
Msg4=Regular and Fib ? "You are on Regular/Fibonacci":na
Msg5=(Intraday and BB and Intraday and Fib and Regular and BB and Regular and Fib) ?" Choose only one Combination":
(Intraday and BB and Intraday and Fib and Regular and BB)?" Choose only one Combination": (Intraday and BB and Intraday and Fib) ?
" Choose only one Combination":(Regular and BB and Regular and Fib) ?" Choose only one Combination":(Regular and BB and Intraday and BB) ?
" Choose only one Combination":(Intraday and Fib and Regular and Fib)?" Choose only one Combination": na
//TABLE
BorderThickness = 1
TableWidth = 0
Tableheight=0
TableLocation = input.string("bottom_right", title='Select Table Position',options=["top_left","top_center","top_right",
"Middle_left","middle_center","middle_right","bottom_left","bottom_center","bottom_right"] ,
tooltip="Default location is at top_ left")
TableTextSize = input.string("Auto", title='Select Table Text Size',options=["Auto","Huge","Large","Normal","Small",
"Tiny"] , tooltip="Default Text Size is Auto")
celltextsize = switch TableTextSize
"Auto" => size.auto
"Huge" => size.huge
"Large" => size.large
"Normal" => size.normal
"Small" => size.small
"Tiny" => size.tiny
var table t = table.new (position=TableLocation,columns=10,rows= 10, bgcolor=color.rgb(231, 231, 223),frame_color=color.black,frame_width=2,
border_color=color.gray,border_width=BorderThickness)
if barstate.islast
table.cell(t,1, 1, str.tostring(Msg1),text_size=celltextsize, width=TableWidth, text_color=color.blue,
height=Tableheight, text_halign=text.align_left)
table.cell(t,2, 1, str.tostring(Msg2),text_size=celltextsize, width=TableWidth, text_color= color.blue,
height=Tableheight, text_halign=text.align_left)
table.cell(t,3, 1, str.tostring(Msg3),text_size=celltextsize, width=TableWidth, text_color=color.blue,
height=Tableheight, text_halign=text.align_left)
table.cell(t,4, 1, str.tostring(Msg4),text_size=celltextsize, width=TableWidth, text_color= color.blue,
height=Tableheight, text_halign=text.align_left)
table.cell(t,5, 1, str.tostring(Msg5),text_size=celltextsize, width=TableWidth, text_color= color.red,
height=Tableheight, text_halign=text.align_left)
|
Odd_Custom Candle Calendar Day | https://www.tradingview.com/script/eFFhQYHL-Odd-Custom-Candle-Calendar-Day/ | OddLogic1618 | https://www.tradingview.com/u/OddLogic1618/ | 33 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OddLogic1618
//@version=5
//Create candles based on calendar days, not market days
indicator("Odd_Custom Candle Calendar Day", max_lines_count = 500, max_boxes_count = 500)
in_tf_multi = input.int(13, "Custom Candle Day Multiplier")
in_start_date = input.time(timestamp("01 Jan 2022 00:00 +0500"), "Start Date")
in_candle_margin = input.int(1, "Margin between candles", tooltip = "Creates margins based on calendar time, so if bar opens or closes during off days, margin may have no or reduced effect.")
in_candle_up_c = input.color(color.green, "Up Color")
in_candle_dw_c = input.color(color.red, "Down Color")
if in_tf_multi % timeframe.multiplier != 0
o = "1"
for i = 2 to in_tf_multi
if in_tf_multi % i == 0
o := o + ", " + str.tostring(i)
runtime.error("Timeframe must be a factor of the Custom TF Period, try " + o)
if not str.contains(timeframe.period, "D")
runtime.error("Switch to a Day Resolution")
u_period = 86400000 * in_tf_multi
c_margin = 86400000 * in_candle_margin
var float c_open = na
var float c_high = na
var float c_low = na
var float c_close = na
var bar_start = in_start_date
var mid_point = bar_start + (u_period / 2)
var box cur_box = na
var line cur_line = na
color cur_color = na
if time >= in_start_date
var next_start = bar_start + u_period
if time >= next_start
bar_start := next_start
next_start := next_start + u_period
mid_point := bar_start + (u_period / 2)
c_open := na
c_high := na
c_low := na
c_close := na
cur_box := na
cur_line := na
if na(c_open)
c_open := open
if c_high < high or na(c_high)
c_high := high
if c_low > low or na(c_low)
c_low := low
c_close := close
cur_color := c_close < c_open ? in_candle_dw_c : in_candle_up_c
if na(cur_box)
cur_box := box.new(bar_start + c_margin, c_close, next_start - c_margin, c_open, border_color = cur_color, border_width = 1, xloc = xloc.bar_time, bgcolor = cur_color)
cur_line := line.new(mid_point, c_high, mid_point, c_low, xloc = xloc.bar_time, color = cur_color, width = 1)
else
box.set_top(cur_box, c_close)
box.set_bgcolor(cur_box, cur_color)
box.set_border_color(cur_box, cur_color)
line.set_y1(cur_line, c_high)
line.set_y2(cur_line, c_low)
line.set_color(cur_line, cur_color)
//Invisible plots to display values
p_color = color.new(cur_color, 100)
plot(c_open , "Open" , color = p_color)
plot(c_high , "High" , color = p_color)
plot(c_low , "Low" , color = p_color)
plot(c_close, "Close" , color = p_color) |
Laguerre Stochastic | Adulari | https://www.tradingview.com/script/R2deCabt-Laguerre-Stochastic-Adulari/ | Adulari | https://www.tradingview.com/u/Adulari/ | 16 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ©Adulari
// @version=5
indicator('Laguerre Stochastic | Adulari', timeframe='',precision=2)
// Inputs
alpha = input.float(title='Alpha', minval=0, maxval=1, step=0.1, defval=0.2,group='General Settings')
kSmoothing = input.int(1,minval=1,title='%K Smoothing',group='General Settings')
dSmoothing = input.int(3,minval=2,title='%D Smoothing',group='General Settings')
maType = input.string('SMA',options=['SMA','EMA','RMA','WMA','VWMA','HMA'],title='MA Type',group='General Settings')
smoothingType = input.string('SMA',options=['SMA','EMA','RMA','WMA','VWMA','HMA'],title='Smoothing Type',group='General Settings')
signals = input.bool(false,title='Signals',tooltip='Show signals when value crosses below oversold line or crosses above overbought line.',group='General Settings')
// Functions
ma(float source, simple int length, string maType) =>
switch maType
'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)
'HMA' => ta.hma(source, length)
// Calculations
k = ma(ta.stoch(close, high, low, 1),kSmoothing,maType)
gamma = 1 - alpha
L0 = 0.0
L0 := (1 - gamma) * k + gamma * nz(L0[1])
L1 = 0.0
L1 := -gamma * L0 + nz(L0[1]) + gamma * nz(L1[1])
L2 = 0.0
L2 := -gamma * L1 + nz(L1[1]) + gamma * nz(L2[1])
L3 = 0.0
L3 := -gamma * L2 + nz(L2[1]) + gamma * nz(L3[1])
cu = (L0 > L1 ? L0 - L1 : 0) + (L1 > L2 ? L1 - L2 : 0) + (L2 > L3 ? L2 - L3 : 0)
cd = (L0 < L1 ? L1 - L0 : 0) + (L1 < L2 ? L2 - L1 : 0) + (L2 < L3 ? L3 - L2 : 0)
temperature = cu + cd == 0 ? -1 : cu + cd
k := (temperature == -1 ? 0 : cu / temperature)*100
d = ma(k, dSmoothing, smoothingType)
// Colors
beColor = #675F76
buColor = #a472ff
// Plots
kPlot = plot(k,color=buColor,title='%K',linewidth=1)
dPlot = plot(d,color=beColor,title='%D',linewidth=1)
fill(kPlot,dPlot,color=k>d ? color.new(buColor,95) : color.new(beColor,95),title='Trend Fill')
hline(80,title='Upper Line',color=beColor)
hline(50,title='Middle Line',color=color.new(color.gray,50))
hline(20,title='Lower Line',color=buColor)
plotshape(signals ? ta.crossunder(k,20) ? 20 : na : na,'Bullish Signal',style=shape.circle,location=location.absolute,size=size.tiny,color=buColor)
plotshape(signals ? ta.crossover(k,80) ? 80 : na : na,'Bearish Signal',style=shape.xcross,location=location.absolute,size=size.tiny,color=beColor) |
DR/IDR Candles [LuxAlgo] | https://www.tradingview.com/script/wRtmtWIQ-DR-IDR-Candles-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,824 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("DR/IDR Candles [LuxAlgo]",overlay=true
, max_lines_count = 500
, max_boxes_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
useRegular = input(true, '', inline = 'regular')
regularSession = input.session('0930-1030', 'Regular', inline = 'regular')
useOvernight = input(true, '', inline = 'overnight')
overnightSession = input.session('0300-0400', 'Overnight', inline = 'overnight')
tzOffset = input.int(-5, 'UTC Offset')
//Retracements
reverse = input(false, 'Reverse', group = 'Fibonacci Retracements')
//Fib 0.236
fib236 = input(false, '', inline = '0', group = 'Fibonacci Retracements')
fib236Value = input(0.236, '', inline = '0', group = 'Fibonacci Retracements')
fib236Css = input(color.yellow, '', inline = '0', group = 'Fibonacci Retracements')
//Fib 0.382
fib382 = input(false, '', inline = '0', group = 'Fibonacci Retracements')
fib382Value = input(0.382, '', inline = '0', group = 'Fibonacci Retracements')
fib382Css = input(color.fuchsia, '', inline = '0', group = 'Fibonacci Retracements')
//Fib 0.5
fib5 = input(true, '', inline = '5', group = 'Fibonacci Retracements')
fib5Value = input(0.5, '', inline = '5', group = 'Fibonacci Retracements')
fib5Css = input(color.red, '', inline = '5', group = 'Fibonacci Retracements')
//Fib 0.618
fib618 = input(false, '', inline = '5', group = 'Fibonacci Retracements')
fib618Value = input(0.618, '', inline = '5', group = 'Fibonacci Retracements')
fib618Css = input(color.aqua, '', inline = '5', group = 'Fibonacci Retracements')
//Fib 0.782
fib782 = input(false, '', inline = '782', group = 'Fibonacci Retracements')
fib782Value = input(0.782, '', inline = '782', group = 'Fibonacci Retracements')
fib782Css = input(color.green, '', inline = '782', group = 'Fibonacci Retracements')
fromTarget = input.string('IDR', 'From', options = ['DR', 'IDR'], group = 'Fibonacci Retracements')
//Display elements
showDR = input(true, 'Show DR' , group = 'Style')
showIDR = input(true, 'Show IDR' , group = 'Style')
showWicks = input(true, 'Show Wicks' , group = 'Style')
showFill = input(true, 'Show Range Fill' , group = 'Style')
showArea = input(true, 'Show Outside Areas' , group = 'Style')
showBg = input(true, 'Highlight Session' , group = 'Style')
//Colors
aboveLvlCss = input(#2157f3, 'Line Colors', inline = 'lvl_colors', group = 'Style')
insideLvlCss = input(color.gray, '' , inline = 'lvl_colors', group = 'Style')
belowLvlCss = input(#ff5d00, '' , inline = 'lvl_colors', group = 'Style')
aboveAreaCss = input(color.new(#2157f3, 80), 'Area Colors', inline = 'area_colors', group = 'Style')
insideAreaCss = input(color.new(color.gray, 90), '' , inline = 'area_colors', group = 'Style')
belowAreaCss = input(color.new(#ff5d00, 80), '' , inline = 'area_colors', group = 'Style')
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
avg(val, idr_max, idr_min, dr_max, dr_min)=>
var float fib = na
max = fromTarget == 'IDR' ? idr_max : dr_max
min = fromTarget == 'IDR' ? idr_min : dr_min
if reverse
fib := val * min + (1 - val) * max
else
fib := val * max + (1 - val) * min
//-----------------------------------------------------------------------------}
//Global variables
//-----------------------------------------------------------------------------{
var float dr_max = na
var float dr_min = na
var float idr_max = na
var float idr_min = na
var float max = na
var float min = na
var int start_anchor = na
var int end_anchor = na
var int count = 0
var box count_bx = na
var line upper_wick = na
var line lower_wick = na
var line dr_range_upper = na
var line dr_range_lower = na
var line idr_range_upper = na
var line idr_range_lower = na
var tz = str.format('UTC{0}{1}', tzOffset >= 0 ? '+' : '', tzOffset)
n = bar_index
regular_session = time(timeframe.period, regularSession, tz) and useRegular
overnight_session = time(timeframe.period, overnightSession, tz) and useOvernight
session = regular_session or overnight_session
//-----------------------------------------------------------------------------}
//Set DR/IDR
//-----------------------------------------------------------------------------{
if session and not session[1]
dr_max := high
dr_min := low
idr_max := math.max(close, open)
idr_min := math.min(close, open)
if showDR
dr_range_upper := line.new(n, dr_max, n, dr_max)
dr_range_lower := line.new(n, dr_min, n, dr_min)
if showIDR
idr_range_upper := line.new(n, idr_max, n, idr_max, style = line.style_dashed)
idr_range_lower := line.new(n, idr_min, n, idr_min, style = line.style_dashed)
start_anchor := n
count := 0
else if not session and session[1]
max := dr_max
min := dr_min
if showWicks
upper_wick := line.new(n, max, n, max)
lower_wick := line.new(n, min, n, min)
if showFill
count_bx := box.new(n, dr_max, n, dr_min, border_color = na)
end_anchor := n
else if session
dr_max := math.max(high, dr_max)
dr_min := math.min(low, dr_min)
idr_max := math.max(close, open, idr_max)
idr_min := math.min(close, open, idr_min)
if showDR
line.set_xy2(dr_range_upper, n, dr_max)
line.set_y1(dr_range_upper, dr_max)
line.set_xy2(dr_range_lower, n, dr_min)
line.set_y1(dr_range_lower, dr_min)
if showIDR
line.set_xy2(idr_range_upper, n, idr_max)
line.set_y1(idr_range_upper, idr_max)
line.set_xy2(idr_range_lower, n, idr_min)
line.set_y1(idr_range_lower, idr_min)
if not session
count += low < idr_max and high > idr_min ? 1 : 0
max := math.max(high, max)
min := math.min(low, min)
lvl_css = close > dr_max ? aboveLvlCss
: close < dr_min ? belowLvlCss
: insideLvlCss
area_css = close > dr_max ? aboveAreaCss
: close < dr_min ? belowAreaCss
: insideAreaCss
//Show DR/IDR ranges
if showDR
line.set_x2(dr_range_upper, n)
line.set_x2(dr_range_lower, n)
line.set_color(dr_range_upper, lvl_css)
line.set_color(dr_range_lower, lvl_css)
if showIDR
line.set_x2(idr_range_upper, n)
line.set_x2(idr_range_lower, n)
line.set_color(idr_range_upper, lvl_css)
line.set_color(idr_range_lower, lvl_css)
//Show outside wicks
if showWicks
line.set_xy2(upper_wick, int(math.avg(n, start_anchor)), max)
line.set_x1(upper_wick, int(math.avg(n, start_anchor)))
line.set_xy2(lower_wick, int(math.avg(n, start_anchor)), min)
line.set_x1(lower_wick, int(math.avg(n, start_anchor)))
line.set_color(upper_wick, lvl_css)
line.set_color(lower_wick, lvl_css)
//Show interior fill
if showFill
box.set_right(count_bx, end_anchor + count)
box.set_bgcolor(count_bx, area_css)
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot_idr_max = plot(idr_max, 'Rolling IDR Maximum', display = display.none)
plot_idr_min = plot(idr_min, 'Rolling IDR Minimum', display = display.none)
plot_close = plot(close, display = display.none, editable = false)
plot_dr_max = plot(dr_max, 'Rolling DR Maximum', display = display.none)
plot_dr_min = plot(dr_min, 'Rolling DR Minimum', display = display.none)
//Fills
fill(plot_dr_max, plot_close
, showArea and not session and not ta.cross(close, dr_max) and close > dr_max ? aboveAreaCss : na
, 'Upper Fill')
fill(plot_close, plot_dr_min
, showArea and not session and not ta.cross(close, dr_min) and close < dr_min ? belowAreaCss : na
, 'Lower Fill')
//Retracements
plot(fib236 ? avg(fib236Value, idr_max, idr_min, dr_max, dr_min) : na, 'Fib 0.236', session ? na : fib236Css)
plot(fib382 ? avg(fib382Value, idr_max, idr_min, dr_max, dr_min) : na, 'Fib 0.382', session ? na : fib382Css)
plot(fib5 ? avg(fib5Value, idr_max, idr_min, dr_max, dr_min) : na, 'Fib 0.5', session ? na : fib5Css)
plot(fib618 ? avg(fib618Value, idr_max, idr_min, dr_max, dr_min) : na, 'Fib 0.618', session ? na : fib618Css)
plot(fib782 ? avg(fib782Value, idr_max, idr_min, dr_max, dr_min) : na, 'Fib 0.782', session ? na : fib782Css)
//Highlight session
bgcolor(showBg and session ? color.new(color.gray, 80) : na)
//-----------------------------------------------------------------------------} |
Flying Dragon Trend Indicator | https://www.tradingview.com/script/L2wC1FSC-Flying-Dragon-Trend-Indicator/ | MarkoP010 | https://www.tradingview.com/u/MarkoP010/ | 251 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MarkoP010 2023
//@version=5
//Indicator plots user selectable Moving Average lines and a colored trend band between the MA lines. The trend bands can be turned off individually if required.
//Trend pivot indicators are shown by selected risk level either when there is MA crossover with price (Leading MA Offset1 on Highest risk level, Lagging MA on Low risk level) or three bands with the same color at the same time (on Lowest risk level, Leading MA Offset1 crossover with Lagging MA). Pivot indicators can be turned off if required.
//The Offset option shifts the selected MA with the set number of steps to the right. That is where the Magic happens and the Dragon roars!
//Indicator version history:
//Version 1 - Initial script
//Version 2 - Bug fix for Lowest risk level to show the indicator
//Version 3 - Alert function added, enabled when indicators are on
indicator("Flying Dragon Trend Indicator", shorttitle="Flying Dragon Trend Indicator", overlay=true)
//Moving Averages function
MA(source, length, type) =>
type == "EMA" ? ta.ema(source, length) :
type == "HMA" ? ta.hma(source, length) :
type == "RMA" ? ta.rma(source, length) :
type == "SMA" ? ta.sma(source, length) :
type == "SWMA" ? ta.swma(source) :
type == "VWMA" ? ta.vwma(source, length) :
type == "WMA" ? ta.wma(source, length) :
na
//Indicator options
riskLevel = input.string(defval="Medium", title="Risk Level", options=["Highest", "High", "Medium", "Low", "Lowest"], inline="Options", group="Indicator Options")
indicatorsOn = input(defval=true, title="Indicators", inline="Options", tooltip="Turn on or off pivot indicators. When risk level Highest then Leading MA Offset1 crossover with price triggers the indicator, when Low then Lagging MA crossover with price, when Lowest then all the Bands are the same color (Leading MA Offset1 crossover with Lagging MA). Alerts are enabled when indicators are on. Create Alert on selected equity and timeframe, select on Condition this indicator and Any alert () function call, Create.", group="Indicator Options")
//Inputs
ma1Type = input.string(defval="HMA", title="", inline="MA1", options=["EMA", "HMA", "RMA", "SMA","SWMA", "VWMA", "WMA"], group="Leading Moving Average")
ma1Length = input.int(defval=35, title="",minval=1, inline="MA1", group="Leading Moving Average")
ma1Source = input(defval=close, title="", tooltip="For short timeframes, minutes to hours, instead of Default values try Lowest risk level and HMA75 with Offsets 0,1,4 and SMA12 with Offset 6.", inline="MA1", group="Leading Moving Average")
ma1Color = input(defval=color.purple, title="", inline="MA-1", group="Leading Moving Average")
ma1Offset = input.int(defval=0, title="Offset1 Steps", minval=0, maxval=10, step=1, tooltip="The Magic happens here! The offset to move the line to the right.", inline="MA-1", group="Leading Moving Average")
ma1 = MA(ma1Source, ma1Length, ma1Type)[ma1Offset]
ma2Color = input(defval=color.lime, title="", inline="MA-2", group="Leading Moving Average")
ma2Offset = input.int(defval=4, title="Offset2 Steps", minval=0, maxval=10, step=1, tooltip="The Magic happens here! The offset to move the line to the right.", inline="MA-2", group="Leading Moving Average")
ma2 = ma1[ma2Offset]
ma3Color = input(defval=color.aqua, title="", inline="MA-3", group="Leading Moving Average")
ma3Offset = input.int(defval=6, title="Offset3 Steps", minval=0, maxval=10, step=1, tooltip="The Magic happens here! The offset to move the line to the right.", inline="MA-3", group="Leading Moving Average")
ma3 = ma1[ma3Offset]
ma4Type = input.string(defval="SMA", title="", inline="MA4", options=["EMA", "HMA", "RMA", "SMA","SWMA", "VWMA", "WMA"], group="Lagging Moving Average")
ma4Length = input.int(defval=22, title="",minval=1, inline="MA4", group="Lagging Moving Average")
ma4Source = input(defval=close, title="", inline="MA4", group="Lagging Moving Average")
ma4Color = input(defval=color.yellow, title="", inline="MA-4", group="Lagging Moving Average")
ma4Offset = input.int(defval=2, title="Offset Steps", minval=0, maxval=10, step=1, tooltip="The Magic happens here! The offset to move the line to the right.", inline="MA-4", group="Lagging Moving Average")
ma4 = MA(ma4Source, ma4Length, ma4Type)[ma4Offset]
bandTransp = input.int(defval=60, title="Band Transparency", minval=20, maxval=80, step=10, group="Banding")
useBand1 = input(defval=true, title="Band 1", inline="Band", group="Banding")
band1Transp = useBand1 ? bandTransp : 100
band1clr = ma1 > ma2 ? color.new(#00ff00, transp=band1Transp) : color.new(#ff0000, transp=band1Transp)
useBand2 = input(defval=true, title="Band 2", inline="Band", group="Banding")
band2Transp = useBand2 ? bandTransp : 100
band2clr = ma1 > ma3 ? color.new(#00ff00, transp=band2Transp) : color.new(#ff0000, transp=band2Transp)
useBand3 = input(defval=true, title="Band 3", tooltip="Up trend green, down trend red. Colors get reversed if MA1 lenght is greater than MA2 lenght, or they are different type and MA2 quicker. In that case, just reverse your selections for MA1 and MA2, or let it be as is.", inline="Band", group="Banding")
band3Transp = useBand3 ? bandTransp : 100
band3clr = ma1 > ma4 ? color.new(#00ff00, transp=band3Transp) : color.new(#ff0000, transp=band3Transp)
//Graphs
piirto1 = plot(ma1, color = ma1Color, title="MA1")
piirto2 = plot(ma2, color = ma2Color, title="MA2")
piirto3 = plot(ma3, color = ma3Color, title="MA3")
piirto4 = plot(ma4, color = ma4Color, title="MA4")
fill(piirto1, piirto2, color=band1clr)
fill(piirto1, piirto3, color=band2clr)
fill(piirto1, piirto4, color=band3clr)
//Indicator plot conditions
longCondition = riskLevel == "Highest" ? ma1Source > ma1 : riskLevel == "High" ? ma1Source > ma2 : riskLevel == "Medium" ? ma1Source > ma3 : riskLevel == "Low" ? ma4Source > ma4 : riskLevel == "Lowest" ? ma1 > ma4 : na
shortCondition = riskLevel == "Highest" ? ma1Source < ma1 : riskLevel == "High" ? ma1Source < ma2 : riskLevel == "Medium" ? ma1Source < ma3 : riskLevel == "Low" ? ma4Source < ma4 : riskLevel == "Lowest" ? ma1 < ma4 : na
pivotUp = longCondition and shortCondition[1] and indicatorsOn ? true : na
pivotDown = shortCondition and longCondition[1] and indicatorsOn ? true : na
plotshape(pivotUp, title="Up", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(pivotDown, title="Down", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small)
//Alerts
if pivotUp
alertMessage = syminfo.ticker + ' - ' + timeframe.period + ": Pivot Up!"
alert(alertMessage, alert.freq_once_per_bar_close)
if pivotDown
alertMessage = syminfo.ticker + ' - ' + timeframe.period + ": Pivot Down!"
alert(alertMessage, alert.freq_once_per_bar_close)
//End
|
Custom_AVWAP_Harpal's-Anchors | https://www.tradingview.com/script/WQlZvYUJ-Custom-AVWAP-Harpal-s-Anchors/ | ak2k2 | https://www.tradingview.com/u/ak2k2/ | 13 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ak2k2
//@version=5
indicator("Custom_AAVWAP", overlay=true,max_labels_count = 500,max_lines_count = 500, max_bars_back = 2000)
lb = input.int(100,"Lookback (# of Periods)",1, 1000,1)
len = lb
src = hlc3
hi = ta.highest(src,len)
hiOffset = - ta.highestbars(src,len)
lo = ta.lowest(src,len)
loOffset = - ta.lowestbars(src,len)
src_vol = volume
hv = ta.highest(src_vol, len)
hvOffset = -ta.highestbars(src_vol, len)
f_avwap(src, date, plotcolor) =>
float[] array_sumSrc = array.new_float( date,na)
float[] array_sumVol = array.new_float( date,na)
// float[] array_final = array.new_float( date,na)
if date>0 and array.size(array_sumSrc)>0
for i=date-1 to 0
sumSrc = src[i] * volume[i]
sumVol = volume[i]
array.set(array_sumSrc,i,sumSrc + sumSrc[1+i])
array.set(array_sumVol,i,sumVol + sumVol[1+i])
finalVal=array.sum(array_sumSrc) / array.sum(array_sumVol)
if barstate.islast
line.new(bar_index[i+1],finalVal,bar_index[i],finalVal,color=plotcolor)
ath_dt = bar_index-bar_index[hiOffset]
atl_dt = bar_index-bar_index[loOffset]
athv_dt = bar_index-bar_index[hvOffset]
fh=f_avwap(src, ath_dt, color.red)
fl = f_avwap(src,atl_dt, color.green)
fhv = f_avwap(src,athv_dt, color.aqua)
|
TOTAL:(RSI+TSI) | https://www.tradingview.com/script/PyLDakYk/ | gokhanpirnal | https://www.tradingview.com/u/gokhanpirnal/ | 20 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gokhanpirnal
//@version=5
indicator('TOTAL:(RSI+TSI)', shorttitle='TOTAL:(RSI+TSI)', format=format.price, precision=4, timeframe='')
long = input(title='TSI Long Length', defval=1)
short = input(title='TSI Short Length', defval=1)
signal = input(title='TSI Signal Length', defval=2)
price = close
double_smooth(src, long, short) =>
fist_smooth = ta.ema(src, long)
ta.ema(fist_smooth, short)
pc = ta.change(price)
double_smoothed_pc = double_smooth(pc, long, short)
double_smoothed_abs_pc = double_smooth(math.abs(pc), long, short)
tsi_value = 100 * (double_smoothed_pc / double_smoothed_abs_pc)
len = input.int(2, minval=1, title='RSI Length')
src = input(close, 'Source')
up = ta.rma(math.max(ta.change(src), 0), len)
down = ta.rma(-math.min(ta.change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
toplam = tsi_value + ta.ema(tsi_value, signal) + rsi
plot(toplam, 'Toplam', color=color.new(#00FF00, 0), linewidth=2)
hline(300, title='Üst Sınır', color=#00FFFF)
hline(-200, title='Alt Sınır', color=#00FFFF) |
Simple STRAT Tool by nnam | https://www.tradingview.com/script/Do5QCtMM-Simple-STRAT-Tool-by-nnam/ | nnamdert | https://www.tradingview.com/u/nnamdert/ | 167 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © nnamdert
//@version=5
//Feb 2023
indicator(title="Simple STRAT Tool by nnam", overlay=true)
//BEGIN Get User Inputs=========================================================================================================//
//USER INPUTS FOR LINES //
show_prices = input.bool( //
defval = true, //
title = 'Show Prices', //
tooltip = 'If checked, the indicator will show prices on the chart.', //
group = 'Price Settings' //
) //
show_current_price_label = input.bool( //
defval = true, //
title = 'Show Live Current Price', //
tooltip = 'If checked, the indicator will display the current price on the chart.', //
group = 'Price Settings' //
) //
//USER INPUT TO ONLY SHOW INSIDE BAR BREAKOUTS //
onlyone = input.bool( //
defval = false, //
title = 'Trade Inside Bars ONLY', //
tooltip = 'If checked, the indicator will only look for INSDIDE bars and exclude other candles.', //
group = 'Breakout Settings' //
) //
//BEGIN USER INPUTS BASIC LINE DISPLAY (show and extend lines etc.)=============================================================//
show_lines = input.bool( //
defval = true, //
title = 'Display Lines on Chart', //
tooltip = 'If this box is unchecked, NO lines will show on the chart - ALL lines will be hidden', //
group = 'Chart Display Settings - Show Lines / Extend Lines' //
) //
extend_lines = input.bool( //
defval = false, //
title = 'Extend Lines', // //
tooltip = 'If this box is checked, lines will be EXTENDED to the right on the chart', //
group = 'Chart Display Settings - Show Lines / Extend Lines' //
) ? extend.both : extend.right //
//END USE INPUTS BASIC LINE DISPLAY (show and extend lines etc.)================================================================//
//BEGIN Get User Inputs - BARS //
//BEGIN Get User Inputs - BAR COLORS //
color_code_candles = input.bool( //
defval=true, //
title = 'Color Code the Candles', //
tooltip='Turn on Color Coded Candles. Expansion. Contraction, Bullish and Bearish Candles will be shaded as listed below.', //
group = 'Set Color Coded Candle Colors' //
) //
inside_bar_color = input.color( //
defval = color.white, //
title = 'Inside Bar', //
tooltip = 'This is the color of the Strat Inside Bar - otherwise known as 1', //
group = 'Set Color Coded Candle Colors', //
//inline = 'inside outside', //
confirm = false) //
outside_bar_color = input.color( //
defval = color.yellow, //
title = 'Outside Bar', //
tooltip = 'This is the color of the Strat Outside Bar - otherwise known as 3', //
group = 'Set Color Coded Candle Colors', //
//inline = 'inside outside', //
confirm = false) //
twoup_bar_color = input.color( //
defval = color.lime, //
title = '2 UP Bar', //
tooltip = 'This is the color of the Strat 2 UP Bar', //
group = 'Set Color Coded Candle Colors', //
//inline = 'twobars', //
confirm = false) //
twodown_bar_color = input.color( //
defval = color.maroon, //
title = '2 DOWN Bar', //
tooltip = 'This is the color of the Strat 2 DOWN Bar', //
group = 'Set Color Coded Candle Colors', //
//inline = 'twobars', //
confirm = false) //
//END BAR COLORS INPUT //
//BEGIN LINE COLORS INPUT //
current_bar_upper_color = input.color( //
defval = color.new(color.orange, 0), //
title = 'Current Bar Upper Line Color', //
tooltip = 'These are the colors for the lines of the current bar', //
group = 'High / Low Lines Settings', //
inline = 'current_bar', //
confirm = false //
) //
current_bar_lower_color = input.color( //
defval = color.new(color.orange, 0), //
title = 'Current Bar Lower Line Color', //
tooltip = 'These are the colors for the lines of the current bar', //
group = 'High / Low Lines Settings', //
inline = 'current_bar', //
confirm = false //
) //
previous_bar_upper_color = input.color( //
defval = color.new(color.orange, 0), //
title = 'Previous Bar Upper Line Color', //
tooltip = 'These are the colors for the lines of the previous bar', //
group = 'High / Low Lines Settings', //
inline = 'previous_bar', //
confirm = false //
) //
previous_bar_lower_color = input.color( //
defval = color.new(color.orange, 0), //
title = 'Previous Bar Upper Line Color', //
tooltip = 'These are the colors for the lines of the previous bar', //
group = 'High / Low Lines Settings', //
inline = 'previous_bar', //
confirm = false //
) //
one_only_bar_upper_color = input.color( //
defval = color.new(color.yellow, 0), //
title = 'Inside Bar Upper Line Color', //
tooltip = 'These are the colors for the lines when "Trade Inside Bars ONLY" is checked', //
group = 'High / Low Lines Settings', //
inline = 'inside_bar', //
confirm = false //
) //
one_only_bar_lower_color = input.color( //
defval = color.new(color.yellow, 0), //
title = 'Inside Bar Upper Line Color', //
tooltip = 'These are the colors for the lines when "Trade Inside Bars ONLY" is checked', //
group = 'High / Low Lines Settings', //
inline = 'inside_bar', //
confirm = false //
) //
//END Get User Inputs - BAR COLORS //
//Begin Bar Colors Script=======================================================================================================//
barcolor(color_code_candles and (high > high[1] and low < low[1]) ? //
color.new(outside_bar_color, 0) : na, title = '3 Outside Bar') //
// //
barcolor(color_code_candles and (high > high[1] and low >= low[1]) ? //
color.new(twoup_bar_color, 0) : na, title = '2 up') //
// //
barcolor(color_code_candles and (high <= high[1] and low < low[1]) ? //
color.new(twodown_bar_color, 0) : na, title = '2 down') //
// //
barcolor(color_code_candles and (high <= high[1] and low >= low[1]) ? //
color.new(inside_bar_color, 0) : na, title = '1 Inside Bar') // //
//End Bar Colors================================================================================================================//
// //
//Strat Calculations============================================================================================================//
green = close >= open //
red = close < open //
one = (high <= high[1]) and (low >= low[1]) //
twoUp = (high > high[1]) and (low >= low[1]) //
twoDown = (high <= high[1]) and (low < low[1]) //
three = (high > high[1]) and (low < low[1]) //
openTime = time //
lowPrice = low //
highPrice = high //
not_inside = (not twoUp and not twoDown and not three) //
// //
//BEGINLINESSCRIPT==============================================================================================================//
////THE LINES BELOW ARE FOR ALL CANDLES INCLUDING INSIDE, OUTSIDE, UP AND DOWN BARS=============================================//
//Calculate and plot the highest high and lowest low for the previous bar (for all scenarios) //
highestHigh = ta.highest(high, 1)[1] //
lowestLow = ta.lowest(low, 1)[1] //
// //
highestHigh_1 = ta.highest(high, 1)[2] //
var line highestline_1 = na //
var line lowestline_1 = na //
// //
var line lowline = na //
var line highline = na //
// //
var line insidehighline = na //
var line insidelowline = na //
// //
lowestLow_1 = ta.lowest(low, 1)[2] //
//Plot Lines //
if highestHigh and barstate.islast and show_lines and onlyone and one == true //
insidehighline := line.new(bar_index[1], //
highestHigh, bar_index, //
highestHigh, //
color = color.new(color.yellow, 0), //
extend=extend_lines) //
line.delete(insidehighline[1]) //
else //
if highestHigh and barstate.islast and show_lines and not onlyone //
highline := line.new(bar_index[1], //
highestHigh, bar_index, //
highestHigh, color = color.new(#fdeb43, 0), //
extend=extend_lines) //
line.delete(highline) //
// //
if lowestLow and barstate.islast and show_lines and onlyone and one == true //
insidelowline := line.new(bar_index[1], //
lowestLow, bar_index, //
lowestLow, color = color.new(color.yellow, 0), //
extend = extend_lines) //
line.delete(insidelowline[1]) //
else //
if lowestLow and barstate.islast and show_lines and not onlyone //
lowline := line.new(bar_index[1], //
lowestLow, bar_index, //
lowestLow, color = color.new(#fdeb43, 0), //
extend = extend_lines) //
line.delete(lowline) //
// //
// //
//THE LINES BELOW ARE FOR ALL CANDLES INCLUDING INSIDE, OUTSIDE, UP AND DOWN BARS //
if highestHigh_1 and show_lines and not onlyone //
highestline_1 := line.new(bar_index[2], //
highestHigh, bar_index, //
highestHigh, color = color.new(color.orange, 0), //
extend=extend_lines) //
line.delete(highestline_1[2]) //
else //
na //
// //
if lowestLow_1 and show_lines and not onlyone //
lowestline_1 := line.new(bar_index[2], //
lowestLow, bar_index, //
lowestLow, color = color.new(color.orange, 0), //
extend = extend_lines) //
line.delete(lowestline_1[2]) //
else //
na //
//ENDLINESCRIPT=================================================================================================================//
//BEGINPRICELABELSCRIPT=========================================================================================================//
var label high_label1 = na //
var label high_label2 = na //
var label low_label1 = na //
var label low_label2 = na //
value_high = high[1] //
value_low = low[1] //
value_high_prev = high[2] //
value_low_prev = low[2] //
//High Label Inside Bar Only //
//label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family) //
if barstate.islast and one and onlyone and show_prices //
high_label1 := label.new(bar_index+4, //
y=value_high, text = str.tostring(value_high), //
style = label.style_none, //
color = color.new(color.orange, 0), //
textcolor = color.orange) //
label.delete(high_label1[1]) //
//Low Label Inside Bar Only //
//label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family) //
if barstate.islast and one and onlyone and show_prices //
low_label1 := label.new(bar_index+4, //
y=value_low, text = str.tostring(value_low), //
style = label.style_none, //
color = color.new(color.orange, 0), //
textcolor = color.orange) //
label.delete(low_label1[1]) //
//High Label for Inside Bar when not Inside Bar Only //
//label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family) //
if barstate.islast and not onlyone and show_prices //
high_label1 := label.new(bar_index+4, //
y=value_high, text = str.tostring(value_high), //
style = label.style_none, //
color = color.new(color.orange, 0), //
textcolor = color.gray) //
label.delete(high_label1[1]) //
//Low Label for Inside Bar when not Inside Bar Only //
//label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family) //
if barstate.islast and not onlyone and show_prices //
low_label1 := label.new(bar_index+4, //
y=value_low, text = str.tostring(value_low), //
style = label.style_none, //
color = color.new(color.orange, 0), //
textcolor = color.gray) //
label.delete(low_label1[1]) //
//High Label Previous Bar //
//label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family) //
if barstate.islast and not onlyone and show_prices //
high_label2 := label.new(bar_index+9, //
y=value_high_prev, //
text = str.tostring(value_high_prev), //
style = label.style_none, //
color = color.new(color.orange, 0), //
textcolor = color.gray) //
label.delete(high_label2[1]) //
//Low Label Previus Bar //
//label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family) //
if barstate.islast and not onlyone and show_prices //
low_label2 := label.new(bar_index+9, //
y=value_low_prev, //
text = str.tostring(value_low_prev), //
style = label.style_none, //
color = color.new(color.orange, 0), //
textcolor = color.gray) //
label.delete(low_label2[1]) //
//ADD CURRENT PRICE LABEL //
//BEGIN script Code=============================================================================================================//
var priceArray = array.new_float(0) //
array.push(priceArray, close) //
size = array.size(priceArray) //
price = array.get(priceArray, size -1) //
// //
//LABEL script for OPTIONAL PRICE LABEL=========================================================================================//
label pricelabel = na //
//label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family) //
if barstate.islast and show_current_price_label and show_prices //
pricelabel := label.new(bar_index, //
y=0, //
yloc=yloc.abovebar, //
color = color.new(color.yellow, 0), //
style = label.style_none, //style_none, //
text="Price:\n " + str.tostring(array.get(priceArray, size -1)), //
textcolor = color.new(color.blue, 0)) //
label.delete(pricelabel[1]) //
//==============END SCRIPT======================================================================================================// |
Consecutive Candles lite | Multi Timeframe | https://www.tradingview.com/script/9ahRWGA8-Consecutive-Candles-lite-Multi-Timeframe/ | Yatagarasu_ | https://www.tradingview.com/u/Yatagarasu_/ | 209 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator("CC lite • Yata",
overlay = true,
timeframe = "")
// -----------------------------------
groupCC = ""
// -----------------------------------
lastN = input.string("6 to 9", title="Show", options=["6 to 9", "7, 8 and 9", "8 and 9", "Only 9", "None"], inline="CC1", group=groupCC)
showSR = input(false, title="Show Support and Resistance", inline="CC", group=groupCC)
Coun13 = input(true, title="Std 13", inline="CC1", group=groupCC)
CounCCA13 = input(true, title="Ag. 13", inline="CC1", group=groupCC)
locB = input.string("Below", title="Label: Buy" , options=["Above", "Below"], inline="CC5", group=groupCC)
locA = input.string("Above", title="Sell" , options=["Above", "Below"], inline="CC5", group=groupCC)
locBc = locB == "Above" ? location.abovebar : locB == "Below" ? location.belowbar : na
locAc = locA == "Above" ? location.abovebar : locA == "Below" ? location.belowbar : na
// -----------------------------------
i_style0 = "Label"
i_style1 = "Arrow"
i_style2 = "Triangle"
i_style3 = "Circle"
i_style4 = "Cross"
Bstyle = input.string(i_style0, title="Style: Buy" , options=[i_style0, i_style1, i_style2, i_style3, i_style4], inline="CC6", group=groupCC)
Sstyle = input.string(i_style0, title="Sell" , options=[i_style0, i_style1, i_style2, i_style3, i_style4], inline="CC6", group=groupCC)
f_getStyleB(_inputStyle) =>
_return = _inputStyle == i_style1 ? shape.arrowup :
_inputStyle == i_style2 ? shape.triangleup :
_inputStyle == i_style3 ? shape.circle :
_inputStyle == i_style4 ? shape.cross : shape.labelup
_return
f_getStyleS(_inputStyle) =>
_return = _inputStyle == i_style1 ? shape.arrowdown :
_inputStyle == i_style2 ? shape.triangledown :
_inputStyle == i_style3 ? shape.circle :
_inputStyle == i_style4 ? shape.xcross : shape.labeldown
_return
// -----------------------------------
sellSet = 0
sellSet := close > close[4] ? sellSet[1] == 9 ? 1 : sellSet[1] + 1 : 0
buySet = 0
buySet := close < close[4] ? buySet[1] == 9 ? 1 : buySet[1] + 1 : 0
// -----------------------------------
highest9 = ta.highest(9)
highTrendLine = 0.0
highTrendLine := buySet == 9 ? highest9 : close > highTrendLine[1] ? 0 : highTrendLine[1]
lowest9 = ta.lowest(9)
lowTrendLine = 0.0
lowTrendLine := sellSet == 9 ? lowest9 : close < lowTrendLine[1] ? 0 : lowTrendLine[1]
S_color = input.color(color.new(#90EE90, 25), title="|", inline="CC", group=groupCC)
R_color = input.color(color.new(#E21B22, 25), title="", inline="CC", group=groupCC)
plot(showSR and lowTrendLine > 0 ? lowTrendLine : na, style=plot.style_circles, linewidth=1, color=S_color, title="Support")
plot(showSR and highTrendLine > 0 ? highTrendLine : na, style=plot.style_circles, linewidth=1, color=R_color, title="Resistance")
// -----------------------------------
buyCounCC = 0.0
buyCounCC8Close = 0.0
isBuyCounCC = close < low[2]
nonQBuy13 = isBuyCounCC and math.abs(buyCounCC[1]) == 12 and low > buyCounCC8Close[1]
buyCounCC := buySet == 9 ? isBuyCounCC ? 1 : 0 : sellSet == 9 or highTrendLine == 0 ? 14 : nonQBuy13 ? -12 : isBuyCounCC ? math.abs(buyCounCC[1]) + 1 : -math.abs(buyCounCC[1])
nonQBuy13 := nonQBuy13 and buyCounCC == -12
buyCounCC8Close := buyCounCC == 8 ? close : buyCounCC8Close[1]
sellCounCC = 0.0
sellCounCC8Close = 0.0
isSellCounCC = close > high[2]
nonQSell13 = isSellCounCC and math.abs(sellCounCC[1]) == 12 and high < sellCounCC8Close[1]
sellCounCC := sellSet == 9 ? isSellCounCC ? 1 : 0 : buySet == 9 or lowTrendLine == 0 ? 14 : nonQSell13 ? -12 : isSellCounCC ? math.abs(sellCounCC[1]) + 1 : -math.abs(sellCounCC[1])
nonQSell13 := nonQSell13 and sellCounCC == -12
sellCounCC8Close := sellCounCC == 8 ? close : sellCounCC8Close[1]
isAggressiveBuy = low < low[2]
aggressiveBuy = 0.0
aggressiveBuy := buySet == 9 ? isAggressiveBuy ? 1 : 0 : sellSet == 9 or highTrendLine == 0 ? 14 : isAggressiveBuy ? math.abs(aggressiveBuy[1]) + 1 : -math.abs(aggressiveBuy[1])
isAggressiveSell = high > high[2]
aggressiveSell = 0.0
aggressiveSell := sellSet == 9 ? isAggressiveSell ? 1 : 0 : buySet == 9 or lowTrendLine == 0 ? 14 : isAggressiveSell ? math.abs(aggressiveSell[1]) + 1 : -math.abs(aggressiveSell[1])
// -----------------------------------
color_btext = input.color(color.new(color.white , 0), title="Colors: Buy", inline="C", group=groupCC)
color_stext = input.color(color.new(color.white , 0), title="Sell", inline="C", group=groupCC)
color_b6 = input.color(color.new(#77F1B0 , 0), title="6", inline="CB", group=groupCC)
color_b7 = input.color(color.new(#00ADAD , 0), title="7", inline="CB", group=groupCC)
color_b8 = input.color(color.new(#0067FF , 0), title="8", inline="CB", group=groupCC)
color_b9 = input.color(color.new(#0014C4 , 0), title="9", inline="CB", group=groupCC)
color_s6 = input.color(color.new(color.yellow , 0), title="6", inline="CS", group=groupCC)
color_s7 = input.color(color.new(color.orange , 0), title="7", inline="CS", group=groupCC)
color_s8 = input.color(color.new(color.red , 0), title="8", inline="CS", group=groupCC)
color_s9 = input.color(color.new(color.maroon , 0), title="9", inline="CS", group=groupCC)
color_b13 = input.color(color.new(color.blue , 0), title="13", inline="CB", group=groupCC)
color_s13 = input.color(color.new(#d69d00 , 0), title="13", inline="CS", group=groupCC)
color_bA13 = input.color(color.new(#6400d6 , 0), title="A13", inline="CB", group=groupCC)
color_sA13 = input.color(color.new(#ff8629 , 0), title="A13", inline="CS", group=groupCC)
// -----------------------------------
plotshape(lastN == "6 to 9" ?
buySet == 6 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.auto, color=color_b6, text="", title="lb6", textcolor=color_btext)
plotshape(lastN == "6 to 9" or lastN == "7, 8 and 9" ?
buySet == 7 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.auto, color=color_b7, text="", title="lb7", textcolor=color_btext)
plotshape(lastN == "6 to 9" or lastN == "7, 8 and 9" or lastN == "8 and 9" ?
buySet == 8 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.auto, color=color_b8, text="", title="lb8", textcolor=color_btext)
plotshape(lastN == "6 to 9" or lastN == "7, 8 and 9" or lastN == "8 and 9" or lastN == "Only 9" ?
buySet == 9 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.auto, color=color_b9, text="9", title="lb9", textcolor=color_btext)
plotshape(lastN == "6 to 9" ?
sellSet == 6 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.auto, color=color_s6, text="", title="ls6", textcolor=color_stext)
plotshape(lastN == "6 to 9" or lastN == "7, 8 and 9" ?
sellSet == 7 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.auto, color=color_s7, text="", title="ls7", textcolor=color_stext)
plotshape(lastN == "6 to 9" or lastN == "7, 8 and 9" or lastN == "8 and 9" ?
sellSet == 8 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.auto, color=color_s8, text="", title="ls8", textcolor=color_stext)
plotshape(lastN == "6 to 9" or lastN == "7, 8 and 9" or lastN == "8 and 9" or lastN == "Only 9" ?
sellSet == 9 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.auto, color=color_s9, text="9", title="ls9", textcolor=color_stext)
// -----------------------------------
showST = input(false, title="St. 9", inline="CC1", group=groupCC)
stealthBuy = ta.barssince(buySet == 8) <= 1 and sellSet == 1
stealthSell = ta.barssince(sellSet == 8) <= 1 and buySet == 1
plotshape(showST ? stealthBuy : na, location=locBc, style=f_getStyleB(Bstyle), size=size.auto, color=color_b9, text="s9", title="lb9", textcolor=color_btext)
plotshape(showST ? stealthSell : na, location=locAc, style=f_getStyleS(Sstyle), size=size.auto, color=color_s9, text="s9", title="ls9", textcolor=color_stext)
// -----------------------------------
plotshape(Coun13 ?
sellCounCC == 13 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.auto, color=color_s13, text="13", title="lsc13", textcolor=color_stext)
plotshape(Coun13 ?
buyCounCC == 13 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.auto, color=color_b13, text="13", title="lbc13", textcolor=color_btext)
plotshape(CounCCA13 ?
aggressiveBuy == 13 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.auto, color=color_bA13, text="a13", title="lbc13", textcolor=color_btext)
plotshape(CounCCA13 ?
aggressiveSell == 13 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.auto, color=color_sA13, text="a13", title="lsc13", textcolor=color_stext)
// -----------------------------------
ct9 = buySet == 9 or sellSet == 9
ct13 = buyCounCC == 13 or sellCounCC == 13
cta13 = aggressiveBuy == 13 or aggressiveSell == 13
ct913 = ct9 or ct13
alertcondition(ct9 , title="9 Alert" , message="9 \n\nTicker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}")
alertcondition(ct13 , title="13 Alert" , message="13 \n\nTicker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}")
alertcondition(cta13 , title="a13 Alert" , message="a13 \n\nTicker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}")
alertcondition(ct913 , title="9 and 13 Alert", message="9, 13 \n\nTicker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}") |
US Fed Rate Cut Historical Dates | https://www.tradingview.com/script/dbbgar4a-US-Fed-Rate-Cut-Historical-Dates/ | SnarkyPuppy | https://www.tradingview.com/u/SnarkyPuppy/ | 6 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SnarkyPuppy
//@version=5
indicator("US Fed Rate Cut Review", overlay = true)
/////////////////////////////////////////////////////////////////////////////////////////////////////////\\
color1= color.rgb(223, 64, 251, 50)
//////////////////Cuts
plot((month==01 and year==1991? high:0),style=plot.style_area, color = color1)
plot((month==02 and year==1991? high:0),style=plot.style_area, color = color1)
plot((month==05 and year==1991? high:0),style=plot.style_area, color = color1)
plot((month==09 and year==1991? high:0),style=plot.style_area, color = color1)
plot((month==10 and year==1991? high:0),style=plot.style_area, color = color1)
plot((month==11 and year==1991? high:0),style=plot.style_area, color = color1)
plot((month==12 and year==1991? high:0),style=plot.style_area, color = color1)
plot((month==04 and year==1992? high:0),style=plot.style_area, color = color1)
plot((month==09 and year==1992? high:0),style=plot.style_area, color = color1)
plot((month==01 and year==1996? high:0),style=plot.style_area, color = color1)
plot((month==07 and year==1998? high:0),style=plot.style_area, color = color1)
plot((month==10 and year==1998? high:0),style=plot.style_area, color = color1)
plot((month==11 and year==1998? high:0),style=plot.style_area, color = color1)
plot((month==01 and year==2001? high:0),style=plot.style_area, color = color1)
plot((month==01 and year==2001? high:0),style=plot.style_area, color = color1)
plot((month==03 and year==2001? high:0),style=plot.style_area, color = color1)
plot((month==04 and year==2001? high:0),style=plot.style_area, color = color1)
plot((month==05 and year==2001? high:0),style=plot.style_area, color = color1)
plot((month==06 and year==2001? high:0),style=plot.style_area, color = color1)
plot((month==08 and year==2001? high:0),style=plot.style_area, color = color1)
plot((month==09 and year==2001? high:0),style=plot.style_area, color = color1)
plot((month==10 and year==2001? high:0),style=plot.style_area, color = color1)
plot((month==11 and year==2001? high:0),style=plot.style_area, color = color1)
plot((month==12 and year==2001? high:0),style=plot.style_area, color = color1)
plot((month==11 and year==2002? high:0),style=plot.style_area, color = color1)
plot((month==06 and year==2003? high:0),style=plot.style_area, color = color1)
plot((month==06 and year==2004? high:0),style=plot.style_area, color = color1)
plot((month==08 and year==2004? high:0),style=plot.style_area, color = color1)
plot((month==09 and year==2004? high:0),style=plot.style_area, color = color1)
plot((month==09 and year==2007? high:0),style=plot.style_area, color = color1)
plot((month==10 and year==2007? high:0),style=plot.style_area, color = color1)
plot((month==12 and year==2007? high:0),style=plot.style_area, color = color1)
plot((month==01 and year==2008? high:0),style=plot.style_area, color = color1)
plot((month==03 and year==2008? high:0),style=plot.style_area, color = color1)
plot((month==04 and year==2008? high:0),style=plot.style_area, color = color1)
plot((month==10 and year==2008? high:0),style=plot.style_area, color = color1)
plot((month==10 and year==2008? high:0),style=plot.style_area, color = color1)
plot((month==12 and year==2008? high:0),style=plot.style_area, color = color1)
plot((month==07 and year==2019? high:0),style=plot.style_area, color = color1)
plot((month==09 and year==2019? high:0),style=plot.style_area, color = color1)
plot((month==10 and year==2019? high:0),style=plot.style_area, color = color1)
plot((month==03 and year==2020? high:0),style=plot.style_area, color = color1)
plot((month==03 and year==2020? high:0),style=plot.style_area, color = color1)
|
Consecutive Candles | Multi Timeframe | https://www.tradingview.com/script/rHyTRtIx-Consecutive-Candles-Multi-Timeframe/ | Yatagarasu_ | https://www.tradingview.com/u/Yatagarasu_/ | 299 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator("CC • Yata",
overlay = true,
timeframe = "")
// -----------------------------------
groupCC = ""
// -----------------------------------
lastN = input.string ("6 to 9" , title="Show" , options=["1 to 9", "6 to 9", "7, 8 and 9", "8 and 9", "Only 9", "None"], inline="CC1", group=groupCC)
showSR = input (true , title="Show Support and Resistance" , inline="CC2", group=groupCC)
showCD = input (true , title="Show 1 to 13 |" , inline="CC3", group=groupCC)
lastCN = input (true , title="Only 13 |" , inline="CC4", group=groupCC)
coun = input.string ("Standard" , title="Mode" , options=["Standard", "Aggressive"], inline="CC3", group=groupCC)
locB = input.string("Below", title="Label: Buy" , options=["Above", "Below"], inline="CC5", group=groupCC)
locA = input.string("Above", title="Sell" , options=["Above", "Below"], inline="CC5", group=groupCC)
locBc = locB == "Above" ? location.abovebar : locB == "Below" ? location.belowbar : na
locAc = locA == "Above" ? location.abovebar : locA == "Below" ? location.belowbar : na
// -----------------------------------
i_style0 = "Label"
i_style1 = "Arrow"
i_style2 = "Triangle"
i_style3 = "Circle"
i_style4 = "Cross"
Bstyle = input.string(i_style0, title="Style: Buy" , options=[i_style0, i_style1, i_style2, i_style3, i_style4], inline="CC6", group=groupCC)
Sstyle = input.string(i_style0, title="Sell" , options=[i_style0, i_style1, i_style2, i_style3, i_style4], inline="CC6", group=groupCC)
f_getStyleB(_inputStyle) =>
_return = _inputStyle == i_style1 ? shape.arrowup :
_inputStyle == i_style2 ? shape.triangleup :
_inputStyle == i_style3 ? shape.circle :
_inputStyle == i_style4 ? shape.cross : shape.labelup
_return
f_getStyleS(_inputStyle) =>
_return = _inputStyle == i_style1 ? shape.arrowdown :
_inputStyle == i_style2 ? shape.triangledown :
_inputStyle == i_style3 ? shape.circle :
_inputStyle == i_style4 ? shape.xcross : shape.labeldown
_return
// -----------------------------------
sellSet = 0
sellSet := close > close[4] ? sellSet[1] == 9 ? 1 : sellSet[1] + 1 : 0
buySet = 0
buySet := close < close[4] ? buySet[1] == 9 ? 1 : buySet[1] + 1 : 0
// -----------------------------------
plotshape(lastN == "1 to 9" ? buySet == 1 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.tiny, color=color.new(#1C61B1, 75), text="1", title="b1", textcolor=color.new(color.white, 75))
plotshape(lastN == "1 to 9" ? buySet == 2 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.tiny, color=color.new(#1D80AF, 70), text="2", title="b2", textcolor=color.new(color.white, 70))
plotshape(lastN == "1 to 9" ? buySet == 3 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.tiny, color=color.new(#1D80AF, 65), text="3", title="b3", textcolor=color.new(color.white, 65))
plotshape(lastN == "1 to 9" ? buySet == 4 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.tiny, color=color.new(#1EA9AC, 60), text="4", title="b4", textcolor=color.new(color.white, 60))
plotshape(lastN == "1 to 9" ? buySet == 5 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.tiny, color=color.new(#1EA9AC, 55), text="5", title="b5", textcolor=color.new(color.white, 55))
plotshape(lastN == "1 to 9" or lastN == "6 to 9" ?
buySet == 6 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.tiny, color=color.new(#34BEA5, 50), text="6", title="b6", textcolor=color.new(color.white, 40))
plotshape(lastN == "1 to 9" or lastN == "6 to 9" or lastN == "7, 8 and 9" ?
buySet == 7 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.tiny, color=color.new(#34BEA5, 40), text="7", title="b7", textcolor=color.new(color.white, 30))
plotshape(lastN == "1 to 9" or lastN == "6 to 9" or lastN == "7, 8 and 9" or lastN == "8 and 9" ?
buySet == 8 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.tiny, color=color.new(#67D89A, 30), text="8", title="b8", textcolor=color.new(color.white, 10))
plotshape(lastN == "1 to 9" or lastN == "6 to 9" or lastN == "7, 8 and 9" or lastN == "8 and 9" or lastN == "Only 9" ?
buySet == 9 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.tiny, color=color.new(#90EE90, 20), text="9", title="b9", textcolor=color.new(color.white, 0))
// -----------------------------------
plotshape(lastN == "1 to 9" ? sellSet == 1 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.tiny, color=color.new(#69208E, 75), text="1", title="s1", textcolor=color.new(color.white, 75))
plotshape(lastN == "1 to 9" ? sellSet == 2 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.tiny, color=color.new(#9138A7, 70), text="2", title="s2", textcolor=color.new(color.white, 70))
plotshape(lastN == "1 to 9" ? sellSet == 3 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.tiny, color=color.new(#9138A7, 65), text="3", title="s3", textcolor=color.new(color.white, 65))
plotshape(lastN == "1 to 9" ? sellSet == 4 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.tiny, color=color.new(#CA3AB0, 60), text="4", title="s4", textcolor=color.new(color.white, 60))
plotshape(lastN == "1 to 9" ? sellSet == 5 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.tiny, color=color.new(#CA3AB0, 55), text="5", title="s5", textcolor=color.new(color.white, 55))
plotshape(lastN == "1 to 9" or lastN == "6 to 9" ?
sellSet == 6 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.tiny, color=color.new(#F23D92, 50), text="6", title="s6", textcolor=color.new(color.white, 40))
plotshape(lastN == "1 to 9" or lastN == "6 to 9" or lastN == "7, 8 and 9" ?
sellSet == 7 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.tiny, color=color.new(#F23D92, 40), text="7", title="s7", textcolor=color.new(color.white, 30))
plotshape(lastN == "1 to 9" or lastN == "6 to 9" or lastN == "7, 8 and 9" or lastN == "8 and 9" ?
sellSet == 8 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.tiny, color=color.new(#F71746, 30), text="8", title="s8", textcolor=color.new(color.white, 10))
plotshape(lastN == "1 to 9" or lastN == "6 to 9" or lastN == "7, 8 and 9" or lastN == "8 and 9" or lastN == "Only 9" ?
sellSet == 9 : na, location=locAc, style=f_getStyleS(Sstyle), size=size.tiny, color=color.new(#E21B22, 20), text="9", title="s9", textcolor=color.new(color.white, 0))
// -----------------------------------
showST = input(false, title="Show Stealth 9", inline="CC1", group=groupCC)
stealthBuy = ta.barssince(buySet == 8) <= 1 and sellSet == 1
stealthSell = ta.barssince(sellSet == 8) <= 1 and buySet == 1
plotshape(showST ? stealthBuy : na, location=locBc, style=f_getStyleB(Bstyle), size=size.tiny, color=color.new(#90EE90, 20), text="s9", title="b9", textcolor=color.new(color.white, 0))
plotshape(showST ? stealthSell : na, location=locAc, style=f_getStyleS(Sstyle), size=size.tiny, color=color.new(#E21B22, 20), text="s9", title="s9", textcolor=color.new(color.white, 0))
// -----------------------------------
highest9 = ta.highest(9)
highTrendLine = 0.0
highTrendLine := buySet == 9 ? highest9 : close > highTrendLine[1] ? 0 : highTrendLine[1]
lowest9 = ta.lowest(9)
lowTrendLine = 0.0
lowTrendLine := sellSet == 9 ? lowest9 : close < lowTrendLine[1] ? 0 : lowTrendLine[1]
S_color = input.color(color.new(#90EE90, 25), title="|", inline="CC2", group=groupCC)
R_color = input.color(color.new(#E21B22, 25), title="", inline="CC2", group=groupCC)
plot(showSR and lowTrendLine > 0 ? lowTrendLine : na, style=plot.style_circles, linewidth=1, color=S_color, title="Support")
plot(showSR and highTrendLine > 0 ? highTrendLine : na, style=plot.style_circles, linewidth=1, color=R_color, title="Resistance")
// -----------------------------------
buyCounCC = 0.0
buyCounCC8Close = 0.0
isBuyCounCC = close < low[2]
nonQBuy13 = isBuyCounCC and math.abs(buyCounCC[1]) == 12 and low > buyCounCC8Close[1]
buyCounCC := buySet == 9 ? isBuyCounCC ? 1 : 0 : sellSet == 9 or highTrendLine == 0 ? 14 : nonQBuy13 ? -12 : isBuyCounCC ? math.abs(buyCounCC[1]) + 1 : -math.abs(buyCounCC[1])
nonQBuy13 := nonQBuy13 and buyCounCC == -12
buyCounCC8Close := buyCounCC == 8 ? close : buyCounCC8Close[1]
sellCounCC = 0.0
sellCounCC8Close = 0.0
isSellCounCC = close > high[2]
nonQSell13 = isSellCounCC and math.abs(sellCounCC[1]) == 12 and high < sellCounCC8Close[1]
sellCounCC := sellSet == 9 ? isSellCounCC ? 1 : 0 : buySet == 9 or lowTrendLine == 0 ? 14 : nonQSell13 ? -12 : isSellCounCC ? math.abs(sellCounCC[1]) + 1 : -math.abs(sellCounCC[1])
nonQSell13 := nonQSell13 and sellCounCC == -12
sellCounCC8Close := sellCounCC == 8 ? close : sellCounCC8Close[1]
isAggressiveBuy = low < low[2]
aggressiveBuy = 0.0
aggressiveBuy := buySet == 9 ? isAggressiveBuy ? 1 : 0 : sellSet == 9 or highTrendLine == 0 ? 14 : isAggressiveBuy ? math.abs(aggressiveBuy[1]) + 1 : -math.abs(aggressiveBuy[1])
isAggressiveSell = high > high[2]
aggressiveSell = 0.0
aggressiveSell := sellSet == 9 ? isAggressiveSell ? 1 : 0 : buySet == 9 or lowTrendLine == 0 ? 14 : isAggressiveSell ? math.abs(aggressiveSell[1]) + 1 : -math.abs(aggressiveSell[1])
showStandardCounCC = coun == "Standard"
showAggressiveCounCC = coun == "Aggressive"
sellCounCCNumber = showStandardCounCC ? sellCounCC : showAggressiveCounCC ? aggressiveSell : na
buyCounCCNumber = showStandardCounCC ? buyCounCC : showAggressiveCounCC ? aggressiveBuy : na
// -----------------------------------
both = input(true, title="Both Mode", inline="CC4", group=groupCC)
plotshape(showCD and not lastCN ? sellCounCCNumber == 1 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#E21B22, 100), text="1" , title="sc1" , textcolor=color.new(color.silver, 75))
plotshape(showCD and not lastCN ? sellCounCCNumber == 2 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#E21B22, 100), text="2" , title="sc2" , textcolor=color.new(color.silver, 70))
plotshape(showCD and not lastCN ? sellCounCCNumber == 3 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#E21B22, 100), text="3" , title="sc3" , textcolor=color.new(color.silver, 65))
plotshape(showCD and not lastCN ? sellCounCCNumber == 4 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#E21B22, 100), text="4" , title="sc4" , textcolor=color.new(color.silver, 60))
plotshape(showCD and not lastCN ? sellCounCCNumber == 5 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#E21B22, 100), text="5" , title="sc5" , textcolor=color.new(color.silver, 55))
plotshape(showCD and not lastCN ? sellCounCCNumber == 6 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#E21B22, 100), text="6" , title="sc6" , textcolor=color.new(color.silver, 50))
plotshape(showCD and not lastCN ? sellCounCCNumber == 7 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#E21B22, 100), text="7" , title="sc7" , textcolor=color.new(color.silver, 45))
plotshape(showCD and not lastCN ? sellCounCCNumber == 8 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#E21B22, 100), text="8" , title="sc8" , textcolor=color.new(color.silver, 40))
plotshape(showCD and not lastCN ? sellCounCCNumber == 9 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#E21B22, 100), text="9" , title="sc9" , textcolor=color.new(color.silver, 35))
plotshape(showCD and not lastCN ? sellCounCCNumber == 10 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#E21B22, 100), text="10" , title="sc10" , textcolor=color.new(color.silver, 30))
plotshape(showCD and not lastCN ? sellCounCCNumber == 11 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#E21B22, 100), text="11" , title="sc11" , textcolor=color.new(color.silver, 25))
plotshape(showCD and not lastCN ? sellCounCCNumber == 12 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#E21B22, 100), text="12" , title="sc12" , textcolor=color.new(color.silver, 20))
plotshape(showCD and not lastCN ? sellCounCCNumber == 13 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#E21B22, 100), text="13" , title="sc13" , textcolor=color.new(color.red , 0))
plotshape(showCD and not lastCN and nonQSell13 and showStandardCounCC , location=locAc, style=f_getStyleS(Sstyle), size=size.small , color=color.new(#E21B22, 100), text="+" , title="+" , textcolor=color.new(color.red, 0))
//plotshape(showCD and not lastCN and sellCounCC == 13 and showAggressiveCounCC , location=locAc, style=f_getStyleS(Sstyle), size=size.normal , color=color.new(#E21B22, 100), text="s13" , title="s13" , textcolor=color.new(color.red, 0))
//plotshape(showCD and not lastCN and aggressiveSell == 13 and showStandardCounCC , location=locAc, style=f_getStyleS(Sstyle), size=size.normal , color=color.new(#E21B22, 100), text="a13" , title="a13" , textcolor=color.new(color.red, 0))
//plotshape(showCD and lastCN ? sellCounCCNumber == 13 : na , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#FF9800, 20), text="13" , title="sc13", textcolor=color.new(color.white, 0))
plotshape(showCD and lastCN and sellCounCC == 13 and showStandardCounCC or showCD and lastCN and sellCounCC == 13 and showAggressiveCounCC and both , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#FF9800, 20), text="13" , title="os13", textcolor=color.new(color.white, 0))
plotshape(showCD and lastCN and aggressiveSell == 13 and showAggressiveCounCC or showCD and lastCN and aggressiveSell == 13 and showStandardCounCC and both , location=locAc, style=f_getStyleS(Sstyle), size=size.small, color=color.new(#FF9800, 20), text="a13" , title="oa13", textcolor=color.new(color.white, 0))
// -----------------------------------
plotshape(showCD and not lastCN ? buyCounCCNumber == 1 : na , location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#90EE90, 100), text="1" , title="bc1" , textcolor=color.new(color.silver, 75))
plotshape(showCD and not lastCN ? buyCounCCNumber == 2 : na , location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#90EE90, 100), text="2" , title="bc2" , textcolor=color.new(color.silver, 70))
plotshape(showCD and not lastCN ? buyCounCCNumber == 3 : na , location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#90EE90, 100), text="3" , title="bc3" , textcolor=color.new(color.silver, 65))
plotshape(showCD and not lastCN ? buyCounCCNumber == 4 : na , location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#90EE90, 100), text="4" , title="bc4" , textcolor=color.new(color.silver, 60))
plotshape(showCD and not lastCN ? buyCounCCNumber == 5 : na , location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#90EE90, 100), text="5" , title="bc5" , textcolor=color.new(color.silver, 55))
plotshape(showCD and not lastCN ? buyCounCCNumber == 6 : na , location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#90EE90, 100), text="6" , title="bc6" , textcolor=color.new(color.silver, 50))
plotshape(showCD and not lastCN ? buyCounCCNumber == 7 : na , location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#90EE90, 100), text="7" , title="bc7" , textcolor=color.new(color.silver, 45))
plotshape(showCD and not lastCN ? buyCounCCNumber == 8 : na , location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#90EE90, 100), text="8" , title="bc8" , textcolor=color.new(color.silver, 40))
plotshape(showCD and not lastCN ? buyCounCCNumber == 9 : na , location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#90EE90, 100), text="9" , title="bc9" , textcolor=color.new(color.silver, 35))
plotshape(showCD and not lastCN ? buyCounCCNumber == 10 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#90EE90, 100), text="10", title="bc10" , textcolor=color.new(color.silver, 30))
plotshape(showCD and not lastCN ? buyCounCCNumber == 11 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#90EE90, 100), text="11", title="bc11" , textcolor=color.new(color.silver, 25))
plotshape(showCD and not lastCN ? buyCounCCNumber == 12 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#90EE90, 100), text="12", title="bc12" , textcolor=color.new(color.silver, 20))
plotshape(showCD and not lastCN ? buyCounCCNumber == 13 : na, location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#90EE90, 100), text="13", title="bc13" , textcolor=color.new(color.green, 0))
plotshape(showCD and not lastCN and nonQBuy13 and showStandardCounCC , location=locBc, style=f_getStyleB(Bstyle), size=size.small , color=color.new(#90EE90, 100), text="+" , title="+", textcolor=color.new(color.green, 0))
//plotshape(showCD and not lastCN and buyCounCC == 13 and showAggressiveCounCC , location=locBc, style=f_getStyleB(Bstyle), size=size.normal , color=color.new(#90EE90, 100), text="s13" , title="s13", textcolor=color.new(color.green, 0))
//plotshape(showCD and not lastCN and aggressiveBuy == 13 and showStandardCounCC , location=locBc, style=f_getStyleB(Bstyle), size=size.normal , color=color.new(#90EE90, 100), text="a13" , title="a13", textcolor=color.new(color.green, 0))
//plotshape(showCD and lastCN ? buyCounCCNumber == 13 : na , location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#2196F3, 20), text="13" , title="bc13", textcolor=color.new(color.white, 0))
plotshape(showCD and lastCN and buyCounCC == 13 and showStandardCounCC or showCD and lastCN and buyCounCC == 13 and showAggressiveCounCC and both , location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#2196F3, 20), text="13" , title="os13", textcolor=color.new(color.white, 0))
plotshape(showCD and lastCN and aggressiveBuy == 13 and showAggressiveCounCC or showCD and lastCN and aggressiveBuy == 13 and showStandardCounCC and both , location=locBc, style=f_getStyleB(Bstyle), size=size.small, color=color.new(#2196F3, 20), text="a13" , title="oa13", textcolor=color.new(color.white, 0))
// -----------------------------------
ct9 = buySet == 9 or sellSet == 9
ct13 = buyCounCC == 13 or sellCounCC == 13
cta13 = aggressiveBuy == 13 or aggressiveSell == 13
ct913 = ct9 or ct13
alertcondition(ct9 , title="9 Alert" , message="9 \n\nTicker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}")
alertcondition(ct13 , title="13 Alert" , message="13 \n\nTicker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}")
alertcondition(cta13 , title="a13 Alert" , message="a13 \n\nTicker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}")
alertcondition(ct913 , title="9 and 13 Alert", message="9, 13 \n\nTicker: {{ticker}}\nTime: {{time}}\nPrice: {{close}}") |
Dual Bollinger Band Mean Reversion | https://www.tradingview.com/script/qQVNek6S-Dual-Bollinger-Band-Mean-Reversion/ | pb-algo | https://www.tradingview.com/u/pb-algo/ | 147 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © pb-algo
//@version=5
indicator(shorttitle="BBMR", title="Dual Bollinger Band Mean Reversion", overlay=true, max_labels_count = 500)
length = input.int(20, minval=1)
length2 = input.int(400, minval=1)
src = input(close, title="Source")
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev")
basis = ta.sma(src, length)
basis2 = ta.sma(src, length2)
dev = mult * ta.stdev(src, length)
dev2 = mult * ta.stdev(src, length2)
upper = basis + dev
lower = basis - dev
upper2 = basis2 + dev2
lower2 = basis2 - dev2
p1 = plot(upper, "Upper", color=color.new(color.yellow, 80))
p2 = plot(lower, "Lower", color=color.new(color.yellow, 80))
p3 = plot(upper2, "Upper", color=color.new(color.white, 80))
p4 = plot(lower2, "Lower", color=color.new(color.white, 80))
cond1 = false
cond2 = false
var cond3 = false
var float candleHigh1 = 0
var float candleLow1 = 0
var float candleLevel1 = 0
var float stopLevel1 = 0
var float targetLevel1 = 0
var label orderLabel = na
var orderCount = 0
var winCount = 0
var lossCount = 0
if barstate.isconfirmed
if close < lower
candleHigh1 := high
candleLow1 := low
candleLevel1 := candleLow1 + ((candleHigh1-candleLow1)/2)
cond1 := true
if cond1[1] and close > lower
cond2:= true
if close < basis2
cond2:= false
if cond2[1] and close > basis2
if not cond3
stopLevel1 := open + (open-upper)
targetLevel1 := upper[1]
cond3:= true
if orderCount == 0
orderLabel := label.new(bar_index, open, size=size.tiny, style=label.style_label_left, color = color.yellow)
orderCount := orderCount +1
// For backtest uncomment these two lines and change "indicator" to "strategy" on line 2.
// strategy.entry("Long", strategy.long)
// strategy.exit("Close Long", "Long", stop=stopLevel1, limit=targetLevel1)
if cond3 and low< stopLevel1
winCount := winCount + orderCount
label.new(bar_index, high, "L: " + str.tostring(math.round(lossCount/winCount,2)) , color=color.red)
cond3:=false
orderCount := 0
if cond3 and high > targetLevel1
lossCount := lossCount + orderCount
label.new(bar_index, high, "W: " + str.tostring(math.round(lossCount/winCount,2)) , color=color.green)
cond3:=false
orderCount := 0
plot(stopLevel1, color = color.white, style = plot.style_stepline)
plot(targetLevel1, color = color.white, style = plot.style_stepline)
plot(basis2, color = color.yellow, style = plot.style_stepline)
|
Nifty36Scanner | https://www.tradingview.com/script/Zo6ocQgv-Nifty36Scanner/ | AtulGoswami | https://www.tradingview.com/u/AtulGoswami/ | 200 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AtulGoswami
// this screener is coded to filter out buy and sell signal son the basis of Inidcators and crossovers.
// credit : This is a modified version of a Scanner video done by Stock Data Analyst youtube channel
// you can select any indicator and crossover and runt the scan on any NSE 36 stocks , a selction of stocks can also be made by going int settings
//HalfTrend inidcator is used to scan the stocks, originally developed by Everget
//@version=5
indicator("Nifty50Scanner", overlay=true)
len=input.int(9, title="RSI Length")
macdcrossscreener=input.bool(true, title="MACD Screener", group="MACD")
EMandSTscanner=input.bool(true, title="EMA200 & Supertrend Cross", group="EMA200 + Supertrend")
Halftrend = input.bool(true, title="Half Trend", group="HalfTrend")
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
//Screener function to calculate Bull and Bear status of teh signal equalent to Buy and Sell Signal
screener() =>
//Buy/Sell signal calculation if scaning for EMA200 cross over and Supertrend and close crossover
if(EMandSTscanner==true and macdcrossscreener==false)
[supertrend,direction] = ta.supertrend(2.5,10)
buy =ta.crossover(close, supertrend) and ta.crossover(open, supertrend) and ta.crossover(close, ta.ema(close, 200))
sell =ta.crossunder(close, supertrend) and ta.crossunder(open, supertrend) and ta.crossunder(close, ta.ema(close, 200))
bull= buy
bear= sell
[bull, bear]
//Buy/Sell signal calculation if scaning for only MACD Crossover based buy/Sell signal
if(macdcrossscreener==true and EMandSTscanner==false)
[macdline, sigline, histline] = ta.macd(close, 12, 26, 9)
buy =ta.crossover(macdline, sigline)
sell =ta.crossunder(macdline, sigline)
bull= buy
bear=sell
[bull, bear]
//Buy/Sell signal calculation if scaning for MACD Crossover based buy/Sell signal and EMA200 cross over and Supertrend and close crossover
if(macdcrossscreener==true and EMandSTscanner==true)
[supertrend,direction] = ta.supertrend(2.5,10)
[macdline, sigline, histline] = ta.macd(close, 12, 26, 9)
buy =ta.crossover(close, supertrend) and ta.crossover(macdline, sigline) and ta.crossover(close, ta.ema(close, 200))
sell =ta.crossunder(close, supertrend) and ta.crossunder(macdline, sigline) and ta.crossunder(close, ta.ema(close, 200))
bull= buy
bear=sell
[bull, bear]
// Consider Half Trend based Buy/Sell signals in addition to EMA200 cross over and Supertrend and close crossover and MACD Crossover
if(Halftrend==true)
//Calculation of Half Trend Buy/Sell signals
amplitude = input(title='Amplitude', defval=2)
channelDeviation = input(title='Channel Deviation', defval=2)
showArrows = input(title='Show Arrows', defval=true)
showChannels = input(title='Show Channels', defval=true)
var int trend = 0
var int nextTrend = 0
var float maxLowPrice = nz(low[1], low)
var float minHighPrice = nz(high[1], high)
var float up = 0.0
var float down = 0.0
float atrHigh = 0.0
float atrLow = 0.0
float arrowUp = na
float arrowDown = na
atr2 = ta.atr(100) / 2
dev = channelDeviation * atr2
highPrice = high[math.abs(ta.highestbars(amplitude))]
lowPrice = low[math.abs(ta.lowestbars(amplitude))]
highma = ta.sma(high, amplitude)
lowma = ta.sma(low, amplitude)
if nextTrend == 1
maxLowPrice := math.max(lowPrice, maxLowPrice)
if highma < maxLowPrice and close < nz(low[1], low)
trend := 1
nextTrend := 0
minHighPrice := highPrice
minHighPrice
else
minHighPrice := math.min(highPrice, minHighPrice)
if lowma > minHighPrice and close > nz(high[1], high)
trend := 0
nextTrend := 1
maxLowPrice := lowPrice
maxLowPrice
if trend == 0
if not na(trend[1]) and trend[1] != 0
up := na(down[1]) ? down : down[1]
arrowUp := up - atr2
arrowUp
else
up := na(up[1]) ? maxLowPrice : math.max(maxLowPrice, up[1])
up
atrHigh := up + dev
atrLow := up - dev
atrLow
else
if not na(trend[1]) and trend[1] != 1
down := na(up[1]) ? up : up[1]
arrowDown := down + atr2
arrowDown
else
down := na(down[1]) ? minHighPrice : math.min(minHighPrice, down[1])
down
atrHigh := down + dev
atrLow := down - dev
atrLow
ht = trend == 0 ? up : down
buySignal = not na(arrowUp) and trend == 0 and trend[1] == 1
sellSignal = not na(arrowDown) and trend == 1 and trend[1] == 0
bull=buySignal
bear=sellSignal
[bull, bear]
////////////////////////////////////////////////
//Calculating Timeframe
tf=timeframe.period
//Assigining Stock symbols for scanning
s1=input.symbol('NSE:NIFTY1!', title='Symbol1', group="Nifty50List", inline='0')
s2=input.symbol('NSE:BANKNIFTY1!', title='Symbol2', group="Nifty50List", inline='0')
s3=input.symbol('NSE:SBIN', title='Symbol3', group="Nifty50List", inline='0')
s4=input.symbol('NSE:ADANIENT', title='Symbol4', group="Nifty50List", inline='0')
s5=input.symbol('NSE:RELIANCE', title='Symbol5', group="Nifty50List", inline='0')
s6=input.symbol('NSE:HDFCBANK', title='Symbol6', group="Nifty50List", inline='0')
s7=input.symbol('NSE:INDUSINDBK', title='Symbol7', group="Nifty50List", inline='0')
s8=input.symbol('NSE:MARUTI', title='Symbol8', group="Nifty50List", inline='0')
s9=input.symbol('NSE:ICICIBANK', title='Symbol9', group="Nifty50List", inline='0')
s10=input.symbol('NSE:TATASTEEL', title='Symbol1', group="Nifty50List", inline='0')
s11=input.symbol('NSE:TATAMOTORS', title='Symbol2', group="Nifty50List", inline='0')
s12=input.symbol('NSE:ADANIPORTS', title='Symbol3', group="Nifty50List", inline='0')
s13=input.symbol('NSE:APOLLOHOSP', title='Symbol4', group="Nifty50List", inline='0')
s14=input.symbol('NSE:ASIANPAINT', title='Symbol5', group="Nifty50List", inline='0')
s15=input.symbol('NSE:AXISBANK', title='Symbol6', group="Nifty50List", inline='0')
s16=input.symbol('NSE:BAJAJFINSV', title='Symbol7', group="Nifty50List", inline='0')
s17=input.symbol('NSE:BAJFINANCE', title='Symbol8', group="Nifty50List", inline='0')
s18=input.symbol('NSE:BAJAJ_AUTO', title='Symbol9', group="Nifty50List", inline='0')
s19=input.symbol('NSE:DRREDDY', title='Symbol1', group="Nifty50List", inline='0')
s20=input.symbol('NSE:HCLTECH', title='Symbol2', group="Nifty50List", inline='0')
s21=input.symbol('NSE:EICHERMOT', title='Symbol3', group="Nifty50List", inline='0')
s22=input.symbol('NSE:HEROMOTOCO', title='Symbol4', group="Nifty50List", inline='0')
s23=input.symbol('NSE:HINDALCO', title='Symbol5', group="Nifty50List", inline='0')
s24=input.symbol('NSE:ITC', title='Symbol6', group="Nifty50List", inline='0')
s25=input.symbol('NSE:LT', title='Symbol7', group="Nifty50List", inline='0')
s26=input.symbol('NSE:KOTAKBANK', title='Symbol8', group="Nifty50List", inline='0')
s27=input.symbol('NSE:M_M', title='Symbol9', group="Nifty50List", inline='0')
s28=input.symbol('NSE:BPCL', title='Symbol1', group="Nifty50List", inline='0')
s29=input.symbol('NSE:ONGC', title='Symbol2', group="Nifty50List", inline='0')
s30=input.symbol('NSE:TCS', title='Symbol3', group="Nifty50List", inline='0')
s31=input.symbol('NSE:TECHM', title='Symbol4', group="Nifty50List", inline='0')
s32=input.symbol('NSE:TITAN', title='Symbol5', group="Nifty50List", inline='0')
s33=input.symbol('NSE:ULTRACEMCO', title='Symbol6', group="Nifty50List", inline='0')
s34=input.symbol('NSE:UPL', title='Symbol7', group="Nifty50List", inline='0')
s35=input.symbol('NSE:WIPRO', title='Symbol8', group="Nifty50List", inline='0')
s36=input.symbol('NSE:TATACONSUM', title='Symbol9', group="Nifty50List", inline='0')
///////////////////////////////////////////////////////////////////////////////////
// Assigning Buy /Sell signals to each stock identified in the given time frame
[c1,v1]=request.security(s1, tf, screener())
[c2,v2]=request.security(s2, tf, screener())
[c3,v3]=request.security(s3, tf, screener())
[c4,v4]=request.security(s4, tf, screener())
[c5,v5]=request.security(s5, tf, screener())
[c6,v6]=request.security(s6, tf, screener())
[c7,v7]=request.security(s7, tf, screener())
[c8,v8]=request.security(s8, tf, screener())
[c9,v9]=request.security(s9, tf, screener())
[c10,v10]=request.security(s10, tf, screener())
[c11,v11]=request.security(s11, tf, screener())
[c12,v12]=request.security(s12, tf, screener())
[c13,v13]=request.security(s13, tf, screener())
[c14,v14]=request.security(s14, tf, screener())
[c15,v15]=request.security(s15, tf, screener())
[c16,v16]=request.security(s16, tf, screener())
[c17,v17]=request.security(s17, tf, screener())
[c18,v18]=request.security(s18, tf, screener())
[c19,v19]=request.security(s19, tf, screener())
[c20,v20]=request.security(s20, tf, screener())
[c21,v21]=request.security(s21, tf, screener())
[c22,v22]=request.security(s22, tf, screener())
[c23,v23]=request.security(s23, tf, screener())
[c24,v24]=request.security(s24, tf, screener())
[c25,v25]=request.security(s25, tf, screener())
[c26,v26]=request.security(s26, tf, screener())
[c27,v27]=request.security(s27, tf, screener())
[c28,v28]=request.security(s28, tf, screener())
[c29,v29]=request.security(s29, tf, screener())
[c30,v30]=request.security(s30, tf, screener())
[c31,v31]=request.security(s31, tf, screener())
[c32,v32]=request.security(s32, tf, screener())
[c33,v33]=request.security(s33, tf, screener())
[c34,v34]=request.security(s34, tf, screener())
[c35,v35]=request.security(s35, tf, screener())
[c36,v36]=request.security(s36, tf, screener())
//////////////////////////////////////////////////////////////////////////////////
//Assiging BUY Label to each stock
buy_label1='---BUY SIGNAL---\n'
buy_label1:= c1?buy_label1+str.tostring(s1)+'\n': buy_label1
buy_label1:= c2?buy_label1+str.tostring(s2)+'\n': buy_label1
buy_label1:= c3?buy_label1+str.tostring(s3)+'\n': buy_label1
buy_label1:= c4?buy_label1+str.tostring(s4)+'\n': buy_label1
buy_label1:= c5?buy_label1+str.tostring(s5)+'\n': buy_label1
buy_label1:= c6?buy_label1+str.tostring(s6)+'\n': buy_label1
buy_label1:= c7?buy_label1+str.tostring(s7)+'\n': buy_label1
buy_label1:= c8?buy_label1+str.tostring(s8)+'\n': buy_label1
buy_label1:= c9?buy_label1+str.tostring(s9)+'\n': buy_label1
buy_label1:= c10?buy_label1+str.tostring(s10)+'\n': buy_label1
buy_label1:= c11?buy_label1+str.tostring(s11)+'\n': buy_label1
buy_label1:= c12?buy_label1+str.tostring(s12)+'\n': buy_label1
buy_label1:= c13?buy_label1+str.tostring(s13)+'\n': buy_label1
buy_label1:= c14?buy_label1+str.tostring(s14)+'\n': buy_label1
buy_label1:= c15?buy_label1+str.tostring(s15)+'\n': buy_label1
buy_label1:= c16?buy_label1+str.tostring(s16)+'\n': buy_label1
buy_label1:= c17?buy_label1+str.tostring(s17)+'\n': buy_label1
buy_label1:= c18?buy_label1+str.tostring(s18)+'\n': buy_label1
buy_label1:= c19?buy_label1+str.tostring(s19)+'\n': buy_label1
buy_label1:= c20?buy_label1+str.tostring(s20)+'\n': buy_label1
buy_label1:= c21?buy_label1+str.tostring(s21)+'\n': buy_label1
buy_label1:= c22?buy_label1+str.tostring(s22)+'\n': buy_label1
buy_label1:= c23?buy_label1+str.tostring(s23)+'\n': buy_label1
buy_label1:= c24?buy_label1+str.tostring(s24)+'\n': buy_label1
buy_label1:= c25?buy_label1+str.tostring(s25)+'\n': buy_label1
buy_label1:= c26?buy_label1+str.tostring(s26)+'\n': buy_label1
buy_label1:= c27?buy_label1+str.tostring(s27)+'\n': buy_label1
buy_label1:= c28?buy_label1+str.tostring(s28)+'\n': buy_label1
buy_label1:= c29?buy_label1+str.tostring(s29)+'\n': buy_label1
buy_label1:= c30?buy_label1+str.tostring(s30)+'\n': buy_label1
buy_label1:= c31?buy_label1+str.tostring(s31)+'\n': buy_label1
buy_label1:= c32?buy_label1+str.tostring(s32)+'\n': buy_label1
buy_label1:= c33?buy_label1+str.tostring(s33)+'\n': buy_label1
buy_label1:= c34?buy_label1+str.tostring(s34)+'\n': buy_label1
buy_label1:= c35?buy_label1+str.tostring(s35)+'\n': buy_label1
buy_label1:= c36?buy_label1+str.tostring(s36)+'\n': buy_label1
// Plotting each Buy/Sell signal in teh label
lab_buy=label.new(bar_index+10, close, buy_label1, color=color.new(color.lime, 70), textcolor = color.white, style=label.style_label_up, yloc=yloc.price, textalign = text.align_left)
//Deleting Buy/Sell signal of the previous candle to remove clutter from the screen
label.delete(lab_buy[1])
//Assigining SELL signal to each stock if SELL siganl comes in for teh same
sell_label1='---SELL SIGNAL---\n'
sell_label1:= v1?sell_label1+str.tostring(s1)+'\n': sell_label1
sell_label1:= v2?sell_label1+str.tostring(s2)+'\n': sell_label1
sell_label1:= v3?sell_label1+str.tostring(s3)+'\n': sell_label1
sell_label1:= v4?sell_label1+str.tostring(s4)+'\n': sell_label1
sell_label1:= v5?sell_label1+str.tostring(s5)+'\n': sell_label1
sell_label1:= v6?sell_label1+str.tostring(s6)+'\n': sell_label1
sell_label1:= v7?sell_label1+str.tostring(s7)+'\n': sell_label1
sell_label1:= v8?sell_label1+str.tostring(s8)+'\n': sell_label1
sell_label1:= v9?sell_label1+str.tostring(s9)+'\n': sell_label1
sell_label1:= v10?sell_label1+str.tostring(s10)+'\n': sell_label1
sell_label1:= v11?sell_label1+str.tostring(s11)+'\n': sell_label1
sell_label1:= v12?sell_label1+str.tostring(s12)+'\n': sell_label1
sell_label1:= v13?sell_label1+str.tostring(s13)+'\n': sell_label1
sell_label1:= v14?sell_label1+str.tostring(s14)+'\n': sell_label1
sell_label1:= v15?sell_label1+str.tostring(s15)+'\n': sell_label1
sell_label1:= v16?sell_label1+str.tostring(s16)+'\n': sell_label1
sell_label1:= v17?sell_label1+str.tostring(s17)+'\n': sell_label1
sell_label1:= v18?sell_label1+str.tostring(s18)+'\n': sell_label1
sell_label1:= v19?sell_label1+str.tostring(s19)+'\n': sell_label1
sell_label1:= v20?sell_label1+str.tostring(s20)+'\n': sell_label1
sell_label1:= v21?sell_label1+str.tostring(s21)+'\n': sell_label1
sell_label1:= v22?sell_label1+str.tostring(s22)+'\n': sell_label1
sell_label1:= v23?sell_label1+str.tostring(s23)+'\n': sell_label1
sell_label1:= v24?sell_label1+str.tostring(s24)+'\n': sell_label1
sell_label1:= v25?sell_label1+str.tostring(s25)+'\n': sell_label1
sell_label1:= v26?sell_label1+str.tostring(s26)+'\n': sell_label1
sell_label1:= v27?sell_label1+str.tostring(s27)+'\n': sell_label1
sell_label1:= v28?sell_label1+str.tostring(s28)+'\n': sell_label1
sell_label1:= v29?sell_label1+str.tostring(s29)+'\n': sell_label1
sell_label1:= v30?sell_label1+str.tostring(s30)+'\n': sell_label1
sell_label1:= v31?sell_label1+str.tostring(s31)+'\n': sell_label1
sell_label1:= v32?sell_label1+str.tostring(s32)+'\n': sell_label1
sell_label1:= v33?sell_label1+str.tostring(s33)+'\n': sell_label1
sell_label1:= v34?sell_label1+str.tostring(s34)+'\n': sell_label1
sell_label1:= v35?sell_label1+str.tostring(s35)+'\n': sell_label1
sell_label1:= v36?sell_label1+str.tostring(s36)+'\n': sell_label1
//plotting SELL signal in the label for stcks if it meets the SELL criteria set above
lab_sell=label.new(bar_index+15, close, sell_label1, color=color.new(color.red, 70), textcolor = color.white, style=label.style_label_down, yloc=yloc.price, textalign = text.align_left)
//Deleting signal of previos candle to remove too many of them showing on screen
label.delete(lab_sell[1])
|
Band-Zigzag Based Trend Follower | https://www.tradingview.com/script/c2thQDcv-Band-Zigzag-Based-Trend-Follower/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 540 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
indicator("Band-Zigzag Based Trend Follower", "BZZ-TF", overlay = true, max_lines_count = 500, max_labels_count = 500)
import HeWhoMustNotBeNamed/ta/1 as eta
import HeWhoMustNotBeNamed/arrays/1 as pa
bandType = input.string('Bollinger Bands', '', ['Bollinger Bands', 'Keltner Channel', 'Donchian Channel'], group='Bands', inline='b1')
maType = input.string('sma', '', options=['sma', 'ema', 'hma', 'rma', 'wma', 'vwma', 'highlow', 'linreg', 'median'], inline = 'b1', group='Bands')
maLength = input.int(20, '', minval = 5, step=5, inline = 'b1', group='Bands')
multiplier = input.float(2.0, '', step=0.5, minval=0.5, group='Bands', inline='b1', tooltip = 'Band parameters let you select type of band/channel, moving average base, length and multiplier')
useTrueRange = input.bool(true, 'Use True Range (For KC only)', group='Bands', tooltip = 'Used only for keltener channel calculation')
sticky = input.bool(true, 'Sticky', group='Bands', tooltip = 'Sticky bands avoids changing the band unless there is breach. Meaning, band positions only change when price is outside the band.')
useAdaptive = input.bool(true, 'Adaptive', group='Bands', tooltip = 'When selected, lower band will not decrease when pivot high is in motion and upper band will not increase when pivot low in motion')
useLatestPivot = input.bool(true, 'Use Recent Pivot Confirmation', group='Confirmation', tooltip = 'Also use current unconfirmed pivot for trend confirmation')
continueWhenNoConfirmation = input.bool(false, 'Nullify Trend If no confirmation', group='Confirmation', tooltip = 'If selected, trend is set to neither if no confirmation obtained. Otherwise, previous trend is carried forward')
showBands = input.bool(true, 'Bands', group='Display', inline='d')
showZigzag = input.bool(true, 'Zigzag', group='Display', inline='d')
colorCandles = input.bool(true, 'Color Bars', group='Display', inline='d')
float upper = 0.0
float lower = 0.0
float middle = 0.0
type Pivot
float price
int bar
int bartime
int direction
float percentB
float ratio = 0
type Drawing
line zigzagLine
label zigzagLabel
unshift(array<Pivot> zigzag, Pivot p)=>
if(array.size(zigzag) > 1)
lastPivot = array.get(zigzag, 0)
llastPivot = array.get(zigzag, 1)
p.direction := p.price*p.direction > llastPivot.price*p.direction ? p.direction*2 : p.direction
p.ratio := math.abs(p.price - lastPivot.price)/math.abs(llastPivot.price - lastPivot.price)
array.unshift(zigzag, p)
if(array.size(zigzag)>15)
array.pop(zigzag)
shift(array<Drawing> drawings)=>
del = array.shift(drawings)
line.delete(del.zigzagLine)
label.delete(del.zigzagLabel)
unshift(array<Drawing> drawings, Drawing drawing, int maxItems)=>
array.unshift(drawings, drawing)
if(array.size(drawings) > maxItems)
del = array.pop(drawings)
line.delete(del.zigzagLine)
label.delete(del.zigzagLabel)
if(bandType == 'Bollinger Bands')
[bmiddle, bupper, blower] = eta.bb(close, maType, maLength, multiplier, sticky)
upper := bupper
lower := blower
middle := bmiddle
if(bandType == 'Keltner Channel')
[kmiddle, kupper, klower] = eta.kc(close, maType, maLength, multiplier, useTrueRange, sticky)
upper := kupper
lower := klower
middle := kmiddle
if(bandType == 'Donchian Channel')
[dmiddle, dupper, dlower] = eta.dc(maLength, false, close, sticky)
upper := dupper
lower := dlower
middle := dmiddle
var zigzag = array.new<Pivot>()
var trend = 0
var currentTrend = 0
var currentDir = 0
if(array.size(zigzag) > 1)
recentPivot = array.get(zigzag, 0)
lastPivot = array.get(zigzag, 1)
currentDir := recentPivot.direction
currentTrend := recentPivot.ratio > recentPivot.percentB? int(math.sign(recentPivot.direction)) : -int(math.sign(recentPivot.direction))
trend := lastPivot.ratio > lastPivot.percentB? int(math.sign(lastPivot.direction)) : -int(math.sign(lastPivot.direction))
var uupper = nz(upper)
var llower = nz(lower)
plot(currentDir, 'CurrentDir', display = display.data_window)
uupper := currentDir >= 0 or not useAdaptive? upper : math.min(upper, uupper)
llower := currentDir <= 0 or not useAdaptive? lower : math.max(lower, llower)
percentBHigh = (high - llower)/(uupper - llower)
percentBLow = (uupper - low)/(uupper - llower)
addPivot(zigzag, direction)=>
lastRemoved = false
price = direction > 0? high : low
percentB = direction > 0? percentBHigh : percentBLow
Pivot p = Pivot.new(price, bar_index, time, int(direction), percentB)
if(array.size(zigzag) == 0)
unshift(zigzag, p)
else
lastPivot = array.get(zigzag, 0)
lastPivotDirection = math.sign(lastPivot.direction)
if (lastPivotDirection != p.direction)
unshift(zigzag, p)
if(lastPivotDirection == p.direction and lastPivot.price*direction < p.price*direction)
array.remove(zigzag, 0)
unshift(zigzag, p)
lastRemoved := true
lastRemoved
add_pivots(zigzag, pHigh, pLow)=>
count = 0
removeLast = false
if(array.size(zigzag) == 0)
if(pHigh)
addPivot(zigzag, 1)
count+=1
if(pLow)
addPivot(zigzag, -1)
count+=1
else
lastPivot = array.get(zigzag, 0)
lastDir = math.sign(lastPivot.direction)
if(pHigh and lastDir == 1) or (pLow and lastDir == -1)
removeLast := addPivot(zigzag, lastDir)
count := removeLast ? count+1 : count
if(pHigh and (lastDir == -1)) or (pLow and (lastDir == 1))
addPivot(zigzag, -lastDir)
count+=1
[count, removeLast]
draw_zigzag(zigzag, count, removeLast)=>
var zigzagDrawings = array.new<Drawing>()
if(removeLast and array.size(zigzagDrawings) > 0)
shift(zigzagDrawings)
if(array.size(zigzag) > count and count >= 1)
for i=count to 1
startPivot = array.get(zigzag, count)
endPivot = array.get(zigzag, count-1)
startDirection = startPivot.direction
endDirection = endPivot.direction
lineColor = endDirection == 2? color.green : endDirection == -2? color.red : color.silver
txt = str.tostring(endPivot.ratio*100, format.percent) + "/" + str.tostring(endPivot.percentB*100, format.percent)
ln = line.new(startPivot.bartime, startPivot.price, endPivot.bartime, endPivot.price, xloc.bar_time, color=lineColor, width = 2)
lbl = label.new(endPivot.bartime, endPivot.price, txt, xloc.bar_time, yloc.price, lineColor, endPivot.direction > 0? label.style_label_down : label.style_label_up, textcolor = color.black)
Drawing dr = Drawing.new(ln, lbl)
unshift(zigzagDrawings, dr, 500)
zigzagDrawings
pHigh = high >= uupper
pLow = low <= llower
[count, removeLast] = add_pivots(zigzag, pHigh, pLow)
if(showZigzag)
draw_zigzag(zigzag, count, removeLast)
plot(showBands? uupper:na, 'Upper', color.green, 0, plot.style_linebr)
plot(showBands? llower:na, 'Lower', color.red, 0, plot.style_linebr)
var combinedTrend = 0
combinedTrend := trend>0 and (not useLatestPivot or not (currentTrend < 0))? 1 :
trend < 0 and (not useLatestPivot or not (currentTrend > 0))? -1 : (continueWhenNoConfirmation? 0: combinedTrend)
candleColor = combinedTrend > 0? color.green : combinedTrend < 0 ? color.red : color.silver
plot(combinedTrend, "Trend", candleColor, display = display.data_window)
barcolor(colorCandles? candleColor : na)
|
HTF Tool 2 | https://www.tradingview.com/script/LXbFgeV2-HTF-Tool-2/ | SamRecio | https://www.tradingview.com/u/SamRecio/ | 297 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SamRecio
//
//@version=5
indicator("HTF Tool 2", shorttitle = "[HTF2]", overlay = true, max_boxes_count = 500, max_lines_count = 500)
//General Inputs
tf = input.timeframe("15", title = "Higher Timeframe", tooltip = "Timeframe must be...\n|Greater-than or Equal-to|\nthe Current Chart Timeframe.")
up_color = input.color(color.rgb(0,230,118,70), title = " Up Color", inline = "2")
down_color = input.color(color.rgb(230,30,50,70), title = " Down Color", inline = "2")
//HTF MA Inputs
ma_tog = input.bool(true, title = "", group = "HTF Moving Average", inline = "1" )
len = input.int(13, minval = 1, title = "HTF MA ➡", group = "HTF Moving Average", inline = "1")
ma_type = input.string("EMA", title = "", options = ["EMA","SMA"], group = "HTF Moving Average", inline = "1")
ma_col = input.color(color.rgb(251,192,45), title = "", group = "HTF Moving Average", inline = "1" )
//Lvl 1 Inputs
lvl1_tog = input.bool(false, title = "Lvl 1 ➡ ", group = "measurments", inline = "1", tooltip = "How levels are drawn:\nGreen Candle = High(0.00) to Low(1.00)\nRed Candle = Low(0.00) to High(1.00)")
in_lvl_1 = input.float(0.382, step = 0.01, title = "", group = "measurments", inline = "1")
lvl1_style = input.string(". . .", title = "", options = ["___","- - -",". . ."], group = "measurments", inline = "1")
lvl1_color = input.color(color.white,title = "", group = "measurments", inline = "1")
//Lvl 2 Inputs
lvl2_tog = input.bool(true, title = "Lvl 2 ➡ ", group = "measurments", inline = "2")
in_lvl_2 = input.float(0.5, title = "", step = 0.01, group = "measurments", inline = "2")
lvl2_style = input.string("- - -", title = "", options = ["___","- - -",". . ."], group = "measurments", inline = "2")
lvl2_color = input.color(color.white,title = "", group = "measurments", inline = "2")
//Lvl 3 Inputs
lvl3_tog = input.bool(false, title = "Lvl 3 ➡ ", group = "measurments", inline = "3")
in_lvl_3 = input.float(0.618, title = "", step = 0.01, group = "measurments", inline = "3")
lvl3_style = input.string(". . .", title = "", options = ["___","- - -",". . ."], group = "measurments", inline = "3")
lvl3_color = input.color(color.white,title = "", group = "measurments", inline = "3")
//Lvl Settings
lvl_extend = input.int(10, title = "Extend Levels", tooltip = "# of bars to extend levels past the current bar.\nNote: Value can be negative.")
lb = input.int(30, maxval = 120, minval = 1, title = "Number of HTF Bars to Display:", tooltip = "MinVal = 1\nMaxVal = 120")
//Check for Same TF to make bars clear
tf_check = timeframe.period == tf
//Check for HTF
if timeframe.in_seconds(tf) < timeframe.in_seconds(timeframe.period)
runtime.error("Please use a HIGHER Timeframe.")
//UD type to store candle box and line data, for easy access later
type candle
box body
line high_wick
line low_wick
//red/green/gray coloring function
rg(_open,_close,_color1,_color2,_color3) =>
_close > _open?_color1:
_close < _open?_color2:
_color3
///
//Candle Drawing Function
draw_candle(_o,_h,_l,_c,_left,_right,_rcolor,_gcolor,_ncolor) =>
top = math.max(_o,_c)
bot = math.min(_o,_c)
mid = math.round(math.avg(_left,_right))
rg_color = rg(_o,_c,_gcolor,_rcolor,_ncolor)
candle.new(box.new(_left,top,_right,bot,bgcolor = tf_check?na:rg_color,border_color = tf_check?na:color.new(rg_color,0)),
line.new(mid,top,mid,_h, color = tf_check?na:color.new(rg_color,0)),
line.new(mid,bot,mid,_l, color = tf_check?na:color.new(rg_color,0)))
//Line style translation Function
linestyle(_input) =>
_input == "___"?line.style_solid:
_input == "- - -"?line.style_dashed:
_input == ". . ."?line.style_dotted:
na
///
//The ticking of the clock
new_tf = timeframe.change(tf)
//
//Necessary Candle Data
last_open = ta.valuewhen(new_tf,open,1)
last_left = ta.valuewhen(new_tf,bar_index,1)
current_open = ta.valuewhen(new_tf,open,0)
current_left = ta.valuewhen(new_tf,bar_index,0)
//HTF High/Low Tracking
//Is easier than using Highest/Lowest and it works flawlessly.
var float h = na
var float l = na
if new_tf
h := high
l := low
if low < l
l := low
if high > h
h := high
///////////////////////
//Lvl function for switching level placement depending on bar direction
lvl(_lvl) =>
close>current_open?h-_lvl:l+_lvl
//Lvl Calc
var lvls = array.new_line(na)
rng = h-l
lvl1 = lvl(in_lvl_1*rng)
lvl2 = lvl(in_lvl_2*rng)
lvl3 = lvl(in_lvl_3*rng)
//Draw Historic Candles on New TF
//and Lvls on historic bars
var candle_array = array.new<candle>(na)
var mid_array = array.new_int(na)
if new_tf
array.push(candle_array,draw_candle(last_open,h[1],l[1],close[1],last_left,bar_index-1,down_color,up_color,color.new(color.gray,70)))
array.push(mid_array,math.round(math.avg(last_left,bar_index-1)))
if new_tf and lvl1_tog
array.push(lvls,line.new(last_left,lvl1[1],bar_index-1,lvl1[1], style = linestyle(lvl1_style), color = lvl1_color))
if new_tf and lvl2_tog
array.push(lvls,line.new(last_left,lvl2[1],bar_index-1,lvl2[1], style = linestyle(lvl2_style), color = lvl2_color))
if new_tf and lvl3_tog
array.push(lvls,line.new(last_left,lvl3[1],bar_index-1,lvl3[1], style = linestyle(lvl3_style), color = lvl3_color))
//Lvl Line Management (Dynamic deletion)
lb_bi = ta.valuewhen(new_tf,bar_index,lb-1) //lookback bar_index
if array.size(lvls) > 0
for i = array.size(lvls) - 1 to 0
lx = array.get(lvls,i)
lx_left = line.get_x1(lx)
lx_lvl = line.get_y1(lx)
cross = (lx_lvl >= close[1] and lx_lvl < close) or (lx_lvl <= close[1] and lx_lvl > close) or (lx_lvl < math.max(open,close) and lx_lvl > math.min(open,close))
toofar = lx_left < lb_bi
if cross or toofar
line.delete(lx)
array.remove(lvls,i)
line.set_x2(lx,bar_index+lvl_extend)
//Drawing live candle
live_candle = draw_candle(current_open,h,l,close,current_left,bar_index,down_color,up_color,color.new(color.gray,70))
box.delete(live_candle.body[1])
line.delete(live_candle.high_wick[1])
line.delete(live_candle.low_wick[1])
//Deleting HTF bars past the lookback number
if array.size(candle_array) > lb-1
box.delete(array.get(candle_array,0).body)
line.delete(array.get(candle_array,0).high_wick)
line.delete(array.get(candle_array,0).low_wick)
array.remove(candle_array,0)
//Live Levels
var ll1 = line.new(na,na,na,na, style = linestyle(lvl1_style), color = lvl1_color)
var ll2 = line.new(na,na,na,na, style = linestyle(lvl2_style), color = lvl2_color)
var ll3 = line.new(na,na,na,na, style = linestyle(lvl3_style), color = lvl3_color)
//Setting Live LVL Values
if lvl1_tog
line.set_xy1(ll1,current_left,lvl1)
line.set_xy2(ll1,bar_index+lvl_extend,lvl1)
if lvl2_tog
line.set_xy1(ll2,current_left,lvl2)
line.set_xy2(ll2,bar_index+lvl_extend,lvl2)
if lvl3_tog
line.set_xy1(ll3,current_left,lvl3)
line.set_xy2(ll3,bar_index+lvl_extend,lvl3)
//MOVING AVERAGE STUFF
//close array(for SMA)
var close_array = array.new_float(na)
if new_tf
array.push(close_array,close[1])
if new_tf and array.size(close_array) > len
array.remove(close_array,0)
//Calculating Historic MA values to append to the historic MA
k = 2/(len + 1)
var float ma = na
if new_tf and ma_type == "EMA"
ma := (close[1]*k) + (nz(ma[1])*(1-k))
if new_tf and ma_type == "SMA"
ma := array.avg(close_array)
//Initiating variables fo draw the mas
var ma_array = array.new_line(na)
last_mid = array.size(mid_array)>1?array.get(mid_array,array.size(mid_array)-1):na
prev_last_mid = array.size(mid_array)>1?array.get(mid_array,array.size(mid_array)-2):na
//Adds a line to the MA every new bar
if new_tf and ma_tog
array.push(ma_array,line.new(prev_last_mid,ma[1],last_mid,ma, width = 2, color = ma_col))
if array.size(ma_array) > lb-1
line.delete(array.get(ma_array,0))
array.remove(ma_array,0)
//Tip of the MA
//Calculating Averages
htf_sma = array.size(close_array) > 0?((array.sum(close_array) - array.get(close_array,0))+close)/len:na
htf_ema = (close*k) + (nz(ma[1])*(1-k))
htf_ma = ma_type == "EMA"?htf_ema:htf_sma
//Drawing the Tip
if ma_tog
live_line = line.new(last_mid,ma,bar_index,htf_ma, width = 2, color = ma_col)
line.delete(live_line[1])
//Plotting for values
plot(ma_tog?htf_ma:na,show_last = 1, title = "HTF_MA",editable = false, display = ma_tog?display.price_scale + display.status_line:display.none, color = ma_col)
|
RSI Pull-Back | https://www.tradingview.com/script/NMbiLIqS-RSI-Pull-Back/ | Sofien-Kaabar | https://www.tradingview.com/u/Sofien-Kaabar/ | 198 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sofien-Kaabar
//@version=5
indicator("RSI Pull-Back", overlay = true)
lookback = input(defval = 14, title = 'Lookback')
lower_barrier = input(defval = 30, title = 'Lower Barrier')
lower_threshold = input(defval = 40, title = 'Lower Threshold')
upper_barrier = input(defval = 70, title = 'Upper Barrier')
upper_threshold = input(defval = 60, title = 'Upper Threshold')
rsi = ta.rsi(close, lookback)
buy_signal = rsi >= lower_barrier and rsi < rsi[1] and rsi[1] > lower_barrier and rsi[1] < lower_threshold and rsi[2] < lower_barrier
sell_signal = rsi <= upper_barrier and rsi > rsi[1] and rsi[1] < upper_barrier and rsi[1] > upper_threshold and rsi[2] > upper_barrier
plotshape(buy_signal, style = shape.triangleup, color = color.blue, location = location.belowbar, size = size.small)
plotshape(sell_signal, style = shape.triangledown, color = color.orange, location = location.abovebar, size = size.small)
|
Sort array alphabetically - educational | https://www.tradingview.com/script/LVEJF1Iy-Sort-array-alphabetically-educational/ | fikira | https://www.tradingview.com/u/fikira/ | 58 | study | 5 | MPL-2.0 | fi(ki)=>'ra' // ©fikira - This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator (title="Sort array alphabetically" , overlay= true)
_=" –––––––––––{ A. INPUT }––––––––––– "
toLowCase = input.bool(defval= true, title= "To Lower Case")
_=" –––––––––––{ A. User Defined Type (UDT) }––––––––––– "
type obj
string ticker = na
float price = na
_=" –––––––––––{ B. Array's }––––––––––– "
aObj = array.new <obj> ()
sort = array.new<string>()
_=" –––––––––––{ C. Function which creates an object 'obj' }––––––––––– "
createObject(sym) => obj.new(ticker= sym, price= request.security(sym, 'D', close[1], barmerge.gaps_off, barmerge.lookahead_on, true))
toLowerCase (str) => toLowCase ? str.lower(str) : str
_=" –––––––––––{ D. Create Objects, add to array's }––––––––––– "
_=" –––––––––––{ 1. createObject() }––––––––––– "
_=" –––––––––––{ 2. add object to array 'aObj' }––––––––––– "
_=" –––––––––––{ 3. add object.ticker to array 'sort' }––––––––––– "
_=" –––––––––––{ -> with option to lower case }––––––––––– "
GOOG = createObject("GOOG" ), array.unshift(aObj, GOOG ), array.unshift(sort, toLowerCase(GOOG.ticker ))
AMZN = createObject("AMZN" ), array.unshift(aObj, AMZN ), array.unshift(sort, toLowerCase(AMZN.ticker ))
GME = createObject("GME" ), array.unshift(aObj, GME ), array.unshift(sort, toLowerCase(GME.ticker ))
ETH = createObject("ETHUSDT"), array.unshift(aObj, ETH ), array.unshift(sort, toLowerCase(ETH.ticker ))
AAPL = createObject("AAPL" ), array.unshift(aObj, AAPL ), array.unshift(sort, toLowerCase(AAPL.ticker ))
gold = createObject("gold" ), array.unshift(aObj, gold ), array.unshift(sort, toLowerCase(gold.ticker ))
SILK = createObject("SILK" ), array.unshift(aObj, SILK ), array.unshift(sort, toLowerCase(SILK.ticker ))
TSLA = createObject("TSLA" ), array.unshift(aObj, TSLA ), array.unshift(sort, toLowerCase(TSLA.ticker ))
BTC = createObject("BTCUSDT"), array.unshift(aObj, BTC ), array.unshift(sort, toLowerCase(BTC.ticker ))
silver = createObject("silver" ), array.unshift(aObj, silver), array.unshift(sort, toLowerCase(silver.ticker))
ROKU = createObject("ROKU" ), array.unshift(aObj, ROKU ), array.unshift(sort, toLowerCase(ROKU.ticker ))
_=" –––––––––––{ E. Sort array 'sort' alphabetically }––––––––––– "
sort_Indices = array.sort_indices(id= sort, order= order.ascending)
_=" –––––––––––{ F. Place sorted data in table }––––––––––– "
if barstate.islastconfirmedhistory
arr_Size = array.size(id= aObj)
var tabl = table.new (position= position.top_right, columns= 2, rows= arr_Size)
for i = 0 to arr_Size -1
even = i % 2 == 0
cBg = even ? #43ffdd : #8e43ff
cTx = even ? #971010 : #e4fffc
get = array.get(id= aObj, index = array.get(id= sort_Indices, index=i))
table.cell(table_id= tabl, column= 0, row= i, text= get.ticker, text_font_family=font.family_monospace, text_color= cTx, bgcolor= cBg)
table.cell(table_id= tabl, column= 1, row= i, text= str.tostring(get.price), text_font_family=font.family_monospace, text_color= cTx, bgcolor= cBg)
_=" –––––––––––{ G. END }––––––––––– "
|
RAINBOW_13th | https://www.tradingview.com/script/DSuLTrqa-RAINBOW-13th/ | shakibsharifian | https://www.tradingview.com/u/shakibsharifian/ | 46 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © shakibsharifian
//@version=5
indicator("RAINBOW_13th",overlay=true)
varip string optTopo1="EMA"
varip string optTopo2="RMA"
varip string optTopo3="WMA"
varip string optTopo4="RSI"
varip string optTopo5="RSI_ATR"
varip string optTopo6="CMO"
//PARETO 20% 80% rule
//PDF=a(x_m)^a/(x^(a+1)); x_m: min value in range; a: pareto ratio
paretoMEAN(src,length,mult)=>
float sum=0
x_m=ta.lowest(src,length)
//PDF=mult*math.pow(x_m,mult)/math.pow(x,mult+1)
//var sum:=0
float coefSum=0
for int _i=0 to length-1
_coef=mult*math.pow(x_m,mult)/math.pow(src[_i],mult+1)
sum:=sum+(_coef*src[_i])
coefSum:=coefSum+_coef
_paretoMean=sum/coefSum
_paretoMean
gaussianMEAN(src,length)=>
float sum=0
for int _i=0 to length-1
sum:=sum+src[_i]
_mean=sum/length
sum:=0
for int _i=0 to length-1
sum:=sum+(math.pow((_mean-src[_i]),2))
_variance=sum/length
_std=math.sqrt(_variance)
sum:=0
float coefSum=0
for int _i=0 to length-1
_coef=(1/(_std*math.sqrt(2*3.1415)))*math.exp(-.5*math.pow(((src[_i]-_mean)/_std),2))
sum:=sum+(_coef*src[_i])
coefSum:=coefSum+_coef
_gaussMean=sum/coefSum
_gaussMean
eval(_src,_bk,i_TopoType)=>
float val = switch i_TopoType
optTopo1 =>ta.ema(_src,_bk)
optTopo2 =>ta.rma(_src,_bk)
optTopo3 =>ta.wma(_src,_bk)
optTopo4 =>ta.rsi(_src,_bk)
optTopo5 =>ta.rsi(ta.atr(_bk),_bk)
optTopo6 =>ta.cmo(_src,_bk)
val
src = input.source(hl2, title='SOURCE',group='GENERAL',inline='a')
bk = input.int(52, minval=1, title='LENGTH',group='GENERAL',inline='b')
isPareto = input.bool(true, title='Draw Pareto Mean',group='GENERAL',inline='c')
isGauss = input.bool(false, title='Draw Gaussian Mean',group='GENERAL',inline='d')
mult = input.float(1, minval=0.1, title='Pareto shape parameter',group='GENERAL',inline='c')
cont = input.int(70, minval=0, title='TRANSPARENCY',group='DISPLAY',inline='a')
bndL = input.int(40, minval=0, title='OVER BOUGHT RSI',group='RSI',inline='a')
bndH = input.int(60, minval=0, title='OVER SOLD RSI',group='RSI',inline='a')
string _i_TopoType = input.string(defval="EMA", title="METHOD", options = [optTopo1,optTopo2, optTopo3,optTopo4,optTopo5,optTopo6],group='GENERAL',inline='a')
txtOpt1="Auto"
txtOpt2="Tiny"
txtOpt3="Small"
txtOpt4="Normal"
txtOpt5="Large"
string listSize = input.string('Auto',title='STATUS SIZE',options=[txtOpt1,txtOpt2,txtOpt3,txtOpt4,txtOpt5],group='DISPLAY',inline='b')
lstSz = switch listSize
txtOpt1 => size.auto
txtOpt2 => size.tiny
txtOpt3 => size.small
txtOpt4 => size.normal
txtOpt5 => size.large
ema1=eval(src,bk ,_i_TopoType)
ema2=eval(ema1,bk ,_i_TopoType)
ema3=eval(ema2,bk ,_i_TopoType)
ema4=eval(ema3,bk ,_i_TopoType)
ema5=eval(ema4,bk ,_i_TopoType)
ema6=eval(ema5,bk ,_i_TopoType)
ema7=eval(ema6,bk ,_i_TopoType)
ema8=eval(ema7,bk ,_i_TopoType)
ema9=eval(ema8,bk ,_i_TopoType)
ema10=eval(ema9,bk ,_i_TopoType)
ema11=eval(ema10,bk,_i_TopoType)
ema12=eval(ema11,bk,_i_TopoType)
ema13=eval(ema12,bk,_i_TopoType)
EMA= ema1
DEMA= (2*ema1)- ema2
TEMA= (3*ema1)- (3*ema2)+ ema3
QEMA= (4*ema1)- (6*ema2)+ (4*ema3)- ema4
QUIEMA= (5*ema1)-(10*ema2)+ (10*ema3)- (5*ema4)+ ema5
SEMA= (6*ema1)-(15*ema2)+ (20*ema3)- (15*ema4)+ (6*ema5)- ema6
SEPEMA= (7*ema1)-(21*ema2)+ (35*ema3)- (35*ema4)+ (21*ema5)- (7*ema6)+ ema7
OCTEMA= (8*ema1)-(28*ema2)+ (56*ema3)- (70*ema4)+ (56*ema5)- (28*ema6)+ (8*ema7)- ema8
NONEMA= (9*ema1)-(36*ema2)+ (84*ema3)-(126*ema4)+(126*ema5)- (84*ema6)+ (36*ema7)- (9*ema8)+ ema9
DECEMA= (10*ema1)-(45*ema2)+ (120*ema3)-(210*ema4)+(252*ema5)-(210*ema6)+(120*ema7)- (45*ema8)+ (10*ema9)- ema10
EMA11th= (11*ema1)-(55*ema2)+ (165*ema3)-(330*ema4)+(462*ema5)-(462*ema6)+(330*ema7)-(165*ema8)+ (55*ema9)-(11*ema10)+ ema11
EMA12th= (12*ema1)-(66*ema2)+ (220*ema3)-(495*ema4)+(792*ema5)-(924*ema6)+(792*ema7)-(495*ema8)+(220*ema9)-(66*ema10)+(12*ema11)-ema12
EMA13th= (13*ema1)-(78*ema2)+ (286*ema3)-(715*ema4)+(1287*ema5)-(1716*ema6)+(1716*ema7)-(1287*ema8)+(715*ema9)-(286*ema10)+(78*ema11)-13*ema12+ema13
color13=color.new(#fc0303,cont)
color12=color.new(#fc0703,cont)
color11=color.new(#fc5603,cont)
color10=color.new(#fc7703,cont)
color9=color.new(#fc9d03,cont)
color8=color.new(#fcca03,cont)
color7=color.new(#fcd703,cont)
color6=color.new(#d3fc03,cont)
color5=color.new(#9dfc03,cont)
color4=color.new(#62fc03,cont)
color3=color.new(#03fc7b,cont)
color2=color.new(#03fcf8,cont)
color1=color.new(#03d3fc,cont)
L1=plot(EMA, color=color1 ,linewidth=1,title='1st LINE')
L2=plot(DEMA, color=color2 ,linewidth=1,title='2nd LINE')
L3=plot(TEMA, color=color3 ,linewidth=1,title='3rd LINE')
L4=plot(QEMA, color=color4 ,linewidth=1,title='4th LINE')
L5=plot(QUIEMA,color= color5,linewidth=1,title='5th LINE')
L6=plot(SEMA, color= color6,linewidth=1,title='6th LINE')
L7=plot(SEPEMA,color= color7,linewidth=1,title='7th LINE')
L8=plot(OCTEMA,color=color8 ,linewidth=1,title='8th LINE')
L9=plot(NONEMA,color=color9 ,linewidth=1,title='9th LINE')
L10=plot(DECEMA,color=color10,linewidth=1,title='10 LINE')
L11=plot(EMA11th,color=color11,linewidth=1,title='11 LINE')
L12=plot(EMA12th,color=color12,linewidth=1,title='12 LINE')
L13=plot(EMA13th,color=color13,linewidth=1,title='13 LINE')
fill(L1,L2, color=color1)
fill(L2,L3, color=color2)
fill(L3,L4, color=color3)
fill(L4,L5, color=color4)
fill(L5,L6, color=color5)
fill(L6,L7, color=color6)
fill(L7,L8, color=color7)
fill(L8,L9, color=color8)
fill(L9,L10,color=color9)
fill(L10,L11,color=color10)
fill(L11,L12,color=color11)
fill(L12,L13,color=color12)
var t = table.new(position.middle_right, 2, 14, color.rgb(240, 240, 126))
table.cell(t,0, 0,'BUY',bgcolor=color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 0,'SELL',bgcolor=color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
buyAssignment=0.0
sellAssignment=0.0
thisLine1=src
thisLine2=src
if _i_TopoType!=(optTopo4) and _i_TopoType!=(optTopo5) and _i_TopoType!=(optTopo6)
buyAssignment:= src<EMA?buyAssignment+1:buyAssignment
sellAssignment:= src>EMA?sellAssignment+1:sellAssignment
buyAssignment:= src<DEMA?buyAssignment+1:buyAssignment
sellAssignment:= src>DEMA?sellAssignment+1:sellAssignment
buyAssignment:= src<TEMA?buyAssignment+1:buyAssignment
sellAssignment:= src>TEMA?sellAssignment+1:sellAssignment
buyAssignment:= src<QEMA?buyAssignment+1:buyAssignment
sellAssignment:= src>QEMA?sellAssignment+1:sellAssignment
buyAssignment:= src<QUIEMA?buyAssignment+1:buyAssignment
sellAssignment:= src>QUIEMA?sellAssignment+1:sellAssignment
buyAssignment:= src<SEMA?buyAssignment+1:buyAssignment
sellAssignment:= src>SEMA?sellAssignment+1:sellAssignment
buyAssignment:= src<SEPEMA?buyAssignment+1:buyAssignment
sellAssignment:= src>SEPEMA?sellAssignment+1:sellAssignment
buyAssignment:= src<OCTEMA?buyAssignment+1:buyAssignment
sellAssignment:= src>OCTEMA?sellAssignment+1:sellAssignment
buyAssignment:= src<NONEMA?buyAssignment+1:buyAssignment
sellAssignment:= src>NONEMA?sellAssignment+1:sellAssignment
buyAssignment:= src<DECEMA?buyAssignment+1:buyAssignment
sellAssignment:= src>DECEMA?sellAssignment+1:sellAssignment
buyAssignment:= src<EMA11th?buyAssignment+1:buyAssignment
sellAssignment:= src>EMA11th?sellAssignment+1:sellAssignment
buyAssignment:= src<EMA12th?buyAssignment+1:buyAssignment
sellAssignment:= src>EMA12th?sellAssignment+1:sellAssignment
buyAssignment:= src<EMA13th?buyAssignment+1:buyAssignment
sellAssignment:= src>EMA13th?sellAssignment+1:sellAssignment
else
thisLine1:=bndH
thisLine2:=bndL
buyAssignment:= bndL>EMA?buyAssignment+0.8:buyAssignment
buyAssignment:= bndH>EMA?buyAssignment+0.2:buyAssignment
sellAssignment:= bndH<EMA?sellAssignment+0.8:sellAssignment
sellAssignment:= bndL<EMA?sellAssignment+0.2:sellAssignment
buyAssignment:= bndL>DEMA?buyAssignment+0.8:buyAssignment
buyAssignment:= bndH>DEMA?buyAssignment+0.2:buyAssignment
sellAssignment:= bndH<DEMA?sellAssignment+0.8:sellAssignment
sellAssignment:= bndL<DEMA?sellAssignment+0.2:sellAssignment
buyAssignment:= bndL>TEMA?buyAssignment+0.8:buyAssignment
buyAssignment:= bndH>TEMA?buyAssignment+0.2:buyAssignment
sellAssignment:= bndH<TEMA?sellAssignment+0.8:sellAssignment
sellAssignment:= bndL<TEMA?sellAssignment+0.2:sellAssignment
buyAssignment:= bndL>QEMA?buyAssignment+0.8:buyAssignment
buyAssignment:= bndH>QEMA?buyAssignment+0.2:buyAssignment
sellAssignment:= bndH<QEMA?sellAssignment+0.8:sellAssignment
sellAssignment:= bndL<QEMA?sellAssignment+0.2:sellAssignment
buyAssignment:= bndL>QUIEMA?buyAssignment+0.8:buyAssignment
buyAssignment:= bndH>QUIEMA?buyAssignment+0.2:buyAssignment
sellAssignment:= bndH<QUIEMA?sellAssignment+0.8:sellAssignment
sellAssignment:= bndL<QUIEMA?sellAssignment+0.2:sellAssignment
buyAssignment:= bndL>SEMA?buyAssignment+0.8:buyAssignment
buyAssignment:= bndH>SEMA?buyAssignment+0.2:buyAssignment
sellAssignment:= bndH<SEMA?sellAssignment+0.8:sellAssignment
sellAssignment:= bndL<SEMA?sellAssignment+0.2:sellAssignment
buyAssignment:= bndL>SEPEMA?buyAssignment+0.8:buyAssignment
buyAssignment:= bndH>SEPEMA?buyAssignment+0.2:buyAssignment
sellAssignment:= bndH<SEPEMA?sellAssignment+0.8:sellAssignment
sellAssignment:= bndL<SEPEMA?sellAssignment+0.2:sellAssignment
buyAssignment:= bndL>OCTEMA?buyAssignment+0.8:buyAssignment
buyAssignment:= bndH>OCTEMA?buyAssignment+0.2:buyAssignment
sellAssignment:= bndH<OCTEMA?sellAssignment+0.8:sellAssignment
sellAssignment:= bndL<OCTEMA?sellAssignment+0.2:sellAssignment
buyAssignment:= bndL>NONEMA?buyAssignment+0.8:buyAssignment
buyAssignment:= bndH>NONEMA?buyAssignment+0.2:buyAssignment
sellAssignment:= bndH<NONEMA?sellAssignment+0.8:sellAssignment
sellAssignment:= bndL<NONEMA?sellAssignment+0.2:sellAssignment
buyAssignment:= bndL>DECEMA?buyAssignment+0.8:buyAssignment
buyAssignment:= bndH>DECEMA?buyAssignment+0.2:buyAssignment
sellAssignment:= bndH<DECEMA?sellAssignment+0.8:sellAssignment
sellAssignment:= bndL<DECEMA?sellAssignment+0.2:sellAssignment
buyAssignment:= bndL>EMA11th?buyAssignment+0.8:buyAssignment
buyAssignment:= bndH>EMA11th?buyAssignment+0.2:buyAssignment
sellAssignment:= bndH<EMA11th?sellAssignment+0.8:sellAssignment
sellAssignment:= bndL<EMA11th?sellAssignment+0.2:sellAssignment
buyAssignment:= bndL>EMA12th?buyAssignment+0.8:buyAssignment
buyAssignment:= bndH>EMA12th?buyAssignment+0.2:buyAssignment
sellAssignment:= bndH<EMA12th?sellAssignment+0.8:sellAssignment
sellAssignment:= bndL<EMA12th?sellAssignment+0.2:sellAssignment
buyAssignment:= bndL>EMA13th?buyAssignment+0.8:buyAssignment
buyAssignment:= bndH>EMA13th?buyAssignment+0.2:buyAssignment
sellAssignment:= bndH<EMA13th?sellAssignment+0.8:sellAssignment
sellAssignment:= bndL<EMA13th?sellAssignment+0.2:sellAssignment
line1 = line.new(bar_index, thisLine1,bar_index + 1, thisLine1,color = color.new(color.white,0) , style=line.style_dashed,extend = extend.both)
line2 = line.new(bar_index, thisLine2, bar_index + 1,thisLine2,color = color.new(color.white,0) , style=line.style_dashed,extend = extend.both)
line.delete(line1[1])
line.delete(line2[1])
table.cell(t,0, 1,' ',bgcolor=buyAssignment>12?color.new(#1eff00, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 1,' ',bgcolor=sellAssignment>12?color.new(#ff5100, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,0, 2,' ',bgcolor=buyAssignment>11?color.new(#1eff00, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 2,' ',bgcolor=sellAssignment>11?color.new(#ff5100, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,0, 3,' ',bgcolor=buyAssignment>10?color.new(#1eff00, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 3,' ',bgcolor=sellAssignment>10?color.new(#ff5100, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,0, 4,' ',bgcolor=buyAssignment>9?color.new(#1eff00, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 4,' ',bgcolor=sellAssignment>9?color.new(#ff5100, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,0, 5,' ',bgcolor=buyAssignment>8?color.new(#1eff00, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 5,' ',bgcolor=sellAssignment>8?color.new(#ff5100, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,0, 6,' ',bgcolor=buyAssignment>7?color.new(#1eff00, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 6,' ',bgcolor=sellAssignment>7?color.new(#ff5100, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,0, 7,' ☰ ',bgcolor=buyAssignment>6?color.new(#86f777, 0):color.new(#424449, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 7,' ☰ ',bgcolor=sellAssignment>6?color.new(#f39d75, 0):color.new(#424449, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,0, 8,' ',bgcolor=buyAssignment>5?color.new(#1eff00, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 8,' ',bgcolor=sellAssignment>5?color.new(#ff5100, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,0, 9,' ',bgcolor=buyAssignment>4?color.new(#1eff00, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 9,' ',bgcolor=sellAssignment>4?color.new(#ff5100, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,0, 10,' ',bgcolor=buyAssignment>3?color.new(#1eff00, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 10,' ',bgcolor=sellAssignment>3?color.new(#ff5100, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,0, 11,' ',bgcolor=buyAssignment>2?color.new(#1eff00, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 11,' ',bgcolor=sellAssignment>2?color.new(#ff5100, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,0, 12,' ',bgcolor=buyAssignment>1?color.new(#1eff00, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 12,' ',bgcolor=sellAssignment>1?color.new(#ff5100, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,0, 13,' ',bgcolor=buyAssignment>0?color.new(#1eff00, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
table.cell(t,1, 13,' ',bgcolor=sellAssignment>0?color.new(#ff5100, 0):color.new(color.black, 0),text_color=color.yellow,text_size=lstSz)
plot(isPareto==true?paretoMEAN(src,bk,mult):EMA,title='Pareto Mean',color=isPareto==true?color.white:color1,linewidth=1)
plot(isGauss==true?gaussianMEAN(src,bk):EMA,title='Gaussian Mean',color=isGauss==true?color.rgb(236, 214, 13):color1,linewidth=1) |
[potatoshop] Volume Profile lower timeframe | https://www.tradingview.com/script/A5VAgcme-potatoshop-Volume-Profile-lower-timeframe/ | potatoshop | https://www.tradingview.com/u/potatoshop/ | 491 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © potatoshop
//@version=5
indicator('[potatoshop] Volume Profile lower timeframe', 'VP LTF', overlay = true, max_boxes_count = 500)
TF = input.timeframe("10S","Resolution of bars used for VP calculation")
[lo,lh,ll,lc,lv] = request.security_lower_tf(syminfo.tickerid,TF,[open,high,low,close,volume])
Currentchart = timeframe.in_seconds(timeframe.period)
LTFqty = math.ceil(Currentchart/ timeframe.in_seconds(TF))
plot(LTFqty,display = display.status_line)
length = input.int(100, 'Lookback length', minval=1, maxval=1000, group='Volume Profile Basic')
row = input.int(15, 'Row Size', minval=1, maxval=500, group='Volume Profile Basic')
check_label = input.bool(true,"Show the qty and qty_percent", group='Option')
check_poc = input.bool(false,"Show POC line", group='Option')
check_Tpoc = input.bool(false,"Show TPOC line", group='Option')
check_reversal = input.bool(false,"Show Reversal line", group='Option')
check_up_dn_box = input.bool(false,"Show up down Box", group='Option')
text_position = input.string("1","Text side",options = ["1","2"])
width = input.int(50, 'Width (% of the box)', minval=1, maxval=100, group='Style')
line_width = input.int(2, 'Line(Poc,Reversal) Width', group='Style')
flip = input.bool(false, 'Flip Histogram', group='Style')
Area_color = input.color(color.rgb(33, 149, 243,97), 'Area_color',inline ="0", group='Color Style')
Area_text_color = input.color(color.rgb(139, 147, 167), 'Area_text_color ',inline ="0", group='Color Style')
TPOC_color = input.color(color.rgb(205, 243, 33, 68), 'TPOC_color ', group='Color Style')
poc_color = input.color(#ff5d00, 'POC line Color', group='Color Style')
Reversal_color = input.color(#fafcfc, 'Revarsal Line Color', group='Color Style')
Box_color = input.color(#2156f341, 'Box_color',inline ="1", group='Total Color Style')
Box_text_color = input.bool(true,"",inline ="1", group='Total Color Style') ? input.color(#e4e6ec41, 'text_color ',inline ="1", group='Total Color Style') : chart.fg_color
Box_color_bull = input.color(#2d97fb, 'Box_color',inline = "2", group='Bull Color Style')
text_color_bull = input.bool(true,"",inline ="2", group='Bull Color Style') ? input.color(#e2d1d1, 'text_color',inline = "2", group='Bull Color Style') : chart.fg_color
Box_color_bear = input.color(#ff6929, 'Box_color',inline = "3", group='Bear Color Style')
text_color_bear = input.bool(true,"",inline ="3", group='Bear Color Style') ? input.color(#040817, 'text_color',inline = "3", group='Bear Color Style') : chart.fg_color
/////////////////////////////////////////////////////////////////////////////////////////////////////////
sum_V = 0.
for i = length-1 to 0 by 1
sum_V := sum_V + volume[i]
highest = ta.highest(length)
lowest = ta.lowest(length)
//Dividing range
divBlock = (highest - lowest) / row
block = array.new_float(row,0.)
block_v = array.new_float(row,0.)
for i = 0 to row-1 by 1
array.set(block,i,lowest+i*divBlock)
show = table.new(position.top_center,1,5,bgcolor = color.rgb(43, 128, 57, 93), border_width = 1)
show2 = table.new(position.middle_right,1,row+1,bgcolor = color.rgb(43, 128, 57, 93), border_width = 1)
Tpoc_arr = array.new_float(row, 0.)
Bull_v = array.new_float(row , 0.)
Bear_v = array.new_float(row , 0.)
reversal_arr = array.new_int(row , 0)
var unconfirmedBox = array.new_box()
var unconfirmedBox_up = array.new_box()
var unconfirmedBox_dn = array.new_box()
line poc = na
box Tpoc = na
box last_area = na
var reversal = array.new_line()
maxTpoc = 0.
Vm = volume
var total_cell_V = 0.
ctime = time_close
mtime = (time+time_close)/2
lengthtime = time-time[length]
con = barstate.islast
if con
if array.size(unconfirmedBox) > 0
for i = 0 to array.size(unconfirmedBox) - 1
box.delete(array.shift(unconfirmedBox))
if check_up_dn_box
box.delete(array.shift(unconfirmedBox_up))
box.delete(array.shift(unconfirmedBox_dn))
if array.size(reversal) > 0
for i = 0 to array.size(reversal) - 1
line.delete(array.shift(reversal))
for Level = 0 to row-1
sum = 0.
sum_T = 0.
up_sum = 0.
dn_sum = 0.
for j = length-1 to 1 by 1
if array.size(lv[j]) == LTFqty
for i = 0 to LTFqty-1 by 1
ltf_H = array.get(lh[j],i) , ltf_L = array.get(ll[j],i)
ltf_C = array.get(lc[j],i) , ltf_O = array.get(lo[j],i)
ltf_V = array.get(lv[j],i)
gap = (ltf_H-ltf_L)/syminfo.mintick > 1 ? (ltf_H-ltf_L)/syminfo.mintick : 1
unit_T = (1/syminfo.mintick) /(gap)
unit_V = (ltf_V/syminfo.mintick) /(gap)
top_cut = math.min(ltf_H,array.get(block,Level)+divBlock) , bottom_cut = math.max(ltf_L,array.get(block,Level))
gap_T = math.abs(top_cut - bottom_cut)*unit_T
gap_V = math.abs(top_cut - bottom_cut)*unit_V
sum := ltf_H > array.get(block, Level) and ltf_L < (array.get(block, Level)+divBlock) ? sum + gap_V : sum
sum_T := ltf_H > array.get(block, Level) and ltf_L < (array.get(block, Level)+divBlock) ? sum_T + gap_T : sum_T
if ltf_C > ltf_O
up_sum := ltf_H > array.get(block, Level) and ltf_L < (array.get(block, Level)+divBlock) ? up_sum + gap_V : up_sum
else
dn_sum := ltf_H > array.get(block, Level) and ltf_L < (array.get(block, Level)+divBlock) ? dn_sum + gap_V : dn_sum
for [i,value] in lv
ltf_H = array.get(lh,i) , ltf_L = array.get(ll,i)
ltf_C = array.get(lc,i) , ltf_O = array.get(lo,i)
ltf_V = array.get(lv,i)
gap = (ltf_H-ltf_L)/syminfo.mintick > 1 ? (ltf_H-ltf_L)/syminfo.mintick : 1
unit_T = (1/syminfo.mintick) /(gap)
unit_V = (ltf_V/syminfo.mintick) /(gap)
top_cut = math.min(ltf_H,array.get(block,Level)+divBlock) , bottom_cut = math.max(ltf_L,array.get(block,Level))
gap_T = math.abs(top_cut - bottom_cut)*unit_T
gap_V = math.abs(top_cut - bottom_cut)*unit_V
sum := ltf_H > array.get(block, Level) and ltf_L < (array.get(block, Level)+divBlock) ? sum + gap_V : sum
sum_T := ltf_H > array.get(block, Level) and ltf_L < (array.get(block, Level)+divBlock) ? sum_T + gap_T : sum_T
if ltf_C > ltf_O
up_sum := ltf_H > array.get(block, Level) and ltf_L < (array.get(block, Level)+divBlock) ? up_sum + gap_V : up_sum
else
dn_sum := ltf_H > array.get(block, Level) and ltf_L < (array.get(block, Level)+divBlock) ? dn_sum + gap_V : dn_sum
array.set(block_v,Level,sum)
array.set(Bull_v,Level, up_sum)
array.set(Bear_v,Level, dn_sum)
array.set(Tpoc_arr,Level, dn_sum)
if up_sum > dn_sum
array.set(reversal_arr,Level,1)
maxTpoc := array.indexof(Tpoc_arr,array.max(Tpoc_arr))
for j = 0 to row-1 by 1
total_cell_V := array.sum(block_v)
ssum = array.get(block_v, j)
mult = ssum / array.max(block_v)
perV = ssum / total_cell_V *100
get = array.get(block, j)
ssum_up = array.get(Bull_v, j)
mult_up = ssum_up / array.max(block_v)
perV_up = ssum_up / total_cell_V *100
ssum_dn = array.get(Bear_v, j)
mult_dn = ssum_dn / array.max(block_v)
perV_dn = ssum_dn / total_cell_V *100
bottom = lowest + (j+0.05)*divBlock
bottom_up = lowest + (j+0.55)*divBlock
bottom_dn = lowest + (j+0.05)*divBlock
top = lowest + (j+0.95)*divBlock
top_up = lowest + (j+0.95)*divBlock
top_dn = lowest + (j+0.45)*divBlock
if flip
array.push(unconfirmedBox, box.new(mtime , top ,ctime - math.round(lengthtime * width / 100 * mult), bottom,xloc = xloc.bar_time, border_color= color.new(Box_color,100), bgcolor = Box_color ,
text_halign = text_position == "1" ? text.align_left : text.align_right, text_valign=text.align_bottom , text_size = size.small , text_color = Box_text_color,
text = check_label ? str.tostring(perV,format.percent)+" "+str.tostring(ssum, format.volume) : na))
if check_up_dn_box
array.push(unconfirmedBox_up, box.new(mtime,top_up,ctime - math.round(lengthtime * width / 100 * mult_up), bottom_up,xloc = xloc.bar_time, border_color= color.new(Box_color_bull,100), bgcolor = Box_color_bull ,
text_halign = text_position == "1" ? text.align_right : text.align_left, text_valign=text.align_bottom , text_size = size.small , text_color = text_color_bull,
text = check_label ? str.tostring(perV_up,format.percent)+" "+str.tostring(ssum_up, format.volume) : na))
array.push(unconfirmedBox_dn, box.new(mtime,top_dn,ctime - math.round(lengthtime * width / 100 * mult_dn), bottom_dn,xloc = xloc.bar_time, border_color= color.new(Box_color_bear,100), bgcolor = Box_color_bear ,
text_halign = text_position == "1" ? text.align_right : text.align_left, text_valign=text.align_bottom , text_size = size.small , text_color = text_color_bear,
text = check_label ? str.tostring(perV_dn,format.percent)+" "+str.tostring(ssum_dn, format.volume) : na))
if not flip
array.push(unconfirmedBox, box.new(mtime - lengthtime ,top, mtime - lengthtime + math.round(lengthtime * width / 100 * mult), bottom,xloc = xloc.bar_time, border_color= color.new(Box_color,100), bgcolor = Box_color ,
text_halign= text_position == "1" ? text.align_right : text.align_left , text_valign=text.align_bottom , text_size = size.small , text_color = Box_text_color,
text = check_label ? str.tostring(perV,format.percent)+" "+str.tostring(ssum, format.volume) : na))
if check_up_dn_box
array.push(unconfirmedBox_up, box.new(mtime - lengthtime ,top_up, mtime - lengthtime + math.round(lengthtime * width / 100 * mult_up), bottom_up,xloc = xloc.bar_time, border_color= color.new(Box_color_bull,100), bgcolor = Box_color_bull ,
text_halign= text_position == "1" ? text.align_left : text.align_right, text_valign=text.align_bottom , text_size = size.small , text_color = text_color_bull,
text = check_label ? str.tostring(perV_up,format.percent)+" "+str.tostring(ssum_up, format.volume) : na))
array.push(unconfirmedBox_dn, box.new(mtime - lengthtime ,top_dn, mtime - lengthtime + math.round(lengthtime * width / 100 * mult_dn), bottom_dn,xloc = xloc.bar_time, border_color= color.new(Box_color_bear,100), bgcolor = Box_color_bear ,
text_halign= text_position == "1" ? text.align_left : text.align_right, text_valign=text.align_bottom , text_size = size.small , text_color = text_color_bear,
text = check_label ? str.tostring(perV_dn,format.percent)+" "+str.tostring(ssum_dn, format.volume) : na))
if mult == 1 and check_poc
line.delete(poc[1])
avg = math.avg(get, (array.get(block, j)+divBlock))
if flip
poc := line.new(mtime, avg, ctime - lengthtime, avg,xloc = xloc.bar_time, color = poc_color , style = line.style_dotted , width = line_width)
else
poc := line.new(mtime - lengthtime, avg, ctime, avg,xloc = xloc.bar_time, color = poc_color , style = line.style_dotted , width = line_width)
if maxTpoc == j and check_Tpoc
box.delete(Tpoc[1])
Tpoc := box.new(mtime - lengthtime ,top, ctime, bottom,xloc = xloc.bar_time, border_color= color.new(TPOC_color,100), bgcolor = TPOC_color ,
text_halign=text.align_right, text_valign=text.align_bottom , text_size = size.small , text_color = Box_text_color,
text = check_label ? "TPOC" : na)
con_reversal = row-1 > j ? array.get(reversal_arr,j+1) != array.get(reversal_arr,j) : false
if check_reversal and con_reversal
array.push(reversal, line.new(mtime - lengthtime,get+divBlock ,ctime ,get+divBlock, xloc = xloc.bar_time ,color = Reversal_color, style = line.style_dotted , width = line_width ))
box.delete(last_area[1])
last_area := box.new(mtime - lengthtime ,highest ,ctime ,lowest,xloc = xloc.bar_time, border_color=color.rgb(33, 149, 243, 80),
bgcolor = Area_color ,text="Highest : "+str.tostring(highest,format.mintick)+ "\n Lowest : "+str.tostring(lowest,format.mintick) +"\n Total cell V: "+ str.tostring(total_cell_V,format.volume)+ "\n Direct T_V : "+str.tostring(sum_V,format.volume) ,
text_halign= flip? text.align_left : text.align_right, text_valign=text.align_bottom, text_size=size.tiny ,text_color= Area_text_color)
|
Market Structure MA Based BOS [liwei666] | https://www.tradingview.com/script/TP8ScS2r-Market-Structure-MA-Based-BOS-liwei666/ | liwei666 | https://www.tradingview.com/u/liwei666/ | 762 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © liwei666
//@version=5
// # ========================================================================= #
// # | ma_based_bos Indicator |
// # ========================================================================= #
indicator(
title = "Market Structure MA Based BOS",
shorttitle = "ma_based_bos",
overlay = true,
max_lines_count = 500,
max_labels_count = 500,
max_boxes_count = 500,
max_bars_back = 5000
)
// # ========================================================================= #
// # | ma_based_bos Indicator |
// # ========================================================================= #
// --------------- Inputs ---------------
smoothing = input.string(title="MA_Type", defval="HMA", options=["RMA", "SMA", "EMA", "WMA", "HMA"], group = 'GRP1')
short_ma_len = input.int(defval = 30, title = "short_ma_len", minval = 5 , maxval = 240 , step = 1 , tooltip = "短MA长度", inline = "11", group = 'GRP1')
show_short_zz = input(false, title='Show short-len Zigzag', inline = "22", group='GRP2')
show_ma_cross_signal = input(false, title='Show ma cross signal', inline = "22", group='GRP2')
zzstyle = input.string(defval='Dashed', title='Zig Zag Line Styles', options=['Dashed', 'Dotted', 'Solid'], group='GRP2')
// --------------- Inputs ---------------
// --------------- vars ---------------
var max_arr_size = 300
var short_ma_color = color.red
short_ma_color := nz(short_ma_color[1], color.red)
var line short_zzline = na
var line short_bosline = na
var label short_bos_lb = na
color label_transp = #ffffff00
var short_pivot_l_arr = array.new_float(size = max_arr_size, initial_value = 0.0)
var short_pivot_h_arr = array.new_float(size = max_arr_size, initial_value = 0.0)
var short_lowestestbar_offset_arr = array.new_int(size = max_arr_size, initial_value = 0)
var short_highestbar_offset_arr = array.new_int(size = max_arr_size, initial_value = 0)
var s_bos_high_arr = array.new_bool(size = 1, initial_value = false)
var s_bos_low_arr = array.new_bool(size = 1, initial_value = false)
// --------------- vars ---------------
// --------------- Functions ---------------
add_to_zigzag(arr, value) =>
array.unshift(arr, value)
if array.size(arr) > max_arr_size
array.pop(arr)
ma_function(source, length) =>
float ma = switch smoothing
"RMA" => nz(ta.rma(source, length), source)
"SMA" => nz(ta.sma(source, length), source)
"EMA" => nz(ta.ema(source, length), source)
"HMA" => nz(ta.hma(source, length), source)
"WMA" => nz(ta.wma(source, length), source)
=> nz(ta.wma(source, length), source)
ma
is_first_break(bos_arr, i) =>
val = array.get(id = bos_arr, index = i)
if val == true
false
else
true
// --------------- Functions ---------------
// --------------- Calculate Pivots ---------------
short_ma = ma_function(close, short_ma_len)
// -- short ma calulate
var s_ma_continue_len = 2
s_ma_continue_len := nz(s_ma_continue_len[1], 2)
int short_highestbar_offset = - ta.highestbars(high, s_ma_continue_len)
int short_lowestbar_offset = - ta.lowestbars(low, s_ma_continue_len)
float short_pivot_h = ta.highest(high, s_ma_continue_len)
float short_pivot_l = ta.lowest(low, s_ma_continue_len)
short_ma_cu = ta.crossunder(source1 = close, source2 = short_ma)
short_ma_co = ta.crossover(source1 = close, source2 = short_ma)
bool alert_bos_high = false
bool alert_bos_low = false
if short_ma_co
// 上穿找 lowest
add_to_zigzag(short_pivot_l_arr, short_pivot_l)
add_to_zigzag(short_lowestestbar_offset_arr, short_lowestbar_offset)
short_ma_color := color.new(#0cdb6d, 10)
barindex0 = math.round(array.get(short_lowestestbar_offset_arr, 0))
price0 = array.get(short_pivot_l_arr, 0)
barindex1 = math.round(array.get(short_highestbar_offset_arr, 0)) + s_ma_continue_len
price1 = array.get(short_pivot_h_arr, 0)
if show_short_zz
short_zzline := line.new(x1 = bar_index[barindex0], y1 = price0, x2 = bar_index[barindex1], y2 = price1, color = color.red, style = line.style_solid )
// labelText = 'H,' + str.tostring(price0) + ',' + str.tostring(barindex0) + ',' + str.tostring(price1) + ',' + str.tostring(barindex1)
// label.new(x = bar_index[short_lowestbar_offset], y = short_pivot_l , text = labelText, yloc = yloc.belowbar , style=label.style_label_up, textcolor = color.white)
// 将barindex更新,下面的判断BOS需要用
array.set(short_highestbar_offset_arr, 0, barindex1)
s_ma_continue_len := 1
// 重置突破前低为初始值
array.fill(s_bos_low_arr, false)
else if short_ma_cu
// 下穿找 highest
add_to_zigzag(short_pivot_h_arr, short_pivot_h)
add_to_zigzag(short_highestbar_offset_arr, short_highestbar_offset)
// 改颜色
short_ma_color := color.red
price0 = array.get(short_pivot_h_arr, 0)
barindex0 = math.round(array.get(short_highestbar_offset_arr, 0))
price1 = array.get(short_pivot_l_arr, 0)
barindex1 = math.round(array.get(short_lowestestbar_offset_arr, 0)) + s_ma_continue_len
if show_short_zz
short_zzline := line.new(x1 = bar_index[barindex0], y1 = price0, x2 = bar_index[barindex1], y2 = price1, color = color.red, style = line.style_solid )
// 将barindex更新,下面的判断BOS需要用
array.set(short_lowestestbar_offset_arr, 0, barindex1)
s_ma_continue_len := 1
// 重置突破前高为初始值
array.fill(s_bos_high_arr, false)
else
s_ma_continue_len := s_ma_continue_len + 1
// 判断是否BOS
// break ligh
for i = 0 to array.size(s_bos_high_arr) - 1
if (close[2] < array.get(short_pivot_h_arr, i) or close[1] < array.get(short_pivot_h_arr, i)) and close > array.get(short_pivot_h_arr, i)
// 判断是否首次突破
if is_first_break(s_bos_high_arr, i)
// 首次突破,赋值
array.set(s_bos_high_arr, i , value = true)
price0 = array.get(short_pivot_h_arr, i)
barindex0 = 0
for j = 0 to i
barindex0 += array.get(short_highestbar_offset_arr, j)
if j == 0
barindex0 += s_ma_continue_len
price1 = array.get(short_pivot_h_arr, i)
barindex1 = 0
labelText = 'L,' + str.tostring(price0) + ',' + str.tostring(barindex0) + ',' + str.tostring(barindex1)
//label.new(x = bar_index[barindex0], y = price0 , text = labelText, yloc = yloc.belowbar , style=label.style_label_up, textcolor = color.white)
short_bosline := line.new(x1 = bar_index[barindex0], y1 = price0, x2 = bar_index[barindex1], y2 = price1,
color = color.new(#0cdb6d, 10), style = line.style_solid, width=1)
short_bos_lb := label.new(int(math.avg(bar_index[barindex0],bar_index[barindex1] )), price1, color = label_transp, text="BOS",
textcolor = color.new(#0cdb6d, 10), size=size.small, style = label.style_label_down)
alert_bos_high := true
// 判断break low
for i = 0 to array.size(s_bos_low_arr) - 1
if (close[2] > array.get(short_pivot_l_arr, i) or close[1] > array.get(short_pivot_l_arr, i)) and close < array.get(short_pivot_l_arr, i)
// 判断是否首次突破
if is_first_break(s_bos_low_arr, i)
// 首次突破,赋值
array.set(s_bos_low_arr, i , value = true)
price0 = array.get(short_pivot_l_arr, i)
barindex0 = 0
for j = 0 to i
barindex0 += array.get(short_lowestestbar_offset_arr, j)
if j == 0
barindex0 += s_ma_continue_len
price1 = array.get(short_pivot_l_arr, i)
barindex1 = 0
labelText = 'H,' + str.tostring(price0) + ',' + str.tostring(barindex0) + ',' + str.tostring(barindex1)
//label.new(x = bar_index[barindex0], y = price0 , text = labelText, yloc = yloc.abovebar , style=label.style_label_up, textcolor = color.white)
short_bosline := line.new(x1 = bar_index[barindex0], y1 = price0, x2 = bar_index[barindex1], y2 = price1, color = color.red, style = line.style_solid )
short_bos_lb := label.new(int(math.avg(bar_index[barindex0],bar_index[barindex1] )), price1, color = label_transp, text="BOS",
textcolor = color.red, size=size.small, style = label.style_label_up)
alert_bos_low := true
plot(short_ma,color = short_ma_color)
// 画出短ma上下穿标识
short_ma_long_signal = short_ma_co and show_ma_cross_signal
plotchar(short_ma_long_signal, "s_co", "▲", location.belowbar, color = color.blue, size = size.tiny)
short_ma_short_signal = short_ma_cu and show_ma_cross_signal
plotchar(short_ma_short_signal, "s_cu", "▼", location.abovebar, color = color.red, size = size.tiny)
// add alert when bos-high or bos-low
alertcondition(alert_bos_high, title='bos_high', message='BOS High, {{ticker}}, {{close}}, {{timenow}}')
alertcondition(alert_bos_low, title='bos_low', message='BOS Low, {{ticker}}, {{close}}, {{timenow}}') |
Chart Time and Price Range | https://www.tradingview.com/script/GE9StfUy-Chart-Time-and-Price-Range/ | kurtsmock | https://www.tradingview.com/u/kurtsmock/ | 60 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kurtsmock
//@version=5
indicator("Chart Range", overlay=true, max_bars_back = 4000)
import PineCoders/VisibleChart/4 as t
bCol = input.color(color.black, "Border Color")
tCol = input.color(color.black, "Text Color")
pos = input.string("Top Right", "Position", options=["Top Right","Top Left","Top Center","Bottom Right","Bottom Left","Bottom Center","Middle Right","Middle Left","Middle Center"])
size = input.string("Small", "Size", options=["Tiny","Small","Normal","Large","Huge","Auto"])
o_pos = switch pos
"Top Right" => position.top_right
"Top Left" => position.top_left
"Top Center" => position.top_center
"Bottom Right" => position.bottom_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Middle Right" => position.middle_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
=> position.top_right
o_size = switch size
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
"Auto" => size.auto
// Chart Time Span
leftBarTime() =>
var int result = na
if time == chart.left_visible_bar_time
result := time
result
timeSpan = (time - leftBarTime()) / 1000
inSec = (timeSpan % 60), inMin = 0, inHrs = 0, inDys = 0
timeUnit = ""
if timeSpan >= 60
inMin := math.floor(timeSpan / 60)
if inMin >= 60
inHrs := math.floor(inMin / 60)
inMin := inMin - (60 * inHrs)
if inHrs > 23
inDys := math.floor(timeSpan / 86400)
inHrs := (((timeSpan % 86400) / 60) / 60)
if timeframe.isdwm
inSec := 0
inMin := 0
inHrs := 0
timeUnit := inDys >= 1 ? str.tostring(inDys) + (inDys == 1 ? " Day. " : " Days. ") : ""
timeUnit := timeUnit + (inHrs > 0 or (inDys > 0 and inMin > 0) ? str.format("{0,number,integer}",inHrs) + (inHrs == 1 ? " Hour. " : " Hours. ") : "")
timeUnit := timeUnit + (inMin > 0 ? str.format("{0,number,integer}",inMin) + " Minutes. ": "")
timeUnit := timeUnit + (inSec > 0 and (timeSpan % 60 != 0) ? str.format("{0,number,integer}", inSec) + " Seconds." : "")
// Chart Range
// Credit for Function: PineCoders: VisibleChart https://www.tradingview.com/script/j7vCseM2-VisibleChart/
leftBarIndex() =>
var int result = na
if time == chart.left_visible_bar_time
result := bar_index
result
startBar = bar_index - t.leftBarIndex()
lowPrice = ta.lowest(nz(math.max(1,startBar),1))
highPrice = ta.highest(nz(math.max(1,startBar),1))
rngPts = (highPrice - lowPrice)
rngTck = (highPrice - lowPrice)/syminfo.mintick
// Display
t = table.new(o_pos, 3,1,frame_color = bCol, frame_width = 1, border_color = bCol, border_width = 1)
cellWidth = o_size == size.small ? 3 : 0
table.cell(t, 0,0, str.tostring(rngPts) + " Pts", width=cellWidth, text_size=o_size, text_color=tCol)
table.cell(t, 1,0, str.tostring(rngTck) + " Ticks", width=cellWidth, text_size=o_size, text_color=tCol)
timeWidth = o_size == size.small ? timeframe.isdwm ? 3 : 7 : 0
table.cell(t, 2,0, timeUnit, width=timeWidth, text_size=o_size, text_color=tCol) |
Kalman Filter [by Hajixde] | https://www.tradingview.com/script/E18JPuKn-Kalman-Filter-by-Hajixde/ | hajixde | https://www.tradingview.com/u/hajixde/ | 51 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hajixde
//@version=5
indicator("Kalman by Hajixde", overlay = true, timeframe = "")
findSlope(src, N) =>
float I = na
float s = na
n = N > 5000 ? 4999 : N
M1 = 0.0
M2 = 0.0
M3 = 0.0
M4 = 0.0
M5 = 0.0
M6 = 0.0
MN = 0.0
if n > 2
for i = 0 to n-1
M1 := M1 + src[i]
M2 := M2 + bar_index[i]*bar_index[i]
M3 := M3 + bar_index[i]
M4 := M4 + bar_index[i]*src[i]
M5 := M5 + src[i]
s := (n*M4 - M3*M1) / (n*M2 - M3*M3)
I := (M1 - s*M3) / (n)
[s, I]
src = input.source(close, "Source")
n1=input.int(100, title = "Model length", minval = 2)
kf_gain1 = input.float(0.3, title = "Kalman gain", step = 0.05, minval = 0, maxval = 1)
n2=input.int(250, title = "Model length", minval = 2)
kf_gain2 = input.float(0.1, title = "Kalman gain", step = 0.05, minval = 0, maxval = 1)
lnCol1 = input.color(color.yellow, title = "Color")
lnCol2 = input.color(color.aqua, title = "Color")
float EST1 = 0.0
float EST2 = 0.0
[s1, I1] = findSlope(src, n1)
[s2, I2] = findSlope(src, n2)
E1 = na(EST1[1]) ? 0.0 : EST1[1]
E2 = na(EST2[1]) ? 0.0 : EST2[1]
error1 = src - E1
error2 = src - E2
EST1 := s1*(bar_index) + I1 + error1*kf_gain1
EST2 := s2*(bar_index) + I2 + error2*kf_gain2
plot(EST1 , offset = 1, color = lnCol1, title = "Kalman Fitting Curve 1")
plot(EST2 , offset = 1, color = lnCol2, title = "Kalman Fitting Curve 2")
|
Basic Position Calculator (BPC) | https://www.tradingview.com/script/6gJ93YnC-Basic-Position-Calculator-BPC/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 55 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("Basic Position Calculator", "BPC", true)
account = input.float(25000, "Account Size")
risk_amount = input.float(10, "Risk Amount %")
stop_loss = input.float(0.25, "Stop Loss", 0, 100, 0.25)
reward = input.float(2, "Reward")
style = input.string("Top Right", "Position",
["Bottom Left","Bottom Middle","Bottom Right","Middle Left","Middle Center","Middle Right",
"Top Left","Top Middle","Top Right"])
txt_col = input.color(color.new(#c8d7ff, 0), "Title Color", inline = "bull", group = "Settings")
box_col = input.color(color.new(#202236, 10), "", inline = "bull", group = "Settings")
location() =>
switch style
"Bottom Left" => position.bottom_left
"Bottom Middle" => position.bottom_center
"Bottom Right" => position.bottom_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Top Left" => position.top_left
"Top Middle" => position.top_center
"Top Right" => position.top_right
risk_amount_percent = (risk_amount/100)*account
position_size = (risk_amount_percent/stop_loss)
take_profit = (stop_loss/100)*open * reward
stop = (stop_loss/100)*open
exit_price = open + take_profit
stop_price = open - stop
var tbl = table.new(location(), 2, 8)
if barstate.islast
table.cell(tbl, 0, 0, "Account Size", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 1, "Position Size", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 2, "Account Risk %", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 3, "Stop Loss", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 4, "Stop Loss %", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 5, "Take Profit", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 6, "Take Profit %", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 7, "Risk Reward Ratio", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 1, 0, str.tostring(account), text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 1, 1, str.tostring((position_size >= risk_amount_percent ? risk_amount_percent : position_size)), text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 1, 2, str.tostring(risk_amount)+"%", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 1, 3, str.tostring(stop_price), text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 1, 4, str.tostring(stop_loss), text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 1, 5, str.tostring(exit_price), text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 1, 6, str.tostring(risk_amount*reward), text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 1, 7, str.tostring(reward), text_color = txt_col, bgcolor = box_col)
plot(exit_price)
plot(stop_price)
|
ICT Killzones [LuxAlgo] | https://www.tradingview.com/script/bmFFb5Rt-ICT-Killzones-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 3,231 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("ICT Killzones [LuxAlgo]"
, overlay = true
, max_lines_count = 500
, max_labels_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
//New York
showNy = input(true, 'New York', inline = 'ny', group = 'Killzones')
nyCss = input.color(color.new(#ff5d00, 80), '', inline = 'ny', group = 'Killzones')
//London Open
showLdno = input(true, 'London Open', inline = 'ldno', group = 'Killzones')
ldnoCss = input.color(color.new(#00bcd4, 80), '', inline = 'ldno', group = 'Killzones')
//London Close
showLdnc = input(true, 'London Close', inline = 'ldnc', group = 'Killzones')
ldncCss = input.color(color.new(#2157f3, 80), '', inline = 'ldnc', group = 'Killzones')
//Asian
showAsia = input(true, 'Asian', inline = 'asia', group = 'Killzones')
asiaCss = input.color(color.new(#e91e63, 80), '', inline = 'asia', group = 'Killzones')
//Fib Retracements
showFibs = input(true, 'Show Retracements', group = 'Killzones Retracements')
extend = input(true, 'Extend', group = 'Killzones Retracements')
reverse = input(false, 'Reverse', group = 'Killzones Retracements')
//Fib 0
fib0 = input(true, '', inline = '0', group = 'Killzones Retracements')
fib0Value = input(0., '', inline = '0', group = 'Killzones Retracements')
fib0Css = input(color.gray, '', inline = '0', group = 'Killzones Retracements')
//Fib 0.236
fib236 = input(true, '', inline = '0', group = 'Killzones Retracements')
fib236Value = input(0.236, '', inline = '0', group = 'Killzones Retracements')
fib236Css = input(color.yellow, '', inline = '0', group = 'Killzones Retracements')
//Fib 0.382
fib382 = input(true, '', inline = '382', group = 'Killzones Retracements')
fib382Value = input(0.382, '', inline = '382', group = 'Killzones Retracements')
fib382Css = input(color.fuchsia, '', inline = '382', group = 'Killzones Retracements')
//Fib 0.5
fib5 = input(true, '', inline = '382', group = 'Killzones Retracements')
fib5Value = input(0.5, '', inline = '382', group = 'Killzones Retracements')
fib5Css = input(color.orange, '', inline = '382', group = 'Killzones Retracements')
//Fib 0.618
fib618 = input(true, '', inline = '618', group = 'Killzones Retracements')
fib618Value = input(0.618, '', inline = '618', group = 'Killzones Retracements')
fib618Css = input(color.blue, '', inline = '618', group = 'Killzones Retracements')
//Fib 0.782
fib782 = input(true, '', inline = '618', group = 'Killzones Retracements')
fib782Value = input(0.782, '', inline = '618', group = 'Killzones Retracements')
fib782Css = input(color.green, '', inline = '618', group = 'Killzones Retracements')
//Fib 1
fib1 = input(true, '', inline = '1', group = 'Killzones Retracements')
fib1Value = input(1., '', inline = '1', group = 'Killzones Retracements')
fib1Css = input(color.gray, '', inline = '1', group = 'Killzones Retracements')
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
n = bar_index
avg(val, max, min)=>
var float fib = na
if reverse
fib := val * min + (1 - val) * max
else
fib := val * max + (1 - val) * min
fib_values()=>
var fibs = array.from(
fib0 ? fib0Value : na
, fib236 ? fib236Value : na
, fib382 ? fib382Value : na
, fib5 ? fib5Value : na
, fib618 ? fib618Value : na
, fib782 ? fib782Value : na
, fib1 ? fib1Value : na)
display_retracements(session)=>
var lines = array.new_line(0)
fibs = fib_values()
var float max = na
var float min = na
if session and not session[1]
max := high
min := low
lines := array.from(
line.new(n,na,na,na, color = fib0Css)
, line.new(n,na,na,na, color = fib236Css)
, line.new(n,na,na,na, color = fib382Css)
, line.new(n,na,na,na, color = fib5Css)
, line.new(n,na,na,na, color = fib618Css)
, line.new(n,na,na,na, color = fib782Css)
, line.new(n,na,na,na, color = fib1Css))
if session
max := math.max(high, max)
min := math.min(low, min)
for [i, lvl] in lines
fib = array.get(fibs, i)
line.set_y1(lvl, avg(fib, max, min))
line.set_xy2(lvl, n, avg(fib, max, min))
else if extend
for [i, lvl] in lines
fib = array.get(fibs, i)
line.set_y1(lvl, avg(fib, max, min))
line.set_xy2(lvl, n, avg(fib, max, min))
labels(session, css, txt)=>
var label lbl = na
var float max = na
var int anchor = na
var get_css = color.rgb(color.r(css), color.g(css), color.b(css))
if session and not session[1]
max := high
anchor := time
lbl := label.new(anchor, max
, txt
, xloc.bar_time
, color = #ffffff00
, style = label.style_label_down
, textcolor = get_css
, size = size.small)
if session
max := math.max(high, max)
label.set_x(lbl, int(math.avg(time, anchor)))
label.set_y(lbl, max)
//-----------------------------------------------------------------------------}
//Retracements
//-----------------------------------------------------------------------------{
ny = time(timeframe.period, '0700-0900', 'UTC-5') and showNy
ldn_open = time(timeframe.period, '0200-0500', 'UTC-5') and showLdno
ldn_close = time(timeframe.period, '1000-1200', 'UTC-5') and showLdnc
asian = time(timeframe.period, '2000-0000', 'UTC-5') and showAsia
if showFibs
display_retracements(ldn_open or ldn_close or ny or asian)
//-----------------------------------------------------------------------------}
//Labels
//-----------------------------------------------------------------------------{
labels(ny, nyCss, 'New York')
labels(ldn_open, ldnoCss, 'London Open')
labels(ldn_close, ldncCss, 'London Close')
labels(asian, asiaCss, 'Asian')
//-----------------------------------------------------------------------------}
//Background
//-----------------------------------------------------------------------------{
bgcolor(ny ? nyCss : na, editable = false)
bgcolor(ldn_open ? ldnoCss : na, editable = false)
bgcolor(ldn_close ? ldncCss : na, editable = false)
bgcolor(asian ? asiaCss : na, editable = false)
//-----------------------------------------------------------------------------} |
HL-D Close Fraction Oscillator | Adulari | https://www.tradingview.com/script/JezxmE0z-HL-D-Close-Fraction-Oscillator-Adulari/ | Adulari | https://www.tradingview.com/u/Adulari/ | 51 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ©Adulari
// @version=5
indicator("HL-D Close Fraction Oscillator | Adulari",precision=2)
// Inputs
length = input.int(20,minval=2,title='Length',group='General Settings')
smoothing = input.int(20,minval=2,title='Smoothing',group='General Settings')
maType = input.string('SMA',options=['SMA','EMA','RMA','WMA','VWMA','HMA'],title='MA Type',group='General Settings')
smoothingType = input.string('SMA',options=['SMA','EMA','RMA','WMA','VWMA','HMA'],title='Smoothing Type',group='General Settings')
signals = input.bool(false,title='Signals',tooltip='Show signals when value crosses below oversold line or crosses above overbought line.',group='General Settings')
lookback = input.int(1,minval=1,title='Lookback',group='Advanced Settings')
rescaleBarsBack = input.int(200,minval=20,title='Rescale Bars Back',group='Advanced Settings')
// Functions
rescale(float value, float oldMin, float oldMax, float newMin, float newMax) =>
newMin + (newMax - newMin) * (value - oldMin) / math.max(oldMax - oldMin, 10e-10)
ma(float source, simple int length, string maType) =>
switch maType
'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)
'HMA' => ta.hma(source, length)
// Calculations
value = close>close[lookback] ? (high-low)/close : (low-high)/close
value := ma(value,length,maType)
value := rescale(value,ta.lowest(value,rescaleBarsBack),ta.highest(value,rescaleBarsBack),0,100)
signal = ma(value,smoothing,smoothingType)
// Colors
beColor = #675F76
buColor = #a472ff
// Plots
pValue = plot(value,color=buColor,title='Value',linewidth=1)
pSignal = plot(signal,color=beColor,title='Signal',linewidth=1)
fill(pValue,pSignal,color=value>signal ? color.new(buColor,95) : color.new(beColor,95),title='Trend Fill')
hline(80,title='Upper Line',color=beColor)
hline(50,title='Middle Line',color=color.new(color.gray,50))
hline(20,title='Lower Line',color=buColor)
plotshape(signals ? ta.crossunder(value,20) ? 20 : na : na,'Bullish Signal',style=shape.circle,location=location.absolute,size=size.tiny,color=buColor)
plotshape(signals ? ta.crossover(value,80) ? 80 : na : na,'Bearish Signal',style=shape.xcross,location=location.absolute,size=size.tiny,color=beColor) |
Supply and Demand Zone Confirmation | https://www.tradingview.com/script/v4cIFqvK-Supply-and-Demand-Zone-Confirmation/ | MBCryptocurrency | https://www.tradingview.com/u/MBCryptocurrency/ | 377 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MBCryptocurrency
//@version=5
indicator("Supply and Demand Zone","MB Supply & Demand" , overlay=true, timeframe="", timeframe_gaps=false)
//CCI
length1 = input.int(20,'CCI length', minval=1, group="CCI Settings")
src1 = input(hlc3, title="Source" , group="CCI Settings")
ma = ta.sma(src1, length1)
cci = (src1 - ma) / (0.015 * ta.dev(src1, length1))
band0 = input.int(-100, "Lower Band" , group="CCI Settings")
band1 = input.int(100, "Upper Band" , group="CCI Settings")
band2= input.int(-150, "Lower Low Band" , group="CCI Settings")
band3= input.int(150, "Upper up Band" , group="CCI Settings")
ma(source1, length1, type) =>
switch type
"SMA" => ta.sma(source1, length1)
"EMA" => ta.ema(source1, length1)
"SMMA (RMA)" => ta.rma(source1, length1)
"WMA" => ta.wma(source1, length1)
"VWMA" => ta.vwma(source1, length1)
timeframe1= input.timeframe('15','First CCI timeframe' , group="CCI Timeframe Settings")
timeframe2= input.timeframe('60','second CCI timeframe' , group="CCI Timeframe Settings")
CCI1= request.security(syminfo.tickerid, timeframe1 ,cci,gaps = barmerge.gaps_off)
plot(CCI1, join= true,display= display.none)
CCI2= request.security(syminfo.tickerid, timeframe2,cci,gaps = barmerge.gaps_off)
plot(CCI2, join= true,display= display.none)
///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 MA Settings")
maLengthInput = input.int(14, title="MA Length", group="RSI MA Settings")
bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev", group="RSI MA 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"
timeframe=input.timeframe('15', "RSI timeframe", group="RSI Settings")
rsi15= request.security(syminfo.tickerid, timeframe,rsi)
plot(rsi, "RSI", color=#7E57C2, display = display.none)
plot(rsiMA, "RSI-based MA", color=color.yellow, display = display.none)
rsiUpperBand = input.int(65, "RSI Upper Band", group="OverBought/OverSold Settings")
midline=input.int(50, "RSI Middle Band", group="OverBought/OverSold Settings")
rsiLowerBand = input.int(35, "RSI Lower Band", group="OverBought/OverSold Settings")
bbUpperBand = plot(isBB ? rsiMA + ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Upper Bollinger Band", color=color.green, display = display.none)
bbLowerBand = plot(isBB ? rsiMA - ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Lower Bollinger Band", color=color.green, display = display.none)
fill(bbUpperBand, bbLowerBand, color= isBB ? color.new(color.green, 90) : na, title="Bollinger Bands Background Fill", display = display.none)
cross= ta.cross(cci,band0)
//condition
signal_buy = false
signal_sell = false
if CCI1 < band0 and CCI2 < band2 and rsiMA < rsiLowerBand and rsi15 < midline //buy when long time is above zero and short time is below zero
signal_buy := true
if CCI1 > band1 and CCI2 > band3 and rsiMA > rsiUpperBand and rsi15 > midline //sell when long time is below zero and short time is above zero
signal_sell := true
//only first signal to show
Buy = false
Sell = false
Buy := signal_buy ? true : signal_sell ? false : cross ? false : Buy[1]
Sell := signal_sell ? true : signal_buy ? false : cross ? false : Sell[1]
Final_buy = signal_buy and not (Buy[1])
Final_sell = signal_sell and not (Sell[1])
// alerts
alertcondition(Final_buy, "Buy", "Time to Buy")
alertcondition(Final_sell , "Sell", "Time to Sell")
//plotshapes
plotshape(Final_sell, title="Sell", style = shape.triangledown, color=color.rgb(255, 0, 0, 50) , size = size.small, location = location.abovebar, text = "Sell Zone", textcolor= color.yellow)
plotshape(Final_buy, title="Buy", style = shape.triangleup, color=color.rgb(0, 255, 0, 50) , size = size.small, location = location.belowbar, text = "Buy Zone", textcolor= color.blue)
|
Adaptative EMA | https://www.tradingview.com/script/Q5HoDd8p-Adaptative-EMA/ | benjaminhay | https://www.tradingview.com/u/benjaminhay/ | 11 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © benjaminhay
//@version=5
indicator("Adaptative EMA", overlay = true)
averageData = input.source(close, title="Average Data Source")
dailyTimeframeFastEma = input.int(8, "D and higher fast EMA length")
dailyTimeframeSlowEma = input.int(21, "D and higher slow EMA length")
lowerTimeframeFastEma = input.int(21, "intraday fast EMA length")
lowerTimeframeSlowEma = input.int(50, "intraday slow EMA length")
fastAverage = ta.ema(averageData, 8)
slowAverage = ta.ema(averageData, 21)
if timeframe.isintraday
fastAverage := ta.ema(averageData, lowerTimeframeFastEma)
slowAverage := ta.ema(averageData, lowerTimeframeSlowEma)
else
fastAverage := ta.ema(averageData, dailyTimeframeFastEma)
slowAverage := ta.ema(averageData, dailyTimeframeSlowEma)
plot(fastAverage, color=color.aqua, title="Fast EMA", linewidth=2)
plot(slowAverage, color=color.fuchsia, title="Slow EMA", linewidth=2)
|
Pivot High/Low Comparison | https://www.tradingview.com/script/oQr3PVh2-Pivot-High-Low-Comparison/ | rmunoz | https://www.tradingview.com/u/rmunoz/ | 170 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © rmunoz
//@version=5
indicator("Pivot High/Low Comparison", overlay = true)
leftBars = input(3)
rightBars=input(3)
pivotHigh = ta.pivothigh(high, leftBars, rightBars)
mostRecentPH = ta.valuewhen(pivotHigh > 0, pivotHigh, 0)
secondMostRecentPH = ta.valuewhen(pivotHigh > 0, pivotHigh, 1)
phColor = color.black
pivotLow = ta.pivotlow(low, leftBars, rightBars)
mostRecentPL = ta.valuewhen(pivotLow > 0, pivotLow, 0)
secondMostRecentPL = ta.valuewhen(pivotLow > 0, pivotLow, 1)
plColor = color.black
if mostRecentPH > secondMostRecentPH
phColor := color.green
else
phColor := color.red
if mostRecentPL > secondMostRecentPL
plColor := color.green
else
plColor := color.red
plot(pivotHigh, style=plot.style_line, linewidth = 1, color = phColor, offset = -rightBars)
plot(pivotLow, style=plot.style_line, linewidth = 1, color = plColor, offset = -rightBars)
plot(pivotHigh, style=plot.style_circles, linewidth = 3, color = phColor, offset = -rightBars)
plot(pivotLow, style=plot.style_circles, linewidth = 3, color = plColor, offset = -rightBars)
|
RSI Multi Length With Divergence Alert [Skiploss] | https://www.tradingview.com/script/2GUnT6UY-RSI-Multi-Length-With-Divergence-Alert-Skiploss/ | Skiploss | https://www.tradingview.com/u/Skiploss/ | 286 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Skiploss
// This is a modified indicator base code from RSI Multi Length [LUX] and we will added some of fuction by finding a classic/hidden divergence
//@version=5
indicator(title = "RSI Multi Length With Divergence Alert [Skiploss]", shorttitle = "RMLWDA v0.77")
// RSI Setting
length_max = input(20, 'Maximum Length', group = 'RSI Setting')
length_min = input(10, 'Minimum Length', group = 'RSI Setting')
level_overbought = input.float(70, 'Overboght Level', step = 5, group = 'RSI Setting')
level_oversold = input.float(30, 'Oversold Level', step = 5, group = 'RSI Setting')
rsi_source = input(close, 'Source', group = 'RSI Setting')
// MA Setting
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"Bollinger Bands" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
ma_type = input.string("EMA", title = "MA Type", options = ["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group = "RSI Base MA Settings")
ma_length = input.int(14, title = "MA Length", group="RSI Base MA Settings")
// Divergence Setting
pivot_look_back_right = input(title = "Pivot Right", defval = 7, group = 'Divergence Setting')
pivot_look_back_left = input(title = "Pivot Left", defval = 7, group = 'Divergence Setting')
rangeUpper = input(title = "Max Range", defval = 60, group = 'Divergence Setting')
rangeLower = input(title = "Min Range", defval = 5, group = 'Divergence Setting')
//Display Settings
plot_ma_base_rsi = input(title = "RSI Base MA", defval = false, group = 'Display Setting')
plotBull = input(title = "Classic Bullish Divergence", defval = true, group = 'Display Setting')
plotBear = input(title = "Classic Bearish Divergence", defval = true, group = 'Display Setting')
plotHiddenBull = input(title = "Hidden Bullish Divergence", defval = false, group = 'Display Setting')
plotHiddenBear = input(title = "Hidden Bearish Divergence", defval = false, group = 'Display Setting')
// Style Setting
color_css_gradient_overbought = input(#bfcdcc, 'Overbought', group = 'Style Setting')
color_css_gradient_oversold = input(#ff8e8e, 'Oversold', group = 'Style Setting')
color_bearish = input(#e8ff8e, 'Bearish', group = 'Style Setting')
color_bullish = input(#8eff8e, 'Bullish', group = 'Style Setting')
color_hidden_bullish = color.new(color_bullish, 80)
color_hidden_bearish = color.new(color_bearish, 80)
textColor = #000000
noneColor = color.new(color.white, 100)
// Define values
counting_numbers = length_max-length_min+1
difference = nz(rsi_source - rsi_source[1])
var numerator = array.new_float(counting_numbers, 0)
var denominator = array.new_float(counting_numbers, 0)
// Lenght Values
factor = 0
overbought = 0
oversold = 0
average = 0.
for i = length_min to length_max
alpha = 1/i
numerator_rma = alpha*difference + (1-alpha)*array.get(numerator,factor)
denominator_rma = alpha*math.abs(difference) + (1-alpha)*array.get(denominator,factor)
value_rsi = 50*numerator_rma/denominator_rma + 50
average += value_rsi
overbought := value_rsi > level_overbought ? overbought + 1 : overbought
oversold := value_rsi < level_oversold ? oversold + 1 : oversold
array.set(numerator, factor, numerator_rma)
array.set(denominator, factor, denominator_rma)
factor += 1
// RSI Values
average_rsi = average/counting_numbers
rsi_bought_ma = 0.
rsi_sold_ma = 0.
rsi_bought_ma := nz(rsi_bought_ma[1] + overbought/counting_numbers*(average_rsi - rsi_bought_ma[1]), average_rsi)
rsi_sold_ma := nz(rsi_sold_ma[1] + oversold/counting_numbers*(average_rsi - rsi_sold_ma[1]), average_rsi)
// RSI Meter
var meter = table.new(position.top_right,2,2)
if barstate.islast
// 1st Row
table.cell(meter, 0, 0, 'Overbought', text_color = #787b86, bgcolor = na)
table.cell(meter, 1, 0, 'Oversold', text_color = #787b86, bgcolor = na)
// 2nd Row
table.cell(meter, 0, 1, str.tostring(overbought/counting_numbers*100, '#.##')+'%', text_color = color_css_gradient_overbought, bgcolor = color.new(color_css_gradient_overbought,90))
table.cell(meter, 1, 1, str.tostring(oversold/counting_numbers*100, '#.##')+'%', text_color = color_css_gradient_oversold, bgcolor = color.new(color_css_gradient_oversold,90))
// Plot RSI
css_gradient = color.from_gradient(average_rsi, rsi_sold_ma, rsi_bought_ma, color_css_gradient_oversold, color_css_gradient_overbought)
plot(average_rsi, color = css_gradient)
// Plot Band
hline(level_overbought, 'Upper Line', color = color.new(color.gray,50), linestyle = hline.style_solid, display = display.all)
hline(50, 'Medium Line', color = color.new(color.gray,50), linestyle = hline.style_solid, display = display.all)
hline(level_oversold, 'Lower Line', color = color.new(color.gray,50), linestyle = hline.style_solid, display = display.all)
// RSI Base MA
rsi_base_ma = ma(average_rsi, ma_length, ma_type)
plot(rsi_base_ma, "RSI Base MA", color = #DFFF00, display = plot_ma_base_rsi == true ? display.all : display.none)
////////////////////////////// Divergence //////////////////////////////
// Set RSI Value to Multi lenge
osc = average_rsi
plFound = na(ta.pivotlow(osc, pivot_look_back_left, pivot_look_back_right)) ? false : true
phFound = na(ta.pivothigh(osc, pivot_look_back_left, pivot_look_back_right)) ? false : true
_inRange(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL = osc[pivot_look_back_right] > ta.valuewhen(plFound, osc[pivot_look_back_right], 1) and _inRange(plFound[1])
// Price: Lower Low
priceLL = low[pivot_look_back_right] < ta.valuewhen(plFound, low[pivot_look_back_right], 1)
bullCond = plotBull and priceLL and oscHL and plFound
plot(
plFound ? osc[pivot_look_back_right] : na,
offset=-pivot_look_back_right,
title="Regular Bullish",
linewidth=2,
color=(bullCond ? color_bullish : noneColor)
)
plotshape(
bullCond ? osc[pivot_look_back_right] : na,
offset=-pivot_look_back_right,
title="Regular Bullish Label",
text=" Bullish ",
style=shape.labelup,
location=location.absolute,
color=color_bullish,
textcolor=textColor
)
// Hidden Bullish
// Osc: Lower Low
oscLL = osc[pivot_look_back_right] < ta.valuewhen(plFound, osc[pivot_look_back_right], 1) and _inRange(plFound[1])
// Price: Higher Low
priceHL = low[pivot_look_back_right] > ta.valuewhen(plFound, low[pivot_look_back_right], 1)
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound
plot(
plFound ? osc[pivot_look_back_right] : na,
offset=-pivot_look_back_right,
title="Hidden Bullish",
linewidth=2,
color=(hiddenBullCond ? color_hidden_bullish : noneColor)
)
plotshape(
hiddenBullCond ? osc[pivot_look_back_right] : na,
offset=-pivot_look_back_right,
title="Hidden Bullish Label",
text=" H Bullish ",
style=shape.labelup,
location=location.absolute,
color=color_bullish,
textcolor=textColor
)
//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High
oscLH = osc[pivot_look_back_right] < ta.valuewhen(phFound, osc[pivot_look_back_right], 1) and _inRange(phFound[1])
// Price: Higher High
priceHH = high[pivot_look_back_right] > ta.valuewhen(phFound, high[pivot_look_back_right], 1)
bearCond = plotBear and priceHH and oscLH and phFound
plot(
phFound ? osc[pivot_look_back_right] : na,
offset=-pivot_look_back_right,
title="Regular Bearish",
linewidth=2,
color=(bearCond ? color_bearish : noneColor)
)
plotshape(
bearCond ? osc[pivot_look_back_right] : na,
offset=-pivot_look_back_right,
title="Regular Bearish Label",
text=" Bearish ",
style=shape.labeldown,
location=location.absolute,
color=color_bearish,
textcolor=textColor
)
//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High
oscHH = osc[pivot_look_back_right] > ta.valuewhen(phFound, osc[pivot_look_back_right], 1) and _inRange(phFound[1])
// Price: Lower High
priceLH = high[pivot_look_back_right] < ta.valuewhen(phFound, high[pivot_look_back_right], 1)
hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound
plot(
phFound ? osc[pivot_look_back_right] : na,
offset=-pivot_look_back_right,
title="Hidden Bearish",
linewidth=2,
color=(hiddenBearCond ? color_hidden_bearish : noneColor)
)
plotshape(
hiddenBearCond ? osc[pivot_look_back_right] : na,
offset=-pivot_look_back_right,
title="Hidden Bearish Label",
text=" H Bearish ",
style=shape.labeldown,
location=location.absolute,
color=color_bearish,
textcolor=textColor
)
// Alert Condition
alertcondition(bullCond, title = "Bullish Divergence", message = "Bullish Divergence")
alertcondition(bearCond, title = "Bearish Divergence", message = "Bearish Divergence")
alertcondition(hiddenBullCond, title = "Hidden Bullish Divergence", message = "Hidden Bullish Divergence")
alertcondition(hiddenBearCond, title = "Hidden Bearish Divergence", message = "Hidden Bearish Divergence") |
Adaptive RSI/Stochastic (ARSIS) | https://www.tradingview.com/script/Yrx3IoA1-Adaptive-RSI-Stochastic-ARSIS/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 105 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("Adaptive RSI/Stochastic")
import lastguru/DominantCycle/2 as d
bes(float source = close, float length = 9)=>
alpha = 2 / (length + 1)
var float smoothed = na
smoothed := alpha * source + (1 - alpha) * nz(smoothed[1])
rsi_count()=>
high_length = d.mamaPeriod(high, 2, 4096)
low_length = d.mamaPeriod(low, 2, 4096)
high_filtered = bes(high, high_length)
low_filtered = bes(low, low_length)
change_high = ta.change(high_filtered)
change_low = -ta.change(low_filtered)
// Variables
upMoves = ta.change(high_filtered) > 0 ? change_high : 0
downMoves = ta.change(low_filtered) < 0 ? change_low : 0
// Up/down move averages
upMovesLength = d.mamaPeriod(upMoves, 2, 4096)
downMovesLength = d.mamaPeriod(downMoves, 2, 4096)
upAvg = bes(upMoves, upMovesLength)
downAvg = bes(downMoves, downMovesLength)
// RSI calculation
rsi = downAvg != 0 ? 100 - (100 / (1 + upAvg / downAvg)) : 0
rsi_standard()=>
close_length = d.mamaPeriod(close, 2, 4096)
close_filtered = bes(close, close_length)
up = math.max(ta.change(close_filtered), 0)
down = -math.min(ta.change(close_filtered), 0)
up_length = d.mamaPeriod(up, 2, 4096)
down_length = d.mamaPeriod(down, 2, 4096)
up_filtered = bes(up, up_length)
down_filtered = bes(down, down_length)
rsi = down_filtered == 0 ? 100 : 100 - (100 / (1 + up_filtered / down_filtered))
stochastic(length, smoothing)=>
close_length = d.mamaPeriod(close, 2, 4096)
high_length = d.mamaPeriod(high, 2, 4096)
low_length = d.mamaPeriod(low, 2, 4096)
close_filtered = bes(close, close_length)
high_filtered = bes(high, high_length)
low_filtered = bes(low, low_length)
stochastic = ta.sma(100 * (close_filtered - ta.lowest(low_filtered, length)) / (ta.highest(high_filtered, length) - ta.lowest(low_filtered, length)), smoothing)
stochastic_length = d.mamaPeriod(stochastic, 2, 4096)
stochastic_d = bes(stochastic, stochastic_length)
[stochastic, stochastic_d]
rsi(select)=>
switch select
"Standard RSI" => rsi_standard()
"Count RSI" => rsi_count()
"Stochastic" => na
select = input.string("Standard RSI", "Select Style", ["Standard RSI","Count RSI","Stochastic"])
smoothing = input.int(1, "Smoothing", 1)
length = input.int(14, "Length", 1, tooltip = "Only avalible for Stochastic.")
rsi = bes(rsi(select), smoothing)
rsi_length = d.mamaPeriod(rsi, 2, 4096)
rsi_smooth = bes(rsi, rsi_length)
[stochastic, stochastic_d] = stochastic(length, smoothing)
colour = color.from_gradient(select == "Stochastic" ? stochastic : rsi, 0, 100, color.new(color.navy, 80), color.new(color.purple, 80))
up_line = hline(20)
hline(50)
dn_line = hline(80)
fill(up_line, dn_line, color = colour)
plot(select == "Stochastic" ? stochastic : rsi, "RSI", color.blue)
plot(select == "Stochastic" ? stochastic_d : rsi_smooth, "MA", color.orange)
|
Emibap's Uniswap V3 HEX/USDC 3% Liquidity Pool | https://www.tradingview.com/script/kucWTTgb-Emibap-s-Uniswap-V3-HEX-USDC-3-Liquidity-Pool/ | emibap | https://www.tradingview.com/u/emibap/ | 153 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Copyright ® emibap
// Last update on 2023-06-02 16:13:31 UTC
//@version=5
indicator("Emibap's Uniswap V3 HEX/USDC 0.3% Liquidity Pool", "LP", overlay=true, max_lines_count=500)
// Inputs
// Pools to display (Default is HEX/USDC 0.3%)
POOLS_SECTION_TITLE = "Pools (in addition to HEX/USDC 0.3%)"
SHOW_POOL_HEXUSDC_1PCT = input.bool(true, "HEX/USCD 1%", "", "Pools", POOLS_SECTION_TITLE)
// SHOW_POOL_HEXETH_1PCT = input.bool(false, "HEX/ETH 1%", "", "Pools", POOLS_SECTION_TITLE)
// Input for Histogram lines and BG color
COLOR_LP_HISTOGRAM_LINES_03pct = input.color(color.new(color.blue, 20), 'HEX/USDC 0.3% Histogram lines color. Default is blue')
COLOR_LP_HISTOGRAM_LINES_1pct = input.color(color.new(color.yellow, 60), 'HEX/USDC 1% Histogram lines color. Default is yellow')
COLOR_LP_DEFAULT_BG = input.color(color.new(color.black, 80), 'Histogram background color. Default is black at 20% opacity')
// Price Limits histogram visibility
upperBoundFromCurrentPricePct = input.float(200, 'Upper price limit of the diagram. Percentage increase from current price. I.E: 200%', minval = 1, maxval = 3000)
lowerBoundFromCurrentPricePct = input.float(50, 'Lower price limit of the diagram. Percentage decrease from current price. I.E: 99%', minval = 1, maxval = 99.99)
WIDEST_BAR_WIDTH = input.int(200, 'Width of the widest bar', minval=20, maxval=200)
// Constants
var COLOR_LP_TRANSPARENT = color.new(color.black, 100)
var COLOR_LP_TEXT_UPDATE = color.new(color.red, 20)
var COLOR_LP_TEXT_NORMAL = color.new(color.gray, 20)
var LINE_THICKNESS_03PCT = 1
var LINE_THICKNESS_1PCT = 1
// Types
type liquidityHistogram
string title
array<float> pricesList
array<float> lockedLinesList
color lineColor
int lineThickness
// Handy functions
draw_histogram_base(float hlimit, float llimit) =>
// BG Box with Title
var bt = box.new(bar_index + 3, hlimit, bar_index + 3 + WIDEST_BAR_WIDTH, llimit, xloc=xloc.bar_index, border_width = 0, bgcolor = COLOR_LP_DEFAULT_BG)
box.set_text(bt, "Emibap's Uniswap V3 LP")
box.set_text_color(bt, COLOR_LP_TEXT_NORMAL)
box.set_text_size(bt, size.small)
box.set_text_halign(bt, text.align_left)
box.set_text_valign(bt, text.align_top)
// BG Box with mode (Overlayed / Combined)
var bt2 = box.new(bar_index + 3, hlimit, bar_index + 3 + WIDEST_BAR_WIDTH, llimit, xloc=xloc.bar_index, border_width = 0, bgcolor = COLOR_LP_DEFAULT_BG)
box.set_text(bt2, "\n[OVERLAYED]")
box.set_text_color(bt2, COLOR_LP_TEXT_NORMAL)
box.set_text_size(bt2, size.small)
box.set_text_halign(bt2, text.align_left)
box.set_text_valign(bt2, text.align_top)
// BG Box with last update
var b = box.new(bar_index + 3, hlimit, bar_index + 3 + WIDEST_BAR_WIDTH, llimit, xloc=xloc.bar_index, border_width = 0, bgcolor = COLOR_LP_DEFAULT_BG)
box.set_text(b, "Last update on 2023-06-02 16:13:31 UTC")
box.set_text_color(b, COLOR_LP_TEXT_UPDATE)
box.set_text_size(b, size.small)
box.set_text_halign(b, text.align_right)
box.set_text_valign(b, text.align_bottom)
draw_histogram_lines(liquidityHistogram h, float hlimit, float llimit, float widthRatio) =>
// BG Box with fee%
b2 = box.new(bar_index + 3, hlimit, bar_index + 3 + WIDEST_BAR_WIDTH, llimit, xloc=xloc.bar_index, border_width = 0, bgcolor = COLOR_LP_TRANSPARENT)
box.set_text(b2, h.title)
box.set_text_color(b2, h.lineColor)
box.set_text_size(b2, size.small)
box.set_text_halign(b2, text.align_right)
box.set_text_valign(b2, text.align_top)
ticksLen = array.size(h.pricesList)
for i = 0 to ticksLen - 1 by 1
currPr = array.get(h.pricesList, i)
if llimit <= currPr and currPr <= hlimit
lockedWidth = math.floor(array.get(h.lockedLinesList, i) * widthRatio)
line.new(bar_index + 3, currPr, bar_index + 3 + lockedWidth, currPr, xloc=xloc.bar_index, color=h.lineColor, width=h.lineThickness)
unify_token_locked_values(immutable_locked_values, mutable_locked_values) =>
for i = 0 to array.size(mutable_locked_values) - 1 by 1
array.set(mutable_locked_values, i, array.get(mutable_locked_values, i) * close)
array.concat(immutable_locked_values, mutable_locked_values)
// LP Histograms
if barstate.islast
var drawable_histograms = array.new<liquidityHistogram>()
// Upper and lower limit of the histogram relative to the current price
var hlimit = close * (1 + upperBoundFromCurrentPricePct/100)
var llimit = close * (1 - lowerBoundFromCurrentPricePct/100)
// HEX/USDC 0.3%
var lockedUSDCList_03pct = array.from(9.89, 9.92, 9.95, 9.98, 10.01, 10.04, 10.07, 10.10, 10.13, 10.16, 10.19, 10.22, 11.83, 11.86, 11.90, 11.93, 11.97, 12.01, 12.04, 12.08, 12.11, 12.15, 12.19, 12.22, 12.26, 12.30, 12.33, 12.37, 12.41, 12.45, 12.48, 12.52, 512.56, 12.60, 12.63, 12.67, 12.71, 12.75, 12.79, 12.82, 12.86, 12.90, 12.94, 12.98, 13.02, 13.06, 13.10, 13.14, 13.18, 13.22, 13.26, 13.30, 13.33, 13.38, 13.42, 13.46, 13.50, 13.54, 13.58, 13.62, 13.66, 13.70, 13.74, 13.78, 13.82, 13.87, 13.91, 13.95, 13.99, 14.03, 14.07, 14.12, 14.16, 14.20, 14.24, 14.29, 14.33, 14.37, 14.42, 14.46, 14.50, 14.55, 14.59, 14.63, 381.19, 382.34, 383.49, 384.64, 385.80, 386.95, 388.12, 389.28, 390.45, 391.63, 392.80, 393.98, 395.17, 396.35, 397.54, 398.74, 399.94, 401.14, 402.34, 403.55, 404.76, 405.98, 420.10, 423.63, 424.90, 426.18, 427.46, 428.74, 430.03, 431.32, 432.62, 433.92, 435.22, 436.53, 437.84, 439.15, 440.47, 441.80, 443.12, 444.46, 445.79, 447.13, 448.47, 449.82, 451.17, 452.53, 453.89, 455.25, 456.62, 457.99, 459.37, 460.75, 462.13, 463.52, 464.91, 466.31, 467.71, 469.11, 470.52, 485.35, 486.81, 488.27, 489.74, 518.34, 521.95, 637.61, 1139.53, 641.45, 643.38, 645.31, 647.25, 649.19, 651.15, 653.10, 655.06, 657.03, 659.01, 660.99, 675.19, 677.22, 679.25, 682.41, 684.46, 686.51, 688.58, 690.64, 2091.81, 2098.09, 2104.40, 2110.72, 2181.98, 2188.54, 2195.12, 2201.71, 2208.32, 2214.96, 2221.61, 2228.29, 2204.84, 2211.46, 2218.11, 2224.77, 2231.46, 2238.16, 2244.88, 2251.63, 2258.39, 2265.18, 4653.72, 4667.70, 4681.73, 4695.79, 4709.90, 4724.05, 4738.24, 4752.38)
var lockedHEXList_03pct = array.from(349691.31, 348643.86, 347599.55, 346558.37, 345520.30, 344485.34, 343453.49, 337382.49, 336371.91, 335473.33, 334468.47, 333894.53, 332894.40, 331897.26, 330903.11, 329911.94, 328923.74, 326823.27, 325844.31, 324868.29, 323895.20, 322925.02, 321957.74, 320993.36, 320031.88, 319073.27, 318117.53, 317164.65, 316214.63, 315267.46, 314457.12, 316398.11, 315450.39, 314515.11, 313573.03, 312633.77, 311697.32, 312730.46, 311793.72, 310859.79, 309928.65, 309000.31, 308074.74, 307151.95, 304306.00, 303394.50, 302485.72, 301579.67, 300676.33, 299775.70, 298877.76, 297982.52, 297089.96, 296200.07, 295312.84, 294428.28, 293546.36, 292667.08, 291790.44, 290916.43, 290045.03, 289176.24, 288310.05, 287446.46, 299018.59, 297978.70, 297086.14, 296207.73, 295320.49, 294550.04, 294259.29, 293377.88, 292499.10, 291622.97, 200803.17, 200201.69, 199547.02, 198949.31, 198353.38, 197759.25, 197095.44, 196346.00, 195757.88, 195171.51, 194586.90, 194004.05, 193422.94, 192843.57, 192265.93, 191676.36, 191102.22, 190529.80, 189959.10, 189390.10, 188822.81, 188257.22, 186818.18, 186258.60, 185700.69, 185144.45, 184589.87, 184036.96, 177826.11, 177293.46, 176762.40, 176232.94, 175705.06, 175132.27, 174607.69, 174084.68, 173563.23, 173022.67, 172504.40, 171987.69, 171507.57, 174034.59, 173513.29, 172993.56, 172475.38, 172034.63, 172309.46, 171793.33, 171278.75, 170765.71, 170254.21, 169744.24, 169506.48, 168998.75, 168747.15, 166634.90, 166135.77, 165638.14, 165885.48, 165388.59, 164922.22, 164428.22, 163935.70, 162612.98, 162125.90, 161640.28, 161156.11, 161389.95, 174240.20, 32056.85, 29173.43, 852699.89, 850145.75, 847599.26, 844333.92, 841804.84, 839283.34, 842273.85, 839750.94, 839116.57, 836603.12, 834097.20, 831598.78, 829107.85, 827051.78, 824574.47, 822145.44, 819682.82, 815446.47, 813003.92, 810568.68, 808140.74, 805727.52, 803314.08, 800907.87, 798508.86, 795531.17, 793798.35, 791420.64, 789050.05, 786031.09, 783676.65, 781329.26, 779003.43, 777183.35, 774855.41, 771783.46, 769471.69, 767166.85, 764868.91, 762577.86, 760293.67, 758016.32, 1316762.38, 1312427.59, 1307663.90, 1303746.98, 734008.66, 731810.04, 729618.01, 727432.55, 725253.63, 723081.23, 720888.03, 718728.71)
// Price Hex locked liquidity in USDC and concat into one
unify_token_locked_values(lockedUSDCList_03pct, lockedHEXList_03pct)
var pricesList_03pct = array.from(0.004093623959031289, 0.004118258300213204, 0.004143040884314239, 0.004167972603420888, 0.004193054354987987, 0.004218287041871012, 0.0042436715723585886, 0.004269208860205177, 0.004294899824663973, 0.004320745390519992, 0.00434674648812336, 0.004372904053422801, 0.004399219027999335, 0.00442569235910016, 0.004452324999672761, 0.004479117908399204, 0.004506072049730653, 0.004533188393922078, 0.004560467917067188, 0.004587911601133566, 0.0046155204339980134, 0.00464329540948211, 0.0046712375273879935, 0.004699347793534343, 0.004727627219792587, 0.004756076824123327, 0.004784697630612982, 0.004813490669510652, 0.0048424569772651995, 0.0048715975965625625, 0.004900913576363286, 0.0049304059719402805, 0.004960075844916808, 0.004989924263304698, 0.005019952301542791, 0.005050161040535614, 0.0050805515676922925, 0.005111124976965688, 0.005141882368891784, 0.005172824850629292, 0.0052039535359995155, 0.005235269545526434, 0.005266774006477045, 0.005298468052901939, 0.005330352825676121, 0.005362429472540081, 0.005394699148141102, 0.005427163014074831, 0.005459822238927089, 0.005492677998315932, 0.0055257314749339774, 0.005558983858590971, 0.005592436346256617, 0.005626090142103666, 0.00565994645755126, 0.005694006511308538, 0.00572827152941851, 0.005762742745302183, 0.005797421399802967, 0.005832308741231338, 0.005867406025409769, 0.005902714515717944, 0.005938235483138226, 0.0059739702063014155, 0.006009919971532771, 0.006046086072898313, 0.006082469812251414, 0.006119072499279647, 0.006155895451551941, 0.006192939994566003, 0.006230207461796033, 0.006267699194740726, 0.006305416542971558, 0.0063433608641813655, 0.006381533524233225, 0.006419935897209612, 0.006458569365461861, 0.006497435319659936, 0.006536535158842479, 0.0065758702904671765, 0.0066154421304614195, 0.006655252103273276, 0.006695301641922764, 0.006735592188053432, 0.00677612519198426, 0.006816902112761862, 0.006857924418213004, 0.006899193584997443, 0.006940711098661088, 0.006982478453689464, 0.007024497153561511, 0.007066768710803709, 0.007109294647044519, 0.00715207649306916, 0.007195115788874707, 0.007238414083725527, 0.007281972936209053, 0.007325793914291881, 0.00736987859537621, 0.007414228566356629, 0.0074588454236772395, 0.007503730773389115, 0.007548886231208119, 0.007594313422573064, 0.007640013982704224, 0.007685989556662187, 0.0077322417994070865, 0.007778772375858162, 0.007825582960953694, 0.0078726752397113, 0.00792005090728858, 0.007967711669044152, 0.008015659240599016, 0.008063895347898331, 0.008112421727273536, 0.008161240125504851, 0.00821035229988415, 0.008259760018278228, 0.008309465059192429, 0.008359469211834674, 0.008409774276179855, 0.008460382063034644, 0.008511294394102654, 0.008562513102050041, 0.008614040030571446, 0.008665877034456383, 0.008718025979655989, 0.008770488743350206, 0.008823267214015343, 0.008876363291492056, 0.008929778887053742, 0.008983515923475328, 0.009037576335102495, 0.009091962067921294, 0.009146675079628212, 0.00920171733970063, 0.009257090829467718, 0.009312797542181764, 0.009368839483089909, 0.00942521866950635, 0.009481937130884938, 0.009538996908892237, 0.009596400057481021, 0.009654148642964207, 0.009712244744089231, 0.009770690452112879, 0.009829487870876567, 0.009888639116882068, 0.009948146319367699, 0.010008011620384968, 0.01006823717487568, 0.010128825150749513, 0.010189777728962039, 0.010251097103593248, 0.010312785481926516, 0.01037484508452807, 0.010437278145326906, 0.01050008691169522, 0.01056327364452929, 0.010626840618330871, 0.010690790121289062, 0.01075512445536268, 0.010819845936363112, 0.01088495689403769, 0.010950459672153542, 0.011016356628581964, 0.011082650135383298, 0.011149342578892309, 0.011216436359804094, 0.011283933893260498, 0.011351837608937043, 0.011420149951130396, 0.011488873378846347, 0.011558010365888336, 0.01162756340094649, 0.011697534987687214, 0.011767927644843312, 0.011838743906304648, 0.011909986321209372, 0.011981657454035661, 0.012053759884694046, 0.012126296208620265, 0.012199269036868712, 0.012272680996206403, 0.012346534729207537, 0.012420832894348635, 0.012495578166104212, 0.012570773235043067, 0.01264642080792512, 0.012722523607798856, 0.012799084374099346, 0.012876105862746852, 0.012953590846246024, 0.01303154211378572, 0.013109962471339389, 0.013188854741766077, 0.013268221764912061, 0.013348066397713042, 0.013428391514297009, 0.013509200006087694, 0.013590494781908638, 0.013672278768087914, 0.013754554908563463, 0.013837326164989056, 0.013920595516840918, 0.014004365961524958, 0.014088640514484687, 0.014173422209309753, 0.014258714097845135, 0.014344519250301007, 0.014430840755363258, 0.014517681720304655, 0.014605045271096719, 0.014692934552522227, 0.014781352728288434, 0.014870302981140934, 0.014959788512978243, 0.015049812544967055, 0.015140378317658184, 0.015231489091103216, 0.01532314814497187, 0.015415358778670033, 0.015508124311458553, 0.015601448082572699, 0.015695333451342372, 0.015789783797313033, 0.015884802520367343, 0.015980393040847557, 0.016076558799678637, 0.016173303258492127, 0.01627062989975073, 0.016368542226873707, 0.016467043764362952, 0.016566138057929877, 0.016665828674623042, 0.016766119202956564, 0.016867013253039274, 0.01696851445670469, 0.017070626467641726, 0.017173352961526233, 0.01727669763615331, 0.017380664211570387, 0.017485256430211163, 0.017590478057030307, 0.017696332879638982, 0.017802824708441186, 0.017909957376770924, 0.01801773474103018, 0.01812616068082774, 0.01823523909911885, 0.018344973922345697, 0.01845536910057876, 0.01856642860765899, 0.01867815644134085, 0.018790556623436244, 0.01890363319995925, 0.019017390241271803, 0.01913183184223018, 0.01924696212233242, 0.019362785225866614, 0.019479305322060065, 0.019596526605229383, 0.019714453294931468, 0.019833089636115377, 0.01995243989927516, 0.02007250838060355, 0.020193299402146633, 0.020314817311959422, 0.020437066484262367, 0.020560051319598815, 0.020683776244993412, 0.020808245714111464, 0.020933464207419247, 0.021059436232345297, 0.021186166323442657, 0.021313659042552106, 0.021441918978966364, 0.021570950749595297, 0.02170075899913211, 0.02183134840022054, 0.021962723653623038, 0.022094889488390015, 0.022227850662030035, 0.022361611960681094, 0.022496178199282884, 0.022631554221750134, 0.02276774490114696, 0.022904755139862287, 0.023042589869786308, 0.02318125405248803, 0.023320752679393854, 0.023461090771967258, 0.02360227338188956, 0.02374430559124176, 0.02388719251268745, 0.02403093928965689, 0.02417555109653213, 0.02432103313883328, 0.024467390653405887, 0.02461462890860943, 0.024762753204506993, 0.024911768873056024, 0.025061681278300278, 0.025212495816562888, 0.025364217916640636, 0.025516853039999357, 0.02567040668097054, 0.025824884366949102, 0.025980291658592336, 0.026136634150020124, 0.026293917469016246, 0.026452147277231004, 0.026611329270385002, 0.026771469178474186, 0.026932572765976083, 0.027094645832057316, 0.027257694210782363, 0.02742172377132354, 0.027586740418172277, 0.027752750091351683, 0.02791975876663034, 0.028087772455737407, 0.02825679720657905, 0.028426839103456107, 0.028597904267283137, 0.028769998855808724, 0.028943129063837163, 0.029117301123451428, 0.0292925213042375, 0.02946879591351008, 0.02964613129653959, 0.02982453383678064, 0.030004009956101748, 0.030184566115016524, 0.030366208812916243, 0.0305489445883038, 0.03073278001902904, 0.03091772172252558, 0.031103776356048985, 0.03129095061691642, 0.03147925124274771, 0.03166868501170791, 0.03185925874275125, 0.03205097929586663, 0.032243853572324524, 0.03243788851492544, 0.03263309110824979, 0.03282946837890934, 0.03302702739580017, 0.03322577527035705, 0.03342571915680951, 0.033626866252439304, 0.03382922379783955, 0.03403279907717531, 0.034237599418445806, 0.034443632193748235, 0.034650904819543096, 0.0348594247569212, 0.035069199511872186, 0.03528023663555478, 0.035492543724568545, 0.03570612842122739, 0.0359209984138346, 0.03613716143695968, 0.03635462527171666, 0.03657339774604429, 0.03679348673498775, 0.03701490016098217, 0.03723764599413777, 0.03746173225252679, 0.037687167002472086, 0.03791395835883751, 0.038142114485320004, 0.038371643594743474, 0.03860255394935441, 0.038834853861119324, 0.039068551692023896, 0.03930365585437406, 0.039540174811098734, 0.03977811707605452, 0.040017491214332124, 0.040258305842564714, 0.04050056962923805, 0.04074429129500255, 0.04098947961298717, 0.04123614340911524, 0.04148429156242214, 0.04173393300537495, 0.04198507672419393, 0.042237731759176035, 0.04249190720502035, 0.04274761221115542, 0.04300485598206861, 0.04326364777763747, 0.043523996913463, 0.04378591276120506, 0.044049404748919614, 0.044314482361398205, 0.044581155140509296)
var maxUSDCLockedInATick = array.max(lockedUSDCList_03pct)
array.push(drawable_histograms, liquidityHistogram.new(title = "HEX/USDC 0.3%", pricesList = pricesList_03pct, lockedLinesList = lockedUSDCList_03pct, lineColor = COLOR_LP_HISTOGRAM_LINES_03pct, lineThickness = LINE_THICKNESS_03PCT))
// HEX/USDC 1%
if SHOW_POOL_HEXUSDC_1PCT
var lockedUSDCList_1pct = array.from(4.78, 4.83, 4.88, 4.93, 4.98, 5.03, 5.08, 5.13, 5.18, 5.23, 5.29, 5.34, 5.39, 5.45, 5.50, 5.56, 5.61, 5.67, 5.73, 5.78, 5.84, 5.90, 5.96, 6.02, 6.08, 6.14, 6.20, 6.26, 6.33, 6.39, 6.46, 6.52, 6.59, 6.65, 6.72, 6.79, 6.85, 6.92, 6.99, 7.06, 7.13, 7.21, 7.28, 7.35, 7.43, 7.50, 7.58, 7.65, 7.73, 7.81, 7.88, 7.96, 8.04, 8.12, 8.21, 8.29, 8.37, 8.46, 8.54, 8.63, 8.71, 8.80, 8.89, 8.98, 9.07, 9.16, 9.25, 9.35, 9.44, 9.53, 9.63, 9.73, 9.82, 9.92, 10.02, 10.12, 10.23, 10.33, 10.43, 10.54, 10.64, 10.75, 10.86, 10.97, 11.08, 11.19, 11.30, 11.41, 11.53, 11.64, 11.76, 11.88, 12.00, 12.12, 12.24, 12.36, 12.49, 12.61, 12.74, 12.87, 13.00, 13.13, 13.26, 15.23, 15.38, 15.53, 15.69, 15.85, 16.01, 16.17, 16.33, 16.49, 16.66, 16.83, 17.00, 17.17, 17.34, 17.51, 17.69, 17.87, 18.05, 18.23, 18.41, 18.60, 18.78, 18.97, 19.16, 19.36, 19.55, 19.75, 19.94, 20.15, 20.35, 20.55, 20.76, 20.97, 21.18, 21.39, 21.61, 21.82, 22.04, 22.26, 22.49, 22.71, 22.94, 23.17, 23.41, 23.64, 23.88, 24.12, 24.36, 24.61, 24.85, 25.10, 25.35, 25.61, 25.87, 26.13, 26.39, 26.65, 26.92, 27.19, 27.47, 27.98, 28.26, 28.54, 28.83, 29.12, 29.41, 29.71, 30.01, 30.31, 30.61, 30.92, 31.23, 31.54, 31.86, 32.18, 32.50, 4.78, 4.83, 4.88, 4.93, 12.24, 12.36, 12.48, 12.61, 12.74, 12.86, 12.99, 13.12, 13.25, 13.39, 13.52, 13.66, 13.80, 13.93, 14.07, 14.22, 14.30)
var lockedHEXList_1pct = array.from(1031.48, 1021.22, 1153.80, 1142.32, 1130.95, 1119.70, 1108.56, 1097.53, 1086.61, 1075.80, 1065.09, 1054.49, 1044.00, 1033.62, 1023.33, 1013.15, 1003.07, 993.09, 983.21, 973.43, 963.74, 954.15, 944.66, 935.26, 925.95, 916.74, 907.62, 898.59, 889.65, 7450.91, 7376.78, 7303.38, 7230.72, 7158.77, 7087.55, 7017.03, 35449.03, 6878.09, 6809.65, 6741.90, 6674.82, 6608.41, 6542.66, 6477.56, 6413.11, 6349.30, 6286.13, 6223.58, 6161.66, 6100.35, 6039.66, 5979.56, 5920.07, 5861.17, 5802.85, 5745.11, 5687.95, 5631.36, 5575.33, 639.10, 632.75, 626.45, 620.22, 614.05, 607.94, 601.89, 595.90, 589.97, 584.10, 601.38, 595.40, 589.48, 583.61, 577.80, 572.06, 566.36, 1608.83, 1592.83, 1576.98, 1561.29, 1545.75, 1530.37, 1515.15, 1500.07, 1485.15, 1470.37, 1455.74, 1537.98, 1522.68, 1724.65, 1707.49, 812.59, 804.50, 660.96, 654.38, 647.87, 5848.25, 6103.74, 5956.35, 5897.09, 5838.42, 5780.33, 5722.81, 5665.87, 5609.50, 5553.69, 5498.43, 495.42, 490.49, 485.61, 480.78, 475.99, 471.26, 466.57, 461.93, 457.33, 452.78, 448.27, 427.95, 423.69, 419.47, 415.30, 411.17, 407.08, 403.03, 399.02, 395.05, 391.12, 387.22, 383.37, 379.56, 233.12, 230.80, 228.50, 226.23, 223.98, 221.75, 219.55, 217.36, 215.20, 213.06, 210.94, 208.84, 206.76, 204.70, 202.67, 186.68, 184.83, 182.99, 181.17, 179.36, 177.58, 175.81, 174.06, 172.33, 170.62, 168.92, 550.81, 545.33, 539.90, 534.53, 529.21, 523.94, 518.73, 513.57, 508.46, 503.40, 498.39, 493.43, 488.52, 483.66, 478.85, 474.09, 469.37, 464.70, 460.08, 455.50, 450.97, 446.48, 442.04, 437.64, 433.28, 428.97, 424.70, 420.48, 416.30, 412.15, 408.05, 403.99, 399.97, 395.99, 119.04, 117.85, 116.68, 115.52, 114.37, 113.23, 112.11, 110.99)
// Price Hex locked liquidity in USDC and concat into one
unify_token_locked_values(lockedUSDCList_1pct, lockedHEXList_1pct)
var pricesList_1pct = array.from(0.0002550155952225021, 0.000260166991823938, 0.00026542244828462353, 0.00027078406664700355, 0.0002762539914154528, 0.00028183441041402044, 0.00028752755566150134, 0.000293335704264184, 0.0002992611793266323, 0.0003053063508808656, 0.00031147363683430804, 0.00031776550393688746, 0.0003241844687676691, 0.00033073309874142036, 0.00033741401313550843, 0.00034422988413754105, 0.00035118343791417045, 0.0003582774557014875, 0.0003655147749174415, 0.0003728982902967324, 0.0003804309550486267, 0.0003881157820381629, 0.0003959558449912174, 0.0004039542797239121, 0.00041211428539685794, 0.00042043912579473356, 0.0004289321306317123, 0.0004375966968832586, 0.00044643629014482844, 0.0004554544460180142, 0.0004646547715246916, 0.0004740409465497322, 0.00048361672531285906, 0.0004933859378702346, 0.0005033524916463809, 0.0005135203729970455, 0.0005238936488036371, 0.0005344764680998697, 0.000545273063731266, 0.0005562877540481819, 0.000567524944633032, 0.0005789891300624053, 0.0005906848957047752, 0.0006026169195545255, 0.0006147899741030227, 0.0006272089282474859, 0.0006398787492384152, 0.0006528045046663602, 0.0006659913644888205, 0.0006794446030980909, 0.000693169601430878, 0.0007071718491205309, 0.0007214569466927489, 0.0007360306078056418, 0.000750898661535041, 0.0007660670547059742, 0.000781541854271237, 0.0007973292497380127, 0.0008134355556435092, 0.0008298672140806063, 0.0008466307972745206, 0.0008637330102115205, 0.000881180693320742, 0.0008989808252101777, 0.0009171405254579342, 0.0009356670574598733, 0.0009545678313347765, 0.0009738504068881958, 0.0009935224966361733, 0.0010135919688900419, 0.001034066850903541, 0.001054955332083503, 0.001076265767265399, 0.0010980066800550482, 0.0011201867662378343, 0.0011428148972567876, 0.0011659001237609256, 0.0011894516792252713, 0.0012134789836439962, 0.0012379916472981681, 0.001262999474599607, 0.0012885124680123868, 0.0013145408320535568, 0.001341094977374674, 0.0013681855249257876, 0.0013958233102035356, 0.0014240193875850542, 0.0014527850347494332, 0.0014821317571884886, 0.0015120712928086515, 0.0015426156166258175, 0.001573776945555034, 0.0016055677432969407, 0.001638000725322917, 0.0016710888639609326, 0.0017048453935841308, 0.0017392838159042264, 0.0017744179053718302, 0.0018102617146858618, 0.001846829580414254, 0.0018841361287281976, 0.0019221962812522217, 0.001961025261032443, 0.0020006385986253796, 0.00204105213830976, 0.002082282044423811, 0.0021243448078305622, 0.002167257252513753, 0.0022110365423069745, 0.0022557001877587485, 0.0023012660531362777, 0.0023477523635706764, 0.0023951777123465386, 0.0024435610683387547, 0.002492921783599556, 0.0025432796010988177, 0.0025946546626207257, 0.002647067516819946, 0.002700539127440545, 0.0027550908817009236, 0.0028107445988481373, 0.002867522538885011, 0.002925447411473548, 0.0029845423850181885, 0.0030448310959325544, 0.003106337658093383, 0.0031690866724854365, 0.003233103237041239, 0.003298412956679578, 0.0033650419535467954, 0.0034330168774649424, 0.003502364916591001, 0.0035731138082914235, 0.0036452918502363355, 0.0037189279117178526, 0.003794051445197025, 0.0038706924980840395, 0.0039488817247563795, 0.00402865039881976, 0.004110030425616735, 0.004193054354987987, 0.004277755394291388, 0.004364167421684067, 0.004452324999672761, 0.0045422633889379005, 0.004634018562436942, 0.004727627219792587, 0.004823126801971657, 0.004920555506260481, 0.005019952301542791, 0.0051213569438862344, 0.005224809992443746, 0.005330352825676121, 0.005438027657902303, 0.005547877556183979, 0.00565994645755126, 0.0057742791865763215, 0.005890921473302037, 0.006009919971532771, 0.006131322277494662, 0.006255176948872845, 0.006381533524233225, 0.006510442542836588, 0.00664195556485295, 0.00677612519198426, 0.006913005088503673, 0.007052650002719826, 0.007195115788874707, 0.007340459429483856, 0.007488739058127859, 0.007640013982704224, 0.007794344709148961, 0.007951792965637345, 0.008112421727273536, 0.008276295241278946, 0.008443479052689407, 0.008614040030571446, 0.008788046394768125, 0.008965567743185156, 0.009146675079628212, 0.009331440842202558, 0.009519938932286351, 0.009712244744089231, 0.009908435194807991, 0.010108588755391407, 0.010312785481926516, 0.010521107047658929, 0.01073363677565994, 0.010950459672153542, 0.011171662460516645, 0.011397333615966112, 0.01162756340094649, 0.011862443901232584, 0.012102069062761303, 0.012346534729207537, 0.01259593868031907, 0.012850380671025865, 0.013109962471339389, 0.013374787907057884, 0.013644962901293946, 0.013920595516840918, 0.014201795999395136, 0.01448867682165128, 0.014781352728288434, 0.015079940781864904, 0.015384560409640124, 0.015695333451342372, 0.01601238420790142, 0.01633583949116557, 0.016665828674623042, 0.01700248374514789, 0.017345939355791255, 0.017696332879638982, 0.018053804464757194, 0.018418497090247784, 0.018790556623436244, 0.019170131878214695, 0.019557374674563494, 0.01995243989927516, 0.020355485567904966, 0.020766672887972962, 0.021186166323442657, 0.021614133660502247, 0.022050746074674592, 0.022496178199282884, 0.02295060819529929, 0.023414217822604635, 0.02388719251268745, 0.02436972144281167, 0.02486199761168248, 0.025364217916640636, 0.02587658323241617, 0.026399298491472937, 0.026932572765976083, 0.027476619351415398, 0.028031655851917785, 0.028597904267283137, 0.029175591081778293, 0.02976494735472476, 0.030366208812916243, 0.030979615944903085, 0.03160541409718128, 0.032243853572324524, 0.032895189729098585, 0.033559683084597954, 0.034237599418445806, 0.03492920987909871, 0.035634791092298786, 0.03635462527171666, 0.03708900033182936, 0.03783821000307846, 0.03860255394935441, 0.03938233788785414, 0.04017787371135971, 0.04098947961298717, 0.04181748021345531, 0.042662206690925276, 0.043523996913463, 0.04440319557417746, 0.04530015432908867, 0.046215231937780744, 0.04714879440689617, 0.0481012151365287, 0.04907287506957341, 0.050064162844093756, 0.05107547494876635, 0.05210721588146593, 0.05315979831105372, 0.0542336432424339, 0.05532918018494444, 0.05644684732414932, 0.057587091697101064, 0.058750369371143696, 0.05993714562632746, 0.06114789514150846, 0.06238310218420753, 0.06364326080430437, 0.06492887503164424, 0.0662404590776366, 0.06757853754092576, 0.06894364561721654, 0.07033632931333818, 0.07175714566563256, 0.0732066629627538, 0.07468546097296869, 0.07619413117604842, 0.07773327699984481, 0.07930351406164529, 0.08090547041440345, 0.08253978679794345, 0.08420711689523884, 0.08590812759386839, 0.08764349925275323, 0.08941392597428242, 0.09122011588193528, 0.09306279140351191, 0.09494268956008511, 0.0968605622607891, 0.09881717660356314, 0.10081331518197029, 0.10284977639821385, 0.10492737478247714, 0.10704694131871367, 0.10920932377701864, 0.11141538705271439, 0.11366601351228546, 0.11596210334630162, 0.1183045749294701, 0.12069436518796102, 0.12313242997415288, 0.12561974444894794, 0.12815730347181067, 0.13074612199868493, 0.13338723548794942, 0.13608170031457323, 0.1388305941926378, 0.14163501660639372, 0.14449608925002522, 0.14741495647629785, 0.15039278575426912, 0.15343076813624493, 0.15653011873416875, 0.1596920772056341, 0.1629179082497144, 0.16620890211280887, 0.16956637510470682, 0.17299167012507632, 0.1764861572005884, 0.18005123403289106, 0.18368832655765266, 0.18739888951489828, 0.1911844070308668, 0.195046393211622, 0.19898639274865437, 0.20300598153671676, 0.2071067673041401, 0.2112903902558818, 0.21555852372956433, 0.21991287486476527, 0.22435518528582774, 0.22888723179846382, 0.23351082710042934, 0.23822782050655464, 0.2430400986884212, 0.2479495864289801, 0.25295824739241357, 0.2580680849095487, 0.26328114277913595, 0.2685995060853145, 0.2740253020315899, 0.2795607007916594, 0.28520791637742265, 0.2909692075245284, 0.2968468785958077, 0.30284328050295817, 0.3089608116468457, 0.31520191887680077, 0.3215690984692934, 0.3280648971263764, 0.334691912994299, 0.3414527967026959, 0.348350252424768, 0.3553870389588803, 0.3625659708320069, 0.3698899194254674, 0.37736181412340253, 0.3849846434844497, 0.392761456437087, 0.40069536349912266, 0.4087895380218203, 0.4170472174591537, 0.42547170466270273, 0.43406636920270586, 0.4428346487157981, 0.45178005027997414, 0.4609061518173263, 0.4702166035251174, 0.47971512933576294, 0.48940552840630425, 0.49929167663797036, 0.509377528226435, 0.5196671172433892, 0.5301645592500631, 0.5408740529433399, 0.5517998818351227, 0.562946415965626, 0.574318113651274, 0.5859195232679094, 0.5977552850700212, 0.6098301330467242, 0.622148896815227, 0.6347165035525514, 0.6475379799662709, 0.66061845430506, 0.6739631584098571, 0.6875774298064609, 0.7014667138403989, 0.7156365658549202, 0.7300926534129843)
maxUSDCLockedInATick := math.max(maxUSDCLockedInATick, array.max(lockedUSDCList_1pct))
array.push(drawable_histograms, liquidityHistogram.new(title = "\nHEX/USDC 1%", pricesList = pricesList_1pct, lockedLinesList = lockedUSDCList_1pct, lineColor = COLOR_LP_HISTOGRAM_LINES_1pct, lineThickness = LINE_THICKNESS_1PCT))
var widthRatio = WIDEST_BAR_WIDTH / maxUSDCLockedInATick
draw_histogram_base(hlimit = hlimit, llimit = llimit)
for i = 0 to array.size(drawable_histograms) - 1 by 1
draw_histogram_lines(array.get(drawable_histograms, i), widthRatio = widthRatio, hlimit = hlimit, llimit = llimit)
|
Dominant Direction (DD) | https://www.tradingview.com/script/OsGPyDnR-Dominant-Direction-DD/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 86 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("Dominant Direction", overlay = true, max_bars_back = 5000)
import lastguru/DominantCycle/2 as d
source = input.source(hl2, "Source")
colour = input.color(color.orange, "Color")
length = d.mamaPeriod(source, 2, 4096)
lines = line.new(bar_index, source, bar_index, source)
if barstate.islast
lines := line.new(bar_index, source , bar_index + int(length), source + (source-source[int(length)]), color = colour, style = line.style_arrow_right)
if barstate.isconfirmed
line.delete(lines)
|
Short vs Long ATR | https://www.tradingview.com/script/7KTkXH4v-Short-vs-Long-ATR/ | cmartin81 | https://www.tradingview.com/u/cmartin81/ | 52 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © cmartin81
//@version=5
indicator("short vs long ATR")
shortAtrLength = input.int(14, "short Atr")
longAtrLength = input.int(100, "long Atr")
painThreshold = input.int(40, "Pain threshold")
shortTermAtr = ta.atr(shortAtrLength)
longTermAtr = ta.atr(longAtrLength)
//plot(shortTermAtr,"short atr", color.green)
//plot(longTermAtr,"long atr", color.red)
pain = (shortTermAtr/longTermAtr * 100) - 100
painColor = pain > painThreshold? color.green: color.red
plot(pain, 'pct change', painColor, 2)
hline(painThreshold) |
RSI Accumulation/Distribution [M] | https://www.tradingview.com/script/iTJhU9aT/ | Milvetti | https://www.tradingview.com/u/Milvetti/ | 262 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Milvetti
//@version=5
indicator("RSI Accumulation/Distribution [M]","RSI A/D [M]",max_bars_back = 500,max_boxes_count = 500)
g1="Settings"
g2="Customize"
len = input.int(14,"Length",group = g1)
upperBand = input.int(70,"Upper Band",group = g1)
lowerBand = input.int(30,"Lower Band",group = g1)
showLevel1 = input(true,"Show 1.Level Signal",inline = "level1",group = g2)
colorLevel1 = input.color(color.new(color.green,70),"",inline = "level1",group = g2)
showLevel2 = input(true,"Show 2.Level Signal",inline = "level2",group = g2)
colorLevel2 = input.color(color.new(color.orange,70),"",inline = "level2",group = g2)
showLevel3 = input(true,"Show 3.Level Signal",inline = "level3",group = g2)
colorLevel3 = input.color(color.new(color.red,70),"",inline = "level3",group = g2)
rsi = ta.sma(ta.rsi(close,len),3)
level1 = 5
level2 = 7
level3 =9
accumulation = nz(ta.barssince(ta.crossunder(rsi,lowerBand)),0)
accumulation:= accumulation==0 ? 1 : accumulation
lowBar = ta.lowest(rsi,accumulation)
distribution = nz(ta.barssince(ta.crossover(rsi,upperBand)),0)
distribution := distribution ==0 ? 1 : distribution
highBar = ta.highest(rsi,distribution )
level3Support = ta.crossover(rsi,lowerBand) and accumulation>=level3
level2Support = ta.crossover(rsi,lowerBand) and accumulation>=level2 and accumulation<level3
level1Support = ta.crossover(rsi,lowerBand) and accumulation>=level1 and accumulation<level2
level3Res = ta.crossunder(rsi,upperBand) and distribution >=level3
level2Res = ta.crossunder(rsi,upperBand) and distribution >=level2 and distribution <level3
level1Res = ta.crossunder(rsi,upperBand) and distribution >=level1 and distribution <level2
boxColor= level1Support or level1Res? colorLevel1 : level2Support or level2Res ? colorLevel2 : level3Support or level3Res ? colorLevel3 :na
if level1Support or level2Support or level3Support
box.new(bar_index-accumulation,lowerBand,bar_index,lowBar,border_color = boxColor,bgcolor = boxColor)
alert("New Accumulation",alert.freq_once_per_bar_close)
if level1Res or level2Res or level3Res
box.new(bar_index-distribution ,upperBand,bar_index,highBar,border_color = boxColor,bgcolor = boxColor)
alert("New Distribution",alert.freq_once_per_bar_close)
plot(rsi,"RSI",#434651,2)
upperLine = hline(upperBand,"Upper Band")
lowerLine = hline(lowerBand,"Lower Band")
fill(upperLine,lowerLine,color=color.new(#434651,97),title = "Background") |
Dollar Cost Volume | https://www.tradingview.com/script/NY4usquY-Dollar-Cost-Volume/ | jocull | https://www.tradingview.com/u/jocull/ | 40 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jocull
//@version=5
indicator("Dollar Cost Volume", shorttitle="DCV", format=format.volume)
source = input.source(hlc3, "Pricing Source")
invert = input.bool(false, "Invert price?")
maLen = input.int(24, "SMA Length")
stDevLen = input.int(200, "Std Dev Length")
stDevMulti = input.float(2, "Std Dev Multiplier")
vol = volume
cost = (invert ? (1 / source) : source) * vol
ma = ta.sma(cost, maLen)
upper = ma + (ta.stdev(cost, stDevLen) * stDevMulti)
riseColor = color.rgb(38, 166, 154, 50)
fallColor = color.rgb(239, 83, 80, 50)
riseOrFallColor = source[0] < source[1] ? fallColor : riseColor
plot(cost, style=plot.style_columns, color=riseOrFallColor, title="Dollar Cost Volume")
plot(ma, style=plot.style_line, color=color.blue, title="Average")
plot(upper, style=plot.style_line, color=color.red, title="Std Dev Band", display=display.none)
|
Momentum Sparkler (MS) | https://www.tradingview.com/script/XQ2dhXke-Momentum-Sparkler-MS/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 38 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("Momentum Sparkler", overlay = true, max_bars_back = 5000)
source = input.source(close, "Source")
length = input.int(45, "Length", 1)
lines = array.new<line>(length)
if barstate.islast
for i = 0 to length
array.push(lines, line.new(bar_index, source , bar_index+i, source + (source-source[i]), color= color.from_gradient(i, 0, length, color.new(color.red, 5 + i*2 - 5), color.new(color.green, 5 + i*2 - 5))))
if barstate.isconfirmed
for i = 0 to array.size(lines) - 1
line.delete(array.get(lines, i)) |
Expected Move Plotter Intraday | https://www.tradingview.com/script/Y2nSIM65-Expected-Move-Plotter-Intraday/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 192 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Steversteves
//@version=5
indicator("Expected Move Plotter Intraday", overlay = true)
// Reference Timeframes
ticker = ticker.new(syminfo.prefix, syminfo.ticker, session.regular)
this_wopen = request.security(ticker, "60", open, lookahead=barmerge.lookahead_on)
this_mopen = request.security(ticker, "15", open, lookahead=barmerge.lookahead_on)
this_dopen = request.security(ticker, "30", open, lookahead=barmerge.lookahead_on)
last_dclose = request.security(ticker, "5", close[1], lookahead=barmerge.lookahead_on)
last_dhigh = request.security(ticker, "5", high[1], lookahead=barmerge.lookahead_on)
last_dlow = request.security(ticker, "5", low[1], lookahead=barmerge.lookahead_on)
today_close = request.security(ticker, "5", close, lookahead=barmerge.lookahead_on)
// Get Hourly Data
whigh1 = request.security(ticker, "60", high[1] - open[1], lookahead=barmerge.lookahead_on)
whigh2 = request.security(ticker, "60", high[2] - open[2], lookahead=barmerge.lookahead_on)
whigh3 = request.security(ticker, "60", high[3] - open[3], lookahead=barmerge.lookahead_on)
whigh4 = request.security(ticker, "60", high[4] - open[4], lookahead=barmerge.lookahead_on)
whigh5 = request.security(ticker, "60", high[5] - open[5], lookahead=barmerge.lookahead_on)
wlow1 = request.security(ticker, "60", open[1] - low[1], lookahead=barmerge.lookahead_on)
wlow2 = request.security(ticker, "60", open[2] - low[2], lookahead=barmerge.lookahead_on)
wlow3 = request.security(ticker, "60", open[3] - low[3], lookahead=barmerge.lookahead_on)
wlow4 = request.security(ticker, "60", open[4] - low[4], lookahead=barmerge.lookahead_on)
wlow5 = request.security(ticker, "60", open[5] - low[5], lookahead=barmerge.lookahead_on)
// Get 15 min data
mhigh1 = request.security(ticker, "15", high[1] - open[1], lookahead=barmerge.lookahead_on)
mhigh2 = request.security(ticker, "15", high[2] - open[2], lookahead=barmerge.lookahead_on)
mhigh3 = request.security(ticker, "15", high[3] - open[3], lookahead=barmerge.lookahead_on)
mhigh4 = request.security(ticker, "15", high[4] - open[4], lookahead=barmerge.lookahead_on)
mhigh5 = request.security(ticker, "15", high[5] - open[5], lookahead=barmerge.lookahead_on)
mlow1 = request.security(ticker, "15", open[1] - low[1], lookahead=barmerge.lookahead_on)
mlow2 = request.security(ticker, "15", open[2] - low[2], lookahead=barmerge.lookahead_on)
mlow3 = request.security(ticker, "15", open[3] - low[3], lookahead=barmerge.lookahead_on)
mlow4 = request.security(ticker, "15", open[4] - low[4], lookahead=barmerge.lookahead_on)
mlow5 = request.security(ticker, "15", open[5] - low[5], lookahead=barmerge.lookahead_on)
// Get 30 Data
dhigh1 = request.security(ticker, "30", high[1] - open[1], lookahead=barmerge.lookahead_on)
dhigh2 = request.security(ticker, "30", high[2] - open[2], lookahead=barmerge.lookahead_on)
dhigh3 = request.security(ticker, "30", high[3] - open[3], lookahead=barmerge.lookahead_on)
dhigh4 = request.security(ticker, "30", high[4] - open[4], lookahead=barmerge.lookahead_on)
dhigh5 = request.security(ticker, "30", high[5] - open[5], lookahead=barmerge.lookahead_on)
dlow1 = request.security(ticker, "30", open[1] - low[1], lookahead=barmerge.lookahead_on)
dlow2 = request.security(ticker, "30", open[2] - low[2], lookahead=barmerge.lookahead_on)
dlow3 = request.security(ticker, "30", open[3] - low[3], lookahead=barmerge.lookahead_on)
dlow4 = request.security(ticker, "30", open[4] - low[4], lookahead=barmerge.lookahead_on)
dlow5 = request.security(ticker, "30", open[5] - low[5], lookahead=barmerge.lookahead_on)
// Hourly Lows
weekly_low_avg = (wlow1 + wlow2 + wlow3 + wlow4 + wlow5) / 5
weekly_low_plot = this_wopen - weekly_low_avg
plot(weekly_low_plot, "60 minute low", color=color.red)
// Hourly Highs
weekly_high_avg = (whigh1 + whigh2 + whigh3 + whigh4 + whigh5) / 5
weekly_high_plot = this_wopen + weekly_high_avg
plot(weekly_high_plot, "60 minute high", color=color.green)
// 15 nminute highs
monthly_high_avg = (mhigh1 + mhigh2 + mhigh3 + mhigh4 + mhigh5) / 5
monthly_high_plot = this_mopen + monthly_high_avg
filla = plot(monthly_high_plot, "15 minute high", color=color.green)
// 15 minute lows
monthly_low_avg = (mlow1 + mlow2 + mlow3 + mlow4 + mlow5) / 5
monthly_low_plot = this_mopen - monthly_low_avg
fillb = plot(monthly_low_plot, "15 minute low", color=color.red)
// 30 minute highs
daily_high_avg = (dhigh1 + dhigh2 + dhigh3 + dhigh4 + dhigh5) / 5
daily_high_plot = this_dopen + daily_high_avg
plot(daily_high_plot, "30 minute high", color=color.green)
// 30 minute low
daily_low_avg = (dlow1 + dlow2 + dlow3 + dlow4 + dlow5) / 5
daily_low_plot = this_dopen - daily_low_avg
plot(daily_low_plot, "30 minute low", color=color.red)
// Sentiment
pp = (last_dhigh + last_dlow + last_dclose) / 3
bool bullish = today_close > pp
bool bearish = today_close < pp
color bullcolor = color.new(color.green, 85)
color bearcolor = color.new(color.red, 85)
color sent = bullish ? bullcolor : bearish ? bearcolor : na
fill(filla, fillb, color=sent) |
Subsets and Splits