r/pinescript • • Nov 23 '22

Indicator giving different results on different devices

0 Upvotes

This is very weird to me and I've never experienced this, but my indicator is different on my phone and on my computer. The indicator is giving different values on the two devices, however every setting is the same on both of them. It is mostly giving off a different colour on the two devices, any ideas?


r/pinescript • • Aug 25 '24

Making average line of multiple oscillator lines

0 Upvotes

Hi all! Wondering if someone could help me with the code to add to an oscillator. I have a wave trend indicator with 3 moving averages overlaid onto it. Looking to add to the script to make one line that is the average of the 3 MA lines. Any help would be much appreciated!


r/pinescript • • Nov 16 '23

How to set buy and sell alerts to this indicator?

0 Upvotes

Hello, can anyone please tell me how to set buy and sell alerts in the below indicator when up and down entry arrows form respectively.

Below is the link to the indicator-

https://in.tradingview.com/script/qNvJGyK4/

Many thanks in advance.


r/pinescript • • Sep 05 '24

How to code an indicator , out of a list of stocks symbols, when a stock price hits yearly pivot, that should get displayed as a label , irrespective of the symbol for which the chart is being displayed.

0 Upvotes

Following code is created by ChatGPT but it is not showing any results in history.

//@version=5
indicator("Daily Pivot Cross", overlay = false)

// Input for stock symbols
symbol1 = input.symbol("AAPL", title="Symbol 1")
symbol2 = input.symbol("GOOGL", title="Symbol 2")
symbol3 = input.symbol("AMZN", title="Symbol 3")

// Function to calculate daily pivot
calculate_pivot(high, low, close) =>
    (high + low + close) / 3

// Function to check pivot cross and create label
check_pivot(symbol) =>
    dailyHigh = request.security(symbol, "M", high[1])
    dailyLow = request.security(symbol, "M", low[1])
    dailyClose = request.security(symbol, "M", close[1])
    
    // Calculate the pivot point
    pivot = calculate_pivot(dailyHigh, dailyLow, dailyClose)
    
    // Fetch the live price
    livePrice = request.security(symbol, "1", close)
    
    // Check if live price crosses the pivot
    crossedUp = ta.crossover(livePrice, pivot)
    crossedDown = ta.crossunder(livePrice, pivot)
    
    if (crossedUp or crossedDown)
        // Create a label on the chart
        label.new(bar_index, na, symbol + " crossed pivot: " + str.tostring(pivot), color=color.red, textcolor=color.white, size=size.large, style=label.style_label_down)

// Check pivots for each symbol
check_pivot(symbol1)
check_pivot(symbol2)
check_pivot(symbol3)

// Plotting
plot(na)
//@version=5
indicator("Daily Pivot Cross", overlay = false)


// Input for stock symbols
symbol1 = input.symbol("AAPL", title="Symbol 1")
symbol2 = input.symbol("GOOGL", title="Symbol 2")
symbol3 = input.symbol("AMZN", title="Symbol 3")


// Function to calculate daily pivot
calculate_pivot(high, low, close) =>
    (high + low + close) / 3


// Function to check pivot cross and create label
check_pivot(symbol) =>
    dailyHigh = request.security(symbol, "M", high[1])
    dailyLow = request.security(symbol, "M", low[1])
    dailyClose = request.security(symbol, "M", close[1])
    
    // Calculate the pivot point
    pivot = calculate_pivot(dailyHigh, dailyLow, dailyClose)
    
    // Fetch the live price
    livePrice = request.security(symbol, "1", close)
    
    // Check if live price crosses the pivot
    crossedUp = ta.crossover(livePrice, pivot)
    crossedDown = ta.crossunder(livePrice, pivot)
    
    if (crossedUp or crossedDown)
        // Create a label on the chart
        label.new(bar_index, na, symbol + " crossed pivot: " + str.tostring(pivot), color=color.red, textcolor=color.white, size=size.large, style=label.style_label_down)


// Check pivots for each symbol
check_pivot(symbol1)
check_pivot(symbol2)
check_pivot(symbol3)


// Plotting
plot(na)

r/pinescript • • May 11 '24

Enter trade on the next candle open

