Tutorials

AI-Generated Pine Script Alerts for Webhooks

Learn to prompt AI for working Pine Script v6 alert code, spot the mistakes it commonly makes, and turn the output into a webhook-ready alert.

Tom Hartman

Marketing

11 Min Read Reviewed by Tom Hartman Fact-checked by Tom Hartman
BluSky — The Future of Trading. Prop firm futures trading. Sign up at BluSky.pro.

Getting AI to write Pine Script alerts for a webhook starts with a precise prompt, but it cannot end with unreviewed AI output. The generated Pine Script must use the right alert function, produce valid JSON, wait for confirmed bars, and expose an event that you manually activate through TradingView’s Create Alert dialog.

This tutorial shows how to prompt for Pine Script v6 alert code, audit common mistakes, correct a moving average crossover example, and connect its JSON message to a webhook. For broader guidance on selecting and using coding assistants, see Best AI for Pine Script.

What AI Alert Code Must Cover

alertcondition() vs alert() in Pine v6

The first decision is whether the script needs alertcondition() or alert(). The alertcondition() function has an effect only in indicators, and its message must be a constant string known at compile time. The alert() function works in indicators and strategies, accepts a dynamic series string, and takes a frequency argument.1

Each alertcondition() call creates a distinct choice in the Create Alert dialog. One or more alert() calls appear under a single “Any alert() function call” choice.2 Use alertcondition() when users need separately selectable conditions. Use alert() when the message must contain calculated values or JSON assembled at runtime.

Why Alert Message Format Matters

When a webhook URL is configured, TradingView sends an HTTP POST request with the alert message in its body. Valid JSON receives an application/json content type. Any other message receives text/plain.3

Pine Script has no built-in JSON generator, so the script must construct JSON as an ordinary string.2 That means escaping the double quotes surrounding keys and string values. Single-quoted keys, trailing commas, and unquoted string values produce invalid JSON.

Where TradersPost Fits

TradersPost receives a JSON message as a Signal through a webhook URL. Fields such as ticker, action, and quantity describe the requested trade. The platform processes that Signal using the configured strategy and subscription, then submits the trade to the connected broker or exchange. The same Pine alert can serve another receiver when its JSON keys and values match that receiver’s specification.

Writing a Precise Prompt for AI

Pin Version and Script Type

State Pine Script v6 and identify the output as either an indicator or a strategy. This prevents the model from mixing obsolete syntax with current behavior or placing an ineffective alertcondition() call in a strategy.

Ask for alert() with an explicit frequency. If you leave this choice to the model, it may omit the argument and inherit alert.freq_once_per_bar, which allows the first qualifying call on the realtime bar to trigger.1

Name Inputs and Conditions

List every adjustable value and its Pine input type. For example, request input.int() for moving average lengths and input.float() for a numeric threshold. Then define the signal in exact terms, such as “the fast EMA crosses above the slow EMA,” rather than asking for a generic crossover alert.

Specify the complete JSON shape too. Name each required key, whether its value is a string or number, and which Pine value supplies it. A useful prompt checklist is:

  • Pine Script v6 and indicator or strategy type
  • Named inputs with types and defaults
  • Exact trigger series and crossing direction
  • Required JSON keys and value sources
  • Confirmed-bar gating and explicit frequency

Require Confirmed-Bar Logic

Ask for the trigger to include barstate.isconfirmed and for the alert call to use alert.freq_once_per_bar_close. Also require a short explanation of both choices. Making the model justify its timing logic exposes contradictions, such as claiming an alert waits for the close while leaving the default frequency in place.

Worked Example: Prompt to Fixed Code

The Initial Prompt

Use a prompt with testable requirements:

“Write a Pine Script v6 indicator named EMA Webhook Alert. Add two input.int() inputs named Fast Length and Slow Length, with defaults of 9 and 21. Trigger when the fast EMA crosses above the slow EMA. Gate the condition with barstate.isconfirmed. Use alert() with alert.freq_once_per_bar_close. Build valid JSON containing ticker, action set to buy, quantity set to 1, and the closing price. Plot both EMAs. Explain the frequency and gating choices.”

Reviewing the AI Output

First, confirm that the response is an indicator and that its chosen alert function matches the required message. Because the ticker and close must be inserted at runtime, alert() is the direct choice. An alertcondition() message cannot concatenate syminfo.ticker or str.tostring(close).

Next, inspect the resulting message rather than trusting its JSON-like appearance. The delivered body needs double quotes around ticker, action, and their string values. Finally, verify that the crossover is gated with barstate.isconfirmed and that the alert call names its frequency.

The Corrected v6 Code

//@version=6
indicator("EMA Webhook Alert", overlay = true)

int fastLength = input.int(9, "Fast Length", minval = 1)
int slowLength = input.int(21, "Slow Length", minval = 1)

float fastEma = ta.ema(close, fastLength)
float slowEma = ta.ema(close, slowLength)

bool longSignal = ta.crossover(fastEma, slowEma) and barstate.isconfirmed

