Tutorials

Coding an AI Pine Script Scalping Strategy

Prompt an AI for a Pine Script v6 scalping strategy, then audit the backtest for the fill, cost, and bar-detail mistakes AI assistants make most.

Tom Hartman

Marketing

12 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 scalping strategy needs more scrutiny than a typical AI-generated strategy. Tight stops, small targets, and short holding periods make results sensitive to intrabar price assumptions, costs, chart type, and Pine Script version changes.

The goal is not to ask an assistant for a profitable system. It is to obtain clearly specified Pine Script v6 code, verify that it compiles, and audit the simulation before treating its results as useful evidence.

The process below covers prompt design, a corrected crossover example, backtest traps, alert behavior, and the path from a TradingView strategy to paper-traded webhook execution. If you have not picked an assistant yet, start with our guide to the best AI for Pine Script.

What Scalping Means Here

Short timeframes and intrabar fills

A scalping strategy operates on short chart intervals and often exits within a few bars. If a stop and target are both inside one historical bar's range, the order in which price supposedly reached them can determine whether the trade wins or loses.

Under Default Bar detalization, each historical bar is replayed as four ticks built from its open, high, low and close. The two middle ticks follow an OHLC or OLHC order, an assumed path rather than recorded trades.1 That assumption has greater influence on a short scalp than on a position held for several days.

Tight targets and stop placement

A target five ticks from entry leaves little room for fill assumptions. One simulated tick can change which exit triggers first or alter the recorded fill price.

Pine v6 also changed strategy.exit(). When related absolute and relative exit parameters appear together, v6 evaluates them instead of automatically ignoring the relative parameters as v5 did. Pine v6 then uses the level expected to trigger first.2 An assistant repeating older patterns may create behavior the user did not request.

Why AI code struggles

AI assistants frequently mix Pine versions. Common failures include adding the removed when parameter, relying on numeric values as booleans, or assuming old strategy margin defaults. Pine v6 removed when, requires explicit boolean casting where numeric values were previously accepted, and sets default long and short margin percentages to 100.2

Syntax is only part of the problem. AI output often leaves chart type, bar detail, commission, slippage, and execution timing unspecified. Those defaults can dominate a scalping backtest.

Prompting an AI for v6

Specify version and script type

Start with “Pine Script v6 strategy,” not “TradingView script.” Require a strategy() declaration and instruct the assistant to avoid constructs removed or changed by the v6 migration guide.

Also request explicit margin settings if leverage assumptions matter. Otherwise, v6's 100 percent default margin applies.2

Name exact inputs and conditions

Describe the system as a specification. Name each input, its default, and its unit. Define whether a crossover creates long trades, short trades, or both. State whether an opposite signal reverses, closes, or does nothing.

  • Fast EMA length: 9
  • Slow EMA length: 21
  • Stop distance: 8 ticks
  • Target distance: 12 ticks
  • Quantity: 1 unit
  • Entries: confirmed crossover or crossunder
  • Position rule: one open position

Require confirmed-bar execution

Require entry conditions to include barstate.isconfirmed. This prevents a crossover observed during an unfinished bar from becoming a confirmed signal unless it still exists at the close.

For separate alert() calls, request alert.freq_once_per_bar_close. Strategies normally recalculate at bar close unless calc_on_every_tick is enabled, but an explicit frequency communicates the intended behavior and avoids ambiguity.3

Declare costs and fill assumptions

Tell the assistant which commission model and slippage value to place in strategy(). If commission arguments are absent, the strategy applies no commission. Slippage defaults to zero and, when configured, is applied as a fixed number of ticks against each fill.4

The prompt should also name a standard candlestick chart and require tests under both Default and High Bar detalization. These are simulation assumptions, not strategy inputs.

A Worked Prompt and Fix

The prompt and first output

Example prompt: Write a Pine Script v6 strategy for a short-timeframe EMA crossover scalp. Use inputs named Fast EMA Length, Slow EMA Length, Stop Ticks, Target Ticks, and Quantity. Enter long on a confirmed fast-over-slow crossover and short on a confirmed crossunder. Use tick-based exits, one position at a time, 0.01 percent commission, two ticks of slippage, 100 percent long and short margin, and JSON alert_message values. Do not use removed v5 constructs. Assume standard candles and compare Default with High Bar detalization.

A typical first draft may still contain this obsolete pattern:

//@version=6
strategy("AI EMA Scalp", overlay = true)

fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
longSignal = ta.crossover(fast, slow)

strategy.entry("Long", strategy.long, when = longSignal)
strategy.exit("Long Exit", "Long", profit = 12, loss = 8)

Audit against v6 rules

This draft fails the requested audit. The when parameter was removed in v6, so the entry belongs inside an if block. It also omits confirmed-bar logic, short entries, quantity, margin, commission, slippage, and alert messages.

Search for other migration hazards as well: numeric expressions used directly as conditions, boolean values treated as na, and exit calls that combine relative and absolute prices without a deliberate reason.

The corrected v6 code

//@version=6
strategy(
    "Confirmed EMA Scalp v6",
    overlay = true,
    pyramiding = 0,
    commission_type = strategy.commission.percent,
    commission_value = 0.01,
    slippage = 2,
    margin_long = 100,
    margin_short = 100
)

int fastLength = input.int(9, "Fast EMA Length", minval = 1)
int slowLength = input.int(21, "Slow EMA Length", minval = 2)
int stopTicks = input.int(8, "Stop Ticks", minval = 1)
int targetTicks = input.int(12, "Target Ticks", minval = 1)
float orderQuantity = input.float(1.0, "Quantity", minval = 0.0001)

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

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

string longMessage = '{"ticker":"' + syminfo.ticker + '","action":"buy","quantity":' + str.tostring(orderQuantity) + ',"orderType":"market"}'
string shortMessage = '{"ticker":"' + syminfo.ticker + '","action":"sell","quantity":' + str.tostring(orderQuantity) + ',"orderType":"market"}'
string exitMessage = '{"ticker":"' + syminfo.ticker + '","action":"exit"}'

if longSignal and strategy.position_size == 0
    strategy.entry("Long", strategy.long, qty = orderQuantity, alert_message = longMessage)

if shortSignal and strategy.position_size == 0
    strategy.entry("Short", strategy.short, qty = orderQuantity, alert_message = shortMessage)

strategy.exit("Long Exit", from_entry = "Long", profit = targetTicks, loss = stopTicks, alert_message = exitMessage)
strategy.exit("Short Exit", from_entry = "Short", profit = targetTicks, loss = stopTicks, alert_message = exitMessage)

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

The declaration makes costs and margin visible, while the entry conditions require closed bars. The stop and target arguments are tick distances. Before reading the results, manually confirm Bar detalization, chart type, testing period, capital, and execution settings in Properties.

Where AI Gets Backtests Wrong

The emulator guesses bar paths

Default detail replays four ticks per historical bar. High detail, available on Premium and Ultimate plans, pulls OHLC data from a lower timeframe instead.4 A mapping table sets that timeframe: a one-minute chart uses 10-second data, or 24 simulated ticks per chart bar, not actual trade ticks.1

TradingView recommends testing the same strategy in both modes because a significant performance difference may indicate fragile entry or exit logic.1 More detail reduces dependence on a four-tick path, but it does not turn the test into a tick-by-tick market replay.

Costs default to zero

Omitted costs are especially damaging for strategies with frequent turnover and small gross outcomes per trade. Set commission and slippage before comparing parameter combinations, then inspect commissions in the report rather than assuming the declaration was applied as intended.

Synthetic charts distort fills

Strategies normally fill from the chart's OHLC values. On Renko, those are brick levels rather than market prices. Heikin Ashi prices are also synthetic, but its Properties panel offers a Standard bars mode that uses standard prices for fills.4

Use standard candles for the primary test. If synthetic charts contribute to signal generation, separate that research choice from the prices used to simulate execution.

Historical tick mode has limits

calc_on_every_history_tick was introduced in July 2026. It executes on every available historical tick, is restricted to standard charts, and is available to Premium and Ultimate users.5

The release notes say it allows more granular calculations and reduces the risk of lookahead bias.5 It is not a repainting fix: TradingView still warns that a strategy can fill orders differently once elapsed realtime bars become historical after a reload.4 Confirmed-bar logic and realtime validation remain necessary.

Scalping Strategy Review Checklist

Confirm settings before results

  • Compile with //@version=6.
  • Remove when and implicit numeric conditions.
  • Verify commission and slippage.
  • Use a standard chart.
  • Record Bar detalization mode.
  • Confirm margin, capital, quantity, and testing period.
  • Check that entries require confirmed bars.

Compare Default and High