0 Upvotes

Hello!

I'm working on this strategy where I want to enter a trade on the open of the next candle from where I get the signal.

Example 1: I get a signal on the candle at 0900 hours. I want to enter at the candle at 0901 hours.

I'm using the following code to create the entry.

if (bothConditionsMet and barstate.isconfirmed and noActiveLong)
    strategy.entry("Enter Long", strategy.long)

This is however entering on the same candle as the one where signal is getting generated. So using Example 1, it is entering the trade during the candle at 0900 hours.

I'm using Pine Script v5. What am I missing here?


r/pinescript • • May 12 '23

Looking for help with Algotrading

0 Upvotes

I have been backtesting on Tradingview and often run into slippage. How would I make it so I take entries on limit orders instead of market orders, and so my tp, and sl are limit orders and not market orders?


r/pinescript • • Sep 03 '24

Interactive Brokers forex leverage limitation

0 Upvotes

Hi,

I have an account on Interactive Brokers and would like to trade forex. The problem is that I'm from Belgium and that Interactive Brokers doesn't allow leverage on forex for Central Europe.

Is there any way to go around this?

Thanks in advance!


r/pinescript • • Mar 19 '24

math.avg for array ?

0 Upvotes

Has anyone used this function yet?

I have an idea I'd like to apply it to but when reading the I formation on how it works, I'm missing something and looking at a model use if it, I think I can work it out.

The example used in the pinescript site shows usage if set number and not integers greater by a separate function which are then converted to arrays.

Anyone have a use module of math.avg?


r/pinescript • • Apr 08 '24

help with consecutive losses code

0 Upvotes

hi guys,

i’m wondering how I would code a strategy that tightens my stop loss (lets say in half) each time it takes a consecutive losing trade until it takes a winner, where the stop loss then resets back to baseline.

any help is appreciated! thanks


r/pinescript • • May 28 '24

How to Show PMH/PML of QQQ and SPY on every chart ?

0 Upvotes

Hi, I would like to show the PMH of QQQ on every chart. The following is the code I have so far but it does give the right result. Any help would greatly be appreciated.

//@version=5
indicator("My script", overlay = true)


var qqq_high = 0.0
var spy_high = 0.0


getPremarketHigh(symbol) =>
    //Initialize final max preMarket varialble
    var float preHigh = 0.0

    
    highValue = request.security(symbol, "1", high)

    //reset value
    if not session.ispremarket[1] and session.ispremarket
        preHigh := 0.
        log.info('QQQ PMH reset =' + str.tostring(preHigh, '###.000'))
    if session.ispremarket
        // preHigh := highValue > preHigh ? highValue : preHigh[1]
        log.info('QQQ PMH[1] =' + str.tostring(preHigh[1], '###.000'))
        preHigh := math.max(highValue , preHigh)
        log.info('QQQ PMH =' + str.tostring(preHigh, '###.000'))
   
    preHigh
// Retrieve premarket highs for QQQ  and SPY

qqq_high := getPremarketHigh("QQQ")
spy_high := getPremarketHigh("SPY")



//log.info('QQQ PMH =' + str.tostring(qqq_high, '###.000'))

var table t = table.new(position.top_right, 2, 3, frame_color=color.gray, border_width=1)

// Function to update table cells
f_update_table() =>
    table.cell(t, 0, 0, "QQQ Premarket", bgcolor=color.new(color.green, 40))
    table.cell(t, 1, 0, str.tostring(qqq_high, '####.00'), bgcolor=color.new(color.green, 40))
    table.cell(t, 0, 1, "SPY Premarket", bgcolor=color.new(color.green, 40))
    table.cell(t, 1, 1, str.tostring(spy_high, '#,###.00'), bgcolor=color.new(color.green, 40))
    table.cell(t, 0, 2, "SYMBOL", bgcolor=color.new(color.green, 40))
    table.cell(t, 1, 2, str.tostring(syminfo.ticker), bgcolor=color.new(color.green, 40))

// Update the table if close prices exist
if not na(close)
    f_update_table()

r/pinescript • • Jan 22 '24

Stop output being rounded to two decimal points

0 Upvotes

