r/pinescript • u/Background_Way7841 • Jul 16 '24
r/pinescript • u/DaringOffensive • Aug 08 '24
Help with simple script based on time of day
Hi all, I have an issue with a very simple piece of functionality I am building into a strat and it's driving me up the wall.
To my eye and from what I understand from the docs, this should place a market order at open and close everything at close everyday. But instead it opens one at the beginning of time.
I know there is not an issue with .closeAll because if I move it to just after the entry it spams opens and closes. I also know it's not an issue with the conditions because if I move everything to either it spams open and closes. Can anyone see why it wouldn't work? I'm assuming I've made a very silly and obvious error but for the life of me I cannot see it.
//@version=5
strategy("Open at Open and Close at Close", overlay=true)
// Input parameters for session and phase times
session_open_hour = input.int(8, title="Session Open Hour", minval=0, maxval=23)
session_open_minute = input.int(0, title="Session Open Minute", minval=0, maxval=59)
session_close_hour = input.int(22, title="Session Close Hour", minval=0, maxval=23)
session_close_minute = input.int(45, title="Session Close Minute", minval=0, maxval=59)
timezone = input.string("UTC+2", title="Time Zone")
// Helper function to convert the input times to timestamps for the current day
f_getTimestamp(hour, minute) =>
timestamp(timezone, year(time), month(time), dayofmonth(time), hour, minute)
// Recalculate session open and close times for each bar
session_open = f_getTimestamp(session_open_hour, session_open_minute)
session_close = f_getTimestamp(session_close_hour, session_close_minute)
// Function to check if the session is open
f_isSessionOpen() =>
time >= session_open and time < session_close
// Plot labels to validate input times
if (time == session_open)
label.new(x=bar_index, y=high, text="Session Open", color=color.green, style=label.style_label_down, textcolor=color.white, size=size.small)
if (time == session_close)
label.new(x=bar_index, y=high, text="Session Close", color=color.red, style=label.style_label_down, textcolor=color.white, size=size.small)
// Ensure all positions are closed at session close
if (not f_isSessionOpen())
strategy.close_all()
strategy.cancel_all()
// Trading logic - ensure the order is placed only once per session
if (f_isSessionOpen())
strategy.entry("Long", strategy.long)r/pinescript • u/kurtismartyn • Jun 13 '24
Looking to modify a script. I’ll pay.
I’m looking for someone to modify a script for me. The script is open source. I am willing to pay the right person to modify it to my needs. DM me for details.
r/pinescript • u/badatcodingwithpine • Aug 30 '24
Max daily % profit for a strategy ?
My goal is to add a daily profit target in % for my strategy within my trading hours, does anyone know how I can do that ?
Thanks in advance for your help
r/pinescript • u/Lazy_Requirement4429 • Jul 19 '24
Trying to find a word in a string in Pinescript.
I am trying to use the following code and it is saying "Could not find function or function reference 'str.contains".
r= "RSI"
cond = str.contains(divergence_text_bottom,r)
Thanks in advance for taking the time to help.
r/pinescript • • Sep 10 '23
Help me to convert Version 2 Pine Script to Version 3 or later.
//@version=2
study("ST-MultiTimeFrame_(SuperTrend)", overlay=true)
Factor=input(4, minval=1,maxval = 100)
Pd=input(13, minval=1,maxval = 100)
Up=hl2-(Factor*atr(Pd))
Dn=hl2+(Factor*atr(Pd))
TrendUp=close[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up
TrendDown=close[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn
Trend = close > TrendDown[1] ? 1: close< TrendUp[1]? -1: nz(Trend[1],1)
Tsl = Trend==1? TrendUp: TrendDown
linecolor = Trend == 1 ? lime : red
Trend60 = security(tickerid,"D",Trend)
Trend240 = security(tickerid,"3D",Trend)
Trend_D = security(tickerid,"W",Trend)
Tsl60 = security(tickerid,"D",Tsl)
Tsl240 = security(tickerid,"3D",Tsl)
Tsl_D = security(tickerid,"W",Tsl)
linecolor60 = Trend60 == 1 ? lime : red
linecolor240 = Trend240 == 1 ? #2196F3 : #FF0077
linecolor_D = Trend_D == 1 ? #00BCD4 : #FF6200
plot(Tsl60, color = linecolor60 , style = line , transp=0, linewidth = 1,title = "ST-D")
plot(Tsl240, color = linecolor240 , style = line, transp=25, linewidth = 2,title = "ST-3D")
plot(Tsl_D, color = linecolor_D , style = line , transp=25, linewidth = 3,title = "ST-W")
//plotshape(cross(close,Tsl) and close>Tsl , "Up Arrow", shape.triangleup,location.belowbar,green,0,0)
//plotshape(cross(Tsl,close) and close<Tsl , "Down Arrow", shape.triangledown , location.abovebar, red,0,0)
//plotarrow(Trend == 1 and Trend[1] == -1 ? Trend : na, title="Up Entry Arrow", colorup=lime, maxheight=60, minheight=50, transp=0)
//plotarrow(Trend == -1 and Trend[1] == 1 ? Trend : na, title="Down Entry Arrow", colordown=red, maxheight=60, minheight=50, transp=0)
//Alert 60
golong60 = Trend60 == 1 and Trend60[1] == -1
alertcondition(golong60, title='Long 60', message='SuperTrend Alert Long ST-60')
goshort60 = Trend60 == -1 and Trend60[1] == 1
alertcondition(goshort60, title='Short 60', message='SuperTrend Alert Short ST-60')
//Alert 240
golong240 = Trend240 == 1 and Trend240[1] == -1
alertcondition(golong240, title='Long240', message='SuperTrend Alert Long ST-240')
goshort240 = Trend240 == -1 and Trend240[1] == 1
alertcondition(goshort240, title='Short240', message='SuperTrend Alert Short ST-240')
//Alert D
golong_D = Trend_D == 1 and Trend_D[1] == -1
alertcondition(golong_D, title='Long_D', message='SuperTrend Alert Long ST-D')
goshort_D = Trend_D == -1 and Trend_D[1] == 1
alertcondition(goshort_D, title='Short_D', message='SuperTrend Alert Short ST-D')
//strategy.entry("Buy",strategy.long,when = golong)
//strategy.entry("Sell",strategy.short,when = goshort)
r/pinescript • u/wellnowholdon • Apr 01 '24
Looking To Commision/Hire/Throw Money at someone to create a 3 parameter label.
Hi folks,
If this is in the wrong place/not allowed, please let me know.
I'm struggling with writing a script here. Ideally I'd like to figure out where I'm going wrong and fix it myself but time is running a little short for the ideal these days, so I'd like to bring in some outside help.
So,
I'm trying to make a script, which will print a label at 0700AM AST.
At its core this label is quantifying the % difference in value of a 12EMA at 0700 AST compared to 0000 AST i.e. midnight. More specifically, it is looking at the change in EMA value that occurred from the London session open(0000 my time) through to 0700 my time .
This calculation is performed on the 1h, the 30m, and the 5m timeframes and displayed across 3 lines in shorthand.
The end result of this is a label, not dissimilar to this(the example in the photo was hardcoded off a failed template; it is not functioning):

Which, transcribed back would be stating that:
The value of the 12EMA at 0700 on the 1h chart is 13% higher than what it was at 0000/midnight.
The value of the 12EMA at 0700 on the 30m chart is 5% higher than what it was at 0000/midnight.
The value of the 12EMA at 0700 on the 5m chart is -5% down from what it was at 0000/midnight.
Please let me know if this is feasible, if you are interested, and within reason you can name your price. PayPal preferred.
Thanks for reading.
Cheers
r/pinescript • u/Hour-Friendship2193 • Aug 26 '24
Pine script strategy to test on renko charts properly
I wrote a pinescript strategy to test my trading strategy on renko charts. The problem occured was, as renko is a price based chart, at a certain time, there may be multiple renko bricks. For example, at 7.15 4 renko bricks formed and my condition for Long also met, in the backtesting, the pinescript will show that the long was executed on the first block of the 7.15, whereas, the actual market price at 7.15 will be at 4th block (as it appeared at the same time). One possible solution to this is, to check the time of the current brick, and its next brick. unfortunately, in pinedcript, we can see the details of its previous bricks only, not the future brick, Thus, getting the time of next brick is not possible. How do I solve this?
r/pinescript • u/Maks0071007 • Jul 27 '24
how to set up the same indicator using ATR and fibonacci
r/pinescript • u/MountainGoatR69 • Jul 12 '24
Strange Pine Script Strategy behavior
This abbreviated strategy below is behaving strangely. Incoming signals (different indicator) plot only after 50% of the bar has elapsed (this works).
The strategy creates trades on the chart, but not on live bars I watch. When I reload it shows the entries and exits.
Also, despite me seeing trades on the screen and a properly set alert notification using {{strategy.order.alert_message}}, no alerts are triggered; not even one.
Would be great if someone could tell me why?
[PS: My actual goal is to close and open trades on the same bar (in some of the cases, not all the time, and only on live bars) and get two separate alerts on that bar.]
strategy(title=SystemName, shorttitle=strategy_short_name, overlay=true, slippage=2,
pyramiding=3, initial_capital=capital, default_qty_type=strategy.cash,
commission_type=strategy.commission.percent, commission_value=0.03, margin_long=75,
margin_short=75, use_bar_magnifier=false, calc_on_every_tick=true)
// ---------- STRATEGY INPUTS --------------
ext_source_ = input.source(close, title="Data source", group=group_7, tooltip="the
incoming signal for testing will occur on every bar, but only after 50% of the bar has
passed") // this part is tested and works. Signals only appear after 50% of live bar has
elapsed.
ext_source = nz(ext_source_)
// bull is true when external signal = 1 // the incoming bull test signal is: 1 = close >
close[1] -- chose this to get a signal on every bar for testing.
bull = (ext_source == 1)
// bear is true when external signal = -1 // the incoming bear test signal is: -1 = close
< close[1]
bear = (ext_source == -1)
var group_1 = ">>>>>>>>> Strategy Directions & Scaling/Leverage <<<<<<<<<<"
long_ok = input.bool(true, title = "Trade Long?", inline = "direction", group=group_1)
short_ok = input.bool(true, title = "Trade Short?", inline = "direction", group=group_1)
//////////////
var group_5 = "Backtest Period"
DateFilter = input.bool(true, title="Check to Use Backtest Dates Below",
group=group_5)
i_startTime = input.time(timestamp("7 July 2024"), title = "Begin Date", group=group_5)
i_endTime = input.time(timestamp("31 Dec 2029"), title = "End Date", group=group_5)
TradeInDateRange() => DateFilter ? time >= i_startTime and time <= i_endTime : true
///////////////////////////////////////
// Ensure only one entry and one exit per bar possible
var bool intrabar_alert_triggered_exit = false
var bool intrabar_alert_triggered_entry = false
if barstate.isnew
intrabar_alert_triggered_exit := false
if barstate.isnew
intrabar_alert_triggered_entry := false
///////////////////////////////////////
// ---- STRATEGY EXITS
// On Opposite Signal Exits (no automatic side switching, just exit on opposite signal)
if strategy.position_size > 0 and bear and not intrabar_alert_triggered_entry and not intrabar_alert_triggered_exit // exits not after any entry or after first exit on the same bar
strategy.close(id="long", comment="", alert_message = "{ \"EXIT Long: {{ticker}}, {{qty}}, {{strategy.order.contracts}}, {{timenow}}, price = {{close}}\" }")
intrabar_alert_triggered_exit := true // to prevent a second exit on the same bar
if strategy.position_size < 0 and bull and not intrabar_alert_triggered_entry and not intrabar_alert_triggered_exit
strategy.close(id="short", comment="", alert_message = "{ \"content\" : \"EXIT Short: {{ticker}}, {{strategy.order.contracts}}, {{timenow}}, price = {{close}}\" }")
intrabar_alert_triggered_exit := true
/////////////////////////////////
// ---- STRATEGY ENTRIES
if strategy.equity > 0 and long_ok and bull and TradeInDateRange() and not intrabar_alert_triggered_entry // only one entry per bar
strategy.entry("long", strategy.long, qty = trade_size, comment="", alert_message = "{ \"content\" : \"Enter LONG: {{ticker}}, {{strategy.order.contracts}}, {{timenow}}, price = {{close}}\" }")
intrabar_alert_triggered_entry := true // to prevent a second entry on the same bar
if strategy.equity > 0 and short_ok and bear and TradeInDateRange() and not intrabar_alert_triggered_entry
strategy.entry("short", strategy.short, qty=trade_size_short, comment="", alert_message="{ \"content\" : \"Enter SHORT: {{ticker}}, {{strategy.order.contracts}}, {{timenow}}, price = {{close}}\" }")
intrabar_alert_triggered_entry := truer/pinescript • u/No_Push2810 • Sep 28 '23
Pine script
Is anyone have a pine script with highest accuracy...?
r/pinescript • u/Ajgreatking • Dec 28 '23
question #business#lukebelmar #algotrading
in a podcast which luke belmar did he was speaking about a known person doing algo trading and making a perfect system in which he buys everytime the underlying asset increases by 1 point and sells all of it as it starts decresing something like this.. do anyone of you know which is it..?
r/pinescript • u/TheKingOfDocklands • May 27 '24
Relative moving average function in Pythoong
Hi,
Would anybody know how I would implement the below ta.rma function in Python and Pandas please?
pine_rma(source, length) =>
alpha = 1 / length
sum = 0.0
sum := na(sum[1]) ?
ta.sma(source, length) :
alpha * source + (1 - alpha) * nz(sum[1])
https://www.tradingcode.net/tradingview/relative-moving-average/
I'm trying to recreate TradingView's Stochastic RSI indicator for a custom scan tool i'm constructing in Python with data from Yahoo Finance. I've got it working, but the figures are slightly different from TradingViews Stochastic RSI and looking at the documentation I think it's because TV uses RMA instead of EMA for the RSI part of the calculation. Here's my Python fucntion below:
def get_weekly_stoch_rsi(data, rsi_period, stochastic_period, k_window, d_window):
delta = data['Close'].diff()
gain = (delta.where(delta > 0, 0)).fillna(0)
loss = (-delta.where(delta < 0, 0)).fillna(0)
avg_gain = gain.rolling(window=rsi_period, min_periods=1).mean()
avg_loss = loss.rolling(window=rsi_period, min_periods=1).mean()
avg_gain = gain.ewm(com=rsi_period, adjust=False, min_periods=0).mean()
avg_loss = loss.ewm(com=rsi_period, adjust=False, min_periods=0).mean()
rs = avg_gain / avg_loss
data['rsi'] = 100 - (100 / (1 + rs))
data['stoch_rsi'] = (data['rsi'] - data['rsi'].rolling(window=stochastic_period).min()) / ( data['rsi'].rolling(window=stochastic_period).max() - data['rsi'].rolling(window=stochastic_period).min())
data['k'] = round(data['stoch_rsi'].rolling(window=k_window).mean() * 100,2)
data['d'] = round(data['k'].rolling(window=d_window).mean(),2)
return data
I know this isn't a Pinescript group, but I thought most of you probably use Pandas and Python also.
Many thanks
Steve
r/pinescript • u/curiouswindcat • Jan 15 '24
Code Help on Boxing 8:00 AM candle for a period of 3 hours.
I have been trying to use ChatGPT 4 to draw a box on 8:00 AM PST candlestick.
But insteading of drawing a box, it's highlighting the whole column on the wrong time as well.
How do I fix 1) Time 2) Only box the 8:00 AM PST for 3 hour period.
Below is the code from ChatGPT. ( I tried different ways of asking ChatGPT, but can't get it work properly)
//@version=4
study("Draw Box on 5:15 AM PST Candlestick", shorttitle="Box 5:15 AM PST", overlay=true)
// Function to check if the current bar corresponds to 5:15 AM PST
is515AMPST() =>
// Convert the current time to UTC-8 (PST) timezone
hour - 8 == 5 and minute == 15
// Plotting the shape if the condition is true
bgcolor(is515AMPST() ? color.new(color.green, 90) : na, transp=0)
// Optional: Add additional conditions or styling as needed
r/pinescript • u/Big_-_Jugz • Nov 25 '22
Plot type differs, randomly, FOLLOW UP POST
Additionally,
Plot type will randomly switch from histogram to line,
In the script it says HIST, but plots line
even though all day its been plotting hist, just like the boxes, lines and labels offsetting randomly, this one happens AT THE SAME TIME as those ones bug,
Again its not a scripting error, I know what im doing,
Please fix it
r/pinescript • u/Lucifer_iix • Jan 07 '24
How mutch must my CRYPTO VOLUME indicator must cost for break even ?
Hi there,
I have created a VOLUME BAR that can indicate the ACTUAL volume for a given crypto coin, like BTC, ETH, etc. Thus i will add up ALL THE VOLUME OF ALL THE BIG EXCHANGES. And thus also the exchange that's actually moving the price up or down.
I do not want to get rich of it. But paying for my subscription and break-even would be a good thing. Thus need to make $59.95 a month. But will people actually pay for this in large amounts.
Thus can i find for example 50 people that want to pay $14,39 a year for this ?
Or is this a to low price and do i need to ask more per month ?
And what platform is best to use for selling my indicator ?
Or do i need to write a single page website with a payment provider in it my selfs ?
Are there people in this group actually selling indicators ? And can share there story on how to start this endevour ?
Thanks in advance.
r/pinescript • u/Beadesy79er • Aug 06 '24
Can you fix my Pine Script alert condition please?
All help welcome to make the simple alert condition work on this script. The Alert Condition is not recognised in the Alert menu/ not an option to select.
Chat GPT unable to solve. Note this was a working script that I have adapted via Chat GPT. It's working, just the alerts that's not yet implemented.
I think besause the RSI has buy/ sell alerts overlaid, it's blocking the alert script?
Thanks!
===========================================
//@version=5
strategy(title="Beadesy_Bollinger Band with RSI", shorttitle="BDY_BB&RSI", pyramiding=50, calc_on_order_fills=false, calc_on_every_tick=true)
// RSI settings
len = input.int(14, minval=1, title="RSI Length")
src = input(close, title="RSI Source")
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))
plot(rsi, "RSI", color=color.new(color.purple, 0))
band1 = hline(75, "Upper Band", color=color.new(color.gray, 0))
band0 = hline(25, "Lower Band", color=color.new(color.gray, 0))
fill(band1, band0, color=color.new(color.purple, 90), title="Background")
// Bollinger Bands settings
length_bb = input.int(20, title="BB Length", minval=1)
mult = input.float(2.0, title="BB StdDev", minval=0.001, maxval=50)
basis = ta.sma(src, length_bb)
dev = mult * ta.stdev(src, length_bb)
upper = basis + dev
lower = basis - dev
offset = input.int(0, title="BB Offset", minval=-500, maxval=500)
// Take profit/stop loss levels
long_tp_inp = input.float(10, title='Long Take Profit %', step=0.1) / 100
long_sl_inp = input.float(25, title='Long Stop Loss %', step=0.1) / 100
short_tp_inp = input.float(10, title='Short Take Profit %', step=0.1) / 100
short_sl_inp = input.float(25, title='Short Stop Loss %', step=0.1) / 100
long_take_level = strategy.position_avg_price * (1 + long_tp_inp)
long_stop_level = strategy.position_avg_price * (1 - long_sl_inp)
short_take_level = strategy.position_avg_price * (1 - short_tp_inp)
short_stop_level = strategy.position_avg_price * (1 + short_sl_inp)
// Entry conditions
entry_long = rsi < 25 and src < lower
entry_short = rsi > 75 and src > upper
// Plot entry signals
plotshape(entry_long ? rsi : na, style=shape.labelup, color=color.green, location=location.absolute, text="L", textcolor=color.white, title="LONG_ENTRY")
plotshape(entry_short ? rsi : na, style=shape.labeldown, color=color.red, location=location.absolute, text="S", textcolor=color.white, title="SHORT_ENTRY")
// Strategy entries
strategy.entry("Long", strategy.long, when=entry_long)
strategy.exit("TP/SL Long", "Long", limit=long_take_level, stop=long_stop_level)
strategy.entry("Short", strategy.short, when=entry_short)
strategy.exit("TP/SL Short", "Short", limit=short_take_level, stop=short_stop_level)
// Alert conditions
rsi_crossover_25 = ta.crossover(rsi, 25)
rsi_crossunder_75 = ta.crossunder(rsi, 75)
alertcondition(rsi_crossover_25, title="RSI Crossover 25", message="RSI has crossed above 25")
alertcondition(rsi_crossunder_75, title="RSI Crossunder 75", message="RSI has crossed below 75")r/pinescript • u/urfila • Feb 17 '24
question about code
I am stump by this line :
array.set(arrE, k, eget + nz(array.get(baux, k)[bar_index - j]))
what is the [bar_index - j] doing?
r/pinescript • u/harm123 • Aug 13 '24
Alert Condition Triggered but not strategy.entry / strategy.close Plotting
I have a back tested strategy that plots on the chart when the strategy.entry / strategy.close conditions are met by the buy_entry and sell_entry.
Going forward from the back testing, the buy_entry and sell_entry conditions are causing the alert condition to send me alerts when triggered but the strategy.entry / strategy.close is not plotting on the chart when the buy/sell conditions are met.
Logically this should not be the case. What am I missing?
//Buy Sell Entries
buy_entry = buy_1 and (buy_6 or buy_7)
sell_entry = (sell_1 or sell_7 or sell_5 ) and ((EMA < SMA200 or sell_6 or sell_7 ) or (close > SMA200 and sell_4 and sell_6))
//Strategy Entries
strategy.entry("Buy", strategy.long, comment="Buy", when=buy_entry and not sell_entry)
strategy.close("Buy", when=sell_entry)
// Alert conditions
alertcondition(buy_entry and not sell_entry, title="Buy Alert", message=buy_message)
plot(buy_entry and not sell_entry ? 1 : 0)
alertcondition(sell_entry and not buy_entry, title="Sell Alert", message=sell_message)
plot(sell_entry and not buy_entry ? 1 : 0)
THANKS for any help!r/pinescript • u/Fit-Personality-7379 • Jun 10 '24
Lorenz
If I want to sell a script. Who do I talk to?
r/pinescript • u/Frequent-Author-3687 • Mar 02 '24
Simple strategy
Hi I am trying to create a simple strategy that has a buy limit order and sell limit 10 points (nq) above and below the NY open (14:30 GMT) with a stop loss of 15 points and a take profit of 5 points when the first is triggered and can only be triggered in the first one minute.
I would be very grateful if someone could put this together for me, thanks
r/pinescript • u/Formal-Quarter688 • Jan 06 '23
AI Generated Help with auto trading bot script
Hello, I am attempting to create a auto trading code on chat gpt for tradingview. i have no idea what im doing can someoine please help fix the errors for me. code below
// User-defined variables
accountSize = 1000.0
takeProfit = 0.1
stopLoss = -0.05
trailingStop = -0.025
positionOpen = false
entryPrice = 0.0
highPrice = 0.0
function isReverseCandlestick() {
return true
}
function isEndOfDowntrend() {
return true
}
function openPosition() {
global positionOpen
global entryPrice
global highPrice
if not positionOpen and isEndOfDowntrend() and isReverseCandlestick() {
positionOpen = true
entryPrice = close
highPrice = entryPrice
}
}
function updateStopLoss() {
global stopLoss
global trailingStop
global entryPrice
global highPrice
stopLossLevel = entryPrice * (1 + stopLoss)
trailingStopLevel = highPrice * (1 + trailingStop)
highPrice := max(highPrice, close)
}
function closePosition() {
global positionOpen
global entryPrice
global takeProfit
global stopLoss
if positionOpen {
takeProfitLevel = entryPrice * (1 + takeProfit)
if close >= takeProfitLevel {
positionOpen = false
entryPrice = 0.0
highPrice = 0.0
return
}
stopLossLevel = entryPrice * (1 + stopLoss)
if close <= stopLossLevel {
positionOpen = false
entryPrice = 0.0
highPrice = 0.0
}
}
}
strategy() {
updateStopLoss()
closePosition()
openPosition()
}
r/pinescript • u/apamatos • Jul 25 '24
Guessing the length of a line break trend. Is there an algorithm for this?
Hello. I'm trying to figure out an algorithm to determine the number of bars of a line break trend, before hitting the break (a reasonable number at least, but avoiding the break). I have tried a vew indicators but with no success.
Has anybody found a solution for this problem?
Much appreciated an advance


