Skip to content

behaviour Specification

Purpose

The behaviour layer models every stateful part of the trading loop (strategies, indicators, executors) as an explicit-state process, and defines how such a process becomes a worker. It is language-agnostic; the .NET reference implementation is Virtufin.Core.Behavior in the lib repo, and the process-to-worker translation is Virtufin.Behavior.DevKit in the worker-devkit repo.

Related specs: - Scenarios -- the strategy triplet leg names which strategy code runs; this spec defines what shape that code has. - Worker Management -- the worker contract (IWorker) that the Worker Translation requirement targets. - Pub/Sub Topics -- the common envelope and derived-event time rule every worker output carries.

Requirements

Requirement: Process Coalgebra

Every stateful component of the trading loop SHALL be modelled as an explicit-state process (coalgebra) with the shape (State, Input) → (State, Output) and a designated initial state.

Scenario: Explicit initial state

  • WHEN a process is defined
  • THEN it SHALL expose its initial state as a designated value
  • AND hidden state (indicator values, model weights, cooldown timers) SHALL be exposed as an explicit parameter and return value, not captured in closures

Scenario: Step threading

  • WHEN a process steps on input i from state s producing (s', o)
  • THEN the next step SHALL accept s' as its state argument
  • AND s' SHALL be the only way state evolves — there SHALL be no separate mutation channel

Requirement: Decide Morphism

The strategy's decide function SHALL be a process specialised to the trading domain: strategy state paired with a market observation and a portfolio state, producing the next strategy state and zero or more trade actions.

Scenario: Domain universes

  • WHEN a decide process is defined
  • THEN its state SHALL belong to the strategy-state universe, its market input to the market-observation universe (covering both raw feed events and derived signals), its portfolio input to the portfolio-state universe, and its actions to the trade-action universe

Scenario: Zero or more actions

  • WHEN decide steps on an observation that warrants no trade
  • THEN it SHALL emit an empty collection of actions
  • WHEN decide steps on an observation that warrants multiple simultaneous intents
  • THEN it SHALL emit all of them as one collection

Scenario: State is not part of the input pair

  • WHEN a decide process is driven over a stream of observations
  • THEN the strategy state SHALL be threaded by the driver as a separate accumulator
  • AND the stream element SHALL consist of the environment inputs (market observation, portfolio state) only — callers SHALL NOT supply strategy state per element

Requirement: Execute Pairing

decide SHALL pair with an executor of the same coalgebra shape — (ExecutionState, Action) → (ExecutionState, Event) — to form the trading loop; fills produced by the executor feed back into the portfolio state observed by the next decide step.

Scenario: Loop composition

  • WHEN decide emits a trade action and the executor produces the corresponding outcome event
  • THEN the outcome SHALL fold into the portfolio state that decide observes on its next step
  • AND the composed system SHALL be corecursive: the portfolio input of decide is an output of the loop

Requirement: Derived Portfolio State

The portfolio state observed by decide SHALL be a value derived by folding position events with an algebra (State, Event) → State; strategies observe the folded state, not the raw event stream.

Scenario: Folding position events

  • WHEN position events (opens, updates, closes, flips) occur
  • THEN the portfolio state SHALL be the fold of those events from an empty initial state
  • AND the same event sequence SHALL always yield the same portfolio state

Scenario: Holdings net of base-asset fees

  • WHEN a strategy folds a fill of its own order whose fees include the instrument's base asset
  • THEN that amount SHALL come off the holdings, once per fill_id, whichever of order.filled and the order's end event arrives first
  • AND a fee in another asset SHALL leave holdings unchanged unless the fold tracks that asset
  • AND when the fee is unknown the strategy SHALL report status degraded naming the symbol, keep it across activations, and clear it when an absolute position event sets the symbol

Requirement: Decision State Across Activations

A strategy worker SHALL decide after a move or a crash as it would have without one: its decision state SHALL survive the activation, and it SHALL never trade on holdings it does not know.

Scenario: Holdings come from the portfolio

  • WHEN a strategy decides whether it is long or flat
  • THEN it SHALL decide on the folded portfolio (holdings plus its own submitted, unfilled orders), not on a flag of its own
  • AND a fill of one of its own orders (sc.<scenarioId>.trading.order.filled, subject order/<order_id>) SHALL fold into its holdings once per fill id, and a canceled, expired or rejected order SHALL stop being pending

Scenario: Decision state saved and restored

  • WHEN the strategy's decision state changes (its window, holdings, pending orders)
  • THEN the worker SHALL save it as one versioned JSON record in the worker's own state store before the input finishes, an order before it is published, unless the strategy opts into batching (bounded by an interval, settled on stop)
  • AND the next activation SHALL restore it before its first input, and SHALL skip a replayed input the record already contains

Scenario: Only the owning activation writes

  • WHEN a new activation starts
  • THEN it SHALL claim the record (an etag-guarded save stamped with its activation id)
  • AND an older activation SHALL NOT overwrite a record it no longer owns, and SHALL publish no order whose state it could not save

Scenario: Unknown position

  • WHEN the saved record is unreadable, of another format or version, or the store cannot be read at start
  • THEN the worker SHALL start empty, report the status degraded with the reason and not crash
  • AND it SHALL withhold every order for a symbol until an absolute position event sets that symbol's holdings

Scenario: Unanswered order

  • WHEN a pending order has had no executor response (accepted, amended, a fill, canceled, expired, rejected) for longer than the order timeout (config ordertimeoutseconds, default 300), because its publish was dropped when the lease was lost in that step or the executor reported its failure only on its error topic
  • THEN the order's symbol SHALL count as unknown: the worker SHALL withhold every order for it and report the status degraded naming the order
  • AND it SHALL NOT submit the order again; a late response, or an absolute position event (which drops the unanswered order), SHALL make the symbol known again
  • AND every pending order in the saved record SHALL carry its submit time and whether an executor answered it

Scenario: Declared symbols

  • WHEN a strategy's config sets symbols (comma-separated canonical pairs)
  • THEN the worker SHALL publish orders only for those symbols, withhold any other and report the status degraded naming it
  • AND a symbols that names none SHALL fail the worker's start

Scenario: Strategy and run ids from config

  • WHEN a strategy's config sets strategyid (the orders' strategy_id) or runid
  • THEN each SHALL be a GUID, and a value that is not one SHALL fail the worker's start with an error naming the key, instead of the worker using its own instance id
  • AND when unset, the worker SHALL use its own instance ids, kept in the decision state across activations

