9. The environment
Everything a robot runs inside of — the shared library itself, the process-wide initial parameters, the contracts and currencies the engine is monomorphized for, the duration grid, thread placement, the grid-search harness, recipe persistence, the data plane and the connection library, and the ex-post analysis surface. Each topic below opens with what the thing is and the rules that govern it, then its data structures, and shows the code last: the C declarations first, then the C++ wrapper form (namespace tse), then the Python form (module tse). The current ABI version is 12; tse_abi_version() returns it at run time.
Loading the library
The engine is an opaque prebuilt binary: the whole machine lives privately inside the shared library libtse_export and every language sees only the narrow waist of tse_* functions. The C headers live under include/tse/, with tse/tse.h as the umbrella header. The C++ wrapper is one header plus one translation unit (tse.hpp + tse.cpp) over the C ABI; the Python wrapper is a single ctypes module, tse.py.
Link -ltse_export. All four arguments are required: the label, the storage regime (an undefined regime fails), the account currency, and the blotter coreId (negative means no separate blotter thread).
The Python constructor is Account(account_label, regime, currency="USD", core_id=-1, lib_path=None). When lib_path is omitted, the TSE_EXPORT_LIB environment variable is consulted, else the default file name on the loader path is used. The default name is platform-specific and may carry the build's version segment: libtse_export[.MAJOR.MINOR].dylib on macOS, .so on Linux, libtse_export[.MAJOR.MINOR].dll on Windows; tse.default_lib_filename() returns it.
#include "tse/tse.h" /* umbrella header */
TseAccountHandle account = tse_account_create("MyAccount", tse_storage_regime_mem, "USD", -1);
/* ... */
tse_account_destroy(account);
#include "tse.hpp"
tse::Account account {"MyAccount", tse::StorageRegime::mem, "USD"};
// the reporting currency is required, coreId defaults to -1
Compile your program together with tse.cpp and link the shared library:
g++ -std=c++20 -I tse -I tse/include main.cpp tse/tse.cpp \
-L tse -ltse_export -Wl,-rpath,tse -o app
import tse
account = tse.Account("MyAccount", tse.StorageRegime.Mem,
lib_path="/path/to/libtse_export.dylib")
tse.abi_version() # 12
a.abi_version() # the same, through an account
Initial parameters and logging
tse_params.h carries the process-wide initial parameters. They are set once, before any account exists, which is why the call has its own error channel (tse_last_init_error) instead of the per-account tse_last_error.
Every non-empty path is genuinely validated, not just stored: a path that names an existing file is an error; a missing folder is created recursively; the folder is then probed for real read and write rights, and any failure returns tse_error with the reason in tse_last_init_error().
The lifecycle is deliberately simple: call it once at process startup, before creating accounts. Repeated calls are legal and last-writer-wins, but the call is not thread-safe against concurrent account creation — it writes plain process-wide state.
An account keeps the database path it computed at construction time. A later tse_set_initial_params affects only objects created after it: existing accounts keep writing where they started, and already-created database files do not move.
The three fields of TseInitialParams are independent and each empty (NULL or "") field means "do not change":
| Field | Type | Meaning |
|---|---|---|
dataFolderPath | char const* | NULL or "" = leave unchanged. The folder where the engine writes its databases: the blotter DB files of db accounts and the ex-post SQLite output. Without it the engine falls back to the executable's own directory. An account built with its own blotter path through tse_account_create_at_path ignores this folder entirely. |
logFolderPath | char const* | NULL or "" = leave unchanged. Setting it switches the library's logging from the console sink to a rotating file sink: tse.log in that folder, with the start date-time appended to the file name, rotated daily at 00:00 and additionally at 100 MiB, opened in append mode. The current log level is preserved across the switch. |
logLevel | int32_t | 0..6 = TseLogLevel, applied immediately; TSE_LOG_LEVEL_UNCHANGED = leave unchanged, keeping the current one. An out-of-range value fails the whole call. |
Log levels live in tse_log.h and can also be changed at any time on their own. The library starts at critical; lower the level explicitly when you want to see more.
| Value | C | C++ tse::LogLevel | Python tse.LogLevel |
|---|---|---|---|
| 0 | tse_log_trace | trace | Trace |
| 1 | tse_log_debug | debug | Debug |
| 2 | tse_log_info | info | Info |
| 3 | tse_log_warning | warning | Warning |
| 4 | tse_log_error | error | Error |
| 5 | tse_log_critical | critical | Critical |
| 6 | tse_log_none | none | Off |
#define TSE_LOG_LEVEL_UNCHANGED (-1)
TseStatus tse_set_initial_params(TseInitialParams const* params);
char const* tse_last_init_error(void);
void tse_set_log_level(TseLogLevel level);
void tse_log_write(TseLogLevel level, char const* tag, char const* file, uint32_t line, char const* message);
struct InitialParams final {
std::string dataFolderPath;
std::string logFolderPath;
LogLevel logLevel;
bool applyLogLevel; // false sends TSE_LOG_LEVEL_UNCHANGED
};
bool setInitialParams(InitialParams const& params) noexcept;
std::string lastInitError();
void setLogLevel(LogLevel level) noexcept;
void logWrite(LogLevel level, std::string const& tag, std::string const& file, std::uint32_t line, std::string const& message) noexcept;
tse.set_initial_params(data_folder="/data", log_folder="/logs",
log_level=tse.LogLevel.Info) # raises TseError on failure
params = tse.make_initial_params(data_folder="", log_folder="", log_level=None)
# log_level None -> tse.LOG_LEVEL_UNCHANGED
a.set_log_level(tse.LogLevel.Off) # Python spells tse_log_none as Off
tse.log_write(tse.LogLevel.Info, "strategy", __file__, 42, "a line of your own")
tse_log_write writes one line of your own into the journal the library writes — the console sink until a log folder is set, the rotating tse.log file afterwards — so a strategy or a connector built on the SDK keeps one time-ordered record together with the engine. The line carries your level, a tag, the source file and line of the caller and the message. A level below the current one, equal to none or outside TseLogLevel writes nothing, and so does a null message; the tag is written the way the engine writes its own, as #tag in front of the message, a null or empty tag adds nothing, a null file name is written as empty text, and an empty message is written as an empty line. The message is written verbatim — braces in it are not a format, UTF-8 text passes as it is, and only control characters other than newline, tab and carriage return are replaced by hex escapes — and every string is copied before the call returns, so none of them has to outlive it. The C++ form is tse::logWrite, the Python form tse.log_write.
Contracts
A contract is a tradable instrument declared standalone in the library, with no account, no market-data type and no feed binding; the same contract may later live on several adapters, and in several accounts, through wiring. The full descriptor includes the venue and the tick size.
A contract precedes everything that uses it, and it lives as long as the process: declare the contract before any input, rule or robot that names it, and pass the handle tse_add_contract returned. The library owns the contract, not the account: the handle stays good until the process ends, there is no removal call, and an account destroyed around it leaves it untouched. You never manage a contract's lifetime yourself, and the same handle may be wired into any number of accounts.
The multiplier is unsigned. It is declared uint32_t in C and mirrored unsigned in both wrappers, so every value from 1 to 4 294 967 295 is declarable and nothing is refused for being large. Zero is refused, with the text Multiple, a contract multiple cannot be zero, because a contract whose multiplier is zero carries no economic meaning. One consequence belongs to the caller rather than to the library: a negative value handed to an unsigned parameter is converted by the language before the library sees it, so -1 arrives as 4 294 967 295 and a contract is created with that multiplier instead of the call being refused. The engine cannot recover the original sign and does not try to guess it; validate the sign on your side when the value comes from input you do not control.
One contract is one handle. The library holds a single copy of every declared contract and hands out a stable address for it, so declaring the same seven terms twice returns the very same handle rather than a second contract. Two declarations that differ in any term — the symbol, the multiple, the instrument class, the underlying, the venue, the tick size or the currency — are two different contracts and receive two different handles.
TseContractHandle tse_add_contract(char const* symbol, uint32_t multiplier,
TseInstrument instrument, TseUnderlying underlying,
TseVenue venue, int64_t tickSize, char const* currency);
/* the reason the last tse_add_contract on this thread refused */
char const* tse_last_contract_create_error(void);
tse::Contract const aapl {"AAPL", 1, tse::Instrument::equity,
tse::Underlying::equity, tse::Venue::NASDAQ, 10'000, "USD"};
tse::Contract const bund {"BUND", 1, tse::Instrument::future,
tse::Underlying::debt, tse::Venue::undefined,
100'000, "EUR"};
TseContractHandle const handle {aapl.handle()};
aapl = tse.Contract("AAPL", 1, tse.Instrument.Equity, tse.Underlying.Equity,
tse.Venue.NASDAQ, 10_000, "USD")
bund = tse.Contract("BUND", 1, tse.Instrument.Future, tse.Underlying.Debt,
tse.Venue.Undefined, 100_000, "EUR")
handle = aapl.handle
The currency belongs to the contract, not to the account. The declaration names it by its three-letter code of the engine's currency table, and one account may be wired to contracts of several currencies at once: the account's own currency is only the one it reports in. On the C boundary the code is a required argument of the declaring call; a code of another length, a code no table row names, and an empty code are each refused with add_contract: the currency is not a three-letter code of the currency table. In the wrappers the argument comes last and is required there as well. How money of one currency is folded into the currency the account reports in is the subject of the exchange-rate table, tse_set_exchange_rate.
A robot recipe written by tse_save records each contract's currency under the key "ccy". A recipe written before this surface carried the currency has no such key, and tse_load then reads the contract as declared in the account's reporting currency — which is exactly what the writing account had declared, because no other currency could be declared then. A recipe whose "ccy" names a code the currency table does not hold is refused with load: the currency is not a three-letter code of the currency table.
Identity
The contract id is a hash fold over all of the contract's fields — the symbol, the multiple, the instrument class, the underlying, the venue, the tick size, and the contract's currency, which the declaration names. Two consequences follow. First, the id is not decomposable: no field can be read back out of it, it is an opaque 64-bit identity. Second, equality is total: contracts with equal fields produce an equal id, and changing any field — including the tick size or the multiple — produces a different contract. Databases keyed by contract id therefore do not survive a change of any contract field; regenerate them instead of expecting old rows to match.
The tick pipeline
Prices cross the boundary as the pair TsePrice — a significand and a decimal scale, two integers and no floating point (tse_types.h) — and live inside the engine as fixed-point integers in millionths of one price unit (the FinValue encoding; tse_finvalue_scale() returns the exponent). Inbound, a scale from 0 to 6 converts exactly: the significand is multiplied by ten to the power of six minus the scale; the call that receives the price refuses a scale outside that range, or a significand whose scaled product does not fit int64_t, through its usual error path. Outbound, the library always writes scale 6 and its raw integer, so 256.27 arrives as {256270000, 6}. tse_price_to_finvalue / tse_finvalue_to_price perform the same two conversions on request, and tse_finvalue_from_double / tse_finvalue_to_double translate a double, rounding half to even at the sixth decimal. The tickSize field of a contract is expressed in the raw millionth units: 10'000 means a tick of 0.01.
Against that grid the engine applies a three-step rule: a price conforms when its distance to the nearest grid node is at most one raw unit (one millionth); a conformant price is snapped exactly onto the grid node; a price farther from the grid is rejected with a diagnostic. A pair written on the grid lands on its node exactly.
The tick is mandatory and constant. A tickSize of zero is refused at the boundary — tse_add_contract returns a null handle with TickSize::Ctor (unsigned) - step must not be 0 in tse_last_contract_create_error, and the wrappers turn the same refusal into tse::Error and tse.TseError; no default is substituted in its place, because the tick is the grid every price of that contract is measured against. Once declared, the tick never changes: it is part of the contract's identity, and no exported call updates it. The engine deliberately does not implement venue tick regimes such as the tiered tables of MiFID II RTS 11, where the step varies with price band and liquidity — one contract carries one step for its whole life. Declaring the step that the venue actually applies, and answering for every price conforming to it, is therefore yours; a mis-declared tick does not fail loudly, it silently snaps or rejects prices against the wrong grid.
Venues
The venue enumeration counts 58 entries — the undefined sentinel, 47 named venues, and ten user_defined_* slots — plus three schedule-group identifiers (US, EU, UK) that name holiday calendars, not exchanges. Each named venue carries a descriptor with its full name and its ISO 10383 MIC where one exists. The regions, compactly: North America (NYSE, NASDAQ, CBOE, CME, ICE, TSX), Latin America (B3, BMV, BCS, BVC, BVL, BYMA), Europe (LSE, EUREX, EURONEXT, MOEX, XETRA, SIX, BME, BIT, OMX, OSLO, WSE, BIST), Asia-Pacific (TSE, HKEX, ASX, SSE, SZSE, NSE, BSE, KRX, SGX, TWSE, IDX, SET, MYX), and ten crypto venues (BINANCE, COINBASE, KRAKEN, BITSTAMP, OKX, BYBIT, BITFINEX, KUCOIN, GEMINI, HTX). The C enum TseVenue mirrors the engine's enumeration one to one, tse_venue_to_string prints a value, and the C++ tse::Venue and Python tse.Venue spell the same names.
Currencies
A currency is named everywhere by its three-letter code, as a zero-terminated string of exactly three characters: "USD", "EUR", "JPY" and every other row of the engine's currency table. A string of another length, or one that names no row, is refused. The three-letter code is used rather than the ISO-4217 number because twenty-two rows of the table carry no number — the offshore and onshore Chinese yuan and twenty crypto-currencies — and because the position of a row in the table is not a promise.
The account's reporting currency is fixed at creation — it is the third argument of tse_account_create and a constructor argument of the wrappers — and cannot be changed afterwards. Accounts of different reporting currencies work side by side in one run. A contract carries its own currency, which participates in the contract's identity fold, and a contract of any currency may be declared on any account: money is brought to the account's reporting currency by the exchange rate table. In a grid search the currency passed to tse_run_grid applies to every grid account the harness creates.
The exchange rate table
The library keeps one exchange rate table for the whole run, shared by every account, keyed by the pair of currencies — the currency of the contract and the reporting currency of the account. A rate says how many units of the second currency one unit of the first buys. It is held as a fraction of two four-byte parts, reduced by the greatest common divisor; a rate that does not fit those parts after the reduction is refused, as 4295.000001 is. There are two ways a rate reaches the table, and the first wins over the second:
- You put it there yourself with
tse_set_exchange_rate. - The library reads it off a market adapter whose currency pair you have named with
tse_market_set_currency_pair, and only from a contract whose instrument field carries the currency bit. The rate taken off a candle is its close, off a trade its price, and off a quote the middle of the bid and the ask.
When neither source has a rate for a pair, the library uses one and writes one line into the log for that pair. A rate never expires and is never evicted.
TseStatus tse_set_exchange_rate(char const* fromCurrency, char const* toCurrency, double rate);
TseStatus tse_market_set_currency_pair(TseMarketHandle market, char const* fromCurrency,
char const* toCurrency);
void tse::setExchangeRate(std::string fromCurrency, std::string toCurrency, double rate);
void tse::Market::setCurrencyPair(std::string fromCurrency, std::string toCurrency);
tse.set_exchange_rate("EUR", "USD", 1.085)
market.set_currency_pair("EUR", "USD")
Durations
tse_duration.h defines the 27-value duration grid. Every input and every pattern takes an explicit duration argument; the engine never derives one.
| Value | C constant | C++ tse::Duration | Python tse.Duration |
|---|---|---|---|
| 0 | tse_duration_nanoseconds | nanoseconds | Nanoseconds |
| 1 | tse_duration_microseconds | microseconds | Microseconds |
| 2 | tse_duration_milliseconds | milliseconds | Milliseconds |
| 3 | tse_duration_seconds | seconds | Seconds |
| 4 | tse_duration_five_seconds | five_seconds | FiveSeconds |
| 5 | tse_duration_ten_seconds | ten_seconds | TenSeconds |
| 6 | tse_duration_thirty_seconds | thirty_seconds | ThirtySeconds |
| 7 | tse_duration_minutes | minutes | Minutes |
| 8 | tse_duration_two_minutes | two_minutes | TwoMinutes |
| 9 | tse_duration_three_minutes | three_minutes | ThreeMinutes |
| 10 | tse_duration_five_minutes | five_minutes | FiveMinutes |
| 11 | tse_duration_ten_minutes | ten_minutes | TenMinutes |
| 12 | tse_duration_fifteen_minutes | fifteen_minutes | FifteenMinutes |
| 13 | tse_duration_thirty_minutes | thirty_minutes | ThirtyMinutes |
| 14 | tse_duration_hours | hours | Hours |
| 15 | tse_duration_two_hours | two_hours | TwoHours |
| 16 | tse_duration_three_hours | three_hours | ThreeHours |
| 17 | tse_duration_six_hours | six_hours | SixHours |
| 18 | tse_duration_eight_hours | eight_hours | EightHours |
| 19 | tse_duration_twelve_hours | twelve_hours | TwelveHours |
| 20 | tse_duration_days | days | Days |
| 21 | tse_duration_two_days | two_days | TwoDays |
| 22 | tse_duration_three_days | three_days | ThreeDays |
| 23 | tse_duration_weeks | weeks | Weeks |
| 24 | tse_duration_months | months | Months |
| 25 | tse_duration_quarters | quarters | Quarters |
| 26 | tse_duration_years | years | Years |
A library build does not have to monomorphize the whole grid. Asking for a duration that is not built in fails loud, with an error text that names the requested duration and lists the built-in ones — it has the shape:
duration "<name>" is not built into this library; it monomorphizes
<built-in list>
tse_version.h lets you enumerate what the loaded binary actually supports; the two enumerating calls follow the count-then-buffer protocol (call with a null buffer to get the count). The same header answers how many cores this process may use, which is the number every core id is checked against:
uint32_t tse_abi_version(void);
int tse_core_count(void);
size_t tse_supported_durations(TseDuration* outDurations, size_t capacity);
size_t tse_supported_mdtypes(TseMdType* outMdTypes, size_t capacity);
std::uint32_t abiVersion() noexcept;
int coreCount() noexcept;
std::vector<Duration> supportedDurations();
std::vector<MdType> supportedMdTypes();
tse.core_count() # int
tse.supported_durations() # [tse.Duration...]
tse.supported_md_types() # [tse.MdType...]
Thread affinity
Thread placement is uniform across the whole object model: every builder that owns a worker thread takes a coreId parameter, and the parameter is mandatory in C (the wrappers default it to -1). A non-negative value pins that node's thread to the given core; a negative value means no separate thread — the node runs inline on its caller.
- the account (
tse_account_create) — the blotter thread; - the execution (
tse_exec_create_simulator,tse_exec_create_custom) — the execution worker; - every input builder (
tse_add_input_ohlcv/_bidask/_trade/_executed) — the input's worker; - every pattern builder (
tse_add_pattern_comparison/_crossover/_threshold/_peak/_timestamp/_formula) — the pattern's worker; - the robot (
tse_add_robot) — the robot's own worker.
Two cores are not yours to take. Cores 0 and 1 stay reserved for the operating system, so the lowest core a node may be pinned to is 2; a non-negative core id below that is refused, and so is a core id at or beyond the number of cores the machine offers. The refusal names the core, the reason and, where the core is simply too large, the half-open range it had to fall in. It comes from the builder itself and before any thread is started, so a refused node leaves nothing behind: in C the call returns tse_error and the text waits on tse_last_error(account), the C++ wrapper throws tse::Error and the Python wrapper raises tse.TseError. The number of cores is taken from the operating system, and on Linux from the set of cores this process is actually allowed to run on, so a process confined to a subset of the machine is held to that subset. That number is readable: tse_core_count returns exactly the number every core id is checked against, so a caller that derives a core id from it is never surprised by the bounds in a refusal.
The per-node core id is part of the saved recipe for inputs and patterns: tse_save persists it with each input and pattern node, and tse_load restores it, so a robot reloaded in another process keeps their thread placement. The robot's own core id is not saved: a robot restored by tse_load carries no core, and the caller names the core it wants on the next tse_add_robot.
Grid search
tse_grid.h runs one robot per parameter point, in parallel, and folds each run into a summary. The builder callback receives a fresh account and must configure a complete robot on it from scratch — adapters, execution, contracts, inputs, patterns, rules, robot, data feed — exactly as it would in a standalone program.
The thread policy is fixed inside the library — there is no thread-count parameter. The pool uses nproc - 2 workers pinned to cores 2 .. nproc - 1, keeping cores 0 and 1 reserved for the OS, and the call fails outright when no spare cores remain. Each worker account is created with the label <prefix>_<index>, the given storage regime, the run's currency, and coreId -1 (no separate blotter thread — the worker itself is already pinned). outResults must hold paramCount entries; a point whose builder or summary fails leaves ok at 0 without aborting the other points.
One TseGridResult record is written per parameter point.
| Field | Type |
|---|---|
| paramValue | double |
| ok | int |
| summary | TseSummary |
typedef TseStatus (*TseGridBuilder)(TseAccountHandle account, double paramValue, void* userData);
TseStatus tse_run_grid(char const* accountLabelPrefix, TseStorageRegime regime,
char const* currency, double const* paramValues, size_t paramCount,
TseGridBuilder builder, void* userData, TseGridResult* outResults);
std::vector<GridResult> runGrid(std::string accountLabelPrefix, StorageRegime regime,
std::vector<double> paramValues,
std::function<void(Account&, double)> builder,
std::string currency = "USD");
results = tse.run_grid(account_label_prefix, regime, param_values, builder,
currency="USD", lib_path=None)
# builder(account, param_value); results[i].param_value, .ok, .summary
Save and load
Persistence is recipe-only, at schema version 7. Saving a robot stores its construction recipe, not live state: the contracts, the inputs (with their market-data type, duration, data length, contract subset and core id, and — for an input built on a shipped processor — the four values that describe it, but unbound to any adapter), the patterns, the rules and their order, the risk policies, and the robot itself, together with the account currency and regime tags. Market adapters and the execution are deliberately not saved — after a load you attach fresh ones.
Each contract is saved with its every field, the venue, the tick size and the multiple included. That matters because the contract id is a fold over all of them (see "Identity" above): a contract rebuilt by tse_load hashes to the same identity it had before the save, so it is the same contract and receives the same handle, and blotter rows and ex-post records keyed by that id keep matching across the round trip.
A processor (an input's data processor, a pattern's formula) is a function pointer and cannot be serialized, so a savable node references a string key instead. Register the key on the account, then build the node with the matching *_by_key builder. The plain (non-keyed) tse_add_input_* / tse_add_pattern_formula builders run fine but make the robot unsavable — tse_save fails on such a robot. A built-in input is the exception that needs no key at all: the library knows how to rebuild the shipped processor from the four values the recipe stores, so an input declared with tse_add_input_ohlcv_builtin and its two siblings is savable as it stands (the built-in processors chapter).
tse_load reconstructs the inputs unbound. The rebinding sequence before start is fixed: create fresh market adapter(s) and an execution, call tse_bind_input for each loaded input — the adapter's type must match the input's saved market-data type, and binding registers the input's contract subset on the adapter — then tse_start. Starting a robot while any loaded input is still unbound is an error.
The round trip is cross-language by construction: the recipe is a SQLite file, and the keys are plain strings. A robot saved from Python loads in C++ or C — create a fresh account, register the same keys (the processors themselves may be reimplemented in the host language), tse_load, bind, start.
TseStatus tse_register_input_processor_ohlcv (TseAccountHandle, char const* key, TseOhlcvInputProcessor, void* userData);
TseStatus tse_register_input_processor_bidask (TseAccountHandle, char const* key, TseBidAskInputProcessor, void* userData);
TseStatus tse_register_input_processor_trade (TseAccountHandle, char const* key, TseTradeInputProcessor, void* userData);
TseStatus tse_register_input_processor_executed(TseAccountHandle, char const* key, TseExecutedInputProcessor, void* userData);
TseStatus tse_register_formula_processor (TseAccountHandle, char const* key, TseFormulaProcessor, void* userData);
TseStatus tse_add_input_ohlcv_by_key(TseAccountHandle, char const* label, int32_t dataLength,
TseDuration, char const* key, TseMarketHandle,
TseContractHandle const* contracts, size_t contractCount);
/* also _bidask_by_key, _trade_by_key, _executed_by_key */
TseStatus tse_add_pattern_formula_by_key(TseAccountHandle, char const* label, TseDuration,
char const* const* inputLabels, size_t inputCount,
char const* key);
TseStatus tse_save(TseAccountHandle account, char const* robotLabel, char const* path);
TseStatus tse_load(TseAccountHandle account, char const* robotLabel, char const* path);
TseStatus tse_bind_input(TseAccountHandle account, char const* inputLabel, TseMarketHandle market);
account.registerInputProcessor("sma", processor); // also ...BidAsk / ...Trade / ...Executed
account.registerFormulaProcessor("cross", formula);
account.addInputOhlcvByKey("in", 20, tse::Duration::days, "sma", market, {"AAPL"});
account.addPatternFormulaByKey("pat", tse::Duration::days, {"in"}, "cross");
account.save("Robot", "robot.db");
account.load("Robot", "robot.db");
account.bindInput("in", market);
a.register_input_processor("sma", processor) # also *_bidask / *_trade / *_executed
a.register_formula_processor("cross", formula)
a.add_input_ohlcv_by_key("in", 20, tse.Duration.Days, "sma", market, ["AAPL"])
a.add_pattern_formula_by_key("pat", tse.Duration.Days, ["in"], "cross")
a.save("Robot", "robot.db"); a.load("Robot", "robot.db"); a.bind_input("in", market)
Market data and connectors
Market data enters the engine through typed adapters (tse_market_create), one push function per market-data type, each addressing the contract by name or by id. An adapter is created on its own with a currency of its own and belongs to no account: the handle that created it and every account it is handed to share it, so one adapter can feed any number of accounts, whatever their reporting currency. Where the adapter's currency differs from an account's, the library writes one line into the log at the moment the adapter is handed over and applies its exchange rate rules from there on. A refused push leaves its reason on the adapter itself, readable with tse_market_last_error; a refused creation leaves it in the thread-local tse_last_market_create_error.
The executed channel (tse_md_executed) and the book channel (tse_md_book) 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.
TseStatus tse_market_push_ohlcv (TseMarketHandle, TseContractHandle contract, TseTickOHLCV const*);
TseStatus tse_market_push_bidask (TseMarketHandle, TseContractHandle contract, TseTickBidAsk const*);
TseStatus tse_market_push_trade (TseMarketHandle, TseContractHandle contract, TseTickTrade const*);
TseStatus tse_market_push_executed(TseMarketHandle, TseContractHandle contract, TseRetained const*);
CSV loaders
tse_dataplane.h keeps the CSV loading helpers for backtest data. The parameterized loaders take a nullable TseCsvOptions; NULL means the per-type defaults.
The *Column fields name columns by role; an empty or NULL role field falls back to that role's default name. indexColumn selects the timestamp column, which matters for dual-timestamp files. The bid/ask roles (bidColumn, bidVolumeColumn, askColumn, askVolumeColumn, lastColumn) apply to the bid/ask loader; priceColumn, volumeColumn and sideColumn apply to the trade loader — volume and side are copied into the tick only (they never form the price serie), and a side cell holds either a numeric TseSide code or the exact textual name mirrored by tse_side_to_string. The OHLCV loader has no role fields of its own: its value columns are fixed at Open/High/Low/Close/Volume. When the same options structure is handed to tse_csv_reader_create (the generic reader of tse_timeserie.h), the header itself says the role-column fields play no part there — only dateFormat, separator, hasHeader, ignoreParseErrors and bufferSize do. ignoreParseErrors drops an unparsable row instead of failing the whole load; bufferSize sizes the reader's I/O buffer, zero meaning the engine-chosen default. Set structSize to sizeof(TseCsvOptions) for forward compatibility.
Defaults per loader: separator ,, date format %m/%d/%Y %H:%M, index column Date; OHLCV value columns Open/High/Low/Close/Volume, bid/ask columns bid/bid_volume/ask/ask_volume/last, trade price column price.
One date-format note that saves an afternoon: the parser's plain %S already consumes an optional fractional part after the seconds. Write %Y-%m-%d %H:%M:%S for both 12:00:05 and 12:00:05.123456; do not write %S.%f.
The options record in full:
| Field | Type | Meaning |
|---|---|---|
structSize | size_t | set to sizeof(TseCsvOptions) |
dateFormat | char const* | e.g. "%m/%d/%Y %H:%M" |
separator | char | , or ; |
hasHeader | int | non-zero if a header row is present |
indexColumn | char const* | header name of the timestamp column |
bidColumn | char const* | BidAsk role |
bidVolumeColumn | char const* | BidAsk role |
askColumn | char const* | BidAsk role |
askVolumeColumn | char const* | BidAsk role |
lastColumn | char const* | BidAsk role |
priceColumn | char const* | Trade role |
volumeColumn | char const* | Trade role |
sideColumn | char const* | Trade role |
ignoreParseErrors | int | drops an unparsable row instead of failing the whole load |
bufferSize | size_t | zero means the engine-chosen default |
TseStatus tse_load_ohlcv_csv (char const* filePath, TseTickOHLCV** outTicks, size_t* outCount);
TseStatus tse_load_ohlcv_csv_ex(char const* filePath, TseCsvOptions const* options, TseTickOHLCV** outTicks, size_t* outCount);
TseStatus tse_load_bidask_csv (char const* filePath, TseCsvOptions const* options, TseTickBidAsk** outTicks, size_t* outCount);
TseStatus tse_load_trade_csv (char const* filePath, TseCsvOptions const* options, TseTickTrade** outTicks, size_t* outCount);
void tse_free_ticks(TseTickOHLCV* ticks);
void tse_free_bidask_ticks(TseTickBidAsk* ticks);
void tse_free_trade_ticks(TseTickTrade* ticks);
char const* tse_last_csv_error(void); /* thread-local text of the last loader failure */
auto ticks = tse::Account::loadOhlcvCsv("bars.csv");
auto ticks2 = tse::Account::loadOhlcvCsv("bars.csv", options); // tse::CsvOptions
auto quotes = tse::Account::loadBidAskCsv("quotes.csv", options);
auto trades = tse::Account::loadTradeCsv("trades.csv", options);
opts = tse.make_csv_options(date_format="%Y-%m-%d %H:%M:%S", index_column="est")
bars = a.load_ohlcv_csv("bars.csv", opts) # None -> default options
quotes = a.load_bidask_csv("quotes.csv", opts)
trades = a.load_trade_csv("trades.csv", opts)
tse.last_csv_error()
The book Simulator: an order standing in a queue
The engine ships two executions that fill orders by themselves. The Simulator described above prices a fill against a quote. The book Simulator prices it against an order book: it keeps a mirror of a book feed for every traded contract, stands the account's own order in the queue of its price level, and fills it as the feed's own executions reach it. It is created with tse_exec_create_simulator_book, and every robot's traded contract must be carried by a book adapter, or the account refuses to start.
A book feed is part of the account's setup, not an action during the run. The mirror holds no past: it fills only from the messages that arrive after the feed is attached. Hand the adapter to the book Simulator with tse_exec_book_feed before the account starts, so that the mirror of a contract begins filling at the moment that contract begins trading. A feed attached later measures the queue only from that moment, and the fill rate of its contract is not comparable with the rest. Once a robot has started, a late book feed is refused.
| Field | Type |
|---|---|
| execLagValue | int32_t |
| execLagDuration | TseDuration |
| ordersCapacity | uint64_t |
ordersCapacity sizes the mirror of each traded contract and must be positive; a zero is refused. It is not a ceiling the feed can break. When a mirror has spent its own capacity, further levels come from a buffer the whole process shares, so the mirror goes on accepting messages instead of refusing them, and it leaves its error text empty. The shared buffer is the real limit, and a run meets it only when it mirrors many books at once.
The mirror is fed by the adapter alone. An order of the account is never put into the mirror, because the feed already carries every order the market holds, and counting the account's own order twice would distort the book. An order reaches the market at the first message later than the moment it arrived plus the lag; until then it holds no place in any queue. On reaching the market it first crosses whatever the opposite side offers within its price, and whatever is left of it rests in the queue of its level, behind every order of the feed that was already there and ahead of every order that arrives later.
Only one kind of message fills a resting order: the execution of another order on the same side. An execution of an order that stood behind the account's own order gives the account the smaller of the two sizes; an execution at a price worse than the account's own price means the aggressor walked through the level, and the whole remainder is filled; an execution ahead of the account gives it nothing. Two consequences follow, and both are worth stating plainly. An order priced better than every order of the feed on its side is filled only when the feed executes at a worse price. And two orders of the account on opposite sides never fill each other, because neither of them is in the book.
A book feed carries no price, so the book Simulator derives a quote from the top of its mirror — the prices and sizes of the best level on each side, and the price of the last execution — and publishes it on an adapter of its own. The portfolio is subscribed to that adapter and marks positions by it, so an account that trades on a book feed needs no price feed for its risk rules to work. The quote is published only once both sides of the mirror hold something, and only when the top of the book or the last execution price has changed.
That adapter is reachable from outside as well. tse_exec_derived_quote_market hands out the derived quote feed as an ordinary TseMarketHandle, so an input, a robot, a rule and the portfolio subscribe to it exactly as they subscribe to a feed of their own making; its label is the execution's label with .derived_quote appended and its market-data type is tse_md_bidask. The rule is read, do not write: the Simulator owns the feed and fills it, so every push function is refused on that handle, and so is tse_market_set_currency_pair, which would set an exchange rate nothing could ever harvest. Handing it to tse_exec_book_feed is refused too, because a bid-ask feed is not a book feed. Each call hands out a fresh wrapper around the same feed, and each wrapper is destroyed by the caller with tse_market_destroy; destroying one leaves the others and the feed itself untouched. The call answers NULL when the account's execution is not a book Simulator, with the reason in tse_last_error.
TSE_API TseMarketHandle tse_exec_derived_quote_market(TseExecHandle exec);
Two readers answer what the account itself has outstanding on a contract. tse_exec_resting_count and tse_exec_resting_order walk every order that has been submitted and not yet finished, the ones still waiting out the lag among them; tse_exec_admitted_count and tse_exec_admitted_order walk the narrower set that has reached the market. Both listings are in the order the orders were submitted, and both hand out a TseOrder, the same record a custom execution receives in its fill callback, where quantity is what is still to execute. Neither listing is a stable index: an order fills or is cancelled between two calls, so a caller that walks a listing reads the count again rather than keeping an old one.
| Field | Type |
|---|---|
| present | int |
| ordersAhead | int64_t |
| contractsAhead | double |
| remaining | double |
| price | TsePrice |
| side | TseSide |
tse_exec_queue_position names an order by its client order id and answers where it stands: how many live orders of the feed are ahead of it on its level, how many contracts they hold, and what is left of the order itself. An order the execution cannot name — one it does not know, one already filled or cancelled, and one that has not yet reached the market — is not an error: the answer comes back with present 0. tse_exec_is_admitted asks the narrower question directly, without walking the admitted listing: whether that order has reached the market and now rests on a level. An order the execution does not know reads as not admitted rather than as an error. The mirror itself is readable through tse_exec_book, which gives a handle that every statistic, level and order function of the book chapter accepts; it takes no messages of its own.
The fill model a book Simulator was created with is read back with tse_exec_get_simulator_book_config and replaced with tse_exec_set_simulator_book_config. The checks are the ones the creator makes: a positive ordersCapacity and a lag representable in nanoseconds. A new capacity governs the orders admitted from that call on and does not disturb the orders already resting, and a refused call leaves the model as it was.
tse_exec_book_clear empties one contract of the Simulator in a single action: every order of the account still resting on that contract is reported cancelled and taken off the books, the execution forgets the queue it kept — the places, the pending amendments, the last executed price and the last quote it published — and the mirror itself is cleared down to an arrival counter of zero. The feed stays attached, so the mirror fills again from the next message on, and the next quote is published afresh rather than suppressed as a repeat of the one before. A contract the Simulator keeps no book state for is refused, and so is an execution that is not a book Simulator. This is the only way to empty a mirror: tse_book_clear on the handle tse_exec_book gave out is refused, because the Simulator must forget its queue in the same action.
TSE_API TseStatus tse_exec_set_simulator_book_config(TseExecHandle exec, TseSimulatorBookConfig const* options);
TSE_API TseStatus tse_exec_book_clear(TseExecHandle exec, TseContractHandle contract);
TSE_API TseStatus tse_exec_is_admitted(TseExecHandle exec, char const* clientOrderId, int32_t* outAdmitted);
An amendment the account makes to its own resting order is carried into the book Simulator's own record of it, so an order whose quantity has been reduced is complete once the reduced quantity has been filled: an order cut from twenty contracts to ten and then filled for ten reads as filled, not as partly filled against the twenty it first asked for. That carrying happens when the amendment lands, not when it is sent: an order already standing in the queue keeps the quantity it was admitted with until the execution lag has run, and only an order that reaches the book after the amendment was admitted is placed with the amended quantity straight away.
A multileg group is not executed by the book Simulator: every leg is rejected with a diagnostic. The time in force of an order is honoured as the venue would honour it: day, gtc, gtd and gts rest and fill in parts, ioc takes what it can at once and cancels the remainder, fok executes whole or not at all, aon rests but fills only on an event that covers all of it, and atc, opg and an undefined time in force are rejected at the moment the order reaches the market. Like the Simulator, the book Simulator assumes the engine is driven from one thread: the feed's callbacks run on the thread that pushes, orders arrive on the robot's thread, and no lock is taken on either path.
Custom execution: the go-live seam
The same robot that backtests against the built-in Simulator goes live by swapping one object: create the execution with tse_exec_create_custom instead of tse_exec_create_simulator. A custom execution is not connected to market data; it receives each outgoing order in your fill callback and reports fills — none, one, or several partials — through tse_exec_apply_fill, addressing the order by its client order id. The report may be made from inside the callback or after it has returned, with the client order id you kept; the contract takes no lock on your behalf and the callback is not required to take one on the engine's. That freedom covers every report and every callback: an acknowledgement, a rejection, a fill and the confirmation of an amendment are all accepted from inside the order callback, from inside the amend callback and from inside the combination callback, and nesting them is allowed — a confirmation made inside a callback may raise a new amendment whose own callback confirms it in turn. An order that a risk rule issued while the engine was marking a position to a new price is no exception, and neither is a cancellation of one: before the engine hands you an order or an amendment it has released the lock of the order pool and the lock of the exposure, so a report made from inside a callback never meets a lock of the engine's already held by its own thread. Both creators take requiredDataLength (the resting-order buffer length per contract) and the mandatory coreId. The record the callback receives is TseOrder:
| Field | Type |
|---|---|
| clientOrderId | char[32] |
| symbol | char[32] |
| txnSide | TseSide |
| quantity | double |
| priceType | TsePriceType |
| limitPrice | TsePrice |
| tsMktEventNanoseconds | int64_t |
| ruleLabel | char[64] |
| robotLabel | char[64] |
| tif | TseTif |
| txnType | TseTxnType |
| hasTrigger | int |
| triggerPrice | TsePrice |
| triggerOffset | double |
The lifecycle of an order at the venue. The engine models the three moments a venue has — acceptance, amendment and completion — and a custom execution reports each of them with one call. When the venue accepts an order, report it with tse_exec_acknowledge, passing the venue's own identifier as the broker order id: the engine marks the order accepted, every later fill of it carries that identifier in brokerOrderId, and the order becomes amendable. When the venue refuses an order, report it with tse_exec_reject_order: the order is marked rejected, its reservation is released and the engine forgets it. An order that was never acknowledged behaves as it always did: its fills are accepted and the engine mints a broker order id of its own, but the engine's own amendments do not reach the venue — a cancel, modify or replace rule that fires is refused as having arrived too late, and tse_cancel_all finds nothing to cancel — because no venue has confirmed the order they would address. After the acknowledgement those amendments reach the amend callback registered with tse_exec_set_amend_callback. It receives the kind of the amendment as a TseBookMessageKind (cancel, modify or replace), the TseOrder record already carrying the terms the engine now wants — the remaining quantity after a modify, the new price after a replace — and the amendment's own timestamp. The engine marks the order pending and adjusts its reservation at once: a cancel releases it, a modify or a replace re-reserves the new terms. When the venue answers, report it with tse_exec_confirm_amend and the same kind. A cancel is accepted from any live state, so it also reports a cancel the venue decided on its own — an expired day order, an unfilled immediate-or-cancel — and completes the order; a modify or a replace is accepted only while the order awaits that very amendment, and leaves the order live with its new terms. Any other kind — new, executed or a value outside the enumeration — is refused as not an amendment. Without an amend callback the engine writes a warning line into the journal and the order stays pending until you confirm or fill it. Every one of these calls refuses an unknown or already completed client order id, a second acknowledgement of the same order and an identifier longer than 31 characters, with the reason in tse_last_error.
A multileg transaction reaches a custom execution as one combination rather than as separate orders. Register a combination callback with tse_exec_set_combo_callback and it receives the combination header — the multileg identifier, the net price and the net side — together with the array of leg orders and their weights. Report the whole group with tse_exec_apply_combo_fill, addressing it by that identifier and supplying one price and one fee per leg, or refuse it with tse_exec_reject_combo. Per-order tse_exec_apply_fill does not address a leg of a combination and is refused for it, and an execution with no combination callback registered rejects every leg of the multileg. A null callback is not a way to unregister: it is refused with a message naming it.
TseExecHandle tse_exec_create_custom(TseAccountHandle account, char const* label,
TseFillCallback fillCallback, void* userData,
int32_t requiredDataLength, int coreId);
TseStatus tse_exec_apply_fill(TseExecHandle exec, char const* clientOrderId,
TsePrice price, double quantity, double fee,
int64_t tsExecutionNanoseconds);
TseStatus tse_exec_acknowledge(TseExecHandle exec, char const* clientOrderId,
char const* brokerOrderId);
TseStatus tse_exec_reject_order(TseExecHandle exec, char const* clientOrderId);
typedef void (*TseAmendCallback)(TseExecHandle exec, TseBookMessageKind kind,
TseOrder const* order, int64_t tsAmendmentNanoseconds,
void* userData);
TseStatus tse_exec_set_amend_callback(TseExecHandle exec, TseAmendCallback amendCallback,
void* userData);
TseStatus tse_exec_confirm_amend(TseExecHandle exec, char const* clientOrderId,
TseBookMessageKind kind);
The connection library
Feeding a live robot is the job of a separate, standalone shared library: libtse_connection, with its own C surface under tse_connection/ (tse_connection.h is the umbrella) and its own ABI version, tse_connection_abi_version(). It is a deliberately small client stack: one handle, six protocols, one message type.
- Protocols (
TseConnectionProtocol):http,https,ws,wss,udp,udp_multicast. - Two ways to consume messages: push (a
TseConnectionMessageHandlerinvoked on the handler threads set bytse_connection_client_set_handler_threads) and pull (tse_connection_client_wait_message, or the combined send-and-waittse_connection_client_request); waiting comes in park and spin flavors (TseConnectionWaitMode), receiving likewise (TseConnectionReceiveModein the config). Both pull calls answer with aTseConnectionStatus:ok(a message is out),timeout(nothing arrived within the budget),closed(the session is gone for good: the server sent a WebSocketCloseframe or dropped the connection and no reconnection is configured, the reconnection attempts are exhausted, the initial connection was refused, or the application calledtse_connection_client_stop),error,invalid_argumentorinvalid_handle. Afterclosed,tse_connection_last_errorreads<call>: connection closed, followed by: <code> <reason>when aCloseframe carried them (: 1000 diagnostic close) or by: connect failedwhen the connection was never established. The push side learns the same fact through aTseConnectionCloseHandlerset bytse_connection_client_set_close_handler: it is invoked exactly once pertse_connection_client_run, on the client's worker thread, with the same reason text (NUL-terminated, valid only during the call); it is not invoked for the application's ownstopordestroy, and it must not callrun,stopordestroyon the same handle. On a server'sCloseframe the library answers with its ownCloseframe before dropping the connection, as RFC 6455 requires. tse_connection_client_run(client, config, reconnect)withreconnect = 1reconnects on its own and reports nothing while the attempts go on;closedand the close handler appear only once the attempts are exhausted. Aftertse_connection_client_stopa newrunstarts the client afresh on the same handle. Intse_connection_client_requesttheverbOrOpcodeargument is aTseConnectionHttpVerbfor http/https and aTseConnectionWsOpcodefor ws/wss (textsends a text frame, every other value a binary one); the Python wrapper passes it through itsverbparameter, which therefore also accepts aWsOpcode.- TLS verification (
TseConnectionTlsVerifyMode):ca_hostname(verify the chain and the host name),ca(chain only),none; the CA can come inline (tlsCaPem) or from a file (tlsCaFile). - A
TseConnectionMessagecarries the raw bytes and, for UDP, the sender endpoint; the HTTP status, the headers and the WebSocket opcode fields are reserved and currently left at zero.
In C++ code every enumeration of the connection library has the fixed underlying type uint32_t (the macro TSE_CONNECTION_ENUM_BASE of tse_connection/tse_connection_api.h), so converting any 32-bit value to it is legal; in C code the macro is empty.
One documented limitation of the kernel-socket path: a single received UDP datagram is capped at 2048 bytes — a larger datagram is truncated by the kernel and the excess is discarded, for unicast and multicast alike. That is sufficient for typical multicast market data, which stays within an Ethernet MTU. Note what this cap is not: it is not SO_RCVBUF, which only sizes the kernel's receive queue (how many datagrams may wait), never the size of one datagram.
TseConnectionClientHandle tse_connection_client_create(TseConnectionProtocol protocol);
void tse_connection_client_destroy(TseConnectionClientHandle client);
TseConnectionStatus tse_connection_client_set_handler_threads(TseConnectionClientHandle, size_t threadCount);
TseConnectionStatus tse_connection_client_set_message_handler(TseConnectionClientHandle,
TseConnectionMessageHandler, void* userData);
TseConnectionStatus tse_connection_client_set_close_handler(TseConnectionClientHandle,
TseConnectionCloseHandler, void* userData);
TseConnectionStatus tse_connection_client_run (TseConnectionClientHandle, TseConnectionConfig const*, int reconnect);
TseConnectionStatus tse_connection_client_stop(TseConnectionClientHandle);
TseConnectionStatus tse_connection_ws_send_text (TseConnectionClientHandle, char const* utf8, size_t length);
TseConnectionStatus tse_connection_ws_send_binary(TseConnectionClientHandle, uint8_t const* data, size_t length);
TseConnectionStatus tse_connection_ws_close (TseConnectionClientHandle, char const* reason);
TseConnectionStatus tse_connection_udp_send (TseConnectionClientHandle, uint8_t const* data, size_t length);
TseConnectionStatus tse_connection_http_request (TseConnectionClientHandle, uint8_t const* body, size_t length,
TseConnectionHttpVerb verb);
TseConnectionStatus tse_connection_client_wait_message(TseConnectionClientHandle,
TseConnectionWaitMode mode, uint64_t timeoutMs,
TseConnectionMessage const** outMessage);
TseConnectionStatus tse_connection_client_request(TseConnectionClientHandle, uint8_t const* body, size_t length,
int verbOrOpcode, TseConnectionWaitMode mode,
uint64_t timeoutMs, TseConnectionMessage const** outMessage);
char const* tse_connection_last_error(TseConnectionClientHandle client);
Ex-post analysis
tse_ex_post.h turns an account's robot-tagged trades into duration-bucketed scoring series — the raw material of candidate selection. There are three ways in. tse_ex_post_create builds a live object from the account's trades and scores it. tse_ex_post_open reads back a journal a previous run wrote, and costs no scoring at all. tse_ex_post_rebuild_from_file and tse_ex_post_rebuild_range put a stored run back together and carry it forward over the trades that follow it, at the cost of the new buckets only. What any of the three returns is read through the same feature readers, and tse_ex_post_save_compact and tse_ex_post_save_complete write a live object back to disk.
tse_ex_post_create builds the per-robot buckets and runs the scoring pass once. step selects the bucket unit (e.g. tse_duration_days). stepCount is the signed width of one bucket, counted in units of step: a negative width cuts backwards from the newest trade, a positive one forwards from the oldest, and in both cases the output runs from the oldest bucket to the newest. Both signs work; a zero width is refused, because a bucket of no width has no grid to align to. windowSize is the scoring window length in buckets and is bounded at both ends: it must be at least two, since no score can be derived from a single bucket, and it must be below 128, the depth of the ranking ring, since a resumed run rewinds that ring by one window and cannot reach further back than the ring remembers. A window outside those bounds is refused rather than silently yielding nothing. threadCount is the number of threads that build the buckets and score the robots of each step; it must be positive and is capped by the number of robots and by the number of hardware threads. The scores do not depend on it, except the thompson_sampling column, which is random by design. emptiesMode decides what the journal does with a step at which a robot did not trade: tse_empties_skip keeps no record of such a step, tse_empties_include records it with absent values. The two give journals of different length, so the row a given moment lands on differs between them.
tse_ex_post_save_compact and tse_ex_post_save_complete write the object's buckets and scores — the strategies, serie, scoring, meta and ranking-state tables — into an SQLite database at dbPath without running the scoring pass again. They differ in what they keep. The compact form drops the inference record, whose outcome is not yet known because the next bucket does not exist yet, and drops every score that came out absent. The complete form writes both, an absent value as SQL NULL. Only a file written in the complete form can be opened back into the journal the run held; a compact file is for reading with SQL, not for resuming from. The tables are created first when the file lacks them; every row of one call is then written in a single transaction, so a failed call leaves no row of its own in the file, while the tables stay. When the write fails, the reason is in tse_last_error of the account the object was created from; a NULL exPost or dbPath returns tse_error and leaves tse_last_error as it was. A handle obtained from tse_ex_post_open holds a journal and no series, so both saves refuse on it with an explanation: there is nothing to write the serie table from, and half a file would be worse than a refusal. tse_ex_post_load is unchanged and remains a check of the file: it opens and validates such a database and returns the stored robot count (outRobotCount may be NULL), building no handle.
tse_ex_post_open returns a handle over the journal read back from a complete file, without touching a single trade and without computing anything. It is the cheap path to the features of a run that has already happened. The bucket width, the window length and the empties mode are taken from the file rather than from the caller, so a stored run is always read back under the conditions it was built with.
tse_ex_post_rebuild_from_file resumes a stored run. The series, the ranking ring and the journal are put back from the file, the series are extended by the trades that follow the greatest stored bucket, and the scoring pass runs again from one window behind that bucket — far enough back that every score the new buckets touch is recomputed, and no further. tse_ex_post_rebuild_range does the same for a range given explicitly in nanoseconds. That range must begin at the bucket right after the greatest stored one: an earlier start would count stored buckets twice and a later one would leave a hole in the serie, and both are refused with a message naming the boundary. A range in which no trade happened is not an error — nothing is added, the log says so, and the call succeeds, so a weekend or a holiday does not interrupt a daily cycle. Two things the resumed pass does with the population are worth stating. First, the journal read from the file ends, for every robot that has one, with an inference record — the row whose outcome is not known yet — and the resumed pass drops that record before it recomputes, then writes a fresh one at the end; a robot that fell silent long before the stored end therefore no longer collides with its own stored record. Second, a robot the file does not hold is admitted: it enters the population with an empty stored serie, takes the buckets its new trades produce, and is scored from the moment it has a window of them; until then it yields no journal rows. Its trades must all follow the stored boundary — a newcomer carrying a trade earlier than that is refused, with the message naming the robot and the moment of its earliest trade, because the stored buckets were cut without it. A robot the file holds but this pass does not register is refused, and the message names that robot, because the stored series it carries would have no owner to extend. A robot offered to an empty stored population is refused as well: an empty population has nothing to extend, and a first run is the only way to admit a robot into it. Admitting a newcomer does not rewrite what the file already holds. The journal rows that lie before the recomputed stretch keep the scores they were given when the population was smaller, and the rank-dependent columns among them are normalised by that smaller population; only the rows from one window behind the stored boundary onwards are recomputed with the newcomer counted in. The ranking ring the file holds is grown to the new population before the pass restarts: every robot the file knows keeps the place it held on each stored step, the newcomers take the places left over at the tail of each step in the order of their labels, so that a step still names every robot exactly once, and a newcomer is marked on those steps as one that had not yet produced an outcome. The five rank-dependent columns — rolling_rank, rank_momentum, top_k_fraction, rank_entropy and expected_holding_duration — read only the steps at which a robot had already produced an outcome, and divide by the number of steps they actually read, so a tail place a newcomer never earned never reaches a score. A newcomer therefore gets rank_momentum only after forty steps of its own and expected_holding_duration only after twenty. A resumed run with a newcomer therefore agrees with a full run over the same trades from that point on, and keeps the earlier scores as they were first computed.
A resumed run reproduces a full run over the same trades, with one qualification worth stating plainly: money is stored in REAL columns, and the round trip through a binary floating-point column is not exact, so a resumed result is very close to a full one rather than bit-for-bit identical to it. The difference observed is at the scale of one millionth of a currency unit per value.
Each of the three entry points refuses, rather than returning an empty object, when: the path is empty or blank; the file does not exist (and no file is created at that path); the file is not a database, or is a database whose table composition precedes the present schema; the file records no build conditions, because it was written by a library that did not record them; the file was cut with a bucket unit other than the one asked for; the file records an unknown empties mode, a zero bucket width or a number of scoring columns other than the present one; the file's schema version is not the one this library reads; the ranking state stored beside the series stands at a step too low to carry the window back, or does not answer the stored population — a state standing at step zero is not among these, because the ring is then rebuilt from the beginning and the stored series are extended; the journal holds a number of robots other than the number the ranking state holds, or more robots than the population; a robot is offered to an empty stored population; threadCount is zero; the window is outside its two bounds; or an explicit range is reversed or does not meet the stored boundary. A sound but empty database — all tables present, no robots — is not an error: it yields a handle with no robots, and reading any feature from it fails as an index out of range.
The handle returned by any of the three is owned by the caller (destroy it with tse_ex_post_destroy) but borrows the account and becomes invalid when the account is destroyed. The feature readers share one protocol:
- Two-phase extraction: call with null output buffers first — the required row count is stored into
*inoutRowCountand nothing else is touched; then call again with buffers of that size. outValuesis a flat buffer ofrowCount * tse_ex_post_param_count()floats, laid out row by row (row-major).- Row order is variant-major: all buckets of the first half-life (for EWMA) or the first lookback (for level crossings) come first, then the second, and so on; momentum has exactly one variant.
- Absent values arrive as NaN — gaps are preserved, not interpolated.
The parameter axis is not mirrored as C constants: its width is tse_ex_post_param_count() and the name of each column is tse_ex_post_param_name(index).
The parameter axis — every scoring column a bucket carries — is the following set:
| Duration-based score parameters (78) | ||
|---|---|---|
1. rolling_mean_return | 27. consequtive_loss | 53. rolling_skewness |
2. ew_mean_return | 28. confirmed_negative_trend | 54. regime_flip_rate |
3. rolling_median_return | 29. return_volatility | 55. net_profit |
4. rolling_sharpe | 30. rolling_kurtosis | 56. gross_profit |
5. return_adjusted | 31. psi_drift | 57. gross_loss |
6. rolling_calmar | 32. equity_curve_strength | 58. total_trades |
7. rolling_omega | 33. hurst_exponent | 59. avg_trade_net_profit |
8. gain_to_pain | 34. linearity_trend | 60. max_equity |
9. hit_rate | 35. return_autocorr_lag1 | 61. min_equity |
10. win_rate | 36. acf_sum | 62. max_drawdown |
11. profit_factor | 37. pacf | 63. return_on_account |
12. pf_momentum | 38. cross_correlation | 64. profit_factor_raw |
13. rolling_rank | 39. rolling_beta | 65. entry_efficiency |
14. rank_momentum | 40. mann_kendall_trend | 66. exit_efficiency |
15. top_k_fraction | 41. theil_sen_slope | 67. win_loss_ratio |
16. cross_sectional_zscore | 42. directional_consistency | 68. kelly |
17. switch_cost_adjusted | 43. market_volatility | 69. mfe_pct |
18. thompson_sampling | 44. feature_correlation | 70. mfe_abs |
19. return_acceleration | 45. performance_dispersion | 71. avg_winning_round_trip |
20. tail_ratio | 46. rank_entropy | 72. avg_losing_round_trip |
21. current_drawdown | 47. step_change | 73. largest_win |
22. drawdown_duration | 48. information_coefficient | 74. largest_loss |
23. rolling_cvar | 49. ic_decay_halflife | 75. consecutive_wins |
24. rolling_mae | 50. rolling_ic_stability | 76. max_consecutive_wins |
25. ulcer_index | 51. granger_causality | 77. trading_days |
26. equity_curve_breakdown | 52. expected_holding_duration | 78. composite |
The five tables such a database holds are tabulated in appendix G.
typedef enum TseEmptiesMode TSE_ENUM_BASE {
tse_empties_skip = 1,
tse_empties_include = 2
} TseEmptiesMode;
TseStatus tse_ex_post_save_compact (TseExPostHandle exPost, char const* dbPath);
TseStatus tse_ex_post_save_complete(TseExPostHandle exPost, char const* dbPath);
TseStatus tse_ex_post_load(TseAccountHandle account, char const* dbPath, size_t* outRobotCount);
TseExPostHandle tse_ex_post_open(TseAccountHandle account, char const* dbPath);
TseExPostHandle tse_ex_post_rebuild_from_file(TseAccountHandle account, char const* dbPath,
uint32_t threadCount);
TseExPostHandle tse_ex_post_rebuild_range(TseAccountHandle account, char const* dbPath,
int64_t fromNanoseconds, int64_t toNanoseconds,
uint32_t threadCount);
TseExPostHandle tse_ex_post_create(TseAccountHandle account, TseDuration step,
int32_t stepCount, int32_t windowSize, uint32_t threadCount,
TseEmptiesMode emptiesMode);
void tse_ex_post_destroy(TseExPostHandle exPost);
TseStatus tse_ex_post_robot_count (TseExPostHandle, size_t* outCount);
TseStatus tse_ex_post_robot_label (TseExPostHandle, size_t robotIndex, char* buf, size_t capacity);
TseStatus tse_ex_post_bucket_count(TseExPostHandle, size_t robotIndex, size_t* outCount);
size_t tse_ex_post_param_count(void);
char const* tse_ex_post_param_name(size_t paramIndex);
TseStatus tse_ex_post_feature_momentum(TseExPostHandle, size_t robotIndex,
int64_t* outTsNanoseconds, float* outValues, size_t* inoutRowCount);
TseStatus tse_ex_post_feature_ewma(TseExPostHandle, size_t robotIndex,
float const* halfLives, size_t halfLifeCount,
int64_t* outTsNanoseconds, float* outValues, size_t* inoutRowCount);
TseStatus tse_ex_post_feature_level_crossings(TseExPostHandle, size_t robotIndex,
size_t const* lookbacks, size_t lookbackCount,
int64_t* outTsNanoseconds, float* outValues, size_t* inoutRowCount);
tse::ExPost ep
{
account.createExPost
(
tse::Duration::days, -1, 30,
tse::coreCount(),
tse::EmptiesMode::skip
)
};
auto [ts, values] = ep.featureEwma(0, {5.0f, 20.0f});
std::size_t n = tse::ExPost::paramCount();
std::string name = tse::ExPost::paramName(0);
ep.saveComplete("scores.sqlite3.db");
tse::ExPost read {account.openExPost("scores.sqlite3.db")};
tse::ExPost today {account.rebuildExPostFromFile("scores.sqlite3.db", 1u)};
today.saveComplete("scores.sqlite3.db");
ep = a.create_ex_post(tse.Duration.Days, -1, 30, os.cpu_count() or 1, tse.EmptiesMode.Skip)
ts, values = ep.feature_momentum(0)
ep.robot_count(); ep.robot_label(0); ep.bucket_count(0)
ep.param_count(); ep.param_name(0)
ep.save_complete("scores.sqlite3.db")
read = a.open_ex_post("scores.sqlite3.db")
today = a.rebuild_ex_post_from_file("scores.sqlite3.db", 1)
today.save_complete("scores.sqlite3.db")
Operational practice: the daily cycle
Starting and stopping a trading process deliberately, once per session day, is standard practice in the industry rather than an admission that the software cannot run longer. A process that is brought up before the session and taken down after it starts each day from a known state: caches are cold and therefore consistent with the data that is about to arrive, the day's log and blotter files are delimited by the run itself, memory that accumulated over the session is returned, and any configuration change made overnight takes effect at a single, observable moment instead of drifting in. The engine is built for that rhythm: tse_stop ends a robot's event flow, the account destructor releases its threads and closes its storage, and the next run reconstructs the object graph — from a saved recipe (tse_load) when you want the previous wiring back verbatim.
Doing this by hand every day is the part worth automating, and the operating system already provides the machinery, so there is no reason to build scheduling into the trading process itself. On Linux the conventional instrument is systemd: a unit describing the process, with a timer (or a calendar-scheduled pair of units) starting it before the session and stopping it afterwards, and the unit's restart policy covering an unexpected exit. The supervisor owns the schedule and the restart semantics; the robot owns only its trading logic.
The shipped library
The product is delivered as a dynamic object and is loaded as a dynamic object: on macOS the file is libtse_export.dylib, and it arrives accompanied by the C headers under include/tse/, the C++ wrapper (tse.hpp together with its one translation unit tse.cpp) and the Python module tse.py. Which file is opened at run time is decided exactly as the "Loading the library" section above describes — either by an explicit path argument, or, when none is given, through the TSE_EXPORT_LIB environment variable, falling back to the platform's default file name on the loader path.
Everything the library carries of its own is linked into it statically: the engine's internal static archives are merged into the single shared object at build time, so nothing of the engine has to be shipped beside it. There is one exception, and it is platform-specific: on macOS the standard libraries are resolved by path rather than absorbed, so they have to be present on the client machine.
The library checks its licence over the network, and that exchange is the only one the engine ever initiates on its own behalf — every other packet it sends is one you asked for, through a connector you configured or through a processor of yours that calls out. The check happens lazily, the first time a protected operation runs: a seat is taken, a checkpoint is reached, or the status is queried — and then once an hour while the process lives. What travels is the licence identifier, a salted hash of four machine attributes — platform UUID, hardware model, serial number and MAC address — a digest of the product binary, and the seat accounting the licence is measured by: the purchased number of robots, the highest number of robots running at once on each of the last eight days, the feature flags, the kind of environment, the hypervisor if the machine runs under one, and a boot identifier. Nothing of yours is in that message and nothing of yours can be: no market data, no contract, no strategy, no order, no trade and no statistic has a field to travel in. Where the check is addressed is yours to set — TSE_LICENSE_HOST, TSE_LICENSE_PORT and TSE_LICENSE_TARGET override the default endpoint, which is how an air-gapped or proxied installation points the library at a licence host of its own. A failed exchange does not stop a running robot: the lease enters a grace phase and work continues, with the condition readable at any time through tse_protection_status and the exchange repeatable on demand through tse_license_heartbeat.
Licence status, heartbeat and transfer
A licence is bound to one machine at a time. The first successful check binds it to the fingerprint of the machine it came from, and from then on the licence server refuses the checks of any other machine: there the library obtains no lease, refuses to start robots and writes an error to the log. The binding moves only on an explicit request, a transfer, made from the machine that should hold the licence next. The transfer releases the old binding, binds the calling machine and grants it a lease at once. The machine that lost the binding keeps its current lease and works until the lease and its grace period run out. A transfer requested by the machine that already holds the binding changes nothing and costs nothing, so a program may request it at every start. The binding can also be released from the licence's page in your account on the website; the next machine that checks in is then bound without a transfer.
Every release of a binding, whether by a transfer from another machine or from the website, spends one unit of the licence's transfer allowance — four per rolling window of twelve months that starts on the same calendar date one year earlier. When the allowance is spent, the server refuses both kinds of release and the binding stays where it is.
tse_protection_status reports the state of the protection layer at any time: whether enforcement is compiled into the library, whether the licence check has run, the lease phase, the robot ceiling in force and whether the licence is unlimited, the peak observed against that ceiling today and the code of the last protection event.
tse_license_transfer requests the transfer and returns tse_ok only when the licence server has confirmed it, so that this machine now holds the licence and a fresh lease. In every other case it returns tse_error and writes the reason to the log: the server cannot be reached, the transfer allowance is spent, the licence is suspended, revoked or expired, or the server's answer fails verification. A failure leaves the local lease as it was, so robots allowed to run before the call keep running. Since a transfer requested by the machine that already holds the licence changes nothing and costs nothing, a failed call can simply be repeated once the server is reachable. tse_license_heartbeat repeats the licence check on demand; it returns tse_ok when the machine holds a valid lease after the call — a lease still running offline counts — and tse_error otherwise.
| Field | Type |
|---|---|
| enforced | int32_t |
| initialized | int32_t |
| phase | TseLeasePhase |
| appliedMaxRobots | uint32_t |
| unlimitedRobots | int32_t |
| peakRobots | uint32_t |
| lastEventCode | uint32_t |
| Value | C | C++ tse::LeasePhase | Python tse.LeasePhase | Meaning |
|---|---|---|---|---|
| 0 | tse_lease_unactivated | unactivated | Unactivated | No lease has been granted on this machine |
| 1 | tse_lease_activated | activated | Activated | A lease is in force |
| 2 | tse_lease_within_grace | within_grace | WithinGrace | The lease has run out and the grace period is running |
| 3 | tse_lease_expired | expired | Expired | The lease and the grace period have run out without a successful check |
| 4 | tse_lease_revoked | revoked | Revoked | The licence has been revoked; the state is terminal |
The protection layer writes these situations to the log at level critical, the level the library starts with, so they appear without any configuration.
| Situation | Log line |
|---|---|
| The licence is bound to another machine and this one holds no lease | license is bound to another machine; call tse_license_transfer on this machine to move it; refusing to start |
| The licence is bound to another machine while this one still holds a lease | license is bound to another machine; running on the local lease until <deadline>; call tse_license_transfer on this machine to move it |
| A transfer is refused because the allowance is spent | license transfer refused: no transfers left for this license; contact support |
| A transfer cannot reach the licence server | license transfer failed: license server unavailable; call tse_license_transfer again once the server is reachable |
| The licence server cannot be reached and the lease holds | license server unavailable; running on offline lease until <deadline> |
| The licence server cannot be reached and the lease and its grace period have run out | offline lease expired without reaching the license server; refusing to start |
| More robots run at once than were purchased | purchased robot limit exceeded: peak <peak> over purchased <purchased>; overage is billed by the server |
| A grid search runs more robots at once than were purchased | grid-search auto-overage: peak <peak> over purchased <purchased>; billed by the server |
| A robot is started while no robots were purchased | robots were purchased in zero quantity; refusing to start |
TseStatus tse_protection_status(TseProtectionStatus* outStatus);
TseStatus tse_license_heartbeat(void);
TseStatus tse_license_transfer(void);
ProtectionStatus protectionStatus(); // TseProtectionStatus with bool flags and tse::LeasePhase; throws tse::Error when it cannot be read
bool licenseHeartbeat() noexcept; // true when the machine holds a valid lease after the call
bool licenseTransfer() noexcept; // true only when the server has confirmed the transfer
status = tse.protection_status() # TseProtectionStatus; raises TseError when it cannot be read
tse.LeasePhase(status.phase) # e.g. tse.LeasePhase.Activated
tse.license_heartbeat() # True when the machine holds a valid lease after the call
tse.license_transfer() # True only when the server has confirmed the transfer
Version 6.1.0.0. Also as Markdown: this chapter, the whole reference in one file, and the llms.txt map.