Skip to content

Pine Script alert() Function: Automate Strategy Signals

If your Pine Script strategy fires signals but nothing happens in MetaTrader, the alert() function is the missing piece. This guide shows you exactly how to write it, configure it, and connect it to live execution using PineConnector.


What the alert() Function Actually Does

Pine Script's alert() function fires a notification every time a condition inside your script is met. On its own, that notification sits in TradingView's Alerts Log. When you pair it with a webhook URL, the notification becomes a trade instruction sent directly to your broker.

The basic syntax is:

alert('LicenseID,buy,EURUSD,risk=1', alert.freq_once_per_bar_close)

Two arguments matter here. The first is the message string, which PineConnector reads to know what trade to place. The second is the frequency setting. Using alert.freq_once_per_bar_close is important because it fires only after the candle closes, which reduces the risk of acting on signals that repaint during the live bar.


Do You Have Code Access? Start Here

The approach you take depends on whether you can open the script in Pine Editor.

If you can open and edit the script, follow PineConnector's Low-Code Alert guide, which this post is based on. It covers both strategy and indicator scripts with step-by-step code examples.

If the script belongs to someone else and the code is locked, check PineConnector's No-Code Alert guide first. That guide walks through three feasibility tests: checking whether the script uses strategy(), whether it exposes alert() via a License ID input, and whether it surfaces alertcondition() options in the alert dialog.


Step 1: Confirm Your Script Version

Before writing any code, open Pine Editor and check the first line. It should read:

//@version=5

PineConnector's low-code documentation is written for Pine Script v5. If your script is on v4 or lower, convert it to v5 before proceeding. The syntax differences are significant enough that mixing versions will break your alerts.


Step 2: Identify Your Script Type

Your script will start with either strategy(...) or indicator(...). The implementation steps differ between the two.

For strategy scripts, your entry conditions are tied to strategy.entry() calls. Search for those lines using CTRL+F (Windows) or CMD+F (Mac). The condition sitting after the if on each row is what you need. For example:

if ta.change(direction) < 0
    strategy.entry('My Long Entry Id', strategy.long)

Here, ta.change(direction) < 0 is your long entry condition.

For indicator scripts, entry conditions are typically declared as boolean variables near the bottom of the script. A standard EMA crossover example looks like this:

long = ta.crossover(ema20, ema50) and close > ema20
short = ta.crossunder(ema20, ema50) and close < ema20

Step 3: Add Visual Confirmation with plotshape

Before writing any alert code, add plotshape() calls so you can visually verify that your entry conditions are correct on the chart. This prevents you from wiring up alerts to the wrong logic.

Place these lines at the bottom of your script:

plotshape(LongEntryCondition, style=shape.arrowup, location=location.belowbar, color=color.blue)
plotshape(ShortEntryCondition, style=shape.arrowdown, location=location.abovebar, color=color.blue)

Replace LongEntryCondition and ShortEntryCondition with your actual conditions. Save the script and click "Add to chart". Blue arrows should appear at your expected entry points. If they do not, your condition variables need adjusting before you move forward.

One thing to note: the blue arrows will appear one candle before the strategy's own entry markers. This is expected behavior. The arrow plots at bar close; the strategy entry triggers at the open of the next bar. Since the close of bar one equals the open of bar two, there is no execution difference.


Step 4: Add the alert() Function

This is where your signals get converted into trade instructions.

For strategy scripts, place the alert call directly after each strategy.entry() line:

if ta.change(direction) < 0
    strategy.entry('My Long Entry Id', strategy.long)
    alert('LicenseID,buy,EURUSD,risk=1', alert.freq_once_per_bar_close)

if ta.change(direction) > 0
    strategy.entry('My Short Entry Id', strategy.short)
    alert('LicenseID,sell,EURUSD,risk=1', alert.freq_once_per_bar_close)

For indicator scripts, wrap the alert call in an if block using your entry condition:

if LongEntryCondition
    alert('LicenseID,buy,EURUSD,risk=1', alert.freq_once_per_bar_close)

if ShortEntryCondition
    alert('LicenseID,sell,EURUSD,risk=1', alert.freq_once_per_bar_close)

Replace LicenseID with your actual PineConnector License ID. It is a long string beginning with 6 or 7, found in your PineConnector licensing dashboard.


Making Your Alerts Dynamic

A static alert hardcoded to EURUSD at risk=1 works for one setup. Once you want to run the same strategy across multiple symbols or vary position sizing, you need dynamic values.

Dynamic Symbol

Instead of hardcoding the ticker, pull it from the chart:

alert('LicenseID,buy,' +syminfo.ticker+ ',risk=1', alert.freq_once_per_bar_close)

Now a single script works on any symbol you apply it to. If your broker uses a different ticker naming convention than TradingView (for example, NAS100 instead of US100), you can remap it:

symbol = syminfo.ticker

if syminfo.ticker == "US100"
    symbol := "NAS100"

if LongEntryCondition
    alert('LicenseID,buy,' +symbol+ ',risk=1', alert.freq_once_per_bar_close)

Dynamic Stop Loss and Take Profit

To use chart-based stop loss and take profit values, store them as variables and convert to strings inside the alert:

LongSL = low[1]
LongTP = ta.ema(close, 50)
RiskValue = 1

if LongEntryCondition
    alert('LicenseID,buy,' +syminfo.ticker+ ',sl=' +str.tostring(LongSL)+ ',tp=' +str.tostring(LongTP)+ ',risk=' +str.tostring(RiskValue), alert.freq_once_per_bar_close)

