Skip to content

SymbolContext

SymbolContext aggregates all per-symbol state needed by trading strategies: order book, position, prices, and timestamps.

struct SymbolContext
{
  static constexpr size_t kDefaultBookLevels = 512;

  NLevelOrderBook<kDefaultBookLevels> book;
  std::optional<BookLevel> touchBid{};
  std::optional<BookLevel> touchAsk{};
  int64_t lastTouchNs{0};
  Quantity position{};
  std::optional<Price> avgEntryPrice{};
  std::optional<Price> entryPrice{};
  uint32_t barsInPosition{0};
  Price lastTradePrice{};
  int64_t lastUpdateNs{0};
  SymbolId symbolId{0};
};

Purpose

  • Consolidate all per-symbol data in a cache-friendly structure
  • Provide computed properties (mid price, spread, PnL)
  • Support multi-symbol strategies with O(1) state access

Fields

Field Type Description
book NLevelOrderBook<512> Order book with 512 price levels
touchBid / touchAsk std::optional<BookLevel> The most recent best bid/ask. Depth frames set it from the applied book; TOP_OF_BOOK frames, which the book ignores, update it directly. Empty when that side has no quote
lastTouchNs int64_t Exchange timestamp of the frame that last wrote the touch; lastUpdateNs only covers trades, depth frames and bars
position Quantity Net position (positive=long, negative=short)
avgEntryPrice std::optional<Price> The attached position manager's cost basis, empty when it reports none. On the shipped trackers it is a FIFO figure after a partial close
entryPrice std::optional<Price> Quantity-weighted average entry of the open position: an add moves it, a partial close leaves it, a fill that flips the position sets it to that fill's price. Empty when flat
barsInPosition uint32_t Bar callbacks received while holding the current position, the bar on which it is first seen counting as 1. 0 when flat, 1 again on the first bar after a flip, and 0 throughout a replay without bars
lastTradePrice Price Most recent trade price
lastUpdateNs int64_t Last update timestamp (nanoseconds)
symbolId SymbolId Symbol identifier

Position facts

Strategy keeps entryPrice and barsInPosition up to date before every hook runs, in a backtest (every runner mode) and on the live runners. The entry moves on the fills the strategy is told of: two buys of 1 at 120 and 140 give 130, a sell of 1 leaves 130 (a FIFO cost basis would say 140), and a sell of 3 that flips the position to short 2 at 180 gives 180. A position that changes without a fill price (one seeded on a live runner) takes the position manager's cost basis. Fees do not move it.

A bar strategy that exits after N bars, or at a percentage from its entry, reads both here instead of keeping its own bookkeeping; see Exit rules.

Computed Properties

Mid Price

std::optional<Price> mid() const noexcept;

Returns midpoint between best bid and ask. Returns nullopt if either side is missing.

Touch Mid

std::optional<Price> touchMid() const noexcept;

Mid of the freshest known touch. mid() answers from the depth book and moves at depth-frame cadence; this one also moves on TOP_OF_BOOK frames.

Book Spread

std::optional<Price> bookSpread() const noexcept;

Returns bid-ask spread. Returns nullopt if book is one-sided.

Unrealized PnL

std::optional<double> unrealizedPnl(Price markPrice) const noexcept;
std::optional<double> unrealizedPnl() const noexcept;  // Uses mid() as mark

The no-argument form marks at the depth-book mid(), not touchMid(): marking at a one-level touch is a separate decision. Pass a mark price to choose.

Unrealized PnL against the average entry price, which the engine reads from the attached IPositionManager once per market-data event, before its handlers run. Empty when there is no entry price to measure against, either because the manager keeps no cost basis or because the no-argument form has no mid to mark at. A flat position returns 0.0, not an empty optional.

Substituting zero for a missing entry price would report position * mark, the whole notional of the position dressed up as profit. That is what this returned before IPositionManager could be asked for one, and it meant a rule like "close when the loss passes X" never fired on a long and fired on the first tick of a short.

Position State

bool isLong() const noexcept;   // position > 0
bool isShort() const noexcept;  // position < 0
bool isFlat() const noexcept;   // position == 0

Reset

void reset() noexcept;

Clears all state: book, position, prices, timestamps.

Cross-Symbol Helpers

Free functions for multi-symbol analysis:

// Price spread: midA - midB
std::optional<Price> spread(const SymbolContext& a, const SymbolContext& b);

// Price ratio: midA / midB
std::optional<double> ratio(const SymbolContext& a, const SymbolContext& b);

Example

class SpreadStrategy : public Strategy
{
public:
  SpreadStrategy(SymbolId front, SymbolId back, const SymbolRegistry& registry)
    : Strategy(1, {front, back}, registry), _front(front), _back(back) {}

protected:
  void onSymbolBook(SymbolContext& c, const BookUpdateEvent& ev) override
  {
    // Get spread between front and back month
    auto spreadOpt = spread(ctx(_front), ctx(_back));
    if (!spreadOpt) return;

    double spreadValue = spreadOpt->toDouble();

    // Check unrealized PnL. Either leg can report "unknown".
    auto frontPnl = ctx(_front).unrealizedPnl();
    auto backPnl = ctx(_back).unrealizedPnl();
    if (!frontPnl || !backPnl) return;

    double pnl = *frontPnl + *backPnl;

    // Check position state
    if (ctx(_front).isLong() && pnl > _target)
    {
      emitClosePosition(_front);
      emitClosePosition(_back);
    }
  }

private:
  SymbolId _front, _back;
  double _target{100.0};
};

Memory Layout

SymbolContext is designed for cache efficiency:

  • 8,384 bytes per symbol in a release build; the 512-level book dominates at 8,320 of them. A build with LRVX_SCALE_CHECKS on (any build without NDEBUG) carries a scale field on every Decimal and doubles this to 16,640
  • Strategy holds 256 of these by value through SymbolStateMap, so the strategy object is about 2 MB in release and about 4 MB in a checked build. Allocate a strategy on the heap: two on one stack frame overrun a default 8 MB stack in a checked build, and the overflow lands in the constructor prologue
  • All fields in single contiguous struct
  • Access via SymbolStateMap provides O(1) lookup

See Also