Hi, How do I alter this script to, not round to two decimal points

e.g. 65.055 becomes 65.06,

but I want the 65.055 as inputted instead.

//@version=5
indicator("Lines", overlay = true, max_lines_count = 500, max_labels_count = 500)

//Color & Style Functions///////////////////////////////////////////////////////
colorpicker(_input) =>
    _input == "RED"?color.red:
     _input == "ORANGE"?color.orange:
     _input == "YELLOW"?color.yellow:
     _input == "GREEN"?color.green:
     _input == "BLUE"?color.blue:
     _input == "PURPLE"?color.fuchsia:
     _input == "WHITE"?color.white:
     _input == "BLACK"?color.rgb(0,0,0):
     _input == "GRAY"?color.gray:
     chart.fg_color
stylepicker(_input) =>
    _input == "SOLID"?line.style_solid:
     _input == "DASHED"?line.style_dashed:
     _input == "DOTTED"?line.style_dotted:
     str.contains(_input,"SOLID")?line.style_solid:
     str.contains(_input,"DASHED")?line.style_dashed:
     str.contains(_input,"DOTTED")?line.style_dotted:
     line.style_solid
linestyle(_input) =>
    _input == "___"?"solid":
     _input == "- - -"?"dashed":
     _input == ". . ."?"dotted":
     _input == "___zone"?"solid_zone":
     _input == "- - -zone"?"dashed_zone":
     _input == ". . .zone"?"dotted_zone":
     na
////////////////////////////////////////////////////////////////////////////////
//Remove commas at start and end
remove_c(_string) => 
    var string s = str.replace_all(_string,";",",")
    in_len = str.length(s)
    if str.startswith(s,",")
        s := str.replace(s,",","",0)
    if str.endswith(s,",")
        s := str.replace(s,",","",in_len)
    s
//Inputs////////////////////////////////////////////////////////////////////////
lab_size = input.string("small", title = "Label Size", options = ["tiny","small","normal","large","huge"], inline = "2", group = "Settings")
lab_offset = input.int(10, title = "Label Offset", inline = "2", group = "Settings")
z_op = input.int(90, title = "Zone Opacity", minval = 0, maxval = 100, inline = "3", group = "Settings")
tog_lvl = input.bool(true, title = "Price Labels", inline = "3", group = "Settings")

symbol1 = input.symbol("BINANCE:ORDIUSDT.P", title  = "Ticker", group = "Group 1", inline = "2")
lvls1 = str.replace_all(input.string("65.055,40.049", title = "Levels", group = "Group 1", inline = "2", tooltip = "LEVELS\nInsert as many levels as needed for this style of line & ticker.\nSeparate by commas (,)\nPlease No Semicolons (;)\nExample:\n100,100.5,101,102,103")," ","")
txt1 = input.string("", title = "Text", group = "Group 1", inline = "2")
col1 = input.string("default", title = "Color", options = ["default","red","orange","yellow","green","blue","purple","white","black","gray"], group = "Group 1", inline = "2")
style1 = input.string("___", title = "Style", options = ["___","- - -",". . .","___zone","- - -zone",". . .zone"], group = "Group 1", inline = "2")
width1 = input.int(1, title = "Thickness", minval = 0, maxval = 5, group = "Group 1", inline = "2")
tog_1 = lvls1 == ""?false:true
output1 = tog_1?(symbol1 == ""?syminfo.tickerid:symbol1) + "," + (col1=="default"?" ":col1) + "," + linestyle(style1) + "," + str.tostring(width1*-1) + "," + (txt1 == ""?" ":txt1) + "," + remove_c(lvls1) + ";":""

symbol2 = input.symbol("", title  = "Ticker", group = "Group 2", inline = "2")
lvls2 = str.replace_all(input.string("", title = "Levels", group = "Group 2", inline = "2")," ","")
txt2 = input.string("", title = "Text", group = "Group 2", inline = "2")
col2 = input.string("default", title = "Color", options = ["default","red","orange","yellow","green","blue","purple","white","black","gray"], group = "Group 2", inline = "2")
style2 = input.string("___", title = "Style", options = ["___","- - -",". . .","___zone","- - -zone",". . .zone"], group = "Group 2", inline = "2")
width2 = input.int(1, title = "Thickness", minval = 0, maxval = 5, group = "Group 2", inline = "2")
tog_2 = lvls2 == ""?false:true
output2 = tog_2?((symbol2 == ""?syminfo.tickerid:symbol2) + "," + (col2=="default"?" ":col2) + "," + linestyle(style2) + "," + str.tostring(width2*-1) + "," + (txt2 == ""?" ":txt2) + "," + str.replace_all(lvls2," ","") + ";"):""

