Pine Script development: why the strategy doesn't work
A strategy on Pine Script shows a smooth rising curve in the tester, but on a live account — a series of losses.
The issue is almost never the market: the tester plays back history on the same bars on which the code calculates the signal, and all logic errors are simply invisible. We break down why a beautiful history doesn't carry over into real trades.
The first reason is over-optimization. When five or six parameters with a small step are selected against history, out of thousands of combinations there is bound to be one that fits past data perfectly: it describes not market behavior but the noise of a specific segment.
The sign is simple — the result stays in a very narrow corridor of values: move a parameter by one step, and the drawdown increases several times over. Such a strategy falls apart on the very first new bars.
The second is that entry and exit logic diverge from execution. The signal is calculated on the bar close, and the order is sent at that same price, although in practice entry occurs at the open of the next bar or at the worst price during volatility.
This also includes the absence of commission, spread, and slippage: with frequent trades, costs eat up the entire edge. Separately, we check repainting — values that recalculate on an unclosed bar and retroactively "confirm" the entry.
Because of this, stops and targets tied to the extremes of the current bar also suffer. To understand where exactly the logic breaks, we run the strategy on a segment that did not participate in tuning, check parameter robustness, and only then add realistic costs. The order is reversed: first honest data and execution, then selection.
What a strategy tested on history and on new data gives
The difference between a strategy that holds up and one that falls apart in the first new month is visible not by profit but by a set of checks. We fix them before the start: if an item is not met, the hypothesis goes back for revision, not into trading.
Below is what the client sees in the report for each strategy on Pine Script, the language of the TradingView platform.
- Drawdown on history and on new data is comparable. A divergence deeper than a quarter is a sign of fitting; such parameters do not go into operation.
- Parameters are not at the edge of the range. Shifting each value by a step in both directions does not flip the result.
- Costs are included in the calculation. Commission, spread, and slippage are calculated on real volumes — otherwise the report will show a return that will not exist on the account.
- The result holds across different assets and market regimes, not on one lucky segment.
- Testing on new data comes after freezing the rules. Further tuning is prohibited: otherwise it is fitting, not testing.
- The run is reproducible. The same dataset and commissions produce the same report — the result can be rechecked.
- A hypothesis is tested in one run, not in a week of manual work: the test harness and template scaffolds are already assembled.
Such a set of checks gives the strategy robustness on new data and cuts off weak hypotheses before trading. Drawdown stops being a surprise, and decisions on parameters rely on measurements, not beliefs.
Comparison of approaches: indicator, robot, portfolio of strategies
The implementation format determines not only the amount of code but also how the logic will survive a change in market regime.
The same signal, assembled as an indicator, as a standalone robot, or as a set of strategies under common capital management, behaves differently during drawdown, connection loss, and data recalculation on new bars.
Below are three options among which people actually choose, with the honest limitations of each in terms of robustness and maintenance cost.
Options and their limits
| Option | When it fits | Limitations of the approach |
|---|---|---|
| Indicator strategy | Visual verification of a hypothesis on history and on a live chart is needed; a human makes the decision | Signals are visible but do not execute themselves: the result depends on the operator's discipline, and manual entry loses to slippage |
| Trading robot | The logic is formalized, entry and exit conditions are unambiguous, operation without human involvement is needed | One scenario per instrument: when volatility changes, the rules become outdated, requiring regular retuning and execution control |
| Portfolio of strategies | Several independent logics share capital; robustness through diversification matters | Debugging and accounting for correlations is more difficult: strategies may duplicate each other, and risk is calculated on the aggregate position |
Separation also works in the opposite direction: some limitations are removed if the indicator is left for control and execution is handed to a robot.
Such a hybrid is encountered more often than pure options, and during assessment we start from which approach the client is ready to maintain.
Pine Script development: stages from schema to handover
The stages of strategy development are the same for an indicator and for a strategy with multiple conditions. First the hypothesis is turned into testable rules, then into a schema, and only then into code — otherwise the logic is imperceptibly fitted to a beautiful chart.
- Hypothesis formulation. We fix the market, timeframe, entry and exit condition, risk rule, and signal cancellation point. Criteria like "strong trend" are replaced with measurable ones: moving average slope, distance from a level, volume.
- Logic schema. We describe position states: entry, holding, reversal, partial close. Separately — behavior at the session boundary: this is where expectations and results most often diverge.
- Implementation. We write the strategy in Pine Script: parameters are exposed in settings, calculation is performed on a closed candle, trading conditions are separated from plotting — behavior is reproducible and does not depend on repainting.
- Historical run. We look not only at return: drawdown, share of profitable trades, distribution of results by periods, number of trades. A dozen trades is not yet statistics.
- Robustness check. We change timeframe and instrument, shift parameters by a step, look at a segment that did not participate in tuning. If the result falls apart from a small shift, the rule is overfitted.
- Code audit. We check the calculation for look-ahead bias, position size, accounting for commission and slippage, and handling of data gaps.
- Handover. Source code with comments, description of parameters and their bounds, known limitations, connection procedure.
Each stage ends with an artifact: schema, code, test report, instruction. From them it is clear what the conclusions are based on and what exactly to change when the market changes.
What we hand over: code, verification report, documentation
The strategy remains with you in a form that does not require our involvement: the code can be read and changed, calculations are reproducible, decisions are explained.
The delivery composition is the same for a new strategy and for reworking an existing one — only the scope changes.
- Pine Script strategy source code — complete, with comments on the logic of entries, exits, and position management. Not a closed library, but a file that can be read line by line and modified for your hypothesis.
- Testing report — a run on historical data in different market regimes: sustained trend, sideways market, sharp moves. The report records the run parameters, drawdown, share of profitable trades and their number, so that the result can be repeated.
- Risk management description — how position size is calculated, how a losing streak is limited, under what conditions the strategy stops.
- Strategy documentation — the purpose of each parameter, safe value ranges, applicability boundaries. It is enough for a new engineer to understand it without communicating with the code author.
- Maintenance regulations — what to check and how often, how to transfer the logic to another instrument or timeframe, how to record changes between versions.
- Set of checks and test data — a reproducible calculation: after any edit, it is clear what exactly changed in the strategy's behavior.
- Decision log — which hypotheses were tested and rejected, and for what reasons. This saves time during the next revision.
Case: how we reduced drawdown and removed over-optimization
A strategy on TradingView came to us working: 14 parameters selected for a specific segment of history, a smooth income curve, and a drawdown of about 18% on it. On new data the picture diverged — drawdown increased to 42%, and some periods went negative.
The parameters described not market behavior but the noise of one lucky segment, and this is classic fitting to history.
What we changed
We analyzed which parameters actually affect the result and which merely adjust entry to the past. Four turned out to be redundant — they were removed; three were combined into one volatility filter.
The final entry logic is described by six parameters instead of fourteen, and each of them is checked for meaning, not for the beauty of the chart.
Next — robustness testing: runs across several instruments and different candle intervals, rolling windows, and sequential testing on segments that the strategy did not see during tuning.
Such a run shows not the best curve but the spread of the result: how much the outcome depends on a randomly chosen period.
After the rework, the historical result became more modest, but the divergence between history and new data shrank from more than three times to 1.2.
Maximum drawdown decreased from 42% to 16%, the share of profitable periods grew from 48% to 61%, and shifting one parameter no longer flips the test outcome.
The main effect is predictability: it is clear under which conditions the strategy works and when it needs to be switched off.
How historical verification differs from demo account trading
Historical testing and a demo account answer different questions. The first shows whether the logic of a Pine Script strategy is reproducible on past data; the second — whether it survives real execution.
In history, the signal appears on the bar close and is executed at that same price, while on demo, time passes between the bar close and the order reaching the server, and the entry price is already different.
The divergence in results consists of several layers: spread and commission, slippage on fast moves, different data quality on lower timeframes, gaps at session open.
A separate cause is intrabar filling: if the logic relies on the candle's high and low, the historical result is more optimistic than is achievable in real time.
The norm is when the number of trades and their direction on demo match, and only return and drawdown diverge, and even then within limits explainable by costs.
A defect is when the sign of the result changes, some trades disappear or appear more often than in history, or the report shows entries at prices that did not exist at that moment. This is no longer execution error but an error in logic or data.
We select the verification period so that it captures a trend, sideways market, and a high-volatility segment; otherwise the strategy looks robust simply because the market was uniform.
We reconcile trade logs line by line by time and price, and calculate costs as a separate line — then it is clear at which layer the result is lost and what to fix: entry conditions or the execution model.
Technical doubts: data, commissions, slippage
A profitable strategy on history diverges from reality more often not because of entry logic but because of costs and tester assumptions. Below are the questions we close before considering backtest results reliable.
How are commissions included in the calculation?
Commission is charged both on entry and on exit, and rates differ for limit and market orders. In the tester we set both and add them to the trade price — otherwise the return curve is inflated more strongly the more often the strategy trades.
How is slippage modeled?
Execution at an ideal price is an illusion: the tester has no real order queue. We set slippage in ticks or as a share of the spread; in a thin market, the divergence from history becomes noticeable.
Which venue limits change the result?
Minimum price step, volume rounding, limit on the number of active orders, and position size. A strategy that places volume above the limit actually receives partial execution — the tester metrics diverge from trading.
How do you check the quality of historical data?
We check for gaps in candles, duplicates, and breaks at session boundaries. If the data is not aligned to the venue's time, the test inflates the result and the strategy will not repeat it on a live account.
Let's discuss the task and come back with an estimate and plan
So that the analysis does not stretch over weeks, it is enough to send a short description: instrument and working timeframe, entry and exit logic, method of calculating risk per trade.
If there is already work in progress — a strategy file, historical run log, and list of trades whose results raise questions. This is enough to discuss the task substantively and come back with an estimate and work plan, rather than with clarifying questions in circles.
What we fix in the plan before the start:
- entry, exit, and protective order transfer rules — with formulas, not "by eye";
- position size, its step of change, maximum drawdown per trade and per series of trades;
- historical dataset for testing, including trending segments and prolonged sideways market;
- list of checks: commission, slippage, missed bars, behavior at market open;
- acceptance metrics: share of profitable trades, profit factor, maximum drawdown, average holding time;
- delivery composition: strategy code, comments on logic, instructions for launch and parameter setup;
- strategy maintenance conditions: what edits we make when the market regime changes and within what timeframes.
We agree on the plan items before the first line of code — then the result can be checked by numbers, not discussed by taste. Describe the task in any convenient form: we will come back with an estimate, work plan, and boundaries of strategy maintenance.