Requirement: Automatic Position Recovery

A strategy degraded with its position or fee unknown MAY be recovered without an operator by a reconciliation worker that publishes the venue's holding as an absolute position event, under option A: automatic only when the strategy is the sole strategy trading that symbol's asset on that account. Publishing a position event is not acting on a venue: such a worker SHALL hold no venue credential and SHALL NOT place, amend or cancel orders. Every case below that cannot be established SHALL end in no event: a wrong absolute event makes a live strategy trade on wrong holdings.

Scenario: Live position status

  • WHEN a strategy worker receives the command positionstatus (InvokeWorkerCommand)
  • THEN it SHALL answer, in order with its inbox and without a step or a save, its decision-state owner (owned, unavailable, fenced, nostore), the known symbols (null: all), the symbols unanswered, fee-unknown and with an order working, the last order or fill per symbol, the activation's start and the holdings of its fold (null: none to read)
  • AND a reconciliation worker SHALL decide on this answer, never on a lifecycle status event or its detail, which are sent once per change and may be missed; a strategy that does not answer SHALL count as unreadable

Scenario: Establishing exclusivity

  • WHEN a reconciliation worker decides for an account
  • THEN it SHALL classify every worker ListWorkers returns, in any state: a worker bound to an order.submitted topic is an executor, a venue order-update translator recognised by its package from the org feed (it places no order and holds no order key) is neither, any other worker of a scenario is a trader, and a scenario is on the account only when every executor of it references the account's API key (worker-secret references, never values), off it only when every executor references another key, and undetermined otherwise
  • AND a symbol SHALL be exclusive only if no other trader of a scenario not off the account, and none of the strategy's own other symbols, trades that symbol's base asset as a base or a quote, every such trader declaring symbols
  • AND an asset fees may be paid in SHALL be exclusive only when nothing else trades
  • AND the workers SHALL be listed again after the statuses are read; a change SHALL void the pass