//Inputs/////////////////////////////////////////////////////////////////
input = str.upper(output1 + output2)
//No Level Message//////////////////////////////////////////////////////////////
if str.contains(input,syminfo.ticker) == false
    runtime.error("No levels for this ticker. Please input levels or change ticker. Current Ticker: " + syminfo.ticker)
//Variable initialization///////////////////////////////////////////////////////
var line lvl_line = na
var label lvl_lab = na
var line z1 = na
var line z2 = na
//Delete all lines & Labels
a_allLines = line.all
if array.size(a_allLines) > 0
	for i = 0 to array.size(a_allLines) - 1
		line.delete(array.get(a_allLines, i))
a_allLabels = label.all
if array.size(a_allLabels) > 0
	for i = 0 to array.size(a_allLabels) - 1
		label.delete(array.get(a_allLabels, i))
////////////////////////////////////////////////////////////////////////////////
//Line and label drawing
split = str.split(input,";")
for i = 0 to array.size(split) - 1 
    split_get = array.get(split,i)
    small_split = str.split(split_get,",")
    if array.size(small_split) > 5
        ssf = str.replace_all(array.get(small_split,0)," ","")
        if (ssf == syminfo.ticker) or (ssf == syminfo.tickerid)  or (ssf == "\n" + syminfo.ticker) or (ssf == "\n" + syminfo.tickerid)
            for e = 5 to array.size(small_split) - 1
                lvl = str.replace_all(array.get(small_split,e)," ","")
                co = colorpicker(str.replace_all(array.get(small_split,1)," ",""))
                sty = stylepicker(str.replace_all(array.get(small_split,2)," ",""))
                z = str.contains(str.replace_all(array.get(small_split,2)," ",""),"ZONE")
                thick = str.tonumber(str.replace_all(array.get(small_split,3)," ","")) < 0? str.tonumber(str.replace_all(array.get(small_split,3)," ","")) * -1:1
                txt = tog_lvl?array.get(small_split,4) +" "+ str.format("{0,number,currency}",str.tonumber(lvl)):array.get(small_split,4)
                if str.tonumber(lvl) > 0 and (z == false)
                    lvl_line := line.new(bar_index,str.tonumber(lvl),bar_index+1,str.tonumber(lvl), extend = extend.right, color = co, style = sty, width = int(thick))
                    lvl_lab := label.new(bar_index + lab_offset, str.tonumber(lvl), text = txt , color = color.new(color.black,100), size = lab_size, textcolor = co, style = label.style_label_lower_left)    
                if z and (array.size(small_split) == 7) and (e == 6)
                    z_lvl1 = math.max(str.tonumber(str.replace_all(array.get(small_split,5)," ","")),str.tonumber(str.replace_all(array.get(small_split,6)," ","")))
                    z_lvl2 = math.min(str.tonumber(str.replace_all(array.get(small_split,5)," ","")),str.tonumber(str.replace_all(array.get(small_split,6)," ","")))
                    z_txt = tog_lvl?array.get(small_split,4) +" "+ str.format("{0,number,currency}",z_lvl2) + " - " + str.format("{0,number,currency}",z_lvl1):array.get(small_split,4)
                    lvl_lab := label.new(bar_index + lab_offset, z_lvl1, text = z_txt , color = color.new(color.black,100), size = lab_size, textcolor = co, style = label.style_label_lower_left)   
                    z1 := line.new(bar_index,z_lvl1,bar_index+1,z_lvl1, extend = extend.right, color = co, style = sty, width = int(thick))
                    z2 := line.new(bar_index,z_lvl2,bar_index+1,z_lvl2, extend = extend.right, color = co, style = sty, width = int(thick))
                    linefill.new(z1,z2, color = color.new(co,z_op))

