Tutorials

Prompting AI for a Pine Script Trend Following Strategy

How to prompt an AI assistant for a Pine Script v6 trend following strategy, fix the reversal, margin and exit mistakes it tends to make, and test order-fill alerts on paper first.

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.

An AI Pine Script trend following strategy can turn a precise specification into usable Pine Script v6 code, but the first draft still needs a technical audit. AI commonly carries over removed v5 syntax, misunderstands position reversals, and leaves margin or trailing-stop behavior implicit.

This guide builds on our best AI for Pine Script guide. You will learn how to prompt for confirmed-bar logic, review a moving average crossover strategy, correct typical AI errors, and move validated order-fill alerts into paper execution.

What Trend Following Strategies Cover

Moving Average Crossover Systems

A moving average crossover is the standard starting point because its rules are easy to state and inspect. A fast average crossing above a slow average triggers a long entry, while a cross below triggers a short entry. In Pine, those conditions normally use ta.crossover(), ta.crossunder(), and strategy.entry().

TradingView's strategy example calculates fast and slow simple moving averages from one integer input, using the selected length for the fast average and twice that value for the slow average. The same example shows that strategy.entry() creates entries and reverses an existing opposite position.1 That reversal behavior must be part of the prompt and review, not an accidental side effect.

Breakout Systems With Trailing Exits

A breakout strategy replaces the moving average cross with a close crossing a defined price level, such as a prior high or channel boundary. After entry, a trailing stop follows favorable movement instead of predicting a fixed exit. This structure also applies to breakout and opening range strategies.

Pine trailing stops require careful units. trail_price is an absolute activation price. trail_points defines an activation distance in ticks, and trail_offset sets the trailing distance in ticks. Once activated, the stop only moves when price establishes a new favorable extreme.1

What the Research Actually Shows

Moskowitz, Ooi, and Pedersen documented time-series momentum across 58 liquid equity index, currency, commodity, and bond futures instruments. Returns showed persistence over one to 12 months and partial reversal over longer horizons.2

AQR later constructed a time-series momentum simulation beginning in 1880 and considered the effects of increased assets using the approach and increased correlations across markets since the credit crisis.3 AQR's page also carries the warning that past performance is not a guarantee of future performance.3 Neither study tested AI-generated Pine code, so treat this research as a reason to investigate trend rules, not as a performance assumption for any script.

Prompting AI for Pine v6 Code

Pin the Version and Inputs

Start the prompt with //@version=6. AI models have learned from years of Pine examples, including obsolete versions, so asking only for “Pine Script” invites mixed syntax.

Name every input and its type. Use input.int() for moving average lengths and input.float() for trailing distances. State the exact long, short, and exit conditions. Also specify whether entries must use strategy.entry() or strategy.order(), because those functions behave differently when an opposite position is open.

Require Confirmed-Bar Logic

Require each signal based on fluid values such as close to include barstate.isconfirmed. Realtime high, low, and close values can change before the bar closes. TradingView demonstrates confirmed-bar gating as a direct way to prevent a crossover from disappearing when the open bar changes.4

Confirmation introduces delay compared with intrabar signals, but it makes historical and realtime behavior easier to reconcile. Make the requirement explicit rather than asking AI vaguely for “non-repainting code.”

A Reusable Prompt Template

Use this template and replace the bracketed items:

Write a Pine Script strategy using //@version=6.

Inputs:
- Fast moving average length: input.int(), default [value]
- Slow moving average length: input.int(), default [value]
- Trailing activation distance: input.float(), default [ticks]
- Trailing offset: input.float(), default [ticks]

Enter long with strategy.entry() when the fast SMA crosses above the slow SMA.
Enter short with strategy.entry() when the fast SMA crosses below the slow SMA.
Gate both conditions with barstate.isconfirmed.
Implement exits with strategy.exit(), trail_points, and trail_offset.
Do not use the when parameter.
Set pyramiding, margin_long, and margin_short explicitly.
State whether opposite strategy.entry() calls should reverse positions.
Do not add profit = 0 or loss = 0 placeholders.
Include JSON alert_message values for long, short, and exit fills.

This prompt pins the language version, order functions, units, and execution assumptions. It also forces the model to disclose pyramiding and margin choices instead of inheriting defaults silently.

Worked Example: Prompt to Fixed Code

The Initial AI Output

For the worked example, ask for 20-bar and 50-bar simple moving averages, long and short reversal entries, a 100-tick activation distance, and a 50-tick trailing offset. Require confirmed bars and order-fill JSON.

