In Pine Script, how can you do something once per day, or keep track if something has been done yet that day? - unix-timestamp

I'm working on a TradingView script (Pine) and i'm trying to use my Daily-bar strategy on the 5-minute chart. To do this, I need to basically only check conditions once per day.
I can do this by having a boolean variable such as dailyCheck = false and set it to true when I run that code and then reset it on a new day.
Does anyone know how to go about doing this? From what I read in the pine manual it says you can get unix time...but I don't know how to work with this and I can't print anything except numbers in the form of plot, so I can't figure out how to tell when a new day has started. Thanks in advance!

Version 1
There are lots of ways to detect a change of day. The Session and time information User Manual page shows a few.
I like detecting a change in the dayofweek or dayofmonth built-in variables:
//#version=4
study("Once per Day")
var dailyTaskDone = false
newDay = change(dayofweek)
doOncePerDay = rising(close, 2) // Your condition here.
dailyTaskDone := doOncePerDay or (dailyTaskDone and not newDay)
plotchar(newDay, "newDay", "▼", location.top, transp = 60)
plotchar(doOncePerDay, "doOncePerDay", "•", location.top, transp = 0)
bgcolor(dailyTaskDone ? color.orange : na)
Version 2
Following Michel's comment, this uses a more robust detection of the day change:
//#version=4
study("Once per Day")
var dailyTaskDone = false
newDay = change(time("D"))
doOncePerDay = rising(close, 2) // Your condition here.
dailyTaskDone := doOncePerDay or (dailyTaskDone and not newDay)
plotchar(newDay, "newDay", "▼", location.top, transp = 60)
plotchar(doOncePerDay, "doOncePerDay", "•", location.top, transp = 0)
bgcolor(dailyTaskDone ? color.orange : na)
And for the OP, a v3 version:
//#version=3
study("Once per Day v3")
dailyTaskDone = false
newDay = change(time("D"))
doOncePerDay = rising(close, 2) // Your condition here.
dailyTaskDone := doOncePerDay or (dailyTaskDone[1] and not newDay)
plotchar(newDay, "newDay", "▼", location.top, transp = 60)
plotchar(doOncePerDay, "doOncePerDay", "•", location.top, transp = 0)
bgcolor(dailyTaskDone ? orange : na)

Related

Pine Script 5 - Unwanted alert messages