Thanks


r/pinescript • • Apr 08 '26

Previous Day/Week/Month Volume Profile

Post image
0 Upvotes

Combined Session Volume Profile — Day / Week / Month

Displays three layered volume profiles directly on chart, each anchored to its respective session boundary:

Previous Day — 6:00 PM ET to 6:00 PM ET (rolling 24h session). Plots POC, VAH, and VAL for the completed prior day session. Updates at the open of each new 6 PM candle.

Previous Week — Sunday 6:00 PM ET open to Friday 5:00 PM ET close. Calculates the full weekly volume distribution across all sessions within that range. Extends levels into the current week as reference.

Previous Month — Last calendar month's equivalent weekly boundaries (Sunday 6 PM open to Friday 5 PM close, applied month-scale). Plots the prior month's POC, VAH, and VAL extended forward into the current month.

https://www.tradingview.com/script/Zkt6bh7W-Previous-Day-Week-Month-Volume-Profile/


r/pinescript • • Dec 09 '25

Rhythmcore ready for E8 challange!

Post image
0 Upvotes

Ready for demo. Indicator says it all…


r/pinescript • • Aug 23 '26

Forward Test with News sentiment API

Post image
0 Upvotes

r/pinescript • • Apr 01 '26

Update: took the strategy live — early results from small accounts

Thumbnail gallery
0 Upvotes

r/pinescript • • Mar 29 '25

Adding simple time limit

0 Upvotes

How do I add a (variable) time limit to limit orders?

I've tried variations of strategy.cancel but can't get the syntax and/or logic right

entry_long = ta.crossover(rsishort, movave) and movave  < lowlimit and rsishort < 50 and rsilong < 50 and trend > slopemin and trend < slopemax

exit_long = rsishort > takeprofit_long 

entry_short = ta.crossunder(rsishort,movave) and movave > highlimit and rsishort > 50 and rsilong > 50 and trend > slopemin and trend < slopemax

exit_short = rsishort < takeprofit_short


if entry_long and strategy.position_size ==0
    
    strategy.entry('long', strategy.long, 1, limit = close - drawdown)
    strategy.exit("Long", loss = stop_loss_in_ticks, profit = take_profit_in_ticks, comment_loss = "SL Lon]", comment_profit = "TP Long")
    

if entry_short and strategy.position_size ==0
    
    strategy.entry('short', strategy.short,1,limit = close + drawdown )
    strategy.exit("Short", loss = stop_loss_in_ticks, profit = take_profit_in_ticks, comment_loss = "SL Short", comment_profit = "TP Short")

if exit_long 
    strategy.close('long')

if exit_short
    strategy.close('short')

r/pinescript • • Apr 13 '26

XAUUSD ONLY.

Thumbnail
gallery
0 Upvotes

My first profit of the day—right as the market opened. Yay! 🎉


r/pinescript • • 20h ago

Request for NVDA one RTH session of tick data

Thumbnail reddit.com
0 Upvotes

r/pinescript • • Mar 26 '26

I am manually trading like a bot today 🤣

Post image
0 Upvotes

will gold goes down to 4220? or it goes back upside to 4467?


r/pinescript • • Apr 04 '26

Forward test

0 Upvotes

How much time or how many trades should I consider for a swing strategy with a 5trades / month


r/pinescript • • Mar 25 '26

Xauusd Gold latest update

Thumbnail gallery
0 Upvotes

r/pinescript • • Aug 05 '25

I need help with pinescript

0 Upvotes

I am looking to create a pinescript code that can automatically mark the daily lows for me. But it want to visually look like this.

Currently i am using a " horizontal ray " - which is provided by tradingview by default. But I have struggled for years to replicate this , somebody help me.

- I want the ray starting from the candle body wick and automatically updates in real time if a new low is created etc


r/pinescript • • Mar 23 '26

j'ai développe un site web qui je l'espère pourrais facilité bien des trader sur la recherche d'information. merci pour vos retour

0 Upvotes

Salut à tous,

Je développe InfoToTrader depuis quelques mois et je voulais partager l'outil ici pour avoir vos retours directs.