Run the identical symbol, timeframe, date range, inputs, and costs in both modes. Compare trade count, average trade, drawdown, and which exits changed. A large gap means the strategy depends on intrabar sequencing and needs further investigation.

Read the full report

Do not stop at the equity curve. The strategy report's Metrics tab includes returns, commissions, trade analysis, drawdowns, and separate long and short columns. The Trades tab shows entry and exit prices plus trade-wise results.4

From Backtest to Live Alerts

Calls versus fill events

An alert() call represents script logic. An order-fill alert represents broker emulator execution. Without calc_on_every_tick = true, strategy alerts based on alert() execute at the bar close. Custom order messages are supplied through alert_message, with {{strategy.order.alert_message}} placed in the alert's Message field.3

Order-fill notifications apply only to orders executed on realtime bars. Historical fills do not send notifications.6

Fast signals can be throttled

TradingView stops a strategy alert if it triggers more than 15 times within three minutes.6 A fast system must account for that ceiling when selecting its timeframe and event types.

Send signals to a broker

A TradersPost webhook message can carry ticker, action, quantity, orderType, and optional stopLoss or takeProfit objects. TradersPost processes the signal using the strategy and subscription settings, then submits the resulting trade to the connected broker or exchange.

Set "test": true to process a test signal without sending an order to the broker. This checks JSON formatting and webhook routing separately from strategy logic. TradersPost is not designed for high-frequency trading: its documentation sets the 1-minute chart as the minimum timeframe and allows 60 webhook requests per minute and 500 per hour. A strategy that needs sub-minute bars or bursts of signals does not fit that workflow.

Connect a paper-trading account and compare TradingView's Alert Log with the received signals and paper orders before enabling live submission.

Account Rules and Scalp Frequency

Margin rules for intraday trades

FINRA replaced the pattern day trader provisions, including the trade-count designation and $25,000 minimum, with intraday margin requirements effective June 4, 2026. Brokerage firms may use a transition period through October 20, 2027.7

Under the new framework, a firm monitors whether account equity is adequate relative to positions during the trading day. Repeated failure to satisfy intraday margin deficits promptly can result in restrictions lasting up to 90 days.

Why scalping is affected

A strategy opening and closing frequent intraday positions interacts directly with this monitoring. During the transition, a firm may keep the old day trading rules or move to the new system sooner, and once it moves it can monitor in real time, compute requirements at the end of the day, or combine both.7

This is an account-mechanics issue, not trading or legal advice. Confirm the current margin policy, transition date, and automated-order rules directly with the broker holding the account.

Bottom Line

  • Prompt for a Pine Script v6 strategy() with named inputs and exact conditions.
  • Require confirmed-bar entries, explicit costs, margin, and alert messages.
  • Test standard candles under Default and High Bar detalization.
  • Audit the Metrics and Trades tabs instead of relying on the equity curve.
  • Validate alerts and webhook routing through paper trading before live submission.

AI can accelerate implementation, but it cannot decide whether the emulator's assumptions match the intended execution model. Use the broader AI for Pine Script guide for model-selection criteria, or compare how prompting changes for trend following, mean reversion, breakout and opening range, and momentum strategies.

Frequently Asked Questions

Does High use real ticks?

No. High Bar detalization uses mapped lower-timeframe OHLC bars. A one-minute chart, for example, uses 10-second data. It improves granularity but remains a simulation rather than actual tick-by-tick trade data.1

Why are trading costs zero?

A strategy applies no commission unless the declaration specifies commission settings. Slippage defaults to zero and must be entered as a fixed number of ticks applied unfavorably to fills.4

Can I test synthetic charts?

You can, but Renko and other non-standard charts fill from synthetic chart prices. On Heikin Ashi, select Standard bars in the Heikin Ashi mode setting to simulate fills with standard prices.8

How often can alerts fire?

An alert stops after more than 15 triggers within three minutes. Order-fill alerts are generated only for realtime executions, not historical fills.6

Does the $25,000 rule apply?

FINRA's new intraday margin requirements removed the PDT trade-count designation and $25,000 day-trading minimum effective June 4, 2026. Firms have until October 20, 2027 to transition, so confirm the rules currently applied by your broker.7

References

1 TradingView: Bar detalization
2 TradingView: To Pine Script version 6
3 TradingView: Alerts
4 TradingView: Strategies
5 TradingView: Pine Script release notes
6 TradingView: Strategy Alerts
7 FINRA: Understanding the New Intraday Margin Requirements
8 TradingView: Non-standard chart strategy results

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.