Strategy Author Guide
Build a strategy worker in three steps: implement IDecide, subclass
StrategyWorkerBase, and wire per-instance config.
1. Implement IDecide
Your strategy is a pure coalgebra — no CloudEvents, no Rx, no I/O. The
hidden state is an explicit record; Step is a pure function.
using Virtufin.Core.Events.Trade;
using Virtufin.Strategy.DevKit;
using Virtufin.Worker.DevKit; // ConfigResolution
public sealed record RsiState(decimal AvgGain, decimal AvgLoss) : IStrategyState;
public sealed class RsiStrategy : IDecide<RsiState, RichMarketEvent, PortfolioState, TradeAction>
{
public RsiState Initial => new(0m, 0m);
public (RsiState, TradeAction[]) Step(RsiState state, (RichMarketEvent, PortfolioState) input)
{
var (market, portfolio) = input;
if (market is not RichMarketEvent.CandleClosed candle)
{
return (state, []); // only candle closes move this strategy
}
// ... compute RSI, consult portfolio.Exposure(candle.Symbol) ...
var next = state;
var actions = new TradeAction[] { /* BuyOrder / SellOrder */ };
return (next, actions);
}
}
Constraints enforce the domain: TMarket : IMarketEvent,
TPortfolio : IPortfolioState, TAction : ITradeAction. Emitting zero
actions is normal (a no-op step).
2. Subclass StrategyWorkerBase
public sealed class RsiWorker : StrategyWorkerBase<RsiState, RichMarketEvent, PortfolioState, TradeAction>
{
public RsiWorker() : base(
"rsi", // worker type: source urn:com.virtufin:worker:rsi, errors com.virtufin.rsi.error on wrk.rsi.error
new RsiStrategy(),
new PortfolioAlgebra())
{
}
protected override OrderRequest ToOrderRequest(CloudEvent input, TradeAction action)
=> action switch
{
TradeAction.BuyOrder buy => new OrderRequest(
buy.OrderId ?? Guid.NewGuid(), buy.Symbol.Value, "buy",
buy.LimitPrice is null ? "market" : "limit", buy.Quantity, buy.LimitPrice,
ConfigResolution.ResolveString(input, "venue", "binance-spot")),
TradeAction.SellOrder sell => new OrderRequest(
sell.OrderId ?? Guid.NewGuid(), sell.Symbol.Value, "sell",
sell.LimitPrice is null ? "market" : "limit", sell.Quantity, sell.LimitPrice,
ConfigResolution.ResolveString(input, "venue", "binance-spot")),
_ => throw new ArgumentOutOfRangeException(nameof(action), action.GetType(),
"RsiStrategy only emits Buy/Sell orders."),
};
}
The base class:
- folds
com.virtufin.position.*events into the portfolio (no response), - steps market events (published candles,
com.virtufin.exchange.<venue>.candle.closed, and thevirtufin.market.*ADT contract) throughStep, - skips market events whose mapped type does not fit
TMarket, - publishes one emitted action as the pubsub-topics spec's "Order
submitted" event, named by the naming library: topic
sc.<scenarioid>.trading.order.submitted,ce-type = com.virtufin.trading.order.submitted,ce-subject = order/<order_id>, payload{"order_id":...,"symbol":...,"side":..., "type":...,"qty":...,"price":...,"venue":...,"submitted_at":...}.scenarioidconfig is required;runid/clocktype/the world triplet default sensibly for a live worker (seeStrategyWorkerBase.ScenarioIdKeyand its siblings).runidandstrategyid(the order'sstrategy_id) are GUIDs; a config value that is not one fails the start. A strategy may emit several actions per step; each becomes its own "Order submitted" event, published in order (WorkManager 0.18.0+).
Override OnMarketEvent to react to config changes (e.g. re-window an
indicator) before each step.
Order ids
Leave the order id to the base: emit OrderId: null. The base derives it from
the decision's trigger (0.19.1): a version 5 UUID of the worker id, the
triggering event's source and id, the order event's type and topic and the
order's position among the actions of that step. Whatever ToOrderRequest
returns as OrderId (buy.OrderId ?? Guid.NewGuid() above) is replaced by it.
Why: inputs arrive at least once (WorkManager 0.38+), and a strategy that moves
to another pod starts with empty state and replays the inputs of its last
cursor window. Deciding the same on the same input it submits the same
order id, so the executor drops it as an order it already has (LiveExecutor
places every order under the Binance client order id vf-<order id> and looks
it up first). A random id would be a new real order.
An id the strategy chooses itself (OrderId: someGuid) is kept; then it must
be just as deterministic (derived from the input, never Guid.NewGuid() in
Step). For an action type of your own that carries an id, override
ChosenOrderId(action).
The ids only help when the moved strategy decides the same. That is what its decision state is for (next section).
Decision state
A worker can move to another pod or crash at any time, and its next activation is a fresh object. It decides the same as the old one only if it starts from the same state. Since 0.20.0 the base keeps that state for you:
- Holdings come from the portfolio. Decide long or flat on
portfolio.Exposure(symbol): the folded holdings (Quantity) plus your own orders that are submitted but not yet filled (Pending). Never keep a "long" flag of your own: after a move it would be wrong, and between an order and its fill it would double the order. The base folds a fill of one of your own orders (sc.<scenarioid>.trading.order.filled, subjectorder/<order_id>) into the holdings once perfill_id, and drops a canceled, expired or rejected order fromPending. A canceled or expired order that executed part of its quantity carriesqty_filledandfill_iditself, so the executed part folds once whichever of the two events arrives first (inputs are ordered only within a topic). Bind the fills topic next to the market and position topics (and the order'saccepted,canceled,expiredandrejectedtopics when your executor publishes them). - Holdings are net of base-asset fees. A fill's
feesstate what the venue charged per asset ({"BTC":0.001}), and the part in the instrument's base asset comes off the holdings, once perfill_id, soQuantitymatches the account: a buy of 1 BTC paying 0.001 BTC holds 0.999. A fee in another asset (the quote, or BNB) leaves the holdings alone: the fold keeps no cash. Sell what you hold, not what you ordered. When a fill's fee is unknown (feesis null: the venue translator missed a trade, or its state failed) the holdings cannot be corrected: the worker reports statusdegradedwithfee unknown for <symbols>, and logs it, until an absolute position event sets the symbol. It keeps trading; a fee is small next to stopping a strategy, and the status survives a restart. - Declare what else the decision depends on. Override
EncodeDecisionState(state)andDecodeDecisionState(json)for your indicator window, latches and guards (JSON only; the State API stores JSON). RaiseDecisionStateVersionwhen the layout changes. Without them your strategy state restarts fromInitial(the holdings are still kept).
protected override JsonNode? EncodeDecisionState(RsiState s) => new JsonObject
{
["avgGain"] = s.AvgGain, ["avgLoss"] = s.AvgLoss,
};
protected override RsiState? DecodeDecisionState(JsonNode saved)
=> new(saved["avgGain"]!.GetValue<decimal>(), saved["avgLoss"]!.GetValue<decimal>());
The base saves one JSON record under the worker's own state key decision
(ctx.State, sys.workmanager.worker.<id>.state.decision, deleted with the
worker): the format and version, your state, the holdings and known symbols,
the pending orders, the newest 1 024 fill ids, the ids of the last 256 inputs,
and the strategy and run ids. It is saved before the input finishes when it
changed, so an order is published only after the state that made it is saved
(a failed save withholds the order and reports degraded). It is restored in
StartAsync, before the first input; a replayed input that the record already
contains is skipped. WorkManager replays the inputs after its cursor, so
the moved strategy resumes where it stopped.
Batching. Override DecisionStateSaveInterval (default zero) for a
strategy on a fast feed: then a change without an order or fill waits at most
that long (a trailing save writes the last one, StopAsync settles it). The
cost: the Runtime saves its input cursor on its own schedule, so a hard crash
can lose the window changes of the last interval, inputs the cursor has
already passed.
Ownership. The activation claims the record at start (an etag-guarded save
stamped with its activation id) and reads each later save back. An older
activation that has not yet noticed it lost the worker cannot overwrite it: it
is fenced, publishes no further order and reports degraded.
Unknown position. A record that does not parse, or has another format or
version, or a store that cannot be read at start: the strategy starts empty,
reports degraded (position unknown), and the base withholds every order for
a symbol until an absolute position event (opened, updated, flipped,
closed) sets it. It never crashes on a bad record. To recover, publish an
absolute position event for the symbol, or delete and recreate the worker.
Unanswered orders (0.21.0). An order no executor answers (its publish was
dropped when the lease was lost in that step, or the executor reported its
failure only on its error topic) would otherwise stay in Pending for ever.
After ordertimeoutseconds (config, default 300 s) without any response
(accepted, amended, a fill, canceled, expired, rejected) its symbol's
position is unknown: orders for it are withheld and the status is degraded,
until the executor answers after all or an absolute position event sets the
holdings (which drops the order). The order is never submitted again.
Trading halt (0.25.0). An operator halts a scenario's trading (the TUI's kill
switch) by saving sc.<scenarioid>.trading.halt = { "halted": true, "reason", "by",
"at" } (TradingHaltJson, Virtufin.Trading.Contracts). The base reads it at most every
haltcheckseconds (config, default 1 s) while inputs arrive. While halted, every order
the strategy decides is withheld before it becomes pending (the position stays known),
the decision state still folds every input, and the status is halted with the reason;
once the entry says halted: false (or is gone) the next decision trades. A halt that
cannot be read keeps the last one known; an entry that is not such an object counts as
halted. Executors refuse a halted scenario's orders too (execution-devkit).
A host without a state store (TestContexts-style WorkerContext without
state:) persists nothing and starts flat, as before 0.20.0.
Automatic position recovery
A strategy degraded with position unknown or fee unknown leaves that state on an
absolute position event. A reconciliation worker publishes one automatically
(portfolio-workers
BinancePositionReconciler,
openspec behaviour, Automatic Position Recovery) only for a strategy that is the
sole trader of a symbol's asset on the account, and only at or below its last known
holding, so a recovery can lower a holding and never raise it. A lost record has no
last known holding and needs an operator. The whole flow, the alerts and the manual
path are on
Position recovery.
What the base contributes:
- Config
symbols: the symbols the strategy may trade, comma-separated canonical pairs (BTC_USDT,ETH_USDT). An order for any other symbol is withheld and the status says so, so the declaration holds. Without it the strategy may trade anything, and the reconciler treats every symbol as shared next to it: set it on every strategy on a recoverable account. - Command
positionstatus(InvokeWorkerCommand, payload{}): the livePositionStatus, in order with the inbox, no step and no save: decision-state owner, known symbols, unanswered, fee-unknown and working-order symbols, last activity per symbol, and holdings. - A position event with the
asofextension (the venue read's time) is a recovery event. It lands only on a symbol that is degraded, with no order working, read after the activation started and after the symbol's last order or fill, and at most the last known holding; otherwise it is dropped and logged and the strategy stays degraded. An absolute event withoutasof(an operator's correction) is folded as before.
3. Per-instance config
CreateWorkerRequest.config entries are stamped onto every triggering
CloudEvent as extension attributes. Read them with
ConfigResolution.* (extension-only — same-named payload fields are
ignored, because strategy payloads are foreign domain schemas).
protected override RsiState OnMarketEvent(CloudEvent input, RsiState state)
{
var period = ConfigResolution.ResolvePositiveInt(input, "rsiperiod", 14);
return state.Period == period ? state : state with { Period = period };
}
Note: CloudEvents extension attribute names cannot contain underscores (the CloudNative SDK and the WorkManager's config stamping both validate). Use a no-underscore spelling for your config keys.
4. Test before you trade
Step is a pure function (state in, state + actions out) — unit test
it directly against IDecide<TState, TMarket, TPortfolio, TAction>,
no CloudEvents or WorkManager involved (see
Virtufin.Strategy.DevKit.Tests/MovingAverageStrategyTests for the
pattern: warm up the indicator, feed known candles, assert the emitted
actions). Backtest by replaying a hyp.BACKTEST world's historical
candle/position events through the deployed worker itself (the same
StrategyWorkerBase code path production uses, not a separate
simulator) before ever wiring a strategy to act.
Before trusting a strategy with act (real capital), route it through
the scenarios spec's
shadow mode: an ObserveOnlyExecutor (see lib's
Virtufin.Base.Execution.Executors) executes nothing — it observes the
same order-submitted events a live executor would receive and records
what would have happened, with zero market or capital risk. A
scenario's active/paused/archived lifecycle (also in the
scenarios spec) governs when a worker is actually live versus parked.
See Bridge for the routing architecture and Helpers for the reusable pieces.