Expand description
§of_ffi_c
of_ffi_c exposes a stable C ABI for embedding the Orderflow runtime in non-Rust environments.
It is the native interface used by Python (ctypes), Java (JNA), and any C-compatible host runtime.
§ABI Surface
- Engine lifecycle:
of_engine_create,of_engine_start,of_engine_stop,of_engine_destroy - Subscription:
of_subscribe,of_unsubscribe,of_unsubscribe_symbol,of_reset_symbol_session - External ingest and supervision:
of_ingest_trade,of_ingest_book,of_configure_external_feed,of_external_set_reconnecting,of_external_health_tick - Polling and snapshots:
of_engine_poll_once,of_get_book_snapshot,of_get_analytics_snapshot,of_get_derived_analytics_snapshot,of_get_session_candle_snapshot,of_get_interval_candle_snapshot,of_get_signal_snapshot - Metrics and memory management:
of_get_metrics_json,of_string_free
§New In 0.4.0
0.4.0 keeps all existing analytics/runtime C ABI symbols valid and adds a
separate execution ABI family. Existing hosts that only call
of_engine_create, subscribe, poll, ingest, and read snapshots do not need to
change those call sites.
New execution ABI concepts:
of_execution_engine_t: synchronous simulated execution handleof_execution_engine_createandof_execution_engine_create_multi: single-route and multi-route constructionof_execution_submit_order,of_execution_cancel_order,of_execution_amend_order, andof_execution_pollof_execution_order_state,of_execution_health, andof_execution_metricsof_execution_concurrent_engine_t: bounded worker for many command producers and one deterministic execution ownerof_execution_command_report_t: typed command completion report with a caller-owned event buffer
The execution ABI is additive and intentionally separate from the market-data engine ABI. That separation lets C, Python, Java, and other FFI users adopt OMS workflows without destabilizing existing analytics deployments.
Version policy:
of_ffi_cpublishes as0.4.0with the established native library line;- the Rust execution crates behind the ABI publish as
0.1.0; - native headers and libraries should still be upgraded together.
§Public ABI Inventory
Public C structs/types:
of_engine_config_tof_symbol_tof_trade_tof_book_tof_external_feed_policy_tof_error_tof_engineof_subscriptionof_event_tof_event_cb
Exported C functions:
of_api_versionof_build_infoof_engine_createof_engine_startof_engine_stopof_engine_destroyof_subscribeof_unsubscribeof_unsubscribe_symbolof_reset_symbol_sessionof_ingest_tradeof_ingest_bookof_configure_external_feedof_external_set_reconnectingof_external_health_tickof_get_book_snapshotof_get_analytics_snapshotof_get_derived_analytics_snapshotof_get_session_candle_snapshotof_get_interval_candle_snapshotof_get_signal_snapshotof_get_metrics_jsonof_string_freeof_engine_poll_once
of_get_book_snapshot returns a materialized JSON snapshot with:
venuesymbolbidsaskslast_sequencets_exchange_nsts_recv_ns
of_get_derived_analytics_snapshot returns additive session metrics with:
total_volumetrade_countvwapaverage_trade_sizeimbalance_bps
of_get_session_candle_snapshot returns candle-style session state with:
openhighlowclosetrade_countfirst_ts_exchange_nslast_ts_exchange_ns
of_get_interval_candle_snapshot returns rolling-window candle state for a caller-supplied window_ns with:
window_nsopenhighlowclosetrade_counttotal_volumevwapfirst_ts_exchange_nslast_ts_exchange_ns
Subscription stream ids:
1:BOOKraw book updates2:TRADESraw trade prints3:ANALYTICSsnapshot callbacks4:SIGNALSsnapshot callbacks5:HEALTHtransition callbacks6:BOOK_SNAPSHOTmaterialized book snapshot callbacks after book changes7:DERIVED_ANALYTICSsession-derived analytics callbacks after trade changes
§C Struct Reference
of_engine_config_t:
instance_id: optional runtime instance id overrideconfig_path: optional.tomlor.jsonruntime config pathlog_level: reserved for host integrationsenable_persistence: non-zero enables persistenceaudit_max_bytes: audit rotation sizeaudit_max_files: audit retention countaudit_redact_tokens_csv: comma-separated audit redaction tokensdata_retention_max_bytes: persistence byte capdata_retention_max_age_secs: persistence age cap in seconds
of_symbol_t:
venue: venue/exchange namesymbol: normalized symbol stringdepth_levels: requested book depth for subscribe calls
of_trade_t:
symbol: embeddedof_symbol_tprice,size: integer-normalized trade valuesaggressor_side: one ofOF_SIDE_BIDorOF_SIDE_ASKsequence: venue sequence or0when unavailablets_exchange_ns,ts_recv_ns: exchange and local timestamps
of_book_t:
symbol: embeddedof_symbol_tside: one ofOF_SIDE_BIDorOF_SIDE_ASKlevel: top-of-book-relative depth indexprice,size: integer-normalized book valuesaction: one ofOF_BOOK_ACTION_UPSERTorOF_BOOK_ACTION_DELETEsequence: venue sequence or0when unavailablets_exchange_ns,ts_recv_ns: exchange and local timestamps
of_external_feed_policy_t:
stale_after_ms: max allowed ingest silence before stale statusenforce_sequence: non-zero enables sequence-gap/out-of-order checks
of_event_t callback envelope:
kind: stream kind idpayload/payload_len: UTF-8 JSON payload bytesschema_id: payload schema id, currently1quality_flags:OF_DQ_*bits associated with the event- timestamps are copied from the underlying event when available
§Function Family Reference
Lifecycle:
of_engine_createof_engine_startof_engine_stopof_engine_destroy
Subscription:
of_subscribeof_unsubscribeof_unsubscribe_symbolof_reset_symbol_session
External ingest and supervision:
of_ingest_tradeof_ingest_bookof_configure_external_feedof_external_set_reconnectingof_external_health_tick
Polling and snapshots:
of_engine_poll_onceof_get_book_snapshotof_get_analytics_snapshotof_get_derived_analytics_snapshotof_get_session_candle_snapshotof_get_interval_candle_snapshotof_get_signal_snapshot
When the runtime backpressure limit is enabled through
OF_RUNTIME_MAX_EVENTS_PER_POLL, of_engine_poll_once returns
OF_ERR_BACKPRESSURE if a poll drains more events than the configured limit.
Metadata and ownership helpers:
of_api_versionof_build_infoof_get_metrics_jsonof_string_free
§Safety Contract
Callers must:
- pass valid non-null pointers for required pointer arguments
- pass UTF-8
char*values where strings are expected - preserve pointer validity for the full duration of each call
- free owned strings returned by the API using
of_string_free
Additional ownership rules:
- snapshot getters that write into caller buffers do not allocate for the caller
- functions returning owned
char*requireof_string_free - callback payload pointers are only valid for the duration of the callback
- opaque
of_engine_t*andof_subscription_t*handles must be destroyed/unsubscribed only through exported API calls
§Minimal C Example
#include "orderflow.h"
int main(void) {
of_engine_t* engine = NULL;
of_engine_config_t cfg = {0};
cfg.instance_id = "demo";
int32_t rc = of_engine_create(&cfg, &engine);
if (rc != OF_OK) return 1;
rc = of_engine_start(engine);
if (rc != OF_OK) {
of_engine_destroy(engine);
return 2;
}
of_engine_stop(engine);
of_engine_destroy(engine);
return 0;
}§Error Semantics
Most functions return int32_t values mapped from of_error_t:
OF_OKfor successOF_ERR_INVALID_ARGfor invalid pointers/inputsOF_ERR_STATEfor lifecycle misuse or invalid runtime stateOF_ERR_IO,OF_ERR_DATA_QUALITY, and other domain-specific failures
§Snapshot and Callback Payload Contracts
of_get_book_snapshot(...)andBOOK_SNAPSHOTcallbacks share the same JSON schemaof_get_derived_analytics_snapshot(...)andDERIVED_ANALYTICScallbacks share the same JSON schemaof_get_session_candle_snapshot(...)andof_get_interval_candle_snapshot(...)are additive snapshot families and do not alter the older analytics/signal contractsinout_lenis both input capacity and output required size; if the buffer is too small, retry with the returned byte count- payload field names are treated as stable once published; new fields are added additively
§Integration Notes
- Treat engine and subscription handles as opaque; do not cast or inspect internals.
- Keep ABI structs initialized (zero-init is recommended before setting fields).
- Prefer explicit timestamps and sequence numbers for external ingest to maximize quality checks.
- Snapshot functions write the required byte length back through
inout_len; if the caller buffer is too small, retry with the returned size. BOOK_SNAPSHOTcallbacks emit the same JSON shape asof_get_book_snapshot(...), but only when book state changes for the subscribed symbol.DERIVED_ANALYTICScallbacks emit the same JSON shape asof_get_derived_analytics_snapshot(...), but only when trade-driven analytics change for the subscribed symbol.
§Real-World Use Cases
§1. Embed the runtime in a C or C++ trading host
Use the lifecycle, subscription, and polling APIs directly from a native host process that already owns process supervision and deployment.
§2. Drive Python or Java bindings from the same native ABI
The Python and Java packages both rely on this ABI, so host-side operators can reason about one native contract instead of three unrelated APIs.
§3. Build a custom host-side event pump
Use callbacks for snapshot/event delivery and poll-driven control for host-side scheduling.
§Detailed Example: Poll And Read Snapshots
#include "orderflow.h"
#include <stdint.h>
#include <stdio.h>
int main(void) {
of_engine_t* engine = NULL;
of_engine_config_t cfg = {0};
cfg.instance_id = "native-demo";
if (of_engine_create(&cfg, &engine) != OF_OK) return 1;
if (of_engine_start(engine) != OF_OK) return 2;
of_symbol_t symbol = {0};
symbol.venue = "SIM";
symbol.symbol = "ESM6";
symbol.depth_levels = 10;
if (of_subscribe(engine, &symbol, OF_STREAM_ANALYTICS, NULL, NULL, NULL) != OF_OK) return 3;
if (of_engine_poll_once(engine, OF_DQ_NONE) != OF_OK) return 4;
char buf[2048];
uint32_t len = (uint32_t)sizeof(buf);
if (of_get_analytics_snapshot(engine, &symbol, buf, &len) == OF_OK) {
printf("analytics: %.*s\n", (int)len, buf);
}
len = (uint32_t)sizeof(buf);
if (of_get_book_snapshot(engine, &symbol, buf, &len) == OF_OK) {
printf("book: %.*s\n", (int)len, buf);
}
of_engine_stop(engine);
of_engine_destroy(engine);
return 0;
}- Prefer explicit timestamps and sequence numbers for external ingest to maximize quality checks.
- Snapshot functions write the required byte length back through
inout_len; if the caller buffer is too small, retry with the returned size. BOOK_SNAPSHOTcallbacks emit the same JSON shape asof_get_book_snapshot(...), but only when book state changes for the subscribed symbol.DERIVED_ANALYTICScallbacks emit the same JSON shape asof_get_derived_analytics_snapshot(...), but only when trade-driven analytics change for the subscribed symbol.
Structs§
- of_
analytics_ config_ t - Analytics configuration passed to
of_engine_set_analytics_config. - of_
book_ t - External order-book payload accepted by
of_ingest_book. - of_
engine - Opaque engine handle.
- of_
engine_ config_ t - Engine configuration passed to
of_engine_create. - of_
event_ t - Event envelope dispatched to subscription callbacks.
- of_
execution_ amend_ request_ t - Execution amend request.
- of_
execution_ cancel_ request_ t - Execution cancel request.
- of_
execution_ command_ report_ t - Concurrent execution command report.
- of_
execution_ concurrent_ config_ t - Concurrent execution worker configuration.
- of_
execution_ concurrent_ engine - Opaque concurrent execution engine handle.
- of_
execution_ engine - Opaque execution engine handle.
- of_
execution_ event_ t - Execution event returned by execution C APIs.
- of_
execution_ health_ t - Execution health snapshot.
- of_
execution_ metrics_ t - Execution metrics snapshot.
- of_
execution_ order_ request_ t - Execution order request.
- of_
execution_ order_ state_ t - Execution order state returned by state query.
- of_
execution_ route_ config_ t - Execution route and risk configuration.
- of_
external_ feed_ policy_ t - External-feed quality policy configured via
of_configure_external_feed. - of_
subscription - Opaque subscription token.
- of_
symbol_ t - Symbol descriptor used by subscription and snapshot functions.
- of_
trade_ t - External trade payload accepted by
of_ingest_trade.
Enums§
- of_
error_ t - Error codes returned by C ABI functions.
Functions§
- of_
api_ version - Returns ABI version (
major << 16 | minorstyle encoding). - of_
build_ info - Returns build/version info as a static NUL-terminated C string.
- of_
compute_ depth_ slope - Computes depth slope for the first
levelsprice levels and writes JSON result. - of_
compute_ lob_ features - Computes LOB feature snapshot from engine book state and caller-provided flow metrics.
- of_
compute_ weighted_ average_ price - Computes weighted average price for an order of
qtyand writes JSON result. - of_
configure_ external_ feed - Configures stale/sequence policy for external ingest mode.
- of_
engine_ create - Creates a runtime engine and stores it in
out_engine. - of_
engine_ destroy - Destroys an engine created by
of_engine_create. - of_
engine_ poll_ once - Polls adapter once and dispatches subscription callbacks.
- of_
engine_ set_ analytics_ config - Override analytics thresholds and buffer sizes at runtime. Pass a pointer to a populated analytics config. Passing NULL resets to defaults.
- of_
engine_ set_ tickbar_ interval - Sets the tickbar aggregation interval for new per-symbol accumulators.
- of_
engine_ start - Starts adapter polling/session for a created engine.
- of_
engine_ stop - Stops adapter polling/session for an engine.
- of_
execution_ amend_ order - Amends an execution order.
- of_
execution_ api_ version - Returns execution ABI version (
major << 16 | minorstyle encoding). - of_
execution_ cancel_ order - Cancels an execution order.
- of_
execution_ concurrent_ amend_ order - Sends a non-blocking amend command to a concurrent execution worker.
- of_
execution_ concurrent_ cancel_ order - Sends a non-blocking cancel command to a concurrent execution worker.
- of_
execution_ concurrent_ engine_ create_ multi - Creates and starts a concurrent simulated execution engine.
- of_
execution_ concurrent_ engine_ destroy - Destroys a concurrent execution engine.
- of_
execution_ concurrent_ poll - Sends a non-blocking poll command to a concurrent execution worker.
- of_
execution_ concurrent_ stop - Requests graceful concurrent execution worker stop.
- of_
execution_ concurrent_ submit_ order - Sends a non-blocking submit command to a concurrent execution worker.
- of_
execution_ concurrent_ try_ recv_ report - Attempts to receive one concurrent command report without blocking.
- of_
execution_ engine_ create - Creates a simulated execution engine and stores it in
out_engine. - of_
execution_ engine_ create_ multi - Creates a simulated execution engine from multiple route configs.
- of_
execution_ engine_ destroy - Destroys an execution engine.
- of_
execution_ engine_ start - Starts an execution engine.
- of_
execution_ engine_ stop - Stops an execution engine.
- of_
execution_ get_ order_ state - Gets current order state for a client order id.
- of_
execution_ health - Gets execution health.
- of_
execution_ metrics - Gets execution metrics.
- of_
execution_ poll - Polls execution events.
- of_
execution_ submit_ order - Submits an execution order.
- of_
external_ health_ tick - Re-evaluates external feed health without ingesting new events.
- of_
external_ set_ reconnecting - Marks external feed reconnecting state.
- of_
get_ acd_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ agent_ type_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ almgren_ chriss_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ amihud_ snapshot - Writes Amihud illiquidity snapshot JSON.
- of_
get_ analytics_ snapshot - Writes current analytics snapshot JSON into caller buffer.
- of_
get_ bar_ series - Writes completed bar series JSON array into caller buffer.
- of_
get_ book_ analytics_ snapshot - Writes current book analytics snapshot JSON into caller buffer.
- of_
get_ book_ event_ analytics - Writes book-event analytics snapshot JSON over
window_ns. - of_
get_ book_ snapshot - Writes current book snapshot JSON into caller buffer.
- of_
get_ cvd_ enhancement_ snapshot - Writes CVD enhancement snapshot JSON.
- of_
get_ dark_ lit_ correlation_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ dark_ pool_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ derived_ analytics_ snapshot - Writes current derived analytics snapshot JSON into caller buffer.
- of_
get_ effective_ spread_ bps - Writes last effective spread in bps as JSON:
{"bps": N}, or{}. - of_
get_ futures_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ half_ spread_ cost_ bps - Writes average half-spread cost over
windowtrades:{"bps": N}. - of_
get_ hasbrouck_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ institutional_ flow_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ interval_ candle_ snapshot - Writes rolling interval candle snapshot JSON into caller buffer.
- of_
get_ kinetic_ energy_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ kyle_ lambda_ snapshot - Writes Kyle’s Lambda snapshot JSON.
- of_
get_ metrics_ json - Allocates and returns metrics JSON (
*out) plus byte length (*out_len). - of_
get_ mid_ price - Writes mid price as JSON:
{"mid": N}, or{}if no book data. - of_
get_ noise_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ oi_ analysis_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ options_ flow_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ pattern_ snapshot - Writes pattern detection snapshot JSON into caller buffer.
- of_
get_ realised_ spread_ bps - Writes realised spread over
hold_ticksticks ago:{"bps": N}. - of_
get_ regime_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ resiliency_ snapshot - Writes resiliency snapshot JSON.
- of_
get_ session_ candle_ snapshot - Writes current session candle snapshot JSON into caller buffer.
- of_
get_ signal_ snapshot - Writes current signal snapshot JSON into caller buffer.
- of_
get_ spread_ decomp_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ vol_ signature_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ volatility_ snapshot - Writes an analytics snapshot JSON payload into the caller-provided buffer.
- of_
get_ vpin_ snapshot - Writes VPIN snapshot JSON.
- of_
ingest_ book - Injects one external book event into runtime processing.
- of_
ingest_ trade - Injects one external trade event into runtime processing.
- of_
reset_ symbol_ session - Resets per-symbol analytics session state.
- of_
string_ free - Frees a C string returned by this library.
- of_
subscribe - Subscribes to a symbol stream and returns a subscription token.
- of_
unsubscribe - Unsubscribes and destroys a subscription token.
- of_
unsubscribe_ symbol - Unsubscribes all active streams for a symbol on this engine.
Type Aliases§
- of_
event_ cb - C callback signature for subscription delivery.