Contents Lesson 7 of 19

11 min read · professional

Entries and exits, as a state machine

By the end of this lesson you will have positions that change one bar after the signal, the strategy's curve beside buy and hold, a table of its first ten trades (about three on the invented year) checked against the bars by eye, and a test that fails if anyone deletes the one-bar shift.

A signal is a boolean per bar. A position is something you hold across bars. Converting one into the other is where the second big class of bug lives.

Signal is not position

signal:    false false true  true  true  false false
position:  0     0     0     1     1     1     0

Look at bar 3. The signal turns true, and the position is still zero. That single column shift is the honest part: the signal was computed from that bar's close, so the earliest you could act is the next bar.

Holding from bar i+1 means your first return is bar i+1's move, which is the same as buying at bar i's close, the price the signal was computed from. That is this unit's fill model, and it is generous: it assumes you could trade at the very price you have only just seen. Unit 3 replaces it with the next open and measures the difference.

Line them up instead — position 1 on the same bar the signal fires — and you have bought at a price you only knew about after the close. It is the same look-ahead leak as lesson 1, wearing different clothes, and it is much harder to see because both columns look plausible.

Signals are computed on bar i; positions change on bar i+1. Write that as a comment above the loop, because it is the line people delete during a refactor.

Three states, not two

Model it explicitly:

type Position = { units: 0 | 1; entryBar: number | null };

Four transitions, and each deserves a named branch: flat and no signal (do nothing), flat and signal (enter next bar), held and signal (hold), held and no signal (exit next bar). Writing them as four branches rather than one clever ternary makes the diff readable and the edge cases obvious.

The edges that get missed, in order of how often:

  • The last bar. An open position at the end of the series needs closing at the final price, or the return is never realised.
  • The first bar. No previous bar, so no signal, so no position.
  • A gap in the data. A missing day is not a signal change, and treating it as one produces phantom trades.

Count the trades and look at them

Your backtester must record every trade: entry date, entry price, exit date, exit price, return. Not for the report — for you, now.

Then read the first ten by eye against the price series. This takes five minutes and it catches things no summary statistic will: entries at prices that never traded, exits before entries, two positions open at once, a trade held for zero days.

A curve is a summary. A trade list is evidence. When the two disagree, the trade list is right.

Ask, then read

Generated state machines are usually correct on the main path and wrong at the ends. Read the diff for: does the loop start at index 1 or 0; is the position shifted by one bar; is the final open position closed; what happens when two signals fire on consecutive bars.

Try it now

Print your first ten trades as a table (up to ten: the 20/50 rule makes only about three on the invented year) and check each entry price against the actual bar. Then deliberately remove the one-bar shift and watch what happens to the total return. The size of that jump is how much your backtest would have lied by, and it is usually larger than any edge you were hoping to find.

The prompt

Mock mode on, plan mode on. Paste this with the two-row trace from the lesson under it:

Plan first. Add src/lib/backtest/positions.ts: positions(signals), one
per bar, where a signal on bar i changes the position on bar i+1 and a
null signal means no position; and trades(bars, positions), written
as four named transitions (staying flat, entering, holding, exiting),
not one expression. A trade records entry date and price, exit date
and price, and its return. For now it fills at the raw close of the
signal bar i (the bar whose signal changed; the first day held is bar
i+1), and the return comes from adjusted closes.
A position still open on the last bar is closed there. Add
runStrategy(bars, params) in src/lib/backtest/strategy.ts, returning
the signals, the positions, the trades, a gross curve, and a net one
that pays costBps on every position change, the forced close on the
last bar included. On the page, draw the strategy's gross and net lines
beside buy and hold's on the same chart (update any older test that
counted two lines), list up to the first ten trades, and add the net
total return and trade count to the run log's result. Tests first in tests/positions.test.ts, with
the trace below as literals. No request. Run npm test, then show me
the diff.

A good answer adds positions.ts, strategy.ts and the test, changes the page, and reproduces the trace exactly: the first position on the bar after the signal turns true.

Check it yourself

  1. The trace test holds the lesson's rows as literals, and the signals false false true true true false false come out as positions 0 0 0 1 1 1 0.
  2. In mock mode the trade table runs in date order: no exit before its entry, never two trades open at once, none held for zero days.
  3. Pick three trades and have the agent print the fixture's bars on their entry dates — no call. Each entry price is the raw close printed on its entry date, and the first day held is the next bar.
  4. If the series ends with the signal on, the last trade exits on the last bar.
  5. Mock off — the cache answers, so no call — and open the defaults once. The run log's line for them now carries a total return and a trade count. Copy that result into PLAN.md beside the defaults, as the last lesson promised. This needs a history cached from a live load on your own free key; on mock nothing is logged, so copy the total return and trade count from the page instead and say in PLAN.md that they are the invented year's.

Break it on purpose

In mock mode, so the leaked run never reaches your log, remove the one-bar shift and run npm test: the trace test goes red. Look at the page as well — the jump in total return is the size of the lie. Put the shift back: green.

Compare with ours

Our positions and the four transitions
// src/lib/backtest/positions.ts
// Signals are computed on bar i; positions change on bar i+1.
export const positions = (signal: (boolean | null)[]): (0 | 1)[] =>
  signal.map((_, i) => (i > 0 && signal[i - 1] === true ? 1 : 0));

for (let i = 1; i < bars.length; i++) {
  const was = position[i - 1], now = position[i];
  if (was === 0 && now === 0) continue;                // flat, no signal: nothing
  else if (was === 0 && now === 1) entry = i - 1;      // enter at the signal bar's close
  else if (was === 1 && now === 1) continue;           // held, signal on: hold
  else trades.push(trade(bars, entry, i - 1));         // exit at the close it turned off
}
if (position.at(-1) === 1) trades.push(trade(bars, entry, bars.length - 1));

trade() takes prices from the raw close and the return from adjusted_close. The full state at the end of this unit is on the starter's branch ref/backtest-strategies/u2.

Checkpoint

npm test && npm run typecheck
git status   # only the files this step touched, no .env*
git add -A
git commit -m "Positions one bar after the signal, every trade recorded, the last one closed"

Then answer this lesson's questions.