A typical first response may still contain three defects:

  • A removed when= argument on an order function
  • profit = 0 or loss = 0 beside another exit level
  • No explicit margin_long or margin_short assumption

Do not patch syntax alone. Ask the model what each order does to the current position, when the trail activates, and which units each exit parameter uses.

Corrected Pine Script v6 Code

The corrected version uses if blocks because Pine v6 removed when from applicable strategy.*() functions.5 It uses only trailing parameters for the exit and declares 1:1 margin assumptions explicitly.

//@version=6
strategy(
    "Confirmed MA Trend With Trailing Exit",
    overlay = true,
    pyramiding = 1,
    margin_long = 100,
    margin_short = 100
)

int fastLength = input.int(20, "Fast SMA length", minval = 1)
int slowLength = input.int(50, "Slow SMA length", minval = 2)
float trailActivationTicks = input.float(100.0, "Trail activation ticks", minval = 1.0)
float trailOffsetTicks = input.float(50.0, "Trail offset ticks", minval = 1.0)

float fastSma = ta.sma(close, fastLength)
float slowSma = ta.sma(close, slowLength)

// Run the cross checks on every bar; v6 evaluates `and` lazily.
bool bullCross = ta.crossover(fastSma, slowSma)
bool bearCross = ta.crossunder(fastSma, slowSma)
bool longSignal = barstate.isconfirmed and bullCross
bool shortSignal = barstate.isconfirmed and bearCross

string longMessage = '{"ticker":"' + syminfo.ticker + '","action":"buy","quantity":1}'
string shortMessage = '{"ticker":"' + syminfo.ticker + '","action":"sell","quantity":1}'
string exitMessage = '{"ticker":"' + syminfo.ticker + '","action":"exit"}'

if longSignal
    strategy.entry("Long", strategy.long, alert_message = longMessage)

if shortSignal
    strategy.entry("Short", strategy.short, alert_message = shortMessage)

strategy.exit(
    "Long Trail",
    from_entry = "Long",
    trail_points = trailActivationTicks,
    trail_offset = trailOffsetTicks,
    alert_message = exitMessage
)

strategy.exit(
    "Short Trail",
    from_entry = "Short",
    trail_points = trailActivationTicks,
    trail_offset = trailOffsetTicks,
    alert_message = exitMessage
)

plot(fastSma, "Fast SMA", color = color.aqua)
plot(slowSma, "Slow SMA", color = color.orange)

The two crossovers are computed in the global scope because v6 evaluates and conditions lazily, and a history-dependent call that only runs on some bars can return inconsistent results.5 This is an implementation example, not a performance claim. Change its inputs only after confirming that the resulting order frequency, sizing, and trailing distance suit the instrument's tick structure.

Where AI Gets Trend Code Wrong

Entries That Reverse Positions

When strategy.entry() executes opposite an open position, Pine adds the existing position size to the new order size. The resulting transaction closes the current position and opens the requested opposite position. strategy.order() does not reverse automatically.1

If the system should close but not reverse, use strategy.risk.allow_entry_in() to restrict the allowed direction. An opposite strategy.entry() call can then close the position without establishing the disallowed side.1

Margin Defaults Block Trades

Pine v6 changed the default margin_long and margin_short values from 0 to 100. Under the v6 default, entries costing more than available funds are not opened, and losing positions can be margin called.5 A simulated margin call liquidates four times the quantity needed to cover the loss.1

Since July 2026, the Properties tab displays Long leverage and Short leverage rather than margin percentage fields. The declaration still accepts margin_long and margin_short for backward compatibility and converts them into the leverage defaults shown in the interface.6

Broken Exits After Migration

The removed when parameter causes a compilation error and must be replaced with a conditional block. A subtler migration error occurs when strategy.exit() contains both relative and absolute levels. Pine v6 evaluates both and uses the level expected to trigger first, while v5 preferred the absolute level.5

Therefore, profit = 0 or loss = 0 is not a harmless placeholder. It places a relative exit at the entry price and can close each trade immediately. Remove unused parameters rather than assigning zero.

A Review Checklist for Trend Code

Confirm Entry and Exit Behavior

  • Decide whether opposite strategy.entry() calls should reverse the position.
  • Check pyramiding. Its default is 1, so further strategy.entry() calls cannot add to an existing position unless configured otherwise.1
  • Verify that trail_price uses price units and that trail_points and trail_offset use ticks.
  • Remove unused exit arguments instead of setting them to zero.

