Load candles through the proxy you already have
By the end of this lesson you will have loadCandles in src/lib/backtest/candles.ts, which pulls a symbol's whole history in one call and keeps it on disk with the date it was pulled, a test proving that a mistyped ticker's plain-text 404 arrives as a message rather than a crash, and the row count of your own history.
Nothing new to build for data. Your proxy from Build Your First Tool already forwards to the API with the key on the server side; a backtest is one more route through it.
The shape
A daily bar from /eod/AAPL.US, captured live:
{"date":"2026-08-24","open":311.47,"high":313.36,"low":309.97,"close":310.34,"adjusted_close":310.34,"volume":34673600}
Seven fields, one row per trading day, oldest first. A bare array this time — not the data envelope the screener used. Two endpoints from one vendor with two different shapes is normal, and it is why the normalisation you wrote in Build Your First Tool belongs at the boundary rather than inside a component. Which shape you will get is in the reference beside each entry, so it is a thing to look up before you write the parser rather than a thing to discover from a stack trace after.
Note the two closes. close is what printed that day; adjusted_close is that price rewritten for every split and dividend since. Which one a backtest uses is the subject of two later lessons, and it is the single most common way a beginner's results become nonsense.
What one call costs
Measure it rather than assume it, the same as always. Here is the measurement, taken today:
- One
/eodcall for five days: the counter moved by 1. - One
/eodcall for forty-five years — 11,516 rows, from 1980-12-12 to 2026-08-24: the counter moved by 1.
Range is free. The expensive axis in a backtester is instruments, not time. Build Your First Tool and Build a Screener both taught that cost follows requests — reload frequency in the watchlist, one call per row in the screener's N+1. The same rule holds here, and the consequence is new: since a request buys any range, pull the whole history once and cache it with the date you pulled it — then refresh deliberately after an ex-dividend or a split, because the adjusted column is rewritten each time. A cache here is a dated snapshot, not the truth.
A second measurement worth having: ten consecutive reads of the usage meter (/api/usage in your app) left the counter unmoved at 1424, so on this account the meter itself is free. Check it on yours — it takes thirty seconds and it changes how often you can afford to look.
The failure the proxy must handle
Ask for a symbol that does not exist and the API answers:
HTTP 404
Ticker Not Found.
Plain text. Not JSON. So await res.json() throws a SyntaxError, which is a different failure from the one your error handling expects, and it happens on the most ordinary mistake there is — a typo in a ticker.
This is exactly what the res.ok check from Build Your First Tool was for, and here is the concrete payoff: check res.ok first, read the body as text on failure, and surface "Ticker Not Found" to the person who typed it.
Cache it on disk, not in memory
A backtest run reloads the same history dozens of times while you iterate. Write the fetched series to a local file keyed by symbol and range, and read from there when it exists.
Two reasons, and the second is the real one. It saves calls, obviously. But it also makes your research reproducible: the run you did on Tuesday used exactly the bytes you still have, so a result you cannot explain can be re-derived rather than argued about.
Try it now
Pull the full history of one symbol through your proxy and count the rows. Then request a deliberately misspelled ticker and watch what your error handling does with a plain-text 404 — if you get a white screen or a silent empty chart, fix that before writing any strategy code. The loader below is where that fix lives, and a test is how you know it holds.
The prompt
Mock mode on (EODHD_MOCK=1 in .env.local; if you set it in the screener course it is already there, so change nothing) and restart. Plan mode on, then paste:
Plan first and wait for my yes. Add loadCandles(symbol) in
src/lib/backtest/candles.ts. It asks through the transport function
in src/lib/market.ts that the watchlist and the screen share (find
it there, whatever it is called), for eod/{symbol} with no date
range: the whole history in one request.
Narrow the answer to bars that carry all seven fields (export their type
as Bar: date, open, high, low, close, adjusted_close, volume), and throw if
they are not oldest-first, in an exported assertOldestFirst(bars) that
later code can reuse. Keep the answer on disk under .cache/eod/
with the date it was pulled, read that file when it exists, never
read or write it in mock mode, and add .cache/ to .gitignore. A 404
arrives with a plain-text body: make that transport keep a body that
is not JSON as text, and have loadCandles return it as a message. Before you
write the request, tell me what one live load costs with
estimateCalls(). Tests first in tests/candles.test.ts, with fetch
stubbed: a 404 whose body is "Ticker Not Found.", and the fixture read
in mock mode. Run npm test and npm run check:leak, then show me the diff.
A good answer states the cost first — one call per load, whatever the range — then adds src/lib/backtest/candles.ts and tests/candles.test.ts, changes src/lib/market.ts and .gitignore, and ends with both commands green.
Check it yourself
estimateCalls("eod/...")gave 1 before any request was written, and nothing in the loader asks for a date range.npm testandnpm run check:leakare green, the two new tests among the passes. Stopnpm run devbeforecheck:leakand start it again afterwards: the check runsnext buildinto the same folder the dev server uses.- After
npm testthere is still no.cache/folder: the mock-mode test read the fixture and wrote nothing. Invented bars never land where live ones are trusted. - Go live once, through your proxy, with your own free key: the shared
demokey answers 403 Forbidden forSPY.US(it servesAAPL.US,MSFT.USand a few more), so withdemocountAAPL.USinstead and expect about 11,500 rows. Switch mock off, restart, and have the agent count the rows atlocalhost:3000/api/proxy/eod/SPY.USand print the first: one call. Expect as many rows as your plan has history — about 250 for a year. Each row has this shape, captured live for AAPL on 2026-08-24:
Put mock mode back on afterwards. The misspelled ticker needs no call at all: the 404 test sends the API's own plain text through your code.{"date":"2026-08-24","open":311.47,"high":313.36,"low":309.97,"close":310.34,"adjusted_close":310.34,"volume":34673600}
Break it on purpose
In src/lib/market.ts, read the error body with await res.json() instead and run npm test. The 404 test goes red: the plain text throws a SyntaxError inside the transport, and depending on where yours catches it the test sees the API reported as unreachable or a bare 404 with no message, never "Ticker Not Found.". A typo in a ticker, disguised as a network failure, caught by a test instead of by you. Restore the line and run it again: green.
Compare with ours
Our loader, the decisive lines
// src/lib/backtest/candles.ts
if (!isMock()) {
const cached = await readCache(file); // .cache/eod/, with pulledAt
if (cached) return { ...cached, cached: true }; // the second load costs nothing
}
const result = await marketGet(`eod/${symbol}`, params, toBars); // whole history, one call
if (!result.ok) {
// a 404 returns { notFound: "Ticker Not Found." }; anything else, the failure itself
}
const pulledAt = new Date().toISOString();
if (!isMock()) await writeCache(file, { pulledAt, bars: result.value });
toBars drops any row missing one of the seven fields and ends in assertOldestFirst(bars). Our transport is marketGet, as the screener course named it; src/lib/market.ts gains readBody: the parsed JSON when the body is JSON, the trimmed text when it is not. The full state at the end of this unit is on the starter's branch ref/backtest-strategies/u1.
Checkpoint
npm test && npm run typecheck
git status # only the files this step touched, no .env*
git add -A
git commit -m "Load candles through the same transport, cached on disk with the date pulled"
Then answer this lesson's questions.