QuantConnect/Lean · error · RegressionTestException

Unexpected holdings

Error message

Unexpected holdings

What it means

In OnEndOfAlgorithm this asserts the final holdings quantity for _symbol is negative: Math.Sign(holdings.Quantity) == -1. Since the Down insight drove a Sell (short) position, the portfolio must end short. A non-negative sign means the position was not established as short (or was flipped/closed).

Source

Thrown at Algorithm.CSharp/EmitInsightNoAlphaModelAlgorithm.cs:99

                {
                    throw new RegressionTestException("Expected open order for emitted insight");
                }
                if (order.Direction != OrderDirection.Sell
                    || order.Symbol != _symbol)
                {
                    throw new RegressionTestException($"Unexpected open order for emitted insight: {order}");
                }

                SetHoldings(_symbol, 1);
            }
        }

        public override void OnEndOfAlgorithm()
        {
            var holdings = Securities[_symbol].Holdings;
            if (Math.Sign(holdings.Quantity) != -1)
            {
                throw new RegressionTestException("Unexpected holdings");
            }
        }

        /// <summary>
        /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
        /// </summary>
        public bool CanRunLocally { get; } = true;

        /// <summary>
        /// This is used by the regression test system to indicate which languages this algorithm is written in.
        /// </summary>
        public List<Language> Languages { get; } = new() { Language.CSharp };

        /// <summary>
        /// Data Points count of all timeslices of algorithm
        /// </summary>
        public long DataPoints => 48;

View on GitHub (pinned to d2c3659f87)

Solutions

  1. Check Securities[_symbol].Holdings.Quantity at end and the fill events for the sell order.
  2. Confirm the brokerage model permits short selling for the security.
  3. Ensure no subsequent insight/order flipped the position before OnEndOfAlgorithm.
Defensive patterns

Strategy: validation

Validate before calling

var qty = Securities[_symbol].Holdings.Quantity;
if (Math.Sign(qty) != -1)
{
    Log($"Expected short position, got qty={qty}. Check fill events and brokerage short-sell permission.");
}

Prevention

When it happens

Trigger: The sell order never filled (quantity stays 0), or the position was later liquidated/flipped before algorithm end. A Buy direction error (118) would also cause this.

Common situations: Order not filled by end of backtest (no data/no liquidity); short-selling blocked by the brokerage model (borrowing not allowed) leaving quantity 0; a later OnData step reversed the position.

Related errors


AI-assisted analysis of QuantConnect/Lean@d2c3659f87 (2026-08-13). Data as JSON: /api/errors/9ee35e89550ae417. Report an issue: GitHub.