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

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.

Related

plot the high low of 1 minute and 15 minutes bar during RTH 9:30 am ET (Pine script)

How do I plot horizontal lines using high and low of the first one minute bar after market opens at 9:30 (NYSE time)?
Possibly I would like to plot the open, high and close of 1st 1 minute bar.
Then when first 15 minutes is done, would like to plot the high and low of that bar as well.
I tried with OHLC indicator and others, but couldn't find something to tackle exactly this.
Also the below code that I got it from chatGPT, but it got couple of errors
type here
indicator("First Minute Bar High and Low", overlay=true)
var float firstBarHigh = na
var float firstBarLow = na
// Define the regular trading hours for the NYSE in Eastern Time
var tradingHoursStart = input("09:30-5", "Trading Hours")
var tradingHoursEnd = input("16:00-5", "Trading Hours")
var tradingHoursRange = time(tradingHoursStart + ":1234567-" + tradingHoursEnd + ":1234567")
// Define the desired time in Eastern Time
var timeInET = timenow("America/New_York")
if hour(timeInET) == 9 and minute(timeInET) == 30 and timeInET >= tradingHoursRange
if barstate.isfirst
firstBarHigh := high
firstBarLow := low
```plot(firstBarHigh, "First Minute High", color=color.green)
```plot(firstBarLow, "First Minute Low", color=color.red)

Historical Camarilla Levels

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.

Keeping orders from closing if conditions are met & multiple orders

First time coding - trying to set up a bot that creates multiple buy orders every time the buying signal is met and closed once the short signal is triggered - and vice versa. It seems to be working in TradingView when I add the strategy to the chart however when I connect it to 3 commas it only takes in one buy order (paper trading account) - and it closes it specifically when the condition to keep the position from closing is triggered.
I think I've set up the strategy correctly to take up to six positions with pyramiding.
strategy("DEMA CROSS STRATEGY", shorttitle = "DEMAC-S", overlay = true, initial_capital = 4000, default_qty_type = strategy.percent_of_equity, default_qty_value = 20, commission_type = strategy.commission.percent, commission_value = 0.03, pyramiding = 6)
The conditions to keep a position from closing if longAction or shortAction are true, then keep the opened positions from closing, otherwise close all positions and open a long/short.
positionState = volume < valueThreshold and ADXsignal < adxThreshold
//logic
longCondition = ta.crossover(DEMA1, DEMA2) and supertrend_X_min < close and mfi+rsi/1.8 > 40 and close > WMA
shortCondition = ta.crossunder(DEMA1, DEMA2) and supertrend_X_min > close and mfi+rsi/1.8 < 60 and close < WMA and atr < .05
longAction = (longCondition and positionState)
shortAction = (shortCondition and positionState)
if (shortAction or longAction)
false
else
if (longCondition)
strategy.entry("Enter Long", strategy.long)
strategy.exit("Exit Short", stop=na)
if (shortCondition)
strategy.entry("Enter Short", strategy.short)
strategy.exit("Exit Long", stop=na)
//
//Buy and sell alerts
buyAlert = XXXXXXXXXXXXXXXXXXXXXXXXXXX
exitAlert = XXXXXXXXXXXXXXXXXXXXXXXXXXXX
if longAction ? na : longCondition
alert(buyAlert, alert.freq_once_per_bar)
if shortAction ? na : shortCondition
alert(exitAlert, alert.freq_once_per_bar)
I've tried multiple different if then statements but honestly I'm not sure if I'm just doing it plain wrong at this stage.
Like I've stated, the code works in TradingView - not in 3Commas

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)

Script for indicating order history - Tradeview Pine

I want to indicate historical trades in tradingview charts via a script based on information on time and price for entry and close.
My best idea is to search through "time" to find matches for entry and close, and then change the background color according to short or long position or draw a horizontal line. However, this seems not optimal. Any suggestions?
I'd implement that in the next way:
//#version=3
strategy("Background changing", overlay=true)
NONE = 0
LONG = 1000
SHORT = -1000
position = NONE
position := nz(position[1], NONE)
longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
strategy.entry("LongEntryId", strategy.long)
position := LONG
if (close < high[1])
strategy.close("LongEntryId")
position := NONE
getColor(state) =>
state == LONG ? green :
state == SHORT ? red :
white
bgcolor(color=getColor(position))
Or you can put arrows to the chart:
//#version=3
study("My Script", overlay=true)
order = 0
if time >= timestamp(2018, 1, 10, 0, 0)
order := 1
if time == timestamp(2018, 1, 17, 0, 0)
order := -1
plotarrow(order)