low[1] is the low of the most recently closed candle. ta.ema(close, 50) updates at each bar close. The str.tostring() wrapper is necessary because alert() only accepts strings, not float values.

Adding a Comment for Trade Identification

To label trades in your broker terminal:

alert('LicenseID,buy,' +syminfo.ticker+ ',sl=' +str.tostring(LongSL)+ ',tp=' +str.tostring(LongTP)+ ',risk=1,comment="Strategy 1"', alert.freq_once_per_bar_close)

Note the quoting: double quotes wrap the full alert string and single quotes wrap comment= values inside.

Multiple License IDs

If you run multiple PineConnector accounts, duplicate the alert line for each License ID:

if LongEntryCondition
    alert('LicenseID_1,buy,' +syminfo.ticker+ ',risk=1', alert.freq_once_per_bar_close)
    alert('LicenseID_2,buy,' +syminfo.ticker+ ',risk=1', alert.freq_once_per_bar_close)

One TradingView alert creation handles all of them. Keep in mind that a single alert can fire up to 15 times within a three-minute window before TradingView pauses it automatically.


Step 5: Create the Alert in TradingView

Adding alert() to your code does not activate anything on its own. You must create an alert for each symbol and timeframe you want to trade.

Press Alt+A (Windows) or Option+A (Mac) to open the alert dialog. Configure it as follows:

Setting Value
Condition Your script name, then "alert() function calls only"
Webhook URL https://webhook.pineconnector.com

Click Create. When your entry conditions are met on the next bar close, a blue arrow appears on the chart, the Alerts Log records the trigger, and PineConnector sends the trade to MetaTrader.

One important note: if you update your script code after creating alerts, the existing alerts will not pick up the changes. They were saved against the original version of the code. Delete the old alerts and create new ones every time you modify your script.


Automating Strategies without Code Access

If the script you want to automate is published by someone else and you cannot edit it, you have three options before giving up.

The first is checking whether it is a strategy() script. Create an alert (Alt+A), select the script under Condition, and look for "Order fills only". If that option exists, the strategy can be automated by selecting it and writing a PineConnector message directly in the alert dialog:

LicenseID,{{strategy.order.action}},{{ticker}},risk={{strategy.order.contracts}}

The second option applies if the script exposes a License ID input. Go to the script's Settings, click Inputs, and look for a License ID field. If present, enter your License ID there and the script may already be wired to fire alert() calls. Create a webhook alert pointing to https://webhook.pineconnector.com and it should work without any code edits.

The third option is checking for alertcondition(). Create an alert, select the script under Condition, and look for options like "Going Long" or "Going Short" above the Crossing field. If those exist, select the appropriate direction, write your PineConnector message in the alert body, and set the webhook URL. Use "Once Per Bar Close" as the trigger option to minimize repainting.

If none of these three tests pass, the script cannot be automated without the author adding PineConnector compatibility. PineConnector provides compatibility instructions you can send directly to the script author.


What Repainting Means for Your Alerts

Repainting is worth understanding before you go live. It refers to the difference in how a script behaves during a live bar versus how it looks on historical bars after the bar has closed.

More than 95% of indicators repaint to some degree, including MACD and RSI. Using alert.freq_once_per_bar_close addresses the most common form: it ensures your alert fires only on confirmed data rather than mid-bar fluctuations. For most strategies, this is sufficient. Misleading repainting (scripts that plot signals in the past that could not have been known in real time) is a separate problem that no alert frequency setting can fix.


A Full Worked Example: The SuperTrend Strategy

If you want to see everything above applied end-to-end, PineConnector's SuperTrend Strategy guide is the clearest reference available. It includes a video tutorial walking through the full setup from Pine Editor to a live MetaTrader position, plus the complete ready-to-use Pine Script v5 code.

The SuperTrend script demonstrates exactly how alert() and plotshape() sit alongside strategy.entry() in practice:

if ta.change(direction) < 0
    strategy.entry('Long', strategy.long)
    alert(str.tostring(LicenseID)+',buy,' + syminfo.ticker + ',risk=' + str.tostring(riskvalue), alert.freq_once_per_bar_close)

if ta.change(direction) > 0
    strategy.entry('Short', strategy.short)
    alert(str.tostring(LicenseID)+',sell,' + syminfo.ticker + ',risk=' + str.tostring(riskvalue), alert.freq_once_per_bar_close)

Notice that syminfo.ticker makes the symbol dynamic and str.tostring(riskvalue) pulls from a user-adjustable input rather than a hardcoded number. This is the pattern to follow for any strategy you build from scratch.

One practical note from the guide: when testing, set the chart to the 1-minute timeframe so alerts trigger sooner and you can confirm the full chain (TradingView Alerts Log → PineConnector Signal Log → MetaTrader terminal) before running it on your actual timeframe.


Start Automating Your Strategy

Once your alert() calls are in the script and your TradingView alert is configured with the PineConnector webhook, the bridge between Pine Script and MetaTrader is live.


Start your free 14-day trial at PineConnector and connect your first strategy today.


Leave a comment

Back To PiCo Blog

Your Bridge to
Effortless Trading.

Automate your TradingView strategies on MetaTrader 4/5 — with analytics, tasks, and real-time alerts built in.

No credit card required
Full Advanced plan — Bridge, Analytics, Tasks, Notifications
Go live in under 30 minutes
Only subscribe if you love it — no obligation
Free 14-Day Advanced Trial
Trusted by 66,000+ traders · Built on Microsoft Azure · Empowering traders since 2021