# solo76 — solo76 Engine reference Version 6.0.0.0, ABI 11. # Disclaimer The solo76 Engine, this website and the services offered on it are provided "as is" and "as available", without warranty of any kind, express or implied, including warranties of merchantability, fitness for a particular purpose and non-infringement. No warranty is given that their use will be uninterrupted or error-free, or that it will produce any particular trading, investment or financial outcome, a profit, or the avoidance of a loss. To the maximum extent permitted by law, Andrey Solovyev PR accepts no liability for any loss or damage arising from the use of, or the inability to use, the solo76 Engine, this website or the services offered on it, including trading losses, lost profits, revenue or data, and indirect, incidental, special, consequential or punitive damages. Where liability cannot be excluded but can be limited, it is limited to the fees you paid in the twelve months preceding the event giving rise to the claim. Nothing here excludes or limits liability that applicable law does not allow to be excluded or limited, including liability for intent or gross negligence, or any right that consumer-protection law gives you. The solo76 Engine is a computational tool. Nothing in it, in its documentation or on this website is financial, investment, trading, legal, accounting or tax advice, a trading signal, or a recommendation to buy or sell any instrument; the example robots illustrate the programming interface and are not strategies recommended for trading. Trading financial instruments carries a substantial risk of loss. Results of backtests and paper trading are hypothetical: they are computed on historical or simulated data, cannot reflect every condition of a live market, and do not predict live results. Every trading and investment decision, including the decision to run code or a strategy written by you, by a third party or by an AI model, is yours alone and is made at your own risk, and you alone are responsible for complying with the laws and regulations that apply to you. # 1. What the engine does The solo76 Engine is a high-performance backtesting and trading engine. It processes large data volumes, handles complex portfolios, produces extensive statistics, and makes ML and AI models straightforward to integrate. It ships as a single binary — one shared library exposing one narrow C ABI, `tse_*` functions over `Tse*` types — with two thin wrappers on top: C++ in namespace `tse` and Python in module `tse`. All three surfaces drive the same machine, and `tse_abi_version()` reports the ABI generation they belong to, currently **10**. The library respects your privacy by construction: it runs on your own premises, and your market data, your strategy code, your models and your results never leave them — the engine reaches the network only where you point it, through the connectors you configure, and on its own behalf only for the licence check the environment chapter describes. Two audiences are assumed throughout, and the engine is a single answer to both: the researcher who wants thousands of candidates measured the same way, and the engineer who has to put one of those candidates into production without rewriting it. That is why this manual describes one pipeline instead of a research tool and a separate trading tool. A run has the same shape whatever it is for. Market data arrives tick by tick; your own code turns it into the series you care about; the engine watches those series for the conditions you declared, converts a firing condition into an order, puts the order through the risk checks, executes it, and journals the result. What comes out the far end is not a single number but a book of statistics: every retained trade, the exposure that stood behind it, and the per-period scores a model can learn from. Everything the engine does is done by a **robot**: a small graph of named nodes that turns a stream of market data into orders, and orders into a book of statistics. How that graph is assembled is the subject of the chapter on how a robot works. The engine's claim is that a very small vocabulary is enough for all of it. An Input turns ticks into a number; a Pattern watches Inputs and fires; a Rule turns a firing into an order; a Robot owns a set of Rules; an Account owns the robots. That vocabulary is the whole of it, and it does not grow as the strategy gets harder. A two-line moving-average crossover is written with those five nodes; so is a machine-learned model that finds the pattern for you; so is an imbalance signal computed from the full depth of the order book; so is a market maker that quotes both sides and amends its live orders as client flow arrives. What differs between them is the code inside one callable and the parameters on the rules — never the shape of the assembly. The examples chapter walks exactly that ladder, from the first rung to the last. The rest of the manual is ordered as a build. The risk management chapter states what the engine refuses to let a robot do. The chapters on the Input, the Pattern, the Rule and the Robot take the nodes of the graph in the order data flows through them, and the Account chapter covers the object that owns all of them and holds the statistics. The chapter on the environment describes what surrounds a run — contracts, executions, currencies, logging and the ex_post scores; the order-book chapter and the timeserie-tools chapter cover the two specialised subsystems, the statistics chapter the measures the engine computes over a serie, and the chapter on the built-in input processors the ones it ships ready to declare. The examples chapter is a course of complete strategies, and the appendix holds the reference tables. ## Why an engine at all A model can now be written in minutes. A moving average, a gradient booster, a transformer scoring the news — the code for the part that decides is no longer the expensive part, and it gets cheaper every month. What did not get cheaper is being right about money. Position accounting through a reversal; the average cost a realised profit is measured against; the exposure snapshot taken at the instant of the fill and not a tick later; the order that has to be refused before it is sent rather than explained after; two feeds whose timestamps must line up; a simulator that must not accidentally see the future — these are invariants, not code. A generated implementation of any of them is plausible on sight and wrong in a way that surfaces only as a number you believed. A backtest that is wrong still prints a profit. So the boundary moved rather than vanished. The scarce thing is now the verified machine underneath the strategy, and that is what this library is: the parts that have to be right, and have to behave identically in research and in production. What sits above them — the edge, the feature, the model — is yours, and the engine never looks inside it. Your processor is a function pointer and a pointer the engine does not interpret; whether a person or a model wrote what is behind it changes nothing here. Three properties make that division worth buying rather than rebuilding. The same binary backtests and trades, so a candidate goes live by swapping its two ends and nothing in between is rewritten. Every candidate is measured the same way, which is what begins to matter once candidates are generated by the thousand: the same statistics for a two-line crossover as for a deep model, and the per-period features a selection model ranks them with. And the boundary is one narrow C ABI under thin C++ and Python wrappers, so whatever language your tooling emits attaches without touching the engine. The inversion is worth stating plainly. Cheap strategy generation raises the value of a library like this one rather than lowering it: when producing candidates costs nothing, the bottleneck becomes trusting them and comparing them — and trust and comparability are the whole subject of what follows. ## From an idea to production The engine exists to shorten the distance between a research idea and a production robot. The same codebase serves backtesting and trading, which is the single design decision most of the rest follows from. A robot developed against historical data goes live by swapping only its two ends — the market-data source it reads and the execution it trades through — while the strategy graph, the risk checks and the statistics stay untouched. Nothing in between is rewritten, re-tuned or re-implemented on the way to production, and nothing in between can therefore behave differently there. The built-in Simulator is an execution like any other, and the robot above it cannot tell the difference: whether an order is filled from historical prices or handed to a broker is a property of the execution attached to the account, not of the strategy. That is the mechanical reason a backtested robot and a live one are the same robot rather than two implementations of one idea. - Runs entirely on the client's own premises — strategy logic and order flow never leave the client's infrastructure. - Separates the decision-making module from the order-routing pipeline: your data processor plugs into an input as an opaque callable, so its logic need never be exposed to the engine. It can be a moving average, a neural network, a gradient-boosted model, or a call to an external service. - Built on architectural ideas from **Developing & Backtesting Systematic Trading Strategies** by Brian G. Peterson (rev. 14 June 2017). The checks that stand between a decision and an order — position limits, exposure limits, stop-loss and take-profit families, and the venue-resting variants of them — are the subject of the risk management chapter. ## Three commitments Backtesting is built around three commitments, and they are what the engine is measured against. - **First**, generalized data ingestion. Any information source that is a time series at all is admissible: market data read from a file, a database or a connector; the output of an ML model; or derived data such as order-flow imbalance computed from the order book. - **Second**, standardized statistics for every strategy candidate. Every run produces SQL-format logging of the retained trades and of the contract and portfolio exposure captured at the moment of each simulated trade — ready for downstream SQL joins with whatever your own processor logged alongside it. - **Third**, feature engineering for ML-based candidate selection. The same run that produces the statistics produces the features a model needs in order to rank one candidate against another. The three are deliberately stated as commitments rather than features, because each of them is a promise about the general case. Ingestion does not privilege one vendor's format or one kind of tick; the statistics are the same for a two-line moving average and for a deep model, so candidates remain comparable; and the features are produced by the run itself, not reconstructed afterwards from logs that were written for human eyes. The data traversal is multithreaded. A single pass over five years of TSLA top-of-book data — three billion BidAsk records — completes in roughly 1,200 seconds on a 24-core / 32-thread i9. Paper trading collects the same statistics and builds the same features as backtesting, and the engine runs thousands of robots concurrently — identical or different. ## The cross-language workflow The intended workflow crosses languages, because research and production rarely want the same one. Develop and backtest a strategy in Python, where the model tooling lives; use ML to select the best candidate out of the many the engine has scored; persist that candidate with one call, `tse_save`; load it in C++ with one call, `tse_load`; attach fresh market adapters and an execution; and put the candidate to trading. What `tse_save` writes is a recipe, at persistence schema version **6**, not live state: the strategy graph — contracts, inputs, patterns, rules and the robot — and nothing else. A data processor is a function pointer and cannot be serialized, so a savable node references it by a string key that the loading process registers again on its own side. Market adapters and the execution are deliberately absent from the recipe, which is exactly what makes the recipe portable: the same graph is attached to a CSV replay in research and to a live feed and a broker in production. Each loaded input arrives unbound and is bound to a fresh adapter before the robot starts. Recipes, processor keys and the storage format are covered in the chapter on how a robot works, and the examples chapter walks the whole round trip in code. The three language surfaces are not tiers of capability. The C ABI is the whole surface, and the wrappers stand directly on it: they add ergonomics — objects with lifetimes and the idioms native to each language — and a set of conventional defaults on top of a C surface that has none, but no behaviour of their own. The appendix tabulates the full name map from every action to its C, C++ and Python spelling, together with those defaults. The direction of travel is not mandatory. A strategy researched in C++ can be saved and reloaded from Python just as easily, and a team that lives in one language never has to cross the boundary at all — the saved recipe is a convenience, not a required stage of the workflow. In code, the round trip is a save on the Python side and a load, a bind and a start on the C++ side. ```python account.save("momentum", "momentum.db") ``` ```cpp account.load("momentum", "momentum.db"); account.bindInput("sma", market); account.start("momentum"); ``` # 2. How a robot works The engine does not execute a program you write; it runs a graph you declare. Market data enters at an adapter, an input turns every tick into a number, a pattern decides when that number means something, a rule turns the decision into a fully specified order, a robot owns the rules and is the thing you start and stop, and an account owns the robots together with everything they touch except the market adapters, which stand on their own and can feed several accounts at once. This chapter walks that chain once, stage by stage, and explains what each stage is for and why it exists at all. It contains no code by design — the names of the calls appear where they belong to the explanation, and the dedicated chapters that follow give every stage its complete surface on all three languages. Two properties hold along the whole chain. Each stage is declared under a unique label and is referred to by that label from the stage above — a pattern names its inputs, a rule names its pattern, a robot names its rules — so the graph is assembled bottom-up out of names rather than out of pointers. And declaring is not running: nothing in the graph touches data until the robot is started. ## Market data arrives at an adapter A market adapter is the single place where the outside world ends and the engine begins. It is a named, typed channel that belongs to no account: named, because inputs and portfolio subscriptions refer to it by that name; typed, because the record it accepts is fixed when it is created and is validated on every push. The handle that creates an adapter and every account the adapter is handed to share it, so one adapter of a currency can feed any number of accounts of that currency, and it lives until the last of them lets go of it. You may create as many adapters as you need — one per feed, per venue, per vendor, per resolution — and the same contract may live on several of them at once. The five adapter types are the five shapes market data takes in this engine. | Adapter type | Record pushed | Push entry points | | --- | --- | --- | | `tse_md_ohlcv` | `TseTickOHLCV` | `tse_market_push_ohlcv` | | `tse_md_bidask` | `TseTickBidAsk` | `tse_market_push_bidask` | | `tse_md_trade` | `TseTickTrade` | `tse_market_push_trade` | | `tse_md_executed` | `TseRetained` | `tse_market_push_executed` | | `tse_md_book` | `TseBookMessage` | `tse_market_push_book` | Data is fed tick by tick, and each push addresses exactly one contract, by the contract handle that `tse_add_contract` returned when the contract was declared. The handle is the contract: it costs no lookup, so a high-rate replay pays nothing for addressing. A contract becomes known to an adapter through wiring only: by binding an input to it, or by subscribing it with `tse_portfolio_subscribe`. There is no standalone call that adds a contract to an adapter, and pushing to a contract the adapter does not carry is an error. Two of the five types are pure input sources. The executed feed carries trades that happened elsewhere, and the book feed carries order-book messages; neither offers a price the portfolio could mark a position against, nor a venue a simulated fill could occur on. A simulator therefore cannot be attached to them, and a portfolio subscription on them is refused with a diagnostic. An adapter is opened with `tse_market_create`, which is given the label the rest of the graph will refer to it by, the `TseMdType` that fixes its record shape for good, and the currency of the accounts it may feed; `tse_market_destroy` releases the share held by the handle, and a refused push leaves its reason on the adapter, readable with `tse_market_last_error`. The order-book chapter covers the book feed in full; the environment chapter covers the loaders that turn CSV files into tick arrays ready to be pushed. ## An Input processes every tick An input is the entry node of the graph and the one place in the whole pipeline where your own ideas live. It is a named, duration-stamped cache built over a set of contracts on one adapter: raw ticks arrive at the adapter, the input hands each tick to your **data processor**, and whatever the processor stores becomes the series that patterns later observe. What crosses the boundary is deliberately minimal. The processor receives the input's storage handle, the contract the tick belongs to, the tick itself and the opaque `userData` pointer it was registered with. It may push a timestamped value into the storage, and it returns a readiness flag — non-zero once the input has enough material to be observed. The engine never inspects the callable — it holds a function pointer of a fixed signature and a pointer it does not interpret, and it calls them. A three-line moving average, a gradient-boosted model, a neural network scoring news sentiment and a call out to an external service are consequently the same object to the engine, and swapping one for another changes no wiring at all. The builders `tse_add_input_ohlcv`, `tse_add_input_bidask`, `tse_add_input_trade` and `tse_add_input_executed` cover the four tick feeds; `tse_add_input_book` and `tse_add_input_book_imbalance` cover the book feed. Each takes the adapter it reads from, the list of contract handles it covers — binding registers those contracts on the adapter — a cache length, an explicit duration and a core id. The callable itself has one type per feed — `TseOhlcvInputProcessor` for candles, and its siblings for the other four — and it stores a value by calling `tse_storage_push` with a timestamp and a number. The Input chapter details every argument and gives each signature. ## A Pattern watches Inputs and fires A pattern is the decision node. It observes one or more inputs by label and emits a signal whenever its condition holds, carrying the timestamp of the input update that produced it and an order — a quantity, a price and a transaction side. The five analytic kinds leave that order zeroed, making no proposal of their own; a formula processor fills in whatever it wants the rule to use. A pattern produces nothing tradeable by itself: a signal becomes an order only through a rule that names the pattern. Six kinds cover the vocabulary of a condition, and each demands an exact number of observed inputs. - `tse_add_pattern_threshold` — one input: fires while the value compares against a constant as asked. - `tse_add_pattern_peak` — one input: fires when the series forms a local peak. - `tse_add_pattern_timestamp` — one input: fires once the input timestamp reaches a checkpoint, then every cool-down thereafter. - `tse_add_pattern_comparison` — two inputs: fires while one compares against the other at the same timestamp. - `tse_add_pattern_crossover` — two inputs: fires on the bar where that comparison flips from false to true. - `tse_add_pattern_formula` — any number of inputs: your callback receives each update, decides, and fills the order the signal will carry. The comparison itself is a `TseCmp` value — `tse_cmp_ge`, `tse_cmp_lt`, `tse_cmp_gt`, `tse_cmp_le`, `tse_cmp_eq`, `tse_cmp_ne`. Every builder takes an explicit `TseDuration`: the engine never derives a pattern's duration from the inputs it observes, exactly as it never derives an input's own. Every builder also takes a mandatory core id, which pins the pattern's worker thread or asks for no separate thread at all. The Pattern chapter gives each kind its exact firing semantics. ## A Rule turns a firing into an order A rule is the bridge between observation and action. Everything the resulting order will carry is fixed when the rule is built — the transaction side, the position side that must hold, the quantity mode and quantity, the price form and limit price, slippage, fee, time-in-force and the rule's priority among the observers of the same pattern. Those ten values travel together in `TseRuleParams`, and none of them has a library-supplied default. The contract is not one of them: it is named separately, as the trailing contract handle argument of the builder. Three of the ten may be left undefined — the quantity mode, the price form and the transaction side — and each one left undefined is taken from the order the signal carries, on every firing. - `tse_add_rule_market` — the market channel proper: an entry, an exit, a rebalance or a flip, selected by `TseRuleType` and bound to a pattern. - `tse_add_rule_risk` — the stop-loss and take-profit families, fixed or trailing. This rule takes no pattern at all: it watches the position and fires when the unrealized-P&L ratio crosses its threshold. - `tse_add_rule_multileg`, `tse_add_rule_bracket`, `tse_add_rule_oco` — several legs emitted as one atomic transaction, an entry with venue-resting protective legs, and a one-cancels-other pair. - `tse_add_rule_cancel`, `tse_add_rule_replace`, `tse_add_rule_modify` — amendments of an order already in flight. A rule decides what to send; it does not decide what is permitted. Permission is a separate layer: risk policies declared with `tse_add_risk_policy` and `tse_add_risk_policy_time_period` gate orders on position value, on position quantity and on the trading window before anything reaches the execution. The risk management chapter treats that layer on its own, and the Rule chapter documents every field of `TseRuleParams`. ## A Robot owns a set of Rules A robot is the execution node that closes the graph at the top, and the unit at which the engine is operated. It is declared over rules that already exist, it receives every instruction those rules emit, and it forwards each one into the account's order management under its own label. Because that label travels onward with every reservation, fill and journaled trade, results can be read back per robot on an account running many robots at once. A robot is declared with `tse_add_robot`, which is handed the labels of the rules it is to own. Since a rule names its pattern and a pattern names its inputs, adding a robot transitively takes in a whole dependency component whose leaves are inputs. Wiring alone changes nothing: `tse_start` is what sets the component in motion, `tse_stop` and `tse_halt` bring it to rest, and the bulk actions `tse_cancel_all`, `tse_sale_all`, `tse_halt_and_cancel_all`, `tse_halt_and_sale_all` and `tse_halt_and_cancel_sale_all` combine halting with withdrawing resting orders and flattening positions. The robot is also the unit the licence counts. Starting one takes a seat keyed by the account and the robot label; stopping or halting it returns that seat. There is a single pool of seats: a robot that backtests, a robot that trades live and a robot started by a grid search all count against the same purchased number of robots, and the applied ceiling, whether the licence is unlimited, and the observed peak are readable at any time through `tse_protection_status`. ## An Account owns the robots The account is the root of every run. It is created first with `tse_account_create` — which asks for a label, a storage regime, a currency and a core id, and supplies no default for any of them — everything else except the market adapters is declared on it, and every result is read back through it. The account owns the single execution, the books, the portfolio that carries the positions, and the blotter that journals the trades — the storage regime chosen at creation selects whether that blotter lives in memory, in a database, or in both. A contract belongs to no account: `tse_add_contract` declares it in the library itself, and the handle it returns stays good for the whole life of the process, so the same contract may be wired into any number of accounts. Handles taken from an account are borrowed views into it, so the account is destroyed last. The market adapters are not among them: an adapter handed to an account is held by it jointly with the handle that created the adapter and with every other account the adapter feeds, so the adapter and the accounts may be destroyed in any order. The execution is the account's outbound edge, and there is exactly one of it. `tse_exec_create_simulator` builds the engine's own fill model, which is connected to market data and fills orders as ticks arrive. `tse_exec_create_custom` builds an execution that is not connected to market data at all: it hands each order to your callback, which reports fills back with `tse_exec_apply_fill`. Swapping one for the other is the whole distance between a backtest and live trading — the graph above it does not change. The declaration order follows the dependency order. - Declare the contracts an already-open position names, if there is one. - Create the account, seeding those positions into it if there is one, then declare the remaining contracts. - Create the market adapters the data will arrive on. - Create the execution, simulated or custom. - Declare the inputs, naming their adapter and contracts. - Declare the patterns over the input labels. - Declare the rules over the pattern labels, and the risk policies that gate them. - Declare the robot over the rule labels. - Start the robot, then push data. Every contract a running robot trades is marked to market automatically; `tse_portfolio_subscribe` adds further contracts you want marked without trading them. The Account chapter covers the portfolio, the booking calls and the resets in full. Positions a client already holds enter at the very top of that order, not partway down it. The seeding form of account creation takes them as an array and builds them into the portfolio while the account is being built, which is before any rule, any robot and any tick, so the robots that are declared afterwards see a book that is already populated. This is the reason the step belongs here rather than among the booking calls: booking reports a transaction and moves a position, while seeding states the position the run begins with. ## What comes back Fills return along the same chain in the opposite direction. Each one moves the portfolio, so the position and the account aggregate are current at any instant: `tse_get_position_state` snapshots one contract into `TsePositionState`, `tse_get_portfolio_state` snapshots the whole book into `TsePortfolioState`. Each fill is also journaled by the blotter as a retained trade. `tse_get_trades` reads them back as `TseTrade` records, filtered by time range and optionally by robot. A retained trade is deliberately wide: besides price, quantity, fee and booked P&L it carries both order identifiers, the rule and robot labels that produced it, and the contract and portfolio exposure captured at the moment of the trade — which is what makes the journal joinable against whatever your own processor logged. Aggregates come from the same store. `tse_get_summary` folds the whole account into a `TseSummary`; `tse_get_robot_summary` and `tse_get_summaries` do the same per robot. Beyond the summary lies the ex-post layer, which buckets each robot's trades over a time step and scores them: `tse_ex_post_create` builds a live object on as many threads as it is given, its feature matrices are read through `tse_ex_post_feature_momentum`, `tse_ex_post_feature_ewma` and `tse_ex_post_feature_level_crossings` — the projections a model uses to choose among strategy candidates — `tse_ex_post_save_compact` and `tse_ex_post_save_complete` write what the object holds into an SQLite database without scoring again, and `tse_ex_post_open` and `tse_ex_post_rebuild_from_file` read such a database back — the first for its features alone, the second to carry the run forward over the trades that have arrived since. Trades executed outside the engine can be folded into the same picture with `tse_book_trade` and `tse_book_trade_with_exposure`. ## The whole assembly at a glance ![Engine architecture: market data, model output and derived series are pushed into a named market adapter, which stands on its own and may be shared by several accounts; the chain then runs Input, where your data processor lives, then Pattern, which fires on a condition, then Rule, which turns a firing into one fully specified order, then Execution, the simulator in a backtest and your callback when live; a robot is a named set of rules and is the unit that starts and stops; contracts are declared in the library and reach the chain as handles; pre-trade risk is computed at the rule, and bracket and OCO orders are left resting at the venue; the account owns the money and remembers what happened; ExPost reports the summary, every retained trade and the duration-bucketed scores.](https://solo76.com/img/reference/architecture.png) Every robot is assembled by 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. The three surfaces differ in spelling alone — the same twelve steps in the same order on each. Read the diagram in that order and the chain explains itself: the outside world stops at the adapter, your own thinking lives in the input and nowhere else, the pattern is where thinking becomes a decision, the rule is where a decision becomes a fully specified instruction, the robot is the thing you switch on, and the account is what owns the money and remembers what happened. Nothing above the input knows what your processor computed, and nothing below the rule knows why it was asked to trade — which is what lets you replace either end without disturbing the other. This chapter has deliberately shown no code: it is the map, not the manual. The chapters that follow give each stage its complete surface on all three languages, and the examples chapter opens with this same assembly written out end to end, from a moving-average crossover to a book-imbalance market maker. # 3. Risk management Every robot in this engine trades against a constraint, and the first architectural decision you make about a strategy is where that constraint is evaluated: inside the engine, on your own machine, against your own view of the portfolio — or at the venue, inside a protective order that has already left you. The engine supports both, they can be mixed freely on one account, and they are not two spellings of the same thing. This chapter states the choice, then documents each side; the exhaustive builder reference stays in the Account chapter for policies and in the Rule chapter for rules. ## Two places where risk can live **Risk computed inside the engine.** Here the account holds the constraint and the engine is the authority. A risk policy (`tse_add_risk_policy`) is a named, account-attached limit checked before an order is allowed out: the engine reserves the order's exposure, tests the policy against the resulting portfolio, and refuses the order if the policy does not hold. A risk rule (`tse_add_rule_risk`) is the second form: it subscribes to a contract's exposure and emits a closing order when the position's unrealized-P&L ratio crosses a threshold. Both see the whole portfolio, both are reproduced bit for bit in a backtest — the very same code runs there — and both are alive only as long as your process is. A stop that lives in the engine protects nothing while the engine is down. **Risk delegated to the venue.** A bracket (`tse_add_rule_bracket`) and a one-cancels-other pair (`tse_add_rule_oco`) do not keep the decision. They emit protective orders with their trigger levels already priced and hand them to the execution point — the Simulator in a backtest, the exchange in production. From that moment the protection is out of your hands in both senses: you cannot recompute it from portfolio state, and it no longer depends on your process being alive. A resting stop survives a crash, a disconnection and a restart. What you give up is exactly what you gained on the other side: the venue sees one contract and one price, never the portfolio, and it cannot refuse an order — it can only execute a level you fixed in advance. | Property | Computed inside the engine | Left at the venue | | --- | --- | --- | | Builders | `tse_add_risk_policy`, `tse_add_rule_risk` | `tse_add_rule_bracket`, `tse_add_rule_oco` | | What arms it | attachment to the account; subscription to the exposure | a pattern firing | | What it watches | the position's unrealized-P&L ratio; the portfolio aggregate | a price level around the entry fill | | Scope | one contract or the whole portfolio | one contract | | Can refuse an order before it leaves | yes, a policy does exactly that | no | | Survives the loss of your process | no | yes | Two differences between the two sides must be read carefully, because they are what makes a number copied from one side to the other wrong. **A threshold on one side is not a threshold on the other.** The `thresholdRatio` of a risk rule is a ratio of the position's unrealized P&L: the engine forms `r` as the contract's unrealized P&L divided by its acquisition value and compares that against the threshold. The `ratio` of a venue risk leg is measured in price space around the entry fill: for a long position the stop trigger is priced at `entry - entry * ratio` and the take-profit at `entry + entry * ratio`, mirrored for a short. The two are different measurements of different quantities, and a value tuned on one side has to be re-derived for the other, never ported. **A bracket needs a pattern to arm it; a risk rule needs none.** `tse_add_rule_bracket` and `tse_add_rule_oco` are market-channel rules: both take a `patternLabel`, and they emit nothing until that pattern fires. `tse_add_rule_risk` takes no pattern label at all — it watches the exposure directly and fires on what the position does, whatever the market is printing. A venue-resting protection is therefore always placed by a signal; an engine-side protection is permanently attached to the position. ## Risk computed inside the engine ### The pre-trade gate A risk policy is a named constraint attached to the account and evaluated at submit time. Three kinds exist, selected by `TseRiskPolicyType`: `tse_risk_policy_value` limits the combined market value of a position or of the whole portfolio, `tse_risk_policy_quantity` limits a position's combined quantity and is per-contract only, and `tse_risk_policy_time_period` is a trading window rather than a magnitude. A threshold policy holds while ` threshold`. The quantity policy is meaningful per contract only — attached portfolio-wide it never holds, because quantities of different instruments are not summable. Both magnitudes are measured on the combined view — the filled part together with the reservations of orders already resting — and that is the property the gate rests on: a second submission is weighed against the first while the first is still alive, so the limit cannot be walked past by splitting one order into two. Read on the realized view the gate would see a flat book under a resting order and let the whole size through twice. The time-period policy is a repeating trading window: `cyclePeriodNs` is the cycle length, `offsetNs` the window start inside the cycle and `activeDurationNs` the window length, all in nanoseconds, and the policy holds while local wall-clock time falls inside the active window. `timeZoneName` is an IANA zone name; an empty name selects the host machine's zone, and an unknown name fails the call with a diagnostic. **The enforcement rule is asymmetric, and this is the property to build on.** While an attached policy does not hold, submissions and amendments that would **increase** exposure are refused: the transaction is rolled back, never reaches the execution, and the refusal is logged with the policy's diagnostic. Transactions that do not increase exposure — reductions and closes — are never blocked. A robot can therefore always trade out of a position a policy has capped, and a breached limit can never trap you inside the position it was meant to bound. The refusal is atomic on the robot side as well: every reservation the submission took, including all legs of a multileg, is rolled back together, and the robot stays active and processes the next signal normally. The Robot chapter describes that gate among the other places an update can be dropped; the Account chapter carries the full policy reference. **Scope is chosen by the contract**: naming a contract makes the policy per-contract, while the value that makes it portfolio-wide is spelled differently in each language. | Language | Portfolio-wide contract | | --- | --- | | C | `NULL` | | C++ | `nullptr` | | Python | `None` | ```c TseStatus tse_add_risk_policy(TseAccountHandle account, char const* label, TseRiskPolicyType policyType, TseContractHandle contract, double threshold, TseCmp comparison); TseStatus tse_add_risk_policy_time_period(TseAccountHandle account, char const* label, TseContractHandle contract, int64_t cyclePeriodNs, int64_t offsetNs, int64_t activeDurationNs, char const* timeZoneName); TseStatus tse_remove_risk_policy(TseAccountHandle account, char const* label, TseContractHandle contract); ``` ```cpp account.addRiskPolicy("MaxValue", tse::RiskPolicy::value, 1'000'000.0, tse::Cmp::le); account.addRiskPolicyTimePeriod("Session", &wtiContract, dayNs, openOffsetNs, activeNs, "America/New_York"); account.removeRiskPolicy("MaxValue"); ``` ```python account.add_risk_policy("MaxValue", tse.RiskPolicy.Value, 1_000_000.0, tse.Cmp.Le) account.add_risk_policy_time_period("Session", wti_contract, day_ns, open_offset_ns, active_ns, "America/New_York") account.remove_risk_policy("MaxValue") ``` ### The position watchers `tse_add_rule_risk` builds the four position-watching rules — `tse_rule_stop_loss`, `tse_rule_take_profit` and their trailing variants `tse_rule_stop_loss_trailing` and `tse_rule_take_profit_trailing`. The rule is bound to the named contract's exposure and takes no pattern. `thresholdRatio` is a positive magnitude compared against the position's unrealized-P&L ratio; a zero threshold never fires. Writing that ratio as `r` and the threshold as `theta`, the four laws are: - **Fixed stop-loss** fires when the loss reaches the threshold: `r <= -theta`. - **Fixed take-profit** fires when the gain reaches the threshold: `r >= +theta`. - **Trailing stop-loss** tracks the running extreme of the position's mark and fires when the retreat from that extreme reaches `theta`. - **Trailing take-profit** first arms — the extreme must itself have travelled `theta` in the position's favour — and only then fires on a retreat of `theta` from it. The order the firing emits is described by the same `TseRuleParams` every trade rule uses: a stop on a long is typically `txnSide` short, `posSide` long, quantity mode `tse_quantity_all`. The undefined forms are the one part of that structure a risk rule may not use: it observes the position rather than a pattern, so there is no signal to read a field from, and a risk rule whose quantity mode, price form or transaction side is undefined is refused at build time. The `posSide` guard applies here exactly as elsewhere — a rule declared for a side the portfolio does not hold simply never fires. The Rule chapter documents the parameter structure field by field. ```c TseStatus tse_add_rule_risk(TseAccountHandle account, char const* label, TseRuleType ruleType, TseRuleParams const* params, double thresholdRatio, TseContractHandle contract); ``` ```cpp account.addRuleRisk("Stop", tse::RuleType::stop_loss, params, 0.02, wtiContract); ``` ```python params = tse.make_rule_params(tse.Quantity.All, 0.0, tse.Price.Market, 0.0, 0.0, 0.0, tse.Side.Short, tse.Side.Long, tse.Tif.Day, 0) account.add_rule_risk("Stop", tse.RuleType.StopLoss, params, 0.02, wti_contract) ``` ## Risk left at the venue A bracket is an entry order that carries its own protection; an OCO is that protection placed alone, on a position that already exists. Both are built from one specification: a pair of optional risk legs and the time-in-force both resting orders share. **The protection is materialized from the position, not from the rule.** Nothing rests at the venue at the moment the rule is built, and nothing rests there when the pattern merely fires. The engine waits for a fill on the contract, reads the position's side, open quantity and acquisition price from the exposure, prices the legs off that acquisition price, sizes them to the open quantity and sends them out as non-replaceable market orders on the side opposite the position. A fixed leg carries an absolute trigger level; a trailing leg carries the ratio and is re-priced against the running extreme. On a partial fill the pair is re-materialized: the previous legs are cancelled and replaced by legs priced and sized against the new position. An OCO fired while the contract is flat has nothing to protect and is refused with `no open position to protect`. **One-cancels-other is the sibling law.** When one leg of a pair executes, the engine cancels the other in the same step. A bracket whose specification carries both legs produces exactly the same linked pair as an OCO, attached to its entry. **What the Simulator does with a resting protective order.** In a backtest the Simulator stands in for the venue. It accepts the protective leg, opens a trigger state for it — the running price extreme on the position's side, plus an armed flag for the trailing take-profit — and from then on tests the trigger on every market event for the contract, reading the price from the same field its fill model uses for that side (the OHLCV and bid/ask preferences of `TseSimulatorConfig`). While the trigger has not fired the order is not executable at all, however reachable its price would otherwise look. A fixed stop fires when the read price falls to or through its level for a long and rises to or through it for a short; a fixed take-profit fires on the mirror condition; a trailing leg fires when the retreat of the price from the observed extreme, as a ratio of that extreme, reaches the leg's `ratio`. When the order is fully executed its trigger state is discarded. Under a custom execution the same legs are handed to your fill callback as `TseOrder` records the moment they are created, and the record says what each leg is: `txnType` reads `tse_txn_stoploss` or `tse_txn_takeprofit` for a fixed leg and `tse_txn_stoploss_trailing` or `tse_txn_takeprofit_trailing` for a trailing one, `hasTrigger` is 1, `triggerPrice` carries the computed trigger level and `triggerOffset` the leg's `ratio`, while `limitPrice` repeats the trigger level and `priceType` reads `tse_price_market`. A trailing stop-loss carries a zero `triggerPrice` and a zero `limitPrice`, because its level follows the price and only the offset is known when the leg is created. Translating that into whatever resting order type your venue actually offers is the integration's responsibility; the environment chapter describes the custom-execution seam, and the examples chapter runs a fixed bracket, a trailing bracket and an OCO end to end. The specification itself, `TseVenueRiskSpec`, is one structure holding the two legs and the shared time-in-force. | Field | Type | | --- | --- | | stopLoss | `TseVenueRiskLeg` | | takeProfit | `TseVenueRiskLeg` | | tif | `TseTif` | Each leg in turn, `TseVenueRiskLeg`, is a presence flag, a threshold flavor and a ratio. | Field | Type | Meaning | | --- | --- | --- | | `present` | `int32_t` | zero: the leg is absent and the rest of the struct is ignored | | `kind` | `int32_t` | 0 fixed, 1 trailing; any other value is rejected | | `ratio` | `double` | the threshold ratio, in price space around the entry fill | At least one leg must be present — a specification with both legs absent is rejected, a stop-only or take-only specification is legal. Every ratio must be strictly positive; a trailing ratio, and any ratio that would price its trigger through zero (a stop under a long, a take-profit under a short), must additionally stay below 1. A degenerate ratio is refused with a diagnostic rather than silently clamped. ```c TseStatus tse_add_rule_bracket(TseAccountHandle account, char const* label, TseLegDescriptor const* entry, TseVenueRiskSpec const* risk, char const* patternLabel); TseStatus tse_add_rule_oco(TseAccountHandle account, char const* label, TseContractHandle contract, TseVenueRiskSpec const* risk, char const* patternLabel); ``` ```cpp tse::VenueRiskSpec const risk {tse::VenueRiskLeg {true, 0, 0.02}, tse::VenueRiskLeg {true, 1, 0.05}, tse::Tif::gtc}; account.addRuleBracket("Bracket", entryLeg, risk, "PatternToLong"); account.addRuleOco("Oco", wtiContract, risk, "PatternAtNoon"); ``` ```python risk = tse.make_venue_risk_spec(tse.make_venue_risk_leg(True, 0, 0.02), tse.make_venue_risk_leg(True, 1, 0.05), tse.Tif.Gtc) account.add_rule_bracket("Bracket", entry_leg, risk, "PatternToLong") account.add_rule_oco("Oco", wti_contract, risk, "PatternAtNoon") ``` # 4. Input An input is the entry node of a robot: a named, duration-stamped cache of a processed time series, built over a set of contracts on one market-data adapter. Raw ticks arrive at the adapter; the input hands each tick to your **data processor**; whatever the processor stores becomes the series that patterns observe (the Pattern chapter). Every input belongs to an account, is addressed by its unique label, and states its duration explicitly — the engine never derives it. ## Your secret sauce The data processor is the one place in the whole pipeline where your ideas live, and the engine treats it as a sealed box. What crosses the boundary is deliberately minimal: a tick comes in, the processor may push a `(timestamp, value)` pair into the input's storage, and a single readiness flag goes back. Nothing about the computation itself is visible to the engine — it holds a function pointer with a fixed signature and an opaque `userData` pointer, and it calls them. The consequence is full interchangeability. A three-line moving average, a gradient-boosted model, a neural network scoring news sentiment, or a call out to an external service are all the same thing to the engine: a callable that sometimes stores a number and reports whether the input is ready. Swapping one for the other changes no wiring — the same builders, the same patterns, the same rules keep working. The engine supplies the machinery (caching, contract routing, timestamp alignment, threading); the processor supplies the edge. ## Building inputs Six input builders exist. Four are declared in `tse_input.h` — `tse_add_input_ohlcv`, `tse_add_input_bidask`, `tse_add_input_trade`, `tse_add_input_executed`. The remaining two, `tse_add_input_book` and `tse_add_input_book_imbalance`, live in `tse_book.h` with the rest of the order-book surface (the order-book chapter). All four `tse_input.h` builders share one shape and differ only in the processor typedef and tick type. `tse_add_input_bidask` takes a `TseBidAskInputProcessor` over `TseTickBidAsk const*`, `tse_add_input_trade` a `TseTradeInputProcessor` over `TseTickTrade const*`, and `tse_add_input_executed` a `TseExecutedInputProcessor` over `TseRetained const*` — everything else is identical. Note the OHLCV typedef name: ABI version 6 renamed the old `TseInputProcessor` to `TseOhlcvInputProcessor`, making every processor typedef name its feed. The C++ wrapper kept the short alias `tse::InputProcessor` for its OHLCV `std::function` form. Every builder returns `TseStatus`; on `tse_error` the reason is available through `tse_last_error`. The C++ wrapper checks the status for you and throws `tse::Error`; Python raises `tse.TseError`. The builders take the same parameters, whatever the feed: | Parameter | Meaning | | --- | --- | | `label` | the input's unique name; patterns reference inputs by it | | `dataLength` | the required data length of the input's value storage (see below) | | `duration` | a `TseDuration` value, explicit and mandatory. A duration the library build does not carry is rejected with a diagnostic naming the requested duration and the supported set (`tse_supported_durations` enumerates it) | | `processor`, `userData` | your callable and its opaque context; a null processor is rejected | | `market` | the market-data adapter the input reads from. The adapter's type must match the builder (`tse_add_input_ohlcv` demands a `tse_md_ohlcv` adapter, and so on); a mismatch fails the call | | `coreId` | mandatory in C: a non-negative value pins the input's worker thread to that core, a negative value runs the input without a separate thread. Both wrappers default it to `-1` | | `contracts`, `contractCount` | the contract handles the input observes (see "Contract binding") | ```c typedef int (*TseOhlcvInputProcessor) ( TseStorageHandle storage, TseContractHandle contract, TseTickOHLCV const* tick, void* userData ); TseStatus tse_add_input_ohlcv ( TseAccountHandle account, char const* label, int32_t dataLength, TseDuration duration, TseOhlcvInputProcessor processor, void* userData, TseMarketHandle market, int coreId, TseContractHandle const* contracts, size_t contractCount ); ``` ```cpp void Account::addInputOhlcv (std::string label, std::int32_t dataLength, Duration duration, InputProcessor processor, Market const& market, std::vector contracts, int coreId = -1) &; void Account::addInputBidAsk (std::string label, std::int32_t dataLength, Duration duration, BidAskInputProcessor processor, Market const& market, std::vector contracts, int coreId = -1) &; void Account::addInputTrade (std::string label, std::int32_t dataLength, Duration duration, TradeInputProcessor processor, Market const& market, std::vector contracts, int coreId = -1) &; void Account::addInputExecuted(std::string label, std::int32_t dataLength, Duration duration, ExecutedInputProcessor processor, Market const& market, std::vector contracts, int coreId = -1) &; ``` ```python Account.add_input_ohlcv(label, data_length, duration, processor, market, contracts, core_id=-1) Account.add_input_bidask(label, data_length, duration, processor, market, contracts, core_id=-1) Account.add_input_trade(label, data_length, duration, processor, market, contracts, core_id=-1) Account.add_input_executed(label, data_length, duration, processor, market, contracts, core_id=-1) ``` ### Data length and capacity `dataLength` is the requested capacity of the input's value storage — the series your processor pushes into and patterns read from. The storage is a ring: its actual capacity is the requested length rounded **up to the next power of two**, and once it is full each new push overwrites the oldest element. A `dataLength` of 15 therefore yields a buffer of 16, which changes only how much history the node retains — the numbers your processor computes are unaffected. Choose `dataLength` from what your computation needs to look back on; readiness is entirely your call — the engine imposes no minimum fill. ### The processor contract The processor receives four things: the storage handle (valid only for the duration of the call), the handle of the contract whose tick is being processed, a pointer to the typed tick, and your `userData`. Inside the call, two functions operate on the storage. The return value is the readiness flag. Returning non-zero (C), `true` (C++) or a truthy value (Python) declares the input ready: the newest stored value is published to every pattern observing the input. Returning zero declares the input not ready: whatever was pushed stays in the storage, but nothing is published and no pattern sees an update — the engine records the not-ready outcome in its log and moves on. There is no error-code channel out of a processor: not-ready is the only outward signal. The C++ and Python trampolines enforce this — any exception escaping your callable is caught at the boundary and converted into the not-ready return, so exceptions never cross the C ABI. ```c void tse_storage_push(TseStorageHandle storage, int64_t tsNanoseconds, double value); size_t tse_storage_size(TseStorageHandle storage); ``` ```cpp class Storage final { void push(std::int64_t tsNanoseconds, double value) const noexcept; std::size_t size() const noexcept; }; ``` ```python Storage.push(ts_nanoseconds, value) Storage.size() ``` The timestamp you push is the tick's own: the `tsNanoseconds` field of the tick record being processed, in epoch-nanoseconds, passed through unchanged. It travels downstream as it is — it stamps the input update, then the signal a pattern derives from it, then the order a rule issues — and the simulator fills that order only on a market event strictly later than it. A timestamp near zero dates the order to 1970, so it fills on the very next quote but the blotter keeps the false time; a timestamp equal to or beyond the quotes that follow leaves the order unfilled for good. A minimal Python processor — a simple moving average that becomes ready once the window is full: ```python def make_sma(period): window = [] def processor(storage, contract_id, tick): window.append(tick.close) del window[:-period] storage.push(tick.tsNanoseconds, sum(window) / len(window)) return storage.size() >= period return processor ``` ## Feed types Five feeds can drive an input; each pairs one adapter type with one tick record and one processor typedef. | Feed | Adapter type | Tick record | Processor typedef | Builder | | --- | --- | --- | --- | --- | | OHLCV | `tse_md_ohlcv` | `TseTickOHLCV` | `TseOhlcvInputProcessor` | `tse_add_input_ohlcv` | | Bid/ask | `tse_md_bidask` | `TseTickBidAsk` | `TseBidAskInputProcessor` | `tse_add_input_bidask` | | Trade | `tse_md_trade` | `TseTickTrade` | `TseTradeInputProcessor` | `tse_add_input_trade` | | Executed | `tse_md_executed` | `TseRetained` | `TseExecutedInputProcessor` | `tse_add_input_executed` | | Book | `tse_md_book` | `TseBookMessage` | `TseBookInputProcessor` | `tse_add_input_book`, `tse_add_input_book_imbalance` | One asymmetry of the trade feed is worth knowing: the engine's internal representation of the trade channel keeps the traded price only. You push a full `TseTickTrade` (price, volume, side), but a trade-input processor receives the price with `volume` equal to zero and `side` equal to `tse_side_undefined`. ### The executed channel The executed feed turns your own fills into an input: a robot can observe the stream of executed trades exactly the way it observes quotes. The channel has no internal producer — the caller pushes each executed trade into an adapter of type `tse_md_executed`, addressed by its contract handle. The executed feed and the book feed are pure input sources: they carry no price the portfolio could mark against and no venue the simulator could fill on, so a simulator cannot be attached to them and a portfolio subscription on them is refused with a diagnostic. The record is `TseRetained` — the same POD that external trade booking uses (`tse_trades.h`): | Field | Type | | --- | --- | | tsNanoseconds | `int64_t` | | symbol | `char[32]` | | contract | `TseContractHandle` | | clientOrderId | `char[32]` | | brokerOrderId | `char[32]` | | ruleLabel | `char[64]` | | robotLabel | `char[64]` | | tsMktEventNanoseconds | `int64_t` | | tsExecutionNanoseconds | `int64_t` | | price | `double` | | quantity | `double` | | fee | `double` | | bookedPL | `double` | | txnSide | `TseSide` | | posSide | `TseSide` | | bookMode | `int32_t` | | execution | `int32_t` | | priceType | `TsePriceType` | | quantityType | `TseQuantityMode` | | tif | `TseTif` | | priorityType | `TsePriority` | ```c TseStatus tse_market_push_executed(TseMarketHandle market, TseContractHandle contract, TseRetained const* trade); ``` ```cpp void Market::pushExecuted(Contract const& contract, Retained const& trade) const &; ``` ```python Market.push_executed(contract, trade) ``` ### Book inputs `tse_add_input_book` runs your processor over every `TseBookMessage` reaching the bound (adapter, contract) pair; to maintain an actual book inside the processor, create one with `tse_book_create` and apply each message via `tse_book_apply`. `tse_add_input_book_imbalance` is the compiled-in alternative: it feeds every message into a book you supply and stores the whole-book imbalance per message, with zero callback crossings. Both are covered with the rest of the book surface in the order-book chapter. ## Contract binding Contracts are declared in the library (`tse_add_contract`) independently of any account and of any feed; an input's contract list is what places them on an adapter. Building an input registers each named contract on that adapter and wires the input to observe exactly that subset — there is no standalone "add contract to adapter" call, and pushing a tick for a contract not registered on the adapter is an error. Three roles must not be confused: | Role | Established by | Ticks reach the processor | Drives portfolio marking / simulator fills | | --- | --- | --- | --- | | Bound | input's `contracts` list | yes | yes | | Traded | a rule's contract | no | only if also bound or subscribed | | Subscribed | `tse_portfolio_subscribe` | no | yes | An input bound to one contract never sees another contract's ticks, even when both flow through the same adapter. Trading a contract does not feed any input: a robot may observe contract B while its rules trade contract A — the motivating case for the split — provided A is registered on the adapter, which is what `tse_portfolio_subscribe` is for when no input binds it. Subscription gives the portfolio its marking stream and the simulator its fill stream without routing a single tick into a processor. The one hard placement requirement is enforced at start time. Every contract a robot trades must be carried by at least one **price-carrying** market adapter — an adapter of the OHLCV, bid/ask or trade type; the executed and book channels carry no price a portfolio could mark against. `tse_start` looks only at the price-carrying adapters handed to this account — through an input builder, `tse_bind_input` or `tse_portfolio_subscribe`. It walks the started robot's traded contracts and, on every such adapter that carries a traded contract, subscribes the portfolio by itself and, under a Simulator execution, attaches the simulator as well; an adapter that carries the contract but was never handed to this account, such as a shared adapter on which only another account registered the contract, takes no part. When the execution is the simulator and no price-carrying adapter handed to this account carries a traded contract, the start fails with the error `traded contract "…" is on no price-carrying market adapter; the Simulator needs market data to fill it`. Binding an input to the contract is therefore sufficient — the input places the contract on its adapter, and the start does the rest; an explicit `tse_portfolio_subscribe` remains the manual tool for contracts outside any input's list. The contract list is validated at build time, and a failed builder leaves the account fully usable: - an empty list is rejected — at least one contract must be specified; - a null contract handle is rejected; - a duplicated contract within the list is rejected by the core. Finally, an input that no pattern references is inert. `tse_start` claims exactly the started robot's dependency component — robot, its rules, their patterns, and the inputs those patterns observe. A bare input outside that component is never attached: it receives nothing, computes nothing, and costs nothing until some started robot's pattern names it. ## Persistence keys A processor is a function pointer, and a function pointer cannot be serialized. The plain builders above therefore produce a robot that runs but cannot be saved. To make an input savable, register the processor under a string key on the account and build the input with the keyed variant — the recipe then stores the key, and any process that registers the same key can rebuild the input. A saved recipe stores each input with its market-data type, duration, data length, contract subset and processor key — but bound to no adapter. After `tse_load` on a fresh account that has registered the same keys, every loaded input is unbound: create the market adapter(s) and execution you want, then bind each input with `tse_bind_input(account, inputLabel, market)`. Binding checks that the adapter's type matches the input's saved market-data type and registers the input's contract subset on the new adapter. Starting a robot while any loaded input is still unbound is an error. The save/load machinery itself — recipes, keys and the storage format — belongs to the environment chapter. The registration and keyed-builder families cover the four `tse_input.h` feeds: | Feed | C register | C keyed builder | C++ register / builder | Python register / builder | | --- | --- | --- | --- | --- | | OHLCV | `tse_register_input_processor_ohlcv` | `tse_add_input_ohlcv_by_key` | `registerInputProcessor`, `addInputOhlcvByKey` | `register_input_processor`, `add_input_ohlcv_by_key` | | Bid/ask | `tse_register_input_processor_bidask` | `tse_add_input_bidask_by_key` | `registerInputProcessorBidAsk`, `addInputBidAskByKey` | `register_input_processor_bidask`, `add_input_bidask_by_key` | | Trade | `tse_register_input_processor_trade` | `tse_add_input_trade_by_key` | `registerInputProcessorTrade`, `addInputTradeByKey` | `register_input_processor_trade`, `add_input_trade_by_key` | | Executed | `tse_register_input_processor_executed` | `tse_add_input_executed_by_key` | `registerInputProcessorExecuted`, `addInputExecutedByKey` | `register_input_processor_executed`, `add_input_executed_by_key` | The book inputs have no keyed form. Pattern formulas follow the same scheme with `tse_register_formula_processor` and `tse_add_pattern_formula_by_key` (the Pattern chapter). ```c TseStatus tse_register_input_processor_ohlcv(TseAccountHandle account, char const* key, TseOhlcvInputProcessor processor, void* userData); TseStatus tse_add_input_ohlcv_by_key(TseAccountHandle account, char const* label, int32_t dataLength, TseDuration duration, char const* key, TseMarketHandle market, TseContractHandle const* contracts, size_t contractCount); ``` ```cpp void Account::registerInputProcessor(std::string key, InputProcessor processor) &; void Account::addInputOhlcvByKey(std::string label, std::int32_t dataLength, Duration duration, std::string key, Market const& market, std::vector contracts) &; void Account::bindInput(std::string inputLabel, Market const& market) &; ``` ```python Account.register_input_processor(key, processor) Account.add_input_ohlcv_by_key(label, data_length, duration, key, market, contracts) Account.bind_input(input_label, market) ``` # 5. Pattern ## What a pattern is A pattern is the decision node of a robot: it observes one or more inputs, referenced by their labels, and emits a trading signal whenever its condition holds. Patterns produce nothing tradeable on their own — a signal becomes an order only through a rule that names the pattern (`tse_add_rule_market` and the other rule builders take a `patternLabel`, see the Rule chapter). Every signal, from every one of the six kinds, carries the timestamp of the input update that produced it and an order: a quantity, a price and a transaction side. The five analytic kinds leave that order zeroed with an undefined side, which says the pattern makes no proposal of its own; a formula processor may fill any of the three fields. A rule reads from the order only those of the three it was itself declared without (see "The signal order" below). Every pattern builder shares the same leading parameters and the same conventions: - `account` — the account handle the pattern is created on; every builder returns `TseStatus` (`tse_ok` / `tse_error`). - `label` — the pattern's unique name; rules bind to it. - `duration` — a `TseDuration` value, explicit and mandatory. The engine does not derive the duration from the observed inputs; you state it, exactly as you do for inputs. - `inputLabels`, `inputCount` — the observed inputs as an array of C strings plus a count. Each kind demands an exact count and rejects any other. - `coreId` — mandatory. A non-negative value pins the pattern's worker thread to that core; a negative value runs the pattern without a separate thread. The C++ and Python wrappers default this argument to `-1`. ## The six kinds `tse_pattern.h` declares six pattern kinds: comparison, crossover, threshold, peak, timestamp, and formula. The first five are closed analytic conditions parameterized by a `TseCmp` comparator and scalar arguments; the sixth hands the decision to your own code. `TseCmp` has six values — `tse_cmp_ge`, `tse_cmp_lt`, `tse_cmp_gt`, `tse_cmp_le`, `tse_cmp_eq`, `tse_cmp_ne` — mirrored as `tse::Cmp::ge` … `tse::Cmp::ne` in C++ and `tse.Cmp.Ge` … `tse.Cmp.Ne` in Python. ### Comparison Observes exactly two inputs and fires when `lhs rhs` holds for the two input values at the same timestamp. The first label in `inputLabels` is the left-hand side, the second is the right-hand side. ```c TseStatus tse_add_pattern_comparison(TseAccountHandle account, char const* label, TseDuration duration, char const* const* inputLabels, size_t inputCount, TseCmp comparison, int coreId); ``` ```cpp void Account::addPatternComparison(std::string label, Duration duration, std::vector inputLabels, Cmp comparison, int coreId = -1) &; ``` ```python Account.add_pattern_comparison(label, duration, input_labels, comparison, core_id=-1) ``` ### Crossover Observes exactly two inputs and fires on the bar where lhs crosses rhs: the comparison was false on the previous pair of values and becomes true on the current pair. It therefore needs two data points per input before it can fire at all. ```c TseStatus tse_add_pattern_crossover(TseAccountHandle account, char const* label, TseDuration duration, char const* const* inputLabels, size_t inputCount, TseCmp comparison, int coreId); ``` ```cpp void Account::addPatternCrossover(std::string label, Duration duration, std::vector inputLabels, Cmp comparison, int coreId = -1) &; ``` ```python Account.add_pattern_crossover(label, duration, input_labels, comparison, core_id=-1) ``` ### Threshold Observes exactly one input and fires when `value threshold` holds for the input's current value. ```c TseStatus tse_add_pattern_threshold(TseAccountHandle account, char const* label, TseDuration duration, char const* const* inputLabels, size_t inputCount, TseCmp comparison, double threshold, int coreId); ``` ```cpp void Account::addPatternThreshold(std::string label, Duration duration, std::vector inputLabels, Cmp comparison, double threshold, int coreId = -1) &; ``` ```python Account.add_pattern_threshold(label, duration, input_labels, comparison, threshold, core_id=-1) ``` ### Peak Observes exactly one input and fires when the input forms a local extremum: over the last three values, with strictly increasing timestamps, the middle value is either strictly above both neighbours (a crest) or strictly below both (a trough). Both directions fire; there is no separate "valley" kind. ```c TseStatus tse_add_pattern_peak(TseAccountHandle account, char const* label, TseDuration duration, char const* const* inputLabels, size_t inputCount, int coreId); ``` ```cpp void Account::addPatternPeak(std::string label, Duration duration, std::vector inputLabels, int coreId = -1) &; ``` ```python Account.add_pattern_peak(label, duration, input_labels, core_id=-1) ``` ### Timestamp Observes exactly one input and fires on the clock rather than on values: once the input's timestamp reaches `checkPoint`, the pattern fires and re-arms itself one `coolDown` period ahead (aligned to the cool-down grid), so it fires again every `coolDown` thereafter. Both arguments are epoch-nanoseconds. ```c TseStatus tse_add_pattern_timestamp(TseAccountHandle account, char const* label, TseDuration duration, char const* const* inputLabels, size_t inputCount, int64_t checkPointNanoseconds, int64_t coolDownNanoseconds, int coreId); ``` ```cpp void Account::addPatternTimestamp(std::string label, Duration duration, std::vector inputLabels, std::int64_t checkPointNanoseconds, std::int64_t coolDownNanoseconds, int coreId = -1) &; ``` ```python Account.add_pattern_timestamp(label, duration, input_labels, check_point_ns, cool_down_ns, core_id=-1) ``` ### Formula Delegates the firing decision to a user callback and accepts any non-zero number of inputs. The callback contract is the subject of the next section. ```c TseStatus tse_add_pattern_formula(TseAccountHandle account, char const* label, TseDuration duration, char const* const* inputLabels, size_t inputCount, TseFormulaProcessor processor, void* userData, int coreId); ``` ```cpp void Account::addPatternFormula(std::string label, Duration duration, std::vector inputLabels, FormulaProcessor processor, int coreId = -1) &; ``` ```python Account.add_pattern_formula(label, duration, input_labels, processor, core_id=-1) ``` ## The formula escape hatch The formula processor is invoked once per input update and decides whether the pattern fires. The processor is handed the order the signal will carry, zeroed before every call, and whatever it writes there travels with the firing. That is what makes the formula kind the escape hatch for sizing and for direction as well as for logic: the quantity, the price and the transaction side of the resulting trade can all be computed per fire — provided the rule bound to the pattern left them undefined when it was built. Nothing written into the order survives a call: a processor that does not fire, or that reports an error, or that throws, leaves no trace in the next call's order, and the next call starts from zeroes again. The callback's parameters and its return convention: | Parameter | Type | Meaning | | --- | --- | --- | | `inputLabel` | `char const*` | Names the input whose update triggered the call — this is how a multi-input formula discriminates its fan-in: observe several inputs, keep whatever state you need in `userData`, and branch on the label. | | `tsNanoseconds` | `int64_t` | The update timestamp in epoch-nanoseconds. | | `value` | `double` | The input's value at that update. | | `order` | `TseSignalOrder*` | The order the signal will carry, zeroed before every call. Fill the fields the bound rule left undefined; the engine reads it only when the call fires. The pointer is valid for the duration of the call and no longer. | | `errorBuffer` | `char*` | To report an error, write a NUL-terminated message into it; a non-empty buffer suppresses the firing and the engine logs the message. Leave the buffer untouched for no error. | | `errorBufferLength` | `size_t` | The capacity of `errorBuffer`. | | `userData` | `void*` | The opaque pointer handed to the builder, where the formula keeps its state. | | return value | `int` | Return non-zero to fire the pattern, zero to stay silent. | The order itself is a four-field POD declared in the same header: | Field | Type | | --- | --- | | clientOrderId | `uint64_t` | | price | `double` | | quantity | `double` | | txnSide | `TseSide` | `clientOrderId` is carried for your own bookkeeping and the engine does not read it: the trade a rule issues gets a fresh client order id of its own on every firing. Its C typedef, declared in `tse_pattern.h`: ```c typedef int (*TseFormulaProcessor)(char const* inputLabel, int64_t tsNanoseconds, double value, TseSignalOrder* order, char* errorBuffer, size_t errorBufferLength, void* userData); ``` The C++ wrapper form drops the buffer and the `userData` pointer — capture state in the closure instead — and takes the order by reference; a thrown exception is treated as "do not fire": ```cpp using FormulaProcessor = std::function; ``` The Python form is any callable with the same four parameters returning a truthy value to fire; the order arrives as a `tse.TseSignalOrder` whose fields are assigned in place, and an exception raised inside the callable is swallowed and treated as "do not fire": ```python def processor(input_label, ts_nanoseconds, value, order): ... ``` ## The signal order A rule names the quantity, the price form and the transaction side of its trade when it is built, and it may leave any of those three undefined instead. Undefined means "the signal brings it": on every firing the rule copies that field out of the order the pattern published, and leaves the others exactly as they were declared. A rule that declared all three never looks at the order at all, and a risk rule never does either — it is rejected at build time if any of the three is undefined, because a stop has to know its own size in advance. Two of the three fields are read through a value, not through a flag, and the reading is worth stating exactly. - **Quantity.** A non-zero quantity from the signal is the size of the trade. A zero names no size at all, so the rule issues nothing and logs the reason. The whole-position form is a declaration, not something a signal can ask for. - **Price.** A zero price from the signal means at market; any other value means a limit order at that price. Zero can never be a real limit, which is what makes the test safe, and it is also how the engine already stores a market price internally. - **Transaction side.** Taken as the signal left it. A side the signal never set is no side, and the rule issues nothing. The five analytic kinds publish a zeroed order, so a rule behind one of them gets a market price for the asking and nothing else: leave the price undefined behind a threshold and the trade goes out at market, but leave the quantity undefined there and the rule has nothing to issue. Quantity and side from a signal are the formula kind's business. `tse_enums.h` defines `TseQuantityMode` with three values and `TsePriceType` with four; `tse_quantity_mode_to_string` renders a quantity mode as text. The former fourth quantity mode, `tse_quantity_from_signal` (numeric 3), is gone: its meaning now belongs to `tse_quantity_undefined`, and a rule handed the old numeric 3 is refused with a diagnostic. | Mode | C | C++ | Python | | --- | --- | --- | --- | | from the signal | `tse_quantity_undefined` | `QuantityMode::undefined` | `Quantity.Undefined` | | whole position | `tse_quantity_all` | `QuantityMode::all` | `Quantity.All` | | fixed size | `tse_quantity_fixed` | `QuantityMode::fixed` | `Quantity.Fixed` | | Price form | C | C++ | Python | | --- | --- | --- | --- | | from the signal | `tse_price_undefined` | `PriceType::undefined` | `Price.Undefined` | | at market | `tse_price_market` | `PriceType::market` | `Price.Market` | | at a limit | `tse_price_limit` | `PriceType::limit` | `Price.Limit` | | general (rejected by rules) | `tse_price_general` | `PriceType::general` | `Price.General` | ## Persistence A robot is saved as a recipe (schema version 6, see the environment chapter), and the five analytic kinds are fully described by their builder parameters, so they round-trip through `tse_save` / `tse_load` with no extra work. A formula processor, however, is a function pointer that cannot be serialized. To keep a robot with formula patterns savable, register the processor under a string key and build the pattern by key; the recipe then stores the key, and a loading process must register the same key before `tse_load`. The by-key builder takes no `coreId`; a pattern built by key runs without a pinned worker thread. The plain `tse_add_pattern_formula` still runs normally, but a robot containing such a pattern is unsavable: `tse_save` fails. ```c TseStatus tse_register_formula_processor(TseAccountHandle account, char const* key, TseFormulaProcessor processor, void* userData); TseStatus tse_add_pattern_formula_by_key(TseAccountHandle account, char const* label, TseDuration duration, char const* const* inputLabels, size_t inputCount, char const* key); ``` ```cpp void Account::registerFormulaProcessor(std::string key, FormulaProcessor processor) &; void Account::addPatternFormulaByKey(std::string label, Duration duration, std::vector inputLabels, std::string key) &; ``` ```python Account.register_formula_processor(key, processor) Account.add_pattern_formula_by_key(label, duration, input_labels, key) ``` # 6. Rule A rule is the bridge between observation and action: it listens to one event source and, on each firing, emits one fully specified instruction — an order, an amend of an in-flight order, or a whole transaction group. A trade order is one of four position verbs — entry, rebalance, flip or exit — one verb for each move a position can make, and the whole chapter rests on that set. Everything an order will carry — contract, side, quantity mode, price form, slippage, fee, time-in-force — is fixed at rule construction, except that three of those may be declared undefined and then come from the signal on every firing: the quantity, the price and the transaction side. All rule builders live in `tse_rule.h`, attach to an account handle, and every one of them requires a unique rule label: the label is how a robot later collects its rules (`tse_add_robot`), and it travels on every trade the rule produces (the `ruleLabel` field of `TseRetained` and `TseTrade`). ## The four position verbs A position is short, flat or long, and a trade moves it from one of those states to another. Five moves exist. Four verbs name the four that a rule may order, one verb per move, and the fifth, flat to flat, is refused because there is nothing to trade. The quantity is what keeps the verbs disjoint rather than merely differently named: a quantity that breaks the bound of its verb is refused when the order is admitted, the position is left exactly as it stood, and no quantity is ever reinterpreted into a different verb. ![The four position verbs: a position is short, flat or long; an entry leaves flat for either side and needs a flat book; a rebalance stays on its side, and against the side it must be smaller than the position; a flip crosses zero to the other side and must be larger than the position, with all meaning twice the position; an exit returns to flat and must equal the position exactly; flat to flat is refused.](https://solo76.com/img/reference/position_verbs.png) | Position before | Position after | Verb | `TseRuleType` | | --- | --- | --- | --- | | flat | long or short | entry | `tse_rule_entry` | | long or short | the same side, another size | rebalance | `tse_rule_rebalance` | | long or short | the other side | flip | `tse_rule_flip` | | long or short | flat | exit | `tse_rule_exit` | | flat | flat | none | refused | | Verb | Requires | Transaction side | Quantity | Position after | | --- | --- | --- | --- | --- | | entry | a flat book | either | positive | open on the side of the transaction | | rebalance | an open position | with the position it grows, against the position it shrinks | against the position, strictly less than it holds | open on the same side | | flip | an open position | against the position | strictly more than it holds; `tse_quantity_all` is twice the position | open on the other side | | exit | an open position | against the position | exactly what it holds; `tse_quantity_all` is the position | flat, and the entry is armed again | The same exactness binds the four protective kinds — stop-loss, trailing stop-loss, take-profit and trailing take-profit — because each of them closes a position: a protective kind always closes the whole position, and the quantity it declares is not honoured. It binds an amendment of a resting order as well: a closing order amended away from the position it closes is refused. The examples chapter walks all four verbs in one chain, `07.1 hello world - basic rules`. ## The rule channels Rules split into two channels by what they observe. - **Market-event-driven rules** watch a pattern. The builders `tse_add_rule_market`, `tse_add_rule_multileg`, `tse_add_rule_bracket`, `tse_add_rule_oco`, `tse_add_rule_cancel`, `tse_add_rule_replace` and `tse_add_rule_modify` all take a `patternLabel` argument and fire when — and only when — that pattern fires. - **Position-risk-driven rules** watch the position itself. The builder `tse_add_rule_risk` takes no pattern label at all: the rule subscribes to the exposure of the named contract and fires when the position's unrealized-P&L ratio crosses its threshold, regardless of what any pattern is doing. Selectivity in the market channel is strict and structural. Each rule names exactly one pattern, and the subscription is keyed by the identifier derived from that pattern label — firings of every other pattern never reach the rule. Several rules may name the same pattern; each of them receives every firing of it independently. The `niceValue` field of `TseRuleParams` orders observers of the same pattern: it is the rule's priority within the robot graph. ## Trade rules There are no separate entry or exit builders. `tse_add_rule_market` is the single builder for all market-event trade rules, and the rule kind is a value of `TseRuleType` passed to it: `tse_rule_entry`, `tse_rule_exit`, `tse_rule_rebalance` or `tse_rule_flip`. Passing a risk value (`tse_rule_stop_loss`, `tse_rule_stop_loss_trailing`, `tse_rule_take_profit`, `tse_rule_take_profit_trailing`) to this builder is an error, exactly as passing a market value to `tse_add_rule_risk` is. The full trade specification is one flat structure, mirroring the engine's rule constructor. All fields are required; the wrappers supply no defaults. | Field | Type | | --- | --- | | quantityMode | `TseQuantityMode` | | quantity | `double` | | priceType | `TsePriceType` | | limitPrice | `double` | | slippage | `double` | | fee | `double` | | txnSide | `TseSide` | | posSide | `TseSide` | | tif | `TseTif` | | niceValue | `int32_t` | **What the signal may supply.** Three of the fields have an undefined form, and declaring one undefined is how a rule says that the signal brings it. On every firing the rule takes each undefined field out of the order the pattern published and leaves every other field exactly as declared; a rule that declared all three never reads the order at all. A risk rule reads nothing from a signal and is rejected at build time if any of the three is undefined. The Pattern chapter describes the order itself. **Quantity modes.** Three values of `TseQuantityMode` are accepted; any other value is rejected, the former numeric 3 (`tse_quantity_from_signal`, now gone) among them. | Mode | Meaning | | --- | --- | | `tse_quantity_fixed` | every firing trades the `quantity` given in the params | | `tse_quantity_all` | every firing resolves the size from the position on the contract and ignores `quantity`: the whole position for an exit or a protective kind, twice the position for a flip | | `tse_quantity_undefined` | the per-fire quantity is read from the order the signal carries; `quantity` is ignored. A signal bringing zero names no size, and the rule then issues nothing and logs the reason | The same pattern can therefore drive differently sized orders on every fire, and nothing carries over: a firing whose signal brings no quantity does not reuse the previous one. **Price forms.** `tse_price_market` places a market order and ignores `limitPrice`; `tse_price_limit` places a limit order at `limitPrice`; `tse_price_undefined` takes the price from the order the signal carries, where a zero means at market and any other value a limit at that price. `tse_price_general` is rejected in a rule (see the last section). `slippage` and `fee` ride on every order the rule emits. **Sides.** `txnSide` is the side of the transaction the rule issues: `tse_side_long`, `tse_side_short`, or `tse_side_undefined` to take it from the order the signal carries. A neutral `txnSide` is rejected — a transaction without a direction is not a transaction — and so is any value outside the three position sides. `posSide` is a guard: the portfolio side that must hold for the rule to fire — `tse_side_neutral` for an entry into a flat book, `tse_side_long` for a rule that closes a long, and so on. It is never taken from a signal, and it must be one of the three position sides. **Time-in-force.** `tif` is a `TseTif` value: `tse_tif_day`, `tse_tif_gtd`, `tse_tif_gtc`, `tse_tif_gts`, `tse_tif_atc`, `tse_tif_opg`, `tse_tif_fok`, `tse_tif_ioc` or `tse_tif_aon`. The C++ mirror is `tse::Tif`, the Python mirror is the `Tif` IntEnum (`Tif.Day` … `Tif.Aon`). Transaction kind (`TseTxnType`) and order priority (`TsePriority`) do not appear in `TseRuleParams`: for a single-contract rule the engine derives the transaction kind from the rule type. Those two enums are per-leg properties of multileg rules and are described below. **Rebalance.** A rebalance firing is not a bring-to-target instruction and computes no distance to any desired size: it emits one order for exactly the quantity its params resolve, on the rule's `txnSide`, and the engine types the result as a chaining transaction (`tse_txn_chaining`) — an adjustment of an existing position. Each fill shifts the position by that amount and re-averages the acquisition price: an entry of 4 at 100 followed by two rebalance fills of 2 at 103 and at 108 leaves a position of 8 whose acquisition price is the volume-weighted average of the three fills, and no realized profit is booked on the same-side adds. A rebalance against the position stays strictly below what is held, so it never leaves the side it is on: the bound is the one the verbs table above states. The builder, in C, C++ and Python: ```c TseStatus tse_add_rule_market(TseAccountHandle account, char const* label, TseRuleType ruleType, TseRuleParams const* params, char const* patternLabel, TseContractHandle contract); ``` ```cpp void Account::addRuleMarket(std::string label, RuleType ruleType, RuleParams const& params, std::string patternLabel, Contract const& contract) &; ``` ```python params = tse.make_rule_params(quantity_mode, quantity, price_type, limit_price, slippage, fee, txn_side, pos_side, tif, nice_value) account.add_rule_market(label, rule_type, params, pattern_label, contract) ``` ## Risk rules `tse_add_rule_risk` builds the four position-watching rules: `tse_rule_stop_loss`, `tse_rule_take_profit` and their trailing variants `tse_rule_stop_loss_trailing`, `tse_rule_take_profit_trailing`. A risk rule is bound to the named contract's exposure, not to any pattern — the market can print any shape it likes; the rule reacts only to what the position's unrealized P&L does. `thresholdRatio` is a positive magnitude the engine compares the position's unrealized-P&L ratio against. A zero threshold never fires. Writing the ratio as r and the threshold as theta: - **Fixed stop-loss** fires when the loss reaches the threshold: r <= -theta. - **Fixed take-profit** fires when the gain reaches the threshold: r >= +theta. - **Trailing stop-loss** tracks the running peak of the ratio and fires when the retreat from that peak reaches theta. - **Trailing take-profit** first arms — the running peak must itself reach theta — and then fires when the ratio retreats from the peak by theta. The trade the firing emits is described by the same `TseRuleParams`: a stop-loss on a long position is typically `txnSide` short, `posSide` long, `tse_quantity_all`. The `posSide` guard applies to risk rules exactly as to market rules. The builder, in C, C++ and Python: ```c TseStatus tse_add_rule_risk(TseAccountHandle account, char const* label, TseRuleType ruleType, TseRuleParams const* params, double thresholdRatio, TseContractHandle contract); ``` ```cpp void Account::addRuleRisk(std::string label, RuleType ruleType, RuleParams const& params, double thresholdRatio, Contract const& contract) &; ``` ```python account.add_rule_risk(label, rule_type, params, threshold_ratio, contract) ``` ## Order mutations Three builders generate amendments of in-flight orders instead of new trades. Each is a market-event rule: it names a pattern, and on every firing it emits one amend envelope for the named contract. The rule does not name a specific order id — the engine routes the envelope to the order currently in flight for that contract. All three share one signature; what differs is which arguments the envelope reads. | Builder | Effect on the in-flight order | Reads | | --- | --- | --- | | `tse_add_rule_cancel` | pulls the order | neither `quantity` nor `price` | | `tse_add_rule_modify` | changes the remaining quantity, keeps the price | `quantity` only | | `tse_add_rule_replace` | re-places the order with a new quantity and a new price | both | The engine additionally rejects a modify or replace whose quantity is not positive. The three builders, in C, C++ and Python: ```c TseStatus tse_add_rule_cancel (TseAccountHandle account, char const* label, TseContractHandle contract, double quantity, double price, char const* patternLabel); TseStatus tse_add_rule_replace(TseAccountHandle account, char const* label, TseContractHandle contract, double quantity, double price, char const* patternLabel); TseStatus tse_add_rule_modify (TseAccountHandle account, char const* label, TseContractHandle contract, double quantity, double price, char const* patternLabel); ``` ```cpp void Account::addRuleCancel (std::string label, Contract const& contract, double quantity, double price, std::string patternLabel) &; void Account::addRuleReplace(std::string label, Contract const& contract, double quantity, double price, std::string patternLabel) &; void Account::addRuleModify (std::string label, Contract const& contract, double quantity, double price, std::string patternLabel) &; ``` ```python account.add_rule_cancel(label, contract, quantity, price, pattern_label) account.add_rule_replace(label, contract, quantity, price, pattern_label) account.add_rule_modify(label, contract, quantity, price, pattern_label) ``` ## Multileg `tse_add_rule_multileg` builds a rule that, on each pattern firing, emits all its legs as one atomic multileg transaction. Legs are passed as an array of descriptors; each leg names its own contract and carries the complete per-order specification. | Field | Type | | --- | --- | | contract | `TseContractHandle` | | quantityMode | `TseQuantityMode` | | quantity | `double` | | priceType | `TsePriceType` | | limitPrice | `double` | | slippage | `double` | | fee | `double` | | txnType | `TseTxnType` | | txnSide | `TseSide` | | posSide | `TseSide` | | tif | `TseTif` | | priority | `TsePriority` | A leg's `quantityMode` accepts `tse_quantity_fixed` (uses `quantity`) or `tse_quantity_all` (resolved by the engine at fire time); a leg takes nothing from a signal, so the signal-driven form carries no value for it. `txnType` is the transaction kind of the leg (`tse_txn_enter`, `tse_txn_exit`, `tse_txn_stoploss`, `tse_txn_stoploss_trailing`, `tse_txn_takeprofit`, `tse_txn_takeprofit_trailing`, `tse_txn_chaining`, `tse_txn_flip` — the numeric values are the engine codes), and `priority` marks the leg's order as `tse_priority_replaceable` or `tse_priority_non_replaceable`. The boundary adds no rule of its own to these fields, so the undefined form of each one is accepted when the rule is built, and this manual states what each then means. An undefined transaction kind opens a position exactly as `tse_txn_enter` does. An undefined time-in-force is accepted and, on a partial fill, behaves as `tse_tif_fok` and `tse_tif_aon` do: the order has no valid partial state, so only a fill in full completes it. An undefined priority is accepted, travels with the order and is journaled; no decision of the engine reads it. An undefined quantity mode or price type is also accepted when the rule is built, but it leaves the leg without the datum an order needs, and the engine's own order validation refuses that leg when the rule fires, naming the missing datum. What the boundary itself refuses is a raw value that maps to no enumerator of the given enumeration, and a number that is not finite or lies outside the `FinValue` range. **One transaction kind and one set of order fields for the whole transaction.** Besides the per-leg form above, the engine's multileg type and its rule generator each take a second form, in which the transaction kind and the four order fields — time-in-force, quantity mode, price type and priority — are given once and written into every leg. That form exists for the caller who builds a multileg transaction directly, and it accepts one time-in-force only: `fok`. Any other value is refused with a message naming the value received, and a rule built that way is refused at construction. The exported builders take the per-leg descriptors described above. A multileg transaction carries between one and eight legs. A `legCount` outside these bounds fails loud: the engine rejects it with an error naming the range. Two refusals of a leg happen when the rule fires rather than when it is built. A leg whose trade side has no direction — neither long nor short — stops the whole transaction, and so does a leg the engine's order validation refuses, for instance one left with an undefined quantity mode or price type. In both cases nothing of the group reaches order management, no reservation is taken, the rule records the reason in its diagnostic message and writes it to the log, and the robot stays active and processes the next firing normally. **Atomic net-price fills.** A multileg transaction is filled as a unit or not at all. When the transaction is built, the engine derives a net price and per-leg weights from the legs' sides, quantities and limit prices. The leg orders then rest as one group: on every market event touching any of the group's contracts, the engine reads the currently reachable price of every leg — a group with even one leg lacking market data stays untouched — combines them with the same weights, long legs adding and short legs subtracting, and compares the result against the net-price bound. Only when the bound is satisfied does the group execute, and then every leg fills in full at its reachable price in the same instant; legs are never filled piecemeal, and a partial group is never left behind. A spread that never becomes reachable simply rests forever. **An amendment addresses a leg, and the group answers as a whole.** A cancel, a modify or a replace with no client order id is routed to the resting leg of the group on the amendment's contract. From the moment such an amendment is sent and until it takes effect the group is not executed, even if its net price becomes reachable in between: a group holding a leg with an amendment in flight is passed over on every market event, and the execution records the reason. When a cancel takes effect, the whole group is cancelled and every leg is reported, the multileg record is erased and every reservation is released, so the pools are free for the next firing. When a modify or a replace takes effect, the net price is recomputed from the amended legs; if the recomputed price is neutral or overflows, the whole group is cancelled for that reason instead. An amendment waiting in the queue of another leg's contract is not drained by a market event on this leg's contract, so until that other contract ticks the group stays frozen and nothing of it fills. The builder, in C, C++ and Python: ```c TseStatus tse_add_rule_multileg(TseAccountHandle account, char const* label, TseLegDescriptor const* legs, size_t legCount, char const* patternLabel); ``` ```cpp void Account::addRuleMultileg(std::string label, std::vector const& legs, std::string patternLabel) &; ``` ```python leg = tse.make_leg_descriptor(contract, quantity_mode, quantity, price_type, limit_price, slippage, fee, txn_type, txn_side, pos_side, tif, priority) account.add_rule_multileg(label, [leg_a, leg_b], pattern_label) ``` ## Bracket and OCO A bracket is an entry order that carries its own venue-resting protection. `tse_add_rule_bracket` takes an entry leg — a full `TseLegDescriptor` — plus a venue-risk specification, and on each pattern firing emits the entry together with the resting stop-loss / take-profit orders derived from it. The specification is a pair of optional risk legs and one time-in-force that both resting orders share. At least one leg must be present. | Field | Type | | --- | --- | | stopLoss | `TseVenueRiskLeg` | | takeProfit | `TseVenueRiskLeg` | | tif | `TseTif` | | Field | Type | | --- | --- | | present | `int32_t` | | kind | `int32_t` | | ratio | `double` | In `TseVenueRiskLeg`, `present` encodes the engine's optional — zero means the leg is absent and the remaining fields are ignored; `kind` selects the threshold flavor, `0` for fixed and `1` for trailing (any other value is rejected); `ratio` is the threshold ratio, with the same fixed/trailing semantics as in the risk-rule section above, applied in price space around the entry fill. `tse_add_rule_oco` emits the protection pair without an entry: on each firing it places the one-cancels-other pair described by the specification for the named contract, guarding a position that already exists. The sibling semantics are what the name says — the two resting orders are linked, and the execution of one causes the engine to cancel the other. A bracket whose specification carries both legs produces the same linked pair, attached to its entry. The two builders, in C, C++ and Python: ```c TseStatus tse_add_rule_bracket(TseAccountHandle account, char const* label, TseLegDescriptor const* entry, TseVenueRiskSpec const* risk, char const* patternLabel); TseStatus tse_add_rule_oco(TseAccountHandle account, char const* label, TseContractHandle contract, TseVenueRiskSpec const* risk, char const* patternLabel); ``` ```cpp void Account::addRuleBracket(std::string label, LegDescriptor const& entry, VenueRiskSpec const& risk, std::string patternLabel) &; void Account::addRuleOco(std::string label, Contract const& contract, VenueRiskSpec const& risk, std::string patternLabel) &; ``` ```python sl = tse.make_venue_risk_leg(True, 0, 0.02) tp = tse.make_venue_risk_leg(True, 1, 0.05) risk = tse.make_venue_risk_spec(sl, tp, tse.Tif.Gtc) account.add_rule_bracket(label, entry_leg, risk, pattern_label) account.add_rule_oco(label, contract, risk, pattern_label) ``` ## Extended sides and prices `TseSide` is a full mirror of the engine's side/quotation enumeration, and the numeric values are the engine codes — deliberately powers of two, so that combinations of directed sides never collide with a named value. `tse_side_long` carries the engine aliases bid/buy, `tse_side_short` carries ask/sell. | Value | Code | Where it matters | | --- | --- | --- | | `tse_side_neutral` | 1 | a flat position; the `posSide` guard of an entry rule | | `tse_side_long` | 2 | order and position side; the bid side of a book | | `tse_side_short` | 4 | order and position side; the ask side of a book | | `tse_side_mid` | 8 | the quotation of a neutral position: exposure marking is side-dependent — long marks against the bid, short against the ask, neutral against the mid | | `tse_side_trade` | 16 | tags values that originate from executed trades — trade prints and actual (traded) prices in the engine's price algebra | | `tse_side_quote` | 32 | tags quoted prices — resting order prices and notionals; a market-priced rule order is typed as a quote-side price | | `tse_side_general` | 64 | the provenance-erased tag: bid and ask are cast to general before being combined (e.g. into a mid), so values of different origins can meet in one expression | Only the three position sides — neutral, long, short — are legal in `txnSide` and `posSide` of a rule or a leg, with the two exceptions already stated: a rule may declare `txnSide` undefined and read it from the signal, and a neutral `txnSide` is refused even though neutral is a position side. The engine rejects everything else there. The extended values surface elsewhere: the `side` field of a trade tick (`TseTickTrade`), the side column of a CSV load (the parser accepts all eight names and their numeric codes), the exposure snapshots, and the string round-trip `tse_side_to_string`. The C++ mirror is `tse::Side` (`long_`, `short_`, `mid`, `trade`, `quote`, `general`), the Python mirror is `Side` (`Side.Long`, `Side.Mid`, …). `TsePriceType` carries one value that never places an order: `tse_price_general` (`PriceType::general` in C++, `Price.General` in Python). A rule or a leg handed it is refused at build time; `tse_price_undefined` is accepted in a rule and means that the price comes from the signal, so of the four values a rule takes three. The general value exists because the engine's price algebra produces provenance-erased prices — a ratio of two prices, a trailing extreme tracked across bars — and the C mirror must be able to represent every engine value that can cross the boundary, such as the `priceType` field of a retained trade. # 7. Robot A robot is the execution node at the top of a robot graph: it owns a set of rules, addressed by their labels, receives every order, amend, multileg and bracket request those rules emit, and forwards each one into the account's order management under its own label. Everything downstream — fills, reservations, journaled trades — is tagged with that label, which is what makes per-robot lifecycle control and per-robot results possible on an account running several robots at once. As everywhere in the API, C calls return `TseStatus` and leave the diagnostic on `tse_last_error(account)`; the C++ wrapper throws `tse::Error` carrying that text; the Python wrapper raises `tse.TseError`. ## Wiring a robot The graph builds bottom-up and the robot closes it at the top: a pattern names the inputs it observes (the Pattern chapter), a rule names its pattern (the Rule chapter), and the robot names its rules — so `tse_add_robot` transitively takes ownership of a complete dependency component whose leaves are inputs. Nothing in that component processes market data yet: wiring only declares the graph, and the whole chain is put in motion by `tse_start`. The robot is declared over rules that already exist: every entry of `ruleLabels` must name a rule previously built on this account, and an unknown rule label fails the whole call. The robot's label must be unique among the account's robots — re-adding under an existing label is an error — and, like every label, is capped at 63 characters (the appendix collects the boundary capacities). The set of contracts the robot trades is the union of its rules' contracts. A robot submits through the account's single execution, so create one first with `tse_exec_create_simulator` or `tse_exec_create_custom`; starting a robot on an account without an execution is an error. The robot owns a worker thread of its own, so it takes a `coreId` like every other builder that does: a non-negative value pins that thread to the given core, a negative value runs the robot inline on its caller, and the parameter is mandatory in C while the two wrappers default it to -1. Cores 0 and 1 stay reserved for the operating system and a core at or beyond the number of cores the machine offers is refused; the Environment chapter states the rule and the refusals in full. Unlike the core id of an input or a pattern, the robot's core id is not part of the saved recipe: a robot restored by `tse_load` carries no core, and the caller names the core it wants on the next `tse_add_robot`. ```c TseStatus tse_add_robot(TseAccountHandle account, char const* label, char const* const* ruleLabels, size_t ruleCount, int coreId); ``` ```cpp void addRobot(std::string label, std::vector ruleLabels, int coreId = -1) &; ``` ```python account.add_robot(label, rule_labels, core_id=-1) ``` ## Reading the traded contracts Two readers hand that union back. `tse_get_robot_contract_count` takes the account, the robot label and a `size_t*` that receives how many contracts the robot trades; `tse_get_robot_contract_symbol` takes the account, the robot label, a zero-based contract index and the caller's buffer with its capacity, and writes that contract's symbol with its terminating zero. The order is fixed and can be relied upon: the robot's rules are walked in the order `tse_add_robot` named them, each rule contributes its own contracts in the order it declares them — one per leg for a multileg rule — and a contract already in the list is never repeated. This is the same list `tse_start` registers on order management and the bulk actions sweep, and it is readable before the start as well: a robot that has only been declared, and a robot restored by `tse_load` and not yet materialized, answer from their recipe. Three refusals. An unknown robot label fails both readers with `unknown robot "