if longSignal
    string message = "{\"ticker\":\"" + syminfo.ticker + "\",\"action\":\"buy\",\"quantity\":1,\"price\":" + str.tostring(close, format.mintick) + "}"
    alert(message, alert.freq_once_per_bar_close)

plot(fastEma, "Fast EMA", color = color.blue)
plot(slowEma, "Slow EMA", color = color.orange)

The correction makes three timing and formatting decisions explicit. The condition waits for bar confirmation, the alert frequency requires the closing iteration, and the message uses escaped double quotes to produce JSON. The numeric quantity and price values remain unquoted, while ticker and action are JSON strings.

Where AI Gets Alerts Wrong

Dynamic alertcondition() Messages

AI often concatenates a calculated value into alertcondition(). That fails because its message requires a constant string. Placeholders such as {{close}}, {{ticker}}, {{plot_0}}, and {{plot("Title")}} let TradingView substitute dynamic values when the alert fires.2

Fix: use placeholders in a constant message, or switch to alert() when the script must assemble fully dynamic text.

alertcondition() Inside a Strategy

An alertcondition() call can compile in a strategy, but it cannot issue an alert trigger there.2 Strategies can trigger alerts through alert() calls, order fill events, or both. For customized fill messages, use the alert_message parameter on order-generating calls and include {{strategy.order.alert_message}} in the alert message field.

Fix: replace strategy alertcondition() calls with alert(), or configure order fill alerts when execution events are what matter.

Default alert() Frequency

In an indicator, the default alert.freq_once_per_bar permits the first executed call during a realtime bar to trigger. The final bar values can differ from those present at that moment. TradingView classifies scripts using realtime intrabars to generate alerts or orders as unacceptable repainting.4

Fix: use alert.freq_once_per_bar_close for confirmed signals and gate the condition with barstate.isconfirmed.

Strategy Frequency Assumptions

Strategies recalculate at bar close by default. Unless calc_on_every_tick = true is enabled, their alert() calls behave as once per bar close regardless of the supplied frequency argument.1 Strategy alert frequency is controlled by code, so the Create Alert dialog does not offer a frequency setting for strategy alerts.5

Fix: do not request every-tick strategy alerts unless intrabar recalculation is intentional and its repainting implications have been reviewed.

Repainting Checks Before You Deploy

Confirming Bar State

barstate.isconfirmed is true on historical bars and on the final update of a realtime bar.6 Adding it to the trigger delays the signal until that bar’s values are final. This trades earlier notification for consistency between the visible closed-bar signal and the webhook event.

Why Intrabar Alerts Fail Review

Ask two questions when reviewing generated code: does it calculate consistently on historical and realtime bars, and do its alerts wait for the realtime bar to close? TradingView specifically recommends these checks when evaluating repainting behavior.4

Test Before Trusting

Pine alert code only exposes alert events. You must still create the running alert through the chart interface and confirm its appearance in the alert log. Creating an alert saves a snapshot of the script, inputs, symbol, and timeframe. Later edits do not update that running alert, so delete and recreate it after correcting the code.1

Review Checklist for This Category

Message and Frequency Checklist

  • Confirm the script declares Pine Script v6.
  • Confirm JSON keys and string values use double quotes.
  • Confirm alert() has an explicit frequency argument.
  • Use bar-close frequency and confirmation for closed-bar signals.
  • Keep effective alertcondition() calls inside indicators.
  • Verify the payload uses fields accepted by the destination.

Limits AI Commonly Ignores

Every alertcondition() call contributes to Pine’s limit of 64 plot counts per script.7 By contrast, all alert() calls in one script count as one alert, regardless of how many calls appear in the code. TradingView also halts further alerts if more than 15 occur within three minutes.2 Review looping or frequently repeated conditions before deployment.

Turning the Indicator Into a Webhook Alert

Write a JSON Alert Message

Format the message as valid JSON with double-quoted keys and string values. A body such as {"text":"signal received"} receives the JSON content type because it parses as JSON.3 For trade automation, replace generic fields with the exact schema expected by the receiving application.

Check Webhook Requirements

TradingView requires two-factor authentication for webhook alerts. Webhook URLs can use ports 80 or 443, requests are cancelled if the remote server takes longer than three seconds, and IPv6 is not supported. TradingView also warns against putting login credentials or passwords in the webhook body. The Webhook status column in the alert log reports delivery results.3

  1. Add the corrected indicator to the intended chart.
  2. Open Create Alert and choose the "Any alert() function call" condition.
  3. Enable the webhook notification and paste the destination URL.
  4. Create the alert, then inspect its first logged message.
  5. Confirm the receiver parsed the expected fields.

Paper Trade Before Going Live

Before any live account is involved, subscribe a paper account to the TradersPost strategy that owns the webhook URL. That can be the basic TradersPost paper broker or a broker's own paper environment. Compare TradingView’s exact logged message with the received Signal and the resulting paper trade. Confirm the ticker, action, quantity, timing, and order behavior before adding a subscription for a live broker account.

For a fuller walkthrough of the setup screens and delivery flow, read How to Use TradingView Webhooks, then test the AI-generated alert from signal through paper execution.

