DEV Community

Lei Chen
Lei Chen

Posted on

I Replaced the Clock With a Trailing Stop. The Strategy Gained $109.65 — and the Exit Wasn't the Problem

TL;DR: Post #17 ended with a pre-commitment: same script, no limit, stop 2×ATR, no time exit — instead a trailing exit, trail = highest close since entry minus 2×ATR, trade closes when the close falls below it. The answer is in: net +$2,530.24, Profit Factor 1.302, in our testing — the best of the four exits, by $109.65 over the 10-bar clock. That margin is less than one average losing trade. The trail did keep the two long winners the clock cut short (#20: 59 bars, +$925.95; #14: 51 bars, +$1,883.80), and it saved three of the seven win-to-loss flips from #17. It also let four trades fall to the hard stop first (−$997.22 against #15), paid a median 156.60 points of give-back on every trail exit, and left the concentration worse than ever: the top 5 winners are 63.7% of gross profit, and net minus trade #45 is +$168.70. The exit was a problem. It wasn't the problem.

Clock 10 bars (#15) Clock 15 bars (#17) Clock 20 bars (#16) Trailing stop (#18)
Closed trades 48 48 48 48
Stop exits 18 21 24 19
Clock / trail exits 30 27 24 29
Net profit +$2,420.59 −$249.40 +$1,578.25 +$2,530.24
Profit Factor 1.378 0.967 1.200 1.302
Win rate 23 / 48 (47.9%) 18 / 48 (37.5%) 19 / 48 (39.6%) 19 / 48 (39.6%)
Gross profit +$8,830.95 +$7,207.18 +$9,469.73 +$10,908.26
Gross loss −$6,410.36 −$7,456.58 −$7,891.48 −$8,378.02
Avg win / avg loss $383.95 / −$256.41 $400.40 / −$248.55 $498.41 / −$272.12 $574.12 / −$288.90
Avg hold 7.77 bars 10.67 bars 13.31 bars 17.04 bars
Max equity drawdown $1,927.79 (19.02%) $2,191.46 (21.08%) $1,783.16 (17.44%) $1,881.50 (18.82%)
Top-5 winners' share 55.7% 55.6% 53.0% 63.7%
Net minus trade #45 +$88.60 −$1,425.16 +$100.47 +$168.70

The contract: one question, chosen before I looked

Post #17 pre-committed this test, word for word: same script, no limit, stop 2×ATR, no time exit — a trailing exit instead, trail = highest close since entry minus 2×ATR, trade closes when the close falls below it. The question it was built to answer was also fixed in advance: if the trail keeps the winners and cuts the six, the exit was the problem all along. If it doesn't, the entry is.

Three questions, in order:

  1. Does the trail keep the winners the clock cut short — and does it cut the six (seven, as counted) winners that flipped to losers between bars 10 and 15?
  2. What does the trail cost — in give-back, in trades that fall to the hard stop first, in fills?
  3. Is the best exit of the four actually a finding, or a fourth draw from the same noise?

The script is post #5's fixed RSI mean-reversion strategy, byte-identical apart from the exit block and the title string. Same 4,089 daily bars of CSI 300 (2010-01-04 → 2026-11-06), same $10,000, same PyneCore patched runtime, no commission, no slippage.

A trailing stop is not a machine for keeping winners. It's a machine for pricing how much of a run-up you're willing to hand back before you leave.

The one-line change, in Pine — the clock block out, the trail block in:

// Trailing exit: trail = highest close since entry minus 2xATR,
// recomputed each bar, tracked with a var so it only ever rises.
// The trade closes when the close falls below it. No time exit.
var float trailLevel = na
inTrade = strategy.position_size != 0
if inTrade
    trailLevel := na(trailLevel) ? close - atrVal * 2 : math.max(trailLevel, close - atrVal * 2)
else
    trailLevel := na

if inTrade
    strategy.exit("Exit Long", "Long", stop=strategy.position_avg_price - atrVal * 2)
    if close < trailLevel
        strategy.close("Long", comment="Trail exit")
Enter fullscreen mode Exit fullscreen mode

The wrong version and the right version of the same idea, one block apart:

if barsInTrade >= maxHold          // WRONG: exit because the clock ran out
    strategy.close("Long", comment="Time exit")

if close < trailLevel              // RIGHT: exit because price gave back 2xATR
    strategy.close("Long", comment="Trail exit")
Enter fullscreen mode Exit fullscreen mode

And the compiled Python, verbatim from the local compiler (node bin/pine2pyne.mjs, zero diagnostics) — the only lines that differ from the #15 run:

trailLevel: Persistent[float] = na
...
    if inTrade:
        trailLevel = ((close - (atrVal * 2)) if na(trailLevel) else math.max(trailLevel, (close - (atrVal * 2))))
    else:
        trailLevel = na
...
    if inTrade:
        strategy.exit("Exit Long", "Long", stop=(strategy.position_avg_price - (atrVal * 2)))
        if (close < trailLevel):
            strategy.close("Long", comment="Trail exit")
Enter fullscreen mode Exit fullscreen mode

Two mechanics worth stating before the numbers, because they decide what the numbers mean. First, the trail is judged on closes but paid at the next bar's open: strategy.close placed at bar b's close fills at bar b+1's open, so any overnight gap between the trigger close and the exit open is yours to keep. Second, the hard stop stays as the backstop — the trail can only exit at a close, the stop can exit intrabar, so on a fast fall the stop fires first and the trail never gets its chance. Both show up in the results below.

What you're checking here:

  • Does the trail keep the two long winners — or does it hand back more than the clock cost?
  • Of the seven flips from #17, how many does the trail actually save?
  • Is +$109.65 over the clock a finding, or noise with a nicer label?

Probe 1: the exit split — the trail column is the biggest winner and the biggest giver-back

Exit reason Trades Wins Net Avg per trade Avg hold
Stop (2×ATR) 19 0 −$6,428.11 −$338.32 6.3 bars
Trail (highest close − 2×ATR) 29 19 +$8,958.35 +$308.91 24.1 bars

Three things to read off this table before anything else.

The trail column is the largest winning column in the whole series. +$8,958.35 beats the 10-bar clock's +$8,199.14, the 20-bar's +$8,840.86, and the 15-bar's +$6,264.54. The trail's average exit (+$308.91) sits between the 10-bar clock (+$273.30) and the 20-bar (+$368.37) — and the trail's winners held 30.3 bars on average against 12.4 for its losers. The trail does what a trail is advertised to do: it lets winners run and cuts losers sooner.

The stop column is still winless, and still the strategy. 19 of 48 exits are stops, 0 wins, −$6,428.11. The stop column alone loses more than the trail column makes, and the net survives only because the trail column is bigger. Same shape as #15 (−$5,778.55 vs +$8,199.14), #16 (−$7,262.61 vs +$8,840.86), #17 (−$6,513.94 vs +$6,264.54 — the one run where the stop column won). The exit changed; the shape didn't.

Every trail exit pays give-back, and I measured it. Give-back = highest close since entry minus exit price, in points: median 156.60, mean 161.78, max 410.85 (trade #19). That is the price of the mechanism, stated as a number instead of a feeling: on a typical trail exit you hand back about 157 points from the best close you ever saw. The 10-bar clock's give-back was zero by construction — it never waited for a high — so the trail's +$109.65 net over the clock is after paying that toll on 29 exits.

Three verdicts hiding in that table:

The best exit of the four won by $109.65 — less than one average losing trade. Net +$2,530.24 against +$2,420.59 at 10 bars, and the Profit Factor went the wrong way (1.302 vs 1.378): gross loss grew faster than gross profit. If the trail were a real improvement, the PF would have moved with the net. It didn't.

The trail kept exactly two winners, and they are the whole improvement. Trades #20 and #14 (Probe 3) are the only structural change in the winner column. Everything else the trail touched, it mostly rearranged — the seven flips below are the receipt.

The stop column didn't shrink, it just changed tenants. 19 stops vs 18 at 10 bars, 21 at 15, 24 at 20. The trail didn't reduce the number of stop deaths; it moved four trades into the stop column that the clock used to exit by time (Probe 2).

Probe 2: the matched 49 — where the $109.65 came from, and the seven flips

The entry stream did not move at all: 49 entries in #15, #16, #17 and #18, identical bars, identical prices. The comparison is fully clean for the fourth time running: same entries, different exits, and every dollar of delta is an exit effect. The trail's trigger logic was also verified independently: all 29 trail exits match a recomputed trigger bar (first close below the running trail) plus a next-bar-open fill, 29/29, no mismatches.

Transition (#15 → trail) Trades Dollar delta Point delta
TIME → TRAIL 26 +$1,571.07 +466.58 pts
TIME → STOP 4 −$997.22 −450.72 pts
STOP → TRAIL 3 +$125.02 +21.31 pts
STOP → STOP 15 −$589.23 +0.00 pts
OPEN → OPEN 1 — —
Total 49 +$109.65 +37.17 pts

Read the point column before the dollar column — the rule from #15. The trail's whole advantage over the clock is +37.17 points across 49 trades. In dollars it looks like +$109.65 only because the trail run was richer by the time the late trades entered (see the sizing note below). The STOP → STOP row is worth exactly what it was worth in #15 (+0.00 pts), and the −$589.23 is sizing only: trades #21, #22 and #48 entered with 3 contracts in the trail run against 2 in #15 — same entry prices, same exit prices, same bars — because the trail run's equity was higher by January 2016, so percent-of-equity sizing bought one more contract, and the same stop cost 1.5× as much. The equity path cuts both ways: it made the trail run richer, and it made its stop deaths more expensive.

Against #16 the trail gains +$951.99; against #17 it gains +$2,779.64. Both are mostly the 15/20-bar clock being bad, not the trail being good — the trail's margin over the best clock is the $109.65 that matters, and it is noise-sized.

Now the seven flips — the trades that were winners at bar 10 and losers at bar 15 in #17. The trail was built, on the record, to cut these:

Trade #15 (10 bars) #17 (15 bars) Trail Verdict
#19 +$463.82 −$373.76 −$75.78 (hold 16) Softened, still a loss
#31 +$266.12 −$8.21 +$25.54 (hold 13) Saved
#23 +$434.67 +$1.08 +$9.18 (hold 14) Saved, barely
#39 +$192.94 −$47.90 −$54.24 (hold 13) Same loss
#44 +$12.94 −$123.70 +$12.94 (hold 10) Saved — identical exit to #15
#13 +$53.13 −$86.96 +$16.50 (hold 11) Saved
#16 +$83.12 −$3.68 −$229.04 (hold 11) Made worse

Three saved, one identical, two still losses, one made worse. That is not "the trail cut the six." That is a coin flip with a mechanism attached. Trade #44 is the cleanest save — the trail fired at hold 10 for exactly #15's exit price (+$12.94 to the cent) — and trade #16 is the cleanest failure, which gets its own section below. Trade #19 deserves one line: it ran to a highest close of 4,250.81, gave back 410.85 points (the largest give-back in the run), and still lost $75.78. The trail watched the biggest run-up in this group and handed back most of it.

The other side of the ledger — the four trades the trail lost to the stop, that the 10-bar clock used to exit by time:

Trade #15 (TIME, 10 bars) Trail (STOP)
#6 −$169.20 −$274.48 (hold 11)
#12 −$62.85 −$244.92 (hold 11, gap)
#27 +$131.50 −$254.08 (hold 17)
#33 −$5.90 −$330.19 (hold 22)

−$997.22 in total, and #27 is the one that hurts: a winning trade at bar 10 that the trail held until the stop took it at bar 17. The trail is judged on closes; when price falls fast enough to hit the stop intrabar, the trail never gets to speak. A close-based exit is slow by construction, and four trades paid for that slowness.

Probe 3: the two winners the trail kept, and the one trade it broke

Trade #20 — the trail's best case. Entry 2015-08-28 @ 3,246.24. The 10-bar clock took −$112.50; the 15-bar clock took +$132.26; the trail held 59 bars and took +$925.95, the third-biggest winner in the run. Highest close in the trade: 3,840.35; the trail finally fired on 2015-11-27 (close 3,556.99, exit at the next open 3,554.89), handing back 285.46 points. This is the trade the whole probe was built for: a winner the clock would have cut short, kept for two extra months, and exited with most of the move intact.

Trade #14 — the other one. Entry 2012-12-03 @ 2,136.70, held 51 bars to +$1,883.80, the second-biggest winner. Highest close 2,775.84, give-back 168.19 points. The longest hold in the run is trade #24 at 64 bars (+$600.88, vs +$257.36 at 10 bars).

Trade #16 — the war story, and the gotcha in the mechanism. Entry 2013-07-05 @ 2,227.35. It ran to a highest close of 2,326.69 — up 99 points — and the trail sat 2×ATR below that high. On 2013-07-19 the close fell to 2,190.48, below the trail: trigger. The exit filled at the next bar's open, 2,170.09 — 20.39 points below the trigger close. Result: −$229.04, against +$83.12 at the 10-bar clock and −$3.68 at 15 bars. The trail was right about the direction and still lost $229, because the trail is judged on closes and paid at opens, and the open gapped down through the gap between the two. The give-back on this trade was 156.60 points — exactly the run's median — which is the point: #16 isn't an outlier, it's the median trade with a gap on top. A trailing stop doesn't exit at the trail. It exits at the next open after the trail breaks. On a gap day, those are different prices, and the difference is yours.

Trade #45 — still the strategy. Entry 2024-09-20 @ 3,192.43, exit at hold 9 for +$2,361.54 — the biggest winner, and the best exit of the four runs for this trade (#15: +$2,331.99 at hold 10; #16: +$1,477.78 at hold 20; #17: +$1,175.76 at hold 15). It ran to a highest close of 4,256.10 on the 2024-09-30 spike and gave back 276.49 points before the trail fired on 2024-10-09. Net minus #45 is +$168.70 — positive, and better than #15's +$88.60, but the concentration check still fails: the top 5 winners are 63.7% of gross profit, the worst share in the series. Remove one trade and the strategy is a rounding error above breakeven. Four exits in, nothing has changed that fact.

What I couldn't verify

  • Costs. No commission, no slippage, same as every post in this series. The trail run trades 48 times in 16 years with an average hold of 17 bars, so costs would bite less here than on a fast strategy — but "less" is not a number, and I haven't run it with costs.
  • Whether the trail distance is special. 2×ATR was inherited from the stop, not chosen. A 1×ATR trail would fire sooner and pay less give-back; a 3×ATR trail would hold longer and pay more. I didn't test either, because the series rule is one change at a time — and because #17 already showed what happens when you tune a number on the same 49 trades.
  • Whether the entry has any edge at all. Four exits, same 49 entries, net ranging from −$249.40 to +$2,530.24 — the exit moves the result by $2,779.64 while the entry never changes. That is the question this post cannot answer, and it is the next post. It is fixed before I look: same trail exit, same 2×ATR stop, entries on a fixed schedule with no price information at all — every 83rd bar (bar_index % 83 == 0, from bar 83), 49 entries, same count as the RSI stream. If the clockwork entries land anywhere near +$2,530, the RSI crossover is not doing the work.
  • Out of sample. Same 4,089 bars as every post in the series. Nothing here has been tested on data the script hasn't already seen.

Bottom line

The trailing stop is the best exit of the four — net +$2,530.24, PF 1.302, in our testing — and the margin over the 10-bar clock is $109.65 on 49 trades, with the Profit Factor moving the wrong way and the concentration getting worse. It kept two long winners (#20, 59 bars; #14, 51 bars), saved three of the seven flips, softened one, and broke one (#16, −$229.04 on a gap between trigger close and exit open). It also let four trades fall to the hard stop that the clock used to exit by time, and charged a median 156.60 points of give-back on every trail exit. The answer to #17's question is: the exit was a problem, not the problem — the trail fixed the clock's impatience and introduced its own slowness, and the strategy is still one trade deep (net ex-#45: +$168.70). The entry is next, and the test is already fixed: 49 entries on a clock with no price in it at all.


Have you ever replaced an exit rule and found the improvement was smaller than one losing trade? I read every comment — the exit-rule stories are what the next posts are built from.


This conversion work was done by Pine2Py, the tool I build for exactly this job: paste a Pine script, get PyneCore-flavored Python back, diagnostics included when something can't be translated. The runtime is the open-source PyneCore project, with a patched build we ship for the two constructs stock PyneCore doesn't handle — details are on the site. It's free to try — every account gets 3 conversions, no card — and Pro is $12/month if you end up converting a whole library. No return promises, ever: a translator moves your logic, it doesn't make it profitable.

Top comments (6)

Collapse
 
kamalmosadegh profile image
Kamal Mosadegh •

Excellent pre-commitment discipline, Lei — and the number that matters most to me is not the +$109.65, it is the stop column staying winless in all four variants: 19 stops, 0 wins, -$6,428.11 here. When the same exit bucket loses in every run, that is no longer an exit-tuning problem; it is the entry putting trades in positions where the 2xATR stop is the most likely outcome. A trailing stop can only reprice that, not fix it.

Two measurements I would add before touching the trail distance. First, report give-back as a distribution per trail exit, not just the median 156.60 points — how much of it is concentrated in the few long holds like #20 and #14, versus a steady tax on every exit? If most give-back sits in the winners, a tighter trail may cost more than it saves. Second, run the trail-distance sensitivity you flagged: 1x, 2x and 3xATR on the same 49 entries, and watch whether the stop count or the give-back moves first. If the stop count barely moves, the entry is doing the damage.

The clockwork-entry placebo test in your 'couldn't verify' section is the decisive next step, in my view. If entries every 83rd bar land anywhere near +$2,530, the RSI crossover is not carrying the strategy — and no exit rule, trailing or otherwise, can manufacture edge the entry does not have. Looking forward to that one. — Kamal

Collapse
 
leichenbuilds profile image
Lei Chen •

Thanks, Kamal — and good news on the decisive test: it's now post #19 (dev.to/leichenbuilds/i-replaced-th...). The clock made +$706.11, PF 1.092, against the RSI's +$2,530.24 / 1.302 — so the RSI is doing real work ($1,824.13), but the clock also made money, and both runs stay one trade deep (net ex-biggest: RSI +$168.70, clock −$2,110.71).

On the give-back distribution — I ran it on the #18 run: 29 trail exits, total 4,691.68 points, mean 161.78, median 156.60. It's a steady tax, not a winners' tax: the top 5 exits are 30.7% of the total, #20 + #14 together only 9.7%, and the 19 exits held under 25 bars account for 67.9% of all give-back (mean 167.55, actually above the long holds' 150.82). 17 of 29 exits sit in the 100–200 point band; only one is above 300 (#19, 410.85 — and that trade lost $75.78). So a tighter trail wouldn't mostly save money on the long winners; it would shave a similar amount off nearly every exit while firing earlier on the trades that pay for the run. That doesn't settle whether 1xATR nets better — only running it does.

On the sensitivity: agreed, and it's queued — one change at a time, so the costs test (#20, 0.1% per round trip) goes first since it's already pre-committed, then the 1x / 2x / 3x trail-distance run on the same 49 entries, watching stop count vs give-back exactly as you framed it.

Collapse
 
kamalmosadegh profile image
Kamal Mosadegh • • Edited

Thanks for running both, Lei — the clock result is the honest surprise here: the RSI does real work, yet both runs are still one trade deep, with the clock at −$2,110.71 and the RSI at only +$168.70 once the biggest trade is removed, so the edge claim rests on a single trade for now. Your give-back breakdown settles my earlier worry nicely — a steady tax across exits, not a winners' tax — though the 90th percentile would still help show how heavy that tail is. The remaining check I'd love to see is a random-entry placebo with the same trailing exit, since the clock entries are periodic and could carry their own rhythm; if random entries also land near the RSI result, the exit is doing the work, and if they don't, the entry earns its keep.

Thread Thread
 
leichenbuilds profile image
Lei Chen •

The 90th percentile is 267.28 points. Full distribution, 29 trail exits, in our testing: median 156.60, mean 161.78, 75th percentile 180.65, 90th 267.28, 95th 281.87, max 410.85 (trade #19). Buckets: 6 exits handed back ≤100 points, 17 handed back 100–200, 6 handed back more than 200. So the typical trail exit costs about 157 points from the best close — but one exit in ten costs more than 267, and the tail is where the mechanism really bites. That spread is the honest version of "the trail lets winners run": it does, and it charges a toll that varies a lot.

The random-entry placebo is a good call and it's queued — it's the next control after the trail-sensitivity test (1×/2×/3×ATR, already promised, next post). Design, fixed before I run it: same script, same exits, entries drawn at random with a fixed published seed so it's reproducible, same 49-entry count as the RSI stream. The question it answers is the one you put your finger on: whether the clock's periodicity itself is doing any work, or whether any 49 entries through this exit machinery land in the same place. If the random entries land near the clock's +$706, the exit is doing the work; if they land near zero, the clock's regularity matters more than it looks.

Thread Thread
 
kamalmosadegh profile image
Kamal Mosadegh •

That distribution is more damning for the trail than the median suggested: p90 at 267.28 against a median of 156.60, and the single worst toll — 410.85 on #19 — was charged to a trade that lost $75.78. So the most expensive give-back in the run bought no winner at all; 'the trail lets winners run' is true on average and false at the tail, which is where the money is.

One normalisation I'd add before the 1x/2x/3x run: report give-back as a share of each trade's own maximum favourable excursion, not just raw points. A 267-point toll on a trade that ran 300 points is a different mechanism from the same toll on one that ran 2,000 — the first says the trail distance is the problem, the second says it's just the price of the exit existing. Raw points can't separate those.

On the placebo design: fixed seed, published in advance, same 49 entries — that's the right pre-commitment. I'd add one more before you run it: state the verdict thresholds now. How close to the clock's +$706 counts as 'the exit is doing the work', and how close to zero counts as 'the entry earns its keep'? Deciding that after seeing the number is how placebos quietly turn into supporting evidence.

Thread Thread
 
kamalmosadegh profile image
Kamal Mosadegh •

Thank you for running the full distribution — this is exactly the table the original post needed. The bucket shape is the story: 17 of 29 exits in the 100–200 band means the typical experience is 'give back ~157 and accept it', but the 6 exits above 200, and #19 at 410.85, are a different animal. That is not trailing-stop cost; that is a trend that kept extending while the stop trailed a fixed distance behind the best close. One split worth trying: recompute the same buckets with the trail distance expressed as a multiple of ATR at entry. If the >200 bucket concentrates in high-ATR entries, an ATR-scaled trail compresses the tail without touching the median. If it does not, the tail is structural and no exit rule fixes it — which would prove your title from the other side.