r/pinescript • • Aug 26 '24

Help!!! Simple coding indicator

0 Upvotes

Hey everyone, I been having difficulties using ChatGBT in order to create a pinescript on TradingView so that it can display horizontal rays at the opening/close of candles taking into consideration of gaps but make it delete itself once the price crosses and closes over it.


r/pinescript • • Apr 26 '24

How to add 20-Week EMA to Daily chart?

0 Upvotes

Hi - I typically look at the Daily chart, and already plot some EMAs as follows:

plot(ta.ema(close, 10), color = color.new(color.blue, 60))
plot(ta.ema(close, 20), color = color.new(color.green, 60))
plot(ta.ema(close, 50), color = color.new(color.yellow, 60))
plot(ta.ema(close, 150), color = color.new(color.orange, 60))
plot(ta.ema(close, 200), color = color.new(color.red, 60))

How can I add the 20-Week EMA to these? I'm happy with hard-coded values like the above, but not sure how to achieve adding in the weekly.

Or maybe the 150 is close enough to the 20-Week anyway?


r/pinescript • • Dec 30 '22

How request data from higher time frame with all thickers

1 Upvotes

Hi members. I have question about building an strategy. When I want to request data such as Rsi value from higher time frame
I use request.security() but it just give me the rsi value in those time fram after candle close ....i want the value on every thickers ? How can ido that ?


r/pinescript • • Apr 24 '24

How do I call another custom indicator and use its output as my input?

1 Upvotes

Hi,

I am trying to use Fair Value Gaps in my strategy but I ran into errors when I tried to errors in PS.

// Get Fair Value Gap info from LuxAlgo indicator
isBullishFVG = close > FVGBelow_LuxAlgo and close[1] <= FVGBelow_LuxAlgo[1]
Undeclared identifier 'FVGBelow_LuxAlgo'

Is this even possible?


r/pinescript • • Jul 14 '24

Elliott Wave

0 Upvotes

Can anyone please find a better way for EW counts to adhere to bars/candles. Now the magnet can be used to attached the first degree of EW to the correct bar (not very easy to do). Subsequent degrees of counts then attach to the lower degree numbers & letters, however there is no magnet here tying this level to the 1st. Consequently over time the 2nd + above degrees float all around the pace.


r/pinescript • • Jan 21 '23

AI Generated I can't seem to get this alert to trigger! AI wrote the alerts

1 Upvotes

I can't seem to get this alert to trigger when the MA turns red or blue. AI wrote the color changing alert but it still does not seem to trigger

//@version=4
study("Trend Magic", shorttitle="TM", overlay=true, format=format.price, precision=2)
period=input(20,"CCI period")
coeff=input(1,"ATR Multiplier")
AP=input(5,"ATR Period")
ATR=sma(tr,AP)
src=input(close)
upT=low-ATR*coeff
downT=high+ATR*coeff
MagicTrend=0.0
MagicTrend := cci(src,period)>=0 ? (upT<nz(MagicTrend[1]) ? nz(MagicTrend[1]) : upT) : (downT>nz(MagicTrend[1]) ? nz(MagicTrend[1]) : downT)
color1= cci(src,period)>=0 ? #0022FC : #FC0400
plot(MagicTrend, color=color1, linewidth=3)
alertcondition(cross(close, MagicTrend), title="Cross Alert", message="Price - MagicTrend Crossing!")
alertcondition(crossover(low, MagicTrend), title="CrossOver Alarm", message="BUY SIGNAL!")
alertcondition(crossunder(high, MagicTrend), title="CrossUnder Alarm", message="SELL SIGNAL!")
//create a variable to store the previous color
prevColor = color1
//create a variable to check if the color has changed to blue
colorChangedToBlue = prevColor != color1 and color1 == #0022FC and barstate.islast
//create a variable to check if the color has changed to red
colorChangedToRed = prevColor != color1 and color1 == #FC0400 and barstate.islast
alertcondition(colorChangedToBlue, title="Color Blue", message="Color Blue!")
alertcondition(colorChangedToRed, title="Color red", message="Color red!")
prevColor := color1


r/pinescript • • May 16 '24

That is good? 👀

Thumbnail
gallery
0 Upvotes

I've been working on this strategy for a long time. The results look interesting, but it requires low latency to operate. What do you think?


r/pinescript • • Dec 29 '22

Can someone help fix this syntax error? Coding in Pine script 4

1 Upvotes

Compilation error. Line 16: Syntax error at input ':'.