I receive unwanted alert messages. I would like to have only 1 "Go Long" alert when going long and then no other "Go Long" alerts until after the first "Go Short" alert. I'm having trouble getting this right.
//#version=5
strategy("Single Alert Strategy", overlay=true)
// Create flags to avoid multiple Long signals when already in Long and multiple Short signals when already in Short
isLong = false // We initialize a value and give it false (we are not in a Long position)
isLong := nz(isLong[1]) // We check the previous value and assign the previous value to this variable (when no previous value exist it will become false)
isShort = false // We initialize a value and give it false (we are not in a Short position)
isShort := nz(isShort[1]) // We check the previous value and assign the previous value to this variable (when no previous value exist it will become false)
// Long Short conditions
tot_rsi = ta.rsi(close, 14)
bullLevel = 30
bearLevel = 70
longCondition = ta.crossover(tot_rsi, bullLevel) and not isLong // Go Long only if we are not already Long
shortCondition = ta.crossunder(tot_rsi, bearLevel) and not isShort // Go Short only if we are not already Short
// Change the flags to avoid duplicate signals
if (longCondition)
isLong := true
isShort := false
if (shortCondition)
isLong := false
isShort := true
if longCondition
strategy.entry('Long', strategy.long, alert_message = "GoLong")
if shortCondition
strategy.entry('Short', strategy.short, alert_message = "GoShort")
// Plot the signals and compare them with the Alerts log
plotshape(series=longCondition, title="Long", text="Long", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(series=shortCondition, title="Short", text="Short", style=shape.triangledown, location=location.belowbar, color=color.red, size=size.small)
I followed the instructions in the answer provided here. While the signal indicators plot correctly (no additional signals), I do get an alert message when there was no signal plotted. This strategy is newly created with a new alert and is only added to 1 chart. The alert was created at 06:58, there were signals plotted before the alert was created but it triggered at 07:05 even though there was no signal plotted.
RSI level at 07:05 was 48.20
Any ideas what may have caused this alert to trigger and how to prevent additional alerts like these?
Link to screenshot
Edit: I'm testing an alternative approach. The unwanted alerts do not come frequently so I may have to run it for some time. If anyone knows of a different work around then I'm happy to give that a try.
//#version=5
strategy("Single Alert Strategy", overlay=true, calc_on_every_tick = true)
noOrder = strategy.closedtrades == 0 // There is no previous order
openLong = strategy.position_size > 0 // We are going Long
openShort = strategy.position_size < 0 // We are going Short
// Long Short conditions
tot_rsi = ta.rsi(close, 14)
bullLevel = 30
bearLevel = 70
longCondition = ta.crossover(tot_rsi, bullLevel) and (openShort[1] or noOrder) // Go Long only if the previous order was Short
shortCondition = ta.crossunder(tot_rsi, bearLevel) and (openLong[1] or noOrder) // Go Short only if the previous order was Long
if longCondition
strategy.entry('Long', strategy.long, alert_message = "GoLong")
if shortCondition
strategy.entry('Short', strategy.short, alert_message = "GoShort")
// Plot the signals and compare them with the Alerts log
plotshape(series=longCondition, title="Long", text="Long", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(series=shortCondition, title="Short", text="Short", style=shape.triangledown, location=location.belowbar, color=color.red, size=size.small)
Edit 2: The 2nd approach also created an alert despite there not being any signal plotted. Screenhot here
You should test also with strategy.opentrades which will return something !=0 if a trade (Long or Short) is currently open :
if longCondition and strategy.opentrades==0
strategy.close_all(comment="close", immediately=true)
strategy.entry('Long', strategy.long, alert_message = "GoLong")
if shortCondition and strategy.opentrades==0
strategy.close_all(comment="close", immediately=true)
strategy.entry('Short', strategy.short, alert_message = "GoShort")

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)

Pine script - using buy limit/sell limit is not firing at an exact price

I am trying to enter using a buy limit order at an exact price using pine script eg. 146.090 but even though the price has gone under and over it - it still does not execute.
I do not want to use close/high/low etc, just the exact price.
It would be greatly appreciated if somebody had a workaround for the issue.
Thx.
//#version=5
VERSION = "V1"
SCRIPT_NAME = "Test " + VERSION
InitCapital = 100000
InitPosition = 100.0
InitCommission = 0.025
InitPyramidMax = 1
CalcOnorderFills = false
ProcessOrdersOnClose = true
CalcOnEveryTick = true
CloseEntriesRule = "FIFO"
strategy(title=SCRIPT_NAME, shorttitle=SCRIPT_NAME, overlay=true, pyramiding=InitPyramidMax, initial_capital=InitCapital, default_qty_type=strategy.fixed, process_orders_on_close=ProcessOrdersOnClose, default_qty_value=InitPosition, commission_type=strategy.commission.percent, calc_on_order_fills=CalcOnorderFills, calc_on_every_tick=CalcOnEveryTick, precision=9, max_lines_count=500, max_labels_count=500, commission_value=InitCommission)
var float entry = 145.606
strategy.entry("Long", strategy.long, limit=entry)
Try to replace :
strategy.entry("Long", strategy.long, limit=entry)
By :
strategy.entry("Long", strategy.long, limit=entry, close=entry)

Buy and sell-markers on lower time frames when longer time frame shows uptrend

So, I'm trying to run a trading bot on medium timeframes (1h - 4h) using the KDJ-indicator. I know it's not the most responsive indicator but it is very reliable, at least on higher time frames (8h - 1D).
What I would like to be able to do is use the following script to send BUY/SELL-signals to my bot, BUT ONLY when the asset is not trending down on the 1D-chart. In other words, I would like to run this script:
//#version=4
study(title="KDJ IndicatorTV", shorttitle="KDJ_TV", format=format.price, precision=2, resolution="", overlay=true)
periodK = input(9, title="K", minval=1)
periodD = input(5, title="D", minval=1)
smoothK = input(3, title="Smooth", minval=1)
multiplierJ = input(3.5, title="Jx", minval=0.1)
k = ema(stoch(hlc3, high, low, periodK), smoothK)
d = ema(k, periodD)
j = multiplierJ * k-2 * d
makeShape1 = if (crossover(j,d) or crossover(j,99))
true
else
false
plotshape(series=makeShape1, style=shape.cross, color=#0094FF, transp=10, text="buy", title='buy')
makeShape2 = if (crossunder(j,d) or crossunder(j,99))
true
else
false
plotshape(series=makeShape2, style=shape.cross, color=#FF6A00, transp=10, text="sell", title='sell')
//end
And I would like to add a condition to makeShape1, something like "AND If j>d on 1D-chart", to ensure that buys are only generated while J is larger than D on the 1D-chart of that asset (ie: when the market for that asset is in an uptrend).
Any ideas on if/how I can achieve that?
Thanks!
-Daniel
You can access higher TFs with security() function
//#version=4
study(title="KDJ IndicatorTV", shorttitle="KDJ_TV", format=format.price, precision=2, resolution="", overlay=true)
periodK = input(9, title="K", minval=1)
periodD = input(5, title="D", minval=1)
smoothK = input(3, title="Smooth", minval=1)
multiplierJ = input(3.5, title="Jx", minval=0.1)
k = ema(stoch(hlc3, high, low, periodK), smoothK)
d = ema(k, periodD)
j = multiplierJ * k-2 * d
j_sec = security(syminfo.tickerid, "D", j) // 1 day time frame for j
d_sec = security(syminfo.tickerid, "D", d) // 1 day time frame for d
makeShape1 = if (crossover(j,d) or crossover(j,99)) and j_sec > d_sec
true
else
false
plotshape(series=makeShape1, style=shape.cross, color=#0094FF, transp=10, text="buy", title='buy')
makeShape2 = if (crossunder(j,d) or crossunder(j,99))
true
else
false
plotshape(series=makeShape2, style=shape.cross, color=#FF6A00, transp=10, text="sell", title='sell')
//end

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)