Portfolio missing_price_instruments stays stale when positions exist before the first AccountState

Author: oochoooCreated Sep 30, 2026Updated Sep 30, 2026

Bug Report

Confirmation

  • I've re-read the relevant sections of the documentation.
  • I've searched existing issues and discussions to avoid duplicates.
  • I've reviewed or skimmed the source code (or examples) to confirm the behavior is not by design.
  • I've tested this issue using a recent pre-release or development wheel (2.0.0rcN, dev develop, or a nightly) and can still reproduce it.

Reproduced on 2.0.0rc5 (PyPI pre-release) against a live node. The logic is unchanged on develop at 112f5c2171a9bfa53fb9813800f50ca9e86e9ff2; I have not run it on a development wheel, only on the rc5 PyPI wheel.

Summary

Portfolio.missing_price_instruments() reports held instruments as unpriceable for the whole life of a live node, even though equity(), unrealized_pnls() and the recorded snapshots all price them correctly.

The equity-curve registration snapshot writes the missing-price tracker under the account-filtered scope Some(account_id). On a live node nothing afterwards ever runs an account-filtered valuation, so that entry is never refreshed — and missing_price_instruments(venue) returns the union across scopes, so the stale entry is exactly what a venue-wide caller sees. Prices arriving afterwards do not clear it: no price handler writes this state at all.

Expected behavior

Two things, from the code and the docs:

  1. The doc comment on the method says an entry is "added the first time Portfolio::mark_values cannot value an open position because its price is missing or its notional is invalid (after also emitting a warn log), and removed once the instrument can be valued again so a subsequent drop re-warns" (crates/portfolio/src/portfolio.rs:1123-1127 at rc5). Mark prices for both instruments are flowing; the entries are not removed.

  2. docs/concepts/portfolio.md tells users to use the tracker as a diagnostic for equity: "If equity() understates what you expect, check missing_price_instruments(venue) before investigating the math." Here equity() is correct and the tracker says the positions are unpriced, so the documented diagnostic gives the wrong answer. A tracker that disagrees with equity() is not usable for the purpose the docs assign it.

The tracker is only a diagnostic, so I am not claiming wrong money. The cost is that a strategy which gates on it refuses to value an otherwise fully priced portfolio, indefinitely.

Actual behavior

PortfolioState.venues_missing_price is AHashMap<Venue, AHashMap<Option<AccountId>, AHashSet<InstrumentId>>> — keyed by the scope of the query that produced it (portfolio.rs:90 at rc5). Four call sites write it, and each writes under the caller's own scope:

  • unrealized_pnls_with_missing at :550-552, guarded by if account_id.is_some(),
  • equity at :835/:867/:876/:878,
  • mark_values_with_mode at :1243/:1245.

No price path writes it. update_quote_tick (:3186) and update_bar (:3196) both delegate to update_instrument_id (:3262), which only does unrealized_pnls.shift_remove(instrument_id) — it invalidates the PnL cache and nothing else.

The writer with no matching refresher is the equity curve. PortfolioConfig.equity_curve defaults to true. On the first AccountState for an account:

