Bridge
StrategyWorkerBase<TS, TM, TP, TA> is the bridge between the pure
IDecide coalgebra and the WorkManager's worker contract
(IWorker.ProcessAsync(CloudEvent input, IWorkerContext context)).
Topic binding
A strategy needs both market and position events. Bind with two
explicit topics at CreateWorker (CreateWorkerRequest.topics; see
workmanager's multi-topic worker support) -- e.g. the
scenario's market-data feed and its position feed. Do not bind with
a wildcard: the deployed Dapr pubsub component is pubsub.redis
(Redis Streams), which has no wildcard subscription support -- a
worker bound to sc.<scenarioId>.> (a pattern this doc used to
recommend) subscribes to a Redis Stream literally named
"sc.<scenarioId>.>", which nothing is ever published to. Both topics
arrive on the one worker and are separated by CloudEvent type.
Dispatch
flowchart TD
E[CloudEvent] --> T{type?}
T -->|com.virtufin.position.*| POS[PortfolioAlgebra.Apply<br/>fold holdings]
POS --> N1[no response]
T -->|candle.closed or virtufin.market.*| M{is TMarket?}
M -->|no| N2[skipped]
M -->|yes| STEP["Decide.Step(state, (market, portfolio))"]
STEP --> ENC["ToOrderRequest"]
ENC --> RESP["Order submitted CloudEvent"]
T -->|other| N3[ignored]
- Position events are the feedback edge: fills fold into the portfolio, so the next decision sees updated holdings. No response is emitted.
- Market events step the strategy; every emitted action becomes one
pubsub-topics "Order submitted" event (see
ToOrderRequest), in action order. Several actions in one step publish several events (IWorker.ProcessAsyncreturns every output).scenarioidis checked before the strategy steps, so a missing one leaves the state untouched. - Shared layer:
StrategyWorkerBaseis built onBehaviorWorkerBasefromVirtufin.Behavior.DevKit(worker-devkit) -- the strategy and its portfolio fold are composed withdecide.WithPortfolio(algebra)and bound to CloudEvents. Order events carry the domain envelope (DomainEnvelope.Stamp, domain-devkit) and inherit the triggering market event'seventtime(pubsub-topics "Envelope on a derived event"). TMarketfiltering: choosingRichMarketEventasTMarketaccepts derived signals (candles, VWAP, volatility) but skips rawMarketEventticks — a deliberate type-level filter.
Response routing
Unlike a typical WorkerBase worker (which publishes on output.Type,
overridable per message via replytopic), the trading envelope keeps
ce-type fixed at com.virtufin.trading.order.submitted regardless of
replytopic -- it's a stable identifier per the pubsub-topics spec,
independent of the per-scenario topic. Routing instead goes through
WorkerBase.PublishTopicAttribute (publishtopic), set by
BuildEnvelope to sc.<scenarioid>.trading.order.submitted, which the
virtufin.trading/order entity of the naming library derives (see
Naming, the fragment Virtufin.Trading.Contracts ships); the
WorkManager reads that extension to pick the publish topic and strips
it before publish, so subscribers never see it (see
workmanager's WorkManager.PublishOutputAsync).
State
Strategy state and portfolio state live in worker instance fields — the engine keeps one worker object alive for the instance's lifetime, so state threads across deliveries — and, since 0.20.0, in the worker's state store across activations (see Redelivery). State is the driver's accumulator, never part of the input pair (see the behaviour spec's "State is not part of the input pair" requirement).
Redelivery
Inputs arrive at least once since WorkManager 0.38.0: after a hard crash the
events of the last cursor window (≤250 ms) come again
(Inputs across a move). StrategyWorkerBase folds each position
event once: BehaviorWorkerBase drops a repeated event (input-id deduplication,
Inputs can arrive twice), and a delta position event
(updated-attributed, add semantics) whose fillId the instance already
folded is dropped whatever its event id (the last 100 000 fills). Absolute
position events (opened, updated, flipped, closed: set semantics) are
idempotent. A repeated market event is dropped the same way, so a strategy
never decides twice on one candle.
Order ids (0.19.1) are derived from the decision's trigger: the
ChosenOrderId of the action when the strategy set one, else
DerivedId(input, com.virtufin.trading.order.submitted, sc.<scenarioid>.trading.order.submitted, null, n)
for the n-th action of the step (BehaviorWorkerBase.DerivedId, worker-devkit
0.42.0: the algorithm of every derived event id, scoped to the worker id). So
the order event's subject and id are stable too. The Python strategy
(MovingAverageCrossoverPython 0.5.5) derives its order ids with the same
algorithm (WorkerBase.derived_id). A moved strategy that replays an input and
decides the same submits the same order id, and the executor drops it
(Simulated/Shadow executors by order id, LiveExecutor by its Binance client
order id).
Decision state (0.20.0). Derived ids cover the same decision repeated, not a different decision from reset state. So the base keeps the decision state across activations (Decision state):
- holdings come from the portfolio fold (position events plus the fills of the
strategy's own orders), and
PortfolioState.Exposureadds its unfilled orders, so a strategy never keeps a "long" flag that resets; - one versioned JSON record (
ctx.Statekeydecision) holds the strategy's declared state (EncodeDecisionState), the holdings, the pending orders and the recent fill and input ids; it is saved before the input finishes, an order before it is published, and restored inStartAsync; - the activation claims the record at start (etag-guarded, activation id), so an older activation that still runs is fenced and writes nothing;
- an unreadable or old record, or a store unreadable at start: empty start,
status
degraded(position unknown), orders withheld per symbol until an absolute position event sets it.
Replayed inputs after the move are skipped when the record already contains
them, and fold normally otherwise; the moved strategy decides as the
uninterrupted one would. Tests: DecisionStateTests (a long strategy
restarted does not buy again; crashes at several points give the uninterrupted
run's orders, ids included; unknown position; batching; the fence).
Unanswered orders (0.21.0). An order the old activation recorded as
pending but whose publish the host dropped (the lease lost during that very
step), or one an executor failed on and reported only on its error topic, gets
no executor response at all. Each pending order carries its submit time and
whether an executor answered it (accepted, amended, a fill; a canceled,
expired or rejected order is dropped). One that is still unanswered after
ordertimeoutseconds (config, default 300) makes its symbol's position
unknown: every order for the symbol is withheld and the status is degraded
(no executor response to order(s) ... : position unknown for ..., orders
withheld). The order is never submitted again: a second order for the same
signal could double the position if the first one did reach the venue. It
resolves when the executor answers after all (a late fill counts) or when an
absolute position event sets the holdings, which drops the unanswered order.
Tests: PendingOrderTests.
Config
Config is extension-only. ConfigResolution reads CloudEvent extension
attributes (where the WorkManager stamps CreateWorkerRequest.config);
payload fields are never consulted as config.
Config keys are lower-case letters and digits: the Runtime stamps config on
each input as CloudEvent attributes, and the CloudEvents SDK refuses any other
name (WorkManager 0.38.3 refuses such a key at CreateWorker). The strategy id
key is strategyid (StrategyIdKey, 0.21.0; strategy_id never reached a
worker). strategyid and runid are GUIDs, and ordertimeoutseconds a
positive integer: another value fails StartAsync, naming the key, instead of
the worker silently falling back to its own id.
Unset, both default to the worker's own id (0.22.0): a GUID derived from
the worker id, the same value on every activation and pod. Before, each
instance minted a random GUID, so a moved strategy stamped a new
strategy_id on its orders and split one strategy's attribution across ids.
The worker id is a GUID in the Runtime, so the default is that id; a local
host's or a notebook's id is hashed deterministically to one. A persisted
decision-state record still wins: an existing worker keeps the id its orders
already carry.
Binary payloads
A binding's decoder normally receives the event's JSON payload. For a payload
that is not JSON — an order book image, a FlatBuffers sample — construct the
worker with LenientJsonCodec (BehaviorWorkerBase(workerType,
codec)): such an event decodes to an empty object and the decoder reads
CloudEvent.Data (bytes) from the event it is given. Workers that do not opt in
keep the strict codec, where a non-JSON payload is an error.