BLUF – Putting two crypto spot exchanges (Binance.US and Kraken), a retail US stock broker (Charles Schwab), and a historical equity feed (Databento) behind one C++23 interface meant stopping every provider quirk at the edge. Inside Kestrel, a strategy never sees BTCUSDT, XXBTZUSD, or BRK/B, and never cares whether it is trading 24/7 crypto or NYSE market hours. Getting there meant taming Kraken’s legacy symbol codes and its HTTP-200 error arrays. It meant surviving Schwab’s 7-day OAuth refresh deadline without restarting a live process, and building a US equity calendar that doesn’t blindly trust a broker’s holiday table. And it meant documenting every place where live API responses disagreed with the official specs.
In this post:
- One Seam For Market Data and Orders (
DataSource,TradingVenue, and Normalized Symbols) - Two Crypto Spot Exchanges, Two Very Different Personalities (Binance.US and Kraken)
- Surviving Charles Schwab’s 7-Day OAuth Refresh Cycle (Without Stopping a Live Run)
- Teaching a 24/7 Engine About US Equity Market Hours
- Where Live Schwab Behavior Disagreed With the Docs (and Why Databento Joined the Lineup)
- Conclusion
In the first post in this series, I introduced Kestrel, a C++23 library and CLI tool for pulling stock and crypto market data, backtesting strategies, paper trading, and executing live orders. The full source is on GitHub if you want to follow along in the code. In the second post, I covered the multi-model AI workflow and C++ guardrails that kept the codebase clean, and in the third post, I walked through fixed-point Decimal math, unknown-outcome order recovery, HTTP session pooling, and TimescaleDB quote batching.
Today I want to look at the integration boundary itself: what it actually took to make Binance.US, Kraken, and Charles Schwab (plus Databento for historical equity backtests) behave like a single, predictable system.
As before, nothing here is financial advice. This post is about getting four very different market APIs to speak the same language without shooting your account in the foot.
One Seam For Market Data and Orders (DataSource, TradingVenue, and Normalized Symbols)
The temptation when you integrate your first exchange is to let its vocabulary leak everywhere: passing raw JSON around, assuming markets never close, or baking BTCUSDT into strategy configs. By the time you add a second crypto exchange and a traditional equity broker, that approach turns every strategy into a pile of if (provider == ...) branches.
Kestrel splits market connectivity into two narrow interfaces, wired together in a single place (src/factory.cpp):
-
data::DataSource(include/kestrel/data/data_source.hpp) owns the read side:GetBars,StreamQuotes,StreamBars,GetTrades(where supported),GetSymbolInfo, andHours(). -
trading::TradingVenue(include/kestrel/trading/trading_venue.hpp) owns the write and account side:PlaceOrder,PlaceOco,CancelOrder,CancelAll,GetOpenOrders,GetOrder,GetFills,GetPositions,GetBalances, andStreamExecutions.
Because market data and execution are separate interfaces, switching [general] mode from "live" to "paper" doesn’t touch the data source or the strategy. CreateComponents() still builds the provider’s real DataSource, and simply swaps the live TradingVenue for PaperTradingVenue, which matches orders locally against the live quote stream with configurable fees, slippage, and latency:
Provider ([general] provider) |
Market | Paper / Import Credentials | Market Data | Live Trading Status |
|---|---|---|---|---|
binanceus |
Crypto spot | None | REST + WebSocket quotes, closed bars, public trades | Live (run, order, cancel) |
kraken |
Crypto spot | None | REST (latest 720 bars) + v2 WebSocket quotes | Written & read-checked live; run gated by [kraken] live_trading = true
|
schwab |
US stocks & ETFs | App key/secret + OAuth token file | REST + single-socket SchwabStreamer + daily bar poller |
Market orders & live run tested Nov 13, 2026; run gated by [schwab] live_trading = true
|
databento |
US stocks & ETFs (historical) | API key for HTTP import (none for local CSVs or backtest) |
Imported into TimescaleDB (kestrel_app databento) |
None (historical import + backtest only) |
Stopping Symbol Quirks At the Edge
Every provider has its own opinion on what to call an asset (src/data/symbols.cpp). Inside Kestrel, a crypto pair is always BASE/QUOTE (BTC/USD, ZEC/USDT) and an equity ticker uses a dot for share classes (AAPL, BRK.B). Provider classes convert on the way out and normalize on the way back in:
-
Binance.US strips the slash (
BTCUSDT). On the way back in,FromBinanceUSSymbolsplits concatenated pairs against a known quote list ordered longest-first soUSDTandUSDCmatch beforeUSD. -
Charles Schwab writes equity share classes with a slash (
BRK/Binstead ofBRK.B). If you sendBRK.Bto Schwab’s/pricehistory, it doesn’t return an error; it quietly returns zero bars. -
Kraken accepts
"BTC/USD"on outbound calls (ToKrakenSymbol), so Kestrel sends one clean format everywhere. Kraken’s responses, however, span three different naming eras at once. Its v2 WebSocket sends"BTC/USD",OpenOrdersandQueryOrdersreturn concatenated aliases like"XBTUSD"and"XDGUSD"(Bitcoin asXBT, Dogecoin asXDG), andOHLC,AssetPairs,BalanceEx,TradeVolume, andTradesHistorystill emit legacy 4-letter codes (Xfor crypto,Zfor fiat:XXBTZUSD,ZUSD,XZEC).
That legacy Z prefix on Kraken hides a fun trap. If you naively split concatenated symbols by matching "ZUSD" or "ZEUR" at the end of a string, you will chop the trailing 'Z' right off Tezos (XTZUSD becomes XT/USD) and Chiliz (CHZUSD becomes CH/USD). FromKrakenSymbol explicitly checks 8-character legacy pairs (XXBTZUSD, USDTZUSD) against the 17 legacy codes before running longest-first quote suffix matching. On the balance side, FromKrakenAsset maps XXBT to BTC and ZUSD to USD, while keeping Kraken Rewards and staking suffixes (like .F and .S) distinct so locked yield balances aren’t mistaken for tradable spot coins.
Scoping Safety Layers Between the Strategy and the Venue
Strategies never talk directly to a TradingVenue. In Runner‘s constructor (src/strategy/runner.cpp), Kestrel wraps the venue in up to three TradingVenue decorators:
textStrategy -> OrderTracker -> SessionGatedVenue -> RiskGatedVenue -> Venue
OrderTracker is always present so Runner can poll active orders. SessionGatedVenue is inserted whenever a market has closing hours (Schwab and Databento), and RiskGatedVenue wraps the venue whenever [risk] is configured (optional in paper mode, mandatory in live run).
Cancels and read calls pass straight through every layer so a strategy can always pull its orders down. On every live venue, GetOpenOrders, GetFills, and CancelAll also filter strictly to the configured [general] symbols. If you hold a long-term ETF or a manual limit order on another ticker in the same brokerage account, Kestrel’s startup cleanup and kill switch leave it untouched.
Two Crypto Spot Exchanges, Two Very Different Personalities (Binance.US and Kraken)
You might expect two US-accessible crypto spot exchanges to look nearly identical in code. Beyond both running 24/7 (MarketHours::AlwaysOpen()), almost everything underneath them works differently.
Binance.US: Merged Streams, Schema Drift, and Request-Weight Math
Unauthenticated market data on Binance.US is straightforward, with a few wrinkles worth handling cleanly (src/data/binanceus_data_source.cpp and src/data/binanceus_quote_stream.cpp):
-
Merging top-of-book and trade streams: Binance.US’s
@bookTickerWebSocket stream fires on every best-bid/ask change but carries no last-trade price or timestamp.@tradecarries each print and whether the buyer was the maker ("m").BinanceUSQuoteStreamsubscribes to both on one combined stream URL, andBinanceUSStreamMergerfolds each event into the latest per-symbol state. EveryQuotedelivered toRunnerorQuoteWritergets the complete picture, including which side took liquidity (on Binance,"m": truemeans the buyer was the maker, so the seller was the taker). -
Filter name drift across listings: In
exchangeInfo, older pairs advertise minimum order value under aMIN_NOTIONALfilter, while newer listings useNOTIONAL.GetSymbolInfochecks both. -
Paginating public trades (
aggTrades): Forkestrel_app trades --store, Binance.US caps time-boundedaggTradesqueries at 1 hour and 1,000 trades, and refusesfromIdifstartTimeandendTimeare also present. When a volatile 1-hour window hits 1,000 prints,BinanceUSDataSource::GetTradesdrops the time parameters and pages forward byfromIduntil trade timestamps cross the hour boundary, then resumes 1-hour slices.
On the live trading side (BinanceUSTradingVenue), two operational limits matter most right now:
-
order --testdoesn’t check balances:POST /api/v3/order/testvalidates signatures, symbol filters, tick/lot precision, and price bands, so Kestrel wires it up behindkestrel_app order --test. Just keep in mind that Binance.US will happily accept a test sell for coins your account doesn’t hold. -
Polling fills is expensive in request weight: Until Kestrel’s WebSocket user-data stream lands (
TODO.md#3), live runs poll REST for fills and order updates every second. On July 30, 2026, Binance.US raised the weight ofGET /api/v3/myTrades(with a symbol) to 20 , plus 3 foropenOrderswhile an order is active. At 1 Hz, that burns roughly 1,380 weight per minute per symbol while orders are working against the conservative2,400/mincap Kestrel enforces (out of6,000/minadvertised). Single-symbol live runs fit comfortably; multi-symbol live runs would need a longerRunnerOptions::fill_poll_intervaluntil pushed executions replace polling.
Kraken: HTTP-200 Errors, 720-Bar Caps, and Starter-Tier Budgets
Kraken (KrakenDataSource, plus KrakenTradingVenue written by Gemini 4 Carbon and reviewed by Opus 5.5 in commit 99c153f) has its own set of rules:
-
HTTP 200 doesn’t mean the call succeeded: Kraken’s REST API routinely returns HTTP
200 OKwith{"error": ["EOrder:Insufficient funds"]}in the JSON body, alongside"W..."warning strings that aren’t fatal. Every response parser inspectserrorfirst, ignoresWentries, and mapsEprefixes (EAPI:Rate limit,EOrder:Post only,EService:Market in ...,EAPI:Invalid nonce) intotypes::ErrorCategorysoutil::Retryand the risk gate react properly. -
Hard 720-bar OHLC history limit: Kraken’s public
OHLCendpoint only retains the newest 720 candles of any timeframe (12 hours of 1-minute bars, or 30 days of hourly bars). Silently returning 720 bars when a backtest asked for six months would produce garbage results, soKrakenDataSource::GetBarsreturnskUnsupportedwhenever a full first page starts after the requestedstarttime. WhenRunnerwarms up a strategy at startup,data::RecentBars(src/data/recent_bars.cpp) catcheskUnsupportedand binary-searches the lookback span in whole-bar steps to grab as much history as Kraken actually keeps. -
Signing and strict nonce serialization: Private calls to
/0/private/*signuri_path + SHA-256(nonce + form_body)withHMAC-SHA512using the base64-decoded secret. As I noted in the last post, when a Kraken API key’s nonce window is zero, two concurrent threads whose requests cross on the network will tripEAPI:Invalid nonce. To prevent that,KrakenTradingVenue::SendOnceholdsmSendMutexacross both microsecond nonce generation andmHttp->Send(). -
Starter-tier rate budgets: Kraken’s Starter tier gives private calls a counter of 15 that decays at just 0.33 points/second , and each
TradesHistorycall costs 2. To stay inside that refill rate,factory.cppslows Kraken’s live fill poll to 15 seconds and its risk-gate watch to 30 seconds (0.20/sidle, rising to~0.27/swhile an order rests). -
All-or-nothing fill pagination:
GetFillspages throughTradesHistory(with_cursor=true,limit=100), steppingstartback 1 second so fractional-second timestamps aren’t clipped. If page 2 or later fails or stalls its cursor,GetFillsfails the entire call rather than returning partial fills. Otherwise, callers would advance theirsincecursor to the newest fill on page 1 and permanently skip the unread older pages. -
Post-only and fee flags: Every Kraken order carries
oflags=fciqso fees are charged in the quote currency rather than leaving fractional dust on base-asset sells (as I covered in the second post). For post-only limit orders (oflags=post,fciq), ifAddOrderrejects synchronously withEOrder:Post onlyKestrel maps it toErrorCategory::kWouldTake. More commonly on Kraken, the engine accepts a crossing post-only order with atxidand immediately cancels it with reason"Post only order", whichParseOrderrewrites toOrderState::kRejected(delivered viaOnOrderUpdate) on the next poll.
Surviving Charles Schwab’s 7-Day OAuth Refresh Cycle (Without Stopping a Live Run)
Crypto API keys sit quietly in secrets.toml until you revoke them. Charles Schwab’s individual Trader API uses browser-based OAuth 2.0 across two developer-portal products ( Market Data Production and Accounts and Trading Production ), and even paper trading requires valid OAuth tokens just to fetch bars or open a quote stream.
Two clocks govern every Schwab session (include/kestrel/data/schwab_auth.hpp and src/data/schwab_auth.cpp):
-
Access tokens last 30 minutes.
SchwabAuth::AccessToken()renews them 5 minutes before expiry (kRefreshMargin), serialized under a mutex so concurrent data and trading threads don’t stampede the token endpoint. If a call still gets HTTP401,SchwabApi::Sendinvalidates that token and retries once. -
Refresh tokens last 7 days, and renewals do not extend them. Confirmed on the live API: refreshing an access token keeps the original 7-day countdown from when you logged in via
kestrel_app authorize. Once fewer than 3 days (72 hours) remain,SchwabAuthlogs an error saying how long is left, and if the login runs out mid-run it logs another (starting up inside the final 24 hours also logs a countdown warning). Because those notices go out as error lines,runand--storerecorders forward them straight to Discord instead of leaving them buried in a log file. And if you start a command with an expired refresh token, or Schwab refuses a renewal (invalid_grantorrefresh_token_authentication_error, handled defensively since a revoked token’s exact live body hasn’t been seen yet), Kestrel logsSCHWAB RE-AUTHORIZATION REQUIREDwith the exact command to run.
Side Note: One tiny UX snag bites almost everyone the first time they use Schwab’s OAuth flow. After you approve access in the browser, Schwab redirects to your callback URL with a code= parameter ending in %40 (a URL-encoded @). Paste that code into a token exchange without percent-decoding it first and Schwab rejects it. SchwabCodeFromRedirect accepts either the full pasted redirect URL or a bare code and runs PercentDecode automatically.
Hot-Swapping Tokens While run Is Live
The 7-day hard cap created a nasty operational race that showed up during review (fixed in commit 21aab88).
Suppose kestrel_app run is running a multi-day swing strategy. Four days in, you see the 72-hour expiry alert in Discord, open a second terminal, and run kestrel_app authorize to write fresh 7-day tokens into schwab_tokens.json. Ten minutes later, the already-running run process hits its routine 25-minute access-token renewal, refreshes using the old refresh token it still holds in memory, and writes its renewed token struct back to schwab_tokens.json. Without coordination, it just overwrote your brand-new 7-day login with one that expires in three days!
Fixing that cleanly took coordination in both SchwabTokenStore (src/config/schwab_token_store.cpp) and SchwabAuth:
-
Atomic
0600writes withfsync:WriteTokensnever writes to the token file in place. It creates<file>.tmp.<pid>.<counter>with mode0600(O_CREAT | O_EXCL), writes the JSON,fsyncs the file descriptor, atomicallyrenames it over the token file, andfsyncs the parent directory. Readers see either the old file or the new one, never a half-written file and never world-readable permissions. -
Directory-locked
SaveUnlessSuperseded: Before saving a routine renewal,SchwabTokenStore::SaveUnlessSupersededtakes an exclusiveflockon the parent directory (DirectoryLock, leaving no stray lockfiles behind) and checks what is currently on disk:
cpptypes::Result<std::optional<SchwabTokens>>SchwabTokenStore::SaveUnlessSuperseded(const SchwabTokens& t) const { const DirectoryLock lock(mPath); if (auto file = Load(); file && file->refresh_expires_at > t.refresh_expires_at) { return std::optional<SchwabTokens>(std::move(*file)); } if (auto written = WriteTokens(mPath, t); !written) { return std::unexpected(written.error()); } return std::optional<SchwabTokens>();}
-
Seamless live adoption:
SchwabAuthalso callsAdoptNewerAuthorization()before renewing, and again whenever its in-memory refresh token is expired or refused (even Schwab’s WebSocket streamer waits and reconnects once a fresh token lands on disk). You can runkestrel_app authorizeonce a week whilerunorstreamstays up without dropping a single position or restarting the process.
On the account side, Schwab’s trading URLs never take raw account numbers; they require an encrypted hashValue from GET /accounts/accountNumbers. SchwabTradingVenue::AccountHash() resolves [schwab] account_number once, masks account numbers to **** 1234 in every log message, and sets HttpRequest::label to .../accounts/{account}/orders/{id} so neither account hashes nor order IDs ever touch logs or the venue_latency table.
Teaching a 24/7 Engine About US Equity Market Hours
Crypto strategies can assume the market is open at 03:00 UTC on Sunday. Put a stock strategy on that same assumption and it will try to fire orders into a closed exchange, panic when zero quotes arrive over the weekend, or come up short on warm-up bars when “the last 16 hours” of 30-minute candles spans Sunday night. (data::RecentBars handles closed gaps at live startup by doubling its lookback window until it collects the full warmup_bars count, and LoadReplayData counts a backtest’s warm-up across open sessions rather than calendar days.)
Rather than sprinkle US equity checks through strategies, DataSource::Hours() returns a types::MarketHours (include/kestrel/types/market_hours.hpp and src/types/market_hours.cpp). Crypto data sources return MarketHours::AlwaysOpen(). Schwab and Databento use a two-layer calendar.
Layer 1: Local Rules (UsEquityCalendar)
UsEquityCalendar computes NYSE/Nasdaq trading sessions directly using C++20’s std::chrono::locate_zone("America/New_York"):
-
Sessions: Regular hours (
09:30to16:00ET, or13:00on early closes) and Schwab’s extended hours (07:00to09:30pre-market, and regular close to20:00, or17:00on early-close days). -
Holidays & edge rules: Covers weekends and all ten NYSE holidays, including Good Friday (via Meeus’s Gregorian Easter algorithm) and Juneteenth starting in 2022. It handles standard Friday/Monday weekend observance—including NYSE’s quirky rule that when New Year’s Day falls on a Saturday, the Friday before (
Dec 31) stays open. It also encodes13:00early closes (Black Friday, July 3, and Christmas Eve) and a table of unscheduled NYSE closures since September 11, 2001 (kSpecialClosures: 9/11, Hurricane Sandy, and national days of mourning through January 9, 2025).
Layer 2: Why SchwabCalendar Only Lets the Broker Restrict a Day
Rules in code can’t know about an unscheduled closure announced tomorrow morning, so SchwabCalendar (src/data/schwab_data_source.cpp) cross-checks upcoming dates against Schwab’s GET /markets?markets=equity&date=YYYY-MM-DD on a background thread (returning UsEquityCalendar‘s answer immediately so callers never block on HTTP).
Why not skip UsEquityCalendar and just trust GET /markets? Because when I tested GET /markets against 2027 dates in November 2026, Schwab reported every single 2027 NYSE holiday as a normal open trading day. They populate next year’s holiday schedule late.
Because of that, SchwabCalendar treats local rules as the ceiling and only allows Schwab’s API to restrict a session (close a day, open later, or close earlier):
cpp// Only dates the rules open are asked about. Schwab can only// restrict them: each time from whichever is more restrictive.const auto rules = mRules.On(date);std::optional<types::TradingDay> chosen;if (*schwab && rules) { types::TradingDay day{ std::max((*schwab)->pre_open, rules->pre_open), std::max((*schwab)->open, rules->open), std::min((*schwab)->close, rules->close), std::min((*schwab)->post_close, rules->post_close)}; if (day.open < day.close) { chosen = day; }}
Five Places MarketHours Quietly Saves You
Once MarketHours existed, five different parts of Kestrel plugged into it without changing a line of strategy logic:
-
Blocking closed-market orders (
SessionGatedVenue): RefusesPlaceOrderandPlaceOcowhile the market is closed, naming the exact ISO-8601 timestamp when trading reopens. (PaperTradingVenuelikewise refuses to match quotes while closed.) -
Session hooks and smart gap backfills (
Runner):RunnerdeliversOnSessionOpenandOnSessionClosing(re-checkingRefreshSessionat least once a minute in caseSchwabCalendarlearned of a short-notice early close). When a bar arrives after a time gap,HandleBarchecksAnyOpenacross the gap (using regular sessions for daily bars) before callingGetBars, so Monday’s09:30open doesn’t trigger a pointless REST backfill across Saturday and Sunday. -
Filtering streamed bars and off-hours quotes (
SchwabDataSource&Runner): Unlessextended_hoursis enabled,SchwabDataSource::StreamBarsdrops incoming minute bars outside the regular session (honoring13:00early closes and holidays automatically), andDailyBarPollerskips dates with no regular session. On regular-session bar strategies,Runner::Handlealso withholds pre-market and after-hours reference quotes fromRiskGatedVenueso off-hours prints can’t trip a halt at prices the strategy never trades. -
Measuring feed silence and late bars in open time:
Runner::CheckQuoteFeedsanddata::FeedWatchmeasure quiet streams in open-market time (OpenDuration). The 65.5 hours from Friday16:00ET to Monday09:30ET count as0 sof silence. During an open session,2 minutesof silence on a single symbol logs a stale-feed warning (and trips[risk] max_quote_age_msif configured), while5 minuteswith zero quotes across the whole stream inrunorstreamlogs a stream-down error to Discord. Likewise,Runner::CheckBarFeedsalerts if a daily candle is30 minuteslate after00:00 UTCon a trading day, while ignoring weekends and holidays. -
Keeping the risk gate from panic-selling on after-hours prints (
RiskGatedVenue): Live equity closes use market orders, which only execute in the regular session. Ifmax_drawdown_closetrips after hours, the gate halts trading and cancels open orders immediately, then holdsmPendingDrawdownCloseuntil the regular session opens (SendPendingClose()). Similarly,max_loss_per_positionchecksHasOpenMarketPrice(): an illiquid pre-market or after-hours print wide enough to breach a position’s loss limit pauses new entries in that ticker for the day, while waiting for a regular-session print before firing a market sell.
Where Live Schwab Behavior Disagreed With the Docs (and Why Databento Joined the Lineup)
Unit tests against mocked JSON only prove your code matches your reading of the documentation. Pointing Kestrel at Schwab’s live endpoints in November 2026 turned up a list of places where live payloads differed from the specs on developer.schwab.com (all documented in docs/venues/schwab.md):
| Area | What Schwab’s Spec Says | What the Live API Actually Does |
|---|---|---|
LEVELONE_EQUITIES sizes |
Bid/ask sizes (fields 4, 5) are in lots of 100 |
Reported in individual shares , matching REST /quotes
|
CHART_EQUITY fields |
0 is key, 1..5 are open, high, low, close, volume |
Shifted up by one: 1 is sequence, 2..6 are OHLCV (with fractional volume), 7 is minute start time |
POST /previewOrder |
Takes a PreviewOrder wrapper schema |
Rejects that wrapper; takes the exact same JSON body as POST /orders (matching schwab-py) |
GET /pricehistory |
Standard [startDate, endDate] query |
Always answers in whole days , defaults needExtendedHoursData to true (including 20:00–04:00 ET overnight bars), returns empty candles instead of an error on unknown symbols, has no 1h bars , and keeps only ~48 days of 1m bars |
| Streamer concurrency | WebSocket LOGIN per client |
Strictly one connection per user ; opening thinkorswim or a second process kicks the first off with notify code 12
|
Working around Schwab’s real-world behavior shaped four of the more interesting pieces in the repository:
1. Multiplexing One Streamer Socket (SchwabStreamer) and Polling Official Daily Bars
Because a second LOGIN from the same user disconnects the first with notify code 12, Kestrel can’t open one WebSocket for quotes and another for bars like it does on Binance.US. SchwabStreamer (src/data/schwab_streamer.cpp) fetches the WebSocket URL and credentials from GET /userPreference, logs in once, and multiplexes LEVELONE_EQUITIES and CHART_EQUITY subscriptions over that single connection (SUBS, ADD, UNSUBS). If thinkorswim takes over the connection (code 12), [schwab] takeover_reconnect_ms defaults to 0, stopping the streamer cleanly and logging an error rather than getting into an infinite tug-of-war stealing the socket back and forth.
For streamed bars, CHART_EQUITY only emits 1-minute candles (re-sending the last closed minute on subscribe, which Kestrel drops). SchwabBarAggregator builds 5m, 10m, 15m, and 30m bars from those minutes, skipping any incomplete window after a reconnect so Runner backfills it cleanly via REST. For 1d bars, however, summing intraday minutes would miss the opening and closing auctions. Instead, DailyBarPoller (StreamBars with 1d) uses zero streamer connections and polls /pricehistory after 00:00 UTC so live daily strategies trade on the exact same official daily candles used in backtests.
2. Tick Sizes Without a Symbol-Metadata Endpoint
Unlike Binance.US (exchangeInfo) or Kraken (AssetPairs), Schwab publishes no tick-size or lot-size endpoint. SchwabDataSource::GetSymbolInfo sends a single GET /quotes check at startup, returning kNotFound on a typoed ticker (which aborts run immediately) or kUnsupported on non-equities (which aborts backtest and rejects any order). From there it applies the SEC’s sub-penny rule (Rule 612): a $0.01 tick for stocks at or above $1.00, and $0.0001 below $1.00, with SchwabTradingVenue re-checking each order’s own limit or stop price in case a stock crossed $1.00 mid-session.
3. Polling Orders Without Scanning 180 Days Every 5 Seconds
Schwab’s GET /accounts/{hash}/orders filters by when an order was entered (fromEnteredTime), not when it last changed or filled, and a GOOD_TILL_CANCEL order can sit open for up to 180 days. Each poll also costs one request when idle—or two while an order is working—against Schwab’s 120 requests/min app limit, which Market Data and Trading share. Because SchwabDataSource and SchwabTradingVenue each keep an independent SchwabApi limiter (1.8 req/s, burst 5), together they could exceed 120/min under load, so live runs poll Schwab every 5 seconds instead of every second. Pulling 180 days of orders on every 5-second poll would inflate latency and risk hitting page limits.
SchwabTradingVenue avoids that in three ways:
-
In-memory watermark (
OrderScan/OldestWorkingSince): Only the first fetch in a process looks back 180 days. Every fetch records the entry timestamp of the oldest still-working order on Kestrel’s symbols. If the10:00:00poll sees that the oldest working order was entered at09:12:00, the10:00:05poll only asks for orders entered from09:12:00onward (minus 5 minutes of clock-skew slack). -
Recursive window splitting: If a busy account ever hits Schwab’s 3,000-order response ceiling in one window,
FetchOrdersrecursively splits the time range in half down to 1 minute and deduplicates order IDs at the seam. -
Targeted fill syncs for one-shot commands: When a fresh process like
kestrel_app account --storesyncs fills without an in-memory watermark, it pairs a narrow order fetch withGET /accounts/{hash}/transactions(types=TRADE) to look up at most 8 older filled orders individually by ID before falling back to a full 180-day scan.
One related quirk shows up on OCO orders (PlaceOco): when Schwab returns 201 Created, the Location header only names the parent order. Kestrel immediately reads back the parent to extract both child leg IDs, cancelling any lone surviving leg if its sibling was rejected.
4. Bringing In Databento For Deep Intraday Equity Backtests
Discovering that Schwab’s /pricehistory only keeps ~48 days of 1-minute bars (even for SPY) created an obvious problem: you can’t seriously evaluate an intraday equity strategy on seven weeks of data.
That led directly to adding provider = "databento" (commit 729101a, documented in docs/venues/databento.md). Because Databento bills by data volume, Kestrel refuses to auto-download from it on a backtest cache miss. Instead, kestrel_app databento runs an explicit import into TimescaleDB under venue = "databento":
-
Pre-flight cost gate: Every HTTP pull queries
/v0/metadata.get_costfirst and requires either--dry-run(spends$0) or--max-cost <USD> --store(aborting with exit code2before downloading if the estimate exceeds your cap). Adding--rollup 5m,15m,30mlater over sessions whose1mbars are already imported builds the higher timeframes locally for$0. -
Session-only slices, data hygiene, and a resumable ledger: Intraday HTTP pulls request only open market hours (
09:30–16:00ET, or07:00–20:00ET withextended_hours = true), reject multi-publisher bundles likeDBEQ.BASICthat mix per-exchange books under one ticker, and split dense tick schemas likembp-1into 15-minute chunks. Sequence numbers (seq) are derived deterministically from nanosecondts_recvtimestamps so out-of-order historical backfills still replay chronologically, and each finished slice is recorded indatabento_imports. Just like order placements, atimeseries.get_rangecall that times out is never automatically retried (since Databento may have delivered and billed the stream); re-running resumes cleanly from the ledger, and multi-year portal downloads (.csv.zst) also pipe straight in viazstdcat ... | kestrel_app ... databento --file - --storein constant memory. -
Drop-in compatibility with Schwab:
DatabentoDataSourcesharesUsEquityCalendarand Kestrel’s normalized tickers (SPY,BRK.B), so moving a strategy from a multi-year Databento backtest to Schwab paper or live trading is a one-lineproviderchange.
Side Note: Where Live Trading Stands Today. Kestrel turns live run on by default only as each venue’s real-account checklist finishes (TODO.md):
-
Binance.US is live (including live
market_makerruns onZEC/USDT, and commit3a63e4dextracted shared client-ID unknown-outcome recovery intotrading/order_recovery.hppalongside a universaldata::CallGuardedstream-callback guard). -
Charles Schwab passed its first live cash-account check on November 13, 2026:
order --test(previewOrder) verified limit, stop, andSCHBETF orders;kestrel_appbought and sold 1 share ofFat market with<orderId>:<activityId>:<leg>fill IDs; and a 15-minute livema_crossoverrun placed 3 orders with zero errors at ~13 requests/minute and a372 msmedian/orderspoll. -
Kraken passed its signed live read check (
BalanceEx,OpenOrders,TradesHistory, andTradeVolume) on an empty account on November 16, 2026.
Both Schwab and Kraken keep live run behind explicit live_trading = true flags while I finish checking resting limits and stops, OCO leg cancellation, and funded Kraken orders (including pending: true cancel replies). With Discord alerts (net::Alerter, commits 0e6ca0a through 5d1d906) now forwarding error lines, stream and daily-bar outages (data::FeedWatch), risk-gate actions (util::Notice), and startup low-disk checks, the last operational piece before leaving live runs unattended is an external dead-man’s-switch heartbeat (healthchecks.io), followed by those real-account order checks and WebSocket StreamExecutions so live runs stop polling REST for fills.
Conclusion
Integrating multiple exchanges and brokers behind a clean C++23 boundary came down to a handful of practical habits:
-
Stop provider quirks at the edge: Keep native symbols (
XXBTZUSD,BRK/B), HTTP-200 error payloads, and account hashes locked inside each venue class so strategy and risk code only ever see one model. -
Make market hours a first-class abstraction: Once
MarketHourslives onDataSource, order gating, bar backfills, streamed-bar session filtering, stale-quote checks, and after-hours risk closes all work automatically. - Design for credential lifecycles on running processes: Short-lived tokens and 7-day re-authorizations need atomic file swaps, directory locks, and in-memory adoption so renewing access never requires killing a live run.
-
Verify every spec against live traffic: From shifted streamer field numbers and
previewOrderpayloads to 2027 holiday tables and 48-day bar retention limits, live endpoints always have opinions the documentation forgot to mention.
Next up, to wrap up this initial series, is When Trading Strategies Meet Reality. I’ll dig into the backtest and live test numbers across Kestrel’s six strategies (trend_ensemble alongside the original five: ma_crossover, market_maker, breakout, momentum_rotation, and mean_reversion): why adding realistic network latency completely flipped a “profitable” market maker on its head, how a short live run verified how prices moved right after each fill compared to the simulator, and which slower daily setups actually held up after fees and slippage.
Have you run into undocumented API surprises or OAuth headaches integrating brokerage or crypto APIs of your own? Drop a comment below. I’d love to hear war stories!
The post Integrating Crypto Exchanges and Charles Schwab appeared first on Taylor Built Solutions.
Top comments (0)