4017 fn update_account(…) {
4069     register_equity_curve_account(clock, cache, inner, config, event.account_id);
4076 fn register_equity_curve_account(…) {
4079     if !config.equity_curve { return; }
4086     let is_new = inner.equity_curve_accounts.insert(account_id);   // once per account
4098     if !is_new { return; }
4101     emit_snapshot(cache, clock, inner, config, account_id, ts_event);
4238 fn emit_snapshot(…) { … portfolio.build_snapshot(&account_id) … }
 892 pub fn build_snapshot(&mut self, account_id: &AccountId) {
 941         self.unrealized_pnls_with_missing(*venue, Some(account_id), None)?;   // ← keyed Some(id)

build_snapshot is the only internal caller that passes an account id, and register_equity_curve_account only runs once per account. The next Some(account_id) write is the next UTC-midnight equity-curve sample or shutdown — up to 24 hours on a live node. Meanwhile the accessor unions every scope:

1128 pub fn missing_price_instruments(&self, venue, account_id) -> Vec<InstrumentId> {
1140     None => observations.map(|o| o.values().flat_map(|ids| ids.iter().copied()).collect::<AHashSet<_>>()…)

The one-shot warn is never retracted either: the re-warn guard at :1178-1197 tests membership in the union of all scopes, so a recovery observed in the venue-wide scope emits nothing.

What makes this reachable on a live node is that the positions already exist when the first AccountState arrives. With a persistent cache backend they are restored at connect, so the registration snapshot sees two open positions with no price and latches them. With the in-memory cache the cache is empty at that instant, reconciliation creates the positions ~760 ms later, equity's flat branch calls clear_missing_price_state (:834-835), and the account is never registered again. The backend is the trigger; the ordering is the mechanism. Any state that is restored before the first AccountState hits this.

Steps to reproduce

  1. Install the wheel: pip install -U nautilus_trader --pre.
  2. Have open positions at the venue before the node starts — two Binance USD-M demo perpetuals is enough. BTCUSDT-PERP.BINANCE +0.0035 and ETHUSDT-PERP.BINANCE -0.057 in my run.
  3. Run the script below once with --cache postgres and once with --cache memory. Both connect a real demo DATA client and a real demo EXECUTION client on the same account, so startup reconciliation loads the positions. --cache postgres needs a database initialised with nautilus database init first.
  4. marks subscribes to mark prices in on_start and measures at 10 s, 20 s and 45 s. The instrument is not special: I also ran a quotes variant with PortfolioConfig(use_mark_prices=False), which behaves identically.
  5. Compare missing_price_instruments in the two runs. Postgres reports both instruments for the whole run; in-memory reports none. In both runs equity and unrealized are correct and cache.mark_price() is populated and fresh (sub-second age).
python
from __future__ import annotations

import argparse
import json
import logging

from nautilus_trader.adapters.binance import (
    BinanceDataClientConfig,
    BinanceDataClientFactory,
    BinanceEnvironment,
    BinanceExecutionClientConfig,
    BinanceExecutionClientFactory,
    BinanceInstrumentProviderConfig,
    BinanceProductType,
)
from nautilus_trader.common import Environment
from nautilus_trader.infrastructure import PostgresCacheConfig
from nautilus_trader.live import LiveNode
from nautilus_trader.model import AccountId, InstrumentId, OmsType, TraderId, Venue
from nautilus_trader.portfolio import PortfolioConfig
from nautilus_trader.trading import Strategy

SECOND_NS = 1_000_000_000
INSTRUMENTS = ("BTCUSDT-PERP.BINANCE", "ETHUSDT-PERP.BINANCE")
VENUE = Venue("BINANCE")
ACCOUNT = "BINANCE-001"
PROVIDER = dict(load_all=True, log_warnings=True, query_commission_rates=False)


class Pricer(Strategy):
    variant = "marks"
    measure_at = [10, 20, 45]

    def on_start(self) -> None:
        start = self.clock.timestamp_ns()
        if self.variant == "marks":
            for name in INSTRUMENTS:
                self.subscribe_mark_prices(InstrumentId.from_str(name))
        else:
            for name in INSTRUMENTS:
                self.subscribe_quotes(InstrumentId.from_str(name))
        for index, seconds in enumerate(self.measure_at, 1):
            self.clock.set_timer_ns(
                f"m{index}", seconds * SECOND_NS, start_time_ns=start,
                callback=lambda event, i=index: self.measure(i),
            )
        self.clock.set_timer_ns(
            "stop", (self.measure_at[-1] + 30) * SECOND_NS, start_time_ns=start,
            callback=lambda event: self.shutdown_system("probe done"),
        )

    def measure(self, index: int) -> None:
        unrealized = self.portfolio.unrealized_pnls(VENUE) or {}
        out = {
            "variant": self.variant,
            "at_seconds": self.measure_at[index - 1],
            # the reported API, called the way a strategy would
            "missing_price_instruments": [
                str(i) for i in self.portfolio.missing_price_instruments(VENUE)
            ],
            "equity": {str(k): str(v) for k, v in (self.portfolio.equity(VENUE) or {}).items()},
            "unrealized": {str(k): str(v) for k, v in unrealized.items()},
            "per_instrument": {},
        }
        for name in INSTRUMENTS:
            instrument_id = InstrumentId.from_str(name)
            mark = self.cache.mark_price(instrument_id)
            out["per_instrument"][name] = {
                "cache_mark_price": None if mark is None else str(mark.value),
                "mark_age_ns": None if mark is None else int(self.clock.timestamp_ns()) - int(mark.ts_event),
            }
        print("PRICING " + json.dumps(out, indent=2, sort_keys=True, default=str), flush=True)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--variant", choices=["marks", "quotes"], default="marks")
    parser.add_argument("--cache", choices=["memory", "postgres"], default="memory")
    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")

    builder = (
        LiveNode.builder("price-source-probe", TraderId.from_str("probe-price-001"), Environment.LIVE)
        .add_data_client(None, BinanceDataClientFactory(), BinanceDataClientConfig(
            api_key=None, api_secret=None, environment=BinanceEnvironment.DEMO,
            product_type=BinanceProductType.USD_M,
            instrument_provider=BinanceInstrumentProviderConfig(**PROVIDER)))
        .add_exec_client("BINANCE", BinanceExecutionClientFactory(), BinanceExecutionClientConfig(
            account_id=AccountId(ACCOUNT), product_type=BinanceProductType.USD_M,
            environment=BinanceEnvironment.DEMO, oms_type=OmsType.NETTING,
            instrument_provider=BinanceInstrumentProviderConfig(**PROVIDER)))
    )
    if args.cache == "postgres":
        builder = builder.with_cache_database_factory(
            PostgresCacheConfig(host="localhost", port=5432, username="candidate",
                                password="", database="issue153_native2"))
    if args.variant == "quotes":
        builder = builder.with_portfolio_config(PortfolioConfig(use_mark_prices=False))

    node = builder.build()
    pricer = Pricer()
    pricer.variant = args.variant
    node.add_strategy(pricer)
    node.run()
    node.dispose()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Code snippets or logs

The blocks below are verbatim from my fuller probe, which is the script above plus quote and clock-age fields in per_instrument.

--cache postgres --variant marks. The two open positions are already in the Cache when the first AccountState arrives, so the registration snapshot sees them with no price:

2026-09-30T02:39:11.429252984Z [INFO] probe-price-001.nautilus_common::cache: Cached 2 general object(s) from database
2026-09-30T02:39:11.471408882Z [INFO] probe-price-001.nautilus_execution::engine: Set PositionId count for PortfolioStrategy-000 to 2
2026-09-30T02:39:11.471409714Z [INFO] probe-price-001.nautilus_execution::engine: Loaded cache in 42ms

2026-09-30T02:39:15.477914493Z [INFO] probe-price-001.nautilus_binance::common::execution: Account BINANCE-001 registered
2026-09-30T02:39:15.477953533Z [INFO] probe-price-001.nautilus_portfolio::portfolio: Updated AccountState(account_id=BINANCE-001, account_type=MARGIN, …)
2026-09-30T02:39:15.478026173Z [WARN] probe-price-001.nautilus_portfolio::portfolio: Cannot value open position BTCUSDT-PERP.BINANCE; ensure its notional inputs are valid and subscribe to quotes, trades, or bars for continuous mark-to-market equity
2026-09-30T02:39:15.478031856Z [WARN] probe-price-001.nautilus_portfolio::portfolio: Cannot value open position ETHUSDT-PERP.BINANCE; ensure its notional inputs are valid and subscribe to quotes, trades, or bars for continuous mark-to-market equity
2026-09-30T02:39:15.912703764Z [INFO] probe-price-001.nautilus_live::node: Starting execution state reconciliation...

The warn fires 73 µs after the AccountState line and ~435 ms before reconciliation starts, which places it inside update_account → register_equity_curve_account → emit_snapshot. It never appears again, at any later point in the run.

At 10 s, with a fresh mark price for both instruments and correct money:

PRICING {
  "at_seconds": 10,
  "equity": {
    "BTC": "0.01000000 BTC",
    "USDC": "5000.00000000 USDC",
    "USDT": "3098.18386898 USDT"
  },
  "missing_price_instruments": [
    "BTCUSDT-PERP.BINANCE",
    "ETHUSDT-PERP.BINANCE"
  ],
  "per_instrument": {
    "BTCUSDT-PERP.BINANCE": {
      "age_ns": 319394255,
      "cache_mark_price": "83321.70",
      "engine_clock_ns": 1790735966319394255,
      "future_ns": -319394255,
      "mark_ts_event": 1790735966000000000
    },
    "ETHUSDT-PERP.BINANCE": {
      "age_ns": 319401657,
      "cache_mark_price": "2665.85",
      "engine_clock_ns": 1790735966319401657,
      "future_ns": -319401657,
      "mark_ts_event": 1790735966000000000
    }
  },
  "stage": 1,
  "unrealized": {
    "USDT": "0.16987000 USDT"
  },
  "variant": "marks"
}

cache_mark_price is populated and 319 ms old; equity and unrealized are priced; missing_price_instruments still lists both. All eight measurement blocks in the run are identical in this respect, through shutdown.

--cache postgres --variant quotes (PortfolioConfig(use_mark_prices=False) + quote subscription) behaves the same, so mark-versus-quote is not the variable:

2026-09-30T02:41:14.515255822Z [WARN] probe-price-001.nautilus_portfolio::portfolio: Cannot value open position BTCUSDT-PERP.BINANCE; ensure its notional inputs are valid and subscribe to quotes, trades, or bars for continuous mark-to-market equity
2026-09-30T02:41:14.515257204Z [WARN] probe-price-001.nautilus_portfolio::portfolio: Cannot value open position ETHUSDT-PERP.BINANCE; ensure its notional inputs are valid and subscribe to quotes, trades, or bars for continuous mark-to-market equity

--cache memory --variant marks — the control. There is no Cannot value open position line anywhere in this run, and the tracker is empty:

2026-09-30T02:25:26.294491433Z [INFO] probe-price-001.nautilus_portfolio::portfolio: Updated AccountState(account_id=BINANCE-001, account_type=MARGIN, …)
2026-09-30T02:25:27.056882583Z [INFO] probe-price-001.nautilus_live::execution::manager: Creating position from venue report for ETHUSDT-PERP.BINANCE: side=Sell, qty=0.057, avg_px=2672.41

PRICING {
  "at_seconds": 20,
  "equity": {
    "USDT": "3098.36539898 USDT"
  },
  "missing_price_instruments": [],
  "per_instrument": {
    "BTCUSDT-PERP.BINANCE": {
      "cache_mark_price": "83430.24",
      "cache_quote_bid": null
    },
    "ETHUSDT-PERP.BINANCE": {
      "cache_mark_price": "2669.33",
      "cache_quote_bid": null
    }
  },
  "unrealized": {
    "USDT": "0.35140000 USDT"
  },
  "variant": "marks"
}

The only difference is that the cache was empty at 02:25:26.294 and the positions were created at 02:25:27.056, after the one-shot registration snapshot.

I also ran the in-memory variant with no price subscription at all. There the warn appears only at shutdown — finalize_equity_curve → emit_snapshot(Some(account_id)) — which is consistent with every latch above being a snapshot-path write:

2026-09-30T02:36:17.227543859Z [WARN] probe-price-001.nautilus_portfolio::portfolio: Cannot value open position BTCUSDT-PERP.BINANCE; …
2026-09-30T02:36:17.227546125Z [WARN] probe-price-001.nautilus_portfolio::portfolio: Cannot value open position ETHUSDT-PERP.BINANCE; …

Two possible resolutions

Either would close it, and I have no strong preference between them:

  1. Clear on recovery. Have update_instrument_id (or the mark/quote/bar handlers) drop an instrument from every scope in which it is currently flagged, mirroring how clear_missing_price_state already clears on venue-flat. This matches the doc comment's "removed once the instrument can be valued again".
  2. Do not let a recording path write the tracker. The registration snapshot exists to seed the equity curve, not to report a valuation state. If build_snapshot collected unpriced without calling update_missing_price_state, the Some(account_id) scope would only ever be written by an actual account-filtered valuation query, which is the scope the doc paragraph on per-scope tracking describes.

I lean to (1), because it also fixes the one-shot-warn behaviour for a scope that has genuinely recovered.

Related

  • #5072 reports missing_price_instruments for a different reason (get_price rejecting non-positive prices for allows_negative_price() instruments). Same accessor, different defect — not a duplicate.
  • docs/concepts/portfolio.md, "Missing-price tracking": documents the per-scope rule ("Each observation remains authoritative until the same scope runs again; a filtered result does not declare an earlier unfiltered result resolved") but does not mention that an internal snapshot write creates a scope the caller never asked for. If that paragraph is the intended contract, the doc comment on missing_price_instruments and the diagnostic tip at the end of that section both need to change instead.

Specifications

  • OS platform: Linux (Debian GNU/Linux 13), kernel 7.0.0-34-generic, x86_64-unknown-linux-gnu
  • Python version: 3.12.14
  • nautilus_trader version: 2.0.0rc5 (nautilus_core 0.64.0, git_commit 1b0a49d2792a, rustc 1.98.1)
  • Installed from: PyPI wheel (pip install -U nautilus_trader --pre)
  • Adapter/venue (if applicable): Binance USD-M Demo, OmsType.NETTING, margin account BINANCE-001; BTCUSDT-PERP.BINANCE, ETHUSDT-PERP.BINANCE. PortfolioConfig defaults throughout (equity_curve=true, use_mark_prices=true).

Source: nautechsystems/nautilus_trader