Check Repainting Before Trusting Signals

Confirm that conditions using close, high, or low wait for barstate.isconfirmed when closed-bar signals are intended. Compare historical markers with realtime alert behavior rather than relying only on a clean backtest.

If the script calls request.security() for higher-timeframe data, request the prior confirmed value with a [1] offset and barmerge.lookahead_on. Lookahead without the offset leaks future information into historical bars.4

Confirm Margin and Sizing Assumptions

Inspect margin_long, margin_short, initial capital, quantity, and pyramiding together. Then review the Capital efficiency area of the strategy report, which includes minimum account size, margin usage, and margin call counts.1 A backtest with attractive trade statistics but recurring simulated liquidations is not ready for automation.

From Pine Script to Live Execution

Generating Alerts From Order Fills

A TradingView strategy alert can trigger from broker-emulator order-fill events when the user creates the alert in the chart interface. The alert_message argument accepts a series string on order-generating calls, including strategy.entry(), strategy.exit(), strategy.order(), and strategy.close().7

Place {{strategy.order.alert_message}} in the alert's Message field so TradingView uses the per-order JSON. Although alertcondition() compiles inside a strategy, users cannot create strategy alerts from those calls.7

Sending Alerts as Webhooks

TradingView sends webhook alerts as HTTP POST requests. Valid JSON receives an application/json content-type header, while plain text receives text/plain. Webhook URLs can use only ports 80 and 443, requests are cancelled when the remote server takes longer than three seconds, and webhook alerts require two-factor authentication.8

Paper Trading Before Going Live

A signal is the webhook event sent by a source such as TradingView. Its JSON can carry a ticker, action, quantity, and optional order instructions. TradersPost processes that signal according to the configured strategy and subscription, then submits the resulting trade to a connected broker or exchange.

Paper execution should reproduce the full operational path, not merely rerun the backtest. Compare each TradingView Alert Log entry with the corresponding signal and paper fill, checking timestamp, action, quantity, and direction. Before risking live capital, connect a TradersPost paper account and confirm that repeated order-fill alerts produce the expected positions and exits. Pay attention to reversals: the strategy fills a reversal as one order and sends one sell or buy message, so confirm that your subscription settings close the old position and open the new one the way the backtest assumes.

Bottom Line

  • Prompt explicitly for Pine Script v6, typed inputs, confirmed bars, order functions, margin, and pyramiding.
  • Assume AI-generated strategy code needs review, especially around reversal behavior and exit parameters.
  • Use strategy.exit() trailing parameters in ticks without zero-distance placeholders.
  • Validate margin calls, repainting, alerts, and paper fills before live execution.

Use this workflow alongside the broader AI Pine Script guide. The same audit process also applies to mean reversion strategies, momentum strategies, and scalping strategies, although their entry timing and execution risks differ.

Frequently Asked Questions

Can AI Write the Complete Strategy?

AI can produce a compiling first draft quickly, but it can retain v5 habits such as when= or add zero-distance exit placeholders. Verify entry and exit behavior, margin assumptions, units, and repainting before trusting the output.

Why Does Every Trade Exit Immediately?

Pine v6 evaluates relative and absolute strategy.exit() levels together. If AI adds profit = 0 or loss = 0, it creates an exit at the entry price. Remove the placeholder and retain only the intended exit parameters.

Why Did v6 Add Margin Calls?

Pine v6 changed the default long and short margin from 0 to 100. Entries that exceed available funds are not opened, and losing positions can be margin called. Declare both margin arguments explicitly so the simulation reflects your intended assumptions.

Does strategy.entry Close or Reverse?

By default, an opposite strategy.entry() order closes and reverses the position. strategy.order() does not reverse automatically. Use strategy.risk.allow_entry_in() when an opposite entry should close without opening the other direction.

Is My Trend Strategy Repainting?

Compare calculations and markers on historical and realtime bars. Confirm that signals using fluid prices wait for barstate.isconfirmed, and inspect every request.security() call for lookahead without a [1] offset.

References

1 TradingView Pine Script Strategies
2 Time Series Momentum
3 A Century of Evidence on Trend-Following Investing
4 TradingView Pine Script Repainting
5 Migrating to Pine Script Version 6
6 TradingView Pine Script Release Notes
7 TradingView Pine Script Alerts
8 How to Configure TradingView Webhook Alerts

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.