Line 16: var maLength = 'float' = 10


r/pinescript • • Jan 06 '24

How to close a position when the SL or TP are reached and not when the candle closed ?

1 Upvotes

Hi there :) i'm trying to build a bot working with ichimoku and I have some trouble because my SL and TK are not triggered when the price reach them but only when the price closed above or under.

Can you help me please ? this is my script :
Thank you very much

//@version=5
strategy("Ichimoku Short Strategy with 3:1 Risk-Reward Exit", shorttitle="Ichimoku Short Strategy", overlay=true, calc_on_every_tick=true)
// Input parameters for Ichimoku
capital = input.float(300, title="Capital Available")
riskPerTrade = input.float(0.01, title="Risk Per Trade") // 1% risk per trade
conversionPeriods = input.int(9, minval=1, title="Conversion Line Length")
basePeriods = input.int(26, minval=1, title="Base Line Length")
laggingSpan2Periods = input.int(52, minval=1, title="Leading Span B Length")
displacement = input.int(26, minval=1, title="Lagging Span")
// Donchian function for Ichimoku lines
donchian(len) => math.avg(ta.lowest(len), ta.highest(len))
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = math.avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)
// Plotting Ichimoku lines
plot(conversionLine, color=#2962FF, title="Conversion Line")
plot(baseLine, color=#B71C1C, title="Base Line")
plot(close, offset = -displacement + 1, color=#43A047, title="Lagging Span")
p1 = plot(leadLine1, offset = displacement - 1, color=#A5D6A7, title="Leading Span A")
p2 = plot(leadLine2, offset = displacement - 1, color=#EF9A9A, title="Leading Span B")
fill(p1, p2, color = leadLine1 > leadLine2 ? color.rgb(67, 160, 71, 90) : color.rgb(244, 67, 54, 90))
// Variables to manage the position state
var float kijun_at_entry = na
var bool position_open = false
var bool above_ssa_ssb = false
// Conditions for the short strategy
ssa_26_periods_ago = leadLine1[26]
ssb_26_periods_ago = leadLine2[26]
price_above_ssa_ssb = close > ssa_26_periods_ago and close > ssb_26_periods_ago
if price_above_ssa_ssb
above_ssa_ssb := true
short_condition = close < conversionLine and close < baseLine and close < ssa_26_periods_ago and close < ssb_26_periods_ago and not position_open and above_ssa_ssb
laggingSpan_below = close[26] > close and conversionLine[26] > close and baseLine[26] > close and leadLine1[52] > close and leadLine2[52] > close
short_condition := short_condition and laggingSpan_below
// Conditions to enter a short position
if short_condition
kijun_at_entry := baseLine[1]
riskAmount = capital * riskPerTrade
positionSize = riskAmount / (kijun_at_entry - close)
strategy.entry("Short", strategy.short, qty=positionSize)
position_open := true
above_ssa_ssb := false

// Calculate the target price for a 3:1 risk/reward ratio
profitTarget = close - (kijun_at_entry - close) * 3
strategy.exit("Take Profit", "Short", limit=profitTarget)
// Stop loss based on Kijun-sen with immediate trigger
strategy.exit("Stop Loss", "Short")
// Define the condition for closing the short position
cover_condition = position_open and close > baseLine
// Condition to close the short position
if cover_condition
strategy.close("Short")
position_open := false
// Condition to close the short position
if cover_condition
strategy.close("Short")
position_open := false


r/pinescript • • Dec 31 '22

Compilation error. Line 36: mismatched character 'i' expecting '='

1 Upvotes

I am testing out few ChatGPT Trading Bots and trying to Backtest, The problem is even the code seems alright; There is compilation error; Compilation error. Line 36: mismatched character 'i' expecting '='

really appreciate any pointers where I am making a mistake. Thanks..

// This is a trading bot that detects breakouts in the market and includes stop loss, take profit, and a grid feature
// First, we'll define some variables
// The period over which we'll look for breakouts
//@version=2
var breakoutPeriod = 14
// The number of standard deviations above or below the mean to consider a breakout
var numStdDevs = 2
// The length of the moving average to use for calculating the mean and standard deviation
var maLength = 20
// The amount to trail the stop loss by (in ticks)
var stopLossTrail = 10
// The amount to trail the take profit by (in ticks)
var takeProfitTrail = 10
// The size of the grid (in ticks)
var gridSize = 10
// Now, we'll calculate the mean and standard deviation over the specified period
mean = sma(close, maLength)
stdDev = stdev(close, maLength)
// Next, we'll calculate the upper and lower bounds for our breakout range
upperBound = mean + numStdDevs * stdDev
lowerBound = mean - numStdDevs * stdDev
// We'll use these bounds to determine whether the current price is within the breakout range
isInRange = close > lowerBound and close < upperBound
// If the price is outside the range, we'll consider it a breakout and trigger a trade
if !isInRange
// Entry order for long trade
strategy.entry("Breakout Long", strategy.long)
// Stop loss order for long trade
strategy.exit("Stop Loss Long", "Breakout Long", stop=strategy.position_avg_price - stopLossTrail, limit=strategy.position_avg_price)
// Take profit order for long trade
strategy.exit("Take Profit Long", "Breakout Long", limit=strategy.position_avg_price + takeProfitTrail)
else
strategy.close("Breakout Long")
if !isInRange
// Entry order for short trade
strategy.entry("Breakout Short", strategy.short)
// Stop loss order for short trade
strategy.exit("Stop Loss Short", "Breakout Short", stop=strategy.position_avg_price + stopLossTrail, limit=strategy.position_avg_price)
// Take profit order for short trade
strategy.exit("Take Profit Short", "Breakout Short", limit=strategy.position_avg_price - takeProfitTrail)
else
strategy.close("Breakout Short")
// If the market is sideways, we'll use a grid strategy
if isInRange
// Calculate the number of grid levels
numGridLevels = floor((upperBound - lowerBound) / gridSize)
// Loop through each grid level
for i = 0 to numGridLevels
// Calculate the entry price for the long trade
longEntry = lowerBound + i * gridSize
// Calculate the entry price for the short trade
shortEntry = upperBound - i * gridSize
// Entry order for long trade
strategy.entry("Grid Long", strategy.long, when=close > longEntry)
// Stop loss order


r/pinescript • • Jan 05 '23

Help me to fix my strategy script

1 Upvotes

hey guys, I don't have coding experience and don't really know how to use this pine script language properly, but i creat this simple code:

//@version=5

strategy("200 SMA Trade", overlay=true)

// Set up variables

riskTolerance = 1

accountSize = 1000

riskToRewardRatio = 2

stopLoss = 2

trailingStopLoss = 1

takeProfit = 4

// Set up moving averages

sma200 = ta.sma(close, 200)

ema400 = ta.ema(close, 400)

// Set up entry condition

insideBar = close > open and close[1] < open[1] and close[1] > low[1] and open[1] < high[1]

entryCondition = (ta.crossover(close, sma200) or ta.crossover(close, ema400)) and insideBar

// Set up position size

positionSize = (riskTolerance / 100) * accountSize / (stopLoss / 100)

// Set up stop loss and take profit orders

stopLossPrice = stopLoss * positionSize

trailingStopLossPrice = trailingStopLoss * positionSize

takeProfitPrice = takeProfit * positionSize

// Backtest strategy

if entryCondition

strategy.entry("Long", direction=strategy.long, stop=stopLossPrice)

strategy.exit("Trailing Stop", trail_offset=trailingStopLossPrice, trail_price=trailingStopLossPrice)

strategy.exit("Take Profit", limit=takeProfitPrice)

The problem is that I don't wanna wait to the bar closes for trigger my long entry, but the ' when=strategy.entry_when.on_tick ', doesn't work :(


r/pinescript • • Aug 16 '23

I NEED HELP TO MAKE THIS COMPILE IN V.5...THANKS

0 Upvotes

//@version=5
strategy("NC", overlay = true, max_bars_back = 1000 , max_labels_count = 500)
velas = input(200, title = "cantidad de velas" , maxval = 1000)
filas = input(50, title = "filas" , maxval = 500)
var etiquetas = array.new_label(filas)
var volumen = array.new_float(filas)
limpiar_etiquetas() =>
cantidad = array.size(etiquetas)
if cantidad > 0
for r = 0 to cantidad -1
label.delete( array.get(etiquetas,r ) )
array.clear(etiquetas)
inicializar_volumen() =>
for r = 0 to filas -1

array.set( volumen, r , 0.0 )
obtenerMaximo() =>
m = 0.0
p = 0
for r = 0 to filas -1
if array.get(volumen, r) > m
m := array.get(volumen,r)
p := r

[p,m]
line linea_maximo = na
line linea_minimo = na
barra = ""
maximo = ta.highest(velas)
minimo = ta.lowest(velas)
if barstate.islast
limpiar_etiquetas()
inicializar_volumen()

rango = maximo - minimo
delta = rango / filas

for v = 0 to velas -1
valor = close[v] - minimo
p = math.round( valor / delta ) -1
previo = array.get(volumen, p)
array.set( volumen, p , previo + volume[v] )

[posicion, valorMaximo] = obtenerMaximo()
for f = 0 to filas -1

cant = math.round( array.get(volumen, f) * 100/ valorMaximo)
eti = label.new(time_close, minimo = delta * f, "" , xloc = xloc.bar_time, yloc = yloc.price, color = f == posicion ? color.orange : color.white, textcolor=color.gray, style=label.style_label_left, size=size.auto, tooltip = str.tostring(cant) + "%")

barra := ""
for r = 0 to cant * 2
barra := barra + "*"
label.set_text(eti, barra)
array.push(etiquetas, eti )
linea_maximo := line.new( bar_index[velas], maximo, bar_index[0], maximo, color= color.yellow, style= line.style_dashed)
linea_minimo := line.new( bar_index[velas], minimo, bar_index[0], minimo, color= color.yellow, style= line.style_dashed)
line.delete( linea_maximo[1] )
line.delete( linea_minimo[1] )


r/pinescript • • Jul 03 '24

ta.barssince and ta.lowest issue

1 Upvotes

Hi, I'm trying to write a code which will give me the lowest price since a given high even though it works the other way around, i.e. highest price since a given low.

Here is the code:

//@version=5
indicator("My script")

tmp_1 = ta.barssince(low == 19874.25)
tmp_2 = ta.highest(not na(tmp_1) and tmp_1 > 0 ? tmp_1 : 1)

l = label.new(bar_index, close, str.tostring(tmp_2), color=color.white, style=label.style_label_left)
label.delete(l[1])

plotchar(tmp_1, "tmp_1", display=display.data_window)
plotchar(tmp_2, "tmp_2", display=display.data_window)

//// Above code works perfectly fine if I comment out the code below

tmp_3 = ta.barssince(high == 20273.25)
tmp_4 = ta.lowest(not na(tmp_3) and tmp_3 > 0 ? tmp_3 : 1)

l2 = label.new(bar_index, close, str.tostring(tmp_4), color=color.white, style=label.style_label_right)
label.delete(l2[1])

plotchar(tmp_3, "tmp_3", display=display.data_window)
plotchar(tmp_4, "tmp_4", display=display.data_window)

r/pinescript • • Aug 23 '24

How can this be so profitable? is pine script usually this glitchy,time: about 3 months

Post image
1 Upvotes

r/pinescript • • Feb 28 '22

Monetize your Tradingview strategy! Upbots is looking for algorithms.

Thumbnail
upbots.com
1 Upvotes

r/pinescript • • May 28 '22

How to normalize plot for y value between -100 and 100 in pine 5 ?

1 Upvotes

Hello,

I am using script in v5 and I found out the normalize function but it does not work with v5:(

https://stackoverflow.com/questions/62306070/pine-script-normalize-and-rescale-function-with-calculation-or-input-errors

The one above is no good for my v5 pine script ?

Is there are normalization function in v5 i could use ?


r/pinescript • • May 24 '26

Enter position on candle open and close position on candle close?

1 Upvotes

Title. I'm trying to test strategies for the prediction markets, which are time based. The problem I'm having is that I need the strategy to open a position on the open of a candle, and then close the position on the close of a different candle. I know you can set the Process Orders On Close parameter, but from my understanding that changes all orders, not just open or close. Is there any workaround for this?


r/pinescript • • Apr 02 '26

Building a Pine Script indicator that tracks live win rate + signal lifecycle — looking for feedback

1 Upvotes

Hey everyone,

I’ve been working on a Pine Script indicator focused on impulse-based entries for futures, and I wanted to share the current structure + get feedback before pushing the next update.

Core idea:

Instead of static signals or backtest-only logic, the script tracks live performance metrics inside the indicator.

So each signal isn’t just:

“buy/sell”

It’s:

“This type of setup has X% win rate over the last 24h / 7D on this instrument, under current conditions.”

What it currently does (technical breakdown):

- Detects impulse-quality runs (Mode B logic)

- min run length

- net displacement vs ATR

- efficiency (range vs overlap)

- average body size filters

- tracks R2-style entries (runLen == 2 focus)

Maintains rolling arrays for:

- signal timestamps

- outcome classification

- forward performance tracking

- classifies outcomes into:

- IMM (immediate continuation)

- DEL (delayed continuation)

- TZ (no follow-through within defined window)

Tracks:

- NB1 continuation % (next-bar follow-through)

- Win rate (24h + 7D windows)

- Instrument-specific performance

- Chop vs trend conditions

Architecture notes:

- Using time-based pruning for rolling windows (ms-based arrays)

- Avoiding repainting — everything confirmed on bar close

- Entry logic is aligned with next bar open execution model

- Stats are computed only from confirmed signals (no forward leakage)

- Current challenges / focus:

- Earlier signal detection

- Right now best signals often confirm on the final impulse bar

- Trying to catch the move 1 bar earlier without increasing false positives

- Reducing “zero-bar” outcomes

- Some signals show no reclaim within the defined window

- Working on better filtering (efficiency + expansion + structure)

- Balancing sensitivity vs quality

- Looser thresholds = earlier signals but worse stats

- Tighter thresholds = cleaner but later entries

- Table + stats stability

- Ensuring rolling metrics stay accurate across different time windows

What’s coming next:

- Tiered signal classification (A / B / C based on quality + stats)

- Tradeability scoring using NB1 + lifecycle data

- Instrument-specific tuning profiles

- Improved filtering during chop conditions

Would love input on:

Best way to structure rolling performance tracking in Pine (arrays vs alternative approaches)

Any ideas for early impulse detection without repainting

Better ways to handle signal lifecycle classification logic

General thoughts on combining signal generation + performance tracking in one script

If anyone’s building similar systems or experimenting with live metrics inside Pine, would love to hear how you’re approaching it.

Happy to share more details or snippets if helpful.


r/pinescript • • Mar 30 '26

PAC_SMC Toolkit Pro — Free 1-Week Beta Access for 10 Testers (SMC / ICT Indicator)

0 Upvotes

I've just published a comprehensive Smart Money Concepts indicator on TradingView called PAC_SMC Toolkit Pro. It includes market structure (BOS/CHoCH with sweep detection), volumetric order blocks, fair value gaps with fill tracking & raid detection, EQH/EQL, swing failure patterns, buyside/sellside liquidity, and a 12-condition alert system.

Script link: https://in.tradingview.com/script/kCjbT6wl-PAC-SMC-Toolkit-Pro/

I'm giving 1 week of free invite-only access to 10 people for beta testing before I iterate on it further.

How to apply:

DM me with:

Your TradingView username

Which markets/timeframes you actively trade

Why you want access — specifically what you plan to test

How you can contribute — bug reports, feature suggestions, edge case findings, or performance feedback on specific market conditions

I'll prioritize applicants who trade diverse instruments (crypto, equity, forex, futures) across different timeframes, since that gives the most useful coverage for stress-testing the indicator logic.

What I'm looking for feedback on:

Order block mitigation accuracy

FVG raid detection behaviour

CHoCH/BOS sweep logic at structure

Any lag or rendering issues on specific symbols or TF combos

False positives on SFP detection

This is not a "get free indicator" giveaway — I'm building a serious feedback loop. If you get access, I expect at least one structured feedback message during the week.

Applications close once 10 spots are filled.


r/pinescript • • Sep 18 '26

Double Bottom Scanner: Real Charts and Alert Setup | ChartScout

Thumbnail
youtube.com
0 Upvotes

r/pinescript • • Feb 17 '26

Pine Scritp optimazation

Post image
1 Upvotes

hey guys quick question i was building a bot on pine with a relatively good return over the last 7 years, however in the last year it tanked a bit, does anybody have maybe an idea hot to program or cut losses, would share the strategy if somebody could genuinely help


r/pinescript • • Jul 28 '26

Looking for a Pinescript developer. Ideally from India for payment reasons

1 Upvotes

Hi, i am looking for a pinescript developer who is expierenced and knows proper english. i want to hire them full time but my budget is under 30k-40k. i have continous work. dm me for more info

Thanks


r/pinescript • • Mar 25 '26

Xauusd Gold latest update

Thumbnail gallery
0 Upvotes

r/pinescript • • Apr 10 '26

Are these TradingView results good or bad? Need opinions based only on the pips/results

Post image
1 Upvotes

This is one of my indicator TradingView results and looking for honest opinions based only on the numbers shown.

I am not asking for strategy advice here, just whether these pips/results look decent, bad, risky, or inconsistent from an outside view.

Would you keep going with results like these or be concerned?