Scenario: Recovering a strategy

  • WHEN a strategy is degraded for a symbol, the symbol is exclusive, the strategy owns its decision state and binds the event's topic, and an account snapshot of the strategy's portfolio world lists the asset
  • AND the snapshot is recent, began after the strategy's activation and its last order or fill on the symbol, and neither the venue nor the strategy has an order working on the asset
  • AND the holding is at or below the strategy's last known holding of the symbol
  • THEN the worker SHALL publish the holding (Recovery event, pubsub-topics spec) once, wait a cooldown before another, and give up with an alert after a bounded number of attempts

Scenario: A recovery never raises a holding

  • WHEN the venue holds more of the asset than the strategy last knew, or the strategy has no last known holding of the symbol, a lost or unreadable record included
  • THEN the worker SHALL NOT publish, even for a flat venue, because a balance cannot say whose coins it holds
  • AND recovery SHALL be left to an operator, whose absolute position event carries no asof

Scenario: Not recovering a strategy

  • WHEN a symbol is shared, exclusivity cannot be established, a read fails, or any condition above does not hold for a degraded strategy
  • THEN the worker SHALL NOT publish, the strategy SHALL stay degraded, and the worker SHALL report the status degraded with the reason and publish an error event, once per change of the reasons
  • AND it SHALL publish nothing for a strategy that is not degraded for the symbol, nor for a symbol the venue does not list

Scenario: A strategy guards the fold

  • WHEN a strategy receives a position event with the asof extension
  • THEN it SHALL fold it only if the event is absolute, the strategy is degraded for the symbol, no order of it on the symbol is working, and asof is after the activation's start and the symbol's last order or fill, and the event's holding is at most the strategy's last known holding
  • AND otherwise it SHALL drop the event with a warning and stay degraded

Requirement: Trading Halt