Bottom Line

  • Prompt for Pine Script v6, a specific script type, exact inputs, and exact trigger logic.
  • Use alert() for runtime JSON and alertcondition() for separately selectable indicator conditions.
  • Require barstate.isconfirmed and alert.freq_once_per_bar_close when signals must wait for candle close.
  • Validate the JSON, recreate alerts after code edits, and inspect webhook delivery logs.
  • Paper trade the complete route before enabling live execution.

AI can accelerate alert development, but the deployable result comes from a disciplined audit. Use the review process here alongside the broader Best AI for Pine Script guide, then connect the verified webhook to a paper subscription before considering live automation.

Frequently Asked Questions

Can AI Code Work Unedited?

Sometimes, but do not assume it will. Generated code can confuse the scope of alertcondition() and alert(), produces malformed JSON, or omits an explicit frequency. Supplying current Pine Script v6 alert documentation can reduce these mistakes, but manual review remains necessary.

How Do Alert Functions Differ?

alertcondition() creates distinct indicator conditions and requires a constant message, although placeholders can insert values at delivery. alert() works in indicators and strategies, accepts a dynamic series string, and uses a frequency selected in code.

Why Does It Fire Early?

An indicator using the default alert.freq_once_per_bar can trigger on its first qualifying call before the candle closes. Use alert.freq_once_per_bar_close and gate the condition with barstate.isconfirmed when the signal must use final bar values.

Can Strategy Frequency Use Dialog Settings?

No. Strategy alert frequency is determined by the strategy code. Without calc_on_every_tick = true, the strategy normally recalculates at bar close and its alert() calls cannot execute on each intrabar update.

Why Did Webhook Delivery Fail?

Confirm that two-factor authentication is enabled, inspect the alert log’s Webhook status, and verify that the URL uses an accepted port. If the destination expects JSON, also compare the exact logged body with a JSON validator and the destination’s field specification.

References

1 TradingView Pine Script v6: Alerts
2 TradingView Pine Script v6 FAQ: Alerts
3 How to Configure Webhook Alerts
4 TradingView Pine Script v6: Repainting
5 Why Is the Once Per Bar Option Missing?
6 TradingView Pine Script v6: Bar States
7 TradingView Pine Script v6: Limitations

All In Tutorials
  • Tutorials Oct 10, 2026

    AI Pine Script Moving Average Indicators

    Learn to prompt AI for working Pine Script v6 moving average, Hull MA, and Supertrend code, catch its common bugs, and turn the result into an alert.

  • Tutorials Oct 9, 2026

    Using AI to Write a Pine Script Futures Strategy for Webhooks

    Learn to prompt AI for a Pine Script v6 futures strategy with webhook-ready alerts, and catch the alert_message, session, and contract mistakes AI makes.

  • Tutorials Oct 9, 2026

    AI Pine Script DCA Strategy: Prompts That Work

    Learn to prompt AI for working Pine Script v6 DCA, grid, and scale-in code, plus the pyramiding, exit, and trimming mistakes to catch before you deploy it.

  • Tutorials Oct 9, 2026

    How to Build an AI Pine Script Swing Trading Strategy

    Prompt AI for a Pine Script v6 swing trading strategy, catch repainting and warm-up errors in the output, then route a confirmed signal to a broker.

Start trading at scale today. Sign up for free.

Free 7-day trial

Set-up in 3 minutes

Paper account for testing

By continuing, you agree to the TradersPost Terms of Service and Privacy Policy. This site is protected by reCAPTCHA.

TradersPost operates as a non-custodial automated trading platform, enabling users to connect alerts from their preferred trading platforms to their selected brokerage or exchange accounts. It abstains from the transmission, custody, or management of customer funds, covering both traditional and cryptocurrency assets. Typically, registration requirements set by regulatory entities such as the SEC, FINRA, or FinCEN apply to entities that hold or transmit customer funds. To ensure ongoing compliance, TradersPost regularly engages with regulatory authorities to confirm its adherence to all relevant local and federal laws.

TradersPost does not provide alerts, signals, research, analysis, or trading advice of any kind. It is designed to assist traders and investors in making their own trading decisions based on their alerts. The platform does not offer recommendations regarding securities to buy or sell, nor does it provide trading or investing advice. The platform and its features, capabilities, and tools are provided 'as-is' without any warranty.

Risk Disclosure: The use of automated trading systems involves inherent risks, including the potential for significant financial loss. These systems operate based on predetermined algorithms that may not fully adapt to changing market conditions, possibly making them unsuitable for some investors. Individuals are advised to thoroughly assess their financial situation and risk tolerance before using this platform.

Testimonials appearing on this website may not be representative of other clients or customers and is not a guarantee of future performance or success.

Broker, exchange, trading platform, company names, product names, service marks, trademarks, and logos appearing on this website are the property of their respective owners and are used solely to identify supported connections and technical compatibility. TradersPost is an independent third-party platform and is not affiliated with, endorsed by, sponsored by, or authorized by any of these organizations unless expressly stated. Technical compatibility does not imply a commercial partnership, sponsorship, endorsement, or authorization. See Important Disclosures for trademark information.

© 2026 TradersPost, Inc. All rights reserved.