Historical Camarilla Levels - pine-script-v5

I've got a simple historical camarilla indicator that I'm mostly happy with, save for one detail. My horizontal lines are plotted from 9:30 until 9:30 the next day, except on the Friday to Monday transition. I don't really understand why this happens. So what I'd like is for the lines to start from 7:00 to 18:00 every day, in order to align with price action in the pre/post market. I'm not very good at pinescript, and I can't seem to find a solution. Is this even possible using 'plot', or should I be using 'line.new'? Any help would be greatly appreciated. The script I have is as follows;
//#version=5
indicator('Camarilla Levels', overlay=true)
// User inputs
showHistoricalCams = input(title='Show Historical Cam Pivots', defval=true)
//Camarilla Calculations
tR3 = close + (high - low) * 1.1 / 4.0
tS3 = close - (high - low) * 1.1 / 4.0
tR4 = close + (high - low) * 1.1 / 2.0
tS4 = close - (high - low) * 1.1 / 2.0
//Pivot Range
_tR4 = request.security(syminfo.tickerid, 'D', tR4)
_tR3 = request.security(syminfo.tickerid, 'D', tR3)
_tS3 = request.security(syminfo.tickerid, 'D', tS3)
_tS4 = request.security(syminfo.tickerid, 'D', tS4)
//Plot Historical Cam
plot(showHistoricalCam ? _tR3 : na, title=' R3', color=_tR3 != _tR3[1] ?
#eeeeee00 : #ff000080, style=plot.style_line, linewidth=1)
plot(showHistoricalCam ? _tR4 : na, title=' R4', color=_tR4 != _tR4[1] ?
#eeeeee00 : #ff000080, style=plot.style_line, linewidth=1)
plot(showHistoricalCam ? _tS3 : na, title=' S3', color=_tS3 != _tS3[1] ?
#eeeeee00 : #008000FF, style=plot.style_line, linewidth=1)
plot(showHistoricalCam ? _tS4 : na, title=' S4', color=_tS4 != _tS4[1] ?
#eeeeee00 : #008000FF, style=plot.style_line, linewidth=1)
**The lines are plotted this way to remove the 'connecting' lines
I've tried setting time parameters, but can't make the script work.

Related

Add extended trading hours (premarket and afterhours) to current pine script code

I have an indicator that plots percentage levels above current high/low/open/close (user selected) for the intraday levels. I would like to incorporate extended trading hours into the code. For example if the premarket high of day is higher than regular hours high of day, I'd like the indicator to calculate the percentage levels using the premarket high instead of the intraday. I'm not sure how to code this into the script but I assume it would be fairly simple (I'm just not a coder). Script below:
study(title="% Levels", overlay=true)
//Select Source to Plot Levels
calc = input(title="Calculation Source", defval="Open", options=["Open","High", "Low", "Close"])
showlast = input(title="Historical Bars to Display", defval=3, options= [1,2,3,4,5,10,15,20,30,50,100,200,300], group="Custom Line Plot Extension Settings || Base Settings for Stocks/ETF's are '1' & '0' Respectively || To Extend Lines: Ideally both values should be equal when adjusting || For Futures: 1 & 0 Recommended")
extendLines = input(title="Offset Starting Plot", defval=0, options=[0,1,3,5,10,15,20,30,50,100,200,300])
//Ticker Variables
o = security(syminfo.tickerid, "D", open)
h = security(syminfo.tickerid, "D", high)
l = security(syminfo.tickerid, "D", low)
c = security(syminfo.tickerid, "D", close)
calcm = if calc == "High"
h
else if calc == "Low"
l
else if calc == "Close"
c
else if calc == "Open"
o
//Calculations for % Levels
pct10= calcm*1.10
pctm10=calcm*0.90
pct12_5 = calcm*1.125
pctm12_5 = calcm*0.875
pct15= calcm*1.15
pctm15=calcm*0.85
//% Levels plotted based on Daily Open, High, Low, or Close
plot(pct10, title="10%", color=color.white, style=plot.style_line, show_last=showlast, offset=extendLines)
plot(pct12_5, title="12.5%", color=color.white, style=plot.style_line, show_last=showlast, offset=extendLines)
plot(pct15, title="15%", color=color.white, style=plot.style_line, show_last=showlast, offset=extendLines)
plot(pctm10, title="-10%", color=color.red, style=plot.style_line, show_last=showlast, offset=extendLines)
plot(pctm12_5, title="-12.5%", color=color.red, style=plot.style_line, show_last=showlast, offset=extendLines)
plot(pctm15, title="-15%", color=color.red, style=plot.style_line, show_last=showlast, offset=extendLines)
Not a coder so not sure what to try.
There are three built-in variables which you can use:
session.ismarket: Returns true if the current bar is a part of the regular trading hours (i.e. market hours), false otherwise
session.ispostmarket: Returns true if the current bar is a part of the post-market, false otherwise. On non-intraday charts always returns false.
session.ispremarket: Returns true if the current bar is a part of the pre-market, false otherwise. On non-intraday charts always returns false.

Looking for current price > previous day high . Works fine but plotting for all the 5 minutes candle

Here is my usecase :
if currentprice of 5 minutes candle is greater than previous day high , plot the chart with the 'x' mark in green .
If currentprice of 5 minutes candle is lesser than previous day low , plot the chart with 'x' mark in green
This script prints the 'x' mark for every 5 minutes but I want to plot only first for the first time when condition is met
I used a counter to check if it is a new day but seems that is not working as expected
//#version=5
indicator("HLPrice", max_lines_count = 11, overlay=true)
emaValue8 = ta.ema(close,8)
emaValue21 = ta.ema(close,21)
vwapValue = ta.vwap(hlc3)
// to highlight the session
timeframe = "1D"
isNewDay = timeframe.change(timeframe)
bgcolor(isNewDay ? color.new(color.green, 80) : na)
[dh,dl,dc] = request.security(syminfo.ticker, "D", [high[1],low[1], close[1]], lookahead=barmerge.lookahead_on)
isNewDayy = time("D") != time("D")[1]
var plotcond = false
greaterThanPreviousDayHigh = false
lesserThanPreviousDayLow = false
if isNewDayy
plotcond := true
if close[0] > dh and plotcond
greaterThanPreviousDayHigh:=true
if close[0] < dl and plotcond
lesserThanPreviousDayLow:=true
plotshape(series=greaterThanPreviousDayHigh , title="Candle on All EMAs" ,color = color.green, size=size.tiny)
plotshape(series=lesserThanPreviousDayLow , title="Candle on All EMAs" ,color = color.red, size=size.tiny)

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')

Pine Script - Tradingview Draw a daily rectangle

I'm working on a TradingView script (Pine) and I would to develop a simply script that draw a rectangle from a start of current day to the end based on my current timeframe from Monday To Friday...
Example: First rectangle drawed from 24/03/2021 to 25/03/2021, Second Rectangle drawed from 25/03/2021 to 26/03/2021, etc...
Any solutions to achieve this result?
Thank's in advance
I think I have understood your request. The below should help assist you
//#version=4
study("Daily Box", overlay=true)
Bottom = input(title="Bottom", type=input.session, defval="0000-2359:1234567")
colourcheck = 1.0
boxheight = input(title="Box Height", type=input.float, defval=3)
DailyHigh = security(syminfo.tickerid, "D", high, lookahead=true)
DailyLow = security(syminfo.tickerid, "D", low, lookahead=true)
dayrange = DailyHigh - DailyLow
BottomLowBox = DailyLow + (dayrange * 0.01 * boxheight)
TopLowBox = DailyHigh - (dayrange * 0.01 * boxheight)
BarInSession(sess) => time(timeframe.period, sess) != 0
//ASIA
BottomL = plot(DailyLow and BarInSession(Bottom) ? DailyLow : na, title="Bottom High", style=plot.style_linebr, linewidth=3, color=na)
TopL = plot(DailyHigh and BarInSession(Bottom) ? DailyHigh : na, title="Bottom Low", style=plot.style_linebr, linewidth=3, color=na)
fill(BottomL, TopL, color=color.purple, title="Fill Box", transp=50)

How to offset an alert on pine editor (TradingView)

I need some help to offset my alert by 1
I'm able to offset the arrow (plotted) but I can't figure out how to offset the actual alert so it comes on the next candle (so the cross is confirmed)
tavg = tos == 1 ? avg(a,avg) : avg(b,avg)
tavgi = tosi == 1 ? avg(ai,avgi) : avg(bi,avgi)
enterLong = crossover(tavgi, tavg)
enterShort = crossunder(tavgi, tavg)
alertcondition(enterLong, title='Long', message='long tradesymbol=EURUSD')
alertcondition(enterShort, title='Short', message='short tradesymbol=EURUSD')
How to add an offset=1 to enterLong and enterShort
I tried
enterLong = crossover(tavgi, tavg)
barcolor(color=enterLong ? blue : na, offset=1)
alertcondition(condition=enterLong,
message="long tradesymbol=EURUSD")
enterShort = crossunder(tavgi, tavg)
barcolor(color=enterShort ? orange : na, offset=1)
alertcondition(condition=enterShort,
message="short tradesymbol=EURUSD")
but it obviously only offset only the barcolor not the alert :(
Sorry I can't put the whole code but if you have an idea it would be highly appreciated thanks
This can be done via the history operator [], checking the condition on the previous bar:
alertcondition(enterLong[1], title='Long', message='long tradesymbol=EURUSD')
alertcondition(enterShort[1], title='Short', message='short tradesymbol=EURUSD')