A scenario's trading SHALL be haltable by the state entry sc.<scenarioId>.trading.halt, JSON { halted, reason, by, at } (Trading.Contracts TradingHaltJson); absent means not halted, and an entry that is not such an object SHALL count as halted. It is not the scenario's lifecycle status and gates no publish (No Topic or Scenario-State Validation): the strategies and executors read it and decide.

  • A strategy (StrategyWorkerBase) SHALL read its scenario's halt at most every haltcheckseconds (config, default 1 s) while inputs arrive and, while halted, SHALL withhold every order before it becomes pending (its position stays known), SHALL still fold every input, and SHALL report status halted with the reason. A halt it cannot read SHALL keep the last one known.
  • An executor (ExecutorWorkerBase, C#) SHALL read the order's scenario halt before executing it and SHALL reject a halted scenario's order, or one whose halt cannot be read (order.rejected, reject_source = risk, reason trading halted: ...).
  • An executor SHALL answer the worker command cancel-all by cancelling the open orders the platform placed at its venue, never others on the account (LiveExecutor: client order id vf-...), SHALL publish order.canceled (canceled_by = user) for those it executed, and SHALL answer { command, ok, canceled, failed, unannounced }. An executor with nothing resting answers an empty list.

Scenario: A halted scenario places nothing

  • WHEN sc.LIVE.trading.halt says halted: true and a strategy of LIVE decides to buy
  • THEN no order.submitted SHALL be published, nothing SHALL become pending, the status SHALL be halted
  • AND an order.submitted that reaches an executor anyway SHALL be rejected with source risk

Scenario: Resume

  • WHEN the entry says halted: false or is deleted
  • THEN the strategy's next decision SHALL trade again, within haltcheckseconds

Scenario: Cancel all

  • WHEN LiveExecutor gets cancel-all while the account has the platform's order vf-<id> and a manual order open
  • THEN it SHALL cancel vf-<id> only, and answer it in canceled

Requirement: Scan Driver

A driver SHALL exist that folds any process over an ordered stream of inputs, emitting the pair of evolved state and output for every input.

Scenario: Per-element emission

  • WHEN a process is run over a stream of n inputs
  • THEN the driver SHALL emit exactly n (state, output) pairs, in input order

Scenario: Fresh state per subscription

  • WHEN the driver is subscribed to the same cold input stream twice
  • THEN each subscription SHALL fold from the process's initial state independently

Scenario: Checkpoint restart

  • WHEN the driver is started with an explicit checkpoint state instead of the initial state
  • THEN folding SHALL resume from the checkpoint as though prior inputs had already been applied

Scenario: Opt-in reactivity

  • WHEN a process is consumed synchronously (tests, batch backtests)
  • THEN the coalgebra SHALL remain callable directly, step by step, without the stream driver

Requirement: Worker Translation

A process SHALL be deployable as a worker through one generic translation layer, so every process kind (strategies, indicators, executors) uses the same input, validation, output and envelope rules rather than a per-kind bridge.

Scenario: Decoding or skipping input

  • WHEN a worker hosting a process receives a CloudEvent
  • THEN the translation layer SHALL decode it to the process's input, or skip it without stepping when the event is not one the process consumes
  • AND a skipped event SHALL change no state and produce no output

Scenario: Configuration validated before stepping

  • WHEN a CloudEvent lacks configuration the process requires (for example scenarioid)
  • THEN the worker SHALL reply with an error naming the missing key
  • AND it SHALL do so before stepping: the process state SHALL be unchanged and no side effect (such as placing an order) SHALL occur

Scenario: Zero or more outputs per step

  • WHEN one step yields n outputs (for example decide emitting several trade actions)
  • THEN the worker SHALL return n CloudEvents, in output order, each routed by its own topic
  • AND n = 0 SHALL publish nothing

Scenario: Common envelope on every output

  • WHEN the worker builds an output CloudEvent
  • THEN it SHALL carry the input's common envelope extensions and the derived-event time rule of the pubsub-topics spec's Common Envelope Extensions requirement
  • AND every output SHALL get its own CloudEvent id

Requirement: Glossary

The platform SHALL use the terms Event, Signal, Indicator, Process state and Market data with one meaning each, so specs, code and docs classify every value the same way. The event catalog lists everything implemented today under these terms.

Scenario: Event

  • WHEN something is an immutable fact with a time
  • THEN it SHALL be an event, and events SHALL be the only thing that travels on topics

Scenario: Signal

  • WHEN a value is folded from events ((State, Event) → State), such as an order book or a portfolio state
  • THEN it SHALL be a signal: state that never travels itself
  • AND a worker that owns a signal MAY publish an event announcing that it changed

Scenario: Indicator

  • WHEN a signal folds samples through the fixed indicator interface (Add(sample), Value), such as a moving average
  • THEN it SHALL be an indicator, and its published changed events SHALL be events about that signal

Scenario: Process state

  • WHEN a process threads state between steps (Process Coalgebra requirement)
  • THEN that state SHALL be process state, and it SHALL NOT travel

Scenario: Market data

  • WHEN a value is a fact about one market stream, raw or derived with no tuning choice (trades, book updates, the order book, candles at a venue's standard intervals, mid, spread)
  • THEN it SHALL be market data: world-scoped, identical for every consumer of that market

Scenario: Classifying a derived value

  • WHEN a value is derived from market data
  • THEN it SHALL be market data if every consumer would derive the identical value (no tuning parameter beyond the venue's own standard intervals)
  • AND it SHALL be an indicator, scenario-scoped, if it depends on a parameter a strategy or scenario chooses (a window length, a lag, a decay, a model): SMA(n), log return over a chosen lag, entropy, volatility estimates

Scenario: Topic follows the classification

  • WHEN market data is published
  • THEN it SHALL use the world-scoped market-data topics (act|hyp.<name>.exchange.<venue>.*) of the pubsub-topics spec
  • WHEN an indicator value is published
  • THEN it SHALL use the scenario-scoped indicator topics (sc.<scenarioId>.indicator.*) of the pubsub-topics spec's Indicator Events requirement

Scenario: A candle is market data

  • WHEN trades are aggregated into a candle over a venue's standard interval (1m, 1h, 1d, ...)
  • THEN the candle SHALL be market data, whatever the interval
  • AND a moving average over those candles SHALL be an indicator, because its window is a strategy's choice

Scenario: The order book is a signal published as market data

  • WHEN a worker folds order-book snapshots and deltas into a book
  • THEN the book SHALL be a signal kept in State, not an event
  • AND the worker's orderbook.changed notifications SHALL be market-data events about that signal