{"record":{"id":"0aa69c5b22995bac","repo":"QuantConnect/Lean","slug":"unexpected-open-order-order-0aa69c","errorCode":null,"errorMessage":"Unexpected open order {order}","messagePattern":"Unexpected open order (.+?)","errorType":"exception","errorClass":"RegressionTestException","httpStatus":null,"severity":"error","filePath":"Algorithm.CSharp/EmitInsightsAlgorithm.cs","lineNumber":70,"sourceCode":"            SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(1), 0.025, null));\n            SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());\n            SetRiskManagement(new MaximumDrawdownPercentPerSecurity(0.01m));\n        }\n\n        /// <summary>\n        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n        /// </summary>\n        /// <param name=\"data\">Slice object keyed by symbol containing the stock data</param>\n        public override void OnData(Slice slice)\n        {\n            if (_toggle)\n            {\n                _toggle = false;\n                var order = Transactions.GetOpenOrders(_symbol).FirstOrDefault();\n\n                if (order != null)\n                {\n                    throw new RegressionTestException($\"Unexpected open order {order}\");\n                }\n\n                // we manually emit an insight\n                EmitInsights(Insight.Price(_symbol, Resolution.Daily, 1, InsightDirection.Down));\n\n                // emitted insight should have triggered a new order\n                order = Transactions.GetOpenOrders(_symbol).FirstOrDefault();\n\n                if (order == null)\n                {\n                    throw new RegressionTestException(\"Expected open order for emitted insight\");\n                }\n                if (order.Direction != OrderDirection.Sell\n                    || order.Symbol != _symbol)\n                {\n                    throw new RegressionTestException($\"Unexpected open order for emitted insight: {order}\");\n                }\n            }","sourceCodeStart":52,"sourceCodeEnd":88,"githubUrl":"https://github.com/QuantConnect/Lean/blob/d2c3659f877bfc2b5d9dc0fc89a9c7566f45e892/Algorithm.CSharp/EmitInsightsAlgorithm.cs#L52-L88","documentation":"Thrown by the EmitInsightsAlgorithm regression test (a C# sample algorithm) inside OnData. It guards the Alpha→Portfolio→Execution pipeline: right before the test manually emits an Insight, there must be NO open order for the symbol. If Transactions.GetOpenOrders(_symbol) returns an order at that checkpoint, the insight-to-order plumbing produced a spurious order, so the test fails fast with the offending order printed.","triggerScenarios":"OnData runs while the per-bar _toggle flag is true, and an order for _symbol is still in the open-orders list (unfilled/uncancelled) when GetOpenOrders(_symbol).FirstOrDefault() is called. Typically a previously emitted insight's order was never filled or a stale order survived into this bar.","commonSituations":"Regression test data changed (fills arriving a bar late), a brokerage/execution-model change that queues orders differently, or market data with no liquidity so the prior order never filled before the toggle branch ran.","solutions":["Inspect the printed order object to see which direction/type leaked through, then trace which earlier insight/order created it.","If you modified the Execution/Portfolio/Risk framework, verify the execution model is not double-submitting or carrying orders across bars.","Ensure the previous order fills or is cancelled before the toggle bar; adjust the regression's expected fill timing / data set if fills genuinely arrive later.","Run the algorithm in the same data/timezone configuration the regression expects (QC cloud or local lean-cli) so fill timing matches."],"exampleFix":"// before\nvar order = Transactions.GetOpenOrders(_symbol).FirstOrDefault();\nif (order != null) { throw new RegressionTestException($\"Unexpected open order {order}\"); }\n\n// diagnostic fix: log/cancel the stale order before asserting\nforeach (var o in Transactions.GetOpenOrders(_symbol))\n{\n    Log($\"Cancelling stale order {o.Id} {o.Type} qty={o.Quantity}\");\n    Transactions.CancelOrder(o.Id, \"stale before insight emit\");\n}","handlingStrategy":"validation","validationCode":"// Before emitting the insight, cancel any stale open orders for the symbol\nvar open = Transactions.GetOpenOrders(_symbol);\nif (open.Any())\n{\n    foreach (var o in open) Transactions.CancelOrder(o.Id);\n    // optionally wait a bar before re-checking\n}\n// only then:\n// EmitInsights(Insight.Price(_symbol, Resolution.Daily, 1, InsightDirection.Down));","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Treat regression test assertions as contracts: the framework must not leave open orders across the toggle boundary.","When modifying Execution/Portfolio/Risk models, run the EmitInsights regression to catch pipeline regressions early.","Log GetOpenOrders contents at diagnostic verbosity during test development to see stale orders before they trip the assertion."],"tags":["regression-test","orders","insights","csharp"],"backgroundTag":null,"analyzedSha":"d2c3659f877bfc2b5d9dc0fc89a9c7566f45e892","analyzedAt":"2026-08-13T13:52:21.013Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}