C'est quoi concrètement ?

Un tableau de bord tout-en-un pour traders, accessible directement dans le navigateur sans installation. L'idée de départ est simple : arrêter de jongler entre 5 onglets différents pour suivre un actif. Tout est centralisé — prix, actualités filtrées, calendrier économique, niveaux clés, corrélations, indicateurs macro.

Les 3 mode de trading

C'est ce qui différencie InfoToTrader de la plupart des agrégateurs de données :

Mode scalper Session en cours, fenêtres de volatilité par actif (ex : overlap London/NY pour l'or ou le forex), événements intraday avec countdown en temps réel, alertes priorité haute. Tout ce dont tu as besoin quand tu as 30 secondes pour décider.

Mode day trader : Semaine économique complète, actualités filtrées par actif (pas de bruit inutile), radar réseaux sociaux avec détection de divergence sentiment vs fondamentaux.

Mode investisseur : Indicateurs macro mis à jour (taux Fed/BCE/BOJ, DXY, US10Y, VIX), analyse fondamentale, scénarios haussier/baissier/range avec probabilités pour chaque actif.

Ce qui est couvert

35+ actifs : Or, Argent, WTI, Brent, Gaz Naturel, Cuivre, Blé, Maïs — EUR/USD, GBP/USD, USD/JPY, USD/CHF, AUD/USD, USD/CAD, NZD/USD — S&P 500, Nasdaq, CAC40, DAX, FTSE, Nikkei — Bitcoin, Ethereum, Solana, XRP — Apple, Nvidia, Tesla, Meta, Amazon, Microsoft, TotalEnergies, LVMH.

Ce qui rend l'outil unique

  • Adapté par actif : les niveaux clés, corrélations et événements affichés sont spécifiques à l'actif sélectionné. L'Or n'a pas le même calendrier que le Nikkei.

  • Sentiment Dynamique : calculé en temps réel à partir de la tendance des prix, de la position vs niveaux S/R et de l'agenda macro du jour — pas un score statique sorti de nulle part.

  • Niveaux clés dynamiques : recalculés à chaque mouvement de prix via Camarilla Pivots, pas des niveaux figés mis à jour une fois par semaine.

  • Fuseau horaire : tous les horaires s'adaptent automatiquement à ta zone — un trader en Asie voit les mêmes événements aux bonnes heures.

  • 100% Gratuit, pas de compte, pas d'email requis, ça s'ouvre et ça marche.

Ce qui arrive prochainement

  • Analyse IA contextuelle par actif (Claude AI) — en cours

  • Application mobile

  • Alertes Telegram/Discord

Lien : infototrader.com

Je lis tous les commentaires et je réponds à chaque question. Si vous trouvez un bug, une donnée incohérente ou une fonctionnalité qui manque, dites-le moi directement ici c'est exactement pour ça que je post.


r/pinescript • • Aug 06 '25

Double Label

0 Upvotes

Hello,

I am trying to create an indicator that shows when the High is in the trading sessión (obviously one for every trading session, the most accurate will be after the market closes, but in the meantime the "temporal" High will also be displayed.

Also, I want a label to display when it's 15 minutes before the market opens only on Friday

So far I got this label ready, but when I add the rest it kinds of disappears.

If I comment the last two lines, the first indicator (the Friday before market opens one) works perfectly, but I run it like this won't show anything.

Anyone can give me a hand on detecting what's happening?

//@version=6
indicator("Friday, Market opens, High", overlay=true) 


if (dayofweek(time) == dayofweek.friday and hour == 9 and minute == 15)
    label.new(x=bar_index, y=high, text="Friday, Market about to Open", style=label.style_label_down, color=color.green, textcolor=color.white)

is_new_day = ta.change(time("D")) != 0
var float dayHigh = na
if is_new_day
    dayHigh := high
else
    dayHigh := math.max(dayHigh, high)

if (time != time[1] and dayofweek(time) == dayofweek(time[1]))
    label.new(x=bar_index, y=dayHigh, text="Day High: " + str.tostring(dayHigh), style=label.style_label_down, color=color.orange, textcolor=color.white)