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.
Marketing
Getting AI to write a Pine Script DCA strategy works only when the prompt defines how entries accumulate, how position size is capped, and how exits apply to the combined position. Ask for generic DCA code and an AI assistant may omit pyramiding, mismatch entry IDs, reserve too much exit quantity, or generate outdated Pine syntax.
The practical goal is not to accept the first script. It is to produce a precise Pine Script v6 draft, audit its order mechanics, and test its alerts before live execution. For broader prompting and code-review techniques, see this guide to the best AI for Pine Script.
What This Strategy Category Covers
Dollar-cost averaging explained
FINRA defines dollar-cost averaging as investing equal portions at regular intervals regardless of current market conditions.1 In Pine Script, that usually becomes repeated same-direction strategy.entry() calls triggered by a time or bar schedule.
This differs from a single lump-sum entry by design. The strategy must track when another addition is due, calculate its quantity, and prevent additions after reaching the configured cap.
Grid strategies as scale-ins
A grid adds at specified price levels instead of fixed time intervals. A long grid might add whenever price falls another configured percentage below its previous entry or reference level. Both grids and scheduled DCA strategies use repeated entry calls, so they share the same pyramiding, capital, and exit-reservation constraints.
Scaling positions in and out
Scaling in means adding through multiple same-direction entries. Scaling out means using multiple strategy.exit() calls with qty or qty_percent. Pine does not redesign later exit quantities to match your intended allocation. Each call reserves part of the position, so quantity management must be explicit.2
Prompting AI for Pine Script v6
Pin version and inputs
Start the prompt with //@version=6. Pine v6 changed strategy defaults and removed patterns used by v5 scripts, including the when parameter on applicable strategy functions.3
Name each required input and its type. For a scheduled scale-in, request input.int() for the interval and maximum entries, plus input.float() for dollars per entry. Include defaults, minimum values, and maximum values rather than allowing the model to choose them.
Require confirmed-bar logic
State the exact trigger and require barstate.isconfirmed when repainting is unacceptable. TradingView alerts operate on realtime bars, and confirmed-bar logic prevents a developing bar from producing a signal that disappears before its close.4
Define whether entries occur every fixed number of bars, at a timestamp interval, or after a price step. If you are experimenting with intrabar behavior, say so explicitly. Do not let the assistant silently choose between backtest convenience and live consistency.
Specify per-order alert messages
Require a distinct alert_message on every entry and exit. Order-generating strategy functions accept custom messages, making it possible to distinguish each fill event downstream.4
Clear names matter when messages are routed to TradersPost. Its JSON webhook can contain fields including ticker, action, quantity, and quantityType. Use messages that identify whether a fill represents an addition, partial exit, or final exit.
Worked Example: Prompt to Code
The prompt used
A useful prompt for this example is:
“Write a long-only Pine Script v6 strategy that invests a configurable dollar amount every configurable number of confirmed bars. Use input.int() for interval bars and maximum entries, and input.float() for dollars per entry. Cap entries at four. Set pyramiding explicitly. Calculate quantity as dollars per entry divided by close. Add two scale-out exits at 5% and 10% above strategy.position_avg_price, each closing 50%. Match every exit to the entry ID. Add distinct JSON alert_message values to entries and exits: the first entry uses action buy, later entries use action add, and entries send the dollar amount with quantityType set to dollar_amount.”
Auditing the first draft
Review the response before compiling it. The three highest-priority checks are:
- Confirm
pyramidingis greater than one and consistent with the entry cap. - Confirm every
from_entryvalue exactly matches a real entry ID. - Confirm combined exit percentages do not exceed 100% of the position.
Also inspect whether the exit prices use strategy.position_avg_price. That variable updates with the average price of the current position, which is the relevant reference after several entries accumulate.5
The corrected v6 script
//@version=6
strategy("Confirmed-Bar DCA Scale-In", overlay = true, pyramiding = 4, margin_long = 100, margin_short = 100)
int intervalBars = input.int(20, "Interval bars", minval = 1)
float dollarsPerEntry = input.float(1000.0, "Dollars per entry", minval = 1.0)
int maxEntries = input.int(4, "Maximum entries", minval = 1, maxval = 4)
bool scheduledBar = bar_index % intervalBars == 0
bool canEnter = barstate.isconfirmed and scheduledBar and strategy.opentrades < maxEntries
float entryQty = dollarsPerEntry / close
string entryAction = strategy.position_size == 0 ? "buy" : "add"
string entryMessage = "{\"ticker\":\"" + syminfo.ticker + "\",\"action\":\"" + entryAction + "\",\"quantity\":" + str.tostring(dollarsPerEntry) + ",\"quantityType\":\"dollar_amount\",\"message\":\"dca_scale_in\"}"
string exitOneMessage = "{\"ticker\":\"" + syminfo.ticker + "\",\"action\":\"exit\",\"quantity\":50,\"quantityType\":\"percent_of_position\",\"message\":\"dca_exit_1\"}"
string exitTwoMessage = "{\"ticker\":\"" + syminfo.ticker + "\",\"action\":\"exit\",\"message\":\"dca_exit_2\"}"
if canEnter
strategy.entry("DCA Long", strategy.long, qty = entryQty, alert_message = entryMessage)
if strategy.position_size > 0
float targetOne = strategy.position_avg_price * 1.05
float targetTwo = strategy.position_avg_price * 1.10
strategy.exit("Exit 1", from_entry = "DCA Long", limit = targetOne, qty_percent = 50, alert_message = exitOneMessage)
strategy.exit("Exit 2", from_entry = "DCA Long", limit = targetTwo, qty_percent = 50, alert_message = exitTwoMessage)
plot(strategy.position_size > 0 ? strategy.position_avg_price : na, "Average entry", color = color.orange)
The declaration creates a hard ceiling of four entries, while the input lets the user choose a lower operational cap. Both exits reference DCA Long, and their percentages reserve the complete position without exceeding it. The script is a mechanics example, not a claim of profitability.
The webhook messages follow the receiving side's rules rather than copying Pine's quantities. The first entry sends buy and later entries send add, because TradersPost rejects an add when no position is open. Entries send the dollar amount with quantityType set to dollar_amount, so the quantity is calculated from the dollar figure instead of a long decimal share count. The second exit sends a plain exit with no quantity: percent_of_position is measured against the position still open, so a second 50% message would close only half of what remains.
Common AI Mistakes
Pyramiding defaults to one
The pyramiding parameter defaults to one. Additional same-direction strategy.entry() calls therefore do not increase the position unless the declaration raises that value.2 Fix the omission by setting a deliberate ceiling and enforcing any lower user-selected cap in entry logic.
Entry IDs and exit reservation
A strategy.exit() call with from_entry creates exits only for trades carrying that exact ID. If nothing matches, no exit order is created. Each exit call also reserves part of the open position, leaving only the unreserved portion available to later calls.2
OCA groups and netting
Exit orders belong to a strategy.oca.reduce group by default, so another exit in the group is reduced when one fills. Meanwhile, strategy.order() ignores properties such as pyramiding and nets its filled quantity against the open position. It does not provide the reversing behavior of strategy.entry().2
That makes strategy.order() a poor substitute when the prompt expects pyramiding to cap grid additions. Use it only when net order arithmetic is intentional.
V6 trims older trades
Pine v6 retains the latest 9,000 trades and trims the oldest instead of stopping the strategy, a change introduced in November 2024.6 Trimmed trades leave the report, calls to strategy.closedtrades.* for them return na, and strategy.closedtrades.first_index identifies the first retained trade.3
A Review Checklist for Scale-Ins
Entry logic checks
- Match the pyramiding ceiling to the maximum possible additions.
- Use
strategy.entry()when same-direction entries should accumulate. - Verify available capital covers every planned addition.
- Require confirmed bars when live signals must not repaint.
Pine v6 sets the default long and short margin percentage to 100, so planned scale-ins must fit within the strategy’s simulated funds unless leverage or margin settings are deliberately changed.3 Since July 2026 the Properties tab shows these settings as Long and Short leverage inputs, while margin_long and margin_short still work in code.
Exit logic checks
Verify every from_entry string, total all reserved exit quantities, and decide how open entries should close. With multiple entries, close_entries_rule controls closing order, which can also change the average price of what remains open.
Backtest report checks
Estimate whether the test can exceed 9,000 trades. Deep Backtesting preserves access to a larger historical test range and is available on Premium and higher plans, with limits of up to two million bars and one million trades.7 In the strategy report, review individual entries and exits alongside drawdown and capital usage.
What Research Says About DCA
FINRA on DCA tradeoffs
FINRA notes that a fixed schedule can reduce emotional decisions and that temporarily uninvested funds can limit losses during a significant decline. It also says DCA often produces lower returns than lump-sum investing, especially over longer periods, and repeated commissions or fees can erode returns.1
Academic evidence is mixed
The conventional academic view has treated DCA as inferior to rational lump-sum alternatives. Brennan, Li, and Torous found that uninformed investors using DCA to add individual stocks to an existing portfolio were better off than if they followed the traditionally recommended rational strategies.8 That finding concerns a specific investor and portfolio context, not every coded scale-in system.
Why coding assumptions matter
Profit factor, drawdown, and trade returns in a Pine strategy report describe hypothetical simulated performance. Treat AI-generated results as debugging evidence, not a forecast. Mixed DCA evidence makes it more important to inspect the schedule, costs, position cap, testing period, and exit assumptions embedded in the prompt.
From Chart to Live Execution
Confirmed signals and messages
Alerts trigger only on realtime bars. The alert() function supports frequencies including alert.freq_once_per_bar_close, while order-generating calls can attach a separate alert_message to each order.4 Recreate any running alert after changing the script or its inputs because TradingView saves a snapshot when the alert is created.
Route signals through webhooks
A TradersPost signal is a JSON webhook. Subscription settings determine whether values such as quantity and order type come from the signal or are replaced by settings for that subscription. Multiple subscriptions can apply different sizing rules to your own broker accounts that receive the same signal. A repeated buy while already long is rejected unless the subscription enables Allow add to position, which is why the example sends add for later entries.
Paper trade before going live
Run the corrected strategy against a paper or simulated account first. Compare TradingView’s alert log, the trades in the strategy report, webhook logs, and resulting order quantities. Repeat the review after Pine migrations or material input changes.
Once the entry IDs, quantities, and confirmed-bar behavior match your design, connect the alerts to a broker through a TradersPost webhook and keep the first deployment in paper trading until the complete signal path behaves as expected.
Bottom Line
- Prompt for Pine Script v6, typed inputs, confirmed bars, and exact entry conditions.
- Set pyramiding explicitly and do not use
strategy.order()as an interchangeable scale-in command. - Match every exit to a real entry ID and keep reserved quantities within the open size.
- Audit alert messages and paper trade the full route before enabling live execution.
AI can accelerate drafting, but it cannot replace order-level review. Use the broader best AI for Pine Script guide to compare prompting workflows, then apply this checklist to every DCA, grid, or scale-in script you generate.
Frequently Asked Questions
Why does my position not grow?
Pyramiding defaults to one, so additional same-direction entries are blocked. Set pyramiding to the intended ceiling and confirm the script uses strategy.entry(). A script using strategy.order() ignores pyramiding rather than obeying that cap.
How do DCA and grids differ?
DCA adds equal portions at scheduled intervals regardless of market conditions. A grid adds at specified price levels. Both can use repeated strategy.entry() calls and require deliberate pyramiding, quantity, and exit-reservation logic.
Does DCA beat lump sum?
Not consistently. FINRA says DCA often has lower returns over longer periods, although gradual deployment can reduce emotional decisions and limit exposure during declines. The result depends on the investor, costs, market path, and use case.
How many trades can v6 test?
Regular Pine v6 strategy results retain the latest 9,000 trades and trim older ones. Deep Backtesting supports up to two million bars and one million trades for eligible plans.
Why did an exit not fire?
Its from_entry value may not match an open trade, or an earlier exit call may have reserved the available quantity. Compare entry IDs exactly and total every qty or qty_percent allocation.
References
1 The Benefits and Limitations of Dollar-Cost Averaging
2 TradingView Pine Script Strategies
3 Migrating to Pine Script Version 6
4 TradingView Pine Script Alerts
5 TradingView Strategy FAQ
6 Pine Script Release Notes
7 How Deep Backtesting Works
8 Dollar Cost Averaging