# 14. Examples

The examples live in a dedicated repository: [github.com/andreysolovyev381/tse](https://github.com/andreysolovyev381/tse). Each example is a directory holding a C++ and a Python version of the same strategy, and both run against the shipped SDK — the headers, the shared library and the `tse.py` module described in the preceding chapters.

The examples are deliberately terse. They carry no self-checking, no assertions and no defensive code: each one prints the few numbers its run produced and leaves the judgement to you. Shared plumbing — loading a CSV, a rolling mean, the standard entry and exit rule parameters — lives in a helpers file next to them, so that the body of an example contains only what the example is about.

They are ordered as a course. The first group brings up a robot from nothing, the second builds strategies with it, the third adds risk control, the fourth reads the statistics back, and the last collects the facilities that surround a running engine. This chapter explains the logic of each example and links its code.

## The shape every example has

Every example in this chapter is the same twelve declarations in the same order, and none of them is optional: the account is created; an adapter is opened for the shape of market data that will arrive; an execution is attached; the traded contracts are declared; an Input is given its processor; a Pattern is pointed at that Input; a Rule is pointed at that Pattern; a Robot is given its rules; the robot is started; data is pushed tick by tick; the summary is read; the account is destroyed and the adapter handle released. What differs between a moving-average crossover and a book-imbalance market maker is the body of one callable and the parameters on the rules — never the shape below.

Written out, on the three surfaces, that assembly is this. Two things are left outside it: the body of `smaProcessor`, which is your code and not the engine's, and the parameter aggregate handed to the rule.

```c
TseAccountHandle account = tse_account_create("research", tse_storage_regime_mem, "USD", -1);
TseMarketHandle market = tse_market_create("md", tse_md_ohlcv, "USD");
TseSimulatorConfig const options = {100, 100, tse_ohlcv_close, tse_ohlcv_open, tse_bidask_bid, tse_bidask_ask};
tse_exec_create_simulator(account, "sim", &options, 3, -1);
TseContractHandle const tsla = tse_add_contract("TSLA", 1, tse_instrument_equity, tse_underlying_undefined, tse_venue_undefined, 100000, "USD");
tse_add_input_ohlcv(account, "sma", 20, tse_duration_days, smaProcessor, &state, market, -1, (TseContractHandle[]){tsla}, 1);
tse_add_pattern_threshold(account, "hot", tse_duration_days, (char const*[]){"sma"}, 1, tse_cmp_gt, 42.0, -1);
TseRuleParams const entry = {tse_quantity_fixed, 100.0, tse_price_market, 0.0, 0.0, 0.0, tse_side_long, tse_side_neutral, tse_tif_day, 10};
tse_add_rule_market(account, "entry", tse_rule_entry, &entry, "hot", tsla);
tse_add_robot(account, "robot", (char const*[]){"entry"}, 1, -1);
tse_start(account, "robot");
tse_market_push_ohlcv(market, tsla, &tick);
TseSummary summary;
tse_get_summary(account, &summary);
tse_account_destroy(account);
tse_market_destroy(market);
```

```cpp
tse::Account account {"research", tse::StorageRegime::mem, "USD", -1};
tse::Market const market {"md", tse::MdType::ohlcv, "USD"};
tse::SimulatorConfig const options {100, 100, tse::OhlcvField::close, tse::OhlcvField::open, tse::BidAskField::bid, tse::BidAskField::ask};
account.createSimulator("sim", options, 3, -1);
tse::Contract const tsla {"TSLA", 1, tse::Instrument::equity, tse::Underlying::undefined, tse::Venue::undefined, 100000, "USD"};
account.addInputOhlcv("sma", 20, tse::Duration::days, smaProcessor, market, {tsla});
account.addPatternThreshold("hot", tse::Duration::days, {"sma"}, tse::Cmp::gt, 42.0);
account.addRuleMarket("entry", tse::RuleType::entry, entryParams, "hot", tsla);
account.addRobot("robot", {"entry"});
account.start("robot");
market.pushOhlcv(tsla, tick);
tse::Summary const summary {account.getSummary()};
```

```python
account = tse.Account("research", tse.StorageRegime.Mem, "USD", -1)
market = tse.Market("md", tse.MdType.Ohlcv, "USD")
options = tse.make_simulator_config(100, 100, tse.OhlcvField.Close, tse.OhlcvField.Open, tse.BidAskField.Bid, tse.BidAskField.Ask)
account.create_simulator("sim", options, 3, -1)
tsla = tse.Contract("TSLA", 1, tse.Instrument.Equity, tse.Underlying.Undefined, tse.Venue.Undefined, 100000, "USD")
account.add_input_ohlcv("sma", 20, tse.Duration.Days, sma_processor, market, [tsla])
account.add_pattern_threshold("hot", tse.Duration.Days, ["sma"], tse.Cmp.Gt, 42.0)
account.add_rule_market("entry", tse.RuleType.Entry, entry_params, "hot", tsla)
account.add_robot("robot", ["entry"])
account.start("robot")
market.push_ohlcv(tsla, tick)
summary = account.get_summary()
```

Everything that follows is a variation on it.

## Hello world

### 01 hello world - initial params

Process-wide configuration comes before the first account, which is why this is the first example. `set_initial_params` names the data folder where database-regime blotters write their SQLite files, the log folder, and the log level; an existing folder is taken as it stands, a missing one is created in full, and a file standing where a folder is expected is refused with a diagnostic that surfaces as a `TseError`.

The lesson worth carrying forward is capture at construction. An account resolves its data folder when it is built, so a later switch never moves the blotter of an account that is already trading: the example builds one account, switches the data folder, builds a second, and shows each blotter file sitting in the folder that was configured at its own construction time. An account that needs a file of its own, rather than one of a shared folder, is built with `tse_account_create_at_path` instead, and reports the file it settled on through `tse_account_blotter_db_path`.

```python
tse.set_initial_params(data_folder=data_a, log_folder=logs, log_level=tse.LogLevel.Off)
captured_a = tse.Account("CapturedA", tse.StorageRegime.Db, "USD")
tse.set_initial_params(data_folder=data_b, log_folder="", log_level=None)
captured_b = tse.Account("CapturedB", tse.StorageRegime.Db, "USD")
```

Code: [01 hello world - initial params](https://github.com/andreysolovyev381/tse/tree/main/01%20hello%20world%20-%20initial%20params)

### 02 hello world - macd

The first complete robot, and the assembly chain every later example repeats: an account, a market adapter, an execution, a contract, an input holding the data processor, patterns over the input, rules bound to the patterns, a robot over the rules, a start, and then the replay of the history.

Pay attention to the stand-alone data processor — this is where the money is made, and it stays yours. Here it is a plain MACD, the distance between a twelve-day and a twenty-six-day exponential average of the close; it pushes that distance into the input's storage and returns readiness only once the slow average has seen enough days, so no rule fires on a half-formed indicator. In later examples the same slot holds a gradient-boosted model, while everything around it is unchanged.

```python
def macd(storage, contract_id, tick):
    storage.push(tick.tsNanoseconds, ema_fast - ema_slow)
    return storage.size() >= slow

account.add_input_ohlcv("MACD", slow, tse.Duration.Days, macd, market, [aapl_contract])
account.add_pattern_threshold("ToLong", tse.Duration.Days, ["MACD"], tse.Cmp.Ge, 0.0)
```

Code: [02 hello world - macd](https://github.com/andreysolovyev381/tse/tree/main/02%20hello%20world%20-%20macd)

### 02.1 hello world - built-in inputs

The same robot as example 02, with one line changed in kind: the indicator is no longer written but **declared**. Nine processors ship with the library — the three moving averages, two volatilities, the average true range, the Parkinson estimator, a rolling median and a robust rolling $z$ score — and a built-in input names which of them it wants, which field of the record it reads, and over how long a window. Here two simple moving averages, twelve days and twenty-six, feed a crossover pattern, and the smoothing coefficient is passed as zero because only the exponential average reads it.

Two things are worth noticing. The processor is engine code called directly, so no tick crosses the language boundary on its way through the indicator. And the robot is savable with nothing registered: a custom processor is a function pointer and needs a string key to survive a save, while a built-in processor is described completely by the four values the recipe stores, so the library rebuilds it on load by itself. The chapter on the built-in input processors lists all nine and what each one refuses.

Example 02 remains the one to read first, and it remains the general case: the point of the engine is that the indicator is yours. This example is for the cases where it needn't be.

Code: [02.1 hello world - built-in inputs](https://github.com/andreysolovyev381/tse/tree/main/02.1%20hello%20world%20-%20built-in%20inputs)

### 03 hello world - grid search

A backtest exists to manufacture choice. Rather than betting on one lookback, the example sweeps four of them — 10, 20, 50 and 100 days against a 200-day trend — and ends with a pool of candidates to choose from. `run_grid` takes a builder callback that assembles a fresh account for every parameter value and feeds it the same history; each `GridResult` carries the parameter value, a success flag and the candidate's full summary, so the selection criterion stays yours.

The grid points are independent backtests, so the engine runs them side by side on a pool of worker threads. The builder notes the identity of the thread it lands on into a set, and the run prints how many distinct workers the pool actually used — the parallelism is visible rather than asserted.

```python
def builder(account, param_value):
    worker_threads.add(threading.get_ident())
    build_robot(account, int(param_value))

results = tse.run_grid("AAPLGrid", tse.StorageRegime.Mem, params, builder, "USD")
```

Code: [03 hello world - grid search](https://github.com/andreysolovyev381/tse/tree/main/03%20hello%20world%20-%20grid%20search)

### 04 hello world - multiple contracts

Three feeds of three different shapes on three adapters: daily AAPL bars, BTC/USDT quotes and WTI trade prints. Two inputs observe the first two instruments — a simple average of the Apple close, a simple average of the Bitcoin mid — while the rules trade a third contract, WTI, which no input watches at all. The long pattern is a threshold on the Apple input, the short one a peak on the Bitcoin input, and the two rules differ in order type: a market order to enter, a limit order to leave. WTI is subscribed to its own price adapter so the portfolio can mark the position it holds.

The part to study is the replay loop. Three feeds share one clock, so the loop keeps an index per feed and always pushes whichever feed holds the oldest unsent tick, using an infinite sentinel for a feed that has run out. The strategy therefore lives through the history in the order it really happened, which is what makes a multi-feed backtest honest.

```python
while aapl_at < len(aapl) or btc_at < len(btc) or wti_at < len(wti):
    aapl_ts = aapl[aapl_at].tsNanoseconds if aapl_at < len(aapl) else far_future
    btc_ts = btc[btc_at].tsNanoseconds if btc_at < len(btc) else far_future
    wti_ts = wti[wti_at].tsNanoseconds if wti_at < len(wti) else far_future
```

Code: [04 hello world - multiple contracts](https://github.com/andreysolovyev381/tse/tree/main/04%20hello%20world%20-%20multiple%20contracts)

### 05 hello world - multiple adapters

One account, two market-data adapters: daily bars for the equity and a quote stream for the crypto pair. AAPL is traded off the golden cross of its fifty-day and two-hundred-day averages, both inputs reading the bar adapter.

BTC/USDT carries no input and no rule. It is registered as a contract and subscribed to the quote adapter with `portfolio_subscribe`, which is what makes a non-traded instrument consume a feed: the run finishes with every trade on AAPL and BTC/USDT carrying a live mark against a zero position. Separate the two roles early — observing a feed and trading an instrument are independent decisions.

Code: [05 hello world - multiple adapters](https://github.com/andreysolovyev381/tse/tree/main/05%20hello%20world%20-%20multiple%20adapters)

### 06 hello world - save load

A strategy researched in Python and then traded from C++, across the language boundary. The Python leg registers its two processors under keys, builds the WTI crossover from inputs declared by those keys, runs the backtest, and saves the recipe. Save is recipe-only: contracts, inputs, patterns, rules and the robot travel; market adapters, execution, market data and results deliberately do not.

The C++ leg re-registers the same processor keys — a recipe remembers the name of a processor, never its code — loads the robot, creates today's adapter, binds each restored input to it, and starts. Binding is not optional: a loaded input is unbound until it is given an adapter, and starting with an unbound input is an error. A model's own weights are persisted separately, next to the recipe.

Code: [06 hello world - save load](https://github.com/andreysolovyev381/tse/tree/main/06%20hello%20world%20-%20save%20load)

### 07 hello world - trading

A robot proven in backtesting goes live by swapping only its two ends, and the example shows exactly that: it is 02 hello world - macd with both ends replaced and nothing in between rewritten. Put the two files side by side and the claim checks itself — the processor, the two thresholds, the two rules and the robot are the same lines.

The IN end is a schematic market-data client in place of the loop over a file: it holds the adapter, hands over one bar at a time and tells the broker where the market is as it goes. The OUT end is a custom execution created with `create_custom` in place of the Simulator; its transmit callback receives every order the engine emits and reports the fill back with `apply_fill`, in full, a millisecond later, at the last price it was told about, charging its fee. A custom execution is started and stopped by whoever created it — the engine never does it for you — and the example does both explicitly. What remains for you is to wire the client to a websocket, a FIX session or a vendor SDK, and the transmit to your broker.

```python
def transmit(execution, order):
    execution.apply_fill(order.clientOrderId.decode(), price, order.quantity, fee, ts)

broker_execution = account.create_custom("BROKER", broker.transmit, 8, -1)
broker_execution.start()
```

Code: [07 hello world - trading](https://github.com/andreysolovyev381/tse/tree/main/07%20hello%20world%20-%20trading)

### 07.1 hello world - basic rules

Four verbs partition every move a position can make, and a rule speaks exactly one of them: an entry opens from flat, a rebalance moves the position without leaving the side it is on, a flip crosses to the other side, and an exit closes it to exactly zero. This example speaks all four in one chain — entry, rebalance, flip, rebalance, flip, exit — and ends flat, so the whole contract is visible in a single run. Nothing else is in it: no indicator, no file of history, no selection criterion.

The quantity is what keeps the four disjoint rather than merely differently named. A flip must strictly exceed the open position, or there would be nothing left on the other side; an exit must equal it exactly, or it would not be an exit; a rebalance that trades against its own position must stay strictly below it, or it would be one of the other two. A quantity that breaks the bound of its verb is refused when the order is admitted, and the position is left exactly as it stood — no quantity is ever reinterpreted into a different verb.

The part to study is the side a rule names. Every rule carries the position side it expects to find, and a leg whose expectation differs from the live position is refused. A flip therefore silences the rules of the side it has just left and hands the chain to the rules of the side it has arrived on, which is why the example declares a rebalance and a flip for each of the two sides rather than one of each. The six steps are a table, and each step's pattern is armed one second after the one before it with a cool down it can never reach, so the six fire once each and in the order they are written.

```python
STEPS = [
    Step("entry",     "RuleEntry",          "EnterAt",          tse.RuleType.Entry,      4.0, tse.Side.Long,  tse.Side.Neutral, 100.0),
    Step("rebalance", "RuleRebalanceLong",  "RebalanceLongAt",  tse.RuleType.Rebalance,  2.0, tse.Side.Long,  tse.Side.Long,    103.0),
    Step("flip",      "RuleFlipToShort",    "FlipToShortAt",    tse.RuleType.Flip,      10.0, tse.Side.Short, tse.Side.Long,    108.0),
    Step("rebalance", "RuleRebalanceShort", "RebalanceShortAt", tse.RuleType.Rebalance,  2.0, tse.Side.Short, tse.Side.Short,   111.0),
    Step("flip",      "RuleFlipToLong",     "FlipToLongAt",     tse.RuleType.Flip,      10.0, tse.Side.Long,  tse.Side.Short,   106.0),
    Step("exit",      "RuleExit",           "ExitAt",           tse.RuleType.Exit,       4.0, tse.Side.Short, tse.Side.Long,    110.0),
]
```

Every rule takes its price at the market, so the only things telling the six apart are the verb, the quantity and the two sides. The run prints the position after each verb, and the chain reads straight off the output: four long, six long, four short, six short, four long, flat. The trade count comes out at eight rather than six, because a flip crosses zero and the engine splits a crossing trade into the half that closes the old position and the half that opens the new one.

Code: [07.1 hello world - basic rules](https://github.com/andreysolovyev381/tse/tree/main/07.1%20hello%20world%20-%20basic%20rules)

## Robots

### 08 robots - gbm model

The counterpart of 02 hello world - macd: the surroundings are identical, only the processor changed. A gradient-boosted model is trained before the run and then lives inside a bid/ask processor, which derives mid price, spread and quote imbalance from every tick, asks the booster for a forecast, and pushes that forecast as the input's value. Two thresholds at zero put the robot long while the forecast is positive and flat once it turns.

The engine never inspects the callable it was handed; it sees a number and a readiness flag. Whether that number comes from a moving average, a booster, a neural network or an external cloud service is a decision entirely on your side of the boundary, and it does not change a single line of the robot around it.

Code: [08 robots - gbm model](https://github.com/andreysolovyev381/tse/tree/main/08%20robots%20-%20gbm%20model)

### 09 robots - rebalance

The rebalance rule maintains an existing position instead of opening or closing one. Its position side names the side it tends, and a firing chains an adjustment order onto the open position. Two timestamp patterns drive the example: the entry pattern carries a cool-down it can never reach, so it fires once; the rebalance pattern rearms one second after firing, so it fires twice.

The arithmetic is deliberately explicit because this is the point most easily misread. The rebalance is additive: it does not measure the distance to a target size and does not bring the position anywhere. Four units at 100, then two more at 103, then two more at 108 leave a position of eight whose acquisition price is the volume-weighted average of the three fills, and nothing is realized along the way because every add joins the side it is already on. A bring-to-target rebalancer is something you compose — leave the rule's quantity undefined and a formula pattern that reads the live position can publish exactly the shortfall it wants filled, the technique 10 robots - market maker uses.

Code: [09 robots - rebalance](https://github.com/andreysolovyev381/tse/tree/main/09%20robots%20-%20rebalance)

### 10 robots - market maker

A naive two-sided maker with an inventory band. Client order flow arrives as book messages and two book inputs split it: one keeps the client sells the maker buys against, the other keeps the client buys it sells against, and each pushes the client order's quantity into its storage. All eight rules leave their quantity undefined and their formulas put the client order's size into the signal, so every order the maker sends is exactly the size of the order it absorbs.

The rule types are the four ways a position can change, and this maker uses all of them that a two-sided book needs. An entry starts from a flat book, an exit ends at one and has to close the whole position, a flip crosses the side, and a rebalance is every change that keeps the side. That is why unwinding an inventory takes two rules per side rather than one: while more than a single quote's worth is still on the book, the reduction keeps the side and so it is a rebalance, `MmSellReduce` on the long side and `MmBuyReduce` on the short one, and only the last quote's worth leaves through an exit, `MmSellClose` and `MmBuyClose`. Growing the inventory is the same verb from the other direction, which is what `MmBuyRebalance` and `MmSellRebalance` do.

Those two top-up rules are also the ones that show why the undefined forms are per field rather than per rule. They leave the price form and the transaction side undefined on top of the quantity, and their formulas fill all three: the size of the client order absorbed, a limit at the price the client asked rather than a market cross, and whichever direction the inventory currently happens to be. None of those three can be known when the rule is built. The other six name their side and their price form at build time, because an entry from flat, an exit to flat and a reduction of a known side all know their direction in advance.

The quoting logic lives in eight formula patterns whose closures read the live position through `get_position_state` — the pattern layer is ordinary code, so it can consult exposure directly. The band is measured on the combined view, `combinedQuantity`, so a quote that is still resting already counts against the inventory; measured on the realized view the maker would go on adding size it has already committed. A small state machine flips between accumulating and unloading: below the upper band the maker quotes both sides, at the band it stops adding and only trades the side that unwinds, until the inventory is back to zero. While unloading, the two closing patterns refuse to fire until a single quote's worth is all that is left and the two reducing patterns refuse once that is the case, so the pair never competes for the same firing. The adverse-selection guard is named rather than buried — `is_every_second_client_order` lets the maker quote against every second client order only, which is the crudest possible refusal to keep accumulating against a flow that may be informed.

```python
def is_every_second_client_order(state):
    return state["order_count"] % 2 == 0

account.add_pattern_formula("MmOpenLong", tse.Duration.Nanoseconds, ["ClientSells"], open_long)
account.add_rule_market("MmBuyOpen", tse.RuleType.Entry,
                        signal_params(tse.Price.Market, tse.Side.Long, tse.Side.Neutral),
                        "MmOpenLong", mmtest_contract)
account.add_rule_market("MmSellReduce", tse.RuleType.Rebalance,
                        signal_params(tse.Price.Market, tse.Side.Short, tse.Side.Long),
                        "MmReduceLong", mmtest_contract)
account.add_rule_market("MmSellClose", tse.RuleType.Exit,
                        signal_params(tse.Price.Market, tse.Side.Short, tse.Side.Long),
                        "MmCloseLong", mmtest_contract)
account.add_rule_market("MmBuyRebalance", tse.RuleType.Rebalance,
                        signal_params(tse.Price.Undefined, tse.Side.Undefined, tse.Side.Long),
                        "MmTopUpLong", mmtest_contract)
```

Code: [10 robots - market maker](https://github.com/andreysolovyev381/tse/tree/main/10%20robots%20-%20market%20maker)

### 11 robots - market maker amend

The maker of the previous example only ever crossed the spread. This one rests a quote and then manages it, which is what order amendment is for. The client flow is read from a recorded file of executed prints, and one measurement pass over each print produces the three facts the maker reacts to: an outsized trade relative to the running average size, a third trade in a row on one side, and a silence longer than ten seconds.

One quote lives at a time, tracked by its client order id, and each amendment does something different to that identity: a cancel drops the id, a replace mints a fresh one, a modify keeps it. A sweep on the quote's own side pulls the quote, a one-sided run steps it away and shrinks it, and a quiet stretch restores it to full size. A separate exit rule unwinds the inventory once it reaches its cap. Read this one together with 21 risk - external tools, oco and amends, which exercises the same three amendment rules in isolation.

```python
account.add_rule_cancel("PullQuote", SYMBOL, 0.0, 0.0, "SweepHit")
account.add_rule_replace("StepAway", SYMBOL, defensive_size, step_away_price, "SameSideRun")
account.add_rule_modify("BackToFullSize", SYMBOL, full_size, 0.0, "QuietGap")
```

Code: [11 robots - market maker amend](https://github.com/andreysolovyev381/tse/tree/main/11%20robots%20-%20market%20maker%20amend)

### 12 robots - voting group

Four robots on one account, where the fourth trades the behaviour of the other three. The engine lets one robot trade a contract, so each robot holds a contract of its own — `WTI_VOTER_1`, `WTI_VOTER_2` and `WTI_VOTER_3` for the traders, `WTI_GROUP` for the voter — and every WTI bar is pushed into all four. Three traders ignore the price entirely and vote by a seeded coin flip on every bar — each trader's price feed is only the heartbeat that makes it decide, and all three decide at the same moments — so their positions come and go for no reason at all, which is precisely what makes the group's aggregate the only thing worth reading.

The group is assembled through the engine's own fills. The replay loop pulls the newly retained trades, skips the voter's own, and pushes the traders' fills into an executed-trade adapter under the group contract; the voter's input over that adapter keeps their signed sum, adding a long fill and subtracting a short one, and two thresholds over that net put the voter long while the group is net long and flat when the net returns to zero. The group contract has no price input of its own, so `portfolio_subscribe` puts it on the price market: the simulator then fills the voter against the WTI bars and the portfolio marks its position. Per-robot statistics are read back with `get_robot_summary`, one summary per label, so the three traders and the voter are measured separately on the same account.

```python
account.add_input_executed("Group net", 1, tse.Duration.Minutes, group_net, executed, [GROUP_CONTRACT])
account.add_pattern_threshold("Group is long", tse.Duration.Minutes, ["Group net"], tse.Cmp.Gt, 0.0)
account.add_pattern_threshold("Group is flat", tse.Duration.Minutes, ["Group net"], tse.Cmp.Le, 0.0)
account.portfolio_subscribe(prices, GROUP_CONTRACT)
```

Code: [12 robots - voting group](https://github.com/andreysolovyev381/tse/tree/main/12%20robots%20-%20voting%20group)

### 13 robots - book imbalance

The first of the three order-book examples, and the one that uses recorded data. The account owns a real L3 book, and the built-in imbalance input feeds the strategy straight from that book: imbalance answers one question — whose resting size is bigger, the buyers' or the sellers' — reading +1 when only bids rest and -1 when only offers do. Two thresholds at plus and minus a fifth drive the robot both ways, with four rules covering entry and exit on each side.

The feed is a file of quote snapshots rather than a hand-written vector. Each snapshot is replayed as the two orders it implies, one per side, and the pair the previous snapshot left resting is cancelled immediately after, so the book always holds the current quote alone instead of a pile of every quote ever seen; a trade print between snapshots gives the portfolio its mark. Note the storage length passed to the input: it is the length of the input's own series, not a book depth.

```python
book = account.create_book("BOOKA", tse.BookLevelKind.L3)
account.add_input_book_imbalance("Imbalance", 4, tse.Duration.Nanoseconds, book, book_mkt, ["BOOKA"])
account.add_pattern_threshold("ToLong", tse.Duration.Nanoseconds, ["Imbalance"], tse.Cmp.Ge, 0.2)
```

Code: [13 robots - book imbalance](https://github.com/andreysolovyev381/tse/tree/main/13%20robots%20-%20book%20imbalance)

### 14 robots - book ofi

The same signal as the previous example, run unchanged on all three book depths a venue may publish. The strategy body is depth-agnostic: the only line that differs between the three variants is the book's construction as L1, L2 or L3.

The feed is a laboratory instrument rather than a recording. Each step adds exactly the size that drags the book onto the next target imbalance, so the sequence of signals is known before the run starts and the three variants can be compared field by field. What L2 adds over L1 is per-level state, and what L3 adds over L2 is per-order state — none of which this signal consults, which is the whole point of the comparison. The order book chapter describes what each depth actually retains.

Code: [14 robots - book ofi](https://github.com/andreysolovyev381/tse/tree/main/14%20robots%20-%20book%20ofi)

### 15 robots - book arbitrage

The composition pattern for cross-book signals. The same asset is quoted on two venues: an L2 book tracks the first, an L3 book tracks the second, and each feeds its own imbalance input. Neither imbalance is a signal on its own — the strategy waits for the two to disagree by more than 0.3 and bets that the disagreement collapses, leaving when the spread is back inside a narrow band around zero.

The fusion lives in the pattern layer. Each formula closure remembers the last value seen from each input, refuses to answer until both books have spoken, and then compares their difference against its own threshold. The position, meanwhile, is taken in a third and liquid contract that neither book observes, fed by its own price adapter — the signal and the trade are separate choices, as in 04 hello world - multiple contracts.

Code: [15 robots - book arbitrage](https://github.com/andreysolovyev381/tse/tree/main/15%20robots%20-%20book%20arbitrage)

### 16 robots - multileg butterfly

A SPY call butterfly — long one 440 call, short two 450 calls, long one 460 call — submitted as a single multileg transaction. Each leg is a descriptor carrying its own contract, side, quantity, limit price and transaction kind, and the entry and exit prices are read from a data file rather than invented in the source.

The fill is atomic: no leg fills until every leg's market has reached its price, so a half-assembled structure never appears in the portfolio, and if one leg's market runs away nothing fills at all. The exit reverses every leg, again in one all-or-nothing transaction, with each exit leg flipping its side and naming the position side it closes. Two timestamp patterns supply the two moments. Option contracts here carry a hundred-share multiplier, so a dollar on a leg is a hundred dollars of profit and loss.

Code: [16 robots - multileg butterfly](https://github.com/andreysolovyev381/tse/tree/main/16%20robots%20-%20multileg%20butterfly)

### 17 robots - multileg strangle hedge

The same atomic mechanics as 16 robots - multileg butterfly, now mixing instrument types inside one transaction. A long CLF26 future carries the directional view, two long out-of-the-money puts at 45 and 44 insure it against a fall, and a far out-of-the-money 60 call buys the upside back: four legs, one hedged position, each leg registered with its own instrument type and a thousand-barrel multiplier.

This is the argument for multileg as a primitive rather than a convenience. A hedge assembled leg by leg exists, for a while, only half built, and that interval is exactly where the risk lives; an all-or-nothing transaction removes the interval. Read the multileg entry of the Rule chapter alongside this example for the exact fill rule.

Code: [17 robots - multileg strangle hedge](https://github.com/andreysolovyev381/tse/tree/main/17%20robots%20-%20multileg%20strangle%20hedge)

## Risk

### 18 risk - internal calc

Risk the engine computes inside itself, in the two forms it offers, measured against a baseline run of the same strategy. The first form is risk policies — pre-trade gates tested against the position an order would leave you holding. The example caps the market value of the whole book at five thousand and the quantity of one name at a hundred shares; once the share price passes fifty, the hundred shares the robot wants are worth more than the value cap and every entry from that point is refused, so the run visibly parts company with the baseline. A third policy confines trading to a repeating window of local time in a named zone, and the example runs it twice: a window a whole day wide, and a window one nanosecond wide, which is a plain way of saying "do not trade at all".

The second form is risk rules — stop-loss and take-profit, each in a fixed and a trailing variant, added with a threshold ratio and the flat-out exit parameters. The fixed pair measures from the entry price, the trailing pair from the best price seen since entry. These rules live in the account and watch the position tick by tick, which makes them fully effective in backtesting; their venue-resting counterparts are the three examples that follow.

Code: [18 risk - internal calc](https://github.com/andreysolovyev381/tse/tree/main/18%20risk%20-%20internal%20calc)

### 19 risk - external tools, bracket fixed

The same protection, relocated. A bracket rule submits one entry leg together with a venue risk specification holding a stop-loss leg and a take-profit leg, both fixed, both resting at the venue with a good-till-cancelled time in force. Here the entry is a 580-lot market order on a WTI three-over-ten crossover, guarded two percent below the fill and three percent above it.

The difference from the internal form is where the protection lives. Nothing is recomputed on every tick: when the entry fills, the engine derives the two price triggers from the fill price and the legs' ratios and rests them, so they guard the position even if your process stops running. Whichever side the market touches first closes the position and cancels its sibling, and the whole life cycle — enter, protect, exit — is one rule over one pattern.

```python
risk = tse.make_venue_risk_spec(
    tse.make_venue_risk_leg(True, 0, 0.02),
    tse.make_venue_risk_leg(True, 0, 0.03),
    tse.Tif.Gtc)
account.add_rule_bracket("Bracket", entry, risk, "PatternToLong")
```

Code: [19 risk - external tools, bracket fixed](https://github.com/andreysolovyev381/tse/tree/main/19%20risk%20-%20external%20tools,%20bracket%20fixed)

### 20 risk - external tools, bracket trailing

The construction of 19 risk - external tools, bracket fixed with one leg changed. On AAPL daily bars a fifty-over-two-hundred golden cross is protected by a five percent trailing stop and a fixed ten percent target; in the risk leg it is the kind field that selects the behaviour, zero for fixed and one for trailing.

A fixed stop is priced once, off the entry. A trailing stop is re-priced off the best price the position has seen, so it ratchets in the position's favour and converts an open gain into a protected one. Running the two examples side by side shows the difference in character rather than in code: the fixed bracket takes symmetric bites, the trailing bracket lets a winner run and cuts the giveback.

Code: [20 risk - external tools, bracket trailing](https://github.com/andreysolovyev381/tse/tree/main/20%20risk%20-%20external%20tools,%20bracket%20trailing)

### 21 risk - external tools, oco and amends

Order management as strategy actions, each scenario on its own clean rig and each fired by a timestamp pattern, so the moment of the action is exact.

Three of the four scenarios are the ways of changing your mind about an order already resting at the venue. A limit entry rests below the market, reserving its quantity; then, at the amendment check point, one rule acts on it — a cancel withdraws it and releases the reservation, a modify shrinks it in place from ten to four, a replace pulls it and posts a fresh one at a different price and size. The fourth scenario arms a stop and a target on an open position as one pair: the entry fills long, the pair rests, the price drops through the stop, and the stop leg closes the position while the target dies with it. A specification with both legs absent is rejected; a one-legged one is legal.

Code: [21 risk - external tools, oco and amends](https://github.com/andreysolovyev381/tse/tree/main/21%20risk%20-%20external%20tools,%20oco%20and%20amends)

## Statistics

### 22 stats - transaction and robot

Two levels of statistics off a single WTI crossover run. The transaction level is the blotter: `get_trades` returns one row per retained fill — symbol, price, quantity, booked profit and loss, side — next to the execution's own count of what it processed. This is the record you reconcile against, and it is read straight back from the export layer rather than out of a database file.

The duration level is ex_post. The very same run is cut into day buckets and each bucket is scored, so a model can study how the robot behaved through time instead of reading one number at the end; the example creates the ex_post object on every core of the machine, asks for the parameter count and the bucket count, then saves the scores the object holds and calls `ex_post_load` on the file. That last call is a check of the file and nothing more — it reports how many robots the file holds and builds nothing; reading the scores back is the subject of 22.2. The score parameters are not a fixed table: the axis is as wide as `param_count` reports, and each column names itself through `param_name`, which is why the example reads the count rather than assuming it.

```python
ex_post = account.create_ex_post(tse.Duration.Days, -1, 5, os.cpu_count() or 1, tse.EmptiesMode.Skip)
buckets = ex_post.bucket_count(0)
ex_post.save_complete(db_path)
saved_robots = account.ex_post_load(db_path)
```

Code: [22 stats - transaction and robot](https://github.com/andreysolovyev381/tse/tree/main/22%20stats%20-%20transaction%20and%20robot)

### 22.1 stats - multithreaded ex-post

Example 22 once more, with eight robots instead of one. They trade the same crossover and differ only in how far back the slow average looks — from 10 to 45 bars in steps of five — and each robot trades a contract of its own that receives the very same WTI bars: the profit of a fill is booked against the exposure of its contract, so robots sharing one contract would not be separate strategies.

The ex_post object is created on every core of the machine. The day buckets of different robots are built in parallel, and at each day step the robots whose scoring window is complete are scored in parallel; ex_post never uses more threads than there are robots. The number of threads changes the time, not the result: the scores are the same, bit for bit, as with one thread, except `thompson_sampling`, which is random by design. The scoring runs once, when the object is created, and the save writes what the object already holds. The example prints each robot's trade count, net profit and bucket count, then the account totals and the number of robots the saved database holds.

```python
ex_post = account.create_ex_post(tse.Duration.Days, -1, 5, os.cpu_count() or 1, tse.EmptiesMode.Skip)
ex_post.save_complete(db_path)
saved_robots = account.ex_post_load(db_path)
```

Code: [22.1 stats - multithreaded ex-post](https://github.com/andreysolovyev381/tse/tree/main/22.1%20stats%20-%20multithreaded%20ex-post)

### 22.2 stats - resuming ex-post

The same WTI run as 22, this time asking what a saved scores database is good for. Three entry points are shown side by side. The full pass builds the object from the account's trades and saves it in the **complete** form, which is the form that keeps the inference record — the last entry, whose outcome the next bucket has not revealed yet — and every score that came out absent. The compact form drops both, which makes it smaller and fit for reading with SQL, but unfit for being read back into a journal.

`open_ex_post` is the cheap way back in: the journal is read from the file and the features come out of it without a single trade being touched and without anything being scored again. The example reads the momentum matrix from the opened handle and checks that it repeats the one the live object gave. Such a handle holds the journal and no series, so both saves refuse on it, and the example shows that refusal rather than hiding it: half a file would be worse than an honest error.

`rebuild_ex_post_from_file` is the resuming way back in, and it is the one a daily cycle uses. The series, the ranking ring and the journal are put back from the file, the series are extended by the trades that follow the newest stored bucket, and the scoring pass runs again from one window behind that bucket — far enough that every score the new buckets touch is recomputed, and no further. In this example no new trade has arrived, so the resumed result repeats the stored one; in a daily cycle the new day enters here, at the cost of its own buckets alone instead of the whole history. One qualification belongs in the open: money is stored in `REAL` columns and the round trip through a binary floating-point column is not exact, so a resumed result is very close to a full one rather than identical to it, at the scale of one millionth of a currency unit per value.

```python
live = account.create_ex_post(tse.Duration.Days, -1, 5, os.cpu_count() or 1, tse.EmptiesMode.Skip)
live.save_complete(db_path)

opened = account.open_ex_post(db_path)
ts, values = opened.feature_momentum(0)

today = account.rebuild_ex_post_from_file(db_path, os.cpu_count() or 1)
today.save_complete(db_path)
```

Code: [22.2 stats - resuming ex-post](https://github.com/andreysolovyev381/tse/tree/main/22.2%20stats%20-%20resuming%20ex-post)

### 23 stats - candidate selection

A backtest produces N candidates, and choosing between them is itself a repeated task best handed to a model. This example closes the loop between 03 hello world - grid search and 22 stats - transaction and robot: five candidates differing only in their fast lookback are swept with the grid runner, and each builder opens an ex_post object on its own finished account and extracts the score matrix.

The feature vector is the last bucket's row — what shape the candidate was in when its backtest ended — and that single row is everything the model gets to see about it. A booster is trained on every candidate but the last, which is held back, and then ranks all five; the pick is the highest predicted profit, not the highest realized one. Five candidates and a handful of scores are a demonstration size: in practice a candidate carries hundreds to thousands of features, and the same pipeline trains on a CPU.

Code: [23 stats - candidate selection](https://github.com/andreysolovyev381/tse/tree/main/23%20stats%20-%20candidate%20selection)

### 23.1 stats - candidate selection, multithreaded

The candidate selection of example 23 with every candidate scored twice. On each finished account of the grid the builder creates two ex_post objects, one on a single thread and one on every core of the machine, and compares their momentum matrices row by row: bit for bit in every column except `thompson_sampling`, which is random by design and must agree only in where it is NaN. The column is found by its name through `param_name` rather than by a fixed index.

The model is trained on the scores of the all-core object, and the example prints, for every candidate, whether the two matrices agree, then the model's pick. Each account of the grid holds a single robot, and ex_post never uses more threads than there are robots, so this example shows the API and the agreement of the results, not a gain in time.

```python
one_thread = account.create_ex_post(tse.Duration.Days, -1, 5, 1)
all_cores = account.create_ex_post(tse.Duration.Days, -1, 5, os.cpu_count() or 1)
```

Code: [23.1 stats - candidate selection, multithreaded](https://github.com/andreysolovyev381/tse/tree/main/23.1%20stats%20-%20candidate%20selection,%20multithreaded)

## Everything else

### 24 misc - core affinity

Every worker in the export surface takes a core identifier as its trailing argument — the account, each execution, each input, each pattern and the robot itself. A non-negative value pins that worker to the named core, and -1 leaves the choice to the operating system. Cores 0 and 1 stay reserved for the operating system, so 2 is the lowest core a worker may be nailed to and anything below it is refused.

The example runs one AAPL trend follower twice, once with everything unpinned and once with the two inputs and the account's blotter nailed to cores, and prints both results side by side. They agree, and that is the claim being made: affinity buys latency stability under load, never a different trade. What it costs is that you now own the topology, which is why the unpinned layout remains the sane default outside a latency budget.

Owning the topology comes with one rule the example follows: a chain input → pattern → rule → robot takes a thread of its own only once. Here each input takes one, on cores 2 and 3, and the patterns, rules and robot, left at -1, run on the thread of whichever input has just updated them. The blotter takes core 4, since every booking waits until its thread has made it, so the pinned layout needs a processor with at least five cores.

### 25 misc - multicurrency

An account's reporting currency is fixed when the account is created and cannot be changed afterwards, and accounts of different reporting currencies run side by side in one process. Every contract declared on an account carries that account's currency, so a single account's books are read in one currency throughout; a market of another currency may still feed it, and amounts then reach the reporting currency through the exchange rate table described in the environment chapter.

An account denominated in euro. The currency is the third argument of account construction, given as its three-letter code, and everything downstream inherits it: prices, cash, booked profit and loss, the summary, the portfolio mark. The strategy itself is a single clean round trip driven by two timestamp patterns — ten units bought at 100 and sold at 110 — because the subject is the unit, not the edge.

The grid runner carries the same parameter, so a whole sweep can be run on a euro book, and the example does exactly that after the single backtest. Where a conversion is needed, the engine takes it from the exchange rate table rather than guessing: the rate you set yourself wins, a rate read off a currency market comes next, and one for one with a single line in the log is the last resort. The rate that held at the moment of execution is written into the trade's row, and the monetary columns stay unconverted beside it.

Code: [25 misc - multicurrency](https://github.com/andreysolovyev381/tse/tree/main/25%20misc%20-%20multicurrency)

### 26 misc - storage regimes

One robot, two storage regimes. The same WTI crossover backtest runs with the blotter in memory and with the blotter on disk in the configured data folder, the regime being nothing more than the second argument of account construction, and both runs agree on net profit and trade count.

The regime decides where the statistics live, never what the strategy does: memory is the fast research mode, the database regime leaves an auditable file behind, and a combined regime gives both. Because the database regime writes into the folder set by the process-wide parameters, this example and 01 hello world - initial params are two halves of one subject.

Code: [26 misc - storage regimes](https://github.com/andreysolovyev381/tse/tree/main/26%20misc%20-%20storage%20regimes)

### 27 misc - manual booking

The portfolio without an adapter and without an execution. A contract is registered directly with the portfolio, and fills the engine never placed — a phone order, another desk, an import from a system of record — are booked by hand.

Booking has two modes and the difference matters. The plain mode runs the average-cost engine: a long five at 100 opens the position, a short two at 110 realizes a positive booked profit and leaves three, a final short three flattens it. The engine computes the profit and loss; the caller only reports what traded. The exposure-parameterized mode instead prices the fill against contract and portfolio exposure snapshots the caller supplies — it answers with the profit and leaves the live position exactly as it was, which is how a what-if is costed or an external record imported without disturbing the book. The Account chapter describes both entry points in full.

Code: [27 misc - manual booking](https://github.com/andreysolovyev381/tse/tree/main/27%20misc%20-%20manual%20booking)

### 27.1 misc - seeded position

A desk that is already long does not start from nothing, and this example starts it where it actually stands: the position is handed to the account at the moment the account is created, and the first thing the engine knows about the contract is that ten of it are held at a hundred. Nothing trades, nothing is journalled, and the position is there to be read back immediately.

The whole of it is one extra argument to account construction, an array of seeded positions. Each record names the contract by its handle and carries six numbers: the quantity, the acquisition price with its stamp, the market price with its stamp, and the side. The library raises the market-price flag itself; the highest and the lowest price seen are deliberately not seedable, so a trailing protective order placed afterwards measures from the first price that arrives rather than from a past the engine cannot verify. There is no field for the unrealized result, because the engine computes that from the two prices and the quantity.

The difference from example 27 is the subject, not the spelling. Manual booking is about the accounting of transactions and the profit and loss they realize: it moves a position by reporting a fill. Seeding is about where the work begins: it states a position that was already there. A seeded position is a real position to the engine, so a closing, reducing or rebalancing rule is accepted against it, whereas an entry rule is refused for the same reason it would be refused after a genuine fill — the desk is not flat. The set is taken whole or not at all: a record with no contract, a contract named twice, or a side and a quantity that contradict each other refuses the whole account, and the reason is readable through the initialization error. Nothing of the seed reaches the journal or the save recipe, so a summary over a seeded account reads as it would over an empty one, and a saved robot reloaded elsewhere comes back flat. The Account chapter describes the two seeding entry points in full.

Code: [27.1 misc - seeded position](https://github.com/andreysolovyev381/tse/tree/main/27.1%20misc%20-%20seeded%20position)

### 28 misc - bulk actions

Emergency and end-of-day controls, addressed by robot label, in three scenarios built on one rig: an entry that fills at the market and an exit that rests as a limit far above it, so there is always both a position and a resting order to act on.

The first scenario cancels the resting orders and flattens the position without stopping the robot, which promptly trades again — these two actions clean the desk, they do not close it. The second is the panic button that keeps the risk: the robot is halted and the resting exit withdrawn, so the probe price that would have filled that exit now does nothing and the position stays open. The third is the panic button that leaves no risk behind: the robot is halted and the position closed at the market, so every later signal reaches a flat desk. The composite that does all three — halt, clean the venue, go flat, in that order — is the kill switch.

```python
account.cancel_all("BulkRobot")
account.sale_all("BulkRobot")
account.halt_and_cancel_sale_all("BulkRobot")
```

Code: [28 misc - bulk actions](https://github.com/andreysolovyev381/tse/tree/main/28%20misc%20-%20bulk%20actions)

### 29 misc - timeserie tools

The data-handling toolkit that surrounds the engine, exercised as one pipeline: a CSV of daily Apple closes is read with an explicit date format, separator and header setting; the index and one named column come back as a timestamp series and a value series; the series is cut down to calendar year 2010 by nanosecond bounds taken as midnight UTC on the first of January in each of two years, so the year is taken whole and neither neighbour leaks in.

The filtered series is written back out with formatted timestamps and then read again, because what the writer put on disk is a series in its own right. Then `head` and `tail` hand back a begin-and-length window into the series rather than a copy of it, a count split cuts the year into segments of five trading days each, an inner join intersects the whole series with the filtered one and returns each side with its own length, and one timestamp crosses between text, nanoseconds and calendar components through the three conversion calls. These tools exist so that data preparation uses the same arithmetic as the engine itself, and the Timeserie tools chapter documents the transforms the toolkit adds beyond reading and writing.

Code: [29 misc - timeserie tools](https://github.com/andreysolovyev381/tse/tree/main/29%20misc%20-%20timeserie%20tools)

### 30 misc - statistics

The measures the engine computes over a series, asked directly. A field of the bar is projected out of the records into a flat array of doubles, and everything after that is plain numbers: the moments in one pass, the median, the ninetieth percentile, the interquartile range, then two robust measures of scale that barely move when a few observations do.

The trend is read by two tests that assume nothing about the shape of the series — the Theil–Sen slope and the Mann–Kendall statistic — and both are asked over the last sixty days rather than over the whole history, because the slope is quadratic in the number of observations and the example says so where it does it. The interval for the mean is built on the Student distribution and takes the tick range itself. The correlogram closes the run: it is an array rather than a number, one value per lag, lag zero included, where the value is always one.

Every one of these calls may legitimately have no answer — an empty sample has no mean, a zero-mean sample has no coefficient of variation — which is why each returns an optional in C++ and `None` in Python instead of a number and a flag. The statistics chapter states that contract once and lists all sixty-five entry points.

Code: [30 misc - statistics](https://github.com/andreysolovyev381/tse/tree/main/30%20misc%20-%20statistics)
