Number of instances where RSI is greater than WMA only on weekly charts - charts

Say from a specific timeline - for eg: Mar 2020 - count the number of instances when RSI crossed WMA. ( only on Weekly charts).
Count is incremented only when RSI comes below WMA and then crosses from below.
So far written the code as below. It highlights as a band the place where RSI crosses WMA.
What I would really like if I can use a counter. Also to do this ONLY on weekly charts.
//#version=5
// RSI WMA EMA
indicator(title="RSI EMA Crossover", overlay=false)
src = input.source(close,title="Source")
len = input.int(9, minval=1, title="RSI")
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))
wmaLength = input.int(21, title="WMA")
emaLength = input.int(3, title="EMA")
wma = ta.wma(rsi, wmaLength)
ema = ta.ema(rsi, emaLength)
longcond = ta.crossover(rsi,wma)
plot(rsi, color=color.red, linewidth=2, title="RSI")
plot(wma, color=color.blue, linewidth=2, title="WMA")
plot(ema, color=color.green, linewidth=2, title="EMA")
bgcolor(longcond ? color.silver: na)

Related

Change RSI Plot Range - Possible or not?

We know that RSI plotting range is between 0 to 100.
Is it possible to change a plotted indicator line so that it will fluctuate in an extended range, say -50 to 100 ?
In simple way I want it to be (stretched) so I can easily draw trend line on the RSI line.
Attached photo is sample of what I mean on is perfect , one that I have is not like it.
I want the the RSI to cross the green and red area without affecting the movement of the indicator. I just want it to be stretching.
enter image description here
enter image description here
//#version=5
indicator(title="Relative Strength Index", shorttitle="RSI", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
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)
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="MA Settings")
maLengthInput = input.int(50, title="MA Length", group="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)
rsicolor = rsi > 70 ? color.new(#ff0057, 0) : rsi < 30 ? color.new(#ff0057, 0) : #1056ee
plot(rsi, "RSI", color=rsicolor, linewidth=2, style=plot.style_stepline)
plot(rsiMA, "RSI-based MA", color=color.rgb(120, 206, 255))
OverBought1 = input.int(80, minval=1)
OverBought2 = input.int(90, minval=1)
OverSold1 = input.int(20, minval=1)
OverSold2 = input.int(10, minval=1)
OB1 = hline(OverBought1 , color=color.red, linestyle=hline.style_dashed)
OB2 = hline(OverBought2 , color=color.red, linestyle=hline.style_dashed)
OS1 = hline(OverSold1 , color=color.green, linestyle=hline.style_dashed)
OS2 = hline(OverSold2 , color=color.green, linestyle=hline.style_dashed)
fill(OB1 , OB2, color=color.rgb(255, 82, 82, 80), title="Red Zoon Fill")
fill(OS1 , OS2 , color=color.rgb(76, 175, 79, 80), title="Green Zoon Fill")
Any ideas, please?
Thank you!
Colin
Is it possible to change a plotted indicator line so that it will fluctuate in an extended range, say -50 to 100 ?
In simple way I want it to be (stretched) so I can easily draw trend line on the RSI line.
Attached photo is sample of what I mean on is perfect , one that I have is not like it.
I want the the RSI to cross the green and red area without affecting the movement of the indicator. I just want it to be stretching.
You can use normalize() function:
//#version=5
indicator("My script")
normalize(_src, _min, _max) =>
// Normalizes series with unknown min/max using historical min/max.
// _src : series to rescale.
// _min, _min: min/max values of rescaled series.
var _historicMin = 10e10
var _historicMax = -10e10
_historicMin := math.min(nz(_src, _historicMin), _historicMin)
_historicMax := math.max(nz(_src, _historicMax), _historicMax)
_min + (_max - _min) * (_src - _historicMin) / math.max(_historicMax - _historicMin, 10e-10)
rsi = ta.rsi(close, 20)
rsiNormalized = normalize(rsi, -50, 100)
plot(rsiNormalized)
hline(-50)
hline(100)
EDIT
In your case, since we know the scale will always be between 0 to 100, we can use math to solve the issue much more accurately:
//#version=5
indicator("My script")
rsi = ta.rsi(close, 20) // this will give a value between 0 to 100
// find the value compared to a scale of 100
rsiPerc = rsi / 100
// multiply by the new range to get the position of rsi on the new range
rsiOnNewScale = rsiPerc * 150
// place the newRsi on a scale of -50 to 100
newRsi = rsiOnNewScale - 50
plot(newRsi)
hline(-50)
hline(100)
Or in short:
//#version=5
indicator("My script")
rsi = ta.rsi(close, 20) // this will give a value between 0 to 100
newRsi = (rsi / 100 * 150) - 50
plot(newRsi)
hline(-50)
hline(100)

Strategy ATR TP/SL target doesn't stay 'locked' to my entry readings

I want a strategy to Take Profit/Stop Loss to be based on the ATR (plus multiplier). However, I want it to be whatever the readings were at the point of entry, not simply the last candle (which is what it seems to be doing). Weird thing is that I have other strategies that use this approach, and they seem fine, so I'm really stumped by what I'm doing wrong.
Any help would be much appreciated!
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dave-browning
//#version=5
strategy("Dead-Cat Bounce", overlay = true, initial_capital = 1000, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, currency = currency.GBP, commission_value = 0.05, use_bar_magnifier = true)
trendEMAlength = input.int(130, "Trend EMA Length")
fastSMALength = input.int(14, "Fast SMA Length")
tpATRmultiplyer = input.float(6.2, "Short TP ATR Multiplier")
slATRmultiplier = input.float(4, "Short SL ATR Multiplier")
//Trade Conditions
shortCondition = close > ta.sma(close, fastSMALength) and close < ta.ema(close, length=trendEMAlength)
notInTrade = strategy.position_size <= 0
atr = ta.atr(14)
ema=ta.ema(close, trendEMAlength)
plot(ta.sma(close,length=fastSMALength), color=color.blue, linewidth = 2)
plot(ta.ema(close, length=trendEMAlength), color=color.yellow, linewidth = 4)
plot(low - (atr * tpATRmultiplyer), color=color.green)
plot(high + (atr * slATRmultiplier), color=color.red)
if shortCondition and notInTrade
stopLoss = (high + (atr * slATRmultiplier))
takeProfit = (low - (atr * tpATRmultiplyer))
strategy.entry("Short", strategy.short)
strategy.exit("Short Exit", "Short", limit=takeProfit, stop=stopLoss)

draw line and color the area above in indicator in Trading View with Pine Script

I want to draw a horizontal line at fixed value 30.000 and color the area above in light green in the DMI Indicator. How is this possible?
Thanks
//#version=5
indicator(title="Directional Movement Index", shorttitle="DMI", format=format.price, precision=4, timeframe="", timeframe_gaps=true)
lensig = input.int(14, title="ADX Smoothing", minval=1, maxval=50)
len = input.int(14, minval=1, title="DI Length")
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), lensig)
plot(adx, color=#F50057, title="ADX")
plot(plus, color=#2962FF, title="+DI")
plot(minus, color=#FF6D00, title="-DI")
You can use the hline and fill functions
https://www.tradingview.com/pine-script-reference/v5/#fun_fill
https://www.tradingview.com/pine-script-reference/v5/#fun_hline
hline(30, title = "30 Line", color=color.blue, linestyle=hline.style_solid, linewidth=2)
fill(30, 100, color = color.new(color.green, 90))

increasing the displayed indicator value by a percentage

i'm trying to find a way to make a indicator like rsi or stochastic but be able to adjust the output by a percentage. For example RSI signal that is increased by a percentage of what i would output by default. So it normally show 70 but is increased to 80 e.g.
Is there a way to do this? I've been scrolling through the manual for hours but couldnt find it.
Any help is appreciated
//#version=4
study(title="RSI", shorttitle="RSI", format=format.price, precision=2, resolution="")
len = input(14, minval=1, title="Length")
src = input(close, "Source", type = input.source)
rsiValue = rsi(src, len)
i_perc = input(10, title = "Percentage", type = input.float) * 0.01
up = rma(max(change(src), 0), len)
down = rma(-min(change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsi_increase_conditon = rsiValue >= rsiValue[1] * (1 + i_perc)
rsi_decrease_conditon = rsiValue <= rsiValue[1] * (1 - i_perc)
plot(rsi, "RSI", color=color.white)
hline(70, "OBBand", color=color.red, linestyle=hline.style_solid)
hline(20, "XOSBand", color=color.blue, linestyle=hline.style_solid)
hline(50, "Mid", color=color.gray, linestyle=hline.style_solid)
hline(80, "XOBBand", color=color.blue, linestyle=hline.style_solid)
hline(30, "OSBand", color=color.red, linestyle=hline.style_solid)
i_perc = input(10, title = "Percentage", type = input.float) * 0.01
...
rsi_increase_conditon = rsiValue >= rsiValue[1] * (1 + i_perc)
rsi_decrease_conditon = rsiValue <= rsiValue[1] * (1 - i_perc)
plotshape(rsi_increase_conditon and not rsi_increase_conditon[1], title = "RSI Increase %", style = shape.triangleup, location = location.belowbar, size = size.normal)
plotshape(rsi_decrease_conditon and not rsi_decrease_conditon[1], title = "RSI Decrease %", style = shape.triangledown, location = location.abovebar, size = size.normal)

TRADE open and close in the same time

in the following strategy all time (trades) open and close in the same time, so I pay only fees.
I have written to tradingview assistance, they have said me (and send) to put OPEN LONG and CLOSE LONG (the first 2 lines in strategy).
But I still have the same problem, I don't know why.
All test are ok, I think that problem is with TRAIDINGVIEW HUB, but I am not scure.
Thanks for your attention and time
strategy V5
Open Long:
{"pair":"BTCUSDT","unitsPercent":"50","unitsType":"percentWallet","exchange":"Bybit","apiKey":"TradingView BYBIT ACC AFF","token":"7dfa66d6-5b94-4047-a11c-e8bdd0f1c0f4","isBuy":true,"isMarket":false,"leverage":"5","marginType":"ISOLATED","closeCurrentPosition":true,"delay":"10"}
Close Long:
{"pair":"BTCUSDT","unitsPercent":"50","exchange":"Bybit","apiKey":"TradingView BYBIT ACC AFF","token":"7dfa66d6-5b94-4047-a11c-e8bdd0f1c0f4","isClose":true,"delay":"10"}
strategy(title='Take profit (% of instrument price)', overlay=true, pyramiding=1)
// STEP 1:
// Make inputs that set the take profit % (optional)
FastPeriod = input.int(title='Fast MA Period', defval=18, minval=1, group='Moving Average')
SlowPeriod = input.int(title='Slow MA Period', defval=20, minval=1, group='Moving Average')
TPPerc = input.float(title='Long Take Profit (%)', minval=0.0, step=0.5, defval=0.9, group='TP & SL')
SLPerc = input.float(title='Long Stop Loss (%)', minval=0.0, step=0.1, defval=4, group='TP & SL')
TP_Ratio = input.float(title='Sell Postion Size % # TP', defval=100, step=1, group='TP & SL', tooltip='Example: 100 closing 100% of the position once TP is reached') / 100
// Calculate moving averages
fastSMA = ta.sma(close, FastPeriod)
slowSMA = ta.sma(close, SlowPeriod)
// Calculate trading conditions
enterLong = ta.crossover(fastSMA, slowSMA)
// Plot moving averages
plot(series=fastSMA, color=color.new(color.green, 0), title='Fase MA')
plot(series=slowSMA, color=color.new(color.red, 0), title='Slow MA')
// STEP 2:
// Figure out take profit price
percentAsPoints(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100.0 * strategy.position_avg_price / syminfo.mintick) : float(na)
percentAsPrice(pcnt) =>
strategy.position_size != 0 ? (pcnt / 100.0 + 2.0) * strategy.position_avg_price : float(na)
current_position_size = math.abs(strategy.position_size)
initial_position_size = math.abs(ta.valuewhen(strategy.position_size[1] == 0.0, strategy.position_size, 0))
TP = strategy.position_avg_price + percentAsPoints(TPPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
SL = strategy.position_avg_price - percentAsPoints(SLPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
// Submit entry orders
if enterLong
strategy.entry(id='Long', direction=strategy.long)
// STEP 3:
// Submit exit orders based on take profit price
if strategy.position_size > 0
strategy.exit('TP', from_entry='Long', qty=initial_position_size * TP_Ratio, limit=TP, stop=SL)
// Plot take profit values for confirmation
plot(series=strategy.position_size > 0 ? TP : na, color=color.new(color.green, 0), style=plot.style_circles, linewidth=1, title='Take Profit 1')
plot(series=strategy.position_size > 0 ? SL : na, color=color.new(color.red, 0), style=plot.style_circles, linewidth=1, title='Stop Loss')