r_trend_exhaustion_upslidedown_8r6oARMe.pine
Copy
// © upslidedown
// One of the first indicators I ever used was %R, and I realized that with crypto strategies a period of 112
// provided very interesting results in trend following strategies. This indicator intends to mix standard %R
// with the longer period %R and show key areas of interest. Using classic overbought/oversold logic, the
// indicator highlights a key trend and a subsequent break in that trend. When this condition is detected it
// will print a reversal arrow down. This is one of my odder ideas that appears to have some merit, so I'm
// publicly publishing for the community to find. If you find this useful please reach out and let me know.
//@version=6
import HeWhoMustNotBeNamed/ta/1
indicator("%R Trend Exhaustion [upslidedown]", format=format.price, precision=2, explicit_plot_zorder=true, max_boxes_count=300)
const string version = "v2.3"
const string groupSettings = "Settings "+ version
// colors
var bullcol = input.color(#2466A7, 'Cold Color', group=groupSettings, inline="col")
var bearcol = input.color(#CA0017, 'Hot Color', group=groupSettings, inline="col")
var invisible = color.rgb(0, 0, 0, 100)
force_overlay = input.bool(true, title="Draw Boxes on Chart", group=groupSettings, inline='overlay')
max_boxes_to_print = input.int(60, title="#", minval=1, maxval=300, group=groupSettings, inline='overlay', active=force_overlay)
const string mode1 = "1 Oscillator Mode"
const string mode2 = "2 Overlay Mode (top and bottom no oscillator)"
const string mode3 = "3 Candle Mode"
mode = input.string(mode1, "Display Mode", options=[mode1, mode2, mode3], tooltip="Modes 2 & 3 are more advanced and expect that you most likely overlay the indicator on top of price action itself or another indiciator using TradingView's object tree panel.", group=groupSettings)
compact = mode == mode2
transparency = input.int(80, 'Base Transparency', minval=0, maxval=100, group=groupSettings)
var bullcol_xlight = color.new(bullcol, transparency)
var bearcol_xlight = color.new(bearcol, transparency)
var bullcol_light = color.new(bullcol, transparency-10)
var bearcol_light = color.new(bearcol, transparency-10)
var bullcol_medium = color.new(bullcol, transparency-20)
var bearcol_medium = color.new(bearcol, transparency-20)
var shortcol = chart.fg_color
var longcol = color.rgb(139, 174, 255)
var pivotcol = color.white
const int bull_signal_loc = -107
const int bear_signal_loc = 5
formula1 = "Standard (2 Period)"
formula2 = "Average"
//formula3 = "Difference" //removed difference because it was too much a headache to maintain and not good IMO
formula = input.string(formula1, "Formula", options=[formula1, formula2], group=groupSettings)
use_average = formula == formula2
src = input.source(close, "Source", group=groupSettings)
threshold = input.int(20, title="Exhaustion Threshold", minval=1, maxval=50, group=groupSettings, tooltip="Sets the overbought/oversold zone size and offset. Lower values will produce less results, higher values towards 50 will produce many results.")
smoothType = input.string('ema', title="Smoothing Type", options=['sma', 'ema', 'hma', 'rma', 'wma', 'vwma', 'swma', 'highlow', 'linreg', 'median', 'mom', 'percentrank'], group=groupSettings)
average_ma = input.int(3, "Average Formula MA", group=groupSettings)
plot_shading = input.bool(true, title="Fill Gradients in OB/OS Zone", group=groupSettings)
plot_crosses = input.bool(false, title="Highlight Crossovers", group=groupSettings, tooltip="Experimental idea for plotting crossovers with attempted bull/bear coloring. This needs to be combined with other TA but typically crossover condition results in interesting price action during or after.")
plot_zero_crosses = input.bool(false, title="Plot Zero Line Crosses", group=groupSettings, tooltip="Experimental idea for plotting crosses")
const string lookbackGroupName = "Dual Signal Setup (Fast/Slow Lookback)"
shortLength = input.int(title="Fast Length", defval=21, group=lookbackGroupName)
shortSmoothingLength = input.int(7, title="Fast Smoothing Length", group=lookbackGroupName)
longLength = input.int(112, title="Slow Length", minval=1, group=lookbackGroupName)
longSmoothingLength = input.int(3, title="Slow Smoothing Length", group=lookbackGroupName)
// functions
_pr(length) =>
float max = ta.highest(length)
float min = ta.lowest(length)
100 * (src - max) / (max - min)
float s_percentR = _pr(shortLength)
float l_percentR = _pr(longLength)
float avg_percentR = math.avg(s_percentR, l_percentR)
if shortSmoothingLength > 1
s_percentR := ta.ma(s_percentR, smoothType, shortSmoothingLength)
if longSmoothingLength > 1
l_percentR := ta.ma(l_percentR, smoothType, longSmoothingLength)
if average_ma > 1
avg_percentR := ta.ma(avg_percentR, smoothType, average_ma)
var was_ob = false
var was_os = false
// ob/os logic
bool overbought = s_percentR >= -threshold and l_percentR >= -threshold
bool oversold = s_percentR <= -100+threshold and l_percentR <= -100+threshold
bool ob_reversal = not overbought and overbought[1]
bool os_reversal = not oversold and oversold[1]
bool ob_trend_start = overbought and not overbought[1]
bool os_trend_start = oversold and not oversold[1]
bool bool_cross_long1 = ta.crossover(s_percentR, -50)
bool bool_cross_long2 = ta.crossover(l_percentR, -50)
bool cross_zero_long = bool_cross_long1 or bool_cross_long2
bool bool_cross_short1 = ta.crossunder(s_percentR, -50)
bool bool_cross_short2 = ta.crossunder(l_percentR, -50)
bool cross_zero_short = bool_cross_short1 or bool_cross_short2
bool zero_long = (s_percentR > -50 and l_percentR > -50) and cross_zero_long
bool zero_short = (s_percentR < -50 and l_percentR < -50) and cross_zero_short
if use_average
// use average
overbought := avg_percentR >= -threshold
oversold := avg_percentR <= -100+threshold
ob_reversal := not overbought and overbought[1]
os_reversal := not oversold and oversold[1]
ob_trend_start := overbought and not overbought[1]
os_trend_start := oversold and not oversold[1]
// detect crossovers for potential "in between" signals
bool cross_bear = ta.crossover(l_percentR, s_percentR)
bool cross_bull = ta.crossunder(l_percentR, s_percentR)
// Print lines for stuff
top = hline(mode == mode1 ? 0 : na, 'Top', bearcol_medium, linestyle=hline.style_solid)
band1 = hline(mode == mode1 ? -threshold : na, 'Top Threshold', bearcol_medium, linestyle=hline.style_solid)
middle = hline(mode == mode1 ? -50 : na, 'Middle Line', color.new(chart.fg_color, 80), linestyle=hline.style_solid)
band0 = hline(mode == mode1 ? -100+threshold : na, 'Bottom Threshold', bullcol_medium, linestyle=hline.style_solid)
bottom = hline(mode == mode1 ? -100 : na, 'Bottom', bullcol_medium, linestyle=hline.style_solid)
// plot %R
p_fastr = plot(mode == mode1 and not use_average ? s_percentR : na, "Fast Period %R", color=shortcol, linewidth=1)
p_slowr = plot(mode == mode1 and not use_average ? l_percentR : na, "Slow Period %R", color=longcol, linewidth=1)
p_avgr = plot(mode == mode1 and use_average ? avg_percentR : na, "Average Formula %R", color=shortcol, linewidth=1)
gradientBullColor = plot_shading ? color.new(bullcol, 100) : invisible
gradientBearColor = plot_shading ? color.new(bearcol, 100) : invisible
fill(p_fastr, p_slowr, 0, -30, top_color = color.new(gradientBearColor, 0), bottom_color = gradientBearColor, title = "Overbought Gradient Fill")
fill(p_fastr, p_slowr, -70, -100, top_color = gradientBullColor, bottom_color = color.new(gradientBullColor, 0), title = "Oversold Gradient Fill")
getlocation(mode, tORb) =>
// expects top or bottom to be passed as second var
location = location.absolute
if (mode == mode2 or mode == mode3)
if tORb == 'top'
if (mode == mode3)
location := location.abovebar
else
location := location.top
else if tORb == 'bottom'
if (mode == mode3)
location := location.belowbar
else
location := location.bottom
location
// Draw persistent price boxes directly on chart while OB/OS conditions are active
var box ob_box = na
var box os_box = na
var float ob_box_top = na
var float ob_box_bottom = na
var float os_box_top = na
var float os_box_bottom = na
var array<box> printed_boxes = array.new_box()
plotshape(ob_reversal ? bear_signal_loc : na, title="Overbought Trend Reversal ▼", style=shape.triangledown, location=getlocation(mode, 'top'), color=bearcol, text='', textcolor=invisible, size=size.tiny)
plotshape(os_reversal ? bull_signal_loc : na, title="Oversold Trend Reversal ▲", style=shape.triangleup, location=getlocation(mode, 'bottom'), color=bullcol, text='', textcolor=invisible, size=size.tiny)
plotshape(force_overlay and ob_reversal and not na(ob_box_top) ? ob_box_top : na, title="Overbought Break Candle ▼", style=shape.triangledown, location=location.absolute, color=bearcol, text='', textcolor=invisible, size=size.tiny, force_overlay=true)
plotshape(force_overlay and os_reversal and not na(os_box_bottom) ? os_box_bottom : na, title="Oversold Break Candle ▲", style=shape.triangleup, location=location.absolute, color=bullcol, text='', textcolor=invisible, size=size.tiny, force_overlay=true)
plotshape(overbought ? bear_signal_loc : na, title="Overbought Trend Warning ■", style=shape.square, location=getlocation(mode, 'top'), color=bearcol_medium, text='', textcolor=invisible, size=size.tiny)
plotshape(oversold ? bull_signal_loc : na, title="Oversold Trend Warning ■", style=shape.square, location=getlocation(mode, 'bottom'), color=bullcol_medium, text='', textcolor=invisible, size=size.tiny)
if force_overlay
// Start a new overbought box on the first OB bar
if ob_trend_start
if not na(ob_box)
box.delete(ob_box)
ob_box_top := high
ob_box_bottom := low
ob_box := box.new(bar_index - 1, ob_box_top, bar_index, ob_box_bottom, bgcolor=bearcol_xlight, border_color=bearcol_medium, border_width=1, force_overlay=true)
array.push(printed_boxes, ob_box)
if array.size(printed_boxes) > max_boxes_to_print
box.delete(array.shift(printed_boxes))
// Extend active overbought box until condition ends
else if overbought and not na(ob_box)
box.set_right(ob_box, bar_index)
if high > ob_box_top
ob_box_top := high
box.set_top(ob_box, ob_box_top)
if low < ob_box_bottom
ob_box_bottom := low
box.set_bottom(ob_box, ob_box_bottom)
// Freeze box when OB condition ends
else if not overbought and not na(ob_box)
box.set_right(ob_box, bar_index - 1)
ob_box := na
// Start a new oversold box on the first OS bar
if os_trend_start
if not na(os_box)
box.delete(os_box)
os_box_top := high
os_box_bottom := low
os_box := box.new(bar_index - 1, os_box_top, bar_index, os_box_bottom, bgcolor=bullcol_xlight, border_color=bullcol_medium, border_width=1, force_overlay=true)
array.push(printed_boxes, os_box)
if array.size(printed_boxes) > max_boxes_to_print
box.delete(array.shift(printed_boxes))
// Extend active oversold box until condition ends
else if oversold and not na(os_box)
box.set_right(os_box, bar_index)
if high > os_box_top
os_box_top := high
box.set_top(os_box, os_box_top)
if low < os_box_bottom
os_box_bottom := low
box.set_bottom(os_box, os_box_bottom)
// Freeze box when OS condition ends
else if not oversold and not na(os_box)
box.set_right(os_box, bar_index - 1)
os_box := na
plotshape(zero_long and plot_zero_crosses ? bear_signal_loc : na, title="Zero Cross Long", style=shape.triangleup, location=getlocation(mode, 'top'), color=color.yellow, text='', textcolor=invisible, size=size.tiny)
plotshape(zero_short and plot_zero_crosses ? bull_signal_loc : na, title="Zero Cross Short", style=shape.triangledown, location=getlocation(mode, 'bottom'), color=color.yellow, text='', textcolor=invisible, size=size.tiny)
plot(not compact and plot_crosses and (cross_bull or cross_bear) ? l_percentR : na, "Crossover Dot (small)", style=plot.style_circles, color=cross_bull ? bullcol : bearcol, linewidth=4)
plot(not compact and plot_crosses and (cross_bull or cross_bear) ? l_percentR : na, "Crossover Dot (big)", style=plot.style_circles, color=cross_bull ? bullcol_light : bearcol_light, linewidth=12)
// Plot trend start
plotchar(ob_trend_start ? bear_signal_loc : na, char="◡", color=bearcol, location=getlocation(mode, 'top'))
plotchar(os_trend_start ? bull_signal_loc : na, char="◠", color=bullcol, location=getlocation(mode, 'bottom'))
// Alerts
varip groupAlerts = "Alerts"
bullStartOn = input.bool(true, "Bull trend start ⏹", group=groupAlerts, inline="bullStart")
bullStartTxt = input.string("%RTE bull trend start ⏹", "", group=groupAlerts, inline="bullStart")
bearStartOn = input.bool(true, "Bear trend start ⏹", group=groupAlerts, inline="bearStart")
bearStartTxt = input.string("%RTE bear trend start ⏹", "", group=groupAlerts, inline="bearStart")
bullReversalOn = input.bool(true, "Bull trend break ▼", group=groupAlerts, inline="bullReversal")
bullReversalTxt = input.string("%RTE bull trend break ▼", "", group=groupAlerts, inline="bullReversal")
bearReversalOn = input.bool(true, "Bear trend break ▲", group=groupAlerts, inline="bearReversal")
bearReversalTxt = input.string("%RTE bear trend break ▲", "", group=groupAlerts, inline="bearReversal")
bullCrossOn = input.bool(false, "Bull cross ⏺", group=groupAlerts, inline="bullCross")
bullCrossTxt = input.string("Bullish crossover", "", group=groupAlerts, inline="bullCross")
bearCrossOn = input.bool(false, "Bear cross ⏺", group=groupAlerts, inline="bearCross")
bearCrossTxt = input.string("Bearish crossover", "", group=groupAlerts, inline="bearCross")
if (bullStartOn and ob_trend_start)
alert(message=bullStartTxt, freq=alert.freq_once_per_bar_close)
if (bearStartOn and os_trend_start)
alert(message=bearStartTxt, freq=alert.freq_once_per_bar_close)
if (bullReversalOn and ob_reversal)
alert(message=bullReversalTxt, freq=alert.freq_once_per_bar_close)
if (bearReversalOn and os_reversal)
alert(message=bearReversalTxt, freq=alert.freq_once_per_bar_close)
if (bullCrossOn and cross_bull)
alert(message=bullCrossTxt, freq=alert.freq_once_per_bar_close)
if (bearCrossOn and cross_bear)
alert(message=bearCrossTxt, freq=alert.freq_once_per_bar_close)
alertcondition(ob_reversal, "Arrow Down (Bearish Reversal)", message="Arrow Down: Overbought trend is exhausted")
alertcondition(os_reversal, "Arrow Up (Bullish Reversal)", message="Arrow Up: Oversold trend is exhausted")
alertcondition(ob_trend_start, "Overbought Trend Started", message="Warning: Possible overbought trend exhaustion")
alertcondition(os_trend_start, "Oversold Trend Started", message="Warning: Possible oversold trend exhaustion")
alertcondition(cross_bull, "Bullish Crossover", message="Potential bullish crossover printed")
alertcondition(cross_bear, "Bearish Crossover", message="Potential bearish crossover printed")
// ---------------------------------------------
// Experimental difference idea
//varip diffGroupName = "Difference (Experimental)"
//plot_difference = input.bool(false, "Plot Difference", group=diffGroupName, tooltip="I thought maybe this would show buying or selling phase... but in the end I don't think this is very useful data. It's interesting to look at though!")
//invert_difference = input.bool(false, "Invert Difference Calcuation", group=diffGroupName)
//diffcol = input.color(color.new(#BABABA, 75), title="Difference Fill Color", group=diffGroupName)
//difference = invert_difference ? s_percentR-l_percentR : l_percentR-s_percentR
//difference := difference - 50
// Plot experimental difference idea
//diff_plot = plot(plot_difference ? difference : na, title="Difference", color=color.new(color.white,80), linewidth=1, style=plot.style_line)
//fill(diff_plot, plot(-50, color=invisible), title="Difference Fill", color=diffcol)
// ---------------------------------------------
const string group_strategy = "Strategy (send external signal to TTS backtester)"
bool plotStrategyEntry = input.bool(false, "Plot Strategy Entries on Chart", group=group_strategy)
bool longDealsEnabled = input.bool(true, "Enable Long Deals", group=group_strategy)
bool shortDealsEnabled = input.bool(true, "Enable Short Deals", group=group_strategy)
strategy1 = "1 Trend Following @ Square"
strategy2 = "2 Reversal @ Square"
strategy3 = "3 Reversal Trade @ Triangle"
strategy4 = "4 Re-enter Trend Trade @ Triangle"
strategy5 = "5 Pings"
strategy6 = "6 Zero Line Cross"
strategyEntry = input.string(strategy3, "Strategy Entry", options=[strategy1, strategy2, strategy3, strategy4, strategy5, strategy6], group=group_strategy)
bool startLongDeal = false
bool startShortDeal = false
bool endLongDeal = false
bool endShortDeal = false
switch strategyEntry
strategy1 =>
if ob_trend_start and longDealsEnabled
startLongDeal := true
else if os_trend_start and shortDealsEnabled
startShortDeal := true
strategy2 =>
if os_trend_start and longDealsEnabled
startLongDeal := true
else if ob_trend_start and shortDealsEnabled
startShortDeal := true
strategy3 =>
//strategy := ob_reversal ? -1 : os_reversal ? 1 : 0
if ob_reversal and shortDealsEnabled
startShortDeal := true
else if os_reversal and longDealsEnabled
startLongDeal := true
strategy4 =>
//strategy := ob_reversal ? -1 : os_reversal ? 1 : 0
if os_reversal and shortDealsEnabled
startShortDeal := true
else if ob_reversal and longDealsEnabled
startLongDeal := true
strategy5 =>
//strategy := ? 1 : cross_bear ? -1 : 0
if cross_bull and longDealsEnabled
startLongDeal := true
else if cross_bear and shortDealsEnabled
startShortDeal := true
strategy6 =>
if zero_long and longDealsEnabled
startLongDeal := true
else if zero_short and shortDealsEnabled
startShortDeal := true
//#region 🔌 SIGNAL
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
import jason5480/tts_convention/7 as conv
// LOGIC ===============================================================================================================
// Calculate the start, end conditions according to the user-defined logic
dealConditions = conv.DealConditions.new(
// Start deals should happen when the main rsi logic applies and the external condition is met
startLongDeal = startLongDeal,
startShortDeal = startShortDeal,
// End deals should happen when the main logic applies either the external condition is not met
endLongDeal = false,
endShortDeal = false)
// Use this signal in scripts like "Template Trailing Strategy (Backtester)" and "Signal Composer" that can utilize its value
// Emit the current signal value according to the TTS framework convention
plot(series = conv.getSignal(dealConditions), title = '🔌Signal to TTS', color = #808000, editable = false, display = display.data_window + display.status_line, precision = 0)
// PLOT ================================================================================================================
plotshape(plotStrategyEntry ? dealConditions.startLongDeal : false, title = 'Start Long', style = shape.triangleup, location = location.belowbar, color = bullcol, size = size.tiny, text="Long", textcolor = chart.fg_color, display = display.all - display.status_line, force_overlay = true)
// plotshape(series = dealConditions.endLongDeal, title = 'End Long', style = shape.square, location = location.belowbar, color = color.new(#C790F1, 70), offset = 1, size = size.tiny, display = display.all - display.status_line)
plotshape(plotStrategyEntry ? dealConditions.startShortDeal : false, title = 'Start Short', style = shape.triangledown, location = location.abovebar, color = bearcol, size = size.tiny, text="Short", textcolor = chart.fg_color, display = display.all - display.status_line, force_overlay = true)
// plotshape(series = dealConditions.endShortDeal, title = 'End Short', style = shape.square, location = location.abovebar, color = color.new(#C790F1, 70), offset = 1, size = size.tiny, display = display.all - display.status_line)
//#endregion ===========================================================================================================
Show all 372 lines